{"repo": "Shopify/kubernetes-deploy", "path": "lib/kubernetes-deploy/deferred_summary_logging.rb", "func_name": "KubernetesDeploy.DeferredSummaryLogging.print_summary", "original_string": "def print_summary(status)\n status_string = status.to_s.humanize.upcase\n if status == :success\n heading(\"Result: \", status_string, :green)\n level = :info\n elsif status == :timed_out\n heading(\"Result: \", status_string, :yellow)\n level = :fatal\n else\n heading(\"Result: \", status_string, :red)\n level = :fatal\n end\n\n if (actions_sentence = summary.actions_sentence.presence)\n public_send(level, actions_sentence)\n blank_line(level)\n end\n\n summary.paragraphs.each do |para|\n msg_lines = para.split(\"\\n\")\n msg_lines.each { |line| public_send(level, line) }\n blank_line(level) unless para == summary.paragraphs.last\n end\n end", "language": "ruby", "code": "def print_summary(status)\n status_string = status.to_s.humanize.upcase\n if status == :success\n heading(\"Result: \", status_string, :green)\n level = :info\n elsif status == :timed_out\n heading(\"Result: \", status_string, :yellow)\n level = :fatal\n else\n heading(\"Result: \", status_string, :red)\n level = :fatal\n end\n\n if (actions_sentence = summary.actions_sentence.presence)\n public_send(level, actions_sentence)\n blank_line(level)\n end\n\n summary.paragraphs.each do |para|\n msg_lines = para.split(\"\\n\")\n msg_lines.each { |line| public_send(level, line) }\n blank_line(level) unless para == summary.paragraphs.last\n end\n end", "code_tokens": ["def", "print_summary", "(", "status", ")", "status_string", "=", "status", ".", "to_s", ".", "humanize", ".", "upcase", "if", "status", "==", ":success", "heading", "(", "\"Result: \"", ",", "status_string", ",", ":green", ")", "level", "=", ":info", "elsif", "status", "==", ":timed_out", "heading", "(", "\"Result: \"", ",", "status_string", ",", ":yellow", ")", "level", "=", ":fatal", "else", "heading", "(", "\"Result: \"", ",", "status_string", ",", ":red", ")", "level", "=", ":fatal", "end", "if", "(", "actions_sentence", "=", "summary", ".", "actions_sentence", ".", "presence", ")", "public_send", "(", "level", ",", "actions_sentence", ")", "blank_line", "(", "level", ")", "end", "summary", ".", "paragraphs", ".", "each", "do", "|", "para", "|", "msg_lines", "=", "para", ".", "split", "(", "\"\\n\"", ")", "msg_lines", ".", "each", "{", "|", "line", "|", "public_send", "(", "level", ",", "line", ")", "}", "blank_line", "(", "level", ")", "unless", "para", "==", "summary", ".", "paragraphs", ".", "last", "end", "end"], "docstring": "Outputs the deferred summary information saved via @logger.summary.add_action and @logger.summary.add_paragraph", "docstring_tokens": ["Outputs", "the", "deferred", "summary", "information", "saved", "via"], "sha": "ab599ee9a4c1268d5a538a622a83160223fd916c", "url": "https://github.com/Shopify/kubernetes-deploy/blob/ab599ee9a4c1268d5a538a622a83160223fd916c/lib/kubernetes-deploy/deferred_summary_logging.rb#L37-L60", "partition": "test"} {"repo": "Shopify/kubernetes-deploy", "path": "lib/kubernetes-deploy/deploy_task.rb", "func_name": "KubernetesDeploy.DeployTask.find_bad_files_from_kubectl_output", "original_string": "def find_bad_files_from_kubectl_output(line)\n # stderr often contains one or more lines like the following, from which we can extract the file path(s):\n # Error from server (TypeOfError): error when creating \"/path/to/service-gqq5oh.yml\": Service \"web\" is invalid:\n\n line.scan(%r{\"(/\\S+\\.ya?ml\\S*)\"}).each_with_object([]) do |matches, bad_files|\n matches.each do |path|\n content = File.read(path) if File.file?(path)\n bad_files << { filename: File.basename(path), err: line, content: content }\n end\n end\n end", "language": "ruby", "code": "def find_bad_files_from_kubectl_output(line)\n # stderr often contains one or more lines like the following, from which we can extract the file path(s):\n # Error from server (TypeOfError): error when creating \"/path/to/service-gqq5oh.yml\": Service \"web\" is invalid:\n\n line.scan(%r{\"(/\\S+\\.ya?ml\\S*)\"}).each_with_object([]) do |matches, bad_files|\n matches.each do |path|\n content = File.read(path) if File.file?(path)\n bad_files << { filename: File.basename(path), err: line, content: content }\n end\n end\n end", "code_tokens": ["def", "find_bad_files_from_kubectl_output", "(", "line", ")", "# stderr often contains one or more lines like the following, from which we can extract the file path(s):", "# Error from server (TypeOfError): error when creating \"/path/to/service-gqq5oh.yml\": Service \"web\" is invalid:", "line", ".", "scan", "(", "%r{", "\\S", "\\.", "\\S", "}", ")", ".", "each_with_object", "(", "[", "]", ")", "do", "|", "matches", ",", "bad_files", "|", "matches", ".", "each", "do", "|", "path", "|", "content", "=", "File", ".", "read", "(", "path", ")", "if", "File", ".", "file?", "(", "path", ")", "bad_files", "<<", "{", "filename", ":", "File", ".", "basename", "(", "path", ")", ",", "err", ":", "line", ",", "content", ":", "content", "}", "end", "end", "end"], "docstring": "Inspect the file referenced in the kubectl stderr\n to make it easier for developer to understand what's going on", "docstring_tokens": ["Inspect", "the", "file", "referenced", "in", "the", "kubectl", "stderr", "to", "make", "it", "easier", "for", "developer", "to", "understand", "what", "s", "going", "on"], "sha": "ab599ee9a4c1268d5a538a622a83160223fd916c", "url": "https://github.com/Shopify/kubernetes-deploy/blob/ab599ee9a4c1268d5a538a622a83160223fd916c/lib/kubernetes-deploy/deploy_task.rb#L514-L524", "partition": "test"} {"repo": "Shopify/kubernetes-deploy", "path": "lib/kubernetes-deploy/deploy_task.rb", "func_name": "KubernetesDeploy.DeployTask.confirm_ejson_keys_not_prunable", "original_string": "def confirm_ejson_keys_not_prunable\n secret = ejson_provisioner.ejson_keys_secret\n return unless secret.dig(\"metadata\", \"annotations\", KubernetesResource::LAST_APPLIED_ANNOTATION)\n\n @logger.error(\"Deploy cannot proceed because protected resource \" \\\n \"Secret/#{EjsonSecretProvisioner::EJSON_KEYS_SECRET} would be pruned.\")\n raise EjsonPrunableError\n rescue Kubectl::ResourceNotFoundError => e\n @logger.debug(\"Secret/#{EjsonSecretProvisioner::EJSON_KEYS_SECRET} does not exist: #{e}\")\n end", "language": "ruby", "code": "def confirm_ejson_keys_not_prunable\n secret = ejson_provisioner.ejson_keys_secret\n return unless secret.dig(\"metadata\", \"annotations\", KubernetesResource::LAST_APPLIED_ANNOTATION)\n\n @logger.error(\"Deploy cannot proceed because protected resource \" \\\n \"Secret/#{EjsonSecretProvisioner::EJSON_KEYS_SECRET} would be pruned.\")\n raise EjsonPrunableError\n rescue Kubectl::ResourceNotFoundError => e\n @logger.debug(\"Secret/#{EjsonSecretProvisioner::EJSON_KEYS_SECRET} does not exist: #{e}\")\n end", "code_tokens": ["def", "confirm_ejson_keys_not_prunable", "secret", "=", "ejson_provisioner", ".", "ejson_keys_secret", "return", "unless", "secret", ".", "dig", "(", "\"metadata\"", ",", "\"annotations\"", ",", "KubernetesResource", "::", "LAST_APPLIED_ANNOTATION", ")", "@logger", ".", "error", "(", "\"Deploy cannot proceed because protected resource \"", "\"Secret/#{EjsonSecretProvisioner::EJSON_KEYS_SECRET} would be pruned.\"", ")", "raise", "EjsonPrunableError", "rescue", "Kubectl", "::", "ResourceNotFoundError", "=>", "e", "@logger", ".", "debug", "(", "\"Secret/#{EjsonSecretProvisioner::EJSON_KEYS_SECRET} does not exist: #{e}\"", ")", "end"], "docstring": "make sure to never prune the ejson-keys secret", "docstring_tokens": ["make", "sure", "to", "never", "prune", "the", "ejson", "-", "keys", "secret"], "sha": "ab599ee9a4c1268d5a538a622a83160223fd916c", "url": "https://github.com/Shopify/kubernetes-deploy/blob/ab599ee9a4c1268d5a538a622a83160223fd916c/lib/kubernetes-deploy/deploy_task.rb#L570-L579", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/compressor.rb", "func_name": "Omnibus.Compressor.for_current_system", "original_string": "def for_current_system(compressors)\n family = Ohai[\"platform_family\"]\n\n if family == \"mac_os_x\"\n if compressors.include?(:dmg)\n return DMG\n end\n\n if compressors.include?(:tgz)\n return TGZ\n end\n end\n\n if compressors.include?(:tgz)\n return TGZ\n else\n log.info(log_key) { \"No compressor defined for `#{family}'.\" }\n return Null\n end\n end", "language": "ruby", "code": "def for_current_system(compressors)\n family = Ohai[\"platform_family\"]\n\n if family == \"mac_os_x\"\n if compressors.include?(:dmg)\n return DMG\n end\n\n if compressors.include?(:tgz)\n return TGZ\n end\n end\n\n if compressors.include?(:tgz)\n return TGZ\n else\n log.info(log_key) { \"No compressor defined for `#{family}'.\" }\n return Null\n end\n end", "code_tokens": ["def", "for_current_system", "(", "compressors", ")", "family", "=", "Ohai", "[", "\"platform_family\"", "]", "if", "family", "==", "\"mac_os_x\"", "if", "compressors", ".", "include?", "(", ":dmg", ")", "return", "DMG", "end", "if", "compressors", ".", "include?", "(", ":tgz", ")", "return", "TGZ", "end", "end", "if", "compressors", ".", "include?", "(", ":tgz", ")", "return", "TGZ", "else", "log", ".", "info", "(", "log_key", ")", "{", "\"No compressor defined for `#{family}'.\"", "}", "return", "Null", "end", "end"], "docstring": "Determine the best compressor for the current system. This method returns\n the class, not an instance of the class.\n\n @example\n Compressor.for_current_system([:dmg, :tgz]) #=> Packager::DMG\n\n @param [Array] compressors\n the list of configured compressors\n\n @return [~Compressor::Base]", "docstring_tokens": ["Determine", "the", "best", "compressor", "for", "the", "current", "system", ".", "This", "method", "returns", "the", "class", "not", "an", "instance", "of", "the", "class", "."], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/compressor.rb#L38-L57", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/packagers/bff.rb", "func_name": "Omnibus.Packager::BFF.create_bff_file", "original_string": "def create_bff_file\n # We are making the assumption that sudo exists.\n # Unforunately, the owner of the file in the staging directory is what\n # will be on the target machine, and mkinstallp can't tell you if that\n # is a bad thing (it usually is).\n # The match is so we only pick the lowest level of the project dir.\n # This implies that if we are in /tmp/staging/project/dir/things,\n # we will chown from 'project' on, rather than 'project/dir', which leaves\n # project owned by the build user (which is incorrect)\n # First - let's find out who we are.\n shellout!(\"sudo chown -Rh 0:0 #{File.join(staging_dir, project.install_dir.match(/^\\/?(\\w+)/).to_s)}\")\n log.info(log_key) { \"Creating .bff file\" }\n\n # Since we want the owner to be root, we need to sudo the mkinstallp\n # command, otherwise it will not have access to the previously chowned\n # directory.\n shellout!(\"sudo /usr/sbin/mkinstallp -d #{staging_dir} -T #{File.join(staging_dir, 'gen.template')}\")\n\n # Print the full contents of the inventory file generated by mkinstallp\n # from within the staging_dir's .info folder (where control files for the\n # packaging process are kept.)\n log.debug(log_key) do\n \"With .inventory file of:\\n\" + File.read(\"#{File.join( staging_dir, '.info', \"#{safe_base_package_name}.inventory\" )}\")\n end\n\n # Copy the resulting package up to the package_dir\n FileSyncer.glob(File.join(staging_dir, \"tmp/*.bff\")).each do |bff|\n copy_file(bff, File.join(Config.package_dir, create_bff_file_name))\n end\n\n ensure\n # chown back to original user's uid/gid so cleanup works correctly\n original_uid = shellout!(\"id -u\").stdout.chomp\n original_gid = shellout!(\"id -g\").stdout.chomp\n\n shellout!(\"sudo chown -Rh #{original_uid}:#{original_gid} #{staging_dir}\")\n end", "language": "ruby", "code": "def create_bff_file\n # We are making the assumption that sudo exists.\n # Unforunately, the owner of the file in the staging directory is what\n # will be on the target machine, and mkinstallp can't tell you if that\n # is a bad thing (it usually is).\n # The match is so we only pick the lowest level of the project dir.\n # This implies that if we are in /tmp/staging/project/dir/things,\n # we will chown from 'project' on, rather than 'project/dir', which leaves\n # project owned by the build user (which is incorrect)\n # First - let's find out who we are.\n shellout!(\"sudo chown -Rh 0:0 #{File.join(staging_dir, project.install_dir.match(/^\\/?(\\w+)/).to_s)}\")\n log.info(log_key) { \"Creating .bff file\" }\n\n # Since we want the owner to be root, we need to sudo the mkinstallp\n # command, otherwise it will not have access to the previously chowned\n # directory.\n shellout!(\"sudo /usr/sbin/mkinstallp -d #{staging_dir} -T #{File.join(staging_dir, 'gen.template')}\")\n\n # Print the full contents of the inventory file generated by mkinstallp\n # from within the staging_dir's .info folder (where control files for the\n # packaging process are kept.)\n log.debug(log_key) do\n \"With .inventory file of:\\n\" + File.read(\"#{File.join( staging_dir, '.info', \"#{safe_base_package_name}.inventory\" )}\")\n end\n\n # Copy the resulting package up to the package_dir\n FileSyncer.glob(File.join(staging_dir, \"tmp/*.bff\")).each do |bff|\n copy_file(bff, File.join(Config.package_dir, create_bff_file_name))\n end\n\n ensure\n # chown back to original user's uid/gid so cleanup works correctly\n original_uid = shellout!(\"id -u\").stdout.chomp\n original_gid = shellout!(\"id -g\").stdout.chomp\n\n shellout!(\"sudo chown -Rh #{original_uid}:#{original_gid} #{staging_dir}\")\n end", "code_tokens": ["def", "create_bff_file", "# We are making the assumption that sudo exists.", "# Unforunately, the owner of the file in the staging directory is what", "# will be on the target machine, and mkinstallp can't tell you if that", "# is a bad thing (it usually is).", "# The match is so we only pick the lowest level of the project dir.", "# This implies that if we are in /tmp/staging/project/dir/things,", "# we will chown from 'project' on, rather than 'project/dir', which leaves", "# project owned by the build user (which is incorrect)", "# First - let's find out who we are.", "shellout!", "(", "\"sudo chown -Rh 0:0 #{File.join(staging_dir, project.install_dir.match(/^\\/?(\\w+)/).to_s)}\"", ")", "log", ".", "info", "(", "log_key", ")", "{", "\"Creating .bff file\"", "}", "# Since we want the owner to be root, we need to sudo the mkinstallp", "# command, otherwise it will not have access to the previously chowned", "# directory.", "shellout!", "(", "\"sudo /usr/sbin/mkinstallp -d #{staging_dir} -T #{File.join(staging_dir, 'gen.template')}\"", ")", "# Print the full contents of the inventory file generated by mkinstallp", "# from within the staging_dir's .info folder (where control files for the", "# packaging process are kept.)", "log", ".", "debug", "(", "log_key", ")", "do", "\"With .inventory file of:\\n\"", "+", "File", ".", "read", "(", "\"#{File.join( staging_dir, '.info', \"#{safe_base_package_name}.inventory\" )}\"", ")", "end", "# Copy the resulting package up to the package_dir", "FileSyncer", ".", "glob", "(", "File", ".", "join", "(", "staging_dir", ",", "\"tmp/*.bff\"", ")", ")", ".", "each", "do", "|", "bff", "|", "copy_file", "(", "bff", ",", "File", ".", "join", "(", "Config", ".", "package_dir", ",", "create_bff_file_name", ")", ")", "end", "ensure", "# chown back to original user's uid/gid so cleanup works correctly", "original_uid", "=", "shellout!", "(", "\"id -u\"", ")", ".", "stdout", ".", "chomp", "original_gid", "=", "shellout!", "(", "\"id -g\"", ")", ".", "stdout", ".", "chomp", "shellout!", "(", "\"sudo chown -Rh #{original_uid}:#{original_gid} #{staging_dir}\"", ")", "end"], "docstring": "Create the bff file using +mkinstallp+.\n\n Warning: This command runs as sudo! AIX requires the use of sudo to run\n the +mkinstallp+ command.\n\n @return [void]", "docstring_tokens": ["Create", "the", "bff", "file", "using", "+", "mkinstallp", "+", "."], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/packagers/bff.rb#L207-L243", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/file_syncer.rb", "func_name": "Omnibus.FileSyncer.glob", "original_string": "def glob(pattern)\n pattern = Pathname.new(pattern).cleanpath.to_s\n Dir.glob(pattern, File::FNM_DOTMATCH).sort.reject do |file|\n basename = File.basename(file)\n IGNORED_FILES.include?(basename)\n end\n end", "language": "ruby", "code": "def glob(pattern)\n pattern = Pathname.new(pattern).cleanpath.to_s\n Dir.glob(pattern, File::FNM_DOTMATCH).sort.reject do |file|\n basename = File.basename(file)\n IGNORED_FILES.include?(basename)\n end\n end", "code_tokens": ["def", "glob", "(", "pattern", ")", "pattern", "=", "Pathname", ".", "new", "(", "pattern", ")", ".", "cleanpath", ".", "to_s", "Dir", ".", "glob", "(", "pattern", ",", "File", "::", "FNM_DOTMATCH", ")", ".", "sort", ".", "reject", "do", "|", "file", "|", "basename", "=", "File", ".", "basename", "(", "file", ")", "IGNORED_FILES", ".", "include?", "(", "basename", ")", "end", "end"], "docstring": "Glob across the given pattern, accounting for dotfiles, removing Ruby's\n dumb idea to include +'.'+ and +'..'+ as entries.\n\n @param [String] pattern\n the path or glob pattern to get all files from\n\n @return [Array]\n the list of all files", "docstring_tokens": ["Glob", "across", "the", "given", "pattern", "accounting", "for", "dotfiles", "removing", "Ruby", "s", "dumb", "idea", "to", "include", "+", ".", "+", "and", "+", "..", "+", "as", "entries", "."], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/file_syncer.rb#L36-L42", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/file_syncer.rb", "func_name": "Omnibus.FileSyncer.sync", "original_string": "def sync(source, destination, options = {})\n unless File.directory?(source)\n raise ArgumentError, \"`source' must be a directory, but was a \" \\\n \"`#{File.ftype(source)}'! If you just want to sync a file, use \" \\\n \"the `copy' method instead.\"\n end\n\n source_files = all_files_under(source, options)\n\n # Ensure the destination directory exists\n FileUtils.mkdir_p(destination) unless File.directory?(destination)\n\n # Copy over the filtered source files\n source_files.each do |source_file|\n relative_path = relative_path_for(source_file, source)\n\n # Create the parent directory\n parent = File.join(destination, File.dirname(relative_path))\n FileUtils.mkdir_p(parent) unless File.directory?(parent)\n\n case File.ftype(source_file).to_sym\n when :directory\n FileUtils.mkdir_p(\"#{destination}/#{relative_path}\")\n when :link\n target = File.readlink(source_file)\n\n Dir.chdir(destination) do\n FileUtils.ln_sf(target, \"#{destination}/#{relative_path}\")\n end\n when :file\n source_stat = File.stat(source_file)\n # Detect 'files' which are hard links and use ln instead of cp to\n # duplicate them, provided their source is in place already\n if hardlink? source_stat\n if existing = hardlink_sources[[source_stat.dev, source_stat.ino]]\n FileUtils.ln(existing, \"#{destination}/#{relative_path}\", force: true)\n else\n begin\n FileUtils.cp(source_file, \"#{destination}/#{relative_path}\")\n rescue Errno::EACCES\n FileUtils.cp_r(source_file, \"#{destination}/#{relative_path}\", remove_destination: true)\n end\n hardlink_sources.store([source_stat.dev, source_stat.ino], \"#{destination}/#{relative_path}\")\n end\n else\n # First attempt a regular copy. If we don't have write\n # permission on the File, open will probably fail with\n # EACCES (making it hard to sync files with permission\n # r--r--r--). Rescue this error and use cp_r's\n # :remove_destination option.\n begin\n FileUtils.cp(source_file, \"#{destination}/#{relative_path}\")\n rescue Errno::EACCES\n FileUtils.cp_r(source_file, \"#{destination}/#{relative_path}\", remove_destination: true)\n end\n end\n else\n raise \"Unknown file type: `File.ftype(source_file)' at `#{source_file}'!\"\n end\n end\n\n # Remove any files in the destination that are not in the source files\n destination_files = glob(\"#{destination}/**/*\")\n\n # Calculate the relative paths of files so we can compare to the\n # source.\n relative_source_files = source_files.map do |file|\n relative_path_for(file, source)\n end\n relative_destination_files = destination_files.map do |file|\n relative_path_for(file, destination)\n end\n\n # Remove any extra files that are present in the destination, but are\n # not in the source list\n extra_files = relative_destination_files - relative_source_files\n extra_files.each do |file|\n FileUtils.rm_rf(File.join(destination, file))\n end\n\n true\n end", "language": "ruby", "code": "def sync(source, destination, options = {})\n unless File.directory?(source)\n raise ArgumentError, \"`source' must be a directory, but was a \" \\\n \"`#{File.ftype(source)}'! If you just want to sync a file, use \" \\\n \"the `copy' method instead.\"\n end\n\n source_files = all_files_under(source, options)\n\n # Ensure the destination directory exists\n FileUtils.mkdir_p(destination) unless File.directory?(destination)\n\n # Copy over the filtered source files\n source_files.each do |source_file|\n relative_path = relative_path_for(source_file, source)\n\n # Create the parent directory\n parent = File.join(destination, File.dirname(relative_path))\n FileUtils.mkdir_p(parent) unless File.directory?(parent)\n\n case File.ftype(source_file).to_sym\n when :directory\n FileUtils.mkdir_p(\"#{destination}/#{relative_path}\")\n when :link\n target = File.readlink(source_file)\n\n Dir.chdir(destination) do\n FileUtils.ln_sf(target, \"#{destination}/#{relative_path}\")\n end\n when :file\n source_stat = File.stat(source_file)\n # Detect 'files' which are hard links and use ln instead of cp to\n # duplicate them, provided their source is in place already\n if hardlink? source_stat\n if existing = hardlink_sources[[source_stat.dev, source_stat.ino]]\n FileUtils.ln(existing, \"#{destination}/#{relative_path}\", force: true)\n else\n begin\n FileUtils.cp(source_file, \"#{destination}/#{relative_path}\")\n rescue Errno::EACCES\n FileUtils.cp_r(source_file, \"#{destination}/#{relative_path}\", remove_destination: true)\n end\n hardlink_sources.store([source_stat.dev, source_stat.ino], \"#{destination}/#{relative_path}\")\n end\n else\n # First attempt a regular copy. If we don't have write\n # permission on the File, open will probably fail with\n # EACCES (making it hard to sync files with permission\n # r--r--r--). Rescue this error and use cp_r's\n # :remove_destination option.\n begin\n FileUtils.cp(source_file, \"#{destination}/#{relative_path}\")\n rescue Errno::EACCES\n FileUtils.cp_r(source_file, \"#{destination}/#{relative_path}\", remove_destination: true)\n end\n end\n else\n raise \"Unknown file type: `File.ftype(source_file)' at `#{source_file}'!\"\n end\n end\n\n # Remove any files in the destination that are not in the source files\n destination_files = glob(\"#{destination}/**/*\")\n\n # Calculate the relative paths of files so we can compare to the\n # source.\n relative_source_files = source_files.map do |file|\n relative_path_for(file, source)\n end\n relative_destination_files = destination_files.map do |file|\n relative_path_for(file, destination)\n end\n\n # Remove any extra files that are present in the destination, but are\n # not in the source list\n extra_files = relative_destination_files - relative_source_files\n extra_files.each do |file|\n FileUtils.rm_rf(File.join(destination, file))\n end\n\n true\n end", "code_tokens": ["def", "sync", "(", "source", ",", "destination", ",", "options", "=", "{", "}", ")", "unless", "File", ".", "directory?", "(", "source", ")", "raise", "ArgumentError", ",", "\"`source' must be a directory, but was a \"", "\"`#{File.ftype(source)}'! If you just want to sync a file, use \"", "\"the `copy' method instead.\"", "end", "source_files", "=", "all_files_under", "(", "source", ",", "options", ")", "# Ensure the destination directory exists", "FileUtils", ".", "mkdir_p", "(", "destination", ")", "unless", "File", ".", "directory?", "(", "destination", ")", "# Copy over the filtered source files", "source_files", ".", "each", "do", "|", "source_file", "|", "relative_path", "=", "relative_path_for", "(", "source_file", ",", "source", ")", "# Create the parent directory", "parent", "=", "File", ".", "join", "(", "destination", ",", "File", ".", "dirname", "(", "relative_path", ")", ")", "FileUtils", ".", "mkdir_p", "(", "parent", ")", "unless", "File", ".", "directory?", "(", "parent", ")", "case", "File", ".", "ftype", "(", "source_file", ")", ".", "to_sym", "when", ":directory", "FileUtils", ".", "mkdir_p", "(", "\"#{destination}/#{relative_path}\"", ")", "when", ":link", "target", "=", "File", ".", "readlink", "(", "source_file", ")", "Dir", ".", "chdir", "(", "destination", ")", "do", "FileUtils", ".", "ln_sf", "(", "target", ",", "\"#{destination}/#{relative_path}\"", ")", "end", "when", ":file", "source_stat", "=", "File", ".", "stat", "(", "source_file", ")", "# Detect 'files' which are hard links and use ln instead of cp to", "# duplicate them, provided their source is in place already", "if", "hardlink?", "source_stat", "if", "existing", "=", "hardlink_sources", "[", "[", "source_stat", ".", "dev", ",", "source_stat", ".", "ino", "]", "]", "FileUtils", ".", "ln", "(", "existing", ",", "\"#{destination}/#{relative_path}\"", ",", "force", ":", "true", ")", "else", "begin", "FileUtils", ".", "cp", "(", "source_file", ",", "\"#{destination}/#{relative_path}\"", ")", "rescue", "Errno", "::", "EACCES", "FileUtils", ".", "cp_r", "(", "source_file", ",", "\"#{destination}/#{relative_path}\"", ",", "remove_destination", ":", "true", ")", "end", "hardlink_sources", ".", "store", "(", "[", "source_stat", ".", "dev", ",", "source_stat", ".", "ino", "]", ",", "\"#{destination}/#{relative_path}\"", ")", "end", "else", "# First attempt a regular copy. If we don't have write", "# permission on the File, open will probably fail with", "# EACCES (making it hard to sync files with permission", "# r--r--r--). Rescue this error and use cp_r's", "# :remove_destination option.", "begin", "FileUtils", ".", "cp", "(", "source_file", ",", "\"#{destination}/#{relative_path}\"", ")", "rescue", "Errno", "::", "EACCES", "FileUtils", ".", "cp_r", "(", "source_file", ",", "\"#{destination}/#{relative_path}\"", ",", "remove_destination", ":", "true", ")", "end", "end", "else", "raise", "\"Unknown file type: `File.ftype(source_file)' at `#{source_file}'!\"", "end", "end", "# Remove any files in the destination that are not in the source files", "destination_files", "=", "glob", "(", "\"#{destination}/**/*\"", ")", "# Calculate the relative paths of files so we can compare to the", "# source.", "relative_source_files", "=", "source_files", ".", "map", "do", "|", "file", "|", "relative_path_for", "(", "file", ",", "source", ")", "end", "relative_destination_files", "=", "destination_files", ".", "map", "do", "|", "file", "|", "relative_path_for", "(", "file", ",", "destination", ")", "end", "# Remove any extra files that are present in the destination, but are", "# not in the source list", "extra_files", "=", "relative_destination_files", "-", "relative_source_files", "extra_files", ".", "each", "do", "|", "file", "|", "FileUtils", ".", "rm_rf", "(", "File", ".", "join", "(", "destination", ",", "file", ")", ")", "end", "true", "end"], "docstring": "Copy the files from +source+ to +destination+, while removing any files\n in +destination+ that are not present in +source+.\n\n The method accepts an optional +:exclude+ parameter to ignore files and\n folders that match the given pattern(s). Note the exclude pattern behaves\n on paths relative to the given source. If you want to exclude a nested\n directory, you will need to use something like +**/directory+.\n\n @raise ArgumentError\n if the +source+ parameter is not a directory\n\n @param [String] source\n the path on disk to sync from\n @param [String] destination\n the path on disk to sync to\n\n @option options [String, Array] :exclude\n a file, folder, or globbing pattern of files to ignore when syncing\n\n @return [true]", "docstring_tokens": ["Copy", "the", "files", "from", "+", "source", "+", "to", "+", "destination", "+", "while", "removing", "any", "files", "in", "+", "destination", "+", "that", "are", "not", "present", "in", "+", "source", "+", "."], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/file_syncer.rb#L91-L172", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/file_syncer.rb", "func_name": "Omnibus.FileSyncer.relative_path_for", "original_string": "def relative_path_for(path, parent)\n Pathname.new(path).relative_path_from(Pathname.new(parent)).to_s\n end", "language": "ruby", "code": "def relative_path_for(path, parent)\n Pathname.new(path).relative_path_from(Pathname.new(parent)).to_s\n end", "code_tokens": ["def", "relative_path_for", "(", "path", ",", "parent", ")", "Pathname", ".", "new", "(", "path", ")", ".", "relative_path_from", "(", "Pathname", ".", "new", "(", "parent", ")", ")", ".", "to_s", "end"], "docstring": "The relative path of the given +path+ to the +parent+.\n\n @param [String] path\n the path to get relative with\n @param [String] parent\n the parent where the path is contained (hopefully)\n\n @return [String]", "docstring_tokens": ["The", "relative", "path", "of", "the", "given", "+", "path", "+", "to", "the", "+", "parent", "+", "."], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/file_syncer.rb#L186-L188", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/compressors/dmg.rb", "func_name": "Omnibus.Compressor::DMG.clean_disks", "original_string": "def clean_disks\n log.info(log_key) { \"Cleaning previously mounted disks\" }\n\n existing_disks = shellout!(\"mount | grep \\\"/Volumes/#{volume_name}\\\" | awk '{print $1}'\")\n existing_disks.stdout.lines.each do |existing_disk|\n existing_disk.chomp!\n\n Omnibus.logger.debug(log_key) do\n \"Detaching disk `#{existing_disk}' before starting dmg packaging.\"\n end\n\n shellout!(\"hdiutil detach '#{existing_disk}'\")\n end\n end", "language": "ruby", "code": "def clean_disks\n log.info(log_key) { \"Cleaning previously mounted disks\" }\n\n existing_disks = shellout!(\"mount | grep \\\"/Volumes/#{volume_name}\\\" | awk '{print $1}'\")\n existing_disks.stdout.lines.each do |existing_disk|\n existing_disk.chomp!\n\n Omnibus.logger.debug(log_key) do\n \"Detaching disk `#{existing_disk}' before starting dmg packaging.\"\n end\n\n shellout!(\"hdiutil detach '#{existing_disk}'\")\n end\n end", "code_tokens": ["def", "clean_disks", "log", ".", "info", "(", "log_key", ")", "{", "\"Cleaning previously mounted disks\"", "}", "existing_disks", "=", "shellout!", "(", "\"mount | grep \\\"/Volumes/#{volume_name}\\\" | awk '{print $1}'\"", ")", "existing_disks", ".", "stdout", ".", "lines", ".", "each", "do", "|", "existing_disk", "|", "existing_disk", ".", "chomp!", "Omnibus", ".", "logger", ".", "debug", "(", "log_key", ")", "do", "\"Detaching disk `#{existing_disk}' before starting dmg packaging.\"", "end", "shellout!", "(", "\"hdiutil detach '#{existing_disk}'\"", ")", "end", "end"], "docstring": "Cleans any previously left over mounted disks.\n\n We are trying to detach disks that look like:\n\n /dev/disk1s1 on /Volumes/chef (hfs, local, nodev, nosuid, read-only, noowners, quarantine, mounted by serdar)\n /dev/disk2s1 on /Volumes/chef 1 (hfs, local, nodev, nosuid, read-only, noowners, quarantine, mounted by serdar)\n\n @return [void]", "docstring_tokens": ["Cleans", "any", "previously", "left", "over", "mounted", "disks", "."], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/compressors/dmg.rb#L119-L132", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/compressors/dmg.rb", "func_name": "Omnibus.Compressor::DMG.copy_assets_to_dmg", "original_string": "def copy_assets_to_dmg\n log.info(log_key) { \"Copying assets into dmg\" }\n\n FileSyncer.glob(\"#{resources_dir}/*\").each do |file|\n FileUtils.cp_r(file, \"/Volumes/#{volume_name}\")\n end\n end", "language": "ruby", "code": "def copy_assets_to_dmg\n log.info(log_key) { \"Copying assets into dmg\" }\n\n FileSyncer.glob(\"#{resources_dir}/*\").each do |file|\n FileUtils.cp_r(file, \"/Volumes/#{volume_name}\")\n end\n end", "code_tokens": ["def", "copy_assets_to_dmg", "log", ".", "info", "(", "log_key", ")", "{", "\"Copying assets into dmg\"", "}", "FileSyncer", ".", "glob", "(", "\"#{resources_dir}/*\"", ")", ".", "each", "do", "|", "file", "|", "FileUtils", ".", "cp_r", "(", "file", ",", "\"/Volumes/#{volume_name}\"", ")", "end", "end"], "docstring": "Copy assets to dmg", "docstring_tokens": ["Copy", "assets", "to", "dmg"], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/compressors/dmg.rb#L175-L181", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/packagers/ips.rb", "func_name": "Omnibus.Packager::IPS.write_transform_file", "original_string": "def write_transform_file\n render_template(resource_path(\"doc-transform.erb\"),\n destination: transform_file,\n variables: {\n pathdir: project.install_dir.split(\"/\")[1],\n }\n )\n end", "language": "ruby", "code": "def write_transform_file\n render_template(resource_path(\"doc-transform.erb\"),\n destination: transform_file,\n variables: {\n pathdir: project.install_dir.split(\"/\")[1],\n }\n )\n end", "code_tokens": ["def", "write_transform_file", "render_template", "(", "resource_path", "(", "\"doc-transform.erb\"", ")", ",", "destination", ":", "transform_file", ",", "variables", ":", "{", "pathdir", ":", "project", ".", "install_dir", ".", "split", "(", "\"/\"", ")", "[", "1", "]", ",", "}", ")", "end"], "docstring": "A set of transform rules that `pkgmogrify' will apply to the package\n manifest.\n\n @return [void]", "docstring_tokens": ["A", "set", "of", "transform", "rules", "that", "pkgmogrify", "will", "apply", "to", "the", "package", "manifest", "."], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/packagers/ips.rb#L207-L214", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/packagers/ips.rb", "func_name": "Omnibus.Packager::IPS.write_pkg_metadata", "original_string": "def write_pkg_metadata\n render_template(resource_path(\"gen.manifestfile.erb\"),\n destination: pkg_metadata_file,\n variables: {\n name: safe_base_package_name,\n fmri_package_name: fmri_package_name,\n description: project.description,\n summary: project.friendly_name,\n arch: safe_architecture,\n }\n )\n\n # Append the contents of symlinks_file if it exists\n if symlinks_file\n File.open(pkg_metadata_file, \"a\") do |symlink|\n symlink.write(render_symlinks)\n end\n end\n\n # Print the full contents of the rendered template file to generate package contents\n log.debug(log_key) { \"Rendered Template:\\n\" + File.read(pkg_metadata_file) }\n end", "language": "ruby", "code": "def write_pkg_metadata\n render_template(resource_path(\"gen.manifestfile.erb\"),\n destination: pkg_metadata_file,\n variables: {\n name: safe_base_package_name,\n fmri_package_name: fmri_package_name,\n description: project.description,\n summary: project.friendly_name,\n arch: safe_architecture,\n }\n )\n\n # Append the contents of symlinks_file if it exists\n if symlinks_file\n File.open(pkg_metadata_file, \"a\") do |symlink|\n symlink.write(render_symlinks)\n end\n end\n\n # Print the full contents of the rendered template file to generate package contents\n log.debug(log_key) { \"Rendered Template:\\n\" + File.read(pkg_metadata_file) }\n end", "code_tokens": ["def", "write_pkg_metadata", "render_template", "(", "resource_path", "(", "\"gen.manifestfile.erb\"", ")", ",", "destination", ":", "pkg_metadata_file", ",", "variables", ":", "{", "name", ":", "safe_base_package_name", ",", "fmri_package_name", ":", "fmri_package_name", ",", "description", ":", "project", ".", "description", ",", "summary", ":", "project", ".", "friendly_name", ",", "arch", ":", "safe_architecture", ",", "}", ")", "# Append the contents of symlinks_file if it exists", "if", "symlinks_file", "File", ".", "open", "(", "pkg_metadata_file", ",", "\"a\"", ")", "do", "|", "symlink", "|", "symlink", ".", "write", "(", "render_symlinks", ")", "end", "end", "# Print the full contents of the rendered template file to generate package contents", "log", ".", "debug", "(", "log_key", ")", "{", "\"Rendered Template:\\n\"", "+", "File", ".", "read", "(", "pkg_metadata_file", ")", "}", "end"], "docstring": "Generate package metadata\n\n Create the gen template for `pkgmogrify`\n\n @return [void]", "docstring_tokens": ["Generate", "package", "metadata"], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/packagers/ips.rb#L256-L277", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/health_check.rb", "func_name": "Omnibus.HealthCheck.health_check_otool", "original_string": "def health_check_otool\n current_library = nil\n bad_libs = {}\n\n read_shared_libs(\"find #{project.install_dir}/ -type f | egrep '\\.(dylib|bundle)$' | xargs otool -L\") do |line|\n case line\n when /^(.+):$/\n current_library = Regexp.last_match[1]\n when /^\\s+(.+) \\(.+\\)$/\n linked = Regexp.last_match[1]\n name = File.basename(linked)\n bad_libs = check_for_bad_library(bad_libs, current_library, name, linked)\n end\n end\n\n bad_libs\n end", "language": "ruby", "code": "def health_check_otool\n current_library = nil\n bad_libs = {}\n\n read_shared_libs(\"find #{project.install_dir}/ -type f | egrep '\\.(dylib|bundle)$' | xargs otool -L\") do |line|\n case line\n when /^(.+):$/\n current_library = Regexp.last_match[1]\n when /^\\s+(.+) \\(.+\\)$/\n linked = Regexp.last_match[1]\n name = File.basename(linked)\n bad_libs = check_for_bad_library(bad_libs, current_library, name, linked)\n end\n end\n\n bad_libs\n end", "code_tokens": ["def", "health_check_otool", "current_library", "=", "nil", "bad_libs", "=", "{", "}", "read_shared_libs", "(", "\"find #{project.install_dir}/ -type f | egrep '\\.(dylib|bundle)$' | xargs otool -L\"", ")", "do", "|", "line", "|", "case", "line", "when", "/", "/", "current_library", "=", "Regexp", ".", "last_match", "[", "1", "]", "when", "/", "\\s", "\\(", "\\)", "/", "linked", "=", "Regexp", ".", "last_match", "[", "1", "]", "name", "=", "File", ".", "basename", "(", "linked", ")", "bad_libs", "=", "check_for_bad_library", "(", "bad_libs", ",", "current_library", ",", "name", ",", "linked", ")", "end", "end", "bad_libs", "end"], "docstring": "Run healthchecks against otool.\n\n @return [Hash>>]\n the bad libraries (library_name -> dependency_name -> satisfied_lib_path -> count)", "docstring_tokens": ["Run", "healthchecks", "against", "otool", "."], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/health_check.rb#L280-L296", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/health_check.rb", "func_name": "Omnibus.HealthCheck.health_check_aix", "original_string": "def health_check_aix\n current_library = nil\n bad_libs = {}\n\n read_shared_libs(\"find #{project.install_dir}/ -type f | xargs file | grep \\\"RISC System\\\" | awk -F: '{print $1}' | xargs -n 1 ldd\") do |line|\n case line\n when /^(.+) needs:$/\n current_library = Regexp.last_match[1]\n log.debug(log_key) { \"Analyzing dependencies for #{current_library}\" }\n when /^\\s+(.+)$/\n name = Regexp.last_match[1]\n linked = Regexp.last_match[1]\n bad_libs = check_for_bad_library(bad_libs, current_library, name, linked)\n when /File is not an executable XCOFF file/ # ignore non-executable files\n else\n log.warn(log_key) { \"Line did not match for #{current_library}\\n#{line}\" }\n end\n end\n\n bad_libs\n end", "language": "ruby", "code": "def health_check_aix\n current_library = nil\n bad_libs = {}\n\n read_shared_libs(\"find #{project.install_dir}/ -type f | xargs file | grep \\\"RISC System\\\" | awk -F: '{print $1}' | xargs -n 1 ldd\") do |line|\n case line\n when /^(.+) needs:$/\n current_library = Regexp.last_match[1]\n log.debug(log_key) { \"Analyzing dependencies for #{current_library}\" }\n when /^\\s+(.+)$/\n name = Regexp.last_match[1]\n linked = Regexp.last_match[1]\n bad_libs = check_for_bad_library(bad_libs, current_library, name, linked)\n when /File is not an executable XCOFF file/ # ignore non-executable files\n else\n log.warn(log_key) { \"Line did not match for #{current_library}\\n#{line}\" }\n end\n end\n\n bad_libs\n end", "code_tokens": ["def", "health_check_aix", "current_library", "=", "nil", "bad_libs", "=", "{", "}", "read_shared_libs", "(", "\"find #{project.install_dir}/ -type f | xargs file | grep \\\"RISC System\\\" | awk -F: '{print $1}' | xargs -n 1 ldd\"", ")", "do", "|", "line", "|", "case", "line", "when", "/", "/", "current_library", "=", "Regexp", ".", "last_match", "[", "1", "]", "log", ".", "debug", "(", "log_key", ")", "{", "\"Analyzing dependencies for #{current_library}\"", "}", "when", "/", "\\s", "/", "name", "=", "Regexp", ".", "last_match", "[", "1", "]", "linked", "=", "Regexp", ".", "last_match", "[", "1", "]", "bad_libs", "=", "check_for_bad_library", "(", "bad_libs", ",", "current_library", ",", "name", ",", "linked", ")", "when", "/", "/", "# ignore non-executable files", "else", "log", ".", "warn", "(", "log_key", ")", "{", "\"Line did not match for #{current_library}\\n#{line}\"", "}", "end", "end", "bad_libs", "end"], "docstring": "Run healthchecks against aix.\n\n @return [Hash>>]\n the bad libraries (library_name -> dependency_name -> satisfied_lib_path -> count)", "docstring_tokens": ["Run", "healthchecks", "against", "aix", "."], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/health_check.rb#L304-L324", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/health_check.rb", "func_name": "Omnibus.HealthCheck.health_check_ldd", "original_string": "def health_check_ldd\n regexp_ends = \".*(\" + IGNORED_ENDINGS.map { |e| e.gsub(/\\./, '\\.') }.join(\"|\") + \")$\"\n regexp_patterns = IGNORED_PATTERNS.map { |e| \".*\" + e.gsub(/\\//, '\\/') + \".*\" }.join(\"|\")\n regexp = regexp_ends + \"|\" + regexp_patterns\n\n current_library = nil\n bad_libs = {}\n\n read_shared_libs(\"find #{project.install_dir}/ -type f -regextype posix-extended ! -regex '#{regexp}' | xargs ldd\") do |line|\n case line\n when /^(.+):$/\n current_library = Regexp.last_match[1]\n log.debug(log_key) { \"Analyzing dependencies for #{current_library}\" }\n when /^\\s+(.+) \\=\\>\\s+(.+)( \\(.+\\))?$/\n name = Regexp.last_match[1]\n linked = Regexp.last_match[2]\n bad_libs = check_for_bad_library(bad_libs, current_library, name, linked)\n when /^\\s+(.+) \\(.+\\)$/\n next\n when /^\\s+statically linked$/\n next\n when /^\\s+libjvm.so/\n next\n when /^\\s+libjava.so/\n next\n when /^\\s+libmawt.so/\n next\n when /^\\s+not a dynamic executable$/ # ignore non-executable files\n else\n log.warn(log_key) do\n \"Line did not match for #{current_library}\\n#{line}\"\n end\n end\n end\n\n bad_libs\n end", "language": "ruby", "code": "def health_check_ldd\n regexp_ends = \".*(\" + IGNORED_ENDINGS.map { |e| e.gsub(/\\./, '\\.') }.join(\"|\") + \")$\"\n regexp_patterns = IGNORED_PATTERNS.map { |e| \".*\" + e.gsub(/\\//, '\\/') + \".*\" }.join(\"|\")\n regexp = regexp_ends + \"|\" + regexp_patterns\n\n current_library = nil\n bad_libs = {}\n\n read_shared_libs(\"find #{project.install_dir}/ -type f -regextype posix-extended ! -regex '#{regexp}' | xargs ldd\") do |line|\n case line\n when /^(.+):$/\n current_library = Regexp.last_match[1]\n log.debug(log_key) { \"Analyzing dependencies for #{current_library}\" }\n when /^\\s+(.+) \\=\\>\\s+(.+)( \\(.+\\))?$/\n name = Regexp.last_match[1]\n linked = Regexp.last_match[2]\n bad_libs = check_for_bad_library(bad_libs, current_library, name, linked)\n when /^\\s+(.+) \\(.+\\)$/\n next\n when /^\\s+statically linked$/\n next\n when /^\\s+libjvm.so/\n next\n when /^\\s+libjava.so/\n next\n when /^\\s+libmawt.so/\n next\n when /^\\s+not a dynamic executable$/ # ignore non-executable files\n else\n log.warn(log_key) do\n \"Line did not match for #{current_library}\\n#{line}\"\n end\n end\n end\n\n bad_libs\n end", "code_tokens": ["def", "health_check_ldd", "regexp_ends", "=", "\".*(\"", "+", "IGNORED_ENDINGS", ".", "map", "{", "|", "e", "|", "e", ".", "gsub", "(", "/", "\\.", "/", ",", "'\\.'", ")", "}", ".", "join", "(", "\"|\"", ")", "+", "\")$\"", "regexp_patterns", "=", "IGNORED_PATTERNS", ".", "map", "{", "|", "e", "|", "\".*\"", "+", "e", ".", "gsub", "(", "/", "\\/", "/", ",", "'\\/'", ")", "+", "\".*\"", "}", ".", "join", "(", "\"|\"", ")", "regexp", "=", "regexp_ends", "+", "\"|\"", "+", "regexp_patterns", "current_library", "=", "nil", "bad_libs", "=", "{", "}", "read_shared_libs", "(", "\"find #{project.install_dir}/ -type f -regextype posix-extended ! -regex '#{regexp}' | xargs ldd\"", ")", "do", "|", "line", "|", "case", "line", "when", "/", "/", "current_library", "=", "Regexp", ".", "last_match", "[", "1", "]", "log", ".", "debug", "(", "log_key", ")", "{", "\"Analyzing dependencies for #{current_library}\"", "}", "when", "/", "\\s", "\\=", "\\>", "\\s", "\\(", "\\)", "/", "name", "=", "Regexp", ".", "last_match", "[", "1", "]", "linked", "=", "Regexp", ".", "last_match", "[", "2", "]", "bad_libs", "=", "check_for_bad_library", "(", "bad_libs", ",", "current_library", ",", "name", ",", "linked", ")", "when", "/", "\\s", "\\(", "\\)", "/", "next", "when", "/", "\\s", "/", "next", "when", "/", "\\s", "/", "next", "when", "/", "\\s", "/", "next", "when", "/", "\\s", "/", "next", "when", "/", "\\s", "/", "# ignore non-executable files", "else", "log", ".", "warn", "(", "log_key", ")", "do", "\"Line did not match for #{current_library}\\n#{line}\"", "end", "end", "end", "bad_libs", "end"], "docstring": "Run healthchecks against ldd.\n\n @return [Hash>>]\n the bad libraries (library_name -> dependency_name -> satisfied_lib_path -> count)", "docstring_tokens": ["Run", "healthchecks", "against", "ldd", "."], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/health_check.rb#L332-L368", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/health_check.rb", "func_name": "Omnibus.HealthCheck.read_shared_libs", "original_string": "def read_shared_libs(command)\n cmd = shellout(command)\n cmd.stdout.each_line do |line|\n yield line\n end\n end", "language": "ruby", "code": "def read_shared_libs(command)\n cmd = shellout(command)\n cmd.stdout.each_line do |line|\n yield line\n end\n end", "code_tokens": ["def", "read_shared_libs", "(", "command", ")", "cmd", "=", "shellout", "(", "command", ")", "cmd", ".", "stdout", ".", "each_line", "do", "|", "line", "|", "yield", "line", "end", "end"], "docstring": "Execute the given command, yielding each line.\n\n @param [String] command\n the command to execute\n @yield [String]\n each line", "docstring_tokens": ["Execute", "the", "given", "command", "yielding", "each", "line", "."], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/health_check.rb#L402-L407", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/health_check.rb", "func_name": "Omnibus.HealthCheck.check_for_bad_library", "original_string": "def check_for_bad_library(bad_libs, current_library, name, linked)\n safe = nil\n\n whitelist_libs = case Ohai[\"platform\"]\n when \"arch\"\n ARCH_WHITELIST_LIBS\n when \"mac_os_x\"\n MAC_WHITELIST_LIBS\n when \"solaris2\"\n SOLARIS_WHITELIST_LIBS\n when \"smartos\"\n SMARTOS_WHITELIST_LIBS\n when \"freebsd\"\n FREEBSD_WHITELIST_LIBS\n when \"aix\"\n AIX_WHITELIST_LIBS\n else\n WHITELIST_LIBS\n end\n\n whitelist_libs.each do |reg|\n safe ||= true if reg.match(name)\n end\n\n whitelist_files.each do |reg|\n safe ||= true if reg.match(current_library)\n end\n\n log.debug(log_key) { \" --> Dependency: #{name}\" }\n log.debug(log_key) { \" --> Provided by: #{linked}\" }\n\n if !safe && linked !~ Regexp.new(project.install_dir)\n log.debug(log_key) { \" -> FAILED: #{current_library} has unsafe dependencies\" }\n bad_libs[current_library] ||= {}\n bad_libs[current_library][name] ||= {}\n if bad_libs[current_library][name].key?(linked)\n bad_libs[current_library][name][linked] += 1\n else\n bad_libs[current_library][name][linked] = 1\n end\n else\n log.debug(log_key) { \" -> PASSED: #{name} is either whitelisted or safely provided.\" }\n end\n\n bad_libs\n end", "language": "ruby", "code": "def check_for_bad_library(bad_libs, current_library, name, linked)\n safe = nil\n\n whitelist_libs = case Ohai[\"platform\"]\n when \"arch\"\n ARCH_WHITELIST_LIBS\n when \"mac_os_x\"\n MAC_WHITELIST_LIBS\n when \"solaris2\"\n SOLARIS_WHITELIST_LIBS\n when \"smartos\"\n SMARTOS_WHITELIST_LIBS\n when \"freebsd\"\n FREEBSD_WHITELIST_LIBS\n when \"aix\"\n AIX_WHITELIST_LIBS\n else\n WHITELIST_LIBS\n end\n\n whitelist_libs.each do |reg|\n safe ||= true if reg.match(name)\n end\n\n whitelist_files.each do |reg|\n safe ||= true if reg.match(current_library)\n end\n\n log.debug(log_key) { \" --> Dependency: #{name}\" }\n log.debug(log_key) { \" --> Provided by: #{linked}\" }\n\n if !safe && linked !~ Regexp.new(project.install_dir)\n log.debug(log_key) { \" -> FAILED: #{current_library} has unsafe dependencies\" }\n bad_libs[current_library] ||= {}\n bad_libs[current_library][name] ||= {}\n if bad_libs[current_library][name].key?(linked)\n bad_libs[current_library][name][linked] += 1\n else\n bad_libs[current_library][name][linked] = 1\n end\n else\n log.debug(log_key) { \" -> PASSED: #{name} is either whitelisted or safely provided.\" }\n end\n\n bad_libs\n end", "code_tokens": ["def", "check_for_bad_library", "(", "bad_libs", ",", "current_library", ",", "name", ",", "linked", ")", "safe", "=", "nil", "whitelist_libs", "=", "case", "Ohai", "[", "\"platform\"", "]", "when", "\"arch\"", "ARCH_WHITELIST_LIBS", "when", "\"mac_os_x\"", "MAC_WHITELIST_LIBS", "when", "\"solaris2\"", "SOLARIS_WHITELIST_LIBS", "when", "\"smartos\"", "SMARTOS_WHITELIST_LIBS", "when", "\"freebsd\"", "FREEBSD_WHITELIST_LIBS", "when", "\"aix\"", "AIX_WHITELIST_LIBS", "else", "WHITELIST_LIBS", "end", "whitelist_libs", ".", "each", "do", "|", "reg", "|", "safe", "||=", "true", "if", "reg", ".", "match", "(", "name", ")", "end", "whitelist_files", ".", "each", "do", "|", "reg", "|", "safe", "||=", "true", "if", "reg", ".", "match", "(", "current_library", ")", "end", "log", ".", "debug", "(", "log_key", ")", "{", "\" --> Dependency: #{name}\"", "}", "log", ".", "debug", "(", "log_key", ")", "{", "\" --> Provided by: #{linked}\"", "}", "if", "!", "safe", "&&", "linked", "!~", "Regexp", ".", "new", "(", "project", ".", "install_dir", ")", "log", ".", "debug", "(", "log_key", ")", "{", "\" -> FAILED: #{current_library} has unsafe dependencies\"", "}", "bad_libs", "[", "current_library", "]", "||=", "{", "}", "bad_libs", "[", "current_library", "]", "[", "name", "]", "||=", "{", "}", "if", "bad_libs", "[", "current_library", "]", "[", "name", "]", ".", "key?", "(", "linked", ")", "bad_libs", "[", "current_library", "]", "[", "name", "]", "[", "linked", "]", "+=", "1", "else", "bad_libs", "[", "current_library", "]", "[", "name", "]", "[", "linked", "]", "=", "1", "end", "else", "log", ".", "debug", "(", "log_key", ")", "{", "\" -> PASSED: #{name} is either whitelisted or safely provided.\"", "}", "end", "bad_libs", "end"], "docstring": "Check the given path and library for \"bad\" libraries.\n\n @param [Hash>>]\n the bad libraries (library_name -> dependency_name -> satisfied_lib_path -> count)\n @param [String]\n the library being analyzed\n @param [String]\n dependency library name\n @param [String]\n actual path of library satisfying the dependency\n\n @return the modified bad_library hash", "docstring_tokens": ["Check", "the", "given", "path", "and", "library", "for", "bad", "libraries", "."], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/health_check.rb#L423-L468", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/digestable.rb", "func_name": "Omnibus.Digestable.digest", "original_string": "def digest(path, type = :md5)\n digest = digest_from_type(type)\n\n update_with_file_contents(digest, path)\n digest.hexdigest\n end", "language": "ruby", "code": "def digest(path, type = :md5)\n digest = digest_from_type(type)\n\n update_with_file_contents(digest, path)\n digest.hexdigest\n end", "code_tokens": ["def", "digest", "(", "path", ",", "type", "=", ":md5", ")", "digest", "=", "digest_from_type", "(", "type", ")", "update_with_file_contents", "(", "digest", ",", "path", ")", "digest", ".", "hexdigest", "end"], "docstring": "Calculate the digest of the file at the given path. Files are read in\n binary chunks to prevent Ruby from exploding.\n\n @param [String] path\n the path of the file to digest\n @param [Symbol] type\n the type of digest to use\n\n @return [String]\n the hexdigest of the file at the path", "docstring_tokens": ["Calculate", "the", "digest", "of", "the", "file", "at", "the", "given", "path", ".", "Files", "are", "read", "in", "binary", "chunks", "to", "prevent", "Ruby", "from", "exploding", "."], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/digestable.rb#L40-L45", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/digestable.rb", "func_name": "Omnibus.Digestable.update_with_file_contents", "original_string": "def update_with_file_contents(digest, filename)\n File.open(filename) do |io|\n while (chunk = io.read(1024 * 8))\n digest.update(chunk)\n end\n end\n end", "language": "ruby", "code": "def update_with_file_contents(digest, filename)\n File.open(filename) do |io|\n while (chunk = io.read(1024 * 8))\n digest.update(chunk)\n end\n end\n end", "code_tokens": ["def", "update_with_file_contents", "(", "digest", ",", "filename", ")", "File", ".", "open", "(", "filename", ")", "do", "|", "io", "|", "while", "(", "chunk", "=", "io", ".", "read", "(", "1024", "*", "8", ")", ")", "digest", ".", "update", "(", "chunk", ")", "end", "end", "end"], "docstring": "Update the digest with the given contents of the file, reading in small\n chunks to reduce memory. This method will update the given +digest+\n parameter, but returns nothing.\n\n @param [Digest] digest\n the digest to update\n @param [String] filename\n the path to the file on disk to read\n\n @return [void]", "docstring_tokens": ["Update", "the", "digest", "with", "the", "given", "contents", "of", "the", "file", "reading", "in", "small", "chunks", "to", "reduce", "memory", ".", "This", "method", "will", "update", "the", "given", "+", "digest", "+", "parameter", "but", "returns", "nothing", "."], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/digestable.rb#L122-L128", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/publisher.rb", "func_name": "Omnibus.Publisher.packages", "original_string": "def packages\n @packages ||= begin\n publish_packages = Array.new\n build_packages = FileSyncer.glob(@pattern).map { |path| Package.new(path) }\n\n if @options[:platform_mappings]\n # the platform map is a simple hash with publish to build platform mappings\n @options[:platform_mappings].each_pair do |build_platform, publish_platforms|\n # Splits `ubuntu-12.04` into `ubuntu` and `12.04`\n build_platform, build_platform_version = build_platform.rpartition(\"-\") - %w{ - }\n\n # locate the package for the build platform\n packages = build_packages.select do |p|\n p.metadata[:platform] == build_platform &&\n p.metadata[:platform_version] == build_platform_version\n end\n\n if packages.empty?\n log.warn(log_key) do\n \"Could not locate a package for build platform #{build_platform}-#{build_platform_version}. \" \\\n \"Publishing will be skipped for: #{publish_platforms.join(', ')}\"\n end\n end\n\n publish_platforms.each do |publish_platform|\n publish_platform, publish_platform_version = publish_platform.rpartition(\"-\") - %w{ - }\n\n packages.each do |p|\n # create a copy of our package before mucking with its metadata\n publish_package = p.dup\n publish_metadata = p.metadata.dup.to_hash\n\n # override the platform and platform version in the metadata\n publish_metadata[:platform] = publish_platform\n publish_metadata[:platform_version] = publish_platform_version\n\n # Set the updated metadata on the package object\n publish_package.metadata = Metadata.new(publish_package, publish_metadata)\n\n publish_packages << publish_package\n end\n end\n end\n else\n publish_packages.concat(build_packages)\n end\n\n if publish_packages.empty?\n log.info(log_key) { \"No packages found, skipping publish\" }\n end\n\n publish_packages\n end\n end", "language": "ruby", "code": "def packages\n @packages ||= begin\n publish_packages = Array.new\n build_packages = FileSyncer.glob(@pattern).map { |path| Package.new(path) }\n\n if @options[:platform_mappings]\n # the platform map is a simple hash with publish to build platform mappings\n @options[:platform_mappings].each_pair do |build_platform, publish_platforms|\n # Splits `ubuntu-12.04` into `ubuntu` and `12.04`\n build_platform, build_platform_version = build_platform.rpartition(\"-\") - %w{ - }\n\n # locate the package for the build platform\n packages = build_packages.select do |p|\n p.metadata[:platform] == build_platform &&\n p.metadata[:platform_version] == build_platform_version\n end\n\n if packages.empty?\n log.warn(log_key) do\n \"Could not locate a package for build platform #{build_platform}-#{build_platform_version}. \" \\\n \"Publishing will be skipped for: #{publish_platforms.join(', ')}\"\n end\n end\n\n publish_platforms.each do |publish_platform|\n publish_platform, publish_platform_version = publish_platform.rpartition(\"-\") - %w{ - }\n\n packages.each do |p|\n # create a copy of our package before mucking with its metadata\n publish_package = p.dup\n publish_metadata = p.metadata.dup.to_hash\n\n # override the platform and platform version in the metadata\n publish_metadata[:platform] = publish_platform\n publish_metadata[:platform_version] = publish_platform_version\n\n # Set the updated metadata on the package object\n publish_package.metadata = Metadata.new(publish_package, publish_metadata)\n\n publish_packages << publish_package\n end\n end\n end\n else\n publish_packages.concat(build_packages)\n end\n\n if publish_packages.empty?\n log.info(log_key) { \"No packages found, skipping publish\" }\n end\n\n publish_packages\n end\n end", "code_tokens": ["def", "packages", "@packages", "||=", "begin", "publish_packages", "=", "Array", ".", "new", "build_packages", "=", "FileSyncer", ".", "glob", "(", "@pattern", ")", ".", "map", "{", "|", "path", "|", "Package", ".", "new", "(", "path", ")", "}", "if", "@options", "[", ":platform_mappings", "]", "# the platform map is a simple hash with publish to build platform mappings", "@options", "[", ":platform_mappings", "]", ".", "each_pair", "do", "|", "build_platform", ",", "publish_platforms", "|", "# Splits `ubuntu-12.04` into `ubuntu` and `12.04`", "build_platform", ",", "build_platform_version", "=", "build_platform", ".", "rpartition", "(", "\"-\"", ")", "-", "%w{", "-", "}", "# locate the package for the build platform", "packages", "=", "build_packages", ".", "select", "do", "|", "p", "|", "p", ".", "metadata", "[", ":platform", "]", "==", "build_platform", "&&", "p", ".", "metadata", "[", ":platform_version", "]", "==", "build_platform_version", "end", "if", "packages", ".", "empty?", "log", ".", "warn", "(", "log_key", ")", "do", "\"Could not locate a package for build platform #{build_platform}-#{build_platform_version}. \"", "\"Publishing will be skipped for: #{publish_platforms.join(', ')}\"", "end", "end", "publish_platforms", ".", "each", "do", "|", "publish_platform", "|", "publish_platform", ",", "publish_platform_version", "=", "publish_platform", ".", "rpartition", "(", "\"-\"", ")", "-", "%w{", "-", "}", "packages", ".", "each", "do", "|", "p", "|", "# create a copy of our package before mucking with its metadata", "publish_package", "=", "p", ".", "dup", "publish_metadata", "=", "p", ".", "metadata", ".", "dup", ".", "to_hash", "# override the platform and platform version in the metadata", "publish_metadata", "[", ":platform", "]", "=", "publish_platform", "publish_metadata", "[", ":platform_version", "]", "=", "publish_platform_version", "# Set the updated metadata on the package object", "publish_package", ".", "metadata", "=", "Metadata", ".", "new", "(", "publish_package", ",", "publish_metadata", ")", "publish_packages", "<<", "publish_package", "end", "end", "end", "else", "publish_packages", ".", "concat", "(", "build_packages", ")", "end", "if", "publish_packages", ".", "empty?", "log", ".", "info", "(", "log_key", ")", "{", "\"No packages found, skipping publish\"", "}", "end", "publish_packages", "end", "end"], "docstring": "Create a new publisher from the given pattern.\n\n @param [String] pattern\n the path/pattern of the release artifact(s)\n\n @param [Hash] options\n the list of options passed to the publisher\n @option options [Hash] :platform_mappings A simple\n mapping of build to publish platform(s)\n @example\n {\n 'ubuntu-10.04' => [\n 'ubuntu-10.04',\n 'ubuntu-12.04',\n 'ubuntu-14.04',\n ],\n }\n\n\n The list of packages that match the pattern in the initializer.\n\n @return [Array]", "docstring_tokens": ["Create", "a", "new", "publisher", "from", "the", "given", "pattern", "."], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/publisher.rb#L70-L123", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/packagers/pkg.rb", "func_name": "Omnibus.Packager::PKG.write_distribution_file", "original_string": "def write_distribution_file\n render_template(resource_path(\"distribution.xml.erb\"),\n destination: \"#{staging_dir}/Distribution\",\n mode: 0600,\n variables: {\n friendly_name: project.friendly_name,\n identifier: safe_identifier,\n version: safe_version,\n component_pkg: component_pkg,\n }\n )\n end", "language": "ruby", "code": "def write_distribution_file\n render_template(resource_path(\"distribution.xml.erb\"),\n destination: \"#{staging_dir}/Distribution\",\n mode: 0600,\n variables: {\n friendly_name: project.friendly_name,\n identifier: safe_identifier,\n version: safe_version,\n component_pkg: component_pkg,\n }\n )\n end", "code_tokens": ["def", "write_distribution_file", "render_template", "(", "resource_path", "(", "\"distribution.xml.erb\"", ")", ",", "destination", ":", "\"#{staging_dir}/Distribution\"", ",", "mode", ":", "0600", ",", "variables", ":", "{", "friendly_name", ":", "project", ".", "friendly_name", ",", "identifier", ":", "safe_identifier", ",", "version", ":", "safe_version", ",", "component_pkg", ":", "component_pkg", ",", "}", ")", "end"], "docstring": "Write the Distribution file to the staging area. This method generates the\n content of the Distribution file, which is used by +productbuild+ to\n select the component packages to include in the product package.\n\n It also includes information used to customize the UI of the Mac OS X\n installer.\n\n @return [void]", "docstring_tokens": ["Write", "the", "Distribution", "file", "to", "the", "staging", "area", ".", "This", "method", "generates", "the", "content", "of", "the", "Distribution", "file", "which", "is", "used", "by", "+", "productbuild", "+", "to", "select", "the", "component", "packages", "to", "include", "in", "the", "product", "package", "."], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/packagers/pkg.rb#L215-L226", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/publishers/artifactory_publisher.rb", "func_name": "Omnibus.ArtifactoryPublisher.artifact_for", "original_string": "def artifact_for(artifact)\n md5 = artifact.respond_to?(:metadata) ? artifact.metadata[:md5] : digest(artifact.path, :md5)\n sha1 = artifact.respond_to?(:metadata) ? artifact.metadata[:sha1] : digest(artifact.path, :sha1)\n\n Artifactory::Resource::Artifact.new(\n local_path: artifact.path,\n client: client,\n checksums: {\n \"md5\" => md5,\n \"sha1\" => sha1,\n }\n )\n end", "language": "ruby", "code": "def artifact_for(artifact)\n md5 = artifact.respond_to?(:metadata) ? artifact.metadata[:md5] : digest(artifact.path, :md5)\n sha1 = artifact.respond_to?(:metadata) ? artifact.metadata[:sha1] : digest(artifact.path, :sha1)\n\n Artifactory::Resource::Artifact.new(\n local_path: artifact.path,\n client: client,\n checksums: {\n \"md5\" => md5,\n \"sha1\" => sha1,\n }\n )\n end", "code_tokens": ["def", "artifact_for", "(", "artifact", ")", "md5", "=", "artifact", ".", "respond_to?", "(", ":metadata", ")", "?", "artifact", ".", "metadata", "[", ":md5", "]", ":", "digest", "(", "artifact", ".", "path", ",", ":md5", ")", "sha1", "=", "artifact", ".", "respond_to?", "(", ":metadata", ")", "?", "artifact", ".", "metadata", "[", ":sha1", "]", ":", "digest", "(", "artifact", ".", "path", ",", ":sha1", ")", "Artifactory", "::", "Resource", "::", "Artifact", ".", "new", "(", "local_path", ":", "artifact", ".", "path", ",", "client", ":", "client", ",", "checksums", ":", "{", "\"md5\"", "=>", "md5", ",", "\"sha1\"", "=>", "sha1", ",", "}", ")", "end"], "docstring": "The artifact object that corresponds to this package.\n\n @param [Package,Metadata] artifact\n the package or metadata file to create the artifact from\n\n @return [Artifactory::Resource::Artifact]", "docstring_tokens": ["The", "artifact", "object", "that", "corresponds", "to", "this", "package", "."], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/publishers/artifactory_publisher.rb#L90-L102", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/publishers/artifactory_publisher.rb", "func_name": "Omnibus.ArtifactoryPublisher.build_for", "original_string": "def build_for(packages)\n metadata = packages.first.metadata\n name = metadata[:name]\n\n # Attempt to load the version manifest data from the packages metadata\n manifest = if version_manifest = metadata[:version_manifest]\n Manifest.from_hash(version_manifest)\n else\n Manifest.new(\n metadata[:version],\n # we already know the `version_manifest` entry is\n # missing so we can't pull in the `build_git_revision`\n nil,\n metadata[:license]\n )\n end\n\n # Upload the actual package\n log.info(log_key) { \"Saving build info for #{name}, Build ##{manifest.build_version}\" }\n\n Artifactory::Resource::Build.new(\n client: client,\n name: name,\n number: manifest.build_version,\n vcs_revision: manifest.build_git_revision,\n build_agent: {\n name: \"omnibus\",\n version: Omnibus::VERSION,\n },\n modules: [\n {\n # com.getchef:chef-server:12.0.0\n id: [\n Config.artifactory_base_path.tr(\"/\", \".\"),\n name,\n manifest.build_version,\n ].join(\":\"),\n artifacts: packages.map do |package|\n [\n {\n type: File.extname(package.path).split(\".\").last,\n sha1: package.metadata[:sha1],\n md5: package.metadata[:md5],\n name: package.metadata[:basename],\n },\n {\n type: File.extname(package.metadata.path).split(\".\").last,\n sha1: digest(package.metadata.path, :sha1),\n md5: digest(package.metadata.path, :md5),\n name: File.basename(package.metadata.path),\n },\n ]\n end.flatten,\n },\n ]\n )\n end", "language": "ruby", "code": "def build_for(packages)\n metadata = packages.first.metadata\n name = metadata[:name]\n\n # Attempt to load the version manifest data from the packages metadata\n manifest = if version_manifest = metadata[:version_manifest]\n Manifest.from_hash(version_manifest)\n else\n Manifest.new(\n metadata[:version],\n # we already know the `version_manifest` entry is\n # missing so we can't pull in the `build_git_revision`\n nil,\n metadata[:license]\n )\n end\n\n # Upload the actual package\n log.info(log_key) { \"Saving build info for #{name}, Build ##{manifest.build_version}\" }\n\n Artifactory::Resource::Build.new(\n client: client,\n name: name,\n number: manifest.build_version,\n vcs_revision: manifest.build_git_revision,\n build_agent: {\n name: \"omnibus\",\n version: Omnibus::VERSION,\n },\n modules: [\n {\n # com.getchef:chef-server:12.0.0\n id: [\n Config.artifactory_base_path.tr(\"/\", \".\"),\n name,\n manifest.build_version,\n ].join(\":\"),\n artifacts: packages.map do |package|\n [\n {\n type: File.extname(package.path).split(\".\").last,\n sha1: package.metadata[:sha1],\n md5: package.metadata[:md5],\n name: package.metadata[:basename],\n },\n {\n type: File.extname(package.metadata.path).split(\".\").last,\n sha1: digest(package.metadata.path, :sha1),\n md5: digest(package.metadata.path, :md5),\n name: File.basename(package.metadata.path),\n },\n ]\n end.flatten,\n },\n ]\n )\n end", "code_tokens": ["def", "build_for", "(", "packages", ")", "metadata", "=", "packages", ".", "first", ".", "metadata", "name", "=", "metadata", "[", ":name", "]", "# Attempt to load the version manifest data from the packages metadata", "manifest", "=", "if", "version_manifest", "=", "metadata", "[", ":version_manifest", "]", "Manifest", ".", "from_hash", "(", "version_manifest", ")", "else", "Manifest", ".", "new", "(", "metadata", "[", ":version", "]", ",", "# we already know the `version_manifest` entry is", "# missing so we can't pull in the `build_git_revision`", "nil", ",", "metadata", "[", ":license", "]", ")", "end", "# Upload the actual package", "log", ".", "info", "(", "log_key", ")", "{", "\"Saving build info for #{name}, Build ##{manifest.build_version}\"", "}", "Artifactory", "::", "Resource", "::", "Build", ".", "new", "(", "client", ":", "client", ",", "name", ":", "name", ",", "number", ":", "manifest", ".", "build_version", ",", "vcs_revision", ":", "manifest", ".", "build_git_revision", ",", "build_agent", ":", "{", "name", ":", "\"omnibus\"", ",", "version", ":", "Omnibus", "::", "VERSION", ",", "}", ",", "modules", ":", "[", "{", "# com.getchef:chef-server:12.0.0", "id", ":", "[", "Config", ".", "artifactory_base_path", ".", "tr", "(", "\"/\"", ",", "\".\"", ")", ",", "name", ",", "manifest", ".", "build_version", ",", "]", ".", "join", "(", "\":\"", ")", ",", "artifacts", ":", "packages", ".", "map", "do", "|", "package", "|", "[", "{", "type", ":", "File", ".", "extname", "(", "package", ".", "path", ")", ".", "split", "(", "\".\"", ")", ".", "last", ",", "sha1", ":", "package", ".", "metadata", "[", ":sha1", "]", ",", "md5", ":", "package", ".", "metadata", "[", ":md5", "]", ",", "name", ":", "package", ".", "metadata", "[", ":basename", "]", ",", "}", ",", "{", "type", ":", "File", ".", "extname", "(", "package", ".", "metadata", ".", "path", ")", ".", "split", "(", "\".\"", ")", ".", "last", ",", "sha1", ":", "digest", "(", "package", ".", "metadata", ".", "path", ",", ":sha1", ")", ",", "md5", ":", "digest", "(", "package", ".", "metadata", ".", "path", ",", ":md5", ")", ",", "name", ":", "File", ".", "basename", "(", "package", ".", "metadata", ".", "path", ")", ",", "}", ",", "]", "end", ".", "flatten", ",", "}", ",", "]", ")", "end"], "docstring": "The build object that corresponds to this package.\n\n @param [Array] packages\n the packages to create the build from\n\n @return [Artifactory::Resource::Build]", "docstring_tokens": ["The", "build", "object", "that", "corresponds", "to", "this", "package", "."], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/publishers/artifactory_publisher.rb#L112-L168", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/publishers/artifactory_publisher.rb", "func_name": "Omnibus.ArtifactoryPublisher.client", "original_string": "def client\n @client ||= Artifactory::Client.new(\n endpoint: Config.artifactory_endpoint,\n username: Config.artifactory_username,\n password: Config.artifactory_password,\n ssl_pem_file: Config.artifactory_ssl_pem_file,\n ssl_verify: Config.artifactory_ssl_verify,\n proxy_username: Config.artifactory_proxy_username,\n proxy_password: Config.artifactory_proxy_password,\n proxy_address: Config.artifactory_proxy_address,\n proxy_port: Config.artifactory_proxy_port\n )\n end", "language": "ruby", "code": "def client\n @client ||= Artifactory::Client.new(\n endpoint: Config.artifactory_endpoint,\n username: Config.artifactory_username,\n password: Config.artifactory_password,\n ssl_pem_file: Config.artifactory_ssl_pem_file,\n ssl_verify: Config.artifactory_ssl_verify,\n proxy_username: Config.artifactory_proxy_username,\n proxy_password: Config.artifactory_proxy_password,\n proxy_address: Config.artifactory_proxy_address,\n proxy_port: Config.artifactory_proxy_port\n )\n end", "code_tokens": ["def", "client", "@client", "||=", "Artifactory", "::", "Client", ".", "new", "(", "endpoint", ":", "Config", ".", "artifactory_endpoint", ",", "username", ":", "Config", ".", "artifactory_username", ",", "password", ":", "Config", ".", "artifactory_password", ",", "ssl_pem_file", ":", "Config", ".", "artifactory_ssl_pem_file", ",", "ssl_verify", ":", "Config", ".", "artifactory_ssl_verify", ",", "proxy_username", ":", "Config", ".", "artifactory_proxy_username", ",", "proxy_password", ":", "Config", ".", "artifactory_proxy_password", ",", "proxy_address", ":", "Config", ".", "artifactory_proxy_address", ",", "proxy_port", ":", "Config", ".", "artifactory_proxy_port", ")", "end"], "docstring": "The Artifactory client object to communicate with the Artifactory API.\n\n @return [Artifactory::Client]", "docstring_tokens": ["The", "Artifactory", "client", "object", "to", "communicate", "with", "the", "Artifactory", "API", "."], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/publishers/artifactory_publisher.rb#L190-L202", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/publishers/artifactory_publisher.rb", "func_name": "Omnibus.ArtifactoryPublisher.metadata_properties_for", "original_string": "def metadata_properties_for(package)\n metadata = {\n \"omnibus.project\" => package.metadata[:name],\n \"omnibus.platform\" => package.metadata[:platform],\n \"omnibus.platform_version\" => package.metadata[:platform_version],\n \"omnibus.architecture\" => package.metadata[:arch],\n \"omnibus.version\" => package.metadata[:version],\n \"omnibus.iteration\" => package.metadata[:iteration],\n \"omnibus.license\" => package.metadata[:license],\n \"omnibus.md5\" => package.metadata[:md5],\n \"omnibus.sha1\" => package.metadata[:sha1],\n \"omnibus.sha256\" => package.metadata[:sha256],\n \"omnibus.sha512\" => package.metadata[:sha512],\n \"md5\" => package.metadata[:md5],\n \"sha1\" => package.metadata[:sha1],\n \"sha256\" => package.metadata[:sha256],\n \"sha512\" => package.metadata[:sha512],\n }.tap do |h|\n if build_record?\n h[\"build.name\"] = package.metadata[:name]\n h[\"build.number\"] = package.metadata[:version]\n end\n end\n\n metadata\n end", "language": "ruby", "code": "def metadata_properties_for(package)\n metadata = {\n \"omnibus.project\" => package.metadata[:name],\n \"omnibus.platform\" => package.metadata[:platform],\n \"omnibus.platform_version\" => package.metadata[:platform_version],\n \"omnibus.architecture\" => package.metadata[:arch],\n \"omnibus.version\" => package.metadata[:version],\n \"omnibus.iteration\" => package.metadata[:iteration],\n \"omnibus.license\" => package.metadata[:license],\n \"omnibus.md5\" => package.metadata[:md5],\n \"omnibus.sha1\" => package.metadata[:sha1],\n \"omnibus.sha256\" => package.metadata[:sha256],\n \"omnibus.sha512\" => package.metadata[:sha512],\n \"md5\" => package.metadata[:md5],\n \"sha1\" => package.metadata[:sha1],\n \"sha256\" => package.metadata[:sha256],\n \"sha512\" => package.metadata[:sha512],\n }.tap do |h|\n if build_record?\n h[\"build.name\"] = package.metadata[:name]\n h[\"build.number\"] = package.metadata[:version]\n end\n end\n\n metadata\n end", "code_tokens": ["def", "metadata_properties_for", "(", "package", ")", "metadata", "=", "{", "\"omnibus.project\"", "=>", "package", ".", "metadata", "[", ":name", "]", ",", "\"omnibus.platform\"", "=>", "package", ".", "metadata", "[", ":platform", "]", ",", "\"omnibus.platform_version\"", "=>", "package", ".", "metadata", "[", ":platform_version", "]", ",", "\"omnibus.architecture\"", "=>", "package", ".", "metadata", "[", ":arch", "]", ",", "\"omnibus.version\"", "=>", "package", ".", "metadata", "[", ":version", "]", ",", "\"omnibus.iteration\"", "=>", "package", ".", "metadata", "[", ":iteration", "]", ",", "\"omnibus.license\"", "=>", "package", ".", "metadata", "[", ":license", "]", ",", "\"omnibus.md5\"", "=>", "package", ".", "metadata", "[", ":md5", "]", ",", "\"omnibus.sha1\"", "=>", "package", ".", "metadata", "[", ":sha1", "]", ",", "\"omnibus.sha256\"", "=>", "package", ".", "metadata", "[", ":sha256", "]", ",", "\"omnibus.sha512\"", "=>", "package", ".", "metadata", "[", ":sha512", "]", ",", "\"md5\"", "=>", "package", ".", "metadata", "[", ":md5", "]", ",", "\"sha1\"", "=>", "package", ".", "metadata", "[", ":sha1", "]", ",", "\"sha256\"", "=>", "package", ".", "metadata", "[", ":sha256", "]", ",", "\"sha512\"", "=>", "package", ".", "metadata", "[", ":sha512", "]", ",", "}", ".", "tap", "do", "|", "h", "|", "if", "build_record?", "h", "[", "\"build.name\"", "]", "=", "package", ".", "metadata", "[", ":name", "]", "h", "[", "\"build.number\"", "]", "=", "package", ".", "metadata", "[", ":version", "]", "end", "end", "metadata", "end"], "docstring": "The metadata for this package.\n\n @param [Package] package\n the package to generate the metadata for\n\n @return [Hash]", "docstring_tokens": ["The", "metadata", "for", "this", "package", "."], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/publishers/artifactory_publisher.rb#L212-L237", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/publishers/artifactory_publisher.rb", "func_name": "Omnibus.ArtifactoryPublisher.remote_path_for", "original_string": "def remote_path_for(package)\n File.join(\n Config.artifactory_base_path,\n Config.artifactory_publish_pattern % package.metadata\n )\n end", "language": "ruby", "code": "def remote_path_for(package)\n File.join(\n Config.artifactory_base_path,\n Config.artifactory_publish_pattern % package.metadata\n )\n end", "code_tokens": ["def", "remote_path_for", "(", "package", ")", "File", ".", "join", "(", "Config", ".", "artifactory_base_path", ",", "Config", ".", "artifactory_publish_pattern", "%", "package", ".", "metadata", ")", "end"], "docstring": "The path where the package will live inside of the Artifactory repository.\n This is dynamically computed from the values in the project definition\n and the package metadata.\n\n @example\n com/getchef/chef/11.6.0/ubuntu/14.04/chef-11.6.0-1.el6.x86_64.rpm\n\n @param [Package] package\n the package to generate the remote path for\n\n @return [String]", "docstring_tokens": ["The", "path", "where", "the", "package", "will", "live", "inside", "of", "the", "Artifactory", "repository", ".", "This", "is", "dynamically", "computed", "from", "the", "values", "in", "the", "project", "definition", "and", "the", "package", "metadata", "."], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/publishers/artifactory_publisher.rb#L270-L275", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/packagers/msi.rb", "func_name": "Omnibus.Packager::MSI.parameters", "original_string": "def parameters(val = NULL)\n if null?(val)\n @parameters || {}\n else\n unless val.is_a?(Hash)\n raise InvalidValue.new(:parameters, \"be a Hash\")\n end\n\n @parameters = val\n end\n end", "language": "ruby", "code": "def parameters(val = NULL)\n if null?(val)\n @parameters || {}\n else\n unless val.is_a?(Hash)\n raise InvalidValue.new(:parameters, \"be a Hash\")\n end\n\n @parameters = val\n end\n end", "code_tokens": ["def", "parameters", "(", "val", "=", "NULL", ")", "if", "null?", "(", "val", ")", "@parameters", "||", "{", "}", "else", "unless", "val", ".", "is_a?", "(", "Hash", ")", "raise", "InvalidValue", ".", "new", "(", ":parameters", ",", "\"be a Hash\"", ")", "end", "@parameters", "=", "val", "end", "end"], "docstring": "Set or retrieve the custom msi building parameters.\n\n @example\n parameters {\n 'MagicParam' => 'ABCD-1234'\n }\n\n @param [Hash] val\n the parameters to set\n\n @return [Hash]\n the set parameters", "docstring_tokens": ["Set", "or", "retrieve", "the", "custom", "msi", "building", "parameters", "."], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/packagers/msi.rb#L135-L145", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/packagers/msi.rb", "func_name": "Omnibus.Packager::MSI.wix_light_extension", "original_string": "def wix_light_extension(extension)\n unless extension.is_a?(String)\n raise InvalidValue.new(:wix_light_extension, \"be an String\")\n end\n\n wix_light_extensions << extension\n end", "language": "ruby", "code": "def wix_light_extension(extension)\n unless extension.is_a?(String)\n raise InvalidValue.new(:wix_light_extension, \"be an String\")\n end\n\n wix_light_extensions << extension\n end", "code_tokens": ["def", "wix_light_extension", "(", "extension", ")", "unless", "extension", ".", "is_a?", "(", "String", ")", "raise", "InvalidValue", ".", "new", "(", ":wix_light_extension", ",", "\"be an String\"", ")", "end", "wix_light_extensions", "<<", "extension", "end"], "docstring": "Set the wix light extensions to load\n\n @example\n wix_light_extension 'WixUtilExtension'\n\n @param [String] extension\n A list of extensions to load\n\n @return [Array]\n The list of extensions that will be loaded", "docstring_tokens": ["Set", "the", "wix", "light", "extensions", "to", "load"], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/packagers/msi.rb#L160-L166", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/packagers/msi.rb", "func_name": "Omnibus.Packager::MSI.wix_light_delay_validation", "original_string": "def wix_light_delay_validation(val = false)\n unless val.is_a?(TrueClass) || val.is_a?(FalseClass)\n raise InvalidValue.new(:iwix_light_delay_validation, \"be TrueClass or FalseClass\")\n end\n @delay_validation ||= val\n unless @delay_validation\n return \"\"\n end\n \"-sval\"\n end", "language": "ruby", "code": "def wix_light_delay_validation(val = false)\n unless val.is_a?(TrueClass) || val.is_a?(FalseClass)\n raise InvalidValue.new(:iwix_light_delay_validation, \"be TrueClass or FalseClass\")\n end\n @delay_validation ||= val\n unless @delay_validation\n return \"\"\n end\n \"-sval\"\n end", "code_tokens": ["def", "wix_light_delay_validation", "(", "val", "=", "false", ")", "unless", "val", ".", "is_a?", "(", "TrueClass", ")", "||", "val", ".", "is_a?", "(", "FalseClass", ")", "raise", "InvalidValue", ".", "new", "(", ":iwix_light_delay_validation", ",", "\"be TrueClass or FalseClass\"", ")", "end", "@delay_validation", "||=", "val", "unless", "@delay_validation", "return", "\"\"", "end", "\"-sval\"", "end"], "docstring": "Signal delay validation for wix light\n\n @example\n wix_light_deplay_validation true\n\n @param [TrueClass, FalseClass] value\n whether to delay validation or not\n\n @return [String]\n whether we're a bundle or not", "docstring_tokens": ["Signal", "delay", "validation", "for", "wix", "light"], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/packagers/msi.rb#L180-L189", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/packagers/msi.rb", "func_name": "Omnibus.Packager::MSI.wix_candle_extension", "original_string": "def wix_candle_extension(extension)\n unless extension.is_a?(String)\n raise InvalidValue.new(:wix_candle_extension, \"be an String\")\n end\n\n wix_candle_extensions << extension\n end", "language": "ruby", "code": "def wix_candle_extension(extension)\n unless extension.is_a?(String)\n raise InvalidValue.new(:wix_candle_extension, \"be an String\")\n end\n\n wix_candle_extensions << extension\n end", "code_tokens": ["def", "wix_candle_extension", "(", "extension", ")", "unless", "extension", ".", "is_a?", "(", "String", ")", "raise", "InvalidValue", ".", "new", "(", ":wix_candle_extension", ",", "\"be an String\"", ")", "end", "wix_candle_extensions", "<<", "extension", "end"], "docstring": "Set the wix candle extensions to load\n\n @example\n wix_candle_extension 'WixUtilExtension'\n\n @param [String] extension\n A list of extensions to load\n\n @return [Array]\n The list of extensions that will be loaded", "docstring_tokens": ["Set", "the", "wix", "candle", "extensions", "to", "load"], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/packagers/msi.rb#L204-L210", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/packagers/msi.rb", "func_name": "Omnibus.Packager::MSI.write_localization_file", "original_string": "def write_localization_file\n render_template(resource_path(\"localization-#{localization}.wxl.erb\"),\n destination: \"#{staging_dir}/localization-#{localization}.wxl\",\n variables: {\n name: project.package_name,\n friendly_name: project.friendly_name,\n maintainer: project.maintainer,\n }\n )\n end", "language": "ruby", "code": "def write_localization_file\n render_template(resource_path(\"localization-#{localization}.wxl.erb\"),\n destination: \"#{staging_dir}/localization-#{localization}.wxl\",\n variables: {\n name: project.package_name,\n friendly_name: project.friendly_name,\n maintainer: project.maintainer,\n }\n )\n end", "code_tokens": ["def", "write_localization_file", "render_template", "(", "resource_path", "(", "\"localization-#{localization}.wxl.erb\"", ")", ",", "destination", ":", "\"#{staging_dir}/localization-#{localization}.wxl\"", ",", "variables", ":", "{", "name", ":", "project", ".", "package_name", ",", "friendly_name", ":", "project", ".", "friendly_name", ",", "maintainer", ":", "project", ".", "maintainer", ",", "}", ")", "end"], "docstring": "Write the localization file into the staging directory.\n\n @return [void]", "docstring_tokens": ["Write", "the", "localization", "file", "into", "the", "staging", "directory", "."], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/packagers/msi.rb#L336-L345", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/packagers/msi.rb", "func_name": "Omnibus.Packager::MSI.write_parameters_file", "original_string": "def write_parameters_file\n render_template(resource_path(\"parameters.wxi.erb\"),\n destination: \"#{staging_dir}/parameters.wxi\",\n variables: {\n name: project.package_name,\n friendly_name: project.friendly_name,\n maintainer: project.maintainer,\n upgrade_code: upgrade_code,\n parameters: parameters,\n version: windows_package_version,\n display_version: msi_display_version,\n }\n )\n end", "language": "ruby", "code": "def write_parameters_file\n render_template(resource_path(\"parameters.wxi.erb\"),\n destination: \"#{staging_dir}/parameters.wxi\",\n variables: {\n name: project.package_name,\n friendly_name: project.friendly_name,\n maintainer: project.maintainer,\n upgrade_code: upgrade_code,\n parameters: parameters,\n version: windows_package_version,\n display_version: msi_display_version,\n }\n )\n end", "code_tokens": ["def", "write_parameters_file", "render_template", "(", "resource_path", "(", "\"parameters.wxi.erb\"", ")", ",", "destination", ":", "\"#{staging_dir}/parameters.wxi\"", ",", "variables", ":", "{", "name", ":", "project", ".", "package_name", ",", "friendly_name", ":", "project", ".", "friendly_name", ",", "maintainer", ":", "project", ".", "maintainer", ",", "upgrade_code", ":", "upgrade_code", ",", "parameters", ":", "parameters", ",", "version", ":", "windows_package_version", ",", "display_version", ":", "msi_display_version", ",", "}", ")", "end"], "docstring": "Write the parameters file into the staging directory.\n\n @return [void]", "docstring_tokens": ["Write", "the", "parameters", "file", "into", "the", "staging", "directory", "."], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/packagers/msi.rb#L352-L365", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/packagers/msi.rb", "func_name": "Omnibus.Packager::MSI.write_source_file", "original_string": "def write_source_file\n paths = []\n\n # Remove C:/\n install_dir = project.install_dir.split(\"/\")[1..-1].join(\"/\")\n\n # Grab all parent paths\n Pathname.new(install_dir).ascend do |path|\n paths << path.to_s\n end\n\n # Create the hierarchy\n hierarchy = paths.reverse.inject({}) do |hash, path|\n hash[File.basename(path)] = path.gsub(/[^[:alnum:]]/, \"\").upcase + \"LOCATION\"\n hash\n end\n\n # The last item in the path MUST be named PROJECTLOCATION or else space\n # robots will cause permanent damage to you and your family.\n hierarchy[hierarchy.keys.last] = \"PROJECTLOCATION\"\n\n # If the path hierarchy is > 1, the customizable installation directory\n # should default to the second-to-last item in the hierarchy. If the\n # hierarchy is smaller than that, then just use the system drive.\n wix_install_dir = if hierarchy.size > 1\n hierarchy.to_a[-2][1]\n else\n \"WINDOWSVOLUME\"\n end\n\n render_template(resource_path(\"source.wxs.erb\"),\n destination: \"#{staging_dir}/source.wxs\",\n variables: {\n name: project.package_name,\n friendly_name: project.friendly_name,\n maintainer: project.maintainer,\n hierarchy: hierarchy,\n fastmsi: fast_msi,\n wix_install_dir: wix_install_dir,\n }\n )\n end", "language": "ruby", "code": "def write_source_file\n paths = []\n\n # Remove C:/\n install_dir = project.install_dir.split(\"/\")[1..-1].join(\"/\")\n\n # Grab all parent paths\n Pathname.new(install_dir).ascend do |path|\n paths << path.to_s\n end\n\n # Create the hierarchy\n hierarchy = paths.reverse.inject({}) do |hash, path|\n hash[File.basename(path)] = path.gsub(/[^[:alnum:]]/, \"\").upcase + \"LOCATION\"\n hash\n end\n\n # The last item in the path MUST be named PROJECTLOCATION or else space\n # robots will cause permanent damage to you and your family.\n hierarchy[hierarchy.keys.last] = \"PROJECTLOCATION\"\n\n # If the path hierarchy is > 1, the customizable installation directory\n # should default to the second-to-last item in the hierarchy. If the\n # hierarchy is smaller than that, then just use the system drive.\n wix_install_dir = if hierarchy.size > 1\n hierarchy.to_a[-2][1]\n else\n \"WINDOWSVOLUME\"\n end\n\n render_template(resource_path(\"source.wxs.erb\"),\n destination: \"#{staging_dir}/source.wxs\",\n variables: {\n name: project.package_name,\n friendly_name: project.friendly_name,\n maintainer: project.maintainer,\n hierarchy: hierarchy,\n fastmsi: fast_msi,\n wix_install_dir: wix_install_dir,\n }\n )\n end", "code_tokens": ["def", "write_source_file", "paths", "=", "[", "]", "# Remove C:/", "install_dir", "=", "project", ".", "install_dir", ".", "split", "(", "\"/\"", ")", "[", "1", "..", "-", "1", "]", ".", "join", "(", "\"/\"", ")", "# Grab all parent paths", "Pathname", ".", "new", "(", "install_dir", ")", ".", "ascend", "do", "|", "path", "|", "paths", "<<", "path", ".", "to_s", "end", "# Create the hierarchy", "hierarchy", "=", "paths", ".", "reverse", ".", "inject", "(", "{", "}", ")", "do", "|", "hash", ",", "path", "|", "hash", "[", "File", ".", "basename", "(", "path", ")", "]", "=", "path", ".", "gsub", "(", "/", "/", ",", "\"\"", ")", ".", "upcase", "+", "\"LOCATION\"", "hash", "end", "# The last item in the path MUST be named PROJECTLOCATION or else space", "# robots will cause permanent damage to you and your family.", "hierarchy", "[", "hierarchy", ".", "keys", ".", "last", "]", "=", "\"PROJECTLOCATION\"", "# If the path hierarchy is > 1, the customizable installation directory", "# should default to the second-to-last item in the hierarchy. If the", "# hierarchy is smaller than that, then just use the system drive.", "wix_install_dir", "=", "if", "hierarchy", ".", "size", ">", "1", "hierarchy", ".", "to_a", "[", "-", "2", "]", "[", "1", "]", "else", "\"WINDOWSVOLUME\"", "end", "render_template", "(", "resource_path", "(", "\"source.wxs.erb\"", ")", ",", "destination", ":", "\"#{staging_dir}/source.wxs\"", ",", "variables", ":", "{", "name", ":", "project", ".", "package_name", ",", "friendly_name", ":", "project", ".", "friendly_name", ",", "maintainer", ":", "project", ".", "maintainer", ",", "hierarchy", ":", "hierarchy", ",", "fastmsi", ":", "fast_msi", ",", "wix_install_dir", ":", "wix_install_dir", ",", "}", ")", "end"], "docstring": "Write the source file into the staging directory.\n\n @return [void]", "docstring_tokens": ["Write", "the", "source", "file", "into", "the", "staging", "directory", "."], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/packagers/msi.rb#L372-L413", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/packagers/msi.rb", "func_name": "Omnibus.Packager::MSI.write_bundle_file", "original_string": "def write_bundle_file\n render_template(resource_path(\"bundle.wxs.erb\"),\n destination: \"#{staging_dir}/bundle.wxs\",\n variables: {\n name: project.package_name,\n friendly_name: project.friendly_name,\n maintainer: project.maintainer,\n upgrade_code: upgrade_code,\n parameters: parameters,\n version: windows_package_version,\n display_version: msi_display_version,\n msi: windows_safe_path(Config.package_dir, msi_name),\n }\n )\n end", "language": "ruby", "code": "def write_bundle_file\n render_template(resource_path(\"bundle.wxs.erb\"),\n destination: \"#{staging_dir}/bundle.wxs\",\n variables: {\n name: project.package_name,\n friendly_name: project.friendly_name,\n maintainer: project.maintainer,\n upgrade_code: upgrade_code,\n parameters: parameters,\n version: windows_package_version,\n display_version: msi_display_version,\n msi: windows_safe_path(Config.package_dir, msi_name),\n }\n )\n end", "code_tokens": ["def", "write_bundle_file", "render_template", "(", "resource_path", "(", "\"bundle.wxs.erb\"", ")", ",", "destination", ":", "\"#{staging_dir}/bundle.wxs\"", ",", "variables", ":", "{", "name", ":", "project", ".", "package_name", ",", "friendly_name", ":", "project", ".", "friendly_name", ",", "maintainer", ":", "project", ".", "maintainer", ",", "upgrade_code", ":", "upgrade_code", ",", "parameters", ":", "parameters", ",", "version", ":", "windows_package_version", ",", "display_version", ":", "msi_display_version", ",", "msi", ":", "windows_safe_path", "(", "Config", ".", "package_dir", ",", "msi_name", ")", ",", "}", ")", "end"], "docstring": "Write the bundle file into the staging directory.\n\n @return [void]", "docstring_tokens": ["Write", "the", "bundle", "file", "into", "the", "staging", "directory", "."], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/packagers/msi.rb#L420-L434", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/build_version_dsl.rb", "func_name": "Omnibus.BuildVersionDSL.resolve", "original_string": "def resolve(dependency)\n if from_dependency? && version_dependency == dependency.name\n construct_build_version(dependency)\n log.info(log_key) { \"Build Version is set to '#{build_version}'\" }\n end\n end", "language": "ruby", "code": "def resolve(dependency)\n if from_dependency? && version_dependency == dependency.name\n construct_build_version(dependency)\n log.info(log_key) { \"Build Version is set to '#{build_version}'\" }\n end\n end", "code_tokens": ["def", "resolve", "(", "dependency", ")", "if", "from_dependency?", "&&", "version_dependency", "==", "dependency", ".", "name", "construct_build_version", "(", "dependency", ")", "log", ".", "info", "(", "log_key", ")", "{", "\"Build Version is set to '#{build_version}'\"", "}", "end", "end"], "docstring": "Callback that is called by software objects to determine the version.\n\n @param dependency [Omnibus::Software] Software object that is making the callback.\n @return [void]", "docstring_tokens": ["Callback", "that", "is", "called", "by", "software", "objects", "to", "determine", "the", "version", "."], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/build_version_dsl.rb#L70-L75", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/build_version_dsl.rb", "func_name": "Omnibus.BuildVersionDSL.maybe_append_timestamp", "original_string": "def maybe_append_timestamp(version)\n if Config.append_timestamp && !has_timestamp?(version)\n [version, Omnibus::BuildVersion.build_start_time].join(\"+\")\n else\n version\n end\n end", "language": "ruby", "code": "def maybe_append_timestamp(version)\n if Config.append_timestamp && !has_timestamp?(version)\n [version, Omnibus::BuildVersion.build_start_time].join(\"+\")\n else\n version\n end\n end", "code_tokens": ["def", "maybe_append_timestamp", "(", "version", ")", "if", "Config", ".", "append_timestamp", "&&", "!", "has_timestamp?", "(", "version", ")", "[", "version", ",", "Omnibus", "::", "BuildVersion", ".", "build_start_time", "]", ".", "join", "(", "\"+\"", ")", "else", "version", "end", "end"], "docstring": "Append the build_start_time to the given string if\n Config.append_timestamp is true\n\n @param [String] version\n @return [String]", "docstring_tokens": ["Append", "the", "build_start_time", "to", "the", "given", "string", "if", "Config", ".", "append_timestamp", "is", "true"], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/build_version_dsl.rb#L119-L125", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/build_version_dsl.rb", "func_name": "Omnibus.BuildVersionDSL.has_timestamp?", "original_string": "def has_timestamp?(version)\n _ver, build_info = version.split(\"+\")\n return false if build_info.nil?\n build_info.split(\".\").any? do |part|\n begin\n Time.strptime(part, Omnibus::BuildVersion::TIMESTAMP_FORMAT)\n true\n rescue ArgumentError\n false\n end\n end\n end", "language": "ruby", "code": "def has_timestamp?(version)\n _ver, build_info = version.split(\"+\")\n return false if build_info.nil?\n build_info.split(\".\").any? do |part|\n begin\n Time.strptime(part, Omnibus::BuildVersion::TIMESTAMP_FORMAT)\n true\n rescue ArgumentError\n false\n end\n end\n end", "code_tokens": ["def", "has_timestamp?", "(", "version", ")", "_ver", ",", "build_info", "=", "version", ".", "split", "(", "\"+\"", ")", "return", "false", "if", "build_info", ".", "nil?", "build_info", ".", "split", "(", "\".\"", ")", ".", "any?", "do", "|", "part", "|", "begin", "Time", ".", "strptime", "(", "part", ",", "Omnibus", "::", "BuildVersion", "::", "TIMESTAMP_FORMAT", ")", "true", "rescue", "ArgumentError", "false", "end", "end", "end"], "docstring": "Returns true if a given version string Looks like it was already\n created with a function that added a timestamp. The goal of this\n is to avoid breaking all of the people who are currently using\n BuildVersion.semver to create dates.\n\n @param [String] version\n @return [Boolean]", "docstring_tokens": ["Returns", "true", "if", "a", "given", "version", "string", "Looks", "like", "it", "was", "already", "created", "with", "a", "function", "that", "added", "a", "timestamp", ".", "The", "goal", "of", "this", "is", "to", "avoid", "breaking", "all", "of", "the", "people", "who", "are", "currently", "using", "BuildVersion", ".", "semver", "to", "create", "dates", "."], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/build_version_dsl.rb#L134-L145", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/build_version_dsl.rb", "func_name": "Omnibus.BuildVersionDSL.construct_build_version", "original_string": "def construct_build_version(version_source = nil)\n case source_type\n when :git\n version = if version_source\n Omnibus::BuildVersion.new(version_source.project_dir)\n else\n Omnibus::BuildVersion.new\n end\n\n output = output_method || :semver\n self.build_version = version.send(output)\n when :version\n if version_source\n self.build_version = version_source.version\n else\n raise \"Please tell me the source to get the version from\"\n end\n else\n raise \"I don't know how to construct a build_version using source '#{source_type}'\"\n end\n end", "language": "ruby", "code": "def construct_build_version(version_source = nil)\n case source_type\n when :git\n version = if version_source\n Omnibus::BuildVersion.new(version_source.project_dir)\n else\n Omnibus::BuildVersion.new\n end\n\n output = output_method || :semver\n self.build_version = version.send(output)\n when :version\n if version_source\n self.build_version = version_source.version\n else\n raise \"Please tell me the source to get the version from\"\n end\n else\n raise \"I don't know how to construct a build_version using source '#{source_type}'\"\n end\n end", "code_tokens": ["def", "construct_build_version", "(", "version_source", "=", "nil", ")", "case", "source_type", "when", ":git", "version", "=", "if", "version_source", "Omnibus", "::", "BuildVersion", ".", "new", "(", "version_source", ".", "project_dir", ")", "else", "Omnibus", "::", "BuildVersion", ".", "new", "end", "output", "=", "output_method", "||", ":semver", "self", ".", "build_version", "=", "version", ".", "send", "(", "output", ")", "when", ":version", "if", "version_source", "self", ".", "build_version", "=", "version_source", ".", "version", "else", "raise", "\"Please tell me the source to get the version from\"", "end", "else", "raise", "\"I don't know how to construct a build_version using source '#{source_type}'\"", "end", "end"], "docstring": "Determines the build_version based on source_type, output_method.\n\n @param version_source [Omnibus::Software] Software object from which the\n build version will be determined from. Default is nil.\n @return [void]", "docstring_tokens": ["Determines", "the", "build_version", "based", "on", "source_type", "output_method", "."], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/build_version_dsl.rb#L152-L172", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/templating.rb", "func_name": "Omnibus.Templating.render_template_content", "original_string": "def render_template_content(source, variables = {})\n template = ERB.new(File.read(source), nil, \"-\")\n\n struct =\n if variables.empty?\n Struct.new(\"Empty\")\n else\n Struct.new(*variables.keys).new(*variables.values)\n end\n\n template.result(struct.instance_eval { binding })\n end", "language": "ruby", "code": "def render_template_content(source, variables = {})\n template = ERB.new(File.read(source), nil, \"-\")\n\n struct =\n if variables.empty?\n Struct.new(\"Empty\")\n else\n Struct.new(*variables.keys).new(*variables.values)\n end\n\n template.result(struct.instance_eval { binding })\n end", "code_tokens": ["def", "render_template_content", "(", "source", ",", "variables", "=", "{", "}", ")", "template", "=", "ERB", ".", "new", "(", "File", ".", "read", "(", "source", ")", ",", "nil", ",", "\"-\"", ")", "struct", "=", "if", "variables", ".", "empty?", "Struct", ".", "new", "(", "\"Empty\"", ")", "else", "Struct", ".", "new", "(", "variables", ".", "keys", ")", ".", "new", "(", "variables", ".", "values", ")", "end", "template", ".", "result", "(", "struct", ".", "instance_eval", "{", "binding", "}", ")", "end"], "docstring": "Render an erb template to a String variable.\n\n @return [String]\n\n @param [String] source\n the path on disk where the ERB template lives\n\n @option options [Fixnum] :mode (default: +0644+)\n the mode of the rendered file\n @option options [Hash] :variables (default: +{}+)\n the list of variables to pass to the template", "docstring_tokens": ["Render", "an", "erb", "template", "to", "a", "String", "variable", "."], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/templating.rb#L38-L49", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/logger.rb", "func_name": "Omnibus.Logger.deprecated", "original_string": "def deprecated(progname, &block)\n meta = Proc.new { \"DEPRECATED: #{yield}\" }\n add(LEVELS.index(\"WARN\"), progname, &meta)\n end", "language": "ruby", "code": "def deprecated(progname, &block)\n meta = Proc.new { \"DEPRECATED: #{yield}\" }\n add(LEVELS.index(\"WARN\"), progname, &meta)\n end", "code_tokens": ["def", "deprecated", "(", "progname", ",", "&", "block", ")", "meta", "=", "Proc", ".", "new", "{", "\"DEPRECATED: #{yield}\"", "}", "add", "(", "LEVELS", ".", "index", "(", "\"WARN\"", ")", ",", "progname", ",", "meta", ")", "end"], "docstring": "Print a deprecation warning. This actually outputs to +WARN+, but is\n prefixed with the string \"DEPRECATED\" first.\n\n @see (Logger#add)", "docstring_tokens": ["Print", "a", "deprecation", "warning", ".", "This", "actually", "outputs", "to", "+", "WARN", "+", "but", "is", "prefixed", "with", "the", "string", "DEPRECATED", "first", "."], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/logger.rb#L71-L74", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/logger.rb", "func_name": "Omnibus.Logger.add", "original_string": "def add(severity, progname, &block)\n return true if io.nil? || severity < level\n message = format_message(severity, progname, yield)\n MUTEX.synchronize { io.write(message) }\n true\n end", "language": "ruby", "code": "def add(severity, progname, &block)\n return true if io.nil? || severity < level\n message = format_message(severity, progname, yield)\n MUTEX.synchronize { io.write(message) }\n true\n end", "code_tokens": ["def", "add", "(", "severity", ",", "progname", ",", "&", "block", ")", "return", "true", "if", "io", ".", "nil?", "||", "severity", "<", "level", "message", "=", "format_message", "(", "severity", ",", "progname", ",", "yield", ")", "MUTEX", ".", "synchronize", "{", "io", ".", "write", "(", "message", ")", "}", "true", "end"], "docstring": "Add a message to the logger with the given severity and progname.", "docstring_tokens": ["Add", "a", "message", "to", "the", "logger", "with", "the", "given", "severity", "and", "progname", "."], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/logger.rb#L103-L108", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/builder.rb", "func_name": "Omnibus.Builder.command", "original_string": "def command(command, options = {})\n warn_for_shell_commands(command)\n\n build_commands << BuildCommand.new(\"Execute: `#{command}'\") do\n shellout!(command, options)\n end\n end", "language": "ruby", "code": "def command(command, options = {})\n warn_for_shell_commands(command)\n\n build_commands << BuildCommand.new(\"Execute: `#{command}'\") do\n shellout!(command, options)\n end\n end", "code_tokens": ["def", "command", "(", "command", ",", "options", "=", "{", "}", ")", "warn_for_shell_commands", "(", "command", ")", "build_commands", "<<", "BuildCommand", ".", "new", "(", "\"Execute: `#{command}'\"", ")", "do", "shellout!", "(", "command", ",", "options", ")", "end", "end"], "docstring": "Create a new builder object for evaluation.\n\n @param [Software] software\n the software definition that created this builder\n\n\n @!group System DSL methods\n\n The following DSL methods are available from within build blocks.\n --------------------------------------------------\n\n Execute the given command string or command arguments.\n\n @example\n command 'make install', env: { 'PATH' => '/my/custom/path' }\n\n @param [String] command\n the command to execute\n @param [Hash] options\n a list of options to pass to the +Mixlib::ShellOut+ instance when it is\n executed\n\n @return [void]", "docstring_tokens": ["Create", "a", "new", "builder", "object", "for", "evaluation", "."], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/builder.rb#L81-L87", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/builder.rb", "func_name": "Omnibus.Builder.make", "original_string": "def make(*args)\n options = args.last.is_a?(Hash) ? args.pop : {}\n\n make = options.delete(:bin) ||\n # Prefer gmake on non-windows environments.\n if !windows? && Omnibus.which(\"gmake\")\n env = options.delete(:env) || {}\n env = { \"MAKE\" => \"gmake\" }.merge(env)\n options[:env] = env\n \"gmake\"\n else\n \"make\"\n end\n\n options[:in_msys_bash] = true\n make_cmd = ([make] + args).join(\" \").strip\n command(make_cmd, options)\n end", "language": "ruby", "code": "def make(*args)\n options = args.last.is_a?(Hash) ? args.pop : {}\n\n make = options.delete(:bin) ||\n # Prefer gmake on non-windows environments.\n if !windows? && Omnibus.which(\"gmake\")\n env = options.delete(:env) || {}\n env = { \"MAKE\" => \"gmake\" }.merge(env)\n options[:env] = env\n \"gmake\"\n else\n \"make\"\n end\n\n options[:in_msys_bash] = true\n make_cmd = ([make] + args).join(\" \").strip\n command(make_cmd, options)\n end", "code_tokens": ["def", "make", "(", "*", "args", ")", "options", "=", "args", ".", "last", ".", "is_a?", "(", "Hash", ")", "?", "args", ".", "pop", ":", "{", "}", "make", "=", "options", ".", "delete", "(", ":bin", ")", "||", "# Prefer gmake on non-windows environments.", "if", "!", "windows?", "&&", "Omnibus", ".", "which", "(", "\"gmake\"", ")", "env", "=", "options", ".", "delete", "(", ":env", ")", "||", "{", "}", "env", "=", "{", "\"MAKE\"", "=>", "\"gmake\"", "}", ".", "merge", "(", "env", ")", "options", "[", ":env", "]", "=", "env", "\"gmake\"", "else", "\"make\"", "end", "options", "[", ":in_msys_bash", "]", "=", "true", "make_cmd", "=", "(", "[", "make", "]", "+", "args", ")", ".", "join", "(", "\" \"", ")", ".", "strip", "command", "(", "make_cmd", ",", "options", ")", "end"], "docstring": "Execute the given make command. When present, this method will prefer the\n use of +gmake+ over +make+. If applicable, this method will also set\n the `MAKE=gmake` environment variable when gmake is to be preferred.\n\n On windows you need to have the msys-base package (or some equivalent)\n before you can invoke this.\n\n @example With no arguments\n make\n\n @example With arguments\n make 'install'\n\n @example With custom make bin\n make 'install', bin: '/path/to/custom/make'\n\n @param (see #command)\n @return (see #command)", "docstring_tokens": ["Execute", "the", "given", "make", "command", ".", "When", "present", "this", "method", "will", "prefer", "the", "use", "of", "+", "gmake", "+", "over", "+", "make", "+", ".", "If", "applicable", "this", "method", "will", "also", "set", "the", "MAKE", "=", "gmake", "environment", "variable", "when", "gmake", "is", "to", "be", "preferred", "."], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/builder.rb#L110-L127", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/builder.rb", "func_name": "Omnibus.Builder.appbundle", "original_string": "def appbundle(software_name, lockdir: nil, gem: nil, without: nil, extra_bin_files: nil , **options)\n build_commands << BuildCommand.new(\"appbundle `#{software_name}'\") do\n bin_dir = \"#{install_dir}/bin\"\n appbundler_bin = embedded_bin(\"appbundler\")\n\n lockdir ||=\n begin\n app_software = project.softwares.find do |p|\n p.name == software_name\n end\n if app_software.nil?\n raise \"could not find software definition for #{software_name}, add a dependency to it, or pass a lockdir argument to appbundle command.\"\n end\n app_software.project_dir\n end\n\n command = [ appbundler_bin, \"'#{lockdir}'\", \"'#{bin_dir}'\" ]\n\n # This option is almost entirely for support of ChefDK and enables transitive gemfile lock construction in order\n # to be able to decouple the dev gems for all the different components of ChefDK. AKA: don't use it outside of\n # ChefDK. You should also explicitly specify the lockdir when going down this road.\n command << [ \"'#{gem}'\" ] if gem\n\n # FIXME: appbundler lacks support for this argument when not also specifying the gem (2-arg appbundling lacks support)\n # (if you really need this bug fixed, though, fix it in appbundler, don't try using the 3-arg version to try to\n # get `--without` support, you will likely wind up going down a sad path).\n command << [ \"--without\", without.join(\",\") ] unless without.nil?\n\n command << [ \"--extra-bin-files\", extra_bin_files.join(\",\") ] unless extra_bin_files.nil? || extra_bin_files.empty?\n\n # Ensure the main bin dir exists\n FileUtils.mkdir_p(bin_dir)\n\n shellout!(command.join(\" \"), options)\n end\n end", "language": "ruby", "code": "def appbundle(software_name, lockdir: nil, gem: nil, without: nil, extra_bin_files: nil , **options)\n build_commands << BuildCommand.new(\"appbundle `#{software_name}'\") do\n bin_dir = \"#{install_dir}/bin\"\n appbundler_bin = embedded_bin(\"appbundler\")\n\n lockdir ||=\n begin\n app_software = project.softwares.find do |p|\n p.name == software_name\n end\n if app_software.nil?\n raise \"could not find software definition for #{software_name}, add a dependency to it, or pass a lockdir argument to appbundle command.\"\n end\n app_software.project_dir\n end\n\n command = [ appbundler_bin, \"'#{lockdir}'\", \"'#{bin_dir}'\" ]\n\n # This option is almost entirely for support of ChefDK and enables transitive gemfile lock construction in order\n # to be able to decouple the dev gems for all the different components of ChefDK. AKA: don't use it outside of\n # ChefDK. You should also explicitly specify the lockdir when going down this road.\n command << [ \"'#{gem}'\" ] if gem\n\n # FIXME: appbundler lacks support for this argument when not also specifying the gem (2-arg appbundling lacks support)\n # (if you really need this bug fixed, though, fix it in appbundler, don't try using the 3-arg version to try to\n # get `--without` support, you will likely wind up going down a sad path).\n command << [ \"--without\", without.join(\",\") ] unless without.nil?\n\n command << [ \"--extra-bin-files\", extra_bin_files.join(\",\") ] unless extra_bin_files.nil? || extra_bin_files.empty?\n\n # Ensure the main bin dir exists\n FileUtils.mkdir_p(bin_dir)\n\n shellout!(command.join(\" \"), options)\n end\n end", "code_tokens": ["def", "appbundle", "(", "software_name", ",", "lockdir", ":", "nil", ",", "gem", ":", "nil", ",", "without", ":", "nil", ",", "extra_bin_files", ":", "nil", ",", "**", "options", ")", "build_commands", "<<", "BuildCommand", ".", "new", "(", "\"appbundle `#{software_name}'\"", ")", "do", "bin_dir", "=", "\"#{install_dir}/bin\"", "appbundler_bin", "=", "embedded_bin", "(", "\"appbundler\"", ")", "lockdir", "||=", "begin", "app_software", "=", "project", ".", "softwares", ".", "find", "do", "|", "p", "|", "p", ".", "name", "==", "software_name", "end", "if", "app_software", ".", "nil?", "raise", "\"could not find software definition for #{software_name}, add a dependency to it, or pass a lockdir argument to appbundle command.\"", "end", "app_software", ".", "project_dir", "end", "command", "=", "[", "appbundler_bin", ",", "\"'#{lockdir}'\"", ",", "\"'#{bin_dir}'\"", "]", "# This option is almost entirely for support of ChefDK and enables transitive gemfile lock construction in order", "# to be able to decouple the dev gems for all the different components of ChefDK. AKA: don't use it outside of", "# ChefDK. You should also explicitly specify the lockdir when going down this road.", "command", "<<", "[", "\"'#{gem}'\"", "]", "if", "gem", "# FIXME: appbundler lacks support for this argument when not also specifying the gem (2-arg appbundling lacks support)", "# (if you really need this bug fixed, though, fix it in appbundler, don't try using the 3-arg version to try to", "# get `--without` support, you will likely wind up going down a sad path).", "command", "<<", "[", "\"--without\"", ",", "without", ".", "join", "(", "\",\"", ")", "]", "unless", "without", ".", "nil?", "command", "<<", "[", "\"--extra-bin-files\"", ",", "extra_bin_files", ".", "join", "(", "\",\"", ")", "]", "unless", "extra_bin_files", ".", "nil?", "||", "extra_bin_files", ".", "empty?", "# Ensure the main bin dir exists", "FileUtils", ".", "mkdir_p", "(", "bin_dir", ")", "shellout!", "(", "command", ".", "join", "(", "\" \"", ")", ",", "options", ")", "end", "end"], "docstring": "Execute the given appbundler command against the embedded Ruby's\n appbundler. This command assumes the +appbundle+ gem is installed and\n in the embedded Ruby. You should add a dependency on the +appbundler+\n software definition if you want to use this command.\n\n @example\n appbundle 'chef'\n\n @param software_name [String]\n The omnibus software definition name that you want to appbundle. We\n assume that this software definition is a gem that already has `bundle\n install` ran on it so it has a Gemfile.lock to appbundle.\n @param (see #command)\n @return (see #command)", "docstring_tokens": ["Execute", "the", "given", "appbundler", "command", "against", "the", "embedded", "Ruby", "s", "appbundler", ".", "This", "command", "assumes", "the", "+", "appbundle", "+", "gem", "is", "installed", "and", "in", "the", "embedded", "Ruby", ".", "You", "should", "add", "a", "dependency", "on", "the", "+", "appbundler", "+", "software", "definition", "if", "you", "want", "to", "use", "this", "command", "."], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/builder.rb#L375-L410", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/builder.rb", "func_name": "Omnibus.Builder.rake", "original_string": "def rake(command, options = {})\n build_commands << BuildCommand.new(\"rake `#{command}'\") do\n bin = embedded_bin(\"rake\")\n shellout!(\"#{bin} #{command}\", options)\n end\n end", "language": "ruby", "code": "def rake(command, options = {})\n build_commands << BuildCommand.new(\"rake `#{command}'\") do\n bin = embedded_bin(\"rake\")\n shellout!(\"#{bin} #{command}\", options)\n end\n end", "code_tokens": ["def", "rake", "(", "command", ",", "options", "=", "{", "}", ")", "build_commands", "<<", "BuildCommand", ".", "new", "(", "\"rake `#{command}'\"", ")", "do", "bin", "=", "embedded_bin", "(", "\"rake\"", ")", "shellout!", "(", "\"#{bin} #{command}\"", ",", "options", ")", "end", "end"], "docstring": "Execute the given Rake command against the embedded Ruby's rake. This\n command assumes the +rake+ gem has been installed.\n\n @example\n rake 'test'\n\n @param (see #command)\n @return (see #command)", "docstring_tokens": ["Execute", "the", "given", "Rake", "command", "against", "the", "embedded", "Ruby", "s", "rake", ".", "This", "command", "assumes", "the", "+", "rake", "+", "gem", "has", "been", "installed", "."], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/builder.rb#L423-L428", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/builder.rb", "func_name": "Omnibus.Builder.touch", "original_string": "def touch(file, options = {})\n build_commands << BuildCommand.new(\"touch `#{file}'\") do\n Dir.chdir(software.project_dir) do\n parent = File.dirname(file)\n FileUtils.mkdir_p(parent) unless File.directory?(parent)\n\n FileUtils.touch(file, options)\n end\n end\n end", "language": "ruby", "code": "def touch(file, options = {})\n build_commands << BuildCommand.new(\"touch `#{file}'\") do\n Dir.chdir(software.project_dir) do\n parent = File.dirname(file)\n FileUtils.mkdir_p(parent) unless File.directory?(parent)\n\n FileUtils.touch(file, options)\n end\n end\n end", "code_tokens": ["def", "touch", "(", "file", ",", "options", "=", "{", "}", ")", "build_commands", "<<", "BuildCommand", ".", "new", "(", "\"touch `#{file}'\"", ")", "do", "Dir", ".", "chdir", "(", "software", ".", "project_dir", ")", "do", "parent", "=", "File", ".", "dirname", "(", "file", ")", "FileUtils", ".", "mkdir_p", "(", "parent", ")", "unless", "File", ".", "directory?", "(", "parent", ")", "FileUtils", ".", "touch", "(", "file", ",", "options", ")", "end", "end", "end"], "docstring": "Touch the given filepath at runtime. This method will also ensure the\n containing directory exists first.\n\n @param [String] file\n the path of the file to touch\n @param (see #mkdir)\n\n @return (see #command)", "docstring_tokens": ["Touch", "the", "given", "filepath", "at", "runtime", ".", "This", "method", "will", "also", "ensure", "the", "containing", "directory", "exists", "first", "."], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/builder.rb#L553-L562", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/builder.rb", "func_name": "Omnibus.Builder.delete", "original_string": "def delete(path, options = {})\n build_commands << BuildCommand.new(\"delete `#{path}'\") do\n Dir.chdir(software.project_dir) do\n FileSyncer.glob(path).each do |file|\n FileUtils.rm_rf(file, options)\n end\n end\n end\n end", "language": "ruby", "code": "def delete(path, options = {})\n build_commands << BuildCommand.new(\"delete `#{path}'\") do\n Dir.chdir(software.project_dir) do\n FileSyncer.glob(path).each do |file|\n FileUtils.rm_rf(file, options)\n end\n end\n end\n end", "code_tokens": ["def", "delete", "(", "path", ",", "options", "=", "{", "}", ")", "build_commands", "<<", "BuildCommand", ".", "new", "(", "\"delete `#{path}'\"", ")", "do", "Dir", ".", "chdir", "(", "software", ".", "project_dir", ")", "do", "FileSyncer", ".", "glob", "(", "path", ")", ".", "each", "do", "|", "file", "|", "FileUtils", ".", "rm_rf", "(", "file", ",", "options", ")", "end", "end", "end", "end"], "docstring": "Delete the given file or directory on the system. This method uses the\n equivalent of +rm -rf+, so you may pass in a specific file or a glob of\n files.\n\n @param [String] path\n the path of the file to delete\n @param (see #mkdir)\n\n @return (see #command)", "docstring_tokens": ["Delete", "the", "given", "file", "or", "directory", "on", "the", "system", ".", "This", "method", "uses", "the", "equivalent", "of", "+", "rm", "-", "rf", "+", "so", "you", "may", "pass", "in", "a", "specific", "file", "or", "a", "glob", "of", "files", "."], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/builder.rb#L576-L584", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/builder.rb", "func_name": "Omnibus.Builder.copy", "original_string": "def copy(source, destination, options = {})\n command = \"copy `#{source}' to `#{destination}'\"\n build_commands << BuildCommand.new(command) do\n Dir.chdir(software.project_dir) do\n files = FileSyncer.glob(source)\n if files.empty?\n log.warn(log_key) { \"no matched files for glob #{command}\" }\n else\n files.each do |file|\n FileUtils.cp_r(file, destination, options)\n end\n end\n end\n end\n end", "language": "ruby", "code": "def copy(source, destination, options = {})\n command = \"copy `#{source}' to `#{destination}'\"\n build_commands << BuildCommand.new(command) do\n Dir.chdir(software.project_dir) do\n files = FileSyncer.glob(source)\n if files.empty?\n log.warn(log_key) { \"no matched files for glob #{command}\" }\n else\n files.each do |file|\n FileUtils.cp_r(file, destination, options)\n end\n end\n end\n end\n end", "code_tokens": ["def", "copy", "(", "source", ",", "destination", ",", "options", "=", "{", "}", ")", "command", "=", "\"copy `#{source}' to `#{destination}'\"", "build_commands", "<<", "BuildCommand", ".", "new", "(", "command", ")", "do", "Dir", ".", "chdir", "(", "software", ".", "project_dir", ")", "do", "files", "=", "FileSyncer", ".", "glob", "(", "source", ")", "if", "files", ".", "empty?", "log", ".", "warn", "(", "log_key", ")", "{", "\"no matched files for glob #{command}\"", "}", "else", "files", ".", "each", "do", "|", "file", "|", "FileUtils", ".", "cp_r", "(", "file", ",", "destination", ",", "options", ")", "end", "end", "end", "end", "end"], "docstring": "Copy the given source to the destination. This method accepts a single\n file or a file pattern to match.\n\n @param [String] source\n the path on disk to copy from\n @param [String] destination\n the path on disk to copy to\n @param (see #mkdir)\n\n @return (see #command)", "docstring_tokens": ["Copy", "the", "given", "source", "to", "the", "destination", ".", "This", "method", "accepts", "a", "single", "file", "or", "a", "file", "pattern", "to", "match", "."], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/builder.rb#L622-L636", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/builder.rb", "func_name": "Omnibus.Builder.update_config_guess", "original_string": "def update_config_guess(target: \".\", install: [:config_guess, :config_sub])\n build_commands << BuildCommand.new(\"update_config_guess `target: #{target} install: #{install.inspect}'\") do\n config_guess_dir = \"#{install_dir}/embedded/lib/config_guess\"\n %w{config.guess config.sub}.each do |c|\n unless File.exist?(File.join(config_guess_dir, c))\n raise \"Can not find #{c}. Make sure you add a dependency on 'config_guess' in your software definition\"\n end\n end\n\n destination = File.join(software.project_dir, target)\n FileUtils.mkdir_p(destination)\n\n FileUtils.cp_r(\"#{config_guess_dir}/config.guess\", destination) if install.include? :config_guess\n FileUtils.cp_r(\"#{config_guess_dir}/config.sub\", destination) if install.include? :config_sub\n end\n end", "language": "ruby", "code": "def update_config_guess(target: \".\", install: [:config_guess, :config_sub])\n build_commands << BuildCommand.new(\"update_config_guess `target: #{target} install: #{install.inspect}'\") do\n config_guess_dir = \"#{install_dir}/embedded/lib/config_guess\"\n %w{config.guess config.sub}.each do |c|\n unless File.exist?(File.join(config_guess_dir, c))\n raise \"Can not find #{c}. Make sure you add a dependency on 'config_guess' in your software definition\"\n end\n end\n\n destination = File.join(software.project_dir, target)\n FileUtils.mkdir_p(destination)\n\n FileUtils.cp_r(\"#{config_guess_dir}/config.guess\", destination) if install.include? :config_guess\n FileUtils.cp_r(\"#{config_guess_dir}/config.sub\", destination) if install.include? :config_sub\n end\n end", "code_tokens": ["def", "update_config_guess", "(", "target", ":", "\".\"", ",", "install", ":", "[", ":config_guess", ",", ":config_sub", "]", ")", "build_commands", "<<", "BuildCommand", ".", "new", "(", "\"update_config_guess `target: #{target} install: #{install.inspect}'\"", ")", "do", "config_guess_dir", "=", "\"#{install_dir}/embedded/lib/config_guess\"", "%w{", "config.guess", "config.sub", "}", ".", "each", "do", "|", "c", "|", "unless", "File", ".", "exist?", "(", "File", ".", "join", "(", "config_guess_dir", ",", "c", ")", ")", "raise", "\"Can not find #{c}. Make sure you add a dependency on 'config_guess' in your software definition\"", "end", "end", "destination", "=", "File", ".", "join", "(", "software", ".", "project_dir", ",", "target", ")", "FileUtils", ".", "mkdir_p", "(", "destination", ")", "FileUtils", ".", "cp_r", "(", "\"#{config_guess_dir}/config.guess\"", ",", "destination", ")", "if", "install", ".", "include?", ":config_guess", "FileUtils", ".", "cp_r", "(", "\"#{config_guess_dir}/config.sub\"", ",", "destination", ")", "if", "install", ".", "include?", ":config_sub", "end", "end"], "docstring": "Helper method to update config_guess in the software's source\n directory.\n You should add a dependency on the +config_guess+ software definition if you\n want to use this command.\n @param [Hash] options\n Supported options are:\n target [String] subdirectory under the software source to copy\n config.guess.to. Default: \".\"\n install [Array] parts of config.guess to copy.\n Default: [:config_guess, :config_sub]", "docstring_tokens": ["Helper", "method", "to", "update", "config_guess", "in", "the", "software", "s", "source", "directory", ".", "You", "should", "add", "a", "dependency", "on", "the", "+", "config_guess", "+", "software", "definition", "if", "you", "want", "to", "use", "this", "command", "."], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/builder.rb#L730-L745", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/compressors/tgz.rb", "func_name": "Omnibus.Compressor::TGZ.write_tgz", "original_string": "def write_tgz\n # Grab the contents of the gzipped tarball for reading\n contents = gzipped_tarball\n\n # Write the .tar.gz into the staging directory\n File.open(\"#{staging_dir}/#{package_name}\", \"wb\") do |tgz|\n while chunk = contents.read(1024)\n tgz.write(chunk)\n end\n end\n\n # Copy the .tar.gz into the package directory\n FileSyncer.glob(\"#{staging_dir}/*.tar.gz\").each do |tgz|\n copy_file(tgz, Config.package_dir)\n end\n end", "language": "ruby", "code": "def write_tgz\n # Grab the contents of the gzipped tarball for reading\n contents = gzipped_tarball\n\n # Write the .tar.gz into the staging directory\n File.open(\"#{staging_dir}/#{package_name}\", \"wb\") do |tgz|\n while chunk = contents.read(1024)\n tgz.write(chunk)\n end\n end\n\n # Copy the .tar.gz into the package directory\n FileSyncer.glob(\"#{staging_dir}/*.tar.gz\").each do |tgz|\n copy_file(tgz, Config.package_dir)\n end\n end", "code_tokens": ["def", "write_tgz", "# Grab the contents of the gzipped tarball for reading", "contents", "=", "gzipped_tarball", "# Write the .tar.gz into the staging directory", "File", ".", "open", "(", "\"#{staging_dir}/#{package_name}\"", ",", "\"wb\"", ")", "do", "|", "tgz", "|", "while", "chunk", "=", "contents", ".", "read", "(", "1024", ")", "tgz", ".", "write", "(", "chunk", ")", "end", "end", "# Copy the .tar.gz into the package directory", "FileSyncer", ".", "glob", "(", "\"#{staging_dir}/*.tar.gz\"", ")", ".", "each", "do", "|", "tgz", "|", "copy_file", "(", "tgz", ",", "Config", ".", "package_dir", ")", "end", "end"], "docstring": "Write the tar.gz to disk, reading in 1024 bytes at a time to reduce\n memory usage.\n\n @return [void]", "docstring_tokens": ["Write", "the", "tar", ".", "gz", "to", "disk", "reading", "in", "1024", "bytes", "at", "a", "time", "to", "reduce", "memory", "usage", "."], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/compressors/tgz.rb#L83-L98", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/compressors/tgz.rb", "func_name": "Omnibus.Compressor::TGZ.tarball", "original_string": "def tarball\n tarfile = StringIO.new(\"\")\n Gem::Package::TarWriter.new(tarfile) do |tar|\n path = \"#{staging_dir}/#{packager.package_name}\"\n name = packager.package_name\n mode = File.stat(path).mode\n\n tar.add_file(name, mode) do |tf|\n File.open(path, \"rb\") do |file|\n tf.write(file.read)\n end\n end\n end\n\n tarfile.rewind\n tarfile\n end", "language": "ruby", "code": "def tarball\n tarfile = StringIO.new(\"\")\n Gem::Package::TarWriter.new(tarfile) do |tar|\n path = \"#{staging_dir}/#{packager.package_name}\"\n name = packager.package_name\n mode = File.stat(path).mode\n\n tar.add_file(name, mode) do |tf|\n File.open(path, \"rb\") do |file|\n tf.write(file.read)\n end\n end\n end\n\n tarfile.rewind\n tarfile\n end", "code_tokens": ["def", "tarball", "tarfile", "=", "StringIO", ".", "new", "(", "\"\"", ")", "Gem", "::", "Package", "::", "TarWriter", ".", "new", "(", "tarfile", ")", "do", "|", "tar", "|", "path", "=", "\"#{staging_dir}/#{packager.package_name}\"", "name", "=", "packager", ".", "package_name", "mode", "=", "File", ".", "stat", "(", "path", ")", ".", "mode", "tar", ".", "add_file", "(", "name", ",", "mode", ")", "do", "|", "tf", "|", "File", ".", "open", "(", "path", ",", "\"rb\"", ")", "do", "|", "file", "|", "tf", ".", "write", "(", "file", ".", "read", ")", "end", "end", "end", "tarfile", ".", "rewind", "tarfile", "end"], "docstring": "Create an in-memory tarball from the given packager.\n\n @return [StringIO]", "docstring_tokens": ["Create", "an", "in", "-", "memory", "tarball", "from", "the", "given", "packager", "."], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/compressors/tgz.rb#L105-L121", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/fetchers/net_fetcher.rb", "func_name": "Omnibus.NetFetcher.clean", "original_string": "def clean\n needs_cleaning = File.exist?(project_dir)\n if needs_cleaning\n log.info(log_key) { \"Cleaning project directory `#{project_dir}'\" }\n FileUtils.rm_rf(project_dir)\n end\n create_required_directories\n deploy\n needs_cleaning\n end", "language": "ruby", "code": "def clean\n needs_cleaning = File.exist?(project_dir)\n if needs_cleaning\n log.info(log_key) { \"Cleaning project directory `#{project_dir}'\" }\n FileUtils.rm_rf(project_dir)\n end\n create_required_directories\n deploy\n needs_cleaning\n end", "code_tokens": ["def", "clean", "needs_cleaning", "=", "File", ".", "exist?", "(", "project_dir", ")", "if", "needs_cleaning", "log", ".", "info", "(", "log_key", ")", "{", "\"Cleaning project directory `#{project_dir}'\"", "}", "FileUtils", ".", "rm_rf", "(", "project_dir", ")", "end", "create_required_directories", "deploy", "needs_cleaning", "end"], "docstring": "Clean the project directory if it exists and actually extract\n the downloaded file.\n\n @return [true, false]\n true if the project directory was removed, false otherwise", "docstring_tokens": ["Clean", "the", "project", "directory", "if", "it", "exists", "and", "actually", "extract", "the", "downloaded", "file", "."], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/fetchers/net_fetcher.rb#L64-L73", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/fetchers/net_fetcher.rb", "func_name": "Omnibus.NetFetcher.deploy", "original_string": "def deploy\n if downloaded_file.end_with?(*ALL_EXTENSIONS)\n log.info(log_key) { \"Extracting `#{safe_downloaded_file}' to `#{safe_project_dir}'\" }\n extract\n else\n log.info(log_key) { \"`#{safe_downloaded_file}' is not an archive - copying to `#{safe_project_dir}'\" }\n\n if File.directory?(downloaded_file)\n # If the file itself was a directory, copy the whole thing over. This\n # seems unlikely, because I do not think it is a possible to download\n # a folder, but better safe than sorry.\n FileUtils.cp_r(\"#{downloaded_file}/.\", project_dir)\n else\n # In the more likely case that we got a \"regular\" file, we want that\n # file to live **inside** the project directory. project_dir should already\n # exist due to create_required_directories\n FileUtils.cp(downloaded_file, project_dir)\n end\n end\n end", "language": "ruby", "code": "def deploy\n if downloaded_file.end_with?(*ALL_EXTENSIONS)\n log.info(log_key) { \"Extracting `#{safe_downloaded_file}' to `#{safe_project_dir}'\" }\n extract\n else\n log.info(log_key) { \"`#{safe_downloaded_file}' is not an archive - copying to `#{safe_project_dir}'\" }\n\n if File.directory?(downloaded_file)\n # If the file itself was a directory, copy the whole thing over. This\n # seems unlikely, because I do not think it is a possible to download\n # a folder, but better safe than sorry.\n FileUtils.cp_r(\"#{downloaded_file}/.\", project_dir)\n else\n # In the more likely case that we got a \"regular\" file, we want that\n # file to live **inside** the project directory. project_dir should already\n # exist due to create_required_directories\n FileUtils.cp(downloaded_file, project_dir)\n end\n end\n end", "code_tokens": ["def", "deploy", "if", "downloaded_file", ".", "end_with?", "(", "ALL_EXTENSIONS", ")", "log", ".", "info", "(", "log_key", ")", "{", "\"Extracting `#{safe_downloaded_file}' to `#{safe_project_dir}'\"", "}", "extract", "else", "log", ".", "info", "(", "log_key", ")", "{", "\"`#{safe_downloaded_file}' is not an archive - copying to `#{safe_project_dir}'\"", "}", "if", "File", ".", "directory?", "(", "downloaded_file", ")", "# If the file itself was a directory, copy the whole thing over. This", "# seems unlikely, because I do not think it is a possible to download", "# a folder, but better safe than sorry.", "FileUtils", ".", "cp_r", "(", "\"#{downloaded_file}/.\"", ",", "project_dir", ")", "else", "# In the more likely case that we got a \"regular\" file, we want that", "# file to live **inside** the project directory. project_dir should already", "# exist due to create_required_directories", "FileUtils", ".", "cp", "(", "downloaded_file", ",", "project_dir", ")", "end", "end", "end"], "docstring": "Extract the downloaded file, using the magical logic based off of the\n ending file extension. In the rare event the file cannot be extracted, it\n is copied over as a raw file.", "docstring_tokens": ["Extract", "the", "downloaded", "file", "using", "the", "magical", "logic", "based", "off", "of", "the", "ending", "file", "extension", ".", "In", "the", "rare", "event", "the", "file", "cannot", "be", "extracted", "it", "is", "copied", "over", "as", "a", "raw", "file", "."], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/fetchers/net_fetcher.rb#L184-L203", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/fetchers/net_fetcher.rb", "func_name": "Omnibus.NetFetcher.extract", "original_string": "def extract\n # Only used by tar\n compression_switch = \"\"\n compression_switch = \"z\" if downloaded_file.end_with?(\"gz\")\n compression_switch = \"--lzma -\" if downloaded_file.end_with?(\"lzma\")\n compression_switch = \"j\" if downloaded_file.end_with?(\"bz2\")\n compression_switch = \"J\" if downloaded_file.end_with?(\"xz\")\n\n if Ohai[\"platform\"] == \"windows\"\n if downloaded_file.end_with?(*TAR_EXTENSIONS) && source[:extract] != :seven_zip\n returns = [0]\n returns << 1 if source[:extract] == :lax_tar\n\n shellout!(\"tar #{compression_switch}xf #{safe_downloaded_file} -C#{safe_project_dir}\", returns: returns)\n elsif downloaded_file.end_with?(*COMPRESSED_TAR_EXTENSIONS)\n Dir.mktmpdir do |temp_dir|\n log.debug(log_key) { \"Temporarily extracting `#{safe_downloaded_file}' to `#{temp_dir}'\" }\n\n shellout!(\"7z.exe x #{safe_downloaded_file} -o#{windows_safe_path(temp_dir)} -r -y\")\n\n fname = File.basename(downloaded_file, File.extname(downloaded_file))\n fname << \".tar\" if downloaded_file.end_with?(\"tgz\", \"txz\")\n next_file = windows_safe_path(File.join(temp_dir, fname))\n\n log.debug(log_key) { \"Temporarily extracting `#{next_file}' to `#{safe_project_dir}'\" }\n shellout!(\"7z.exe x #{next_file} -o#{safe_project_dir} -r -y\")\n end\n else\n shellout!(\"7z.exe x #{safe_downloaded_file} -o#{safe_project_dir} -r -y\")\n end\n elsif downloaded_file.end_with?(\".7z\")\n shellout!(\"7z x #{safe_downloaded_file} -o#{safe_project_dir} -r -y\")\n elsif downloaded_file.end_with?(\".zip\")\n shellout!(\"unzip #{safe_downloaded_file} -d #{safe_project_dir}\")\n else\n shellout!(\"#{tar} #{compression_switch}xf #{safe_downloaded_file} -C#{safe_project_dir}\")\n end\n end", "language": "ruby", "code": "def extract\n # Only used by tar\n compression_switch = \"\"\n compression_switch = \"z\" if downloaded_file.end_with?(\"gz\")\n compression_switch = \"--lzma -\" if downloaded_file.end_with?(\"lzma\")\n compression_switch = \"j\" if downloaded_file.end_with?(\"bz2\")\n compression_switch = \"J\" if downloaded_file.end_with?(\"xz\")\n\n if Ohai[\"platform\"] == \"windows\"\n if downloaded_file.end_with?(*TAR_EXTENSIONS) && source[:extract] != :seven_zip\n returns = [0]\n returns << 1 if source[:extract] == :lax_tar\n\n shellout!(\"tar #{compression_switch}xf #{safe_downloaded_file} -C#{safe_project_dir}\", returns: returns)\n elsif downloaded_file.end_with?(*COMPRESSED_TAR_EXTENSIONS)\n Dir.mktmpdir do |temp_dir|\n log.debug(log_key) { \"Temporarily extracting `#{safe_downloaded_file}' to `#{temp_dir}'\" }\n\n shellout!(\"7z.exe x #{safe_downloaded_file} -o#{windows_safe_path(temp_dir)} -r -y\")\n\n fname = File.basename(downloaded_file, File.extname(downloaded_file))\n fname << \".tar\" if downloaded_file.end_with?(\"tgz\", \"txz\")\n next_file = windows_safe_path(File.join(temp_dir, fname))\n\n log.debug(log_key) { \"Temporarily extracting `#{next_file}' to `#{safe_project_dir}'\" }\n shellout!(\"7z.exe x #{next_file} -o#{safe_project_dir} -r -y\")\n end\n else\n shellout!(\"7z.exe x #{safe_downloaded_file} -o#{safe_project_dir} -r -y\")\n end\n elsif downloaded_file.end_with?(\".7z\")\n shellout!(\"7z x #{safe_downloaded_file} -o#{safe_project_dir} -r -y\")\n elsif downloaded_file.end_with?(\".zip\")\n shellout!(\"unzip #{safe_downloaded_file} -d #{safe_project_dir}\")\n else\n shellout!(\"#{tar} #{compression_switch}xf #{safe_downloaded_file} -C#{safe_project_dir}\")\n end\n end", "code_tokens": ["def", "extract", "# Only used by tar", "compression_switch", "=", "\"\"", "compression_switch", "=", "\"z\"", "if", "downloaded_file", ".", "end_with?", "(", "\"gz\"", ")", "compression_switch", "=", "\"--lzma -\"", "if", "downloaded_file", ".", "end_with?", "(", "\"lzma\"", ")", "compression_switch", "=", "\"j\"", "if", "downloaded_file", ".", "end_with?", "(", "\"bz2\"", ")", "compression_switch", "=", "\"J\"", "if", "downloaded_file", ".", "end_with?", "(", "\"xz\"", ")", "if", "Ohai", "[", "\"platform\"", "]", "==", "\"windows\"", "if", "downloaded_file", ".", "end_with?", "(", "TAR_EXTENSIONS", ")", "&&", "source", "[", ":extract", "]", "!=", ":seven_zip", "returns", "=", "[", "0", "]", "returns", "<<", "1", "if", "source", "[", ":extract", "]", "==", ":lax_tar", "shellout!", "(", "\"tar #{compression_switch}xf #{safe_downloaded_file} -C#{safe_project_dir}\"", ",", "returns", ":", "returns", ")", "elsif", "downloaded_file", ".", "end_with?", "(", "COMPRESSED_TAR_EXTENSIONS", ")", "Dir", ".", "mktmpdir", "do", "|", "temp_dir", "|", "log", ".", "debug", "(", "log_key", ")", "{", "\"Temporarily extracting `#{safe_downloaded_file}' to `#{temp_dir}'\"", "}", "shellout!", "(", "\"7z.exe x #{safe_downloaded_file} -o#{windows_safe_path(temp_dir)} -r -y\"", ")", "fname", "=", "File", ".", "basename", "(", "downloaded_file", ",", "File", ".", "extname", "(", "downloaded_file", ")", ")", "fname", "<<", "\".tar\"", "if", "downloaded_file", ".", "end_with?", "(", "\"tgz\"", ",", "\"txz\"", ")", "next_file", "=", "windows_safe_path", "(", "File", ".", "join", "(", "temp_dir", ",", "fname", ")", ")", "log", ".", "debug", "(", "log_key", ")", "{", "\"Temporarily extracting `#{next_file}' to `#{safe_project_dir}'\"", "}", "shellout!", "(", "\"7z.exe x #{next_file} -o#{safe_project_dir} -r -y\"", ")", "end", "else", "shellout!", "(", "\"7z.exe x #{safe_downloaded_file} -o#{safe_project_dir} -r -y\"", ")", "end", "elsif", "downloaded_file", ".", "end_with?", "(", "\".7z\"", ")", "shellout!", "(", "\"7z x #{safe_downloaded_file} -o#{safe_project_dir} -r -y\"", ")", "elsif", "downloaded_file", ".", "end_with?", "(", "\".zip\"", ")", "shellout!", "(", "\"unzip #{safe_downloaded_file} -d #{safe_project_dir}\"", ")", "else", "shellout!", "(", "\"#{tar} #{compression_switch}xf #{safe_downloaded_file} -C#{safe_project_dir}\"", ")", "end", "end"], "docstring": "Extracts the downloaded archive file into project_dir.\n\n On windows, this is a fuster cluck and we allow users to specify the\n preferred extractor to be used. The default is to use tar. User overrides\n can be set in source[:extract] as:\n :tar - use tar.exe and fail on errors (default strategy).\n :seven_zip - use 7zip for all tar/compressed tar files on windows.\n :lax_tar - use tar.exe on windows but ignore errors.\n\n Both 7z and bsdtar have issues on windows.\n\n 7z cannot extract and untar at the same time. You need to extract to a\n temporary location and then extract again into project_dir.\n\n 7z also doesn't handle symlinks well. A symlink to a non-existent\n location simply results in a text file with the target path written in\n it. It does this without throwing any errors.\n\n bsdtar will exit(1) if it is encounters symlinks on windows. So we can't\n use shellout! directly.\n\n bsdtar will also exit(1) and fail to overwrite files at the destination\n during extraction if a file already exists at the destination and is\n marked read-only. This used to be a problem when we weren't properly\n cleaning an existing project_dir. It should be less of a problem now...\n but who knows.", "docstring_tokens": ["Extracts", "the", "downloaded", "archive", "file", "into", "project_dir", "."], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/fetchers/net_fetcher.rb#L233-L270", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/fetchers/net_fetcher.rb", "func_name": "Omnibus.NetFetcher.digest_type", "original_string": "def digest_type\n DIGESTS.each do |digest|\n return digest if source.key? digest\n end\n raise ChecksumMissing.new(self)\n end", "language": "ruby", "code": "def digest_type\n DIGESTS.each do |digest|\n return digest if source.key? digest\n end\n raise ChecksumMissing.new(self)\n end", "code_tokens": ["def", "digest_type", "DIGESTS", ".", "each", "do", "|", "digest", "|", "return", "digest", "if", "source", ".", "key?", "digest", "end", "raise", "ChecksumMissing", ".", "new", "(", "self", ")", "end"], "docstring": "The digest type defined in the software definition\n\n @raise [ChecksumMissing]\n if the checksum does not exist\n\n @return [Symbol]", "docstring_tokens": ["The", "digest", "type", "defined", "in", "the", "software", "definition"], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/fetchers/net_fetcher.rb#L280-L285", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/fetchers/net_fetcher.rb", "func_name": "Omnibus.NetFetcher.verify_checksum!", "original_string": "def verify_checksum!\n log.info(log_key) { \"Verifying checksum\" }\n\n expected = checksum\n actual = digest(downloaded_file, digest_type)\n\n if expected != actual\n raise ChecksumMismatch.new(self, expected, actual)\n end\n end", "language": "ruby", "code": "def verify_checksum!\n log.info(log_key) { \"Verifying checksum\" }\n\n expected = checksum\n actual = digest(downloaded_file, digest_type)\n\n if expected != actual\n raise ChecksumMismatch.new(self, expected, actual)\n end\n end", "code_tokens": ["def", "verify_checksum!", "log", ".", "info", "(", "log_key", ")", "{", "\"Verifying checksum\"", "}", "expected", "=", "checksum", "actual", "=", "digest", "(", "downloaded_file", ",", "digest_type", ")", "if", "expected", "!=", "actual", "raise", "ChecksumMismatch", ".", "new", "(", "self", ",", "expected", ",", "actual", ")", "end", "end"], "docstring": "Verify the downloaded file has the correct checksum.\n\n @raise [ChecksumMismatch]\n if the checksum does not match", "docstring_tokens": ["Verify", "the", "downloaded", "file", "has", "the", "correct", "checksum", "."], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/fetchers/net_fetcher.rb#L293-L302", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/packagers/windows_base.rb", "func_name": "Omnibus.Packager::WindowsBase.signing_identity", "original_string": "def signing_identity(thumbprint = NULL, params = NULL)\n unless null?(thumbprint)\n @signing_identity = {}\n unless thumbprint.is_a?(String)\n raise InvalidValue.new(:signing_identity, \"be a String\")\n end\n\n @signing_identity[:thumbprint] = thumbprint\n\n if !null?(params)\n unless params.is_a?(Hash)\n raise InvalidValue.new(:params, \"be a Hash\")\n end\n\n valid_keys = [:store, :timestamp_servers, :machine_store, :algorithm]\n invalid_keys = params.keys - valid_keys\n unless invalid_keys.empty?\n raise InvalidValue.new(:params, \"contain keys from [#{valid_keys.join(', ')}]. \"\\\n \"Found invalid keys [#{invalid_keys.join(', ')}]\")\n end\n\n if !params[:machine_store].nil? && !(\n params[:machine_store].is_a?(TrueClass) ||\n params[:machine_store].is_a?(FalseClass))\n raise InvalidValue.new(:params, \"contain key :machine_store of type TrueClass or FalseClass\")\n end\n else\n params = {}\n end\n\n @signing_identity[:store] = params[:store] || \"My\"\n @signing_identity[:algorithm] = params[:algorithm] || \"SHA256\"\n servers = params[:timestamp_servers] || DEFAULT_TIMESTAMP_SERVERS\n @signing_identity[:timestamp_servers] = [servers].flatten\n @signing_identity[:machine_store] = params[:machine_store] || false\n end\n\n @signing_identity\n end", "language": "ruby", "code": "def signing_identity(thumbprint = NULL, params = NULL)\n unless null?(thumbprint)\n @signing_identity = {}\n unless thumbprint.is_a?(String)\n raise InvalidValue.new(:signing_identity, \"be a String\")\n end\n\n @signing_identity[:thumbprint] = thumbprint\n\n if !null?(params)\n unless params.is_a?(Hash)\n raise InvalidValue.new(:params, \"be a Hash\")\n end\n\n valid_keys = [:store, :timestamp_servers, :machine_store, :algorithm]\n invalid_keys = params.keys - valid_keys\n unless invalid_keys.empty?\n raise InvalidValue.new(:params, \"contain keys from [#{valid_keys.join(', ')}]. \"\\\n \"Found invalid keys [#{invalid_keys.join(', ')}]\")\n end\n\n if !params[:machine_store].nil? && !(\n params[:machine_store].is_a?(TrueClass) ||\n params[:machine_store].is_a?(FalseClass))\n raise InvalidValue.new(:params, \"contain key :machine_store of type TrueClass or FalseClass\")\n end\n else\n params = {}\n end\n\n @signing_identity[:store] = params[:store] || \"My\"\n @signing_identity[:algorithm] = params[:algorithm] || \"SHA256\"\n servers = params[:timestamp_servers] || DEFAULT_TIMESTAMP_SERVERS\n @signing_identity[:timestamp_servers] = [servers].flatten\n @signing_identity[:machine_store] = params[:machine_store] || false\n end\n\n @signing_identity\n end", "code_tokens": ["def", "signing_identity", "(", "thumbprint", "=", "NULL", ",", "params", "=", "NULL", ")", "unless", "null?", "(", "thumbprint", ")", "@signing_identity", "=", "{", "}", "unless", "thumbprint", ".", "is_a?", "(", "String", ")", "raise", "InvalidValue", ".", "new", "(", ":signing_identity", ",", "\"be a String\"", ")", "end", "@signing_identity", "[", ":thumbprint", "]", "=", "thumbprint", "if", "!", "null?", "(", "params", ")", "unless", "params", ".", "is_a?", "(", "Hash", ")", "raise", "InvalidValue", ".", "new", "(", ":params", ",", "\"be a Hash\"", ")", "end", "valid_keys", "=", "[", ":store", ",", ":timestamp_servers", ",", ":machine_store", ",", ":algorithm", "]", "invalid_keys", "=", "params", ".", "keys", "-", "valid_keys", "unless", "invalid_keys", ".", "empty?", "raise", "InvalidValue", ".", "new", "(", ":params", ",", "\"contain keys from [#{valid_keys.join(', ')}]. \"", "\"Found invalid keys [#{invalid_keys.join(', ')}]\"", ")", "end", "if", "!", "params", "[", ":machine_store", "]", ".", "nil?", "&&", "!", "(", "params", "[", ":machine_store", "]", ".", "is_a?", "(", "TrueClass", ")", "||", "params", "[", ":machine_store", "]", ".", "is_a?", "(", "FalseClass", ")", ")", "raise", "InvalidValue", ".", "new", "(", ":params", ",", "\"contain key :machine_store of type TrueClass or FalseClass\"", ")", "end", "else", "params", "=", "{", "}", "end", "@signing_identity", "[", ":store", "]", "=", "params", "[", ":store", "]", "||", "\"My\"", "@signing_identity", "[", ":algorithm", "]", "=", "params", "[", ":algorithm", "]", "||", "\"SHA256\"", "servers", "=", "params", "[", ":timestamp_servers", "]", "||", "DEFAULT_TIMESTAMP_SERVERS", "@signing_identity", "[", ":timestamp_servers", "]", "=", "[", "servers", "]", ".", "flatten", "@signing_identity", "[", ":machine_store", "]", "=", "params", "[", ":machine_store", "]", "||", "false", "end", "@signing_identity", "end"], "docstring": "Set the signing certificate name\n\n @example\n signing_identity 'FooCert'\n signing_identity 'FooCert', store: 'BarStore'\n\n @param [String] thumbprint\n the thumbprint of the certificate in the certificate store\n @param [Hash] params\n an optional hash that defines the parameters for the singing identity\n\n @option params [String] :store (My)\n The name of the certificate store which contains the certificate\n @option params [Array, String] :timestamp_servers\n A trusted timestamp server or a list of truested timestamp servers to\n be tried. They are tried in the order provided.\n @option params [TrueClass, FalseClass] :machine_store (false)\n If set to true, the local machine store will be searched for a valid\n certificate. Otherwise, the current user store is used\n\n Setting nothing will default to trying ['http://timestamp.digicert.com',\n 'http://timestamp.verisign.com/scripts/timestamp.dll']\n\n @return [Hash{:thumbprint => String, :store => String, :timestamp_servers => Array[String]}]", "docstring_tokens": ["Set", "the", "signing", "certificate", "name"], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/packagers/windows_base.rb#L48-L86", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/packagers/windows_base.rb", "func_name": "Omnibus.Packager::WindowsBase.sign_package", "original_string": "def sign_package(package_file)\n success = false\n timestamp_servers.each do |ts|\n success = try_sign(package_file, ts)\n break if success\n end\n raise FailedToSignWindowsPackage.new if !success\n end", "language": "ruby", "code": "def sign_package(package_file)\n success = false\n timestamp_servers.each do |ts|\n success = try_sign(package_file, ts)\n break if success\n end\n raise FailedToSignWindowsPackage.new if !success\n end", "code_tokens": ["def", "sign_package", "(", "package_file", ")", "success", "=", "false", "timestamp_servers", ".", "each", "do", "|", "ts", "|", "success", "=", "try_sign", "(", "package_file", ",", "ts", ")", "break", "if", "success", "end", "raise", "FailedToSignWindowsPackage", ".", "new", "if", "!", "success", "end"], "docstring": "Iterates through available timestamp servers and tries to sign\n the file with with each server, stopping after the first to succeed.\n If none succeed, an exception is raised.", "docstring_tokens": ["Iterates", "through", "available", "timestamp", "servers", "and", "tries", "to", "sign", "the", "file", "with", "with", "each", "server", "stopping", "after", "the", "first", "to", "succeed", ".", "If", "none", "succeed", "an", "exception", "is", "raised", "."], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/packagers/windows_base.rb#L114-L121", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/packagers/windows_base.rb", "func_name": "Omnibus.Packager::WindowsBase.certificate_subject", "original_string": "def certificate_subject\n return \"CN=#{project.package_name}\" unless signing_identity\n store = machine_store? ? \"LocalMachine\" : \"CurrentUser\"\n cmd = Array.new.tap do |arr|\n arr << \"powershell.exe\"\n arr << \"-ExecutionPolicy Bypass\"\n arr << \"-NoProfile\"\n arr << \"-Command (Get-Item Cert:/#{store}/#{cert_store_name}/#{thumbprint}).Subject\"\n end.join(\" \")\n\n shellout!(cmd).stdout.strip\n end", "language": "ruby", "code": "def certificate_subject\n return \"CN=#{project.package_name}\" unless signing_identity\n store = machine_store? ? \"LocalMachine\" : \"CurrentUser\"\n cmd = Array.new.tap do |arr|\n arr << \"powershell.exe\"\n arr << \"-ExecutionPolicy Bypass\"\n arr << \"-NoProfile\"\n arr << \"-Command (Get-Item Cert:/#{store}/#{cert_store_name}/#{thumbprint}).Subject\"\n end.join(\" \")\n\n shellout!(cmd).stdout.strip\n end", "code_tokens": ["def", "certificate_subject", "return", "\"CN=#{project.package_name}\"", "unless", "signing_identity", "store", "=", "machine_store?", "?", "\"LocalMachine\"", ":", "\"CurrentUser\"", "cmd", "=", "Array", ".", "new", ".", "tap", "do", "|", "arr", "|", "arr", "<<", "\"powershell.exe\"", "arr", "<<", "\"-ExecutionPolicy Bypass\"", "arr", "<<", "\"-NoProfile\"", "arr", "<<", "\"-Command (Get-Item Cert:/#{store}/#{cert_store_name}/#{thumbprint}).Subject\"", "end", ".", "join", "(", "\" \"", ")", "shellout!", "(", "cmd", ")", ".", "stdout", ".", "strip", "end"], "docstring": "Get the certificate subject of the signing identity\n\n @return [String]", "docstring_tokens": ["Get", "the", "certificate", "subject", "of", "the", "signing", "identity"], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/packagers/windows_base.rb#L159-L170", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/software.rb", "func_name": "Omnibus.Software.manifest_entry", "original_string": "def manifest_entry\n @manifest_entry ||= if manifest\n log.info(log_key) { \"Using user-supplied manifest entry for #{name}\" }\n manifest.entry_for(name)\n else\n log.info(log_key) { \"Resolving manifest entry for #{name}\" }\n to_manifest_entry\n end\n end", "language": "ruby", "code": "def manifest_entry\n @manifest_entry ||= if manifest\n log.info(log_key) { \"Using user-supplied manifest entry for #{name}\" }\n manifest.entry_for(name)\n else\n log.info(log_key) { \"Resolving manifest entry for #{name}\" }\n to_manifest_entry\n end\n end", "code_tokens": ["def", "manifest_entry", "@manifest_entry", "||=", "if", "manifest", "log", ".", "info", "(", "log_key", ")", "{", "\"Using user-supplied manifest entry for #{name}\"", "}", "manifest", ".", "entry_for", "(", "name", ")", "else", "log", ".", "info", "(", "log_key", ")", "{", "\"Resolving manifest entry for #{name}\"", "}", "to_manifest_entry", "end", "end"], "docstring": "Create a new software object.\n\n @param [Project] project\n the Omnibus project that instantiated this software definition\n @param [String] filepath\n the path to where this software definition lives on disk\n @param [String] manifest\n the user-supplied software manifest\n\n @return [Software]", "docstring_tokens": ["Create", "a", "new", "software", "object", "."], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/software.rb#L110-L118", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/software.rb", "func_name": "Omnibus.Software.source", "original_string": "def source(val = NULL)\n unless null?(val)\n unless val.is_a?(Hash)\n raise InvalidValue.new(:source,\n \"be a kind of `Hash', but was `#{val.class.inspect}'\")\n end\n\n val = canonicalize_source(val)\n\n extra_keys = val.keys - [\n :git, :file, :path, :url, # fetcher types\n :md5, :sha1, :sha256, :sha512, # hash type - common to all fetchers\n :cookie, :warning, :unsafe, :extract, :cached_name, :authorization, # used by net_fetcher\n :options, # used by path_fetcher\n :submodules # used by git_fetcher\n ]\n unless extra_keys.empty?\n raise InvalidValue.new(:source,\n \"only include valid keys. Invalid keys: #{extra_keys.inspect}\")\n end\n\n duplicate_keys = val.keys & [:git, :file, :path, :url]\n unless duplicate_keys.size < 2\n raise InvalidValue.new(:source,\n \"not include duplicate keys. Duplicate keys: #{duplicate_keys.inspect}\")\n end\n\n @source ||= {}\n @source.merge!(val)\n end\n\n override = canonicalize_source(overrides[:source])\n apply_overrides(:source, override)\n end", "language": "ruby", "code": "def source(val = NULL)\n unless null?(val)\n unless val.is_a?(Hash)\n raise InvalidValue.new(:source,\n \"be a kind of `Hash', but was `#{val.class.inspect}'\")\n end\n\n val = canonicalize_source(val)\n\n extra_keys = val.keys - [\n :git, :file, :path, :url, # fetcher types\n :md5, :sha1, :sha256, :sha512, # hash type - common to all fetchers\n :cookie, :warning, :unsafe, :extract, :cached_name, :authorization, # used by net_fetcher\n :options, # used by path_fetcher\n :submodules # used by git_fetcher\n ]\n unless extra_keys.empty?\n raise InvalidValue.new(:source,\n \"only include valid keys. Invalid keys: #{extra_keys.inspect}\")\n end\n\n duplicate_keys = val.keys & [:git, :file, :path, :url]\n unless duplicate_keys.size < 2\n raise InvalidValue.new(:source,\n \"not include duplicate keys. Duplicate keys: #{duplicate_keys.inspect}\")\n end\n\n @source ||= {}\n @source.merge!(val)\n end\n\n override = canonicalize_source(overrides[:source])\n apply_overrides(:source, override)\n end", "code_tokens": ["def", "source", "(", "val", "=", "NULL", ")", "unless", "null?", "(", "val", ")", "unless", "val", ".", "is_a?", "(", "Hash", ")", "raise", "InvalidValue", ".", "new", "(", ":source", ",", "\"be a kind of `Hash', but was `#{val.class.inspect}'\"", ")", "end", "val", "=", "canonicalize_source", "(", "val", ")", "extra_keys", "=", "val", ".", "keys", "-", "[", ":git", ",", ":file", ",", ":path", ",", ":url", ",", "# fetcher types", ":md5", ",", ":sha1", ",", ":sha256", ",", ":sha512", ",", "# hash type - common to all fetchers", ":cookie", ",", ":warning", ",", ":unsafe", ",", ":extract", ",", ":cached_name", ",", ":authorization", ",", "# used by net_fetcher", ":options", ",", "# used by path_fetcher", ":submodules", "# used by git_fetcher", "]", "unless", "extra_keys", ".", "empty?", "raise", "InvalidValue", ".", "new", "(", ":source", ",", "\"only include valid keys. Invalid keys: #{extra_keys.inspect}\"", ")", "end", "duplicate_keys", "=", "val", ".", "keys", "&", "[", ":git", ",", ":file", ",", ":path", ",", ":url", "]", "unless", "duplicate_keys", ".", "size", "<", "2", "raise", "InvalidValue", ".", "new", "(", ":source", ",", "\"not include duplicate keys. Duplicate keys: #{duplicate_keys.inspect}\"", ")", "end", "@source", "||=", "{", "}", "@source", ".", "merge!", "(", "val", ")", "end", "override", "=", "canonicalize_source", "(", "overrides", "[", ":source", "]", ")", "apply_overrides", "(", ":source", ",", "override", ")", "end"], "docstring": "Set or retrieve the source for the software.\n\n @raise [InvalidValue]\n if the parameter is not a Hash\n @raise [InvalidValue]\n if the hash includes extraneous keys\n @raise [InvalidValue]\n if the hash declares keys that cannot work together\n (like +:git+ and +:path+)\n\n @example\n source url: 'http://ftp.gnu.org/gnu/autoconf/autoconf-2.68.tar.gz',\n md5: 'c3b5247592ce694f7097873aa07d66fe'\n\n @param [Hash] val\n a single key/pair that defines the kind of source and a path specifier\n\n @option val [String] :git (nil)\n a git URL\n @option val [String] :github (nil)\n a github ORG/REPO pair (e.g. chef/chef) that will be transformed to https://github.com/ORG/REPO.git\n @option val [String] :url (nil)\n general URL\n @option val [String] :path (nil)\n a fully-qualified local file system path\n @option val [String] :md5 (nil)\n the MD5 checksum of the downloaded artifact\n @option val [String] :sha1 (nil)\n the SHA1 checksum of the downloaded artifact\n @option val [String] :sha256 (nil)\n the SHA256 checksum of the downloaded artifact\n @option val [String] :sha512 (nil)\n the SHA512 checksum of the downloaded artifact\n\n Only used in net_fetcher:\n\n @option val [String] :cookie (nil)\n a cookie to set\n @option val [String] :authorization (nil)\n an authorization header to set\n @option val [String] :warning (nil)\n a warning message to print when downloading\n @option val [Symbol] :extract (nil)\n either :tar, :lax_tar :seven_zip\n\n Only used in path_fetcher:\n\n @option val [Hash] :options (nil)\n flags/options that are passed through to file_syncer in path_fetcher\n\n Only used in git_fetcher:\n\n @option val [Boolean] :submodules (false)\n clone git submodules\n\n If multiple checksum types are provided, only the strongest will be used.\n\n @return [Hash]", "docstring_tokens": ["Set", "or", "retrieve", "the", "source", "for", "the", "software", "."], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/software.rb#L287-L320", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/software.rb", "func_name": "Omnibus.Software.version", "original_string": "def version(val = NULL, &block)\n final_version = apply_overrides(:version)\n\n if block_given?\n if val.equal?(NULL)\n raise InvalidValue.new(:version,\n \"pass a block when given a version argument\")\n else\n if val == final_version\n #\n # Unfortunately we need to make a specific logic here for license files.\n # We support multiple calls `license_file` and we support overriding the\n # license files inside a version block. We can not differentiate whether\n # `license_file` is being called from a version block or not. So we need\n # to check if the license files are being overridden during the call to\n # block.\n #\n # If so we use the new set, otherwise we restore the old license files.\n #\n current_license_files = @license_files\n @license_files = []\n\n yield\n\n new_license_files = @license_files\n\n if new_license_files.empty?\n @license_files = current_license_files\n end\n end\n end\n end\n\n return if final_version.nil?\n\n begin\n Chef::Sugar::Constraints::Version.new(final_version)\n rescue ArgumentError\n log.warn(log_key) do\n \"Version #{final_version} for software #{name} was not parseable. \" \\\n \"Comparison methods such as #satisfies? will not be available for this version.\"\n end\n final_version\n end\n end", "language": "ruby", "code": "def version(val = NULL, &block)\n final_version = apply_overrides(:version)\n\n if block_given?\n if val.equal?(NULL)\n raise InvalidValue.new(:version,\n \"pass a block when given a version argument\")\n else\n if val == final_version\n #\n # Unfortunately we need to make a specific logic here for license files.\n # We support multiple calls `license_file` and we support overriding the\n # license files inside a version block. We can not differentiate whether\n # `license_file` is being called from a version block or not. So we need\n # to check if the license files are being overridden during the call to\n # block.\n #\n # If so we use the new set, otherwise we restore the old license files.\n #\n current_license_files = @license_files\n @license_files = []\n\n yield\n\n new_license_files = @license_files\n\n if new_license_files.empty?\n @license_files = current_license_files\n end\n end\n end\n end\n\n return if final_version.nil?\n\n begin\n Chef::Sugar::Constraints::Version.new(final_version)\n rescue ArgumentError\n log.warn(log_key) do\n \"Version #{final_version} for software #{name} was not parseable. \" \\\n \"Comparison methods such as #satisfies? will not be available for this version.\"\n end\n final_version\n end\n end", "code_tokens": ["def", "version", "(", "val", "=", "NULL", ",", "&", "block", ")", "final_version", "=", "apply_overrides", "(", ":version", ")", "if", "block_given?", "if", "val", ".", "equal?", "(", "NULL", ")", "raise", "InvalidValue", ".", "new", "(", ":version", ",", "\"pass a block when given a version argument\"", ")", "else", "if", "val", "==", "final_version", "#", "# Unfortunately we need to make a specific logic here for license files.", "# We support multiple calls `license_file` and we support overriding the", "# license files inside a version block. We can not differentiate whether", "# `license_file` is being called from a version block or not. So we need", "# to check if the license files are being overridden during the call to", "# block.", "#", "# If so we use the new set, otherwise we restore the old license files.", "#", "current_license_files", "=", "@license_files", "@license_files", "=", "[", "]", "yield", "new_license_files", "=", "@license_files", "if", "new_license_files", ".", "empty?", "@license_files", "=", "current_license_files", "end", "end", "end", "end", "return", "if", "final_version", ".", "nil?", "begin", "Chef", "::", "Sugar", "::", "Constraints", "::", "Version", ".", "new", "(", "final_version", ")", "rescue", "ArgumentError", "log", ".", "warn", "(", "log_key", ")", "do", "\"Version #{final_version} for software #{name} was not parseable. \"", "\"Comparison methods such as #satisfies? will not be available for this version.\"", "end", "final_version", "end", "end"], "docstring": "Evaluate a block only if the version matches.\n\n @example\n version '1.2.3' do\n source path: '/local/path/to/software-1.2.3'\n end\n\n @param [String] val\n the version of the software\n @param [Proc] block\n the block to run if the version we are building matches the argument\n\n @return [String, Proc]", "docstring_tokens": ["Evaluate", "a", "block", "only", "if", "the", "version", "matches", "."], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/software.rb#L452-L496", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/software.rb", "func_name": "Omnibus.Software.whitelist_file", "original_string": "def whitelist_file(file)\n file = Regexp.new(file) unless file.kind_of?(Regexp)\n whitelist_files << file\n whitelist_files.dup\n end", "language": "ruby", "code": "def whitelist_file(file)\n file = Regexp.new(file) unless file.kind_of?(Regexp)\n whitelist_files << file\n whitelist_files.dup\n end", "code_tokens": ["def", "whitelist_file", "(", "file", ")", "file", "=", "Regexp", ".", "new", "(", "file", ")", "unless", "file", ".", "kind_of?", "(", "Regexp", ")", "whitelist_files", "<<", "file", "whitelist_files", ".", "dup", "end"], "docstring": "Add a file to the healthcheck whitelist.\n\n @example\n whitelist_file '/path/to/file'\n\n @param [String, Regexp] file\n the name of a file to ignore in the healthcheck\n\n @return [Array]\n the list of currently whitelisted files", "docstring_tokens": ["Add", "a", "file", "to", "the", "healthcheck", "whitelist", "."], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/software.rb#L511-L515", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/software.rb", "func_name": "Omnibus.Software.project_file", "original_string": "def project_file\n if fetcher && fetcher.is_a?(NetFetcher)\n log.deprecated(log_key) do\n \"project_file (DSL). This is a property of the NetFetcher and will \" \\\n \"not be publically exposed in the next major release. In general, \" \\\n \"you should not be using this method in your software definitions \" \\\n \"as it is an internal implementation detail of the NetFetcher. If \" \\\n \"you disagree with this statement, you should open an issue on the \" \\\n \"Omnibus repository on GitHub an explain your use case. For now, \" \\\n \"I will return the path to the downloaded file on disk, but please \" \\\n \"rethink the problem you are trying to solve :).\"\n end\n\n fetcher.downloaded_file\n else\n log.warn(log_key) do\n \"Cannot retrieve a `project_file' for software `#{name}'. This \" \\\n \"attribute is actually an internal representation that is unique \" \\\n \"to the NetFetcher class and requires the use of a `source' \" \\\n \"attribute that is declared using a `:url' key. For backwards-\" \\\n \"compatability, I will return `nil', but this is most likely not \" \\\n \"your desired behavior.\"\n end\n\n nil\n end\n end", "language": "ruby", "code": "def project_file\n if fetcher && fetcher.is_a?(NetFetcher)\n log.deprecated(log_key) do\n \"project_file (DSL). This is a property of the NetFetcher and will \" \\\n \"not be publically exposed in the next major release. In general, \" \\\n \"you should not be using this method in your software definitions \" \\\n \"as it is an internal implementation detail of the NetFetcher. If \" \\\n \"you disagree with this statement, you should open an issue on the \" \\\n \"Omnibus repository on GitHub an explain your use case. For now, \" \\\n \"I will return the path to the downloaded file on disk, but please \" \\\n \"rethink the problem you are trying to solve :).\"\n end\n\n fetcher.downloaded_file\n else\n log.warn(log_key) do\n \"Cannot retrieve a `project_file' for software `#{name}'. This \" \\\n \"attribute is actually an internal representation that is unique \" \\\n \"to the NetFetcher class and requires the use of a `source' \" \\\n \"attribute that is declared using a `:url' key. For backwards-\" \\\n \"compatability, I will return `nil', but this is most likely not \" \\\n \"your desired behavior.\"\n end\n\n nil\n end\n end", "code_tokens": ["def", "project_file", "if", "fetcher", "&&", "fetcher", ".", "is_a?", "(", "NetFetcher", ")", "log", ".", "deprecated", "(", "log_key", ")", "do", "\"project_file (DSL). This is a property of the NetFetcher and will \"", "\"not be publically exposed in the next major release. In general, \"", "\"you should not be using this method in your software definitions \"", "\"as it is an internal implementation detail of the NetFetcher. If \"", "\"you disagree with this statement, you should open an issue on the \"", "\"Omnibus repository on GitHub an explain your use case. For now, \"", "\"I will return the path to the downloaded file on disk, but please \"", "\"rethink the problem you are trying to solve :).\"", "end", "fetcher", ".", "downloaded_file", "else", "log", ".", "warn", "(", "log_key", ")", "do", "\"Cannot retrieve a `project_file' for software `#{name}'. This \"", "\"attribute is actually an internal representation that is unique \"", "\"to the NetFetcher class and requires the use of a `source' \"", "\"attribute that is declared using a `:url' key. For backwards-\"", "\"compatability, I will return `nil', but this is most likely not \"", "\"your desired behavior.\"", "end", "nil", "end", "end"], "docstring": "The path to the downloaded file from a NetFetcher.\n\n @deprecated There is no replacement for this DSL method", "docstring_tokens": ["The", "path", "to", "the", "downloaded", "file", "from", "a", "NetFetcher", "."], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/software.rb#L614-L640", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/software.rb", "func_name": "Omnibus.Software.prepend_path", "original_string": "def prepend_path(*paths)\n path_values = Array(paths)\n path_values << ENV[path_key]\n\n separator = File::PATH_SEPARATOR || \":\"\n path_values.join(separator)\n end", "language": "ruby", "code": "def prepend_path(*paths)\n path_values = Array(paths)\n path_values << ENV[path_key]\n\n separator = File::PATH_SEPARATOR || \":\"\n path_values.join(separator)\n end", "code_tokens": ["def", "prepend_path", "(", "*", "paths", ")", "path_values", "=", "Array", "(", "paths", ")", "path_values", "<<", "ENV", "[", "path_key", "]", "separator", "=", "File", "::", "PATH_SEPARATOR", "||", "\":\"", "path_values", ".", "join", "(", "separator", ")", "end"], "docstring": "A PATH variable format string representing the current PATH with the\n given path prepended. The correct path separator\n for the platform is used to join the paths.\n\n @param [Array] paths\n\n @return [String]", "docstring_tokens": ["A", "PATH", "variable", "format", "string", "representing", "the", "current", "PATH", "with", "the", "given", "path", "prepended", ".", "The", "correct", "path", "separator", "for", "the", "platform", "is", "used", "to", "join", "the", "paths", "."], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/software.rb#L810-L816", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/software.rb", "func_name": "Omnibus.Software.overrides", "original_string": "def overrides\n if null?(@overrides)\n # lazily initialized because we need the 'name' to be parsed first\n @overrides = {}\n @overrides = project.overrides[name.to_sym].dup if project.overrides[name.to_sym]\n end\n\n @overrides\n end", "language": "ruby", "code": "def overrides\n if null?(@overrides)\n # lazily initialized because we need the 'name' to be parsed first\n @overrides = {}\n @overrides = project.overrides[name.to_sym].dup if project.overrides[name.to_sym]\n end\n\n @overrides\n end", "code_tokens": ["def", "overrides", "if", "null?", "(", "@overrides", ")", "# lazily initialized because we need the 'name' to be parsed first", "@overrides", "=", "{", "}", "@overrides", "=", "project", ".", "overrides", "[", "name", ".", "to_sym", "]", ".", "dup", "if", "project", ".", "overrides", "[", "name", ".", "to_sym", "]", "end", "@overrides", "end"], "docstring": "The repo-level and project-level overrides for the software.\n\n @return [Hash]", "docstring_tokens": ["The", "repo", "-", "level", "and", "project", "-", "level", "overrides", "for", "the", "software", "."], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/software.rb#L941-L949", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/software.rb", "func_name": "Omnibus.Software.version_for_cache", "original_string": "def version_for_cache\n @version_for_cache ||= if fetcher.version_for_cache\n fetcher.version_for_cache\n elsif version\n version\n else\n log.warn(log_key) do\n \"No version given! This is probably a bad thing. I am going to \" \\\n \"assume the version `0.0.0', but that is most certainly not your \" \\\n \"desired behavior. If git caching seems off, this is probably why.\"\n end\n\n \"0.0.0\"\n end\n end", "language": "ruby", "code": "def version_for_cache\n @version_for_cache ||= if fetcher.version_for_cache\n fetcher.version_for_cache\n elsif version\n version\n else\n log.warn(log_key) do\n \"No version given! This is probably a bad thing. I am going to \" \\\n \"assume the version `0.0.0', but that is most certainly not your \" \\\n \"desired behavior. If git caching seems off, this is probably why.\"\n end\n\n \"0.0.0\"\n end\n end", "code_tokens": ["def", "version_for_cache", "@version_for_cache", "||=", "if", "fetcher", ".", "version_for_cache", "fetcher", ".", "version_for_cache", "elsif", "version", "version", "else", "log", ".", "warn", "(", "log_key", ")", "do", "\"No version given! This is probably a bad thing. I am going to \"", "\"assume the version `0.0.0', but that is most certainly not your \"", "\"desired behavior. If git caching seems off, this is probably why.\"", "end", "\"0.0.0\"", "end", "end"], "docstring": "Returns the version to be used in cache.", "docstring_tokens": ["Returns", "the", "version", "to", "be", "used", "in", "cache", "."], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/software.rb#L991-L1005", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/software.rb", "func_name": "Omnibus.Software.fetcher", "original_string": "def fetcher\n @fetcher ||=\n if source_type == :url && File.basename(source[:url], \"?*\").end_with?(*NetFetcher::ALL_EXTENSIONS)\n Fetcher.fetcher_class_for_source(source).new(manifest_entry, fetch_dir, build_dir)\n else\n Fetcher.fetcher_class_for_source(source).new(manifest_entry, project_dir, build_dir)\n end\n end", "language": "ruby", "code": "def fetcher\n @fetcher ||=\n if source_type == :url && File.basename(source[:url], \"?*\").end_with?(*NetFetcher::ALL_EXTENSIONS)\n Fetcher.fetcher_class_for_source(source).new(manifest_entry, fetch_dir, build_dir)\n else\n Fetcher.fetcher_class_for_source(source).new(manifest_entry, project_dir, build_dir)\n end\n end", "code_tokens": ["def", "fetcher", "@fetcher", "||=", "if", "source_type", "==", ":url", "&&", "File", ".", "basename", "(", "source", "[", ":url", "]", ",", "\"?*\"", ")", ".", "end_with?", "(", "NetFetcher", "::", "ALL_EXTENSIONS", ")", "Fetcher", ".", "fetcher_class_for_source", "(", "source", ")", ".", "new", "(", "manifest_entry", ",", "fetch_dir", ",", "build_dir", ")", "else", "Fetcher", ".", "fetcher_class_for_source", "(", "source", ")", ".", "new", "(", "manifest_entry", ",", "project_dir", ",", "build_dir", ")", "end", "end"], "docstring": "The fetcher for this software\n\n This is where we handle all the crazy back-compat on relative_path.\n All fetchers in omnibus 4 use relative_path incorrectly. net_fetcher was\n the only one to use to sensibly, and even then only if fetch_dir was\n Config.source_dir and the source was an archive. Therefore, to not break\n everyone ever, we will still pass project_dir for all other fetchers.\n There is still one issue where other omnibus software (such as the\n appbundler dsl) currently assume that fetch_dir the same as source_dir.\n Therefore, we make one extra concession - when relative_path is set in a\n software definition to be the same as name (a very common scenario), we\n land the source into the fetch directory instead of project_dir. This\n is to avoid fiddling with the appbundler dsl until it gets sorted out.\n\n @return [Fetcher]", "docstring_tokens": ["The", "fetcher", "for", "this", "software"], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/software.rb#L1024-L1031", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/software.rb", "func_name": "Omnibus.Software.shasum", "original_string": "def shasum\n @shasum ||= begin\n digest = Digest::SHA256.new\n\n update_with_string(digest, project.shasum)\n update_with_string(digest, builder.shasum)\n update_with_string(digest, name)\n update_with_string(digest, version_for_cache)\n update_with_string(digest, FFI_Yajl::Encoder.encode(overrides))\n\n if filepath && File.exist?(filepath)\n update_with_file_contents(digest, filepath)\n else\n update_with_string(digest, \"\")\n end\n\n digest.hexdigest\n end\n end", "language": "ruby", "code": "def shasum\n @shasum ||= begin\n digest = Digest::SHA256.new\n\n update_with_string(digest, project.shasum)\n update_with_string(digest, builder.shasum)\n update_with_string(digest, name)\n update_with_string(digest, version_for_cache)\n update_with_string(digest, FFI_Yajl::Encoder.encode(overrides))\n\n if filepath && File.exist?(filepath)\n update_with_file_contents(digest, filepath)\n else\n update_with_string(digest, \"\")\n end\n\n digest.hexdigest\n end\n end", "code_tokens": ["def", "shasum", "@shasum", "||=", "begin", "digest", "=", "Digest", "::", "SHA256", ".", "new", "update_with_string", "(", "digest", ",", "project", ".", "shasum", ")", "update_with_string", "(", "digest", ",", "builder", ".", "shasum", ")", "update_with_string", "(", "digest", ",", "name", ")", "update_with_string", "(", "digest", ",", "version_for_cache", ")", "update_with_string", "(", "digest", ",", "FFI_Yajl", "::", "Encoder", ".", "encode", "(", "overrides", ")", ")", "if", "filepath", "&&", "File", ".", "exist?", "(", "filepath", ")", "update_with_file_contents", "(", "digest", ",", "filepath", ")", "else", "update_with_string", "(", "digest", ",", "\"\"", ")", "end", "digest", ".", "hexdigest", "end", "end"], "docstring": "The unique SHA256 for this sofware definition.\n\n A software is defined by its parent project's shasum, its own name, its\n version_for_cache, and any overrides (as JSON). Additionally, if provided,\n the actual file contents are included in the SHA to ensure uniqueness.\n\n @return [String]", "docstring_tokens": ["The", "unique", "SHA256", "for", "this", "sofware", "definition", "."], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/software.rb#L1126-L1144", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/software.rb", "func_name": "Omnibus.Software.canonicalize_source", "original_string": "def canonicalize_source(source)\n if source.is_a?(Hash) && source[:github]\n source = source.dup\n source[:git] = \"https://github.com/#{source[:github]}.git\"\n source.delete(:github)\n end\n source\n end", "language": "ruby", "code": "def canonicalize_source(source)\n if source.is_a?(Hash) && source[:github]\n source = source.dup\n source[:git] = \"https://github.com/#{source[:github]}.git\"\n source.delete(:github)\n end\n source\n end", "code_tokens": ["def", "canonicalize_source", "(", "source", ")", "if", "source", ".", "is_a?", "(", "Hash", ")", "&&", "source", "[", ":github", "]", "source", "=", "source", ".", "dup", "source", "[", ":git", "]", "=", "\"https://github.com/#{source[:github]}.git\"", "source", ".", "delete", "(", ":github", ")", "end", "source", "end"], "docstring": "Transform github -> git in source", "docstring_tokens": ["Transform", "github", "-", ">", "git", "in", "source"], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/software.rb#L1175-L1182", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/packagers/makeself.rb", "func_name": "Omnibus.Packager::Makeself.write_makeselfinst", "original_string": "def write_makeselfinst\n makeselfinst_staging_path = File.join(staging_dir, \"makeselfinst\")\n render_template(resource_path(\"makeselfinst.erb\"),\n destination: makeselfinst_staging_path,\n variables: {\n install_dir: project.install_dir,\n }\n )\n FileUtils.chmod(0755, makeselfinst_staging_path)\n end", "language": "ruby", "code": "def write_makeselfinst\n makeselfinst_staging_path = File.join(staging_dir, \"makeselfinst\")\n render_template(resource_path(\"makeselfinst.erb\"),\n destination: makeselfinst_staging_path,\n variables: {\n install_dir: project.install_dir,\n }\n )\n FileUtils.chmod(0755, makeselfinst_staging_path)\n end", "code_tokens": ["def", "write_makeselfinst", "makeselfinst_staging_path", "=", "File", ".", "join", "(", "staging_dir", ",", "\"makeselfinst\"", ")", "render_template", "(", "resource_path", "(", "\"makeselfinst.erb\"", ")", ",", "destination", ":", "makeselfinst_staging_path", ",", "variables", ":", "{", "install_dir", ":", "project", ".", "install_dir", ",", "}", ")", "FileUtils", ".", "chmod", "(", "0755", ",", "makeselfinst_staging_path", ")", "end"], "docstring": "Render a makeselfinst in the staging directory using the supplied ERB\n template. This file will be used to move the contents of the self-\n extracting archive into place following extraction.\n\n @return [void]", "docstring_tokens": ["Render", "a", "makeselfinst", "in", "the", "staging", "directory", "using", "the", "supplied", "ERB", "template", ".", "This", "file", "will", "be", "used", "to", "move", "the", "contents", "of", "the", "self", "-", "extracting", "archive", "into", "place", "following", "extraction", "."], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/packagers/makeself.rb#L78-L87", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/git_cache.rb", "func_name": "Omnibus.GitCache.create_cache_path", "original_string": "def create_cache_path\n if File.directory?(cache_path)\n false\n else\n create_directory(File.dirname(cache_path))\n git_cmd(\"init -q\")\n # On windows, git is very picky about single vs double quotes\n git_cmd(\"config --local user.name \\\"Omnibus Git Cache\\\"\")\n git_cmd(\"config --local user.email \\\"omnibus@localhost\\\"\")\n true\n end\n end", "language": "ruby", "code": "def create_cache_path\n if File.directory?(cache_path)\n false\n else\n create_directory(File.dirname(cache_path))\n git_cmd(\"init -q\")\n # On windows, git is very picky about single vs double quotes\n git_cmd(\"config --local user.name \\\"Omnibus Git Cache\\\"\")\n git_cmd(\"config --local user.email \\\"omnibus@localhost\\\"\")\n true\n end\n end", "code_tokens": ["def", "create_cache_path", "if", "File", ".", "directory?", "(", "cache_path", ")", "false", "else", "create_directory", "(", "File", ".", "dirname", "(", "cache_path", ")", ")", "git_cmd", "(", "\"init -q\"", ")", "# On windows, git is very picky about single vs double quotes", "git_cmd", "(", "\"config --local user.name \\\"Omnibus Git Cache\\\"\"", ")", "git_cmd", "(", "\"config --local user.email \\\"omnibus@localhost\\\"\"", ")", "true", "end", "end"], "docstring": "Creates the full path if it does not exist already.\n\n @return [true, false]\n true if the path was created, false otherwise", "docstring_tokens": ["Creates", "the", "full", "path", "if", "it", "does", "not", "exist", "already", "."], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/git_cache.rb#L73-L84", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/git_cache.rb", "func_name": "Omnibus.GitCache.tag", "original_string": "def tag\n return @tag if @tag\n\n log.internal(log_key) { \"Calculating tag\" }\n\n # Accumulate an array of all the software projects that come before\n # the name and version we are tagging. So if you have\n #\n # build_order = [ 1, 2, 3, 4, 5 ]\n #\n # And we are tagging 3, you would get dep_list = [ 1, 2 ]\n dep_list = software.project.library.build_order.take_while do |dep|\n if dep.name == software.name && dep.version == software.version\n false\n else\n true\n end\n end\n\n log.internal(log_key) { \"dep_list: #{dep_list.map(&:name).inspect}\" }\n\n # This is the list of all the unqiue shasums of all the software build\n # dependencies, including the on currently being acted upon.\n shasums = [dep_list.map(&:shasum), software.shasum].flatten\n suffix = Digest::SHA256.hexdigest(shasums.join(\"|\"))\n @tag = \"#{software.name}-#{suffix}-#{SERIAL_NUMBER}\"\n\n log.internal(log_key) { \"tag: #{@tag}\" }\n\n @tag\n end", "language": "ruby", "code": "def tag\n return @tag if @tag\n\n log.internal(log_key) { \"Calculating tag\" }\n\n # Accumulate an array of all the software projects that come before\n # the name and version we are tagging. So if you have\n #\n # build_order = [ 1, 2, 3, 4, 5 ]\n #\n # And we are tagging 3, you would get dep_list = [ 1, 2 ]\n dep_list = software.project.library.build_order.take_while do |dep|\n if dep.name == software.name && dep.version == software.version\n false\n else\n true\n end\n end\n\n log.internal(log_key) { \"dep_list: #{dep_list.map(&:name).inspect}\" }\n\n # This is the list of all the unqiue shasums of all the software build\n # dependencies, including the on currently being acted upon.\n shasums = [dep_list.map(&:shasum), software.shasum].flatten\n suffix = Digest::SHA256.hexdigest(shasums.join(\"|\"))\n @tag = \"#{software.name}-#{suffix}-#{SERIAL_NUMBER}\"\n\n log.internal(log_key) { \"tag: #{@tag}\" }\n\n @tag\n end", "code_tokens": ["def", "tag", "return", "@tag", "if", "@tag", "log", ".", "internal", "(", "log_key", ")", "{", "\"Calculating tag\"", "}", "# Accumulate an array of all the software projects that come before", "# the name and version we are tagging. So if you have", "#", "# build_order = [ 1, 2, 3, 4, 5 ]", "#", "# And we are tagging 3, you would get dep_list = [ 1, 2 ]", "dep_list", "=", "software", ".", "project", ".", "library", ".", "build_order", ".", "take_while", "do", "|", "dep", "|", "if", "dep", ".", "name", "==", "software", ".", "name", "&&", "dep", ".", "version", "==", "software", ".", "version", "false", "else", "true", "end", "end", "log", ".", "internal", "(", "log_key", ")", "{", "\"dep_list: #{dep_list.map(&:name).inspect}\"", "}", "# This is the list of all the unqiue shasums of all the software build", "# dependencies, including the on currently being acted upon.", "shasums", "=", "[", "dep_list", ".", "map", "(", ":shasum", ")", ",", "software", ".", "shasum", "]", ".", "flatten", "suffix", "=", "Digest", "::", "SHA256", ".", "hexdigest", "(", "shasums", ".", "join", "(", "\"|\"", ")", ")", "@tag", "=", "\"#{software.name}-#{suffix}-#{SERIAL_NUMBER}\"", "log", ".", "internal", "(", "log_key", ")", "{", "\"tag: #{@tag}\"", "}", "@tag", "end"], "docstring": "Computes the tag for this cache entry.\n\n @return [String]", "docstring_tokens": ["Computes", "the", "tag", "for", "this", "cache", "entry", "."], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/git_cache.rb#L91-L121", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/git_cache.rb", "func_name": "Omnibus.GitCache.incremental", "original_string": "def incremental\n log.internal(log_key) { \"Performing incremental cache\" }\n\n create_cache_path\n remove_git_dirs\n\n git_cmd(\"add -A -f\")\n\n begin\n git_cmd(%Q{commit -q -m \"Backup of #{tag}\"})\n rescue CommandFailed => e\n raise unless e.message.include?(\"nothing to commit\")\n end\n\n git_cmd(%Q{tag -f \"#{tag}\"})\n end", "language": "ruby", "code": "def incremental\n log.internal(log_key) { \"Performing incremental cache\" }\n\n create_cache_path\n remove_git_dirs\n\n git_cmd(\"add -A -f\")\n\n begin\n git_cmd(%Q{commit -q -m \"Backup of #{tag}\"})\n rescue CommandFailed => e\n raise unless e.message.include?(\"nothing to commit\")\n end\n\n git_cmd(%Q{tag -f \"#{tag}\"})\n end", "code_tokens": ["def", "incremental", "log", ".", "internal", "(", "log_key", ")", "{", "\"Performing incremental cache\"", "}", "create_cache_path", "remove_git_dirs", "git_cmd", "(", "\"add -A -f\"", ")", "begin", "git_cmd", "(", "%Q{commit -q -m \"Backup of #{tag}\"}", ")", "rescue", "CommandFailed", "=>", "e", "raise", "unless", "e", ".", "message", ".", "include?", "(", "\"nothing to commit\"", ")", "end", "git_cmd", "(", "%Q{tag -f \"#{tag}\"}", ")", "end"], "docstring": "Create an incremental install path cache for the software step", "docstring_tokens": ["Create", "an", "incremental", "install", "path", "cache", "for", "the", "software", "step"], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/git_cache.rb#L124-L139", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/git_cache.rb", "func_name": "Omnibus.GitCache.remove_git_dirs", "original_string": "def remove_git_dirs\n log.internal(log_key) { \"Removing git directories\" }\n\n Dir.glob(\"#{install_dir}/**/{,.*}/config\").reject do |path|\n REQUIRED_GIT_FILES.any? do |required_file|\n !File.exist?(File.join(File.dirname(path), required_file))\n end\n end.each do |path|\n log.internal(log_key) { \"Removing git dir `#{path}'\" }\n FileUtils.rm_rf(File.dirname(path))\n end\n\n true\n end", "language": "ruby", "code": "def remove_git_dirs\n log.internal(log_key) { \"Removing git directories\" }\n\n Dir.glob(\"#{install_dir}/**/{,.*}/config\").reject do |path|\n REQUIRED_GIT_FILES.any? do |required_file|\n !File.exist?(File.join(File.dirname(path), required_file))\n end\n end.each do |path|\n log.internal(log_key) { \"Removing git dir `#{path}'\" }\n FileUtils.rm_rf(File.dirname(path))\n end\n\n true\n end", "code_tokens": ["def", "remove_git_dirs", "log", ".", "internal", "(", "log_key", ")", "{", "\"Removing git directories\"", "}", "Dir", ".", "glob", "(", "\"#{install_dir}/**/{,.*}/config\"", ")", ".", "reject", "do", "|", "path", "|", "REQUIRED_GIT_FILES", ".", "any?", "do", "|", "required_file", "|", "!", "File", ".", "exist?", "(", "File", ".", "join", "(", "File", ".", "dirname", "(", "path", ")", ",", "required_file", ")", ")", "end", "end", ".", "each", "do", "|", "path", "|", "log", ".", "internal", "(", "log_key", ")", "{", "\"Removing git dir `#{path}'\"", "}", "FileUtils", ".", "rm_rf", "(", "File", ".", "dirname", "(", "path", ")", ")", "end", "true", "end"], "docstring": "Git caching will attempt to version embedded git directories, partially\n versioning them. This causes failures on subsequent runs. This method\n will find git directories and remove them to prevent those errors.\n\n @return [true]", "docstring_tokens": ["Git", "caching", "will", "attempt", "to", "version", "embedded", "git", "directories", "partially", "versioning", "them", ".", "This", "causes", "failures", "on", "subsequent", "runs", ".", "This", "method", "will", "find", "git", "directories", "and", "remove", "them", "to", "prevent", "those", "errors", "."], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/git_cache.rb#L172-L185", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/packagers/appx.rb", "func_name": "Omnibus.Packager::APPX.write_manifest_file", "original_string": "def write_manifest_file\n render_template(resource_path(\"AppxManifest.xml.erb\"),\n destination: \"#{windows_safe_path(project.install_dir)}/AppxManifest.xml\",\n variables: {\n name: project.package_name,\n friendly_name: project.friendly_name,\n version: windows_package_version,\n maintainer: project.maintainer,\n certificate_subject: certificate_subject.gsub('\"', \""\"),\n }\n )\n end", "language": "ruby", "code": "def write_manifest_file\n render_template(resource_path(\"AppxManifest.xml.erb\"),\n destination: \"#{windows_safe_path(project.install_dir)}/AppxManifest.xml\",\n variables: {\n name: project.package_name,\n friendly_name: project.friendly_name,\n version: windows_package_version,\n maintainer: project.maintainer,\n certificate_subject: certificate_subject.gsub('\"', \""\"),\n }\n )\n end", "code_tokens": ["def", "write_manifest_file", "render_template", "(", "resource_path", "(", "\"AppxManifest.xml.erb\"", ")", ",", "destination", ":", "\"#{windows_safe_path(project.install_dir)}/AppxManifest.xml\"", ",", "variables", ":", "{", "name", ":", "project", ".", "package_name", ",", "friendly_name", ":", "project", ".", "friendly_name", ",", "version", ":", "windows_package_version", ",", "maintainer", ":", "project", ".", "maintainer", ",", "certificate_subject", ":", "certificate_subject", ".", "gsub", "(", "'\"'", ",", "\""\"", ")", ",", "}", ")", "end"], "docstring": "Write the manifest file into the staging directory.\n\n @return [void]", "docstring_tokens": ["Write", "the", "manifest", "file", "into", "the", "staging", "directory", "."], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/packagers/appx.rb#L63-L74", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/util.rb", "func_name": "Omnibus.Util.shellout", "original_string": "def shellout(*args)\n options = args.last.kind_of?(Hash) ? args.pop : {}\n options = SHELLOUT_OPTIONS.merge(options)\n\n command_string = args.join(\" \")\n in_msys = options.delete(:in_msys_bash) && ENV[\"MSYSTEM\"]\n # Mixlib will handle escaping characters for cmd but our command might\n # contain '. For now, assume that won't happen because I don't know\n # whether this command is going to be played via cmd or through\n # ProcessCreate.\n command_string = \"bash -c \\'#{command_string}\\'\" if in_msys\n\n # Grab the log_level\n log_level = options.delete(:log_level)\n\n # Set the live stream if one was not given\n options[:live_stream] ||= log.live_stream(:internal)\n\n # Since Mixlib::ShellOut supports :environment and :env, we want to\n # standardize here\n if options[:env]\n options[:environment] = options.fetch(:environment, {}).merge(options[:env])\n end\n\n # Log any environment options given\n unless options[:environment].empty?\n log.public_send(log_level, log_key) { \"Environment:\" }\n options[:environment].sort.each do |key, value|\n log.public_send(log_level, log_key) { \" #{key}=#{value.inspect}\" }\n end\n end\n\n # Log the actual command\n log.public_send(log_level, log_key) { \"$ #{command_string}\" }\n\n cmd = Mixlib::ShellOut.new(command_string, options)\n cmd.environment[\"HOME\"] = \"/tmp\" unless ENV[\"HOME\"]\n cmd.run_command\n cmd\n end", "language": "ruby", "code": "def shellout(*args)\n options = args.last.kind_of?(Hash) ? args.pop : {}\n options = SHELLOUT_OPTIONS.merge(options)\n\n command_string = args.join(\" \")\n in_msys = options.delete(:in_msys_bash) && ENV[\"MSYSTEM\"]\n # Mixlib will handle escaping characters for cmd but our command might\n # contain '. For now, assume that won't happen because I don't know\n # whether this command is going to be played via cmd or through\n # ProcessCreate.\n command_string = \"bash -c \\'#{command_string}\\'\" if in_msys\n\n # Grab the log_level\n log_level = options.delete(:log_level)\n\n # Set the live stream if one was not given\n options[:live_stream] ||= log.live_stream(:internal)\n\n # Since Mixlib::ShellOut supports :environment and :env, we want to\n # standardize here\n if options[:env]\n options[:environment] = options.fetch(:environment, {}).merge(options[:env])\n end\n\n # Log any environment options given\n unless options[:environment].empty?\n log.public_send(log_level, log_key) { \"Environment:\" }\n options[:environment].sort.each do |key, value|\n log.public_send(log_level, log_key) { \" #{key}=#{value.inspect}\" }\n end\n end\n\n # Log the actual command\n log.public_send(log_level, log_key) { \"$ #{command_string}\" }\n\n cmd = Mixlib::ShellOut.new(command_string, options)\n cmd.environment[\"HOME\"] = \"/tmp\" unless ENV[\"HOME\"]\n cmd.run_command\n cmd\n end", "code_tokens": ["def", "shellout", "(", "*", "args", ")", "options", "=", "args", ".", "last", ".", "kind_of?", "(", "Hash", ")", "?", "args", ".", "pop", ":", "{", "}", "options", "=", "SHELLOUT_OPTIONS", ".", "merge", "(", "options", ")", "command_string", "=", "args", ".", "join", "(", "\" \"", ")", "in_msys", "=", "options", ".", "delete", "(", ":in_msys_bash", ")", "&&", "ENV", "[", "\"MSYSTEM\"", "]", "# Mixlib will handle escaping characters for cmd but our command might", "# contain '. For now, assume that won't happen because I don't know", "# whether this command is going to be played via cmd or through", "# ProcessCreate.", "command_string", "=", "\"bash -c \\'#{command_string}\\'\"", "if", "in_msys", "# Grab the log_level", "log_level", "=", "options", ".", "delete", "(", ":log_level", ")", "# Set the live stream if one was not given", "options", "[", ":live_stream", "]", "||=", "log", ".", "live_stream", "(", ":internal", ")", "# Since Mixlib::ShellOut supports :environment and :env, we want to", "# standardize here", "if", "options", "[", ":env", "]", "options", "[", ":environment", "]", "=", "options", ".", "fetch", "(", ":environment", ",", "{", "}", ")", ".", "merge", "(", "options", "[", ":env", "]", ")", "end", "# Log any environment options given", "unless", "options", "[", ":environment", "]", ".", "empty?", "log", ".", "public_send", "(", "log_level", ",", "log_key", ")", "{", "\"Environment:\"", "}", "options", "[", ":environment", "]", ".", "sort", ".", "each", "do", "|", "key", ",", "value", "|", "log", ".", "public_send", "(", "log_level", ",", "log_key", ")", "{", "\" #{key}=#{value.inspect}\"", "}", "end", "end", "# Log the actual command", "log", ".", "public_send", "(", "log_level", ",", "log_key", ")", "{", "\"$ #{command_string}\"", "}", "cmd", "=", "Mixlib", "::", "ShellOut", ".", "new", "(", "command_string", ",", "options", ")", "cmd", ".", "environment", "[", "\"HOME\"", "]", "=", "\"/tmp\"", "unless", "ENV", "[", "\"HOME\"", "]", "cmd", ".", "run_command", "cmd", "end"], "docstring": "Shells out and runs +command+.\n\n @overload shellout(command, options = {})\n @param command [String]\n @param options [Hash] the options passed to the initializer of the\n +Mixlib::ShellOut+ instance.\n @overload shellout(command_fragments, options = {})\n @param command [Array] command argv as individual strings\n @param options [Hash] the options passed to the initializer of the\n +Mixlib::ShellOut+ instance.\n @return [Mixlib::ShellOut] the underlying +Mixlib::ShellOut+ instance\n which has +stdout+, +stderr+, +status+, and +exitstatus+\n populated with results of the command.", "docstring_tokens": ["Shells", "out", "and", "runs", "+", "command", "+", "."], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/util.rb#L82-L121", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/util.rb", "func_name": "Omnibus.Util.shellout!", "original_string": "def shellout!(*args)\n cmd = shellout(*args)\n cmd.error!\n cmd\n rescue Mixlib::ShellOut::ShellCommandFailed\n raise CommandFailed.new(cmd)\n rescue Mixlib::ShellOut::CommandTimeout\n raise CommandTimeout.new(cmd)\n end", "language": "ruby", "code": "def shellout!(*args)\n cmd = shellout(*args)\n cmd.error!\n cmd\n rescue Mixlib::ShellOut::ShellCommandFailed\n raise CommandFailed.new(cmd)\n rescue Mixlib::ShellOut::CommandTimeout\n raise CommandTimeout.new(cmd)\n end", "code_tokens": ["def", "shellout!", "(", "*", "args", ")", "cmd", "=", "shellout", "(", "args", ")", "cmd", ".", "error!", "cmd", "rescue", "Mixlib", "::", "ShellOut", "::", "ShellCommandFailed", "raise", "CommandFailed", ".", "new", "(", "cmd", ")", "rescue", "Mixlib", "::", "ShellOut", "::", "CommandTimeout", "raise", "CommandTimeout", ".", "new", "(", "cmd", ")", "end"], "docstring": "Similar to +shellout+ method except it raises an exception if the\n command fails.\n\n @see #shellout\n\n @raise [CommandFailed]\n if +exitstatus+ is not in the list of +valid_exit_codes+\n @raise [CommandTimeout]\n if execution time exceeds +timeout+", "docstring_tokens": ["Similar", "to", "+", "shellout", "+", "method", "except", "it", "raises", "an", "exception", "if", "the", "command", "fails", "."], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/util.rb#L134-L142", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/util.rb", "func_name": "Omnibus.Util.retry_block", "original_string": "def retry_block(logstr, retried_exceptions = [], retries = Omnibus::Config.fetcher_retries, &block)\n yield\n rescue Exception => e\n raise e unless retried_exceptions.any? { |eclass| e.is_a?(eclass) }\n if retries != 0\n log.info(log_key) { \"Retrying failed #{logstr} due to #{e} (#{retries} retries left)...\" }\n retries -= 1\n retry\n else\n log.error(log_key) { \"#{logstr} failed - #{e.class}!\" }\n raise\n end\n end", "language": "ruby", "code": "def retry_block(logstr, retried_exceptions = [], retries = Omnibus::Config.fetcher_retries, &block)\n yield\n rescue Exception => e\n raise e unless retried_exceptions.any? { |eclass| e.is_a?(eclass) }\n if retries != 0\n log.info(log_key) { \"Retrying failed #{logstr} due to #{e} (#{retries} retries left)...\" }\n retries -= 1\n retry\n else\n log.error(log_key) { \"#{logstr} failed - #{e.class}!\" }\n raise\n end\n end", "code_tokens": ["def", "retry_block", "(", "logstr", ",", "retried_exceptions", "=", "[", "]", ",", "retries", "=", "Omnibus", "::", "Config", ".", "fetcher_retries", ",", "&", "block", ")", "yield", "rescue", "Exception", "=>", "e", "raise", "e", "unless", "retried_exceptions", ".", "any?", "{", "|", "eclass", "|", "e", ".", "is_a?", "(", "eclass", ")", "}", "if", "retries", "!=", "0", "log", ".", "info", "(", "log_key", ")", "{", "\"Retrying failed #{logstr} due to #{e} (#{retries} retries left)...\"", "}", "retries", "-=", "1", "retry", "else", "log", ".", "error", "(", "log_key", ")", "{", "\"#{logstr} failed - #{e.class}!\"", "}", "raise", "end", "end"], "docstring": "Retry the given block if a retriable exception is\n raised. Returns the value of the block call if successful.\n\n @param [String] logstr\n Description of the action being retried. Used in log output.\n\n @param [Array] retried_exceptions\n List of exceptions to retry. Any other exceptions are raisesd.\n\n @param [Integer] retries\n Number of times to retry the given block.", "docstring_tokens": ["Retry", "the", "given", "block", "if", "a", "retriable", "exception", "is", "raised", ".", "Returns", "the", "value", "of", "the", "block", "call", "if", "successful", "."], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/util.rb#L157-L169", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/util.rb", "func_name": "Omnibus.Util.windows_safe_path", "original_string": "def windows_safe_path(*pieces)\n path = File.join(*pieces)\n\n if File::ALT_SEPARATOR\n path.gsub(File::SEPARATOR, File::ALT_SEPARATOR)\n else\n path\n end\n end", "language": "ruby", "code": "def windows_safe_path(*pieces)\n path = File.join(*pieces)\n\n if File::ALT_SEPARATOR\n path.gsub(File::SEPARATOR, File::ALT_SEPARATOR)\n else\n path\n end\n end", "code_tokens": ["def", "windows_safe_path", "(", "*", "pieces", ")", "path", "=", "File", ".", "join", "(", "pieces", ")", "if", "File", "::", "ALT_SEPARATOR", "path", ".", "gsub", "(", "File", "::", "SEPARATOR", ",", "File", "::", "ALT_SEPARATOR", ")", "else", "path", "end", "end"], "docstring": "Convert the given path to be appropiate for shelling out on Windows.\n\n @param [String, Array] pieces\n the pieces of the path to join and fix\n @return [String]\n the path with applied changes", "docstring_tokens": ["Convert", "the", "given", "path", "to", "be", "appropiate", "for", "shelling", "out", "on", "Windows", "."], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/util.rb#L179-L187", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/util.rb", "func_name": "Omnibus.Util.compiler_safe_path", "original_string": "def compiler_safe_path(*pieces)\n path = File.join(*pieces)\n path = path.sub(/^([A-Za-z]):\\//, \"/\\\\1/\") if ENV[\"MSYSTEM\"]\n path\n end", "language": "ruby", "code": "def compiler_safe_path(*pieces)\n path = File.join(*pieces)\n path = path.sub(/^([A-Za-z]):\\//, \"/\\\\1/\") if ENV[\"MSYSTEM\"]\n path\n end", "code_tokens": ["def", "compiler_safe_path", "(", "*", "pieces", ")", "path", "=", "File", ".", "join", "(", "pieces", ")", "path", "=", "path", ".", "sub", "(", "/", "\\/", "/", ",", "\"/\\\\1/\"", ")", "if", "ENV", "[", "\"MSYSTEM\"", "]", "path", "end"], "docstring": "Convert the given path to be appropriate for usage with the given compiler\n\n @param [String, Array] pieces\n the pieces of the path to join and fix\n @return [String]\n the path with applied changes", "docstring_tokens": ["Convert", "the", "given", "path", "to", "be", "appropriate", "for", "usage", "with", "the", "given", "compiler"], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/util.rb#L197-L201", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/util.rb", "func_name": "Omnibus.Util.create_directory", "original_string": "def create_directory(*paths)\n path = File.join(*paths)\n log.debug(log_key) { \"Creating directory `#{path}'\" }\n FileUtils.mkdir_p(path)\n path\n end", "language": "ruby", "code": "def create_directory(*paths)\n path = File.join(*paths)\n log.debug(log_key) { \"Creating directory `#{path}'\" }\n FileUtils.mkdir_p(path)\n path\n end", "code_tokens": ["def", "create_directory", "(", "*", "paths", ")", "path", "=", "File", ".", "join", "(", "paths", ")", "log", ".", "debug", "(", "log_key", ")", "{", "\"Creating directory `#{path}'\"", "}", "FileUtils", ".", "mkdir_p", "(", "path", ")", "path", "end"], "docstring": "Create a directory at the given +path+.\n\n @param [String, Array] paths\n the path or list of paths to join to create\n\n @return [String]\n the path to the created directory", "docstring_tokens": ["Create", "a", "directory", "at", "the", "given", "+", "path", "+", "."], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/util.rb#L212-L217", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/util.rb", "func_name": "Omnibus.Util.remove_directory", "original_string": "def remove_directory(*paths)\n path = File.join(*paths)\n log.debug(log_key) { \"Remove directory `#{path}'\" }\n FileUtils.rm_rf(path)\n path\n end", "language": "ruby", "code": "def remove_directory(*paths)\n path = File.join(*paths)\n log.debug(log_key) { \"Remove directory `#{path}'\" }\n FileUtils.rm_rf(path)\n path\n end", "code_tokens": ["def", "remove_directory", "(", "*", "paths", ")", "path", "=", "File", ".", "join", "(", "paths", ")", "log", ".", "debug", "(", "log_key", ")", "{", "\"Remove directory `#{path}'\"", "}", "FileUtils", ".", "rm_rf", "(", "path", ")", "path", "end"], "docstring": "Remove the directory at the given +path+.\n\n @param [String, Array] paths\n the path or list of paths to join to delete\n\n @return [String]\n the path to the removed directory", "docstring_tokens": ["Remove", "the", "directory", "at", "the", "given", "+", "path", "+", "."], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/util.rb#L228-L233", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/util.rb", "func_name": "Omnibus.Util.copy_file", "original_string": "def copy_file(source, destination)\n log.debug(log_key) { \"Copying `#{source}' to `#{destination}'\" }\n FileUtils.cp(source, destination)\n destination\n end", "language": "ruby", "code": "def copy_file(source, destination)\n log.debug(log_key) { \"Copying `#{source}' to `#{destination}'\" }\n FileUtils.cp(source, destination)\n destination\n end", "code_tokens": ["def", "copy_file", "(", "source", ",", "destination", ")", "log", ".", "debug", "(", "log_key", ")", "{", "\"Copying `#{source}' to `#{destination}'\"", "}", "FileUtils", ".", "cp", "(", "source", ",", "destination", ")", "destination", "end"], "docstring": "Copy the +source+ file to the +destination+.\n\n @param [String] source\n @param [String] destination\n\n @return [String]\n the destination path", "docstring_tokens": ["Copy", "the", "+", "source", "+", "file", "to", "the", "+", "destination", "+", "."], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/util.rb#L244-L248", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/util.rb", "func_name": "Omnibus.Util.remove_file", "original_string": "def remove_file(*paths)\n path = File.join(*paths)\n log.debug(log_key) { \"Removing file `#{path}'\" }\n FileUtils.rm_f(path)\n path\n end", "language": "ruby", "code": "def remove_file(*paths)\n path = File.join(*paths)\n log.debug(log_key) { \"Removing file `#{path}'\" }\n FileUtils.rm_f(path)\n path\n end", "code_tokens": ["def", "remove_file", "(", "*", "paths", ")", "path", "=", "File", ".", "join", "(", "paths", ")", "log", ".", "debug", "(", "log_key", ")", "{", "\"Removing file `#{path}'\"", "}", "FileUtils", ".", "rm_f", "(", "path", ")", "path", "end"], "docstring": "Remove the file at the given path.\n\n @param [String, Array] paths\n the path or list of paths to join to delete\n\n @return [String]\n the path to the removed file", "docstring_tokens": ["Remove", "the", "file", "at", "the", "given", "path", "."], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/util.rb#L259-L264", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/util.rb", "func_name": "Omnibus.Util.create_file", "original_string": "def create_file(*paths, &block)\n path = File.join(*paths)\n log.debug(log_key) { \"Creating file `#{path}'\" }\n\n FileUtils.mkdir_p(File.dirname(path))\n\n if block\n File.open(path, \"wb\") { |f| f.write(yield) }\n else\n FileUtils.touch(path)\n end\n\n path\n end", "language": "ruby", "code": "def create_file(*paths, &block)\n path = File.join(*paths)\n log.debug(log_key) { \"Creating file `#{path}'\" }\n\n FileUtils.mkdir_p(File.dirname(path))\n\n if block\n File.open(path, \"wb\") { |f| f.write(yield) }\n else\n FileUtils.touch(path)\n end\n\n path\n end", "code_tokens": ["def", "create_file", "(", "*", "paths", ",", "&", "block", ")", "path", "=", "File", ".", "join", "(", "paths", ")", "log", ".", "debug", "(", "log_key", ")", "{", "\"Creating file `#{path}'\"", "}", "FileUtils", ".", "mkdir_p", "(", "File", ".", "dirname", "(", "path", ")", ")", "if", "block", "File", ".", "open", "(", "path", ",", "\"wb\"", ")", "{", "|", "f", "|", "f", ".", "write", "(", "yield", ")", "}", "else", "FileUtils", ".", "touch", "(", "path", ")", "end", "path", "end"], "docstring": "Create a file at the given path. If a block is given, the contents of the\n block are written to the file. If the block is not given, the file is\n simply \"touched\".\n\n @param [String, Array] paths\n the path or list of paths to join to create\n\n @return [String]\n the path to the created file", "docstring_tokens": ["Create", "a", "file", "at", "the", "given", "path", ".", "If", "a", "block", "is", "given", "the", "contents", "of", "the", "block", "are", "written", "to", "the", "file", ".", "If", "the", "block", "is", "not", "given", "the", "file", "is", "simply", "touched", "."], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/util.rb#L277-L290", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/util.rb", "func_name": "Omnibus.Util.create_link", "original_string": "def create_link(a, b)\n log.debug(log_key) { \"Linking `#{a}' to `#{b}'\" }\n FileUtils.ln_s(a, b)\n end", "language": "ruby", "code": "def create_link(a, b)\n log.debug(log_key) { \"Linking `#{a}' to `#{b}'\" }\n FileUtils.ln_s(a, b)\n end", "code_tokens": ["def", "create_link", "(", "a", ",", "b", ")", "log", ".", "debug", "(", "log_key", ")", "{", "\"Linking `#{a}' to `#{b}'\"", "}", "FileUtils", ".", "ln_s", "(", "a", ",", "b", ")", "end"], "docstring": "Create a symlink from a to b\n\n @param [String] a\n @param [String] b", "docstring_tokens": ["Create", "a", "symlink", "from", "a", "to", "b"], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/util.rb#L298-L301", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/licensing.rb", "func_name": "Omnibus.Licensing.validate_license_info", "original_string": "def validate_license_info\n # First check the project licensing information\n\n # Check existence of licensing information\n if project.license == \"Unspecified\"\n licensing_warning(\"Project '#{project.name}' does not contain licensing information.\")\n end\n\n # Check license file exists\n if project.license != \"Unspecified\" && project.license_file.nil?\n licensing_warning(\"Project '#{project.name}' does not point to a license file.\")\n end\n\n # Check used license is a standard license\n if project.license != \"Unspecified\" && !STANDARD_LICENSES.include?(project.license)\n licensing_info(\"Project '#{project.name}' is using '#{project.license}' which is not one of the standard licenses identified in https://opensource.org/licenses/alphabetical. Consider using one of the standard licenses.\")\n end\n\n # Now let's check the licensing info for software components\n license_map.each do |software_name, license_info|\n # First check if the software specified a license\n if license_info[:license] == \"Unspecified\"\n licensing_warning(\"Software '#{software_name}' does not contain licensing information.\")\n end\n\n # Check if the software specifies any license files\n if license_info[:license] != \"Unspecified\" && license_info[:license_files].empty?\n licensing_warning(\"Software '#{software_name}' does not point to any license files.\")\n end\n\n # Check if the software license is one of the standard licenses\n if license_info[:license] != \"Unspecified\" && !STANDARD_LICENSES.include?(license_info[:license])\n licensing_info(\"Software '#{software_name}' uses license '#{license_info[:license]}' which is not one of the standard licenses identified in https://opensource.org/licenses/alphabetical. Consider using one of the standard licenses.\")\n end\n end\n end", "language": "ruby", "code": "def validate_license_info\n # First check the project licensing information\n\n # Check existence of licensing information\n if project.license == \"Unspecified\"\n licensing_warning(\"Project '#{project.name}' does not contain licensing information.\")\n end\n\n # Check license file exists\n if project.license != \"Unspecified\" && project.license_file.nil?\n licensing_warning(\"Project '#{project.name}' does not point to a license file.\")\n end\n\n # Check used license is a standard license\n if project.license != \"Unspecified\" && !STANDARD_LICENSES.include?(project.license)\n licensing_info(\"Project '#{project.name}' is using '#{project.license}' which is not one of the standard licenses identified in https://opensource.org/licenses/alphabetical. Consider using one of the standard licenses.\")\n end\n\n # Now let's check the licensing info for software components\n license_map.each do |software_name, license_info|\n # First check if the software specified a license\n if license_info[:license] == \"Unspecified\"\n licensing_warning(\"Software '#{software_name}' does not contain licensing information.\")\n end\n\n # Check if the software specifies any license files\n if license_info[:license] != \"Unspecified\" && license_info[:license_files].empty?\n licensing_warning(\"Software '#{software_name}' does not point to any license files.\")\n end\n\n # Check if the software license is one of the standard licenses\n if license_info[:license] != \"Unspecified\" && !STANDARD_LICENSES.include?(license_info[:license])\n licensing_info(\"Software '#{software_name}' uses license '#{license_info[:license]}' which is not one of the standard licenses identified in https://opensource.org/licenses/alphabetical. Consider using one of the standard licenses.\")\n end\n end\n end", "code_tokens": ["def", "validate_license_info", "# First check the project licensing information", "# Check existence of licensing information", "if", "project", ".", "license", "==", "\"Unspecified\"", "licensing_warning", "(", "\"Project '#{project.name}' does not contain licensing information.\"", ")", "end", "# Check license file exists", "if", "project", ".", "license", "!=", "\"Unspecified\"", "&&", "project", ".", "license_file", ".", "nil?", "licensing_warning", "(", "\"Project '#{project.name}' does not point to a license file.\"", ")", "end", "# Check used license is a standard license", "if", "project", ".", "license", "!=", "\"Unspecified\"", "&&", "!", "STANDARD_LICENSES", ".", "include?", "(", "project", ".", "license", ")", "licensing_info", "(", "\"Project '#{project.name}' is using '#{project.license}' which is not one of the standard licenses identified in https://opensource.org/licenses/alphabetical. Consider using one of the standard licenses.\"", ")", "end", "# Now let's check the licensing info for software components", "license_map", ".", "each", "do", "|", "software_name", ",", "license_info", "|", "# First check if the software specified a license", "if", "license_info", "[", ":license", "]", "==", "\"Unspecified\"", "licensing_warning", "(", "\"Software '#{software_name}' does not contain licensing information.\"", ")", "end", "# Check if the software specifies any license files", "if", "license_info", "[", ":license", "]", "!=", "\"Unspecified\"", "&&", "license_info", "[", ":license_files", "]", ".", "empty?", "licensing_warning", "(", "\"Software '#{software_name}' does not point to any license files.\"", ")", "end", "# Check if the software license is one of the standard licenses", "if", "license_info", "[", ":license", "]", "!=", "\"Unspecified\"", "&&", "!", "STANDARD_LICENSES", ".", "include?", "(", "license_info", "[", ":license", "]", ")", "licensing_info", "(", "\"Software '#{software_name}' uses license '#{license_info[:license]}' which is not one of the standard licenses identified in https://opensource.org/licenses/alphabetical. Consider using one of the standard licenses.\"", ")", "end", "end", "end"], "docstring": "Inspects the licensing information for the project and the included\n software components. Logs the found issues to the log as warning.\n\n @return [void]", "docstring_tokens": ["Inspects", "the", "licensing", "information", "for", "the", "project", "and", "the", "included", "software", "components", ".", "Logs", "the", "found", "issues", "to", "the", "log", "as", "warning", "."], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/licensing.rb#L160-L195", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/licensing.rb", "func_name": "Omnibus.Licensing.project_license_content", "original_string": "def project_license_content\n project.license_file.nil? ? \"\" : IO.read(File.join(Config.project_root, project.license_file))\n end", "language": "ruby", "code": "def project_license_content\n project.license_file.nil? ? \"\" : IO.read(File.join(Config.project_root, project.license_file))\n end", "code_tokens": ["def", "project_license_content", "project", ".", "license_file", ".", "nil?", "?", "\"\"", ":", "IO", ".", "read", "(", "File", ".", "join", "(", "Config", ".", "project_root", ",", "project", ".", "license_file", ")", ")", "end"], "docstring": "Contents of the project's license\n\n @return [String]", "docstring_tokens": ["Contents", "of", "the", "project", "s", "license"], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/licensing.rb#L223-L225", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/licensing.rb", "func_name": "Omnibus.Licensing.license_map", "original_string": "def license_map\n @license_map ||= begin\n map = {}\n\n project.library.each do |component|\n # Some of the components do not bundle any software but contain\n # some logic that we use during the build. These components are\n # covered under the project's license and they do not need specific\n # license files.\n next if component.license == :project_license\n\n map[component.name] = {\n license: component.license,\n license_files: component.license_files,\n version: component.version,\n project_dir: component.project_dir,\n }\n end\n\n map\n end\n end", "language": "ruby", "code": "def license_map\n @license_map ||= begin\n map = {}\n\n project.library.each do |component|\n # Some of the components do not bundle any software but contain\n # some logic that we use during the build. These components are\n # covered under the project's license and they do not need specific\n # license files.\n next if component.license == :project_license\n\n map[component.name] = {\n license: component.license,\n license_files: component.license_files,\n version: component.version,\n project_dir: component.project_dir,\n }\n end\n\n map\n end\n end", "code_tokens": ["def", "license_map", "@license_map", "||=", "begin", "map", "=", "{", "}", "project", ".", "library", ".", "each", "do", "|", "component", "|", "# Some of the components do not bundle any software but contain", "# some logic that we use during the build. These components are", "# covered under the project's license and they do not need specific", "# license files.", "next", "if", "component", ".", "license", "==", ":project_license", "map", "[", "component", ".", "name", "]", "=", "{", "license", ":", "component", ".", "license", ",", "license_files", ":", "component", ".", "license_files", ",", "version", ":", "component", ".", "version", ",", "project_dir", ":", "component", ".", "project_dir", ",", "}", "end", "map", "end", "end"], "docstring": "Map that collects information about the licenses of the softwares\n included in the project.\n\n @example\n {\n ...\n \"python\" => {\n \"license\" => \"Python\",\n \"license_files\" => \"LICENSE\",\n \"version\" => \"2.7.9\",\n \"project_dir\" => \"/var/cache/omnibus/src/python/Python-2.7.9/\"\n },\n ...\n }\n\n @return [Hash]", "docstring_tokens": ["Map", "that", "collects", "information", "about", "the", "licenses", "of", "the", "softwares", "included", "in", "the", "project", "."], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/licensing.rb#L314-L335", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/licensing.rb", "func_name": "Omnibus.Licensing.process_transitive_dependency_licensing_info", "original_string": "def process_transitive_dependency_licensing_info\n Dir.glob(\"#{cache_dir}/*/*-dependency-licenses.json\").each do |license_manifest_path|\n license_manifest_data = FFI_Yajl::Parser.parse(File.read(license_manifest_path))\n project_name = license_manifest_data[\"project_name\"]\n dependency_license_dir = File.dirname(license_manifest_path)\n\n license_manifest_data[\"dependency_managers\"].each do |dep_mgr_name, dependencies|\n dep_license_map[dep_mgr_name] ||= {}\n\n dependencies.each do |dependency|\n # Copy dependency files\n dependency[\"license_files\"].each do |f|\n license_path = File.join(dependency_license_dir, f)\n output_path = File.join(output_dir, f)\n FileUtils.cp(license_path, output_path)\n end\n\n dep_name = dependency[\"name\"]\n dep_version = dependency[\"version\"]\n\n # If we already have this dependency we do not need to add it again.\n if dep_license_map[dep_mgr_name][dep_name] && dep_license_map[dep_mgr_name][dep_name][dep_version]\n dep_license_map[dep_mgr_name][dep_name][dep_version][\"dependency_of\"] << project_name\n else\n dep_license_map[dep_mgr_name][dep_name] ||= {}\n dep_license_map[dep_mgr_name][dep_name][dep_version] = {\n \"license\" => dependency[\"license\"],\n \"license_files\" => dependency[\"license_files\"],\n \"dependency_of\" => [ project_name ],\n }\n end\n end\n end\n end\n\n FileUtils.rm_rf(cache_dir)\n end", "language": "ruby", "code": "def process_transitive_dependency_licensing_info\n Dir.glob(\"#{cache_dir}/*/*-dependency-licenses.json\").each do |license_manifest_path|\n license_manifest_data = FFI_Yajl::Parser.parse(File.read(license_manifest_path))\n project_name = license_manifest_data[\"project_name\"]\n dependency_license_dir = File.dirname(license_manifest_path)\n\n license_manifest_data[\"dependency_managers\"].each do |dep_mgr_name, dependencies|\n dep_license_map[dep_mgr_name] ||= {}\n\n dependencies.each do |dependency|\n # Copy dependency files\n dependency[\"license_files\"].each do |f|\n license_path = File.join(dependency_license_dir, f)\n output_path = File.join(output_dir, f)\n FileUtils.cp(license_path, output_path)\n end\n\n dep_name = dependency[\"name\"]\n dep_version = dependency[\"version\"]\n\n # If we already have this dependency we do not need to add it again.\n if dep_license_map[dep_mgr_name][dep_name] && dep_license_map[dep_mgr_name][dep_name][dep_version]\n dep_license_map[dep_mgr_name][dep_name][dep_version][\"dependency_of\"] << project_name\n else\n dep_license_map[dep_mgr_name][dep_name] ||= {}\n dep_license_map[dep_mgr_name][dep_name][dep_version] = {\n \"license\" => dependency[\"license\"],\n \"license_files\" => dependency[\"license_files\"],\n \"dependency_of\" => [ project_name ],\n }\n end\n end\n end\n end\n\n FileUtils.rm_rf(cache_dir)\n end", "code_tokens": ["def", "process_transitive_dependency_licensing_info", "Dir", ".", "glob", "(", "\"#{cache_dir}/*/*-dependency-licenses.json\"", ")", ".", "each", "do", "|", "license_manifest_path", "|", "license_manifest_data", "=", "FFI_Yajl", "::", "Parser", ".", "parse", "(", "File", ".", "read", "(", "license_manifest_path", ")", ")", "project_name", "=", "license_manifest_data", "[", "\"project_name\"", "]", "dependency_license_dir", "=", "File", ".", "dirname", "(", "license_manifest_path", ")", "license_manifest_data", "[", "\"dependency_managers\"", "]", ".", "each", "do", "|", "dep_mgr_name", ",", "dependencies", "|", "dep_license_map", "[", "dep_mgr_name", "]", "||=", "{", "}", "dependencies", ".", "each", "do", "|", "dependency", "|", "# Copy dependency files", "dependency", "[", "\"license_files\"", "]", ".", "each", "do", "|", "f", "|", "license_path", "=", "File", ".", "join", "(", "dependency_license_dir", ",", "f", ")", "output_path", "=", "File", ".", "join", "(", "output_dir", ",", "f", ")", "FileUtils", ".", "cp", "(", "license_path", ",", "output_path", ")", "end", "dep_name", "=", "dependency", "[", "\"name\"", "]", "dep_version", "=", "dependency", "[", "\"version\"", "]", "# If we already have this dependency we do not need to add it again.", "if", "dep_license_map", "[", "dep_mgr_name", "]", "[", "dep_name", "]", "&&", "dep_license_map", "[", "dep_mgr_name", "]", "[", "dep_name", "]", "[", "dep_version", "]", "dep_license_map", "[", "dep_mgr_name", "]", "[", "dep_name", "]", "[", "dep_version", "]", "[", "\"dependency_of\"", "]", "<<", "project_name", "else", "dep_license_map", "[", "dep_mgr_name", "]", "[", "dep_name", "]", "||=", "{", "}", "dep_license_map", "[", "dep_mgr_name", "]", "[", "dep_name", "]", "[", "dep_version", "]", "=", "{", "\"license\"", "=>", "dependency", "[", "\"license\"", "]", ",", "\"license_files\"", "=>", "dependency", "[", "\"license_files\"", "]", ",", "\"dependency_of\"", "=>", "[", "project_name", "]", ",", "}", "end", "end", "end", "end", "FileUtils", ".", "rm_rf", "(", "cache_dir", ")", "end"], "docstring": "0. Translate all transitive dependency licensing issues into omnibus warnings\n 1. Parse all the licensing information for all software from 'cache_dir'\n 2. Merge and drop the duplicates\n 3. Add these licenses to the main manifest, to be merged with the main\n licensing information from software definitions.", "docstring_tokens": ["0", ".", "Translate", "all", "transitive", "dependency", "licensing", "issues", "into", "omnibus", "warnings", "1", ".", "Parse", "all", "the", "licensing", "information", "for", "all", "software", "from", "cache_dir", "2", ".", "Merge", "and", "drop", "the", "duplicates", "3", ".", "Add", "these", "licenses", "to", "the", "main", "manifest", "to", "be", "merged", "with", "the", "main", "licensing", "information", "from", "software", "definitions", "."], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/licensing.rb#L455-L491", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/licensing.rb", "func_name": "Omnibus.Licensing.collect_licenses_for", "original_string": "def collect_licenses_for(software)\n return nil if software.license == :project_license\n\n software_name = software.name\n license_data = license_map[software_name]\n license_files = license_data[:license_files]\n\n license_files.each do |license_file|\n if license_file\n output_file = license_package_location(software_name, license_file)\n\n if local?(license_file)\n input_file = File.expand_path(license_file, license_data[:project_dir])\n if File.exist?(input_file)\n FileUtils.cp(input_file, output_file)\n File.chmod 0644, output_file unless windows?\n else\n licensing_warning(\"License file '#{input_file}' does not exist for software '#{software_name}'.\")\n # If we got here, we need to fail now so we don't take a git\n # cache snapshot, or else the software build could be restored\n # from cache without fixing the license issue.\n raise_if_warnings_fatal!\n end\n else\n begin\n download_file!(license_file, output_file, enable_progress_bar: false)\n File.chmod 0644, output_file unless windows?\n rescue SocketError,\n Errno::ECONNREFUSED,\n Errno::ECONNRESET,\n Errno::ENETUNREACH,\n Timeout::Error,\n OpenURI::HTTPError,\n OpenSSL::SSL::SSLError\n licensing_warning(\"Can not download license file '#{license_file}' for software '#{software_name}'.\")\n # If we got here, we need to fail now so we don't take a git\n # cache snapshot, or else the software build could be restored\n # from cache without fixing the license issue.\n raise_if_warnings_fatal!\n end\n end\n end\n end\n end", "language": "ruby", "code": "def collect_licenses_for(software)\n return nil if software.license == :project_license\n\n software_name = software.name\n license_data = license_map[software_name]\n license_files = license_data[:license_files]\n\n license_files.each do |license_file|\n if license_file\n output_file = license_package_location(software_name, license_file)\n\n if local?(license_file)\n input_file = File.expand_path(license_file, license_data[:project_dir])\n if File.exist?(input_file)\n FileUtils.cp(input_file, output_file)\n File.chmod 0644, output_file unless windows?\n else\n licensing_warning(\"License file '#{input_file}' does not exist for software '#{software_name}'.\")\n # If we got here, we need to fail now so we don't take a git\n # cache snapshot, or else the software build could be restored\n # from cache without fixing the license issue.\n raise_if_warnings_fatal!\n end\n else\n begin\n download_file!(license_file, output_file, enable_progress_bar: false)\n File.chmod 0644, output_file unless windows?\n rescue SocketError,\n Errno::ECONNREFUSED,\n Errno::ECONNRESET,\n Errno::ENETUNREACH,\n Timeout::Error,\n OpenURI::HTTPError,\n OpenSSL::SSL::SSLError\n licensing_warning(\"Can not download license file '#{license_file}' for software '#{software_name}'.\")\n # If we got here, we need to fail now so we don't take a git\n # cache snapshot, or else the software build could be restored\n # from cache without fixing the license issue.\n raise_if_warnings_fatal!\n end\n end\n end\n end\n end", "code_tokens": ["def", "collect_licenses_for", "(", "software", ")", "return", "nil", "if", "software", ".", "license", "==", ":project_license", "software_name", "=", "software", ".", "name", "license_data", "=", "license_map", "[", "software_name", "]", "license_files", "=", "license_data", "[", ":license_files", "]", "license_files", ".", "each", "do", "|", "license_file", "|", "if", "license_file", "output_file", "=", "license_package_location", "(", "software_name", ",", "license_file", ")", "if", "local?", "(", "license_file", ")", "input_file", "=", "File", ".", "expand_path", "(", "license_file", ",", "license_data", "[", ":project_dir", "]", ")", "if", "File", ".", "exist?", "(", "input_file", ")", "FileUtils", ".", "cp", "(", "input_file", ",", "output_file", ")", "File", ".", "chmod", "0644", ",", "output_file", "unless", "windows?", "else", "licensing_warning", "(", "\"License file '#{input_file}' does not exist for software '#{software_name}'.\"", ")", "# If we got here, we need to fail now so we don't take a git", "# cache snapshot, or else the software build could be restored", "# from cache without fixing the license issue.", "raise_if_warnings_fatal!", "end", "else", "begin", "download_file!", "(", "license_file", ",", "output_file", ",", "enable_progress_bar", ":", "false", ")", "File", ".", "chmod", "0644", ",", "output_file", "unless", "windows?", "rescue", "SocketError", ",", "Errno", "::", "ECONNREFUSED", ",", "Errno", "::", "ECONNRESET", ",", "Errno", "::", "ENETUNREACH", ",", "Timeout", "::", "Error", ",", "OpenURI", "::", "HTTPError", ",", "OpenSSL", "::", "SSL", "::", "SSLError", "licensing_warning", "(", "\"Can not download license file '#{license_file}' for software '#{software_name}'.\"", ")", "# If we got here, we need to fail now so we don't take a git", "# cache snapshot, or else the software build could be restored", "# from cache without fixing the license issue.", "raise_if_warnings_fatal!", "end", "end", "end", "end", "end"], "docstring": "Collect the license files for the software.", "docstring_tokens": ["Collect", "the", "license", "files", "for", "the", "software", "."], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/licensing.rb#L582-L625", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/packagers/solaris.rb", "func_name": "Omnibus.Packager::Solaris.write_prototype_file", "original_string": "def write_prototype_file\n shellout! \"cd #{install_dirname} && find #{install_basename} -print > #{staging_dir_path('files')}\"\n\n File.open staging_dir_path(\"files.clean\"), \"w+\" do |fout|\n File.open staging_dir_path(\"files\") do |fin|\n fin.each_line do |line|\n if line.chomp =~ /\\s/\n log.warn(log_key) { \"Skipping packaging '#{line}' file due to whitespace in filename\" }\n else\n fout.write(line)\n end\n end\n end\n end\n\n # generate list of control files\n File.open staging_dir_path(\"Prototype\"), \"w+\" do |f|\n f.write <<-EOF.gsub(/^ {10}/, \"\")\n i pkginfo\n i postinstall\n i postremove\n EOF\n end\n\n # generate the prototype's file list\n shellout! \"cd #{install_dirname} && pkgproto < #{staging_dir_path('files.clean')} > #{staging_dir_path('Prototype.files')}\"\n\n # fix up the user and group in the file list to root\n shellout! \"awk '{ $5 = \\\"root\\\"; $6 = \\\"root\\\"; print }' < #{staging_dir_path('Prototype.files')} >> #{staging_dir_path('Prototype')}\"\n end", "language": "ruby", "code": "def write_prototype_file\n shellout! \"cd #{install_dirname} && find #{install_basename} -print > #{staging_dir_path('files')}\"\n\n File.open staging_dir_path(\"files.clean\"), \"w+\" do |fout|\n File.open staging_dir_path(\"files\") do |fin|\n fin.each_line do |line|\n if line.chomp =~ /\\s/\n log.warn(log_key) { \"Skipping packaging '#{line}' file due to whitespace in filename\" }\n else\n fout.write(line)\n end\n end\n end\n end\n\n # generate list of control files\n File.open staging_dir_path(\"Prototype\"), \"w+\" do |f|\n f.write <<-EOF.gsub(/^ {10}/, \"\")\n i pkginfo\n i postinstall\n i postremove\n EOF\n end\n\n # generate the prototype's file list\n shellout! \"cd #{install_dirname} && pkgproto < #{staging_dir_path('files.clean')} > #{staging_dir_path('Prototype.files')}\"\n\n # fix up the user and group in the file list to root\n shellout! \"awk '{ $5 = \\\"root\\\"; $6 = \\\"root\\\"; print }' < #{staging_dir_path('Prototype.files')} >> #{staging_dir_path('Prototype')}\"\n end", "code_tokens": ["def", "write_prototype_file", "shellout!", "\"cd #{install_dirname} && find #{install_basename} -print > #{staging_dir_path('files')}\"", "File", ".", "open", "staging_dir_path", "(", "\"files.clean\"", ")", ",", "\"w+\"", "do", "|", "fout", "|", "File", ".", "open", "staging_dir_path", "(", "\"files\"", ")", "do", "|", "fin", "|", "fin", ".", "each_line", "do", "|", "line", "|", "if", "line", ".", "chomp", "=~", "/", "\\s", "/", "log", ".", "warn", "(", "log_key", ")", "{", "\"Skipping packaging '#{line}' file due to whitespace in filename\"", "}", "else", "fout", ".", "write", "(", "line", ")", "end", "end", "end", "end", "# generate list of control files", "File", ".", "open", "staging_dir_path", "(", "\"Prototype\"", ")", ",", "\"w+\"", "do", "|", "f", "|", "f", ".", "write", "<<-EOF", ".", "gsub", "(", "/", "/", ",", "\"\"", ")", "EOF", "end", "# generate the prototype's file list", "shellout!", "\"cd #{install_dirname} && pkgproto < #{staging_dir_path('files.clean')} > #{staging_dir_path('Prototype.files')}\"", "# fix up the user and group in the file list to root", "shellout!", "\"awk '{ $5 = \\\"root\\\"; $6 = \\\"root\\\"; print }' < #{staging_dir_path('Prototype.files')} >> #{staging_dir_path('Prototype')}\"", "end"], "docstring": "Generate a Prototype file for solaris build", "docstring_tokens": ["Generate", "a", "Prototype", "file", "for", "solaris", "build"], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/packagers/solaris.rb#L78-L107", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/package.rb", "func_name": "Omnibus.Package.content", "original_string": "def content\n @content ||= IO.read(path)\n rescue Errno::ENOENT\n raise NoPackageFile.new(path)\n end", "language": "ruby", "code": "def content\n @content ||= IO.read(path)\n rescue Errno::ENOENT\n raise NoPackageFile.new(path)\n end", "code_tokens": ["def", "content", "@content", "||=", "IO", ".", "read", "(", "path", ")", "rescue", "Errno", "::", "ENOENT", "raise", "NoPackageFile", ".", "new", "(", "path", ")", "end"], "docstring": "The actual contents of the package.\n\n @return [String]", "docstring_tokens": ["The", "actual", "contents", "of", "the", "package", "."], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/package.rb#L88-L92", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/package.rb", "func_name": "Omnibus.Package.validate!", "original_string": "def validate!\n unless File.exist?(path)\n raise NoPackageFile.new(path)\n end\n\n unless File.exist?(metadata.path)\n raise NoPackageMetadataFile.new(metadata.path)\n end\n\n true\n end", "language": "ruby", "code": "def validate!\n unless File.exist?(path)\n raise NoPackageFile.new(path)\n end\n\n unless File.exist?(metadata.path)\n raise NoPackageMetadataFile.new(metadata.path)\n end\n\n true\n end", "code_tokens": ["def", "validate!", "unless", "File", ".", "exist?", "(", "path", ")", "raise", "NoPackageFile", ".", "new", "(", "path", ")", "end", "unless", "File", ".", "exist?", "(", "metadata", ".", "path", ")", "raise", "NoPackageMetadataFile", ".", "new", "(", "metadata", ".", "path", ")", "end", "true", "end"], "docstring": "Validate the presence of the required components for the package.\n\n @raise [NoPackageFile] if the package is not present\n @raise [NoPackageMetadataFile] if the metadata file is not present\n\n @return [true]", "docstring_tokens": ["Validate", "the", "presence", "of", "the", "required", "components", "for", "the", "package", "."], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/package.rb#L123-L133", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/publishers/s3_publisher.rb", "func_name": "Omnibus.S3Publisher.key_for", "original_string": "def key_for(package, *stuff)\n File.join(\n Config.s3_publish_pattern % package.metadata,\n *stuff\n )\n end", "language": "ruby", "code": "def key_for(package, *stuff)\n File.join(\n Config.s3_publish_pattern % package.metadata,\n *stuff\n )\n end", "code_tokens": ["def", "key_for", "(", "package", ",", "*", "stuff", ")", "File", ".", "join", "(", "Config", ".", "s3_publish_pattern", "%", "package", ".", "metadata", ",", "stuff", ")", "end"], "docstring": "The unique upload key for this package. The additional \"stuff\" is\n postfixed to the end of the path.\n\n @example\n 'el/6/x86_64/chef-11.6.0-1.el6.x86_64.rpm/chef-11.6.0-1.el6.x86_64.rpm'\n\n @param [Package] package\n the package this key is for\n @param [Array] stuff\n the additional things to append\n\n @return [String]", "docstring_tokens": ["The", "unique", "upload", "key", "for", "this", "package", ".", "The", "additional", "stuff", "is", "postfixed", "to", "the", "end", "of", "the", "path", "."], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/publishers/s3_publisher.rb#L92-L97", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/build_version.rb", "func_name": "Omnibus.BuildVersion.semver", "original_string": "def semver\n build_tag = version_tag\n\n # PRERELEASE VERSION\n if prerelease_version?\n # ensure all dashes are dots per precedence rules (#12) in Semver\n # 2.0.0-rc.1\n prerelease = prerelease_tag.tr(\"-\", \".\")\n build_tag << \"-\" << prerelease\n end\n\n # BUILD VERSION\n # Follows SemVer conventions and the build version begins with a '+'.\n build_version_items = []\n\n # By default we will append a timestamp to every build. This behavior can\n # be overriden by setting the OMNIBUS_APPEND_TIMESTAMP environment\n # variable to a 'falsey' value (ie false, f, no, n or 0).\n #\n # format: YYYYMMDDHHMMSS example: 20130131123345\n if Config.append_timestamp\n build_version_items << build_start_time\n end\n\n # We'll append the git describe information unless we are sitting right\n # on an annotated tag.\n #\n # format: git.COMMITS_SINCE_TAG.GIT_SHA example: git.207.694b062\n unless commits_since_tag == 0\n build_version_items << [\"git\", commits_since_tag, git_sha_tag].join(\".\")\n end\n\n unless build_version_items.empty?\n build_tag << \"+\" << build_version_items.join(\".\")\n end\n\n build_tag\n end", "language": "ruby", "code": "def semver\n build_tag = version_tag\n\n # PRERELEASE VERSION\n if prerelease_version?\n # ensure all dashes are dots per precedence rules (#12) in Semver\n # 2.0.0-rc.1\n prerelease = prerelease_tag.tr(\"-\", \".\")\n build_tag << \"-\" << prerelease\n end\n\n # BUILD VERSION\n # Follows SemVer conventions and the build version begins with a '+'.\n build_version_items = []\n\n # By default we will append a timestamp to every build. This behavior can\n # be overriden by setting the OMNIBUS_APPEND_TIMESTAMP environment\n # variable to a 'falsey' value (ie false, f, no, n or 0).\n #\n # format: YYYYMMDDHHMMSS example: 20130131123345\n if Config.append_timestamp\n build_version_items << build_start_time\n end\n\n # We'll append the git describe information unless we are sitting right\n # on an annotated tag.\n #\n # format: git.COMMITS_SINCE_TAG.GIT_SHA example: git.207.694b062\n unless commits_since_tag == 0\n build_version_items << [\"git\", commits_since_tag, git_sha_tag].join(\".\")\n end\n\n unless build_version_items.empty?\n build_tag << \"+\" << build_version_items.join(\".\")\n end\n\n build_tag\n end", "code_tokens": ["def", "semver", "build_tag", "=", "version_tag", "# PRERELEASE VERSION", "if", "prerelease_version?", "# ensure all dashes are dots per precedence rules (#12) in Semver", "# 2.0.0-rc.1", "prerelease", "=", "prerelease_tag", ".", "tr", "(", "\"-\"", ",", "\".\"", ")", "build_tag", "<<", "\"-\"", "<<", "prerelease", "end", "# BUILD VERSION", "# Follows SemVer conventions and the build version begins with a '+'.", "build_version_items", "=", "[", "]", "# By default we will append a timestamp to every build. This behavior can", "# be overriden by setting the OMNIBUS_APPEND_TIMESTAMP environment", "# variable to a 'falsey' value (ie false, f, no, n or 0).", "#", "# format: YYYYMMDDHHMMSS example: 20130131123345", "if", "Config", ".", "append_timestamp", "build_version_items", "<<", "build_start_time", "end", "# We'll append the git describe information unless we are sitting right", "# on an annotated tag.", "#", "# format: git.COMMITS_SINCE_TAG.GIT_SHA example: git.207.694b062", "unless", "commits_since_tag", "==", "0", "build_version_items", "<<", "[", "\"git\"", ",", "commits_since_tag", ",", "git_sha_tag", "]", ".", "join", "(", "\".\"", ")", "end", "unless", "build_version_items", ".", "empty?", "build_tag", "<<", "\"+\"", "<<", "build_version_items", ".", "join", "(", "\".\"", ")", "end", "build_tag", "end"], "docstring": "Create a new BuildVersion\n\n @param [String] path\n Path from which to read git version information\n @!group Version Generator Methods\n Generate a {http://semver.org/ SemVer 2.0.0-rc.1 compliant}\n version string for an Omnibus project.\n\n This relies on the Omnibus project being a Git repository, as\n well as having tags named according to SemVer conventions\n (specifically, the `MAJOR.MINOR.PATCH-PRERELEASE` aspects)\n\n The specific format of the version string is:\n\n MAJOR.MINOR.PATCH-PRERELEASE+TIMESTAMP.git.COMMITS_SINCE.GIT_SHA\n\n By default, a timestamp is incorporated into the build component of\n version string (see {Omnibus::BuildVersion::TIMESTAMP_FORMAT}). This\n option is configurable via the {Config}.\n\n @example 11.0.0-alpha.1+20121218164140.git.207.694b062\n @return [String]\n @see #git_describe\n @todo Issue a warning or throw an exception if the tags of the\n repository are not themselves SemVer-compliant?\n @todo Consider making the {#build_start_time} method public, as\n its function influences how build timestamps are generated,\n and can be influenced by users.", "docstring_tokens": ["Create", "a", "new", "BuildVersion"], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/build_version.rb#L88-L125", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/build_version.rb", "func_name": "Omnibus.BuildVersion.build_start_time", "original_string": "def build_start_time\n @build_start_time ||= begin\n if ENV[\"BUILD_TIMESTAMP\"]\n begin\n Time.strptime(ENV[\"BUILD_TIMESTAMP\"], \"%Y-%m-%d_%H-%M-%S\")\n rescue ArgumentError\n error_message = \"BUILD_TIMESTAMP environment variable \"\n error_message << \"should be in YYYY-MM-DD_hh-mm-ss \"\n error_message << \"format.\"\n raise ArgumentError, error_message\n end\n elsif ENV[\"BUILD_ID\"]\n begin\n Time.strptime(ENV[\"BUILD_ID\"], \"%Y-%m-%d_%H-%M-%S\")\n rescue ArgumentError\n error_message = \"BUILD_ID environment variable \"\n error_message << \"should be in YYYY-MM-DD_hh-mm-ss \"\n error_message << \"format.\"\n raise ArgumentError, error_message\n end\n else\n Time.now.utc\n end\n end.strftime(TIMESTAMP_FORMAT)\n end", "language": "ruby", "code": "def build_start_time\n @build_start_time ||= begin\n if ENV[\"BUILD_TIMESTAMP\"]\n begin\n Time.strptime(ENV[\"BUILD_TIMESTAMP\"], \"%Y-%m-%d_%H-%M-%S\")\n rescue ArgumentError\n error_message = \"BUILD_TIMESTAMP environment variable \"\n error_message << \"should be in YYYY-MM-DD_hh-mm-ss \"\n error_message << \"format.\"\n raise ArgumentError, error_message\n end\n elsif ENV[\"BUILD_ID\"]\n begin\n Time.strptime(ENV[\"BUILD_ID\"], \"%Y-%m-%d_%H-%M-%S\")\n rescue ArgumentError\n error_message = \"BUILD_ID environment variable \"\n error_message << \"should be in YYYY-MM-DD_hh-mm-ss \"\n error_message << \"format.\"\n raise ArgumentError, error_message\n end\n else\n Time.now.utc\n end\n end.strftime(TIMESTAMP_FORMAT)\n end", "code_tokens": ["def", "build_start_time", "@build_start_time", "||=", "begin", "if", "ENV", "[", "\"BUILD_TIMESTAMP\"", "]", "begin", "Time", ".", "strptime", "(", "ENV", "[", "\"BUILD_TIMESTAMP\"", "]", ",", "\"%Y-%m-%d_%H-%M-%S\"", ")", "rescue", "ArgumentError", "error_message", "=", "\"BUILD_TIMESTAMP environment variable \"", "error_message", "<<", "\"should be in YYYY-MM-DD_hh-mm-ss \"", "error_message", "<<", "\"format.\"", "raise", "ArgumentError", ",", "error_message", "end", "elsif", "ENV", "[", "\"BUILD_ID\"", "]", "begin", "Time", ".", "strptime", "(", "ENV", "[", "\"BUILD_ID\"", "]", ",", "\"%Y-%m-%d_%H-%M-%S\"", ")", "rescue", "ArgumentError", "error_message", "=", "\"BUILD_ID environment variable \"", "error_message", "<<", "\"should be in YYYY-MM-DD_hh-mm-ss \"", "error_message", "<<", "\"format.\"", "raise", "ArgumentError", ",", "error_message", "end", "else", "Time", ".", "now", ".", "utc", "end", "end", ".", "strftime", "(", "TIMESTAMP_FORMAT", ")", "end"], "docstring": "We'll attempt to retrieve the timestamp from the Jenkin's set BUILD_TIMESTAMP\n or fall back to BUILD_ID environment variable. This will ensure platform specfic\n packages for the same build will share the same timestamp.", "docstring_tokens": ["We", "ll", "attempt", "to", "retrieve", "the", "timestamp", "from", "the", "Jenkin", "s", "set", "BUILD_TIMESTAMP", "or", "fall", "back", "to", "BUILD_ID", "environment", "variable", ".", "This", "will", "ensure", "platform", "specfic", "packages", "for", "the", "same", "build", "will", "share", "the", "same", "timestamp", "."], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/build_version.rb#L130-L154", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/metadata.rb", "func_name": "Omnibus.Metadata.save", "original_string": "def save\n File.open(path, \"w+\") do |f|\n f.write(FFI_Yajl::Encoder.encode(to_hash, pretty: true))\n end\n\n true\n end", "language": "ruby", "code": "def save\n File.open(path, \"w+\") do |f|\n f.write(FFI_Yajl::Encoder.encode(to_hash, pretty: true))\n end\n\n true\n end", "code_tokens": ["def", "save", "File", ".", "open", "(", "path", ",", "\"w+\"", ")", "do", "|", "f", "|", "f", ".", "write", "(", "FFI_Yajl", "::", "Encoder", ".", "encode", "(", "to_hash", ",", "pretty", ":", "true", ")", ")", "end", "true", "end"], "docstring": "Save the file to disk.\n\n @return [true]", "docstring_tokens": ["Save", "the", "file", "to", "disk", "."], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/metadata.rb#L270-L276", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/packagers/rpm.rb", "func_name": "Omnibus.Packager::RPM.vendor", "original_string": "def vendor(val = NULL)\n if null?(val)\n @vendor || \"Omnibus \"\n else\n unless val.is_a?(String)\n raise InvalidValue.new(:vendor, \"be a String\")\n end\n\n @vendor = val\n end\n end", "language": "ruby", "code": "def vendor(val = NULL)\n if null?(val)\n @vendor || \"Omnibus \"\n else\n unless val.is_a?(String)\n raise InvalidValue.new(:vendor, \"be a String\")\n end\n\n @vendor = val\n end\n end", "code_tokens": ["def", "vendor", "(", "val", "=", "NULL", ")", "if", "null?", "(", "val", ")", "@vendor", "||", "\"Omnibus \"", "else", "unless", "val", ".", "is_a?", "(", "String", ")", "raise", "InvalidValue", ".", "new", "(", ":vendor", ",", "\"be a String\"", ")", "end", "@vendor", "=", "val", "end", "end"], "docstring": "Set or return the vendor who made this package.\n\n @example\n vendor \"Seth Vargo \"\n\n @param [String] val\n the vendor who make this package\n\n @return [String]\n the vendor who make this package", "docstring_tokens": ["Set", "or", "return", "the", "vendor", "who", "made", "this", "package", "."], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/packagers/rpm.rb#L117-L127", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/packagers/rpm.rb", "func_name": "Omnibus.Packager::RPM.license", "original_string": "def license(val = NULL)\n if null?(val)\n @license || project.license\n else\n unless val.is_a?(String)\n raise InvalidValue.new(:license, \"be a String\")\n end\n\n @license = val\n end\n end", "language": "ruby", "code": "def license(val = NULL)\n if null?(val)\n @license || project.license\n else\n unless val.is_a?(String)\n raise InvalidValue.new(:license, \"be a String\")\n end\n\n @license = val\n end\n end", "code_tokens": ["def", "license", "(", "val", "=", "NULL", ")", "if", "null?", "(", "val", ")", "@license", "||", "project", ".", "license", "else", "unless", "val", ".", "is_a?", "(", "String", ")", "raise", "InvalidValue", ".", "new", "(", ":license", ",", "\"be a String\"", ")", "end", "@license", "=", "val", "end", "end"], "docstring": "Set or return the license for this package.\n\n @example\n license \"Apache 2.0\"\n\n @param [String] val\n the license for this package\n\n @return [String]\n the license for this package", "docstring_tokens": ["Set", "or", "return", "the", "license", "for", "this", "package", "."], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/packagers/rpm.rb#L142-L152", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/packagers/rpm.rb", "func_name": "Omnibus.Packager::RPM.build_filepath", "original_string": "def build_filepath(path)\n filepath = rpm_safe(\"/\" + path.gsub(\"#{build_dir}/\", \"\"))\n return if config_files.include?(filepath)\n full_path = build_dir + filepath.gsub(\"[%]\", \"%\")\n # FileSyncer.glob quotes pathnames that contain spaces, which is a problem on el7\n full_path.delete!('\"')\n # Mark directories with the %dir directive to prevent rpmbuild from counting their contents twice.\n return mark_filesystem_directories(filepath) if !File.symlink?(full_path) && File.directory?(full_path)\n filepath\n end", "language": "ruby", "code": "def build_filepath(path)\n filepath = rpm_safe(\"/\" + path.gsub(\"#{build_dir}/\", \"\"))\n return if config_files.include?(filepath)\n full_path = build_dir + filepath.gsub(\"[%]\", \"%\")\n # FileSyncer.glob quotes pathnames that contain spaces, which is a problem on el7\n full_path.delete!('\"')\n # Mark directories with the %dir directive to prevent rpmbuild from counting their contents twice.\n return mark_filesystem_directories(filepath) if !File.symlink?(full_path) && File.directory?(full_path)\n filepath\n end", "code_tokens": ["def", "build_filepath", "(", "path", ")", "filepath", "=", "rpm_safe", "(", "\"/\"", "+", "path", ".", "gsub", "(", "\"#{build_dir}/\"", ",", "\"\"", ")", ")", "return", "if", "config_files", ".", "include?", "(", "filepath", ")", "full_path", "=", "build_dir", "+", "filepath", ".", "gsub", "(", "\"[%]\"", ",", "\"%\"", ")", "# FileSyncer.glob quotes pathnames that contain spaces, which is a problem on el7", "full_path", ".", "delete!", "(", "'\"'", ")", "# Mark directories with the %dir directive to prevent rpmbuild from counting their contents twice.", "return", "mark_filesystem_directories", "(", "filepath", ")", "if", "!", "File", ".", "symlink?", "(", "full_path", ")", "&&", "File", ".", "directory?", "(", "full_path", ")", "filepath", "end"], "docstring": "Convert the path of a file in the staging directory to an entry for use in the spec file.\n\n @return [String]", "docstring_tokens": ["Convert", "the", "path", "of", "a", "file", "in", "the", "staging", "directory", "to", "an", "entry", "for", "use", "in", "the", "spec", "file", "."], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/packagers/rpm.rb#L466-L475", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/packagers/rpm.rb", "func_name": "Omnibus.Packager::RPM.with_rpm_signing", "original_string": "def with_rpm_signing(&block)\n directory = Dir.mktmpdir\n destination = \"#{directory}/sign-rpm\"\n\n render_template(resource_path(\"signing.erb\"),\n destination: destination,\n mode: 0700,\n variables: {\n passphrase: signing_passphrase,\n }\n )\n\n # Yield the destination to the block\n yield(destination)\n ensure\n remove_file(destination)\n remove_directory(directory)\n end", "language": "ruby", "code": "def with_rpm_signing(&block)\n directory = Dir.mktmpdir\n destination = \"#{directory}/sign-rpm\"\n\n render_template(resource_path(\"signing.erb\"),\n destination: destination,\n mode: 0700,\n variables: {\n passphrase: signing_passphrase,\n }\n )\n\n # Yield the destination to the block\n yield(destination)\n ensure\n remove_file(destination)\n remove_directory(directory)\n end", "code_tokens": ["def", "with_rpm_signing", "(", "&", "block", ")", "directory", "=", "Dir", ".", "mktmpdir", "destination", "=", "\"#{directory}/sign-rpm\"", "render_template", "(", "resource_path", "(", "\"signing.erb\"", ")", ",", "destination", ":", "destination", ",", "mode", ":", "0700", ",", "variables", ":", "{", "passphrase", ":", "signing_passphrase", ",", "}", ")", "# Yield the destination to the block", "yield", "(", "destination", ")", "ensure", "remove_file", "(", "destination", ")", "remove_directory", "(", "directory", ")", "end"], "docstring": "Render the rpm signing script with secure permissions, call the given\n block with the path to the script, and ensure deletion of the script from\n disk since it contains sensitive information.\n\n @param [Proc] block\n the block to call\n\n @return [String]", "docstring_tokens": ["Render", "the", "rpm", "signing", "script", "with", "secure", "permissions", "call", "the", "given", "block", "with", "the", "path", "to", "the", "script", "and", "ensure", "deletion", "of", "the", "script", "from", "disk", "since", "it", "contains", "sensitive", "information", "."], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/packagers/rpm.rb#L496-L513", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/cli/publish.rb", "func_name": "Omnibus.Command::Publish.publish", "original_string": "def publish(klass, pattern, options)\n if options[:platform_mappings]\n options[:platform_mappings] = FFI_Yajl::Parser.parse(File.read(File.expand_path(options[:platform_mappings])))\n end\n\n klass.publish(pattern, options) do |package|\n say(\"Published '#{package.name}' for #{package.metadata[:platform]}-#{package.metadata[:platform_version]}\", :green)\n end\n end", "language": "ruby", "code": "def publish(klass, pattern, options)\n if options[:platform_mappings]\n options[:platform_mappings] = FFI_Yajl::Parser.parse(File.read(File.expand_path(options[:platform_mappings])))\n end\n\n klass.publish(pattern, options) do |package|\n say(\"Published '#{package.name}' for #{package.metadata[:platform]}-#{package.metadata[:platform_version]}\", :green)\n end\n end", "code_tokens": ["def", "publish", "(", "klass", ",", "pattern", ",", "options", ")", "if", "options", "[", ":platform_mappings", "]", "options", "[", ":platform_mappings", "]", "=", "FFI_Yajl", "::", "Parser", ".", "parse", "(", "File", ".", "read", "(", "File", ".", "expand_path", "(", "options", "[", ":platform_mappings", "]", ")", ")", ")", "end", "klass", ".", "publish", "(", "pattern", ",", "options", ")", "do", "|", "package", "|", "say", "(", "\"Published '#{package.name}' for #{package.metadata[:platform]}-#{package.metadata[:platform_version]}\"", ",", ":green", ")", "end", "end"], "docstring": "Shortcut method for executing a publisher.\n\n @return [void]", "docstring_tokens": ["Shortcut", "method", "for", "executing", "a", "publisher", "."], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/cli/publish.rb#L96-L104", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/project.rb", "func_name": "Omnibus.Project.build_version", "original_string": "def build_version(val = NULL, &block)\n if block && !null?(val)\n raise Error, \"You cannot specify additional parameters to \" \\\n \"#build_version when a block is given!\"\n end\n\n if block\n @build_version_dsl = BuildVersionDSL.new(&block)\n else\n if null?(val)\n @build_version_dsl.build_version\n else\n @build_version_dsl = BuildVersionDSL.new(val)\n end\n end\n end", "language": "ruby", "code": "def build_version(val = NULL, &block)\n if block && !null?(val)\n raise Error, \"You cannot specify additional parameters to \" \\\n \"#build_version when a block is given!\"\n end\n\n if block\n @build_version_dsl = BuildVersionDSL.new(&block)\n else\n if null?(val)\n @build_version_dsl.build_version\n else\n @build_version_dsl = BuildVersionDSL.new(val)\n end\n end\n end", "code_tokens": ["def", "build_version", "(", "val", "=", "NULL", ",", "&", "block", ")", "if", "block", "&&", "!", "null?", "(", "val", ")", "raise", "Error", ",", "\"You cannot specify additional parameters to \"", "\"#build_version when a block is given!\"", "end", "if", "block", "@build_version_dsl", "=", "BuildVersionDSL", ".", "new", "(", "block", ")", "else", "if", "null?", "(", "val", ")", "@build_version_dsl", ".", "build_version", "else", "@build_version_dsl", "=", "BuildVersionDSL", ".", "new", "(", "val", ")", "end", "end", "end"], "docstring": "Set or retrieve the version of the project.\n\n @example Using a string\n build_version '1.0.0'\n\n @example From git\n build_version do\n source :git\n end\n\n @example From the version of a dependency\n build_version do\n source :version, from_dependency: 'chef'\n end\n\n @example From git of a dependency\n build_version do\n source :git, from_dependency: 'chef'\n end\n\n When using the +:git+ source, by default the output format of the\n +build_version+ is semver. This can be modified using the +:output_format+\n parameter to any of the methods of +BuildVersion+. For example:\n\n build version do\n source :git, from_dependency: 'chef'\n output_format :git_describe\n end\n\n @see Omnibus::BuildVersion\n @see Omnibus::BuildVersionDSL\n\n @param [String] val\n the build version to set\n @param [Proc] block\n the block to run when constructing the +build_version+\n\n @return [String]", "docstring_tokens": ["Set", "or", "retrieve", "the", "version", "of", "the", "project", "."], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/project.rb#L368-L383", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/project.rb", "func_name": "Omnibus.Project.package", "original_string": "def package(id, &block)\n unless block\n raise InvalidValue.new(:package, \"have a block\")\n end\n\n packagers[id] << block\n end", "language": "ruby", "code": "def package(id, &block)\n unless block\n raise InvalidValue.new(:package, \"have a block\")\n end\n\n packagers[id] << block\n end", "code_tokens": ["def", "package", "(", "id", ",", "&", "block", ")", "unless", "block", "raise", "InvalidValue", ".", "new", "(", ":package", ",", "\"have a block\"", ")", "end", "packagers", "[", "id", "]", "<<", "block", "end"], "docstring": "Add or override a customization for the packager with the given +id+. When\n given multiple blocks with the same +id+, they are evaluated _in order_,\n so the last block evaluated will take precedence over the previous ones.\n\n @example\n package :id do\n key 'value'\n end\n\n @param [Symbol] id\n the id of the packager to customize", "docstring_tokens": ["Add", "or", "override", "a", "customization", "for", "the", "packager", "with", "the", "given", "+", "id", "+", ".", "When", "given", "multiple", "blocks", "with", "the", "same", "+", "id", "+", "they", "are", "evaluated", "_in", "order_", "so", "the", "last", "block", "evaluated", "will", "take", "precedence", "over", "the", "previous", "ones", "."], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/project.rb#L437-L443", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/project.rb", "func_name": "Omnibus.Project.compress", "original_string": "def compress(id, &block)\n if block\n compressors[id] << block\n else\n compressors[id] << Proc.new {}\n end\n end", "language": "ruby", "code": "def compress(id, &block)\n if block\n compressors[id] << block\n else\n compressors[id] << Proc.new {}\n end\n end", "code_tokens": ["def", "compress", "(", "id", ",", "&", "block", ")", "if", "block", "compressors", "[", "id", "]", "<<", "block", "else", "compressors", "[", "id", "]", "<<", "Proc", ".", "new", "{", "}", "end", "end"], "docstring": "Add or override a customization for the compressor with the given +id+.\n When given multiple blocks with the same +id+, they are evaluated\n _in order_, so the last block evaluated will take precedence over the\n previous ones.\n\n @example With customization\n compress :dmg do\n window_bounds '10, 20, 30, 40'\n end\n\n @example Without customization\n compress :tgz\n\n If multiple +compress+ blocks are specified, the \"most prefered\" one for\n the current system will be used.\n\n @param [Symbol] id\n the id of the compressor to customize", "docstring_tokens": ["Add", "or", "override", "a", "customization", "for", "the", "compressor", "with", "the", "given", "+", "id", "+", ".", "When", "given", "multiple", "blocks", "with", "the", "same", "+", "id", "+", "they", "are", "evaluated", "_in", "order_", "so", "the", "last", "block", "evaluated", "will", "take", "precedence", "over", "the", "previous", "ones", "."], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/project.rb#L466-L472", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/project.rb", "func_name": "Omnibus.Project.override", "original_string": "def override(name, val = NULL)\n if null?(val)\n overrides[name.to_sym]\n else\n overrides[name.to_sym] = val\n end\n end", "language": "ruby", "code": "def override(name, val = NULL)\n if null?(val)\n overrides[name.to_sym]\n else\n overrides[name.to_sym] = val\n end\n end", "code_tokens": ["def", "override", "(", "name", ",", "val", "=", "NULL", ")", "if", "null?", "(", "val", ")", "overrides", "[", "name", ".", "to_sym", "]", "else", "overrides", "[", "name", ".", "to_sym", "]", "=", "val", "end", "end"], "docstring": "Set or retrieve the overrides hash for one piece of software being\n overridden. Calling it as a setter does not merge hash entries and it will\n set all the overrides for a given software definition.\n\n @example\n override 'chef', version: '1.2.3'\n\n @param [Hash] val\n the value to override\n\n @return [Hash]", "docstring_tokens": ["Set", "or", "retrieve", "the", "overrides", "hash", "for", "one", "piece", "of", "software", "being", "overridden", ".", "Calling", "it", "as", "a", "setter", "does", "not", "merge", "hash", "entries", "and", "it", "will", "set", "all", "the", "overrides", "for", "a", "given", "software", "definition", "."], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/project.rb#L512-L518", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/project.rb", "func_name": "Omnibus.Project.license_file_path", "original_string": "def license_file_path(path = NULL)\n if null?(path)\n @license_file_path || File.join(install_dir, \"LICENSE\")\n else\n @license_file_path = File.join(install_dir, path)\n end\n end", "language": "ruby", "code": "def license_file_path(path = NULL)\n if null?(path)\n @license_file_path || File.join(install_dir, \"LICENSE\")\n else\n @license_file_path = File.join(install_dir, path)\n end\n end", "code_tokens": ["def", "license_file_path", "(", "path", "=", "NULL", ")", "if", "null?", "(", "path", ")", "@license_file_path", "||", "File", ".", "join", "(", "install_dir", ",", "\"LICENSE\"", ")", "else", "@license_file_path", "=", "File", ".", "join", "(", "install_dir", ",", "path", ")", "end", "end"], "docstring": "Location of license file that omnibus will create and that will contain\n the information about the license of the project plus the details about\n the licenses of the software components included in the project.\n\n If no path is specified install_dir/LICENSE is used.\n\n @example\n license_file_path\n\n @return [String]", "docstring_tokens": ["Location", "of", "license", "file", "that", "omnibus", "will", "create", "and", "that", "will", "contain", "the", "information", "about", "the", "license", "of", "the", "project", "plus", "the", "details", "about", "the", "licenses", "of", "the", "software", "components", "included", "in", "the", "project", "."], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/project.rb#L755-L761", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/project.rb", "func_name": "Omnibus.Project.dependency?", "original_string": "def dependency?(software)\n name = software.is_a?(Software) ? software.name : software\n dependencies.include?(name)\n end", "language": "ruby", "code": "def dependency?(software)\n name = software.is_a?(Software) ? software.name : software\n dependencies.include?(name)\n end", "code_tokens": ["def", "dependency?", "(", "software", ")", "name", "=", "software", ".", "is_a?", "(", "Software", ")", "?", "software", ".", "name", ":", "software", "dependencies", ".", "include?", "(", "name", ")", "end"], "docstring": "Indicates whether the given +software+ is defined as a software component\n of this project.\n\n @param [String, Software] software\n the software or name of the software to find\n\n @return [true, false]", "docstring_tokens": ["Indicates", "whether", "the", "given", "+", "software", "+", "is", "defined", "as", "a", "software", "component", "of", "this", "project", "."], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/project.rb#L984-L987", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/project.rb", "func_name": "Omnibus.Project.built_manifest", "original_string": "def built_manifest\n log.info(log_key) { \"Building version manifest\" }\n m = Omnibus::Manifest.new(build_version, build_git_revision, license)\n softwares.each do |software|\n m.add(software.name, software.manifest_entry)\n end\n m\n end", "language": "ruby", "code": "def built_manifest\n log.info(log_key) { \"Building version manifest\" }\n m = Omnibus::Manifest.new(build_version, build_git_revision, license)\n softwares.each do |software|\n m.add(software.name, software.manifest_entry)\n end\n m\n end", "code_tokens": ["def", "built_manifest", "log", ".", "info", "(", "log_key", ")", "{", "\"Building version manifest\"", "}", "m", "=", "Omnibus", "::", "Manifest", ".", "new", "(", "build_version", ",", "build_git_revision", ",", "license", ")", "softwares", ".", "each", "do", "|", "software", "|", "m", ".", "add", "(", "software", ".", "name", ",", "software", ".", "manifest_entry", ")", "end", "m", "end"], "docstring": "Generate a version manifest of the loaded software sources.\n\n @returns [Omnibus::Manifest]", "docstring_tokens": ["Generate", "a", "version", "manifest", "of", "the", "loaded", "software", "sources", "."], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/project.rb#L1054-L1061", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/project.rb", "func_name": "Omnibus.Project.write_text_manifest", "original_string": "def write_text_manifest\n File.open(text_manifest_path, \"w\") do |f|\n f.puts \"#{name} #{build_version}\"\n f.puts \"\"\n f.puts Omnibus::Reports.pretty_version_map(self)\n end\n end", "language": "ruby", "code": "def write_text_manifest\n File.open(text_manifest_path, \"w\") do |f|\n f.puts \"#{name} #{build_version}\"\n f.puts \"\"\n f.puts Omnibus::Reports.pretty_version_map(self)\n end\n end", "code_tokens": ["def", "write_text_manifest", "File", ".", "open", "(", "text_manifest_path", ",", "\"w\"", ")", "do", "|", "f", "|", "f", ".", "puts", "\"#{name} #{build_version}\"", "f", ".", "puts", "\"\"", "f", ".", "puts", "Omnibus", "::", "Reports", ".", "pretty_version_map", "(", "self", ")", "end", "end"], "docstring": "Writes a text manifest to the text_manifest_path. This uses the\n same method as the \"version-manifest\" software definition in\n omnibus-software.", "docstring_tokens": ["Writes", "a", "text", "manifest", "to", "the", "text_manifest_path", ".", "This", "uses", "the", "same", "method", "as", "the", "version", "-", "manifest", "software", "definition", "in", "omnibus", "-", "software", "."], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/project.rb#L1109-L1115", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/packagers/deb.rb", "func_name": "Omnibus.Packager::DEB.write_conffiles_file", "original_string": "def write_conffiles_file\n return if project.config_files.empty?\n\n render_template(resource_path(\"conffiles.erb\"),\n destination: File.join(debian_dir, \"conffiles\"),\n variables: {\n config_files: project.config_files,\n }\n )\n end", "language": "ruby", "code": "def write_conffiles_file\n return if project.config_files.empty?\n\n render_template(resource_path(\"conffiles.erb\"),\n destination: File.join(debian_dir, \"conffiles\"),\n variables: {\n config_files: project.config_files,\n }\n )\n end", "code_tokens": ["def", "write_conffiles_file", "return", "if", "project", ".", "config_files", ".", "empty?", "render_template", "(", "resource_path", "(", "\"conffiles.erb\"", ")", ",", "destination", ":", "File", ".", "join", "(", "debian_dir", ",", "\"conffiles\"", ")", ",", "variables", ":", "{", "config_files", ":", "project", ".", "config_files", ",", "}", ")", "end"], "docstring": "Render the list of config files into the conffile.\n\n @return [void]", "docstring_tokens": ["Render", "the", "list", "of", "config", "files", "into", "the", "conffile", "."], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/packagers/deb.rb#L332-L341", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/packagers/deb.rb", "func_name": "Omnibus.Packager::DEB.package_size", "original_string": "def package_size\n @package_size ||= begin\n path = \"#{project.install_dir}/**/*\"\n total = FileSyncer.glob(path).inject(0) do |size, path|\n unless File.directory?(path) || File.symlink?(path)\n size += File.size(path)\n end\n\n size\n end\n\n # Per http://www.debian.org/doc/debian-policy/ch-controlfields.html, the\n # disk space is given as the integer value of the estimated installed\n # size in bytes, divided by 1024 and rounded up.\n total / 1024\n end\n end", "language": "ruby", "code": "def package_size\n @package_size ||= begin\n path = \"#{project.install_dir}/**/*\"\n total = FileSyncer.glob(path).inject(0) do |size, path|\n unless File.directory?(path) || File.symlink?(path)\n size += File.size(path)\n end\n\n size\n end\n\n # Per http://www.debian.org/doc/debian-policy/ch-controlfields.html, the\n # disk space is given as the integer value of the estimated installed\n # size in bytes, divided by 1024 and rounded up.\n total / 1024\n end\n end", "code_tokens": ["def", "package_size", "@package_size", "||=", "begin", "path", "=", "\"#{project.install_dir}/**/*\"", "total", "=", "FileSyncer", ".", "glob", "(", "path", ")", ".", "inject", "(", "0", ")", "do", "|", "size", ",", "path", "|", "unless", "File", ".", "directory?", "(", "path", ")", "||", "File", ".", "symlink?", "(", "path", ")", "size", "+=", "File", ".", "size", "(", "path", ")", "end", "size", "end", "# Per http://www.debian.org/doc/debian-policy/ch-controlfields.html, the", "# disk space is given as the integer value of the estimated installed", "# size in bytes, divided by 1024 and rounded up.", "total", "/", "1024", "end", "end"], "docstring": "The size of this Debian package. This is dynamically calculated.\n\n @return [Fixnum]", "docstring_tokens": ["The", "size", "of", "this", "Debian", "package", ".", "This", "is", "dynamically", "calculated", "."], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/packagers/deb.rb#L478-L494", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/fetchers/git_fetcher.rb", "func_name": "Omnibus.GitFetcher.dir_empty?", "original_string": "def dir_empty?(dir)\n Dir.entries(dir).reject { |d| [\".\", \"..\"].include?(d) }.empty?\n end", "language": "ruby", "code": "def dir_empty?(dir)\n Dir.entries(dir).reject { |d| [\".\", \"..\"].include?(d) }.empty?\n end", "code_tokens": ["def", "dir_empty?", "(", "dir", ")", "Dir", ".", "entries", "(", "dir", ")", ".", "reject", "{", "|", "d", "|", "[", "\".\"", ",", "\"..\"", "]", ".", "include?", "(", "d", ")", "}", ".", "empty?", "end"], "docstring": "Determine if a directory is empty\n\n @return [true, false]", "docstring_tokens": ["Determine", "if", "a", "directory", "is", "empty"], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/fetchers/git_fetcher.rb#L116-L118", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/fetchers/git_fetcher.rb", "func_name": "Omnibus.GitFetcher.force_recreate_project_dir!", "original_string": "def force_recreate_project_dir!\n log.warn(log_key) { \"Removing existing directory #{project_dir} before cloning\" }\n FileUtils.rm_rf(project_dir)\n Dir.mkdir(project_dir)\n end", "language": "ruby", "code": "def force_recreate_project_dir!\n log.warn(log_key) { \"Removing existing directory #{project_dir} before cloning\" }\n FileUtils.rm_rf(project_dir)\n Dir.mkdir(project_dir)\n end", "code_tokens": ["def", "force_recreate_project_dir!", "log", ".", "warn", "(", "log_key", ")", "{", "\"Removing existing directory #{project_dir} before cloning\"", "}", "FileUtils", ".", "rm_rf", "(", "project_dir", ")", "Dir", ".", "mkdir", "(", "project_dir", ")", "end"], "docstring": "Forcibly remove and recreate the project directory", "docstring_tokens": ["Forcibly", "remove", "and", "recreate", "the", "project", "directory"], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/fetchers/git_fetcher.rb#L123-L127", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/fetchers/git_fetcher.rb", "func_name": "Omnibus.GitFetcher.current_revision", "original_string": "def current_revision\n cmd = git(\"rev-parse HEAD\")\n cmd.stdout.strip\n rescue CommandFailed\n log.debug(log_key) { \"unable to determine current revision\" }\n nil\n end", "language": "ruby", "code": "def current_revision\n cmd = git(\"rev-parse HEAD\")\n cmd.stdout.strip\n rescue CommandFailed\n log.debug(log_key) { \"unable to determine current revision\" }\n nil\n end", "code_tokens": ["def", "current_revision", "cmd", "=", "git", "(", "\"rev-parse HEAD\"", ")", "cmd", ".", "stdout", ".", "strip", "rescue", "CommandFailed", "log", ".", "debug", "(", "log_key", ")", "{", "\"unable to determine current revision\"", "}", "nil", "end"], "docstring": "The current revision for the cloned checkout.\n\n @return [String]", "docstring_tokens": ["The", "current", "revision", "for", "the", "cloned", "checkout", "."], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/fetchers/git_fetcher.rb#L184-L190", "partition": "test"} {"repo": "chef/omnibus", "path": "lib/omnibus/fetchers/git_fetcher.rb", "func_name": "Omnibus.GitFetcher.contains_revision?", "original_string": "def contains_revision?(rev)\n cmd = git(\"cat-file -t #{rev}\")\n cmd.stdout.strip == \"commit\"\n rescue CommandFailed\n log.debug(log_key) { \"unable to determine presence of commit #{rev}\" }\n false\n end", "language": "ruby", "code": "def contains_revision?(rev)\n cmd = git(\"cat-file -t #{rev}\")\n cmd.stdout.strip == \"commit\"\n rescue CommandFailed\n log.debug(log_key) { \"unable to determine presence of commit #{rev}\" }\n false\n end", "code_tokens": ["def", "contains_revision?", "(", "rev", ")", "cmd", "=", "git", "(", "\"cat-file -t #{rev}\"", ")", "cmd", ".", "stdout", ".", "strip", "==", "\"commit\"", "rescue", "CommandFailed", "log", ".", "debug", "(", "log_key", ")", "{", "\"unable to determine presence of commit #{rev}\"", "}", "false", "end"], "docstring": "Check if the current clone has the requested commit id.\n\n @return [true, false]", "docstring_tokens": ["Check", "if", "the", "current", "clone", "has", "the", "requested", "commit", "id", "."], "sha": "968307c129ee54416f5a4d07ca8f8ca2d2b12825", "url": "https://github.com/chef/omnibus/blob/968307c129ee54416f5a4d07ca8f8ca2d2b12825/lib/omnibus/fetchers/git_fetcher.rb#L197-L203", "partition": "test"} {"repo": "net-ssh/net-ssh", "path": "lib/net/ssh/transport/openssl.rb", "func_name": "OpenSSL.BN.to_ssh", "original_string": "def to_ssh\n if zero?\n return [0].pack(\"N\")\n else\n buf = to_s(2)\n if buf.getbyte(0)[7] == 1\n return [buf.length + 1, 0, buf].pack(\"NCA*\")\n else\n return [buf.length, buf].pack(\"NA*\")\n end\n end\n end", "language": "ruby", "code": "def to_ssh\n if zero?\n return [0].pack(\"N\")\n else\n buf = to_s(2)\n if buf.getbyte(0)[7] == 1\n return [buf.length + 1, 0, buf].pack(\"NCA*\")\n else\n return [buf.length, buf].pack(\"NA*\")\n end\n end\n end", "code_tokens": ["def", "to_ssh", "if", "zero?", "return", "[", "0", "]", ".", "pack", "(", "\"N\"", ")", "else", "buf", "=", "to_s", "(", "2", ")", "if", "buf", ".", "getbyte", "(", "0", ")", "[", "7", "]", "==", "1", "return", "[", "buf", ".", "length", "+", "1", ",", "0", ",", "buf", "]", ".", "pack", "(", "\"NCA*\"", ")", "else", "return", "[", "buf", ".", "length", ",", "buf", "]", ".", "pack", "(", "\"NA*\"", ")", "end", "end", "end"], "docstring": "Converts a BN object to a string. The format used is that which is\n required by the SSH2 protocol.", "docstring_tokens": ["Converts", "a", "BN", "object", "to", "a", "string", ".", "The", "format", "used", "is", "that", "which", "is", "required", "by", "the", "SSH2", "protocol", "."], "sha": "07d046d335986edc4b6d3a64360c46f7025c3164", "url": "https://github.com/net-ssh/net-ssh/blob/07d046d335986edc4b6d3a64360c46f7025c3164/lib/net/ssh/transport/openssl.rb#L12-L23", "partition": "test"} {"repo": "net-ssh/net-ssh", "path": "lib/net/ssh/transport/kex/diffie_hellman_group_exchange_sha1.rb", "func_name": "Net::SSH::Transport::Kex.DiffieHellmanGroupExchangeSHA1.compute_need_bits", "original_string": "def compute_need_bits\n # for Compatibility: OpenSSH requires (need_bits * 2 + 1) length of parameter\n need_bits = data[:need_bytes] * 8 * 2 + 1\n\n data[:minimum_dh_bits] ||= MINIMUM_BITS\n\n if need_bits < data[:minimum_dh_bits]\n need_bits = data[:minimum_dh_bits]\n elsif need_bits > MAXIMUM_BITS\n need_bits = MAXIMUM_BITS\n end\n\n data[:need_bits] = need_bits\n data[:need_bytes] = need_bits / 8\n end", "language": "ruby", "code": "def compute_need_bits\n # for Compatibility: OpenSSH requires (need_bits * 2 + 1) length of parameter\n need_bits = data[:need_bytes] * 8 * 2 + 1\n\n data[:minimum_dh_bits] ||= MINIMUM_BITS\n\n if need_bits < data[:minimum_dh_bits]\n need_bits = data[:minimum_dh_bits]\n elsif need_bits > MAXIMUM_BITS\n need_bits = MAXIMUM_BITS\n end\n\n data[:need_bits] = need_bits\n data[:need_bytes] = need_bits / 8\n end", "code_tokens": ["def", "compute_need_bits", "# for Compatibility: OpenSSH requires (need_bits * 2 + 1) length of parameter", "need_bits", "=", "data", "[", ":need_bytes", "]", "*", "8", "*", "2", "+", "1", "data", "[", ":minimum_dh_bits", "]", "||=", "MINIMUM_BITS", "if", "need_bits", "<", "data", "[", ":minimum_dh_bits", "]", "need_bits", "=", "data", "[", ":minimum_dh_bits", "]", "elsif", "need_bits", ">", "MAXIMUM_BITS", "need_bits", "=", "MAXIMUM_BITS", "end", "data", "[", ":need_bits", "]", "=", "need_bits", "data", "[", ":need_bytes", "]", "=", "need_bits", "/", "8", "end"], "docstring": "Compute the number of bits needed for the given number of bytes.", "docstring_tokens": ["Compute", "the", "number", "of", "bits", "needed", "for", "the", "given", "number", "of", "bytes", "."], "sha": "07d046d335986edc4b6d3a64360c46f7025c3164", "url": "https://github.com/net-ssh/net-ssh/blob/07d046d335986edc4b6d3a64360c46f7025c3164/lib/net/ssh/transport/kex/diffie_hellman_group_exchange_sha1.rb#L21-L35", "partition": "test"} {"repo": "net-ssh/net-ssh", "path": "lib/net/ssh/transport/kex/diffie_hellman_group_exchange_sha1.rb", "func_name": "Net::SSH::Transport::Kex.DiffieHellmanGroupExchangeSHA1.get_parameters", "original_string": "def get_parameters\n compute_need_bits\n\n # request the DH key parameters for the given number of bits.\n buffer = Net::SSH::Buffer.from(:byte, KEXDH_GEX_REQUEST, :long, data[:minimum_dh_bits],\n :long, data[:need_bits], :long, MAXIMUM_BITS)\n connection.send_message(buffer)\n\n buffer = connection.next_message\n raise Net::SSH::Exception, \"expected KEXDH_GEX_GROUP, got #{buffer.type}\" unless buffer.type == KEXDH_GEX_GROUP\n\n p = buffer.read_bignum\n g = buffer.read_bignum\n\n [p, g]\n end", "language": "ruby", "code": "def get_parameters\n compute_need_bits\n\n # request the DH key parameters for the given number of bits.\n buffer = Net::SSH::Buffer.from(:byte, KEXDH_GEX_REQUEST, :long, data[:minimum_dh_bits],\n :long, data[:need_bits], :long, MAXIMUM_BITS)\n connection.send_message(buffer)\n\n buffer = connection.next_message\n raise Net::SSH::Exception, \"expected KEXDH_GEX_GROUP, got #{buffer.type}\" unless buffer.type == KEXDH_GEX_GROUP\n\n p = buffer.read_bignum\n g = buffer.read_bignum\n\n [p, g]\n end", "code_tokens": ["def", "get_parameters", "compute_need_bits", "# request the DH key parameters for the given number of bits.", "buffer", "=", "Net", "::", "SSH", "::", "Buffer", ".", "from", "(", ":byte", ",", "KEXDH_GEX_REQUEST", ",", ":long", ",", "data", "[", ":minimum_dh_bits", "]", ",", ":long", ",", "data", "[", ":need_bits", "]", ",", ":long", ",", "MAXIMUM_BITS", ")", "connection", ".", "send_message", "(", "buffer", ")", "buffer", "=", "connection", ".", "next_message", "raise", "Net", "::", "SSH", "::", "Exception", ",", "\"expected KEXDH_GEX_GROUP, got #{buffer.type}\"", "unless", "buffer", ".", "type", "==", "KEXDH_GEX_GROUP", "p", "=", "buffer", ".", "read_bignum", "g", "=", "buffer", ".", "read_bignum", "[", "p", ",", "g", "]", "end"], "docstring": "Returns the DH key parameters for the given session.", "docstring_tokens": ["Returns", "the", "DH", "key", "parameters", "for", "the", "given", "session", "."], "sha": "07d046d335986edc4b6d3a64360c46f7025c3164", "url": "https://github.com/net-ssh/net-ssh/blob/07d046d335986edc4b6d3a64360c46f7025c3164/lib/net/ssh/transport/kex/diffie_hellman_group_exchange_sha1.rb#L38-L53", "partition": "test"} {"repo": "net-ssh/net-ssh", "path": "lib/net/ssh/transport/kex/diffie_hellman_group_exchange_sha1.rb", "func_name": "Net::SSH::Transport::Kex.DiffieHellmanGroupExchangeSHA1.build_signature_buffer", "original_string": "def build_signature_buffer(result)\n response = Net::SSH::Buffer.new\n response.write_string data[:client_version_string],\n data[:server_version_string],\n data[:client_algorithm_packet],\n data[:server_algorithm_packet],\n result[:key_blob]\n response.write_long MINIMUM_BITS,\n data[:need_bits],\n MAXIMUM_BITS\n response.write_bignum dh.p, dh.g, dh.pub_key,\n result[:server_dh_pubkey],\n result[:shared_secret]\n response\n end", "language": "ruby", "code": "def build_signature_buffer(result)\n response = Net::SSH::Buffer.new\n response.write_string data[:client_version_string],\n data[:server_version_string],\n data[:client_algorithm_packet],\n data[:server_algorithm_packet],\n result[:key_blob]\n response.write_long MINIMUM_BITS,\n data[:need_bits],\n MAXIMUM_BITS\n response.write_bignum dh.p, dh.g, dh.pub_key,\n result[:server_dh_pubkey],\n result[:shared_secret]\n response\n end", "code_tokens": ["def", "build_signature_buffer", "(", "result", ")", "response", "=", "Net", "::", "SSH", "::", "Buffer", ".", "new", "response", ".", "write_string", "data", "[", ":client_version_string", "]", ",", "data", "[", ":server_version_string", "]", ",", "data", "[", ":client_algorithm_packet", "]", ",", "data", "[", ":server_algorithm_packet", "]", ",", "result", "[", ":key_blob", "]", "response", ".", "write_long", "MINIMUM_BITS", ",", "data", "[", ":need_bits", "]", ",", "MAXIMUM_BITS", "response", ".", "write_bignum", "dh", ".", "p", ",", "dh", ".", "g", ",", "dh", ".", "pub_key", ",", "result", "[", ":server_dh_pubkey", "]", ",", "result", "[", ":shared_secret", "]", "response", "end"], "docstring": "Build the signature buffer to use when verifying a signature from\n the server.", "docstring_tokens": ["Build", "the", "signature", "buffer", "to", "use", "when", "verifying", "a", "signature", "from", "the", "server", "."], "sha": "07d046d335986edc4b6d3a64360c46f7025c3164", "url": "https://github.com/net-ssh/net-ssh/blob/07d046d335986edc4b6d3a64360c46f7025c3164/lib/net/ssh/transport/kex/diffie_hellman_group_exchange_sha1.rb#L62-L76", "partition": "test"} {"repo": "natritmeyer/site_prism", "path": "lib/site_prism/loadable.rb", "func_name": "SitePrism.Loadable.when_loaded", "original_string": "def when_loaded\n # Get original loaded value, in case we are nested\n # inside another when_loaded block.\n previously_loaded = loaded\n\n # Within the block, check (and cache) loaded?, to see whether the\n # page has indeed loaded according to the rules defined by the user.\n self.loaded = loaded?\n\n # If the page hasn't loaded. Then crash and return the error message.\n # If one isn't defined, just return the Error code.\n raise SitePrism::FailedLoadValidationError, load_error unless loaded\n\n # Return the yield value of the block if one was supplied.\n yield self if block_given?\n ensure\n self.loaded = previously_loaded\n end", "language": "ruby", "code": "def when_loaded\n # Get original loaded value, in case we are nested\n # inside another when_loaded block.\n previously_loaded = loaded\n\n # Within the block, check (and cache) loaded?, to see whether the\n # page has indeed loaded according to the rules defined by the user.\n self.loaded = loaded?\n\n # If the page hasn't loaded. Then crash and return the error message.\n # If one isn't defined, just return the Error code.\n raise SitePrism::FailedLoadValidationError, load_error unless loaded\n\n # Return the yield value of the block if one was supplied.\n yield self if block_given?\n ensure\n self.loaded = previously_loaded\n end", "code_tokens": ["def", "when_loaded", "# Get original loaded value, in case we are nested", "# inside another when_loaded block.", "previously_loaded", "=", "loaded", "# Within the block, check (and cache) loaded?, to see whether the", "# page has indeed loaded according to the rules defined by the user.", "self", ".", "loaded", "=", "loaded?", "# If the page hasn't loaded. Then crash and return the error message.", "# If one isn't defined, just return the Error code.", "raise", "SitePrism", "::", "FailedLoadValidationError", ",", "load_error", "unless", "loaded", "# Return the yield value of the block if one was supplied.", "yield", "self", "if", "block_given?", "ensure", "self", ".", "loaded", "=", "previously_loaded", "end"], "docstring": "Executes the given block after the page is loaded.\n\n The loadable object instance is yielded into the block.", "docstring_tokens": ["Executes", "the", "given", "block", "after", "the", "page", "is", "loaded", "."], "sha": "f208a6f6b44744869fe170168d326927f6077e94", "url": "https://github.com/natritmeyer/site_prism/blob/f208a6f6b44744869fe170168d326927f6077e94/lib/site_prism/loadable.rb#L57-L74", "partition": "test"} {"repo": "natritmeyer/site_prism", "path": "lib/site_prism/loadable.rb", "func_name": "SitePrism.Loadable.load_validations_pass?", "original_string": "def load_validations_pass?\n self.class.load_validations.all? do |validation|\n passed, message = instance_eval(&validation)\n\n self.load_error = message if message && !passed\n passed\n end\n end", "language": "ruby", "code": "def load_validations_pass?\n self.class.load_validations.all? do |validation|\n passed, message = instance_eval(&validation)\n\n self.load_error = message if message && !passed\n passed\n end\n end", "code_tokens": ["def", "load_validations_pass?", "self", ".", "class", ".", "load_validations", ".", "all?", "do", "|", "validation", "|", "passed", ",", "message", "=", "instance_eval", "(", "validation", ")", "self", ".", "load_error", "=", "message", "if", "message", "&&", "!", "passed", "passed", "end", "end"], "docstring": "If any load validations from page subclasses returns false,\n immediately return false.", "docstring_tokens": ["If", "any", "load", "validations", "from", "page", "subclasses", "returns", "false", "immediately", "return", "false", "."], "sha": "f208a6f6b44744869fe170168d326927f6077e94", "url": "https://github.com/natritmeyer/site_prism/blob/f208a6f6b44744869fe170168d326927f6077e94/lib/site_prism/loadable.rb#L94-L101", "partition": "test"} {"repo": "natritmeyer/site_prism", "path": "lib/site_prism/dsl.rb", "func_name": "SitePrism.DSL.raise_if_block", "original_string": "def raise_if_block(obj, name, has_block, type)\n return unless has_block\n\n SitePrism.logger.debug(\"Type passed in: #{type}\")\n SitePrism.logger.warn('section / iFrame can only accept blocks.')\n SitePrism.logger.error(\"#{obj.class}##{name} does not accept blocks\")\n\n raise SitePrism::UnsupportedBlockError\n end", "language": "ruby", "code": "def raise_if_block(obj, name, has_block, type)\n return unless has_block\n\n SitePrism.logger.debug(\"Type passed in: #{type}\")\n SitePrism.logger.warn('section / iFrame can only accept blocks.')\n SitePrism.logger.error(\"#{obj.class}##{name} does not accept blocks\")\n\n raise SitePrism::UnsupportedBlockError\n end", "code_tokens": ["def", "raise_if_block", "(", "obj", ",", "name", ",", "has_block", ",", "type", ")", "return", "unless", "has_block", "SitePrism", ".", "logger", ".", "debug", "(", "\"Type passed in: #{type}\"", ")", "SitePrism", ".", "logger", ".", "warn", "(", "'section / iFrame can only accept blocks.'", ")", "SitePrism", ".", "logger", ".", "error", "(", "\"#{obj.class}##{name} does not accept blocks\"", ")", "raise", "SitePrism", "::", "UnsupportedBlockError", "end"], "docstring": "Prevent users from calling methods with blocks when they shouldn't be.\n\n Example (Triggering error):\n\n class MyPage\n element :sample, '.css-locator' do\n puts \"This won't be output\"\n end\n end\n\n At runtime this will generate a `SitePrism::UnsupportedBlockError`\n\n The only DSL keywords that can use blocks are :section and :iframe", "docstring_tokens": ["Prevent", "users", "from", "calling", "methods", "with", "blocks", "when", "they", "shouldn", "t", "be", "."], "sha": "f208a6f6b44744869fe170168d326927f6077e94", "url": "https://github.com/natritmeyer/site_prism/blob/f208a6f6b44744869fe170168d326927f6077e94/lib/site_prism/dsl.rb#L29-L37", "partition": "test"} {"repo": "natritmeyer/site_prism", "path": "lib/site_prism/dsl.rb", "func_name": "SitePrism.DSL.merge_args", "original_string": "def merge_args(find_args, runtime_args, visibility_args = {})\n find_args = find_args.dup\n runtime_args = runtime_args.dup\n options = visibility_args.dup\n SitePrism.logger.debug(\"Initial args: #{find_args}, #{runtime_args}.\")\n\n recombine_args(find_args, runtime_args, options)\n\n return [*find_args, *runtime_args] if options.empty?\n\n [*find_args, *runtime_args, options]\n end", "language": "ruby", "code": "def merge_args(find_args, runtime_args, visibility_args = {})\n find_args = find_args.dup\n runtime_args = runtime_args.dup\n options = visibility_args.dup\n SitePrism.logger.debug(\"Initial args: #{find_args}, #{runtime_args}.\")\n\n recombine_args(find_args, runtime_args, options)\n\n return [*find_args, *runtime_args] if options.empty?\n\n [*find_args, *runtime_args, options]\n end", "code_tokens": ["def", "merge_args", "(", "find_args", ",", "runtime_args", ",", "visibility_args", "=", "{", "}", ")", "find_args", "=", "find_args", ".", "dup", "runtime_args", "=", "runtime_args", ".", "dup", "options", "=", "visibility_args", ".", "dup", "SitePrism", ".", "logger", ".", "debug", "(", "\"Initial args: #{find_args}, #{runtime_args}.\"", ")", "recombine_args", "(", "find_args", ",", "runtime_args", ",", "options", ")", "return", "[", "find_args", ",", "runtime_args", "]", "if", "options", ".", "empty?", "[", "find_args", ",", "runtime_args", ",", "options", "]", "end"], "docstring": "Sanitize method called before calling any SitePrism DSL method or\n meta-programmed method. This ensures that the Capybara query is correct.\n\n Accepts any combination of arguments sent at DSL definition or runtime\n and combines them in such a way that Capybara can operate with them.", "docstring_tokens": ["Sanitize", "method", "called", "before", "calling", "any", "SitePrism", "DSL", "method", "or", "meta", "-", "programmed", "method", ".", "This", "ensures", "that", "the", "Capybara", "query", "is", "correct", "."], "sha": "f208a6f6b44744869fe170168d326927f6077e94", "url": "https://github.com/natritmeyer/site_prism/blob/f208a6f6b44744869fe170168d326927f6077e94/lib/site_prism/dsl.rb#L44-L55", "partition": "test"} {"repo": "natritmeyer/site_prism", "path": "lib/site_prism/dsl.rb", "func_name": "SitePrism.DSL.recombine_args", "original_string": "def recombine_args(find_args, runtime_args, options)\n options.merge!(find_args.pop) if find_args.last.is_a? Hash\n options.merge!(runtime_args.pop) if runtime_args.last.is_a? Hash\n options[:wait] = wait_time unless wait_key_present?(options)\n end", "language": "ruby", "code": "def recombine_args(find_args, runtime_args, options)\n options.merge!(find_args.pop) if find_args.last.is_a? Hash\n options.merge!(runtime_args.pop) if runtime_args.last.is_a? Hash\n options[:wait] = wait_time unless wait_key_present?(options)\n end", "code_tokens": ["def", "recombine_args", "(", "find_args", ",", "runtime_args", ",", "options", ")", "options", ".", "merge!", "(", "find_args", ".", "pop", ")", "if", "find_args", ".", "last", ".", "is_a?", "Hash", "options", ".", "merge!", "(", "runtime_args", ".", "pop", ")", "if", "runtime_args", ".", "last", ".", "is_a?", "Hash", "options", "[", ":wait", "]", "=", "wait_time", "unless", "wait_key_present?", "(", "options", ")", "end"], "docstring": "Options re-combiner. This takes the original inputs and combines\n them such that there is only one hash passed as a final argument\n to Capybara.\n\n If the hash is empty, then the hash is omitted from the payload sent\n to Capybara, and the find / runtime arguments are sent alone.", "docstring_tokens": ["Options", "re", "-", "combiner", ".", "This", "takes", "the", "original", "inputs", "and", "combines", "them", "such", "that", "there", "is", "only", "one", "hash", "passed", "as", "a", "final", "argument", "to", "Capybara", "."], "sha": "f208a6f6b44744869fe170168d326927f6077e94", "url": "https://github.com/natritmeyer/site_prism/blob/f208a6f6b44744869fe170168d326927f6077e94/lib/site_prism/dsl.rb#L63-L67", "partition": "test"} {"repo": "natritmeyer/site_prism", "path": "lib/site_prism/element_checker.rb", "func_name": "SitePrism.ElementChecker.elements_to_check", "original_string": "def elements_to_check\n if _expected_items\n SitePrism.logger.debug('Expected Items has been set.')\n _mapped_items.select { |item_name| _expected_items.include?(item_name) }\n else\n _mapped_items\n end\n end", "language": "ruby", "code": "def elements_to_check\n if _expected_items\n SitePrism.logger.debug('Expected Items has been set.')\n _mapped_items.select { |item_name| _expected_items.include?(item_name) }\n else\n _mapped_items\n end\n end", "code_tokens": ["def", "elements_to_check", "if", "_expected_items", "SitePrism", ".", "logger", ".", "debug", "(", "'Expected Items has been set.'", ")", "_mapped_items", ".", "select", "{", "|", "item_name", "|", "_expected_items", ".", "include?", "(", "item_name", ")", "}", "else", "_mapped_items", "end", "end"], "docstring": "If the page or section has expected_items set, return expected_items\n that are mapped; otherwise just return the list of all mapped_items", "docstring_tokens": ["If", "the", "page", "or", "section", "has", "expected_items", "set", "return", "expected_items", "that", "are", "mapped", ";", "otherwise", "just", "return", "the", "list", "of", "all", "mapped_items"], "sha": "f208a6f6b44744869fe170168d326927f6077e94", "url": "https://github.com/natritmeyer/site_prism/blob/f208a6f6b44744869fe170168d326927f6077e94/lib/site_prism/element_checker.rb#L41-L48", "partition": "test"} {"repo": "natritmeyer/site_prism", "path": "lib/site_prism/addressable_url_matcher.rb", "func_name": "SitePrism.AddressableUrlMatcher.matches?", "original_string": "def matches?(url, expected_mappings = {})\n actual_mappings = mappings(url)\n return false unless actual_mappings\n\n expected_mappings.empty? ||\n all_expected_mappings_match?(expected_mappings, actual_mappings)\n end", "language": "ruby", "code": "def matches?(url, expected_mappings = {})\n actual_mappings = mappings(url)\n return false unless actual_mappings\n\n expected_mappings.empty? ||\n all_expected_mappings_match?(expected_mappings, actual_mappings)\n end", "code_tokens": ["def", "matches?", "(", "url", ",", "expected_mappings", "=", "{", "}", ")", "actual_mappings", "=", "mappings", "(", "url", ")", "return", "false", "unless", "actual_mappings", "expected_mappings", ".", "empty?", "||", "all_expected_mappings_match?", "(", "expected_mappings", ",", "actual_mappings", ")", "end"], "docstring": "Determine whether URL matches our pattern, and\n optionally whether the extracted mappings match\n a hash of expected values. You can specify values\n as strings, numbers or regular expressions.", "docstring_tokens": ["Determine", "whether", "URL", "matches", "our", "pattern", "and", "optionally", "whether", "the", "extracted", "mappings", "match", "a", "hash", "of", "expected", "values", ".", "You", "can", "specify", "values", "as", "strings", "numbers", "or", "regular", "expressions", "."], "sha": "f208a6f6b44744869fe170168d326927f6077e94", "url": "https://github.com/natritmeyer/site_prism/blob/f208a6f6b44744869fe170168d326927f6077e94/lib/site_prism/addressable_url_matcher.rb#L33-L39", "partition": "test"} {"repo": "natritmeyer/site_prism", "path": "lib/site_prism/addressable_url_matcher.rb", "func_name": "SitePrism.AddressableUrlMatcher.component_matches", "original_string": "def component_matches(component, uri)\n component_template = component_templates[component]\n return {} unless component_template\n\n component_url = uri.public_send(component).to_s\n mappings = component_template.extract(component_url)\n return mappings if mappings\n\n # to support Addressable's expansion of queries\n # ensure it's parsing the fragment as appropriate (e.g. {?params*})\n prefix = component_prefixes[component]\n return nil unless prefix\n\n component_template.extract(prefix + component_url)\n end", "language": "ruby", "code": "def component_matches(component, uri)\n component_template = component_templates[component]\n return {} unless component_template\n\n component_url = uri.public_send(component).to_s\n mappings = component_template.extract(component_url)\n return mappings if mappings\n\n # to support Addressable's expansion of queries\n # ensure it's parsing the fragment as appropriate (e.g. {?params*})\n prefix = component_prefixes[component]\n return nil unless prefix\n\n component_template.extract(prefix + component_url)\n end", "code_tokens": ["def", "component_matches", "(", "component", ",", "uri", ")", "component_template", "=", "component_templates", "[", "component", "]", "return", "{", "}", "unless", "component_template", "component_url", "=", "uri", ".", "public_send", "(", "component", ")", ".", "to_s", "mappings", "=", "component_template", ".", "extract", "(", "component_url", ")", "return", "mappings", "if", "mappings", "# to support Addressable's expansion of queries", "# ensure it's parsing the fragment as appropriate (e.g. {?params*})", "prefix", "=", "component_prefixes", "[", "component", "]", "return", "nil", "unless", "prefix", "component_template", ".", "extract", "(", "prefix", "+", "component_url", ")", "end"], "docstring": "Returns empty hash if the template omits the component or a set of\n substitutions if the provided URI component matches the template\n component or nil if the match fails.", "docstring_tokens": ["Returns", "empty", "hash", "if", "the", "template", "omits", "the", "component", "or", "a", "set", "of", "substitutions", "if", "the", "provided", "URI", "component", "matches", "the", "template", "component", "or", "nil", "if", "the", "match", "fails", "."], "sha": "f208a6f6b44744869fe170168d326927f6077e94", "url": "https://github.com/natritmeyer/site_prism/blob/f208a6f6b44744869fe170168d326927f6077e94/lib/site_prism/addressable_url_matcher.rb#L77-L91", "partition": "test"} {"repo": "natritmeyer/site_prism", "path": "lib/site_prism/addressable_url_matcher.rb", "func_name": "SitePrism.AddressableUrlMatcher.to_substituted_uri", "original_string": "def to_substituted_uri\n url = pattern\n substitutions.each_pair { |slug, value| url = url.sub(slug, value) }\n begin\n Addressable::URI.parse(url)\n rescue Addressable::URI::InvalidURIError\n SitePrism.logger.warn(\"Ensure you don't use templated port numbers.\")\n raise SitePrism::InvalidUrlMatcherError\n end\n end", "language": "ruby", "code": "def to_substituted_uri\n url = pattern\n substitutions.each_pair { |slug, value| url = url.sub(slug, value) }\n begin\n Addressable::URI.parse(url)\n rescue Addressable::URI::InvalidURIError\n SitePrism.logger.warn(\"Ensure you don't use templated port numbers.\")\n raise SitePrism::InvalidUrlMatcherError\n end\n end", "code_tokens": ["def", "to_substituted_uri", "url", "=", "pattern", "substitutions", ".", "each_pair", "{", "|", "slug", ",", "value", "|", "url", "=", "url", ".", "sub", "(", "slug", ",", "value", ")", "}", "begin", "Addressable", "::", "URI", ".", "parse", "(", "url", ")", "rescue", "Addressable", "::", "URI", "::", "InvalidURIError", "SitePrism", ".", "logger", ".", "warn", "(", "\"Ensure you don't use templated port numbers.\"", ")", "raise", "SitePrism", "::", "InvalidUrlMatcherError", "end", "end"], "docstring": "Convert the pattern into an Addressable URI by substituting\n the template slugs with nonsense strings.", "docstring_tokens": ["Convert", "the", "pattern", "into", "an", "Addressable", "URI", "by", "substituting", "the", "template", "slugs", "with", "nonsense", "strings", "."], "sha": "f208a6f6b44744869fe170168d326927f6077e94", "url": "https://github.com/natritmeyer/site_prism/blob/f208a6f6b44744869fe170168d326927f6077e94/lib/site_prism/addressable_url_matcher.rb#L95-L104", "partition": "test"} {"repo": "natritmeyer/site_prism", "path": "lib/site_prism/addressable_url_matcher.rb", "func_name": "SitePrism.AddressableUrlMatcher.substitution_value", "original_string": "def substitution_value(index)\n sha = Digest::SHA1.digest(index.to_s)\n Base64.urlsafe_encode64(sha).gsub(/[^A-Za-z]/, '')[0..5]\n end", "language": "ruby", "code": "def substitution_value(index)\n sha = Digest::SHA1.digest(index.to_s)\n Base64.urlsafe_encode64(sha).gsub(/[^A-Za-z]/, '')[0..5]\n end", "code_tokens": ["def", "substitution_value", "(", "index", ")", "sha", "=", "Digest", "::", "SHA1", ".", "digest", "(", "index", ".", "to_s", ")", "Base64", ".", "urlsafe_encode64", "(", "sha", ")", ".", "gsub", "(", "/", "/", ",", "''", ")", "[", "0", "..", "5", "]", "end"], "docstring": "Generate a repeatable 5 character uniform alphabetical nonsense string\n to allow parsing as a URI", "docstring_tokens": ["Generate", "a", "repeatable", "5", "character", "uniform", "alphabetical", "nonsense", "string", "to", "allow", "parsing", "as", "a", "URI"], "sha": "f208a6f6b44744869fe170168d326927f6077e94", "url": "https://github.com/natritmeyer/site_prism/blob/f208a6f6b44744869fe170168d326927f6077e94/lib/site_prism/addressable_url_matcher.rb#L138-L141", "partition": "test"} {"repo": "Shopify/job-iteration", "path": "lib/job-iteration/enumerator_builder.rb", "func_name": "JobIteration.EnumeratorBuilder.build_times_enumerator", "original_string": "def build_times_enumerator(number, cursor:)\n raise ArgumentError, \"First argument must be an Integer\" unless number.is_a?(Integer)\n wrap(self, build_array_enumerator(number.times.to_a, cursor: cursor))\n end", "language": "ruby", "code": "def build_times_enumerator(number, cursor:)\n raise ArgumentError, \"First argument must be an Integer\" unless number.is_a?(Integer)\n wrap(self, build_array_enumerator(number.times.to_a, cursor: cursor))\n end", "code_tokens": ["def", "build_times_enumerator", "(", "number", ",", "cursor", ":", ")", "raise", "ArgumentError", ",", "\"First argument must be an Integer\"", "unless", "number", ".", "is_a?", "(", "Integer", ")", "wrap", "(", "self", ",", "build_array_enumerator", "(", "number", ".", "times", ".", "to_a", ",", "cursor", ":", "cursor", ")", ")", "end"], "docstring": "Builds Enumerator objects that iterates N times and yields number starting from zero.", "docstring_tokens": ["Builds", "Enumerator", "objects", "that", "iterates", "N", "times", "and", "yields", "number", "starting", "from", "zero", "."], "sha": "443f2095eece2c179c4bd182ef1e7b4398f8875a", "url": "https://github.com/Shopify/job-iteration/blob/443f2095eece2c179c4bd182ef1e7b4398f8875a/lib/job-iteration/enumerator_builder.rb#L41-L44", "partition": "test"} {"repo": "Shopify/job-iteration", "path": "lib/job-iteration/enumerator_builder.rb", "func_name": "JobIteration.EnumeratorBuilder.build_array_enumerator", "original_string": "def build_array_enumerator(enumerable, cursor:)\n unless enumerable.is_a?(Array)\n raise ArgumentError, \"enumerable must be an Array\"\n end\n if enumerable.any? { |i| defined?(ActiveRecord) && i.is_a?(ActiveRecord::Base) }\n raise ArgumentError, \"array cannot contain ActiveRecord objects\"\n end\n drop =\n if cursor.nil?\n 0\n else\n cursor + 1\n end\n\n wrap(self, enumerable.each_with_index.drop(drop).to_enum { enumerable.size })\n end", "language": "ruby", "code": "def build_array_enumerator(enumerable, cursor:)\n unless enumerable.is_a?(Array)\n raise ArgumentError, \"enumerable must be an Array\"\n end\n if enumerable.any? { |i| defined?(ActiveRecord) && i.is_a?(ActiveRecord::Base) }\n raise ArgumentError, \"array cannot contain ActiveRecord objects\"\n end\n drop =\n if cursor.nil?\n 0\n else\n cursor + 1\n end\n\n wrap(self, enumerable.each_with_index.drop(drop).to_enum { enumerable.size })\n end", "code_tokens": ["def", "build_array_enumerator", "(", "enumerable", ",", "cursor", ":", ")", "unless", "enumerable", ".", "is_a?", "(", "Array", ")", "raise", "ArgumentError", ",", "\"enumerable must be an Array\"", "end", "if", "enumerable", ".", "any?", "{", "|", "i", "|", "defined?", "(", "ActiveRecord", ")", "&&", "i", ".", "is_a?", "(", "ActiveRecord", "::", "Base", ")", "}", "raise", "ArgumentError", ",", "\"array cannot contain ActiveRecord objects\"", "end", "drop", "=", "if", "cursor", ".", "nil?", "0", "else", "cursor", "+", "1", "end", "wrap", "(", "self", ",", "enumerable", ".", "each_with_index", ".", "drop", "(", "drop", ")", ".", "to_enum", "{", "enumerable", ".", "size", "}", ")", "end"], "docstring": "Builds Enumerator object from a given array, using +cursor+ as an offset.", "docstring_tokens": ["Builds", "Enumerator", "object", "from", "a", "given", "array", "using", "+", "cursor", "+", "as", "an", "offset", "."], "sha": "443f2095eece2c179c4bd182ef1e7b4398f8875a", "url": "https://github.com/Shopify/job-iteration/blob/443f2095eece2c179c4bd182ef1e7b4398f8875a/lib/job-iteration/enumerator_builder.rb#L47-L62", "partition": "test"} {"repo": "Shopify/job-iteration", "path": "lib/job-iteration/enumerator_builder.rb", "func_name": "JobIteration.EnumeratorBuilder.build_lock_queue_enumerator", "original_string": "def build_lock_queue_enumerator(lock_queue, at_most_once:)\n unless lock_queue.is_a?(BackgroundQueue::LockQueue::RedisQueue) ||\n lock_queue.is_a?(BackgroundQueue::LockQueue::RolloutRedisQueue)\n raise ArgumentError, \"an argument to #build_lock_queue_enumerator must be a LockQueue\"\n end\n wrap(self, BackgroundQueue::LockQueueEnumerator.new(lock_queue, at_most_once: at_most_once).to_enum)\n end", "language": "ruby", "code": "def build_lock_queue_enumerator(lock_queue, at_most_once:)\n unless lock_queue.is_a?(BackgroundQueue::LockQueue::RedisQueue) ||\n lock_queue.is_a?(BackgroundQueue::LockQueue::RolloutRedisQueue)\n raise ArgumentError, \"an argument to #build_lock_queue_enumerator must be a LockQueue\"\n end\n wrap(self, BackgroundQueue::LockQueueEnumerator.new(lock_queue, at_most_once: at_most_once).to_enum)\n end", "code_tokens": ["def", "build_lock_queue_enumerator", "(", "lock_queue", ",", "at_most_once", ":", ")", "unless", "lock_queue", ".", "is_a?", "(", "BackgroundQueue", "::", "LockQueue", "::", "RedisQueue", ")", "||", "lock_queue", ".", "is_a?", "(", "BackgroundQueue", "::", "LockQueue", "::", "RolloutRedisQueue", ")", "raise", "ArgumentError", ",", "\"an argument to #build_lock_queue_enumerator must be a LockQueue\"", "end", "wrap", "(", "self", ",", "BackgroundQueue", "::", "LockQueueEnumerator", ".", "new", "(", "lock_queue", ",", "at_most_once", ":", "at_most_once", ")", ".", "to_enum", ")", "end"], "docstring": "Builds Enumerator from a lock queue instance that belongs to a job.\n The helper is only to be used from jobs that use LockQueue module.", "docstring_tokens": ["Builds", "Enumerator", "from", "a", "lock", "queue", "instance", "that", "belongs", "to", "a", "job", ".", "The", "helper", "is", "only", "to", "be", "used", "from", "jobs", "that", "use", "LockQueue", "module", "."], "sha": "443f2095eece2c179c4bd182ef1e7b4398f8875a", "url": "https://github.com/Shopify/job-iteration/blob/443f2095eece2c179c4bd182ef1e7b4398f8875a/lib/job-iteration/enumerator_builder.rb#L66-L72", "partition": "test"} {"repo": "Shopify/job-iteration", "path": "lib/job-iteration/enumerator_builder.rb", "func_name": "JobIteration.EnumeratorBuilder.build_active_record_enumerator_on_records", "original_string": "def build_active_record_enumerator_on_records(scope, cursor:, **args)\n enum = build_active_record_enumerator(\n scope,\n cursor: cursor,\n **args\n ).records\n wrap(self, enum)\n end", "language": "ruby", "code": "def build_active_record_enumerator_on_records(scope, cursor:, **args)\n enum = build_active_record_enumerator(\n scope,\n cursor: cursor,\n **args\n ).records\n wrap(self, enum)\n end", "code_tokens": ["def", "build_active_record_enumerator_on_records", "(", "scope", ",", "cursor", ":", ",", "**", "args", ")", "enum", "=", "build_active_record_enumerator", "(", "scope", ",", "cursor", ":", "cursor", ",", "**", "args", ")", ".", "records", "wrap", "(", "self", ",", "enum", ")", "end"], "docstring": "Builds Enumerator from Active Record Relation. Each Enumerator tick moves the cursor one row forward.\n\n +columns:+ argument is used to build the actual query for iteration. +columns+: defaults to primary key:\n\n 1) SELECT * FROM users ORDER BY id LIMIT 100\n\n When iteration is resumed, +cursor:+ and +columns:+ values will be used to continue from the point\n where iteration stopped:\n\n 2) SELECT * FROM users WHERE id > $CURSOR ORDER BY id LIMIT 100\n\n +columns:+ can also take more than one column. In that case, +cursor+ will contain serialized values\n of all columns at the point where iteration stopped.\n\n Consider this example with +columns: [:created_at, :id]+. Here's the query will use on the first iteration:\n\n 1) SELECT * FROM `products` ORDER BY created_at, id LIMIT 100\n\n And the query on the next iteration:\n\n 2) SELECT * FROM `products`\n WHERE (created_at > '$LAST_CREATED_AT_CURSOR'\n OR (created_at = '$LAST_CREATED_AT_CURSOR' AND (id > '$LAST_ID_CURSOR')))\n ORDER BY created_at, id LIMIT 100", "docstring_tokens": ["Builds", "Enumerator", "from", "Active", "Record", "Relation", ".", "Each", "Enumerator", "tick", "moves", "the", "cursor", "one", "row", "forward", "."], "sha": "443f2095eece2c179c4bd182ef1e7b4398f8875a", "url": "https://github.com/Shopify/job-iteration/blob/443f2095eece2c179c4bd182ef1e7b4398f8875a/lib/job-iteration/enumerator_builder.rb#L98-L105", "partition": "test"} {"repo": "Shopify/job-iteration", "path": "lib/job-iteration/enumerator_builder.rb", "func_name": "JobIteration.EnumeratorBuilder.build_active_record_enumerator_on_batches", "original_string": "def build_active_record_enumerator_on_batches(scope, cursor:, **args)\n enum = build_active_record_enumerator(\n scope,\n cursor: cursor,\n **args\n ).batches\n wrap(self, enum)\n end", "language": "ruby", "code": "def build_active_record_enumerator_on_batches(scope, cursor:, **args)\n enum = build_active_record_enumerator(\n scope,\n cursor: cursor,\n **args\n ).batches\n wrap(self, enum)\n end", "code_tokens": ["def", "build_active_record_enumerator_on_batches", "(", "scope", ",", "cursor", ":", ",", "**", "args", ")", "enum", "=", "build_active_record_enumerator", "(", "scope", ",", "cursor", ":", "cursor", ",", "**", "args", ")", ".", "batches", "wrap", "(", "self", ",", "enum", ")", "end"], "docstring": "Builds Enumerator from Active Record Relation and enumerates on batches.\n Each Enumerator tick moves the cursor +batch_size+ rows forward.\n\n +batch_size:+ sets how many records will be fetched in one batch. Defaults to 100.\n\n For the rest of arguments, see documentation for #build_active_record_enumerator_on_records", "docstring_tokens": ["Builds", "Enumerator", "from", "Active", "Record", "Relation", "and", "enumerates", "on", "batches", ".", "Each", "Enumerator", "tick", "moves", "the", "cursor", "+", "batch_size", "+", "rows", "forward", "."], "sha": "443f2095eece2c179c4bd182ef1e7b4398f8875a", "url": "https://github.com/Shopify/job-iteration/blob/443f2095eece2c179c4bd182ef1e7b4398f8875a/lib/job-iteration/enumerator_builder.rb#L113-L120", "partition": "test"} {"repo": "Shopify/job-iteration", "path": "lib/job-iteration/csv_enumerator.rb", "func_name": "JobIteration.CsvEnumerator.batches", "original_string": "def batches(batch_size:, cursor:)\n @csv.lazy\n .each_slice(batch_size)\n .each_with_index\n .drop(cursor.to_i)\n .to_enum { (count_rows_in_file.to_f / batch_size).ceil }\n end", "language": "ruby", "code": "def batches(batch_size:, cursor:)\n @csv.lazy\n .each_slice(batch_size)\n .each_with_index\n .drop(cursor.to_i)\n .to_enum { (count_rows_in_file.to_f / batch_size).ceil }\n end", "code_tokens": ["def", "batches", "(", "batch_size", ":", ",", "cursor", ":", ")", "@csv", ".", "lazy", ".", "each_slice", "(", "batch_size", ")", ".", "each_with_index", ".", "drop", "(", "cursor", ".", "to_i", ")", ".", "to_enum", "{", "(", "count_rows_in_file", ".", "to_f", "/", "batch_size", ")", ".", "ceil", "}", "end"], "docstring": "Constructs a enumerator on batches of CSV rows\n @return [Enumerator] Enumerator instance", "docstring_tokens": ["Constructs", "a", "enumerator", "on", "batches", "of", "CSV", "rows"], "sha": "443f2095eece2c179c4bd182ef1e7b4398f8875a", "url": "https://github.com/Shopify/job-iteration/blob/443f2095eece2c179c4bd182ef1e7b4398f8875a/lib/job-iteration/csv_enumerator.rb#L41-L47", "partition": "test"} {"repo": "paper-trail-gem/paper_trail", "path": "lib/paper_trail/version_concern.rb", "func_name": "PaperTrail.VersionConcern.reify", "original_string": "def reify(options = {})\n unless self.class.column_names.include? \"object\"\n raise \"reify can't be called without an object column\"\n end\n return nil if object.nil?\n ::PaperTrail::Reifier.reify(self, options)\n end", "language": "ruby", "code": "def reify(options = {})\n unless self.class.column_names.include? \"object\"\n raise \"reify can't be called without an object column\"\n end\n return nil if object.nil?\n ::PaperTrail::Reifier.reify(self, options)\n end", "code_tokens": ["def", "reify", "(", "options", "=", "{", "}", ")", "unless", "self", ".", "class", ".", "column_names", ".", "include?", "\"object\"", "raise", "\"reify can't be called without an object column\"", "end", "return", "nil", "if", "object", ".", "nil?", "::", "PaperTrail", "::", "Reifier", ".", "reify", "(", "self", ",", "options", ")", "end"], "docstring": "Restore the item from this version.\n\n Optionally this can also restore all :has_one and :has_many (including\n has_many :through) associations as they were \"at the time\", if they are\n also being versioned by PaperTrail.\n\n Options:\n\n - :has_one\n - `true` - Also reify has_one associations.\n - `false - Default.\n - :has_many\n - `true` - Also reify has_many and has_many :through associations.\n - `false` - Default.\n - :mark_for_destruction\n - `true` - Mark the has_one/has_many associations that did not exist in\n the reified version for destruction, instead of removing them.\n - `false` - Default. Useful for persisting the reified version.\n - :dup\n - `false` - Default.\n - `true` - Always create a new object instance. Useful for\n comparing two versions of the same object.\n - :unversioned_attributes\n - `:nil` - Default. Attributes undefined in version record are set to\n nil in reified record.\n - `:preserve` - Attributes undefined in version record are not modified.", "docstring_tokens": ["Restore", "the", "item", "from", "this", "version", "."], "sha": "5fee6f3d4c5ff56c36981711d93b5742465304c2", "url": "https://github.com/paper-trail-gem/paper_trail/blob/5fee6f3d4c5ff56c36981711d93b5742465304c2/lib/paper_trail/version_concern.rb#L233-L239", "partition": "test"} {"repo": "paper-trail-gem/paper_trail", "path": "lib/paper_trail/version_concern.rb", "func_name": "PaperTrail.VersionConcern.version_limit", "original_string": "def version_limit\n if self.class.item_subtype_column_present?\n klass = (item_subtype || item_type).constantize\n if klass&.paper_trail_options&.key?(:limit)\n return klass.paper_trail_options[:limit]\n end\n end\n PaperTrail.config.version_limit\n end", "language": "ruby", "code": "def version_limit\n if self.class.item_subtype_column_present?\n klass = (item_subtype || item_type).constantize\n if klass&.paper_trail_options&.key?(:limit)\n return klass.paper_trail_options[:limit]\n end\n end\n PaperTrail.config.version_limit\n end", "code_tokens": ["def", "version_limit", "if", "self", ".", "class", ".", "item_subtype_column_present?", "klass", "=", "(", "item_subtype", "||", "item_type", ")", ".", "constantize", "if", "klass", "&.", "paper_trail_options", "&.", "key?", "(", ":limit", ")", "return", "klass", ".", "paper_trail_options", "[", ":limit", "]", "end", "end", "PaperTrail", ".", "config", ".", "version_limit", "end"], "docstring": "See docs section 2.e. Limiting the Number of Versions Created.\n The version limit can be global or per-model.\n\n @api private\n\n TODO: Duplication: similar `constantize` in Reifier#version_reification_class", "docstring_tokens": ["See", "docs", "section", "2", ".", "e", ".", "Limiting", "the", "Number", "of", "Versions", "Created", ".", "The", "version", "limit", "can", "be", "global", "or", "per", "-", "model", "."], "sha": "5fee6f3d4c5ff56c36981711d93b5742465304c2", "url": "https://github.com/paper-trail-gem/paper_trail/blob/5fee6f3d4c5ff56c36981711d93b5742465304c2/lib/paper_trail/version_concern.rb#L351-L359", "partition": "test"} {"repo": "paper-trail-gem/paper_trail", "path": "lib/paper_trail/model_config.rb", "func_name": "PaperTrail.ModelConfig.on_create", "original_string": "def on_create\n @model_class.after_create { |r|\n r.paper_trail.record_create if r.paper_trail.save_version?\n }\n return if @model_class.paper_trail_options[:on].include?(:create)\n @model_class.paper_trail_options[:on] << :create\n end", "language": "ruby", "code": "def on_create\n @model_class.after_create { |r|\n r.paper_trail.record_create if r.paper_trail.save_version?\n }\n return if @model_class.paper_trail_options[:on].include?(:create)\n @model_class.paper_trail_options[:on] << :create\n end", "code_tokens": ["def", "on_create", "@model_class", ".", "after_create", "{", "|", "r", "|", "r", ".", "paper_trail", ".", "record_create", "if", "r", ".", "paper_trail", ".", "save_version?", "}", "return", "if", "@model_class", ".", "paper_trail_options", "[", ":on", "]", ".", "include?", "(", ":create", ")", "@model_class", ".", "paper_trail_options", "[", ":on", "]", "<<", ":create", "end"], "docstring": "Adds a callback that records a version after a \"create\" event.\n\n @api public", "docstring_tokens": ["Adds", "a", "callback", "that", "records", "a", "version", "after", "a", "create", "event", "."], "sha": "5fee6f3d4c5ff56c36981711d93b5742465304c2", "url": "https://github.com/paper-trail-gem/paper_trail/blob/5fee6f3d4c5ff56c36981711d93b5742465304c2/lib/paper_trail/model_config.rb#L44-L50", "partition": "test"} {"repo": "paper-trail-gem/paper_trail", "path": "lib/paper_trail/model_config.rb", "func_name": "PaperTrail.ModelConfig.on_destroy", "original_string": "def on_destroy(recording_order = \"before\")\n unless %w[after before].include?(recording_order.to_s)\n raise ArgumentError, 'recording order can only be \"after\" or \"before\"'\n end\n\n if recording_order.to_s == \"after\" && cannot_record_after_destroy?\n raise E_CANNOT_RECORD_AFTER_DESTROY\n end\n\n @model_class.send(\n \"#{recording_order}_destroy\",\n lambda do |r|\n return unless r.paper_trail.save_version?\n r.paper_trail.record_destroy(recording_order)\n end\n )\n\n return if @model_class.paper_trail_options[:on].include?(:destroy)\n @model_class.paper_trail_options[:on] << :destroy\n end", "language": "ruby", "code": "def on_destroy(recording_order = \"before\")\n unless %w[after before].include?(recording_order.to_s)\n raise ArgumentError, 'recording order can only be \"after\" or \"before\"'\n end\n\n if recording_order.to_s == \"after\" && cannot_record_after_destroy?\n raise E_CANNOT_RECORD_AFTER_DESTROY\n end\n\n @model_class.send(\n \"#{recording_order}_destroy\",\n lambda do |r|\n return unless r.paper_trail.save_version?\n r.paper_trail.record_destroy(recording_order)\n end\n )\n\n return if @model_class.paper_trail_options[:on].include?(:destroy)\n @model_class.paper_trail_options[:on] << :destroy\n end", "code_tokens": ["def", "on_destroy", "(", "recording_order", "=", "\"before\"", ")", "unless", "%w[", "after", "before", "]", ".", "include?", "(", "recording_order", ".", "to_s", ")", "raise", "ArgumentError", ",", "'recording order can only be \"after\" or \"before\"'", "end", "if", "recording_order", ".", "to_s", "==", "\"after\"", "&&", "cannot_record_after_destroy?", "raise", "E_CANNOT_RECORD_AFTER_DESTROY", "end", "@model_class", ".", "send", "(", "\"#{recording_order}_destroy\"", ",", "lambda", "do", "|", "r", "|", "return", "unless", "r", ".", "paper_trail", ".", "save_version?", "r", ".", "paper_trail", ".", "record_destroy", "(", "recording_order", ")", "end", ")", "return", "if", "@model_class", ".", "paper_trail_options", "[", ":on", "]", ".", "include?", "(", ":destroy", ")", "@model_class", ".", "paper_trail_options", "[", ":on", "]", "<<", ":destroy", "end"], "docstring": "Adds a callback that records a version before or after a \"destroy\" event.\n\n @api public", "docstring_tokens": ["Adds", "a", "callback", "that", "records", "a", "version", "before", "or", "after", "a", "destroy", "event", "."], "sha": "5fee6f3d4c5ff56c36981711d93b5742465304c2", "url": "https://github.com/paper-trail-gem/paper_trail/blob/5fee6f3d4c5ff56c36981711d93b5742465304c2/lib/paper_trail/model_config.rb#L55-L74", "partition": "test"} {"repo": "paper-trail-gem/paper_trail", "path": "lib/paper_trail/model_config.rb", "func_name": "PaperTrail.ModelConfig.on_update", "original_string": "def on_update\n @model_class.before_save { |r|\n r.paper_trail.reset_timestamp_attrs_for_update_if_needed\n }\n @model_class.after_update { |r|\n if r.paper_trail.save_version?\n r.paper_trail.record_update(\n force: false,\n in_after_callback: true,\n is_touch: false\n )\n end\n }\n @model_class.after_update { |r|\n r.paper_trail.clear_version_instance\n }\n return if @model_class.paper_trail_options[:on].include?(:update)\n @model_class.paper_trail_options[:on] << :update\n end", "language": "ruby", "code": "def on_update\n @model_class.before_save { |r|\n r.paper_trail.reset_timestamp_attrs_for_update_if_needed\n }\n @model_class.after_update { |r|\n if r.paper_trail.save_version?\n r.paper_trail.record_update(\n force: false,\n in_after_callback: true,\n is_touch: false\n )\n end\n }\n @model_class.after_update { |r|\n r.paper_trail.clear_version_instance\n }\n return if @model_class.paper_trail_options[:on].include?(:update)\n @model_class.paper_trail_options[:on] << :update\n end", "code_tokens": ["def", "on_update", "@model_class", ".", "before_save", "{", "|", "r", "|", "r", ".", "paper_trail", ".", "reset_timestamp_attrs_for_update_if_needed", "}", "@model_class", ".", "after_update", "{", "|", "r", "|", "if", "r", ".", "paper_trail", ".", "save_version?", "r", ".", "paper_trail", ".", "record_update", "(", "force", ":", "false", ",", "in_after_callback", ":", "true", ",", "is_touch", ":", "false", ")", "end", "}", "@model_class", ".", "after_update", "{", "|", "r", "|", "r", ".", "paper_trail", ".", "clear_version_instance", "}", "return", "if", "@model_class", ".", "paper_trail_options", "[", ":on", "]", ".", "include?", "(", ":update", ")", "@model_class", ".", "paper_trail_options", "[", ":on", "]", "<<", ":update", "end"], "docstring": "Adds a callback that records a version after an \"update\" event.\n\n @api public", "docstring_tokens": ["Adds", "a", "callback", "that", "records", "a", "version", "after", "an", "update", "event", "."], "sha": "5fee6f3d4c5ff56c36981711d93b5742465304c2", "url": "https://github.com/paper-trail-gem/paper_trail/blob/5fee6f3d4c5ff56c36981711d93b5742465304c2/lib/paper_trail/model_config.rb#L79-L97", "partition": "test"} {"repo": "paper-trail-gem/paper_trail", "path": "lib/paper_trail/model_config.rb", "func_name": "PaperTrail.ModelConfig.on_touch", "original_string": "def on_touch\n @model_class.after_touch { |r|\n r.paper_trail.record_update(\n force: true,\n in_after_callback: true,\n is_touch: true\n )\n }\n end", "language": "ruby", "code": "def on_touch\n @model_class.after_touch { |r|\n r.paper_trail.record_update(\n force: true,\n in_after_callback: true,\n is_touch: true\n )\n }\n end", "code_tokens": ["def", "on_touch", "@model_class", ".", "after_touch", "{", "|", "r", "|", "r", ".", "paper_trail", ".", "record_update", "(", "force", ":", "true", ",", "in_after_callback", ":", "true", ",", "is_touch", ":", "true", ")", "}", "end"], "docstring": "Adds a callback that records a version after a \"touch\" event.\n @api public", "docstring_tokens": ["Adds", "a", "callback", "that", "records", "a", "version", "after", "a", "touch", "event", "."], "sha": "5fee6f3d4c5ff56c36981711d93b5742465304c2", "url": "https://github.com/paper-trail-gem/paper_trail/blob/5fee6f3d4c5ff56c36981711d93b5742465304c2/lib/paper_trail/model_config.rb#L101-L109", "partition": "test"} {"repo": "paper-trail-gem/paper_trail", "path": "lib/paper_trail/model_config.rb", "func_name": "PaperTrail.ModelConfig.check_presence_of_item_subtype_column", "original_string": "def check_presence_of_item_subtype_column(options)\n return unless options.key?(:limit)\n return if version_class.item_subtype_column_present?\n raise format(E_MODEL_LIMIT_REQUIRES_ITEM_SUBTYPE, @model_class.name)\n end", "language": "ruby", "code": "def check_presence_of_item_subtype_column(options)\n return unless options.key?(:limit)\n return if version_class.item_subtype_column_present?\n raise format(E_MODEL_LIMIT_REQUIRES_ITEM_SUBTYPE, @model_class.name)\n end", "code_tokens": ["def", "check_presence_of_item_subtype_column", "(", "options", ")", "return", "unless", "options", ".", "key?", "(", ":limit", ")", "return", "if", "version_class", ".", "item_subtype_column_present?", "raise", "format", "(", "E_MODEL_LIMIT_REQUIRES_ITEM_SUBTYPE", ",", "@model_class", ".", "name", ")", "end"], "docstring": "Some options require the presence of the `item_subtype` column. Currently\n only `limit`, but in the future there may be others.\n\n @api private", "docstring_tokens": ["Some", "options", "require", "the", "presence", "of", "the", "item_subtype", "column", ".", "Currently", "only", "limit", "but", "in", "the", "future", "there", "may", "be", "others", "."], "sha": "5fee6f3d4c5ff56c36981711d93b5742465304c2", "url": "https://github.com/paper-trail-gem/paper_trail/blob/5fee6f3d4c5ff56c36981711d93b5742465304c2/lib/paper_trail/model_config.rb#L152-L156", "partition": "test"} {"repo": "paper-trail-gem/paper_trail", "path": "lib/paper_trail/record_trail.rb", "func_name": "PaperTrail.RecordTrail.save_version?", "original_string": "def save_version?\n if_condition = @record.paper_trail_options[:if]\n unless_condition = @record.paper_trail_options[:unless]\n (if_condition.blank? || if_condition.call(@record)) && !unless_condition.try(:call, @record)\n end", "language": "ruby", "code": "def save_version?\n if_condition = @record.paper_trail_options[:if]\n unless_condition = @record.paper_trail_options[:unless]\n (if_condition.blank? || if_condition.call(@record)) && !unless_condition.try(:call, @record)\n end", "code_tokens": ["def", "save_version?", "if_condition", "=", "@record", ".", "paper_trail_options", "[", ":if", "]", "unless_condition", "=", "@record", ".", "paper_trail_options", "[", ":unless", "]", "(", "if_condition", ".", "blank?", "||", "if_condition", ".", "call", "(", "@record", ")", ")", "&&", "!", "unless_condition", ".", "try", "(", ":call", ",", "@record", ")", "end"], "docstring": "AR callback.\n @api private", "docstring_tokens": ["AR", "callback", "."], "sha": "5fee6f3d4c5ff56c36981711d93b5742465304c2", "url": "https://github.com/paper-trail-gem/paper_trail/blob/5fee6f3d4c5ff56c36981711d93b5742465304c2/lib/paper_trail/record_trail.rb#L186-L190", "partition": "test"} {"repo": "guard/listen", "path": "lib/listen/queue_optimizer.rb", "func_name": "Listen.QueueOptimizer._squash_changes", "original_string": "def _squash_changes(changes)\n # We combine here for backward compatibility\n # Newer clients should receive dir and path separately\n changes = changes.map { |change, dir, path| [change, dir + path] }\n\n actions = changes.group_by(&:last).map do |path, action_list|\n [_logical_action_for(path, action_list.map(&:first)), path.to_s]\n end\n\n config.debug(\"listen: raw changes: #{actions.inspect}\")\n\n { modified: [], added: [], removed: [] }.tap do |squashed|\n actions.each do |type, path|\n squashed[type] << path unless type.nil?\n end\n config.debug(\"listen: final changes: #{squashed.inspect}\")\n end\n end", "language": "ruby", "code": "def _squash_changes(changes)\n # We combine here for backward compatibility\n # Newer clients should receive dir and path separately\n changes = changes.map { |change, dir, path| [change, dir + path] }\n\n actions = changes.group_by(&:last).map do |path, action_list|\n [_logical_action_for(path, action_list.map(&:first)), path.to_s]\n end\n\n config.debug(\"listen: raw changes: #{actions.inspect}\")\n\n { modified: [], added: [], removed: [] }.tap do |squashed|\n actions.each do |type, path|\n squashed[type] << path unless type.nil?\n end\n config.debug(\"listen: final changes: #{squashed.inspect}\")\n end\n end", "code_tokens": ["def", "_squash_changes", "(", "changes", ")", "# We combine here for backward compatibility", "# Newer clients should receive dir and path separately", "changes", "=", "changes", ".", "map", "{", "|", "change", ",", "dir", ",", "path", "|", "[", "change", ",", "dir", "+", "path", "]", "}", "actions", "=", "changes", ".", "group_by", "(", ":last", ")", ".", "map", "do", "|", "path", ",", "action_list", "|", "[", "_logical_action_for", "(", "path", ",", "action_list", ".", "map", "(", ":first", ")", ")", ",", "path", ".", "to_s", "]", "end", "config", ".", "debug", "(", "\"listen: raw changes: #{actions.inspect}\"", ")", "{", "modified", ":", "[", "]", ",", "added", ":", "[", "]", ",", "removed", ":", "[", "]", "}", ".", "tap", "do", "|", "squashed", "|", "actions", ".", "each", "do", "|", "type", ",", "path", "|", "squashed", "[", "type", "]", "<<", "path", "unless", "type", ".", "nil?", "end", "config", ".", "debug", "(", "\"listen: final changes: #{squashed.inspect}\"", ")", "end", "end"], "docstring": "groups changes into the expected structure expected by\n clients", "docstring_tokens": ["groups", "changes", "into", "the", "expected", "structure", "expected", "by", "clients"], "sha": "8d85b4cd5788592799adea61af14a29bf2895d87", "url": "https://github.com/guard/listen/blob/8d85b4cd5788592799adea61af14a29bf2895d87/lib/listen/queue_optimizer.rb#L40-L57", "partition": "test"} {"repo": "stefankroes/ancestry", "path": "lib/ancestry/class_methods.rb", "func_name": "Ancestry.ClassMethods.to_node", "original_string": "def to_node object\n if object.is_a?(self.ancestry_base_class) then object else unscoped_where{|scope| scope.find object} end\n end", "language": "ruby", "code": "def to_node object\n if object.is_a?(self.ancestry_base_class) then object else unscoped_where{|scope| scope.find object} end\n end", "code_tokens": ["def", "to_node", "object", "if", "object", ".", "is_a?", "(", "self", ".", "ancestry_base_class", ")", "then", "object", "else", "unscoped_where", "{", "|", "scope", "|", "scope", ".", "find", "object", "}", "end", "end"], "docstring": "Fetch tree node if necessary", "docstring_tokens": ["Fetch", "tree", "node", "if", "necessary"], "sha": "c91c19929d5bc9e4d2ff2cc85799a1c318b0f9a5", "url": "https://github.com/stefankroes/ancestry/blob/c91c19929d5bc9e4d2ff2cc85799a1c318b0f9a5/lib/ancestry/class_methods.rb#L4-L6", "partition": "test"} {"repo": "stefankroes/ancestry", "path": "lib/ancestry/class_methods.rb", "func_name": "Ancestry.ClassMethods.scope_depth", "original_string": "def scope_depth depth_options, depth\n depth_options.inject(self.ancestry_base_class) do |scope, option|\n scope_name, relative_depth = option\n if [:before_depth, :to_depth, :at_depth, :from_depth, :after_depth].include? scope_name\n scope.send scope_name, depth + relative_depth\n else\n raise Ancestry::AncestryException.new(\"Unknown depth option: #{scope_name}.\")\n end\n end\n end", "language": "ruby", "code": "def scope_depth depth_options, depth\n depth_options.inject(self.ancestry_base_class) do |scope, option|\n scope_name, relative_depth = option\n if [:before_depth, :to_depth, :at_depth, :from_depth, :after_depth].include? scope_name\n scope.send scope_name, depth + relative_depth\n else\n raise Ancestry::AncestryException.new(\"Unknown depth option: #{scope_name}.\")\n end\n end\n end", "code_tokens": ["def", "scope_depth", "depth_options", ",", "depth", "depth_options", ".", "inject", "(", "self", ".", "ancestry_base_class", ")", "do", "|", "scope", ",", "option", "|", "scope_name", ",", "relative_depth", "=", "option", "if", "[", ":before_depth", ",", ":to_depth", ",", ":at_depth", ",", ":from_depth", ",", ":after_depth", "]", ".", "include?", "scope_name", "scope", ".", "send", "scope_name", ",", "depth", "+", "relative_depth", "else", "raise", "Ancestry", "::", "AncestryException", ".", "new", "(", "\"Unknown depth option: #{scope_name}.\"", ")", "end", "end", "end"], "docstring": "Scope on relative depth options", "docstring_tokens": ["Scope", "on", "relative", "depth", "options"], "sha": "c91c19929d5bc9e4d2ff2cc85799a1c318b0f9a5", "url": "https://github.com/stefankroes/ancestry/blob/c91c19929d5bc9e4d2ff2cc85799a1c318b0f9a5/lib/ancestry/class_methods.rb#L9-L18", "partition": "test"} {"repo": "stefankroes/ancestry", "path": "lib/ancestry/class_methods.rb", "func_name": "Ancestry.ClassMethods.orphan_strategy=", "original_string": "def orphan_strategy= orphan_strategy\n # Check value of orphan strategy, only rootify, adopt, restrict or destroy is allowed\n if [:rootify, :adopt, :restrict, :destroy].include? orphan_strategy\n class_variable_set :@@orphan_strategy, orphan_strategy\n else\n raise Ancestry::AncestryException.new(\"Invalid orphan strategy, valid ones are :rootify,:adopt, :restrict and :destroy.\")\n end\n end", "language": "ruby", "code": "def orphan_strategy= orphan_strategy\n # Check value of orphan strategy, only rootify, adopt, restrict or destroy is allowed\n if [:rootify, :adopt, :restrict, :destroy].include? orphan_strategy\n class_variable_set :@@orphan_strategy, orphan_strategy\n else\n raise Ancestry::AncestryException.new(\"Invalid orphan strategy, valid ones are :rootify,:adopt, :restrict and :destroy.\")\n end\n end", "code_tokens": ["def", "orphan_strategy", "=", "orphan_strategy", "# Check value of orphan strategy, only rootify, adopt, restrict or destroy is allowed", "if", "[", ":rootify", ",", ":adopt", ",", ":restrict", ",", ":destroy", "]", ".", "include?", "orphan_strategy", "class_variable_set", ":@@orphan_strategy", ",", "orphan_strategy", "else", "raise", "Ancestry", "::", "AncestryException", ".", "new", "(", "\"Invalid orphan strategy, valid ones are :rootify,:adopt, :restrict and :destroy.\"", ")", "end", "end"], "docstring": "Orphan strategy writer", "docstring_tokens": ["Orphan", "strategy", "writer"], "sha": "c91c19929d5bc9e4d2ff2cc85799a1c318b0f9a5", "url": "https://github.com/stefankroes/ancestry/blob/c91c19929d5bc9e4d2ff2cc85799a1c318b0f9a5/lib/ancestry/class_methods.rb#L21-L28", "partition": "test"} {"repo": "stefankroes/ancestry", "path": "lib/ancestry/class_methods.rb", "func_name": "Ancestry.ClassMethods.arrange", "original_string": "def arrange options = {}\n if (order = options.delete(:order))\n arrange_nodes self.ancestry_base_class.order(order).where(options)\n else\n arrange_nodes self.ancestry_base_class.where(options)\n end\n end", "language": "ruby", "code": "def arrange options = {}\n if (order = options.delete(:order))\n arrange_nodes self.ancestry_base_class.order(order).where(options)\n else\n arrange_nodes self.ancestry_base_class.where(options)\n end\n end", "code_tokens": ["def", "arrange", "options", "=", "{", "}", "if", "(", "order", "=", "options", ".", "delete", "(", ":order", ")", ")", "arrange_nodes", "self", ".", "ancestry_base_class", ".", "order", "(", "order", ")", ".", "where", "(", "options", ")", "else", "arrange_nodes", "self", ".", "ancestry_base_class", ".", "where", "(", "options", ")", "end", "end"], "docstring": "Get all nodes and sorting them into an empty hash", "docstring_tokens": ["Get", "all", "nodes", "and", "sorting", "them", "into", "an", "empty", "hash"], "sha": "c91c19929d5bc9e4d2ff2cc85799a1c318b0f9a5", "url": "https://github.com/stefankroes/ancestry/blob/c91c19929d5bc9e4d2ff2cc85799a1c318b0f9a5/lib/ancestry/class_methods.rb#L31-L37", "partition": "test"} {"repo": "stefankroes/ancestry", "path": "lib/ancestry/class_methods.rb", "func_name": "Ancestry.ClassMethods.arrange_serializable", "original_string": "def arrange_serializable options={}, nodes=nil, &block\n nodes = arrange(options) if nodes.nil?\n nodes.map do |parent, children|\n if block_given?\n yield parent, arrange_serializable(options, children, &block)\n else\n parent.serializable_hash.merge 'children' => arrange_serializable(options, children)\n end\n end\n end", "language": "ruby", "code": "def arrange_serializable options={}, nodes=nil, &block\n nodes = arrange(options) if nodes.nil?\n nodes.map do |parent, children|\n if block_given?\n yield parent, arrange_serializable(options, children, &block)\n else\n parent.serializable_hash.merge 'children' => arrange_serializable(options, children)\n end\n end\n end", "code_tokens": ["def", "arrange_serializable", "options", "=", "{", "}", ",", "nodes", "=", "nil", ",", "&", "block", "nodes", "=", "arrange", "(", "options", ")", "if", "nodes", ".", "nil?", "nodes", ".", "map", "do", "|", "parent", ",", "children", "|", "if", "block_given?", "yield", "parent", ",", "arrange_serializable", "(", "options", ",", "children", ",", "block", ")", "else", "parent", ".", "serializable_hash", ".", "merge", "'children'", "=>", "arrange_serializable", "(", "options", ",", "children", ")", "end", "end", "end"], "docstring": "Arrangement to nested array", "docstring_tokens": ["Arrangement", "to", "nested", "array"], "sha": "c91c19929d5bc9e4d2ff2cc85799a1c318b0f9a5", "url": "https://github.com/stefankroes/ancestry/blob/c91c19929d5bc9e4d2ff2cc85799a1c318b0f9a5/lib/ancestry/class_methods.rb#L54-L63", "partition": "test"} {"repo": "stefankroes/ancestry", "path": "lib/ancestry/class_methods.rb", "func_name": "Ancestry.ClassMethods.build_ancestry_from_parent_ids!", "original_string": "def build_ancestry_from_parent_ids! parent_id = nil, ancestry = nil\n unscoped_where do |scope|\n scope.where(:parent_id => parent_id).find_each do |node|\n node.without_ancestry_callbacks do\n node.update_attribute ancestry_column, ancestry\n end\n build_ancestry_from_parent_ids! node.id, if ancestry.nil? then \"#{node.id}\" else \"#{ancestry}/#{node.id}\" end\n end\n end\n end", "language": "ruby", "code": "def build_ancestry_from_parent_ids! parent_id = nil, ancestry = nil\n unscoped_where do |scope|\n scope.where(:parent_id => parent_id).find_each do |node|\n node.without_ancestry_callbacks do\n node.update_attribute ancestry_column, ancestry\n end\n build_ancestry_from_parent_ids! node.id, if ancestry.nil? then \"#{node.id}\" else \"#{ancestry}/#{node.id}\" end\n end\n end\n end", "code_tokens": ["def", "build_ancestry_from_parent_ids!", "parent_id", "=", "nil", ",", "ancestry", "=", "nil", "unscoped_where", "do", "|", "scope", "|", "scope", ".", "where", "(", ":parent_id", "=>", "parent_id", ")", ".", "find_each", "do", "|", "node", "|", "node", ".", "without_ancestry_callbacks", "do", "node", ".", "update_attribute", "ancestry_column", ",", "ancestry", "end", "build_ancestry_from_parent_ids!", "node", ".", "id", ",", "if", "ancestry", ".", "nil?", "then", "\"#{node.id}\"", "else", "\"#{ancestry}/#{node.id}\"", "end", "end", "end", "end"], "docstring": "Build ancestry from parent id's for migration purposes", "docstring_tokens": ["Build", "ancestry", "from", "parent", "id", "s", "for", "migration", "purposes"], "sha": "c91c19929d5bc9e4d2ff2cc85799a1c318b0f9a5", "url": "https://github.com/stefankroes/ancestry/blob/c91c19929d5bc9e4d2ff2cc85799a1c318b0f9a5/lib/ancestry/class_methods.rb#L171-L180", "partition": "test"} {"repo": "stefankroes/ancestry", "path": "lib/ancestry/class_methods.rb", "func_name": "Ancestry.ClassMethods.rebuild_depth_cache!", "original_string": "def rebuild_depth_cache!\n raise Ancestry::AncestryException.new(\"Cannot rebuild depth cache for model without depth caching.\") unless respond_to? :depth_cache_column\n\n self.ancestry_base_class.transaction do\n unscoped_where do |scope|\n scope.find_each do |node|\n node.update_attribute depth_cache_column, node.depth\n end\n end\n end\n end", "language": "ruby", "code": "def rebuild_depth_cache!\n raise Ancestry::AncestryException.new(\"Cannot rebuild depth cache for model without depth caching.\") unless respond_to? :depth_cache_column\n\n self.ancestry_base_class.transaction do\n unscoped_where do |scope|\n scope.find_each do |node|\n node.update_attribute depth_cache_column, node.depth\n end\n end\n end\n end", "code_tokens": ["def", "rebuild_depth_cache!", "raise", "Ancestry", "::", "AncestryException", ".", "new", "(", "\"Cannot rebuild depth cache for model without depth caching.\"", ")", "unless", "respond_to?", ":depth_cache_column", "self", ".", "ancestry_base_class", ".", "transaction", "do", "unscoped_where", "do", "|", "scope", "|", "scope", ".", "find_each", "do", "|", "node", "|", "node", ".", "update_attribute", "depth_cache_column", ",", "node", ".", "depth", "end", "end", "end", "end"], "docstring": "Rebuild depth cache if it got corrupted or if depth caching was just turned on", "docstring_tokens": ["Rebuild", "depth", "cache", "if", "it", "got", "corrupted", "or", "if", "depth", "caching", "was", "just", "turned", "on"], "sha": "c91c19929d5bc9e4d2ff2cc85799a1c318b0f9a5", "url": "https://github.com/stefankroes/ancestry/blob/c91c19929d5bc9e4d2ff2cc85799a1c318b0f9a5/lib/ancestry/class_methods.rb#L183-L193", "partition": "test"} {"repo": "stefankroes/ancestry", "path": "lib/ancestry/materialized_path.rb", "func_name": "Ancestry.MaterializedPath.indirect_conditions", "original_string": "def indirect_conditions(object)\n t = arel_table\n node = to_node(object)\n # rails has case sensitive matching.\n if ActiveRecord::VERSION::MAJOR >= 5\n t[ancestry_column].matches(\"#{node.child_ancestry}/%\", nil, true)\n else\n t[ancestry_column].matches(\"#{node.child_ancestry}/%\")\n end\n end", "language": "ruby", "code": "def indirect_conditions(object)\n t = arel_table\n node = to_node(object)\n # rails has case sensitive matching.\n if ActiveRecord::VERSION::MAJOR >= 5\n t[ancestry_column].matches(\"#{node.child_ancestry}/%\", nil, true)\n else\n t[ancestry_column].matches(\"#{node.child_ancestry}/%\")\n end\n end", "code_tokens": ["def", "indirect_conditions", "(", "object", ")", "t", "=", "arel_table", "node", "=", "to_node", "(", "object", ")", "# rails has case sensitive matching.", "if", "ActiveRecord", "::", "VERSION", "::", "MAJOR", ">=", "5", "t", "[", "ancestry_column", "]", ".", "matches", "(", "\"#{node.child_ancestry}/%\"", ",", "nil", ",", "true", ")", "else", "t", "[", "ancestry_column", "]", ".", "matches", "(", "\"#{node.child_ancestry}/%\"", ")", "end", "end"], "docstring": "indirect = anyone who is a descendant, but not a child", "docstring_tokens": ["indirect", "=", "anyone", "who", "is", "a", "descendant", "but", "not", "a", "child"], "sha": "c91c19929d5bc9e4d2ff2cc85799a1c318b0f9a5", "url": "https://github.com/stefankroes/ancestry/blob/c91c19929d5bc9e4d2ff2cc85799a1c318b0f9a5/lib/ancestry/materialized_path.rb#L31-L40", "partition": "test"} {"repo": "NARKOZ/gitlab", "path": "lib/gitlab/request.rb", "func_name": "Gitlab.Request.request_defaults", "original_string": "def request_defaults(sudo = nil)\n self.class.default_params sudo: sudo\n raise Error::MissingCredentials, 'Please set an endpoint to API' unless @endpoint\n\n self.class.default_params.delete(:sudo) if sudo.nil?\n end", "language": "ruby", "code": "def request_defaults(sudo = nil)\n self.class.default_params sudo: sudo\n raise Error::MissingCredentials, 'Please set an endpoint to API' unless @endpoint\n\n self.class.default_params.delete(:sudo) if sudo.nil?\n end", "code_tokens": ["def", "request_defaults", "(", "sudo", "=", "nil", ")", "self", ".", "class", ".", "default_params", "sudo", ":", "sudo", "raise", "Error", "::", "MissingCredentials", ",", "'Please set an endpoint to API'", "unless", "@endpoint", "self", ".", "class", ".", "default_params", ".", "delete", "(", ":sudo", ")", "if", "sudo", ".", "nil?", "end"], "docstring": "Sets a base_uri and default_params for requests.\n @raise [Error::MissingCredentials] if endpoint not set.", "docstring_tokens": ["Sets", "a", "base_uri", "and", "default_params", "for", "requests", "."], "sha": "338d5d9be49ff28263d9946d8cd6c9006e5ecb09", "url": "https://github.com/NARKOZ/gitlab/blob/338d5d9be49ff28263d9946d8cd6c9006e5ecb09/lib/gitlab/request.rb#L64-L69", "partition": "test"} {"repo": "NARKOZ/gitlab", "path": "lib/gitlab/configuration.rb", "func_name": "Gitlab.Configuration.options", "original_string": "def options\n VALID_OPTIONS_KEYS.inject({}) do |option, key|\n option.merge!(key => send(key))\n end\n end", "language": "ruby", "code": "def options\n VALID_OPTIONS_KEYS.inject({}) do |option, key|\n option.merge!(key => send(key))\n end\n end", "code_tokens": ["def", "options", "VALID_OPTIONS_KEYS", ".", "inject", "(", "{", "}", ")", "do", "|", "option", ",", "key", "|", "option", ".", "merge!", "(", "key", "=>", "send", "(", "key", ")", ")", "end", "end"], "docstring": "Creates a hash of options and their values.", "docstring_tokens": ["Creates", "a", "hash", "of", "options", "and", "their", "values", "."], "sha": "338d5d9be49ff28263d9946d8cd6c9006e5ecb09", "url": "https://github.com/NARKOZ/gitlab/blob/338d5d9be49ff28263d9946d8cd6c9006e5ecb09/lib/gitlab/configuration.rb#L30-L34", "partition": "test"} {"repo": "NARKOZ/gitlab", "path": "lib/gitlab/configuration.rb", "func_name": "Gitlab.Configuration.reset", "original_string": "def reset\n self.endpoint = ENV['GITLAB_API_ENDPOINT']\n self.private_token = ENV['GITLAB_API_PRIVATE_TOKEN'] || ENV['GITLAB_API_AUTH_TOKEN']\n self.httparty = get_httparty_config(ENV['GITLAB_API_HTTPARTY_OPTIONS'])\n self.sudo = nil\n self.user_agent = DEFAULT_USER_AGENT\n end", "language": "ruby", "code": "def reset\n self.endpoint = ENV['GITLAB_API_ENDPOINT']\n self.private_token = ENV['GITLAB_API_PRIVATE_TOKEN'] || ENV['GITLAB_API_AUTH_TOKEN']\n self.httparty = get_httparty_config(ENV['GITLAB_API_HTTPARTY_OPTIONS'])\n self.sudo = nil\n self.user_agent = DEFAULT_USER_AGENT\n end", "code_tokens": ["def", "reset", "self", ".", "endpoint", "=", "ENV", "[", "'GITLAB_API_ENDPOINT'", "]", "self", ".", "private_token", "=", "ENV", "[", "'GITLAB_API_PRIVATE_TOKEN'", "]", "||", "ENV", "[", "'GITLAB_API_AUTH_TOKEN'", "]", "self", ".", "httparty", "=", "get_httparty_config", "(", "ENV", "[", "'GITLAB_API_HTTPARTY_OPTIONS'", "]", ")", "self", ".", "sudo", "=", "nil", "self", ".", "user_agent", "=", "DEFAULT_USER_AGENT", "end"], "docstring": "Resets all configuration options to the defaults.", "docstring_tokens": ["Resets", "all", "configuration", "options", "to", "the", "defaults", "."], "sha": "338d5d9be49ff28263d9946d8cd6c9006e5ecb09", "url": "https://github.com/NARKOZ/gitlab/blob/338d5d9be49ff28263d9946d8cd6c9006e5ecb09/lib/gitlab/configuration.rb#L37-L43", "partition": "test"} {"repo": "NARKOZ/gitlab", "path": "lib/gitlab/configuration.rb", "func_name": "Gitlab.Configuration.get_httparty_config", "original_string": "def get_httparty_config(options)\n return if options.nil?\n\n httparty = Gitlab::CLI::Helpers.yaml_load(options)\n raise ArgumentError, 'HTTParty config should be a Hash.' unless httparty.is_a? Hash\n\n Gitlab::CLI::Helpers.symbolize_keys httparty\n end", "language": "ruby", "code": "def get_httparty_config(options)\n return if options.nil?\n\n httparty = Gitlab::CLI::Helpers.yaml_load(options)\n raise ArgumentError, 'HTTParty config should be a Hash.' unless httparty.is_a? Hash\n\n Gitlab::CLI::Helpers.symbolize_keys httparty\n end", "code_tokens": ["def", "get_httparty_config", "(", "options", ")", "return", "if", "options", ".", "nil?", "httparty", "=", "Gitlab", "::", "CLI", "::", "Helpers", ".", "yaml_load", "(", "options", ")", "raise", "ArgumentError", ",", "'HTTParty config should be a Hash.'", "unless", "httparty", ".", "is_a?", "Hash", "Gitlab", "::", "CLI", "::", "Helpers", ".", "symbolize_keys", "httparty", "end"], "docstring": "Allows HTTParty config to be specified in ENV using YAML hash.", "docstring_tokens": ["Allows", "HTTParty", "config", "to", "be", "specified", "in", "ENV", "using", "YAML", "hash", "."], "sha": "338d5d9be49ff28263d9946d8cd6c9006e5ecb09", "url": "https://github.com/NARKOZ/gitlab/blob/338d5d9be49ff28263d9946d8cd6c9006e5ecb09/lib/gitlab/configuration.rb#L48-L55", "partition": "test"} {"repo": "socketry/socketry", "path": "lib/socketry/timeout.rb", "func_name": "Socketry.Timeout.start_timer", "original_string": "def start_timer(timer = DEFAULT_TIMER.new)\n raise Socketry::InternalError, \"timer already started\" if defined?(@timer)\n raise Socketry::InternalError, \"deadline already set\" if defined?(@deadline)\n\n @deadline = nil\n @timer = timer\n @timer.start\n true\n end", "language": "ruby", "code": "def start_timer(timer = DEFAULT_TIMER.new)\n raise Socketry::InternalError, \"timer already started\" if defined?(@timer)\n raise Socketry::InternalError, \"deadline already set\" if defined?(@deadline)\n\n @deadline = nil\n @timer = timer\n @timer.start\n true\n end", "code_tokens": ["def", "start_timer", "(", "timer", "=", "DEFAULT_TIMER", ".", "new", ")", "raise", "Socketry", "::", "InternalError", ",", "\"timer already started\"", "if", "defined?", "(", "@timer", ")", "raise", "Socketry", "::", "InternalError", ",", "\"deadline already set\"", "if", "defined?", "(", "@deadline", ")", "@deadline", "=", "nil", "@timer", "=", "timer", "@timer", ".", "start", "true", "end"], "docstring": "Start a timer in the included object\n\n @param timer [#start, #to_f] a timer object (ideally monotonic)\n @return [true] timer started successfully\n @raise [Socketry::InternalError] if timer is already started", "docstring_tokens": ["Start", "a", "timer", "in", "the", "included", "object"], "sha": "010af1cd74449addf7130aa14ffff00496479680", "url": "https://github.com/socketry/socketry/blob/010af1cd74449addf7130aa14ffff00496479680/lib/socketry/timeout.rb#L20-L28", "partition": "test"} {"repo": "socketry/socketry", "path": "lib/socketry/timeout.rb", "func_name": "Socketry.Timeout.set_timeout", "original_string": "def set_timeout(timeout)\n raise Socketry::InternalError, \"deadline already set\" if @deadline\n return unless timeout\n raise Socketry::TimeoutError, \"time expired\" if timeout < 0\n\n @deadline = lifetime + timeout\n end", "language": "ruby", "code": "def set_timeout(timeout)\n raise Socketry::InternalError, \"deadline already set\" if @deadline\n return unless timeout\n raise Socketry::TimeoutError, \"time expired\" if timeout < 0\n\n @deadline = lifetime + timeout\n end", "code_tokens": ["def", "set_timeout", "(", "timeout", ")", "raise", "Socketry", "::", "InternalError", ",", "\"deadline already set\"", "if", "@deadline", "return", "unless", "timeout", "raise", "Socketry", "::", "TimeoutError", ",", "\"time expired\"", "if", "timeout", "<", "0", "@deadline", "=", "lifetime", "+", "timeout", "end"], "docstring": "Set a timeout. Only one timeout may be active at a given time for a given object.\n\n @param timeout [Numeric] number of seconds until the timeout is reached\n @return [Float] deadline (relative to #lifetime) at which the timeout is reached\n @raise [Socketry::InternalError] if timeout is already set", "docstring_tokens": ["Set", "a", "timeout", ".", "Only", "one", "timeout", "may", "be", "active", "at", "a", "given", "time", "for", "a", "given", "object", "."], "sha": "010af1cd74449addf7130aa14ffff00496479680", "url": "https://github.com/socketry/socketry/blob/010af1cd74449addf7130aa14ffff00496479680/lib/socketry/timeout.rb#L45-L51", "partition": "test"} {"repo": "socketry/socketry", "path": "lib/socketry/timeout.rb", "func_name": "Socketry.Timeout.time_remaining", "original_string": "def time_remaining(timeout)\n return unless timeout\n raise Socketry::InternalError, \"no deadline set\" unless @deadline\n\n remaining = @deadline - lifetime\n raise Socketry::TimeoutError, \"time expired\" if remaining <= 0\n\n remaining\n end", "language": "ruby", "code": "def time_remaining(timeout)\n return unless timeout\n raise Socketry::InternalError, \"no deadline set\" unless @deadline\n\n remaining = @deadline - lifetime\n raise Socketry::TimeoutError, \"time expired\" if remaining <= 0\n\n remaining\n end", "code_tokens": ["def", "time_remaining", "(", "timeout", ")", "return", "unless", "timeout", "raise", "Socketry", "::", "InternalError", ",", "\"no deadline set\"", "unless", "@deadline", "remaining", "=", "@deadline", "-", "lifetime", "raise", "Socketry", "::", "TimeoutError", ",", "\"time expired\"", "if", "remaining", "<=", "0", "remaining", "end"], "docstring": "Calculate number of seconds remaining until we hit the timeout\n\n @param timeout [Numeric] to gauge whether a timeout needs to be calculated\n @return [Float] number of seconds remaining until we hit the timeout\n @raise [Socketry::TimeoutError] if we've already hit the timeout\n @raise [Socketry::InternalError] if timeout has not been set", "docstring_tokens": ["Calculate", "number", "of", "seconds", "remaining", "until", "we", "hit", "the", "timeout"], "sha": "010af1cd74449addf7130aa14ffff00496479680", "url": "https://github.com/socketry/socketry/blob/010af1cd74449addf7130aa14ffff00496479680/lib/socketry/timeout.rb#L70-L78", "partition": "test"} {"repo": "ruby-json-schema/json-schema", "path": "lib/json-schema/validator.rb", "func_name": "JSON.Validator.build_schemas", "original_string": "def build_schemas(parent_schema)\n schema = parent_schema.schema\n\n # Build ref schemas if they exist\n if schema[\"$ref\"]\n load_ref_schema(parent_schema, schema[\"$ref\"])\n end\n\n case schema[\"extends\"]\n when String\n load_ref_schema(parent_schema, schema[\"extends\"])\n when Array\n schema['extends'].each do |type|\n handle_schema(parent_schema, type)\n end\n end\n\n # Check for schemas in union types\n [\"type\", \"disallow\"].each do |key|\n if schema[key].is_a?(Array)\n schema[key].each do |type|\n if type.is_a?(Hash)\n handle_schema(parent_schema, type)\n end\n end\n end\n end\n\n # Schema properties whose values are objects, the values of which\n # are themselves schemas.\n %w[definitions properties patternProperties].each do |key|\n next unless value = schema[key]\n value.each do |k, inner_schema|\n handle_schema(parent_schema, inner_schema)\n end\n end\n\n # Schema properties whose values are themselves schemas.\n %w[additionalProperties additionalItems dependencies extends].each do |key|\n next unless schema[key].is_a?(Hash)\n handle_schema(parent_schema, schema[key])\n end\n\n # Schema properties whose values may be an array of schemas.\n %w[allOf anyOf oneOf not].each do |key|\n next unless value = schema[key]\n Array(value).each do |inner_schema|\n handle_schema(parent_schema, inner_schema)\n end\n end\n\n # Items are always schemas\n if schema[\"items\"]\n items = schema[\"items\"].clone\n items = [items] unless items.is_a?(Array)\n\n items.each do |item|\n handle_schema(parent_schema, item)\n end\n end\n\n # Convert enum to a ArraySet\n if schema[\"enum\"].is_a?(Array)\n schema[\"enum\"] = ArraySet.new(schema[\"enum\"])\n end\n\n end", "language": "ruby", "code": "def build_schemas(parent_schema)\n schema = parent_schema.schema\n\n # Build ref schemas if they exist\n if schema[\"$ref\"]\n load_ref_schema(parent_schema, schema[\"$ref\"])\n end\n\n case schema[\"extends\"]\n when String\n load_ref_schema(parent_schema, schema[\"extends\"])\n when Array\n schema['extends'].each do |type|\n handle_schema(parent_schema, type)\n end\n end\n\n # Check for schemas in union types\n [\"type\", \"disallow\"].each do |key|\n if schema[key].is_a?(Array)\n schema[key].each do |type|\n if type.is_a?(Hash)\n handle_schema(parent_schema, type)\n end\n end\n end\n end\n\n # Schema properties whose values are objects, the values of which\n # are themselves schemas.\n %w[definitions properties patternProperties].each do |key|\n next unless value = schema[key]\n value.each do |k, inner_schema|\n handle_schema(parent_schema, inner_schema)\n end\n end\n\n # Schema properties whose values are themselves schemas.\n %w[additionalProperties additionalItems dependencies extends].each do |key|\n next unless schema[key].is_a?(Hash)\n handle_schema(parent_schema, schema[key])\n end\n\n # Schema properties whose values may be an array of schemas.\n %w[allOf anyOf oneOf not].each do |key|\n next unless value = schema[key]\n Array(value).each do |inner_schema|\n handle_schema(parent_schema, inner_schema)\n end\n end\n\n # Items are always schemas\n if schema[\"items\"]\n items = schema[\"items\"].clone\n items = [items] unless items.is_a?(Array)\n\n items.each do |item|\n handle_schema(parent_schema, item)\n end\n end\n\n # Convert enum to a ArraySet\n if schema[\"enum\"].is_a?(Array)\n schema[\"enum\"] = ArraySet.new(schema[\"enum\"])\n end\n\n end", "code_tokens": ["def", "build_schemas", "(", "parent_schema", ")", "schema", "=", "parent_schema", ".", "schema", "# Build ref schemas if they exist", "if", "schema", "[", "\"$ref\"", "]", "load_ref_schema", "(", "parent_schema", ",", "schema", "[", "\"$ref\"", "]", ")", "end", "case", "schema", "[", "\"extends\"", "]", "when", "String", "load_ref_schema", "(", "parent_schema", ",", "schema", "[", "\"extends\"", "]", ")", "when", "Array", "schema", "[", "'extends'", "]", ".", "each", "do", "|", "type", "|", "handle_schema", "(", "parent_schema", ",", "type", ")", "end", "end", "# Check for schemas in union types", "[", "\"type\"", ",", "\"disallow\"", "]", ".", "each", "do", "|", "key", "|", "if", "schema", "[", "key", "]", ".", "is_a?", "(", "Array", ")", "schema", "[", "key", "]", ".", "each", "do", "|", "type", "|", "if", "type", ".", "is_a?", "(", "Hash", ")", "handle_schema", "(", "parent_schema", ",", "type", ")", "end", "end", "end", "end", "# Schema properties whose values are objects, the values of which", "# are themselves schemas.", "%w[", "definitions", "properties", "patternProperties", "]", ".", "each", "do", "|", "key", "|", "next", "unless", "value", "=", "schema", "[", "key", "]", "value", ".", "each", "do", "|", "k", ",", "inner_schema", "|", "handle_schema", "(", "parent_schema", ",", "inner_schema", ")", "end", "end", "# Schema properties whose values are themselves schemas.", "%w[", "additionalProperties", "additionalItems", "dependencies", "extends", "]", ".", "each", "do", "|", "key", "|", "next", "unless", "schema", "[", "key", "]", ".", "is_a?", "(", "Hash", ")", "handle_schema", "(", "parent_schema", ",", "schema", "[", "key", "]", ")", "end", "# Schema properties whose values may be an array of schemas.", "%w[", "allOf", "anyOf", "oneOf", "not", "]", ".", "each", "do", "|", "key", "|", "next", "unless", "value", "=", "schema", "[", "key", "]", "Array", "(", "value", ")", ".", "each", "do", "|", "inner_schema", "|", "handle_schema", "(", "parent_schema", ",", "inner_schema", ")", "end", "end", "# Items are always schemas", "if", "schema", "[", "\"items\"", "]", "items", "=", "schema", "[", "\"items\"", "]", ".", "clone", "items", "=", "[", "items", "]", "unless", "items", ".", "is_a?", "(", "Array", ")", "items", ".", "each", "do", "|", "item", "|", "handle_schema", "(", "parent_schema", ",", "item", ")", "end", "end", "# Convert enum to a ArraySet", "if", "schema", "[", "\"enum\"", "]", ".", "is_a?", "(", "Array", ")", "schema", "[", "\"enum\"", "]", "=", "ArraySet", ".", "new", "(", "schema", "[", "\"enum\"", "]", ")", "end", "end"], "docstring": "Build all schemas with IDs, mapping out the namespace", "docstring_tokens": ["Build", "all", "schemas", "with", "IDs", "mapping", "out", "the", "namespace"], "sha": "ab1253a874f05a811fdb3280ca1f77ebc9af2902", "url": "https://github.com/ruby-json-schema/json-schema/blob/ab1253a874f05a811fdb3280ca1f77ebc9af2902/lib/json-schema/validator.rb#L148-L214", "partition": "test"} {"repo": "ruby-json-schema/json-schema", "path": "lib/json-schema/validator.rb", "func_name": "JSON.Validator.handle_schema", "original_string": "def handle_schema(parent_schema, obj)\n if obj.is_a?(Hash)\n schema_uri = parent_schema.uri.dup\n schema = JSON::Schema.new(obj, schema_uri, parent_schema.validator)\n if obj['id']\n self.class.add_schema(schema)\n end\n build_schemas(schema)\n end\n end", "language": "ruby", "code": "def handle_schema(parent_schema, obj)\n if obj.is_a?(Hash)\n schema_uri = parent_schema.uri.dup\n schema = JSON::Schema.new(obj, schema_uri, parent_schema.validator)\n if obj['id']\n self.class.add_schema(schema)\n end\n build_schemas(schema)\n end\n end", "code_tokens": ["def", "handle_schema", "(", "parent_schema", ",", "obj", ")", "if", "obj", ".", "is_a?", "(", "Hash", ")", "schema_uri", "=", "parent_schema", ".", "uri", ".", "dup", "schema", "=", "JSON", "::", "Schema", ".", "new", "(", "obj", ",", "schema_uri", ",", "parent_schema", ".", "validator", ")", "if", "obj", "[", "'id'", "]", "self", ".", "class", ".", "add_schema", "(", "schema", ")", "end", "build_schemas", "(", "schema", ")", "end", "end"], "docstring": "Either load a reference schema or create a new schema", "docstring_tokens": ["Either", "load", "a", "reference", "schema", "or", "create", "a", "new", "schema"], "sha": "ab1253a874f05a811fdb3280ca1f77ebc9af2902", "url": "https://github.com/ruby-json-schema/json-schema/blob/ab1253a874f05a811fdb3280ca1f77ebc9af2902/lib/json-schema/validator.rb#L217-L226", "partition": "test"} {"repo": "ryanb/cancan", "path": "lib/cancan/rule.rb", "func_name": "CanCan.Rule.matches_conditions?", "original_string": "def matches_conditions?(action, subject, extra_args)\n if @match_all\n call_block_with_all(action, subject, extra_args)\n elsif @block && !subject_class?(subject)\n @block.call(subject, *extra_args)\n elsif @conditions.kind_of?(Hash) && subject.class == Hash\n nested_subject_matches_conditions?(subject)\n elsif @conditions.kind_of?(Hash) && !subject_class?(subject)\n matches_conditions_hash?(subject)\n else\n # Don't stop at \"cannot\" definitions when there are conditions.\n @conditions.empty? ? true : @base_behavior\n end\n end", "language": "ruby", "code": "def matches_conditions?(action, subject, extra_args)\n if @match_all\n call_block_with_all(action, subject, extra_args)\n elsif @block && !subject_class?(subject)\n @block.call(subject, *extra_args)\n elsif @conditions.kind_of?(Hash) && subject.class == Hash\n nested_subject_matches_conditions?(subject)\n elsif @conditions.kind_of?(Hash) && !subject_class?(subject)\n matches_conditions_hash?(subject)\n else\n # Don't stop at \"cannot\" definitions when there are conditions.\n @conditions.empty? ? true : @base_behavior\n end\n end", "code_tokens": ["def", "matches_conditions?", "(", "action", ",", "subject", ",", "extra_args", ")", "if", "@match_all", "call_block_with_all", "(", "action", ",", "subject", ",", "extra_args", ")", "elsif", "@block", "&&", "!", "subject_class?", "(", "subject", ")", "@block", ".", "call", "(", "subject", ",", "extra_args", ")", "elsif", "@conditions", ".", "kind_of?", "(", "Hash", ")", "&&", "subject", ".", "class", "==", "Hash", "nested_subject_matches_conditions?", "(", "subject", ")", "elsif", "@conditions", ".", "kind_of?", "(", "Hash", ")", "&&", "!", "subject_class?", "(", "subject", ")", "matches_conditions_hash?", "(", "subject", ")", "else", "# Don't stop at \"cannot\" definitions when there are conditions.", "@conditions", ".", "empty?", "?", "true", ":", "@base_behavior", "end", "end"], "docstring": "Matches the block or conditions hash", "docstring_tokens": ["Matches", "the", "block", "or", "conditions", "hash"], "sha": "4560928dc375f9b31de00381c98334eb6aabc4b9", "url": "https://github.com/ryanb/cancan/blob/4560928dc375f9b31de00381c98334eb6aabc4b9/lib/cancan/rule.rb#L30-L43", "partition": "test"} {"repo": "ryanb/cancan", "path": "lib/cancan/ability.rb", "func_name": "CanCan.Ability.alias_action", "original_string": "def alias_action(*args)\n target = args.pop[:to]\n validate_target(target)\n aliased_actions[target] ||= []\n aliased_actions[target] += args\n end", "language": "ruby", "code": "def alias_action(*args)\n target = args.pop[:to]\n validate_target(target)\n aliased_actions[target] ||= []\n aliased_actions[target] += args\n end", "code_tokens": ["def", "alias_action", "(", "*", "args", ")", "target", "=", "args", ".", "pop", "[", ":to", "]", "validate_target", "(", "target", ")", "aliased_actions", "[", "target", "]", "||=", "[", "]", "aliased_actions", "[", "target", "]", "+=", "args", "end"], "docstring": "Alias one or more actions into another one.\n\n alias_action :update, :destroy, :to => :modify\n can :modify, Comment\n\n Then :modify permission will apply to both :update and :destroy requests.\n\n can? :update, Comment # => true\n can? :destroy, Comment # => true\n\n This only works in one direction. Passing the aliased action into the \"can?\" call\n will not work because aliases are meant to generate more generic actions.\n\n alias_action :update, :destroy, :to => :modify\n can :update, Comment\n can? :modify, Comment # => false\n\n Unless that exact alias is used.\n\n can :modify, Comment\n can? :modify, Comment # => true\n\n The following aliases are added by default for conveniently mapping common controller actions.\n\n alias_action :index, :show, :to => :read\n alias_action :new, :to => :create\n alias_action :edit, :to => :update\n\n This way one can use params[:action] in the controller to determine the permission.", "docstring_tokens": ["Alias", "one", "or", "more", "actions", "into", "another", "one", "."], "sha": "4560928dc375f9b31de00381c98334eb6aabc4b9", "url": "https://github.com/ryanb/cancan/blob/4560928dc375f9b31de00381c98334eb6aabc4b9/lib/cancan/ability.rb#L173-L178", "partition": "test"} {"repo": "ryanb/cancan", "path": "lib/cancan/ability.rb", "func_name": "CanCan.Ability.expand_actions", "original_string": "def expand_actions(actions)\n actions.map do |action|\n aliased_actions[action] ? [action, *expand_actions(aliased_actions[action])] : action\n end.flatten\n end", "language": "ruby", "code": "def expand_actions(actions)\n actions.map do |action|\n aliased_actions[action] ? [action, *expand_actions(aliased_actions[action])] : action\n end.flatten\n end", "code_tokens": ["def", "expand_actions", "(", "actions", ")", "actions", ".", "map", "do", "|", "action", "|", "aliased_actions", "[", "action", "]", "?", "[", "action", ",", "expand_actions", "(", "aliased_actions", "[", "action", "]", ")", "]", ":", "action", "end", ".", "flatten", "end"], "docstring": "Accepts an array of actions and returns an array of actions which match.\n This should be called before \"matches?\" and other checking methods since they\n rely on the actions to be expanded.", "docstring_tokens": ["Accepts", "an", "array", "of", "actions", "and", "returns", "an", "array", "of", "actions", "which", "match", ".", "This", "should", "be", "called", "before", "matches?", "and", "other", "checking", "methods", "since", "they", "rely", "on", "the", "actions", "to", "be", "expanded", "."], "sha": "4560928dc375f9b31de00381c98334eb6aabc4b9", "url": "https://github.com/ryanb/cancan/blob/4560928dc375f9b31de00381c98334eb6aabc4b9/lib/cancan/ability.rb#L258-L262", "partition": "test"} {"repo": "ryanb/cancan", "path": "lib/cancan/ability.rb", "func_name": "CanCan.Ability.aliases_for_action", "original_string": "def aliases_for_action(action)\n results = [action]\n aliased_actions.each do |aliased_action, actions|\n results += aliases_for_action(aliased_action) if actions.include? action\n end\n results\n end", "language": "ruby", "code": "def aliases_for_action(action)\n results = [action]\n aliased_actions.each do |aliased_action, actions|\n results += aliases_for_action(aliased_action) if actions.include? action\n end\n results\n end", "code_tokens": ["def", "aliases_for_action", "(", "action", ")", "results", "=", "[", "action", "]", "aliased_actions", ".", "each", "do", "|", "aliased_action", ",", "actions", "|", "results", "+=", "aliases_for_action", "(", "aliased_action", ")", "if", "actions", ".", "include?", "action", "end", "results", "end"], "docstring": "Given an action, it will try to find all of the actions which are aliased to it.\n This does the opposite kind of lookup as expand_actions.", "docstring_tokens": ["Given", "an", "action", "it", "will", "try", "to", "find", "all", "of", "the", "actions", "which", "are", "aliased", "to", "it", ".", "This", "does", "the", "opposite", "kind", "of", "lookup", "as", "expand_actions", "."], "sha": "4560928dc375f9b31de00381c98334eb6aabc4b9", "url": "https://github.com/ryanb/cancan/blob/4560928dc375f9b31de00381c98334eb6aabc4b9/lib/cancan/ability.rb#L266-L272", "partition": "test"} {"repo": "ryanb/cancan", "path": "lib/cancan/ability.rb", "func_name": "CanCan.Ability.relevant_rules", "original_string": "def relevant_rules(action, subject)\n rules.reverse.select do |rule|\n rule.expanded_actions = expand_actions(rule.actions)\n rule.relevant? action, subject\n end\n end", "language": "ruby", "code": "def relevant_rules(action, subject)\n rules.reverse.select do |rule|\n rule.expanded_actions = expand_actions(rule.actions)\n rule.relevant? action, subject\n end\n end", "code_tokens": ["def", "relevant_rules", "(", "action", ",", "subject", ")", "rules", ".", "reverse", ".", "select", "do", "|", "rule", "|", "rule", ".", "expanded_actions", "=", "expand_actions", "(", "rule", ".", "actions", ")", "rule", ".", "relevant?", "action", ",", "subject", "end", "end"], "docstring": "Returns an array of Rule instances which match the action and subject\n This does not take into consideration any hash conditions or block statements", "docstring_tokens": ["Returns", "an", "array", "of", "Rule", "instances", "which", "match", "the", "action", "and", "subject", "This", "does", "not", "take", "into", "consideration", "any", "hash", "conditions", "or", "block", "statements"], "sha": "4560928dc375f9b31de00381c98334eb6aabc4b9", "url": "https://github.com/ryanb/cancan/blob/4560928dc375f9b31de00381c98334eb6aabc4b9/lib/cancan/ability.rb#L280-L285", "partition": "test"} {"repo": "fakefs/fakefs", "path": "lib/fakefs/file.rb", "func_name": "FakeFS.File.create_missing_file", "original_string": "def create_missing_file\n raise Errno::EISDIR, path.to_s if File.directory?(@path)\n\n return if File.exist?(@path) # Unnecessary check, probably.\n dirname = RealFile.dirname @path\n\n unless dirname == '.'\n dir = FileSystem.find dirname\n\n raise Errno::ENOENT, path.to_s unless dir.is_a? FakeDir\n end\n\n @file = FileSystem.add(path, FakeFile.new)\n end", "language": "ruby", "code": "def create_missing_file\n raise Errno::EISDIR, path.to_s if File.directory?(@path)\n\n return if File.exist?(@path) # Unnecessary check, probably.\n dirname = RealFile.dirname @path\n\n unless dirname == '.'\n dir = FileSystem.find dirname\n\n raise Errno::ENOENT, path.to_s unless dir.is_a? FakeDir\n end\n\n @file = FileSystem.add(path, FakeFile.new)\n end", "code_tokens": ["def", "create_missing_file", "raise", "Errno", "::", "EISDIR", ",", "path", ".", "to_s", "if", "File", ".", "directory?", "(", "@path", ")", "return", "if", "File", ".", "exist?", "(", "@path", ")", "# Unnecessary check, probably.", "dirname", "=", "RealFile", ".", "dirname", "@path", "unless", "dirname", "==", "'.'", "dir", "=", "FileSystem", ".", "find", "dirname", "raise", "Errno", "::", "ENOENT", ",", "path", ".", "to_s", "unless", "dir", ".", "is_a?", "FakeDir", "end", "@file", "=", "FileSystem", ".", "add", "(", "path", ",", "FakeFile", ".", "new", ")", "end"], "docstring": "Create a missing file if the path is valid.", "docstring_tokens": ["Create", "a", "missing", "file", "if", "the", "path", "is", "valid", "."], "sha": "0561dfb66cbb6076c54d1ebf407677ee502cd9ab", "url": "https://github.com/fakefs/fakefs/blob/0561dfb66cbb6076c54d1ebf407677ee502cd9ab/lib/fakefs/file.rb#L885-L898", "partition": "test"} {"repo": "fakefs/fakefs", "path": "lib/fakefs/pathname.rb", "func_name": "FakeFS.Pathname.each_filename", "original_string": "def each_filename # :yield: filename\n return to_enum(__method__) unless block_given?\n _prefix, names = split_names(@path)\n names.each { |filename| yield filename }\n nil\n end", "language": "ruby", "code": "def each_filename # :yield: filename\n return to_enum(__method__) unless block_given?\n _prefix, names = split_names(@path)\n names.each { |filename| yield filename }\n nil\n end", "code_tokens": ["def", "each_filename", "# :yield: filename", "return", "to_enum", "(", "__method__", ")", "unless", "block_given?", "_prefix", ",", "names", "=", "split_names", "(", "@path", ")", "names", ".", "each", "{", "|", "filename", "|", "yield", "filename", "}", "nil", "end"], "docstring": "Iterates over each component of the path.\n\n Pathname.new(\"/usr/bin/ruby\").each_filename { |filename| ... }\n # yields \"usr\", \"bin\", and \"ruby\".", "docstring_tokens": ["Iterates", "over", "each", "component", "of", "the", "path", "."], "sha": "0561dfb66cbb6076c54d1ebf407677ee502cd9ab", "url": "https://github.com/fakefs/fakefs/blob/0561dfb66cbb6076c54d1ebf407677ee502cd9ab/lib/fakefs/pathname.rb#L231-L236", "partition": "test"} {"repo": "fakefs/fakefs", "path": "lib/fakefs/pathname.rb", "func_name": "FakeFS.Pathname.descend", "original_string": "def descend\n vs = []\n ascend { |v| vs << v }\n vs.reverse_each { |v| yield v }\n nil\n end", "language": "ruby", "code": "def descend\n vs = []\n ascend { |v| vs << v }\n vs.reverse_each { |v| yield v }\n nil\n end", "code_tokens": ["def", "descend", "vs", "=", "[", "]", "ascend", "{", "|", "v", "|", "vs", "<<", "v", "}", "vs", ".", "reverse_each", "{", "|", "v", "|", "yield", "v", "}", "nil", "end"], "docstring": "Iterates over and yields a new Pathname object\n for each element in the given path in descending order.\n\n Pathname.new('/path/to/some/file.rb').descend { |v| p v}\n #\n #\n #\n #\n #\n\n Pathname.new('path/to/some/file.rb').descend { |v| p v}\n #\n #\n #\n #\n\n It doesn't access actual filesystem.\n\n This method is available since 1.8.5.", "docstring_tokens": ["Iterates", "over", "and", "yields", "a", "new", "Pathname", "object", "for", "each", "element", "in", "the", "given", "path", "in", "descending", "order", "."], "sha": "0561dfb66cbb6076c54d1ebf407677ee502cd9ab", "url": "https://github.com/fakefs/fakefs/blob/0561dfb66cbb6076c54d1ebf407677ee502cd9ab/lib/fakefs/pathname.rb#L258-L263", "partition": "test"} {"repo": "fakefs/fakefs", "path": "lib/fakefs/pathname.rb", "func_name": "FakeFS.Pathname.ascend", "original_string": "def ascend\n path = @path\n yield self\n while (r = chop_basename(path))\n path, _name = r\n break if path.empty?\n yield self.class.new(del_trailing_separator(path))\n end\n end", "language": "ruby", "code": "def ascend\n path = @path\n yield self\n while (r = chop_basename(path))\n path, _name = r\n break if path.empty?\n yield self.class.new(del_trailing_separator(path))\n end\n end", "code_tokens": ["def", "ascend", "path", "=", "@path", "yield", "self", "while", "(", "r", "=", "chop_basename", "(", "path", ")", ")", "path", ",", "_name", "=", "r", "break", "if", "path", ".", "empty?", "yield", "self", ".", "class", ".", "new", "(", "del_trailing_separator", "(", "path", ")", ")", "end", "end"], "docstring": "Iterates over and yields a new Pathname object\n for each element in the given path in ascending order.\n\n Pathname.new('/path/to/some/file.rb').ascend { |v| p v}\n #\n #\n #\n #\n #\n\n Pathname.new('path/to/some/file.rb').ascend { |v| p v}\n #\n #\n #\n #\n\n It doesn't access actual filesystem.\n\n This method is available since 1.8.5.", "docstring_tokens": ["Iterates", "over", "and", "yields", "a", "new", "Pathname", "object", "for", "each", "element", "in", "the", "given", "path", "in", "ascending", "order", "."], "sha": "0561dfb66cbb6076c54d1ebf407677ee502cd9ab", "url": "https://github.com/fakefs/fakefs/blob/0561dfb66cbb6076c54d1ebf407677ee502cd9ab/lib/fakefs/pathname.rb#L285-L293", "partition": "test"} {"repo": "toretore/barby", "path": "lib/barby/barcode/code_93.rb", "func_name": "Barby.Code93.c_checksum", "original_string": "def c_checksum\n sum = 0\n checksum_values.each_with_index do |value, index|\n sum += ((index % 20) + 1) * value\n end\n sum % 47\n end", "language": "ruby", "code": "def c_checksum\n sum = 0\n checksum_values.each_with_index do |value, index|\n sum += ((index % 20) + 1) * value\n end\n sum % 47\n end", "code_tokens": ["def", "c_checksum", "sum", "=", "0", "checksum_values", ".", "each_with_index", "do", "|", "value", ",", "index", "|", "sum", "+=", "(", "(", "index", "%", "20", ")", "+", "1", ")", "*", "value", "end", "sum", "%", "47", "end"], "docstring": "Calculates the C checksum based on checksum_values", "docstring_tokens": ["Calculates", "the", "C", "checksum", "based", "on", "checksum_values"], "sha": "9e701373a3c811701aeb50fccbe7b08ab92aef45", "url": "https://github.com/toretore/barby/blob/9e701373a3c811701aeb50fccbe7b08ab92aef45/lib/barby/barcode/code_93.rb#L184-L190", "partition": "test"} {"repo": "toretore/barby", "path": "lib/barby/barcode/code_93.rb", "func_name": "Barby.Code93.k_checksum", "original_string": "def k_checksum\n sum = 0\n checksum_values_with_c_checksum.each_with_index do |value, index|\n sum += ((index % 15) + 1) * value\n end\n sum % 47\n end", "language": "ruby", "code": "def k_checksum\n sum = 0\n checksum_values_with_c_checksum.each_with_index do |value, index|\n sum += ((index % 15) + 1) * value\n end\n sum % 47\n end", "code_tokens": ["def", "k_checksum", "sum", "=", "0", "checksum_values_with_c_checksum", ".", "each_with_index", "do", "|", "value", ",", "index", "|", "sum", "+=", "(", "(", "index", "%", "15", ")", "+", "1", ")", "*", "value", "end", "sum", "%", "47", "end"], "docstring": "Calculates the K checksum based on checksum_values_with_c_checksum", "docstring_tokens": ["Calculates", "the", "K", "checksum", "based", "on", "checksum_values_with_c_checksum"], "sha": "9e701373a3c811701aeb50fccbe7b08ab92aef45", "url": "https://github.com/toretore/barby/blob/9e701373a3c811701aeb50fccbe7b08ab92aef45/lib/barby/barcode/code_93.rb#L202-L208", "partition": "test"} {"repo": "toretore/barby", "path": "lib/barby/outputter/pdfwriter_outputter.rb", "func_name": "Barby.PDFWriterOutputter.annotate_pdf", "original_string": "def annotate_pdf(pdf, options={})\n with_options options do\n\n xpos, ypos = x, y\n orig_xpos = xpos\n\n if barcode.two_dimensional?\n boolean_groups.reverse_each do |groups|\n groups.each do |bar,amount|\n if bar\n pdf.move_to(xpos, ypos).\n line_to(xpos, ypos+xdim).\n line_to(xpos+(xdim*amount), ypos+xdim).\n line_to(xpos+(xdim*amount), ypos).\n line_to(xpos, ypos).\n fill\n end\n xpos += (xdim*amount)\n end\n xpos = orig_xpos\n ypos += xdim\n end\n else\n boolean_groups.each do |bar,amount|\n if bar\n pdf.move_to(xpos, ypos).\n line_to(xpos, ypos+height).\n line_to(xpos+(xdim*amount), ypos+height).\n line_to(xpos+(xdim*amount), ypos).\n line_to(xpos, ypos).\n fill\n end\n xpos += (xdim*amount)\n end\n end\n\n end\n\n pdf\n end", "language": "ruby", "code": "def annotate_pdf(pdf, options={})\n with_options options do\n\n xpos, ypos = x, y\n orig_xpos = xpos\n\n if barcode.two_dimensional?\n boolean_groups.reverse_each do |groups|\n groups.each do |bar,amount|\n if bar\n pdf.move_to(xpos, ypos).\n line_to(xpos, ypos+xdim).\n line_to(xpos+(xdim*amount), ypos+xdim).\n line_to(xpos+(xdim*amount), ypos).\n line_to(xpos, ypos).\n fill\n end\n xpos += (xdim*amount)\n end\n xpos = orig_xpos\n ypos += xdim\n end\n else\n boolean_groups.each do |bar,amount|\n if bar\n pdf.move_to(xpos, ypos).\n line_to(xpos, ypos+height).\n line_to(xpos+(xdim*amount), ypos+height).\n line_to(xpos+(xdim*amount), ypos).\n line_to(xpos, ypos).\n fill\n end\n xpos += (xdim*amount)\n end\n end\n\n end\n\n pdf\n end", "code_tokens": ["def", "annotate_pdf", "(", "pdf", ",", "options", "=", "{", "}", ")", "with_options", "options", "do", "xpos", ",", "ypos", "=", "x", ",", "y", "orig_xpos", "=", "xpos", "if", "barcode", ".", "two_dimensional?", "boolean_groups", ".", "reverse_each", "do", "|", "groups", "|", "groups", ".", "each", "do", "|", "bar", ",", "amount", "|", "if", "bar", "pdf", ".", "move_to", "(", "xpos", ",", "ypos", ")", ".", "line_to", "(", "xpos", ",", "ypos", "+", "xdim", ")", ".", "line_to", "(", "xpos", "+", "(", "xdim", "amount", ")", ",", "ypos", "+", "xdim", ")", ".", "line_to", "(", "xpos", "+", "(", "xdim", "amount", ")", ",", "ypos", ")", ".", "line_to", "(", "xpos", ",", "ypos", ")", ".", "fill", "end", "xpos", "+=", "(", "xdim", "amount", ")", "end", "xpos", "=", "orig_xpos", "ypos", "+=", "xdim", "end", "else", "boolean_groups", ".", "each", "do", "|", "bar", ",", "amount", "|", "if", "bar", "pdf", ".", "move_to", "(", "xpos", ",", "ypos", ")", ".", "line_to", "(", "xpos", ",", "ypos", "+", "height", ")", ".", "line_to", "(", "xpos", "+", "(", "xdim", "amount", ")", ",", "ypos", "+", "height", ")", ".", "line_to", "(", "xpos", "+", "(", "xdim", "amount", ")", ",", "ypos", ")", ".", "line_to", "(", "xpos", ",", "ypos", ")", ".", "fill", "end", "xpos", "+=", "(", "xdim", "amount", ")", "end", "end", "end", "pdf", "end"], "docstring": "Annotate a PDFWriter document with the barcode\n\nValid options are:\n\nx, y - The point in the document to start rendering from\nheight - The height of the bars in PDF units\nxdim - The X dimension in PDF units", "docstring_tokens": ["Annotate", "a", "PDFWriter", "document", "with", "the", "barcode"], "sha": "9e701373a3c811701aeb50fccbe7b08ab92aef45", "url": "https://github.com/toretore/barby/blob/9e701373a3c811701aeb50fccbe7b08ab92aef45/lib/barby/outputter/pdfwriter_outputter.rb#L22-L61", "partition": "test"} {"repo": "toretore/barby", "path": "lib/barby/barcode/code_39.rb", "func_name": "Barby.Code39.characters", "original_string": "def characters\n chars = raw_characters\n extended ? chars.map{|c| EXTENDED_ENCODINGS[c].split(//) }.flatten : chars\n end", "language": "ruby", "code": "def characters\n chars = raw_characters\n extended ? chars.map{|c| EXTENDED_ENCODINGS[c].split(//) }.flatten : chars\n end", "code_tokens": ["def", "characters", "chars", "=", "raw_characters", "extended", "?", "chars", ".", "map", "{", "|", "c", "|", "EXTENDED_ENCODINGS", "[", "c", "]", ".", "split", "(", "/", "/", ")", "}", ".", "flatten", ":", "chars", "end"], "docstring": "Returns the encodable characters. If extended mode is enabled, each character will\nfirst be replaced by two characters from the encodable charset", "docstring_tokens": ["Returns", "the", "encodable", "characters", ".", "If", "extended", "mode", "is", "enabled", "each", "character", "will", "first", "be", "replaced", "by", "two", "characters", "from", "the", "encodable", "charset"], "sha": "9e701373a3c811701aeb50fccbe7b08ab92aef45", "url": "https://github.com/toretore/barby/blob/9e701373a3c811701aeb50fccbe7b08ab92aef45/lib/barby/barcode/code_39.rb#L111-L114", "partition": "test"} {"repo": "toretore/barby", "path": "lib/barby/barcode/code_128.rb", "func_name": "Barby.Code128.characters", "original_string": "def characters\n chars = data.split(//n)\n\n if type == 'C'\n result = []\n count = 0\n while count < chars.size\n if chars[count] =~ /^\\d$/\n #If encountering a digit, next char/byte *must* be second digit in pair. I.e. if chars[count] is 5,\n #chars[count+1] must be /[0-9]/, otherwise it's not valid\n result << \"#{chars[count]}#{chars[count+1]}\"\n count += 2\n else\n result << chars[count]\n count += 1\n end\n end\n result\n else\n chars\n end\n end", "language": "ruby", "code": "def characters\n chars = data.split(//n)\n\n if type == 'C'\n result = []\n count = 0\n while count < chars.size\n if chars[count] =~ /^\\d$/\n #If encountering a digit, next char/byte *must* be second digit in pair. I.e. if chars[count] is 5,\n #chars[count+1] must be /[0-9]/, otherwise it's not valid\n result << \"#{chars[count]}#{chars[count+1]}\"\n count += 2\n else\n result << chars[count]\n count += 1\n end\n end\n result\n else\n chars\n end\n end", "code_tokens": ["def", "characters", "chars", "=", "data", ".", "split", "(", "/", "/n", ")", "if", "type", "==", "'C'", "result", "=", "[", "]", "count", "=", "0", "while", "count", "<", "chars", ".", "size", "if", "chars", "[", "count", "]", "=~", "/", "\\d", "/", "#If encountering a digit, next char/byte *must* be second digit in pair. I.e. if chars[count] is 5,", "#chars[count+1] must be /[0-9]/, otherwise it's not valid", "result", "<<", "\"#{chars[count]}#{chars[count+1]}\"", "count", "+=", "2", "else", "result", "<<", "chars", "[", "count", "]", "count", "+=", "1", "end", "end", "result", "else", "chars", "end", "end"], "docstring": "Get an array of the individual characters for this barcode. Special\ncharacters like FNC1 will be present. Characters from extras are not\npresent.", "docstring_tokens": ["Get", "an", "array", "of", "the", "individual", "characters", "for", "this", "barcode", ".", "Special", "characters", "like", "FNC1", "will", "be", "present", ".", "Characters", "from", "extras", "are", "not", "present", "."], "sha": "9e701373a3c811701aeb50fccbe7b08ab92aef45", "url": "https://github.com/toretore/barby/blob/9e701373a3c811701aeb50fccbe7b08ab92aef45/lib/barby/barcode/code_128.rb#L257-L278", "partition": "test"} {"repo": "toretore/barby", "path": "lib/barby/barcode/code_128.rb", "func_name": "Barby.Code128.checksum", "original_string": "def checksum\n pos = 0\n (numbers+extra_numbers).inject(start_num) do |sum,number|\n pos += 1\n sum + (number * pos)\n end % 103\n end", "language": "ruby", "code": "def checksum\n pos = 0\n (numbers+extra_numbers).inject(start_num) do |sum,number|\n pos += 1\n sum + (number * pos)\n end % 103\n end", "code_tokens": ["def", "checksum", "pos", "=", "0", "(", "numbers", "+", "extra_numbers", ")", ".", "inject", "(", "start_num", ")", "do", "|", "sum", ",", "number", "|", "pos", "+=", "1", "sum", "+", "(", "number", "*", "pos", ")", "end", "%", "103", "end"], "docstring": "Calculate the checksum for the data in this barcode. The data includes\ndata from extras.", "docstring_tokens": ["Calculate", "the", "checksum", "for", "the", "data", "in", "this", "barcode", ".", "The", "data", "includes", "data", "from", "extras", "."], "sha": "9e701373a3c811701aeb50fccbe7b08ab92aef45", "url": "https://github.com/toretore/barby/blob/9e701373a3c811701aeb50fccbe7b08ab92aef45/lib/barby/barcode/code_128.rb#L307-L313", "partition": "test"} {"repo": "toretore/barby", "path": "lib/barby/barcode/code_25.rb", "func_name": "Barby.Code25.encoding_for_bars", "original_string": "def encoding_for_bars(*bars)\n wide, narrow, space = wide_encoding, narrow_encoding, space_encoding\n bars.flatten.inject '' do |enc,bar|\n enc + (bar == WIDE ? wide : narrow) + space\n end\n end", "language": "ruby", "code": "def encoding_for_bars(*bars)\n wide, narrow, space = wide_encoding, narrow_encoding, space_encoding\n bars.flatten.inject '' do |enc,bar|\n enc + (bar == WIDE ? wide : narrow) + space\n end\n end", "code_tokens": ["def", "encoding_for_bars", "(", "*", "bars", ")", "wide", ",", "narrow", ",", "space", "=", "wide_encoding", ",", "narrow_encoding", ",", "space_encoding", "bars", ".", "flatten", ".", "inject", "''", "do", "|", "enc", ",", "bar", "|", "enc", "+", "(", "bar", "==", "WIDE", "?", "wide", ":", "narrow", ")", "+", "space", "end", "end"], "docstring": "Generate encoding for an array of W,N", "docstring_tokens": ["Generate", "encoding", "for", "an", "array", "of", "W", "N"], "sha": "9e701373a3c811701aeb50fccbe7b08ab92aef45", "url": "https://github.com/toretore/barby/blob/9e701373a3c811701aeb50fccbe7b08ab92aef45/lib/barby/barcode/code_25.rb#L96-L101", "partition": "test"} {"repo": "toretore/barby", "path": "lib/barby/outputter/cairo_outputter.rb", "func_name": "Barby.CairoOutputter.render_to_cairo_context", "original_string": "def render_to_cairo_context(context, options={})\n if context.respond_to?(:have_current_point?) and\n context.have_current_point?\n current_x, current_y = context.current_point\n else\n current_x = x(options) || margin(options)\n current_y = y(options) || margin(options)\n end\n\n _xdim = xdim(options)\n _height = height(options)\n original_current_x = current_x\n context.save do\n context.set_source_color(:black)\n context.fill do\n if barcode.two_dimensional?\n boolean_groups.each do |groups|\n groups.each do |bar,amount|\n current_width = _xdim * amount\n if bar\n context.rectangle(current_x, current_y, current_width, _xdim)\n end\n current_x += current_width\n end\n current_x = original_current_x\n current_y += _xdim\n end\n else\n boolean_groups.each do |bar,amount|\n current_width = _xdim * amount\n if bar\n context.rectangle(current_x, current_y, current_width, _height)\n end\n current_x += current_width\n end\n end\n end\n end\n\n context\n end", "language": "ruby", "code": "def render_to_cairo_context(context, options={})\n if context.respond_to?(:have_current_point?) and\n context.have_current_point?\n current_x, current_y = context.current_point\n else\n current_x = x(options) || margin(options)\n current_y = y(options) || margin(options)\n end\n\n _xdim = xdim(options)\n _height = height(options)\n original_current_x = current_x\n context.save do\n context.set_source_color(:black)\n context.fill do\n if barcode.two_dimensional?\n boolean_groups.each do |groups|\n groups.each do |bar,amount|\n current_width = _xdim * amount\n if bar\n context.rectangle(current_x, current_y, current_width, _xdim)\n end\n current_x += current_width\n end\n current_x = original_current_x\n current_y += _xdim\n end\n else\n boolean_groups.each do |bar,amount|\n current_width = _xdim * amount\n if bar\n context.rectangle(current_x, current_y, current_width, _height)\n end\n current_x += current_width\n end\n end\n end\n end\n\n context\n end", "code_tokens": ["def", "render_to_cairo_context", "(", "context", ",", "options", "=", "{", "}", ")", "if", "context", ".", "respond_to?", "(", ":have_current_point?", ")", "and", "context", ".", "have_current_point?", "current_x", ",", "current_y", "=", "context", ".", "current_point", "else", "current_x", "=", "x", "(", "options", ")", "||", "margin", "(", "options", ")", "current_y", "=", "y", "(", "options", ")", "||", "margin", "(", "options", ")", "end", "_xdim", "=", "xdim", "(", "options", ")", "_height", "=", "height", "(", "options", ")", "original_current_x", "=", "current_x", "context", ".", "save", "do", "context", ".", "set_source_color", "(", ":black", ")", "context", ".", "fill", "do", "if", "barcode", ".", "two_dimensional?", "boolean_groups", ".", "each", "do", "|", "groups", "|", "groups", ".", "each", "do", "|", "bar", ",", "amount", "|", "current_width", "=", "_xdim", "*", "amount", "if", "bar", "context", ".", "rectangle", "(", "current_x", ",", "current_y", ",", "current_width", ",", "_xdim", ")", "end", "current_x", "+=", "current_width", "end", "current_x", "=", "original_current_x", "current_y", "+=", "_xdim", "end", "else", "boolean_groups", ".", "each", "do", "|", "bar", ",", "amount", "|", "current_width", "=", "_xdim", "*", "amount", "if", "bar", "context", ".", "rectangle", "(", "current_x", ",", "current_y", ",", "current_width", ",", "_height", ")", "end", "current_x", "+=", "current_width", "end", "end", "end", "end", "context", "end"], "docstring": "Render the barcode onto a Cairo context", "docstring_tokens": ["Render", "the", "barcode", "onto", "a", "Cairo", "context"], "sha": "9e701373a3c811701aeb50fccbe7b08ab92aef45", "url": "https://github.com/toretore/barby/blob/9e701373a3c811701aeb50fccbe7b08ab92aef45/lib/barby/outputter/cairo_outputter.rb#L32-L72", "partition": "test"} {"repo": "toretore/barby", "path": "lib/barby/outputter/cairo_outputter.rb", "func_name": "Barby.CairoOutputter.to_png", "original_string": "def to_png(options={})\n output_to_string_io do |io|\n Cairo::ImageSurface.new(options[:format],\n full_width(options),\n full_height(options)) do |surface|\n render(surface, options)\n surface.write_to_png(io)\n end\n end\n end", "language": "ruby", "code": "def to_png(options={})\n output_to_string_io do |io|\n Cairo::ImageSurface.new(options[:format],\n full_width(options),\n full_height(options)) do |surface|\n render(surface, options)\n surface.write_to_png(io)\n end\n end\n end", "code_tokens": ["def", "to_png", "(", "options", "=", "{", "}", ")", "output_to_string_io", "do", "|", "io", "|", "Cairo", "::", "ImageSurface", ".", "new", "(", "options", "[", ":format", "]", ",", "full_width", "(", "options", ")", ",", "full_height", "(", "options", ")", ")", "do", "|", "surface", "|", "render", "(", "surface", ",", "options", ")", "surface", ".", "write_to_png", "(", "io", ")", "end", "end", "end"], "docstring": "Render the barcode to a PNG image", "docstring_tokens": ["Render", "the", "barcode", "to", "a", "PNG", "image"], "sha": "9e701373a3c811701aeb50fccbe7b08ab92aef45", "url": "https://github.com/toretore/barby/blob/9e701373a3c811701aeb50fccbe7b08ab92aef45/lib/barby/outputter/cairo_outputter.rb#L76-L85", "partition": "test"} {"repo": "toretore/barby", "path": "lib/barby/outputter/cairo_outputter.rb", "func_name": "Barby.CairoOutputter.to_ps", "original_string": "def to_ps(options={})\n output_to_string_io do |io|\n Cairo::PSSurface.new(io,\n full_width(options),\n full_height(options)) do |surface|\n surface.eps = options[:eps] if surface.respond_to?(:eps=)\n render(surface, options)\n end\n end\n end", "language": "ruby", "code": "def to_ps(options={})\n output_to_string_io do |io|\n Cairo::PSSurface.new(io,\n full_width(options),\n full_height(options)) do |surface|\n surface.eps = options[:eps] if surface.respond_to?(:eps=)\n render(surface, options)\n end\n end\n end", "code_tokens": ["def", "to_ps", "(", "options", "=", "{", "}", ")", "output_to_string_io", "do", "|", "io", "|", "Cairo", "::", "PSSurface", ".", "new", "(", "io", ",", "full_width", "(", "options", ")", ",", "full_height", "(", "options", ")", ")", "do", "|", "surface", "|", "surface", ".", "eps", "=", "options", "[", ":eps", "]", "if", "surface", ".", "respond_to?", "(", ":eps=", ")", "render", "(", "surface", ",", "options", ")", "end", "end", "end"], "docstring": "Render the barcode to a PS document", "docstring_tokens": ["Render", "the", "barcode", "to", "a", "PS", "document"], "sha": "9e701373a3c811701aeb50fccbe7b08ab92aef45", "url": "https://github.com/toretore/barby/blob/9e701373a3c811701aeb50fccbe7b08ab92aef45/lib/barby/outputter/cairo_outputter.rb#L89-L98", "partition": "test"} {"repo": "toretore/barby", "path": "lib/barby/outputter/cairo_outputter.rb", "func_name": "Barby.CairoOutputter.to_pdf", "original_string": "def to_pdf(options={})\n output_to_string_io do |io|\n Cairo::PDFSurface.new(io,\n full_width(options),\n full_height(options)) do |surface|\n render(surface, options)\n end\n end\n end", "language": "ruby", "code": "def to_pdf(options={})\n output_to_string_io do |io|\n Cairo::PDFSurface.new(io,\n full_width(options),\n full_height(options)) do |surface|\n render(surface, options)\n end\n end\n end", "code_tokens": ["def", "to_pdf", "(", "options", "=", "{", "}", ")", "output_to_string_io", "do", "|", "io", "|", "Cairo", "::", "PDFSurface", ".", "new", "(", "io", ",", "full_width", "(", "options", ")", ",", "full_height", "(", "options", ")", ")", "do", "|", "surface", "|", "render", "(", "surface", ",", "options", ")", "end", "end", "end"], "docstring": "Render the barcode to a PDF document", "docstring_tokens": ["Render", "the", "barcode", "to", "a", "PDF", "document"], "sha": "9e701373a3c811701aeb50fccbe7b08ab92aef45", "url": "https://github.com/toretore/barby/blob/9e701373a3c811701aeb50fccbe7b08ab92aef45/lib/barby/outputter/cairo_outputter.rb#L108-L116", "partition": "test"} {"repo": "toretore/barby", "path": "lib/barby/outputter/cairo_outputter.rb", "func_name": "Barby.CairoOutputter.to_svg", "original_string": "def to_svg(options={})\n output_to_string_io do |io|\n Cairo::SVGSurface.new(io,\n full_width(options),\n full_height(options)) do |surface|\n render(surface, options)\n end\n end\n end", "language": "ruby", "code": "def to_svg(options={})\n output_to_string_io do |io|\n Cairo::SVGSurface.new(io,\n full_width(options),\n full_height(options)) do |surface|\n render(surface, options)\n end\n end\n end", "code_tokens": ["def", "to_svg", "(", "options", "=", "{", "}", ")", "output_to_string_io", "do", "|", "io", "|", "Cairo", "::", "SVGSurface", ".", "new", "(", "io", ",", "full_width", "(", "options", ")", ",", "full_height", "(", "options", ")", ")", "do", "|", "surface", "|", "render", "(", "surface", ",", "options", ")", "end", "end", "end"], "docstring": "Render the barcode to an SVG document", "docstring_tokens": ["Render", "the", "barcode", "to", "an", "SVG", "document"], "sha": "9e701373a3c811701aeb50fccbe7b08ab92aef45", "url": "https://github.com/toretore/barby/blob/9e701373a3c811701aeb50fccbe7b08ab92aef45/lib/barby/outputter/cairo_outputter.rb#L120-L128", "partition": "test"} {"repo": "wpscanteam/CMSScanner", "path": "lib/cms_scanner/browser/options.rb", "func_name": "CMSScanner.Browser.max_threads=", "original_string": "def max_threads=(number)\n @max_threads = number.to_i.positive? && throttle.zero? ? number.to_i : 1\n\n hydra.max_concurrency = @max_threads\n end", "language": "ruby", "code": "def max_threads=(number)\n @max_threads = number.to_i.positive? && throttle.zero? ? number.to_i : 1\n\n hydra.max_concurrency = @max_threads\n end", "code_tokens": ["def", "max_threads", "=", "(", "number", ")", "@max_threads", "=", "number", ".", "to_i", ".", "positive?", "&&", "throttle", ".", "zero?", "?", "number", ".", "to_i", ":", "1", "hydra", ".", "max_concurrency", "=", "@max_threads", "end"], "docstring": "Set the threads attribute and update hydra accordinly\n If the throttle attribute is > 0, max_threads will be forced to 1\n\n @param [ Integer ] number", "docstring_tokens": ["Set", "the", "threads", "attribute", "and", "update", "hydra", "accordinly", "If", "the", "throttle", "attribute", "is", ">", "0", "max_threads", "will", "be", "forced", "to", "1"], "sha": "07b169d3e97b742f4e94473a1180cb6c4506465f", "url": "https://github.com/wpscanteam/CMSScanner/blob/07b169d3e97b742f4e94473a1180cb6c4506465f/lib/cms_scanner/browser/options.rb#L48-L52", "partition": "test"} {"repo": "wpscanteam/CMSScanner", "path": "lib/cms_scanner/web_site.rb", "func_name": "CMSScanner.WebSite.online?", "original_string": "def online?(path = nil)\n NS::Browser.get(url(path)).code.nonzero? ? true : false\n end", "language": "ruby", "code": "def online?(path = nil)\n NS::Browser.get(url(path)).code.nonzero? ? true : false\n end", "code_tokens": ["def", "online?", "(", "path", "=", "nil", ")", "NS", "::", "Browser", ".", "get", "(", "url", "(", "path", ")", ")", ".", "code", ".", "nonzero?", "?", "true", ":", "false", "end"], "docstring": "Checks if the remote website is up.\n\n @param [ String ] path\n\n @return [ Boolean ]", "docstring_tokens": ["Checks", "if", "the", "remote", "website", "is", "up", "."], "sha": "07b169d3e97b742f4e94473a1180cb6c4506465f", "url": "https://github.com/wpscanteam/CMSScanner/blob/07b169d3e97b742f4e94473a1180cb6c4506465f/lib/cms_scanner/web_site.rb#L63-L65", "partition": "test"} {"repo": "wpscanteam/CMSScanner", "path": "lib/cms_scanner/web_site.rb", "func_name": "CMSScanner.WebSite.head_and_get", "original_string": "def head_and_get(path, codes = [200], params = {})\n url_to_get = url(path)\n head_params = (params[:head] || {}).merge(head_or_get_params)\n\n head_res = NS::Browser.forge_request(url_to_get, head_params).run\n\n codes.include?(head_res.code) ? NS::Browser.get(url_to_get, params[:get] || {}) : head_res\n end", "language": "ruby", "code": "def head_and_get(path, codes = [200], params = {})\n url_to_get = url(path)\n head_params = (params[:head] || {}).merge(head_or_get_params)\n\n head_res = NS::Browser.forge_request(url_to_get, head_params).run\n\n codes.include?(head_res.code) ? NS::Browser.get(url_to_get, params[:get] || {}) : head_res\n end", "code_tokens": ["def", "head_and_get", "(", "path", ",", "codes", "=", "[", "200", "]", ",", "params", "=", "{", "}", ")", "url_to_get", "=", "url", "(", "path", ")", "head_params", "=", "(", "params", "[", ":head", "]", "||", "{", "}", ")", ".", "merge", "(", "head_or_get_params", ")", "head_res", "=", "NS", "::", "Browser", ".", "forge_request", "(", "url_to_get", ",", "head_params", ")", ".", "run", "codes", ".", "include?", "(", "head_res", ".", "code", ")", "?", "NS", "::", "Browser", ".", "get", "(", "url_to_get", ",", "params", "[", ":get", "]", "||", "{", "}", ")", ":", "head_res", "end"], "docstring": "Perform a HEAD request to the path provided, then if its response code\n is in the array of codes given, a GET is done and the response returned. Otherwise the\n HEAD response is returned.\n\n @param [ String ] path\n @param [ Array ] codes\n @param [ Hash ] params The requests params\n @option params [ Hash ] :head Request params for the HEAD\n @option params [ hash ] :get Request params for the GET\n\n @return [ Typhoeus::Response ]", "docstring_tokens": ["Perform", "a", "HEAD", "request", "to", "the", "path", "provided", "then", "if", "its", "response", "code", "is", "in", "the", "array", "of", "codes", "given", "a", "GET", "is", "done", "and", "the", "response", "returned", ".", "Otherwise", "the", "HEAD", "response", "is", "returned", "."], "sha": "07b169d3e97b742f4e94473a1180cb6c4506465f", "url": "https://github.com/wpscanteam/CMSScanner/blob/07b169d3e97b742f4e94473a1180cb6c4506465f/lib/cms_scanner/web_site.rb#L125-L132", "partition": "test"} {"repo": "gousiosg/github-mirror", "path": "lib/ghtorrent/ghtorrent.rb", "func_name": "GHTorrent.Mirror.db", "original_string": "def db\n return @db unless @db.nil?\n\n Sequel.single_threaded = true\n @db = Sequel.connect(config(:sql_url), :encoding => 'utf8')\n #@db.loggers << Logger.new(STDOUT)\n if @db.tables.empty?\n dir = File.join(File.dirname(__FILE__), 'migrations')\n puts \"Database empty, running migrations from #{dir}\"\n Sequel.extension :migration\n Sequel::Migrator.apply(@db, dir)\n end\n\n @db\n end", "language": "ruby", "code": "def db\n return @db unless @db.nil?\n\n Sequel.single_threaded = true\n @db = Sequel.connect(config(:sql_url), :encoding => 'utf8')\n #@db.loggers << Logger.new(STDOUT)\n if @db.tables.empty?\n dir = File.join(File.dirname(__FILE__), 'migrations')\n puts \"Database empty, running migrations from #{dir}\"\n Sequel.extension :migration\n Sequel::Migrator.apply(@db, dir)\n end\n\n @db\n end", "code_tokens": ["def", "db", "return", "@db", "unless", "@db", ".", "nil?", "Sequel", ".", "single_threaded", "=", "true", "@db", "=", "Sequel", ".", "connect", "(", "config", "(", ":sql_url", ")", ",", ":encoding", "=>", "'utf8'", ")", "#@db.loggers << Logger.new(STDOUT)", "if", "@db", ".", "tables", ".", "empty?", "dir", "=", "File", ".", "join", "(", "File", ".", "dirname", "(", "__FILE__", ")", ",", "'migrations'", ")", "puts", "\"Database empty, running migrations from #{dir}\"", "Sequel", ".", "extension", ":migration", "Sequel", "::", "Migrator", ".", "apply", "(", "@db", ",", "dir", ")", "end", "@db", "end"], "docstring": "Get a connection to the database", "docstring_tokens": ["Get", "a", "connection", "to", "the", "database"], "sha": "3566294a3e4a4c7574bc7376f7e6a9435529b5de", "url": "https://github.com/gousiosg/github-mirror/blob/3566294a3e4a4c7574bc7376f7e6a9435529b5de/lib/ghtorrent/ghtorrent.rb#L38-L52", "partition": "test"} {"repo": "gousiosg/github-mirror", "path": "lib/ghtorrent/ghtorrent.rb", "func_name": "GHTorrent.Mirror.ensure_commit", "original_string": "def ensure_commit(repo, sha, user, comments = true)\n ensure_repo(user, repo)\n c = retrieve_commit(repo, sha, user)\n\n if c.nil?\n warn \"Commit #{user}/#{repo} -> #{sha} does not exist\"\n return\n end\n\n stored = store_commit(c, repo, user)\n ensure_parents(c)\n if not c['commit']['comment_count'].nil? \\\n and c['commit']['comment_count'] > 0\n ensure_commit_comments(user, repo, sha) if comments\n end\n ensure_repo_commit(user, repo, sha)\n stored\n end", "language": "ruby", "code": "def ensure_commit(repo, sha, user, comments = true)\n ensure_repo(user, repo)\n c = retrieve_commit(repo, sha, user)\n\n if c.nil?\n warn \"Commit #{user}/#{repo} -> #{sha} does not exist\"\n return\n end\n\n stored = store_commit(c, repo, user)\n ensure_parents(c)\n if not c['commit']['comment_count'].nil? \\\n and c['commit']['comment_count'] > 0\n ensure_commit_comments(user, repo, sha) if comments\n end\n ensure_repo_commit(user, repo, sha)\n stored\n end", "code_tokens": ["def", "ensure_commit", "(", "repo", ",", "sha", ",", "user", ",", "comments", "=", "true", ")", "ensure_repo", "(", "user", ",", "repo", ")", "c", "=", "retrieve_commit", "(", "repo", ",", "sha", ",", "user", ")", "if", "c", ".", "nil?", "warn", "\"Commit #{user}/#{repo} -> #{sha} does not exist\"", "return", "end", "stored", "=", "store_commit", "(", "c", ",", "repo", ",", "user", ")", "ensure_parents", "(", "c", ")", "if", "not", "c", "[", "'commit'", "]", "[", "'comment_count'", "]", ".", "nil?", "and", "c", "[", "'commit'", "]", "[", "'comment_count'", "]", ">", "0", "ensure_commit_comments", "(", "user", ",", "repo", ",", "sha", ")", "if", "comments", "end", "ensure_repo_commit", "(", "user", ",", "repo", ",", "sha", ")", "stored", "end"], "docstring": "Make sure a commit exists", "docstring_tokens": ["Make", "sure", "a", "commit", "exists"], "sha": "3566294a3e4a4c7574bc7376f7e6a9435529b5de", "url": "https://github.com/gousiosg/github-mirror/blob/3566294a3e4a4c7574bc7376f7e6a9435529b5de/lib/ghtorrent/ghtorrent.rb#L67-L84", "partition": "test"} {"repo": "gousiosg/github-mirror", "path": "lib/ghtorrent/ghtorrent.rb", "func_name": "GHTorrent.Mirror.ensure_parents", "original_string": "def ensure_parents(commit)\n commits = db[:commits]\n parents = db[:commit_parents]\n commit['parents'].map do |p|\n save do\n url = p['url'].split(/\\//)\n this = commits.first(:sha => commit['sha'])\n parent = commits.first(:sha => url[7])\n\n if parent.nil?\n c = retrieve_commit(url[5], url[7], url[4])\n if c.nil?\n warn \"Could not retrieve commit_parent #{url[4]}/#{url[5]} -> #{url[7]} to #{this[:sha]}\"\n next\n end\n parent = store_commit(c, url[5], url[4])\n end\n\n if parent.nil?\n warn \"Could not find #{url[4]}/#{url[5]} -> #{url[7]}, parent to commit #{this[:sha]}\"\n next\n end\n\n if parents.first(:commit_id => this[:id],\n :parent_id => parent[:id]).nil?\n\n parents.insert(:commit_id => this[:id],\n :parent_id => parent[:id])\n info \"Added commit_parent #{parent[:sha]} to commit #{this[:sha]}\"\n else\n debug \"Parent #{parent[:sha]} for commit #{this[:sha]} exists\"\n end\n parents.first(:commit_id => this[:id], :parent_id => parent[:id])\n end\n end.select{|x| !x.nil?}\n end", "language": "ruby", "code": "def ensure_parents(commit)\n commits = db[:commits]\n parents = db[:commit_parents]\n commit['parents'].map do |p|\n save do\n url = p['url'].split(/\\//)\n this = commits.first(:sha => commit['sha'])\n parent = commits.first(:sha => url[7])\n\n if parent.nil?\n c = retrieve_commit(url[5], url[7], url[4])\n if c.nil?\n warn \"Could not retrieve commit_parent #{url[4]}/#{url[5]} -> #{url[7]} to #{this[:sha]}\"\n next\n end\n parent = store_commit(c, url[5], url[4])\n end\n\n if parent.nil?\n warn \"Could not find #{url[4]}/#{url[5]} -> #{url[7]}, parent to commit #{this[:sha]}\"\n next\n end\n\n if parents.first(:commit_id => this[:id],\n :parent_id => parent[:id]).nil?\n\n parents.insert(:commit_id => this[:id],\n :parent_id => parent[:id])\n info \"Added commit_parent #{parent[:sha]} to commit #{this[:sha]}\"\n else\n debug \"Parent #{parent[:sha]} for commit #{this[:sha]} exists\"\n end\n parents.first(:commit_id => this[:id], :parent_id => parent[:id])\n end\n end.select{|x| !x.nil?}\n end", "code_tokens": ["def", "ensure_parents", "(", "commit", ")", "commits", "=", "db", "[", ":commits", "]", "parents", "=", "db", "[", ":commit_parents", "]", "commit", "[", "'parents'", "]", ".", "map", "do", "|", "p", "|", "save", "do", "url", "=", "p", "[", "'url'", "]", ".", "split", "(", "/", "\\/", "/", ")", "this", "=", "commits", ".", "first", "(", ":sha", "=>", "commit", "[", "'sha'", "]", ")", "parent", "=", "commits", ".", "first", "(", ":sha", "=>", "url", "[", "7", "]", ")", "if", "parent", ".", "nil?", "c", "=", "retrieve_commit", "(", "url", "[", "5", "]", ",", "url", "[", "7", "]", ",", "url", "[", "4", "]", ")", "if", "c", ".", "nil?", "warn", "\"Could not retrieve commit_parent #{url[4]}/#{url[5]} -> #{url[7]} to #{this[:sha]}\"", "next", "end", "parent", "=", "store_commit", "(", "c", ",", "url", "[", "5", "]", ",", "url", "[", "4", "]", ")", "end", "if", "parent", ".", "nil?", "warn", "\"Could not find #{url[4]}/#{url[5]} -> #{url[7]}, parent to commit #{this[:sha]}\"", "next", "end", "if", "parents", ".", "first", "(", ":commit_id", "=>", "this", "[", ":id", "]", ",", ":parent_id", "=>", "parent", "[", ":id", "]", ")", ".", "nil?", "parents", ".", "insert", "(", ":commit_id", "=>", "this", "[", ":id", "]", ",", ":parent_id", "=>", "parent", "[", ":id", "]", ")", "info", "\"Added commit_parent #{parent[:sha]} to commit #{this[:sha]}\"", "else", "debug", "\"Parent #{parent[:sha]} for commit #{this[:sha]} exists\"", "end", "parents", ".", "first", "(", ":commit_id", "=>", "this", "[", ":id", "]", ",", ":parent_id", "=>", "parent", "[", ":id", "]", ")", "end", "end", ".", "select", "{", "|", "x", "|", "!", "x", ".", "nil?", "}", "end"], "docstring": "Get the parents for a specific commit. The commit must be first stored\n in the database.", "docstring_tokens": ["Get", "the", "parents", "for", "a", "specific", "commit", ".", "The", "commit", "must", "be", "first", "stored", "in", "the", "database", "."], "sha": "3566294a3e4a4c7574bc7376f7e6a9435529b5de", "url": "https://github.com/gousiosg/github-mirror/blob/3566294a3e4a4c7574bc7376f7e6a9435529b5de/lib/ghtorrent/ghtorrent.rb#L144-L179", "partition": "test"} {"repo": "gousiosg/github-mirror", "path": "lib/ghtorrent/ghtorrent.rb", "func_name": "GHTorrent.Mirror.ensure_user_followers", "original_string": "def ensure_user_followers(followed)\n curuser = ensure_user(followed, false, false)\n followers = db.from(:followers, :users).\\\n where(Sequel.qualify('followers', 'follower_id') => Sequel.qualify('users', 'id')).\\\n where(Sequel.qualify('followers', 'user_id') => curuser[:id]).select(:login).all\n\n retrieve_user_followers(followed).reduce([]) do |acc, x|\n if followers.find {|y| y[:login] == x['login']}.nil?\n acc << x\n else\n acc\n end\n end.map { |x| save{ensure_user_follower(followed, x['login']) }}.select{|x| !x.nil?}\n end", "language": "ruby", "code": "def ensure_user_followers(followed)\n curuser = ensure_user(followed, false, false)\n followers = db.from(:followers, :users).\\\n where(Sequel.qualify('followers', 'follower_id') => Sequel.qualify('users', 'id')).\\\n where(Sequel.qualify('followers', 'user_id') => curuser[:id]).select(:login).all\n\n retrieve_user_followers(followed).reduce([]) do |acc, x|\n if followers.find {|y| y[:login] == x['login']}.nil?\n acc << x\n else\n acc\n end\n end.map { |x| save{ensure_user_follower(followed, x['login']) }}.select{|x| !x.nil?}\n end", "code_tokens": ["def", "ensure_user_followers", "(", "followed", ")", "curuser", "=", "ensure_user", "(", "followed", ",", "false", ",", "false", ")", "followers", "=", "db", ".", "from", "(", ":followers", ",", ":users", ")", ".", "where", "(", "Sequel", ".", "qualify", "(", "'followers'", ",", "'follower_id'", ")", "=>", "Sequel", ".", "qualify", "(", "'users'", ",", "'id'", ")", ")", ".", "where", "(", "Sequel", ".", "qualify", "(", "'followers'", ",", "'user_id'", ")", "=>", "curuser", "[", ":id", "]", ")", ".", "select", "(", ":login", ")", ".", "all", "retrieve_user_followers", "(", "followed", ")", ".", "reduce", "(", "[", "]", ")", "do", "|", "acc", ",", "x", "|", "if", "followers", ".", "find", "{", "|", "y", "|", "y", "[", ":login", "]", "==", "x", "[", "'login'", "]", "}", ".", "nil?", "acc", "<<", "x", "else", "acc", "end", "end", ".", "map", "{", "|", "x", "|", "save", "{", "ensure_user_follower", "(", "followed", ",", "x", "[", "'login'", "]", ")", "}", "}", ".", "select", "{", "|", "x", "|", "!", "x", ".", "nil?", "}", "end"], "docstring": "Get all followers for a user. Since we do not know when the actual\n follow event took place, we set the created_at field to the timestamp\n of the method call.\n\n ==Parameters:\n [user] The user login to find followers by", "docstring_tokens": ["Get", "all", "followers", "for", "a", "user", ".", "Since", "we", "do", "not", "know", "when", "the", "actual", "follow", "event", "took", "place", "we", "set", "the", "created_at", "field", "to", "the", "timestamp", "of", "the", "method", "call", "."], "sha": "3566294a3e4a4c7574bc7376f7e6a9435529b5de", "url": "https://github.com/gousiosg/github-mirror/blob/3566294a3e4a4c7574bc7376f7e6a9435529b5de/lib/ghtorrent/ghtorrent.rb#L399-L412", "partition": "test"} {"repo": "gousiosg/github-mirror", "path": "lib/ghtorrent/ghtorrent.rb", "func_name": "GHTorrent.Mirror.ensure_user_follower", "original_string": "def ensure_user_follower(followed, follower, date_added = nil)\n follower_user = ensure_user(follower, false, false)\n followed_user = ensure_user(followed, false, false)\n\n if followed_user.nil? or follower_user.nil?\n warn \"Could not find follower #{follower} or user #{followed}\"\n return\n end\n\n followers = db[:followers]\n follower_id = follower_user[:id]\n followed_id = followed_user[:id]\n\n follower_exists = followers.first(:user_id => followed_id,\n :follower_id => follower_id)\n if follower_exists.nil?\n added = if date_added.nil?\n max(follower_user[:created_at], followed_user[:created_at])\n else\n date_added\n end\n retrieved = retrieve_user_follower(followed, follower)\n\n if retrieved.nil?\n warn \"Could not retrieve follower #{follower} for #{followed}\"\n return\n end\n\n followers.insert(:user_id => followed_id,\n :follower_id => follower_id,\n :created_at => added)\n info \"Added follower #{follower} to #{followed}\"\n else\n debug \"Follower #{follower} for user #{followed} exists\"\n end\n\n unless date_added.nil?\n followers.filter(:user_id => followed_id, :follower_id => follower_id)\n .update(:created_at => date(date_added))\n info \"Updated follower #{followed} -> #{follower}, created_at -> #{date(date_added)}\"\n end\n\n followers.first(:user_id => followed_id, :follower_id => follower_id)\n end", "language": "ruby", "code": "def ensure_user_follower(followed, follower, date_added = nil)\n follower_user = ensure_user(follower, false, false)\n followed_user = ensure_user(followed, false, false)\n\n if followed_user.nil? or follower_user.nil?\n warn \"Could not find follower #{follower} or user #{followed}\"\n return\n end\n\n followers = db[:followers]\n follower_id = follower_user[:id]\n followed_id = followed_user[:id]\n\n follower_exists = followers.first(:user_id => followed_id,\n :follower_id => follower_id)\n if follower_exists.nil?\n added = if date_added.nil?\n max(follower_user[:created_at], followed_user[:created_at])\n else\n date_added\n end\n retrieved = retrieve_user_follower(followed, follower)\n\n if retrieved.nil?\n warn \"Could not retrieve follower #{follower} for #{followed}\"\n return\n end\n\n followers.insert(:user_id => followed_id,\n :follower_id => follower_id,\n :created_at => added)\n info \"Added follower #{follower} to #{followed}\"\n else\n debug \"Follower #{follower} for user #{followed} exists\"\n end\n\n unless date_added.nil?\n followers.filter(:user_id => followed_id, :follower_id => follower_id)\n .update(:created_at => date(date_added))\n info \"Updated follower #{followed} -> #{follower}, created_at -> #{date(date_added)}\"\n end\n\n followers.first(:user_id => followed_id, :follower_id => follower_id)\n end", "code_tokens": ["def", "ensure_user_follower", "(", "followed", ",", "follower", ",", "date_added", "=", "nil", ")", "follower_user", "=", "ensure_user", "(", "follower", ",", "false", ",", "false", ")", "followed_user", "=", "ensure_user", "(", "followed", ",", "false", ",", "false", ")", "if", "followed_user", ".", "nil?", "or", "follower_user", ".", "nil?", "warn", "\"Could not find follower #{follower} or user #{followed}\"", "return", "end", "followers", "=", "db", "[", ":followers", "]", "follower_id", "=", "follower_user", "[", ":id", "]", "followed_id", "=", "followed_user", "[", ":id", "]", "follower_exists", "=", "followers", ".", "first", "(", ":user_id", "=>", "followed_id", ",", ":follower_id", "=>", "follower_id", ")", "if", "follower_exists", ".", "nil?", "added", "=", "if", "date_added", ".", "nil?", "max", "(", "follower_user", "[", ":created_at", "]", ",", "followed_user", "[", ":created_at", "]", ")", "else", "date_added", "end", "retrieved", "=", "retrieve_user_follower", "(", "followed", ",", "follower", ")", "if", "retrieved", ".", "nil?", "warn", "\"Could not retrieve follower #{follower} for #{followed}\"", "return", "end", "followers", ".", "insert", "(", ":user_id", "=>", "followed_id", ",", ":follower_id", "=>", "follower_id", ",", ":created_at", "=>", "added", ")", "info", "\"Added follower #{follower} to #{followed}\"", "else", "debug", "\"Follower #{follower} for user #{followed} exists\"", "end", "unless", "date_added", ".", "nil?", "followers", ".", "filter", "(", ":user_id", "=>", "followed_id", ",", ":follower_id", "=>", "follower_id", ")", ".", "update", "(", ":created_at", "=>", "date", "(", "date_added", ")", ")", "info", "\"Updated follower #{followed} -> #{follower}, created_at -> #{date(date_added)}\"", "end", "followers", ".", "first", "(", ":user_id", "=>", "followed_id", ",", ":follower_id", "=>", "follower_id", ")", "end"], "docstring": "Make sure that a user follows another one", "docstring_tokens": ["Make", "sure", "that", "a", "user", "follows", "another", "one"], "sha": "3566294a3e4a4c7574bc7376f7e6a9435529b5de", "url": "https://github.com/gousiosg/github-mirror/blob/3566294a3e4a4c7574bc7376f7e6a9435529b5de/lib/ghtorrent/ghtorrent.rb#L416-L459", "partition": "test"} {"repo": "gousiosg/github-mirror", "path": "lib/ghtorrent/ghtorrent.rb", "func_name": "GHTorrent.Mirror.ensure_user_byemail", "original_string": "def ensure_user_byemail(email, name)\n users = db[:users]\n usr = users.first(:email => email)\n\n if usr.nil?\n\n u = retrieve_user_byemail(email, name)\n\n if u.nil? or u['login'].nil?\n warn \"Could not retrieve user #{email} through search API query\"\n login = (0...8).map { 65.+(rand(25)).chr }.join\n users.insert(:email => email,\n :name => name,\n :login => login,\n :fake => true,\n :deleted => false,\n :created_at => Time.now)\n info \"Added user fake #{login} -> #{email}\"\n users.first(:login => login)\n else\n in_db = users.first(:login => u['login'])\n geo = geolocate(location: u['location'])\n if in_db.nil?\n users.insert(:login => u['login'],\n :name => u['name'],\n :company => u['company'],\n :email => u['email'],\n :long => geo[:long],\n :lat => geo[:lat],\n :country_code => geo[:country_code],\n :state => geo[:state],\n :city => geo[:city],\n :fake => false,\n :deleted => false,\n :created_at => date(u['created_at']))\n info \"Added user #{u['login']} (#{email}) through search API query\"\n else\n in_db.update(:name => u['name'],\n :company => u['company'],\n :email => u['email'],\n :long => geo[:long],\n :lat => geo[:lat],\n :country_code => geo[:country_code],\n :state => geo[:state],\n :city => geo[:city],\n :fake => false,\n :deleted => false,\n :created_at => date(u['created_at']))\n debug \"User #{u['login']} with email #{email} exists\"\n end\n users.first(:login => u['login'])\n end\n else\n debug \"User with email #{email} exists\"\n usr\n end\n end", "language": "ruby", "code": "def ensure_user_byemail(email, name)\n users = db[:users]\n usr = users.first(:email => email)\n\n if usr.nil?\n\n u = retrieve_user_byemail(email, name)\n\n if u.nil? or u['login'].nil?\n warn \"Could not retrieve user #{email} through search API query\"\n login = (0...8).map { 65.+(rand(25)).chr }.join\n users.insert(:email => email,\n :name => name,\n :login => login,\n :fake => true,\n :deleted => false,\n :created_at => Time.now)\n info \"Added user fake #{login} -> #{email}\"\n users.first(:login => login)\n else\n in_db = users.first(:login => u['login'])\n geo = geolocate(location: u['location'])\n if in_db.nil?\n users.insert(:login => u['login'],\n :name => u['name'],\n :company => u['company'],\n :email => u['email'],\n :long => geo[:long],\n :lat => geo[:lat],\n :country_code => geo[:country_code],\n :state => geo[:state],\n :city => geo[:city],\n :fake => false,\n :deleted => false,\n :created_at => date(u['created_at']))\n info \"Added user #{u['login']} (#{email}) through search API query\"\n else\n in_db.update(:name => u['name'],\n :company => u['company'],\n :email => u['email'],\n :long => geo[:long],\n :lat => geo[:lat],\n :country_code => geo[:country_code],\n :state => geo[:state],\n :city => geo[:city],\n :fake => false,\n :deleted => false,\n :created_at => date(u['created_at']))\n debug \"User #{u['login']} with email #{email} exists\"\n end\n users.first(:login => u['login'])\n end\n else\n debug \"User with email #{email} exists\"\n usr\n end\n end", "code_tokens": ["def", "ensure_user_byemail", "(", "email", ",", "name", ")", "users", "=", "db", "[", ":users", "]", "usr", "=", "users", ".", "first", "(", ":email", "=>", "email", ")", "if", "usr", ".", "nil?", "u", "=", "retrieve_user_byemail", "(", "email", ",", "name", ")", "if", "u", ".", "nil?", "or", "u", "[", "'login'", "]", ".", "nil?", "warn", "\"Could not retrieve user #{email} through search API query\"", "login", "=", "(", "0", "...", "8", ")", ".", "map", "{", "65", ".", "+", "(", "rand", "(", "25", ")", ")", ".", "chr", "}", ".", "join", "users", ".", "insert", "(", ":email", "=>", "email", ",", ":name", "=>", "name", ",", ":login", "=>", "login", ",", ":fake", "=>", "true", ",", ":deleted", "=>", "false", ",", ":created_at", "=>", "Time", ".", "now", ")", "info", "\"Added user fake #{login} -> #{email}\"", "users", ".", "first", "(", ":login", "=>", "login", ")", "else", "in_db", "=", "users", ".", "first", "(", ":login", "=>", "u", "[", "'login'", "]", ")", "geo", "=", "geolocate", "(", "location", ":", "u", "[", "'location'", "]", ")", "if", "in_db", ".", "nil?", "users", ".", "insert", "(", ":login", "=>", "u", "[", "'login'", "]", ",", ":name", "=>", "u", "[", "'name'", "]", ",", ":company", "=>", "u", "[", "'company'", "]", ",", ":email", "=>", "u", "[", "'email'", "]", ",", ":long", "=>", "geo", "[", ":long", "]", ",", ":lat", "=>", "geo", "[", ":lat", "]", ",", ":country_code", "=>", "geo", "[", ":country_code", "]", ",", ":state", "=>", "geo", "[", ":state", "]", ",", ":city", "=>", "geo", "[", ":city", "]", ",", ":fake", "=>", "false", ",", ":deleted", "=>", "false", ",", ":created_at", "=>", "date", "(", "u", "[", "'created_at'", "]", ")", ")", "info", "\"Added user #{u['login']} (#{email}) through search API query\"", "else", "in_db", ".", "update", "(", ":name", "=>", "u", "[", "'name'", "]", ",", ":company", "=>", "u", "[", "'company'", "]", ",", ":email", "=>", "u", "[", "'email'", "]", ",", ":long", "=>", "geo", "[", ":long", "]", ",", ":lat", "=>", "geo", "[", ":lat", "]", ",", ":country_code", "=>", "geo", "[", ":country_code", "]", ",", ":state", "=>", "geo", "[", ":state", "]", ",", ":city", "=>", "geo", "[", ":city", "]", ",", ":fake", "=>", "false", ",", ":deleted", "=>", "false", ",", ":created_at", "=>", "date", "(", "u", "[", "'created_at'", "]", ")", ")", "debug", "\"User #{u['login']} with email #{email} exists\"", "end", "users", ".", "first", "(", ":login", "=>", "u", "[", "'login'", "]", ")", "end", "else", "debug", "\"User with email #{email} exists\"", "usr", "end", "end"], "docstring": "Try to retrieve a user by email. Search the DB first, fall back to\n Github search API if unsuccessful.\n\n ==Parameters:\n [email] The email to lookup the user by\n [name] The user's name\n == Returns:\n If the user can be retrieved, it is returned as a Hash. Otherwise,\n the result is nil", "docstring_tokens": ["Try", "to", "retrieve", "a", "user", "by", "email", ".", "Search", "the", "DB", "first", "fall", "back", "to", "Github", "search", "API", "if", "unsuccessful", "."], "sha": "3566294a3e4a4c7574bc7376f7e6a9435529b5de", "url": "https://github.com/gousiosg/github-mirror/blob/3566294a3e4a4c7574bc7376f7e6a9435529b5de/lib/ghtorrent/ghtorrent.rb#L487-L543", "partition": "test"} {"repo": "gousiosg/github-mirror", "path": "lib/ghtorrent/ghtorrent.rb", "func_name": "GHTorrent.Mirror.ensure_repo", "original_string": "def ensure_repo(user, repo, recursive = false)\n\n repos = db[:projects]\n curuser = ensure_user(user, false, false)\n\n if curuser.nil?\n warn \"Could not find user #{user}\"\n return\n end\n\n currepo = repos.first(:owner_id => curuser[:id], :name => repo)\n\n unless currepo.nil?\n debug \"Repo #{user}/#{repo} exists\"\n return refresh_repo(user, repo, currepo)\n end\n\n r = retrieve_repo(user, repo, true)\n\n if r.nil?\n warn \"Could not retrieve repo #{user}/#{repo}\"\n return\n end\n\n if r['owner']['login'] != curuser[:login]\n info \"Repo changed owner from #{curuser[:login]} to #{r['owner']['login']}\"\n curuser = ensure_user(r['owner']['login'], false, false)\n end\n\n repos.insert(:url => r['url'],\n :owner_id => curuser[:id],\n :name => r['name'],\n :description => unless r['description'].nil? then r['description'][0..254] else nil end,\n :language => r['language'],\n :created_at => date(r['created_at']),\n :updated_at => date(Time.now),\n :etag => unless r['etag'].nil? then r['etag'] end)\n\n unless r['parent'].nil?\n parent_owner = r['parent']['owner']['login']\n parent_repo = r['parent']['name']\n\n parent = ensure_repo(parent_owner, parent_repo)\n\n if parent.nil?\n warn \"Could not find repo #{parent_owner}/#{parent_repo}, parent of: #{user}/#{repo}\"\n repos.filter(:owner_id => curuser[:id], :name => repo).update(:forked_from => -1)\n else\n repos.filter(:owner_id => curuser[:id], :name => repo).update(:forked_from => parent[:id])\n info \"Repo #{user}/#{repo} is a fork of #{parent_owner}/#{parent_repo}\"\n\n unless ensure_fork_point(user, repo).nil?\n warn \"Could not find fork point for #{user}/#{repo}, fork of #{parent_owner}/#{parent_repo}\"\n end\n end\n end\n\n if recursive and not ensure_repo_recursive(user, repo)\n warn \"Could retrieve #{user}/#{repo} recursively\"\n return nil\n end\n\n info \"Added repo #{user}/#{repo}\"\n return repos.first(:owner_id => curuser[:id], :name => repo)\n end", "language": "ruby", "code": "def ensure_repo(user, repo, recursive = false)\n\n repos = db[:projects]\n curuser = ensure_user(user, false, false)\n\n if curuser.nil?\n warn \"Could not find user #{user}\"\n return\n end\n\n currepo = repos.first(:owner_id => curuser[:id], :name => repo)\n\n unless currepo.nil?\n debug \"Repo #{user}/#{repo} exists\"\n return refresh_repo(user, repo, currepo)\n end\n\n r = retrieve_repo(user, repo, true)\n\n if r.nil?\n warn \"Could not retrieve repo #{user}/#{repo}\"\n return\n end\n\n if r['owner']['login'] != curuser[:login]\n info \"Repo changed owner from #{curuser[:login]} to #{r['owner']['login']}\"\n curuser = ensure_user(r['owner']['login'], false, false)\n end\n\n repos.insert(:url => r['url'],\n :owner_id => curuser[:id],\n :name => r['name'],\n :description => unless r['description'].nil? then r['description'][0..254] else nil end,\n :language => r['language'],\n :created_at => date(r['created_at']),\n :updated_at => date(Time.now),\n :etag => unless r['etag'].nil? then r['etag'] end)\n\n unless r['parent'].nil?\n parent_owner = r['parent']['owner']['login']\n parent_repo = r['parent']['name']\n\n parent = ensure_repo(parent_owner, parent_repo)\n\n if parent.nil?\n warn \"Could not find repo #{parent_owner}/#{parent_repo}, parent of: #{user}/#{repo}\"\n repos.filter(:owner_id => curuser[:id], :name => repo).update(:forked_from => -1)\n else\n repos.filter(:owner_id => curuser[:id], :name => repo).update(:forked_from => parent[:id])\n info \"Repo #{user}/#{repo} is a fork of #{parent_owner}/#{parent_repo}\"\n\n unless ensure_fork_point(user, repo).nil?\n warn \"Could not find fork point for #{user}/#{repo}, fork of #{parent_owner}/#{parent_repo}\"\n end\n end\n end\n\n if recursive and not ensure_repo_recursive(user, repo)\n warn \"Could retrieve #{user}/#{repo} recursively\"\n return nil\n end\n\n info \"Added repo #{user}/#{repo}\"\n return repos.first(:owner_id => curuser[:id], :name => repo)\n end", "code_tokens": ["def", "ensure_repo", "(", "user", ",", "repo", ",", "recursive", "=", "false", ")", "repos", "=", "db", "[", ":projects", "]", "curuser", "=", "ensure_user", "(", "user", ",", "false", ",", "false", ")", "if", "curuser", ".", "nil?", "warn", "\"Could not find user #{user}\"", "return", "end", "currepo", "=", "repos", ".", "first", "(", ":owner_id", "=>", "curuser", "[", ":id", "]", ",", ":name", "=>", "repo", ")", "unless", "currepo", ".", "nil?", "debug", "\"Repo #{user}/#{repo} exists\"", "return", "refresh_repo", "(", "user", ",", "repo", ",", "currepo", ")", "end", "r", "=", "retrieve_repo", "(", "user", ",", "repo", ",", "true", ")", "if", "r", ".", "nil?", "warn", "\"Could not retrieve repo #{user}/#{repo}\"", "return", "end", "if", "r", "[", "'owner'", "]", "[", "'login'", "]", "!=", "curuser", "[", ":login", "]", "info", "\"Repo changed owner from #{curuser[:login]} to #{r['owner']['login']}\"", "curuser", "=", "ensure_user", "(", "r", "[", "'owner'", "]", "[", "'login'", "]", ",", "false", ",", "false", ")", "end", "repos", ".", "insert", "(", ":url", "=>", "r", "[", "'url'", "]", ",", ":owner_id", "=>", "curuser", "[", ":id", "]", ",", ":name", "=>", "r", "[", "'name'", "]", ",", ":description", "=>", "unless", "r", "[", "'description'", "]", ".", "nil?", "then", "r", "[", "'description'", "]", "[", "0", "..", "254", "]", "else", "nil", "end", ",", ":language", "=>", "r", "[", "'language'", "]", ",", ":created_at", "=>", "date", "(", "r", "[", "'created_at'", "]", ")", ",", ":updated_at", "=>", "date", "(", "Time", ".", "now", ")", ",", ":etag", "=>", "unless", "r", "[", "'etag'", "]", ".", "nil?", "then", "r", "[", "'etag'", "]", "end", ")", "unless", "r", "[", "'parent'", "]", ".", "nil?", "parent_owner", "=", "r", "[", "'parent'", "]", "[", "'owner'", "]", "[", "'login'", "]", "parent_repo", "=", "r", "[", "'parent'", "]", "[", "'name'", "]", "parent", "=", "ensure_repo", "(", "parent_owner", ",", "parent_repo", ")", "if", "parent", ".", "nil?", "warn", "\"Could not find repo #{parent_owner}/#{parent_repo}, parent of: #{user}/#{repo}\"", "repos", ".", "filter", "(", ":owner_id", "=>", "curuser", "[", ":id", "]", ",", ":name", "=>", "repo", ")", ".", "update", "(", ":forked_from", "=>", "-", "1", ")", "else", "repos", ".", "filter", "(", ":owner_id", "=>", "curuser", "[", ":id", "]", ",", ":name", "=>", "repo", ")", ".", "update", "(", ":forked_from", "=>", "parent", "[", ":id", "]", ")", "info", "\"Repo #{user}/#{repo} is a fork of #{parent_owner}/#{parent_repo}\"", "unless", "ensure_fork_point", "(", "user", ",", "repo", ")", ".", "nil?", "warn", "\"Could not find fork point for #{user}/#{repo}, fork of #{parent_owner}/#{parent_repo}\"", "end", "end", "end", "if", "recursive", "and", "not", "ensure_repo_recursive", "(", "user", ",", "repo", ")", "warn", "\"Could retrieve #{user}/#{repo} recursively\"", "return", "nil", "end", "info", "\"Added repo #{user}/#{repo}\"", "return", "repos", ".", "first", "(", ":owner_id", "=>", "curuser", "[", ":id", "]", ",", ":name", "=>", "repo", ")", "end"], "docstring": "Ensure that a repo exists, or fetch its latest state from Github\n\n ==Parameters:\n [user] The email or login name to which this repo belongs\n [repo] The repo name\n\n == Returns:\n If the repo can be retrieved, it is returned as a Hash. Otherwise,\n the result is nil", "docstring_tokens": ["Ensure", "that", "a", "repo", "exists", "or", "fetch", "its", "latest", "state", "from", "Github"], "sha": "3566294a3e4a4c7574bc7376f7e6a9435529b5de", "url": "https://github.com/gousiosg/github-mirror/blob/3566294a3e4a4c7574bc7376f7e6a9435529b5de/lib/ghtorrent/ghtorrent.rb#L555-L619", "partition": "test"} {"repo": "gousiosg/github-mirror", "path": "lib/ghtorrent/ghtorrent.rb", "func_name": "GHTorrent.Mirror.ensure_languages", "original_string": "def ensure_languages(owner, repo)\n currepo = ensure_repo(owner, repo)\n langs = retrieve_languages(owner, repo)\n\n if langs.nil? or langs.empty?\n warn \"Could not find languages for repo #{owner}/#{repo}\"\n return\n end\n\n ts = Time.now\n langs.keys.each do |lang|\n db[:project_languages].insert(\n :project_id => currepo[:id],\n :language => lang.downcase,\n :bytes => langs[lang],\n :created_at => ts\n )\n info \"Added project_language #{owner}/#{repo} -> #{lang} (#{langs[lang]} bytes)\"\n end\n db[:project_languages].where(:project_id => currepo[:id]).where(:created_at => ts).all\n end", "language": "ruby", "code": "def ensure_languages(owner, repo)\n currepo = ensure_repo(owner, repo)\n langs = retrieve_languages(owner, repo)\n\n if langs.nil? or langs.empty?\n warn \"Could not find languages for repo #{owner}/#{repo}\"\n return\n end\n\n ts = Time.now\n langs.keys.each do |lang|\n db[:project_languages].insert(\n :project_id => currepo[:id],\n :language => lang.downcase,\n :bytes => langs[lang],\n :created_at => ts\n )\n info \"Added project_language #{owner}/#{repo} -> #{lang} (#{langs[lang]} bytes)\"\n end\n db[:project_languages].where(:project_id => currepo[:id]).where(:created_at => ts).all\n end", "code_tokens": ["def", "ensure_languages", "(", "owner", ",", "repo", ")", "currepo", "=", "ensure_repo", "(", "owner", ",", "repo", ")", "langs", "=", "retrieve_languages", "(", "owner", ",", "repo", ")", "if", "langs", ".", "nil?", "or", "langs", ".", "empty?", "warn", "\"Could not find languages for repo #{owner}/#{repo}\"", "return", "end", "ts", "=", "Time", ".", "now", "langs", ".", "keys", ".", "each", "do", "|", "lang", "|", "db", "[", ":project_languages", "]", ".", "insert", "(", ":project_id", "=>", "currepo", "[", ":id", "]", ",", ":language", "=>", "lang", ".", "downcase", ",", ":bytes", "=>", "langs", "[", "lang", "]", ",", ":created_at", "=>", "ts", ")", "info", "\"Added project_language #{owner}/#{repo} -> #{lang} (#{langs[lang]} bytes)\"", "end", "db", "[", ":project_languages", "]", ".", "where", "(", ":project_id", "=>", "currepo", "[", ":id", "]", ")", ".", "where", "(", ":created_at", "=>", "ts", ")", ".", "all", "end"], "docstring": "Get details about the languages used in the repository", "docstring_tokens": ["Get", "details", "about", "the", "languages", "used", "in", "the", "repository"], "sha": "3566294a3e4a4c7574bc7376f7e6a9435529b5de", "url": "https://github.com/gousiosg/github-mirror/blob/3566294a3e4a4c7574bc7376f7e6a9435529b5de/lib/ghtorrent/ghtorrent.rb#L634-L654", "partition": "test"} {"repo": "gousiosg/github-mirror", "path": "lib/ghtorrent/ghtorrent.rb", "func_name": "GHTorrent.Mirror.ensure_fork_commits", "original_string": "def ensure_fork_commits(owner, repo, parent_owner, parent_repo)\n\n currepo = ensure_repo(owner, repo)\n\n if currepo.nil?\n warn \"Could not find repo #{owner}/#{repo}\"\n return\n end\n\n parent = ensure_repo(parent_owner, parent_repo)\n\n if parent.nil?\n warn \"Could not find repo #{parent_owner}/#{parent_repo}, parent of #{owner}/#{repo}\"\n return\n end\n\n strategy = case\n when config(:fork_commits).match(/all/i)\n :all\n when config(:fork_commits).match(/fork_point/i)\n :fork_point\n when config(:fork_commits).match(/none/i)\n :none\n else\n :fork_point\n end\n\n fork_commit = ensure_fork_point(owner, repo)\n\n if fork_commit.nil? or fork_commit.empty?\n warn \"Could not find fork commit for repo #{owner}/#{repo}. Retrieving all commits.\"\n return ensure_commits(owner, repo, fork_all: true)\n end\n\n debug \"Retrieving commits for fork #{owner}/#{repo}: strategy is #{strategy}\"\n return if strategy == :none\n\n if strategy == :fork_point\n # Retrieve commits up to fork point (fork_commit strategy)\n info \"Retrieving commits for #{owner}/#{repo} until fork commit #{fork_commit[:sha]}\"\n master_branch = retrieve_default_branch(parent_owner, parent_repo)\n return if master_branch.nil?\n\n sha = master_branch\n found = false\n while not found\n commits = retrieve_commits(repo, sha, owner, 1)\n\n # This means that we retrieved no commits\n if commits.size == 0\n break\n end\n\n # This means we retrieved the last page again\n if commits.size == 1 and commits[0]['sha'] == sha\n break\n end\n\n for c in commits\n ensure_commit(repo, c['sha'], owner)\n sha = c['sha']\n if c['sha'] == fork_commit[:sha]\n found = true\n break\n end\n end\n end\n end\n\n if strategy == :all\n\n shared_commit = db[:commits].first(:sha => fork_commit)\n copied = 0\n to_copy = db.from(:project_commits, :commits).\\\n where(Sequel.qualify('project_commits', 'commit_id') => Sequel.qualify('commits', 'id')).\\\n where(Sequel.qualify('project_commits', 'project_id') => parent[:id]).\\\n where('commits.created_at < ?', shared_commit[:created_at]).\\\n select(Sequel.qualify('commits','id'))\n\n to_copy.each do |c|\n copied += 1\n begin\n db[:project_commits].insert(\n :project_id => currepo[:id],\n :commit_id => c[:id]\n )\n debug \"Copied commit #{c[:sha]} #{parent_owner}/#{parent_repo} -> #{owner}/#{repo} (#{copied} total)\"\n rescue StandardError => e\n warn \"Could not copy commit #{c[:sha]} #{parent_owner}/#{parent_repo} -> #{owner}/#{repo} : #{e.message}\"\n end\n end\n info \"Finished copying commits from #{parent_owner}/#{parent_repo} -> #{owner}/#{repo}: #{copied} total\"\n end\n\n end", "language": "ruby", "code": "def ensure_fork_commits(owner, repo, parent_owner, parent_repo)\n\n currepo = ensure_repo(owner, repo)\n\n if currepo.nil?\n warn \"Could not find repo #{owner}/#{repo}\"\n return\n end\n\n parent = ensure_repo(parent_owner, parent_repo)\n\n if parent.nil?\n warn \"Could not find repo #{parent_owner}/#{parent_repo}, parent of #{owner}/#{repo}\"\n return\n end\n\n strategy = case\n when config(:fork_commits).match(/all/i)\n :all\n when config(:fork_commits).match(/fork_point/i)\n :fork_point\n when config(:fork_commits).match(/none/i)\n :none\n else\n :fork_point\n end\n\n fork_commit = ensure_fork_point(owner, repo)\n\n if fork_commit.nil? or fork_commit.empty?\n warn \"Could not find fork commit for repo #{owner}/#{repo}. Retrieving all commits.\"\n return ensure_commits(owner, repo, fork_all: true)\n end\n\n debug \"Retrieving commits for fork #{owner}/#{repo}: strategy is #{strategy}\"\n return if strategy == :none\n\n if strategy == :fork_point\n # Retrieve commits up to fork point (fork_commit strategy)\n info \"Retrieving commits for #{owner}/#{repo} until fork commit #{fork_commit[:sha]}\"\n master_branch = retrieve_default_branch(parent_owner, parent_repo)\n return if master_branch.nil?\n\n sha = master_branch\n found = false\n while not found\n commits = retrieve_commits(repo, sha, owner, 1)\n\n # This means that we retrieved no commits\n if commits.size == 0\n break\n end\n\n # This means we retrieved the last page again\n if commits.size == 1 and commits[0]['sha'] == sha\n break\n end\n\n for c in commits\n ensure_commit(repo, c['sha'], owner)\n sha = c['sha']\n if c['sha'] == fork_commit[:sha]\n found = true\n break\n end\n end\n end\n end\n\n if strategy == :all\n\n shared_commit = db[:commits].first(:sha => fork_commit)\n copied = 0\n to_copy = db.from(:project_commits, :commits).\\\n where(Sequel.qualify('project_commits', 'commit_id') => Sequel.qualify('commits', 'id')).\\\n where(Sequel.qualify('project_commits', 'project_id') => parent[:id]).\\\n where('commits.created_at < ?', shared_commit[:created_at]).\\\n select(Sequel.qualify('commits','id'))\n\n to_copy.each do |c|\n copied += 1\n begin\n db[:project_commits].insert(\n :project_id => currepo[:id],\n :commit_id => c[:id]\n )\n debug \"Copied commit #{c[:sha]} #{parent_owner}/#{parent_repo} -> #{owner}/#{repo} (#{copied} total)\"\n rescue StandardError => e\n warn \"Could not copy commit #{c[:sha]} #{parent_owner}/#{parent_repo} -> #{owner}/#{repo} : #{e.message}\"\n end\n end\n info \"Finished copying commits from #{parent_owner}/#{parent_repo} -> #{owner}/#{repo}: #{copied} total\"\n end\n\n end", "code_tokens": ["def", "ensure_fork_commits", "(", "owner", ",", "repo", ",", "parent_owner", ",", "parent_repo", ")", "currepo", "=", "ensure_repo", "(", "owner", ",", "repo", ")", "if", "currepo", ".", "nil?", "warn", "\"Could not find repo #{owner}/#{repo}\"", "return", "end", "parent", "=", "ensure_repo", "(", "parent_owner", ",", "parent_repo", ")", "if", "parent", ".", "nil?", "warn", "\"Could not find repo #{parent_owner}/#{parent_repo}, parent of #{owner}/#{repo}\"", "return", "end", "strategy", "=", "case", "when", "config", "(", ":fork_commits", ")", ".", "match", "(", "/", "/i", ")", ":all", "when", "config", "(", ":fork_commits", ")", ".", "match", "(", "/", "/i", ")", ":fork_point", "when", "config", "(", ":fork_commits", ")", ".", "match", "(", "/", "/i", ")", ":none", "else", ":fork_point", "end", "fork_commit", "=", "ensure_fork_point", "(", "owner", ",", "repo", ")", "if", "fork_commit", ".", "nil?", "or", "fork_commit", ".", "empty?", "warn", "\"Could not find fork commit for repo #{owner}/#{repo}. Retrieving all commits.\"", "return", "ensure_commits", "(", "owner", ",", "repo", ",", "fork_all", ":", "true", ")", "end", "debug", "\"Retrieving commits for fork #{owner}/#{repo}: strategy is #{strategy}\"", "return", "if", "strategy", "==", ":none", "if", "strategy", "==", ":fork_point", "# Retrieve commits up to fork point (fork_commit strategy)", "info", "\"Retrieving commits for #{owner}/#{repo} until fork commit #{fork_commit[:sha]}\"", "master_branch", "=", "retrieve_default_branch", "(", "parent_owner", ",", "parent_repo", ")", "return", "if", "master_branch", ".", "nil?", "sha", "=", "master_branch", "found", "=", "false", "while", "not", "found", "commits", "=", "retrieve_commits", "(", "repo", ",", "sha", ",", "owner", ",", "1", ")", "# This means that we retrieved no commits", "if", "commits", ".", "size", "==", "0", "break", "end", "# This means we retrieved the last page again", "if", "commits", ".", "size", "==", "1", "and", "commits", "[", "0", "]", "[", "'sha'", "]", "==", "sha", "break", "end", "for", "c", "in", "commits", "ensure_commit", "(", "repo", ",", "c", "[", "'sha'", "]", ",", "owner", ")", "sha", "=", "c", "[", "'sha'", "]", "if", "c", "[", "'sha'", "]", "==", "fork_commit", "[", ":sha", "]", "found", "=", "true", "break", "end", "end", "end", "end", "if", "strategy", "==", ":all", "shared_commit", "=", "db", "[", ":commits", "]", ".", "first", "(", ":sha", "=>", "fork_commit", ")", "copied", "=", "0", "to_copy", "=", "db", ".", "from", "(", ":project_commits", ",", ":commits", ")", ".", "where", "(", "Sequel", ".", "qualify", "(", "'project_commits'", ",", "'commit_id'", ")", "=>", "Sequel", ".", "qualify", "(", "'commits'", ",", "'id'", ")", ")", ".", "where", "(", "Sequel", ".", "qualify", "(", "'project_commits'", ",", "'project_id'", ")", "=>", "parent", "[", ":id", "]", ")", ".", "where", "(", "'commits.created_at < ?'", ",", "shared_commit", "[", ":created_at", "]", ")", ".", "select", "(", "Sequel", ".", "qualify", "(", "'commits'", ",", "'id'", ")", ")", "to_copy", ".", "each", "do", "|", "c", "|", "copied", "+=", "1", "begin", "db", "[", ":project_commits", "]", ".", "insert", "(", ":project_id", "=>", "currepo", "[", ":id", "]", ",", ":commit_id", "=>", "c", "[", ":id", "]", ")", "debug", "\"Copied commit #{c[:sha]} #{parent_owner}/#{parent_repo} -> #{owner}/#{repo} (#{copied} total)\"", "rescue", "StandardError", "=>", "e", "warn", "\"Could not copy commit #{c[:sha]} #{parent_owner}/#{parent_repo} -> #{owner}/#{repo} : #{e.message}\"", "end", "end", "info", "\"Finished copying commits from #{parent_owner}/#{parent_repo} -> #{owner}/#{repo}: #{copied} total\"", "end", "end"], "docstring": "Fast path to project forking. Retrieve all commits page by page\n until we reach a commit that has been registered with the parent\n repository. Then, copy all remaining parent commits to this repo.", "docstring_tokens": ["Fast", "path", "to", "project", "forking", ".", "Retrieve", "all", "commits", "page", "by", "page", "until", "we", "reach", "a", "commit", "that", "has", "been", "registered", "with", "the", "parent", "repository", ".", "Then", "copy", "all", "remaining", "parent", "commits", "to", "this", "repo", "."], "sha": "3566294a3e4a4c7574bc7376f7e6a9435529b5de", "url": "https://github.com/gousiosg/github-mirror/blob/3566294a3e4a4c7574bc7376f7e6a9435529b5de/lib/ghtorrent/ghtorrent.rb#L659-L753", "partition": "test"} {"repo": "gousiosg/github-mirror", "path": "lib/ghtorrent/ghtorrent.rb", "func_name": "GHTorrent.Mirror.ensure_fork_point", "original_string": "def ensure_fork_point(owner, repo)\n\n fork = ensure_repo(owner, repo, false)\n\n if fork[:forked_from].nil?\n warn \"Repo #{owner}/#{repo} is not a fork\"\n return nil\n end\n\n # Return commit if already specified\n unless fork[:forked_commit_id].nil?\n commit = db[:commits].where(:id => fork[:forked_commit_id]).first\n return commit unless commit.nil?\n end\n\n parent = db.from(:projects, :users).\\\n where(Sequel.qualify('projects', 'owner_id') => Sequel.qualify('users', 'id')).\\\n where(Sequel.qualify('projects', 'id') => fork[:forked_from]).\\\n select(Sequel.qualify('users', 'login'), Sequel.qualify('projects','name')).first\n\n if parent.nil?\n warn \"Unknown parent for repo #{owner}/#{repo}\"\n return nil\n end\n\n default_branch = retrieve_default_branch(parent[:login], parent[:name])\n\n # Retrieve diff between parent and fork master branch\n diff = retrieve_master_branch_diff(owner, repo, default_branch, parent[:login], parent[:name], default_branch)\n\n if diff.nil? or diff.empty?\n # Try a bit harder by refreshing the default branch\n default_branch = retrieve_default_branch(parent[:login], parent[:name], true)\n diff = retrieve_master_branch_diff(owner, repo, default_branch, parent[:login], parent[:name], default_branch)\n end\n\n if diff.nil? or diff.empty?\n # This means that the are no common ancestors between the repos\n # This can apparently happen when the parent repo was renamed or force-pushed\n # example: https://github.com/openzipkin/zipkin/compare/master...aa1wi:master\n warn \"No common ancestor between #{parent[:login]}/#{parent[:name]} and #{owner}/#{repo}\"\n return nil\n else\n debug \"Fork #{owner}/#{repo} is #{diff['ahead_by']} commits ahead and #{diff['behind_by']} commits behind #{parent[:login]}/#{parent[:name]}\"\n end\n\n if diff['ahead_by'].to_i > 0\n # This means that the fork has diverged, and we need to search through the fork\n # commit graph for the earliest commit that is shared with the parent. GitHub's\n # diff contains a list of divergent commits. We are sorting those by date\n # and select the earliest one. We do date sort instead of graph walking as this\n # would be prohibetively slow if the commits for the parent did not exist.\n earliest_diverging = diff['commits'].sort_by{|x| x['commit']['author']['date']}.first\n\n if earliest_diverging['parents'].nil?\n # this means that the repo was forked from the from the parent repo's initial commit. thus, they both share an initial commit.\n # example: https://api.github.com/repos/btakita/pain-point/compare/master...spent:master\n likely_fork_point = ensure_commit(parent[:name], earliest_diverging['sha'], parent['login'])\n else\n # Make sure that all likely fork points exist for the parent project\n # and select the latest of them.\n # https://github.com/gousiosg/github-mirror/compare/master...pombredanne:master\n likely_fork_point = earliest_diverging['parents'].\\\n map{ |x| ensure_commit(parent[:name], x['sha'], parent[:login])}.\\\n select{|x| !x.nil?}.\\\n sort_by { |x| x[:created_at]}.\\\n last\n end\n forked_sha = likely_fork_point[:sha]\n else\n # This means that the fork has not diverged.\n forked_sha = diff['merge_base_commit']['sha']\n end\n\n forked_commit = ensure_commit(repo, forked_sha, owner);\n\n debug \"Fork commit for #{owner}/#{repo} is #{forked_sha}\"\n\n unless forked_commit.nil?\n db[:projects].filter(:id => fork[:id]).update(:forked_commit_id => forked_commit[:id])\n info \"Repo #{owner}/#{repo} was forked at #{parent[:login]}/#{parent[:name]}:#{forked_sha}\"\n end\n\n db[:commits].where(:sha => forked_sha).first\n end", "language": "ruby", "code": "def ensure_fork_point(owner, repo)\n\n fork = ensure_repo(owner, repo, false)\n\n if fork[:forked_from].nil?\n warn \"Repo #{owner}/#{repo} is not a fork\"\n return nil\n end\n\n # Return commit if already specified\n unless fork[:forked_commit_id].nil?\n commit = db[:commits].where(:id => fork[:forked_commit_id]).first\n return commit unless commit.nil?\n end\n\n parent = db.from(:projects, :users).\\\n where(Sequel.qualify('projects', 'owner_id') => Sequel.qualify('users', 'id')).\\\n where(Sequel.qualify('projects', 'id') => fork[:forked_from]).\\\n select(Sequel.qualify('users', 'login'), Sequel.qualify('projects','name')).first\n\n if parent.nil?\n warn \"Unknown parent for repo #{owner}/#{repo}\"\n return nil\n end\n\n default_branch = retrieve_default_branch(parent[:login], parent[:name])\n\n # Retrieve diff between parent and fork master branch\n diff = retrieve_master_branch_diff(owner, repo, default_branch, parent[:login], parent[:name], default_branch)\n\n if diff.nil? or diff.empty?\n # Try a bit harder by refreshing the default branch\n default_branch = retrieve_default_branch(parent[:login], parent[:name], true)\n diff = retrieve_master_branch_diff(owner, repo, default_branch, parent[:login], parent[:name], default_branch)\n end\n\n if diff.nil? or diff.empty?\n # This means that the are no common ancestors between the repos\n # This can apparently happen when the parent repo was renamed or force-pushed\n # example: https://github.com/openzipkin/zipkin/compare/master...aa1wi:master\n warn \"No common ancestor between #{parent[:login]}/#{parent[:name]} and #{owner}/#{repo}\"\n return nil\n else\n debug \"Fork #{owner}/#{repo} is #{diff['ahead_by']} commits ahead and #{diff['behind_by']} commits behind #{parent[:login]}/#{parent[:name]}\"\n end\n\n if diff['ahead_by'].to_i > 0\n # This means that the fork has diverged, and we need to search through the fork\n # commit graph for the earliest commit that is shared with the parent. GitHub's\n # diff contains a list of divergent commits. We are sorting those by date\n # and select the earliest one. We do date sort instead of graph walking as this\n # would be prohibetively slow if the commits for the parent did not exist.\n earliest_diverging = diff['commits'].sort_by{|x| x['commit']['author']['date']}.first\n\n if earliest_diverging['parents'].nil?\n # this means that the repo was forked from the from the parent repo's initial commit. thus, they both share an initial commit.\n # example: https://api.github.com/repos/btakita/pain-point/compare/master...spent:master\n likely_fork_point = ensure_commit(parent[:name], earliest_diverging['sha'], parent['login'])\n else\n # Make sure that all likely fork points exist for the parent project\n # and select the latest of them.\n # https://github.com/gousiosg/github-mirror/compare/master...pombredanne:master\n likely_fork_point = earliest_diverging['parents'].\\\n map{ |x| ensure_commit(parent[:name], x['sha'], parent[:login])}.\\\n select{|x| !x.nil?}.\\\n sort_by { |x| x[:created_at]}.\\\n last\n end\n forked_sha = likely_fork_point[:sha]\n else\n # This means that the fork has not diverged.\n forked_sha = diff['merge_base_commit']['sha']\n end\n\n forked_commit = ensure_commit(repo, forked_sha, owner);\n\n debug \"Fork commit for #{owner}/#{repo} is #{forked_sha}\"\n\n unless forked_commit.nil?\n db[:projects].filter(:id => fork[:id]).update(:forked_commit_id => forked_commit[:id])\n info \"Repo #{owner}/#{repo} was forked at #{parent[:login]}/#{parent[:name]}:#{forked_sha}\"\n end\n\n db[:commits].where(:sha => forked_sha).first\n end", "code_tokens": ["def", "ensure_fork_point", "(", "owner", ",", "repo", ")", "fork", "=", "ensure_repo", "(", "owner", ",", "repo", ",", "false", ")", "if", "fork", "[", ":forked_from", "]", ".", "nil?", "warn", "\"Repo #{owner}/#{repo} is not a fork\"", "return", "nil", "end", "# Return commit if already specified", "unless", "fork", "[", ":forked_commit_id", "]", ".", "nil?", "commit", "=", "db", "[", ":commits", "]", ".", "where", "(", ":id", "=>", "fork", "[", ":forked_commit_id", "]", ")", ".", "first", "return", "commit", "unless", "commit", ".", "nil?", "end", "parent", "=", "db", ".", "from", "(", ":projects", ",", ":users", ")", ".", "where", "(", "Sequel", ".", "qualify", "(", "'projects'", ",", "'owner_id'", ")", "=>", "Sequel", ".", "qualify", "(", "'users'", ",", "'id'", ")", ")", ".", "where", "(", "Sequel", ".", "qualify", "(", "'projects'", ",", "'id'", ")", "=>", "fork", "[", ":forked_from", "]", ")", ".", "select", "(", "Sequel", ".", "qualify", "(", "'users'", ",", "'login'", ")", ",", "Sequel", ".", "qualify", "(", "'projects'", ",", "'name'", ")", ")", ".", "first", "if", "parent", ".", "nil?", "warn", "\"Unknown parent for repo #{owner}/#{repo}\"", "return", "nil", "end", "default_branch", "=", "retrieve_default_branch", "(", "parent", "[", ":login", "]", ",", "parent", "[", ":name", "]", ")", "# Retrieve diff between parent and fork master branch", "diff", "=", "retrieve_master_branch_diff", "(", "owner", ",", "repo", ",", "default_branch", ",", "parent", "[", ":login", "]", ",", "parent", "[", ":name", "]", ",", "default_branch", ")", "if", "diff", ".", "nil?", "or", "diff", ".", "empty?", "# Try a bit harder by refreshing the default branch", "default_branch", "=", "retrieve_default_branch", "(", "parent", "[", ":login", "]", ",", "parent", "[", ":name", "]", ",", "true", ")", "diff", "=", "retrieve_master_branch_diff", "(", "owner", ",", "repo", ",", "default_branch", ",", "parent", "[", ":login", "]", ",", "parent", "[", ":name", "]", ",", "default_branch", ")", "end", "if", "diff", ".", "nil?", "or", "diff", ".", "empty?", "# This means that the are no common ancestors between the repos", "# This can apparently happen when the parent repo was renamed or force-pushed", "# example: https://github.com/openzipkin/zipkin/compare/master...aa1wi:master", "warn", "\"No common ancestor between #{parent[:login]}/#{parent[:name]} and #{owner}/#{repo}\"", "return", "nil", "else", "debug", "\"Fork #{owner}/#{repo} is #{diff['ahead_by']} commits ahead and #{diff['behind_by']} commits behind #{parent[:login]}/#{parent[:name]}\"", "end", "if", "diff", "[", "'ahead_by'", "]", ".", "to_i", ">", "0", "# This means that the fork has diverged, and we need to search through the fork", "# commit graph for the earliest commit that is shared with the parent. GitHub's", "# diff contains a list of divergent commits. We are sorting those by date", "# and select the earliest one. We do date sort instead of graph walking as this", "# would be prohibetively slow if the commits for the parent did not exist.", "earliest_diverging", "=", "diff", "[", "'commits'", "]", ".", "sort_by", "{", "|", "x", "|", "x", "[", "'commit'", "]", "[", "'author'", "]", "[", "'date'", "]", "}", ".", "first", "if", "earliest_diverging", "[", "'parents'", "]", ".", "nil?", "# this means that the repo was forked from the from the parent repo's initial commit. thus, they both share an initial commit.", "# example: https://api.github.com/repos/btakita/pain-point/compare/master...spent:master", "likely_fork_point", "=", "ensure_commit", "(", "parent", "[", ":name", "]", ",", "earliest_diverging", "[", "'sha'", "]", ",", "parent", "[", "'login'", "]", ")", "else", "# Make sure that all likely fork points exist for the parent project", "# and select the latest of them.", "# https://github.com/gousiosg/github-mirror/compare/master...pombredanne:master", "likely_fork_point", "=", "earliest_diverging", "[", "'parents'", "]", ".", "map", "{", "|", "x", "|", "ensure_commit", "(", "parent", "[", ":name", "]", ",", "x", "[", "'sha'", "]", ",", "parent", "[", ":login", "]", ")", "}", ".", "select", "{", "|", "x", "|", "!", "x", ".", "nil?", "}", ".", "sort_by", "{", "|", "x", "|", "x", "[", ":created_at", "]", "}", ".", "last", "end", "forked_sha", "=", "likely_fork_point", "[", ":sha", "]", "else", "# This means that the fork has not diverged.", "forked_sha", "=", "diff", "[", "'merge_base_commit'", "]", "[", "'sha'", "]", "end", "forked_commit", "=", "ensure_commit", "(", "repo", ",", "forked_sha", ",", "owner", ")", ";", "debug", "\"Fork commit for #{owner}/#{repo} is #{forked_sha}\"", "unless", "forked_commit", ".", "nil?", "db", "[", ":projects", "]", ".", "filter", "(", ":id", "=>", "fork", "[", ":id", "]", ")", ".", "update", "(", ":forked_commit_id", "=>", "forked_commit", "[", ":id", "]", ")", "info", "\"Repo #{owner}/#{repo} was forked at #{parent[:login]}/#{parent[:name]}:#{forked_sha}\"", "end", "db", "[", ":commits", "]", ".", "where", "(", ":sha", "=>", "forked_sha", ")", ".", "first", "end"], "docstring": "Retrieve and return the commit at which the provided fork was forked at", "docstring_tokens": ["Retrieve", "and", "return", "the", "commit", "at", "which", "the", "provided", "fork", "was", "forked", "at"], "sha": "3566294a3e4a4c7574bc7376f7e6a9435529b5de", "url": "https://github.com/gousiosg/github-mirror/blob/3566294a3e4a4c7574bc7376f7e6a9435529b5de/lib/ghtorrent/ghtorrent.rb#L756-L840", "partition": "test"} {"repo": "gousiosg/github-mirror", "path": "lib/ghtorrent/ghtorrent.rb", "func_name": "GHTorrent.Mirror.ensure_orgs", "original_string": "def ensure_orgs(user)\n retrieve_orgs(user).map{|o| save{ensure_participation(user, o['login'])}}.select{|x| !x.nil?}\n end", "language": "ruby", "code": "def ensure_orgs(user)\n retrieve_orgs(user).map{|o| save{ensure_participation(user, o['login'])}}.select{|x| !x.nil?}\n end", "code_tokens": ["def", "ensure_orgs", "(", "user", ")", "retrieve_orgs", "(", "user", ")", ".", "map", "{", "|", "o", "|", "save", "{", "ensure_participation", "(", "user", ",", "o", "[", "'login'", "]", ")", "}", "}", ".", "select", "{", "|", "x", "|", "!", "x", ".", "nil?", "}", "end"], "docstring": "Make sure that the organizations the user participates into exist\n\n ==Parameters:\n [user] The login name of the user to check the organizations for", "docstring_tokens": ["Make", "sure", "that", "the", "organizations", "the", "user", "participates", "into", "exist"], "sha": "3566294a3e4a4c7574bc7376f7e6a9435529b5de", "url": "https://github.com/gousiosg/github-mirror/blob/3566294a3e4a4c7574bc7376f7e6a9435529b5de/lib/ghtorrent/ghtorrent.rb#L848-L850", "partition": "test"} {"repo": "gousiosg/github-mirror", "path": "lib/ghtorrent/ghtorrent.rb", "func_name": "GHTorrent.Mirror.ensure_participation", "original_string": "def ensure_participation(user, organization, members = true)\n org = ensure_org(organization, members)\n\n if org.nil?\n warn \"Could not find organization #{organization}\"\n return\n end\n\n usr = ensure_user(user, false, false)\n\n org_members = db[:organization_members]\n participates = org_members.first(:user_id => usr[:id], :org_id => org[:id])\n\n if participates.nil?\n org_members.insert(:user_id => usr[:id],\n :org_id => org[:id])\n info \"Added participation #{organization} -> #{user}\"\n org_members.first(:user_id => usr[:id], :org_id => org[:id])\n else\n debug \"Participation #{organization} -> #{user} exists\"\n participates\n end\n\n end", "language": "ruby", "code": "def ensure_participation(user, organization, members = true)\n org = ensure_org(organization, members)\n\n if org.nil?\n warn \"Could not find organization #{organization}\"\n return\n end\n\n usr = ensure_user(user, false, false)\n\n org_members = db[:organization_members]\n participates = org_members.first(:user_id => usr[:id], :org_id => org[:id])\n\n if participates.nil?\n org_members.insert(:user_id => usr[:id],\n :org_id => org[:id])\n info \"Added participation #{organization} -> #{user}\"\n org_members.first(:user_id => usr[:id], :org_id => org[:id])\n else\n debug \"Participation #{organization} -> #{user} exists\"\n participates\n end\n\n end", "code_tokens": ["def", "ensure_participation", "(", "user", ",", "organization", ",", "members", "=", "true", ")", "org", "=", "ensure_org", "(", "organization", ",", "members", ")", "if", "org", ".", "nil?", "warn", "\"Could not find organization #{organization}\"", "return", "end", "usr", "=", "ensure_user", "(", "user", ",", "false", ",", "false", ")", "org_members", "=", "db", "[", ":organization_members", "]", "participates", "=", "org_members", ".", "first", "(", ":user_id", "=>", "usr", "[", ":id", "]", ",", ":org_id", "=>", "org", "[", ":id", "]", ")", "if", "participates", ".", "nil?", "org_members", ".", "insert", "(", ":user_id", "=>", "usr", "[", ":id", "]", ",", ":org_id", "=>", "org", "[", ":id", "]", ")", "info", "\"Added participation #{organization} -> #{user}\"", "org_members", ".", "first", "(", ":user_id", "=>", "usr", "[", ":id", "]", ",", ":org_id", "=>", "org", "[", ":id", "]", ")", "else", "debug", "\"Participation #{organization} -> #{user} exists\"", "participates", "end", "end"], "docstring": "Make sure that a user participates to the provided organization\n\n ==Parameters:\n [user] The login name of the user to check the organizations for\n [org] The login name of the organization to check whether the user\n belongs in", "docstring_tokens": ["Make", "sure", "that", "a", "user", "participates", "to", "the", "provided", "organization"], "sha": "3566294a3e4a4c7574bc7376f7e6a9435529b5de", "url": "https://github.com/gousiosg/github-mirror/blob/3566294a3e4a4c7574bc7376f7e6a9435529b5de/lib/ghtorrent/ghtorrent.rb#L860-L883", "partition": "test"} {"repo": "gousiosg/github-mirror", "path": "lib/ghtorrent/ghtorrent.rb", "func_name": "GHTorrent.Mirror.ensure_org", "original_string": "def ensure_org(organization, members = true)\n org = db[:users].first(:login => organization, :type => 'org')\n\n if org.nil?\n org = ensure_user(organization, false, false)\n\n # Not an organization, don't go ahead\n if org[:type] != 'ORG'\n warn \"User #{organization} is not an organization\"\n return nil\n end\n end\n if members\n retrieve_org_members(organization).map do |x|\n ensure_participation(ensure_user(x['login'], false, false)[:login],\n organization, false)\n end\n end\n org\n end", "language": "ruby", "code": "def ensure_org(organization, members = true)\n org = db[:users].first(:login => organization, :type => 'org')\n\n if org.nil?\n org = ensure_user(organization, false, false)\n\n # Not an organization, don't go ahead\n if org[:type] != 'ORG'\n warn \"User #{organization} is not an organization\"\n return nil\n end\n end\n if members\n retrieve_org_members(organization).map do |x|\n ensure_participation(ensure_user(x['login'], false, false)[:login],\n organization, false)\n end\n end\n org\n end", "code_tokens": ["def", "ensure_org", "(", "organization", ",", "members", "=", "true", ")", "org", "=", "db", "[", ":users", "]", ".", "first", "(", ":login", "=>", "organization", ",", ":type", "=>", "'org'", ")", "if", "org", ".", "nil?", "org", "=", "ensure_user", "(", "organization", ",", "false", ",", "false", ")", "# Not an organization, don't go ahead", "if", "org", "[", ":type", "]", "!=", "'ORG'", "warn", "\"User #{organization} is not an organization\"", "return", "nil", "end", "end", "if", "members", "retrieve_org_members", "(", "organization", ")", ".", "map", "do", "|", "x", "|", "ensure_participation", "(", "ensure_user", "(", "x", "[", "'login'", "]", ",", "false", ",", "false", ")", "[", ":login", "]", ",", "organization", ",", "false", ")", "end", "end", "org", "end"], "docstring": "Make sure that an organization exists\n\n ==Parameters:\n [organization] The login name of the organization", "docstring_tokens": ["Make", "sure", "that", "an", "organization", "exists"], "sha": "3566294a3e4a4c7574bc7376f7e6a9435529b5de", "url": "https://github.com/gousiosg/github-mirror/blob/3566294a3e4a4c7574bc7376f7e6a9435529b5de/lib/ghtorrent/ghtorrent.rb#L891-L910", "partition": "test"} {"repo": "gousiosg/github-mirror", "path": "lib/ghtorrent/ghtorrent.rb", "func_name": "GHTorrent.Mirror.ensure_commit_comments", "original_string": "def ensure_commit_comments(user, repo, sha)\n commit_id = db[:commits].first(:sha => sha)[:id]\n stored_comments = db[:commit_comments].filter(:commit_id => commit_id)\n commit_comments = retrieve_commit_comments(user, repo, sha)\n\n not_saved = commit_comments.reduce([]) do |acc, x|\n if stored_comments.find{|y| y[:comment_id] == x['id']}.nil?\n acc << x\n else\n acc\n end\n end\n\n not_saved.map{|x| save{ensure_commit_comment(user, repo, sha, x['id'])}}.select{|x| !x.nil?}\n end", "language": "ruby", "code": "def ensure_commit_comments(user, repo, sha)\n commit_id = db[:commits].first(:sha => sha)[:id]\n stored_comments = db[:commit_comments].filter(:commit_id => commit_id)\n commit_comments = retrieve_commit_comments(user, repo, sha)\n\n not_saved = commit_comments.reduce([]) do |acc, x|\n if stored_comments.find{|y| y[:comment_id] == x['id']}.nil?\n acc << x\n else\n acc\n end\n end\n\n not_saved.map{|x| save{ensure_commit_comment(user, repo, sha, x['id'])}}.select{|x| !x.nil?}\n end", "code_tokens": ["def", "ensure_commit_comments", "(", "user", ",", "repo", ",", "sha", ")", "commit_id", "=", "db", "[", ":commits", "]", ".", "first", "(", ":sha", "=>", "sha", ")", "[", ":id", "]", "stored_comments", "=", "db", "[", ":commit_comments", "]", ".", "filter", "(", ":commit_id", "=>", "commit_id", ")", "commit_comments", "=", "retrieve_commit_comments", "(", "user", ",", "repo", ",", "sha", ")", "not_saved", "=", "commit_comments", ".", "reduce", "(", "[", "]", ")", "do", "|", "acc", ",", "x", "|", "if", "stored_comments", ".", "find", "{", "|", "y", "|", "y", "[", ":comment_id", "]", "==", "x", "[", "'id'", "]", "}", ".", "nil?", "acc", "<<", "x", "else", "acc", "end", "end", "not_saved", ".", "map", "{", "|", "x", "|", "save", "{", "ensure_commit_comment", "(", "user", ",", "repo", ",", "sha", ",", "x", "[", "'id'", "]", ")", "}", "}", ".", "select", "{", "|", "x", "|", "!", "x", ".", "nil?", "}", "end"], "docstring": "Get all comments for a commit\n\n ==Parameters:\n [user] The login name of the organization\n [user] The repository containing the commit whose comments will be retrieved\n [sha] The commit sha to retrieve comments for", "docstring_tokens": ["Get", "all", "comments", "for", "a", "commit"], "sha": "3566294a3e4a4c7574bc7376f7e6a9435529b5de", "url": "https://github.com/gousiosg/github-mirror/blob/3566294a3e4a4c7574bc7376f7e6a9435529b5de/lib/ghtorrent/ghtorrent.rb#L919-L933", "partition": "test"} {"repo": "gousiosg/github-mirror", "path": "lib/ghtorrent/ghtorrent.rb", "func_name": "GHTorrent.Mirror.ensure_watchers", "original_string": "def ensure_watchers(owner, repo)\n currepo = ensure_repo(owner, repo)\n\n if currepo.nil?\n warn \"Could not find repo #{owner}/#{repo} for retrieving watchers\"\n return\n end\n\n watchers = db.from(:watchers, :users).\\\n where(Sequel.qualify('watchers', 'user_id') => Sequel.qualify('users', 'id')).\\\n where(Sequel.qualify('watchers', 'repo_id') => currepo[:id]).select(:login).all\n\n retrieve_watchers(owner, repo).reduce([]) do |acc, x|\n if watchers.find { |y|\n y[:login] == x['login']\n }.nil?\n acc << x\n else\n acc\n end\n end.map { |x| save{ensure_watcher(owner, repo, x['login']) }}.select{|x| !x.nil?}\n end", "language": "ruby", "code": "def ensure_watchers(owner, repo)\n currepo = ensure_repo(owner, repo)\n\n if currepo.nil?\n warn \"Could not find repo #{owner}/#{repo} for retrieving watchers\"\n return\n end\n\n watchers = db.from(:watchers, :users).\\\n where(Sequel.qualify('watchers', 'user_id') => Sequel.qualify('users', 'id')).\\\n where(Sequel.qualify('watchers', 'repo_id') => currepo[:id]).select(:login).all\n\n retrieve_watchers(owner, repo).reduce([]) do |acc, x|\n if watchers.find { |y|\n y[:login] == x['login']\n }.nil?\n acc << x\n else\n acc\n end\n end.map { |x| save{ensure_watcher(owner, repo, x['login']) }}.select{|x| !x.nil?}\n end", "code_tokens": ["def", "ensure_watchers", "(", "owner", ",", "repo", ")", "currepo", "=", "ensure_repo", "(", "owner", ",", "repo", ")", "if", "currepo", ".", "nil?", "warn", "\"Could not find repo #{owner}/#{repo} for retrieving watchers\"", "return", "end", "watchers", "=", "db", ".", "from", "(", ":watchers", ",", ":users", ")", ".", "where", "(", "Sequel", ".", "qualify", "(", "'watchers'", ",", "'user_id'", ")", "=>", "Sequel", ".", "qualify", "(", "'users'", ",", "'id'", ")", ")", ".", "where", "(", "Sequel", ".", "qualify", "(", "'watchers'", ",", "'repo_id'", ")", "=>", "currepo", "[", ":id", "]", ")", ".", "select", "(", ":login", ")", ".", "all", "retrieve_watchers", "(", "owner", ",", "repo", ")", ".", "reduce", "(", "[", "]", ")", "do", "|", "acc", ",", "x", "|", "if", "watchers", ".", "find", "{", "|", "y", "|", "y", "[", ":login", "]", "==", "x", "[", "'login'", "]", "}", ".", "nil?", "acc", "<<", "x", "else", "acc", "end", "end", ".", "map", "{", "|", "x", "|", "save", "{", "ensure_watcher", "(", "owner", ",", "repo", ",", "x", "[", "'login'", "]", ")", "}", "}", ".", "select", "{", "|", "x", "|", "!", "x", ".", "nil?", "}", "end"], "docstring": "Make sure that all watchers exist for a repository", "docstring_tokens": ["Make", "sure", "that", "all", "watchers", "exist", "for", "a", "repository"], "sha": "3566294a3e4a4c7574bc7376f7e6a9435529b5de", "url": "https://github.com/gousiosg/github-mirror/blob/3566294a3e4a4c7574bc7376f7e6a9435529b5de/lib/ghtorrent/ghtorrent.rb#L977-L998", "partition": "test"} {"repo": "gousiosg/github-mirror", "path": "lib/ghtorrent/ghtorrent.rb", "func_name": "GHTorrent.Mirror.ensure_pull_requests", "original_string": "def ensure_pull_requests(owner, repo, refresh = false)\n currepo = ensure_repo(owner, repo)\n if currepo.nil?\n warn \"Could not find repo #{owner}/#{repo} for retrieving pull requests\"\n return\n end\n\n raw_pull_reqs = if refresh\n retrieve_pull_requests(owner, repo, refresh = true)\n else\n pull_reqs = db[:pull_requests].filter(:base_repo_id => currepo[:id]).all\n retrieve_pull_requests(owner, repo).reduce([]) do |acc, x|\n if pull_reqs.find { |y| y[:pullreq_id] == x['number'] }.nil?\n acc << x\n else\n acc\n end\n end\n end\n\n raw_pull_reqs.map { |x| save { ensure_pull_request(owner, repo, x['number']) } }.select { |x| !x.nil? }\n end", "language": "ruby", "code": "def ensure_pull_requests(owner, repo, refresh = false)\n currepo = ensure_repo(owner, repo)\n if currepo.nil?\n warn \"Could not find repo #{owner}/#{repo} for retrieving pull requests\"\n return\n end\n\n raw_pull_reqs = if refresh\n retrieve_pull_requests(owner, repo, refresh = true)\n else\n pull_reqs = db[:pull_requests].filter(:base_repo_id => currepo[:id]).all\n retrieve_pull_requests(owner, repo).reduce([]) do |acc, x|\n if pull_reqs.find { |y| y[:pullreq_id] == x['number'] }.nil?\n acc << x\n else\n acc\n end\n end\n end\n\n raw_pull_reqs.map { |x| save { ensure_pull_request(owner, repo, x['number']) } }.select { |x| !x.nil? }\n end", "code_tokens": ["def", "ensure_pull_requests", "(", "owner", ",", "repo", ",", "refresh", "=", "false", ")", "currepo", "=", "ensure_repo", "(", "owner", ",", "repo", ")", "if", "currepo", ".", "nil?", "warn", "\"Could not find repo #{owner}/#{repo} for retrieving pull requests\"", "return", "end", "raw_pull_reqs", "=", "if", "refresh", "retrieve_pull_requests", "(", "owner", ",", "repo", ",", "refresh", "=", "true", ")", "else", "pull_reqs", "=", "db", "[", ":pull_requests", "]", ".", "filter", "(", ":base_repo_id", "=>", "currepo", "[", ":id", "]", ")", ".", "all", "retrieve_pull_requests", "(", "owner", ",", "repo", ")", ".", "reduce", "(", "[", "]", ")", "do", "|", "acc", ",", "x", "|", "if", "pull_reqs", ".", "find", "{", "|", "y", "|", "y", "[", ":pullreq_id", "]", "==", "x", "[", "'number'", "]", "}", ".", "nil?", "acc", "<<", "x", "else", "acc", "end", "end", "end", "raw_pull_reqs", ".", "map", "{", "|", "x", "|", "save", "{", "ensure_pull_request", "(", "owner", ",", "repo", ",", "x", "[", "'number'", "]", ")", "}", "}", ".", "select", "{", "|", "x", "|", "!", "x", ".", "nil?", "}", "end"], "docstring": "Process all pull requests", "docstring_tokens": ["Process", "all", "pull", "requests"], "sha": "3566294a3e4a4c7574bc7376f7e6a9435529b5de", "url": "https://github.com/gousiosg/github-mirror/blob/3566294a3e4a4c7574bc7376f7e6a9435529b5de/lib/ghtorrent/ghtorrent.rb#L1059-L1080", "partition": "test"} {"repo": "gousiosg/github-mirror", "path": "lib/ghtorrent/ghtorrent.rb", "func_name": "GHTorrent.Mirror.ensure_pull_request_history", "original_string": "def ensure_pull_request_history(id, ts, act, actor)\n user = unless actor.nil?\n ensure_user(actor, false, false)\n end\n pull_req_history = db[:pull_request_history]\n\n entry = if ['opened', 'merged'].include? act\n pull_req_history.first(:pull_request_id => id,\n :action => act)\n else\n pull_req_history.first(:pull_request_id => id,\n :created_at => (ts - 3)..(ts + 3),\n :action => act)\n end\n\n if entry.nil?\n pull_req_history.insert(:pull_request_id => id,\n :created_at => ts,\n :action => act,\n :actor_id => unless user.nil? then user[:id] end)\n info \"Added pullreq_event (#{id}) -> (#{act}) by (#{actor}) timestamp #{ts}\"\n else\n debug \"Pull request (#{id}) event (#{act}) by (#{actor}) timestamp #{ts} exists\"\n if entry[:actor_id].nil? and not user.nil?\n pull_req_history.where(:pull_request_id => id,\n :created_at => (ts - 3)..(ts + 3),\n :action => act)\\\n .update(:actor_id => user[:id])\n info \"Updated pull request (#{id}) event (#{act}) timestamp #{ts}, actor -> #{user[:login]}\"\n end\n end\n end", "language": "ruby", "code": "def ensure_pull_request_history(id, ts, act, actor)\n user = unless actor.nil?\n ensure_user(actor, false, false)\n end\n pull_req_history = db[:pull_request_history]\n\n entry = if ['opened', 'merged'].include? act\n pull_req_history.first(:pull_request_id => id,\n :action => act)\n else\n pull_req_history.first(:pull_request_id => id,\n :created_at => (ts - 3)..(ts + 3),\n :action => act)\n end\n\n if entry.nil?\n pull_req_history.insert(:pull_request_id => id,\n :created_at => ts,\n :action => act,\n :actor_id => unless user.nil? then user[:id] end)\n info \"Added pullreq_event (#{id}) -> (#{act}) by (#{actor}) timestamp #{ts}\"\n else\n debug \"Pull request (#{id}) event (#{act}) by (#{actor}) timestamp #{ts} exists\"\n if entry[:actor_id].nil? and not user.nil?\n pull_req_history.where(:pull_request_id => id,\n :created_at => (ts - 3)..(ts + 3),\n :action => act)\\\n .update(:actor_id => user[:id])\n info \"Updated pull request (#{id}) event (#{act}) timestamp #{ts}, actor -> #{user[:login]}\"\n end\n end\n end", "code_tokens": ["def", "ensure_pull_request_history", "(", "id", ",", "ts", ",", "act", ",", "actor", ")", "user", "=", "unless", "actor", ".", "nil?", "ensure_user", "(", "actor", ",", "false", ",", "false", ")", "end", "pull_req_history", "=", "db", "[", ":pull_request_history", "]", "entry", "=", "if", "[", "'opened'", ",", "'merged'", "]", ".", "include?", "act", "pull_req_history", ".", "first", "(", ":pull_request_id", "=>", "id", ",", ":action", "=>", "act", ")", "else", "pull_req_history", ".", "first", "(", ":pull_request_id", "=>", "id", ",", ":created_at", "=>", "(", "ts", "-", "3", ")", "..", "(", "ts", "+", "3", ")", ",", ":action", "=>", "act", ")", "end", "if", "entry", ".", "nil?", "pull_req_history", ".", "insert", "(", ":pull_request_id", "=>", "id", ",", ":created_at", "=>", "ts", ",", ":action", "=>", "act", ",", ":actor_id", "=>", "unless", "user", ".", "nil?", "then", "user", "[", ":id", "]", "end", ")", "info", "\"Added pullreq_event (#{id}) -> (#{act}) by (#{actor}) timestamp #{ts}\"", "else", "debug", "\"Pull request (#{id}) event (#{act}) by (#{actor}) timestamp #{ts} exists\"", "if", "entry", "[", ":actor_id", "]", ".", "nil?", "and", "not", "user", ".", "nil?", "pull_req_history", ".", "where", "(", ":pull_request_id", "=>", "id", ",", ":created_at", "=>", "(", "ts", "-", "3", ")", "..", "(", "ts", "+", "3", ")", ",", ":action", "=>", "act", ")", ".", "update", "(", ":actor_id", "=>", "user", "[", ":id", "]", ")", "info", "\"Updated pull request (#{id}) event (#{act}) timestamp #{ts}, actor -> #{user[:login]}\"", "end", "end", "end"], "docstring": "Adds a pull request history event", "docstring_tokens": ["Adds", "a", "pull", "request", "history", "event"], "sha": "3566294a3e4a4c7574bc7376f7e6a9435529b5de", "url": "https://github.com/gousiosg/github-mirror/blob/3566294a3e4a4c7574bc7376f7e6a9435529b5de/lib/ghtorrent/ghtorrent.rb#L1083-L1114", "partition": "test"} {"repo": "gousiosg/github-mirror", "path": "lib/ghtorrent/ghtorrent.rb", "func_name": "GHTorrent.Mirror.pr_is_intra_branch", "original_string": "def pr_is_intra_branch(req)\n return false unless pr_has_head_repo(req)\n\n if req['head']['repo']['owner']['login'] ==\n req['base']['repo']['owner']['login'] and\n req['head']['repo']['full_name'] == req['base']['repo']['full_name']\n true\n else\n false\n end\n end", "language": "ruby", "code": "def pr_is_intra_branch(req)\n return false unless pr_has_head_repo(req)\n\n if req['head']['repo']['owner']['login'] ==\n req['base']['repo']['owner']['login'] and\n req['head']['repo']['full_name'] == req['base']['repo']['full_name']\n true\n else\n false\n end\n end", "code_tokens": ["def", "pr_is_intra_branch", "(", "req", ")", "return", "false", "unless", "pr_has_head_repo", "(", "req", ")", "if", "req", "[", "'head'", "]", "[", "'repo'", "]", "[", "'owner'", "]", "[", "'login'", "]", "==", "req", "[", "'base'", "]", "[", "'repo'", "]", "[", "'owner'", "]", "[", "'login'", "]", "and", "req", "[", "'head'", "]", "[", "'repo'", "]", "[", "'full_name'", "]", "==", "req", "[", "'base'", "]", "[", "'repo'", "]", "[", "'full_name'", "]", "true", "else", "false", "end", "end"], "docstring": "Checks whether a pull request concerns two branches of the same\n repository", "docstring_tokens": ["Checks", "whether", "a", "pull", "request", "concerns", "two", "branches", "of", "the", "same", "repository"], "sha": "3566294a3e4a4c7574bc7376f7e6a9435529b5de", "url": "https://github.com/gousiosg/github-mirror/blob/3566294a3e4a4c7574bc7376f7e6a9435529b5de/lib/ghtorrent/ghtorrent.rb#L1118-L1128", "partition": "test"} {"repo": "gousiosg/github-mirror", "path": "lib/ghtorrent/ghtorrent.rb", "func_name": "GHTorrent.Mirror.ensure_forks", "original_string": "def ensure_forks(owner, repo)\n currepo = ensure_repo(owner, repo)\n\n if currepo.nil?\n warn \"Could not find repo #{owner}/#{repo} for retrieving forks\"\n return\n end\n\n existing_forks = db.from(:projects, :users).\\\n where(Sequel.qualify('users', 'id') => Sequel.qualify('projects', 'owner_id')). \\\n where(Sequel.qualify('projects', 'forked_from') => currepo[:id]).\\\n select(Sequel.qualify('projects', 'name'), :login).all\n\n retrieve_forks(owner, repo).reduce([]) do |acc, x|\n if existing_forks.find do |y|\n forked_repo_owner = x['url'].split(/\\//)[4]\n forked_repo_name = x['url'].split(/\\//)[5]\n y[:login] == forked_repo_owner && y[:name] == forked_repo_name\n end.nil?\n acc << x\n else\n acc\n end\n end.map { |x| save{ensure_fork(owner, repo, x['id']) }}.select{|x| !x.nil?}\n end", "language": "ruby", "code": "def ensure_forks(owner, repo)\n currepo = ensure_repo(owner, repo)\n\n if currepo.nil?\n warn \"Could not find repo #{owner}/#{repo} for retrieving forks\"\n return\n end\n\n existing_forks = db.from(:projects, :users).\\\n where(Sequel.qualify('users', 'id') => Sequel.qualify('projects', 'owner_id')). \\\n where(Sequel.qualify('projects', 'forked_from') => currepo[:id]).\\\n select(Sequel.qualify('projects', 'name'), :login).all\n\n retrieve_forks(owner, repo).reduce([]) do |acc, x|\n if existing_forks.find do |y|\n forked_repo_owner = x['url'].split(/\\//)[4]\n forked_repo_name = x['url'].split(/\\//)[5]\n y[:login] == forked_repo_owner && y[:name] == forked_repo_name\n end.nil?\n acc << x\n else\n acc\n end\n end.map { |x| save{ensure_fork(owner, repo, x['id']) }}.select{|x| !x.nil?}\n end", "code_tokens": ["def", "ensure_forks", "(", "owner", ",", "repo", ")", "currepo", "=", "ensure_repo", "(", "owner", ",", "repo", ")", "if", "currepo", ".", "nil?", "warn", "\"Could not find repo #{owner}/#{repo} for retrieving forks\"", "return", "end", "existing_forks", "=", "db", ".", "from", "(", ":projects", ",", ":users", ")", ".", "where", "(", "Sequel", ".", "qualify", "(", "'users'", ",", "'id'", ")", "=>", "Sequel", ".", "qualify", "(", "'projects'", ",", "'owner_id'", ")", ")", ".", "where", "(", "Sequel", ".", "qualify", "(", "'projects'", ",", "'forked_from'", ")", "=>", "currepo", "[", ":id", "]", ")", ".", "select", "(", "Sequel", ".", "qualify", "(", "'projects'", ",", "'name'", ")", ",", ":login", ")", ".", "all", "retrieve_forks", "(", "owner", ",", "repo", ")", ".", "reduce", "(", "[", "]", ")", "do", "|", "acc", ",", "x", "|", "if", "existing_forks", ".", "find", "do", "|", "y", "|", "forked_repo_owner", "=", "x", "[", "'url'", "]", ".", "split", "(", "/", "\\/", "/", ")", "[", "4", "]", "forked_repo_name", "=", "x", "[", "'url'", "]", ".", "split", "(", "/", "\\/", "/", ")", "[", "5", "]", "y", "[", ":login", "]", "==", "forked_repo_owner", "&&", "y", "[", ":name", "]", "==", "forked_repo_name", "end", ".", "nil?", "acc", "<<", "x", "else", "acc", "end", "end", ".", "map", "{", "|", "x", "|", "save", "{", "ensure_fork", "(", "owner", ",", "repo", ",", "x", "[", "'id'", "]", ")", "}", "}", ".", "select", "{", "|", "x", "|", "!", "x", ".", "nil?", "}", "end"], "docstring": "Get all forks for a project.\n\n ==Parameters:\n [owner] The user to which the project belongs\n [repo] The repository/project to find forks for", "docstring_tokens": ["Get", "all", "forks", "for", "a", "project", "."], "sha": "3566294a3e4a4c7574bc7376f7e6a9435529b5de", "url": "https://github.com/gousiosg/github-mirror/blob/3566294a3e4a4c7574bc7376f7e6a9435529b5de/lib/ghtorrent/ghtorrent.rb#L1379-L1403", "partition": "test"} {"repo": "gousiosg/github-mirror", "path": "lib/ghtorrent/ghtorrent.rb", "func_name": "GHTorrent.Mirror.ensure_fork", "original_string": "def ensure_fork(owner, repo, fork_id)\n fork = retrieve_fork(owner, repo, fork_id)\n\n if fork.nil?\n warn \"Could not retrieve fork #{owner}/#{repo} -> #{fork_id}\"\n return\n end\n\n fork_name = if fork['full_name'].nil? then fork['url'].split(/\\//)[4..5].join('/') else fork['full_name'] end\n fork_owner = fork_name.split(/\\//)[0]\n fork_name = fork_name.split(/\\//)[1]\n\n r = ensure_repo(fork_owner, fork_name, true)\n\n if r.nil?\n warn \"Could not add #{fork_owner}/#{fork_name} as fork of #{owner}/#{repo}\"\n else\n info \"Added fork #{fork_owner}/#{fork_name} of #{owner}/#{repo}\"\n end\n r\n end", "language": "ruby", "code": "def ensure_fork(owner, repo, fork_id)\n fork = retrieve_fork(owner, repo, fork_id)\n\n if fork.nil?\n warn \"Could not retrieve fork #{owner}/#{repo} -> #{fork_id}\"\n return\n end\n\n fork_name = if fork['full_name'].nil? then fork['url'].split(/\\//)[4..5].join('/') else fork['full_name'] end\n fork_owner = fork_name.split(/\\//)[0]\n fork_name = fork_name.split(/\\//)[1]\n\n r = ensure_repo(fork_owner, fork_name, true)\n\n if r.nil?\n warn \"Could not add #{fork_owner}/#{fork_name} as fork of #{owner}/#{repo}\"\n else\n info \"Added fork #{fork_owner}/#{fork_name} of #{owner}/#{repo}\"\n end\n r\n end", "code_tokens": ["def", "ensure_fork", "(", "owner", ",", "repo", ",", "fork_id", ")", "fork", "=", "retrieve_fork", "(", "owner", ",", "repo", ",", "fork_id", ")", "if", "fork", ".", "nil?", "warn", "\"Could not retrieve fork #{owner}/#{repo} -> #{fork_id}\"", "return", "end", "fork_name", "=", "if", "fork", "[", "'full_name'", "]", ".", "nil?", "then", "fork", "[", "'url'", "]", ".", "split", "(", "/", "\\/", "/", ")", "[", "4", "..", "5", "]", ".", "join", "(", "'/'", ")", "else", "fork", "[", "'full_name'", "]", "end", "fork_owner", "=", "fork_name", ".", "split", "(", "/", "\\/", "/", ")", "[", "0", "]", "fork_name", "=", "fork_name", ".", "split", "(", "/", "\\/", "/", ")", "[", "1", "]", "r", "=", "ensure_repo", "(", "fork_owner", ",", "fork_name", ",", "true", ")", "if", "r", ".", "nil?", "warn", "\"Could not add #{fork_owner}/#{fork_name} as fork of #{owner}/#{repo}\"", "else", "info", "\"Added fork #{fork_owner}/#{fork_name} of #{owner}/#{repo}\"", "end", "r", "end"], "docstring": "Make sure that a fork is retrieved for a project", "docstring_tokens": ["Make", "sure", "that", "a", "fork", "is", "retrieved", "for", "a", "project"], "sha": "3566294a3e4a4c7574bc7376f7e6a9435529b5de", "url": "https://github.com/gousiosg/github-mirror/blob/3566294a3e4a4c7574bc7376f7e6a9435529b5de/lib/ghtorrent/ghtorrent.rb#L1407-L1427", "partition": "test"} {"repo": "gousiosg/github-mirror", "path": "lib/ghtorrent/ghtorrent.rb", "func_name": "GHTorrent.Mirror.ensure_issues", "original_string": "def ensure_issues(owner, repo)\n currepo = ensure_repo(owner, repo)\n if currepo.nil?\n warn \"Could not find repo #{owner}/#{repo} for retrieving issues\"\n return\n end\n\n issues = db[:issues].filter(:repo_id => currepo[:id]).all\n raw_issues = retrieve_issues(owner, repo).reduce([]) do |acc, x|\n if issues.find { |y| y[:issue_id] == x['number'] }.nil?\n acc << x\n else\n acc\n end\n end\n\n raw_issues.map { |x| save { ensure_issue(owner, repo, x['number']) } }.select { |x| !x.nil? }\n end", "language": "ruby", "code": "def ensure_issues(owner, repo)\n currepo = ensure_repo(owner, repo)\n if currepo.nil?\n warn \"Could not find repo #{owner}/#{repo} for retrieving issues\"\n return\n end\n\n issues = db[:issues].filter(:repo_id => currepo[:id]).all\n raw_issues = retrieve_issues(owner, repo).reduce([]) do |acc, x|\n if issues.find { |y| y[:issue_id] == x['number'] }.nil?\n acc << x\n else\n acc\n end\n end\n\n raw_issues.map { |x| save { ensure_issue(owner, repo, x['number']) } }.select { |x| !x.nil? }\n end", "code_tokens": ["def", "ensure_issues", "(", "owner", ",", "repo", ")", "currepo", "=", "ensure_repo", "(", "owner", ",", "repo", ")", "if", "currepo", ".", "nil?", "warn", "\"Could not find repo #{owner}/#{repo} for retrieving issues\"", "return", "end", "issues", "=", "db", "[", ":issues", "]", ".", "filter", "(", ":repo_id", "=>", "currepo", "[", ":id", "]", ")", ".", "all", "raw_issues", "=", "retrieve_issues", "(", "owner", ",", "repo", ")", ".", "reduce", "(", "[", "]", ")", "do", "|", "acc", ",", "x", "|", "if", "issues", ".", "find", "{", "|", "y", "|", "y", "[", ":issue_id", "]", "==", "x", "[", "'number'", "]", "}", ".", "nil?", "acc", "<<", "x", "else", "acc", "end", "end", "raw_issues", ".", "map", "{", "|", "x", "|", "save", "{", "ensure_issue", "(", "owner", ",", "repo", ",", "x", "[", "'number'", "]", ")", "}", "}", ".", "select", "{", "|", "x", "|", "!", "x", ".", "nil?", "}", "end"], "docstring": "Make sure all issues exist for a project", "docstring_tokens": ["Make", "sure", "all", "issues", "exist", "for", "a", "project"], "sha": "3566294a3e4a4c7574bc7376f7e6a9435529b5de", "url": "https://github.com/gousiosg/github-mirror/blob/3566294a3e4a4c7574bc7376f7e6a9435529b5de/lib/ghtorrent/ghtorrent.rb#L1431-L1448", "partition": "test"} {"repo": "gousiosg/github-mirror", "path": "lib/ghtorrent/ghtorrent.rb", "func_name": "GHTorrent.Mirror.ensure_issue", "original_string": "def ensure_issue(owner, repo, issue_id, events = true,\n comments = true, labels = true)\n\n issues = db[:issues]\n repository = ensure_repo(owner, repo)\n\n if repository.nil?\n warn \"Could not find repo #{owner}/#{repo} for retrieving issue #{issue_id}\"\n return\n end\n\n cur_issue = issues.first(:issue_id => issue_id,\n :repo_id => repository[:id])\n\n retrieved = retrieve_issue(owner, repo, issue_id)\n\n if retrieved.nil?\n warn \"Could not retrieve issue #{owner}/#{repo} -> #{issue_id}\"\n return\n end\n\n # Pull requests and issues share the same issue_id\n pull_req = unless retrieved['pull_request'].nil? or\n retrieved['pull_request']['patch_url'].nil?\n debug \"Issue #{owner}/#{repo}->#{issue_id} is a pull request\"\n ensure_pull_request(owner, repo, issue_id, false, false, false)\n end\n\n if cur_issue.nil?\n\n reporter = ensure_user(retrieved['user']['login'], false, false)\n assignee = unless retrieved['assignee'].nil?\n ensure_user(retrieved['assignee']['login'], false, false)\n end\n\n issues.insert(:repo_id => repository[:id],\n :assignee_id => unless assignee.nil? then assignee[:id] end,\n :reporter_id => reporter[:id],\n :issue_id => issue_id,\n :pull_request => if pull_req.nil? then false else true end,\n :pull_request_id => unless pull_req.nil? then pull_req[:id] end,\n :created_at => date(retrieved['created_at']))\n\n info \"Added issue #{owner}/#{repo} -> #{issue_id}\"\n else\n debug \"Issue #{owner}/#{repo}->#{issue_id} exists\"\n if cur_issue[:pull_request] == false and not pull_req.nil?\n info \"Updated issue #{owner}/#{repo}->#{issue_id} as pull request\"\n issues.filter(:issue_id => issue_id, :repo_id => repository[:id]).update(\n :pull_request => true,\n :pull_request_id => pull_req[:id])\n end\n end\n ensure_issue_events(owner, repo, issue_id) if events\n ensure_issue_comments(owner, repo, issue_id) if comments\n ensure_issue_labels(owner, repo, issue_id) if labels\n issues.first(:issue_id => issue_id,\n :repo_id => repository[:id])\n end", "language": "ruby", "code": "def ensure_issue(owner, repo, issue_id, events = true,\n comments = true, labels = true)\n\n issues = db[:issues]\n repository = ensure_repo(owner, repo)\n\n if repository.nil?\n warn \"Could not find repo #{owner}/#{repo} for retrieving issue #{issue_id}\"\n return\n end\n\n cur_issue = issues.first(:issue_id => issue_id,\n :repo_id => repository[:id])\n\n retrieved = retrieve_issue(owner, repo, issue_id)\n\n if retrieved.nil?\n warn \"Could not retrieve issue #{owner}/#{repo} -> #{issue_id}\"\n return\n end\n\n # Pull requests and issues share the same issue_id\n pull_req = unless retrieved['pull_request'].nil? or\n retrieved['pull_request']['patch_url'].nil?\n debug \"Issue #{owner}/#{repo}->#{issue_id} is a pull request\"\n ensure_pull_request(owner, repo, issue_id, false, false, false)\n end\n\n if cur_issue.nil?\n\n reporter = ensure_user(retrieved['user']['login'], false, false)\n assignee = unless retrieved['assignee'].nil?\n ensure_user(retrieved['assignee']['login'], false, false)\n end\n\n issues.insert(:repo_id => repository[:id],\n :assignee_id => unless assignee.nil? then assignee[:id] end,\n :reporter_id => reporter[:id],\n :issue_id => issue_id,\n :pull_request => if pull_req.nil? then false else true end,\n :pull_request_id => unless pull_req.nil? then pull_req[:id] end,\n :created_at => date(retrieved['created_at']))\n\n info \"Added issue #{owner}/#{repo} -> #{issue_id}\"\n else\n debug \"Issue #{owner}/#{repo}->#{issue_id} exists\"\n if cur_issue[:pull_request] == false and not pull_req.nil?\n info \"Updated issue #{owner}/#{repo}->#{issue_id} as pull request\"\n issues.filter(:issue_id => issue_id, :repo_id => repository[:id]).update(\n :pull_request => true,\n :pull_request_id => pull_req[:id])\n end\n end\n ensure_issue_events(owner, repo, issue_id) if events\n ensure_issue_comments(owner, repo, issue_id) if comments\n ensure_issue_labels(owner, repo, issue_id) if labels\n issues.first(:issue_id => issue_id,\n :repo_id => repository[:id])\n end", "code_tokens": ["def", "ensure_issue", "(", "owner", ",", "repo", ",", "issue_id", ",", "events", "=", "true", ",", "comments", "=", "true", ",", "labels", "=", "true", ")", "issues", "=", "db", "[", ":issues", "]", "repository", "=", "ensure_repo", "(", "owner", ",", "repo", ")", "if", "repository", ".", "nil?", "warn", "\"Could not find repo #{owner}/#{repo} for retrieving issue #{issue_id}\"", "return", "end", "cur_issue", "=", "issues", ".", "first", "(", ":issue_id", "=>", "issue_id", ",", ":repo_id", "=>", "repository", "[", ":id", "]", ")", "retrieved", "=", "retrieve_issue", "(", "owner", ",", "repo", ",", "issue_id", ")", "if", "retrieved", ".", "nil?", "warn", "\"Could not retrieve issue #{owner}/#{repo} -> #{issue_id}\"", "return", "end", "# Pull requests and issues share the same issue_id", "pull_req", "=", "unless", "retrieved", "[", "'pull_request'", "]", ".", "nil?", "or", "retrieved", "[", "'pull_request'", "]", "[", "'patch_url'", "]", ".", "nil?", "debug", "\"Issue #{owner}/#{repo}->#{issue_id} is a pull request\"", "ensure_pull_request", "(", "owner", ",", "repo", ",", "issue_id", ",", "false", ",", "false", ",", "false", ")", "end", "if", "cur_issue", ".", "nil?", "reporter", "=", "ensure_user", "(", "retrieved", "[", "'user'", "]", "[", "'login'", "]", ",", "false", ",", "false", ")", "assignee", "=", "unless", "retrieved", "[", "'assignee'", "]", ".", "nil?", "ensure_user", "(", "retrieved", "[", "'assignee'", "]", "[", "'login'", "]", ",", "false", ",", "false", ")", "end", "issues", ".", "insert", "(", ":repo_id", "=>", "repository", "[", ":id", "]", ",", ":assignee_id", "=>", "unless", "assignee", ".", "nil?", "then", "assignee", "[", ":id", "]", "end", ",", ":reporter_id", "=>", "reporter", "[", ":id", "]", ",", ":issue_id", "=>", "issue_id", ",", ":pull_request", "=>", "if", "pull_req", ".", "nil?", "then", "false", "else", "true", "end", ",", ":pull_request_id", "=>", "unless", "pull_req", ".", "nil?", "then", "pull_req", "[", ":id", "]", "end", ",", ":created_at", "=>", "date", "(", "retrieved", "[", "'created_at'", "]", ")", ")", "info", "\"Added issue #{owner}/#{repo} -> #{issue_id}\"", "else", "debug", "\"Issue #{owner}/#{repo}->#{issue_id} exists\"", "if", "cur_issue", "[", ":pull_request", "]", "==", "false", "and", "not", "pull_req", ".", "nil?", "info", "\"Updated issue #{owner}/#{repo}->#{issue_id} as pull request\"", "issues", ".", "filter", "(", ":issue_id", "=>", "issue_id", ",", ":repo_id", "=>", "repository", "[", ":id", "]", ")", ".", "update", "(", ":pull_request", "=>", "true", ",", ":pull_request_id", "=>", "pull_req", "[", ":id", "]", ")", "end", "end", "ensure_issue_events", "(", "owner", ",", "repo", ",", "issue_id", ")", "if", "events", "ensure_issue_comments", "(", "owner", ",", "repo", ",", "issue_id", ")", "if", "comments", "ensure_issue_labels", "(", "owner", ",", "repo", ",", "issue_id", ")", "if", "labels", "issues", ".", "first", "(", ":issue_id", "=>", "issue_id", ",", ":repo_id", "=>", "repository", "[", ":id", "]", ")", "end"], "docstring": "Make sure that the issue exists", "docstring_tokens": ["Make", "sure", "that", "the", "issue", "exists"], "sha": "3566294a3e4a4c7574bc7376f7e6a9435529b5de", "url": "https://github.com/gousiosg/github-mirror/blob/3566294a3e4a4c7574bc7376f7e6a9435529b5de/lib/ghtorrent/ghtorrent.rb#L1452-L1510", "partition": "test"} {"repo": "gousiosg/github-mirror", "path": "lib/ghtorrent/ghtorrent.rb", "func_name": "GHTorrent.Mirror.ensure_issue_events", "original_string": "def ensure_issue_events(owner, repo, issue_id)\n currepo = ensure_repo(owner, repo)\n\n if currepo.nil?\n warn \"Could not find repository #{owner}/#{repo} for retrieving events for issue #{issue_id}\"\n return\n end\n\n issue = ensure_issue(owner, repo, issue_id, false, false, false)\n if issue.nil?\n warn \"Could not find issue #{owner}/#{repo} -> #{issue_id} for retrieving events\"\n return\n end\n\n retrieve_issue_events(owner, repo, issue_id).reduce([]) do |acc, x|\n\n if db[:issue_events].first(:issue_id => issue[:id],\n :event_id => x['id']).nil?\n acc << x\n else\n acc\n end\n end.map { |x|\n save{ensure_issue_event(owner, repo, issue_id, x['id'])}\n }.select{|x| !x.nil?}\n end", "language": "ruby", "code": "def ensure_issue_events(owner, repo, issue_id)\n currepo = ensure_repo(owner, repo)\n\n if currepo.nil?\n warn \"Could not find repository #{owner}/#{repo} for retrieving events for issue #{issue_id}\"\n return\n end\n\n issue = ensure_issue(owner, repo, issue_id, false, false, false)\n if issue.nil?\n warn \"Could not find issue #{owner}/#{repo} -> #{issue_id} for retrieving events\"\n return\n end\n\n retrieve_issue_events(owner, repo, issue_id).reduce([]) do |acc, x|\n\n if db[:issue_events].first(:issue_id => issue[:id],\n :event_id => x['id']).nil?\n acc << x\n else\n acc\n end\n end.map { |x|\n save{ensure_issue_event(owner, repo, issue_id, x['id'])}\n }.select{|x| !x.nil?}\n end", "code_tokens": ["def", "ensure_issue_events", "(", "owner", ",", "repo", ",", "issue_id", ")", "currepo", "=", "ensure_repo", "(", "owner", ",", "repo", ")", "if", "currepo", ".", "nil?", "warn", "\"Could not find repository #{owner}/#{repo} for retrieving events for issue #{issue_id}\"", "return", "end", "issue", "=", "ensure_issue", "(", "owner", ",", "repo", ",", "issue_id", ",", "false", ",", "false", ",", "false", ")", "if", "issue", ".", "nil?", "warn", "\"Could not find issue #{owner}/#{repo} -> #{issue_id} for retrieving events\"", "return", "end", "retrieve_issue_events", "(", "owner", ",", "repo", ",", "issue_id", ")", ".", "reduce", "(", "[", "]", ")", "do", "|", "acc", ",", "x", "|", "if", "db", "[", ":issue_events", "]", ".", "first", "(", ":issue_id", "=>", "issue", "[", ":id", "]", ",", ":event_id", "=>", "x", "[", "'id'", "]", ")", ".", "nil?", "acc", "<<", "x", "else", "acc", "end", "end", ".", "map", "{", "|", "x", "|", "save", "{", "ensure_issue_event", "(", "owner", ",", "repo", ",", "issue_id", ",", "x", "[", "'id'", "]", ")", "}", "}", ".", "select", "{", "|", "x", "|", "!", "x", ".", "nil?", "}", "end"], "docstring": "Retrieve and process all events for an issue", "docstring_tokens": ["Retrieve", "and", "process", "all", "events", "for", "an", "issue"], "sha": "3566294a3e4a4c7574bc7376f7e6a9435529b5de", "url": "https://github.com/gousiosg/github-mirror/blob/3566294a3e4a4c7574bc7376f7e6a9435529b5de/lib/ghtorrent/ghtorrent.rb#L1514-L1539", "partition": "test"} {"repo": "gousiosg/github-mirror", "path": "lib/ghtorrent/ghtorrent.rb", "func_name": "GHTorrent.Mirror.ensure_issue_event", "original_string": "def ensure_issue_event(owner, repo, issue_id, event_id)\n issue = ensure_issue(owner, repo, issue_id, false, false, false)\n\n if issue.nil?\n warn \"Could not find issue #{owner}/#{repo} -> #{issue_id} for retrieving event #{event_id}\"\n return\n end\n\n issue_event_str = \"#{owner}/#{repo} -> #{issue_id}/#{event_id}\"\n\n curevent = db[:issue_events].first(:issue_id => issue[:id],\n :event_id => event_id)\n if curevent.nil?\n\n retrieved = retrieve_issue_event(owner, repo, issue_id, event_id)\n\n if retrieved.nil?\n warn \"Could not retrieve issue_event #{owner}/#{repo} -> #{issue_id}/#{issue_event_str}\"\n return\n elsif retrieved['actor'].nil?\n warn \"Could not find issue_event_actor #{owner}/#{repo} -> #{issue_id}/#{issue_event_str}\"\n return\n end\n\n actor = ensure_user(retrieved['actor']['login'], false, false)\n\n action_specific = case retrieved['event']\n when \"referenced\" then retrieved['commit_id']\n when \"merged\" then retrieved['commit_id']\n when \"closed\" then retrieved['commit_id']\n else nil\n end\n\n if retrieved['event'] == 'assigned'\n\n def update_assignee(owner, repo, issue, actor)\n db[:issues].first(:id => issue[:id]).update(:assignee_id => actor[:id])\n info \"Updated #{owner}/#{repo} -> #{issue[:id]}, assignee -> #{actor[:id]}\"\n end\n\n if issue[:assignee_id].nil? then\n update_assignee(owner, repo, issue, actor)\n else\n existing = db[:issue_events].\\\n filter(:issue_id => issue[:id],:action => 'assigned').\\\n order(Sequel.desc(:created_at)).first\n if existing.nil?\n update_assignee(owner, repo, issue, actor)\n elsif date(existing[:created_at]) < date(retrieved['created_at'])\n update_assignee(owner, repo, issue, actor)\n end\n end\n end\n\n db[:issue_events].insert(\n :event_id => event_id,\n :issue_id => issue[:id],\n :actor_id => unless actor.nil? then actor[:id] end,\n :action => retrieved['event'],\n :action_specific => action_specific,\n :created_at => date(retrieved['created_at']))\n\n info \"Added issue_event #{owner}/#{repo} -> #{issue_id}/#{issue_event_str}\"\n db[:issue_events].first(:issue_id => issue[:id],\n :event_id => event_id)\n else\n debug \"Issue event #{owner}/#{repo} -> #{issue_id}/#{issue_event_str} exists\"\n curevent\n end\n end", "language": "ruby", "code": "def ensure_issue_event(owner, repo, issue_id, event_id)\n issue = ensure_issue(owner, repo, issue_id, false, false, false)\n\n if issue.nil?\n warn \"Could not find issue #{owner}/#{repo} -> #{issue_id} for retrieving event #{event_id}\"\n return\n end\n\n issue_event_str = \"#{owner}/#{repo} -> #{issue_id}/#{event_id}\"\n\n curevent = db[:issue_events].first(:issue_id => issue[:id],\n :event_id => event_id)\n if curevent.nil?\n\n retrieved = retrieve_issue_event(owner, repo, issue_id, event_id)\n\n if retrieved.nil?\n warn \"Could not retrieve issue_event #{owner}/#{repo} -> #{issue_id}/#{issue_event_str}\"\n return\n elsif retrieved['actor'].nil?\n warn \"Could not find issue_event_actor #{owner}/#{repo} -> #{issue_id}/#{issue_event_str}\"\n return\n end\n\n actor = ensure_user(retrieved['actor']['login'], false, false)\n\n action_specific = case retrieved['event']\n when \"referenced\" then retrieved['commit_id']\n when \"merged\" then retrieved['commit_id']\n when \"closed\" then retrieved['commit_id']\n else nil\n end\n\n if retrieved['event'] == 'assigned'\n\n def update_assignee(owner, repo, issue, actor)\n db[:issues].first(:id => issue[:id]).update(:assignee_id => actor[:id])\n info \"Updated #{owner}/#{repo} -> #{issue[:id]}, assignee -> #{actor[:id]}\"\n end\n\n if issue[:assignee_id].nil? then\n update_assignee(owner, repo, issue, actor)\n else\n existing = db[:issue_events].\\\n filter(:issue_id => issue[:id],:action => 'assigned').\\\n order(Sequel.desc(:created_at)).first\n if existing.nil?\n update_assignee(owner, repo, issue, actor)\n elsif date(existing[:created_at]) < date(retrieved['created_at'])\n update_assignee(owner, repo, issue, actor)\n end\n end\n end\n\n db[:issue_events].insert(\n :event_id => event_id,\n :issue_id => issue[:id],\n :actor_id => unless actor.nil? then actor[:id] end,\n :action => retrieved['event'],\n :action_specific => action_specific,\n :created_at => date(retrieved['created_at']))\n\n info \"Added issue_event #{owner}/#{repo} -> #{issue_id}/#{issue_event_str}\"\n db[:issue_events].first(:issue_id => issue[:id],\n :event_id => event_id)\n else\n debug \"Issue event #{owner}/#{repo} -> #{issue_id}/#{issue_event_str} exists\"\n curevent\n end\n end", "code_tokens": ["def", "ensure_issue_event", "(", "owner", ",", "repo", ",", "issue_id", ",", "event_id", ")", "issue", "=", "ensure_issue", "(", "owner", ",", "repo", ",", "issue_id", ",", "false", ",", "false", ",", "false", ")", "if", "issue", ".", "nil?", "warn", "\"Could not find issue #{owner}/#{repo} -> #{issue_id} for retrieving event #{event_id}\"", "return", "end", "issue_event_str", "=", "\"#{owner}/#{repo} -> #{issue_id}/#{event_id}\"", "curevent", "=", "db", "[", ":issue_events", "]", ".", "first", "(", ":issue_id", "=>", "issue", "[", ":id", "]", ",", ":event_id", "=>", "event_id", ")", "if", "curevent", ".", "nil?", "retrieved", "=", "retrieve_issue_event", "(", "owner", ",", "repo", ",", "issue_id", ",", "event_id", ")", "if", "retrieved", ".", "nil?", "warn", "\"Could not retrieve issue_event #{owner}/#{repo} -> #{issue_id}/#{issue_event_str}\"", "return", "elsif", "retrieved", "[", "'actor'", "]", ".", "nil?", "warn", "\"Could not find issue_event_actor #{owner}/#{repo} -> #{issue_id}/#{issue_event_str}\"", "return", "end", "actor", "=", "ensure_user", "(", "retrieved", "[", "'actor'", "]", "[", "'login'", "]", ",", "false", ",", "false", ")", "action_specific", "=", "case", "retrieved", "[", "'event'", "]", "when", "\"referenced\"", "then", "retrieved", "[", "'commit_id'", "]", "when", "\"merged\"", "then", "retrieved", "[", "'commit_id'", "]", "when", "\"closed\"", "then", "retrieved", "[", "'commit_id'", "]", "else", "nil", "end", "if", "retrieved", "[", "'event'", "]", "==", "'assigned'", "def", "update_assignee", "(", "owner", ",", "repo", ",", "issue", ",", "actor", ")", "db", "[", ":issues", "]", ".", "first", "(", ":id", "=>", "issue", "[", ":id", "]", ")", ".", "update", "(", ":assignee_id", "=>", "actor", "[", ":id", "]", ")", "info", "\"Updated #{owner}/#{repo} -> #{issue[:id]}, assignee -> #{actor[:id]}\"", "end", "if", "issue", "[", ":assignee_id", "]", ".", "nil?", "then", "update_assignee", "(", "owner", ",", "repo", ",", "issue", ",", "actor", ")", "else", "existing", "=", "db", "[", ":issue_events", "]", ".", "filter", "(", ":issue_id", "=>", "issue", "[", ":id", "]", ",", ":action", "=>", "'assigned'", ")", ".", "order", "(", "Sequel", ".", "desc", "(", ":created_at", ")", ")", ".", "first", "if", "existing", ".", "nil?", "update_assignee", "(", "owner", ",", "repo", ",", "issue", ",", "actor", ")", "elsif", "date", "(", "existing", "[", ":created_at", "]", ")", "<", "date", "(", "retrieved", "[", "'created_at'", "]", ")", "update_assignee", "(", "owner", ",", "repo", ",", "issue", ",", "actor", ")", "end", "end", "end", "db", "[", ":issue_events", "]", ".", "insert", "(", ":event_id", "=>", "event_id", ",", ":issue_id", "=>", "issue", "[", ":id", "]", ",", ":actor_id", "=>", "unless", "actor", ".", "nil?", "then", "actor", "[", ":id", "]", "end", ",", ":action", "=>", "retrieved", "[", "'event'", "]", ",", ":action_specific", "=>", "action_specific", ",", ":created_at", "=>", "date", "(", "retrieved", "[", "'created_at'", "]", ")", ")", "info", "\"Added issue_event #{owner}/#{repo} -> #{issue_id}/#{issue_event_str}\"", "db", "[", ":issue_events", "]", ".", "first", "(", ":issue_id", "=>", "issue", "[", ":id", "]", ",", ":event_id", "=>", "event_id", ")", "else", "debug", "\"Issue event #{owner}/#{repo} -> #{issue_id}/#{issue_event_str} exists\"", "curevent", "end", "end"], "docstring": "Retrieve and process +event_id+ for an +issue_id+", "docstring_tokens": ["Retrieve", "and", "process", "+", "event_id", "+", "for", "an", "+", "issue_id", "+"], "sha": "3566294a3e4a4c7574bc7376f7e6a9435529b5de", "url": "https://github.com/gousiosg/github-mirror/blob/3566294a3e4a4c7574bc7376f7e6a9435529b5de/lib/ghtorrent/ghtorrent.rb#L1543-L1612", "partition": "test"} {"repo": "gousiosg/github-mirror", "path": "lib/ghtorrent/ghtorrent.rb", "func_name": "GHTorrent.Mirror.ensure_issue_comments", "original_string": "def ensure_issue_comments(owner, repo, issue_id, pull_req_id = nil)\n currepo = ensure_repo(owner, repo)\n\n if currepo.nil?\n warn \"Could not find repository #{owner}/#{repo} for retrieving issue comments for issue #{issue_id}\"\n return\n end\n\n issue = if pull_req_id.nil?\n ensure_issue(owner, repo, issue_id, false, false, false)\n else\n db[:issues].first(:pull_request_id => pull_req_id)\n end\n\n if issue.nil?\n warn \"Could not find issue #{owner}/#{repo} -> #{issue_id} for retrieving issue comments\"\n return\n end\n\n retrieve_issue_comments(owner, repo, issue_id).reduce([]) do |acc, x|\n\n if db[:issue_comments].first(:issue_id => issue[:id],\n :comment_id => x['id']).nil?\n acc << x\n else\n acc\n end\n end.map { |x|\n save{ensure_issue_comment(owner, repo, issue_id, x['id'], pull_req_id)}\n }.select{|x| !x.nil?}\n end", "language": "ruby", "code": "def ensure_issue_comments(owner, repo, issue_id, pull_req_id = nil)\n currepo = ensure_repo(owner, repo)\n\n if currepo.nil?\n warn \"Could not find repository #{owner}/#{repo} for retrieving issue comments for issue #{issue_id}\"\n return\n end\n\n issue = if pull_req_id.nil?\n ensure_issue(owner, repo, issue_id, false, false, false)\n else\n db[:issues].first(:pull_request_id => pull_req_id)\n end\n\n if issue.nil?\n warn \"Could not find issue #{owner}/#{repo} -> #{issue_id} for retrieving issue comments\"\n return\n end\n\n retrieve_issue_comments(owner, repo, issue_id).reduce([]) do |acc, x|\n\n if db[:issue_comments].first(:issue_id => issue[:id],\n :comment_id => x['id']).nil?\n acc << x\n else\n acc\n end\n end.map { |x|\n save{ensure_issue_comment(owner, repo, issue_id, x['id'], pull_req_id)}\n }.select{|x| !x.nil?}\n end", "code_tokens": ["def", "ensure_issue_comments", "(", "owner", ",", "repo", ",", "issue_id", ",", "pull_req_id", "=", "nil", ")", "currepo", "=", "ensure_repo", "(", "owner", ",", "repo", ")", "if", "currepo", ".", "nil?", "warn", "\"Could not find repository #{owner}/#{repo} for retrieving issue comments for issue #{issue_id}\"", "return", "end", "issue", "=", "if", "pull_req_id", ".", "nil?", "ensure_issue", "(", "owner", ",", "repo", ",", "issue_id", ",", "false", ",", "false", ",", "false", ")", "else", "db", "[", ":issues", "]", ".", "first", "(", ":pull_request_id", "=>", "pull_req_id", ")", "end", "if", "issue", ".", "nil?", "warn", "\"Could not find issue #{owner}/#{repo} -> #{issue_id} for retrieving issue comments\"", "return", "end", "retrieve_issue_comments", "(", "owner", ",", "repo", ",", "issue_id", ")", ".", "reduce", "(", "[", "]", ")", "do", "|", "acc", ",", "x", "|", "if", "db", "[", ":issue_comments", "]", ".", "first", "(", ":issue_id", "=>", "issue", "[", ":id", "]", ",", ":comment_id", "=>", "x", "[", "'id'", "]", ")", ".", "nil?", "acc", "<<", "x", "else", "acc", "end", "end", ".", "map", "{", "|", "x", "|", "save", "{", "ensure_issue_comment", "(", "owner", ",", "repo", ",", "issue_id", ",", "x", "[", "'id'", "]", ",", "pull_req_id", ")", "}", "}", ".", "select", "{", "|", "x", "|", "!", "x", ".", "nil?", "}", "end"], "docstring": "Retrieve and process all comments for an issue.\n If pull_req_id is not nil this means that we are only retrieving\n comments for the pull request discussion for projects that don't have\n issues enabled", "docstring_tokens": ["Retrieve", "and", "process", "all", "comments", "for", "an", "issue", ".", "If", "pull_req_id", "is", "not", "nil", "this", "means", "that", "we", "are", "only", "retrieving", "comments", "for", "the", "pull", "request", "discussion", "for", "projects", "that", "don", "t", "have", "issues", "enabled"], "sha": "3566294a3e4a4c7574bc7376f7e6a9435529b5de", "url": "https://github.com/gousiosg/github-mirror/blob/3566294a3e4a4c7574bc7376f7e6a9435529b5de/lib/ghtorrent/ghtorrent.rb#L1619-L1649", "partition": "test"} {"repo": "gousiosg/github-mirror", "path": "lib/ghtorrent/ghtorrent.rb", "func_name": "GHTorrent.Mirror.ensure_issue_comment", "original_string": "def ensure_issue_comment(owner, repo, issue_id, comment_id, pull_req_id = nil)\n issue = if pull_req_id.nil?\n ensure_issue(owner, repo, issue_id, false, false, false)\n else\n db[:issues].first(:pull_request_id => pull_req_id)\n end\n\n if issue.nil?\n warn \"Could not find issue #{owner}/#{repo} -> #{issue_id} for retrieving comment #{comment_id}\"\n return\n end\n\n issue_comment_str = \"#{owner}/#{repo} -> #{issue_id}/#{comment_id}\"\n\n curcomment = db[:issue_comments].first(:issue_id => issue[:id],\n :comment_id => comment_id)\n if curcomment.nil?\n\n retrieved = retrieve_issue_comment(owner, repo, issue_id, comment_id)\n\n if retrieved.nil?\n warn \"Could not retrieve issue_comment #{issue_comment_str}\"\n return\n end\n\n user = ensure_user(retrieved['user']['login'], false, false)\n\n db[:issue_comments].insert(\n :comment_id => comment_id,\n :issue_id => issue[:id],\n :user_id => unless user.nil? then user[:id] end,\n :created_at => date(retrieved['created_at'])\n )\n\n info \"Added issue_comment #{issue_comment_str}\"\n db[:issue_comments].first(:issue_id => issue[:id],\n :comment_id => comment_id)\n else\n debug \"Issue comment #{issue_comment_str} exists\"\n curcomment\n end\n end", "language": "ruby", "code": "def ensure_issue_comment(owner, repo, issue_id, comment_id, pull_req_id = nil)\n issue = if pull_req_id.nil?\n ensure_issue(owner, repo, issue_id, false, false, false)\n else\n db[:issues].first(:pull_request_id => pull_req_id)\n end\n\n if issue.nil?\n warn \"Could not find issue #{owner}/#{repo} -> #{issue_id} for retrieving comment #{comment_id}\"\n return\n end\n\n issue_comment_str = \"#{owner}/#{repo} -> #{issue_id}/#{comment_id}\"\n\n curcomment = db[:issue_comments].first(:issue_id => issue[:id],\n :comment_id => comment_id)\n if curcomment.nil?\n\n retrieved = retrieve_issue_comment(owner, repo, issue_id, comment_id)\n\n if retrieved.nil?\n warn \"Could not retrieve issue_comment #{issue_comment_str}\"\n return\n end\n\n user = ensure_user(retrieved['user']['login'], false, false)\n\n db[:issue_comments].insert(\n :comment_id => comment_id,\n :issue_id => issue[:id],\n :user_id => unless user.nil? then user[:id] end,\n :created_at => date(retrieved['created_at'])\n )\n\n info \"Added issue_comment #{issue_comment_str}\"\n db[:issue_comments].first(:issue_id => issue[:id],\n :comment_id => comment_id)\n else\n debug \"Issue comment #{issue_comment_str} exists\"\n curcomment\n end\n end", "code_tokens": ["def", "ensure_issue_comment", "(", "owner", ",", "repo", ",", "issue_id", ",", "comment_id", ",", "pull_req_id", "=", "nil", ")", "issue", "=", "if", "pull_req_id", ".", "nil?", "ensure_issue", "(", "owner", ",", "repo", ",", "issue_id", ",", "false", ",", "false", ",", "false", ")", "else", "db", "[", ":issues", "]", ".", "first", "(", ":pull_request_id", "=>", "pull_req_id", ")", "end", "if", "issue", ".", "nil?", "warn", "\"Could not find issue #{owner}/#{repo} -> #{issue_id} for retrieving comment #{comment_id}\"", "return", "end", "issue_comment_str", "=", "\"#{owner}/#{repo} -> #{issue_id}/#{comment_id}\"", "curcomment", "=", "db", "[", ":issue_comments", "]", ".", "first", "(", ":issue_id", "=>", "issue", "[", ":id", "]", ",", ":comment_id", "=>", "comment_id", ")", "if", "curcomment", ".", "nil?", "retrieved", "=", "retrieve_issue_comment", "(", "owner", ",", "repo", ",", "issue_id", ",", "comment_id", ")", "if", "retrieved", ".", "nil?", "warn", "\"Could not retrieve issue_comment #{issue_comment_str}\"", "return", "end", "user", "=", "ensure_user", "(", "retrieved", "[", "'user'", "]", "[", "'login'", "]", ",", "false", ",", "false", ")", "db", "[", ":issue_comments", "]", ".", "insert", "(", ":comment_id", "=>", "comment_id", ",", ":issue_id", "=>", "issue", "[", ":id", "]", ",", ":user_id", "=>", "unless", "user", ".", "nil?", "then", "user", "[", ":id", "]", "end", ",", ":created_at", "=>", "date", "(", "retrieved", "[", "'created_at'", "]", ")", ")", "info", "\"Added issue_comment #{issue_comment_str}\"", "db", "[", ":issue_comments", "]", ".", "first", "(", ":issue_id", "=>", "issue", "[", ":id", "]", ",", ":comment_id", "=>", "comment_id", ")", "else", "debug", "\"Issue comment #{issue_comment_str} exists\"", "curcomment", "end", "end"], "docstring": "Retrieve and process +comment_id+ for an +issue_id+", "docstring_tokens": ["Retrieve", "and", "process", "+", "comment_id", "+", "for", "an", "+", "issue_id", "+"], "sha": "3566294a3e4a4c7574bc7376f7e6a9435529b5de", "url": "https://github.com/gousiosg/github-mirror/blob/3566294a3e4a4c7574bc7376f7e6a9435529b5de/lib/ghtorrent/ghtorrent.rb#L1653-L1694", "partition": "test"} {"repo": "gousiosg/github-mirror", "path": "lib/ghtorrent/ghtorrent.rb", "func_name": "GHTorrent.Mirror.ensure_labels", "original_string": "def ensure_labels(owner, repo)\n currepo = ensure_repo(owner, repo)\n\n if currepo.nil?\n warn \"Could not find #{owner}/#{repo} for retrieving issue labels\"\n return\n end\n\n repo_labels = db[:repo_labels].filter(:repo_id => currepo[:id]).all\n\n retrieve_repo_labels(owner, repo).reduce([]) do |acc, x|\n if repo_labels.find {|y| y[:name] == x['name']}.nil?\n acc << x\n else\n acc\n end\n end.map { |x| save { ensure_repo_label(owner, repo, x['name']) } }.select { |x| !x.nil? }\n end", "language": "ruby", "code": "def ensure_labels(owner, repo)\n currepo = ensure_repo(owner, repo)\n\n if currepo.nil?\n warn \"Could not find #{owner}/#{repo} for retrieving issue labels\"\n return\n end\n\n repo_labels = db[:repo_labels].filter(:repo_id => currepo[:id]).all\n\n retrieve_repo_labels(owner, repo).reduce([]) do |acc, x|\n if repo_labels.find {|y| y[:name] == x['name']}.nil?\n acc << x\n else\n acc\n end\n end.map { |x| save { ensure_repo_label(owner, repo, x['name']) } }.select { |x| !x.nil? }\n end", "code_tokens": ["def", "ensure_labels", "(", "owner", ",", "repo", ")", "currepo", "=", "ensure_repo", "(", "owner", ",", "repo", ")", "if", "currepo", ".", "nil?", "warn", "\"Could not find #{owner}/#{repo} for retrieving issue labels\"", "return", "end", "repo_labels", "=", "db", "[", ":repo_labels", "]", ".", "filter", "(", ":repo_id", "=>", "currepo", "[", ":id", "]", ")", ".", "all", "retrieve_repo_labels", "(", "owner", ",", "repo", ")", ".", "reduce", "(", "[", "]", ")", "do", "|", "acc", ",", "x", "|", "if", "repo_labels", ".", "find", "{", "|", "y", "|", "y", "[", ":name", "]", "==", "x", "[", "'name'", "]", "}", ".", "nil?", "acc", "<<", "x", "else", "acc", "end", "end", ".", "map", "{", "|", "x", "|", "save", "{", "ensure_repo_label", "(", "owner", ",", "repo", ",", "x", "[", "'name'", "]", ")", "}", "}", ".", "select", "{", "|", "x", "|", "!", "x", ".", "nil?", "}", "end"], "docstring": "Retrieve repository issue labels", "docstring_tokens": ["Retrieve", "repository", "issue", "labels"], "sha": "3566294a3e4a4c7574bc7376f7e6a9435529b5de", "url": "https://github.com/gousiosg/github-mirror/blob/3566294a3e4a4c7574bc7376f7e6a9435529b5de/lib/ghtorrent/ghtorrent.rb#L1698-L1715", "partition": "test"} {"repo": "gousiosg/github-mirror", "path": "lib/ghtorrent/ghtorrent.rb", "func_name": "GHTorrent.Mirror.ensure_repo_label", "original_string": "def ensure_repo_label(owner, repo, name)\n currepo = ensure_repo(owner, repo)\n\n if currepo.nil?\n warn \"Could not find #{owner}/#{repo} for retrieving label #{name}\"\n return\n end\n\n label = db[:repo_labels].first(:repo_id => currepo[:id], :name => name)\n\n if label.nil?\n retrieved = retrieve_repo_label(owner, repo, name)\n\n if retrieved.nil?\n warn \"Could not retrieve repo_label #{owner}/#{repo} -> #{name}\"\n return\n end\n\n db[:repo_labels].insert(\n :repo_id => currepo[:id],\n :name => name\n )\n\n info \"Added repo_label #{owner}/#{repo} -> #{name}\"\n db[:repo_labels].first(:repo_id => currepo[:id], :name => name)\n else\n label\n end\n end", "language": "ruby", "code": "def ensure_repo_label(owner, repo, name)\n currepo = ensure_repo(owner, repo)\n\n if currepo.nil?\n warn \"Could not find #{owner}/#{repo} for retrieving label #{name}\"\n return\n end\n\n label = db[:repo_labels].first(:repo_id => currepo[:id], :name => name)\n\n if label.nil?\n retrieved = retrieve_repo_label(owner, repo, name)\n\n if retrieved.nil?\n warn \"Could not retrieve repo_label #{owner}/#{repo} -> #{name}\"\n return\n end\n\n db[:repo_labels].insert(\n :repo_id => currepo[:id],\n :name => name\n )\n\n info \"Added repo_label #{owner}/#{repo} -> #{name}\"\n db[:repo_labels].first(:repo_id => currepo[:id], :name => name)\n else\n label\n end\n end", "code_tokens": ["def", "ensure_repo_label", "(", "owner", ",", "repo", ",", "name", ")", "currepo", "=", "ensure_repo", "(", "owner", ",", "repo", ")", "if", "currepo", ".", "nil?", "warn", "\"Could not find #{owner}/#{repo} for retrieving label #{name}\"", "return", "end", "label", "=", "db", "[", ":repo_labels", "]", ".", "first", "(", ":repo_id", "=>", "currepo", "[", ":id", "]", ",", ":name", "=>", "name", ")", "if", "label", ".", "nil?", "retrieved", "=", "retrieve_repo_label", "(", "owner", ",", "repo", ",", "name", ")", "if", "retrieved", ".", "nil?", "warn", "\"Could not retrieve repo_label #{owner}/#{repo} -> #{name}\"", "return", "end", "db", "[", ":repo_labels", "]", ".", "insert", "(", ":repo_id", "=>", "currepo", "[", ":id", "]", ",", ":name", "=>", "name", ")", "info", "\"Added repo_label #{owner}/#{repo} -> #{name}\"", "db", "[", ":repo_labels", "]", ".", "first", "(", ":repo_id", "=>", "currepo", "[", ":id", "]", ",", ":name", "=>", "name", ")", "else", "label", "end", "end"], "docstring": "Retrieve a single repository issue label by name", "docstring_tokens": ["Retrieve", "a", "single", "repository", "issue", "label", "by", "name"], "sha": "3566294a3e4a4c7574bc7376f7e6a9435529b5de", "url": "https://github.com/gousiosg/github-mirror/blob/3566294a3e4a4c7574bc7376f7e6a9435529b5de/lib/ghtorrent/ghtorrent.rb#L1719-L1747", "partition": "test"} {"repo": "gousiosg/github-mirror", "path": "lib/ghtorrent/ghtorrent.rb", "func_name": "GHTorrent.Mirror.ensure_issue_labels", "original_string": "def ensure_issue_labels(owner, repo, issue_id)\n\n issue = ensure_issue(owner, repo, issue_id, false, false, false)\n\n if issue.nil?\n warn \"Could not find issue #{owner}/#{repo} -> #{issue_id} for retrieving labels\"\n return\n end\n\n issue_labels = db.from(:issue_labels, :repo_labels)\\\n .where(Sequel.qualify('issue_labels', 'label_id') => Sequel.qualify('repo_labels', 'id'))\\\n .where(Sequel.qualify('issue_labels', 'issue_id') => issue[:id])\\\n .select(Sequel.qualify('repo_labels', 'name')).all\n\n retrieve_issue_labels(owner, repo, issue_id).reduce([]) do |acc, x|\n if issue_labels.find {|y| y[:name] == x['name']}.nil?\n acc << x\n else\n acc\n end\n end.map { |x| save{ensure_issue_label(owner, repo, issue[:issue_id], x['name']) }}.select{|x| !x.nil?}\n\n end", "language": "ruby", "code": "def ensure_issue_labels(owner, repo, issue_id)\n\n issue = ensure_issue(owner, repo, issue_id, false, false, false)\n\n if issue.nil?\n warn \"Could not find issue #{owner}/#{repo} -> #{issue_id} for retrieving labels\"\n return\n end\n\n issue_labels = db.from(:issue_labels, :repo_labels)\\\n .where(Sequel.qualify('issue_labels', 'label_id') => Sequel.qualify('repo_labels', 'id'))\\\n .where(Sequel.qualify('issue_labels', 'issue_id') => issue[:id])\\\n .select(Sequel.qualify('repo_labels', 'name')).all\n\n retrieve_issue_labels(owner, repo, issue_id).reduce([]) do |acc, x|\n if issue_labels.find {|y| y[:name] == x['name']}.nil?\n acc << x\n else\n acc\n end\n end.map { |x| save{ensure_issue_label(owner, repo, issue[:issue_id], x['name']) }}.select{|x| !x.nil?}\n\n end", "code_tokens": ["def", "ensure_issue_labels", "(", "owner", ",", "repo", ",", "issue_id", ")", "issue", "=", "ensure_issue", "(", "owner", ",", "repo", ",", "issue_id", ",", "false", ",", "false", ",", "false", ")", "if", "issue", ".", "nil?", "warn", "\"Could not find issue #{owner}/#{repo} -> #{issue_id} for retrieving labels\"", "return", "end", "issue_labels", "=", "db", ".", "from", "(", ":issue_labels", ",", ":repo_labels", ")", ".", "where", "(", "Sequel", ".", "qualify", "(", "'issue_labels'", ",", "'label_id'", ")", "=>", "Sequel", ".", "qualify", "(", "'repo_labels'", ",", "'id'", ")", ")", ".", "where", "(", "Sequel", ".", "qualify", "(", "'issue_labels'", ",", "'issue_id'", ")", "=>", "issue", "[", ":id", "]", ")", ".", "select", "(", "Sequel", ".", "qualify", "(", "'repo_labels'", ",", "'name'", ")", ")", ".", "all", "retrieve_issue_labels", "(", "owner", ",", "repo", ",", "issue_id", ")", ".", "reduce", "(", "[", "]", ")", "do", "|", "acc", ",", "x", "|", "if", "issue_labels", ".", "find", "{", "|", "y", "|", "y", "[", ":name", "]", "==", "x", "[", "'name'", "]", "}", ".", "nil?", "acc", "<<", "x", "else", "acc", "end", "end", ".", "map", "{", "|", "x", "|", "save", "{", "ensure_issue_label", "(", "owner", ",", "repo", ",", "issue", "[", ":issue_id", "]", ",", "x", "[", "'name'", "]", ")", "}", "}", ".", "select", "{", "|", "x", "|", "!", "x", ".", "nil?", "}", "end"], "docstring": "Ensure that all labels have been assigned to the issue", "docstring_tokens": ["Ensure", "that", "all", "labels", "have", "been", "assigned", "to", "the", "issue"], "sha": "3566294a3e4a4c7574bc7376f7e6a9435529b5de", "url": "https://github.com/gousiosg/github-mirror/blob/3566294a3e4a4c7574bc7376f7e6a9435529b5de/lib/ghtorrent/ghtorrent.rb#L1751-L1773", "partition": "test"} {"repo": "gousiosg/github-mirror", "path": "lib/ghtorrent/ghtorrent.rb", "func_name": "GHTorrent.Mirror.ensure_issue_label", "original_string": "def ensure_issue_label(owner, repo, issue_id, name)\n\n issue = ensure_issue(owner, repo, issue_id, false, false, false)\n\n if issue.nil?\n warn \"Could not find issue #{owner}/#{repo} -> #{issue_id} to assign label #{name}\"\n return\n end\n\n label = ensure_repo_label(owner, repo, name)\n\n if label.nil?\n warn \"Could not find repo label #{owner}/#{repo} -> #{name}\"\n return\n end\n\n issue_lbl = db[:issue_labels].first(:label_id => label[:id],\n :issue_id => issue[:id])\n\n if issue_lbl.nil?\n\n db[:issue_labels].insert(\n :label_id => label[:id],\n :issue_id => issue[:id],\n )\n info \"Added issue_label #{name} to issue #{owner}/#{repo} -> #{issue_id}\"\n db[:issue_labels].first(:label_id => label[:id],\n :issue_id => issue[:id])\n else\n debug \"Issue label #{name} to issue #{owner}/#{repo} -> #{issue_id} exists\"\n issue_lbl\n end\n\n end", "language": "ruby", "code": "def ensure_issue_label(owner, repo, issue_id, name)\n\n issue = ensure_issue(owner, repo, issue_id, false, false, false)\n\n if issue.nil?\n warn \"Could not find issue #{owner}/#{repo} -> #{issue_id} to assign label #{name}\"\n return\n end\n\n label = ensure_repo_label(owner, repo, name)\n\n if label.nil?\n warn \"Could not find repo label #{owner}/#{repo} -> #{name}\"\n return\n end\n\n issue_lbl = db[:issue_labels].first(:label_id => label[:id],\n :issue_id => issue[:id])\n\n if issue_lbl.nil?\n\n db[:issue_labels].insert(\n :label_id => label[:id],\n :issue_id => issue[:id],\n )\n info \"Added issue_label #{name} to issue #{owner}/#{repo} -> #{issue_id}\"\n db[:issue_labels].first(:label_id => label[:id],\n :issue_id => issue[:id])\n else\n debug \"Issue label #{name} to issue #{owner}/#{repo} -> #{issue_id} exists\"\n issue_lbl\n end\n\n end", "code_tokens": ["def", "ensure_issue_label", "(", "owner", ",", "repo", ",", "issue_id", ",", "name", ")", "issue", "=", "ensure_issue", "(", "owner", ",", "repo", ",", "issue_id", ",", "false", ",", "false", ",", "false", ")", "if", "issue", ".", "nil?", "warn", "\"Could not find issue #{owner}/#{repo} -> #{issue_id} to assign label #{name}\"", "return", "end", "label", "=", "ensure_repo_label", "(", "owner", ",", "repo", ",", "name", ")", "if", "label", ".", "nil?", "warn", "\"Could not find repo label #{owner}/#{repo} -> #{name}\"", "return", "end", "issue_lbl", "=", "db", "[", ":issue_labels", "]", ".", "first", "(", ":label_id", "=>", "label", "[", ":id", "]", ",", ":issue_id", "=>", "issue", "[", ":id", "]", ")", "if", "issue_lbl", ".", "nil?", "db", "[", ":issue_labels", "]", ".", "insert", "(", ":label_id", "=>", "label", "[", ":id", "]", ",", ":issue_id", "=>", "issue", "[", ":id", "]", ",", ")", "info", "\"Added issue_label #{name} to issue #{owner}/#{repo} -> #{issue_id}\"", "db", "[", ":issue_labels", "]", ".", "first", "(", ":label_id", "=>", "label", "[", ":id", "]", ",", ":issue_id", "=>", "issue", "[", ":id", "]", ")", "else", "debug", "\"Issue label #{name} to issue #{owner}/#{repo} -> #{issue_id} exists\"", "issue_lbl", "end", "end"], "docstring": "Ensure that a specific label has been assigned to the issue", "docstring_tokens": ["Ensure", "that", "a", "specific", "label", "has", "been", "assigned", "to", "the", "issue"], "sha": "3566294a3e4a4c7574bc7376f7e6a9435529b5de", "url": "https://github.com/gousiosg/github-mirror/blob/3566294a3e4a4c7574bc7376f7e6a9435529b5de/lib/ghtorrent/ghtorrent.rb#L1777-L1810", "partition": "test"} {"repo": "gousiosg/github-mirror", "path": "lib/ghtorrent/ghtorrent.rb", "func_name": "GHTorrent.Mirror.transaction", "original_string": "def transaction(&block)\n db\n persister\n\n result = nil\n start_time = Time.now\n begin\n db.transaction(:rollback => :reraise, :isolation => :repeatable,\n :retry_on => @retry_on_error, :num_retries => 3) do\n result = yield block\n end\n total = Time.now.to_ms - start_time.to_ms\n debug \"Transaction committed (#{total} ms)\"\n result\n rescue StandardError => e\n total = Time.now.to_ms - start_time.to_ms\n warn \"Transaction failed (#{total} ms)\"\n raise e\n ensure\n GC.start\n end\n end", "language": "ruby", "code": "def transaction(&block)\n db\n persister\n\n result = nil\n start_time = Time.now\n begin\n db.transaction(:rollback => :reraise, :isolation => :repeatable,\n :retry_on => @retry_on_error, :num_retries => 3) do\n result = yield block\n end\n total = Time.now.to_ms - start_time.to_ms\n debug \"Transaction committed (#{total} ms)\"\n result\n rescue StandardError => e\n total = Time.now.to_ms - start_time.to_ms\n warn \"Transaction failed (#{total} ms)\"\n raise e\n ensure\n GC.start\n end\n end", "code_tokens": ["def", "transaction", "(", "&", "block", ")", "db", "persister", "result", "=", "nil", "start_time", "=", "Time", ".", "now", "begin", "db", ".", "transaction", "(", ":rollback", "=>", ":reraise", ",", ":isolation", "=>", ":repeatable", ",", ":retry_on", "=>", "@retry_on_error", ",", ":num_retries", "=>", "3", ")", "do", "result", "=", "yield", "block", "end", "total", "=", "Time", ".", "now", ".", "to_ms", "-", "start_time", ".", "to_ms", "debug", "\"Transaction committed (#{total} ms)\"", "result", "rescue", "StandardError", "=>", "e", "total", "=", "Time", ".", "now", ".", "to_ms", "-", "start_time", ".", "to_ms", "warn", "\"Transaction failed (#{total} ms)\"", "raise", "e", "ensure", "GC", ".", "start", "end", "end"], "docstring": "Run a block in a DB transaction. Exceptions trigger transaction rollback\n and are rethrown.", "docstring_tokens": ["Run", "a", "block", "in", "a", "DB", "transaction", ".", "Exceptions", "trigger", "transaction", "rollback", "and", "are", "rethrown", "."], "sha": "3566294a3e4a4c7574bc7376f7e6a9435529b5de", "url": "https://github.com/gousiosg/github-mirror/blob/3566294a3e4a4c7574bc7376f7e6a9435529b5de/lib/ghtorrent/ghtorrent.rb#L1847-L1868", "partition": "test"} {"repo": "gousiosg/github-mirror", "path": "lib/ghtorrent/ghtorrent.rb", "func_name": "GHTorrent.Mirror.store_commit", "original_string": "def store_commit(c, repo, user)\n commits = db[:commits]\n commit = commits.first(:sha => c['sha'])\n\n if commit.nil?\n author = commit_user(c['author'], c['commit']['author'])\n commiter = commit_user(c['committer'], c['commit']['committer'])\n\n repository = ensure_repo(user, repo)\n\n if repository.nil?\n warn \"Could not find repo #{user}/#{repo} for storing commit #{c['sha']}\"\n end\n\n commits.insert(:sha => c['sha'],\n :author_id => author[:id],\n :committer_id => commiter[:id],\n :project_id => if repository.nil? then nil else repository[:id] end ,\n :created_at => date(c['commit']['author']['date'])\n )\n info \"Added commit #{user}/#{repo} -> #{c['sha']} \"\n commits.first(:sha => c['sha'])\n else\n debug \"Commit #{user}/#{repo} -> #{c['sha']} exists\"\n commit\n end\n end", "language": "ruby", "code": "def store_commit(c, repo, user)\n commits = db[:commits]\n commit = commits.first(:sha => c['sha'])\n\n if commit.nil?\n author = commit_user(c['author'], c['commit']['author'])\n commiter = commit_user(c['committer'], c['commit']['committer'])\n\n repository = ensure_repo(user, repo)\n\n if repository.nil?\n warn \"Could not find repo #{user}/#{repo} for storing commit #{c['sha']}\"\n end\n\n commits.insert(:sha => c['sha'],\n :author_id => author[:id],\n :committer_id => commiter[:id],\n :project_id => if repository.nil? then nil else repository[:id] end ,\n :created_at => date(c['commit']['author']['date'])\n )\n info \"Added commit #{user}/#{repo} -> #{c['sha']} \"\n commits.first(:sha => c['sha'])\n else\n debug \"Commit #{user}/#{repo} -> #{c['sha']} exists\"\n commit\n end\n end", "code_tokens": ["def", "store_commit", "(", "c", ",", "repo", ",", "user", ")", "commits", "=", "db", "[", ":commits", "]", "commit", "=", "commits", ".", "first", "(", ":sha", "=>", "c", "[", "'sha'", "]", ")", "if", "commit", ".", "nil?", "author", "=", "commit_user", "(", "c", "[", "'author'", "]", ",", "c", "[", "'commit'", "]", "[", "'author'", "]", ")", "commiter", "=", "commit_user", "(", "c", "[", "'committer'", "]", ",", "c", "[", "'commit'", "]", "[", "'committer'", "]", ")", "repository", "=", "ensure_repo", "(", "user", ",", "repo", ")", "if", "repository", ".", "nil?", "warn", "\"Could not find repo #{user}/#{repo} for storing commit #{c['sha']}\"", "end", "commits", ".", "insert", "(", ":sha", "=>", "c", "[", "'sha'", "]", ",", ":author_id", "=>", "author", "[", ":id", "]", ",", ":committer_id", "=>", "commiter", "[", ":id", "]", ",", ":project_id", "=>", "if", "repository", ".", "nil?", "then", "nil", "else", "repository", "[", ":id", "]", "end", ",", ":created_at", "=>", "date", "(", "c", "[", "'commit'", "]", "[", "'author'", "]", "[", "'date'", "]", ")", ")", "info", "\"Added commit #{user}/#{repo} -> #{c['sha']} \"", "commits", ".", "first", "(", ":sha", "=>", "c", "[", "'sha'", "]", ")", "else", "debug", "\"Commit #{user}/#{repo} -> #{c['sha']} exists\"", "commit", "end", "end"], "docstring": "Store a commit contained in a hash. First check whether the commit exists.", "docstring_tokens": ["Store", "a", "commit", "contained", "in", "a", "hash", ".", "First", "check", "whether", "the", "commit", "exists", "."], "sha": "3566294a3e4a4c7574bc7376f7e6a9435529b5de", "url": "https://github.com/gousiosg/github-mirror/blob/3566294a3e4a4c7574bc7376f7e6a9435529b5de/lib/ghtorrent/ghtorrent.rb#L1885-L1911", "partition": "test"} {"repo": "gousiosg/github-mirror", "path": "lib/ghtorrent/logging.rb", "func_name": "GHTorrent.Logging.log", "original_string": "def log(level, msg)\n\n case level\n when :fatal then\n loggerr.fatal (retrieve_caller + msg)\n when :error then\n loggerr.error (retrieve_caller + msg)\n when :warn then\n loggerr.warn (retrieve_caller + msg)\n when :info then\n loggerr.info (retrieve_caller + msg)\n when :debug then\n loggerr.debug (retrieve_caller + msg)\n else\n loggerr.debug (retrieve_caller + msg)\n end\n end", "language": "ruby", "code": "def log(level, msg)\n\n case level\n when :fatal then\n loggerr.fatal (retrieve_caller + msg)\n when :error then\n loggerr.error (retrieve_caller + msg)\n when :warn then\n loggerr.warn (retrieve_caller + msg)\n when :info then\n loggerr.info (retrieve_caller + msg)\n when :debug then\n loggerr.debug (retrieve_caller + msg)\n else\n loggerr.debug (retrieve_caller + msg)\n end\n end", "code_tokens": ["def", "log", "(", "level", ",", "msg", ")", "case", "level", "when", ":fatal", "then", "loggerr", ".", "fatal", "(", "retrieve_caller", "+", "msg", ")", "when", ":error", "then", "loggerr", ".", "error", "(", "retrieve_caller", "+", "msg", ")", "when", ":warn", "then", "loggerr", ".", "warn", "(", "retrieve_caller", "+", "msg", ")", "when", ":info", "then", "loggerr", ".", "info", "(", "retrieve_caller", "+", "msg", ")", "when", ":debug", "then", "loggerr", ".", "debug", "(", "retrieve_caller", "+", "msg", ")", "else", "loggerr", ".", "debug", "(", "retrieve_caller", "+", "msg", ")", "end", "end"], "docstring": "Log a message at the given level.", "docstring_tokens": ["Log", "a", "message", "at", "the", "given", "level", "."], "sha": "3566294a3e4a4c7574bc7376f7e6a9435529b5de", "url": "https://github.com/gousiosg/github-mirror/blob/3566294a3e4a4c7574bc7376f7e6a9435529b5de/lib/ghtorrent/logging.rb#L82-L98", "partition": "test"} {"repo": "gousiosg/github-mirror", "path": "lib/ghtorrent/api_client.rb", "func_name": "GHTorrent.APIClient.paged_api_request", "original_string": "def paged_api_request(url, pages = config(:mirror_history_pages_back),\n last = nil)\n\n url = ensure_max_per_page(url)\n data = api_request_raw(url)\n\n return [] if data.nil?\n\n unless data.meta['link'].nil?\n links = parse_links(data.meta['link'])\n last = links['last'] if last.nil?\n\n if pages > 0\n pages = pages - 1\n if pages == 0\n return parse_request_result(data)\n end\n end\n\n if links['next'].nil?\n parse_request_result(data)\n else\n parse_request_result(data) | paged_api_request(links['next'], pages, last)\n end\n else\n parse_request_result(data)\n end\n end", "language": "ruby", "code": "def paged_api_request(url, pages = config(:mirror_history_pages_back),\n last = nil)\n\n url = ensure_max_per_page(url)\n data = api_request_raw(url)\n\n return [] if data.nil?\n\n unless data.meta['link'].nil?\n links = parse_links(data.meta['link'])\n last = links['last'] if last.nil?\n\n if pages > 0\n pages = pages - 1\n if pages == 0\n return parse_request_result(data)\n end\n end\n\n if links['next'].nil?\n parse_request_result(data)\n else\n parse_request_result(data) | paged_api_request(links['next'], pages, last)\n end\n else\n parse_request_result(data)\n end\n end", "code_tokens": ["def", "paged_api_request", "(", "url", ",", "pages", "=", "config", "(", ":mirror_history_pages_back", ")", ",", "last", "=", "nil", ")", "url", "=", "ensure_max_per_page", "(", "url", ")", "data", "=", "api_request_raw", "(", "url", ")", "return", "[", "]", "if", "data", ".", "nil?", "unless", "data", ".", "meta", "[", "'link'", "]", ".", "nil?", "links", "=", "parse_links", "(", "data", ".", "meta", "[", "'link'", "]", ")", "last", "=", "links", "[", "'last'", "]", "if", "last", ".", "nil?", "if", "pages", ">", "0", "pages", "=", "pages", "-", "1", "if", "pages", "==", "0", "return", "parse_request_result", "(", "data", ")", "end", "end", "if", "links", "[", "'next'", "]", ".", "nil?", "parse_request_result", "(", "data", ")", "else", "parse_request_result", "(", "data", ")", "|", "paged_api_request", "(", "links", "[", "'next'", "]", ",", "pages", ",", "last", ")", "end", "else", "parse_request_result", "(", "data", ")", "end", "end"], "docstring": "A paged request. Used when the result can expand to more than one\n result pages.", "docstring_tokens": ["A", "paged", "request", ".", "Used", "when", "the", "result", "can", "expand", "to", "more", "than", "one", "result", "pages", "."], "sha": "3566294a3e4a4c7574bc7376f7e6a9435529b5de", "url": "https://github.com/gousiosg/github-mirror/blob/3566294a3e4a4c7574bc7376f7e6a9435529b5de/lib/ghtorrent/api_client.rb#L20-L47", "partition": "test"} {"repo": "gousiosg/github-mirror", "path": "lib/ghtorrent/api_client.rb", "func_name": "GHTorrent.APIClient.last_updated", "original_string": "def last_updated(url, etag)\n begin\n ts = Time.now\n response = do_request(url, '', etag)\n info \"Successful etag request. URL: #{url}, Etag: #{etag}, Remaining: #{@remaining}, Total: #{Time.now.to_ms - ts.to_ms} ms\"\n rescue OpenURI::HTTPError => e\n response = e.io\n if response.status.first != '304'\n etag_request_error_message(url, e, etag)\n raise e\n end\n end\n\n return Time.parse(response.meta['last-modified']) unless response.meta['last-modified'].nil?\n return Time.at(86400)\n end", "language": "ruby", "code": "def last_updated(url, etag)\n begin\n ts = Time.now\n response = do_request(url, '', etag)\n info \"Successful etag request. URL: #{url}, Etag: #{etag}, Remaining: #{@remaining}, Total: #{Time.now.to_ms - ts.to_ms} ms\"\n rescue OpenURI::HTTPError => e\n response = e.io\n if response.status.first != '304'\n etag_request_error_message(url, e, etag)\n raise e\n end\n end\n\n return Time.parse(response.meta['last-modified']) unless response.meta['last-modified'].nil?\n return Time.at(86400)\n end", "code_tokens": ["def", "last_updated", "(", "url", ",", "etag", ")", "begin", "ts", "=", "Time", ".", "now", "response", "=", "do_request", "(", "url", ",", "''", ",", "etag", ")", "info", "\"Successful etag request. URL: #{url}, Etag: #{etag}, Remaining: #{@remaining}, Total: #{Time.now.to_ms - ts.to_ms} ms\"", "rescue", "OpenURI", "::", "HTTPError", "=>", "e", "response", "=", "e", ".", "io", "if", "response", ".", "status", ".", "first", "!=", "'304'", "etag_request_error_message", "(", "url", ",", "e", ",", "etag", ")", "raise", "e", "end", "end", "return", "Time", ".", "parse", "(", "response", ".", "meta", "[", "'last-modified'", "]", ")", "unless", "response", ".", "meta", "[", "'last-modified'", "]", ".", "nil?", "return", "Time", ".", "at", "(", "86400", ")", "end"], "docstring": "Check whether the resource identified by the provided url has changed", "docstring_tokens": ["Check", "whether", "the", "resource", "identified", "by", "the", "provided", "url", "has", "changed"], "sha": "3566294a3e4a4c7574bc7376f7e6a9435529b5de", "url": "https://github.com/gousiosg/github-mirror/blob/3566294a3e4a4c7574bc7376f7e6a9435529b5de/lib/ghtorrent/api_client.rb#L57-L72", "partition": "test"} {"repo": "gousiosg/github-mirror", "path": "lib/ghtorrent/api_client.rb", "func_name": "GHTorrent.APIClient.num_pages", "original_string": "def num_pages(url)\n url = ensure_max_per_page(url)\n data = api_request_raw(url)\n\n if data.nil? or data.meta.nil? or data.meta['link'].nil?\n return 1\n end\n\n links = parse_links(data.meta['link'])\n\n if links.nil? or links['last'].nil?\n return 1\n end\n\n params = CGI::parse(URI::parse(links['last']).query)\n params['page'][0].to_i\n end", "language": "ruby", "code": "def num_pages(url)\n url = ensure_max_per_page(url)\n data = api_request_raw(url)\n\n if data.nil? or data.meta.nil? or data.meta['link'].nil?\n return 1\n end\n\n links = parse_links(data.meta['link'])\n\n if links.nil? or links['last'].nil?\n return 1\n end\n\n params = CGI::parse(URI::parse(links['last']).query)\n params['page'][0].to_i\n end", "code_tokens": ["def", "num_pages", "(", "url", ")", "url", "=", "ensure_max_per_page", "(", "url", ")", "data", "=", "api_request_raw", "(", "url", ")", "if", "data", ".", "nil?", "or", "data", ".", "meta", ".", "nil?", "or", "data", ".", "meta", "[", "'link'", "]", ".", "nil?", "return", "1", "end", "links", "=", "parse_links", "(", "data", ".", "meta", "[", "'link'", "]", ")", "if", "links", ".", "nil?", "or", "links", "[", "'last'", "]", ".", "nil?", "return", "1", "end", "params", "=", "CGI", "::", "parse", "(", "URI", "::", "parse", "(", "links", "[", "'last'", "]", ")", ".", "query", ")", "params", "[", "'page'", "]", "[", "0", "]", ".", "to_i", "end"], "docstring": "Determine the number of pages contained in a multi-page API response", "docstring_tokens": ["Determine", "the", "number", "of", "pages", "contained", "in", "a", "multi", "-", "page", "API", "response"], "sha": "3566294a3e4a4c7574bc7376f7e6a9435529b5de", "url": "https://github.com/gousiosg/github-mirror/blob/3566294a3e4a4c7574bc7376f7e6a9435529b5de/lib/ghtorrent/api_client.rb#L75-L91", "partition": "test"} {"repo": "gousiosg/github-mirror", "path": "lib/ghtorrent/api_client.rb", "func_name": "GHTorrent.APIClient.parse_links", "original_string": "def parse_links(links)\n links.split(/,/).reduce({}) do |acc, x|\n matches = x.strip.match(/<(.*)>; rel=\\\"(.*)\\\"/)\n acc[matches[2]] = matches[1]\n acc\n end\n end", "language": "ruby", "code": "def parse_links(links)\n links.split(/,/).reduce({}) do |acc, x|\n matches = x.strip.match(/<(.*)>; rel=\\\"(.*)\\\"/)\n acc[matches[2]] = matches[1]\n acc\n end\n end", "code_tokens": ["def", "parse_links", "(", "links", ")", "links", ".", "split", "(", "/", "/", ")", ".", "reduce", "(", "{", "}", ")", "do", "|", "acc", ",", "x", "|", "matches", "=", "x", ".", "strip", ".", "match", "(", "/", "\\\"", "\\\"", "/", ")", "acc", "[", "matches", "[", "2", "]", "]", "=", "matches", "[", "1", "]", "acc", "end", "end"], "docstring": "Parse a Github link header", "docstring_tokens": ["Parse", "a", "Github", "link", "header"], "sha": "3566294a3e4a4c7574bc7376f7e6a9435529b5de", "url": "https://github.com/gousiosg/github-mirror/blob/3566294a3e4a4c7574bc7376f7e6a9435529b5de/lib/ghtorrent/api_client.rb#L112-L118", "partition": "test"} {"repo": "gousiosg/github-mirror", "path": "lib/ghtorrent/api_client.rb", "func_name": "GHTorrent.APIClient.parse_request_result", "original_string": "def parse_request_result(result)\n if result.nil?\n []\n else\n json = result.read\n\n if json.nil?\n []\n else\n r = JSON.parse(json)\n\n # Add the etag to the response only for individual entities\n if result.meta['etag'] and r.class != Array\n r['etag'] = result.meta['etag']\n end\n\n r\n end\n end\n end", "language": "ruby", "code": "def parse_request_result(result)\n if result.nil?\n []\n else\n json = result.read\n\n if json.nil?\n []\n else\n r = JSON.parse(json)\n\n # Add the etag to the response only for individual entities\n if result.meta['etag'] and r.class != Array\n r['etag'] = result.meta['etag']\n end\n\n r\n end\n end\n end", "code_tokens": ["def", "parse_request_result", "(", "result", ")", "if", "result", ".", "nil?", "[", "]", "else", "json", "=", "result", ".", "read", "if", "json", ".", "nil?", "[", "]", "else", "r", "=", "JSON", ".", "parse", "(", "json", ")", "# Add the etag to the response only for individual entities", "if", "result", ".", "meta", "[", "'etag'", "]", "and", "r", ".", "class", "!=", "Array", "r", "[", "'etag'", "]", "=", "result", ".", "meta", "[", "'etag'", "]", "end", "r", "end", "end", "end"], "docstring": "Parse the JSON result array", "docstring_tokens": ["Parse", "the", "JSON", "result", "array"], "sha": "3566294a3e4a4c7574bc7376f7e6a9435529b5de", "url": "https://github.com/gousiosg/github-mirror/blob/3566294a3e4a4c7574bc7376f7e6a9435529b5de/lib/ghtorrent/api_client.rb#L121-L140", "partition": "test"} {"repo": "gousiosg/github-mirror", "path": "lib/ghtorrent/api_client.rb", "func_name": "GHTorrent.APIClient.api_request_raw", "original_string": "def api_request_raw(url, media_type = '')\n\n begin\n start_time = Time.now\n\n contents = do_request(url, media_type)\n total = Time.now.to_ms - start_time.to_ms\n info \"Successful request. URL: #{url}, Remaining: #{@remaining}, Total: #{total} ms\"\n\n contents\n rescue OpenURI::HTTPError => e\n @remaining = e.io.meta['x-ratelimit-remaining'].to_i\n @reset = e.io.meta['x-ratelimit-reset'].to_i\n\n case e.io.status[0].to_i\n # The following indicate valid Github return codes\n when 400, # Bad request\n 403, # Forbidden\n 404, # Not found\n 409, # Conflict -- returned on gets of empty repos\n 422 then # Unprocessable entity\n warn request_error_msg(url, e)\n return nil\n when 401 # Unauthorized\n warn request_error_msg(url, e)\n warn \"Unauthorised request with token: #{@token}\"\n raise e\n when 451 # DMCA takedown\n warn request_error_msg(url, e)\n warn \"Repo was taken down (DMCA)\"\n return nil\n else # Server error or HTTP conditions that Github does not report\n warn request_error_msg(url, e)\n raise e\n end\n rescue StandardError => e\n warn error_msg(url, e)\n raise e\n ensure\n # The exact limit is only enforced upon the first @reset\n # No idea how many requests are available on this key. Sleep if we have run out\n if @remaining < @req_limit\n to_sleep = @reset - Time.now.to_i + 2\n warn \"Request limit reached, reset in: #{to_sleep} secs\"\n t = Thread.new do\n slept = 0\n while true do\n debug \"Sleeping for #{to_sleep - slept} seconds\"\n sleep 1\n slept += 1\n end\n end\n sleep([0, to_sleep].max)\n t.exit\n end\n end\n end", "language": "ruby", "code": "def api_request_raw(url, media_type = '')\n\n begin\n start_time = Time.now\n\n contents = do_request(url, media_type)\n total = Time.now.to_ms - start_time.to_ms\n info \"Successful request. URL: #{url}, Remaining: #{@remaining}, Total: #{total} ms\"\n\n contents\n rescue OpenURI::HTTPError => e\n @remaining = e.io.meta['x-ratelimit-remaining'].to_i\n @reset = e.io.meta['x-ratelimit-reset'].to_i\n\n case e.io.status[0].to_i\n # The following indicate valid Github return codes\n when 400, # Bad request\n 403, # Forbidden\n 404, # Not found\n 409, # Conflict -- returned on gets of empty repos\n 422 then # Unprocessable entity\n warn request_error_msg(url, e)\n return nil\n when 401 # Unauthorized\n warn request_error_msg(url, e)\n warn \"Unauthorised request with token: #{@token}\"\n raise e\n when 451 # DMCA takedown\n warn request_error_msg(url, e)\n warn \"Repo was taken down (DMCA)\"\n return nil\n else # Server error or HTTP conditions that Github does not report\n warn request_error_msg(url, e)\n raise e\n end\n rescue StandardError => e\n warn error_msg(url, e)\n raise e\n ensure\n # The exact limit is only enforced upon the first @reset\n # No idea how many requests are available on this key. Sleep if we have run out\n if @remaining < @req_limit\n to_sleep = @reset - Time.now.to_i + 2\n warn \"Request limit reached, reset in: #{to_sleep} secs\"\n t = Thread.new do\n slept = 0\n while true do\n debug \"Sleeping for #{to_sleep - slept} seconds\"\n sleep 1\n slept += 1\n end\n end\n sleep([0, to_sleep].max)\n t.exit\n end\n end\n end", "code_tokens": ["def", "api_request_raw", "(", "url", ",", "media_type", "=", "''", ")", "begin", "start_time", "=", "Time", ".", "now", "contents", "=", "do_request", "(", "url", ",", "media_type", ")", "total", "=", "Time", ".", "now", ".", "to_ms", "-", "start_time", ".", "to_ms", "info", "\"Successful request. URL: #{url}, Remaining: #{@remaining}, Total: #{total} ms\"", "contents", "rescue", "OpenURI", "::", "HTTPError", "=>", "e", "@remaining", "=", "e", ".", "io", ".", "meta", "[", "'x-ratelimit-remaining'", "]", ".", "to_i", "@reset", "=", "e", ".", "io", ".", "meta", "[", "'x-ratelimit-reset'", "]", ".", "to_i", "case", "e", ".", "io", ".", "status", "[", "0", "]", ".", "to_i", "# The following indicate valid Github return codes", "when", "400", ",", "# Bad request", "403", ",", "# Forbidden", "404", ",", "# Not found", "409", ",", "# Conflict -- returned on gets of empty repos", "422", "then", "# Unprocessable entity", "warn", "request_error_msg", "(", "url", ",", "e", ")", "return", "nil", "when", "401", "# Unauthorized", "warn", "request_error_msg", "(", "url", ",", "e", ")", "warn", "\"Unauthorised request with token: #{@token}\"", "raise", "e", "when", "451", "# DMCA takedown", "warn", "request_error_msg", "(", "url", ",", "e", ")", "warn", "\"Repo was taken down (DMCA)\"", "return", "nil", "else", "# Server error or HTTP conditions that Github does not report", "warn", "request_error_msg", "(", "url", ",", "e", ")", "raise", "e", "end", "rescue", "StandardError", "=>", "e", "warn", "error_msg", "(", "url", ",", "e", ")", "raise", "e", "ensure", "# The exact limit is only enforced upon the first @reset", "# No idea how many requests are available on this key. Sleep if we have run out", "if", "@remaining", "<", "@req_limit", "to_sleep", "=", "@reset", "-", "Time", ".", "now", ".", "to_i", "+", "2", "warn", "\"Request limit reached, reset in: #{to_sleep} secs\"", "t", "=", "Thread", ".", "new", "do", "slept", "=", "0", "while", "true", "do", "debug", "\"Sleeping for #{to_sleep - slept} seconds\"", "sleep", "1", "slept", "+=", "1", "end", "end", "sleep", "(", "[", "0", ",", "to_sleep", "]", ".", "max", ")", "t", ".", "exit", "end", "end", "end"], "docstring": "Do the actual request and return the result object", "docstring_tokens": ["Do", "the", "actual", "request", "and", "return", "the", "result", "object"], "sha": "3566294a3e4a4c7574bc7376f7e6a9435529b5de", "url": "https://github.com/gousiosg/github-mirror/blob/3566294a3e4a4c7574bc7376f7e6a9435529b5de/lib/ghtorrent/api_client.rb#L174-L230", "partition": "test"} {"repo": "gousiosg/github-mirror", "path": "lib/ghtorrent/api_client.rb", "func_name": "GHTorrent.APIClient.attach_to", "original_string": "def attach_to(ip)\n TCPSocket.instance_eval do\n (class << self; self; end).instance_eval do\n alias_method :original_open, :open\n\n case RUBY_VERSION\n when /1.8/, /1.9/\n define_method(:open) do |conn_address, conn_port|\n original_open(conn_address, conn_port, ip)\n end\n else\n define_method(:open) do |conn_address, conn_port, local_host, local_port|\n original_open(conn_address, conn_port, ip, local_port)\n end\n end\n end\n end\n\n result = begin\n yield\n rescue StandardError => e\n raise e\n ensure\n TCPSocket.instance_eval do\n (class << self; self; end).instance_eval do\n alias_method :open, :original_open\n remove_method :original_open\n end\n end\n end\n\n result\n end", "language": "ruby", "code": "def attach_to(ip)\n TCPSocket.instance_eval do\n (class << self; self; end).instance_eval do\n alias_method :original_open, :open\n\n case RUBY_VERSION\n when /1.8/, /1.9/\n define_method(:open) do |conn_address, conn_port|\n original_open(conn_address, conn_port, ip)\n end\n else\n define_method(:open) do |conn_address, conn_port, local_host, local_port|\n original_open(conn_address, conn_port, ip, local_port)\n end\n end\n end\n end\n\n result = begin\n yield\n rescue StandardError => e\n raise e\n ensure\n TCPSocket.instance_eval do\n (class << self; self; end).instance_eval do\n alias_method :open, :original_open\n remove_method :original_open\n end\n end\n end\n\n result\n end", "code_tokens": ["def", "attach_to", "(", "ip", ")", "TCPSocket", ".", "instance_eval", "do", "(", "class", "<<", "self", ";", "self", ";", "end", ")", ".", "instance_eval", "do", "alias_method", ":original_open", ",", ":open", "case", "RUBY_VERSION", "when", "/", "/", ",", "/", "/", "define_method", "(", ":open", ")", "do", "|", "conn_address", ",", "conn_port", "|", "original_open", "(", "conn_address", ",", "conn_port", ",", "ip", ")", "end", "else", "define_method", "(", ":open", ")", "do", "|", "conn_address", ",", "conn_port", ",", "local_host", ",", "local_port", "|", "original_open", "(", "conn_address", ",", "conn_port", ",", "ip", ",", "local_port", ")", "end", "end", "end", "end", "result", "=", "begin", "yield", "rescue", "StandardError", "=>", "e", "raise", "e", "ensure", "TCPSocket", ".", "instance_eval", "do", "(", "class", "<<", "self", ";", "self", ";", "end", ")", ".", "instance_eval", "do", "alias_method", ":open", ",", ":original_open", "remove_method", ":original_open", "end", "end", "end", "result", "end"], "docstring": "Attach to a specific IP address if the machine has multiple", "docstring_tokens": ["Attach", "to", "a", "specific", "IP", "address", "if", "the", "machine", "has", "multiple"], "sha": "3566294a3e4a4c7574bc7376f7e6a9435529b5de", "url": "https://github.com/gousiosg/github-mirror/blob/3566294a3e4a4c7574bc7376f7e6a9435529b5de/lib/ghtorrent/api_client.rb#L269-L301", "partition": "test"} {"repo": "gousiosg/github-mirror", "path": "lib/ghtorrent/persister.rb", "func_name": "GHTorrent.Persister.connect", "original_string": "def connect(adapter, settings)\n driver = ADAPTERS[adapter.intern]\n driver.new(settings)\n end", "language": "ruby", "code": "def connect(adapter, settings)\n driver = ADAPTERS[adapter.intern]\n driver.new(settings)\n end", "code_tokens": ["def", "connect", "(", "adapter", ",", "settings", ")", "driver", "=", "ADAPTERS", "[", "adapter", ".", "intern", "]", "driver", ".", "new", "(", "settings", ")", "end"], "docstring": "Factory method for retrieving persistence connections.\n The +settings+ argument is a fully parsed YAML document\n passed on to adapters. The available +adapter+ are 'mongo' and 'noop'", "docstring_tokens": ["Factory", "method", "for", "retrieving", "persistence", "connections", ".", "The", "+", "settings", "+", "argument", "is", "a", "fully", "parsed", "YAML", "document", "passed", "on", "to", "adapters", ".", "The", "available", "+", "adapter", "+", "are", "mongo", "and", "noop"], "sha": "3566294a3e4a4c7574bc7376f7e6a9435529b5de", "url": "https://github.com/gousiosg/github-mirror/blob/3566294a3e4a4c7574bc7376f7e6a9435529b5de/lib/ghtorrent/persister.rb#L17-L20", "partition": "test"} {"repo": "gousiosg/github-mirror", "path": "lib/ghtorrent/retriever.rb", "func_name": "GHTorrent.Retriever.retrieve_commit", "original_string": "def retrieve_commit(repo, sha, user)\n commit = persister.find(:commits, {'sha' => \"#{sha}\"})\n\n if commit.empty?\n url = ghurl \"repos/#{user}/#{repo}/commits/#{sha}\"\n c = api_request(url)\n\n if c.nil? or c.empty?\n return\n end\n\n # commit patches are big and not always interesting\n if config(:commit_handling) == 'trim'\n c['files'].each { |file| file.delete('patch') }\n end\n persister.store(:commits, c)\n info \"Added commit #{user}/#{repo} -> #{sha}\"\n c\n else\n debug \"Commit #{user}/#{repo} -> #{sha} exists\"\n commit.first\n end\n end", "language": "ruby", "code": "def retrieve_commit(repo, sha, user)\n commit = persister.find(:commits, {'sha' => \"#{sha}\"})\n\n if commit.empty?\n url = ghurl \"repos/#{user}/#{repo}/commits/#{sha}\"\n c = api_request(url)\n\n if c.nil? or c.empty?\n return\n end\n\n # commit patches are big and not always interesting\n if config(:commit_handling) == 'trim'\n c['files'].each { |file| file.delete('patch') }\n end\n persister.store(:commits, c)\n info \"Added commit #{user}/#{repo} -> #{sha}\"\n c\n else\n debug \"Commit #{user}/#{repo} -> #{sha} exists\"\n commit.first\n end\n end", "code_tokens": ["def", "retrieve_commit", "(", "repo", ",", "sha", ",", "user", ")", "commit", "=", "persister", ".", "find", "(", ":commits", ",", "{", "'sha'", "=>", "\"#{sha}\"", "}", ")", "if", "commit", ".", "empty?", "url", "=", "ghurl", "\"repos/#{user}/#{repo}/commits/#{sha}\"", "c", "=", "api_request", "(", "url", ")", "if", "c", ".", "nil?", "or", "c", ".", "empty?", "return", "end", "# commit patches are big and not always interesting", "if", "config", "(", ":commit_handling", ")", "==", "'trim'", "c", "[", "'files'", "]", ".", "each", "{", "|", "file", "|", "file", ".", "delete", "(", "'patch'", ")", "}", "end", "persister", ".", "store", "(", ":commits", ",", "c", ")", "info", "\"Added commit #{user}/#{repo} -> #{sha}\"", "c", "else", "debug", "\"Commit #{user}/#{repo} -> #{sha} exists\"", "commit", ".", "first", "end", "end"], "docstring": "Retrieve a single commit from a repo", "docstring_tokens": ["Retrieve", "a", "single", "commit", "from", "a", "repo"], "sha": "3566294a3e4a4c7574bc7376f7e6a9435529b5de", "url": "https://github.com/gousiosg/github-mirror/blob/3566294a3e4a4c7574bc7376f7e6a9435529b5de/lib/ghtorrent/retriever.rb#L180-L202", "partition": "test"} {"repo": "gousiosg/github-mirror", "path": "lib/ghtorrent/retriever.rb", "func_name": "GHTorrent.Retriever.retrieve_commits", "original_string": "def retrieve_commits(repo, sha, user, pages = -1)\n\n url = if sha.nil?\n ghurl \"repos/#{user}/#{repo}/commits\"\n else\n ghurl \"repos/#{user}/#{repo}/commits?sha=#{sha}\"\n end\n\n commits = restricted_page_request(url, pages)\n\n commits.map do |c|\n retrieve_commit(repo, c['sha'], user)\n end.select{|x| not x.nil?}\n end", "language": "ruby", "code": "def retrieve_commits(repo, sha, user, pages = -1)\n\n url = if sha.nil?\n ghurl \"repos/#{user}/#{repo}/commits\"\n else\n ghurl \"repos/#{user}/#{repo}/commits?sha=#{sha}\"\n end\n\n commits = restricted_page_request(url, pages)\n\n commits.map do |c|\n retrieve_commit(repo, c['sha'], user)\n end.select{|x| not x.nil?}\n end", "code_tokens": ["def", "retrieve_commits", "(", "repo", ",", "sha", ",", "user", ",", "pages", "=", "-", "1", ")", "url", "=", "if", "sha", ".", "nil?", "ghurl", "\"repos/#{user}/#{repo}/commits\"", "else", "ghurl", "\"repos/#{user}/#{repo}/commits?sha=#{sha}\"", "end", "commits", "=", "restricted_page_request", "(", "url", ",", "pages", ")", "commits", ".", "map", "do", "|", "c", "|", "retrieve_commit", "(", "repo", ",", "c", "[", "'sha'", "]", ",", "user", ")", "end", ".", "select", "{", "|", "x", "|", "not", "x", ".", "nil?", "}", "end"], "docstring": "Retrieve commits starting from the provided +sha+", "docstring_tokens": ["Retrieve", "commits", "starting", "from", "the", "provided", "+", "sha", "+"], "sha": "3566294a3e4a4c7574bc7376f7e6a9435529b5de", "url": "https://github.com/gousiosg/github-mirror/blob/3566294a3e4a4c7574bc7376f7e6a9435529b5de/lib/ghtorrent/retriever.rb#L205-L218", "partition": "test"} {"repo": "gousiosg/github-mirror", "path": "lib/ghtorrent/retriever.rb", "func_name": "GHTorrent.Retriever.retrieve_orgs", "original_string": "def retrieve_orgs(user)\n url = ghurl \"users/#{user}/orgs\"\n orgs = paged_api_request(url)\n orgs.map{|o| retrieve_org(o['login'])}\n end", "language": "ruby", "code": "def retrieve_orgs(user)\n url = ghurl \"users/#{user}/orgs\"\n orgs = paged_api_request(url)\n orgs.map{|o| retrieve_org(o['login'])}\n end", "code_tokens": ["def", "retrieve_orgs", "(", "user", ")", "url", "=", "ghurl", "\"users/#{user}/orgs\"", "orgs", "=", "paged_api_request", "(", "url", ")", "orgs", ".", "map", "{", "|", "o", "|", "retrieve_org", "(", "o", "[", "'login'", "]", ")", "}", "end"], "docstring": "Retrieve organizations the provided user participates into", "docstring_tokens": ["Retrieve", "organizations", "the", "provided", "user", "participates", "into"], "sha": "3566294a3e4a4c7574bc7376f7e6a9435529b5de", "url": "https://github.com/gousiosg/github-mirror/blob/3566294a3e4a4c7574bc7376f7e6a9435529b5de/lib/ghtorrent/retriever.rb#L250-L254", "partition": "test"} {"repo": "gousiosg/github-mirror", "path": "lib/ghtorrent/retriever.rb", "func_name": "GHTorrent.Retriever.retrieve_watchers", "original_string": "def retrieve_watchers(user, repo)\n repo_bound_items(user, repo, :watchers,\n [\"repos/#{user}/#{repo}/stargazers\"],\n {'repo' => repo, 'owner' => user},\n 'login', item = nil, refresh = false, order = :desc)\n end", "language": "ruby", "code": "def retrieve_watchers(user, repo)\n repo_bound_items(user, repo, :watchers,\n [\"repos/#{user}/#{repo}/stargazers\"],\n {'repo' => repo, 'owner' => user},\n 'login', item = nil, refresh = false, order = :desc)\n end", "code_tokens": ["def", "retrieve_watchers", "(", "user", ",", "repo", ")", "repo_bound_items", "(", "user", ",", "repo", ",", ":watchers", ",", "[", "\"repos/#{user}/#{repo}/stargazers\"", "]", ",", "{", "'repo'", "=>", "repo", ",", "'owner'", "=>", "user", "}", ",", "'login'", ",", "item", "=", "nil", ",", "refresh", "=", "false", ",", "order", "=", ":desc", ")", "end"], "docstring": "Retrieve all watchers for a repository", "docstring_tokens": ["Retrieve", "all", "watchers", "for", "a", "repository"], "sha": "3566294a3e4a4c7574bc7376f7e6a9435529b5de", "url": "https://github.com/gousiosg/github-mirror/blob/3566294a3e4a4c7574bc7376f7e6a9435529b5de/lib/ghtorrent/retriever.rb#L320-L325", "partition": "test"} {"repo": "gousiosg/github-mirror", "path": "lib/ghtorrent/retriever.rb", "func_name": "GHTorrent.Retriever.retrieve_watcher", "original_string": "def retrieve_watcher(user, repo, watcher)\n repo_bound_item(user, repo, watcher, :watchers,\n [\"repos/#{user}/#{repo}/stargazers\"],\n {'repo' => repo, 'owner' => user},\n 'login', order = :desc)\n end", "language": "ruby", "code": "def retrieve_watcher(user, repo, watcher)\n repo_bound_item(user, repo, watcher, :watchers,\n [\"repos/#{user}/#{repo}/stargazers\"],\n {'repo' => repo, 'owner' => user},\n 'login', order = :desc)\n end", "code_tokens": ["def", "retrieve_watcher", "(", "user", ",", "repo", ",", "watcher", ")", "repo_bound_item", "(", "user", ",", "repo", ",", "watcher", ",", ":watchers", ",", "[", "\"repos/#{user}/#{repo}/stargazers\"", "]", ",", "{", "'repo'", "=>", "repo", ",", "'owner'", "=>", "user", "}", ",", "'login'", ",", "order", "=", ":desc", ")", "end"], "docstring": "Retrieve a single watcher for a repository", "docstring_tokens": ["Retrieve", "a", "single", "watcher", "for", "a", "repository"], "sha": "3566294a3e4a4c7574bc7376f7e6a9435529b5de", "url": "https://github.com/gousiosg/github-mirror/blob/3566294a3e4a4c7574bc7376f7e6a9435529b5de/lib/ghtorrent/retriever.rb#L328-L333", "partition": "test"} {"repo": "gousiosg/github-mirror", "path": "lib/ghtorrent/retriever.rb", "func_name": "GHTorrent.Retriever.get_repo_events", "original_string": "def get_repo_events(owner, repo)\n url = ghurl(\"repos/#{owner}/#{repo}/events\")\n r = paged_api_request(url)\n\n r.each do |e|\n unless get_event(e['id']).empty?\n debug \"Repository event #{owner}/#{repo} -> #{e['type']}-#{e['id']} already exists\"\n else\n persister.store(:events, e)\n info \"Added event for repository #{owner}/#{repo} -> #{e['type']}-#{e['id']}\"\n end\n end\n\n persister.find(:events, {'repo.name' => \"#{owner}/#{repo}\"})\n\n end", "language": "ruby", "code": "def get_repo_events(owner, repo)\n url = ghurl(\"repos/#{owner}/#{repo}/events\")\n r = paged_api_request(url)\n\n r.each do |e|\n unless get_event(e['id']).empty?\n debug \"Repository event #{owner}/#{repo} -> #{e['type']}-#{e['id']} already exists\"\n else\n persister.store(:events, e)\n info \"Added event for repository #{owner}/#{repo} -> #{e['type']}-#{e['id']}\"\n end\n end\n\n persister.find(:events, {'repo.name' => \"#{owner}/#{repo}\"})\n\n end", "code_tokens": ["def", "get_repo_events", "(", "owner", ",", "repo", ")", "url", "=", "ghurl", "(", "\"repos/#{owner}/#{repo}/events\"", ")", "r", "=", "paged_api_request", "(", "url", ")", "r", ".", "each", "do", "|", "e", "|", "unless", "get_event", "(", "e", "[", "'id'", "]", ")", ".", "empty?", "debug", "\"Repository event #{owner}/#{repo} -> #{e['type']}-#{e['id']} already exists\"", "else", "persister", ".", "store", "(", ":events", ",", "e", ")", "info", "\"Added event for repository #{owner}/#{repo} -> #{e['type']}-#{e['id']}\"", "end", "end", "persister", ".", "find", "(", ":events", ",", "{", "'repo.name'", "=>", "\"#{owner}/#{repo}\"", "}", ")", "end"], "docstring": "Get all events for the specified repo.\n GitHub will only return 90 days of events", "docstring_tokens": ["Get", "all", "events", "for", "the", "specified", "repo", ".", "GitHub", "will", "only", "return", "90", "days", "of", "events"], "sha": "3566294a3e4a4c7574bc7376f7e6a9435529b5de", "url": "https://github.com/gousiosg/github-mirror/blob/3566294a3e4a4c7574bc7376f7e6a9435529b5de/lib/ghtorrent/retriever.rb#L609-L624", "partition": "test"} {"repo": "gousiosg/github-mirror", "path": "lib/ghtorrent/retriever.rb", "func_name": "GHTorrent.Retriever.retrieve_master_branch_diff", "original_string": "def retrieve_master_branch_diff(owner, repo, branch, parent_owner, parent_repo, parent_branch)\n branch = retrieve_default_branch(owner, repo) if branch.nil?\n parent_branch = retrieve_default_branch(parent_owner, parent_repo) if parent_branch.nil?\n return nil if branch.nil? or parent_branch.nil?\n\n cmp_url = \"https://api.github.com/repos/#{parent_owner}/#{parent_repo}/compare/#{parent_branch}...#{owner}:#{branch}\"\n api_request(cmp_url)\n end", "language": "ruby", "code": "def retrieve_master_branch_diff(owner, repo, branch, parent_owner, parent_repo, parent_branch)\n branch = retrieve_default_branch(owner, repo) if branch.nil?\n parent_branch = retrieve_default_branch(parent_owner, parent_repo) if parent_branch.nil?\n return nil if branch.nil? or parent_branch.nil?\n\n cmp_url = \"https://api.github.com/repos/#{parent_owner}/#{parent_repo}/compare/#{parent_branch}...#{owner}:#{branch}\"\n api_request(cmp_url)\n end", "code_tokens": ["def", "retrieve_master_branch_diff", "(", "owner", ",", "repo", ",", "branch", ",", "parent_owner", ",", "parent_repo", ",", "parent_branch", ")", "branch", "=", "retrieve_default_branch", "(", "owner", ",", "repo", ")", "if", "branch", ".", "nil?", "parent_branch", "=", "retrieve_default_branch", "(", "parent_owner", ",", "parent_repo", ")", "if", "parent_branch", ".", "nil?", "return", "nil", "if", "branch", ".", "nil?", "or", "parent_branch", ".", "nil?", "cmp_url", "=", "\"https://api.github.com/repos/#{parent_owner}/#{parent_repo}/compare/#{parent_branch}...#{owner}:#{branch}\"", "api_request", "(", "cmp_url", ")", "end"], "docstring": "Retrieve diff between two branches. If either branch name is not provided\n the branch name is resolved to the corresponding default branch", "docstring_tokens": ["Retrieve", "diff", "between", "two", "branches", ".", "If", "either", "branch", "name", "is", "not", "provided", "the", "branch", "name", "is", "resolved", "to", "the", "corresponding", "default", "branch"], "sha": "3566294a3e4a4c7574bc7376f7e6a9435529b5de", "url": "https://github.com/gousiosg/github-mirror/blob/3566294a3e4a4c7574bc7376f7e6a9435529b5de/lib/ghtorrent/retriever.rb#L633-L640", "partition": "test"} {"repo": "gousiosg/github-mirror", "path": "lib/ghtorrent/retriever.rb", "func_name": "GHTorrent.Retriever.retrieve_default_branch", "original_string": "def retrieve_default_branch(owner, repo, refresh = false)\n retrieved = retrieve_repo(owner, repo, refresh)\n return nil if retrieved.nil?\n\n master_branch = 'master'\n if retrieved['default_branch'].nil?\n # The currently stored repo entry has been created before the\n # default_branch field was added to the schema\n retrieved = retrieve_repo(owner, repo, true)\n return nil if retrieved.nil?\n end\n master_branch = retrieved['default_branch'] unless retrieved.nil?\n master_branch\n end", "language": "ruby", "code": "def retrieve_default_branch(owner, repo, refresh = false)\n retrieved = retrieve_repo(owner, repo, refresh)\n return nil if retrieved.nil?\n\n master_branch = 'master'\n if retrieved['default_branch'].nil?\n # The currently stored repo entry has been created before the\n # default_branch field was added to the schema\n retrieved = retrieve_repo(owner, repo, true)\n return nil if retrieved.nil?\n end\n master_branch = retrieved['default_branch'] unless retrieved.nil?\n master_branch\n end", "code_tokens": ["def", "retrieve_default_branch", "(", "owner", ",", "repo", ",", "refresh", "=", "false", ")", "retrieved", "=", "retrieve_repo", "(", "owner", ",", "repo", ",", "refresh", ")", "return", "nil", "if", "retrieved", ".", "nil?", "master_branch", "=", "'master'", "if", "retrieved", "[", "'default_branch'", "]", ".", "nil?", "# The currently stored repo entry has been created before the", "# default_branch field was added to the schema", "retrieved", "=", "retrieve_repo", "(", "owner", ",", "repo", ",", "true", ")", "return", "nil", "if", "retrieved", ".", "nil?", "end", "master_branch", "=", "retrieved", "[", "'default_branch'", "]", "unless", "retrieved", ".", "nil?", "master_branch", "end"], "docstring": "Retrieve the default branch for a repo. If nothing is retrieved, 'master' is returned", "docstring_tokens": ["Retrieve", "the", "default", "branch", "for", "a", "repo", ".", "If", "nothing", "is", "retrieved", "master", "is", "returned"], "sha": "3566294a3e4a4c7574bc7376f7e6a9435529b5de", "url": "https://github.com/gousiosg/github-mirror/blob/3566294a3e4a4c7574bc7376f7e6a9435529b5de/lib/ghtorrent/retriever.rb#L643-L656", "partition": "test"} {"repo": "gousiosg/github-mirror", "path": "lib/ghtorrent/command.rb", "func_name": "GHTorrent.Command.process_options", "original_string": "def process_options\n command = self\n @options = Trollop::options(command.args) do\n\n command.prepare_options(self)\n\n banner <<-END\nStandard options:\n END\n\n opt :config, 'config.yaml file location', :short => 'c',\n :default => 'config.yaml'\n opt :verbose, 'verbose mode', :short => 'v'\n opt :addr, 'IP address to use for performing requests', :short => 'a',\n :type => String\n opt :token, 'GitHub OAuth token',\n :type => String, :short => 't'\n opt :req_limit, 'Number or requests to leave on any provided account (in reqs/hour)',\n :type => Integer, :short => 'l'\n opt :uniq, 'Unique name for this command. Will appear in logs.',\n :type => String, :short => 'u'\n end\n end", "language": "ruby", "code": "def process_options\n command = self\n @options = Trollop::options(command.args) do\n\n command.prepare_options(self)\n\n banner <<-END\nStandard options:\n END\n\n opt :config, 'config.yaml file location', :short => 'c',\n :default => 'config.yaml'\n opt :verbose, 'verbose mode', :short => 'v'\n opt :addr, 'IP address to use for performing requests', :short => 'a',\n :type => String\n opt :token, 'GitHub OAuth token',\n :type => String, :short => 't'\n opt :req_limit, 'Number or requests to leave on any provided account (in reqs/hour)',\n :type => Integer, :short => 'l'\n opt :uniq, 'Unique name for this command. Will appear in logs.',\n :type => String, :short => 'u'\n end\n end", "code_tokens": ["def", "process_options", "command", "=", "self", "@options", "=", "Trollop", "::", "options", "(", "command", ".", "args", ")", "do", "command", ".", "prepare_options", "(", "self", ")", "banner", "<<-END", "END", "opt", ":config", ",", "'config.yaml file location'", ",", ":short", "=>", "'c'", ",", ":default", "=>", "'config.yaml'", "opt", ":verbose", ",", "'verbose mode'", ",", ":short", "=>", "'v'", "opt", ":addr", ",", "'IP address to use for performing requests'", ",", ":short", "=>", "'a'", ",", ":type", "=>", "String", "opt", ":token", ",", "'GitHub OAuth token'", ",", ":type", "=>", "String", ",", ":short", "=>", "'t'", "opt", ":req_limit", ",", "'Number or requests to leave on any provided account (in reqs/hour)'", ",", ":type", "=>", "Integer", ",", ":short", "=>", "'l'", "opt", ":uniq", ",", "'Unique name for this command. Will appear in logs.'", ",", ":type", "=>", "String", ",", ":short", "=>", "'u'", "end", "end"], "docstring": "Specify and parse top-level command line options.", "docstring_tokens": ["Specify", "and", "parse", "top", "-", "level", "command", "line", "options", "."], "sha": "3566294a3e4a4c7574bc7376f7e6a9435529b5de", "url": "https://github.com/gousiosg/github-mirror/blob/3566294a3e4a4c7574bc7376f7e6a9435529b5de/lib/ghtorrent/command.rb#L80-L102", "partition": "test"} {"repo": "gousiosg/github-mirror", "path": "lib/ghtorrent/command.rb", "func_name": "GHTorrent.Command.validate", "original_string": "def validate\n if options[:config].nil?\n unless (File.exist?(\"config.yaml\"))\n Trollop::die \"No config file in default location (#{Dir.pwd}). You\n need to specify the #{:config} parameter. Read the\n documentation on how to create a config.yaml file.\"\n end\n else\n Trollop::die \"Cannot find file #{options[:config]}\" \\\n unless File.exist?(options[:config])\n end\n\n unless @options[:user].nil?\n if not Process.uid == 0\n Trollop::die \"Option --user (-u) can only be specified by root\"\n end\n begin\n Etc.getpwnam(@options[:user])\n rescue ArgumentError\n Trollop::die \"No such user: #{@options[:user]}\"\n end\n end\n end", "language": "ruby", "code": "def validate\n if options[:config].nil?\n unless (File.exist?(\"config.yaml\"))\n Trollop::die \"No config file in default location (#{Dir.pwd}). You\n need to specify the #{:config} parameter. Read the\n documentation on how to create a config.yaml file.\"\n end\n else\n Trollop::die \"Cannot find file #{options[:config]}\" \\\n unless File.exist?(options[:config])\n end\n\n unless @options[:user].nil?\n if not Process.uid == 0\n Trollop::die \"Option --user (-u) can only be specified by root\"\n end\n begin\n Etc.getpwnam(@options[:user])\n rescue ArgumentError\n Trollop::die \"No such user: #{@options[:user]}\"\n end\n end\n end", "code_tokens": ["def", "validate", "if", "options", "[", ":config", "]", ".", "nil?", "unless", "(", "File", ".", "exist?", "(", "\"config.yaml\"", ")", ")", "Trollop", "::", "die", "\"No config file in default location (#{Dir.pwd}). You\n need to specify the #{:config} parameter. Read the\n documentation on how to create a config.yaml file.\"", "end", "else", "Trollop", "::", "die", "\"Cannot find file #{options[:config]}\"", "unless", "File", ".", "exist?", "(", "options", "[", ":config", "]", ")", "end", "unless", "@options", "[", ":user", "]", ".", "nil?", "if", "not", "Process", ".", "uid", "==", "0", "Trollop", "::", "die", "\"Option --user (-u) can only be specified by root\"", "end", "begin", "Etc", ".", "getpwnam", "(", "@options", "[", ":user", "]", ")", "rescue", "ArgumentError", "Trollop", "::", "die", "\"No such user: #{@options[:user]}\"", "end", "end", "end"], "docstring": "Examine the validity of the provided options in the context of the\n executed command. Subclasses can also call super to also invoke the checks\n provided by this class.", "docstring_tokens": ["Examine", "the", "validity", "of", "the", "provided", "options", "in", "the", "context", "of", "the", "executed", "command", ".", "Subclasses", "can", "also", "call", "super", "to", "also", "invoke", "the", "checks", "provided", "by", "this", "class", "."], "sha": "3566294a3e4a4c7574bc7376f7e6a9435529b5de", "url": "https://github.com/gousiosg/github-mirror/blob/3566294a3e4a4c7574bc7376f7e6a9435529b5de/lib/ghtorrent/command.rb#L117-L139", "partition": "test"} {"repo": "gousiosg/github-mirror", "path": "lib/ghtorrent/command.rb", "func_name": "GHTorrent.Command.queue_client", "original_string": "def queue_client(queue, key = queue, ack = :after, block)\n\n stopped = false\n while not stopped\n begin\n conn = Bunny.new(:host => config(:amqp_host),\n :port => config(:amqp_port),\n :username => config(:amqp_username),\n :password => config(:amqp_password))\n conn.start\n\n ch = conn.create_channel\n debug \"Queue setting prefetch to #{config(:amqp_prefetch)}\"\n ch.prefetch(config(:amqp_prefetch))\n debug \"Queue connection to #{config(:amqp_host)} succeeded\"\n\n x = ch.topic(config(:amqp_exchange), :durable => true,\n :auto_delete => false)\n q = ch.queue(queue, :durable => true)\n q.bind(x, :routing_key => key)\n\n q.subscribe(:block => true,\n :manual_ack => true) do |delivery_info, properties, msg|\n\n if ack == :before\n ch.acknowledge(delivery_info.delivery_tag)\n end\n\n begin\n block.call(msg)\n ensure\n if ack != :before\n ch.acknowledge(delivery_info.delivery_tag)\n end\n end\n end\n\n rescue Bunny::TCPConnectionFailed => e\n warn \"Connection to #{config(:amqp_host)} failed. Retrying in 1 sec\"\n sleep(1)\n rescue Bunny::PossibleAuthenticationFailureError => e\n warn \"Could not authenticate as #{conn.username}\"\n rescue Bunny::NotFound, Bunny::AccessRefused, Bunny::PreconditionFailed => e\n warn \"Channel error: #{e}. Retrying in 1 sec\"\n sleep(1)\n rescue Interrupt => _\n stopped = true\n rescue StandardError => e\n raise e\n end\n end\n\n ch.close unless ch.nil?\n conn.close unless conn.nil?\n\n end", "language": "ruby", "code": "def queue_client(queue, key = queue, ack = :after, block)\n\n stopped = false\n while not stopped\n begin\n conn = Bunny.new(:host => config(:amqp_host),\n :port => config(:amqp_port),\n :username => config(:amqp_username),\n :password => config(:amqp_password))\n conn.start\n\n ch = conn.create_channel\n debug \"Queue setting prefetch to #{config(:amqp_prefetch)}\"\n ch.prefetch(config(:amqp_prefetch))\n debug \"Queue connection to #{config(:amqp_host)} succeeded\"\n\n x = ch.topic(config(:amqp_exchange), :durable => true,\n :auto_delete => false)\n q = ch.queue(queue, :durable => true)\n q.bind(x, :routing_key => key)\n\n q.subscribe(:block => true,\n :manual_ack => true) do |delivery_info, properties, msg|\n\n if ack == :before\n ch.acknowledge(delivery_info.delivery_tag)\n end\n\n begin\n block.call(msg)\n ensure\n if ack != :before\n ch.acknowledge(delivery_info.delivery_tag)\n end\n end\n end\n\n rescue Bunny::TCPConnectionFailed => e\n warn \"Connection to #{config(:amqp_host)} failed. Retrying in 1 sec\"\n sleep(1)\n rescue Bunny::PossibleAuthenticationFailureError => e\n warn \"Could not authenticate as #{conn.username}\"\n rescue Bunny::NotFound, Bunny::AccessRefused, Bunny::PreconditionFailed => e\n warn \"Channel error: #{e}. Retrying in 1 sec\"\n sleep(1)\n rescue Interrupt => _\n stopped = true\n rescue StandardError => e\n raise e\n end\n end\n\n ch.close unless ch.nil?\n conn.close unless conn.nil?\n\n end", "code_tokens": ["def", "queue_client", "(", "queue", ",", "key", "=", "queue", ",", "ack", "=", ":after", ",", "block", ")", "stopped", "=", "false", "while", "not", "stopped", "begin", "conn", "=", "Bunny", ".", "new", "(", ":host", "=>", "config", "(", ":amqp_host", ")", ",", ":port", "=>", "config", "(", ":amqp_port", ")", ",", ":username", "=>", "config", "(", ":amqp_username", ")", ",", ":password", "=>", "config", "(", ":amqp_password", ")", ")", "conn", ".", "start", "ch", "=", "conn", ".", "create_channel", "debug", "\"Queue setting prefetch to #{config(:amqp_prefetch)}\"", "ch", ".", "prefetch", "(", "config", "(", ":amqp_prefetch", ")", ")", "debug", "\"Queue connection to #{config(:amqp_host)} succeeded\"", "x", "=", "ch", ".", "topic", "(", "config", "(", ":amqp_exchange", ")", ",", ":durable", "=>", "true", ",", ":auto_delete", "=>", "false", ")", "q", "=", "ch", ".", "queue", "(", "queue", ",", ":durable", "=>", "true", ")", "q", ".", "bind", "(", "x", ",", ":routing_key", "=>", "key", ")", "q", ".", "subscribe", "(", ":block", "=>", "true", ",", ":manual_ack", "=>", "true", ")", "do", "|", "delivery_info", ",", "properties", ",", "msg", "|", "if", "ack", "==", ":before", "ch", ".", "acknowledge", "(", "delivery_info", ".", "delivery_tag", ")", "end", "begin", "block", ".", "call", "(", "msg", ")", "ensure", "if", "ack", "!=", ":before", "ch", ".", "acknowledge", "(", "delivery_info", ".", "delivery_tag", ")", "end", "end", "end", "rescue", "Bunny", "::", "TCPConnectionFailed", "=>", "e", "warn", "\"Connection to #{config(:amqp_host)} failed. Retrying in 1 sec\"", "sleep", "(", "1", ")", "rescue", "Bunny", "::", "PossibleAuthenticationFailureError", "=>", "e", "warn", "\"Could not authenticate as #{conn.username}\"", "rescue", "Bunny", "::", "NotFound", ",", "Bunny", "::", "AccessRefused", ",", "Bunny", "::", "PreconditionFailed", "=>", "e", "warn", "\"Channel error: #{e}. Retrying in 1 sec\"", "sleep", "(", "1", ")", "rescue", "Interrupt", "=>", "_", "stopped", "=", "true", "rescue", "StandardError", "=>", "e", "raise", "e", "end", "end", "ch", ".", "close", "unless", "ch", ".", "nil?", "conn", ".", "close", "unless", "conn", ".", "nil?", "end"], "docstring": "Specify a handler to incoming messages from a connection to a queue.\n\n @param queue [String] the queue name to bind to\n @param key [String] routing key for msgs for binding the queue to the exchange.\n @param ack [Symbol] when should acks be send, :before or :after the block returns\n @param block [Block]: A block accepting one argument (the message)", "docstring_tokens": ["Specify", "a", "handler", "to", "incoming", "messages", "from", "a", "connection", "to", "a", "queue", "."], "sha": "3566294a3e4a4c7574bc7376f7e6a9435529b5de", "url": "https://github.com/gousiosg/github-mirror/blob/3566294a3e4a4c7574bc7376f7e6a9435529b5de/lib/ghtorrent/command.rb#L156-L211", "partition": "test"} {"repo": "gousiosg/github-mirror", "path": "lib/ghtorrent/utils.rb", "func_name": "GHTorrent.Utils.read_value", "original_string": "def read_value(from, key)\n return from if key.nil? or key == \"\"\n\n key.split(/\\./).reduce({}) do |acc, x|\n unless acc.nil?\n if acc.empty?\n # Initial run\n acc = from[x]\n else\n if acc.has_key?(x)\n acc = acc[x]\n else\n # Some intermediate key does not exist\n return nil\n end\n end\n else\n # Some intermediate key returned a null value\n # This indicates a malformed entry\n return nil\n end\n end\n end", "language": "ruby", "code": "def read_value(from, key)\n return from if key.nil? or key == \"\"\n\n key.split(/\\./).reduce({}) do |acc, x|\n unless acc.nil?\n if acc.empty?\n # Initial run\n acc = from[x]\n else\n if acc.has_key?(x)\n acc = acc[x]\n else\n # Some intermediate key does not exist\n return nil\n end\n end\n else\n # Some intermediate key returned a null value\n # This indicates a malformed entry\n return nil\n end\n end\n end", "code_tokens": ["def", "read_value", "(", "from", ",", "key", ")", "return", "from", "if", "key", ".", "nil?", "or", "key", "==", "\"\"", "key", ".", "split", "(", "/", "\\.", "/", ")", ".", "reduce", "(", "{", "}", ")", "do", "|", "acc", ",", "x", "|", "unless", "acc", ".", "nil?", "if", "acc", ".", "empty?", "# Initial run", "acc", "=", "from", "[", "x", "]", "else", "if", "acc", ".", "has_key?", "(", "x", ")", "acc", "=", "acc", "[", "x", "]", "else", "# Some intermediate key does not exist", "return", "nil", "end", "end", "else", "# Some intermediate key returned a null value", "# This indicates a malformed entry", "return", "nil", "end", "end", "end"], "docstring": "Read the value for a key whose format is \"foo.bar.baz\" from a hierarchical\n map, where a dot represents one level deep in the hierarchy.", "docstring_tokens": ["Read", "the", "value", "for", "a", "key", "whose", "format", "is", "foo", ".", "bar", ".", "baz", "from", "a", "hierarchical", "map", "where", "a", "dot", "represents", "one", "level", "deep", "in", "the", "hierarchy", "."], "sha": "3566294a3e4a4c7574bc7376f7e6a9435529b5de", "url": "https://github.com/gousiosg/github-mirror/blob/3566294a3e4a4c7574bc7376f7e6a9435529b5de/lib/ghtorrent/utils.rb#L12-L34", "partition": "test"} {"repo": "gousiosg/github-mirror", "path": "lib/ghtorrent/geolocator.rb", "func_name": "GHTorrent.Geolocator.location_filter", "original_string": "def location_filter(location)\n return nil if location.nil?\n location.\\\n strip.\\\n downcase.\\\n tr('#\"<>[]', '').\\\n gsub(/^[0-9,\\/().:]*/, '').\\\n gsub(/ +/, ' ').\\\n gsub(/,([a-z]*)/, '\\1')\n end", "language": "ruby", "code": "def location_filter(location)\n return nil if location.nil?\n location.\\\n strip.\\\n downcase.\\\n tr('#\"<>[]', '').\\\n gsub(/^[0-9,\\/().:]*/, '').\\\n gsub(/ +/, ' ').\\\n gsub(/,([a-z]*)/, '\\1')\n end", "code_tokens": ["def", "location_filter", "(", "location", ")", "return", "nil", "if", "location", ".", "nil?", "location", ".", "strip", ".", "downcase", ".", "tr", "(", "'#\"<>[]'", ",", "''", ")", ".", "gsub", "(", "/", "\\/", "/", ",", "''", ")", ".", "gsub", "(", "/", "/", ",", "' '", ")", ".", "gsub", "(", "/", "/", ",", "'\\1'", ")", "end"], "docstring": "Standard filtering on all locations used by GHTorrent", "docstring_tokens": ["Standard", "filtering", "on", "all", "locations", "used", "by", "GHTorrent"], "sha": "3566294a3e4a4c7574bc7376f7e6a9435529b5de", "url": "https://github.com/gousiosg/github-mirror/blob/3566294a3e4a4c7574bc7376f7e6a9435529b5de/lib/ghtorrent/geolocator.rb#L220-L229", "partition": "test"} {"repo": "karafka/karafka", "path": "lib/karafka/base_responder.rb", "func_name": "Karafka.BaseResponder.validate_usage!", "original_string": "def validate_usage!\n registered_topics = self.class.topics.map do |name, topic|\n topic.to_h.merge!(\n usage_count: messages_buffer[name]&.count || 0\n )\n end\n\n used_topics = messages_buffer.map do |name, usage|\n topic = self.class.topics[name] || Responders::Topic.new(name, registered: false)\n topic.to_h.merge!(usage_count: usage.count)\n end\n\n result = Karafka::Schemas::ResponderUsage.call(\n registered_topics: registered_topics,\n used_topics: used_topics\n )\n\n return if result.success?\n\n raise Karafka::Errors::InvalidResponderUsageError, result.errors\n end", "language": "ruby", "code": "def validate_usage!\n registered_topics = self.class.topics.map do |name, topic|\n topic.to_h.merge!(\n usage_count: messages_buffer[name]&.count || 0\n )\n end\n\n used_topics = messages_buffer.map do |name, usage|\n topic = self.class.topics[name] || Responders::Topic.new(name, registered: false)\n topic.to_h.merge!(usage_count: usage.count)\n end\n\n result = Karafka::Schemas::ResponderUsage.call(\n registered_topics: registered_topics,\n used_topics: used_topics\n )\n\n return if result.success?\n\n raise Karafka::Errors::InvalidResponderUsageError, result.errors\n end", "code_tokens": ["def", "validate_usage!", "registered_topics", "=", "self", ".", "class", ".", "topics", ".", "map", "do", "|", "name", ",", "topic", "|", "topic", ".", "to_h", ".", "merge!", "(", "usage_count", ":", "messages_buffer", "[", "name", "]", "&.", "count", "||", "0", ")", "end", "used_topics", "=", "messages_buffer", ".", "map", "do", "|", "name", ",", "usage", "|", "topic", "=", "self", ".", "class", ".", "topics", "[", "name", "]", "||", "Responders", "::", "Topic", ".", "new", "(", "name", ",", "registered", ":", "false", ")", "topic", ".", "to_h", ".", "merge!", "(", "usage_count", ":", "usage", ".", "count", ")", "end", "result", "=", "Karafka", "::", "Schemas", "::", "ResponderUsage", ".", "call", "(", "registered_topics", ":", "registered_topics", ",", "used_topics", ":", "used_topics", ")", "return", "if", "result", ".", "success?", "raise", "Karafka", "::", "Errors", "::", "InvalidResponderUsageError", ",", "result", ".", "errors", "end"], "docstring": "Checks if we met all the topics requirements. It will fail if we didn't send a message to\n a registered required topic, etc.", "docstring_tokens": ["Checks", "if", "we", "met", "all", "the", "topics", "requirements", ".", "It", "will", "fail", "if", "we", "didn", "t", "send", "a", "message", "to", "a", "registered", "required", "topic", "etc", "."], "sha": "1127c5f4b19c1ab2bcc5ee0c708bf500862842b1", "url": "https://github.com/karafka/karafka/blob/1127c5f4b19c1ab2bcc5ee0c708bf500862842b1/lib/karafka/base_responder.rb#L134-L154", "partition": "test"} {"repo": "karafka/karafka", "path": "lib/karafka/base_responder.rb", "func_name": "Karafka.BaseResponder.validate_options!", "original_string": "def validate_options!\n return true unless self.class.options_schema\n\n messages_buffer.each_value do |messages_set|\n messages_set.each do |message_data|\n result = self.class.options_schema.call(message_data.last)\n next if result.success?\n\n raise Karafka::Errors::InvalidResponderMessageOptionsError, result.errors\n end\n end\n end", "language": "ruby", "code": "def validate_options!\n return true unless self.class.options_schema\n\n messages_buffer.each_value do |messages_set|\n messages_set.each do |message_data|\n result = self.class.options_schema.call(message_data.last)\n next if result.success?\n\n raise Karafka::Errors::InvalidResponderMessageOptionsError, result.errors\n end\n end\n end", "code_tokens": ["def", "validate_options!", "return", "true", "unless", "self", ".", "class", ".", "options_schema", "messages_buffer", ".", "each_value", "do", "|", "messages_set", "|", "messages_set", ".", "each", "do", "|", "message_data", "|", "result", "=", "self", ".", "class", ".", "options_schema", ".", "call", "(", "message_data", ".", "last", ")", "next", "if", "result", ".", "success?", "raise", "Karafka", "::", "Errors", "::", "InvalidResponderMessageOptionsError", ",", "result", ".", "errors", "end", "end", "end"], "docstring": "Checks if we met all the options requirements before sending them to the producer.", "docstring_tokens": ["Checks", "if", "we", "met", "all", "the", "options", "requirements", "before", "sending", "them", "to", "the", "producer", "."], "sha": "1127c5f4b19c1ab2bcc5ee0c708bf500862842b1", "url": "https://github.com/karafka/karafka/blob/1127c5f4b19c1ab2bcc5ee0c708bf500862842b1/lib/karafka/base_responder.rb#L157-L168", "partition": "test"} {"repo": "karafka/karafka", "path": "lib/karafka/base_responder.rb", "func_name": "Karafka.BaseResponder.deliver!", "original_string": "def deliver!\n messages_buffer.each_value do |data_elements|\n data_elements.each do |data, options|\n # We map this topic name, so it will match namespaced/etc topic in Kafka\n # @note By default will not change topic (if default mapper used)\n mapped_topic = Karafka::App.config.topic_mapper.outgoing(options[:topic])\n external_options = options.merge(topic: mapped_topic)\n producer(options).call(data, external_options)\n end\n end\n end", "language": "ruby", "code": "def deliver!\n messages_buffer.each_value do |data_elements|\n data_elements.each do |data, options|\n # We map this topic name, so it will match namespaced/etc topic in Kafka\n # @note By default will not change topic (if default mapper used)\n mapped_topic = Karafka::App.config.topic_mapper.outgoing(options[:topic])\n external_options = options.merge(topic: mapped_topic)\n producer(options).call(data, external_options)\n end\n end\n end", "code_tokens": ["def", "deliver!", "messages_buffer", ".", "each_value", "do", "|", "data_elements", "|", "data_elements", ".", "each", "do", "|", "data", ",", "options", "|", "# We map this topic name, so it will match namespaced/etc topic in Kafka", "# @note By default will not change topic (if default mapper used)", "mapped_topic", "=", "Karafka", "::", "App", ".", "config", ".", "topic_mapper", ".", "outgoing", "(", "options", "[", ":topic", "]", ")", "external_options", "=", "options", ".", "merge", "(", "topic", ":", "mapped_topic", ")", "producer", "(", "options", ")", ".", "call", "(", "data", ",", "external_options", ")", "end", "end", "end"], "docstring": "Takes all the messages from the buffer and delivers them one by one\n @note This method is executed after the validation, so we're sure that\n what we send is legit and it will go to a proper topics", "docstring_tokens": ["Takes", "all", "the", "messages", "from", "the", "buffer", "and", "delivers", "them", "one", "by", "one"], "sha": "1127c5f4b19c1ab2bcc5ee0c708bf500862842b1", "url": "https://github.com/karafka/karafka/blob/1127c5f4b19c1ab2bcc5ee0c708bf500862842b1/lib/karafka/base_responder.rb#L173-L183", "partition": "test"} {"repo": "karafka/karafka", "path": "lib/karafka/process.rb", "func_name": "Karafka.Process.notice_signal", "original_string": "def notice_signal(signal)\n Thread.new do\n Karafka.monitor.instrument('process.notice_signal', caller: self, signal: signal)\n end\n end", "language": "ruby", "code": "def notice_signal(signal)\n Thread.new do\n Karafka.monitor.instrument('process.notice_signal', caller: self, signal: signal)\n end\n end", "code_tokens": ["def", "notice_signal", "(", "signal", ")", "Thread", ".", "new", "do", "Karafka", ".", "monitor", ".", "instrument", "(", "'process.notice_signal'", ",", "caller", ":", "self", ",", "signal", ":", "signal", ")", "end", "end"], "docstring": "Informs monitoring about trapped signal\n @param [Symbol] signal type that we received\n @note We cannot perform logging from trap context, that's why\n we have to spin up a new thread to do this", "docstring_tokens": ["Informs", "monitoring", "about", "trapped", "signal"], "sha": "1127c5f4b19c1ab2bcc5ee0c708bf500862842b1", "url": "https://github.com/karafka/karafka/blob/1127c5f4b19c1ab2bcc5ee0c708bf500862842b1/lib/karafka/process.rb#L56-L60", "partition": "test"} {"repo": "jedld/tensor_stream", "path": "lib/tensor_stream/nn/embedding_lookup.rb", "func_name": "TensorStream.EmbeddingLookup.embedding_lookup", "original_string": "def embedding_lookup(params, ids, partition_strategy: \"mod\", name: nil, validate_indices: true, max_norm: nil)\n _embedding_lookup_and_transform(params, ids, partition_strategy: partition_strategy, name: name, max_norm: max_norm, transform_fn: nil)\n end", "language": "ruby", "code": "def embedding_lookup(params, ids, partition_strategy: \"mod\", name: nil, validate_indices: true, max_norm: nil)\n _embedding_lookup_and_transform(params, ids, partition_strategy: partition_strategy, name: name, max_norm: max_norm, transform_fn: nil)\n end", "code_tokens": ["def", "embedding_lookup", "(", "params", ",", "ids", ",", "partition_strategy", ":", "\"mod\"", ",", "name", ":", "nil", ",", "validate_indices", ":", "true", ",", "max_norm", ":", "nil", ")", "_embedding_lookup_and_transform", "(", "params", ",", "ids", ",", "partition_strategy", ":", "partition_strategy", ",", "name", ":", "name", ",", "max_norm", ":", "max_norm", ",", "transform_fn", ":", "nil", ")", "end"], "docstring": "Looks up `ids` in a list of embedding tensors.", "docstring_tokens": ["Looks", "up", "ids", "in", "a", "list", "of", "embedding", "tensors", "."], "sha": "1be668620d86a12d4a2223502722d99968bdf854", "url": "https://github.com/jedld/tensor_stream/blob/1be668620d86a12d4a2223502722d99968bdf854/lib/tensor_stream/nn/embedding_lookup.rb#L11-L13", "partition": "test"} {"repo": "jedld/tensor_stream", "path": "lib/tensor_stream/nn/embedding_lookup.rb", "func_name": "TensorStream.EmbeddingLookup._embedding_lookup_and_transform", "original_string": "def _embedding_lookup_and_transform(params, ids, partition_strategy: \"mod\", name: nil, max_norm: nil, transform_fn: nil)\n raise TensorStream::ValueError, \"Need at least one param\" if params.nil?\n\n params = [params] unless params.is_a?(Array)\n\n TensorStream.name_scope(name, \"embedding_lookup\", values: params + [ids]) do |name|\n np = params.size\n ids = TensorStream.convert_to_tensor(ids, name: \"ids\")\n if (np == 1) && (transform_fn.nil? || (ids.shape.size == 1))\n result = nil\n TensorStream.colocate_with(params[0]) do\n result = _clip(TensorStream.gather(params[0], ids, name: name), ids, max_norm)\n result = transform_fn.call(result) if transform_fn\n end\n\n return TensorStream.identity(result)\n else\n flat_ids = TensorStream.reshape(ids, [-1])\n original_indices = TensorStream.range(TensorStream.size(flat_ids))\n\n p_assignments = nil\n new_ids = nil\n\n if partition_strategy == \"mod\"\n p_assignments = flat_ids % np\n new_ids = floor_div(flat_ids, np)\n elsif partition_strategy == \"div\"\n raise \"not yet supported!\"\n else\n raise TensorStream::ValueError, \"Unrecognized partition strategy: \" + partition_strategy\n end\n\n p_assignments = TensorStream.cast(p_assignments, :int32)\n gather_ids = TensorStream.dynamic_partition(new_ids, p_assignments, np)\n pindices = TensorStream.dynamic_partition(original_indices, p_assignments, np)\n partitioned_result = []\n (0...np).each do |p|\n pids = gather_ids[p]\n result = nil\n TensorStream.colocate_with(params[p]) do\n result = TensorStream.gather(params[p], pids)\n if transform_fn\n # If transform_fn is provided, the clip_by_norm precedes\n # the transform and hence must be co-located. See below\n # for the counterpart if transform_fn is not proveded.\n result = transform_fn.call(_clip(result, pids, max_norm))\n end\n end\n partitioned_result << result\n end\n ret = TensorStream.dynamic_stitch(pindices, partitioned_result, name: name)\n\n if transform_fn.nil?\n element_shape_s = params[0].shape[1..-1]\n params[1..-1].each { |p| element_shape_s = element_shape_s.merge_with(p.shape[1..-1]) }\n else\n element_shape_s = ret.shape[1..-1]\n end\n\n # Compute the dynamic element shape.\n element_shape_d = if element_shape_s.fully_defined?\n element_shape_s\n elsif transform_fn.nil?\n # It's important that we compute params[0].shape on the right device\n # to avoid data motion.\n TensorStream.colocate_with(params[0]) do\n params_shape = TensorStream.shape(params[0])\n params_shape[1..-1]\n end\n else\n TensorStream.shape(ret)[1..-1]\n end\n ret = TensorStream.reshape(ret, TensorStream.concat([TensorStream.shape(ids), element_shape_d], 0))\n ret = _clip(ret, ids, max_norm) unless transform_fn\n ret\n end\n end\n end", "language": "ruby", "code": "def _embedding_lookup_and_transform(params, ids, partition_strategy: \"mod\", name: nil, max_norm: nil, transform_fn: nil)\n raise TensorStream::ValueError, \"Need at least one param\" if params.nil?\n\n params = [params] unless params.is_a?(Array)\n\n TensorStream.name_scope(name, \"embedding_lookup\", values: params + [ids]) do |name|\n np = params.size\n ids = TensorStream.convert_to_tensor(ids, name: \"ids\")\n if (np == 1) && (transform_fn.nil? || (ids.shape.size == 1))\n result = nil\n TensorStream.colocate_with(params[0]) do\n result = _clip(TensorStream.gather(params[0], ids, name: name), ids, max_norm)\n result = transform_fn.call(result) if transform_fn\n end\n\n return TensorStream.identity(result)\n else\n flat_ids = TensorStream.reshape(ids, [-1])\n original_indices = TensorStream.range(TensorStream.size(flat_ids))\n\n p_assignments = nil\n new_ids = nil\n\n if partition_strategy == \"mod\"\n p_assignments = flat_ids % np\n new_ids = floor_div(flat_ids, np)\n elsif partition_strategy == \"div\"\n raise \"not yet supported!\"\n else\n raise TensorStream::ValueError, \"Unrecognized partition strategy: \" + partition_strategy\n end\n\n p_assignments = TensorStream.cast(p_assignments, :int32)\n gather_ids = TensorStream.dynamic_partition(new_ids, p_assignments, np)\n pindices = TensorStream.dynamic_partition(original_indices, p_assignments, np)\n partitioned_result = []\n (0...np).each do |p|\n pids = gather_ids[p]\n result = nil\n TensorStream.colocate_with(params[p]) do\n result = TensorStream.gather(params[p], pids)\n if transform_fn\n # If transform_fn is provided, the clip_by_norm precedes\n # the transform and hence must be co-located. See below\n # for the counterpart if transform_fn is not proveded.\n result = transform_fn.call(_clip(result, pids, max_norm))\n end\n end\n partitioned_result << result\n end\n ret = TensorStream.dynamic_stitch(pindices, partitioned_result, name: name)\n\n if transform_fn.nil?\n element_shape_s = params[0].shape[1..-1]\n params[1..-1].each { |p| element_shape_s = element_shape_s.merge_with(p.shape[1..-1]) }\n else\n element_shape_s = ret.shape[1..-1]\n end\n\n # Compute the dynamic element shape.\n element_shape_d = if element_shape_s.fully_defined?\n element_shape_s\n elsif transform_fn.nil?\n # It's important that we compute params[0].shape on the right device\n # to avoid data motion.\n TensorStream.colocate_with(params[0]) do\n params_shape = TensorStream.shape(params[0])\n params_shape[1..-1]\n end\n else\n TensorStream.shape(ret)[1..-1]\n end\n ret = TensorStream.reshape(ret, TensorStream.concat([TensorStream.shape(ids), element_shape_d], 0))\n ret = _clip(ret, ids, max_norm) unless transform_fn\n ret\n end\n end\n end", "code_tokens": ["def", "_embedding_lookup_and_transform", "(", "params", ",", "ids", ",", "partition_strategy", ":", "\"mod\"", ",", "name", ":", "nil", ",", "max_norm", ":", "nil", ",", "transform_fn", ":", "nil", ")", "raise", "TensorStream", "::", "ValueError", ",", "\"Need at least one param\"", "if", "params", ".", "nil?", "params", "=", "[", "params", "]", "unless", "params", ".", "is_a?", "(", "Array", ")", "TensorStream", ".", "name_scope", "(", "name", ",", "\"embedding_lookup\"", ",", "values", ":", "params", "+", "[", "ids", "]", ")", "do", "|", "name", "|", "np", "=", "params", ".", "size", "ids", "=", "TensorStream", ".", "convert_to_tensor", "(", "ids", ",", "name", ":", "\"ids\"", ")", "if", "(", "np", "==", "1", ")", "&&", "(", "transform_fn", ".", "nil?", "||", "(", "ids", ".", "shape", ".", "size", "==", "1", ")", ")", "result", "=", "nil", "TensorStream", ".", "colocate_with", "(", "params", "[", "0", "]", ")", "do", "result", "=", "_clip", "(", "TensorStream", ".", "gather", "(", "params", "[", "0", "]", ",", "ids", ",", "name", ":", "name", ")", ",", "ids", ",", "max_norm", ")", "result", "=", "transform_fn", ".", "call", "(", "result", ")", "if", "transform_fn", "end", "return", "TensorStream", ".", "identity", "(", "result", ")", "else", "flat_ids", "=", "TensorStream", ".", "reshape", "(", "ids", ",", "[", "-", "1", "]", ")", "original_indices", "=", "TensorStream", ".", "range", "(", "TensorStream", ".", "size", "(", "flat_ids", ")", ")", "p_assignments", "=", "nil", "new_ids", "=", "nil", "if", "partition_strategy", "==", "\"mod\"", "p_assignments", "=", "flat_ids", "%", "np", "new_ids", "=", "floor_div", "(", "flat_ids", ",", "np", ")", "elsif", "partition_strategy", "==", "\"div\"", "raise", "\"not yet supported!\"", "else", "raise", "TensorStream", "::", "ValueError", ",", "\"Unrecognized partition strategy: \"", "+", "partition_strategy", "end", "p_assignments", "=", "TensorStream", ".", "cast", "(", "p_assignments", ",", ":int32", ")", "gather_ids", "=", "TensorStream", ".", "dynamic_partition", "(", "new_ids", ",", "p_assignments", ",", "np", ")", "pindices", "=", "TensorStream", ".", "dynamic_partition", "(", "original_indices", ",", "p_assignments", ",", "np", ")", "partitioned_result", "=", "[", "]", "(", "0", "...", "np", ")", ".", "each", "do", "|", "p", "|", "pids", "=", "gather_ids", "[", "p", "]", "result", "=", "nil", "TensorStream", ".", "colocate_with", "(", "params", "[", "p", "]", ")", "do", "result", "=", "TensorStream", ".", "gather", "(", "params", "[", "p", "]", ",", "pids", ")", "if", "transform_fn", "# If transform_fn is provided, the clip_by_norm precedes", "# the transform and hence must be co-located. See below", "# for the counterpart if transform_fn is not proveded.", "result", "=", "transform_fn", ".", "call", "(", "_clip", "(", "result", ",", "pids", ",", "max_norm", ")", ")", "end", "end", "partitioned_result", "<<", "result", "end", "ret", "=", "TensorStream", ".", "dynamic_stitch", "(", "pindices", ",", "partitioned_result", ",", "name", ":", "name", ")", "if", "transform_fn", ".", "nil?", "element_shape_s", "=", "params", "[", "0", "]", ".", "shape", "[", "1", "..", "-", "1", "]", "params", "[", "1", "..", "-", "1", "]", ".", "each", "{", "|", "p", "|", "element_shape_s", "=", "element_shape_s", ".", "merge_with", "(", "p", ".", "shape", "[", "1", "..", "-", "1", "]", ")", "}", "else", "element_shape_s", "=", "ret", ".", "shape", "[", "1", "..", "-", "1", "]", "end", "# Compute the dynamic element shape.", "element_shape_d", "=", "if", "element_shape_s", ".", "fully_defined?", "element_shape_s", "elsif", "transform_fn", ".", "nil?", "# It's important that we compute params[0].shape on the right device", "# to avoid data motion.", "TensorStream", ".", "colocate_with", "(", "params", "[", "0", "]", ")", "do", "params_shape", "=", "TensorStream", ".", "shape", "(", "params", "[", "0", "]", ")", "params_shape", "[", "1", "..", "-", "1", "]", "end", "else", "TensorStream", ".", "shape", "(", "ret", ")", "[", "1", "..", "-", "1", "]", "end", "ret", "=", "TensorStream", ".", "reshape", "(", "ret", ",", "TensorStream", ".", "concat", "(", "[", "TensorStream", ".", "shape", "(", "ids", ")", ",", "element_shape_d", "]", ",", "0", ")", ")", "ret", "=", "_clip", "(", "ret", ",", "ids", ",", "max_norm", ")", "unless", "transform_fn", "ret", "end", "end", "end"], "docstring": "Helper function for embedding_lookup and _compute_sampled_logits.", "docstring_tokens": ["Helper", "function", "for", "embedding_lookup", "and", "_compute_sampled_logits", "."], "sha": "1be668620d86a12d4a2223502722d99968bdf854", "url": "https://github.com/jedld/tensor_stream/blob/1be668620d86a12d4a2223502722d99968bdf854/lib/tensor_stream/nn/embedding_lookup.rb#L17-L94", "partition": "test"} {"repo": "jedld/tensor_stream", "path": "lib/tensor_stream/graph_deserializers/protobuf.rb", "func_name": "TensorStream.Protobuf.load", "original_string": "def load(pbfile)\n f = File.new(pbfile, \"r\")\n lines = []\n while !f.eof? && (str = f.readline.strip)\n lines << str\n end\n evaluate_lines(lines)\n end", "language": "ruby", "code": "def load(pbfile)\n f = File.new(pbfile, \"r\")\n lines = []\n while !f.eof? && (str = f.readline.strip)\n lines << str\n end\n evaluate_lines(lines)\n end", "code_tokens": ["def", "load", "(", "pbfile", ")", "f", "=", "File", ".", "new", "(", "pbfile", ",", "\"r\"", ")", "lines", "=", "[", "]", "while", "!", "f", ".", "eof?", "&&", "(", "str", "=", "f", ".", "readline", ".", "strip", ")", "lines", "<<", "str", "end", "evaluate_lines", "(", "lines", ")", "end"], "docstring": "parsers a protobuf file and spits out\n a ruby hash", "docstring_tokens": ["parsers", "a", "protobuf", "file", "and", "spits", "out", "a", "ruby", "hash"], "sha": "1be668620d86a12d4a2223502722d99968bdf854", "url": "https://github.com/jedld/tensor_stream/blob/1be668620d86a12d4a2223502722d99968bdf854/lib/tensor_stream/graph_deserializers/protobuf.rb#L16-L23", "partition": "test"} {"repo": "jedld/tensor_stream", "path": "lib/tensor_stream/ops.rb", "func_name": "TensorStream.Ops.assert_equal", "original_string": "def assert_equal(x, y, data: nil, summarize: nil, message: nil, name: nil)\n _op(:assert_equal, x, y, data: data, summarize: summarize, message: message, name: name)\n end", "language": "ruby", "code": "def assert_equal(x, y, data: nil, summarize: nil, message: nil, name: nil)\n _op(:assert_equal, x, y, data: data, summarize: summarize, message: message, name: name)\n end", "code_tokens": ["def", "assert_equal", "(", "x", ",", "y", ",", "data", ":", "nil", ",", "summarize", ":", "nil", ",", "message", ":", "nil", ",", "name", ":", "nil", ")", "_op", "(", ":assert_equal", ",", "x", ",", "y", ",", "data", ":", "data", ",", "summarize", ":", "summarize", ",", "message", ":", "message", ",", "name", ":", "name", ")", "end"], "docstring": "Assert the condition x == y holds element-wise.\n\n Argmuments\n\n +x+ Numeric Tensor.\n +y+ Numeric Tensor, same dtype as and broadcastable to x.\n\n Returns\n Op that raises InvalidArgumentError if x == y is false", "docstring_tokens": ["Assert", "the", "condition", "x", "==", "y", "holds", "element", "-", "wise", "."], "sha": "1be668620d86a12d4a2223502722d99968bdf854", "url": "https://github.com/jedld/tensor_stream/blob/1be668620d86a12d4a2223502722d99968bdf854/lib/tensor_stream/ops.rb#L29-L31", "partition": "test"} {"repo": "jedld/tensor_stream", "path": "lib/tensor_stream/ops.rb", "func_name": "TensorStream.Ops.gradients", "original_string": "def gradients(tensor_ys, wrt_xs, name: \"gradients\", stop_gradients: nil)\n tensor_ys = tensor_ys.op\n gs = wrt_xs.map(&:op).collect { |x|\n stops = stop_gradients ? stop_gradients.map(&:name).join(\"_\") : \"\"\n gradient_program_name = \"grad_#{tensor_ys.name}_#{x.name}_#{stops}\".to_sym\n tensor_graph = tensor_ys.graph\n\n tensor_program = if tensor_graph.node_added?(gradient_program_name)\n tensor_graph.get_node(gradient_program_name)\n else\n tensor_graph.name_scope(\"gradient_wrt_#{x.name}\") do\n derivative_ops = TensorStream::MathGradients.derivative(tensor_ys, x, graph: tensor_graph,\n stop_gradients: stop_gradients)\n tensor_graph.add_node!(gradient_program_name, derivative_ops)\n end\n end\n tensor_program\n }\n\n gs\n end", "language": "ruby", "code": "def gradients(tensor_ys, wrt_xs, name: \"gradients\", stop_gradients: nil)\n tensor_ys = tensor_ys.op\n gs = wrt_xs.map(&:op).collect { |x|\n stops = stop_gradients ? stop_gradients.map(&:name).join(\"_\") : \"\"\n gradient_program_name = \"grad_#{tensor_ys.name}_#{x.name}_#{stops}\".to_sym\n tensor_graph = tensor_ys.graph\n\n tensor_program = if tensor_graph.node_added?(gradient_program_name)\n tensor_graph.get_node(gradient_program_name)\n else\n tensor_graph.name_scope(\"gradient_wrt_#{x.name}\") do\n derivative_ops = TensorStream::MathGradients.derivative(tensor_ys, x, graph: tensor_graph,\n stop_gradients: stop_gradients)\n tensor_graph.add_node!(gradient_program_name, derivative_ops)\n end\n end\n tensor_program\n }\n\n gs\n end", "code_tokens": ["def", "gradients", "(", "tensor_ys", ",", "wrt_xs", ",", "name", ":", "\"gradients\"", ",", "stop_gradients", ":", "nil", ")", "tensor_ys", "=", "tensor_ys", ".", "op", "gs", "=", "wrt_xs", ".", "map", "(", ":op", ")", ".", "collect", "{", "|", "x", "|", "stops", "=", "stop_gradients", "?", "stop_gradients", ".", "map", "(", ":name", ")", ".", "join", "(", "\"_\"", ")", ":", "\"\"", "gradient_program_name", "=", "\"grad_#{tensor_ys.name}_#{x.name}_#{stops}\"", ".", "to_sym", "tensor_graph", "=", "tensor_ys", ".", "graph", "tensor_program", "=", "if", "tensor_graph", ".", "node_added?", "(", "gradient_program_name", ")", "tensor_graph", ".", "get_node", "(", "gradient_program_name", ")", "else", "tensor_graph", ".", "name_scope", "(", "\"gradient_wrt_#{x.name}\"", ")", "do", "derivative_ops", "=", "TensorStream", "::", "MathGradients", ".", "derivative", "(", "tensor_ys", ",", "x", ",", "graph", ":", "tensor_graph", ",", "stop_gradients", ":", "stop_gradients", ")", "tensor_graph", ".", "add_node!", "(", "gradient_program_name", ",", "derivative_ops", ")", "end", "end", "tensor_program", "}", "gs", "end"], "docstring": "Constructs symbolic derivatives of ys of input w.r.t. x in wrt_xs.\n\n ys and xs are each a Tensor or a list of tensors. grad_ys is a list of Tensor, holding the gradients received by the ys. The list must be the same length as ys.\n\n Arguments:\n +tensor_ys+ : A Tensor or list of tensors to be differentiated.\n +wrt_xs+ : A Tensor or list of tensors to be used for differentiation.\n +stop_gradients+ : Optional. A Tensor or list of tensors not to differentiate through", "docstring_tokens": ["Constructs", "symbolic", "derivatives", "of", "ys", "of", "input", "w", ".", "r", ".", "t", ".", "x", "in", "wrt_xs", "."], "sha": "1be668620d86a12d4a2223502722d99968bdf854", "url": "https://github.com/jedld/tensor_stream/blob/1be668620d86a12d4a2223502722d99968bdf854/lib/tensor_stream/ops.rb#L42-L62", "partition": "test"} {"repo": "jedld/tensor_stream", "path": "lib/tensor_stream/ops.rb", "func_name": "TensorStream.Ops.random_normal", "original_string": "def random_normal(shape, dtype: :float32, mean: 0.0, stddev: 1.0, seed: nil, name: nil)\n options = {dtype: dtype, mean: mean, stddev: stddev, seed: seed, name: name}\n _op(:random_standard_normal, shape, options)\n end", "language": "ruby", "code": "def random_normal(shape, dtype: :float32, mean: 0.0, stddev: 1.0, seed: nil, name: nil)\n options = {dtype: dtype, mean: mean, stddev: stddev, seed: seed, name: name}\n _op(:random_standard_normal, shape, options)\n end", "code_tokens": ["def", "random_normal", "(", "shape", ",", "dtype", ":", ":float32", ",", "mean", ":", "0.0", ",", "stddev", ":", "1.0", ",", "seed", ":", "nil", ",", "name", ":", "nil", ")", "options", "=", "{", "dtype", ":", "dtype", ",", "mean", ":", "mean", ",", "stddev", ":", "stddev", ",", "seed", ":", "seed", ",", "name", ":", "name", "}", "_op", "(", ":random_standard_normal", ",", "shape", ",", "options", ")", "end"], "docstring": "Outputs random values from a normal distribution.", "docstring_tokens": ["Outputs", "random", "values", "from", "a", "normal", "distribution", "."], "sha": "1be668620d86a12d4a2223502722d99968bdf854", "url": "https://github.com/jedld/tensor_stream/blob/1be668620d86a12d4a2223502722d99968bdf854/lib/tensor_stream/ops.rb#L66-L69", "partition": "test"} {"repo": "jedld/tensor_stream", "path": "lib/tensor_stream/ops.rb", "func_name": "TensorStream.Ops.eye", "original_string": "def eye(num_rows, num_columns: nil, dtype: :float32, name: nil)\n _op(:eye, num_rows, num_columns || num_rows, data_type: dtype, name: name)\n end", "language": "ruby", "code": "def eye(num_rows, num_columns: nil, dtype: :float32, name: nil)\n _op(:eye, num_rows, num_columns || num_rows, data_type: dtype, name: name)\n end", "code_tokens": ["def", "eye", "(", "num_rows", ",", "num_columns", ":", "nil", ",", "dtype", ":", ":float32", ",", "name", ":", "nil", ")", "_op", "(", ":eye", ",", "num_rows", ",", "num_columns", "||", "num_rows", ",", "data_type", ":", "dtype", ",", "name", ":", "name", ")", "end"], "docstring": "Construct an identity matrix", "docstring_tokens": ["Construct", "an", "identity", "matrix"], "sha": "1be668620d86a12d4a2223502722d99968bdf854", "url": "https://github.com/jedld/tensor_stream/blob/1be668620d86a12d4a2223502722d99968bdf854/lib/tensor_stream/ops.rb#L88-L90", "partition": "test"} {"repo": "jedld/tensor_stream", "path": "lib/tensor_stream/ops.rb", "func_name": "TensorStream.Ops.glorot_uniform_initializer", "original_string": "def glorot_uniform_initializer(seed: nil, dtype: nil)\n TensorStream::Initializer.new(-> { _op(:glorot_uniform, seed: seed, data_type: dtype) })\n end", "language": "ruby", "code": "def glorot_uniform_initializer(seed: nil, dtype: nil)\n TensorStream::Initializer.new(-> { _op(:glorot_uniform, seed: seed, data_type: dtype) })\n end", "code_tokens": ["def", "glorot_uniform_initializer", "(", "seed", ":", "nil", ",", "dtype", ":", "nil", ")", "TensorStream", "::", "Initializer", ".", "new", "(", "->", "{", "_op", "(", ":glorot_uniform", ",", "seed", ":", "seed", ",", "data_type", ":", "dtype", ")", "}", ")", "end"], "docstring": "The Glorot uniform initializer, also called Xavier uniform initializer.\n\n It draws samples from a uniform distribution within [-limit, limit]\n where limit is sqrt(6 / (fan_in + fan_out)) where fan_in is the number\n of input units in the weight tensor and fan_out is the number of output units in the weight tensor.", "docstring_tokens": ["The", "Glorot", "uniform", "initializer", "also", "called", "Xavier", "uniform", "initializer", "."], "sha": "1be668620d86a12d4a2223502722d99968bdf854", "url": "https://github.com/jedld/tensor_stream/blob/1be668620d86a12d4a2223502722d99968bdf854/lib/tensor_stream/ops.rb#L140-L142", "partition": "test"} {"repo": "jedld/tensor_stream", "path": "lib/tensor_stream/ops.rb", "func_name": "TensorStream.Ops.random_uniform_initializer", "original_string": "def random_uniform_initializer(minval: 0, maxval: 1, seed: nil, dtype: nil)\n TensorStream::Initializer.new(-> { _op(:random_uniform, minval: 0, maxval: 1, seed: seed, data_type: dtype) })\n end", "language": "ruby", "code": "def random_uniform_initializer(minval: 0, maxval: 1, seed: nil, dtype: nil)\n TensorStream::Initializer.new(-> { _op(:random_uniform, minval: 0, maxval: 1, seed: seed, data_type: dtype) })\n end", "code_tokens": ["def", "random_uniform_initializer", "(", "minval", ":", "0", ",", "maxval", ":", "1", ",", "seed", ":", "nil", ",", "dtype", ":", "nil", ")", "TensorStream", "::", "Initializer", ".", "new", "(", "->", "{", "_op", "(", ":random_uniform", ",", "minval", ":", "0", ",", "maxval", ":", "1", ",", "seed", ":", "seed", ",", "data_type", ":", "dtype", ")", "}", ")", "end"], "docstring": "Initializer that generates tensors with a uniform distribution.", "docstring_tokens": ["Initializer", "that", "generates", "tensors", "with", "a", "uniform", "distribution", "."], "sha": "1be668620d86a12d4a2223502722d99968bdf854", "url": "https://github.com/jedld/tensor_stream/blob/1be668620d86a12d4a2223502722d99968bdf854/lib/tensor_stream/ops.rb#L146-L148", "partition": "test"} {"repo": "jedld/tensor_stream", "path": "lib/tensor_stream/ops.rb", "func_name": "TensorStream.Ops.slice", "original_string": "def slice(input, start, size, name: nil)\n _op(:slice, input, start, size: size, name: name)\n end", "language": "ruby", "code": "def slice(input, start, size, name: nil)\n _op(:slice, input, start, size: size, name: name)\n end", "code_tokens": ["def", "slice", "(", "input", ",", "start", ",", "size", ",", "name", ":", "nil", ")", "_op", "(", ":slice", ",", "input", ",", "start", ",", "size", ":", "size", ",", "name", ":", "name", ")", "end"], "docstring": "Extracts a slice from a tensor.\n\n This operation extracts a slice of size size from a tensor input starting at the location specified by begin.\n The slice size is represented as a tensor shape, where size[i] is the number of elements of the 'i'th dimension of input that you want to slice. The starting location (begin) for the slice is\n represented as an offset in each dimension of input. In other words, begin[i] is the offset into the 'i'th dimension of input that you want to slice from.", "docstring_tokens": ["Extracts", "a", "slice", "from", "a", "tensor", "."], "sha": "1be668620d86a12d4a2223502722d99968bdf854", "url": "https://github.com/jedld/tensor_stream/blob/1be668620d86a12d4a2223502722d99968bdf854/lib/tensor_stream/ops.rb#L156-L158", "partition": "test"} {"repo": "jedld/tensor_stream", "path": "lib/tensor_stream/ops.rb", "func_name": "TensorStream.Ops.ones", "original_string": "def ones(shape, dtype: :float32, name: nil)\n _op(:ones, shape, data_type: dtype, name: name)\n end", "language": "ruby", "code": "def ones(shape, dtype: :float32, name: nil)\n _op(:ones, shape, data_type: dtype, name: name)\n end", "code_tokens": ["def", "ones", "(", "shape", ",", "dtype", ":", ":float32", ",", "name", ":", "nil", ")", "_op", "(", ":ones", ",", "shape", ",", "data_type", ":", "dtype", ",", "name", ":", "name", ")", "end"], "docstring": "Creates a tensor with all elements set to 1.", "docstring_tokens": ["Creates", "a", "tensor", "with", "all", "elements", "set", "to", "1", "."], "sha": "1be668620d86a12d4a2223502722d99968bdf854", "url": "https://github.com/jedld/tensor_stream/blob/1be668620d86a12d4a2223502722d99968bdf854/lib/tensor_stream/ops.rb#L162-L164", "partition": "test"} {"repo": "jedld/tensor_stream", "path": "lib/tensor_stream/ops.rb", "func_name": "TensorStream.Ops.logical_and", "original_string": "def logical_and(input_a, input_b, name: nil)\n check_data_types(input_a, input_b)\n _op(:logical_and, input_a, input_b, name: name)\n end", "language": "ruby", "code": "def logical_and(input_a, input_b, name: nil)\n check_data_types(input_a, input_b)\n _op(:logical_and, input_a, input_b, name: name)\n end", "code_tokens": ["def", "logical_and", "(", "input_a", ",", "input_b", ",", "name", ":", "nil", ")", "check_data_types", "(", "input_a", ",", "input_b", ")", "_op", "(", ":logical_and", ",", "input_a", ",", "input_b", ",", "name", ":", "name", ")", "end"], "docstring": "Returns the truth value of x AND y element-wise.", "docstring_tokens": ["Returns", "the", "truth", "value", "of", "x", "AND", "y", "element", "-", "wise", "."], "sha": "1be668620d86a12d4a2223502722d99968bdf854", "url": "https://github.com/jedld/tensor_stream/blob/1be668620d86a12d4a2223502722d99968bdf854/lib/tensor_stream/ops.rb#L168-L171", "partition": "test"} {"repo": "jedld/tensor_stream", "path": "lib/tensor_stream/ops.rb", "func_name": "TensorStream.Ops.reduce_mean", "original_string": "def reduce_mean(input_tensor, axis = nil, keepdims: false, name: nil)\n reduce(:mean, input_tensor, axis, keepdims: keepdims, name: name)\n end", "language": "ruby", "code": "def reduce_mean(input_tensor, axis = nil, keepdims: false, name: nil)\n reduce(:mean, input_tensor, axis, keepdims: keepdims, name: name)\n end", "code_tokens": ["def", "reduce_mean", "(", "input_tensor", ",", "axis", "=", "nil", ",", "keepdims", ":", "false", ",", "name", ":", "nil", ")", "reduce", "(", ":mean", ",", "input_tensor", ",", "axis", ",", "keepdims", ":", "keepdims", ",", "name", ":", "name", ")", "end"], "docstring": "Computes the mean of elements across dimensions of a tensor.", "docstring_tokens": ["Computes", "the", "mean", "of", "elements", "across", "dimensions", "of", "a", "tensor", "."], "sha": "1be668620d86a12d4a2223502722d99968bdf854", "url": "https://github.com/jedld/tensor_stream/blob/1be668620d86a12d4a2223502722d99968bdf854/lib/tensor_stream/ops.rb#L175-L177", "partition": "test"} {"repo": "jedld/tensor_stream", "path": "lib/tensor_stream/ops.rb", "func_name": "TensorStream.Ops.concat", "original_string": "def concat(values, axis, name: \"concat\")\n if values.is_a?(Array)\n _op(:concat, axis, *values, name: name)\n else\n _op(:concat, axis, values, name: name)\n end\n end", "language": "ruby", "code": "def concat(values, axis, name: \"concat\")\n if values.is_a?(Array)\n _op(:concat, axis, *values, name: name)\n else\n _op(:concat, axis, values, name: name)\n end\n end", "code_tokens": ["def", "concat", "(", "values", ",", "axis", ",", "name", ":", "\"concat\"", ")", "if", "values", ".", "is_a?", "(", "Array", ")", "_op", "(", ":concat", ",", "axis", ",", "values", ",", "name", ":", "name", ")", "else", "_op", "(", ":concat", ",", "axis", ",", "values", ",", "name", ":", "name", ")", "end", "end"], "docstring": "Concatenates tensors along one dimension.", "docstring_tokens": ["Concatenates", "tensors", "along", "one", "dimension", "."], "sha": "1be668620d86a12d4a2223502722d99968bdf854", "url": "https://github.com/jedld/tensor_stream/blob/1be668620d86a12d4a2223502722d99968bdf854/lib/tensor_stream/ops.rb#L190-L196", "partition": "test"} {"repo": "jedld/tensor_stream", "path": "lib/tensor_stream/ops.rb", "func_name": "TensorStream.Ops.dynamic_partition", "original_string": "def dynamic_partition(data, partitions, num_partitions, name: nil)\n result = _op(:dynamic_partition, data, partitions, num_partitions: num_partitions, name: nil)\n num_partitions.times.map do |index|\n result[index]\n end\n end", "language": "ruby", "code": "def dynamic_partition(data, partitions, num_partitions, name: nil)\n result = _op(:dynamic_partition, data, partitions, num_partitions: num_partitions, name: nil)\n num_partitions.times.map do |index|\n result[index]\n end\n end", "code_tokens": ["def", "dynamic_partition", "(", "data", ",", "partitions", ",", "num_partitions", ",", "name", ":", "nil", ")", "result", "=", "_op", "(", ":dynamic_partition", ",", "data", ",", "partitions", ",", "num_partitions", ":", "num_partitions", ",", "name", ":", "nil", ")", "num_partitions", ".", "times", ".", "map", "do", "|", "index", "|", "result", "[", "index", "]", "end", "end"], "docstring": "Partitions data into num_partitions tensors using indices from partitions", "docstring_tokens": ["Partitions", "data", "into", "num_partitions", "tensors", "using", "indices", "from", "partitions"], "sha": "1be668620d86a12d4a2223502722d99968bdf854", "url": "https://github.com/jedld/tensor_stream/blob/1be668620d86a12d4a2223502722d99968bdf854/lib/tensor_stream/ops.rb#L200-L205", "partition": "test"} {"repo": "jedld/tensor_stream", "path": "lib/tensor_stream/ops.rb", "func_name": "TensorStream.Ops.where", "original_string": "def where(condition, true_t = nil, false_t = nil, name: nil)\n _op(:where, condition, true_t, false_t, name: name)\n end", "language": "ruby", "code": "def where(condition, true_t = nil, false_t = nil, name: nil)\n _op(:where, condition, true_t, false_t, name: name)\n end", "code_tokens": ["def", "where", "(", "condition", ",", "true_t", "=", "nil", ",", "false_t", "=", "nil", ",", "name", ":", "nil", ")", "_op", "(", ":where", ",", "condition", ",", "true_t", ",", "false_t", ",", "name", ":", "name", ")", "end"], "docstring": "Return the elements, either from x or y, depending on the condition.", "docstring_tokens": ["Return", "the", "elements", "either", "from", "x", "or", "y", "depending", "on", "the", "condition", "."], "sha": "1be668620d86a12d4a2223502722d99968bdf854", "url": "https://github.com/jedld/tensor_stream/blob/1be668620d86a12d4a2223502722d99968bdf854/lib/tensor_stream/ops.rb#L287-L289", "partition": "test"} {"repo": "jedld/tensor_stream", "path": "lib/tensor_stream/ops.rb", "func_name": "TensorStream.Ops.asin", "original_string": "def asin(input, name: nil)\n check_allowed_types(input, FLOATING_POINT_TYPES)\n _op(:asin, input, name: name)\n end", "language": "ruby", "code": "def asin(input, name: nil)\n check_allowed_types(input, FLOATING_POINT_TYPES)\n _op(:asin, input, name: name)\n end", "code_tokens": ["def", "asin", "(", "input", ",", "name", ":", "nil", ")", "check_allowed_types", "(", "input", ",", "FLOATING_POINT_TYPES", ")", "_op", "(", ":asin", ",", "input", ",", "name", ":", "name", ")", "end"], "docstring": "Computes asin of input element-wise", "docstring_tokens": ["Computes", "asin", "of", "input", "element", "-", "wise"], "sha": "1be668620d86a12d4a2223502722d99968bdf854", "url": "https://github.com/jedld/tensor_stream/blob/1be668620d86a12d4a2223502722d99968bdf854/lib/tensor_stream/ops.rb#L301-L304", "partition": "test"} {"repo": "jedld/tensor_stream", "path": "lib/tensor_stream/ops.rb", "func_name": "TensorStream.Ops.acos", "original_string": "def acos(input, name: nil)\n check_allowed_types(input, FLOATING_POINT_TYPES)\n _op(:acos, input, name: name)\n end", "language": "ruby", "code": "def acos(input, name: nil)\n check_allowed_types(input, FLOATING_POINT_TYPES)\n _op(:acos, input, name: name)\n end", "code_tokens": ["def", "acos", "(", "input", ",", "name", ":", "nil", ")", "check_allowed_types", "(", "input", ",", "FLOATING_POINT_TYPES", ")", "_op", "(", ":acos", ",", "input", ",", "name", ":", "name", ")", "end"], "docstring": "Computes acos of input element-wise", "docstring_tokens": ["Computes", "acos", "of", "input", "element", "-", "wise"], "sha": "1be668620d86a12d4a2223502722d99968bdf854", "url": "https://github.com/jedld/tensor_stream/blob/1be668620d86a12d4a2223502722d99968bdf854/lib/tensor_stream/ops.rb#L308-L311", "partition": "test"} {"repo": "jedld/tensor_stream", "path": "lib/tensor_stream/ops.rb", "func_name": "TensorStream.Ops.atan", "original_string": "def atan(input, name: nil)\n check_allowed_types(input, FLOATING_POINT_TYPES)\n _op(:atan, input, name: name)\n end", "language": "ruby", "code": "def atan(input, name: nil)\n check_allowed_types(input, FLOATING_POINT_TYPES)\n _op(:atan, input, name: name)\n end", "code_tokens": ["def", "atan", "(", "input", ",", "name", ":", "nil", ")", "check_allowed_types", "(", "input", ",", "FLOATING_POINT_TYPES", ")", "_op", "(", ":atan", ",", "input", ",", "name", ":", "name", ")", "end"], "docstring": "Computes atan of input element-wise", "docstring_tokens": ["Computes", "atan", "of", "input", "element", "-", "wise"], "sha": "1be668620d86a12d4a2223502722d99968bdf854", "url": "https://github.com/jedld/tensor_stream/blob/1be668620d86a12d4a2223502722d99968bdf854/lib/tensor_stream/ops.rb#L315-L318", "partition": "test"} {"repo": "jedld/tensor_stream", "path": "lib/tensor_stream/ops.rb", "func_name": "TensorStream.Ops.cast", "original_string": "def cast(input, dtype, name: nil)\n input = convert_to_tensor(input)\n return input if input.data_type == dtype\n\n _op(:cast, input, data_type: dtype, name: name)\n end", "language": "ruby", "code": "def cast(input, dtype, name: nil)\n input = convert_to_tensor(input)\n return input if input.data_type == dtype\n\n _op(:cast, input, data_type: dtype, name: name)\n end", "code_tokens": ["def", "cast", "(", "input", ",", "dtype", ",", "name", ":", "nil", ")", "input", "=", "convert_to_tensor", "(", "input", ")", "return", "input", "if", "input", ".", "data_type", "==", "dtype", "_op", "(", ":cast", ",", "input", ",", "data_type", ":", "dtype", ",", "name", ":", "name", ")", "end"], "docstring": "Casts a tensor to a new type, if needed", "docstring_tokens": ["Casts", "a", "tensor", "to", "a", "new", "type", "if", "needed"], "sha": "1be668620d86a12d4a2223502722d99968bdf854", "url": "https://github.com/jedld/tensor_stream/blob/1be668620d86a12d4a2223502722d99968bdf854/lib/tensor_stream/ops.rb#L329-L334", "partition": "test"} {"repo": "jedld/tensor_stream", "path": "lib/tensor_stream/ops.rb", "func_name": "TensorStream.Ops.print", "original_string": "def print(input, data, message: nil, name: nil)\n _op(:print, input, data, message: message, name: name)\n end", "language": "ruby", "code": "def print(input, data, message: nil, name: nil)\n _op(:print, input, data, message: message, name: name)\n end", "code_tokens": ["def", "print", "(", "input", ",", "data", ",", "message", ":", "nil", ",", "name", ":", "nil", ")", "_op", "(", ":print", ",", "input", ",", "data", ",", "message", ":", "message", ",", "name", ":", "name", ")", "end"], "docstring": "Prints a list of tensors.\n\n This is an identity op (behaves like tf.identity) with the side effect of printing data when evaluating.", "docstring_tokens": ["Prints", "a", "list", "of", "tensors", "."], "sha": "1be668620d86a12d4a2223502722d99968bdf854", "url": "https://github.com/jedld/tensor_stream/blob/1be668620d86a12d4a2223502722d99968bdf854/lib/tensor_stream/ops.rb#L352-L354", "partition": "test"} {"repo": "jedld/tensor_stream", "path": "lib/tensor_stream/ops.rb", "func_name": "TensorStream.Ops.sec", "original_string": "def sec(input, name: nil)\n check_allowed_types(input, FLOATING_POINT_TYPES)\n _op(:sec, input, name: name)\n end", "language": "ruby", "code": "def sec(input, name: nil)\n check_allowed_types(input, FLOATING_POINT_TYPES)\n _op(:sec, input, name: name)\n end", "code_tokens": ["def", "sec", "(", "input", ",", "name", ":", "nil", ")", "check_allowed_types", "(", "input", ",", "FLOATING_POINT_TYPES", ")", "_op", "(", ":sec", ",", "input", ",", "name", ":", "name", ")", "end"], "docstring": "Computes sec of input element-wise.", "docstring_tokens": ["Computes", "sec", "of", "input", "element", "-", "wise", "."], "sha": "1be668620d86a12d4a2223502722d99968bdf854", "url": "https://github.com/jedld/tensor_stream/blob/1be668620d86a12d4a2223502722d99968bdf854/lib/tensor_stream/ops.rb#L410-L413", "partition": "test"} {"repo": "jedld/tensor_stream", "path": "lib/tensor_stream/ops.rb", "func_name": "TensorStream.Ops.sqrt", "original_string": "def sqrt(input, name: nil)\n check_allowed_types(input, FLOATING_POINT_TYPES)\n _op(:sqrt, input, name: name)\n end", "language": "ruby", "code": "def sqrt(input, name: nil)\n check_allowed_types(input, FLOATING_POINT_TYPES)\n _op(:sqrt, input, name: name)\n end", "code_tokens": ["def", "sqrt", "(", "input", ",", "name", ":", "nil", ")", "check_allowed_types", "(", "input", ",", "FLOATING_POINT_TYPES", ")", "_op", "(", ":sqrt", ",", "input", ",", "name", ":", "name", ")", "end"], "docstring": "Computes sqrt of input element-wise.", "docstring_tokens": ["Computes", "sqrt", "of", "input", "element", "-", "wise", "."], "sha": "1be668620d86a12d4a2223502722d99968bdf854", "url": "https://github.com/jedld/tensor_stream/blob/1be668620d86a12d4a2223502722d99968bdf854/lib/tensor_stream/ops.rb#L417-L420", "partition": "test"} {"repo": "jedld/tensor_stream", "path": "lib/tensor_stream/ops.rb", "func_name": "TensorStream.Ops.log", "original_string": "def log(input, name: nil)\n check_allowed_types(input, FLOATING_POINT_TYPES)\n _op(:log, input, name: name)\n end", "language": "ruby", "code": "def log(input, name: nil)\n check_allowed_types(input, FLOATING_POINT_TYPES)\n _op(:log, input, name: name)\n end", "code_tokens": ["def", "log", "(", "input", ",", "name", ":", "nil", ")", "check_allowed_types", "(", "input", ",", "FLOATING_POINT_TYPES", ")", "_op", "(", ":log", ",", "input", ",", "name", ":", "name", ")", "end"], "docstring": "Computes natural logarithm of x element-wise.", "docstring_tokens": ["Computes", "natural", "logarithm", "of", "x", "element", "-", "wise", "."], "sha": "1be668620d86a12d4a2223502722d99968bdf854", "url": "https://github.com/jedld/tensor_stream/blob/1be668620d86a12d4a2223502722d99968bdf854/lib/tensor_stream/ops.rb#L424-L427", "partition": "test"} {"repo": "jedld/tensor_stream", "path": "lib/tensor_stream/ops.rb", "func_name": "TensorStream.Ops.exp", "original_string": "def exp(input, name: nil)\n check_allowed_types(input, FLOATING_POINT_TYPES)\n _op(:exp, input, name: name)\n end", "language": "ruby", "code": "def exp(input, name: nil)\n check_allowed_types(input, FLOATING_POINT_TYPES)\n _op(:exp, input, name: name)\n end", "code_tokens": ["def", "exp", "(", "input", ",", "name", ":", "nil", ")", "check_allowed_types", "(", "input", ",", "FLOATING_POINT_TYPES", ")", "_op", "(", ":exp", ",", "input", ",", "name", ":", "name", ")", "end"], "docstring": "Computes exponential of x element-wise.", "docstring_tokens": ["Computes", "exponential", "of", "x", "element", "-", "wise", "."], "sha": "1be668620d86a12d4a2223502722d99968bdf854", "url": "https://github.com/jedld/tensor_stream/blob/1be668620d86a12d4a2223502722d99968bdf854/lib/tensor_stream/ops.rb#L438-L441", "partition": "test"} {"repo": "jedld/tensor_stream", "path": "lib/tensor_stream/ops.rb", "func_name": "TensorStream.Ops.pad", "original_string": "def pad(tensor, paddings, mode: \"CONSTANT\", name: nil)\n _op(:pad, tensor, paddings, mode: mode, name: name)\n end", "language": "ruby", "code": "def pad(tensor, paddings, mode: \"CONSTANT\", name: nil)\n _op(:pad, tensor, paddings, mode: mode, name: name)\n end", "code_tokens": ["def", "pad", "(", "tensor", ",", "paddings", ",", "mode", ":", "\"CONSTANT\"", ",", "name", ":", "nil", ")", "_op", "(", ":pad", ",", "tensor", ",", "paddings", ",", "mode", ":", "mode", ",", "name", ":", "name", ")", "end"], "docstring": "Pads a tensor.\n This operation pads a tensor according to the paddings you specify.", "docstring_tokens": ["Pads", "a", "tensor", ".", "This", "operation", "pads", "a", "tensor", "according", "to", "the", "paddings", "you", "specify", "."], "sha": "1be668620d86a12d4a2223502722d99968bdf854", "url": "https://github.com/jedld/tensor_stream/blob/1be668620d86a12d4a2223502722d99968bdf854/lib/tensor_stream/ops.rb#L452-L454", "partition": "test"} {"repo": "jedld/tensor_stream", "path": "lib/tensor_stream/ops.rb", "func_name": "TensorStream.Ops.gather", "original_string": "def gather(params, indices, validate_indices: nil,\n name: nil,\n axis: 0)\n _op(:gather, params, indices, validate_indices: validate_indices, name: name, axis: axis)\n end", "language": "ruby", "code": "def gather(params, indices, validate_indices: nil,\n name: nil,\n axis: 0)\n _op(:gather, params, indices, validate_indices: validate_indices, name: name, axis: axis)\n end", "code_tokens": ["def", "gather", "(", "params", ",", "indices", ",", "validate_indices", ":", "nil", ",", "name", ":", "nil", ",", "axis", ":", "0", ")", "_op", "(", ":gather", ",", "params", ",", "indices", ",", "validate_indices", ":", "validate_indices", ",", "name", ":", "name", ",", "axis", ":", "axis", ")", "end"], "docstring": "Gather slices from params and axis according to indices.", "docstring_tokens": ["Gather", "slices", "from", "params", "and", "axis", "according", "to", "indices", "."], "sha": "1be668620d86a12d4a2223502722d99968bdf854", "url": "https://github.com/jedld/tensor_stream/blob/1be668620d86a12d4a2223502722d99968bdf854/lib/tensor_stream/ops.rb#L475-L479", "partition": "test"} {"repo": "jedld/tensor_stream", "path": "lib/tensor_stream/ops.rb", "func_name": "TensorStream.Ops.pack", "original_string": "def pack(values, axis: 0, name: \"pack\")\n _op(:stack, *values, axis: axis, name: name)\n end", "language": "ruby", "code": "def pack(values, axis: 0, name: \"pack\")\n _op(:stack, *values, axis: axis, name: name)\n end", "code_tokens": ["def", "pack", "(", "values", ",", "axis", ":", "0", ",", "name", ":", "\"pack\"", ")", "_op", "(", ":stack", ",", "values", ",", "axis", ":", "axis", ",", "name", ":", "name", ")", "end"], "docstring": "Same as stack", "docstring_tokens": ["Same", "as", "stack"], "sha": "1be668620d86a12d4a2223502722d99968bdf854", "url": "https://github.com/jedld/tensor_stream/blob/1be668620d86a12d4a2223502722d99968bdf854/lib/tensor_stream/ops.rb#L516-L518", "partition": "test"} {"repo": "jedld/tensor_stream", "path": "lib/tensor_stream/ops.rb", "func_name": "TensorStream.Ops.unpack", "original_string": "def unpack(value, num: nil, axis: 0, name: \"unpack\")\n unstack(value, num: num, axis: axis, name: name)\n end", "language": "ruby", "code": "def unpack(value, num: nil, axis: 0, name: \"unpack\")\n unstack(value, num: num, axis: axis, name: name)\n end", "code_tokens": ["def", "unpack", "(", "value", ",", "num", ":", "nil", ",", "axis", ":", "0", ",", "name", ":", "\"unpack\"", ")", "unstack", "(", "value", ",", "num", ":", "num", ",", "axis", ":", "axis", ",", "name", ":", "name", ")", "end"], "docstring": "Same as unstack", "docstring_tokens": ["Same", "as", "unstack"], "sha": "1be668620d86a12d4a2223502722d99968bdf854", "url": "https://github.com/jedld/tensor_stream/blob/1be668620d86a12d4a2223502722d99968bdf854/lib/tensor_stream/ops.rb#L523-L525", "partition": "test"} {"repo": "jedld/tensor_stream", "path": "lib/tensor_stream/ops.rb", "func_name": "TensorStream.Ops.case", "original_string": "def case(args = {})\n args = args.dup\n default = args.delete(:default)\n exclusive = args.delete(:exclusive)\n strict = args.delete(:strict)\n name = args.delete(:name)\n\n predicates = []\n functions = []\n\n args.each do |k, v|\n raise \"Invalid argment or option #{k}\" unless k.is_a?(Tensor)\n\n predicates << k\n functions << (v.is_a?(Proc) ? v.call : v)\n end\n\n _op(:case, predicates, default, *functions, exclusive: exclusive, strict: strict, name: name)\n end", "language": "ruby", "code": "def case(args = {})\n args = args.dup\n default = args.delete(:default)\n exclusive = args.delete(:exclusive)\n strict = args.delete(:strict)\n name = args.delete(:name)\n\n predicates = []\n functions = []\n\n args.each do |k, v|\n raise \"Invalid argment or option #{k}\" unless k.is_a?(Tensor)\n\n predicates << k\n functions << (v.is_a?(Proc) ? v.call : v)\n end\n\n _op(:case, predicates, default, *functions, exclusive: exclusive, strict: strict, name: name)\n end", "code_tokens": ["def", "case", "(", "args", "=", "{", "}", ")", "args", "=", "args", ".", "dup", "default", "=", "args", ".", "delete", "(", ":default", ")", "exclusive", "=", "args", ".", "delete", "(", ":exclusive", ")", "strict", "=", "args", ".", "delete", "(", ":strict", ")", "name", "=", "args", ".", "delete", "(", ":name", ")", "predicates", "=", "[", "]", "functions", "=", "[", "]", "args", ".", "each", "do", "|", "k", ",", "v", "|", "raise", "\"Invalid argment or option #{k}\"", "unless", "k", ".", "is_a?", "(", "Tensor", ")", "predicates", "<<", "k", "functions", "<<", "(", "v", ".", "is_a?", "(", "Proc", ")", "?", "v", ".", "call", ":", "v", ")", "end", "_op", "(", ":case", ",", "predicates", ",", "default", ",", "functions", ",", "exclusive", ":", "exclusive", ",", "strict", ":", "strict", ",", "name", ":", "name", ")", "end"], "docstring": "Create a case operation.\n\n The pred_fn_pairs parameter is a dict or list of pairs of size N.\n Each pair contains a boolean scalar tensor and a proc that creates the tensors to be returned if the boolean evaluates to true.\n default is a proc generating a list of tensors. All the proc in pred_fn_pairs as well as default (if provided) should return the\n same number and types of tensors.", "docstring_tokens": ["Create", "a", "case", "operation", "."], "sha": "1be668620d86a12d4a2223502722d99968bdf854", "url": "https://github.com/jedld/tensor_stream/blob/1be668620d86a12d4a2223502722d99968bdf854/lib/tensor_stream/ops.rb#L559-L577", "partition": "test"} {"repo": "jedld/tensor_stream", "path": "lib/tensor_stream/helpers/op_helper.rb", "func_name": "TensorStream.OpHelper.i_op", "original_string": "def i_op(code, *args)\n options = if args.last.is_a?(Hash)\n args.pop\n else\n {}\n end\n\n args << options.merge(internal: true)\n Graph.get_default_graph.add_op!(code.to_sym, *args)\n end", "language": "ruby", "code": "def i_op(code, *args)\n options = if args.last.is_a?(Hash)\n args.pop\n else\n {}\n end\n\n args << options.merge(internal: true)\n Graph.get_default_graph.add_op!(code.to_sym, *args)\n end", "code_tokens": ["def", "i_op", "(", "code", ",", "*", "args", ")", "options", "=", "if", "args", ".", "last", ".", "is_a?", "(", "Hash", ")", "args", ".", "pop", "else", "{", "}", "end", "args", "<<", "options", ".", "merge", "(", "internal", ":", "true", ")", "Graph", ".", "get_default_graph", ".", "add_op!", "(", "code", ".", "to_sym", ",", "args", ")", "end"], "docstring": "same as op but with a marker that it was internal generated", "docstring_tokens": ["same", "as", "op", "but", "with", "a", "marker", "that", "it", "was", "internal", "generated"], "sha": "1be668620d86a12d4a2223502722d99968bdf854", "url": "https://github.com/jedld/tensor_stream/blob/1be668620d86a12d4a2223502722d99968bdf854/lib/tensor_stream/helpers/op_helper.rb#L16-L25", "partition": "test"} {"repo": "jedld/tensor_stream", "path": "lib/tensor_stream/evaluator/operation_helpers/array_ops_helper.rb", "func_name": "TensorStream.ArrayOpsHelper.broadcast_dimensions", "original_string": "def broadcast_dimensions(input, dims = [])\n return input if dims.empty?\n\n d = dims.shift\n\n if input.is_a?(Array) && (get_rank(input) - 1) == dims.size\n row_to_dup = input.collect { |item|\n broadcast_dimensions(item, dims.dup)\n }\n\n row_to_dup + Array.new(d) { row_to_dup }.flatten(1)\n elsif input.is_a?(Array)\n Array.new(d) { broadcast_dimensions(input, dims.dup) }\n else\n Array.new(d + 1) { input }\n end\n end", "language": "ruby", "code": "def broadcast_dimensions(input, dims = [])\n return input if dims.empty?\n\n d = dims.shift\n\n if input.is_a?(Array) && (get_rank(input) - 1) == dims.size\n row_to_dup = input.collect { |item|\n broadcast_dimensions(item, dims.dup)\n }\n\n row_to_dup + Array.new(d) { row_to_dup }.flatten(1)\n elsif input.is_a?(Array)\n Array.new(d) { broadcast_dimensions(input, dims.dup) }\n else\n Array.new(d + 1) { input }\n end\n end", "code_tokens": ["def", "broadcast_dimensions", "(", "input", ",", "dims", "=", "[", "]", ")", "return", "input", "if", "dims", ".", "empty?", "d", "=", "dims", ".", "shift", "if", "input", ".", "is_a?", "(", "Array", ")", "&&", "(", "get_rank", "(", "input", ")", "-", "1", ")", "==", "dims", ".", "size", "row_to_dup", "=", "input", ".", "collect", "{", "|", "item", "|", "broadcast_dimensions", "(", "item", ",", "dims", ".", "dup", ")", "}", "row_to_dup", "+", "Array", ".", "new", "(", "d", ")", "{", "row_to_dup", "}", ".", "flatten", "(", "1", ")", "elsif", "input", ".", "is_a?", "(", "Array", ")", "Array", ".", "new", "(", "d", ")", "{", "broadcast_dimensions", "(", "input", ",", "dims", ".", "dup", ")", "}", "else", "Array", ".", "new", "(", "d", "+", "1", ")", "{", "input", "}", "end", "end"], "docstring": "explicit broadcasting helper", "docstring_tokens": ["explicit", "broadcasting", "helper"], "sha": "1be668620d86a12d4a2223502722d99968bdf854", "url": "https://github.com/jedld/tensor_stream/blob/1be668620d86a12d4a2223502722d99968bdf854/lib/tensor_stream/evaluator/operation_helpers/array_ops_helper.rb#L94-L110", "partition": "test"} {"repo": "jedld/tensor_stream", "path": "lib/tensor_stream/evaluator/operation_helpers/array_ops_helper.rb", "func_name": "TensorStream.ArrayOpsHelper.vector_op", "original_string": "def vector_op(vector, vector2, switch = false, safe = true, &block)\n if get_rank(vector) < get_rank(vector2) # upgrade rank of A\n duplicated = Array.new(vector2.size) {\n vector\n }\n return vector_op(duplicated, vector2, switch, &block)\n end\n\n return yield(vector, vector2) unless vector.is_a?(Array)\n\n vector.each_with_index.collect { |input, index|\n next vector_op(input, vector2, switch, &block) if input.is_a?(Array) && get_rank(vector) > get_rank(vector2)\n\n if safe && vector2.is_a?(Array)\n next nil if vector2.size != 1 && index >= vector2.size\n end\n\n z = if vector2.is_a?(Array)\n if index < vector2.size\n vector2[index]\n else\n raise \"incompatible tensor shapes used during op\" if vector2.size != 1\n vector2[0]\n end\n else\n vector2\n end\n\n if input.is_a?(Array)\n vector_op(input, z, switch, &block)\n else\n switch ? yield(z, input) : yield(input, z)\n end\n }.compact\n end", "language": "ruby", "code": "def vector_op(vector, vector2, switch = false, safe = true, &block)\n if get_rank(vector) < get_rank(vector2) # upgrade rank of A\n duplicated = Array.new(vector2.size) {\n vector\n }\n return vector_op(duplicated, vector2, switch, &block)\n end\n\n return yield(vector, vector2) unless vector.is_a?(Array)\n\n vector.each_with_index.collect { |input, index|\n next vector_op(input, vector2, switch, &block) if input.is_a?(Array) && get_rank(vector) > get_rank(vector2)\n\n if safe && vector2.is_a?(Array)\n next nil if vector2.size != 1 && index >= vector2.size\n end\n\n z = if vector2.is_a?(Array)\n if index < vector2.size\n vector2[index]\n else\n raise \"incompatible tensor shapes used during op\" if vector2.size != 1\n vector2[0]\n end\n else\n vector2\n end\n\n if input.is_a?(Array)\n vector_op(input, z, switch, &block)\n else\n switch ? yield(z, input) : yield(input, z)\n end\n }.compact\n end", "code_tokens": ["def", "vector_op", "(", "vector", ",", "vector2", ",", "switch", "=", "false", ",", "safe", "=", "true", ",", "&", "block", ")", "if", "get_rank", "(", "vector", ")", "<", "get_rank", "(", "vector2", ")", "# upgrade rank of A", "duplicated", "=", "Array", ".", "new", "(", "vector2", ".", "size", ")", "{", "vector", "}", "return", "vector_op", "(", "duplicated", ",", "vector2", ",", "switch", ",", "block", ")", "end", "return", "yield", "(", "vector", ",", "vector2", ")", "unless", "vector", ".", "is_a?", "(", "Array", ")", "vector", ".", "each_with_index", ".", "collect", "{", "|", "input", ",", "index", "|", "next", "vector_op", "(", "input", ",", "vector2", ",", "switch", ",", "block", ")", "if", "input", ".", "is_a?", "(", "Array", ")", "&&", "get_rank", "(", "vector", ")", ">", "get_rank", "(", "vector2", ")", "if", "safe", "&&", "vector2", ".", "is_a?", "(", "Array", ")", "next", "nil", "if", "vector2", ".", "size", "!=", "1", "&&", "index", ">=", "vector2", ".", "size", "end", "z", "=", "if", "vector2", ".", "is_a?", "(", "Array", ")", "if", "index", "<", "vector2", ".", "size", "vector2", "[", "index", "]", "else", "raise", "\"incompatible tensor shapes used during op\"", "if", "vector2", ".", "size", "!=", "1", "vector2", "[", "0", "]", "end", "else", "vector2", "end", "if", "input", ".", "is_a?", "(", "Array", ")", "vector_op", "(", "input", ",", "z", ",", "switch", ",", "block", ")", "else", "switch", "?", "yield", "(", "z", ",", "input", ")", ":", "yield", "(", "input", ",", "z", ")", "end", "}", ".", "compact", "end"], "docstring": "handle 2 tensor math operations", "docstring_tokens": ["handle", "2", "tensor", "math", "operations"], "sha": "1be668620d86a12d4a2223502722d99968bdf854", "url": "https://github.com/jedld/tensor_stream/blob/1be668620d86a12d4a2223502722d99968bdf854/lib/tensor_stream/evaluator/operation_helpers/array_ops_helper.rb#L113-L147", "partition": "test"} {"repo": "jedld/tensor_stream", "path": "lib/tensor_stream/evaluator/operation_helpers/array_ops_helper.rb", "func_name": "TensorStream.ArrayOpsHelper.transpose_with_perm", "original_string": "def transpose_with_perm(arr, new_arr, shape, new_shape, perm)\n arr_size = shape.reduce(:*)\n divisors = shape.dup.drop(1).reverse.inject([1]) { |a, s|\n a << s * a.last\n }.reverse\n\n multipliers = new_shape.dup.drop(1).reverse.inject([1]) { |a, s|\n a << s * a.last\n }.reverse\n\n arr_size.times do |p|\n ptr = p\n index = []\n divisors.each_with_object(index) do |div, a|\n a << (ptr / div.to_f).floor\n ptr = ptr % div\n end\n\n # remap based on perm\n remaped = perm.map { |x| index[x] }\n\n ptr2 = 0\n multipliers.each_with_index do |m, idx|\n ptr2 += remaped[idx] * m\n end\n\n new_arr[ptr2] = arr[p]\n end\n\n [new_arr, new_shape]\n end", "language": "ruby", "code": "def transpose_with_perm(arr, new_arr, shape, new_shape, perm)\n arr_size = shape.reduce(:*)\n divisors = shape.dup.drop(1).reverse.inject([1]) { |a, s|\n a << s * a.last\n }.reverse\n\n multipliers = new_shape.dup.drop(1).reverse.inject([1]) { |a, s|\n a << s * a.last\n }.reverse\n\n arr_size.times do |p|\n ptr = p\n index = []\n divisors.each_with_object(index) do |div, a|\n a << (ptr / div.to_f).floor\n ptr = ptr % div\n end\n\n # remap based on perm\n remaped = perm.map { |x| index[x] }\n\n ptr2 = 0\n multipliers.each_with_index do |m, idx|\n ptr2 += remaped[idx] * m\n end\n\n new_arr[ptr2] = arr[p]\n end\n\n [new_arr, new_shape]\n end", "code_tokens": ["def", "transpose_with_perm", "(", "arr", ",", "new_arr", ",", "shape", ",", "new_shape", ",", "perm", ")", "arr_size", "=", "shape", ".", "reduce", "(", ":*", ")", "divisors", "=", "shape", ".", "dup", ".", "drop", "(", "1", ")", ".", "reverse", ".", "inject", "(", "[", "1", "]", ")", "{", "|", "a", ",", "s", "|", "a", "<<", "s", "*", "a", ".", "last", "}", ".", "reverse", "multipliers", "=", "new_shape", ".", "dup", ".", "drop", "(", "1", ")", ".", "reverse", ".", "inject", "(", "[", "1", "]", ")", "{", "|", "a", ",", "s", "|", "a", "<<", "s", "*", "a", ".", "last", "}", ".", "reverse", "arr_size", ".", "times", "do", "|", "p", "|", "ptr", "=", "p", "index", "=", "[", "]", "divisors", ".", "each_with_object", "(", "index", ")", "do", "|", "div", ",", "a", "|", "a", "<<", "(", "ptr", "/", "div", ".", "to_f", ")", ".", "floor", "ptr", "=", "ptr", "%", "div", "end", "# remap based on perm", "remaped", "=", "perm", ".", "map", "{", "|", "x", "|", "index", "[", "x", "]", "}", "ptr2", "=", "0", "multipliers", ".", "each_with_index", "do", "|", "m", ",", "idx", "|", "ptr2", "+=", "remaped", "[", "idx", "]", "*", "m", "end", "new_arr", "[", "ptr2", "]", "=", "arr", "[", "p", "]", "end", "[", "new_arr", ",", "new_shape", "]", "end"], "docstring": "general case transposition with flat arrays", "docstring_tokens": ["general", "case", "transposition", "with", "flat", "arrays"], "sha": "1be668620d86a12d4a2223502722d99968bdf854", "url": "https://github.com/jedld/tensor_stream/blob/1be668620d86a12d4a2223502722d99968bdf854/lib/tensor_stream/evaluator/operation_helpers/array_ops_helper.rb#L245-L275", "partition": "test"} {"repo": "jedld/tensor_stream", "path": "lib/tensor_stream/generated_stub/ops.rb", "func_name": "TensorStream.OpStub.add", "original_string": "def add(input_a, input_b, name: nil)\n input_a, input_b = apply_data_type_coercion(input_a, input_b)\n _op(:add, input_a, input_b, name: name)\n end", "language": "ruby", "code": "def add(input_a, input_b, name: nil)\n input_a, input_b = apply_data_type_coercion(input_a, input_b)\n _op(:add, input_a, input_b, name: name)\n end", "code_tokens": ["def", "add", "(", "input_a", ",", "input_b", ",", "name", ":", "nil", ")", "input_a", ",", "input_b", "=", "apply_data_type_coercion", "(", "input_a", ",", "input_b", ")", "_op", "(", ":add", ",", "input_a", ",", "input_b", ",", "name", ":", "name", ")", "end"], "docstring": "Returns x + y element-wise.\n\n This operation supports broadcasting\n\n @param input_a tensor X\n @param input_b tensor Y\n\n Options:\n @option name Optional name\n @return Tensor", "docstring_tokens": ["Returns", "x", "+", "y", "element", "-", "wise", "."], "sha": "1be668620d86a12d4a2223502722d99968bdf854", "url": "https://github.com/jedld/tensor_stream/blob/1be668620d86a12d4a2223502722d99968bdf854/lib/tensor_stream/generated_stub/ops.rb#L18-L21", "partition": "test"} {"repo": "jedld/tensor_stream", "path": "lib/tensor_stream/generated_stub/ops.rb", "func_name": "TensorStream.OpStub.argmax", "original_string": "def argmax(input_a, axis = nil, name: nil, dimension: nil, output_type: :int32)\n check_allowed_types(input_a, TensorStream::Ops::NUMERIC_TYPES)\n check_allowed_types(axis, TensorStream::Ops::INTEGER_TYPES)\n _op(:argmax, input_a, axis, name: name, dimension: dimension, output_type: output_type)\n end", "language": "ruby", "code": "def argmax(input_a, axis = nil, name: nil, dimension: nil, output_type: :int32)\n check_allowed_types(input_a, TensorStream::Ops::NUMERIC_TYPES)\n check_allowed_types(axis, TensorStream::Ops::INTEGER_TYPES)\n _op(:argmax, input_a, axis, name: name, dimension: dimension, output_type: output_type)\n end", "code_tokens": ["def", "argmax", "(", "input_a", ",", "axis", "=", "nil", ",", "name", ":", "nil", ",", "dimension", ":", "nil", ",", "output_type", ":", ":int32", ")", "check_allowed_types", "(", "input_a", ",", "TensorStream", "::", "Ops", "::", "NUMERIC_TYPES", ")", "check_allowed_types", "(", "axis", ",", "TensorStream", "::", "Ops", "::", "INTEGER_TYPES", ")", "_op", "(", ":argmax", ",", "input_a", ",", "axis", ",", "name", ":", "name", ",", "dimension", ":", "dimension", ",", "output_type", ":", "output_type", ")", "end"], "docstring": "Returns the index with the largest value across axes of a tensor.\n\n\n @param input_a tensor X (of type NUMERIC_TYPES)\n @param axis Describes which axis of the input tensor to reduce across. For vectors, use axis = 0 (of type INTEGER_TYPES)\n\n Options:\n @option name Optional name\n @option dimension Same as axis\n @option output_type Output data type defaults to int32 default (:int32)\n @return Tensor", "docstring_tokens": ["Returns", "the", "index", "with", "the", "largest", "value", "across", "axes", "of", "a", "tensor", "."], "sha": "1be668620d86a12d4a2223502722d99968bdf854", "url": "https://github.com/jedld/tensor_stream/blob/1be668620d86a12d4a2223502722d99968bdf854/lib/tensor_stream/generated_stub/ops.rb#L36-L40", "partition": "test"} {"repo": "jedld/tensor_stream", "path": "lib/tensor_stream/generated_stub/ops.rb", "func_name": "TensorStream.OpStub.ceil", "original_string": "def ceil(input_a, name: nil)\n check_allowed_types(input_a, TensorStream::Ops::FLOATING_POINT_TYPES)\n _op(:ceil, input_a, name: name)\n end", "language": "ruby", "code": "def ceil(input_a, name: nil)\n check_allowed_types(input_a, TensorStream::Ops::FLOATING_POINT_TYPES)\n _op(:ceil, input_a, name: name)\n end", "code_tokens": ["def", "ceil", "(", "input_a", ",", "name", ":", "nil", ")", "check_allowed_types", "(", "input_a", ",", "TensorStream", "::", "Ops", "::", "FLOATING_POINT_TYPES", ")", "_op", "(", ":ceil", ",", "input_a", ",", "name", ":", "name", ")", "end"], "docstring": "Returns element-wise smallest integer in not less than x\n\n\n @param input_a tensor X (of type FLOATING_POINT_TYPES)\n\n Options:\n @option name Optional name\n @return Tensor", "docstring_tokens": ["Returns", "element", "-", "wise", "smallest", "integer", "in", "not", "less", "than", "x"], "sha": "1be668620d86a12d4a2223502722d99968bdf854", "url": "https://github.com/jedld/tensor_stream/blob/1be668620d86a12d4a2223502722d99968bdf854/lib/tensor_stream/generated_stub/ops.rb#L71-L74", "partition": "test"} {"repo": "jedld/tensor_stream", "path": "lib/tensor_stream/generated_stub/ops.rb", "func_name": "TensorStream.OpStub.cos", "original_string": "def cos(input_a, name: nil)\n check_allowed_types(input_a, TensorStream::Ops::FLOATING_POINT_TYPES)\n _op(:cos, input_a, name: name)\n end", "language": "ruby", "code": "def cos(input_a, name: nil)\n check_allowed_types(input_a, TensorStream::Ops::FLOATING_POINT_TYPES)\n _op(:cos, input_a, name: name)\n end", "code_tokens": ["def", "cos", "(", "input_a", ",", "name", ":", "nil", ")", "check_allowed_types", "(", "input_a", ",", "TensorStream", "::", "Ops", "::", "FLOATING_POINT_TYPES", ")", "_op", "(", ":cos", ",", "input_a", ",", "name", ":", "name", ")", "end"], "docstring": "Computes cos of input element-wise.\n\n\n @param input_a tensor X (of type FLOATING_POINT_TYPES)\n\n Options:\n @option name Optional name\n @return Tensor", "docstring_tokens": ["Computes", "cos", "of", "input", "element", "-", "wise", "."], "sha": "1be668620d86a12d4a2223502722d99968bdf854", "url": "https://github.com/jedld/tensor_stream/blob/1be668620d86a12d4a2223502722d99968bdf854/lib/tensor_stream/generated_stub/ops.rb#L86-L89", "partition": "test"} {"repo": "jedld/tensor_stream", "path": "lib/tensor_stream/generated_stub/ops.rb", "func_name": "TensorStream.OpStub.floor", "original_string": "def floor(input_a, name: nil)\n check_allowed_types(input_a, TensorStream::Ops::FLOATING_POINT_TYPES)\n _op(:floor, input_a, name: name)\n end", "language": "ruby", "code": "def floor(input_a, name: nil)\n check_allowed_types(input_a, TensorStream::Ops::FLOATING_POINT_TYPES)\n _op(:floor, input_a, name: name)\n end", "code_tokens": ["def", "floor", "(", "input_a", ",", "name", ":", "nil", ")", "check_allowed_types", "(", "input_a", ",", "TensorStream", "::", "Ops", "::", "FLOATING_POINT_TYPES", ")", "_op", "(", ":floor", ",", "input_a", ",", "name", ":", "name", ")", "end"], "docstring": "Returns element-wise largest integer not greater than x.\n\n\n @param input_a tensor X (of type FLOATING_POINT_TYPES)\n\n Options:\n @option name Optional name\n @return Tensor", "docstring_tokens": ["Returns", "element", "-", "wise", "largest", "integer", "not", "greater", "than", "x", "."], "sha": "1be668620d86a12d4a2223502722d99968bdf854", "url": "https://github.com/jedld/tensor_stream/blob/1be668620d86a12d4a2223502722d99968bdf854/lib/tensor_stream/generated_stub/ops.rb#L167-L170", "partition": "test"} {"repo": "jedld/tensor_stream", "path": "lib/tensor_stream/generated_stub/ops.rb", "func_name": "TensorStream.OpStub.mod", "original_string": "def mod(input_a, input_b, name: nil)\n input_a, input_b = apply_data_type_coercion(input_a, input_b)\n _op(:mod, input_a, input_b, name: name)\n end", "language": "ruby", "code": "def mod(input_a, input_b, name: nil)\n input_a, input_b = apply_data_type_coercion(input_a, input_b)\n _op(:mod, input_a, input_b, name: name)\n end", "code_tokens": ["def", "mod", "(", "input_a", ",", "input_b", ",", "name", ":", "nil", ")", "input_a", ",", "input_b", "=", "apply_data_type_coercion", "(", "input_a", ",", "input_b", ")", "_op", "(", ":mod", ",", "input_a", ",", "input_b", ",", "name", ":", "name", ")", "end"], "docstring": "Returns element-wise remainder of division.\n\n This operation supports broadcasting\n\n @param input_a tensor X\n @param input_b tensor Y\n\n Options:\n @option name Optional name\n @return Tensor", "docstring_tokens": ["Returns", "element", "-", "wise", "remainder", "of", "division", "."], "sha": "1be668620d86a12d4a2223502722d99968bdf854", "url": "https://github.com/jedld/tensor_stream/blob/1be668620d86a12d4a2223502722d99968bdf854/lib/tensor_stream/generated_stub/ops.rb#L341-L344", "partition": "test"} {"repo": "jedld/tensor_stream", "path": "lib/tensor_stream/generated_stub/ops.rb", "func_name": "TensorStream.OpStub.pow", "original_string": "def pow(input_a, input_b, name: nil)\n input_a, input_b = apply_data_type_coercion(input_a, input_b)\n _op(:pow, input_a, input_b, name: name)\n end", "language": "ruby", "code": "def pow(input_a, input_b, name: nil)\n input_a, input_b = apply_data_type_coercion(input_a, input_b)\n _op(:pow, input_a, input_b, name: name)\n end", "code_tokens": ["def", "pow", "(", "input_a", ",", "input_b", ",", "name", ":", "nil", ")", "input_a", ",", "input_b", "=", "apply_data_type_coercion", "(", "input_a", ",", "input_b", ")", "_op", "(", ":pow", ",", "input_a", ",", "input_b", ",", "name", ":", "name", ")", "end"], "docstring": "Computes the power of one value to another X^Y element wise\n\n This operation supports broadcasting\n\n @param input_a tensor X\n @param input_b tensor Y\n\n Options:\n @option name Optional name\n @return Tensor", "docstring_tokens": ["Computes", "the", "power", "of", "one", "value", "to", "another", "X^Y", "element", "wise"], "sha": "1be668620d86a12d4a2223502722d99968bdf854", "url": "https://github.com/jedld/tensor_stream/blob/1be668620d86a12d4a2223502722d99968bdf854/lib/tensor_stream/generated_stub/ops.rb#L424-L427", "partition": "test"} {"repo": "jedld/tensor_stream", "path": "lib/tensor_stream/generated_stub/ops.rb", "func_name": "TensorStream.OpStub.prod", "original_string": "def prod(input_a, axis = nil, name: nil, keepdims: false)\n check_allowed_types(axis, TensorStream::Ops::INTEGER_TYPES)\n input_a = TensorStream.convert_to_tensor(input_a)\n return input_a if input_a.shape.scalar?\n axis = cast_axis(input_a, axis)\n _op(:prod, input_a, axis, name: name, keepdims: keepdims)\n end", "language": "ruby", "code": "def prod(input_a, axis = nil, name: nil, keepdims: false)\n check_allowed_types(axis, TensorStream::Ops::INTEGER_TYPES)\n input_a = TensorStream.convert_to_tensor(input_a)\n return input_a if input_a.shape.scalar?\n axis = cast_axis(input_a, axis)\n _op(:prod, input_a, axis, name: name, keepdims: keepdims)\n end", "code_tokens": ["def", "prod", "(", "input_a", ",", "axis", "=", "nil", ",", "name", ":", "nil", ",", "keepdims", ":", "false", ")", "check_allowed_types", "(", "axis", ",", "TensorStream", "::", "Ops", "::", "INTEGER_TYPES", ")", "input_a", "=", "TensorStream", ".", "convert_to_tensor", "(", "input_a", ")", "return", "input_a", "if", "input_a", ".", "shape", ".", "scalar?", "axis", "=", "cast_axis", "(", "input_a", ",", "axis", ")", "_op", "(", ":prod", ",", "input_a", ",", "axis", ",", "name", ":", "name", ",", "keepdims", ":", "keepdims", ")", "end"], "docstring": "Computes the product of elements across dimensions of a tensor.\n Reduces input_tensor along the dimensions given in axis. Unless keepdims is true, the rank of the\n tensor is reduced by 1 for each entry in axis. If keepdims is true, the reduced dimensions are\n retained with length 1.\n If axis has no entries, all dimensions are reduced, and a tensor with a single element is returned.\n\n\n @param input_a tensor X\n @param axis tensor X (of type INTEGER_TYPES)\n\n Options:\n @option name Optional name\n @option keepdims If true, retains reduced dimensions with length 1. default (false)\n @return Tensor", "docstring_tokens": ["Computes", "the", "product", "of", "elements", "across", "dimensions", "of", "a", "tensor", ".", "Reduces", "input_tensor", "along", "the", "dimensions", "given", "in", "axis", ".", "Unless", "keepdims", "is", "true", "the", "rank", "of", "the", "tensor", "is", "reduced", "by", "1", "for", "each", "entry", "in", "axis", ".", "If", "keepdims", "is", "true", "the", "reduced", "dimensions", "are", "retained", "with", "length", "1", ".", "If", "axis", "has", "no", "entries", "all", "dimensions", "are", "reduced", "and", "a", "tensor", "with", "a", "single", "element", "is", "returned", "."], "sha": "1be668620d86a12d4a2223502722d99968bdf854", "url": "https://github.com/jedld/tensor_stream/blob/1be668620d86a12d4a2223502722d99968bdf854/lib/tensor_stream/generated_stub/ops.rb#L445-L451", "partition": "test"} {"repo": "jedld/tensor_stream", "path": "lib/tensor_stream/generated_stub/ops.rb", "func_name": "TensorStream.OpStub.random_uniform", "original_string": "def random_uniform(shape, name: nil, dtype: :float32, minval: 0, maxval: 1, seed: nil)\n _op(:random_uniform, shape, name: name, dtype: dtype, minval: minval, maxval: maxval, seed: seed)\n end", "language": "ruby", "code": "def random_uniform(shape, name: nil, dtype: :float32, minval: 0, maxval: 1, seed: nil)\n _op(:random_uniform, shape, name: name, dtype: dtype, minval: minval, maxval: maxval, seed: seed)\n end", "code_tokens": ["def", "random_uniform", "(", "shape", ",", "name", ":", "nil", ",", "dtype", ":", ":float32", ",", "minval", ":", "0", ",", "maxval", ":", "1", ",", "seed", ":", "nil", ")", "_op", "(", ":random_uniform", ",", "shape", ",", "name", ":", "name", ",", "dtype", ":", "dtype", ",", "minval", ":", "minval", ",", "maxval", ":", "maxval", ",", "seed", ":", "seed", ")", "end"], "docstring": "Outputs random values from a uniform distribution.\n\n\n @param shape A 1-D integer Tensor or array. The shape of the output tensor.\n\n Options:\n @option name Optional name\n @option dtype The type of the output: float16, float32, float64, int32, or int64 default (:float32)\n @option minval A 0-D Tensor or ruby value of type dtype. The lower bound on the range of random values to generate. Defaults to 0. default (0)\n @option maxval A 0-D Tensor or ruby value of type dtype. The upper bound on the range of random values to generate. Defaults to 1 if dtype is floating point. default (1)\n @option seed A ruby integer. Used to create a random seed for the distribution. See set_random_seed for behavior.\n @return Tensor", "docstring_tokens": ["Outputs", "random", "values", "from", "a", "uniform", "distribution", "."], "sha": "1be668620d86a12d4a2223502722d99968bdf854", "url": "https://github.com/jedld/tensor_stream/blob/1be668620d86a12d4a2223502722d99968bdf854/lib/tensor_stream/generated_stub/ops.rb#L468-L470", "partition": "test"} {"repo": "jedld/tensor_stream", "path": "lib/tensor_stream/generated_stub/ops.rb", "func_name": "TensorStream.OpStub.range", "original_string": "def range(start = 0, limit = 0, delta = 1, name: \"range\", dtype: nil, output_type: :int32)\n _op(:range, start, limit, delta, name: name, dtype: dtype, output_type: output_type)\n end", "language": "ruby", "code": "def range(start = 0, limit = 0, delta = 1, name: \"range\", dtype: nil, output_type: :int32)\n _op(:range, start, limit, delta, name: name, dtype: dtype, output_type: output_type)\n end", "code_tokens": ["def", "range", "(", "start", "=", "0", ",", "limit", "=", "0", ",", "delta", "=", "1", ",", "name", ":", "\"range\"", ",", "dtype", ":", "nil", ",", "output_type", ":", ":int32", ")", "_op", "(", ":range", ",", "start", ",", "limit", ",", "delta", ",", "name", ":", "name", ",", "dtype", ":", "dtype", ",", "output_type", ":", "output_type", ")", "end"], "docstring": "Creates a sequence of numbers.\n Creates a sequence of numbers that begins at start and extends by increments of delta up to but not including limit.\n\n\n @param start Acts as first entry in the range if limit is not nil; otherwise, acts as range limit and first entry defaults to 0.\n @param limit Upper limit of sequence, exclusive. If nil, defaults to the value of start while the first entry of the range defaults to 0.\n @param delta Number that increments start. Defaults to 1.\n\n Options:\n @option name A name for the operation. Defaults to \"range\". default (\"range\")\n @option dtype The type of the elements of the resulting tensor.\n @option output_type Output data type defaults to int32 default (:int32)\n @return Tensor", "docstring_tokens": ["Creates", "a", "sequence", "of", "numbers", ".", "Creates", "a", "sequence", "of", "numbers", "that", "begins", "at", "start", "and", "extends", "by", "increments", "of", "delta", "up", "to", "but", "not", "including", "limit", "."], "sha": "1be668620d86a12d4a2223502722d99968bdf854", "url": "https://github.com/jedld/tensor_stream/blob/1be668620d86a12d4a2223502722d99968bdf854/lib/tensor_stream/generated_stub/ops.rb#L487-L489", "partition": "test"} {"repo": "jedld/tensor_stream", "path": "lib/tensor_stream/generated_stub/ops.rb", "func_name": "TensorStream.OpStub.rank", "original_string": "def rank(input, name: nil)\n input = convert_to_tensor(input)\n return cons(input.shape.ndims) if input.shape.known?\n _op(:rank, input, name: name)\n end", "language": "ruby", "code": "def rank(input, name: nil)\n input = convert_to_tensor(input)\n return cons(input.shape.ndims) if input.shape.known?\n _op(:rank, input, name: name)\n end", "code_tokens": ["def", "rank", "(", "input", ",", "name", ":", "nil", ")", "input", "=", "convert_to_tensor", "(", "input", ")", "return", "cons", "(", "input", ".", "shape", ".", "ndims", ")", "if", "input", ".", "shape", ".", "known?", "_op", "(", ":rank", ",", "input", ",", "name", ":", "name", ")", "end"], "docstring": "Returns the rank of a tensor\n\n\n @param input A tensor\n\n Options:\n @option name Optional name\n @return Tensor", "docstring_tokens": ["Returns", "the", "rank", "of", "a", "tensor"], "sha": "1be668620d86a12d4a2223502722d99968bdf854", "url": "https://github.com/jedld/tensor_stream/blob/1be668620d86a12d4a2223502722d99968bdf854/lib/tensor_stream/generated_stub/ops.rb#L501-L505", "partition": "test"} {"repo": "jedld/tensor_stream", "path": "lib/tensor_stream/generated_stub/ops.rb", "func_name": "TensorStream.OpStub.round", "original_string": "def round(input_a, name: nil)\n check_allowed_types(input_a, TensorStream::Ops::FLOATING_POINT_TYPES)\n _op(:round, input_a, name: name)\n end", "language": "ruby", "code": "def round(input_a, name: nil)\n check_allowed_types(input_a, TensorStream::Ops::FLOATING_POINT_TYPES)\n _op(:round, input_a, name: name)\n end", "code_tokens": ["def", "round", "(", "input_a", ",", "name", ":", "nil", ")", "check_allowed_types", "(", "input_a", ",", "TensorStream", "::", "Ops", "::", "FLOATING_POINT_TYPES", ")", "_op", "(", ":round", ",", "input_a", ",", "name", ":", "name", ")", "end"], "docstring": "Rounds the values of a tensor to the nearest integer, element-wise\n\n\n @param input_a tensor X (of type FLOATING_POINT_TYPES)\n\n Options:\n @option name Optional name\n @return Tensor", "docstring_tokens": ["Rounds", "the", "values", "of", "a", "tensor", "to", "the", "nearest", "integer", "element", "-", "wise"], "sha": "1be668620d86a12d4a2223502722d99968bdf854", "url": "https://github.com/jedld/tensor_stream/blob/1be668620d86a12d4a2223502722d99968bdf854/lib/tensor_stream/generated_stub/ops.rb#L533-L536", "partition": "test"} {"repo": "jedld/tensor_stream", "path": "lib/tensor_stream/generated_stub/ops.rb", "func_name": "TensorStream.OpStub.rsqrt", "original_string": "def rsqrt(input_a, name: nil)\n check_allowed_types(input_a, TensorStream::Ops::FLOATING_POINT_TYPES)\n _op(:rsqrt, input_a, name: name)\n end", "language": "ruby", "code": "def rsqrt(input_a, name: nil)\n check_allowed_types(input_a, TensorStream::Ops::FLOATING_POINT_TYPES)\n _op(:rsqrt, input_a, name: name)\n end", "code_tokens": ["def", "rsqrt", "(", "input_a", ",", "name", ":", "nil", ")", "check_allowed_types", "(", "input_a", ",", "TensorStream", "::", "Ops", "::", "FLOATING_POINT_TYPES", ")", "_op", "(", ":rsqrt", ",", "input_a", ",", "name", ":", "name", ")", "end"], "docstring": "Computes reciprocal of square root of x element-wise.\n\n\n @param input_a tensor X (of type FLOATING_POINT_TYPES)\n\n Options:\n @option name Optional name\n @return Tensor", "docstring_tokens": ["Computes", "reciprocal", "of", "square", "root", "of", "x", "element", "-", "wise", "."], "sha": "1be668620d86a12d4a2223502722d99968bdf854", "url": "https://github.com/jedld/tensor_stream/blob/1be668620d86a12d4a2223502722d99968bdf854/lib/tensor_stream/generated_stub/ops.rb#L548-L551", "partition": "test"} {"repo": "jedld/tensor_stream", "path": "lib/tensor_stream/generated_stub/ops.rb", "func_name": "TensorStream.OpStub.shape", "original_string": "def shape(input, name: nil, out_type: :int32)\n return constant(shape_eval(input, out_type), dtype: out_type, name: \"Shape/#{name}\") if input.is_a?(Array) && !input[0].is_a?(Tensor)\n return constant(input.shape.shape, dtype: out_type, name: \"Shape/#{input.name}_c\") if shape_full_specified(input)\n _op(:shape, input, name: name, out_type: out_type)\n end", "language": "ruby", "code": "def shape(input, name: nil, out_type: :int32)\n return constant(shape_eval(input, out_type), dtype: out_type, name: \"Shape/#{name}\") if input.is_a?(Array) && !input[0].is_a?(Tensor)\n return constant(input.shape.shape, dtype: out_type, name: \"Shape/#{input.name}_c\") if shape_full_specified(input)\n _op(:shape, input, name: name, out_type: out_type)\n end", "code_tokens": ["def", "shape", "(", "input", ",", "name", ":", "nil", ",", "out_type", ":", ":int32", ")", "return", "constant", "(", "shape_eval", "(", "input", ",", "out_type", ")", ",", "dtype", ":", "out_type", ",", "name", ":", "\"Shape/#{name}\"", ")", "if", "input", ".", "is_a?", "(", "Array", ")", "&&", "!", "input", "[", "0", "]", ".", "is_a?", "(", "Tensor", ")", "return", "constant", "(", "input", ".", "shape", ".", "shape", ",", "dtype", ":", "out_type", ",", "name", ":", "\"Shape/#{input.name}_c\"", ")", "if", "shape_full_specified", "(", "input", ")", "_op", "(", ":shape", ",", "input", ",", "name", ":", "name", ",", "out_type", ":", "out_type", ")", "end"], "docstring": "This operation returns a 1-D integer tensor representing the shape of input\n\n\n @param input A tensor\n\n Options:\n @option name Optional name\n @option out_type Optional output type default (:int32)\n @return Tensor", "docstring_tokens": ["This", "operation", "returns", "a", "1", "-", "D", "integer", "tensor", "representing", "the", "shape", "of", "input"], "sha": "1be668620d86a12d4a2223502722d99968bdf854", "url": "https://github.com/jedld/tensor_stream/blob/1be668620d86a12d4a2223502722d99968bdf854/lib/tensor_stream/generated_stub/ops.rb#L564-L568", "partition": "test"} {"repo": "jedld/tensor_stream", "path": "lib/tensor_stream/generated_stub/ops.rb", "func_name": "TensorStream.OpStub.sigmoid", "original_string": "def sigmoid(input_a, name: nil)\n check_allowed_types(input_a, TensorStream::Ops::FLOATING_POINT_TYPES)\n _op(:sigmoid, input_a, name: name)\n end", "language": "ruby", "code": "def sigmoid(input_a, name: nil)\n check_allowed_types(input_a, TensorStream::Ops::FLOATING_POINT_TYPES)\n _op(:sigmoid, input_a, name: name)\n end", "code_tokens": ["def", "sigmoid", "(", "input_a", ",", "name", ":", "nil", ")", "check_allowed_types", "(", "input_a", ",", "TensorStream", "::", "Ops", "::", "FLOATING_POINT_TYPES", ")", "_op", "(", ":sigmoid", ",", "input_a", ",", "name", ":", "name", ")", "end"], "docstring": "Computes sigmoid of x element-wise.\n\n\n @param input_a tensor X (of type FLOATING_POINT_TYPES)\n\n Options:\n @option name Optional name\n @return Tensor", "docstring_tokens": ["Computes", "sigmoid", "of", "x", "element", "-", "wise", "."], "sha": "1be668620d86a12d4a2223502722d99968bdf854", "url": "https://github.com/jedld/tensor_stream/blob/1be668620d86a12d4a2223502722d99968bdf854/lib/tensor_stream/generated_stub/ops.rb#L580-L583", "partition": "test"} {"repo": "jedld/tensor_stream", "path": "lib/tensor_stream/generated_stub/ops.rb", "func_name": "TensorStream.OpStub.sin", "original_string": "def sin(input_a, name: nil)\n check_allowed_types(input_a, TensorStream::Ops::FLOATING_POINT_TYPES)\n _op(:sin, input_a, name: name)\n end", "language": "ruby", "code": "def sin(input_a, name: nil)\n check_allowed_types(input_a, TensorStream::Ops::FLOATING_POINT_TYPES)\n _op(:sin, input_a, name: name)\n end", "code_tokens": ["def", "sin", "(", "input_a", ",", "name", ":", "nil", ")", "check_allowed_types", "(", "input_a", ",", "TensorStream", "::", "Ops", "::", "FLOATING_POINT_TYPES", ")", "_op", "(", ":sin", ",", "input_a", ",", "name", ":", "name", ")", "end"], "docstring": "Computes sin of input element-wise.\n\n\n @param input_a tensor X (of type FLOATING_POINT_TYPES)\n\n Options:\n @option name Optional name\n @return Tensor", "docstring_tokens": ["Computes", "sin", "of", "input", "element", "-", "wise", "."], "sha": "1be668620d86a12d4a2223502722d99968bdf854", "url": "https://github.com/jedld/tensor_stream/blob/1be668620d86a12d4a2223502722d99968bdf854/lib/tensor_stream/generated_stub/ops.rb#L611-L614", "partition": "test"} {"repo": "jedld/tensor_stream", "path": "lib/tensor_stream/generated_stub/ops.rb", "func_name": "TensorStream.OpStub.sub", "original_string": "def sub(input_a, input_b, name: nil)\n input_a, input_b = apply_data_type_coercion(input_a, input_b)\n _op(:sub, input_a, input_b, name: name)\n end", "language": "ruby", "code": "def sub(input_a, input_b, name: nil)\n input_a, input_b = apply_data_type_coercion(input_a, input_b)\n _op(:sub, input_a, input_b, name: name)\n end", "code_tokens": ["def", "sub", "(", "input_a", ",", "input_b", ",", "name", ":", "nil", ")", "input_a", ",", "input_b", "=", "apply_data_type_coercion", "(", "input_a", ",", "input_b", ")", "_op", "(", ":sub", ",", "input_a", ",", "input_b", ",", "name", ":", "name", ")", "end"], "docstring": "Returns x - y element-wise.\n\n This operation supports broadcasting\n\n @param input_a tensor X\n @param input_b tensor Y\n\n Options:\n @option name Optional name\n @return Tensor", "docstring_tokens": ["Returns", "x", "-", "y", "element", "-", "wise", "."], "sha": "1be668620d86a12d4a2223502722d99968bdf854", "url": "https://github.com/jedld/tensor_stream/blob/1be668620d86a12d4a2223502722d99968bdf854/lib/tensor_stream/generated_stub/ops.rb#L666-L669", "partition": "test"} {"repo": "jedld/tensor_stream", "path": "lib/tensor_stream/generated_stub/ops.rb", "func_name": "TensorStream.OpStub.sum", "original_string": "def sum(input_a, axis_p = nil, axis: nil, name: nil, keepdims: false)\n check_allowed_types(axis_p, TensorStream::Ops::INTEGER_TYPES)\n input_a = TensorStream.convert_to_tensor(input_a)\n return input_a if input_a.shape.scalar?\n axis_p = axis_p || axis\n axis_p = cast_axis(input_a, axis_p)\n _op(:sum, input_a, axis_p, name: name, keepdims: keepdims)\n end", "language": "ruby", "code": "def sum(input_a, axis_p = nil, axis: nil, name: nil, keepdims: false)\n check_allowed_types(axis_p, TensorStream::Ops::INTEGER_TYPES)\n input_a = TensorStream.convert_to_tensor(input_a)\n return input_a if input_a.shape.scalar?\n axis_p = axis_p || axis\n axis_p = cast_axis(input_a, axis_p)\n _op(:sum, input_a, axis_p, name: name, keepdims: keepdims)\n end", "code_tokens": ["def", "sum", "(", "input_a", ",", "axis_p", "=", "nil", ",", "axis", ":", "nil", ",", "name", ":", "nil", ",", "keepdims", ":", "false", ")", "check_allowed_types", "(", "axis_p", ",", "TensorStream", "::", "Ops", "::", "INTEGER_TYPES", ")", "input_a", "=", "TensorStream", ".", "convert_to_tensor", "(", "input_a", ")", "return", "input_a", "if", "input_a", ".", "shape", ".", "scalar?", "axis_p", "=", "axis_p", "||", "axis", "axis_p", "=", "cast_axis", "(", "input_a", ",", "axis_p", ")", "_op", "(", ":sum", ",", "input_a", ",", "axis_p", ",", "name", ":", "name", ",", "keepdims", ":", "keepdims", ")", "end"], "docstring": "Computes the sum of elements across dimensions of a tensor.\n Reduces input_tensor along the dimensions given in axis. Unless keepdims is true, the rank of the\n tensor is reduced by 1 for each entry in axis. If keepdims is true, the reduced dimensions are\n retained with length 1.\n If axis has no entries, all dimensions are reduced, and a tensor with a single element is returned.\n\n\n @param input_a tensor X\n @param axis_p tensor X (of type INTEGER_TYPES)\n\n Options:\n @option axis axis\n @option name Optional name\n @option keepdims If true, retains reduced dimensions with length 1. default (false)\n @return Tensor", "docstring_tokens": ["Computes", "the", "sum", "of", "elements", "across", "dimensions", "of", "a", "tensor", ".", "Reduces", "input_tensor", "along", "the", "dimensions", "given", "in", "axis", ".", "Unless", "keepdims", "is", "true", "the", "rank", "of", "the", "tensor", "is", "reduced", "by", "1", "for", "each", "entry", "in", "axis", ".", "If", "keepdims", "is", "true", "the", "reduced", "dimensions", "are", "retained", "with", "length", "1", ".", "If", "axis", "has", "no", "entries", "all", "dimensions", "are", "reduced", "and", "a", "tensor", "with", "a", "single", "element", "is", "returned", "."], "sha": "1be668620d86a12d4a2223502722d99968bdf854", "url": "https://github.com/jedld/tensor_stream/blob/1be668620d86a12d4a2223502722d99968bdf854/lib/tensor_stream/generated_stub/ops.rb#L689-L696", "partition": "test"} {"repo": "jedld/tensor_stream", "path": "lib/tensor_stream/generated_stub/ops.rb", "func_name": "TensorStream.OpStub.tan", "original_string": "def tan(input_a, name: nil)\n check_allowed_types(input_a, TensorStream::Ops::FLOATING_POINT_TYPES)\n _op(:tan, input_a, name: name)\n end", "language": "ruby", "code": "def tan(input_a, name: nil)\n check_allowed_types(input_a, TensorStream::Ops::FLOATING_POINT_TYPES)\n _op(:tan, input_a, name: name)\n end", "code_tokens": ["def", "tan", "(", "input_a", ",", "name", ":", "nil", ")", "check_allowed_types", "(", "input_a", ",", "TensorStream", "::", "Ops", "::", "FLOATING_POINT_TYPES", ")", "_op", "(", ":tan", ",", "input_a", ",", "name", ":", "name", ")", "end"], "docstring": "Computes tan of input element-wise.\n\n\n @param input_a tensor X (of type FLOATING_POINT_TYPES)\n\n Options:\n @option name Optional name\n @return Tensor", "docstring_tokens": ["Computes", "tan", "of", "input", "element", "-", "wise", "."], "sha": "1be668620d86a12d4a2223502722d99968bdf854", "url": "https://github.com/jedld/tensor_stream/blob/1be668620d86a12d4a2223502722d99968bdf854/lib/tensor_stream/generated_stub/ops.rb#L709-L712", "partition": "test"} {"repo": "jedld/tensor_stream", "path": "lib/tensor_stream/generated_stub/ops.rb", "func_name": "TensorStream.OpStub.tanh", "original_string": "def tanh(input_a, name: nil)\n check_allowed_types(input_a, TensorStream::Ops::FLOATING_POINT_TYPES)\n _op(:tanh, input_a, name: name)\n end", "language": "ruby", "code": "def tanh(input_a, name: nil)\n check_allowed_types(input_a, TensorStream::Ops::FLOATING_POINT_TYPES)\n _op(:tanh, input_a, name: name)\n end", "code_tokens": ["def", "tanh", "(", "input_a", ",", "name", ":", "nil", ")", "check_allowed_types", "(", "input_a", ",", "TensorStream", "::", "Ops", "::", "FLOATING_POINT_TYPES", ")", "_op", "(", ":tanh", ",", "input_a", ",", "name", ":", "name", ")", "end"], "docstring": "Computes tanh of input element-wise.\n\n\n @param input_a tensor X (of type FLOATING_POINT_TYPES)\n\n Options:\n @option name Optional name\n @return Tensor", "docstring_tokens": ["Computes", "tanh", "of", "input", "element", "-", "wise", "."], "sha": "1be668620d86a12d4a2223502722d99968bdf854", "url": "https://github.com/jedld/tensor_stream/blob/1be668620d86a12d4a2223502722d99968bdf854/lib/tensor_stream/generated_stub/ops.rb#L724-L727", "partition": "test"} {"repo": "jedld/tensor_stream", "path": "lib/tensor_stream/generated_stub/ops.rb", "func_name": "TensorStream.OpStub.top_k", "original_string": "def top_k(input, k = 1, sorted: true, name: nil)\n result = _op(:top_k, input, k, sorted: sorted, name: name)\n [result[0], result[1]]\n end", "language": "ruby", "code": "def top_k(input, k = 1, sorted: true, name: nil)\n result = _op(:top_k, input, k, sorted: sorted, name: name)\n [result[0], result[1]]\n end", "code_tokens": ["def", "top_k", "(", "input", ",", "k", "=", "1", ",", "sorted", ":", "true", ",", "name", ":", "nil", ")", "result", "=", "_op", "(", ":top_k", ",", "input", ",", "k", ",", "sorted", ":", "sorted", ",", "name", ":", "name", ")", "[", "result", "[", "0", "]", ",", "result", "[", "1", "]", "]", "end"], "docstring": "Finds values and indices of the `k` largest entries for the last dimension.\n\n\n @param input 1-D or higher `Tensor` with last dimension at least `k`.\n @param k 0-D `int32` `Tensor`. Number of top elements to look for along the last dimension (along each row for matrices)\n\n Options:\n @option sorted If true the resulting `k` elements will be sorted by the values in descending order. default (true)\n @option name Optional name\n @return Tensor", "docstring_tokens": ["Finds", "values", "and", "indices", "of", "the", "k", "largest", "entries", "for", "the", "last", "dimension", "."], "sha": "1be668620d86a12d4a2223502722d99968bdf854", "url": "https://github.com/jedld/tensor_stream/blob/1be668620d86a12d4a2223502722d99968bdf854/lib/tensor_stream/generated_stub/ops.rb#L759-L762", "partition": "test"} {"repo": "jedld/tensor_stream", "path": "lib/tensor_stream/generated_stub/ops.rb", "func_name": "TensorStream.OpStub.zeros", "original_string": "def zeros(shape, dtype: :float32, name: nil)\n _op(:zeros, shape, dtype: dtype, name: name)\n end", "language": "ruby", "code": "def zeros(shape, dtype: :float32, name: nil)\n _op(:zeros, shape, dtype: dtype, name: name)\n end", "code_tokens": ["def", "zeros", "(", "shape", ",", "dtype", ":", ":float32", ",", "name", ":", "nil", ")", "_op", "(", ":zeros", ",", "shape", ",", "dtype", ":", "dtype", ",", "name", ":", "name", ")", "end"], "docstring": "Creates a tensor with all elements set to zero\n\n\n @param shape A 1-D integer Tensor or ruby array. The shape of the output tensor.\n\n Options:\n @option dtype Optional name default (:float32)\n @option name Optional name\n @return Tensor", "docstring_tokens": ["Creates", "a", "tensor", "with", "all", "elements", "set", "to", "zero"], "sha": "1be668620d86a12d4a2223502722d99968bdf854", "url": "https://github.com/jedld/tensor_stream/blob/1be668620d86a12d4a2223502722d99968bdf854/lib/tensor_stream/generated_stub/ops.rb#L775-L777", "partition": "test"} {"repo": "jedld/tensor_stream", "path": "lib/tensor_stream/utils/freezer.rb", "func_name": "TensorStream.Freezer.convert", "original_string": "def convert(session, checkpoint_folder, output_file)\n model_file = File.join(checkpoint_folder, \"model.yaml\")\n TensorStream.graph.as_default do |current_graph|\n YamlLoader.new.load_from_string(File.read(model_file))\n saver = TensorStream::Train::Saver.new\n saver.restore(session, checkpoint_folder)\n\n # collect all assign ops and remove them from the graph\n remove_nodes = Set.new(current_graph.nodes.values.select { |op| op.is_a?(TensorStream::Operation) && op.operation == :assign }.map { |op| op.consumers.to_a }.flatten.uniq)\n\n output_buffer = TensorStream::Yaml.new.get_string(current_graph) { |graph, node_key|\n node = graph.get_tensor_by_name(node_key)\n case node.operation\n when :variable_v2\n value = node.container\n options = {\n value: value,\n data_type: node.data_type,\n shape: shape_eval(value),\n }\n const_op = TensorStream::Operation.new(current_graph, inputs: [], options: options)\n const_op.name = node.name\n const_op.operation = :const\n const_op.data_type = node.data_type\n const_op.shape = TensorShape.new(shape_eval(value))\n\n const_op\n when :assign\n nil\n else\n remove_nodes.include?(node.name) ? nil : node\n end\n }\n File.write(output_file, output_buffer)\n end\n end", "language": "ruby", "code": "def convert(session, checkpoint_folder, output_file)\n model_file = File.join(checkpoint_folder, \"model.yaml\")\n TensorStream.graph.as_default do |current_graph|\n YamlLoader.new.load_from_string(File.read(model_file))\n saver = TensorStream::Train::Saver.new\n saver.restore(session, checkpoint_folder)\n\n # collect all assign ops and remove them from the graph\n remove_nodes = Set.new(current_graph.nodes.values.select { |op| op.is_a?(TensorStream::Operation) && op.operation == :assign }.map { |op| op.consumers.to_a }.flatten.uniq)\n\n output_buffer = TensorStream::Yaml.new.get_string(current_graph) { |graph, node_key|\n node = graph.get_tensor_by_name(node_key)\n case node.operation\n when :variable_v2\n value = node.container\n options = {\n value: value,\n data_type: node.data_type,\n shape: shape_eval(value),\n }\n const_op = TensorStream::Operation.new(current_graph, inputs: [], options: options)\n const_op.name = node.name\n const_op.operation = :const\n const_op.data_type = node.data_type\n const_op.shape = TensorShape.new(shape_eval(value))\n\n const_op\n when :assign\n nil\n else\n remove_nodes.include?(node.name) ? nil : node\n end\n }\n File.write(output_file, output_buffer)\n end\n end", "code_tokens": ["def", "convert", "(", "session", ",", "checkpoint_folder", ",", "output_file", ")", "model_file", "=", "File", ".", "join", "(", "checkpoint_folder", ",", "\"model.yaml\"", ")", "TensorStream", ".", "graph", ".", "as_default", "do", "|", "current_graph", "|", "YamlLoader", ".", "new", ".", "load_from_string", "(", "File", ".", "read", "(", "model_file", ")", ")", "saver", "=", "TensorStream", "::", "Train", "::", "Saver", ".", "new", "saver", ".", "restore", "(", "session", ",", "checkpoint_folder", ")", "# collect all assign ops and remove them from the graph", "remove_nodes", "=", "Set", ".", "new", "(", "current_graph", ".", "nodes", ".", "values", ".", "select", "{", "|", "op", "|", "op", ".", "is_a?", "(", "TensorStream", "::", "Operation", ")", "&&", "op", ".", "operation", "==", ":assign", "}", ".", "map", "{", "|", "op", "|", "op", ".", "consumers", ".", "to_a", "}", ".", "flatten", ".", "uniq", ")", "output_buffer", "=", "TensorStream", "::", "Yaml", ".", "new", ".", "get_string", "(", "current_graph", ")", "{", "|", "graph", ",", "node_key", "|", "node", "=", "graph", ".", "get_tensor_by_name", "(", "node_key", ")", "case", "node", ".", "operation", "when", ":variable_v2", "value", "=", "node", ".", "container", "options", "=", "{", "value", ":", "value", ",", "data_type", ":", "node", ".", "data_type", ",", "shape", ":", "shape_eval", "(", "value", ")", ",", "}", "const_op", "=", "TensorStream", "::", "Operation", ".", "new", "(", "current_graph", ",", "inputs", ":", "[", "]", ",", "options", ":", "options", ")", "const_op", ".", "name", "=", "node", ".", "name", "const_op", ".", "operation", "=", ":const", "const_op", ".", "data_type", "=", "node", ".", "data_type", "const_op", ".", "shape", "=", "TensorShape", ".", "new", "(", "shape_eval", "(", "value", ")", ")", "const_op", "when", ":assign", "nil", "else", "remove_nodes", ".", "include?", "(", "node", ".", "name", ")", "?", "nil", ":", "node", "end", "}", "File", ".", "write", "(", "output_file", ",", "output_buffer", ")", "end", "end"], "docstring": "Utility class to convert variables to constants for production deployment", "docstring_tokens": ["Utility", "class", "to", "convert", "variables", "to", "constants", "for", "production", "deployment"], "sha": "1be668620d86a12d4a2223502722d99968bdf854", "url": "https://github.com/jedld/tensor_stream/blob/1be668620d86a12d4a2223502722d99968bdf854/lib/tensor_stream/utils/freezer.rb#L8-L43", "partition": "test"} {"repo": "jedld/tensor_stream", "path": "lib/tensor_stream/graph.rb", "func_name": "TensorStream.Graph.device", "original_string": "def device(device_name)\n Thread.current[\"ts_graph_#{object_id}\"] ||= {}\n Thread.current[\"ts_graph_#{object_id}\"][:default_device] ||= []\n Thread.current[\"ts_graph_#{object_id}\"][:default_device] << device_name\n begin\n yield\n ensure\n Thread.current[\"ts_graph_#{object_id}\"][:default_device].pop\n end\n end", "language": "ruby", "code": "def device(device_name)\n Thread.current[\"ts_graph_#{object_id}\"] ||= {}\n Thread.current[\"ts_graph_#{object_id}\"][:default_device] ||= []\n Thread.current[\"ts_graph_#{object_id}\"][:default_device] << device_name\n begin\n yield\n ensure\n Thread.current[\"ts_graph_#{object_id}\"][:default_device].pop\n end\n end", "code_tokens": ["def", "device", "(", "device_name", ")", "Thread", ".", "current", "[", "\"ts_graph_#{object_id}\"", "]", "||=", "{", "}", "Thread", ".", "current", "[", "\"ts_graph_#{object_id}\"", "]", "[", ":default_device", "]", "||=", "[", "]", "Thread", ".", "current", "[", "\"ts_graph_#{object_id}\"", "]", "[", ":default_device", "]", "<<", "device_name", "begin", "yield", "ensure", "Thread", ".", "current", "[", "\"ts_graph_#{object_id}\"", "]", "[", ":default_device", "]", ".", "pop", "end", "end"], "docstring": "Returns a context manager that specifies the default device to use.", "docstring_tokens": ["Returns", "a", "context", "manager", "that", "specifies", "the", "default", "device", "to", "use", "."], "sha": "1be668620d86a12d4a2223502722d99968bdf854", "url": "https://github.com/jedld/tensor_stream/blob/1be668620d86a12d4a2223502722d99968bdf854/lib/tensor_stream/graph.rb#L59-L68", "partition": "test"} {"repo": "jedld/tensor_stream", "path": "lib/tensor_stream/graph_deserializers/yaml_loader.rb", "func_name": "TensorStream.YamlLoader.load_from_string", "original_string": "def load_from_string(buffer)\n serialized_ops = YAML.safe_load(buffer, [Symbol], [], true)\n serialized_ops.each do |op_def|\n inputs = op_def[:inputs].map { |i| @graph.get_tensor_by_name(i) }\n options = {}\n\n new_var = nil\n if op_def.dig(:attrs, :container)\n new_var = Variable.new(op_def.dig(:attrs, :data_type))\n var_shape = op_def.dig(:attrs, :container, :shape)\n var_options = op_def.dig(:attrs, :container, :options)\n var_options[:name] = op_def[:name]\n\n new_var.prepare(var_shape.size, var_shape, TensorStream.get_variable_scope, var_options)\n options[:container] = new_var\n\n @graph.add_variable(new_var, var_options)\n end\n\n new_op = Operation.new(@graph, inputs: inputs, options: op_def[:attrs].merge(options))\n new_op.operation = op_def[:op].to_sym\n new_op.name = op_def[:name]\n new_op.shape = TensorShape.new(TensorStream::InferShape.infer_shape(new_op))\n new_op.rank = new_op.shape.rank\n new_op.data_type = new_op.set_data_type(op_def.dig(:attrs, :data_type))\n new_op.is_const = new_op.infer_const\n new_op.given_name = new_op.name\n new_var.op = new_op if new_var\n\n @graph.add_node(new_op)\n end\n @graph\n end", "language": "ruby", "code": "def load_from_string(buffer)\n serialized_ops = YAML.safe_load(buffer, [Symbol], [], true)\n serialized_ops.each do |op_def|\n inputs = op_def[:inputs].map { |i| @graph.get_tensor_by_name(i) }\n options = {}\n\n new_var = nil\n if op_def.dig(:attrs, :container)\n new_var = Variable.new(op_def.dig(:attrs, :data_type))\n var_shape = op_def.dig(:attrs, :container, :shape)\n var_options = op_def.dig(:attrs, :container, :options)\n var_options[:name] = op_def[:name]\n\n new_var.prepare(var_shape.size, var_shape, TensorStream.get_variable_scope, var_options)\n options[:container] = new_var\n\n @graph.add_variable(new_var, var_options)\n end\n\n new_op = Operation.new(@graph, inputs: inputs, options: op_def[:attrs].merge(options))\n new_op.operation = op_def[:op].to_sym\n new_op.name = op_def[:name]\n new_op.shape = TensorShape.new(TensorStream::InferShape.infer_shape(new_op))\n new_op.rank = new_op.shape.rank\n new_op.data_type = new_op.set_data_type(op_def.dig(:attrs, :data_type))\n new_op.is_const = new_op.infer_const\n new_op.given_name = new_op.name\n new_var.op = new_op if new_var\n\n @graph.add_node(new_op)\n end\n @graph\n end", "code_tokens": ["def", "load_from_string", "(", "buffer", ")", "serialized_ops", "=", "YAML", ".", "safe_load", "(", "buffer", ",", "[", "Symbol", "]", ",", "[", "]", ",", "true", ")", "serialized_ops", ".", "each", "do", "|", "op_def", "|", "inputs", "=", "op_def", "[", ":inputs", "]", ".", "map", "{", "|", "i", "|", "@graph", ".", "get_tensor_by_name", "(", "i", ")", "}", "options", "=", "{", "}", "new_var", "=", "nil", "if", "op_def", ".", "dig", "(", ":attrs", ",", ":container", ")", "new_var", "=", "Variable", ".", "new", "(", "op_def", ".", "dig", "(", ":attrs", ",", ":data_type", ")", ")", "var_shape", "=", "op_def", ".", "dig", "(", ":attrs", ",", ":container", ",", ":shape", ")", "var_options", "=", "op_def", ".", "dig", "(", ":attrs", ",", ":container", ",", ":options", ")", "var_options", "[", ":name", "]", "=", "op_def", "[", ":name", "]", "new_var", ".", "prepare", "(", "var_shape", ".", "size", ",", "var_shape", ",", "TensorStream", ".", "get_variable_scope", ",", "var_options", ")", "options", "[", ":container", "]", "=", "new_var", "@graph", ".", "add_variable", "(", "new_var", ",", "var_options", ")", "end", "new_op", "=", "Operation", ".", "new", "(", "@graph", ",", "inputs", ":", "inputs", ",", "options", ":", "op_def", "[", ":attrs", "]", ".", "merge", "(", "options", ")", ")", "new_op", ".", "operation", "=", "op_def", "[", ":op", "]", ".", "to_sym", "new_op", ".", "name", "=", "op_def", "[", ":name", "]", "new_op", ".", "shape", "=", "TensorShape", ".", "new", "(", "TensorStream", "::", "InferShape", ".", "infer_shape", "(", "new_op", ")", ")", "new_op", ".", "rank", "=", "new_op", ".", "shape", ".", "rank", "new_op", ".", "data_type", "=", "new_op", ".", "set_data_type", "(", "op_def", ".", "dig", "(", ":attrs", ",", ":data_type", ")", ")", "new_op", ".", "is_const", "=", "new_op", ".", "infer_const", "new_op", ".", "given_name", "=", "new_op", ".", "name", "new_var", ".", "op", "=", "new_op", "if", "new_var", "@graph", ".", "add_node", "(", "new_op", ")", "end", "@graph", "end"], "docstring": "Loads a model Yaml file and builds the model from it\n\n Args:\n buffer: String - String in Yaml format of the model\n\n Returns: Graph where model is restored to", "docstring_tokens": ["Loads", "a", "model", "Yaml", "file", "and", "builds", "the", "model", "from", "it"], "sha": "1be668620d86a12d4a2223502722d99968bdf854", "url": "https://github.com/jedld/tensor_stream/blob/1be668620d86a12d4a2223502722d99968bdf854/lib/tensor_stream/graph_deserializers/yaml_loader.rb#L27-L59", "partition": "test"} {"repo": "jedld/tensor_stream", "path": "lib/tensor_stream/utils.rb", "func_name": "TensorStream.Utils.variable", "original_string": "def variable(value, name: nil, initializer: nil, graph: nil, dtype: nil, trainable: true)\n op = Graph.get_default_graph.add_op(:assign, nil, value)\n common_options = {\n initializer: initializer || op,\n name: name,\n graph: graph,\n dtype: dtype,\n trainable: trainable,\n }\n tensor = if value.is_a?(String)\n i_var(dtype || :string, 0, [], get_variable_scope, common_options)\n elsif value.is_a?(Integer)\n i_var(dtype || :int32, 0, [], get_variable_scope, common_options)\n elsif value.is_a?(Float)\n i_var(dtype || :float32, 0, [], get_variable_scope, common_options)\n else\n i_var(dtype || :float32, 0, nil, get_variable_scope, common_options)\n end\n op.set_input(0, tensor.op)\n Graph.get_default_graph.add_node(op)\n tensor\n end", "language": "ruby", "code": "def variable(value, name: nil, initializer: nil, graph: nil, dtype: nil, trainable: true)\n op = Graph.get_default_graph.add_op(:assign, nil, value)\n common_options = {\n initializer: initializer || op,\n name: name,\n graph: graph,\n dtype: dtype,\n trainable: trainable,\n }\n tensor = if value.is_a?(String)\n i_var(dtype || :string, 0, [], get_variable_scope, common_options)\n elsif value.is_a?(Integer)\n i_var(dtype || :int32, 0, [], get_variable_scope, common_options)\n elsif value.is_a?(Float)\n i_var(dtype || :float32, 0, [], get_variable_scope, common_options)\n else\n i_var(dtype || :float32, 0, nil, get_variable_scope, common_options)\n end\n op.set_input(0, tensor.op)\n Graph.get_default_graph.add_node(op)\n tensor\n end", "code_tokens": ["def", "variable", "(", "value", ",", "name", ":", "nil", ",", "initializer", ":", "nil", ",", "graph", ":", "nil", ",", "dtype", ":", "nil", ",", "trainable", ":", "true", ")", "op", "=", "Graph", ".", "get_default_graph", ".", "add_op", "(", ":assign", ",", "nil", ",", "value", ")", "common_options", "=", "{", "initializer", ":", "initializer", "||", "op", ",", "name", ":", "name", ",", "graph", ":", "graph", ",", "dtype", ":", "dtype", ",", "trainable", ":", "trainable", ",", "}", "tensor", "=", "if", "value", ".", "is_a?", "(", "String", ")", "i_var", "(", "dtype", "||", ":string", ",", "0", ",", "[", "]", ",", "get_variable_scope", ",", "common_options", ")", "elsif", "value", ".", "is_a?", "(", "Integer", ")", "i_var", "(", "dtype", "||", ":int32", ",", "0", ",", "[", "]", ",", "get_variable_scope", ",", "common_options", ")", "elsif", "value", ".", "is_a?", "(", "Float", ")", "i_var", "(", "dtype", "||", ":float32", ",", "0", ",", "[", "]", ",", "get_variable_scope", ",", "common_options", ")", "else", "i_var", "(", "dtype", "||", ":float32", ",", "0", ",", "nil", ",", "get_variable_scope", ",", "common_options", ")", "end", "op", ".", "set_input", "(", "0", ",", "tensor", ".", "op", ")", "Graph", ".", "get_default_graph", ".", "add_node", "(", "op", ")", "tensor", "end"], "docstring": "Creates a variable\n A variable maintains state across sessions", "docstring_tokens": ["Creates", "a", "variable", "A", "variable", "maintains", "state", "across", "sessions"], "sha": "1be668620d86a12d4a2223502722d99968bdf854", "url": "https://github.com/jedld/tensor_stream/blob/1be668620d86a12d4a2223502722d99968bdf854/lib/tensor_stream/utils.rb#L47-L68", "partition": "test"} {"repo": "jedld/tensor_stream", "path": "lib/tensor_stream/utils.rb", "func_name": "TensorStream.Utils.variable_scope", "original_string": "def variable_scope(scope = nil, default_name = nil, reuse: nil, initializer: nil)\n Thread.current[:tensor_stream_variable_scope] ||= [VariableScope.new]\n\n # uniquenifier\n if scope.nil? && default_name\n same_names = get_variable_scope.used_names.select { |s| s.start_with?(default_name) }\n new_name = default_name\n index = 1\n while same_names.include?(new_name)\n new_name = \"#{default_name}_#{index}\"\n index += 1\n end\n scope = new_name\n end\n\n variable_scope = VariableScope.new(name: scope, reuse: reuse, initializer: initializer)\n get_variable_scope.register_name(scope || \"\")\n Thread.current[:tensor_stream_variable_scope] << variable_scope\n scope_name = __v_scope_name\n if block_given?\n begin\n TensorStream.get_default_graph.name_scope(scope) do\n yield(scope_name)\n end\n ensure\n Thread.current[:tensor_stream_variable_scope].pop\n end\n else\n variable_scope\n end\n end", "language": "ruby", "code": "def variable_scope(scope = nil, default_name = nil, reuse: nil, initializer: nil)\n Thread.current[:tensor_stream_variable_scope] ||= [VariableScope.new]\n\n # uniquenifier\n if scope.nil? && default_name\n same_names = get_variable_scope.used_names.select { |s| s.start_with?(default_name) }\n new_name = default_name\n index = 1\n while same_names.include?(new_name)\n new_name = \"#{default_name}_#{index}\"\n index += 1\n end\n scope = new_name\n end\n\n variable_scope = VariableScope.new(name: scope, reuse: reuse, initializer: initializer)\n get_variable_scope.register_name(scope || \"\")\n Thread.current[:tensor_stream_variable_scope] << variable_scope\n scope_name = __v_scope_name\n if block_given?\n begin\n TensorStream.get_default_graph.name_scope(scope) do\n yield(scope_name)\n end\n ensure\n Thread.current[:tensor_stream_variable_scope].pop\n end\n else\n variable_scope\n end\n end", "code_tokens": ["def", "variable_scope", "(", "scope", "=", "nil", ",", "default_name", "=", "nil", ",", "reuse", ":", "nil", ",", "initializer", ":", "nil", ")", "Thread", ".", "current", "[", ":tensor_stream_variable_scope", "]", "||=", "[", "VariableScope", ".", "new", "]", "# uniquenifier", "if", "scope", ".", "nil?", "&&", "default_name", "same_names", "=", "get_variable_scope", ".", "used_names", ".", "select", "{", "|", "s", "|", "s", ".", "start_with?", "(", "default_name", ")", "}", "new_name", "=", "default_name", "index", "=", "1", "while", "same_names", ".", "include?", "(", "new_name", ")", "new_name", "=", "\"#{default_name}_#{index}\"", "index", "+=", "1", "end", "scope", "=", "new_name", "end", "variable_scope", "=", "VariableScope", ".", "new", "(", "name", ":", "scope", ",", "reuse", ":", "reuse", ",", "initializer", ":", "initializer", ")", "get_variable_scope", ".", "register_name", "(", "scope", "||", "\"\"", ")", "Thread", ".", "current", "[", ":tensor_stream_variable_scope", "]", "<<", "variable_scope", "scope_name", "=", "__v_scope_name", "if", "block_given?", "begin", "TensorStream", ".", "get_default_graph", ".", "name_scope", "(", "scope", ")", "do", "yield", "(", "scope_name", ")", "end", "ensure", "Thread", ".", "current", "[", ":tensor_stream_variable_scope", "]", ".", "pop", "end", "else", "variable_scope", "end", "end"], "docstring": "Defines a variable context manager", "docstring_tokens": ["Defines", "a", "variable", "context", "manager"], "sha": "1be668620d86a12d4a2223502722d99968bdf854", "url": "https://github.com/jedld/tensor_stream/blob/1be668620d86a12d4a2223502722d99968bdf854/lib/tensor_stream/utils.rb#L72-L102", "partition": "test"} {"repo": "jedld/tensor_stream", "path": "lib/tensor_stream/utils.rb", "func_name": "TensorStream.Utils.session", "original_string": "def session(evaluator = nil, thread_pool_class: Concurrent::ImmediateExecutor, log_device_placement: false, profile_enabled: false)\n session = TensorStream::Session.new(evaluator, thread_pool_class: thread_pool_class, log_device_placement: log_device_placement, profile_enabled: profile_enabled)\n yield session if block_given?\n\n session\n end", "language": "ruby", "code": "def session(evaluator = nil, thread_pool_class: Concurrent::ImmediateExecutor, log_device_placement: false, profile_enabled: false)\n session = TensorStream::Session.new(evaluator, thread_pool_class: thread_pool_class, log_device_placement: log_device_placement, profile_enabled: profile_enabled)\n yield session if block_given?\n\n session\n end", "code_tokens": ["def", "session", "(", "evaluator", "=", "nil", ",", "thread_pool_class", ":", "Concurrent", "::", "ImmediateExecutor", ",", "log_device_placement", ":", "false", ",", "profile_enabled", ":", "false", ")", "session", "=", "TensorStream", "::", "Session", ".", "new", "(", "evaluator", ",", "thread_pool_class", ":", "thread_pool_class", ",", "log_device_placement", ":", "log_device_placement", ",", "profile_enabled", ":", "profile_enabled", ")", "yield", "session", "if", "block_given?", "session", "end"], "docstring": "Creates a session context where operations can be executed\n\n Args:\n evaluator: Specific evaluator to use, otherwise the best evaluator will automatically be determined\n\n Options:\n thread_pool_class: Class to use to manage thread pooling\n log_device_placement: Show assigned device/evalutor for each tensor op\n profile_enabled: Log performance metrics for each operation", "docstring_tokens": ["Creates", "a", "session", "context", "where", "operations", "can", "be", "executed"], "sha": "1be668620d86a12d4a2223502722d99968bdf854", "url": "https://github.com/jedld/tensor_stream/blob/1be668620d86a12d4a2223502722d99968bdf854/lib/tensor_stream/utils.rb#L143-L148", "partition": "test"} {"repo": "jedld/tensor_stream", "path": "lib/tensor_stream/utils.rb", "func_name": "TensorStream.Utils.placeholder", "original_string": "def placeholder(dtype, shape: nil, name: nil)\n TensorStream::Placeholder.new(dtype, nil, shape, name: name)\n end", "language": "ruby", "code": "def placeholder(dtype, shape: nil, name: nil)\n TensorStream::Placeholder.new(dtype, nil, shape, name: name)\n end", "code_tokens": ["def", "placeholder", "(", "dtype", ",", "shape", ":", "nil", ",", "name", ":", "nil", ")", "TensorStream", "::", "Placeholder", ".", "new", "(", "dtype", ",", "nil", ",", "shape", ",", "name", ":", "name", ")", "end"], "docstring": "Inserts a placeholder for a tensor that will be always fed.", "docstring_tokens": ["Inserts", "a", "placeholder", "for", "a", "tensor", "that", "will", "be", "always", "fed", "."], "sha": "1be668620d86a12d4a2223502722d99968bdf854", "url": "https://github.com/jedld/tensor_stream/blob/1be668620d86a12d4a2223502722d99968bdf854/lib/tensor_stream/utils.rb#L210-L212", "partition": "test"} {"repo": "jedld/tensor_stream", "path": "lib/tensor_stream/utils.rb", "func_name": "TensorStream.Utils.check_if_dense", "original_string": "def check_if_dense(value, expected_shape = nil)\n return unless value.is_a?(Array)\n return if value.empty?\n\n expected_shape ||= shape_eval(value)\n\n s = expected_shape.shift\n raise TensorStream::ValueError, \"Argument must be a dense tensor: #{value}, expected size #{s} got #{value.size}\" if value.size != s\n\n return if expected_shape.empty?\n\n value.each do |item|\n check_if_dense(item, expected_shape.dup)\n end\n end", "language": "ruby", "code": "def check_if_dense(value, expected_shape = nil)\n return unless value.is_a?(Array)\n return if value.empty?\n\n expected_shape ||= shape_eval(value)\n\n s = expected_shape.shift\n raise TensorStream::ValueError, \"Argument must be a dense tensor: #{value}, expected size #{s} got #{value.size}\" if value.size != s\n\n return if expected_shape.empty?\n\n value.each do |item|\n check_if_dense(item, expected_shape.dup)\n end\n end", "code_tokens": ["def", "check_if_dense", "(", "value", ",", "expected_shape", "=", "nil", ")", "return", "unless", "value", ".", "is_a?", "(", "Array", ")", "return", "if", "value", ".", "empty?", "expected_shape", "||=", "shape_eval", "(", "value", ")", "s", "=", "expected_shape", ".", "shift", "raise", "TensorStream", "::", "ValueError", ",", "\"Argument must be a dense tensor: #{value}, expected size #{s} got #{value.size}\"", "if", "value", ".", "size", "!=", "s", "return", "if", "expected_shape", ".", "empty?", "value", ".", "each", "do", "|", "item", "|", "check_if_dense", "(", "item", ",", "expected_shape", ".", "dup", ")", "end", "end"], "docstring": "Check to make sure passed array is dense", "docstring_tokens": ["Check", "to", "make", "sure", "passed", "array", "is", "dense"], "sha": "1be668620d86a12d4a2223502722d99968bdf854", "url": "https://github.com/jedld/tensor_stream/blob/1be668620d86a12d4a2223502722d99968bdf854/lib/tensor_stream/utils.rb#L266-L280", "partition": "test"} {"repo": "jedld/tensor_stream", "path": "lib/tensor_stream/utils.rb", "func_name": "TensorStream.Utils.apply_data_type_coercion", "original_string": "def apply_data_type_coercion(*args)\n coerced_type = check_data_types(*args)\n args.map { |a| a.is_a?(Tensor) ? a : convert_to_tensor(a, dtype: coerced_type) }\n end", "language": "ruby", "code": "def apply_data_type_coercion(*args)\n coerced_type = check_data_types(*args)\n args.map { |a| a.is_a?(Tensor) ? a : convert_to_tensor(a, dtype: coerced_type) }\n end", "code_tokens": ["def", "apply_data_type_coercion", "(", "*", "args", ")", "coerced_type", "=", "check_data_types", "(", "args", ")", "args", ".", "map", "{", "|", "a", "|", "a", ".", "is_a?", "(", "Tensor", ")", "?", "a", ":", "convert_to_tensor", "(", "a", ",", "dtype", ":", "coerced_type", ")", "}", "end"], "docstring": "Auto cast ruby constant data types to the same\n tensor types of other operands", "docstring_tokens": ["Auto", "cast", "ruby", "constant", "data", "types", "to", "the", "same", "tensor", "types", "of", "other", "operands"], "sha": "1be668620d86a12d4a2223502722d99968bdf854", "url": "https://github.com/jedld/tensor_stream/blob/1be668620d86a12d4a2223502722d99968bdf854/lib/tensor_stream/utils.rb#L302-L305", "partition": "test"} {"repo": "watson-developer-cloud/ruby-sdk", "path": "lib/ibm_watson/speech_to_text_v1.rb", "func_name": "IBMWatson.SpeechToTextV1.add_audio", "original_string": "def add_audio(customization_id:, audio_name:, audio_resource:, contained_content_type: nil, allow_overwrite: nil, content_type: nil)\n raise ArgumentError.new(\"customization_id must be provided\") if customization_id.nil?\n\n raise ArgumentError.new(\"audio_name must be provided\") if audio_name.nil?\n\n raise ArgumentError.new(\"audio_resource must be provided\") if audio_resource.nil?\n\n headers = {\n \"Contained-Content-Type\" => contained_content_type,\n \"Content-Type\" => content_type\n }\n sdk_headers = Common.new.get_sdk_headers(\"speech_to_text\", \"V1\", \"add_audio\")\n headers.merge!(sdk_headers)\n\n params = {\n \"allow_overwrite\" => allow_overwrite\n }\n\n data = audio_resource\n\n method_url = \"/v1/acoustic_customizations/%s/audio/%s\" % [ERB::Util.url_encode(customization_id), ERB::Util.url_encode(audio_name)]\n\n request(\n method: \"POST\",\n url: method_url,\n headers: headers,\n params: params,\n data: data,\n accept_json: true\n )\n nil\n end", "language": "ruby", "code": "def add_audio(customization_id:, audio_name:, audio_resource:, contained_content_type: nil, allow_overwrite: nil, content_type: nil)\n raise ArgumentError.new(\"customization_id must be provided\") if customization_id.nil?\n\n raise ArgumentError.new(\"audio_name must be provided\") if audio_name.nil?\n\n raise ArgumentError.new(\"audio_resource must be provided\") if audio_resource.nil?\n\n headers = {\n \"Contained-Content-Type\" => contained_content_type,\n \"Content-Type\" => content_type\n }\n sdk_headers = Common.new.get_sdk_headers(\"speech_to_text\", \"V1\", \"add_audio\")\n headers.merge!(sdk_headers)\n\n params = {\n \"allow_overwrite\" => allow_overwrite\n }\n\n data = audio_resource\n\n method_url = \"/v1/acoustic_customizations/%s/audio/%s\" % [ERB::Util.url_encode(customization_id), ERB::Util.url_encode(audio_name)]\n\n request(\n method: \"POST\",\n url: method_url,\n headers: headers,\n params: params,\n data: data,\n accept_json: true\n )\n nil\n end", "code_tokens": ["def", "add_audio", "(", "customization_id", ":", ",", "audio_name", ":", ",", "audio_resource", ":", ",", "contained_content_type", ":", "nil", ",", "allow_overwrite", ":", "nil", ",", "content_type", ":", "nil", ")", "raise", "ArgumentError", ".", "new", "(", "\"customization_id must be provided\"", ")", "if", "customization_id", ".", "nil?", "raise", "ArgumentError", ".", "new", "(", "\"audio_name must be provided\"", ")", "if", "audio_name", ".", "nil?", "raise", "ArgumentError", ".", "new", "(", "\"audio_resource must be provided\"", ")", "if", "audio_resource", ".", "nil?", "headers", "=", "{", "\"Contained-Content-Type\"", "=>", "contained_content_type", ",", "\"Content-Type\"", "=>", "content_type", "}", "sdk_headers", "=", "Common", ".", "new", ".", "get_sdk_headers", "(", "\"speech_to_text\"", ",", "\"V1\"", ",", "\"add_audio\"", ")", "headers", ".", "merge!", "(", "sdk_headers", ")", "params", "=", "{", "\"allow_overwrite\"", "=>", "allow_overwrite", "}", "data", "=", "audio_resource", "method_url", "=", "\"/v1/acoustic_customizations/%s/audio/%s\"", "%", "[", "ERB", "::", "Util", ".", "url_encode", "(", "customization_id", ")", ",", "ERB", "::", "Util", ".", "url_encode", "(", "audio_name", ")", "]", "request", "(", "method", ":", "\"POST\"", ",", "url", ":", "method_url", ",", "headers", ":", "headers", ",", "params", ":", "params", ",", "data", ":", "data", ",", "accept_json", ":", "true", ")", "nil", "end"], "docstring": "Custom audio resources\n\n\n @!method add_audio(customization_id:, audio_name:, audio_resource:, contained_content_type: nil, allow_overwrite: nil, content_type: nil)\n Add an audio resource.\n Adds an audio resource to a custom acoustic model. Add audio content that reflects\n the acoustic characteristics of the audio that you plan to transcribe. You must\n use credentials for the instance of the service that owns a model to add an audio\n resource to it. Adding audio data does not affect the custom acoustic model until\n you train the model for the new data by using the **Train a custom acoustic\n model** method.\n\n You can add individual audio files or an archive file that contains multiple audio\n files. Adding multiple audio files via a single archive file is significantly more\n efficient than adding each file individually. You can add audio resources in any\n format that the service supports for speech recognition.\n\n You can use this method to add any number of audio resources to a custom model by\n calling the method once for each audio or archive file. But the addition of one\n audio resource must be fully complete before you can add another. You must add a\n minimum of 10 minutes and a maximum of 100 hours of audio that includes speech,\n not just silence, to a custom acoustic model before you can train it. No audio\n resource, audio- or archive-type, can be larger than 100 MB. To add an audio\n resource that has the same name as an existing audio resource, set the\n `allow_overwrite` parameter to `true`; otherwise, the request fails.\n\n The method is asynchronous. It can take several seconds to complete depending on\n the duration of the audio and, in the case of an archive file, the total number of\n audio files being processed. The service returns a 201 response code if the audio\n is valid. It then asynchronously analyzes the contents of the audio file or files\n and automatically extracts information about the audio such as its length,\n sampling rate, and encoding. You cannot submit requests to add additional audio\n resources to a custom acoustic model, or to train the model, until the service's\n analysis of all audio files for the current request completes.\n\n To determine the status of the service's analysis of the audio, use the **Get an\n audio resource** method to poll the status of the audio. The method accepts the\n customization ID of the custom model and the name of the audio resource, and it\n returns the status of the resource. Use a loop to check the status of the audio\n every few seconds until it becomes `ok`.\n\n **See also:** [Add audio to the custom acoustic\n model](https://cloud.ibm.com/docs/services/speech-to-text/acoustic-create.html#addAudio).\n\n\n ### Content types for audio-type resources\n\n You can add an individual audio file in any format that the service supports for\n speech recognition. For an audio-type resource, use the `Content-Type` parameter\n to specify the audio format (MIME type) of the audio file, including specifying\n the sampling rate, channels, and endianness where indicated.\n * `audio/alaw` (Specify the sampling rate (`rate`) of the audio.)\n * `audio/basic` (Use only with narrowband models.)\n * `audio/flac`\n * `audio/g729` (Use only with narrowband models.)\n * `audio/l16` (Specify the sampling rate (`rate`) and optionally the number of\n channels (`channels`) and endianness (`endianness`) of the audio.)\n * `audio/mp3`\n * `audio/mpeg`\n * `audio/mulaw` (Specify the sampling rate (`rate`) of the audio.)\n * `audio/ogg` (The service automatically detects the codec of the input audio.)\n * `audio/ogg;codecs=opus`\n * `audio/ogg;codecs=vorbis`\n * `audio/wav` (Provide audio with a maximum of nine channels.)\n * `audio/webm` (The service automatically detects the codec of the input audio.)\n * `audio/webm;codecs=opus`\n * `audio/webm;codecs=vorbis`\n\n The sampling rate of an audio file must match the sampling rate of the base model\n for the custom model: for broadband models, at least 16 kHz; for narrowband\n models, at least 8 kHz. If the sampling rate of the audio is higher than the\n minimum required rate, the service down-samples the audio to the appropriate rate.\n If the sampling rate of the audio is lower than the minimum required rate, the\n service labels the audio file as `invalid`.\n\n **See also:** [Audio\n formats](https://cloud.ibm.com/docs/services/speech-to-text/audio-formats.html).\n\n ### Content types for archive-type resources\n\n You can add an archive file (**.zip** or **.tar.gz** file) that contains audio\n files in any format that the service supports for speech recognition. For an\n archive-type resource, use the `Content-Type` parameter to specify the media type\n of the archive file:\n * `application/zip` for a **.zip** file\n * `application/gzip` for a **.tar.gz** file.\n\n When you add an archive-type resource, the `Contained-Content-Type` header is\n optional depending on the format of the files that you are adding:\n * For audio files of type `audio/alaw`, `audio/basic`, `audio/l16`, or\n `audio/mulaw`, you must use the `Contained-Content-Type` header to specify the\n format of the contained audio files. Include the `rate`, `channels`, and\n `endianness` parameters where necessary. In this case, all audio files contained\n in the archive file must have the same audio format.\n * For audio files of all other types, you can omit the `Contained-Content-Type`\n header. In this case, the audio files contained in the archive file can have any\n of the formats not listed in the previous bullet. The audio files do not need to\n have the same format.\n\n Do not use the `Contained-Content-Type` header when adding an audio-type resource.\n\n\n ### Naming restrictions for embedded audio files\n\n The name of an audio file that is embedded within an archive-type resource must\n meet the following restrictions:\n * Include a maximum of 128 characters in the file name; this includes the file\n extension.\n * Do not include spaces, slashes, or backslashes in the file name.\n * Do not use the name of an audio file that has already been added to the custom\n model as part of an archive-type resource.\n @param customization_id [String] The customization ID (GUID) of the custom acoustic model that is to be used for\n the request. You must make the request with credentials for the instance of the\n service that owns the custom model.\n @param audio_name [String] The name of the new audio resource for the custom acoustic model. Use a localized\n name that matches the language of the custom model and reflects the contents of\n the resource.\n * Include a maximum of 128 characters in the name.\n * Do not include spaces, slashes, or backslashes in the name.\n * Do not use the name of an audio resource that has already been added to the\n custom model.\n @param audio_resource [String] The audio resource that is to be added to the custom acoustic model, an individual\n audio file or an archive file.\n @param contained_content_type [String] **For an archive-type resource,** specify the format of the audio files that are\n contained in the archive file if they are of type `audio/alaw`, `audio/basic`,\n `audio/l16`, or `audio/mulaw`. Include the `rate`, `channels`, and `endianness`\n parameters where necessary. In this case, all audio files that are contained in\n the archive file must be of the indicated type.\n\n For all other audio formats, you can omit the header. In this case, the audio\n files can be of multiple types as long as they are not of the types listed in the\n previous paragraph.\n\n The parameter accepts all of the audio formats that are supported for use with\n speech recognition. For more information, see **Content types for audio-type\n resources** in the method description.\n\n **For an audio-type resource,** omit the header.\n @param allow_overwrite [Boolean] If `true`, the specified audio resource overwrites an existing audio resource with\n the same name. If `false`, the request fails if an audio resource with the same\n name already exists. The parameter has no effect if an audio resource with the\n same name does not already exist.\n @param content_type [String] For an audio-type resource, the format (MIME type) of the audio. For more\n information, see **Content types for audio-type resources** in the method\n description.\n\n For an archive-type resource, the media type of the archive file. For more\n information, see **Content types for archive-type resources** in the method\n description.\n @return [nil]", "docstring_tokens": ["Custom", "audio", "resources"], "sha": "1a8912d040de4831162c801be6d71b5f0da8d3b3", "url": "https://github.com/watson-developer-cloud/ruby-sdk/blob/1a8912d040de4831162c801be6d71b5f0da8d3b3/lib/ibm_watson/speech_to_text_v1.rb#L2699-L2730", "partition": "test"} {"repo": "watson-developer-cloud/ruby-sdk", "path": "lib/ibm_watson/discovery_v1.rb", "func_name": "IBMWatson.DiscoveryV1.create_event", "original_string": "def create_event(type:, data:)\n raise ArgumentError.new(\"type must be provided\") if type.nil?\n\n raise ArgumentError.new(\"data must be provided\") if data.nil?\n\n headers = {\n }\n sdk_headers = Common.new.get_sdk_headers(\"discovery\", \"V1\", \"create_event\")\n headers.merge!(sdk_headers)\n\n params = {\n \"version\" => @version\n }\n\n data = {\n \"type\" => type,\n \"data\" => data\n }\n\n method_url = \"/v1/events\"\n\n response = request(\n method: \"POST\",\n url: method_url,\n headers: headers,\n params: params,\n json: data,\n accept_json: true\n )\n response\n end", "language": "ruby", "code": "def create_event(type:, data:)\n raise ArgumentError.new(\"type must be provided\") if type.nil?\n\n raise ArgumentError.new(\"data must be provided\") if data.nil?\n\n headers = {\n }\n sdk_headers = Common.new.get_sdk_headers(\"discovery\", \"V1\", \"create_event\")\n headers.merge!(sdk_headers)\n\n params = {\n \"version\" => @version\n }\n\n data = {\n \"type\" => type,\n \"data\" => data\n }\n\n method_url = \"/v1/events\"\n\n response = request(\n method: \"POST\",\n url: method_url,\n headers: headers,\n params: params,\n json: data,\n accept_json: true\n )\n response\n end", "code_tokens": ["def", "create_event", "(", "type", ":", ",", "data", ":", ")", "raise", "ArgumentError", ".", "new", "(", "\"type must be provided\"", ")", "if", "type", ".", "nil?", "raise", "ArgumentError", ".", "new", "(", "\"data must be provided\"", ")", "if", "data", ".", "nil?", "headers", "=", "{", "}", "sdk_headers", "=", "Common", ".", "new", ".", "get_sdk_headers", "(", "\"discovery\"", ",", "\"V1\"", ",", "\"create_event\"", ")", "headers", ".", "merge!", "(", "sdk_headers", ")", "params", "=", "{", "\"version\"", "=>", "@version", "}", "data", "=", "{", "\"type\"", "=>", "type", ",", "\"data\"", "=>", "data", "}", "method_url", "=", "\"/v1/events\"", "response", "=", "request", "(", "method", ":", "\"POST\"", ",", "url", ":", "method_url", ",", "headers", ":", "headers", ",", "params", ":", "params", ",", "json", ":", "data", ",", "accept_json", ":", "true", ")", "response", "end"], "docstring": "Events and feedback\n\n\n @!method create_event(type:, data:)\n Create event.\n The **Events** API can be used to create log entries that are associated with\n specific queries. For example, you can record which documents in the results set\n were \\\"clicked\\\" by a user and when that click occured.\n @param type [String] The event type to be created.\n @param data [EventData] Query event data object.\n @return [IBMCloudSdkCore::DetailedResponse] A `IBMCloudSdkCore::DetailedResponse` object representing the response.", "docstring_tokens": ["Events", "and", "feedback"], "sha": "1a8912d040de4831162c801be6d71b5f0da8d3b3", "url": "https://github.com/watson-developer-cloud/ruby-sdk/blob/1a8912d040de4831162c801be6d71b5f0da8d3b3/lib/ibm_watson/discovery_v1.rb#L2392-L2422", "partition": "test"} {"repo": "crypto-rb/rbnacl", "path": "lib/rbnacl/util.rb", "func_name": "RbNaCl.Util.zero_pad", "original_string": "def zero_pad(n, message)\n len = message.bytesize\n if len == n\n message\n elsif len > n\n raise LengthError, \"String too long for zero-padding to #{n} bytes\"\n else\n message + zeros(n - len)\n end\n end", "language": "ruby", "code": "def zero_pad(n, message)\n len = message.bytesize\n if len == n\n message\n elsif len > n\n raise LengthError, \"String too long for zero-padding to #{n} bytes\"\n else\n message + zeros(n - len)\n end\n end", "code_tokens": ["def", "zero_pad", "(", "n", ",", "message", ")", "len", "=", "message", ".", "bytesize", "if", "len", "==", "n", "message", "elsif", "len", ">", "n", "raise", "LengthError", ",", "\"String too long for zero-padding to #{n} bytes\"", "else", "message", "+", "zeros", "(", "n", "-", "len", ")", "end", "end"], "docstring": "Pad a string out to n characters with zeros\n\n @param [Integer] n The length of the resulting string\n @param [String] message the message to be padded\n\n @raise [RbNaCl::LengthError] If the string is too long\n\n @return [String] A string, n bytes long", "docstring_tokens": ["Pad", "a", "string", "out", "to", "n", "characters", "with", "zeros"], "sha": "4b04cd0db7d5df1053c6047904ca446c78a33d8e", "url": "https://github.com/crypto-rb/rbnacl/blob/4b04cd0db7d5df1053c6047904ca446c78a33d8e/lib/rbnacl/util.rb#L62-L71", "partition": "test"} {"repo": "crypto-rb/rbnacl", "path": "lib/rbnacl/util.rb", "func_name": "RbNaCl.Util.check_length", "original_string": "def check_length(string, length, description)\n if string.nil?\n # code below is runs only in test cases\n # nil can't be converted to str with #to_str method\n raise LengthError,\n \"#{description} was nil (Expected #{length.to_int})\",\n caller\n end\n\n if string.bytesize != length.to_int\n raise LengthError,\n \"#{description} was #{string.bytesize} bytes (Expected #{length.to_int})\",\n caller\n end\n true\n end", "language": "ruby", "code": "def check_length(string, length, description)\n if string.nil?\n # code below is runs only in test cases\n # nil can't be converted to str with #to_str method\n raise LengthError,\n \"#{description} was nil (Expected #{length.to_int})\",\n caller\n end\n\n if string.bytesize != length.to_int\n raise LengthError,\n \"#{description} was #{string.bytesize} bytes (Expected #{length.to_int})\",\n caller\n end\n true\n end", "code_tokens": ["def", "check_length", "(", "string", ",", "length", ",", "description", ")", "if", "string", ".", "nil?", "# code below is runs only in test cases", "# nil can't be converted to str with #to_str method", "raise", "LengthError", ",", "\"#{description} was nil (Expected #{length.to_int})\"", ",", "caller", "end", "if", "string", ".", "bytesize", "!=", "length", ".", "to_int", "raise", "LengthError", ",", "\"#{description} was #{string.bytesize} bytes (Expected #{length.to_int})\"", ",", "caller", "end", "true", "end"], "docstring": "Check the length of the passed in string\n\n In several places through the codebase we have to be VERY strict with\n what length of string we accept. This method supports that.\n\n @raise [RbNaCl::LengthError] If the string is not the right length\n\n @param string [String] The string to compare\n @param length [Integer] The desired length\n @param description [String] Description of the string (used in the error)", "docstring_tokens": ["Check", "the", "length", "of", "the", "passed", "in", "string"], "sha": "4b04cd0db7d5df1053c6047904ca446c78a33d8e", "url": "https://github.com/crypto-rb/rbnacl/blob/4b04cd0db7d5df1053c6047904ca446c78a33d8e/lib/rbnacl/util.rb#L83-L98", "partition": "test"} {"repo": "crypto-rb/rbnacl", "path": "lib/rbnacl/util.rb", "func_name": "RbNaCl.Util.check_string", "original_string": "def check_string(string, length, description)\n check_string_validation(string)\n string = string.to_s\n check_length(string, length, description)\n\n string\n end", "language": "ruby", "code": "def check_string(string, length, description)\n check_string_validation(string)\n string = string.to_s\n check_length(string, length, description)\n\n string\n end", "code_tokens": ["def", "check_string", "(", "string", ",", "length", ",", "description", ")", "check_string_validation", "(", "string", ")", "string", "=", "string", ".", "to_s", "check_length", "(", "string", ",", "length", ",", "description", ")", "string", "end"], "docstring": "Check a passed in string, converting the argument if necessary\n\n In several places through the codebase we have to be VERY strict with\n the strings we accept. This method supports that.\n\n @raise [ArgumentError] If we cannot convert to a string with #to_str\n @raise [RbNaCl::LengthError] If the string is not the right length\n\n @param string [#to_str] The input string\n @param length [Integer] The only acceptable length of the string\n @param description [String] Description of the string (used in the error)", "docstring_tokens": ["Check", "a", "passed", "in", "string", "converting", "the", "argument", "if", "necessary"], "sha": "4b04cd0db7d5df1053c6047904ca446c78a33d8e", "url": "https://github.com/crypto-rb/rbnacl/blob/4b04cd0db7d5df1053c6047904ca446c78a33d8e/lib/rbnacl/util.rb#L111-L117", "partition": "test"} {"repo": "crypto-rb/rbnacl", "path": "lib/rbnacl/util.rb", "func_name": "RbNaCl.Util.check_hmac_key", "original_string": "def check_hmac_key(string, _description)\n check_string_validation(string)\n\n string = string.to_str\n\n if string.bytesize.zero?\n raise LengthError,\n \"#{Description} was #{string.bytesize} bytes (Expected more than 0)\",\n caller\n end\n\n string\n end", "language": "ruby", "code": "def check_hmac_key(string, _description)\n check_string_validation(string)\n\n string = string.to_str\n\n if string.bytesize.zero?\n raise LengthError,\n \"#{Description} was #{string.bytesize} bytes (Expected more than 0)\",\n caller\n end\n\n string\n end", "code_tokens": ["def", "check_hmac_key", "(", "string", ",", "_description", ")", "check_string_validation", "(", "string", ")", "string", "=", "string", ".", "to_str", "if", "string", ".", "bytesize", ".", "zero?", "raise", "LengthError", ",", "\"#{Description} was #{string.bytesize} bytes (Expected more than 0)\"", ",", "caller", "end", "string", "end"], "docstring": "Check a passed in string, convertion if necessary\n\n This method will check the key, and raise error\n if argument is not a string, and if it's empty string.\n\n RFC 2104 HMAC\n The key for HMAC can be of any length (keys longer than B bytes are\n first hashed using H). However, less than L bytes is strongly\n discouraged as it would decrease the security strength of the\n function. Keys longer than L bytes are acceptable but the extra\n length would not significantly increase the function strength. (A\n longer key may be advisable if the randomness of the key is\n considered weak.)\n\n see https://tools.ietf.org/html/rfc2104#section-3\n\n\n @raise [ArgumentError] If we cannot convert to a string with #to_str\n @raise [RbNaCl::LengthError] If the string is empty\n\n @param string [#to_str] The input string", "docstring_tokens": ["Check", "a", "passed", "in", "string", "convertion", "if", "necessary"], "sha": "4b04cd0db7d5df1053c6047904ca446c78a33d8e", "url": "https://github.com/crypto-rb/rbnacl/blob/4b04cd0db7d5df1053c6047904ca446c78a33d8e/lib/rbnacl/util.rb#L140-L152", "partition": "test"} {"repo": "crypto-rb/rbnacl", "path": "lib/rbnacl/util.rb", "func_name": "RbNaCl.Util.check_string_validation", "original_string": "def check_string_validation(string)\n raise TypeError, \"can't convert #{string.class} into String with #to_str\" unless string.respond_to? :to_str\n\n string = string.to_str\n\n raise EncodingError, \"strings must use BINARY encoding (got #{string.encoding})\" if string.encoding != Encoding::BINARY\n end", "language": "ruby", "code": "def check_string_validation(string)\n raise TypeError, \"can't convert #{string.class} into String with #to_str\" unless string.respond_to? :to_str\n\n string = string.to_str\n\n raise EncodingError, \"strings must use BINARY encoding (got #{string.encoding})\" if string.encoding != Encoding::BINARY\n end", "code_tokens": ["def", "check_string_validation", "(", "string", ")", "raise", "TypeError", ",", "\"can't convert #{string.class} into String with #to_str\"", "unless", "string", ".", "respond_to?", ":to_str", "string", "=", "string", ".", "to_str", "raise", "EncodingError", ",", "\"strings must use BINARY encoding (got #{string.encoding})\"", "if", "string", ".", "encoding", "!=", "Encoding", "::", "BINARY", "end"], "docstring": "Check a passed string is it valid\n\n Raise an error if passed argument is invalid\n\n @raise [TypeError] If string cannot convert to a string with #to_str\n @raise [EncodingError] If string have wrong encoding\n\n @param string [#to_str] The input string", "docstring_tokens": ["Check", "a", "passed", "string", "is", "it", "valid"], "sha": "4b04cd0db7d5df1053c6047904ca446c78a33d8e", "url": "https://github.com/crypto-rb/rbnacl/blob/4b04cd0db7d5df1053c6047904ca446c78a33d8e/lib/rbnacl/util.rb#L162-L168", "partition": "test"} {"repo": "crypto-rb/rbnacl", "path": "lib/rbnacl/auth.rb", "func_name": "RbNaCl.Auth.auth", "original_string": "def auth(message)\n authenticator = Util.zeros(tag_bytes)\n message = message.to_str\n compute_authenticator(authenticator, message)\n authenticator\n end", "language": "ruby", "code": "def auth(message)\n authenticator = Util.zeros(tag_bytes)\n message = message.to_str\n compute_authenticator(authenticator, message)\n authenticator\n end", "code_tokens": ["def", "auth", "(", "message", ")", "authenticator", "=", "Util", ".", "zeros", "(", "tag_bytes", ")", "message", "=", "message", ".", "to_str", "compute_authenticator", "(", "authenticator", ",", "message", ")", "authenticator", "end"], "docstring": "Compute authenticator for message\n\n @param [#to_str] message the message to authenticate\n\n @return [String] the authenticator as raw bytes", "docstring_tokens": ["Compute", "authenticator", "for", "message"], "sha": "4b04cd0db7d5df1053c6047904ca446c78a33d8e", "url": "https://github.com/crypto-rb/rbnacl/blob/4b04cd0db7d5df1053c6047904ca446c78a33d8e/lib/rbnacl/auth.rb#L56-L61", "partition": "test"} {"repo": "crypto-rb/rbnacl", "path": "lib/rbnacl/auth.rb", "func_name": "RbNaCl.Auth.verify", "original_string": "def verify(authenticator, message)\n auth = authenticator.to_s\n Util.check_length(auth, tag_bytes, \"Provided authenticator\")\n verify_message(auth, message) || raise(BadAuthenticatorError, \"Invalid authenticator provided, message is corrupt\")\n end", "language": "ruby", "code": "def verify(authenticator, message)\n auth = authenticator.to_s\n Util.check_length(auth, tag_bytes, \"Provided authenticator\")\n verify_message(auth, message) || raise(BadAuthenticatorError, \"Invalid authenticator provided, message is corrupt\")\n end", "code_tokens": ["def", "verify", "(", "authenticator", ",", "message", ")", "auth", "=", "authenticator", ".", "to_s", "Util", ".", "check_length", "(", "auth", ",", "tag_bytes", ",", "\"Provided authenticator\"", ")", "verify_message", "(", "auth", ",", "message", ")", "||", "raise", "(", "BadAuthenticatorError", ",", "\"Invalid authenticator provided, message is corrupt\"", ")", "end"], "docstring": "Verifies the given authenticator with the message.\n\n @param [#to_str] authenticator to be checked\n @param [#to_str] message the message to be authenticated\n\n @raise [BadAuthenticatorError] if the tag isn't valid\n @raise [LengthError] if the tag is of the wrong length\n\n @return [Boolean] Was it valid?", "docstring_tokens": ["Verifies", "the", "given", "authenticator", "with", "the", "message", "."], "sha": "4b04cd0db7d5df1053c6047904ca446c78a33d8e", "url": "https://github.com/crypto-rb/rbnacl/blob/4b04cd0db7d5df1053c6047904ca446c78a33d8e/lib/rbnacl/auth.rb#L72-L76", "partition": "test"} {"repo": "crypto-rb/rbnacl", "path": "lib/rbnacl/simple_box.rb", "func_name": "RbNaCl.SimpleBox.box", "original_string": "def box(message)\n nonce = generate_nonce\n cipher_text = @box.box(nonce, message)\n nonce + cipher_text\n end", "language": "ruby", "code": "def box(message)\n nonce = generate_nonce\n cipher_text = @box.box(nonce, message)\n nonce + cipher_text\n end", "code_tokens": ["def", "box", "(", "message", ")", "nonce", "=", "generate_nonce", "cipher_text", "=", "@box", ".", "box", "(", "nonce", ",", "message", ")", "nonce", "+", "cipher_text", "end"], "docstring": "Encrypts the message with a random nonce\n\n Encrypts the message with a random nonce, then returns the ciphertext with\n the nonce prepended. Optionally encodes the message using an encoder.\n\n @param message [String] The message to encrypt\n\n @return [String] The enciphered message", "docstring_tokens": ["Encrypts", "the", "message", "with", "a", "random", "nonce"], "sha": "4b04cd0db7d5df1053c6047904ca446c78a33d8e", "url": "https://github.com/crypto-rb/rbnacl/blob/4b04cd0db7d5df1053c6047904ca446c78a33d8e/lib/rbnacl/simple_box.rb#L80-L84", "partition": "test"} {"repo": "crypto-rb/rbnacl", "path": "lib/rbnacl/simple_box.rb", "func_name": "RbNaCl.SimpleBox.open", "original_string": "def open(enciphered_message)\n nonce, ciphertext = extract_nonce(enciphered_message.to_s)\n @box.open(nonce, ciphertext)\n end", "language": "ruby", "code": "def open(enciphered_message)\n nonce, ciphertext = extract_nonce(enciphered_message.to_s)\n @box.open(nonce, ciphertext)\n end", "code_tokens": ["def", "open", "(", "enciphered_message", ")", "nonce", ",", "ciphertext", "=", "extract_nonce", "(", "enciphered_message", ".", "to_s", ")", "@box", ".", "open", "(", "nonce", ",", "ciphertext", ")", "end"], "docstring": "Decrypts the ciphertext with a random nonce\n\n Takes a ciphertext, optionally decodes it, then splits the nonce off the\n front and uses this to decrypt. Returns the message.\n\n @param enciphered_message [String] The message to decrypt.\n\n @raise [CryptoError] If the message has been tampered with.\n\n @return [String] The decoded message", "docstring_tokens": ["Decrypts", "the", "ciphertext", "with", "a", "random", "nonce"], "sha": "4b04cd0db7d5df1053c6047904ca446c78a33d8e", "url": "https://github.com/crypto-rb/rbnacl/blob/4b04cd0db7d5df1053c6047904ca446c78a33d8e/lib/rbnacl/simple_box.rb#L97-L100", "partition": "test"} {"repo": "rocketjob/semantic_logger", "path": "lib/semantic_logger/appenders.rb", "func_name": "SemanticLogger.Appenders.reopen", "original_string": "def reopen\n each do |appender|\n begin\n next unless appender.respond_to?(:reopen)\n\n logger.trace \"Reopening appender: #{appender.name}\"\n appender.reopen\n rescue Exception => exc\n logger.error \"Failed to re-open appender: #{appender.inspect}\", exc\n end\n end\n logger.trace 'All appenders re-opened'\n end", "language": "ruby", "code": "def reopen\n each do |appender|\n begin\n next unless appender.respond_to?(:reopen)\n\n logger.trace \"Reopening appender: #{appender.name}\"\n appender.reopen\n rescue Exception => exc\n logger.error \"Failed to re-open appender: #{appender.inspect}\", exc\n end\n end\n logger.trace 'All appenders re-opened'\n end", "code_tokens": ["def", "reopen", "each", "do", "|", "appender", "|", "begin", "next", "unless", "appender", ".", "respond_to?", "(", ":reopen", ")", "logger", ".", "trace", "\"Reopening appender: #{appender.name}\"", "appender", ".", "reopen", "rescue", "Exception", "=>", "exc", "logger", ".", "error", "\"Failed to re-open appender: #{appender.inspect}\"", ",", "exc", "end", "end", "logger", ".", "trace", "'All appenders re-opened'", "end"], "docstring": "After a fork the appender thread is not running, start it if it is not running.", "docstring_tokens": ["After", "a", "fork", "the", "appender", "thread", "is", "not", "running", "start", "it", "if", "it", "is", "not", "running", "."], "sha": "0196730749a6912fbd177c099d76be17be901e0b", "url": "https://github.com/rocketjob/semantic_logger/blob/0196730749a6912fbd177c099d76be17be901e0b/lib/semantic_logger/appenders.rb#L55-L67", "partition": "test"} {"repo": "rocketjob/semantic_logger", "path": "lib/semantic_logger/subscriber.rb", "func_name": "SemanticLogger.Subscriber.logger", "original_string": "def logger\n @logger ||= begin\n logger = SemanticLogger::Processor.logger.clone\n logger.name = self.class.name\n logger\n end\n end", "language": "ruby", "code": "def logger\n @logger ||= begin\n logger = SemanticLogger::Processor.logger.clone\n logger.name = self.class.name\n logger\n end\n end", "code_tokens": ["def", "logger", "@logger", "||=", "begin", "logger", "=", "SemanticLogger", "::", "Processor", ".", "logger", ".", "clone", "logger", ".", "name", "=", "self", ".", "class", ".", "name", "logger", "end", "end"], "docstring": "Give each appender its own logger for logging.\n For example trace messages sent to services or errors when something fails.", "docstring_tokens": ["Give", "each", "appender", "its", "own", "logger", "for", "logging", ".", "For", "example", "trace", "messages", "sent", "to", "services", "or", "errors", "when", "something", "fails", "."], "sha": "0196730749a6912fbd177c099d76be17be901e0b", "url": "https://github.com/rocketjob/semantic_logger/blob/0196730749a6912fbd177c099d76be17be901e0b/lib/semantic_logger/subscriber.rb#L42-L48", "partition": "test"} {"repo": "rocketjob/semantic_logger", "path": "lib/semantic_logger/base.rb", "func_name": "SemanticLogger.Base.measure", "original_string": "def measure(level, message, params = {}, &block)\n index = Levels.index(level)\n if level_index <= index\n measure_internal(level, index, message, params, &block)\n elsif block\n yield(params)\n end\n end", "language": "ruby", "code": "def measure(level, message, params = {}, &block)\n index = Levels.index(level)\n if level_index <= index\n measure_internal(level, index, message, params, &block)\n elsif block\n yield(params)\n end\n end", "code_tokens": ["def", "measure", "(", "level", ",", "message", ",", "params", "=", "{", "}", ",", "&", "block", ")", "index", "=", "Levels", ".", "index", "(", "level", ")", "if", "level_index", "<=", "index", "measure_internal", "(", "level", ",", "index", ",", "message", ",", "params", ",", "block", ")", "elsif", "block", "yield", "(", "params", ")", "end", "end"], "docstring": "Dynamically supply the log level with every measurement call", "docstring_tokens": ["Dynamically", "supply", "the", "log", "level", "with", "every", "measurement", "call"], "sha": "0196730749a6912fbd177c099d76be17be901e0b", "url": "https://github.com/rocketjob/semantic_logger/blob/0196730749a6912fbd177c099d76be17be901e0b/lib/semantic_logger/base.rb#L114-L121", "partition": "test"} {"repo": "rocketjob/semantic_logger", "path": "lib/semantic_logger/base.rb", "func_name": "SemanticLogger.Base.backtrace", "original_string": "def backtrace(thread: Thread.current,\n level: :warn,\n message: 'Backtrace:',\n payload: nil,\n metric: nil,\n metric_amount: nil)\n\n log = Log.new(name, level)\n return false unless meets_log_level?(log)\n\n backtrace =\n if thread == Thread.current\n Utils.extract_backtrace\n else\n log.thread_name = thread.name\n log.tags = (thread[:semantic_logger_tags] || []).clone\n log.named_tags = (thread[:semantic_logger_named_tags] || {}).clone\n thread.backtrace\n end\n # TODO: Keep backtrace instead of transforming into a text message at this point\n # Maybe log_backtrace: true\n if backtrace\n message += \"\\n\"\n message << backtrace.join(\"\\n\")\n end\n\n if log.assign(message: message,\n backtrace: backtrace,\n payload: payload,\n metric: metric,\n metric_amount: metric_amount) && !filtered?(log)\n self.log(log)\n else\n false\n end\n end", "language": "ruby", "code": "def backtrace(thread: Thread.current,\n level: :warn,\n message: 'Backtrace:',\n payload: nil,\n metric: nil,\n metric_amount: nil)\n\n log = Log.new(name, level)\n return false unless meets_log_level?(log)\n\n backtrace =\n if thread == Thread.current\n Utils.extract_backtrace\n else\n log.thread_name = thread.name\n log.tags = (thread[:semantic_logger_tags] || []).clone\n log.named_tags = (thread[:semantic_logger_named_tags] || {}).clone\n thread.backtrace\n end\n # TODO: Keep backtrace instead of transforming into a text message at this point\n # Maybe log_backtrace: true\n if backtrace\n message += \"\\n\"\n message << backtrace.join(\"\\n\")\n end\n\n if log.assign(message: message,\n backtrace: backtrace,\n payload: payload,\n metric: metric,\n metric_amount: metric_amount) && !filtered?(log)\n self.log(log)\n else\n false\n end\n end", "code_tokens": ["def", "backtrace", "(", "thread", ":", "Thread", ".", "current", ",", "level", ":", ":warn", ",", "message", ":", "'Backtrace:'", ",", "payload", ":", "nil", ",", "metric", ":", "nil", ",", "metric_amount", ":", "nil", ")", "log", "=", "Log", ".", "new", "(", "name", ",", "level", ")", "return", "false", "unless", "meets_log_level?", "(", "log", ")", "backtrace", "=", "if", "thread", "==", "Thread", ".", "current", "Utils", ".", "extract_backtrace", "else", "log", ".", "thread_name", "=", "thread", ".", "name", "log", ".", "tags", "=", "(", "thread", "[", ":semantic_logger_tags", "]", "||", "[", "]", ")", ".", "clone", "log", ".", "named_tags", "=", "(", "thread", "[", ":semantic_logger_named_tags", "]", "||", "{", "}", ")", ".", "clone", "thread", ".", "backtrace", "end", "# TODO: Keep backtrace instead of transforming into a text message at this point", "# Maybe log_backtrace: true", "if", "backtrace", "message", "+=", "\"\\n\"", "message", "<<", "backtrace", ".", "join", "(", "\"\\n\"", ")", "end", "if", "log", ".", "assign", "(", "message", ":", "message", ",", "backtrace", ":", "backtrace", ",", "payload", ":", "payload", ",", "metric", ":", "metric", ",", "metric_amount", ":", "metric_amount", ")", "&&", "!", "filtered?", "(", "log", ")", "self", ".", "log", "(", "log", ")", "else", "false", "end", "end"], "docstring": "Log a thread backtrace", "docstring_tokens": ["Log", "a", "thread", "backtrace"], "sha": "0196730749a6912fbd177c099d76be17be901e0b", "url": "https://github.com/rocketjob/semantic_logger/blob/0196730749a6912fbd177c099d76be17be901e0b/lib/semantic_logger/base.rb#L127-L162", "partition": "test"} {"repo": "rocketjob/semantic_logger", "path": "lib/semantic_logger/base.rb", "func_name": "SemanticLogger.Base.tagged", "original_string": "def tagged(*tags, &block)\n # Allow named tags to be passed into the logger\n if tags.size == 1\n tag = tags[0]\n return yield if tag.nil? || tag == ''\n return tag.is_a?(Hash) ? SemanticLogger.named_tagged(tag, &block) : SemanticLogger.fast_tag(tag.to_s, &block)\n end\n\n # Need to flatten and reject empties to support calls from Rails 4\n new_tags = tags.flatten.collect(&:to_s).reject(&:empty?)\n SemanticLogger.tagged(*new_tags, &block)\n end", "language": "ruby", "code": "def tagged(*tags, &block)\n # Allow named tags to be passed into the logger\n if tags.size == 1\n tag = tags[0]\n return yield if tag.nil? || tag == ''\n return tag.is_a?(Hash) ? SemanticLogger.named_tagged(tag, &block) : SemanticLogger.fast_tag(tag.to_s, &block)\n end\n\n # Need to flatten and reject empties to support calls from Rails 4\n new_tags = tags.flatten.collect(&:to_s).reject(&:empty?)\n SemanticLogger.tagged(*new_tags, &block)\n end", "code_tokens": ["def", "tagged", "(", "*", "tags", ",", "&", "block", ")", "# Allow named tags to be passed into the logger", "if", "tags", ".", "size", "==", "1", "tag", "=", "tags", "[", "0", "]", "return", "yield", "if", "tag", ".", "nil?", "||", "tag", "==", "''", "return", "tag", ".", "is_a?", "(", "Hash", ")", "?", "SemanticLogger", ".", "named_tagged", "(", "tag", ",", "block", ")", ":", "SemanticLogger", ".", "fast_tag", "(", "tag", ".", "to_s", ",", "block", ")", "end", "# Need to flatten and reject empties to support calls from Rails 4", "new_tags", "=", "tags", ".", "flatten", ".", "collect", "(", ":to_s", ")", ".", "reject", "(", ":empty?", ")", "SemanticLogger", ".", "tagged", "(", "new_tags", ",", "block", ")", "end"], "docstring": "Add the tags or named tags to the list of tags to log for this thread whilst the supplied block is active.\n\n Returns result of block.\n\n Tagged example:\n SemanticLogger.tagged(12345, 'jack') do\n logger.debug('Hello World')\n end\n\n Named Tags (Hash) example:\n SemanticLogger.tagged(tracking_number: 12345) do\n logger.debug('Hello World')\n end\n\n Notes:\n - Named tags are the recommended approach since the tag consists of a name value pair this is more useful\n than just a string value in the logs, or centralized logging system.\n - This method is slow when using multiple text tags since it needs to flatten the tags and\n remove empty elements to support Rails 4.\n - It is recommended to keep tags as a list without any empty values, or contain any child arrays.\n However, this api will convert:\n `logger.tagged([['first', nil], nil, ['more'], 'other'])`\n to:\n `logger.tagged('first', 'more', 'other')`\n - For better performance with clean tags, see `SemanticLogger.tagged`.", "docstring_tokens": ["Add", "the", "tags", "or", "named", "tags", "to", "the", "list", "of", "tags", "to", "log", "for", "this", "thread", "whilst", "the", "supplied", "block", "is", "active", "."], "sha": "0196730749a6912fbd177c099d76be17be901e0b", "url": "https://github.com/rocketjob/semantic_logger/blob/0196730749a6912fbd177c099d76be17be901e0b/lib/semantic_logger/base.rb#L189-L200", "partition": "test"} {"repo": "rocketjob/semantic_logger", "path": "lib/semantic_logger/base.rb", "func_name": "SemanticLogger.Base.push_tags", "original_string": "def push_tags(*tags)\n # Need to flatten and reject empties to support calls from Rails 4\n new_tags = tags.flatten.collect(&:to_s).reject(&:empty?)\n SemanticLogger.push_tags(*new_tags)\n end", "language": "ruby", "code": "def push_tags(*tags)\n # Need to flatten and reject empties to support calls from Rails 4\n new_tags = tags.flatten.collect(&:to_s).reject(&:empty?)\n SemanticLogger.push_tags(*new_tags)\n end", "code_tokens": ["def", "push_tags", "(", "*", "tags", ")", "# Need to flatten and reject empties to support calls from Rails 4", "new_tags", "=", "tags", ".", "flatten", ".", "collect", "(", ":to_s", ")", ".", "reject", "(", ":empty?", ")", "SemanticLogger", ".", "push_tags", "(", "new_tags", ")", "end"], "docstring": "Returns the list of tags pushed after flattening them out and removing blanks\n\n Note:\n - This method is slow since it needs to flatten the tags and remove empty elements\n to support Rails 4.\n - For better performance with clean tags, use `SemanticLogger.push_tags`", "docstring_tokens": ["Returns", "the", "list", "of", "tags", "pushed", "after", "flattening", "them", "out", "and", "removing", "blanks"], "sha": "0196730749a6912fbd177c099d76be17be901e0b", "url": "https://github.com/rocketjob/semantic_logger/blob/0196730749a6912fbd177c099d76be17be901e0b/lib/semantic_logger/base.rb#L220-L224", "partition": "test"} {"repo": "rocketjob/semantic_logger", "path": "lib/semantic_logger/base.rb", "func_name": "SemanticLogger.Base.filtered?", "original_string": "def filtered?(log)\n return false if @filter.nil?\n\n @filter.is_a?(Regexp) ? (@filter =~ log.name).nil? : @filter.call(log) != true\n end", "language": "ruby", "code": "def filtered?(log)\n return false if @filter.nil?\n\n @filter.is_a?(Regexp) ? (@filter =~ log.name).nil? : @filter.call(log) != true\n end", "code_tokens": ["def", "filtered?", "(", "log", ")", "return", "false", "if", "@filter", ".", "nil?", "@filter", ".", "is_a?", "(", "Regexp", ")", "?", "(", "@filter", "=~", "log", ".", "name", ")", ".", "nil?", ":", "@filter", ".", "call", "(", "log", ")", "!=", "true", "end"], "docstring": "Whether to log the supplied message based on the current filter if any", "docstring_tokens": ["Whether", "to", "log", "the", "supplied", "message", "based", "on", "the", "current", "filter", "if", "any"], "sha": "0196730749a6912fbd177c099d76be17be901e0b", "url": "https://github.com/rocketjob/semantic_logger/blob/0196730749a6912fbd177c099d76be17be901e0b/lib/semantic_logger/base.rb#L305-L309", "partition": "test"} {"repo": "rocketjob/semantic_logger", "path": "lib/semantic_logger/base.rb", "func_name": "SemanticLogger.Base.log_internal", "original_string": "def log_internal(level, index, message = nil, payload = nil, exception = nil, &block)\n log = Log.new(name, level, index)\n should_log =\n if payload.nil? && exception.nil? && message.is_a?(Hash)\n # Check if someone just logged a hash payload instead of meaning to call semantic logger\n if message.key?(:message) || message.key?(:payload) || message.key?(:exception) || message.key?(:metric)\n log.assign(message)\n else\n log.assign_positional(nil, message, nil, &block)\n end\n else\n log.assign_positional(message, payload, exception, &block)\n end\n\n # Log level may change during assign due to :on_exception_level\n self.log(log) if should_log && should_log?(log)\n end", "language": "ruby", "code": "def log_internal(level, index, message = nil, payload = nil, exception = nil, &block)\n log = Log.new(name, level, index)\n should_log =\n if payload.nil? && exception.nil? && message.is_a?(Hash)\n # Check if someone just logged a hash payload instead of meaning to call semantic logger\n if message.key?(:message) || message.key?(:payload) || message.key?(:exception) || message.key?(:metric)\n log.assign(message)\n else\n log.assign_positional(nil, message, nil, &block)\n end\n else\n log.assign_positional(message, payload, exception, &block)\n end\n\n # Log level may change during assign due to :on_exception_level\n self.log(log) if should_log && should_log?(log)\n end", "code_tokens": ["def", "log_internal", "(", "level", ",", "index", ",", "message", "=", "nil", ",", "payload", "=", "nil", ",", "exception", "=", "nil", ",", "&", "block", ")", "log", "=", "Log", ".", "new", "(", "name", ",", "level", ",", "index", ")", "should_log", "=", "if", "payload", ".", "nil?", "&&", "exception", ".", "nil?", "&&", "message", ".", "is_a?", "(", "Hash", ")", "# Check if someone just logged a hash payload instead of meaning to call semantic logger", "if", "message", ".", "key?", "(", ":message", ")", "||", "message", ".", "key?", "(", ":payload", ")", "||", "message", ".", "key?", "(", ":exception", ")", "||", "message", ".", "key?", "(", ":metric", ")", "log", ".", "assign", "(", "message", ")", "else", "log", ".", "assign_positional", "(", "nil", ",", "message", ",", "nil", ",", "block", ")", "end", "else", "log", ".", "assign_positional", "(", "message", ",", "payload", ",", "exception", ",", "block", ")", "end", "# Log level may change during assign due to :on_exception_level", "self", ".", "log", "(", "log", ")", "if", "should_log", "&&", "should_log?", "(", "log", ")", "end"], "docstring": "Log message at the specified level", "docstring_tokens": ["Log", "message", "at", "the", "specified", "level"], "sha": "0196730749a6912fbd177c099d76be17be901e0b", "url": "https://github.com/rocketjob/semantic_logger/blob/0196730749a6912fbd177c099d76be17be901e0b/lib/semantic_logger/base.rb#L317-L333", "partition": "test"} {"repo": "rocketjob/semantic_logger", "path": "lib/semantic_logger/base.rb", "func_name": "SemanticLogger.Base.measure_internal", "original_string": "def measure_internal(level, index, message, params)\n exception = nil\n result = nil\n # Single parameter is a hash\n if params.empty? && message.is_a?(Hash)\n params = message\n message = nil\n end\n start = Process.clock_gettime(Process::CLOCK_MONOTONIC)\n begin\n if block_given?\n result =\n if (silence_level = params[:silence])\n # In case someone accidentally sets `silence: true` instead of `silence: :error`\n silence_level = :error if silence_level == true\n silence(silence_level) { yield(params) }\n else\n yield(params)\n end\n end\n rescue Exception => exc\n exception = exc\n ensure\n # Must use ensure block otherwise a `return` in the yield above will skip the log entry\n log = Log.new(name, level, index)\n exception ||= params[:exception]\n message = params[:message] if params[:message]\n duration =\n if block_given?\n 1_000.0 * (Process.clock_gettime(Process::CLOCK_MONOTONIC) - start)\n else\n params[:duration] || raise('Mandatory block missing when :duration option is not supplied')\n end\n\n # Extract options after block completes so that block can modify any of the options\n payload = params[:payload]\n\n # May return false due to elastic logging\n should_log = log.assign(\n message: message,\n payload: payload,\n min_duration: params[:min_duration] || 0.0,\n exception: exception,\n metric: params[:metric],\n metric_amount: params[:metric_amount],\n duration: duration,\n log_exception: params[:log_exception] || :partial,\n on_exception_level: params[:on_exception_level]\n )\n\n # Log level may change during assign due to :on_exception_level\n self.log(log) if should_log && should_log?(log)\n raise exception if exception\n result\n end\n end", "language": "ruby", "code": "def measure_internal(level, index, message, params)\n exception = nil\n result = nil\n # Single parameter is a hash\n if params.empty? && message.is_a?(Hash)\n params = message\n message = nil\n end\n start = Process.clock_gettime(Process::CLOCK_MONOTONIC)\n begin\n if block_given?\n result =\n if (silence_level = params[:silence])\n # In case someone accidentally sets `silence: true` instead of `silence: :error`\n silence_level = :error if silence_level == true\n silence(silence_level) { yield(params) }\n else\n yield(params)\n end\n end\n rescue Exception => exc\n exception = exc\n ensure\n # Must use ensure block otherwise a `return` in the yield above will skip the log entry\n log = Log.new(name, level, index)\n exception ||= params[:exception]\n message = params[:message] if params[:message]\n duration =\n if block_given?\n 1_000.0 * (Process.clock_gettime(Process::CLOCK_MONOTONIC) - start)\n else\n params[:duration] || raise('Mandatory block missing when :duration option is not supplied')\n end\n\n # Extract options after block completes so that block can modify any of the options\n payload = params[:payload]\n\n # May return false due to elastic logging\n should_log = log.assign(\n message: message,\n payload: payload,\n min_duration: params[:min_duration] || 0.0,\n exception: exception,\n metric: params[:metric],\n metric_amount: params[:metric_amount],\n duration: duration,\n log_exception: params[:log_exception] || :partial,\n on_exception_level: params[:on_exception_level]\n )\n\n # Log level may change during assign due to :on_exception_level\n self.log(log) if should_log && should_log?(log)\n raise exception if exception\n result\n end\n end", "code_tokens": ["def", "measure_internal", "(", "level", ",", "index", ",", "message", ",", "params", ")", "exception", "=", "nil", "result", "=", "nil", "# Single parameter is a hash", "if", "params", ".", "empty?", "&&", "message", ".", "is_a?", "(", "Hash", ")", "params", "=", "message", "message", "=", "nil", "end", "start", "=", "Process", ".", "clock_gettime", "(", "Process", "::", "CLOCK_MONOTONIC", ")", "begin", "if", "block_given?", "result", "=", "if", "(", "silence_level", "=", "params", "[", ":silence", "]", ")", "# In case someone accidentally sets `silence: true` instead of `silence: :error`", "silence_level", "=", ":error", "if", "silence_level", "==", "true", "silence", "(", "silence_level", ")", "{", "yield", "(", "params", ")", "}", "else", "yield", "(", "params", ")", "end", "end", "rescue", "Exception", "=>", "exc", "exception", "=", "exc", "ensure", "# Must use ensure block otherwise a `return` in the yield above will skip the log entry", "log", "=", "Log", ".", "new", "(", "name", ",", "level", ",", "index", ")", "exception", "||=", "params", "[", ":exception", "]", "message", "=", "params", "[", ":message", "]", "if", "params", "[", ":message", "]", "duration", "=", "if", "block_given?", "1_000.0", "*", "(", "Process", ".", "clock_gettime", "(", "Process", "::", "CLOCK_MONOTONIC", ")", "-", "start", ")", "else", "params", "[", ":duration", "]", "||", "raise", "(", "'Mandatory block missing when :duration option is not supplied'", ")", "end", "# Extract options after block completes so that block can modify any of the options", "payload", "=", "params", "[", ":payload", "]", "# May return false due to elastic logging", "should_log", "=", "log", ".", "assign", "(", "message", ":", "message", ",", "payload", ":", "payload", ",", "min_duration", ":", "params", "[", ":min_duration", "]", "||", "0.0", ",", "exception", ":", "exception", ",", "metric", ":", "params", "[", ":metric", "]", ",", "metric_amount", ":", "params", "[", ":metric_amount", "]", ",", "duration", ":", "duration", ",", "log_exception", ":", "params", "[", ":log_exception", "]", "||", ":partial", ",", "on_exception_level", ":", "params", "[", ":on_exception_level", "]", ")", "# Log level may change during assign due to :on_exception_level", "self", ".", "log", "(", "log", ")", "if", "should_log", "&&", "should_log?", "(", "log", ")", "raise", "exception", "if", "exception", "result", "end", "end"], "docstring": "Measure the supplied block and log the message", "docstring_tokens": ["Measure", "the", "supplied", "block", "and", "log", "the", "message"], "sha": "0196730749a6912fbd177c099d76be17be901e0b", "url": "https://github.com/rocketjob/semantic_logger/blob/0196730749a6912fbd177c099d76be17be901e0b/lib/semantic_logger/base.rb#L336-L391", "partition": "test"} {"repo": "rocketjob/semantic_logger", "path": "lib/semantic_logger/base.rb", "func_name": "SemanticLogger.Base.measure_method", "original_string": "def measure_method(index:,\n level:,\n message:,\n min_duration:,\n metric:,\n log_exception:,\n on_exception_level:)\n\n # Ignores filter, silence, payload\n exception = nil\n start = Process.clock_gettime(Process::CLOCK_MONOTONIC)\n begin\n yield\n rescue Exception => exc\n exception = exc\n ensure\n log = Log.new(name, level, index)\n # May return false due to elastic logging\n should_log = log.assign(\n message: message,\n min_duration: min_duration,\n exception: exception,\n metric: metric,\n duration: 1_000.0 * (Process.clock_gettime(Process::CLOCK_MONOTONIC) - start),\n log_exception: log_exception,\n on_exception_level: on_exception_level\n )\n\n # Log level may change during assign due to :on_exception_level\n log(log) if should_log && should_log?(log)\n raise exception if exception\n end\n end", "language": "ruby", "code": "def measure_method(index:,\n level:,\n message:,\n min_duration:,\n metric:,\n log_exception:,\n on_exception_level:)\n\n # Ignores filter, silence, payload\n exception = nil\n start = Process.clock_gettime(Process::CLOCK_MONOTONIC)\n begin\n yield\n rescue Exception => exc\n exception = exc\n ensure\n log = Log.new(name, level, index)\n # May return false due to elastic logging\n should_log = log.assign(\n message: message,\n min_duration: min_duration,\n exception: exception,\n metric: metric,\n duration: 1_000.0 * (Process.clock_gettime(Process::CLOCK_MONOTONIC) - start),\n log_exception: log_exception,\n on_exception_level: on_exception_level\n )\n\n # Log level may change during assign due to :on_exception_level\n log(log) if should_log && should_log?(log)\n raise exception if exception\n end\n end", "code_tokens": ["def", "measure_method", "(", "index", ":", ",", "level", ":", ",", "message", ":", ",", "min_duration", ":", ",", "metric", ":", ",", "log_exception", ":", ",", "on_exception_level", ":", ")", "# Ignores filter, silence, payload", "exception", "=", "nil", "start", "=", "Process", ".", "clock_gettime", "(", "Process", "::", "CLOCK_MONOTONIC", ")", "begin", "yield", "rescue", "Exception", "=>", "exc", "exception", "=", "exc", "ensure", "log", "=", "Log", ".", "new", "(", "name", ",", "level", ",", "index", ")", "# May return false due to elastic logging", "should_log", "=", "log", ".", "assign", "(", "message", ":", "message", ",", "min_duration", ":", "min_duration", ",", "exception", ":", "exception", ",", "metric", ":", "metric", ",", "duration", ":", "1_000.0", "*", "(", "Process", ".", "clock_gettime", "(", "Process", "::", "CLOCK_MONOTONIC", ")", "-", "start", ")", ",", "log_exception", ":", "log_exception", ",", "on_exception_level", ":", "on_exception_level", ")", "# Log level may change during assign due to :on_exception_level", "log", "(", "log", ")", "if", "should_log", "&&", "should_log?", "(", "log", ")", "raise", "exception", "if", "exception", "end", "end"], "docstring": "For measuring methods and logging their duration.", "docstring_tokens": ["For", "measuring", "methods", "and", "logging", "their", "duration", "."], "sha": "0196730749a6912fbd177c099d76be17be901e0b", "url": "https://github.com/rocketjob/semantic_logger/blob/0196730749a6912fbd177c099d76be17be901e0b/lib/semantic_logger/base.rb#L394-L426", "partition": "test"} {"repo": "rocketjob/semantic_logger", "path": "lib/semantic_logger/logger.rb", "func_name": "SemanticLogger.Logger.log", "original_string": "def log(log, message = nil, progname = nil, &block)\n # Compatibility with ::Logger\n return add(log, message, progname, &block) unless log.is_a?(SemanticLogger::Log)\n\n Logger.call_subscribers(log)\n\n Logger.processor.log(log)\n end", "language": "ruby", "code": "def log(log, message = nil, progname = nil, &block)\n # Compatibility with ::Logger\n return add(log, message, progname, &block) unless log.is_a?(SemanticLogger::Log)\n\n Logger.call_subscribers(log)\n\n Logger.processor.log(log)\n end", "code_tokens": ["def", "log", "(", "log", ",", "message", "=", "nil", ",", "progname", "=", "nil", ",", "&", "block", ")", "# Compatibility with ::Logger", "return", "add", "(", "log", ",", "message", ",", "progname", ",", "block", ")", "unless", "log", ".", "is_a?", "(", "SemanticLogger", "::", "Log", ")", "Logger", ".", "call_subscribers", "(", "log", ")", "Logger", ".", "processor", ".", "log", "(", "log", ")", "end"], "docstring": "Returns a Logger instance\n\n Return the logger for a specific class, supports class specific log levels\n logger = SemanticLogger::Logger.new(self)\n OR\n logger = SemanticLogger::Logger.new('MyClass')\n\n Parameters:\n klass\n A class, module or a string with the application/class name\n to be used in the logger\n\n level\n The initial log level to start with for this logger instance\n Default: SemanticLogger.default_level\n\n filter [Regexp|Proc]\n RegExp: Only include log messages where the class name matches the supplied\n regular expression. All other messages will be ignored\n Proc: Only include log messages where the supplied Proc returns true\n The Proc must return true or false\n Place log request on the queue for the Appender thread to write to each\n appender in the order that they were registered\n\n Subscribers are called inline before handing off to the queue so that\n they can capture additional context information as needed.", "docstring_tokens": ["Returns", "a", "Logger", "instance"], "sha": "0196730749a6912fbd177c099d76be17be901e0b", "url": "https://github.com/rocketjob/semantic_logger/blob/0196730749a6912fbd177c099d76be17be901e0b/lib/semantic_logger/logger.rb#L57-L64", "partition": "test"} {"repo": "rocketjob/semantic_logger", "path": "lib/semantic_logger/log.rb", "func_name": "SemanticLogger.Log.assign", "original_string": "def assign(message: nil,\n payload: nil,\n min_duration: 0.0,\n exception: nil,\n metric: nil,\n metric_amount: nil,\n duration: nil,\n backtrace: nil,\n log_exception: :full,\n on_exception_level: nil,\n dimensions: nil)\n # Elastic logging: Log when :duration exceeds :min_duration\n # Except if there is an exception when it will always be logged\n if duration\n self.duration = duration\n return false if (duration < min_duration) && exception.nil?\n end\n\n self.message = message\n if payload && payload.is_a?(Hash)\n self.payload = payload\n elsif payload\n self.message = message.nil? ? payload.to_s : \"#{message} -- #{payload}\"\n self.payload = nil\n end\n\n if exception\n case log_exception\n when :full\n self.exception = exception\n when :partial\n self.message = \"#{message} -- Exception: #{exception.class}: #{exception.message}\"\n when nil, :none\n # Log the message without the exception that was raised\n nil\n else\n raise(ArgumentError, \"Invalid value:#{log_exception.inspect} for argument :log_exception\")\n end\n # On exception change the log level\n if on_exception_level\n self.level = on_exception_level\n self.level_index = Levels.index(level)\n end\n end\n\n if backtrace\n self.backtrace = Utils.extract_backtrace(backtrace)\n elsif level_index >= SemanticLogger.backtrace_level_index\n self.backtrace = Utils.extract_backtrace\n end\n\n if metric\n self.metric = metric\n self.metric_amount = metric_amount\n self.dimensions = dimensions\n end\n\n true\n end", "language": "ruby", "code": "def assign(message: nil,\n payload: nil,\n min_duration: 0.0,\n exception: nil,\n metric: nil,\n metric_amount: nil,\n duration: nil,\n backtrace: nil,\n log_exception: :full,\n on_exception_level: nil,\n dimensions: nil)\n # Elastic logging: Log when :duration exceeds :min_duration\n # Except if there is an exception when it will always be logged\n if duration\n self.duration = duration\n return false if (duration < min_duration) && exception.nil?\n end\n\n self.message = message\n if payload && payload.is_a?(Hash)\n self.payload = payload\n elsif payload\n self.message = message.nil? ? payload.to_s : \"#{message} -- #{payload}\"\n self.payload = nil\n end\n\n if exception\n case log_exception\n when :full\n self.exception = exception\n when :partial\n self.message = \"#{message} -- Exception: #{exception.class}: #{exception.message}\"\n when nil, :none\n # Log the message without the exception that was raised\n nil\n else\n raise(ArgumentError, \"Invalid value:#{log_exception.inspect} for argument :log_exception\")\n end\n # On exception change the log level\n if on_exception_level\n self.level = on_exception_level\n self.level_index = Levels.index(level)\n end\n end\n\n if backtrace\n self.backtrace = Utils.extract_backtrace(backtrace)\n elsif level_index >= SemanticLogger.backtrace_level_index\n self.backtrace = Utils.extract_backtrace\n end\n\n if metric\n self.metric = metric\n self.metric_amount = metric_amount\n self.dimensions = dimensions\n end\n\n true\n end", "code_tokens": ["def", "assign", "(", "message", ":", "nil", ",", "payload", ":", "nil", ",", "min_duration", ":", "0.0", ",", "exception", ":", "nil", ",", "metric", ":", "nil", ",", "metric_amount", ":", "nil", ",", "duration", ":", "nil", ",", "backtrace", ":", "nil", ",", "log_exception", ":", ":full", ",", "on_exception_level", ":", "nil", ",", "dimensions", ":", "nil", ")", "# Elastic logging: Log when :duration exceeds :min_duration", "# Except if there is an exception when it will always be logged", "if", "duration", "self", ".", "duration", "=", "duration", "return", "false", "if", "(", "duration", "<", "min_duration", ")", "&&", "exception", ".", "nil?", "end", "self", ".", "message", "=", "message", "if", "payload", "&&", "payload", ".", "is_a?", "(", "Hash", ")", "self", ".", "payload", "=", "payload", "elsif", "payload", "self", ".", "message", "=", "message", ".", "nil?", "?", "payload", ".", "to_s", ":", "\"#{message} -- #{payload}\"", "self", ".", "payload", "=", "nil", "end", "if", "exception", "case", "log_exception", "when", ":full", "self", ".", "exception", "=", "exception", "when", ":partial", "self", ".", "message", "=", "\"#{message} -- Exception: #{exception.class}: #{exception.message}\"", "when", "nil", ",", ":none", "# Log the message without the exception that was raised", "nil", "else", "raise", "(", "ArgumentError", ",", "\"Invalid value:#{log_exception.inspect} for argument :log_exception\"", ")", "end", "# On exception change the log level", "if", "on_exception_level", "self", ".", "level", "=", "on_exception_level", "self", ".", "level_index", "=", "Levels", ".", "index", "(", "level", ")", "end", "end", "if", "backtrace", "self", ".", "backtrace", "=", "Utils", ".", "extract_backtrace", "(", "backtrace", ")", "elsif", "level_index", ">=", "SemanticLogger", ".", "backtrace_level_index", "self", ".", "backtrace", "=", "Utils", ".", "extract_backtrace", "end", "if", "metric", "self", ".", "metric", "=", "metric", "self", ".", "metric_amount", "=", "metric_amount", "self", ".", "dimensions", "=", "dimensions", "end", "true", "end"], "docstring": "Assign named arguments to this log entry, supplying defaults where applicable\n\n Returns [true|false] whether this log entry should be logged\n\n Example:\n logger.info(name: 'value')", "docstring_tokens": ["Assign", "named", "arguments", "to", "this", "log", "entry", "supplying", "defaults", "where", "applicable"], "sha": "0196730749a6912fbd177c099d76be17be901e0b", "url": "https://github.com/rocketjob/semantic_logger/blob/0196730749a6912fbd177c099d76be17be901e0b/lib/semantic_logger/log.rb#L71-L129", "partition": "test"} {"repo": "rocketjob/semantic_logger", "path": "lib/semantic_logger/log.rb", "func_name": "SemanticLogger.Log.assign_positional", "original_string": "def assign_positional(message = nil, payload = nil, exception = nil)\n # Exception being logged?\n # Under JRuby a java exception is not a Ruby Exception\n # Java::JavaLang::ClassCastException.new.is_a?(Exception) => false\n if exception.nil? && payload.nil? && message.respond_to?(:backtrace) && message.respond_to?(:message)\n exception = message\n message = nil\n elsif exception.nil? && payload && payload.respond_to?(:backtrace) && payload.respond_to?(:message)\n exception = payload\n payload = nil\n elsif payload && !payload.is_a?(Hash)\n message = message.nil? ? payload : \"#{message} -- #{payload}\"\n payload = nil\n end\n\n # Add result of block as message or payload if not nil\n if block_given? && (result = yield)\n if result.is_a?(String)\n message = message.nil? ? result : \"#{message} -- #{result}\"\n assign(message: message, payload: payload, exception: exception)\n elsif message.nil? && result.is_a?(Hash) && %i[message payload exception].any? { |k| result.key? k }\n assign(result)\n elsif payload&.respond_to?(:merge)\n assign(message: message, payload: payload.merge(result), exception: exception)\n else\n assign(message: message, payload: result, exception: exception)\n end\n else\n assign(message: message, payload: payload, exception: exception)\n end\n end", "language": "ruby", "code": "def assign_positional(message = nil, payload = nil, exception = nil)\n # Exception being logged?\n # Under JRuby a java exception is not a Ruby Exception\n # Java::JavaLang::ClassCastException.new.is_a?(Exception) => false\n if exception.nil? && payload.nil? && message.respond_to?(:backtrace) && message.respond_to?(:message)\n exception = message\n message = nil\n elsif exception.nil? && payload && payload.respond_to?(:backtrace) && payload.respond_to?(:message)\n exception = payload\n payload = nil\n elsif payload && !payload.is_a?(Hash)\n message = message.nil? ? payload : \"#{message} -- #{payload}\"\n payload = nil\n end\n\n # Add result of block as message or payload if not nil\n if block_given? && (result = yield)\n if result.is_a?(String)\n message = message.nil? ? result : \"#{message} -- #{result}\"\n assign(message: message, payload: payload, exception: exception)\n elsif message.nil? && result.is_a?(Hash) && %i[message payload exception].any? { |k| result.key? k }\n assign(result)\n elsif payload&.respond_to?(:merge)\n assign(message: message, payload: payload.merge(result), exception: exception)\n else\n assign(message: message, payload: result, exception: exception)\n end\n else\n assign(message: message, payload: payload, exception: exception)\n end\n end", "code_tokens": ["def", "assign_positional", "(", "message", "=", "nil", ",", "payload", "=", "nil", ",", "exception", "=", "nil", ")", "# Exception being logged?", "# Under JRuby a java exception is not a Ruby Exception", "# Java::JavaLang::ClassCastException.new.is_a?(Exception) => false", "if", "exception", ".", "nil?", "&&", "payload", ".", "nil?", "&&", "message", ".", "respond_to?", "(", ":backtrace", ")", "&&", "message", ".", "respond_to?", "(", ":message", ")", "exception", "=", "message", "message", "=", "nil", "elsif", "exception", ".", "nil?", "&&", "payload", "&&", "payload", ".", "respond_to?", "(", ":backtrace", ")", "&&", "payload", ".", "respond_to?", "(", ":message", ")", "exception", "=", "payload", "payload", "=", "nil", "elsif", "payload", "&&", "!", "payload", ".", "is_a?", "(", "Hash", ")", "message", "=", "message", ".", "nil?", "?", "payload", ":", "\"#{message} -- #{payload}\"", "payload", "=", "nil", "end", "# Add result of block as message or payload if not nil", "if", "block_given?", "&&", "(", "result", "=", "yield", ")", "if", "result", ".", "is_a?", "(", "String", ")", "message", "=", "message", ".", "nil?", "?", "result", ":", "\"#{message} -- #{result}\"", "assign", "(", "message", ":", "message", ",", "payload", ":", "payload", ",", "exception", ":", "exception", ")", "elsif", "message", ".", "nil?", "&&", "result", ".", "is_a?", "(", "Hash", ")", "&&", "%i[", "message", "payload", "exception", "]", ".", "any?", "{", "|", "k", "|", "result", ".", "key?", "k", "}", "assign", "(", "result", ")", "elsif", "payload", "&.", "respond_to?", "(", ":merge", ")", "assign", "(", "message", ":", "message", ",", "payload", ":", "payload", ".", "merge", "(", "result", ")", ",", "exception", ":", "exception", ")", "else", "assign", "(", "message", ":", "message", ",", "payload", ":", "result", ",", "exception", ":", "exception", ")", "end", "else", "assign", "(", "message", ":", "message", ",", "payload", ":", "payload", ",", "exception", ":", "exception", ")", "end", "end"], "docstring": "Assign positional arguments to this log entry, supplying defaults where applicable\n\n Returns [true|false] whether this log entry should be logged\n\n Example:\n logger.info('value', :debug, 0, \"hello world\")", "docstring_tokens": ["Assign", "positional", "arguments", "to", "this", "log", "entry", "supplying", "defaults", "where", "applicable"], "sha": "0196730749a6912fbd177c099d76be17be901e0b", "url": "https://github.com/rocketjob/semantic_logger/blob/0196730749a6912fbd177c099d76be17be901e0b/lib/semantic_logger/log.rb#L137-L167", "partition": "test"} {"repo": "rocketjob/semantic_logger", "path": "lib/semantic_logger/log.rb", "func_name": "SemanticLogger.Log.each_exception", "original_string": "def each_exception\n # With thanks to https://github.com/bugsnag/bugsnag-ruby/blob/6348306e44323eee347896843d16c690cd7c4362/lib/bugsnag/notification.rb#L81\n depth = 0\n exceptions = []\n ex = exception\n while !ex.nil? && !exceptions.include?(ex) && exceptions.length < MAX_EXCEPTIONS_TO_UNWRAP\n exceptions << ex\n yield(ex, depth)\n\n depth += 1\n ex =\n if ex.respond_to?(:cause) && ex.cause\n ex.cause\n elsif ex.respond_to?(:continued_exception) && ex.continued_exception\n ex.continued_exception\n elsif ex.respond_to?(:original_exception) && ex.original_exception\n ex.original_exception\n end\n end\n end", "language": "ruby", "code": "def each_exception\n # With thanks to https://github.com/bugsnag/bugsnag-ruby/blob/6348306e44323eee347896843d16c690cd7c4362/lib/bugsnag/notification.rb#L81\n depth = 0\n exceptions = []\n ex = exception\n while !ex.nil? && !exceptions.include?(ex) && exceptions.length < MAX_EXCEPTIONS_TO_UNWRAP\n exceptions << ex\n yield(ex, depth)\n\n depth += 1\n ex =\n if ex.respond_to?(:cause) && ex.cause\n ex.cause\n elsif ex.respond_to?(:continued_exception) && ex.continued_exception\n ex.continued_exception\n elsif ex.respond_to?(:original_exception) && ex.original_exception\n ex.original_exception\n end\n end\n end", "code_tokens": ["def", "each_exception", "# With thanks to https://github.com/bugsnag/bugsnag-ruby/blob/6348306e44323eee347896843d16c690cd7c4362/lib/bugsnag/notification.rb#L81", "depth", "=", "0", "exceptions", "=", "[", "]", "ex", "=", "exception", "while", "!", "ex", ".", "nil?", "&&", "!", "exceptions", ".", "include?", "(", "ex", ")", "&&", "exceptions", ".", "length", "<", "MAX_EXCEPTIONS_TO_UNWRAP", "exceptions", "<<", "ex", "yield", "(", "ex", ",", "depth", ")", "depth", "+=", "1", "ex", "=", "if", "ex", ".", "respond_to?", "(", ":cause", ")", "&&", "ex", ".", "cause", "ex", ".", "cause", "elsif", "ex", ".", "respond_to?", "(", ":continued_exception", ")", "&&", "ex", ".", "continued_exception", "ex", ".", "continued_exception", "elsif", "ex", ".", "respond_to?", "(", ":original_exception", ")", "&&", "ex", ".", "original_exception", "ex", ".", "original_exception", "end", "end", "end"], "docstring": "Call the block for exception and any nested exception", "docstring_tokens": ["Call", "the", "block", "for", "exception", "and", "any", "nested", "exception"], "sha": "0196730749a6912fbd177c099d76be17be901e0b", "url": "https://github.com/rocketjob/semantic_logger/blob/0196730749a6912fbd177c099d76be17be901e0b/lib/semantic_logger/log.rb#L171-L190", "partition": "test"} {"repo": "rocketjob/semantic_logger", "path": "lib/semantic_logger/log.rb", "func_name": "SemanticLogger.Log.extract_file_and_line", "original_string": "def extract_file_and_line(stack, short_name = false)\n match = CALLER_REGEXP.match(stack.first)\n [short_name ? File.basename(match[1]) : match[1], match[2].to_i]\n end", "language": "ruby", "code": "def extract_file_and_line(stack, short_name = false)\n match = CALLER_REGEXP.match(stack.first)\n [short_name ? File.basename(match[1]) : match[1], match[2].to_i]\n end", "code_tokens": ["def", "extract_file_and_line", "(", "stack", ",", "short_name", "=", "false", ")", "match", "=", "CALLER_REGEXP", ".", "match", "(", "stack", ".", "first", ")", "[", "short_name", "?", "File", ".", "basename", "(", "match", "[", "1", "]", ")", ":", "match", "[", "1", "]", ",", "match", "[", "2", "]", ".", "to_i", "]", "end"], "docstring": "Extract the filename and line number from the last entry in the supplied backtrace", "docstring_tokens": ["Extract", "the", "filename", "and", "line", "number", "from", "the", "last", "entry", "in", "the", "supplied", "backtrace"], "sha": "0196730749a6912fbd177c099d76be17be901e0b", "url": "https://github.com/rocketjob/semantic_logger/blob/0196730749a6912fbd177c099d76be17be901e0b/lib/semantic_logger/log.rb#L254-L257", "partition": "test"} {"repo": "yuki24/did_you_mean", "path": "lib/did_you_mean/formatters/verbose_formatter.rb", "func_name": "DidYouMean.VerboseFormatter.message_for", "original_string": "def message_for(corrections)\n return \"\" if corrections.empty?\n\n output = \"\\n\\n Did you mean? \".dup\n output << corrections.join(\"\\n \")\n output << \"\\n \"\n end", "language": "ruby", "code": "def message_for(corrections)\n return \"\" if corrections.empty?\n\n output = \"\\n\\n Did you mean? \".dup\n output << corrections.join(\"\\n \")\n output << \"\\n \"\n end", "code_tokens": ["def", "message_for", "(", "corrections", ")", "return", "\"\"", "if", "corrections", ".", "empty?", "output", "=", "\"\\n\\n Did you mean? \"", ".", "dup", "output", "<<", "corrections", ".", "join", "(", "\"\\n \"", ")", "output", "<<", "\"\\n \"", "end"], "docstring": "Returns a human readable string that contains +corrections+. This\n formatter is designed to be less verbose to not take too much screen\n space while being helpful enough to the user.\n\n @example\n\n formatter = DidYouMean::PlainFormatter.new\n\n puts formatter.message_for([\"methods\", \"method\"])\n\n\n Did you mean? methods\n method\n\n # => nil", "docstring_tokens": ["Returns", "a", "human", "readable", "string", "that", "contains", "+", "corrections", "+", ".", "This", "formatter", "is", "designed", "to", "be", "less", "verbose", "to", "not", "take", "too", "much", "screen", "space", "while", "being", "helpful", "enough", "to", "the", "user", "."], "sha": "42acf90df5ae6b5a6128178ad213dd94cb75c2da", "url": "https://github.com/yuki24/did_you_mean/blob/42acf90df5ae6b5a6128178ad213dd94cb75c2da/lib/did_you_mean/formatters/verbose_formatter.rb#L41-L47", "partition": "test"} {"repo": "floraison/flor", "path": "lib/flor/unit/ganger.rb", "func_name": "Flor.Ganger.gather_vars", "original_string": "def gather_vars(executor, tconf, message)\n\n # try to return before a potentially costly call to executor.vars(nid)\n\n return nil if (tconf.keys & %w[ include_vars exclude_vars ]).empty?\n # default behaviour, don't pass variables to taskers\n\n iv = expand_filter(tconf['include_vars'])\n return nil if iv == false\n\n ev = expand_filter(tconf['exclude_vars'])\n return {} if ev == true\n\n vars = executor.vars(message['nid'])\n\n return vars if iv == true\n\n vars = vars.select { |k, v| var_match(k, iv) } if iv\n vars = vars.reject { |k, v| var_match(k, ev) } if ev\n\n vars\n end", "language": "ruby", "code": "def gather_vars(executor, tconf, message)\n\n # try to return before a potentially costly call to executor.vars(nid)\n\n return nil if (tconf.keys & %w[ include_vars exclude_vars ]).empty?\n # default behaviour, don't pass variables to taskers\n\n iv = expand_filter(tconf['include_vars'])\n return nil if iv == false\n\n ev = expand_filter(tconf['exclude_vars'])\n return {} if ev == true\n\n vars = executor.vars(message['nid'])\n\n return vars if iv == true\n\n vars = vars.select { |k, v| var_match(k, iv) } if iv\n vars = vars.reject { |k, v| var_match(k, ev) } if ev\n\n vars\n end", "code_tokens": ["def", "gather_vars", "(", "executor", ",", "tconf", ",", "message", ")", "# try to return before a potentially costly call to executor.vars(nid)", "return", "nil", "if", "(", "tconf", ".", "keys", "&", "%w[", "include_vars", "exclude_vars", "]", ")", ".", "empty?", "# default behaviour, don't pass variables to taskers", "iv", "=", "expand_filter", "(", "tconf", "[", "'include_vars'", "]", ")", "return", "nil", "if", "iv", "==", "false", "ev", "=", "expand_filter", "(", "tconf", "[", "'exclude_vars'", "]", ")", "return", "{", "}", "if", "ev", "==", "true", "vars", "=", "executor", ".", "vars", "(", "message", "[", "'nid'", "]", ")", "return", "vars", "if", "iv", "==", "true", "vars", "=", "vars", ".", "select", "{", "|", "k", ",", "v", "|", "var_match", "(", "k", ",", "iv", ")", "}", "if", "iv", "vars", "=", "vars", ".", "reject", "{", "|", "k", ",", "v", "|", "var_match", "(", "k", ",", "ev", ")", "}", "if", "ev", "vars", "end"], "docstring": "By default, taskers don't see the flor variables in the execution.\n If 'include_vars' or 'exclude_vars' is present in the configuration\n of the tasker, some or all of the variables are passed.", "docstring_tokens": ["By", "default", "taskers", "don", "t", "see", "the", "flor", "variables", "in", "the", "execution", ".", "If", "include_vars", "or", "exclude_vars", "is", "present", "in", "the", "configuration", "of", "the", "tasker", "some", "or", "all", "of", "the", "variables", "are", "passed", "."], "sha": "e55de19728cc4c507170a77b3df75b3f6787977c", "url": "https://github.com/floraison/flor/blob/e55de19728cc4c507170a77b3df75b3f6787977c/lib/flor/unit/ganger.rb#L138-L159", "partition": "test"} {"repo": "floraison/flor", "path": "lib/flor/unit/executor.rb", "func_name": "Flor.UnitExecutor.do_run", "original_string": "def do_run\n\n @unit.logger.log_run_start(self)\n\n counter_next('runs')\n\n t0 = Time.now\n\n (@unit.conf['exe_max_messages'] || 77).times do |i|\n\n break if @shutdown\n\n m = @messages.shift\n break unless m\n\n m = (@messages << m).shift \\\n if m['point'] == 'terminated' && @messages.any?\n #\n # handle 'terminated' messages last\n\n ms = process(m)\n\n @consumed << m\n\n ims, oms = ms.partition { |mm| mm['exid'] == @exid }\n # qui est \"in\", qui est \"out\"?\n\n counter_add('omsgs', oms.size)\n # keep track of \"out\" messages, messages to other executions\n\n @messages.concat(ims)\n @unit.storage.put_messages(oms)\n end\n\n @alive = false\n\n @execution.merge!(\n closing_messages: @consumed.select { |m|\n CLOSING_POINTS.include?(m['point']) })\n\n @unit.storage.put_execution(@execution)\n @unit.storage.consume(@consumed)\n\n @unit.storage.put_messages(@messages)\n\n du = Time.now - t0\n t0 = Flor.tstamp(t0)\n\n @unit.logger.log_run_end(self, t0, du)\n @unit.hooker.notify(self, make_end_message(t0, du, @execution['size']))\n\n @consumed.clear\n\n rescue Exception => exc\n\n# TODO eventually, have a dump dir\n fn =\n [\n 'flor',\n @unit.conf['env'], @unit.identifier, @exid,\n 'r' + counter('runs').to_s\n ].collect(&:to_s).join('_') + '.dump'\n\n @unit.logger.error(\n \"#{self.class}#do_run()\", exc, \"(dumping to #{fn})\")\n\n File.open(fn, 'wb') do |f|\n f.puts(Flor.to_pretty_s({\n execution: @execution,\n messages: @messages,\n consumed: @consumed,\n traps: @traps.collect(&:to_h),\n exid: @exid,\n alive: @alive,\n shutdown: @shutdown,\n thread: [ @thread.object_id, @thread.to_s ]\n }))\n f.puts('-' * 80)\n f.puts(on_do_run_exc(exc))\n end\n\n #puts on_do_run_exc(exc)\n # dump notification above\n end", "language": "ruby", "code": "def do_run\n\n @unit.logger.log_run_start(self)\n\n counter_next('runs')\n\n t0 = Time.now\n\n (@unit.conf['exe_max_messages'] || 77).times do |i|\n\n break if @shutdown\n\n m = @messages.shift\n break unless m\n\n m = (@messages << m).shift \\\n if m['point'] == 'terminated' && @messages.any?\n #\n # handle 'terminated' messages last\n\n ms = process(m)\n\n @consumed << m\n\n ims, oms = ms.partition { |mm| mm['exid'] == @exid }\n # qui est \"in\", qui est \"out\"?\n\n counter_add('omsgs', oms.size)\n # keep track of \"out\" messages, messages to other executions\n\n @messages.concat(ims)\n @unit.storage.put_messages(oms)\n end\n\n @alive = false\n\n @execution.merge!(\n closing_messages: @consumed.select { |m|\n CLOSING_POINTS.include?(m['point']) })\n\n @unit.storage.put_execution(@execution)\n @unit.storage.consume(@consumed)\n\n @unit.storage.put_messages(@messages)\n\n du = Time.now - t0\n t0 = Flor.tstamp(t0)\n\n @unit.logger.log_run_end(self, t0, du)\n @unit.hooker.notify(self, make_end_message(t0, du, @execution['size']))\n\n @consumed.clear\n\n rescue Exception => exc\n\n# TODO eventually, have a dump dir\n fn =\n [\n 'flor',\n @unit.conf['env'], @unit.identifier, @exid,\n 'r' + counter('runs').to_s\n ].collect(&:to_s).join('_') + '.dump'\n\n @unit.logger.error(\n \"#{self.class}#do_run()\", exc, \"(dumping to #{fn})\")\n\n File.open(fn, 'wb') do |f|\n f.puts(Flor.to_pretty_s({\n execution: @execution,\n messages: @messages,\n consumed: @consumed,\n traps: @traps.collect(&:to_h),\n exid: @exid,\n alive: @alive,\n shutdown: @shutdown,\n thread: [ @thread.object_id, @thread.to_s ]\n }))\n f.puts('-' * 80)\n f.puts(on_do_run_exc(exc))\n end\n\n #puts on_do_run_exc(exc)\n # dump notification above\n end", "code_tokens": ["def", "do_run", "@unit", ".", "logger", ".", "log_run_start", "(", "self", ")", "counter_next", "(", "'runs'", ")", "t0", "=", "Time", ".", "now", "(", "@unit", ".", "conf", "[", "'exe_max_messages'", "]", "||", "77", ")", ".", "times", "do", "|", "i", "|", "break", "if", "@shutdown", "m", "=", "@messages", ".", "shift", "break", "unless", "m", "m", "=", "(", "@messages", "<<", "m", ")", ".", "shift", "if", "m", "[", "'point'", "]", "==", "'terminated'", "&&", "@messages", ".", "any?", "#", "# handle 'terminated' messages last", "ms", "=", "process", "(", "m", ")", "@consumed", "<<", "m", "ims", ",", "oms", "=", "ms", ".", "partition", "{", "|", "mm", "|", "mm", "[", "'exid'", "]", "==", "@exid", "}", "# qui est \"in\", qui est \"out\"?", "counter_add", "(", "'omsgs'", ",", "oms", ".", "size", ")", "# keep track of \"out\" messages, messages to other executions", "@messages", ".", "concat", "(", "ims", ")", "@unit", ".", "storage", ".", "put_messages", "(", "oms", ")", "end", "@alive", "=", "false", "@execution", ".", "merge!", "(", "closing_messages", ":", "@consumed", ".", "select", "{", "|", "m", "|", "CLOSING_POINTS", ".", "include?", "(", "m", "[", "'point'", "]", ")", "}", ")", "@unit", ".", "storage", ".", "put_execution", "(", "@execution", ")", "@unit", ".", "storage", ".", "consume", "(", "@consumed", ")", "@unit", ".", "storage", ".", "put_messages", "(", "@messages", ")", "du", "=", "Time", ".", "now", "-", "t0", "t0", "=", "Flor", ".", "tstamp", "(", "t0", ")", "@unit", ".", "logger", ".", "log_run_end", "(", "self", ",", "t0", ",", "du", ")", "@unit", ".", "hooker", ".", "notify", "(", "self", ",", "make_end_message", "(", "t0", ",", "du", ",", "@execution", "[", "'size'", "]", ")", ")", "@consumed", ".", "clear", "rescue", "Exception", "=>", "exc", "# TODO eventually, have a dump dir", "fn", "=", "[", "'flor'", ",", "@unit", ".", "conf", "[", "'env'", "]", ",", "@unit", ".", "identifier", ",", "@exid", ",", "'r'", "+", "counter", "(", "'runs'", ")", ".", "to_s", "]", ".", "collect", "(", ":to_s", ")", ".", "join", "(", "'_'", ")", "+", "'.dump'", "@unit", ".", "logger", ".", "error", "(", "\"#{self.class}#do_run()\"", ",", "exc", ",", "\"(dumping to #{fn})\"", ")", "File", ".", "open", "(", "fn", ",", "'wb'", ")", "do", "|", "f", "|", "f", ".", "puts", "(", "Flor", ".", "to_pretty_s", "(", "{", "execution", ":", "@execution", ",", "messages", ":", "@messages", ",", "consumed", ":", "@consumed", ",", "traps", ":", "@traps", ".", "collect", "(", ":to_h", ")", ",", "exid", ":", "@exid", ",", "alive", ":", "@alive", ",", "shutdown", ":", "@shutdown", ",", "thread", ":", "[", "@thread", ".", "object_id", ",", "@thread", ".", "to_s", "]", "}", ")", ")", "f", ".", "puts", "(", "'-'", "*", "80", ")", "f", ".", "puts", "(", "on_do_run_exc", "(", "exc", ")", ")", "end", "#puts on_do_run_exc(exc)", "# dump notification above", "end"], "docstring": "point for messages that, after consumption, are conserved\n in the execution's \"closing_messages\" array", "docstring_tokens": ["point", "for", "messages", "that", "after", "consumption", "are", "conserved", "in", "the", "execution", "s", "closing_messages", "array"], "sha": "e55de19728cc4c507170a77b3df75b3f6787977c", "url": "https://github.com/floraison/flor/blob/e55de19728cc4c507170a77b3df75b3f6787977c/lib/flor/unit/executor.rb#L55-L138", "partition": "test"} {"repo": "floraison/flor", "path": "lib/flor/unit/taskers.rb", "func_name": "Flor.BasicTasker.route", "original_string": "def route(name)\n\n if name.is_a?(String)\n\n [ Flor.dup_and_merge(\n @message,\n 'tasker' => name, 'original_tasker' => @message['tasker'],\n 'routed' => true) ]\n\n else\n\n [ Flor.dup_and_merge(\n @message,\n 'routed' => !! name) ]\n end\n end", "language": "ruby", "code": "def route(name)\n\n if name.is_a?(String)\n\n [ Flor.dup_and_merge(\n @message,\n 'tasker' => name, 'original_tasker' => @message['tasker'],\n 'routed' => true) ]\n\n else\n\n [ Flor.dup_and_merge(\n @message,\n 'routed' => !! name) ]\n end\n end", "code_tokens": ["def", "route", "(", "name", ")", "if", "name", ".", "is_a?", "(", "String", ")", "[", "Flor", ".", "dup_and_merge", "(", "@message", ",", "'tasker'", "=>", "name", ",", "'original_tasker'", "=>", "@message", "[", "'tasker'", "]", ",", "'routed'", "=>", "true", ")", "]", "else", "[", "Flor", ".", "dup_and_merge", "(", "@message", ",", "'routed'", "=>", "!", "!", "name", ")", "]", "end", "end"], "docstring": "For domain taskers", "docstring_tokens": ["For", "domain", "taskers"], "sha": "e55de19728cc4c507170a77b3df75b3f6787977c", "url": "https://github.com/floraison/flor/blob/e55de19728cc4c507170a77b3df75b3f6787977c/lib/flor/unit/taskers.rb#L39-L54", "partition": "test"} {"repo": "floraison/flor", "path": "lib/flor/unit/waiter.rb", "func_name": "Flor.Waiter.row_waiter?", "original_string": "def row_waiter?\n\n @serie.find { |_, points|\n points.find { |po|\n pos = po.split(':')\n pos.length > 1 && ROW_PSEUDO_POINTS.include?(pos[0]) } }\n end", "language": "ruby", "code": "def row_waiter?\n\n @serie.find { |_, points|\n points.find { |po|\n pos = po.split(':')\n pos.length > 1 && ROW_PSEUDO_POINTS.include?(pos[0]) } }\n end", "code_tokens": ["def", "row_waiter?", "@serie", ".", "find", "{", "|", "_", ",", "points", "|", "points", ".", "find", "{", "|", "po", "|", "pos", "=", "po", ".", "split", "(", "':'", ")", "pos", ".", "length", ">", "1", "&&", "ROW_PSEUDO_POINTS", ".", "include?", "(", "pos", "[", "0", "]", ")", "}", "}", "end"], "docstring": "\"tasker\", not \"task\", since \"task\" is already a message point", "docstring_tokens": ["tasker", "not", "task", "since", "task", "is", "already", "a", "message", "point"], "sha": "e55de19728cc4c507170a77b3df75b3f6787977c", "url": "https://github.com/floraison/flor/blob/e55de19728cc4c507170a77b3df75b3f6787977c/lib/flor/unit/waiter.rb#L28-L34", "partition": "test"} {"repo": "floraison/flor", "path": "lib/flor/unit/models.rb", "func_name": "Flor.FlorModel.node", "original_string": "def node(reload=false)\n\n nid = @values[:nid]; return nil unless nid\n exe = execution(reload); return nil unless exe\n\n nodes = exe.data['nodes']; return nil unless nodes\n nodes[nid]\n end", "language": "ruby", "code": "def node(reload=false)\n\n nid = @values[:nid]; return nil unless nid\n exe = execution(reload); return nil unless exe\n\n nodes = exe.data['nodes']; return nil unless nodes\n nodes[nid]\n end", "code_tokens": ["def", "node", "(", "reload", "=", "false", ")", "nid", "=", "@values", "[", ":nid", "]", ";", "return", "nil", "unless", "nid", "exe", "=", "execution", "(", "reload", ")", ";", "return", "nil", "unless", "exe", "nodes", "=", "exe", ".", "data", "[", "'nodes'", "]", ";", "return", "nil", "unless", "nodes", "nodes", "[", "nid", "]", "end"], "docstring": "Returns the node hash linked to this model", "docstring_tokens": ["Returns", "the", "node", "hash", "linked", "to", "this", "model"], "sha": "e55de19728cc4c507170a77b3df75b3f6787977c", "url": "https://github.com/floraison/flor/blob/e55de19728cc4c507170a77b3df75b3f6787977c/lib/flor/unit/models.rb#L52-L59", "partition": "test"} {"repo": "floraison/flor", "path": "lib/flor/core/executor.rb", "func_name": "Flor.Executor.vars", "original_string": "def vars(nid, vs={})\n\n n = node(nid); return vs unless n\n\n (n['vars'] || {})\n .each { |k, v| vs[k] = Flor.dup(v) unless vs.has_key?(k) }\n\n pnid = n['parent']\n\n if @unit.loader && pnid == nil && n['vdomain'] != false\n\n @unit.loader.variables(n['vdomain'] || Flor.domain(@exid))\n .each { |k, v| vs[k] = Flor.dup(v) unless vs.has_key?(k) }\n end\n\n if cn = n['cnid']; vars(cn, vs); end\n vars(pnid, vs) if pnid\n\n vs\n end", "language": "ruby", "code": "def vars(nid, vs={})\n\n n = node(nid); return vs unless n\n\n (n['vars'] || {})\n .each { |k, v| vs[k] = Flor.dup(v) unless vs.has_key?(k) }\n\n pnid = n['parent']\n\n if @unit.loader && pnid == nil && n['vdomain'] != false\n\n @unit.loader.variables(n['vdomain'] || Flor.domain(@exid))\n .each { |k, v| vs[k] = Flor.dup(v) unless vs.has_key?(k) }\n end\n\n if cn = n['cnid']; vars(cn, vs); end\n vars(pnid, vs) if pnid\n\n vs\n end", "code_tokens": ["def", "vars", "(", "nid", ",", "vs", "=", "{", "}", ")", "n", "=", "node", "(", "nid", ")", ";", "return", "vs", "unless", "n", "(", "n", "[", "'vars'", "]", "||", "{", "}", ")", ".", "each", "{", "|", "k", ",", "v", "|", "vs", "[", "k", "]", "=", "Flor", ".", "dup", "(", "v", ")", "unless", "vs", ".", "has_key?", "(", "k", ")", "}", "pnid", "=", "n", "[", "'parent'", "]", "if", "@unit", ".", "loader", "&&", "pnid", "==", "nil", "&&", "n", "[", "'vdomain'", "]", "!=", "false", "@unit", ".", "loader", ".", "variables", "(", "n", "[", "'vdomain'", "]", "||", "Flor", ".", "domain", "(", "@exid", ")", ")", ".", "each", "{", "|", "k", ",", "v", "|", "vs", "[", "k", "]", "=", "Flor", ".", "dup", "(", "v", ")", "unless", "vs", ".", "has_key?", "(", "k", ")", "}", "end", "if", "cn", "=", "n", "[", "'cnid'", "]", ";", "vars", "(", "cn", ",", "vs", ")", ";", "end", "vars", "(", "pnid", ",", "vs", ")", "if", "pnid", "vs", "end"], "docstring": "Given a nid, returns a copy of all the var the node sees at that point.", "docstring_tokens": ["Given", "a", "nid", "returns", "a", "copy", "of", "all", "the", "var", "the", "node", "sees", "at", "that", "point", "."], "sha": "e55de19728cc4c507170a77b3df75b3f6787977c", "url": "https://github.com/floraison/flor/blob/e55de19728cc4c507170a77b3df75b3f6787977c/lib/flor/core/executor.rb#L105-L124", "partition": "test"} {"repo": "floraison/flor", "path": "lib/flor/core/executor.rb", "func_name": "Flor.Executor.lookup_on_error_parent", "original_string": "def lookup_on_error_parent(message)\n\n nd = Flor::Node.new(self, nil, message).on_error_parent\n nd ? nd.to_procedure_node : nil\n end", "language": "ruby", "code": "def lookup_on_error_parent(message)\n\n nd = Flor::Node.new(self, nil, message).on_error_parent\n nd ? nd.to_procedure_node : nil\n end", "code_tokens": ["def", "lookup_on_error_parent", "(", "message", ")", "nd", "=", "Flor", "::", "Node", ".", "new", "(", "self", ",", "nil", ",", "message", ")", ".", "on_error_parent", "nd", "?", "nd", ".", "to_procedure_node", ":", "nil", "end"], "docstring": "Return an empty array of new messages. No direct effect.\n\n Some trap, hook, and/or waiter might lie in wait though.", "docstring_tokens": ["Return", "an", "empty", "array", "of", "new", "messages", ".", "No", "direct", "effect", "."], "sha": "e55de19728cc4c507170a77b3df75b3f6787977c", "url": "https://github.com/floraison/flor/blob/e55de19728cc4c507170a77b3df75b3f6787977c/lib/flor/core/executor.rb#L528-L532", "partition": "test"} {"repo": "floraison/flor", "path": "lib/flor/unit/models/trap.rb", "func_name": "Flor.Trap.decrement", "original_string": "def decrement\n\n c = data['count']\n return false unless c\n\n c = c - 1\n data['count'] = c\n self[:status] = s = (c > 0) ? 'active' : 'consumed'\n\n self.update(\n content: Flor::Storage.to_blob(@flor_model_cache_data),\n status: s)\n\n c < 1\n end", "language": "ruby", "code": "def decrement\n\n c = data['count']\n return false unless c\n\n c = c - 1\n data['count'] = c\n self[:status] = s = (c > 0) ? 'active' : 'consumed'\n\n self.update(\n content: Flor::Storage.to_blob(@flor_model_cache_data),\n status: s)\n\n c < 1\n end", "code_tokens": ["def", "decrement", "c", "=", "data", "[", "'count'", "]", "return", "false", "unless", "c", "c", "=", "c", "-", "1", "data", "[", "'count'", "]", "=", "c", "self", "[", ":status", "]", "=", "s", "=", "(", "c", ">", "0", ")", "?", "'active'", ":", "'consumed'", "self", ".", "update", "(", "content", ":", "Flor", "::", "Storage", ".", "to_blob", "(", "@flor_model_cache_data", ")", ",", "status", ":", "s", ")", "c", "<", "1", "end"], "docstring": "returns true if the trap should be removed from the execution's list\n of traps", "docstring_tokens": ["returns", "true", "if", "the", "trap", "should", "be", "removed", "from", "the", "execution", "s", "list", "of", "traps"], "sha": "e55de19728cc4c507170a77b3df75b3f6787977c", "url": "https://github.com/floraison/flor/blob/e55de19728cc4c507170a77b3df75b3f6787977c/lib/flor/unit/models/trap.rb#L84-L98", "partition": "test"} {"repo": "QueueClassic/queue_classic", "path": "lib/queue_classic/worker.rb", "func_name": "QC.Worker.work", "original_string": "def work\n queue, job = lock_job\n if queue && job\n QC.log_yield(:at => \"work\", :job => job[:id]) do\n process(queue, job)\n end\n end\n end", "language": "ruby", "code": "def work\n queue, job = lock_job\n if queue && job\n QC.log_yield(:at => \"work\", :job => job[:id]) do\n process(queue, job)\n end\n end\n end", "code_tokens": ["def", "work", "queue", ",", "job", "=", "lock_job", "if", "queue", "&&", "job", "QC", ".", "log_yield", "(", ":at", "=>", "\"work\"", ",", ":job", "=>", "job", "[", ":id", "]", ")", "do", "process", "(", "queue", ",", "job", ")", "end", "end", "end"], "docstring": "Blocks on locking a job, and once a job is locked,\n it will process the job.", "docstring_tokens": ["Blocks", "on", "locking", "a", "job", "and", "once", "a", "job", "is", "locked", "it", "will", "process", "the", "job", "."], "sha": "4cdc9b8e804badf7dea7078dd81092972d292c14", "url": "https://github.com/QueueClassic/queue_classic/blob/4cdc9b8e804badf7dea7078dd81092972d292c14/lib/queue_classic/worker.rb#L71-L78", "partition": "test"} {"repo": "QueueClassic/queue_classic", "path": "lib/queue_classic/worker.rb", "func_name": "QC.Worker.lock_job", "original_string": "def lock_job\n log(:at => \"lock_job\")\n job = nil\n while @running\n @queues.each do |queue|\n if job = queue.lock\n return [queue, job]\n end\n end\n @conn_adapter.wait(@wait_interval, *@queues.map {|q| q.name})\n end\n end", "language": "ruby", "code": "def lock_job\n log(:at => \"lock_job\")\n job = nil\n while @running\n @queues.each do |queue|\n if job = queue.lock\n return [queue, job]\n end\n end\n @conn_adapter.wait(@wait_interval, *@queues.map {|q| q.name})\n end\n end", "code_tokens": ["def", "lock_job", "log", "(", ":at", "=>", "\"lock_job\"", ")", "job", "=", "nil", "while", "@running", "@queues", ".", "each", "do", "|", "queue", "|", "if", "job", "=", "queue", ".", "lock", "return", "[", "queue", ",", "job", "]", "end", "end", "@conn_adapter", ".", "wait", "(", "@wait_interval", ",", "@queues", ".", "map", "{", "|", "q", "|", "q", ".", "name", "}", ")", "end", "end"], "docstring": "Attempt to lock a job in the queue's table.\n If a job can be locked, this method returns an array with\n 2 elements. The first element is the queue from which the job was locked\n and the second is a hash representation of the job.\n If a job is returned, its locked_at column has been set in the\n job's row. It is the caller's responsibility to delete the job row\n from the table when the job is complete.", "docstring_tokens": ["Attempt", "to", "lock", "a", "job", "in", "the", "queue", "s", "table", ".", "If", "a", "job", "can", "be", "locked", "this", "method", "returns", "an", "array", "with", "2", "elements", ".", "The", "first", "element", "is", "the", "queue", "from", "which", "the", "job", "was", "locked", "and", "the", "second", "is", "a", "hash", "representation", "of", "the", "job", ".", "If", "a", "job", "is", "returned", "its", "locked_at", "column", "has", "been", "set", "in", "the", "job", "s", "row", ".", "It", "is", "the", "caller", "s", "responsibility", "to", "delete", "the", "job", "row", "from", "the", "table", "when", "the", "job", "is", "complete", "."], "sha": "4cdc9b8e804badf7dea7078dd81092972d292c14", "url": "https://github.com/QueueClassic/queue_classic/blob/4cdc9b8e804badf7dea7078dd81092972d292c14/lib/queue_classic/worker.rb#L87-L98", "partition": "test"} {"repo": "QueueClassic/queue_classic", "path": "lib/queue_classic/worker.rb", "func_name": "QC.Worker.call", "original_string": "def call(job)\n args = job[:args]\n receiver_str, _, message = job[:method].rpartition('.')\n receiver = eval(receiver_str)\n receiver.send(message, *args)\n end", "language": "ruby", "code": "def call(job)\n args = job[:args]\n receiver_str, _, message = job[:method].rpartition('.')\n receiver = eval(receiver_str)\n receiver.send(message, *args)\n end", "code_tokens": ["def", "call", "(", "job", ")", "args", "=", "job", "[", ":args", "]", "receiver_str", ",", "_", ",", "message", "=", "job", "[", ":method", "]", ".", "rpartition", "(", "'.'", ")", "receiver", "=", "eval", "(", "receiver_str", ")", "receiver", ".", "send", "(", "message", ",", "args", ")", "end"], "docstring": "Each job includes a method column. We will use ruby's eval\n to grab the ruby object from memory. We send the method to\n the object and pass the args.", "docstring_tokens": ["Each", "job", "includes", "a", "method", "column", ".", "We", "will", "use", "ruby", "s", "eval", "to", "grab", "the", "ruby", "object", "from", "memory", ".", "We", "send", "the", "method", "to", "the", "object", "and", "pass", "the", "args", "."], "sha": "4cdc9b8e804badf7dea7078dd81092972d292c14", "url": "https://github.com/QueueClassic/queue_classic/blob/4cdc9b8e804badf7dea7078dd81092972d292c14/lib/queue_classic/worker.rb#L130-L135", "partition": "test"} {"repo": "michelson/lazy_high_charts", "path": "lib/lazy_high_charts/high_chart.rb", "func_name": "LazyHighCharts.HighChart.method_missing", "original_string": "def method_missing(meth, opts = {})\n if meth.to_s == 'to_ary'\n super\n end\n\n if meth.to_s.end_with? '!'\n deep_merge_options meth[0..-2].to_sym, opts\n else\n merge_options meth, opts\n end\n end", "language": "ruby", "code": "def method_missing(meth, opts = {})\n if meth.to_s == 'to_ary'\n super\n end\n\n if meth.to_s.end_with? '!'\n deep_merge_options meth[0..-2].to_sym, opts\n else\n merge_options meth, opts\n end\n end", "code_tokens": ["def", "method_missing", "(", "meth", ",", "opts", "=", "{", "}", ")", "if", "meth", ".", "to_s", "==", "'to_ary'", "super", "end", "if", "meth", ".", "to_s", ".", "end_with?", "'!'", "deep_merge_options", "meth", "[", "0", "..", "-", "2", "]", ".", "to_sym", ",", "opts", "else", "merge_options", "meth", ",", "opts", "end", "end"], "docstring": "Pass other methods through to the javascript high_chart object.\n\n For instance: high_chart.grid(:color => \"#699\")", "docstring_tokens": ["Pass", "other", "methods", "through", "to", "the", "javascript", "high_chart", "object", "."], "sha": "a86783132a0baaa4a8cd2dda615bc5d67d62905c", "url": "https://github.com/michelson/lazy_high_charts/blob/a86783132a0baaa4a8cd2dda615bc5d67d62905c/lib/lazy_high_charts/high_chart.rb#L40-L50", "partition": "test"} {"repo": "biola/rack-cas", "path": "lib/rack-cas/url.rb", "func_name": "RackCAS.URL.remove_params", "original_string": "def remove_params(params)\n self.tap do |u|\n u.query_values = (u.query_values || {}).tap do |qv|\n params.each do |key, value|\n qv.delete key\n end\n end\n if u.query_values.empty?\n u.query_values = nil\n end\n end\n end", "language": "ruby", "code": "def remove_params(params)\n self.tap do |u|\n u.query_values = (u.query_values || {}).tap do |qv|\n params.each do |key, value|\n qv.delete key\n end\n end\n if u.query_values.empty?\n u.query_values = nil\n end\n end\n end", "code_tokens": ["def", "remove_params", "(", "params", ")", "self", ".", "tap", "do", "|", "u", "|", "u", ".", "query_values", "=", "(", "u", ".", "query_values", "||", "{", "}", ")", ".", "tap", "do", "|", "qv", "|", "params", ".", "each", "do", "|", "key", ",", "value", "|", "qv", ".", "delete", "key", "end", "end", "if", "u", ".", "query_values", ".", "empty?", "u", ".", "query_values", "=", "nil", "end", "end", "end"], "docstring": "params can be an array or a hash", "docstring_tokens": ["params", "can", "be", "an", "array", "or", "a", "hash"], "sha": "0fe5e801a9bedebc2172b572bb32962e34b6752f", "url": "https://github.com/biola/rack-cas/blob/0fe5e801a9bedebc2172b572bb32962e34b6752f/lib/rack-cas/url.rb#L35-L46", "partition": "test"} {"repo": "biola/rack-cas", "path": "lib/rack-cas/service_validation_response.rb", "func_name": "RackCAS.ServiceValidationResponse.parse_user_info", "original_string": "def parse_user_info(node)\n return nil if node.nil?\n {}.tap do |hash|\n node.children.each do |e|\n unless e.kind_of?(Nokogiri::XML::Text) || e.name == 'proxies'\n # There are no child elements\n if e.element_children.count == 0\n if hash.has_key?(e.name)\n hash[e.name] = [hash[e.name]] if hash[e.name].is_a? String\n hash[e.name] << e.content\n else\n hash[e.name] = e.content\n end\n elsif e.element_children.count\n # JASIG style extra attributes\n if e.name == 'attributes'\n hash.merge!(parse_user_info(e))\n else\n hash[e.name] = [] if hash[e.name].nil?\n hash[e.name] = [hash[e.name]] if hash[e.name].is_a? String\n hash[e.name].push(parse_user_info(e))\n end\n end\n end\n end\n end\n end", "language": "ruby", "code": "def parse_user_info(node)\n return nil if node.nil?\n {}.tap do |hash|\n node.children.each do |e|\n unless e.kind_of?(Nokogiri::XML::Text) || e.name == 'proxies'\n # There are no child elements\n if e.element_children.count == 0\n if hash.has_key?(e.name)\n hash[e.name] = [hash[e.name]] if hash[e.name].is_a? String\n hash[e.name] << e.content\n else\n hash[e.name] = e.content\n end\n elsif e.element_children.count\n # JASIG style extra attributes\n if e.name == 'attributes'\n hash.merge!(parse_user_info(e))\n else\n hash[e.name] = [] if hash[e.name].nil?\n hash[e.name] = [hash[e.name]] if hash[e.name].is_a? String\n hash[e.name].push(parse_user_info(e))\n end\n end\n end\n end\n end\n end", "code_tokens": ["def", "parse_user_info", "(", "node", ")", "return", "nil", "if", "node", ".", "nil?", "{", "}", ".", "tap", "do", "|", "hash", "|", "node", ".", "children", ".", "each", "do", "|", "e", "|", "unless", "e", ".", "kind_of?", "(", "Nokogiri", "::", "XML", "::", "Text", ")", "||", "e", ".", "name", "==", "'proxies'", "# There are no child elements", "if", "e", ".", "element_children", ".", "count", "==", "0", "if", "hash", ".", "has_key?", "(", "e", ".", "name", ")", "hash", "[", "e", ".", "name", "]", "=", "[", "hash", "[", "e", ".", "name", "]", "]", "if", "hash", "[", "e", ".", "name", "]", ".", "is_a?", "String", "hash", "[", "e", ".", "name", "]", "<<", "e", ".", "content", "else", "hash", "[", "e", ".", "name", "]", "=", "e", ".", "content", "end", "elsif", "e", ".", "element_children", ".", "count", "# JASIG style extra attributes", "if", "e", ".", "name", "==", "'attributes'", "hash", ".", "merge!", "(", "parse_user_info", "(", "e", ")", ")", "else", "hash", "[", "e", ".", "name", "]", "=", "[", "]", "if", "hash", "[", "e", ".", "name", "]", ".", "nil?", "hash", "[", "e", ".", "name", "]", "=", "[", "hash", "[", "e", ".", "name", "]", "]", "if", "hash", "[", "e", ".", "name", "]", ".", "is_a?", "String", "hash", "[", "e", ".", "name", "]", ".", "push", "(", "parse_user_info", "(", "e", ")", ")", "end", "end", "end", "end", "end", "end"], "docstring": "initially borrowed from omniauth-cas", "docstring_tokens": ["initially", "borrowed", "from", "omniauth", "-", "cas"], "sha": "0fe5e801a9bedebc2172b572bb32962e34b6752f", "url": "https://github.com/biola/rack-cas/blob/0fe5e801a9bedebc2172b572bb32962e34b6752f/lib/rack-cas/service_validation_response.rb#L101-L127", "partition": "test"} {"repo": "theforeman/foreman_remote_execution", "path": "lib/foreman_remote_execution_core/script_runner.rb", "func_name": "ForemanRemoteExecutionCore.ScriptRunner.run_async", "original_string": "def run_async(command)\n raise 'Async command already in progress' if @started\n @started = false\n @user_method.reset\n\n session.open_channel do |channel|\n channel.request_pty\n channel.on_data do |ch, data|\n publish_data(data, 'stdout') unless @user_method.filter_password?(data)\n @user_method.on_data(data, ch)\n end\n channel.on_extended_data { |ch, type, data| publish_data(data, 'stderr') }\n # standard exit of the command\n channel.on_request('exit-status') { |ch, data| publish_exit_status(data.read_long) }\n # on signal: sending the signal value (such as 'TERM')\n channel.on_request('exit-signal') do |ch, data|\n publish_exit_status(data.read_string)\n ch.close\n # wait for the channel to finish so that we know at the end\n # that the session is inactive\n ch.wait\n end\n channel.exec(command) do |_, success|\n @started = true\n raise('Error initializing command') unless success\n end\n end\n session.process(0) { !run_started? }\n return true\n end", "language": "ruby", "code": "def run_async(command)\n raise 'Async command already in progress' if @started\n @started = false\n @user_method.reset\n\n session.open_channel do |channel|\n channel.request_pty\n channel.on_data do |ch, data|\n publish_data(data, 'stdout') unless @user_method.filter_password?(data)\n @user_method.on_data(data, ch)\n end\n channel.on_extended_data { |ch, type, data| publish_data(data, 'stderr') }\n # standard exit of the command\n channel.on_request('exit-status') { |ch, data| publish_exit_status(data.read_long) }\n # on signal: sending the signal value (such as 'TERM')\n channel.on_request('exit-signal') do |ch, data|\n publish_exit_status(data.read_string)\n ch.close\n # wait for the channel to finish so that we know at the end\n # that the session is inactive\n ch.wait\n end\n channel.exec(command) do |_, success|\n @started = true\n raise('Error initializing command') unless success\n end\n end\n session.process(0) { !run_started? }\n return true\n end", "code_tokens": ["def", "run_async", "(", "command", ")", "raise", "'Async command already in progress'", "if", "@started", "@started", "=", "false", "@user_method", ".", "reset", "session", ".", "open_channel", "do", "|", "channel", "|", "channel", ".", "request_pty", "channel", ".", "on_data", "do", "|", "ch", ",", "data", "|", "publish_data", "(", "data", ",", "'stdout'", ")", "unless", "@user_method", ".", "filter_password?", "(", "data", ")", "@user_method", ".", "on_data", "(", "data", ",", "ch", ")", "end", "channel", ".", "on_extended_data", "{", "|", "ch", ",", "type", ",", "data", "|", "publish_data", "(", "data", ",", "'stderr'", ")", "}", "# standard exit of the command", "channel", ".", "on_request", "(", "'exit-status'", ")", "{", "|", "ch", ",", "data", "|", "publish_exit_status", "(", "data", ".", "read_long", ")", "}", "# on signal: sending the signal value (such as 'TERM')", "channel", ".", "on_request", "(", "'exit-signal'", ")", "do", "|", "ch", ",", "data", "|", "publish_exit_status", "(", "data", ".", "read_string", ")", "ch", ".", "close", "# wait for the channel to finish so that we know at the end", "# that the session is inactive", "ch", ".", "wait", "end", "channel", ".", "exec", "(", "command", ")", "do", "|", "_", ",", "success", "|", "@started", "=", "true", "raise", "(", "'Error initializing command'", ")", "unless", "success", "end", "end", "session", ".", "process", "(", "0", ")", "{", "!", "run_started?", "}", "return", "true", "end"], "docstring": "Initiates run of the remote command and yields the data when\n available. The yielding doesn't happen automatically, but as\n part of calling the `refresh` method.", "docstring_tokens": ["Initiates", "run", "of", "the", "remote", "command", "and", "yields", "the", "data", "when", "available", ".", "The", "yielding", "doesn", "t", "happen", "automatically", "but", "as", "part", "of", "calling", "the", "refresh", "method", "."], "sha": "b535e8a2e1343594ed0a663e19d1463782bfdef3", "url": "https://github.com/theforeman/foreman_remote_execution/blob/b535e8a2e1343594ed0a663e19d1463782bfdef3/lib/foreman_remote_execution_core/script_runner.rb#L291-L320", "partition": "test"} {"repo": "theforeman/foreman_remote_execution", "path": "lib/foreman_remote_execution_core/fake_script_runner.rb", "func_name": "ForemanRemoteExecutionCore.FakeScriptRunner.exit_code", "original_string": "def exit_code\n fail_chance = ENV.fetch('REX_SIMULATE_FAIL_CHANCE', 0).to_i\n fail_exitcode = ENV.fetch('REX_SIMULATE_EXIT', 0).to_i\n if fail_exitcode == 0 || fail_chance < (Random.rand * 100).round\n 0\n else\n fail_exitcode\n end\n end", "language": "ruby", "code": "def exit_code\n fail_chance = ENV.fetch('REX_SIMULATE_FAIL_CHANCE', 0).to_i\n fail_exitcode = ENV.fetch('REX_SIMULATE_EXIT', 0).to_i\n if fail_exitcode == 0 || fail_chance < (Random.rand * 100).round\n 0\n else\n fail_exitcode\n end\n end", "code_tokens": ["def", "exit_code", "fail_chance", "=", "ENV", ".", "fetch", "(", "'REX_SIMULATE_FAIL_CHANCE'", ",", "0", ")", ".", "to_i", "fail_exitcode", "=", "ENV", ".", "fetch", "(", "'REX_SIMULATE_EXIT'", ",", "0", ")", ".", "to_i", "if", "fail_exitcode", "==", "0", "||", "fail_chance", "<", "(", "Random", ".", "rand", "*", "100", ")", ".", "round", "0", "else", "fail_exitcode", "end", "end"], "docstring": "Decide if the execution should fail or not", "docstring_tokens": ["Decide", "if", "the", "execution", "should", "fail", "or", "not"], "sha": "b535e8a2e1343594ed0a663e19d1463782bfdef3", "url": "https://github.com/theforeman/foreman_remote_execution/blob/b535e8a2e1343594ed0a663e19d1463782bfdef3/lib/foreman_remote_execution_core/fake_script_runner.rb#L77-L85", "partition": "test"} {"repo": "solnic/transproc", "path": "lib/transproc/store.rb", "func_name": "Transproc.Store.import_method", "original_string": "def import_method(source, name, new_name = name)\n from = name.to_sym\n to = new_name.to_sym\n\n fn = source.is_a?(Registry) ? source.fetch(from) : source.method(from)\n self.class.new(methods.merge(to => fn))\n end", "language": "ruby", "code": "def import_method(source, name, new_name = name)\n from = name.to_sym\n to = new_name.to_sym\n\n fn = source.is_a?(Registry) ? source.fetch(from) : source.method(from)\n self.class.new(methods.merge(to => fn))\n end", "code_tokens": ["def", "import_method", "(", "source", ",", "name", ",", "new_name", "=", "name", ")", "from", "=", "name", ".", "to_sym", "to", "=", "new_name", ".", "to_sym", "fn", "=", "source", ".", "is_a?", "(", "Registry", ")", "?", "source", ".", "fetch", "(", "from", ")", ":", "source", ".", "method", "(", "from", ")", "self", ".", "class", ".", "new", "(", "methods", ".", "merge", "(", "to", "=>", "fn", ")", ")", "end"], "docstring": "Creates new immutable collection from the current one,\n updated with either the module's singleton method,\n or the proc having been imported from another module.\n\n @param [Module] source\n @param [Symbol] name\n @param [Symbol] new_name\n\n @return [Transproc::Store]", "docstring_tokens": ["Creates", "new", "immutable", "collection", "from", "the", "current", "one", "updated", "with", "either", "the", "module", "s", "singleton", "method", "or", "the", "proc", "having", "been", "imported", "from", "another", "module", "."], "sha": "52f22f2a3e6b7eab353ddec9dae0bff8b8b9b61a", "url": "https://github.com/solnic/transproc/blob/52f22f2a3e6b7eab353ddec9dae0bff8b8b9b61a/lib/transproc/store.rb#L88-L94", "partition": "test"} {"repo": "solnic/transproc", "path": "lib/transproc/store.rb", "func_name": "Transproc.Store.import_methods", "original_string": "def import_methods(source, names)\n names.inject(self) { |a, e| a.import_method(source, e) }\n end", "language": "ruby", "code": "def import_methods(source, names)\n names.inject(self) { |a, e| a.import_method(source, e) }\n end", "code_tokens": ["def", "import_methods", "(", "source", ",", "names", ")", "names", ".", "inject", "(", "self", ")", "{", "|", "a", ",", "e", "|", "a", ".", "import_method", "(", "source", ",", "e", ")", "}", "end"], "docstring": "Creates new immutable collection from the current one,\n updated with either the module's singleton methods,\n or the procs having been imported from another module.\n\n @param [Module] source\n @param [Array] names\n\n @return [Transproc::Store]", "docstring_tokens": ["Creates", "new", "immutable", "collection", "from", "the", "current", "one", "updated", "with", "either", "the", "module", "s", "singleton", "methods", "or", "the", "procs", "having", "been", "imported", "from", "another", "module", "."], "sha": "52f22f2a3e6b7eab353ddec9dae0bff8b8b9b61a", "url": "https://github.com/solnic/transproc/blob/52f22f2a3e6b7eab353ddec9dae0bff8b8b9b61a/lib/transproc/store.rb#L105-L107", "partition": "test"} {"repo": "solnic/transproc", "path": "lib/transproc/store.rb", "func_name": "Transproc.Store.import_all", "original_string": "def import_all(source)\n names = source.public_methods - Registry.instance_methods - Module.methods\n names -= [:initialize] # for compatibility with Rubinius\n names += source.store.methods.keys if source.is_a? Registry\n\n import_methods(source, names)\n end", "language": "ruby", "code": "def import_all(source)\n names = source.public_methods - Registry.instance_methods - Module.methods\n names -= [:initialize] # for compatibility with Rubinius\n names += source.store.methods.keys if source.is_a? Registry\n\n import_methods(source, names)\n end", "code_tokens": ["def", "import_all", "(", "source", ")", "names", "=", "source", ".", "public_methods", "-", "Registry", ".", "instance_methods", "-", "Module", ".", "methods", "names", "-=", "[", ":initialize", "]", "# for compatibility with Rubinius", "names", "+=", "source", ".", "store", ".", "methods", ".", "keys", "if", "source", ".", "is_a?", "Registry", "import_methods", "(", "source", ",", "names", ")", "end"], "docstring": "Creates new immutable collection from the current one,\n updated with all singleton methods and imported methods\n from the other module\n\n @param [Module] source The module to import procedures from\n\n @return [Transproc::Store]", "docstring_tokens": ["Creates", "new", "immutable", "collection", "from", "the", "current", "one", "updated", "with", "all", "singleton", "methods", "and", "imported", "methods", "from", "the", "other", "module"], "sha": "52f22f2a3e6b7eab353ddec9dae0bff8b8b9b61a", "url": "https://github.com/solnic/transproc/blob/52f22f2a3e6b7eab353ddec9dae0bff8b8b9b61a/lib/transproc/store.rb#L117-L123", "partition": "test"} {"repo": "solnic/transproc", "path": "lib/transproc/registry.rb", "func_name": "Transproc.Registry.[]", "original_string": "def [](fn, *args)\n fetched = fetch(fn)\n\n return Function.new(fetched, args: args, name: fn) unless already_wrapped?(fetched)\n args.empty? ? fetched : fetched.with(*args)\n end", "language": "ruby", "code": "def [](fn, *args)\n fetched = fetch(fn)\n\n return Function.new(fetched, args: args, name: fn) unless already_wrapped?(fetched)\n args.empty? ? fetched : fetched.with(*args)\n end", "code_tokens": ["def", "[]", "(", "fn", ",", "*", "args", ")", "fetched", "=", "fetch", "(", "fn", ")", "return", "Function", ".", "new", "(", "fetched", ",", "args", ":", "args", ",", "name", ":", "fn", ")", "unless", "already_wrapped?", "(", "fetched", ")", "args", ".", "empty?", "?", "fetched", ":", "fetched", ".", "with", "(", "args", ")", "end"], "docstring": "Builds the transformation\n\n @param [Proc, Symbol] fn\n A proc, a name of the module's own function, or a name of imported\n procedure from another module\n @param [Object, Array] args\n Args to be carried by the transproc\n\n @return [Transproc::Function]\n\n @alias :t", "docstring_tokens": ["Builds", "the", "transformation"], "sha": "52f22f2a3e6b7eab353ddec9dae0bff8b8b9b61a", "url": "https://github.com/solnic/transproc/blob/52f22f2a3e6b7eab353ddec9dae0bff8b8b9b61a/lib/transproc/registry.rb#L47-L52", "partition": "test"} {"repo": "solnic/transproc", "path": "lib/transproc/registry.rb", "func_name": "Transproc.Registry.fetch", "original_string": "def fetch(fn)\n return fn unless fn.instance_of? Symbol\n respond_to?(fn) ? method(fn) : store.fetch(fn)\n rescue\n raise FunctionNotFoundError.new(fn, self)\n end", "language": "ruby", "code": "def fetch(fn)\n return fn unless fn.instance_of? Symbol\n respond_to?(fn) ? method(fn) : store.fetch(fn)\n rescue\n raise FunctionNotFoundError.new(fn, self)\n end", "code_tokens": ["def", "fetch", "(", "fn", ")", "return", "fn", "unless", "fn", ".", "instance_of?", "Symbol", "respond_to?", "(", "fn", ")", "?", "method", "(", "fn", ")", ":", "store", ".", "fetch", "(", "fn", ")", "rescue", "raise", "FunctionNotFoundError", ".", "new", "(", "fn", ",", "self", ")", "end"], "docstring": "Gets the procedure for creating a transproc\n\n @param [#call, Symbol] fn\n Either the procedure, or the name of the method of the current module,\n or the registered key of imported procedure in a store.\n\n @return [#call]", "docstring_tokens": ["Gets", "the", "procedure", "for", "creating", "a", "transproc"], "sha": "52f22f2a3e6b7eab353ddec9dae0bff8b8b9b61a", "url": "https://github.com/solnic/transproc/blob/52f22f2a3e6b7eab353ddec9dae0bff8b8b9b61a/lib/transproc/registry.rb#L131-L136", "partition": "test"} {"repo": "solnic/transproc", "path": "lib/transproc/function.rb", "func_name": "Transproc.Function.to_ast", "original_string": "def to_ast\n args_ast = args.map { |arg| arg.respond_to?(:to_ast) ? arg.to_ast : arg }\n [name, args_ast]\n end", "language": "ruby", "code": "def to_ast\n args_ast = args.map { |arg| arg.respond_to?(:to_ast) ? arg.to_ast : arg }\n [name, args_ast]\n end", "code_tokens": ["def", "to_ast", "args_ast", "=", "args", ".", "map", "{", "|", "arg", "|", "arg", ".", "respond_to?", "(", ":to_ast", ")", "?", "arg", ".", "to_ast", ":", "arg", "}", "[", "name", ",", "args_ast", "]", "end"], "docstring": "Return a simple AST representation of this function\n\n @return [Array]\n\n @api public", "docstring_tokens": ["Return", "a", "simple", "AST", "representation", "of", "this", "function"], "sha": "52f22f2a3e6b7eab353ddec9dae0bff8b8b9b61a", "url": "https://github.com/solnic/transproc/blob/52f22f2a3e6b7eab353ddec9dae0bff8b8b9b61a/lib/transproc/function.rb#L87-L90", "partition": "test"} {"repo": "solnic/transproc", "path": "lib/transproc/function.rb", "func_name": "Transproc.Function.to_proc", "original_string": "def to_proc\n if args.size > 0\n proc { |*value| fn.call(*value, *args) }\n else\n fn.to_proc\n end\n end", "language": "ruby", "code": "def to_proc\n if args.size > 0\n proc { |*value| fn.call(*value, *args) }\n else\n fn.to_proc\n end\n end", "code_tokens": ["def", "to_proc", "if", "args", ".", "size", ">", "0", "proc", "{", "|", "*", "value", "|", "fn", ".", "call", "(", "value", ",", "args", ")", "}", "else", "fn", ".", "to_proc", "end", "end"], "docstring": "Converts a transproc to a simple proc\n\n @return [Proc]", "docstring_tokens": ["Converts", "a", "transproc", "to", "a", "simple", "proc"], "sha": "52f22f2a3e6b7eab353ddec9dae0bff8b8b9b61a", "url": "https://github.com/solnic/transproc/blob/52f22f2a3e6b7eab353ddec9dae0bff8b8b9b61a/lib/transproc/function.rb#L96-L102", "partition": "test"} {"repo": "ua-parser/uap-ruby", "path": "lib/user_agent_parser/parser.rb", "func_name": "UserAgentParser.Parser.from_pattern_match", "original_string": "def from_pattern_match(keys, pattern, match)\n keys.each_with_index.map do |key, idx|\n # Check if there is any replacement specified\n if pattern[key]\n interpolate(pattern[key], match)\n else\n # No replacement defined, just return correct match group\n match[idx + 1]\n end\n end\n end", "language": "ruby", "code": "def from_pattern_match(keys, pattern, match)\n keys.each_with_index.map do |key, idx|\n # Check if there is any replacement specified\n if pattern[key]\n interpolate(pattern[key], match)\n else\n # No replacement defined, just return correct match group\n match[idx + 1]\n end\n end\n end", "code_tokens": ["def", "from_pattern_match", "(", "keys", ",", "pattern", ",", "match", ")", "keys", ".", "each_with_index", ".", "map", "do", "|", "key", ",", "idx", "|", "# Check if there is any replacement specified", "if", "pattern", "[", "key", "]", "interpolate", "(", "pattern", "[", "key", "]", ",", "match", ")", "else", "# No replacement defined, just return correct match group", "match", "[", "idx", "+", "1", "]", "end", "end", "end"], "docstring": "Maps replacement keys to their values", "docstring_tokens": ["Maps", "replacement", "keys", "to", "their", "values"], "sha": "502f6544a888e4b76be9df7db54020e8f1aad6da", "url": "https://github.com/ua-parser/uap-ruby/blob/502f6544a888e4b76be9df7db54020e8f1aad6da/lib/user_agent_parser/parser.rb#L140-L150", "partition": "test"} {"repo": "ua-parser/uap-ruby", "path": "lib/user_agent_parser/parser.rb", "func_name": "UserAgentParser.Parser.interpolate", "original_string": "def interpolate(replacement, match)\n group_idx = replacement.index('$')\n return replacement if group_idx.nil?\n\n group_nbr = replacement[group_idx + 1]\n replacement.sub(\"$#{group_nbr}\", match[group_nbr.to_i])\n end", "language": "ruby", "code": "def interpolate(replacement, match)\n group_idx = replacement.index('$')\n return replacement if group_idx.nil?\n\n group_nbr = replacement[group_idx + 1]\n replacement.sub(\"$#{group_nbr}\", match[group_nbr.to_i])\n end", "code_tokens": ["def", "interpolate", "(", "replacement", ",", "match", ")", "group_idx", "=", "replacement", ".", "index", "(", "'$'", ")", "return", "replacement", "if", "group_idx", ".", "nil?", "group_nbr", "=", "replacement", "[", "group_idx", "+", "1", "]", "replacement", ".", "sub", "(", "\"$#{group_nbr}\"", ",", "match", "[", "group_nbr", ".", "to_i", "]", ")", "end"], "docstring": "Interpolates a string with data from matches if specified", "docstring_tokens": ["Interpolates", "a", "string", "with", "data", "from", "matches", "if", "specified"], "sha": "502f6544a888e4b76be9df7db54020e8f1aad6da", "url": "https://github.com/ua-parser/uap-ruby/blob/502f6544a888e4b76be9df7db54020e8f1aad6da/lib/user_agent_parser/parser.rb#L153-L159", "partition": "test"} {"repo": "achiurizo/consular", "path": "lib/consular/dsl.rb", "func_name": "Consular.DSL.before", "original_string": "def before(*commands, &block)\n context = (@_context[:before] ||= [])\n block_given? ? run_context(context, &block) : context.concat(commands)\n end", "language": "ruby", "code": "def before(*commands, &block)\n context = (@_context[:before] ||= [])\n block_given? ? run_context(context, &block) : context.concat(commands)\n end", "code_tokens": ["def", "before", "(", "*", "commands", ",", "&", "block", ")", "context", "=", "(", "@_context", "[", ":before", "]", "||=", "[", "]", ")", "block_given?", "?", "run_context", "(", "context", ",", "block", ")", ":", "context", ".", "concat", "(", "commands", ")", "end"], "docstring": "Run commands prior to each tab context.\n\n @param [Array] commands\n Commands to be executed.\n @param [Proc] block\n Proc of commands to run\n\n @example\n # Executes `whoami` before tab with `ls` and `gitx`\n window do\n before { run 'whoami' }\n tab 'ls'\n tab 'gitx'\n end\n\n @api public", "docstring_tokens": ["Run", "commands", "prior", "to", "each", "tab", "context", "."], "sha": "85bb4a86dd7665f5d93c5fd3d899fcd177cc3654", "url": "https://github.com/achiurizo/consular/blob/85bb4a86dd7665f5d93c5fd3d899fcd177cc3654/lib/consular/dsl.rb#L77-L80", "partition": "test"} {"repo": "achiurizo/consular", "path": "lib/consular/dsl.rb", "func_name": "Consular.DSL.window", "original_string": "def window(*args, &block)\n key = \"window#{@_windows.keys.size}\"\n options = args.extract_options!\n options[:name] = args.first unless args.empty?\n context = (@_windows[key] = window_hash.merge(:options => options))\n run_context context, &block\n end", "language": "ruby", "code": "def window(*args, &block)\n key = \"window#{@_windows.keys.size}\"\n options = args.extract_options!\n options[:name] = args.first unless args.empty?\n context = (@_windows[key] = window_hash.merge(:options => options))\n run_context context, &block\n end", "code_tokens": ["def", "window", "(", "*", "args", ",", "&", "block", ")", "key", "=", "\"window#{@_windows.keys.size}\"", "options", "=", "args", ".", "extract_options!", "options", "[", ":name", "]", "=", "args", ".", "first", "unless", "args", ".", "empty?", "context", "=", "(", "@_windows", "[", "key", "]", "=", "window_hash", ".", "merge", "(", ":options", "=>", "options", ")", ")", "run_context", "context", ",", "block", "end"], "docstring": "Run commands in the conext of a window.\n\n @param [Array] args\n Hash to pass options to each context of a window. Each core can\n implement the desired behavior for the window based on the options set here.\n Can also pass a string as first parameter which will be set as\n the :name\n @param [Proc] block\n block of commands to run in window context.\n\n @example\n window 'my project', :size => [80, 30] do\n run 'ps aux'\n end\n\n @api public", "docstring_tokens": ["Run", "commands", "in", "the", "conext", "of", "a", "window", "."], "sha": "85bb4a86dd7665f5d93c5fd3d899fcd177cc3654", "url": "https://github.com/achiurizo/consular/blob/85bb4a86dd7665f5d93c5fd3d899fcd177cc3654/lib/consular/dsl.rb#L98-L104", "partition": "test"} {"repo": "achiurizo/consular", "path": "lib/consular/dsl.rb", "func_name": "Consular.DSL.tab", "original_string": "def tab(*args, &block)\n tabs = @_context[:tabs]\n key = \"tab#{tabs.keys.size}\"\n return (tabs[key] = { :commands => args }) unless block_given?\n\n context = (tabs[key] = {:commands => []})\n options = args.extract_options!\n options[:name] = args.first unless args.empty?\n context[:options] = options\n\n run_context context, &block\n @_context = @_windows[@_windows.keys.last] # Jump back out into the context of the last window.\n end", "language": "ruby", "code": "def tab(*args, &block)\n tabs = @_context[:tabs]\n key = \"tab#{tabs.keys.size}\"\n return (tabs[key] = { :commands => args }) unless block_given?\n\n context = (tabs[key] = {:commands => []})\n options = args.extract_options!\n options[:name] = args.first unless args.empty?\n context[:options] = options\n\n run_context context, &block\n @_context = @_windows[@_windows.keys.last] # Jump back out into the context of the last window.\n end", "code_tokens": ["def", "tab", "(", "*", "args", ",", "&", "block", ")", "tabs", "=", "@_context", "[", ":tabs", "]", "key", "=", "\"tab#{tabs.keys.size}\"", "return", "(", "tabs", "[", "key", "]", "=", "{", ":commands", "=>", "args", "}", ")", "unless", "block_given?", "context", "=", "(", "tabs", "[", "key", "]", "=", "{", ":commands", "=>", "[", "]", "}", ")", "options", "=", "args", ".", "extract_options!", "options", "[", ":name", "]", "=", "args", ".", "first", "unless", "args", ".", "empty?", "context", "[", ":options", "]", "=", "options", "run_context", "context", ",", "block", "@_context", "=", "@_windows", "[", "@_windows", ".", "keys", ".", "last", "]", "# Jump back out into the context of the last window.", "end"], "docstring": "Run commands in the context of a tab.\n\n @param [Array] args\n Accepts either:\n - an array of string commands\n - a hash containing options for the tab.\n @param [Proc] block\n\n @example\n tab 'first tab', :settings => 'Grass' do\n run 'ps aux'\n end\n\n tab 'ls', 'gitx'\n\n @api public", "docstring_tokens": ["Run", "commands", "in", "the", "context", "of", "a", "tab", "."], "sha": "85bb4a86dd7665f5d93c5fd3d899fcd177cc3654", "url": "https://github.com/achiurizo/consular/blob/85bb4a86dd7665f5d93c5fd3d899fcd177cc3654/lib/consular/dsl.rb#L122-L134", "partition": "test"} {"repo": "achiurizo/consular", "path": "lib/consular/dsl.rb", "func_name": "Consular.DSL.run", "original_string": "def run(*commands)\n context = case\n when @_context.is_a?(Hash) && @_context[:tabs]\n @_context[:tabs]['default'][:commands]\n when @_context.is_a?(Hash)\n @_context[:commands]\n else\n @_context\n end\n context << commands.map { |c| c =~ /&$/ ? \"(#{c})\" : c }.join(\" && \")\n end", "language": "ruby", "code": "def run(*commands)\n context = case\n when @_context.is_a?(Hash) && @_context[:tabs]\n @_context[:tabs]['default'][:commands]\n when @_context.is_a?(Hash)\n @_context[:commands]\n else\n @_context\n end\n context << commands.map { |c| c =~ /&$/ ? \"(#{c})\" : c }.join(\" && \")\n end", "code_tokens": ["def", "run", "(", "*", "commands", ")", "context", "=", "case", "when", "@_context", ".", "is_a?", "(", "Hash", ")", "&&", "@_context", "[", ":tabs", "]", "@_context", "[", ":tabs", "]", "[", "'default'", "]", "[", ":commands", "]", "when", "@_context", ".", "is_a?", "(", "Hash", ")", "@_context", "[", ":commands", "]", "else", "@_context", "end", "context", "<<", "commands", ".", "map", "{", "|", "c", "|", "c", "=~", "/", "/", "?", "\"(#{c})\"", ":", "c", "}", ".", "join", "(", "\" && \"", ")", "end"], "docstring": "Store commands to run in context.\n\n @param [Array] commands\n Array of commands to be executed.\n\n @example\n run 'brew update', 'gitx'\n\n @api public", "docstring_tokens": ["Store", "commands", "to", "run", "in", "context", "."], "sha": "85bb4a86dd7665f5d93c5fd3d899fcd177cc3654", "url": "https://github.com/achiurizo/consular/blob/85bb4a86dd7665f5d93c5fd3d899fcd177cc3654/lib/consular/dsl.rb#L145-L155", "partition": "test"} {"repo": "aerospike/aerospike-client-ruby", "path": "lib/aerospike/command/command.rb", "func_name": "Aerospike.Command.set_write", "original_string": "def set_write(policy, operation, key, bins)\n begin_cmd\n field_count = estimate_key_size(key, policy)\n\n bins.each do |bin|\n estimate_operation_size_for_bin(bin)\n end\n\n size_buffer\n\n write_header_with_policy(policy, 0, INFO2_WRITE, field_count, bins.length)\n write_key(key, policy)\n\n bins.each do |bin|\n write_operation_for_bin(bin, operation)\n end\n\n end_cmd\n end", "language": "ruby", "code": "def set_write(policy, operation, key, bins)\n begin_cmd\n field_count = estimate_key_size(key, policy)\n\n bins.each do |bin|\n estimate_operation_size_for_bin(bin)\n end\n\n size_buffer\n\n write_header_with_policy(policy, 0, INFO2_WRITE, field_count, bins.length)\n write_key(key, policy)\n\n bins.each do |bin|\n write_operation_for_bin(bin, operation)\n end\n\n end_cmd\n end", "code_tokens": ["def", "set_write", "(", "policy", ",", "operation", ",", "key", ",", "bins", ")", "begin_cmd", "field_count", "=", "estimate_key_size", "(", "key", ",", "policy", ")", "bins", ".", "each", "do", "|", "bin", "|", "estimate_operation_size_for_bin", "(", "bin", ")", "end", "size_buffer", "write_header_with_policy", "(", "policy", ",", "0", ",", "INFO2_WRITE", ",", "field_count", ",", "bins", ".", "length", ")", "write_key", "(", "key", ",", "policy", ")", "bins", ".", "each", "do", "|", "bin", "|", "write_operation_for_bin", "(", "bin", ",", "operation", ")", "end", "end_cmd", "end"], "docstring": "Writes the command for write operations", "docstring_tokens": ["Writes", "the", "command", "for", "write", "operations"], "sha": "e9d61b8c87e1ec67cb0d70772051f86353b1de45", "url": "https://github.com/aerospike/aerospike-client-ruby/blob/e9d61b8c87e1ec67cb0d70772051f86353b1de45/lib/aerospike/command/command.rb#L93-L111", "partition": "test"} {"repo": "aerospike/aerospike-client-ruby", "path": "lib/aerospike/command/command.rb", "func_name": "Aerospike.Command.set_delete", "original_string": "def set_delete(policy, key)\n begin_cmd\n field_count = estimate_key_size(key)\n size_buffer\n write_header_with_policy(policy, 0, INFO2_WRITE|INFO2_DELETE, field_count, 0)\n write_key(key)\n end_cmd\n end", "language": "ruby", "code": "def set_delete(policy, key)\n begin_cmd\n field_count = estimate_key_size(key)\n size_buffer\n write_header_with_policy(policy, 0, INFO2_WRITE|INFO2_DELETE, field_count, 0)\n write_key(key)\n end_cmd\n end", "code_tokens": ["def", "set_delete", "(", "policy", ",", "key", ")", "begin_cmd", "field_count", "=", "estimate_key_size", "(", "key", ")", "size_buffer", "write_header_with_policy", "(", "policy", ",", "0", ",", "INFO2_WRITE", "|", "INFO2_DELETE", ",", "field_count", ",", "0", ")", "write_key", "(", "key", ")", "end_cmd", "end"], "docstring": "Writes the command for delete operations", "docstring_tokens": ["Writes", "the", "command", "for", "delete", "operations"], "sha": "e9d61b8c87e1ec67cb0d70772051f86353b1de45", "url": "https://github.com/aerospike/aerospike-client-ruby/blob/e9d61b8c87e1ec67cb0d70772051f86353b1de45/lib/aerospike/command/command.rb#L114-L121", "partition": "test"} {"repo": "aerospike/aerospike-client-ruby", "path": "lib/aerospike/command/command.rb", "func_name": "Aerospike.Command.set_touch", "original_string": "def set_touch(policy, key)\n begin_cmd\n field_count = estimate_key_size(key)\n estimate_operation_size\n size_buffer\n write_header_with_policy(policy, 0, INFO2_WRITE, field_count, 1)\n write_key(key)\n write_operation_for_operation_type(Aerospike::Operation::TOUCH)\n end_cmd\n end", "language": "ruby", "code": "def set_touch(policy, key)\n begin_cmd\n field_count = estimate_key_size(key)\n estimate_operation_size\n size_buffer\n write_header_with_policy(policy, 0, INFO2_WRITE, field_count, 1)\n write_key(key)\n write_operation_for_operation_type(Aerospike::Operation::TOUCH)\n end_cmd\n end", "code_tokens": ["def", "set_touch", "(", "policy", ",", "key", ")", "begin_cmd", "field_count", "=", "estimate_key_size", "(", "key", ")", "estimate_operation_size", "size_buffer", "write_header_with_policy", "(", "policy", ",", "0", ",", "INFO2_WRITE", ",", "field_count", ",", "1", ")", "write_key", "(", "key", ")", "write_operation_for_operation_type", "(", "Aerospike", "::", "Operation", "::", "TOUCH", ")", "end_cmd", "end"], "docstring": "Writes the command for touch operations", "docstring_tokens": ["Writes", "the", "command", "for", "touch", "operations"], "sha": "e9d61b8c87e1ec67cb0d70772051f86353b1de45", "url": "https://github.com/aerospike/aerospike-client-ruby/blob/e9d61b8c87e1ec67cb0d70772051f86353b1de45/lib/aerospike/command/command.rb#L124-L133", "partition": "test"} {"repo": "aerospike/aerospike-client-ruby", "path": "lib/aerospike/command/command.rb", "func_name": "Aerospike.Command.set_exists", "original_string": "def set_exists(policy, key)\n begin_cmd\n field_count = estimate_key_size(key)\n size_buffer\n write_header(policy, INFO1_READ|INFO1_NOBINDATA, 0, field_count, 0)\n write_key(key)\n end_cmd\n end", "language": "ruby", "code": "def set_exists(policy, key)\n begin_cmd\n field_count = estimate_key_size(key)\n size_buffer\n write_header(policy, INFO1_READ|INFO1_NOBINDATA, 0, field_count, 0)\n write_key(key)\n end_cmd\n end", "code_tokens": ["def", "set_exists", "(", "policy", ",", "key", ")", "begin_cmd", "field_count", "=", "estimate_key_size", "(", "key", ")", "size_buffer", "write_header", "(", "policy", ",", "INFO1_READ", "|", "INFO1_NOBINDATA", ",", "0", ",", "field_count", ",", "0", ")", "write_key", "(", "key", ")", "end_cmd", "end"], "docstring": "Writes the command for exist operations", "docstring_tokens": ["Writes", "the", "command", "for", "exist", "operations"], "sha": "e9d61b8c87e1ec67cb0d70772051f86353b1de45", "url": "https://github.com/aerospike/aerospike-client-ruby/blob/e9d61b8c87e1ec67cb0d70772051f86353b1de45/lib/aerospike/command/command.rb#L136-L143", "partition": "test"} {"repo": "aerospike/aerospike-client-ruby", "path": "lib/aerospike/command/command.rb", "func_name": "Aerospike.Command.set_read_header", "original_string": "def set_read_header(policy, key)\n begin_cmd\n field_count = estimate_key_size(key)\n estimate_operation_size_for_bin_name('')\n size_buffer\n\n # The server does not currently return record header data with _INFO1_NOBINDATA attribute set.\n # The workaround is to request a non-existent bin.\n # TODO: Fix this on server.\n #command.set_read(INFO1_READ | _INFO1_NOBINDATA);\n write_header(policy, INFO1_READ, 0, field_count, 1)\n\n write_key(key)\n write_operation_for_bin_name('', Aerospike::Operation::READ)\n end_cmd\n end", "language": "ruby", "code": "def set_read_header(policy, key)\n begin_cmd\n field_count = estimate_key_size(key)\n estimate_operation_size_for_bin_name('')\n size_buffer\n\n # The server does not currently return record header data with _INFO1_NOBINDATA attribute set.\n # The workaround is to request a non-existent bin.\n # TODO: Fix this on server.\n #command.set_read(INFO1_READ | _INFO1_NOBINDATA);\n write_header(policy, INFO1_READ, 0, field_count, 1)\n\n write_key(key)\n write_operation_for_bin_name('', Aerospike::Operation::READ)\n end_cmd\n end", "code_tokens": ["def", "set_read_header", "(", "policy", ",", "key", ")", "begin_cmd", "field_count", "=", "estimate_key_size", "(", "key", ")", "estimate_operation_size_for_bin_name", "(", "''", ")", "size_buffer", "# The server does not currently return record header data with _INFO1_NOBINDATA attribute set.", "# The workaround is to request a non-existent bin.", "# TODO: Fix this on server.", "#command.set_read(INFO1_READ | _INFO1_NOBINDATA);", "write_header", "(", "policy", ",", "INFO1_READ", ",", "0", ",", "field_count", ",", "1", ")", "write_key", "(", "key", ")", "write_operation_for_bin_name", "(", "''", ",", "Aerospike", "::", "Operation", "::", "READ", ")", "end_cmd", "end"], "docstring": "Writes the command for getting metadata operations", "docstring_tokens": ["Writes", "the", "command", "for", "getting", "metadata", "operations"], "sha": "e9d61b8c87e1ec67cb0d70772051f86353b1de45", "url": "https://github.com/aerospike/aerospike-client-ruby/blob/e9d61b8c87e1ec67cb0d70772051f86353b1de45/lib/aerospike/command/command.rb#L180-L195", "partition": "test"} {"repo": "aerospike/aerospike-client-ruby", "path": "lib/aerospike/command/command.rb", "func_name": "Aerospike.Command.set_operate", "original_string": "def set_operate(policy, key, operations)\n begin_cmd\n field_count = estimate_key_size(key, policy)\n read_attr = 0\n write_attr = 0\n read_header = false\n\n operations.each do |operation|\n case operation.op_type\n when Aerospike::Operation::READ\n read_attr |= INFO1_READ\n\n # Read all bins if no bin is specified.\n read_attr |= INFO1_GET_ALL unless operation.bin_name\n\n when Aerospike::Operation::READ_HEADER\n # The server does not currently return record header data with _INFO1_NOBINDATA attribute set.\n # The workaround is to request a non-existent bin.\n # TODO: Fix this on server.\n # read_attr |= _INFO1_READ | _INFO1_NOBINDATA\n read_attr |= INFO1_READ\n read_header = true\n\n else\n write_attr = INFO2_WRITE\n end\n\n estimate_operation_size_for_operation(operation)\n end\n size_buffer\n\n if write_attr != 0\n write_header_with_policy(policy, read_attr, write_attr, field_count, operations.length)\n else\n write_header(policy, read_attr, write_attr, field_count, operations.length)\n end\n write_key(key, policy)\n\n operations.each do |operation|\n write_operation_for_operation(operation)\n end\n\n write_operation_for_bin(nil, Aerospike::Operation::READ) if read_header\n\n end_cmd\n end", "language": "ruby", "code": "def set_operate(policy, key, operations)\n begin_cmd\n field_count = estimate_key_size(key, policy)\n read_attr = 0\n write_attr = 0\n read_header = false\n\n operations.each do |operation|\n case operation.op_type\n when Aerospike::Operation::READ\n read_attr |= INFO1_READ\n\n # Read all bins if no bin is specified.\n read_attr |= INFO1_GET_ALL unless operation.bin_name\n\n when Aerospike::Operation::READ_HEADER\n # The server does not currently return record header data with _INFO1_NOBINDATA attribute set.\n # The workaround is to request a non-existent bin.\n # TODO: Fix this on server.\n # read_attr |= _INFO1_READ | _INFO1_NOBINDATA\n read_attr |= INFO1_READ\n read_header = true\n\n else\n write_attr = INFO2_WRITE\n end\n\n estimate_operation_size_for_operation(operation)\n end\n size_buffer\n\n if write_attr != 0\n write_header_with_policy(policy, read_attr, write_attr, field_count, operations.length)\n else\n write_header(policy, read_attr, write_attr, field_count, operations.length)\n end\n write_key(key, policy)\n\n operations.each do |operation|\n write_operation_for_operation(operation)\n end\n\n write_operation_for_bin(nil, Aerospike::Operation::READ) if read_header\n\n end_cmd\n end", "code_tokens": ["def", "set_operate", "(", "policy", ",", "key", ",", "operations", ")", "begin_cmd", "field_count", "=", "estimate_key_size", "(", "key", ",", "policy", ")", "read_attr", "=", "0", "write_attr", "=", "0", "read_header", "=", "false", "operations", ".", "each", "do", "|", "operation", "|", "case", "operation", ".", "op_type", "when", "Aerospike", "::", "Operation", "::", "READ", "read_attr", "|=", "INFO1_READ", "# Read all bins if no bin is specified.", "read_attr", "|=", "INFO1_GET_ALL", "unless", "operation", ".", "bin_name", "when", "Aerospike", "::", "Operation", "::", "READ_HEADER", "# The server does not currently return record header data with _INFO1_NOBINDATA attribute set.", "# The workaround is to request a non-existent bin.", "# TODO: Fix this on server.", "# read_attr |= _INFO1_READ | _INFO1_NOBINDATA", "read_attr", "|=", "INFO1_READ", "read_header", "=", "true", "else", "write_attr", "=", "INFO2_WRITE", "end", "estimate_operation_size_for_operation", "(", "operation", ")", "end", "size_buffer", "if", "write_attr", "!=", "0", "write_header_with_policy", "(", "policy", ",", "read_attr", ",", "write_attr", ",", "field_count", ",", "operations", ".", "length", ")", "else", "write_header", "(", "policy", ",", "read_attr", ",", "write_attr", ",", "field_count", ",", "operations", ".", "length", ")", "end", "write_key", "(", "key", ",", "policy", ")", "operations", ".", "each", "do", "|", "operation", "|", "write_operation_for_operation", "(", "operation", ")", "end", "write_operation_for_bin", "(", "nil", ",", "Aerospike", "::", "Operation", "::", "READ", ")", "if", "read_header", "end_cmd", "end"], "docstring": "Implements different command operations", "docstring_tokens": ["Implements", "different", "command", "operations"], "sha": "e9d61b8c87e1ec67cb0d70772051f86353b1de45", "url": "https://github.com/aerospike/aerospike-client-ruby/blob/e9d61b8c87e1ec67cb0d70772051f86353b1de45/lib/aerospike/command/command.rb#L198-L243", "partition": "test"} {"repo": "aerospike/aerospike-client-ruby", "path": "lib/aerospike/command/command.rb", "func_name": "Aerospike.Command.write_header", "original_string": "def write_header(policy, read_attr, write_attr, field_count, operation_count)\n read_attr |= INFO1_CONSISTENCY_ALL if policy.consistency_level == Aerospike::ConsistencyLevel::CONSISTENCY_ALL\n\n # Write all header data except total size which must be written last.\n @data_buffer.write_byte(MSG_REMAINING_HEADER_SIZE, 8) # Message heade.length.\n @data_buffer.write_byte(read_attr, 9)\n @data_buffer.write_byte(write_attr, 10)\n\n i = 11\n while i <= 25\n @data_buffer.write_byte(0, i)\n i = i.succ\n end\n\n @data_buffer.write_int16(field_count, 26)\n @data_buffer.write_int16(operation_count, 28)\n\n @data_offset = MSG_TOTAL_HEADER_SIZE\n end", "language": "ruby", "code": "def write_header(policy, read_attr, write_attr, field_count, operation_count)\n read_attr |= INFO1_CONSISTENCY_ALL if policy.consistency_level == Aerospike::ConsistencyLevel::CONSISTENCY_ALL\n\n # Write all header data except total size which must be written last.\n @data_buffer.write_byte(MSG_REMAINING_HEADER_SIZE, 8) # Message heade.length.\n @data_buffer.write_byte(read_attr, 9)\n @data_buffer.write_byte(write_attr, 10)\n\n i = 11\n while i <= 25\n @data_buffer.write_byte(0, i)\n i = i.succ\n end\n\n @data_buffer.write_int16(field_count, 26)\n @data_buffer.write_int16(operation_count, 28)\n\n @data_offset = MSG_TOTAL_HEADER_SIZE\n end", "code_tokens": ["def", "write_header", "(", "policy", ",", "read_attr", ",", "write_attr", ",", "field_count", ",", "operation_count", ")", "read_attr", "|=", "INFO1_CONSISTENCY_ALL", "if", "policy", ".", "consistency_level", "==", "Aerospike", "::", "ConsistencyLevel", "::", "CONSISTENCY_ALL", "# Write all header data except total size which must be written last.", "@data_buffer", ".", "write_byte", "(", "MSG_REMAINING_HEADER_SIZE", ",", "8", ")", "# Message heade.length.", "@data_buffer", ".", "write_byte", "(", "read_attr", ",", "9", ")", "@data_buffer", ".", "write_byte", "(", "write_attr", ",", "10", ")", "i", "=", "11", "while", "i", "<=", "25", "@data_buffer", ".", "write_byte", "(", "0", ",", "i", ")", "i", "=", "i", ".", "succ", "end", "@data_buffer", ".", "write_int16", "(", "field_count", ",", "26", ")", "@data_buffer", ".", "write_int16", "(", "operation_count", ",", "28", ")", "@data_offset", "=", "MSG_TOTAL_HEADER_SIZE", "end"], "docstring": "Generic header write.", "docstring_tokens": ["Generic", "header", "write", "."], "sha": "e9d61b8c87e1ec67cb0d70772051f86353b1de45", "url": "https://github.com/aerospike/aerospike-client-ruby/blob/e9d61b8c87e1ec67cb0d70772051f86353b1de45/lib/aerospike/command/command.rb#L502-L520", "partition": "test"} {"repo": "aerospike/aerospike-client-ruby", "path": "lib/aerospike/command/command.rb", "func_name": "Aerospike.Command.write_header_with_policy", "original_string": "def write_header_with_policy(policy, read_attr, write_attr, field_count, operation_count)\n # Set flags.\n generation = Integer(0)\n info_attr = Integer(0)\n\n case policy.record_exists_action\n when Aerospike::RecordExistsAction::UPDATE\n when Aerospike::RecordExistsAction::UPDATE_ONLY\n info_attr |= INFO3_UPDATE_ONLY\n when Aerospike::RecordExistsAction::REPLACE\n info_attr |= INFO3_CREATE_OR_REPLACE\n when Aerospike::RecordExistsAction::REPLACE_ONLY\n info_attr |= INFO3_REPLACE_ONLY\n when Aerospike::RecordExistsAction::CREATE_ONLY\n write_attr |= INFO2_CREATE_ONLY\n end\n\n case policy.generation_policy\n when Aerospike::GenerationPolicy::NONE\n when Aerospike::GenerationPolicy::EXPECT_GEN_EQUAL\n generation = policy.generation\n write_attr |= INFO2_GENERATION\n when Aerospike::GenerationPolicy::EXPECT_GEN_GT\n generation = policy.generation\n write_attr |= INFO2_GENERATION_GT\n end\n\n info_attr |= INFO3_COMMIT_MASTER if policy.commit_level == Aerospike::CommitLevel::COMMIT_MASTER\n read_attr |= INFO1_CONSISTENCY_ALL if policy.consistency_level == Aerospike::ConsistencyLevel::CONSISTENCY_ALL\n write_attr |= INFO2_DURABLE_DELETE if policy.durable_delete\n\n # Write all header data except total size which must be written last.\n @data_buffer.write_byte(MSG_REMAINING_HEADER_SIZE, 8) # Message heade.length.\n @data_buffer.write_byte(read_attr, 9)\n @data_buffer.write_byte(write_attr, 10)\n @data_buffer.write_byte(info_attr, 11)\n @data_buffer.write_byte(0, 12) # unused\n @data_buffer.write_byte(0, 13) # clear the result code\n @data_buffer.write_uint32(generation, 14)\n @data_buffer.write_uint32(policy.ttl, 18)\n\n # Initialize timeout. It will be written later.\n @data_buffer.write_byte(0, 22)\n @data_buffer.write_byte(0, 23)\n @data_buffer.write_byte(0, 24)\n @data_buffer.write_byte(0, 25)\n\n\n @data_buffer.write_int16(field_count, 26)\n @data_buffer.write_int16(operation_count, 28)\n\n @data_offset = MSG_TOTAL_HEADER_SIZE\n end", "language": "ruby", "code": "def write_header_with_policy(policy, read_attr, write_attr, field_count, operation_count)\n # Set flags.\n generation = Integer(0)\n info_attr = Integer(0)\n\n case policy.record_exists_action\n when Aerospike::RecordExistsAction::UPDATE\n when Aerospike::RecordExistsAction::UPDATE_ONLY\n info_attr |= INFO3_UPDATE_ONLY\n when Aerospike::RecordExistsAction::REPLACE\n info_attr |= INFO3_CREATE_OR_REPLACE\n when Aerospike::RecordExistsAction::REPLACE_ONLY\n info_attr |= INFO3_REPLACE_ONLY\n when Aerospike::RecordExistsAction::CREATE_ONLY\n write_attr |= INFO2_CREATE_ONLY\n end\n\n case policy.generation_policy\n when Aerospike::GenerationPolicy::NONE\n when Aerospike::GenerationPolicy::EXPECT_GEN_EQUAL\n generation = policy.generation\n write_attr |= INFO2_GENERATION\n when Aerospike::GenerationPolicy::EXPECT_GEN_GT\n generation = policy.generation\n write_attr |= INFO2_GENERATION_GT\n end\n\n info_attr |= INFO3_COMMIT_MASTER if policy.commit_level == Aerospike::CommitLevel::COMMIT_MASTER\n read_attr |= INFO1_CONSISTENCY_ALL if policy.consistency_level == Aerospike::ConsistencyLevel::CONSISTENCY_ALL\n write_attr |= INFO2_DURABLE_DELETE if policy.durable_delete\n\n # Write all header data except total size which must be written last.\n @data_buffer.write_byte(MSG_REMAINING_HEADER_SIZE, 8) # Message heade.length.\n @data_buffer.write_byte(read_attr, 9)\n @data_buffer.write_byte(write_attr, 10)\n @data_buffer.write_byte(info_attr, 11)\n @data_buffer.write_byte(0, 12) # unused\n @data_buffer.write_byte(0, 13) # clear the result code\n @data_buffer.write_uint32(generation, 14)\n @data_buffer.write_uint32(policy.ttl, 18)\n\n # Initialize timeout. It will be written later.\n @data_buffer.write_byte(0, 22)\n @data_buffer.write_byte(0, 23)\n @data_buffer.write_byte(0, 24)\n @data_buffer.write_byte(0, 25)\n\n\n @data_buffer.write_int16(field_count, 26)\n @data_buffer.write_int16(operation_count, 28)\n\n @data_offset = MSG_TOTAL_HEADER_SIZE\n end", "code_tokens": ["def", "write_header_with_policy", "(", "policy", ",", "read_attr", ",", "write_attr", ",", "field_count", ",", "operation_count", ")", "# Set flags.", "generation", "=", "Integer", "(", "0", ")", "info_attr", "=", "Integer", "(", "0", ")", "case", "policy", ".", "record_exists_action", "when", "Aerospike", "::", "RecordExistsAction", "::", "UPDATE", "when", "Aerospike", "::", "RecordExistsAction", "::", "UPDATE_ONLY", "info_attr", "|=", "INFO3_UPDATE_ONLY", "when", "Aerospike", "::", "RecordExistsAction", "::", "REPLACE", "info_attr", "|=", "INFO3_CREATE_OR_REPLACE", "when", "Aerospike", "::", "RecordExistsAction", "::", "REPLACE_ONLY", "info_attr", "|=", "INFO3_REPLACE_ONLY", "when", "Aerospike", "::", "RecordExistsAction", "::", "CREATE_ONLY", "write_attr", "|=", "INFO2_CREATE_ONLY", "end", "case", "policy", ".", "generation_policy", "when", "Aerospike", "::", "GenerationPolicy", "::", "NONE", "when", "Aerospike", "::", "GenerationPolicy", "::", "EXPECT_GEN_EQUAL", "generation", "=", "policy", ".", "generation", "write_attr", "|=", "INFO2_GENERATION", "when", "Aerospike", "::", "GenerationPolicy", "::", "EXPECT_GEN_GT", "generation", "=", "policy", ".", "generation", "write_attr", "|=", "INFO2_GENERATION_GT", "end", "info_attr", "|=", "INFO3_COMMIT_MASTER", "if", "policy", ".", "commit_level", "==", "Aerospike", "::", "CommitLevel", "::", "COMMIT_MASTER", "read_attr", "|=", "INFO1_CONSISTENCY_ALL", "if", "policy", ".", "consistency_level", "==", "Aerospike", "::", "ConsistencyLevel", "::", "CONSISTENCY_ALL", "write_attr", "|=", "INFO2_DURABLE_DELETE", "if", "policy", ".", "durable_delete", "# Write all header data except total size which must be written last.", "@data_buffer", ".", "write_byte", "(", "MSG_REMAINING_HEADER_SIZE", ",", "8", ")", "# Message heade.length.", "@data_buffer", ".", "write_byte", "(", "read_attr", ",", "9", ")", "@data_buffer", ".", "write_byte", "(", "write_attr", ",", "10", ")", "@data_buffer", ".", "write_byte", "(", "info_attr", ",", "11", ")", "@data_buffer", ".", "write_byte", "(", "0", ",", "12", ")", "# unused", "@data_buffer", ".", "write_byte", "(", "0", ",", "13", ")", "# clear the result code", "@data_buffer", ".", "write_uint32", "(", "generation", ",", "14", ")", "@data_buffer", ".", "write_uint32", "(", "policy", ".", "ttl", ",", "18", ")", "# Initialize timeout. It will be written later.", "@data_buffer", ".", "write_byte", "(", "0", ",", "22", ")", "@data_buffer", ".", "write_byte", "(", "0", ",", "23", ")", "@data_buffer", ".", "write_byte", "(", "0", ",", "24", ")", "@data_buffer", ".", "write_byte", "(", "0", ",", "25", ")", "@data_buffer", ".", "write_int16", "(", "field_count", ",", "26", ")", "@data_buffer", ".", "write_int16", "(", "operation_count", ",", "28", ")", "@data_offset", "=", "MSG_TOTAL_HEADER_SIZE", "end"], "docstring": "Header write for write operations.", "docstring_tokens": ["Header", "write", "for", "write", "operations", "."], "sha": "e9d61b8c87e1ec67cb0d70772051f86353b1de45", "url": "https://github.com/aerospike/aerospike-client-ruby/blob/e9d61b8c87e1ec67cb0d70772051f86353b1de45/lib/aerospike/command/command.rb#L523-L575", "partition": "test"} {"repo": "aerospike/aerospike-client-ruby", "path": "lib/aerospike/task/execute_task.rb", "func_name": "Aerospike.ExecuteTask.all_nodes_done?", "original_string": "def all_nodes_done?\n\n if @scan\n command = 'scan-list'\n else\n command = 'query-list'\n end\n\n nodes = @cluster.nodes\n done = false\n\n nodes.each do |node|\n conn = node.get_connection(0)\n responseMap, _ = Info.request(conn, command)\n node.put_connection(conn)\n\n response = responseMap[command]\n find = \"job_id=#{@task_id}:\"\n index = response.index(find)\n\n unless index\n # don't return on first check\n done = true\n next\n end\n\n b = index + find.length\n response = response[b, response.length]\n find = 'job_status='\n index = response.index(find)\n\n next unless index\n\n b = index + find.length\n response = response[b, response.length]\n e = response.index(':')\n status = response[0, e]\n\n case status\n when 'ABORTED'\n raise raise Aerospike::Exceptions::QueryTerminated\n when 'IN PROGRESS'\n return false\n when 'DONE'\n done = true\n end\n end\n\n done\n end", "language": "ruby", "code": "def all_nodes_done?\n\n if @scan\n command = 'scan-list'\n else\n command = 'query-list'\n end\n\n nodes = @cluster.nodes\n done = false\n\n nodes.each do |node|\n conn = node.get_connection(0)\n responseMap, _ = Info.request(conn, command)\n node.put_connection(conn)\n\n response = responseMap[command]\n find = \"job_id=#{@task_id}:\"\n index = response.index(find)\n\n unless index\n # don't return on first check\n done = true\n next\n end\n\n b = index + find.length\n response = response[b, response.length]\n find = 'job_status='\n index = response.index(find)\n\n next unless index\n\n b = index + find.length\n response = response[b, response.length]\n e = response.index(':')\n status = response[0, e]\n\n case status\n when 'ABORTED'\n raise raise Aerospike::Exceptions::QueryTerminated\n when 'IN PROGRESS'\n return false\n when 'DONE'\n done = true\n end\n end\n\n done\n end", "code_tokens": ["def", "all_nodes_done?", "if", "@scan", "command", "=", "'scan-list'", "else", "command", "=", "'query-list'", "end", "nodes", "=", "@cluster", ".", "nodes", "done", "=", "false", "nodes", ".", "each", "do", "|", "node", "|", "conn", "=", "node", ".", "get_connection", "(", "0", ")", "responseMap", ",", "_", "=", "Info", ".", "request", "(", "conn", ",", "command", ")", "node", ".", "put_connection", "(", "conn", ")", "response", "=", "responseMap", "[", "command", "]", "find", "=", "\"job_id=#{@task_id}:\"", "index", "=", "response", ".", "index", "(", "find", ")", "unless", "index", "# don't return on first check", "done", "=", "true", "next", "end", "b", "=", "index", "+", "find", ".", "length", "response", "=", "response", "[", "b", ",", "response", ".", "length", "]", "find", "=", "'job_status='", "index", "=", "response", ".", "index", "(", "find", ")", "next", "unless", "index", "b", "=", "index", "+", "find", ".", "length", "response", "=", "response", "[", "b", ",", "response", ".", "length", "]", "e", "=", "response", ".", "index", "(", "':'", ")", "status", "=", "response", "[", "0", ",", "e", "]", "case", "status", "when", "'ABORTED'", "raise", "raise", "Aerospike", "::", "Exceptions", "::", "QueryTerminated", "when", "'IN PROGRESS'", "return", "false", "when", "'DONE'", "done", "=", "true", "end", "end", "done", "end"], "docstring": "NewExecuteTask initializes task with fields needed to query server nodes.\n IsDone queries all nodes for task completion status.", "docstring_tokens": ["NewExecuteTask", "initializes", "task", "with", "fields", "needed", "to", "query", "server", "nodes", ".", "IsDone", "queries", "all", "nodes", "for", "task", "completion", "status", "."], "sha": "e9d61b8c87e1ec67cb0d70772051f86353b1de45", "url": "https://github.com/aerospike/aerospike-client-ruby/blob/e9d61b8c87e1ec67cb0d70772051f86353b1de45/lib/aerospike/task/execute_task.rb#L33-L82", "partition": "test"} {"repo": "aerospike/aerospike-client-ruby", "path": "lib/aerospike/node.rb", "func_name": "Aerospike.Node.get_connection", "original_string": "def get_connection(timeout)\n loop do\n conn = @connections.poll\n if conn.connected?\n conn.timeout = timeout.to_f\n return conn\n end\n end\n end", "language": "ruby", "code": "def get_connection(timeout)\n loop do\n conn = @connections.poll\n if conn.connected?\n conn.timeout = timeout.to_f\n return conn\n end\n end\n end", "code_tokens": ["def", "get_connection", "(", "timeout", ")", "loop", "do", "conn", "=", "@connections", ".", "poll", "if", "conn", ".", "connected?", "conn", ".", "timeout", "=", "timeout", ".", "to_f", "return", "conn", "end", "end", "end"], "docstring": "Initialize server node with connection parameters.\n Get a connection to the node. If no cached connection is not available,\n a new connection will be created", "docstring_tokens": ["Initialize", "server", "node", "with", "connection", "parameters", ".", "Get", "a", "connection", "to", "the", "node", ".", "If", "no", "cached", "connection", "is", "not", "available", "a", "new", "connection", "will", "be", "created"], "sha": "e9d61b8c87e1ec67cb0d70772051f86353b1de45", "url": "https://github.com/aerospike/aerospike-client-ruby/blob/e9d61b8c87e1ec67cb0d70772051f86353b1de45/lib/aerospike/node.rb#L60-L68", "partition": "test"} {"repo": "aerospike/aerospike-client-ruby", "path": "lib/aerospike/command/multi_command.rb", "func_name": "Aerospike.MultiCommand.parse_record", "original_string": "def parse_record(key, op_count, generation, expiration)\n bins = op_count > 0 ? {} : nil\n i = 0\n while i < op_count\n raise Aerospike::Exceptions::QueryTerminated.new unless valid?\n\n read_bytes(8)\n\n op_size = @data_buffer.read_int32(0).ord\n particle_type = @data_buffer.read(5).ord\n name_size = @data_buffer.read(7).ord\n\n read_bytes(name_size)\n name = @data_buffer.read(0, name_size).force_encoding('utf-8')\n\n particle_bytes_size = op_size - (4 + name_size)\n read_bytes(particle_bytes_size)\n value = Aerospike.bytes_to_particle(particle_type, @data_buffer, 0, particle_bytes_size)\n\n bins[name] = value\n\n i = i.succ\n end\n\n Record.new(@node, key, bins, generation, expiration)\n end", "language": "ruby", "code": "def parse_record(key, op_count, generation, expiration)\n bins = op_count > 0 ? {} : nil\n i = 0\n while i < op_count\n raise Aerospike::Exceptions::QueryTerminated.new unless valid?\n\n read_bytes(8)\n\n op_size = @data_buffer.read_int32(0).ord\n particle_type = @data_buffer.read(5).ord\n name_size = @data_buffer.read(7).ord\n\n read_bytes(name_size)\n name = @data_buffer.read(0, name_size).force_encoding('utf-8')\n\n particle_bytes_size = op_size - (4 + name_size)\n read_bytes(particle_bytes_size)\n value = Aerospike.bytes_to_particle(particle_type, @data_buffer, 0, particle_bytes_size)\n\n bins[name] = value\n\n i = i.succ\n end\n\n Record.new(@node, key, bins, generation, expiration)\n end", "code_tokens": ["def", "parse_record", "(", "key", ",", "op_count", ",", "generation", ",", "expiration", ")", "bins", "=", "op_count", ">", "0", "?", "{", "}", ":", "nil", "i", "=", "0", "while", "i", "<", "op_count", "raise", "Aerospike", "::", "Exceptions", "::", "QueryTerminated", ".", "new", "unless", "valid?", "read_bytes", "(", "8", ")", "op_size", "=", "@data_buffer", ".", "read_int32", "(", "0", ")", ".", "ord", "particle_type", "=", "@data_buffer", ".", "read", "(", "5", ")", ".", "ord", "name_size", "=", "@data_buffer", ".", "read", "(", "7", ")", ".", "ord", "read_bytes", "(", "name_size", ")", "name", "=", "@data_buffer", ".", "read", "(", "0", ",", "name_size", ")", ".", "force_encoding", "(", "'utf-8'", ")", "particle_bytes_size", "=", "op_size", "-", "(", "4", "+", "name_size", ")", "read_bytes", "(", "particle_bytes_size", ")", "value", "=", "Aerospike", ".", "bytes_to_particle", "(", "particle_type", ",", "@data_buffer", ",", "0", ",", "particle_bytes_size", ")", "bins", "[", "name", "]", "=", "value", "i", "=", "i", ".", "succ", "end", "Record", ".", "new", "(", "@node", ",", "key", ",", "bins", ",", "generation", ",", "expiration", ")", "end"], "docstring": "Parses the given byte buffer and populate the result object.\n Returns the number of bytes that were parsed from the given buffer.", "docstring_tokens": ["Parses", "the", "given", "byte", "buffer", "and", "populate", "the", "result", "object", ".", "Returns", "the", "number", "of", "bytes", "that", "were", "parsed", "from", "the", "given", "buffer", "."], "sha": "e9d61b8c87e1ec67cb0d70772051f86353b1de45", "url": "https://github.com/aerospike/aerospike-client-ruby/blob/e9d61b8c87e1ec67cb0d70772051f86353b1de45/lib/aerospike/command/multi_command.rb#L116-L141", "partition": "test"} {"repo": "aerospike/aerospike-client-ruby", "path": "lib/aerospike/cluster.rb", "func_name": "Aerospike.Cluster.random_node", "original_string": "def random_node\n # Must copy array reference for copy on write semantics to work.\n node_array = nodes\n length = node_array.length\n i = 0\n while i < length\n # Must handle concurrency with other non-tending threads, so node_index is consistent.\n index = (@node_index.update{ |v| v+1 } % node_array.length).abs\n node = node_array[index]\n\n return node if node.active?\n\n i = i.succ\n end\n raise Aerospike::Exceptions::InvalidNode\n end", "language": "ruby", "code": "def random_node\n # Must copy array reference for copy on write semantics to work.\n node_array = nodes\n length = node_array.length\n i = 0\n while i < length\n # Must handle concurrency with other non-tending threads, so node_index is consistent.\n index = (@node_index.update{ |v| v+1 } % node_array.length).abs\n node = node_array[index]\n\n return node if node.active?\n\n i = i.succ\n end\n raise Aerospike::Exceptions::InvalidNode\n end", "code_tokens": ["def", "random_node", "# Must copy array reference for copy on write semantics to work.", "node_array", "=", "nodes", "length", "=", "node_array", ".", "length", "i", "=", "0", "while", "i", "<", "length", "# Must handle concurrency with other non-tending threads, so node_index is consistent.", "index", "=", "(", "@node_index", ".", "update", "{", "|", "v", "|", "v", "+", "1", "}", "%", "node_array", ".", "length", ")", ".", "abs", "node", "=", "node_array", "[", "index", "]", "return", "node", "if", "node", ".", "active?", "i", "=", "i", ".", "succ", "end", "raise", "Aerospike", "::", "Exceptions", "::", "InvalidNode", "end"], "docstring": "Returns a random node on the cluster", "docstring_tokens": ["Returns", "a", "random", "node", "on", "the", "cluster"], "sha": "e9d61b8c87e1ec67cb0d70772051f86353b1de45", "url": "https://github.com/aerospike/aerospike-client-ruby/blob/e9d61b8c87e1ec67cb0d70772051f86353b1de45/lib/aerospike/cluster.rb#L120-L135", "partition": "test"} {"repo": "aerospike/aerospike-client-ruby", "path": "lib/aerospike/cluster.rb", "func_name": "Aerospike.Cluster.get_node_by_name", "original_string": "def get_node_by_name(node_name)\n node = find_node_by_name(node_name)\n\n raise Aerospike::Exceptions::InvalidNode unless node\n\n node\n end", "language": "ruby", "code": "def get_node_by_name(node_name)\n node = find_node_by_name(node_name)\n\n raise Aerospike::Exceptions::InvalidNode unless node\n\n node\n end", "code_tokens": ["def", "get_node_by_name", "(", "node_name", ")", "node", "=", "find_node_by_name", "(", "node_name", ")", "raise", "Aerospike", "::", "Exceptions", "::", "InvalidNode", "unless", "node", "node", "end"], "docstring": "Find a node by name and returns an error if not found", "docstring_tokens": ["Find", "a", "node", "by", "name", "and", "returns", "an", "error", "if", "not", "found"], "sha": "e9d61b8c87e1ec67cb0d70772051f86353b1de45", "url": "https://github.com/aerospike/aerospike-client-ruby/blob/e9d61b8c87e1ec67cb0d70772051f86353b1de45/lib/aerospike/cluster.rb#L146-L152", "partition": "test"} {"repo": "aerospike/aerospike-client-ruby", "path": "lib/aerospike/client.rb", "func_name": "Aerospike.Client.prepend", "original_string": "def prepend(key, bins, options = nil)\n policy = create_policy(options, WritePolicy, default_write_policy)\n command = WriteCommand.new(@cluster, policy, key, hash_to_bins(bins), Aerospike::Operation::PREPEND)\n execute_command(command)\n end", "language": "ruby", "code": "def prepend(key, bins, options = nil)\n policy = create_policy(options, WritePolicy, default_write_policy)\n command = WriteCommand.new(@cluster, policy, key, hash_to_bins(bins), Aerospike::Operation::PREPEND)\n execute_command(command)\n end", "code_tokens": ["def", "prepend", "(", "key", ",", "bins", ",", "options", "=", "nil", ")", "policy", "=", "create_policy", "(", "options", ",", "WritePolicy", ",", "default_write_policy", ")", "command", "=", "WriteCommand", ".", "new", "(", "@cluster", ",", "policy", ",", "key", ",", "hash_to_bins", "(", "bins", ")", ",", "Aerospike", "::", "Operation", "::", "PREPEND", ")", "execute_command", "(", "command", ")", "end"], "docstring": "Prepends bin values string to existing record bin values.\n The policy specifies the transaction timeout, record expiration and\n how the transaction is handled when the record already exists.\n\n This call works only for string values.\n\n If no policy options are provided, +@default_write_policy+ will be used.\n Examples:\n\n client.prepend key, {'bin', 'value to prepend'}, :timeout => 0.001", "docstring_tokens": ["Prepends", "bin", "values", "string", "to", "existing", "record", "bin", "values", ".", "The", "policy", "specifies", "the", "transaction", "timeout", "record", "expiration", "and", "how", "the", "transaction", "is", "handled", "when", "the", "record", "already", "exists", "."], "sha": "e9d61b8c87e1ec67cb0d70772051f86353b1de45", "url": "https://github.com/aerospike/aerospike-client-ruby/blob/e9d61b8c87e1ec67cb0d70772051f86353b1de45/lib/aerospike/client.rb#L157-L161", "partition": "test"} {"repo": "aerospike/aerospike-client-ruby", "path": "lib/aerospike/client.rb", "func_name": "Aerospike.Client.get_header", "original_string": "def get_header(key, options = nil)\n policy = create_policy(options, Policy, default_read_policy)\n command = ReadHeaderCommand.new(@cluster, policy, key)\n execute_command(command)\n command.record\n end", "language": "ruby", "code": "def get_header(key, options = nil)\n policy = create_policy(options, Policy, default_read_policy)\n command = ReadHeaderCommand.new(@cluster, policy, key)\n execute_command(command)\n command.record\n end", "code_tokens": ["def", "get_header", "(", "key", ",", "options", "=", "nil", ")", "policy", "=", "create_policy", "(", "options", ",", "Policy", ",", "default_read_policy", ")", "command", "=", "ReadHeaderCommand", ".", "new", "(", "@cluster", ",", "policy", ",", "key", ")", "execute_command", "(", "command", ")", "command", ".", "record", "end"], "docstring": "Read record generation and expiration only for specified key. Bins are not read.\n The policy can be used to specify timeouts.", "docstring_tokens": ["Read", "record", "generation", "and", "expiration", "only", "for", "specified", "key", ".", "Bins", "are", "not", "read", ".", "The", "policy", "can", "be", "used", "to", "specify", "timeouts", "."], "sha": "e9d61b8c87e1ec67cb0d70772051f86353b1de45", "url": "https://github.com/aerospike/aerospike-client-ruby/blob/e9d61b8c87e1ec67cb0d70772051f86353b1de45/lib/aerospike/client.rb#L294-L299", "partition": "test"} {"repo": "aerospike/aerospike-client-ruby", "path": "lib/aerospike/client.rb", "func_name": "Aerospike.Client.batch_exists", "original_string": "def batch_exists(keys, options = nil)\n policy = create_policy(options, BatchPolicy, default_batch_policy)\n results = Array.new(keys.length)\n\n if policy.use_batch_direct\n key_map = BatchItem.generate_map(keys)\n execute_batch_direct_commands(keys) do |node, batch|\n BatchDirectExistsCommand.new(node, batch, policy, key_map, results)\n end\n else\n execute_batch_index_commands(keys) do |node, batch|\n BatchIndexExistsCommand.new(node, batch, policy, results)\n end\n end\n\n results\n end", "language": "ruby", "code": "def batch_exists(keys, options = nil)\n policy = create_policy(options, BatchPolicy, default_batch_policy)\n results = Array.new(keys.length)\n\n if policy.use_batch_direct\n key_map = BatchItem.generate_map(keys)\n execute_batch_direct_commands(keys) do |node, batch|\n BatchDirectExistsCommand.new(node, batch, policy, key_map, results)\n end\n else\n execute_batch_index_commands(keys) do |node, batch|\n BatchIndexExistsCommand.new(node, batch, policy, results)\n end\n end\n\n results\n end", "code_tokens": ["def", "batch_exists", "(", "keys", ",", "options", "=", "nil", ")", "policy", "=", "create_policy", "(", "options", ",", "BatchPolicy", ",", "default_batch_policy", ")", "results", "=", "Array", ".", "new", "(", "keys", ".", "length", ")", "if", "policy", ".", "use_batch_direct", "key_map", "=", "BatchItem", ".", "generate_map", "(", "keys", ")", "execute_batch_direct_commands", "(", "keys", ")", "do", "|", "node", ",", "batch", "|", "BatchDirectExistsCommand", ".", "new", "(", "node", ",", "batch", ",", "policy", ",", "key_map", ",", "results", ")", "end", "else", "execute_batch_index_commands", "(", "keys", ")", "do", "|", "node", ",", "batch", "|", "BatchIndexExistsCommand", ".", "new", "(", "node", ",", "batch", ",", "policy", ",", "results", ")", "end", "end", "results", "end"], "docstring": "Check if multiple record keys exist in one batch call.\n The returned boolean array is in positional order with the original key array order.\n The policy can be used to specify timeouts and protocol type.", "docstring_tokens": ["Check", "if", "multiple", "record", "keys", "exist", "in", "one", "batch", "call", ".", "The", "returned", "boolean", "array", "is", "in", "positional", "order", "with", "the", "original", "key", "array", "order", ".", "The", "policy", "can", "be", "used", "to", "specify", "timeouts", "and", "protocol", "type", "."], "sha": "e9d61b8c87e1ec67cb0d70772051f86353b1de45", "url": "https://github.com/aerospike/aerospike-client-ruby/blob/e9d61b8c87e1ec67cb0d70772051f86353b1de45/lib/aerospike/client.rb#L348-L364", "partition": "test"} {"repo": "aerospike/aerospike-client-ruby", "path": "lib/aerospike/client.rb", "func_name": "Aerospike.Client.register_udf", "original_string": "def register_udf(udf_body, server_path, language, options = nil)\n policy = create_policy(options, Policy, default_info_policy)\n\n content = Base64.strict_encode64(udf_body).force_encoding('binary')\n str_cmd = \"udf-put:filename=#{server_path};content=#{content};\"\n str_cmd << \"content-len=#{content.length};udf-type=#{language};\"\n\n # Send UDF to one node. That node will distribute the UDF to other nodes.\n response_map = @cluster.request_info(policy, str_cmd)\n\n res = {}\n response_map.each do |k, response|\n vals = response.to_s.split(';')\n vals.each do |pair|\n k, v = pair.split(\"=\", 2)\n res[k] = v\n end\n end\n\n if res['error']\n raise Aerospike::Exceptions::CommandRejected.new(\"Registration failed: #{res['error']}\\nFile: #{res['file']}\\nLine: #{res['line']}\\nMessage: #{res['message']}\")\n end\n\n UdfRegisterTask.new(@cluster, server_path)\n end", "language": "ruby", "code": "def register_udf(udf_body, server_path, language, options = nil)\n policy = create_policy(options, Policy, default_info_policy)\n\n content = Base64.strict_encode64(udf_body).force_encoding('binary')\n str_cmd = \"udf-put:filename=#{server_path};content=#{content};\"\n str_cmd << \"content-len=#{content.length};udf-type=#{language};\"\n\n # Send UDF to one node. That node will distribute the UDF to other nodes.\n response_map = @cluster.request_info(policy, str_cmd)\n\n res = {}\n response_map.each do |k, response|\n vals = response.to_s.split(';')\n vals.each do |pair|\n k, v = pair.split(\"=\", 2)\n res[k] = v\n end\n end\n\n if res['error']\n raise Aerospike::Exceptions::CommandRejected.new(\"Registration failed: #{res['error']}\\nFile: #{res['file']}\\nLine: #{res['line']}\\nMessage: #{res['message']}\")\n end\n\n UdfRegisterTask.new(@cluster, server_path)\n end", "code_tokens": ["def", "register_udf", "(", "udf_body", ",", "server_path", ",", "language", ",", "options", "=", "nil", ")", "policy", "=", "create_policy", "(", "options", ",", "Policy", ",", "default_info_policy", ")", "content", "=", "Base64", ".", "strict_encode64", "(", "udf_body", ")", ".", "force_encoding", "(", "'binary'", ")", "str_cmd", "=", "\"udf-put:filename=#{server_path};content=#{content};\"", "str_cmd", "<<", "\"content-len=#{content.length};udf-type=#{language};\"", "# Send UDF to one node. That node will distribute the UDF to other nodes.", "response_map", "=", "@cluster", ".", "request_info", "(", "policy", ",", "str_cmd", ")", "res", "=", "{", "}", "response_map", ".", "each", "do", "|", "k", ",", "response", "|", "vals", "=", "response", ".", "to_s", ".", "split", "(", "';'", ")", "vals", ".", "each", "do", "|", "pair", "|", "k", ",", "v", "=", "pair", ".", "split", "(", "\"=\"", ",", "2", ")", "res", "[", "k", "]", "=", "v", "end", "end", "if", "res", "[", "'error'", "]", "raise", "Aerospike", "::", "Exceptions", "::", "CommandRejected", ".", "new", "(", "\"Registration failed: #{res['error']}\\nFile: #{res['file']}\\nLine: #{res['line']}\\nMessage: #{res['message']}\"", ")", "end", "UdfRegisterTask", ".", "new", "(", "@cluster", ",", "server_path", ")", "end"], "docstring": "Register package containing user defined functions with server.\n This asynchronous server call will return before command is complete.\n The user can optionally wait for command completion by using the returned\n RegisterTask instance.\n\n This method is only supported by Aerospike 3 servers.", "docstring_tokens": ["Register", "package", "containing", "user", "defined", "functions", "with", "server", ".", "This", "asynchronous", "server", "call", "will", "return", "before", "command", "is", "complete", ".", "The", "user", "can", "optionally", "wait", "for", "command", "completion", "by", "using", "the", "returned", "RegisterTask", "instance", "."], "sha": "e9d61b8c87e1ec67cb0d70772051f86353b1de45", "url": "https://github.com/aerospike/aerospike-client-ruby/blob/e9d61b8c87e1ec67cb0d70772051f86353b1de45/lib/aerospike/client.rb#L403-L427", "partition": "test"} {"repo": "aerospike/aerospike-client-ruby", "path": "lib/aerospike/client.rb", "func_name": "Aerospike.Client.remove_udf", "original_string": "def remove_udf(udf_name, options = nil)\n policy = create_policy(options, Policy, default_info_policy)\n\n str_cmd = \"udf-remove:filename=#{udf_name};\"\n\n # Send command to one node. That node will distribute it to other nodes.\n # Send UDF to one node. That node will distribute the UDF to other nodes.\n response_map = @cluster.request_info(policy, str_cmd)\n _, response = response_map.first\n\n if response == 'ok'\n UdfRemoveTask.new(@cluster, udf_name)\n else\n raise Aerospike::Exceptions::Aerospike.new(Aerospike::ResultCode::SERVER_ERROR, response)\n end\n end", "language": "ruby", "code": "def remove_udf(udf_name, options = nil)\n policy = create_policy(options, Policy, default_info_policy)\n\n str_cmd = \"udf-remove:filename=#{udf_name};\"\n\n # Send command to one node. That node will distribute it to other nodes.\n # Send UDF to one node. That node will distribute the UDF to other nodes.\n response_map = @cluster.request_info(policy, str_cmd)\n _, response = response_map.first\n\n if response == 'ok'\n UdfRemoveTask.new(@cluster, udf_name)\n else\n raise Aerospike::Exceptions::Aerospike.new(Aerospike::ResultCode::SERVER_ERROR, response)\n end\n end", "code_tokens": ["def", "remove_udf", "(", "udf_name", ",", "options", "=", "nil", ")", "policy", "=", "create_policy", "(", "options", ",", "Policy", ",", "default_info_policy", ")", "str_cmd", "=", "\"udf-remove:filename=#{udf_name};\"", "# Send command to one node. That node will distribute it to other nodes.", "# Send UDF to one node. That node will distribute the UDF to other nodes.", "response_map", "=", "@cluster", ".", "request_info", "(", "policy", ",", "str_cmd", ")", "_", ",", "response", "=", "response_map", ".", "first", "if", "response", "==", "'ok'", "UdfRemoveTask", ".", "new", "(", "@cluster", ",", "udf_name", ")", "else", "raise", "Aerospike", "::", "Exceptions", "::", "Aerospike", ".", "new", "(", "Aerospike", "::", "ResultCode", "::", "SERVER_ERROR", ",", "response", ")", "end", "end"], "docstring": "RemoveUDF removes a package containing user defined functions in the server.\n This asynchronous server call will return before command is complete.\n The user can optionally wait for command completion by using the returned\n RemoveTask instance.\n\n This method is only supported by Aerospike 3 servers.", "docstring_tokens": ["RemoveUDF", "removes", "a", "package", "containing", "user", "defined", "functions", "in", "the", "server", ".", "This", "asynchronous", "server", "call", "will", "return", "before", "command", "is", "complete", ".", "The", "user", "can", "optionally", "wait", "for", "command", "completion", "by", "using", "the", "returned", "RemoveTask", "instance", "."], "sha": "e9d61b8c87e1ec67cb0d70772051f86353b1de45", "url": "https://github.com/aerospike/aerospike-client-ruby/blob/e9d61b8c87e1ec67cb0d70772051f86353b1de45/lib/aerospike/client.rb#L435-L450", "partition": "test"} {"repo": "aerospike/aerospike-client-ruby", "path": "lib/aerospike/client.rb", "func_name": "Aerospike.Client.list_udf", "original_string": "def list_udf(options = nil)\n policy = create_policy(options, Policy, default_info_policy)\n\n str_cmd = 'udf-list'\n\n # Send command to one node. That node will distribute it to other nodes.\n response_map = @cluster.request_info(policy, str_cmd)\n _, response = response_map.first\n\n vals = response.split(';')\n\n vals.map do |udf_info|\n next if udf_info.strip! == ''\n\n udf_parts = udf_info.split(',')\n udf = UDF.new\n udf_parts.each do |values|\n k, v = values.split('=', 2)\n case k\n when 'filename'\n udf.filename = v\n when 'hash'\n udf.hash = v\n when 'type'\n udf.language = v\n end\n end\n udf\n end\n end", "language": "ruby", "code": "def list_udf(options = nil)\n policy = create_policy(options, Policy, default_info_policy)\n\n str_cmd = 'udf-list'\n\n # Send command to one node. That node will distribute it to other nodes.\n response_map = @cluster.request_info(policy, str_cmd)\n _, response = response_map.first\n\n vals = response.split(';')\n\n vals.map do |udf_info|\n next if udf_info.strip! == ''\n\n udf_parts = udf_info.split(',')\n udf = UDF.new\n udf_parts.each do |values|\n k, v = values.split('=', 2)\n case k\n when 'filename'\n udf.filename = v\n when 'hash'\n udf.hash = v\n when 'type'\n udf.language = v\n end\n end\n udf\n end\n end", "code_tokens": ["def", "list_udf", "(", "options", "=", "nil", ")", "policy", "=", "create_policy", "(", "options", ",", "Policy", ",", "default_info_policy", ")", "str_cmd", "=", "'udf-list'", "# Send command to one node. That node will distribute it to other nodes.", "response_map", "=", "@cluster", ".", "request_info", "(", "policy", ",", "str_cmd", ")", "_", ",", "response", "=", "response_map", ".", "first", "vals", "=", "response", ".", "split", "(", "';'", ")", "vals", ".", "map", "do", "|", "udf_info", "|", "next", "if", "udf_info", ".", "strip!", "==", "''", "udf_parts", "=", "udf_info", ".", "split", "(", "','", ")", "udf", "=", "UDF", ".", "new", "udf_parts", ".", "each", "do", "|", "values", "|", "k", ",", "v", "=", "values", ".", "split", "(", "'='", ",", "2", ")", "case", "k", "when", "'filename'", "udf", ".", "filename", "=", "v", "when", "'hash'", "udf", ".", "hash", "=", "v", "when", "'type'", "udf", ".", "language", "=", "v", "end", "end", "udf", "end", "end"], "docstring": "ListUDF lists all packages containing user defined functions in the server.\n This method is only supported by Aerospike 3 servers.", "docstring_tokens": ["ListUDF", "lists", "all", "packages", "containing", "user", "defined", "functions", "in", "the", "server", ".", "This", "method", "is", "only", "supported", "by", "Aerospike", "3", "servers", "."], "sha": "e9d61b8c87e1ec67cb0d70772051f86353b1de45", "url": "https://github.com/aerospike/aerospike-client-ruby/blob/e9d61b8c87e1ec67cb0d70772051f86353b1de45/lib/aerospike/client.rb#L454-L483", "partition": "test"} {"repo": "aerospike/aerospike-client-ruby", "path": "lib/aerospike/client.rb", "func_name": "Aerospike.Client.execute_udf_on_query", "original_string": "def execute_udf_on_query(statement, package_name, function_name, function_args=[], options = nil)\n policy = create_policy(options, QueryPolicy, default_query_policy)\n\n nodes = @cluster.nodes\n if nodes.empty?\n raise Aerospike::Exceptions::Aerospike.new(Aerospike::ResultCode::SERVER_NOT_AVAILABLE, \"Executing UDF failed because cluster is empty.\")\n end\n\n # TODO: wait until all migrations are finished\n statement.set_aggregate_function(package_name, function_name, function_args, false)\n\n # Use a thread per node\n nodes.each do |node|\n Thread.new do\n Thread.current.abort_on_exception = true\n begin\n command = QueryCommand.new(node, policy, statement, nil)\n execute_command(command)\n rescue => e\n Aerospike.logger.error(e)\n raise e\n end\n end\n end\n\n ExecuteTask.new(@cluster, statement)\n end", "language": "ruby", "code": "def execute_udf_on_query(statement, package_name, function_name, function_args=[], options = nil)\n policy = create_policy(options, QueryPolicy, default_query_policy)\n\n nodes = @cluster.nodes\n if nodes.empty?\n raise Aerospike::Exceptions::Aerospike.new(Aerospike::ResultCode::SERVER_NOT_AVAILABLE, \"Executing UDF failed because cluster is empty.\")\n end\n\n # TODO: wait until all migrations are finished\n statement.set_aggregate_function(package_name, function_name, function_args, false)\n\n # Use a thread per node\n nodes.each do |node|\n Thread.new do\n Thread.current.abort_on_exception = true\n begin\n command = QueryCommand.new(node, policy, statement, nil)\n execute_command(command)\n rescue => e\n Aerospike.logger.error(e)\n raise e\n end\n end\n end\n\n ExecuteTask.new(@cluster, statement)\n end", "code_tokens": ["def", "execute_udf_on_query", "(", "statement", ",", "package_name", ",", "function_name", ",", "function_args", "=", "[", "]", ",", "options", "=", "nil", ")", "policy", "=", "create_policy", "(", "options", ",", "QueryPolicy", ",", "default_query_policy", ")", "nodes", "=", "@cluster", ".", "nodes", "if", "nodes", ".", "empty?", "raise", "Aerospike", "::", "Exceptions", "::", "Aerospike", ".", "new", "(", "Aerospike", "::", "ResultCode", "::", "SERVER_NOT_AVAILABLE", ",", "\"Executing UDF failed because cluster is empty.\"", ")", "end", "# TODO: wait until all migrations are finished", "statement", ".", "set_aggregate_function", "(", "package_name", ",", "function_name", ",", "function_args", ",", "false", ")", "# Use a thread per node", "nodes", ".", "each", "do", "|", "node", "|", "Thread", ".", "new", "do", "Thread", ".", "current", ".", "abort_on_exception", "=", "true", "begin", "command", "=", "QueryCommand", ".", "new", "(", "node", ",", "policy", ",", "statement", ",", "nil", ")", "execute_command", "(", "command", ")", "rescue", "=>", "e", "Aerospike", ".", "logger", ".", "error", "(", "e", ")", "raise", "e", "end", "end", "end", "ExecuteTask", ".", "new", "(", "@cluster", ",", "statement", ")", "end"], "docstring": "execute_udf_on_query applies user defined function on records that match the statement filter.\n Records are not returned to the client.\n This asynchronous server call will return before command is complete.\n The user can optionally wait for command completion by using the returned\n ExecuteTask instance.\n\n This method is only supported by Aerospike 3 servers.\n If the policy is nil, the default relevant policy will be used.", "docstring_tokens": ["execute_udf_on_query", "applies", "user", "defined", "function", "on", "records", "that", "match", "the", "statement", "filter", ".", "Records", "are", "not", "returned", "to", "the", "client", ".", "This", "asynchronous", "server", "call", "will", "return", "before", "command", "is", "complete", ".", "The", "user", "can", "optionally", "wait", "for", "command", "completion", "by", "using", "the", "returned", "ExecuteTask", "instance", "."], "sha": "e9d61b8c87e1ec67cb0d70772051f86353b1de45", "url": "https://github.com/aerospike/aerospike-client-ruby/blob/e9d61b8c87e1ec67cb0d70772051f86353b1de45/lib/aerospike/client.rb#L521-L547", "partition": "test"} {"repo": "aerospike/aerospike-client-ruby", "path": "lib/aerospike/client.rb", "func_name": "Aerospike.Client.create_index", "original_string": "def create_index(namespace, set_name, index_name, bin_name, index_type, collection_type = nil, options = nil)\n if options.nil? && collection_type.is_a?(Hash)\n options, collection_type = collection_type, nil\n end\n policy = create_policy(options, Policy, default_info_policy)\n\n str_cmd = \"sindex-create:ns=#{namespace}\"\n str_cmd << \";set=#{set_name}\" unless set_name.to_s.strip.empty?\n str_cmd << \";indexname=#{index_name};numbins=1\"\n str_cmd << \";indextype=#{collection_type.to_s.upcase}\" if collection_type\n str_cmd << \";indexdata=#{bin_name},#{index_type.to_s.upcase}\"\n str_cmd << \";priority=normal\"\n\n # Send index command to one node. That node will distribute the command to other nodes.\n response = send_info_command(policy, str_cmd).upcase\n if response == 'OK'\n # Return task that could optionally be polled for completion.\n return IndexTask.new(@cluster, namespace, index_name)\n end\n\n if response.start_with?('FAIL:200')\n # Index has already been created. Do not need to poll for completion.\n return IndexTask.new(@cluster, namespace, index_name, true)\n end\n\n raise Aerospike::Exceptions::Aerospike.new(Aerospike::ResultCode::INDEX_GENERIC, \"Create index failed: #{response}\")\n end", "language": "ruby", "code": "def create_index(namespace, set_name, index_name, bin_name, index_type, collection_type = nil, options = nil)\n if options.nil? && collection_type.is_a?(Hash)\n options, collection_type = collection_type, nil\n end\n policy = create_policy(options, Policy, default_info_policy)\n\n str_cmd = \"sindex-create:ns=#{namespace}\"\n str_cmd << \";set=#{set_name}\" unless set_name.to_s.strip.empty?\n str_cmd << \";indexname=#{index_name};numbins=1\"\n str_cmd << \";indextype=#{collection_type.to_s.upcase}\" if collection_type\n str_cmd << \";indexdata=#{bin_name},#{index_type.to_s.upcase}\"\n str_cmd << \";priority=normal\"\n\n # Send index command to one node. That node will distribute the command to other nodes.\n response = send_info_command(policy, str_cmd).upcase\n if response == 'OK'\n # Return task that could optionally be polled for completion.\n return IndexTask.new(@cluster, namespace, index_name)\n end\n\n if response.start_with?('FAIL:200')\n # Index has already been created. Do not need to poll for completion.\n return IndexTask.new(@cluster, namespace, index_name, true)\n end\n\n raise Aerospike::Exceptions::Aerospike.new(Aerospike::ResultCode::INDEX_GENERIC, \"Create index failed: #{response}\")\n end", "code_tokens": ["def", "create_index", "(", "namespace", ",", "set_name", ",", "index_name", ",", "bin_name", ",", "index_type", ",", "collection_type", "=", "nil", ",", "options", "=", "nil", ")", "if", "options", ".", "nil?", "&&", "collection_type", ".", "is_a?", "(", "Hash", ")", "options", ",", "collection_type", "=", "collection_type", ",", "nil", "end", "policy", "=", "create_policy", "(", "options", ",", "Policy", ",", "default_info_policy", ")", "str_cmd", "=", "\"sindex-create:ns=#{namespace}\"", "str_cmd", "<<", "\";set=#{set_name}\"", "unless", "set_name", ".", "to_s", ".", "strip", ".", "empty?", "str_cmd", "<<", "\";indexname=#{index_name};numbins=1\"", "str_cmd", "<<", "\";indextype=#{collection_type.to_s.upcase}\"", "if", "collection_type", "str_cmd", "<<", "\";indexdata=#{bin_name},#{index_type.to_s.upcase}\"", "str_cmd", "<<", "\";priority=normal\"", "# Send index command to one node. That node will distribute the command to other nodes.", "response", "=", "send_info_command", "(", "policy", ",", "str_cmd", ")", ".", "upcase", "if", "response", "==", "'OK'", "# Return task that could optionally be polled for completion.", "return", "IndexTask", ".", "new", "(", "@cluster", ",", "namespace", ",", "index_name", ")", "end", "if", "response", ".", "start_with?", "(", "'FAIL:200'", ")", "# Index has already been created. Do not need to poll for completion.", "return", "IndexTask", ".", "new", "(", "@cluster", ",", "namespace", ",", "index_name", ",", "true", ")", "end", "raise", "Aerospike", "::", "Exceptions", "::", "Aerospike", ".", "new", "(", "Aerospike", "::", "ResultCode", "::", "INDEX_GENERIC", ",", "\"Create index failed: #{response}\"", ")", "end"], "docstring": "Create secondary index.\n This asynchronous server call will return before command is complete.\n The user can optionally wait for command completion by using the returned\n IndexTask instance.\n\n This method is only supported by Aerospike 3 servers.\n index_type should be :string, :numeric or :geo2dsphere (requires server version 3.7 or later)\n collection_type should be :list, :mapkeys or :mapvalues", "docstring_tokens": ["Create", "secondary", "index", ".", "This", "asynchronous", "server", "call", "will", "return", "before", "command", "is", "complete", ".", "The", "user", "can", "optionally", "wait", "for", "command", "completion", "by", "using", "the", "returned", "IndexTask", "instance", "."], "sha": "e9d61b8c87e1ec67cb0d70772051f86353b1de45", "url": "https://github.com/aerospike/aerospike-client-ruby/blob/e9d61b8c87e1ec67cb0d70772051f86353b1de45/lib/aerospike/client.rb#L558-L584", "partition": "test"} {"repo": "aerospike/aerospike-client-ruby", "path": "lib/aerospike/client.rb", "func_name": "Aerospike.Client.drop_index", "original_string": "def drop_index(namespace, set_name, index_name, options = nil)\n policy = create_policy(options, Policy, default_info_policy)\n\n str_cmd = \"sindex-delete:ns=#{namespace}\"\n str_cmd << \";set=#{set_name}\" unless set_name.to_s.strip.empty?\n str_cmd << \";indexname=#{index_name}\"\n\n # Send index command to one node. That node will distribute the command to other nodes.\n response = send_info_command(policy, str_cmd).upcase\n return if response == 'OK'\n\n # Index did not previously exist. Return without error.\n return if response.start_with?('FAIL:201')\n\n raise Aerospike::Exceptions::Aerospike.new(Aerospike::ResultCode::INDEX_GENERIC, \"Drop index failed: #{response}\")\n end", "language": "ruby", "code": "def drop_index(namespace, set_name, index_name, options = nil)\n policy = create_policy(options, Policy, default_info_policy)\n\n str_cmd = \"sindex-delete:ns=#{namespace}\"\n str_cmd << \";set=#{set_name}\" unless set_name.to_s.strip.empty?\n str_cmd << \";indexname=#{index_name}\"\n\n # Send index command to one node. That node will distribute the command to other nodes.\n response = send_info_command(policy, str_cmd).upcase\n return if response == 'OK'\n\n # Index did not previously exist. Return without error.\n return if response.start_with?('FAIL:201')\n\n raise Aerospike::Exceptions::Aerospike.new(Aerospike::ResultCode::INDEX_GENERIC, \"Drop index failed: #{response}\")\n end", "code_tokens": ["def", "drop_index", "(", "namespace", ",", "set_name", ",", "index_name", ",", "options", "=", "nil", ")", "policy", "=", "create_policy", "(", "options", ",", "Policy", ",", "default_info_policy", ")", "str_cmd", "=", "\"sindex-delete:ns=#{namespace}\"", "str_cmd", "<<", "\";set=#{set_name}\"", "unless", "set_name", ".", "to_s", ".", "strip", ".", "empty?", "str_cmd", "<<", "\";indexname=#{index_name}\"", "# Send index command to one node. That node will distribute the command to other nodes.", "response", "=", "send_info_command", "(", "policy", ",", "str_cmd", ")", ".", "upcase", "return", "if", "response", "==", "'OK'", "# Index did not previously exist. Return without error.", "return", "if", "response", ".", "start_with?", "(", "'FAIL:201'", ")", "raise", "Aerospike", "::", "Exceptions", "::", "Aerospike", ".", "new", "(", "Aerospike", "::", "ResultCode", "::", "INDEX_GENERIC", ",", "\"Drop index failed: #{response}\"", ")", "end"], "docstring": "Delete secondary index.\n This method is only supported by Aerospike 3 servers.", "docstring_tokens": ["Delete", "secondary", "index", ".", "This", "method", "is", "only", "supported", "by", "Aerospike", "3", "servers", "."], "sha": "e9d61b8c87e1ec67cb0d70772051f86353b1de45", "url": "https://github.com/aerospike/aerospike-client-ruby/blob/e9d61b8c87e1ec67cb0d70772051f86353b1de45/lib/aerospike/client.rb#L588-L603", "partition": "test"} {"repo": "aerospike/aerospike-client-ruby", "path": "lib/aerospike/client.rb", "func_name": "Aerospike.Client.scan_node", "original_string": "def scan_node(node, namespace, set_name, bin_names = nil, options = nil)\n policy = create_policy(options, ScanPolicy, default_scan_policy)\n # wait until all migrations are finished\n # TODO: implement\n # @cluster.WaitUntillMigrationIsFinished(policy.timeout)\n\n # Retry policy must be one-shot for scans.\n # copy on write for policy\n new_policy = policy.clone\n new_policy.max_retries = 0\n\n node = @cluster.get_node_by_name(node) unless node.is_a?(Aerospike::Node)\n\n recordset = Recordset.new(policy.record_queue_size, 1, :scan)\n\n Thread.new do\n Thread.current.abort_on_exception = true\n command = ScanCommand.new(node, new_policy, namespace, set_name, bin_names, recordset)\n begin\n execute_command(command)\n rescue => e\n Aerospike.logger.error(e.backtrace.join(\"\\n\")) unless e == SCAN_TERMINATED_EXCEPTION\n recordset.cancel(e)\n ensure\n recordset.thread_finished\n end\n end\n\n recordset\n end", "language": "ruby", "code": "def scan_node(node, namespace, set_name, bin_names = nil, options = nil)\n policy = create_policy(options, ScanPolicy, default_scan_policy)\n # wait until all migrations are finished\n # TODO: implement\n # @cluster.WaitUntillMigrationIsFinished(policy.timeout)\n\n # Retry policy must be one-shot for scans.\n # copy on write for policy\n new_policy = policy.clone\n new_policy.max_retries = 0\n\n node = @cluster.get_node_by_name(node) unless node.is_a?(Aerospike::Node)\n\n recordset = Recordset.new(policy.record_queue_size, 1, :scan)\n\n Thread.new do\n Thread.current.abort_on_exception = true\n command = ScanCommand.new(node, new_policy, namespace, set_name, bin_names, recordset)\n begin\n execute_command(command)\n rescue => e\n Aerospike.logger.error(e.backtrace.join(\"\\n\")) unless e == SCAN_TERMINATED_EXCEPTION\n recordset.cancel(e)\n ensure\n recordset.thread_finished\n end\n end\n\n recordset\n end", "code_tokens": ["def", "scan_node", "(", "node", ",", "namespace", ",", "set_name", ",", "bin_names", "=", "nil", ",", "options", "=", "nil", ")", "policy", "=", "create_policy", "(", "options", ",", "ScanPolicy", ",", "default_scan_policy", ")", "# wait until all migrations are finished", "# TODO: implement", "# @cluster.WaitUntillMigrationIsFinished(policy.timeout)", "# Retry policy must be one-shot for scans.", "# copy on write for policy", "new_policy", "=", "policy", ".", "clone", "new_policy", ".", "max_retries", "=", "0", "node", "=", "@cluster", ".", "get_node_by_name", "(", "node", ")", "unless", "node", ".", "is_a?", "(", "Aerospike", "::", "Node", ")", "recordset", "=", "Recordset", ".", "new", "(", "policy", ".", "record_queue_size", ",", "1", ",", ":scan", ")", "Thread", ".", "new", "do", "Thread", ".", "current", ".", "abort_on_exception", "=", "true", "command", "=", "ScanCommand", ".", "new", "(", "node", ",", "new_policy", ",", "namespace", ",", "set_name", ",", "bin_names", ",", "recordset", ")", "begin", "execute_command", "(", "command", ")", "rescue", "=>", "e", "Aerospike", ".", "logger", ".", "error", "(", "e", ".", "backtrace", ".", "join", "(", "\"\\n\"", ")", ")", "unless", "e", "==", "SCAN_TERMINATED_EXCEPTION", "recordset", ".", "cancel", "(", "e", ")", "ensure", "recordset", ".", "thread_finished", "end", "end", "recordset", "end"], "docstring": "ScanNode reads all records in specified namespace and set, from one node only.\n The policy can be used to specify timeouts.", "docstring_tokens": ["ScanNode", "reads", "all", "records", "in", "specified", "namespace", "and", "set", "from", "one", "node", "only", ".", "The", "policy", "can", "be", "used", "to", "specify", "timeouts", "."], "sha": "e9d61b8c87e1ec67cb0d70772051f86353b1de45", "url": "https://github.com/aerospike/aerospike-client-ruby/blob/e9d61b8c87e1ec67cb0d70772051f86353b1de45/lib/aerospike/client.rb#L670-L699", "partition": "test"} {"repo": "aerospike/aerospike-client-ruby", "path": "lib/aerospike/client.rb", "func_name": "Aerospike.Client.drop_user", "original_string": "def drop_user(user, options = nil)\n policy = create_policy(options, AdminPolicy, default_admin_policy)\n command = AdminCommand.new\n command.drop_user(@cluster, policy, user)\n end", "language": "ruby", "code": "def drop_user(user, options = nil)\n policy = create_policy(options, AdminPolicy, default_admin_policy)\n command = AdminCommand.new\n command.drop_user(@cluster, policy, user)\n end", "code_tokens": ["def", "drop_user", "(", "user", ",", "options", "=", "nil", ")", "policy", "=", "create_policy", "(", "options", ",", "AdminPolicy", ",", "default_admin_policy", ")", "command", "=", "AdminCommand", ".", "new", "command", ".", "drop_user", "(", "@cluster", ",", "policy", ",", "user", ")", "end"], "docstring": "Remove user from cluster.", "docstring_tokens": ["Remove", "user", "from", "cluster", "."], "sha": "e9d61b8c87e1ec67cb0d70772051f86353b1de45", "url": "https://github.com/aerospike/aerospike-client-ruby/blob/e9d61b8c87e1ec67cb0d70772051f86353b1de45/lib/aerospike/client.rb#L756-L760", "partition": "test"} {"repo": "aerospike/aerospike-client-ruby", "path": "lib/aerospike/client.rb", "func_name": "Aerospike.Client.change_password", "original_string": "def change_password(user, password, options = nil)\n raise Aerospike::Exceptions::Aerospike.new(INVALID_USER) unless @cluster.user && @cluster.user != \"\"\n policy = create_policy(options, AdminPolicy, default_admin_policy)\n\n hash = AdminCommand.hash_password(password)\n command = AdminCommand.new\n\n if user == @cluster.user\n # Change own password.\n command.change_password(@cluster, policy, user, hash)\n else\n # Change other user's password by user admin.\n command.set_password(@cluster, policy, user, hash)\n end\n\n @cluster.change_password(user, hash)\n end", "language": "ruby", "code": "def change_password(user, password, options = nil)\n raise Aerospike::Exceptions::Aerospike.new(INVALID_USER) unless @cluster.user && @cluster.user != \"\"\n policy = create_policy(options, AdminPolicy, default_admin_policy)\n\n hash = AdminCommand.hash_password(password)\n command = AdminCommand.new\n\n if user == @cluster.user\n # Change own password.\n command.change_password(@cluster, policy, user, hash)\n else\n # Change other user's password by user admin.\n command.set_password(@cluster, policy, user, hash)\n end\n\n @cluster.change_password(user, hash)\n end", "code_tokens": ["def", "change_password", "(", "user", ",", "password", ",", "options", "=", "nil", ")", "raise", "Aerospike", "::", "Exceptions", "::", "Aerospike", ".", "new", "(", "INVALID_USER", ")", "unless", "@cluster", ".", "user", "&&", "@cluster", ".", "user", "!=", "\"\"", "policy", "=", "create_policy", "(", "options", ",", "AdminPolicy", ",", "default_admin_policy", ")", "hash", "=", "AdminCommand", ".", "hash_password", "(", "password", ")", "command", "=", "AdminCommand", ".", "new", "if", "user", "==", "@cluster", ".", "user", "# Change own password.", "command", ".", "change_password", "(", "@cluster", ",", "policy", ",", "user", ",", "hash", ")", "else", "# Change other user's password by user admin.", "command", ".", "set_password", "(", "@cluster", ",", "policy", ",", "user", ",", "hash", ")", "end", "@cluster", ".", "change_password", "(", "user", ",", "hash", ")", "end"], "docstring": "Change user's password. Clear-text password will be hashed using bcrypt before sending to server.", "docstring_tokens": ["Change", "user", "s", "password", ".", "Clear", "-", "text", "password", "will", "be", "hashed", "using", "bcrypt", "before", "sending", "to", "server", "."], "sha": "e9d61b8c87e1ec67cb0d70772051f86353b1de45", "url": "https://github.com/aerospike/aerospike-client-ruby/blob/e9d61b8c87e1ec67cb0d70772051f86353b1de45/lib/aerospike/client.rb#L763-L779", "partition": "test"} {"repo": "aerospike/aerospike-client-ruby", "path": "lib/aerospike/client.rb", "func_name": "Aerospike.Client.grant_roles", "original_string": "def grant_roles(user, roles, options = nil)\n policy = create_policy(options, AdminPolicy, default_admin_policy)\n command = AdminCommand.new\n command.grant_roles(@cluster, policy, user, roles)\n end", "language": "ruby", "code": "def grant_roles(user, roles, options = nil)\n policy = create_policy(options, AdminPolicy, default_admin_policy)\n command = AdminCommand.new\n command.grant_roles(@cluster, policy, user, roles)\n end", "code_tokens": ["def", "grant_roles", "(", "user", ",", "roles", ",", "options", "=", "nil", ")", "policy", "=", "create_policy", "(", "options", ",", "AdminPolicy", ",", "default_admin_policy", ")", "command", "=", "AdminCommand", ".", "new", "command", ".", "grant_roles", "(", "@cluster", ",", "policy", ",", "user", ",", "roles", ")", "end"], "docstring": "Add roles to user's list of roles.", "docstring_tokens": ["Add", "roles", "to", "user", "s", "list", "of", "roles", "."], "sha": "e9d61b8c87e1ec67cb0d70772051f86353b1de45", "url": "https://github.com/aerospike/aerospike-client-ruby/blob/e9d61b8c87e1ec67cb0d70772051f86353b1de45/lib/aerospike/client.rb#L782-L786", "partition": "test"} {"repo": "aerospike/aerospike-client-ruby", "path": "lib/aerospike/client.rb", "func_name": "Aerospike.Client.query_users", "original_string": "def query_users(options = nil)\n policy = create_policy(options, AdminPolicy, default_admin_policy)\n command = AdminCommand.new\n command.query_users(@cluster, policy)\n end", "language": "ruby", "code": "def query_users(options = nil)\n policy = create_policy(options, AdminPolicy, default_admin_policy)\n command = AdminCommand.new\n command.query_users(@cluster, policy)\n end", "code_tokens": ["def", "query_users", "(", "options", "=", "nil", ")", "policy", "=", "create_policy", "(", "options", ",", "AdminPolicy", ",", "default_admin_policy", ")", "command", "=", "AdminCommand", ".", "new", "command", ".", "query_users", "(", "@cluster", ",", "policy", ")", "end"], "docstring": "Retrieve all users and their roles.", "docstring_tokens": ["Retrieve", "all", "users", "and", "their", "roles", "."], "sha": "e9d61b8c87e1ec67cb0d70772051f86353b1de45", "url": "https://github.com/aerospike/aerospike-client-ruby/blob/e9d61b8c87e1ec67cb0d70772051f86353b1de45/lib/aerospike/client.rb#L803-L807", "partition": "test"} {"repo": "aerospike/aerospike-client-ruby", "path": "lib/aerospike/query/recordset.rb", "func_name": "Aerospike.Recordset.next_record", "original_string": "def next_record\n raise @thread_exception.get unless @thread_exception.get.nil?\n\n r = @records.deq\n\n set_exception if r.nil?\n\n r\n end", "language": "ruby", "code": "def next_record\n raise @thread_exception.get unless @thread_exception.get.nil?\n\n r = @records.deq\n\n set_exception if r.nil?\n\n r\n end", "code_tokens": ["def", "next_record", "raise", "@thread_exception", ".", "get", "unless", "@thread_exception", ".", "get", ".", "nil?", "r", "=", "@records", ".", "deq", "set_exception", "if", "r", ".", "nil?", "r", "end"], "docstring": "fetches and return the first record from the queue\n if the operation is not finished and the queue is empty it blocks and waits for new records\n it sets the exception if it reaches the EOF mark, and returns nil\n EOF means the operation has finished and no more records are comming from server nodes\n it re-raises the exception occurred in threads, or which was set after reaching the EOF in the previous call", "docstring_tokens": ["fetches", "and", "return", "the", "first", "record", "from", "the", "queue", "if", "the", "operation", "is", "not", "finished", "and", "the", "queue", "is", "empty", "it", "blocks", "and", "waits", "for", "new", "records", "it", "sets", "the", "exception", "if", "it", "reaches", "the", "EOF", "mark", "and", "returns", "nil", "EOF", "means", "the", "operation", "has", "finished", "and", "no", "more", "records", "are", "comming", "from", "server", "nodes", "it", "re", "-", "raises", "the", "exception", "occurred", "in", "threads", "or", "which", "was", "set", "after", "reaching", "the", "EOF", "in", "the", "previous", "call"], "sha": "e9d61b8c87e1ec67cb0d70772051f86353b1de45", "url": "https://github.com/aerospike/aerospike-client-ruby/blob/e9d61b8c87e1ec67cb0d70772051f86353b1de45/lib/aerospike/query/recordset.rb#L52-L60", "partition": "test"} {"repo": "aerospike/aerospike-client-ruby", "path": "lib/aerospike/query/recordset.rb", "func_name": "Aerospike.Recordset.each", "original_string": "def each(&block)\n r = true\n while r\n r = next_record\n # nil means EOF\n unless r.nil?\n block.call(r)\n else\n # reached the EOF\n break\n end\n end\n end", "language": "ruby", "code": "def each(&block)\n r = true\n while r\n r = next_record\n # nil means EOF\n unless r.nil?\n block.call(r)\n else\n # reached the EOF\n break\n end\n end\n end", "code_tokens": ["def", "each", "(", "&", "block", ")", "r", "=", "true", "while", "r", "r", "=", "next_record", "# nil means EOF", "unless", "r", ".", "nil?", "block", ".", "call", "(", "r", ")", "else", "# reached the EOF", "break", "end", "end", "end"], "docstring": "fetches and returns all the records from the queue until the whole operation is finished and it reaches an EOF mark\n calling cancel inside the each block raises an exception to signal other consumer threads", "docstring_tokens": ["fetches", "and", "returns", "all", "the", "records", "from", "the", "queue", "until", "the", "whole", "operation", "is", "finished", "and", "it", "reaches", "an", "EOF", "mark", "calling", "cancel", "inside", "the", "each", "block", "raises", "an", "exception", "to", "signal", "other", "consumer", "threads"], "sha": "e9d61b8c87e1ec67cb0d70772051f86353b1de45", "url": "https://github.com/aerospike/aerospike-client-ruby/blob/e9d61b8c87e1ec67cb0d70772051f86353b1de45/lib/aerospike/query/recordset.rb#L88-L100", "partition": "test"} {"repo": "intercom/intercom-rails", "path": "lib/intercom-rails/script_tag_helper.rb", "func_name": "IntercomRails.ScriptTagHelper.intercom_script_tag", "original_string": "def intercom_script_tag(user_details = nil, options={})\n controller.instance_variable_set(IntercomRails::SCRIPT_TAG_HELPER_CALLED_INSTANCE_VARIABLE, true) if defined?(controller)\n options[:user_details] = user_details if user_details.present?\n options[:find_current_user_details] = !options[:user_details]\n options[:find_current_company_details] = !(options[:user_details] && options[:user_details][:company])\n options[:controller] = controller if defined?(controller)\n ScriptTag.new(options)\n end", "language": "ruby", "code": "def intercom_script_tag(user_details = nil, options={})\n controller.instance_variable_set(IntercomRails::SCRIPT_TAG_HELPER_CALLED_INSTANCE_VARIABLE, true) if defined?(controller)\n options[:user_details] = user_details if user_details.present?\n options[:find_current_user_details] = !options[:user_details]\n options[:find_current_company_details] = !(options[:user_details] && options[:user_details][:company])\n options[:controller] = controller if defined?(controller)\n ScriptTag.new(options)\n end", "code_tokens": ["def", "intercom_script_tag", "(", "user_details", "=", "nil", ",", "options", "=", "{", "}", ")", "controller", ".", "instance_variable_set", "(", "IntercomRails", "::", "SCRIPT_TAG_HELPER_CALLED_INSTANCE_VARIABLE", ",", "true", ")", "if", "defined?", "(", "controller", ")", "options", "[", ":user_details", "]", "=", "user_details", "if", "user_details", ".", "present?", "options", "[", ":find_current_user_details", "]", "=", "!", "options", "[", ":user_details", "]", "options", "[", ":find_current_company_details", "]", "=", "!", "(", "options", "[", ":user_details", "]", "&&", "options", "[", ":user_details", "]", "[", ":company", "]", ")", "options", "[", ":controller", "]", "=", "controller", "if", "defined?", "(", "controller", ")", "ScriptTag", ".", "new", "(", "options", ")", "end"], "docstring": "Generate an intercom script tag.\n\n @param user_details [Hash] a customizable hash of user details\n @param options [Hash] an optional hash for Identity Verification and widget customization\n @option user_details [String] :app_id Your application id\n @option user_details [String] :user_id unique id of this user within your application\n @option user_details [String] :email email address for this user\n @option user_details [String] :name the users name, _optional_ but useful for identify people in the Intercom App.\n @option user_details [Hash] :custom_data custom attributes you'd like saved for this user on Intercom.\n @option options [String] :widget a hash containing a css selector for an element which when clicked should show the Intercom widget\n @option options [String] :secret Your app secret for Identity Verification\n @option options [String] :nonce a nonce generated by your CSP framework to be included inside the javascript tag\n @return [String] Intercom script tag\n @example basic example\n <%= intercom_script_tag({ :app_id => \"your-app-id\",\n :user_id => current_user.id,\n :email => current_user.email,\n :custom_data => { :plan => current_user.plan.name },\n :name => current_user.name }) %>\n @example with widget activator for launching then widget when an element matching the css selector '#Intercom' is clicked.\n <%= intercom_script_tag({ :app_id => \"your-app-id\",\n :user_id => current_user.id,\n :email => current_user.email,\n :custom_data => { :plan => current_user.plan.name },\n :name => current_user.name },\n {:widget => {:activator => \"#Intercom\"}},) %>", "docstring_tokens": ["Generate", "an", "intercom", "script", "tag", "."], "sha": "40ecba4290498a7aaed69e69880821f3400f63ae", "url": "https://github.com/intercom/intercom-rails/blob/40ecba4290498a7aaed69e69880821f3400f63ae/lib/intercom-rails/script_tag_helper.rb#L31-L38", "partition": "test"} {"repo": "victords/minigl", "path": "lib/minigl/movement.rb", "func_name": "MiniGL.Movement.move_free", "original_string": "def move_free(aim, speed)\n if aim.is_a? Vector\n x_d = aim.x - @x; y_d = aim.y - @y\n distance = Math.sqrt(x_d**2 + y_d**2)\n\n if distance == 0\n @speed.x = @speed.y = 0\n return\n end\n\n @speed.x = 1.0 * x_d * speed / distance\n @speed.y = 1.0 * y_d * speed / distance\n\n if (@speed.x < 0 and @x + @speed.x <= aim.x) or (@speed.x >= 0 and @x + @speed.x >= aim.x)\n @x = aim.x\n @speed.x = 0\n else\n @x += @speed.x\n end\n\n if (@speed.y < 0 and @y + @speed.y <= aim.y) or (@speed.y >= 0 and @y + @speed.y >= aim.y)\n @y = aim.y\n @speed.y = 0\n else\n @y += @speed.y\n end\n else\n rads = aim * Math::PI / 180\n @speed.x = speed * Math.cos(rads)\n @speed.y = speed * Math.sin(rads)\n @x += @speed.x\n @y += @speed.y\n end\n end", "language": "ruby", "code": "def move_free(aim, speed)\n if aim.is_a? Vector\n x_d = aim.x - @x; y_d = aim.y - @y\n distance = Math.sqrt(x_d**2 + y_d**2)\n\n if distance == 0\n @speed.x = @speed.y = 0\n return\n end\n\n @speed.x = 1.0 * x_d * speed / distance\n @speed.y = 1.0 * y_d * speed / distance\n\n if (@speed.x < 0 and @x + @speed.x <= aim.x) or (@speed.x >= 0 and @x + @speed.x >= aim.x)\n @x = aim.x\n @speed.x = 0\n else\n @x += @speed.x\n end\n\n if (@speed.y < 0 and @y + @speed.y <= aim.y) or (@speed.y >= 0 and @y + @speed.y >= aim.y)\n @y = aim.y\n @speed.y = 0\n else\n @y += @speed.y\n end\n else\n rads = aim * Math::PI / 180\n @speed.x = speed * Math.cos(rads)\n @speed.y = speed * Math.sin(rads)\n @x += @speed.x\n @y += @speed.y\n end\n end", "code_tokens": ["def", "move_free", "(", "aim", ",", "speed", ")", "if", "aim", ".", "is_a?", "Vector", "x_d", "=", "aim", ".", "x", "-", "@x", ";", "y_d", "=", "aim", ".", "y", "-", "@y", "distance", "=", "Math", ".", "sqrt", "(", "x_d", "**", "2", "+", "y_d", "**", "2", ")", "if", "distance", "==", "0", "@speed", ".", "x", "=", "@speed", ".", "y", "=", "0", "return", "end", "@speed", ".", "x", "=", "1.0", "*", "x_d", "*", "speed", "/", "distance", "@speed", ".", "y", "=", "1.0", "*", "y_d", "*", "speed", "/", "distance", "if", "(", "@speed", ".", "x", "<", "0", "and", "@x", "+", "@speed", ".", "x", "<=", "aim", ".", "x", ")", "or", "(", "@speed", ".", "x", ">=", "0", "and", "@x", "+", "@speed", ".", "x", ">=", "aim", ".", "x", ")", "@x", "=", "aim", ".", "x", "@speed", ".", "x", "=", "0", "else", "@x", "+=", "@speed", ".", "x", "end", "if", "(", "@speed", ".", "y", "<", "0", "and", "@y", "+", "@speed", ".", "y", "<=", "aim", ".", "y", ")", "or", "(", "@speed", ".", "y", ">=", "0", "and", "@y", "+", "@speed", ".", "y", ">=", "aim", ".", "y", ")", "@y", "=", "aim", ".", "y", "@speed", ".", "y", "=", "0", "else", "@y", "+=", "@speed", ".", "y", "end", "else", "rads", "=", "aim", "*", "Math", "::", "PI", "/", "180", "@speed", ".", "x", "=", "speed", "*", "Math", ".", "cos", "(", "rads", ")", "@speed", ".", "y", "=", "speed", "*", "Math", ".", "sin", "(", "rads", ")", "@x", "+=", "@speed", ".", "x", "@y", "+=", "@speed", ".", "y", "end", "end"], "docstring": "Moves this object, without performing any collision checking, towards\n a specified point or in a specified direction.\n\n Parameters:\n [aim] A +Vector+ specifying where the object will move to or an angle (in\n degrees) indicating the direction of the movement. Angles are\n measured starting from the right (i.e., to move to the right, the\n angle must be 0) and raising clockwise.\n [speed] The constant speed at which the object will move. This must be\n provided as a scalar, not a vector.", "docstring_tokens": ["Moves", "this", "object", "without", "performing", "any", "collision", "checking", "towards", "a", "specified", "point", "or", "in", "a", "specified", "direction", "."], "sha": "a7117a566141cd922a4fd90ab71ba63ed8a92080", "url": "https://github.com/victords/minigl/blob/a7117a566141cd922a4fd90ab71ba63ed8a92080/lib/minigl/movement.rb#L451-L484", "partition": "test"} {"repo": "victords/minigl", "path": "lib/minigl/map.rb", "func_name": "MiniGL.Map.get_absolute_size", "original_string": "def get_absolute_size\n return Vector.new(@tile_size.x * @size.x, @tile_size.y * @size.y) unless @isometric\n avg = (@size.x + @size.y) * 0.5\n Vector.new (avg * @tile_size.x).to_i, (avg * @tile_size.y).to_i\n end", "language": "ruby", "code": "def get_absolute_size\n return Vector.new(@tile_size.x * @size.x, @tile_size.y * @size.y) unless @isometric\n avg = (@size.x + @size.y) * 0.5\n Vector.new (avg * @tile_size.x).to_i, (avg * @tile_size.y).to_i\n end", "code_tokens": ["def", "get_absolute_size", "return", "Vector", ".", "new", "(", "@tile_size", ".", "x", "*", "@size", ".", "x", ",", "@tile_size", ".", "y", "*", "@size", ".", "y", ")", "unless", "@isometric", "avg", "=", "(", "@size", ".", "x", "+", "@size", ".", "y", ")", "*", "0.5", "Vector", ".", "new", "(", "avg", "*", "@tile_size", ".", "x", ")", ".", "to_i", ",", "(", "avg", "*", "@tile_size", ".", "y", ")", ".", "to_i", "end"], "docstring": "Creates a new map.\n\n Parameters:\n [t_w] The width of the tiles.\n [t_h] The height of the tiles.\n [t_x_count] The horizontal count of tiles in the map.\n [t_y_count] The vertical count of tiles in the map.\n [scr_w] Width of the viewport for the map.\n [scr_h] Height of the viewport for the map.\n [isometric] Whether to use a isometric map. By default, an ortogonal map\n is used.\n [limit_cam] Whether the camera should respect the bounds of the map\n (i.e., when given coordinates that would imply regions\n outside the map to appear in the screen, the camera would\n move to the nearest position where only the map shows up\n in the screen).\n Returns a Vector with the total size of the map, in pixels (x for the\n width and y for the height).", "docstring_tokens": ["Creates", "a", "new", "map", "."], "sha": "a7117a566141cd922a4fd90ab71ba63ed8a92080", "url": "https://github.com/victords/minigl/blob/a7117a566141cd922a4fd90ab71ba63ed8a92080/lib/minigl/map.rb#L59-L63", "partition": "test"} {"repo": "victords/minigl", "path": "lib/minigl/map.rb", "func_name": "MiniGL.Map.get_screen_pos", "original_string": "def get_screen_pos(map_x, map_y)\n return Vector.new(map_x * @tile_size.x - @cam.x, map_y * @tile_size.y - @cam.y) unless @isometric\n Vector.new ((map_x - map_y - 1) * @tile_size.x * 0.5) - @cam.x + @x_offset,\n ((map_x + map_y) * @tile_size.y * 0.5) - @cam.y\n end", "language": "ruby", "code": "def get_screen_pos(map_x, map_y)\n return Vector.new(map_x * @tile_size.x - @cam.x, map_y * @tile_size.y - @cam.y) unless @isometric\n Vector.new ((map_x - map_y - 1) * @tile_size.x * 0.5) - @cam.x + @x_offset,\n ((map_x + map_y) * @tile_size.y * 0.5) - @cam.y\n end", "code_tokens": ["def", "get_screen_pos", "(", "map_x", ",", "map_y", ")", "return", "Vector", ".", "new", "(", "map_x", "*", "@tile_size", ".", "x", "-", "@cam", ".", "x", ",", "map_y", "*", "@tile_size", ".", "y", "-", "@cam", ".", "y", ")", "unless", "@isometric", "Vector", ".", "new", "(", "(", "map_x", "-", "map_y", "-", "1", ")", "*", "@tile_size", ".", "x", "*", "0.5", ")", "-", "@cam", ".", "x", "+", "@x_offset", ",", "(", "(", "map_x", "+", "map_y", ")", "*", "@tile_size", ".", "y", "*", "0.5", ")", "-", "@cam", ".", "y", "end"], "docstring": "Returns the position in the screen corresponding to the given tile\n indices.\n\n Parameters:\n [map_x] The index of the tile in the horizontal direction. It must be in\n the interval 0..t_x_count.\n [map_y] The index of the tile in the vertical direction. It must be in\n the interval 0..t_y_count.", "docstring_tokens": ["Returns", "the", "position", "in", "the", "screen", "corresponding", "to", "the", "given", "tile", "indices", "."], "sha": "a7117a566141cd922a4fd90ab71ba63ed8a92080", "url": "https://github.com/victords/minigl/blob/a7117a566141cd922a4fd90ab71ba63ed8a92080/lib/minigl/map.rb#L79-L83", "partition": "test"} {"repo": "victords/minigl", "path": "lib/minigl/map.rb", "func_name": "MiniGL.Map.get_map_pos", "original_string": "def get_map_pos(scr_x, scr_y)\n return Vector.new((scr_x + @cam.x) / @tile_size.x, (scr_y + @cam.y) / @tile_size.y) unless @isometric\n\n # Gets the position transformed to isometric coordinates\n v = get_isometric_position scr_x, scr_y\n\n # divides by the square size to find the position in the matrix\n Vector.new((v.x * @inverse_square_size).to_i, (v.y * @inverse_square_size).to_i)\n end", "language": "ruby", "code": "def get_map_pos(scr_x, scr_y)\n return Vector.new((scr_x + @cam.x) / @tile_size.x, (scr_y + @cam.y) / @tile_size.y) unless @isometric\n\n # Gets the position transformed to isometric coordinates\n v = get_isometric_position scr_x, scr_y\n\n # divides by the square size to find the position in the matrix\n Vector.new((v.x * @inverse_square_size).to_i, (v.y * @inverse_square_size).to_i)\n end", "code_tokens": ["def", "get_map_pos", "(", "scr_x", ",", "scr_y", ")", "return", "Vector", ".", "new", "(", "(", "scr_x", "+", "@cam", ".", "x", ")", "/", "@tile_size", ".", "x", ",", "(", "scr_y", "+", "@cam", ".", "y", ")", "/", "@tile_size", ".", "y", ")", "unless", "@isometric", "# Gets the position transformed to isometric coordinates", "v", "=", "get_isometric_position", "scr_x", ",", "scr_y", "# divides by the square size to find the position in the matrix", "Vector", ".", "new", "(", "(", "v", ".", "x", "*", "@inverse_square_size", ")", ".", "to_i", ",", "(", "v", ".", "y", "*", "@inverse_square_size", ")", ".", "to_i", ")", "end"], "docstring": "Returns the tile in the map that corresponds to the given position in\n the screen, as a Vector, where x is the horizontal index and y the\n vertical index.\n\n Parameters:\n [scr_x] The x-coordinate in the screen.\n [scr_y] The y-coordinate in the screen.", "docstring_tokens": ["Returns", "the", "tile", "in", "the", "map", "that", "corresponds", "to", "the", "given", "position", "in", "the", "screen", "as", "a", "Vector", "where", "x", "is", "the", "horizontal", "index", "and", "y", "the", "vertical", "index", "."], "sha": "a7117a566141cd922a4fd90ab71ba63ed8a92080", "url": "https://github.com/victords/minigl/blob/a7117a566141cd922a4fd90ab71ba63ed8a92080/lib/minigl/map.rb#L92-L100", "partition": "test"} {"repo": "victords/minigl", "path": "lib/minigl/map.rb", "func_name": "MiniGL.Map.is_in_map", "original_string": "def is_in_map(v)\n v.x >= 0 && v.y >= 0 && v.x < @size.x && v.y < @size.y\n end", "language": "ruby", "code": "def is_in_map(v)\n v.x >= 0 && v.y >= 0 && v.x < @size.x && v.y < @size.y\n end", "code_tokens": ["def", "is_in_map", "(", "v", ")", "v", ".", "x", ">=", "0", "&&", "v", ".", "y", ">=", "0", "&&", "v", ".", "x", "<", "@size", ".", "x", "&&", "v", ".", "y", "<", "@size", ".", "y", "end"], "docstring": "Verifies whether a tile is inside the map.\n\n Parameters:\n [v] A Vector representing the tile, with x as the horizontal index and\n y as the vertical index.", "docstring_tokens": ["Verifies", "whether", "a", "tile", "is", "inside", "the", "map", "."], "sha": "a7117a566141cd922a4fd90ab71ba63ed8a92080", "url": "https://github.com/victords/minigl/blob/a7117a566141cd922a4fd90ab71ba63ed8a92080/lib/minigl/map.rb#L107-L109", "partition": "test"} {"repo": "victords/minigl", "path": "lib/minigl/game_object.rb", "func_name": "MiniGL.Sprite.animate_once", "original_string": "def animate_once(indices, interval)\n if @animate_once_control == 2\n return if indices == @animate_once_indices && interval == @animate_once_interval\n @animate_once_control = 0\n end\n\n unless @animate_once_control == 1\n @anim_counter = 0\n @img_index = indices[0]\n @index_index = 0\n @animate_once_indices = indices\n @animate_once_interval = interval\n @animate_once_control = 1\n return\n end\n\n @anim_counter += 1\n return unless @anim_counter >= interval\n\n @index_index += 1\n @img_index = indices[@index_index]\n @anim_counter = 0\n @animate_once_control = 2 if @index_index == indices.length - 1\n end", "language": "ruby", "code": "def animate_once(indices, interval)\n if @animate_once_control == 2\n return if indices == @animate_once_indices && interval == @animate_once_interval\n @animate_once_control = 0\n end\n\n unless @animate_once_control == 1\n @anim_counter = 0\n @img_index = indices[0]\n @index_index = 0\n @animate_once_indices = indices\n @animate_once_interval = interval\n @animate_once_control = 1\n return\n end\n\n @anim_counter += 1\n return unless @anim_counter >= interval\n\n @index_index += 1\n @img_index = indices[@index_index]\n @anim_counter = 0\n @animate_once_control = 2 if @index_index == indices.length - 1\n end", "code_tokens": ["def", "animate_once", "(", "indices", ",", "interval", ")", "if", "@animate_once_control", "==", "2", "return", "if", "indices", "==", "@animate_once_indices", "&&", "interval", "==", "@animate_once_interval", "@animate_once_control", "=", "0", "end", "unless", "@animate_once_control", "==", "1", "@anim_counter", "=", "0", "@img_index", "=", "indices", "[", "0", "]", "@index_index", "=", "0", "@animate_once_indices", "=", "indices", "@animate_once_interval", "=", "interval", "@animate_once_control", "=", "1", "return", "end", "@anim_counter", "+=", "1", "return", "unless", "@anim_counter", ">=", "interval", "@index_index", "+=", "1", "@img_index", "=", "indices", "[", "@index_index", "]", "@anim_counter", "=", "0", "@animate_once_control", "=", "2", "if", "@index_index", "==", "indices", ".", "length", "-", "1", "end"], "docstring": "Causes the sprite to animate through the +indices+ array exactly once,\n so that the animation stops once it reaches the last index in the array.\n Subsequent calls with the same parameters will have no effect, but if\n the index or interval changes, or if +set_animation+ is called, then a\n new animation cycle will begin.\n\n Parameters:\n [indices] The sequence of image indices used in the animation. See\n +animate+ for details.\n [interval] The amount of frames between each change in the image index.\n See +animate+ for details.", "docstring_tokens": ["Causes", "the", "sprite", "to", "animate", "through", "the", "+", "indices", "+", "array", "exactly", "once", "so", "that", "the", "animation", "stops", "once", "it", "reaches", "the", "last", "index", "in", "the", "array", ".", "Subsequent", "calls", "with", "the", "same", "parameters", "will", "have", "no", "effect", "but", "if", "the", "index", "or", "interval", "changes", "or", "if", "+", "set_animation", "+", "is", "called", "then", "a", "new", "animation", "cycle", "will", "begin", "."], "sha": "a7117a566141cd922a4fd90ab71ba63ed8a92080", "url": "https://github.com/victords/minigl/blob/a7117a566141cd922a4fd90ab71ba63ed8a92080/lib/minigl/game_object.rb#L84-L107", "partition": "test"} {"repo": "victords/minigl", "path": "lib/minigl/game_object.rb", "func_name": "MiniGL.Sprite.draw", "original_string": "def draw(map = nil, scale_x = 1, scale_y = 1, alpha = 0xff, color = 0xffffff, angle = nil, flip = nil, z_index = 0, round = false)\n if map.is_a? Hash\n scale_x = map.fetch(:scale_x, 1)\n scale_y = map.fetch(:scale_y, 1)\n alpha = map.fetch(:alpha, 0xff)\n color = map.fetch(:color, 0xffffff)\n angle = map.fetch(:angle, nil)\n flip = map.fetch(:flip, nil)\n z_index = map.fetch(:z_index, 0)\n round = map.fetch(:round, false)\n map = map.fetch(:map, nil)\n end\n\n color = (alpha << 24) | color\n if angle\n @img[@img_index].draw_rot @x - (map ? map.cam.x : 0) + @img[0].width * scale_x * 0.5,\n @y - (map ? map.cam.y : 0) + @img[0].height * scale_y * 0.5,\n z_index, angle, 0.5, 0.5, (flip == :horiz ? -scale_x : scale_x),\n (flip == :vert ? -scale_y : scale_y), color\n else\n x = @x - (map ? map.cam.x : 0) + (flip == :horiz ? scale_x * @img[0].width : 0)\n y = @y - (map ? map.cam.y : 0) + (flip == :vert ? scale_y * @img[0].height : 0)\n @img[@img_index].draw (round ? x.round : x), (round ? y.round : y),\n z_index, (flip == :horiz ? -scale_x : scale_x),\n (flip == :vert ? -scale_y : scale_y), color\n end\n end", "language": "ruby", "code": "def draw(map = nil, scale_x = 1, scale_y = 1, alpha = 0xff, color = 0xffffff, angle = nil, flip = nil, z_index = 0, round = false)\n if map.is_a? Hash\n scale_x = map.fetch(:scale_x, 1)\n scale_y = map.fetch(:scale_y, 1)\n alpha = map.fetch(:alpha, 0xff)\n color = map.fetch(:color, 0xffffff)\n angle = map.fetch(:angle, nil)\n flip = map.fetch(:flip, nil)\n z_index = map.fetch(:z_index, 0)\n round = map.fetch(:round, false)\n map = map.fetch(:map, nil)\n end\n\n color = (alpha << 24) | color\n if angle\n @img[@img_index].draw_rot @x - (map ? map.cam.x : 0) + @img[0].width * scale_x * 0.5,\n @y - (map ? map.cam.y : 0) + @img[0].height * scale_y * 0.5,\n z_index, angle, 0.5, 0.5, (flip == :horiz ? -scale_x : scale_x),\n (flip == :vert ? -scale_y : scale_y), color\n else\n x = @x - (map ? map.cam.x : 0) + (flip == :horiz ? scale_x * @img[0].width : 0)\n y = @y - (map ? map.cam.y : 0) + (flip == :vert ? scale_y * @img[0].height : 0)\n @img[@img_index].draw (round ? x.round : x), (round ? y.round : y),\n z_index, (flip == :horiz ? -scale_x : scale_x),\n (flip == :vert ? -scale_y : scale_y), color\n end\n end", "code_tokens": ["def", "draw", "(", "map", "=", "nil", ",", "scale_x", "=", "1", ",", "scale_y", "=", "1", ",", "alpha", "=", "0xff", ",", "color", "=", "0xffffff", ",", "angle", "=", "nil", ",", "flip", "=", "nil", ",", "z_index", "=", "0", ",", "round", "=", "false", ")", "if", "map", ".", "is_a?", "Hash", "scale_x", "=", "map", ".", "fetch", "(", ":scale_x", ",", "1", ")", "scale_y", "=", "map", ".", "fetch", "(", ":scale_y", ",", "1", ")", "alpha", "=", "map", ".", "fetch", "(", ":alpha", ",", "0xff", ")", "color", "=", "map", ".", "fetch", "(", ":color", ",", "0xffffff", ")", "angle", "=", "map", ".", "fetch", "(", ":angle", ",", "nil", ")", "flip", "=", "map", ".", "fetch", "(", ":flip", ",", "nil", ")", "z_index", "=", "map", ".", "fetch", "(", ":z_index", ",", "0", ")", "round", "=", "map", ".", "fetch", "(", ":round", ",", "false", ")", "map", "=", "map", ".", "fetch", "(", ":map", ",", "nil", ")", "end", "color", "=", "(", "alpha", "<<", "24", ")", "|", "color", "if", "angle", "@img", "[", "@img_index", "]", ".", "draw_rot", "@x", "-", "(", "map", "?", "map", ".", "cam", ".", "x", ":", "0", ")", "+", "@img", "[", "0", "]", ".", "width", "*", "scale_x", "*", "0.5", ",", "@y", "-", "(", "map", "?", "map", ".", "cam", ".", "y", ":", "0", ")", "+", "@img", "[", "0", "]", ".", "height", "*", "scale_y", "*", "0.5", ",", "z_index", ",", "angle", ",", "0.5", ",", "0.5", ",", "(", "flip", "==", ":horiz", "?", "-", "scale_x", ":", "scale_x", ")", ",", "(", "flip", "==", ":vert", "?", "-", "scale_y", ":", "scale_y", ")", ",", "color", "else", "x", "=", "@x", "-", "(", "map", "?", "map", ".", "cam", ".", "x", ":", "0", ")", "+", "(", "flip", "==", ":horiz", "?", "scale_x", "*", "@img", "[", "0", "]", ".", "width", ":", "0", ")", "y", "=", "@y", "-", "(", "map", "?", "map", ".", "cam", ".", "y", ":", "0", ")", "+", "(", "flip", "==", ":vert", "?", "scale_y", "*", "@img", "[", "0", "]", ".", "height", ":", "0", ")", "@img", "[", "@img_index", "]", ".", "draw", "(", "round", "?", "x", ".", "round", ":", "x", ")", ",", "(", "round", "?", "y", ".", "round", ":", "y", ")", ",", "z_index", ",", "(", "flip", "==", ":horiz", "?", "-", "scale_x", ":", "scale_x", ")", ",", "(", "flip", "==", ":vert", "?", "-", "scale_y", ":", "scale_y", ")", ",", "color", "end", "end"], "docstring": "Draws the sprite in the screen\n\n Parameters:\n [map] A Map object, relative to which the sprite will be drawn (the x\n and y coordinates of the sprite will be changed according to the\n position of the camera).\n [scale_x] A scale factor to be applied horizontally to the image.\n [scale_y] A scale factor to be applied vertically to the image.\n [alpha] The opacity with which the image will be drawn. Valid values\n vary from 0 (fully transparent) to 255 (fully opaque).\n [color] A color filter to apply to the image. A white (0xffffff) filter\n will keep all colors unchanged, while a black (0x000000) filter\n will turn all colors to black. A red (0xff0000) filter will keep\n reddish colors with slight or no change, whereas bluish colors\n will be darkened, for example.\n [angle] A rotation, in degrees, to be applied to the image, relative to\n its center.\n [flip] Specify +:horiz+ to draw the image horizontally flipped or +:vert+\n to draw it vertically flipped.\n [z_index] The z-order to draw the object. Objects with larger z-orders\n will be drawn on top of the ones with smaller z-orders.\n [round] Specify whether the drawing coordinates should be rounded to an\n integer before drawing, to avoid little distortions of the image.\n Only applies when the image is not rotated.\n\n *Obs.:* This method accepts named parameters.", "docstring_tokens": ["Draws", "the", "sprite", "in", "the", "screen"], "sha": "a7117a566141cd922a4fd90ab71ba63ed8a92080", "url": "https://github.com/victords/minigl/blob/a7117a566141cd922a4fd90ab71ba63ed8a92080/lib/minigl/game_object.rb#L147-L173", "partition": "test"} {"repo": "victords/minigl", "path": "lib/minigl/forms.rb", "func_name": "MiniGL.Button.update", "original_string": "def update\n return unless @enabled and @visible\n\n mouse_over = Mouse.over? @x, @y, @w, @h\n mouse_press = Mouse.button_pressed? :left\n mouse_rel = Mouse.button_released? :left\n\n if @state == :up\n if mouse_over\n @img_index = 1\n @state = :over\n else\n @img_index = 0\n end\n elsif @state == :over\n if not mouse_over\n @img_index = 0\n @state = :up\n elsif mouse_press\n @img_index = 2\n @state = :down\n else\n @img_index = 1\n end\n elsif @state == :down\n if not mouse_over\n @img_index = 0\n @state = :down_out\n elsif mouse_rel\n @img_index = 1\n @state = :over\n click\n else\n @img_index = 2\n end\n else # :down_out\n if mouse_over\n @img_index = 2\n @state = :down\n elsif mouse_rel\n @img_index = 0\n @state = :up\n else\n @img_index = 0\n end\n end\n end", "language": "ruby", "code": "def update\n return unless @enabled and @visible\n\n mouse_over = Mouse.over? @x, @y, @w, @h\n mouse_press = Mouse.button_pressed? :left\n mouse_rel = Mouse.button_released? :left\n\n if @state == :up\n if mouse_over\n @img_index = 1\n @state = :over\n else\n @img_index = 0\n end\n elsif @state == :over\n if not mouse_over\n @img_index = 0\n @state = :up\n elsif mouse_press\n @img_index = 2\n @state = :down\n else\n @img_index = 1\n end\n elsif @state == :down\n if not mouse_over\n @img_index = 0\n @state = :down_out\n elsif mouse_rel\n @img_index = 1\n @state = :over\n click\n else\n @img_index = 2\n end\n else # :down_out\n if mouse_over\n @img_index = 2\n @state = :down\n elsif mouse_rel\n @img_index = 0\n @state = :up\n else\n @img_index = 0\n end\n end\n end", "code_tokens": ["def", "update", "return", "unless", "@enabled", "and", "@visible", "mouse_over", "=", "Mouse", ".", "over?", "@x", ",", "@y", ",", "@w", ",", "@h", "mouse_press", "=", "Mouse", ".", "button_pressed?", ":left", "mouse_rel", "=", "Mouse", ".", "button_released?", ":left", "if", "@state", "==", ":up", "if", "mouse_over", "@img_index", "=", "1", "@state", "=", ":over", "else", "@img_index", "=", "0", "end", "elsif", "@state", "==", ":over", "if", "not", "mouse_over", "@img_index", "=", "0", "@state", "=", ":up", "elsif", "mouse_press", "@img_index", "=", "2", "@state", "=", ":down", "else", "@img_index", "=", "1", "end", "elsif", "@state", "==", ":down", "if", "not", "mouse_over", "@img_index", "=", "0", "@state", "=", ":down_out", "elsif", "mouse_rel", "@img_index", "=", "1", "@state", "=", ":over", "click", "else", "@img_index", "=", "2", "end", "else", "# :down_out", "if", "mouse_over", "@img_index", "=", "2", "@state", "=", ":down", "elsif", "mouse_rel", "@img_index", "=", "0", "@state", "=", ":up", "else", "@img_index", "=", "0", "end", "end", "end"], "docstring": "Creates a button.\n\n Parameters:\n [x] The x-coordinate where the button will be drawn in the screen.\n [y] The y-coordinate where the button will be drawn in the screen.\n [font] The Gosu::Font object that will be used to draw the\n button text.\n [text] The button text. Can be +nil+ or empty.\n [img] A spritesheet containing four images in a column, representing,\n from top to bottom, the default state, the hover state (when the\n mouse is over the button), the pressed state (when the mouse\n button is down and the cursor is over the button) and the disabled\n state. If +nil+, the +width+ and +height+ parameters must be\n provided.\n [text_color] Color of the button text, in hexadecimal RRGGBB format.\n [disabled_text_color] Color of the button text, when it's disabled, in\n hexadecimal RRGGBB format.\n [over_text_color] Color of the button text, when the cursor is over it\n (hexadecimal RRGGBB).\n [down_text_color] Color of the button text, when it is pressed\n (hexadecimal RRGGBB).\n [center_x] Whether the button text should be horizontally centered in its\n area (the area is defined by the image size, if an image is\n given, or by the +width+ and +height+ parameters, otherwise).\n [center_y] Whether the button text should be vertically centered in its\n area (the area is defined by the image size, if an image is\n given, or by the +width+ and +height+ parameters, otherwise).\n [margin_x] The x offset, from the button x-coordinate, to draw the text.\n This parameter is used only if +center+ is false.\n [margin_y] The y offset, from the button y-coordinate, to draw the text.\n This parameter is used only if +center+ is false.\n [width] Width of the button clickable area. This parameter is used only\n if +img+ is +nil+.\n [height] Height of the button clickable area. This parameter is used\n only if +img+ is +nil+.\n [params] An object containing any parameters you want passed to the\n +action+ block. When the button is clicked, the following is\n called:\n @action.call @params\n Note that this doesn't force you to declare a block that takes\n parameters.\n [retro] Whether the image should be loaded with the 'retro' option set\n (see +Gosu::Image+ for details). If the value is omitted, the\n +Res.retro_images+ value will be used.\n [scale_x] Horizontal scale to draw the component with.\n [scale_y] Vertical scale to draw the component with.\n [anchor] See parameter with the same name in Panel#initialize for details.\n [action] The block of code executed when the button is clicked (or by\n calling the +click+ method).\n\n *Obs.:* This method accepts named parameters, but +x+ and +y+ are\n mandatory (also, +img+ is mandatory when +width+ and +height+ are not\n provided, and vice-versa).\n Updates the button, checking the mouse movement and buttons to define\n the button state.", "docstring_tokens": ["Creates", "a", "button", "."], "sha": "a7117a566141cd922a4fd90ab71ba63ed8a92080", "url": "https://github.com/victords/minigl/blob/a7117a566141cd922a4fd90ab71ba63ed8a92080/lib/minigl/forms.rb#L326-L372", "partition": "test"} {"repo": "victords/minigl", "path": "lib/minigl/forms.rb", "func_name": "MiniGL.Button.draw", "original_string": "def draw(alpha = 0xff, z_index = 0, color = 0xffffff)\n return unless @visible\n\n color = (alpha << 24) | color\n text_color =\n if @enabled\n if @state == :down\n @down_text_color\n else\n @state == :over ? @over_text_color : @text_color\n end\n else\n @disabled_text_color\n end\n text_color = (alpha << 24) | text_color\n @img[@img_index].draw @x, @y, z_index, @scale_x, @scale_y, color if @img\n if @text\n if @center_x or @center_y\n rel_x = @center_x ? 0.5 : 0\n rel_y = @center_y ? 0.5 : 0\n @font.draw_text_rel @text, @text_x, @text_y, z_index, rel_x, rel_y, @scale_x, @scale_y, text_color\n else\n @font.draw_text @text, @text_x, @text_y, z_index, @scale_x, @scale_y, text_color\n end\n end\n end", "language": "ruby", "code": "def draw(alpha = 0xff, z_index = 0, color = 0xffffff)\n return unless @visible\n\n color = (alpha << 24) | color\n text_color =\n if @enabled\n if @state == :down\n @down_text_color\n else\n @state == :over ? @over_text_color : @text_color\n end\n else\n @disabled_text_color\n end\n text_color = (alpha << 24) | text_color\n @img[@img_index].draw @x, @y, z_index, @scale_x, @scale_y, color if @img\n if @text\n if @center_x or @center_y\n rel_x = @center_x ? 0.5 : 0\n rel_y = @center_y ? 0.5 : 0\n @font.draw_text_rel @text, @text_x, @text_y, z_index, rel_x, rel_y, @scale_x, @scale_y, text_color\n else\n @font.draw_text @text, @text_x, @text_y, z_index, @scale_x, @scale_y, text_color\n end\n end\n end", "code_tokens": ["def", "draw", "(", "alpha", "=", "0xff", ",", "z_index", "=", "0", ",", "color", "=", "0xffffff", ")", "return", "unless", "@visible", "color", "=", "(", "alpha", "<<", "24", ")", "|", "color", "text_color", "=", "if", "@enabled", "if", "@state", "==", ":down", "@down_text_color", "else", "@state", "==", ":over", "?", "@over_text_color", ":", "@text_color", "end", "else", "@disabled_text_color", "end", "text_color", "=", "(", "alpha", "<<", "24", ")", "|", "text_color", "@img", "[", "@img_index", "]", ".", "draw", "@x", ",", "@y", ",", "z_index", ",", "@scale_x", ",", "@scale_y", ",", "color", "if", "@img", "if", "@text", "if", "@center_x", "or", "@center_y", "rel_x", "=", "@center_x", "?", "0.5", ":", "0", "rel_y", "=", "@center_y", "?", "0.5", ":", "0", "@font", ".", "draw_text_rel", "@text", ",", "@text_x", ",", "@text_y", ",", "z_index", ",", "rel_x", ",", "rel_y", ",", "@scale_x", ",", "@scale_y", ",", "text_color", "else", "@font", ".", "draw_text", "@text", ",", "@text_x", ",", "@text_y", ",", "z_index", ",", "@scale_x", ",", "@scale_y", ",", "text_color", "end", "end", "end"], "docstring": "Draws the button in the screen.\n\n Parameters:\n [alpha] The opacity with which the button will be drawn. Allowed values\n vary between 0 (fully transparent) and 255 (fully opaque).\n [z_index] The z-order to draw the object. Objects with larger z-orders\n will be drawn on top of the ones with smaller z-orders.\n [color] Color to apply a filter to the image.", "docstring_tokens": ["Draws", "the", "button", "in", "the", "screen", "."], "sha": "a7117a566141cd922a4fd90ab71ba63ed8a92080", "url": "https://github.com/victords/minigl/blob/a7117a566141cd922a4fd90ab71ba63ed8a92080/lib/minigl/forms.rb#L400-L425", "partition": "test"} {"repo": "victords/minigl", "path": "lib/minigl/forms.rb", "func_name": "MiniGL.TextField.text=", "original_string": "def text=(value, trigger_changed = true)\n @text = value[0...@max_length]\n @nodes.clear; @nodes << @text_x\n x = @nodes[0]\n @text.chars.each { |char|\n x += @font.text_width(char) * @scale_x\n @nodes << x\n }\n @cur_node = @nodes.size - 1\n @anchor1 = nil\n @anchor2 = nil\n set_cursor_visible\n @on_text_changed.call @text, @params if trigger_changed && @on_text_changed\n end", "language": "ruby", "code": "def text=(value, trigger_changed = true)\n @text = value[0...@max_length]\n @nodes.clear; @nodes << @text_x\n x = @nodes[0]\n @text.chars.each { |char|\n x += @font.text_width(char) * @scale_x\n @nodes << x\n }\n @cur_node = @nodes.size - 1\n @anchor1 = nil\n @anchor2 = nil\n set_cursor_visible\n @on_text_changed.call @text, @params if trigger_changed && @on_text_changed\n end", "code_tokens": ["def", "text", "=", "(", "value", ",", "trigger_changed", "=", "true", ")", "@text", "=", "value", "[", "0", "...", "@max_length", "]", "@nodes", ".", "clear", ";", "@nodes", "<<", "@text_x", "x", "=", "@nodes", "[", "0", "]", "@text", ".", "chars", ".", "each", "{", "|", "char", "|", "x", "+=", "@font", ".", "text_width", "(", "char", ")", "*", "@scale_x", "@nodes", "<<", "x", "}", "@cur_node", "=", "@nodes", ".", "size", "-", "1", "@anchor1", "=", "nil", "@anchor2", "=", "nil", "set_cursor_visible", "@on_text_changed", ".", "call", "@text", ",", "@params", "if", "trigger_changed", "&&", "@on_text_changed", "end"], "docstring": "Sets the text of the text field to the specified value.\n\n Parameters:\n [value] The new text to be set. If it's longer than the +max_length+\n parameter used in the constructor, it will be truncated to\n +max_length+ characters.", "docstring_tokens": ["Sets", "the", "text", "of", "the", "text", "field", "to", "the", "specified", "value", "."], "sha": "a7117a566141cd922a4fd90ab71ba63ed8a92080", "url": "https://github.com/victords/minigl/blob/a7117a566141cd922a4fd90ab71ba63ed8a92080/lib/minigl/forms.rb#L858-L871", "partition": "test"} {"repo": "victords/minigl", "path": "lib/minigl/forms.rb", "func_name": "MiniGL.TextField.set_position", "original_string": "def set_position(x, y)\n d_x = x - @x\n d_y = y - @y\n @x = x; @y = y\n @text_x += d_x\n @text_y += d_y\n @nodes.map! do |n|\n n + d_x\n end\n end", "language": "ruby", "code": "def set_position(x, y)\n d_x = x - @x\n d_y = y - @y\n @x = x; @y = y\n @text_x += d_x\n @text_y += d_y\n @nodes.map! do |n|\n n + d_x\n end\n end", "code_tokens": ["def", "set_position", "(", "x", ",", "y", ")", "d_x", "=", "x", "-", "@x", "d_y", "=", "y", "-", "@y", "@x", "=", "x", ";", "@y", "=", "y", "@text_x", "+=", "d_x", "@text_y", "+=", "d_y", "@nodes", ".", "map!", "do", "|", "n", "|", "n", "+", "d_x", "end", "end"], "docstring": "Sets the position of the text field in the screen.\n\n Parameters:\n [x] The new x-coordinate for the text field.\n [y] The new y-coordinate for the text field.", "docstring_tokens": ["Sets", "the", "position", "of", "the", "text", "field", "in", "the", "screen", "."], "sha": "a7117a566141cd922a4fd90ab71ba63ed8a92080", "url": "https://github.com/victords/minigl/blob/a7117a566141cd922a4fd90ab71ba63ed8a92080/lib/minigl/forms.rb#L919-L928", "partition": "test"} {"repo": "victords/minigl", "path": "lib/minigl/forms.rb", "func_name": "MiniGL.TextField.draw", "original_string": "def draw(alpha = 0xff, z_index = 0, color = 0xffffff, disabled_color = 0x808080)\n return unless @visible\n\n color = (alpha << 24) | ((@enabled or @disabled_img) ? color : disabled_color)\n text_color = (alpha << 24) | (@enabled ? @text_color : @disabled_text_color)\n img = ((@enabled or @disabled_img.nil?) ? @img : @disabled_img)\n img.draw @x, @y, z_index, @scale_x, @scale_y, color\n @font.draw_text @text, @text_x, @text_y, z_index, @scale_x, @scale_y, text_color\n\n if @anchor1 and @anchor2\n selection_color = ((alpha / 2) << 24) | @selection_color\n G.window.draw_quad @nodes[@anchor1], @text_y, selection_color,\n @nodes[@anchor2] + 1, @text_y, selection_color,\n @nodes[@anchor2] + 1, @text_y + @font.height * @scale_y, selection_color,\n @nodes[@anchor1], @text_y + @font.height * @scale_y, selection_color, z_index\n end\n\n if @cursor_visible\n if @cursor_img\n @cursor_img.draw @nodes[@cur_node] - (@cursor_img.width * @scale_x) / 2, @text_y, z_index, @scale_x, @scale_y\n else\n cursor_color = alpha << 24\n G.window.draw_quad @nodes[@cur_node], @text_y, cursor_color,\n @nodes[@cur_node] + 1, @text_y, cursor_color,\n @nodes[@cur_node] + 1, @text_y + @font.height * @scale_y, cursor_color,\n @nodes[@cur_node], @text_y + @font.height * @scale_y, cursor_color, z_index\n end\n end\n end", "language": "ruby", "code": "def draw(alpha = 0xff, z_index = 0, color = 0xffffff, disabled_color = 0x808080)\n return unless @visible\n\n color = (alpha << 24) | ((@enabled or @disabled_img) ? color : disabled_color)\n text_color = (alpha << 24) | (@enabled ? @text_color : @disabled_text_color)\n img = ((@enabled or @disabled_img.nil?) ? @img : @disabled_img)\n img.draw @x, @y, z_index, @scale_x, @scale_y, color\n @font.draw_text @text, @text_x, @text_y, z_index, @scale_x, @scale_y, text_color\n\n if @anchor1 and @anchor2\n selection_color = ((alpha / 2) << 24) | @selection_color\n G.window.draw_quad @nodes[@anchor1], @text_y, selection_color,\n @nodes[@anchor2] + 1, @text_y, selection_color,\n @nodes[@anchor2] + 1, @text_y + @font.height * @scale_y, selection_color,\n @nodes[@anchor1], @text_y + @font.height * @scale_y, selection_color, z_index\n end\n\n if @cursor_visible\n if @cursor_img\n @cursor_img.draw @nodes[@cur_node] - (@cursor_img.width * @scale_x) / 2, @text_y, z_index, @scale_x, @scale_y\n else\n cursor_color = alpha << 24\n G.window.draw_quad @nodes[@cur_node], @text_y, cursor_color,\n @nodes[@cur_node] + 1, @text_y, cursor_color,\n @nodes[@cur_node] + 1, @text_y + @font.height * @scale_y, cursor_color,\n @nodes[@cur_node], @text_y + @font.height * @scale_y, cursor_color, z_index\n end\n end\n end", "code_tokens": ["def", "draw", "(", "alpha", "=", "0xff", ",", "z_index", "=", "0", ",", "color", "=", "0xffffff", ",", "disabled_color", "=", "0x808080", ")", "return", "unless", "@visible", "color", "=", "(", "alpha", "<<", "24", ")", "|", "(", "(", "@enabled", "or", "@disabled_img", ")", "?", "color", ":", "disabled_color", ")", "text_color", "=", "(", "alpha", "<<", "24", ")", "|", "(", "@enabled", "?", "@text_color", ":", "@disabled_text_color", ")", "img", "=", "(", "(", "@enabled", "or", "@disabled_img", ".", "nil?", ")", "?", "@img", ":", "@disabled_img", ")", "img", ".", "draw", "@x", ",", "@y", ",", "z_index", ",", "@scale_x", ",", "@scale_y", ",", "color", "@font", ".", "draw_text", "@text", ",", "@text_x", ",", "@text_y", ",", "z_index", ",", "@scale_x", ",", "@scale_y", ",", "text_color", "if", "@anchor1", "and", "@anchor2", "selection_color", "=", "(", "(", "alpha", "/", "2", ")", "<<", "24", ")", "|", "@selection_color", "G", ".", "window", ".", "draw_quad", "@nodes", "[", "@anchor1", "]", ",", "@text_y", ",", "selection_color", ",", "@nodes", "[", "@anchor2", "]", "+", "1", ",", "@text_y", ",", "selection_color", ",", "@nodes", "[", "@anchor2", "]", "+", "1", ",", "@text_y", "+", "@font", ".", "height", "*", "@scale_y", ",", "selection_color", ",", "@nodes", "[", "@anchor1", "]", ",", "@text_y", "+", "@font", ".", "height", "*", "@scale_y", ",", "selection_color", ",", "z_index", "end", "if", "@cursor_visible", "if", "@cursor_img", "@cursor_img", ".", "draw", "@nodes", "[", "@cur_node", "]", "-", "(", "@cursor_img", ".", "width", "*", "@scale_x", ")", "/", "2", ",", "@text_y", ",", "z_index", ",", "@scale_x", ",", "@scale_y", "else", "cursor_color", "=", "alpha", "<<", "24", "G", ".", "window", ".", "draw_quad", "@nodes", "[", "@cur_node", "]", ",", "@text_y", ",", "cursor_color", ",", "@nodes", "[", "@cur_node", "]", "+", "1", ",", "@text_y", ",", "cursor_color", ",", "@nodes", "[", "@cur_node", "]", "+", "1", ",", "@text_y", "+", "@font", ".", "height", "*", "@scale_y", ",", "cursor_color", ",", "@nodes", "[", "@cur_node", "]", ",", "@text_y", "+", "@font", ".", "height", "*", "@scale_y", ",", "cursor_color", ",", "z_index", "end", "end", "end"], "docstring": "Draws the text field in the screen.\n\n Parameters:\n [alpha] The opacity with which the text field will be drawn. Allowed\n values vary between 0 (fully transparent) and 255 (fully opaque).\n [z_index] The z-order to draw the object. Objects with larger z-orders\n will be drawn on top of the ones with smaller z-orders.\n [color] Color to apply a filter to the image.\n [disabled_color] Color to apply a filter to the image when the field is\n disabled.", "docstring_tokens": ["Draws", "the", "text", "field", "in", "the", "screen", "."], "sha": "a7117a566141cd922a4fd90ab71ba63ed8a92080", "url": "https://github.com/victords/minigl/blob/a7117a566141cd922a4fd90ab71ba63ed8a92080/lib/minigl/forms.rb#L940-L968", "partition": "test"} {"repo": "victords/minigl", "path": "lib/minigl/forms.rb", "func_name": "MiniGL.ProgressBar.draw", "original_string": "def draw(alpha = 0xff, z_index = 0, color = 0xffffff)\n return unless @visible\n\n if @bg\n c = (alpha << 24) | color\n @bg.draw @x, @y, z_index, @scale_x, @scale_y, c\n else\n c = (alpha << 24) | @bg_color\n G.window.draw_quad @x, @y, c,\n @x + @w, @y, c,\n @x + @w, @y + @h, c,\n @x, @y + @h, c, z_index\n end\n if @fg\n c = (alpha << 24) | color\n w1 = @fg.width * @scale_x\n w2 = (@value.to_f / @max_value * @w).round\n x0 = @x + @fg_margin_x\n x = 0\n while x <= w2 - w1\n @fg.draw x0 + x, @y + @fg_margin_y, z_index, @scale_x, @scale_y, c\n x += w1\n end\n if w2 - x > 0\n img = Gosu::Image.new(@fg_path, tileable: true, retro: @retro, rect: [0, 0, ((w2 - x) / @scale_x).round, @fg.height])\n img.draw x0 + x, @y + @fg_margin_y, z_index, @scale_x, @scale_y, c\n end\n else\n c = (alpha << 24) | @fg_color\n rect_r = @x + (@value.to_f / @max_value * @w).round\n G.window.draw_quad @x, @y, c,\n rect_r, @y, c,\n rect_r, @y + @h, c,\n @x, @y + @h, c, z_index\n end\n if @font\n c = (alpha << 24) | @text_color\n @text = @format == '%' ? \"#{(@value.to_f / @max_value * 100).round}%\" : \"#{@value}/#{@max_value}\"\n @font.draw_text_rel @text, @x + @w / 2, @y + @h / 2, z_index, 0.5, 0.5, @scale_x, @scale_y, c\n end\n end", "language": "ruby", "code": "def draw(alpha = 0xff, z_index = 0, color = 0xffffff)\n return unless @visible\n\n if @bg\n c = (alpha << 24) | color\n @bg.draw @x, @y, z_index, @scale_x, @scale_y, c\n else\n c = (alpha << 24) | @bg_color\n G.window.draw_quad @x, @y, c,\n @x + @w, @y, c,\n @x + @w, @y + @h, c,\n @x, @y + @h, c, z_index\n end\n if @fg\n c = (alpha << 24) | color\n w1 = @fg.width * @scale_x\n w2 = (@value.to_f / @max_value * @w).round\n x0 = @x + @fg_margin_x\n x = 0\n while x <= w2 - w1\n @fg.draw x0 + x, @y + @fg_margin_y, z_index, @scale_x, @scale_y, c\n x += w1\n end\n if w2 - x > 0\n img = Gosu::Image.new(@fg_path, tileable: true, retro: @retro, rect: [0, 0, ((w2 - x) / @scale_x).round, @fg.height])\n img.draw x0 + x, @y + @fg_margin_y, z_index, @scale_x, @scale_y, c\n end\n else\n c = (alpha << 24) | @fg_color\n rect_r = @x + (@value.to_f / @max_value * @w).round\n G.window.draw_quad @x, @y, c,\n rect_r, @y, c,\n rect_r, @y + @h, c,\n @x, @y + @h, c, z_index\n end\n if @font\n c = (alpha << 24) | @text_color\n @text = @format == '%' ? \"#{(@value.to_f / @max_value * 100).round}%\" : \"#{@value}/#{@max_value}\"\n @font.draw_text_rel @text, @x + @w / 2, @y + @h / 2, z_index, 0.5, 0.5, @scale_x, @scale_y, c\n end\n end", "code_tokens": ["def", "draw", "(", "alpha", "=", "0xff", ",", "z_index", "=", "0", ",", "color", "=", "0xffffff", ")", "return", "unless", "@visible", "if", "@bg", "c", "=", "(", "alpha", "<<", "24", ")", "|", "color", "@bg", ".", "draw", "@x", ",", "@y", ",", "z_index", ",", "@scale_x", ",", "@scale_y", ",", "c", "else", "c", "=", "(", "alpha", "<<", "24", ")", "|", "@bg_color", "G", ".", "window", ".", "draw_quad", "@x", ",", "@y", ",", "c", ",", "@x", "+", "@w", ",", "@y", ",", "c", ",", "@x", "+", "@w", ",", "@y", "+", "@h", ",", "c", ",", "@x", ",", "@y", "+", "@h", ",", "c", ",", "z_index", "end", "if", "@fg", "c", "=", "(", "alpha", "<<", "24", ")", "|", "color", "w1", "=", "@fg", ".", "width", "*", "@scale_x", "w2", "=", "(", "@value", ".", "to_f", "/", "@max_value", "*", "@w", ")", ".", "round", "x0", "=", "@x", "+", "@fg_margin_x", "x", "=", "0", "while", "x", "<=", "w2", "-", "w1", "@fg", ".", "draw", "x0", "+", "x", ",", "@y", "+", "@fg_margin_y", ",", "z_index", ",", "@scale_x", ",", "@scale_y", ",", "c", "x", "+=", "w1", "end", "if", "w2", "-", "x", ">", "0", "img", "=", "Gosu", "::", "Image", ".", "new", "(", "@fg_path", ",", "tileable", ":", "true", ",", "retro", ":", "@retro", ",", "rect", ":", "[", "0", ",", "0", ",", "(", "(", "w2", "-", "x", ")", "/", "@scale_x", ")", ".", "round", ",", "@fg", ".", "height", "]", ")", "img", ".", "draw", "x0", "+", "x", ",", "@y", "+", "@fg_margin_y", ",", "z_index", ",", "@scale_x", ",", "@scale_y", ",", "c", "end", "else", "c", "=", "(", "alpha", "<<", "24", ")", "|", "@fg_color", "rect_r", "=", "@x", "+", "(", "@value", ".", "to_f", "/", "@max_value", "*", "@w", ")", ".", "round", "G", ".", "window", ".", "draw_quad", "@x", ",", "@y", ",", "c", ",", "rect_r", ",", "@y", ",", "c", ",", "rect_r", ",", "@y", "+", "@h", ",", "c", ",", "@x", ",", "@y", "+", "@h", ",", "c", ",", "z_index", "end", "if", "@font", "c", "=", "(", "alpha", "<<", "24", ")", "|", "@text_color", "@text", "=", "@format", "==", "'%'", "?", "\"#{(@value.to_f / @max_value * 100).round}%\"", ":", "\"#{@value}/#{@max_value}\"", "@font", ".", "draw_text_rel", "@text", ",", "@x", "+", "@w", "/", "2", ",", "@y", "+", "@h", "/", "2", ",", "z_index", ",", "0.5", ",", "0.5", ",", "@scale_x", ",", "@scale_y", ",", "c", "end", "end"], "docstring": "Draws the progress bar.\n\n Parameters:\n [alpha] (+Fixnum+) The opacity with which the progress bar will be drawn.\n Allowed values vary between 0 (fully transparent) and 255 (fully\n opaque).\n [z_index] (+Fixnum+) The z-order to draw the object. Objects with larger\n z-orders will be drawn on top of the ones with smaller z-orders.\n [color] Color to apply a filter to the images (when these are provided).", "docstring_tokens": ["Draws", "the", "progress", "bar", "."], "sha": "a7117a566141cd922a4fd90ab71ba63ed8a92080", "url": "https://github.com/victords/minigl/blob/a7117a566141cd922a4fd90ab71ba63ed8a92080/lib/minigl/forms.rb#L1201-L1241", "partition": "test"} {"repo": "victords/minigl", "path": "lib/minigl/forms.rb", "func_name": "MiniGL.DropDownList.update", "original_string": "def update\n return unless @enabled and @visible\n if @open and Mouse.button_pressed? :left and not Mouse.over?(@x, @y, @w, @max_h)\n toggle\n return\n end\n @buttons.each { |b| b.update }\n end", "language": "ruby", "code": "def update\n return unless @enabled and @visible\n if @open and Mouse.button_pressed? :left and not Mouse.over?(@x, @y, @w, @max_h)\n toggle\n return\n end\n @buttons.each { |b| b.update }\n end", "code_tokens": ["def", "update", "return", "unless", "@enabled", "and", "@visible", "if", "@open", "and", "Mouse", ".", "button_pressed?", ":left", "and", "not", "Mouse", ".", "over?", "(", "@x", ",", "@y", ",", "@w", ",", "@max_h", ")", "toggle", "return", "end", "@buttons", ".", "each", "{", "|", "b", "|", "b", ".", "update", "}", "end"], "docstring": "Creates a new drop-down list.\n\n Parameters:\n [x] The x-coordinate of the object.\n [y] The y-coordinate of the object.\n [font] Font to be used by the buttons that compose the drop-down list.\n [img] Image of the main button, i.e., the one at the top, that toggles\n visibility of the other buttons (the \"option\" buttons).\n [opt_img] Image for the \"option\" buttons, as described above.\n [options] Array of available options for this control (+String+s).\n [option] Index of the firstly selected option.\n [text_margin] Left margin of the text inside the buttons (vertically, the\n text will always be centered).\n [width] Width of the control, used when no image is provided.\n [height] Height of the control, used when no image is provided.\n [text_color] Used as the +text_color+ parameter in the constructor of the\n buttons.\n [disabled_text_color] Analogous to +text_color+.\n [over_text_color] Same as above.\n [down_text_color] Same as above.\n [retro] Whether the images should be loaded with the 'retro' option set\n (see +Gosu::Image+ for details). If the value is omitted, the\n +Res.retro_images+ value will be used.\n [scale_x] Horizontal scale to draw the component with.\n [scale_y] Vertical scale to draw the component with.\n [anchor] See parameter with the same name in Panel#initialize for details.\n [on_changed] Action performed when the value of the dropdown is changed.\n It must be a block with two parameters, which will receive\n the old and the new value, respectively.\n\n *Obs.:* This method accepts named parameters, but +x+, +y+, +font+ and\n +options+ are mandatory (also, +img+ and +opt_img+ are mandatory when\n +width+ and +height+ are not provided, and vice-versa).\n Updates the control.", "docstring_tokens": ["Creates", "a", "new", "drop", "-", "down", "list", "."], "sha": "a7117a566141cd922a4fd90ab71ba63ed8a92080", "url": "https://github.com/victords/minigl/blob/a7117a566141cd922a4fd90ab71ba63ed8a92080/lib/minigl/forms.rb#L1351-L1358", "partition": "test"} {"repo": "victords/minigl", "path": "lib/minigl/forms.rb", "func_name": "MiniGL.DropDownList.value=", "original_string": "def value=(val)\n if @options.include? val\n old = @value\n @value = @buttons[0].text = val\n @on_changed.call(old, val) if @on_changed\n end\n end", "language": "ruby", "code": "def value=(val)\n if @options.include? val\n old = @value\n @value = @buttons[0].text = val\n @on_changed.call(old, val) if @on_changed\n end\n end", "code_tokens": ["def", "value", "=", "(", "val", ")", "if", "@options", ".", "include?", "val", "old", "=", "@value", "@value", "=", "@buttons", "[", "0", "]", ".", "text", "=", "val", "@on_changed", ".", "call", "(", "old", ",", "val", ")", "if", "@on_changed", "end", "end"], "docstring": "Sets the currently selected value of the drop-down list. It is ignored if\n it is not among the available options.", "docstring_tokens": ["Sets", "the", "currently", "selected", "value", "of", "the", "drop", "-", "down", "list", ".", "It", "is", "ignored", "if", "it", "is", "not", "among", "the", "available", "options", "."], "sha": "a7117a566141cd922a4fd90ab71ba63ed8a92080", "url": "https://github.com/victords/minigl/blob/a7117a566141cd922a4fd90ab71ba63ed8a92080/lib/minigl/forms.rb#L1362-L1368", "partition": "test"} {"repo": "victords/minigl", "path": "lib/minigl/forms.rb", "func_name": "MiniGL.DropDownList.draw", "original_string": "def draw(alpha = 0xff, z_index = 0, color = 0xffffff, over_color = 0xcccccc)\n return unless @visible\n unless @img\n bottom = @y + (@open ? @max_h : @h) + @scale_y\n b_color = (alpha << 24)\n G.window.draw_quad @x - @scale_x, @y - @scale_y, b_color,\n @x + @w + @scale_x, @y - @scale_y, b_color,\n @x + @w + @scale_x, bottom, b_color,\n @x - @scale_x, bottom, b_color, z_index\n @buttons.each do |b|\n c = (alpha << 24) | (b.state == :over ? over_color : color)\n G.window.draw_quad b.x, b.y, c,\n b.x + b.w, b.y, c,\n b.x + b.w, b.y + b.h, c,\n b.x, b.y + b.h, c, z_index + 1 if b.visible\n end\n end\n @buttons[0].draw(alpha, z_index, color)\n @buttons[1..-1].each { |b| b.draw alpha, z_index + 1, color }\n end", "language": "ruby", "code": "def draw(alpha = 0xff, z_index = 0, color = 0xffffff, over_color = 0xcccccc)\n return unless @visible\n unless @img\n bottom = @y + (@open ? @max_h : @h) + @scale_y\n b_color = (alpha << 24)\n G.window.draw_quad @x - @scale_x, @y - @scale_y, b_color,\n @x + @w + @scale_x, @y - @scale_y, b_color,\n @x + @w + @scale_x, bottom, b_color,\n @x - @scale_x, bottom, b_color, z_index\n @buttons.each do |b|\n c = (alpha << 24) | (b.state == :over ? over_color : color)\n G.window.draw_quad b.x, b.y, c,\n b.x + b.w, b.y, c,\n b.x + b.w, b.y + b.h, c,\n b.x, b.y + b.h, c, z_index + 1 if b.visible\n end\n end\n @buttons[0].draw(alpha, z_index, color)\n @buttons[1..-1].each { |b| b.draw alpha, z_index + 1, color }\n end", "code_tokens": ["def", "draw", "(", "alpha", "=", "0xff", ",", "z_index", "=", "0", ",", "color", "=", "0xffffff", ",", "over_color", "=", "0xcccccc", ")", "return", "unless", "@visible", "unless", "@img", "bottom", "=", "@y", "+", "(", "@open", "?", "@max_h", ":", "@h", ")", "+", "@scale_y", "b_color", "=", "(", "alpha", "<<", "24", ")", "G", ".", "window", ".", "draw_quad", "@x", "-", "@scale_x", ",", "@y", "-", "@scale_y", ",", "b_color", ",", "@x", "+", "@w", "+", "@scale_x", ",", "@y", "-", "@scale_y", ",", "b_color", ",", "@x", "+", "@w", "+", "@scale_x", ",", "bottom", ",", "b_color", ",", "@x", "-", "@scale_x", ",", "bottom", ",", "b_color", ",", "z_index", "@buttons", ".", "each", "do", "|", "b", "|", "c", "=", "(", "alpha", "<<", "24", ")", "|", "(", "b", ".", "state", "==", ":over", "?", "over_color", ":", "color", ")", "G", ".", "window", ".", "draw_quad", "b", ".", "x", ",", "b", ".", "y", ",", "c", ",", "b", ".", "x", "+", "b", ".", "w", ",", "b", ".", "y", ",", "c", ",", "b", ".", "x", "+", "b", ".", "w", ",", "b", ".", "y", "+", "b", ".", "h", ",", "c", ",", "b", ".", "x", ",", "b", ".", "y", "+", "b", ".", "h", ",", "c", ",", "z_index", "+", "1", "if", "b", ".", "visible", "end", "end", "@buttons", "[", "0", "]", ".", "draw", "(", "alpha", ",", "z_index", ",", "color", ")", "@buttons", "[", "1", "..", "-", "1", "]", ".", "each", "{", "|", "b", "|", "b", ".", "draw", "alpha", ",", "z_index", "+", "1", ",", "color", "}", "end"], "docstring": "Draws the drop-down list.\n\n Parameters:\n [alpha] (+Fixnum+) The opacity with which the drop-down list will be\n drawn. Allowed values vary between 0 (fully transparent) and 255\n (fully opaque).\n [z_index] (+Fixnum+) The z-order to draw the object. Objects with larger\n z-orders will be drawn on top of the ones with smaller z-orders.\n [color] Color of the buttons, if no image was provided, or color to apply\n a filter to the images.\n [over_color] Color of the buttons when the mouse is over them (when no\n image was provided).", "docstring_tokens": ["Draws", "the", "drop", "-", "down", "list", "."], "sha": "a7117a566141cd922a4fd90ab71ba63ed8a92080", "url": "https://github.com/victords/minigl/blob/a7117a566141cd922a4fd90ab71ba63ed8a92080/lib/minigl/forms.rb#L1393-L1412", "partition": "test"} {"repo": "victords/minigl", "path": "lib/minigl/forms.rb", "func_name": "MiniGL.Label.draw", "original_string": "def draw(alpha = 255, z_index = 0, color = 0xffffff)\n c = @enabled ? @text_color : @disabled_text_color\n r1 = c >> 16\n g1 = (c & 0xff00) >> 8\n b1 = (c & 0xff)\n r2 = color >> 16\n g2 = (color & 0xff00) >> 8\n b2 = (color & 0xff)\n r1 *= r2; r1 /= 255\n g1 *= g2; g1 /= 255\n b1 *= b2; b1 /= 255\n color = (alpha << 24) | (r1 << 16) | (g1 << 8) | b1\n @font.draw_text(@text, @x, @y, z_index, @scale_x, @scale_y, color)\n end", "language": "ruby", "code": "def draw(alpha = 255, z_index = 0, color = 0xffffff)\n c = @enabled ? @text_color : @disabled_text_color\n r1 = c >> 16\n g1 = (c & 0xff00) >> 8\n b1 = (c & 0xff)\n r2 = color >> 16\n g2 = (color & 0xff00) >> 8\n b2 = (color & 0xff)\n r1 *= r2; r1 /= 255\n g1 *= g2; g1 /= 255\n b1 *= b2; b1 /= 255\n color = (alpha << 24) | (r1 << 16) | (g1 << 8) | b1\n @font.draw_text(@text, @x, @y, z_index, @scale_x, @scale_y, color)\n end", "code_tokens": ["def", "draw", "(", "alpha", "=", "255", ",", "z_index", "=", "0", ",", "color", "=", "0xffffff", ")", "c", "=", "@enabled", "?", "@text_color", ":", "@disabled_text_color", "r1", "=", "c", ">>", "16", "g1", "=", "(", "c", "&", "0xff00", ")", ">>", "8", "b1", "=", "(", "c", "&", "0xff", ")", "r2", "=", "color", ">>", "16", "g2", "=", "(", "color", "&", "0xff00", ")", ">>", "8", "b2", "=", "(", "color", "&", "0xff", ")", "r1", "*=", "r2", ";", "r1", "/=", "255", "g1", "*=", "g2", ";", "g1", "/=", "255", "b1", "*=", "b2", ";", "b1", "/=", "255", "color", "=", "(", "alpha", "<<", "24", ")", "|", "(", "r1", "<<", "16", ")", "|", "(", "g1", "<<", "8", ")", "|", "b1", "@font", ".", "draw_text", "(", "@text", ",", "@x", ",", "@y", ",", "z_index", ",", "@scale_x", ",", "@scale_y", ",", "color", ")", "end"], "docstring": "Creates a new label.\n\n Parameters:\n [x] The x-coordinate of the label.\n [y] The x-coordinate of the label.\n [font] Font that will be used to draw the label's text.\n [text] The label's text.\n [text_color] The default text color.\n [disabled_text_color] The text color when the label is disabled.\n [scale_x] The horizontal scale factor.\n [scale_y] The vertical scale factor.\n [anchor] See parameter with the same name in Panel#initialize for details.\n Draws the label.\n\n Parameters:\n [alpha] The opacity with which the label will be drawn. Allowed values\n vary between 0 (fully transparent) and 255 (fully opaque).\n [z_index] The z-order to draw the object. Objects with larger z-orders\n will be drawn on top of the ones with smaller z-orders.\n [color] Color to apply a filter to the text.", "docstring_tokens": ["Creates", "a", "new", "label", "."], "sha": "a7117a566141cd922a4fd90ab71ba63ed8a92080", "url": "https://github.com/victords/minigl/blob/a7117a566141cd922a4fd90ab71ba63ed8a92080/lib/minigl/forms.rb#L1471-L1484", "partition": "test"} {"repo": "victords/minigl", "path": "lib/minigl/text.rb", "func_name": "MiniGL.TextHelper.write_line", "original_string": "def write_line(text, x = nil, y = nil, mode = :left, color = 0, alpha = 0xff,\n effect = nil, effect_color = 0, effect_size = 1, effect_alpha = 0xff,\n z_index = 0)\n if text.is_a? Hash\n x = text[:x]\n y = text[:y]\n mode = text.fetch(:mode, :left)\n color = text.fetch(:color, 0)\n alpha = text.fetch(:alpha, 0xff)\n effect = text.fetch(:effect, nil)\n effect_color = text.fetch(:effect_color, 0)\n effect_size = text.fetch(:effect_size, 1)\n effect_alpha = text.fetch(:effect_alpha, 0xff)\n z_index = text.fetch(:z_index, 0)\n text = text[:text]\n end\n\n color = (alpha << 24) | color\n rel =\n case mode\n when :left then 0\n when :center then 0.5\n when :right then 1\n else 0\n end\n if effect\n effect_color = (effect_alpha << 24) | effect_color\n if effect == :border\n @font.draw_markup_rel text, x - effect_size, y - effect_size, z_index, rel, 0, 1, 1, effect_color\n @font.draw_markup_rel text, x, y - effect_size, z_index, rel, 0, 1, 1, effect_color\n @font.draw_markup_rel text, x + effect_size, y - effect_size, z_index, rel, 0, 1, 1, effect_color\n @font.draw_markup_rel text, x + effect_size, y, z_index, rel, 0, 1, 1, effect_color\n @font.draw_markup_rel text, x + effect_size, y + effect_size, z_index, rel, 0, 1, 1, effect_color\n @font.draw_markup_rel text, x, y + effect_size, z_index, rel, 0, 1, 1, effect_color\n @font.draw_markup_rel text, x - effect_size, y + effect_size, z_index, rel, 0, 1, 1, effect_color\n @font.draw_markup_rel text, x - effect_size, y, z_index, rel, 0, 1, 1, effect_color\n elsif effect == :shadow\n @font.draw_markup_rel text, x + effect_size, y + effect_size, z_index, rel, 0, 1, 1, effect_color\n end\n end\n @font.draw_markup_rel text, x, y, z_index, rel, 0, 1, 1, color\n end", "language": "ruby", "code": "def write_line(text, x = nil, y = nil, mode = :left, color = 0, alpha = 0xff,\n effect = nil, effect_color = 0, effect_size = 1, effect_alpha = 0xff,\n z_index = 0)\n if text.is_a? Hash\n x = text[:x]\n y = text[:y]\n mode = text.fetch(:mode, :left)\n color = text.fetch(:color, 0)\n alpha = text.fetch(:alpha, 0xff)\n effect = text.fetch(:effect, nil)\n effect_color = text.fetch(:effect_color, 0)\n effect_size = text.fetch(:effect_size, 1)\n effect_alpha = text.fetch(:effect_alpha, 0xff)\n z_index = text.fetch(:z_index, 0)\n text = text[:text]\n end\n\n color = (alpha << 24) | color\n rel =\n case mode\n when :left then 0\n when :center then 0.5\n when :right then 1\n else 0\n end\n if effect\n effect_color = (effect_alpha << 24) | effect_color\n if effect == :border\n @font.draw_markup_rel text, x - effect_size, y - effect_size, z_index, rel, 0, 1, 1, effect_color\n @font.draw_markup_rel text, x, y - effect_size, z_index, rel, 0, 1, 1, effect_color\n @font.draw_markup_rel text, x + effect_size, y - effect_size, z_index, rel, 0, 1, 1, effect_color\n @font.draw_markup_rel text, x + effect_size, y, z_index, rel, 0, 1, 1, effect_color\n @font.draw_markup_rel text, x + effect_size, y + effect_size, z_index, rel, 0, 1, 1, effect_color\n @font.draw_markup_rel text, x, y + effect_size, z_index, rel, 0, 1, 1, effect_color\n @font.draw_markup_rel text, x - effect_size, y + effect_size, z_index, rel, 0, 1, 1, effect_color\n @font.draw_markup_rel text, x - effect_size, y, z_index, rel, 0, 1, 1, effect_color\n elsif effect == :shadow\n @font.draw_markup_rel text, x + effect_size, y + effect_size, z_index, rel, 0, 1, 1, effect_color\n end\n end\n @font.draw_markup_rel text, x, y, z_index, rel, 0, 1, 1, color\n end", "code_tokens": ["def", "write_line", "(", "text", ",", "x", "=", "nil", ",", "y", "=", "nil", ",", "mode", "=", ":left", ",", "color", "=", "0", ",", "alpha", "=", "0xff", ",", "effect", "=", "nil", ",", "effect_color", "=", "0", ",", "effect_size", "=", "1", ",", "effect_alpha", "=", "0xff", ",", "z_index", "=", "0", ")", "if", "text", ".", "is_a?", "Hash", "x", "=", "text", "[", ":x", "]", "y", "=", "text", "[", ":y", "]", "mode", "=", "text", ".", "fetch", "(", ":mode", ",", ":left", ")", "color", "=", "text", ".", "fetch", "(", ":color", ",", "0", ")", "alpha", "=", "text", ".", "fetch", "(", ":alpha", ",", "0xff", ")", "effect", "=", "text", ".", "fetch", "(", ":effect", ",", "nil", ")", "effect_color", "=", "text", ".", "fetch", "(", ":effect_color", ",", "0", ")", "effect_size", "=", "text", ".", "fetch", "(", ":effect_size", ",", "1", ")", "effect_alpha", "=", "text", ".", "fetch", "(", ":effect_alpha", ",", "0xff", ")", "z_index", "=", "text", ".", "fetch", "(", ":z_index", ",", "0", ")", "text", "=", "text", "[", ":text", "]", "end", "color", "=", "(", "alpha", "<<", "24", ")", "|", "color", "rel", "=", "case", "mode", "when", ":left", "then", "0", "when", ":center", "then", "0.5", "when", ":right", "then", "1", "else", "0", "end", "if", "effect", "effect_color", "=", "(", "effect_alpha", "<<", "24", ")", "|", "effect_color", "if", "effect", "==", ":border", "@font", ".", "draw_markup_rel", "text", ",", "x", "-", "effect_size", ",", "y", "-", "effect_size", ",", "z_index", ",", "rel", ",", "0", ",", "1", ",", "1", ",", "effect_color", "@font", ".", "draw_markup_rel", "text", ",", "x", ",", "y", "-", "effect_size", ",", "z_index", ",", "rel", ",", "0", ",", "1", ",", "1", ",", "effect_color", "@font", ".", "draw_markup_rel", "text", ",", "x", "+", "effect_size", ",", "y", "-", "effect_size", ",", "z_index", ",", "rel", ",", "0", ",", "1", ",", "1", ",", "effect_color", "@font", ".", "draw_markup_rel", "text", ",", "x", "+", "effect_size", ",", "y", ",", "z_index", ",", "rel", ",", "0", ",", "1", ",", "1", ",", "effect_color", "@font", ".", "draw_markup_rel", "text", ",", "x", "+", "effect_size", ",", "y", "+", "effect_size", ",", "z_index", ",", "rel", ",", "0", ",", "1", ",", "1", ",", "effect_color", "@font", ".", "draw_markup_rel", "text", ",", "x", ",", "y", "+", "effect_size", ",", "z_index", ",", "rel", ",", "0", ",", "1", ",", "1", ",", "effect_color", "@font", ".", "draw_markup_rel", "text", ",", "x", "-", "effect_size", ",", "y", "+", "effect_size", ",", "z_index", ",", "rel", ",", "0", ",", "1", ",", "1", ",", "effect_color", "@font", ".", "draw_markup_rel", "text", ",", "x", "-", "effect_size", ",", "y", ",", "z_index", ",", "rel", ",", "0", ",", "1", ",", "1", ",", "effect_color", "elsif", "effect", "==", ":shadow", "@font", ".", "draw_markup_rel", "text", ",", "x", "+", "effect_size", ",", "y", "+", "effect_size", ",", "z_index", ",", "rel", ",", "0", ",", "1", ",", "1", ",", "effect_color", "end", "end", "@font", ".", "draw_markup_rel", "text", ",", "x", ",", "y", ",", "z_index", ",", "rel", ",", "0", ",", "1", ",", "1", ",", "color", "end"], "docstring": "Creates a TextHelper.\n\n Parameters:\n [font] A Gosu::Font that will be used to draw the text.\n [line_spacing] When drawing multiple lines, the distance, in pixels,\n between each line.\n Draws a single line of text.\n\n Parameters:\n [text] The text to be drawn. No line breaks are allowed. You can use the\n `` tag for bold, `` for italic and `` for colors.\n [x] The horizontal reference for drawing the text. If +mode+ is +:left+,\n all text will be drawn from this point to the right; if +mode+ is\n +:right+, all text will be drawn from this point to the left; and if\n +mode+ is +:center+, the text will be equally distributed to the\n left and to the right of this point.\n [y] The vertical reference for drawing the text. All text will be drawn\n from this point down.\n [mode] The alignment of the text. Valid values are +:left+, +:right+ and\n +:center+.\n [color] The color of the text, in hexadecimal RRGGBB format.\n [alpha] The opacity of the text. Valid values vary from 0 (fully\n transparent) to 255 (fully opaque).\n [effect] Effect to add to the text. It can be either +nil+, for no effect,\n +:border+ for bordered text, or +:shadow+ for shadowed text (the\n shadow is always placed below and to the right of the text).\n [effect_color] Color of the effect, if any.\n [effect_size] Size of the effect, if any. In the case of +:border+, this\n will be the width of the border (the border will only look\n good when +effect_size+ is relatively small, compared to the\n size of the font); in the case of +:shadow+, it will be the\n distance between the text and the shadow.\n [effect_alpha] Opacity of the effect, if any. For shadows, it is usual to\n provide less than 255.\n [z_index] The z-order to draw the object. Objects with larger z-orders\n will be drawn on top of the ones with smaller z-orders.\n\n *Obs.:* This method accepts named parameters, but +text+, +x+ and +y+ are\n mandatory.", "docstring_tokens": ["Creates", "a", "TextHelper", "."], "sha": "a7117a566141cd922a4fd90ab71ba63ed8a92080", "url": "https://github.com/victords/minigl/blob/a7117a566141cd922a4fd90ab71ba63ed8a92080/lib/minigl/text.rb#L49-L90", "partition": "test"} {"repo": "victords/minigl", "path": "lib/minigl/text.rb", "func_name": "MiniGL.TextHelper.write_breaking", "original_string": "def write_breaking(text, x, y, width, mode = :left, color = 0, alpha = 0xff, z_index = 0)\n color = (alpha << 24) | color\n text.split(\"\\n\").each do |p|\n if mode == :justified\n y = write_paragraph_justified p, x, y, width, color, z_index\n else\n rel =\n case mode\n when :left then 0\n when :center then 0.5\n when :right then 1\n else 0\n end\n y = write_paragraph p, x, y, width, rel, color, z_index\n end\n end\n end", "language": "ruby", "code": "def write_breaking(text, x, y, width, mode = :left, color = 0, alpha = 0xff, z_index = 0)\n color = (alpha << 24) | color\n text.split(\"\\n\").each do |p|\n if mode == :justified\n y = write_paragraph_justified p, x, y, width, color, z_index\n else\n rel =\n case mode\n when :left then 0\n when :center then 0.5\n when :right then 1\n else 0\n end\n y = write_paragraph p, x, y, width, rel, color, z_index\n end\n end\n end", "code_tokens": ["def", "write_breaking", "(", "text", ",", "x", ",", "y", ",", "width", ",", "mode", "=", ":left", ",", "color", "=", "0", ",", "alpha", "=", "0xff", ",", "z_index", "=", "0", ")", "color", "=", "(", "alpha", "<<", "24", ")", "|", "color", "text", ".", "split", "(", "\"\\n\"", ")", ".", "each", "do", "|", "p", "|", "if", "mode", "==", ":justified", "y", "=", "write_paragraph_justified", "p", ",", "x", ",", "y", ",", "width", ",", "color", ",", "z_index", "else", "rel", "=", "case", "mode", "when", ":left", "then", "0", "when", ":center", "then", "0.5", "when", ":right", "then", "1", "else", "0", "end", "y", "=", "write_paragraph", "p", ",", "x", ",", "y", ",", "width", ",", "rel", ",", "color", ",", "z_index", "end", "end", "end"], "docstring": "Draws text, breaking lines when needed and when explicitly caused by the\n \"\\n\" character.\n\n Parameters:\n [text] The text to be drawn. Line breaks are allowed. You can use the\n `` tag for bold, `` for italic and `` for colors.\n [x] The horizontal reference for drawing the text. Works like in\n +write_line+ for the +:left+, +:right+ and +:center+ modes. For the\n +:justified+ mode, works the same as for +:left+.\n [y] The vertical reference for drawing the text. All text will be drawn\n from this point down.\n [width] The maximum width for the lines of text. Line is broken when\n this width is exceeded.\n [mode] The alignment of the text. Valid values are +:left+, +:right+,\n +:center+ and +:justified+.\n [color] The color of the text, in hexadecimal RRGGBB format.\n [alpha] The opacity of the text. Valid values vary from 0 (fully\n transparent) to 255 (fully opaque).\n [z_index] The z-order to draw the object. Objects with larger z-orders\n will be drawn on top of the ones with smaller z-orders.", "docstring_tokens": ["Draws", "text", "breaking", "lines", "when", "needed", "and", "when", "explicitly", "caused", "by", "the", "\\", "n", "character", "."], "sha": "a7117a566141cd922a4fd90ab71ba63ed8a92080", "url": "https://github.com/victords/minigl/blob/a7117a566141cd922a4fd90ab71ba63ed8a92080/lib/minigl/text.rb#L112-L128", "partition": "test"} {"repo": "scrapper/fit4ruby", "path": "lib/fit4ruby/FitMessageIdMapper.rb", "func_name": "Fit4Ruby.FitMessageIdMapper.add_global", "original_string": "def add_global(message)\n unless (slot = @entries.index { |e| e.nil? })\n # No more free slots. We have to find the least recently used one.\n slot = 0\n 0.upto(15) do |i|\n if i != slot && @entries[slot].last_use > @entries[i].last_use\n slot = i\n end\n end\n end\n @entries[slot] = Entry.new(message, Time.now)\n\n slot\n end", "language": "ruby", "code": "def add_global(message)\n unless (slot = @entries.index { |e| e.nil? })\n # No more free slots. We have to find the least recently used one.\n slot = 0\n 0.upto(15) do |i|\n if i != slot && @entries[slot].last_use > @entries[i].last_use\n slot = i\n end\n end\n end\n @entries[slot] = Entry.new(message, Time.now)\n\n slot\n end", "code_tokens": ["def", "add_global", "(", "message", ")", "unless", "(", "slot", "=", "@entries", ".", "index", "{", "|", "e", "|", "e", ".", "nil?", "}", ")", "# No more free slots. We have to find the least recently used one.", "slot", "=", "0", "0", ".", "upto", "(", "15", ")", "do", "|", "i", "|", "if", "i", "!=", "slot", "&&", "@entries", "[", "slot", "]", ".", "last_use", ">", "@entries", "[", "i", "]", ".", "last_use", "slot", "=", "i", "end", "end", "end", "@entries", "[", "slot", "]", "=", "Entry", ".", "new", "(", "message", ",", "Time", ".", "now", ")", "slot", "end"], "docstring": "Add a new GlobalFitMessage to the mapper and return the local message\n number.", "docstring_tokens": ["Add", "a", "new", "GlobalFitMessage", "to", "the", "mapper", "and", "return", "the", "local", "message", "number", "."], "sha": "ec0781abad95c1fea8998640e49873186e9f67d9", "url": "https://github.com/scrapper/fit4ruby/blob/ec0781abad95c1fea8998640e49873186e9f67d9/lib/fit4ruby/FitMessageIdMapper.rb#L33-L46", "partition": "test"} {"repo": "scrapper/fit4ruby", "path": "lib/fit4ruby/FitMessageIdMapper.rb", "func_name": "Fit4Ruby.FitMessageIdMapper.get_local", "original_string": "def get_local(message)\n 0.upto(15) do |i|\n if (entry = @entries[i]) && entry.global_message == message\n entry.last_use = Time.now\n return i\n end\n end\n nil\n end", "language": "ruby", "code": "def get_local(message)\n 0.upto(15) do |i|\n if (entry = @entries[i]) && entry.global_message == message\n entry.last_use = Time.now\n return i\n end\n end\n nil\n end", "code_tokens": ["def", "get_local", "(", "message", ")", "0", ".", "upto", "(", "15", ")", "do", "|", "i", "|", "if", "(", "entry", "=", "@entries", "[", "i", "]", ")", "&&", "entry", ".", "global_message", "==", "message", "entry", ".", "last_use", "=", "Time", ".", "now", "return", "i", "end", "end", "nil", "end"], "docstring": "Get the local message number for a given GlobalFitMessage. If there is\n no message number, nil is returned.", "docstring_tokens": ["Get", "the", "local", "message", "number", "for", "a", "given", "GlobalFitMessage", ".", "If", "there", "is", "no", "message", "number", "nil", "is", "returned", "."], "sha": "ec0781abad95c1fea8998640e49873186e9f67d9", "url": "https://github.com/scrapper/fit4ruby/blob/ec0781abad95c1fea8998640e49873186e9f67d9/lib/fit4ruby/FitMessageIdMapper.rb#L50-L58", "partition": "test"} {"repo": "scrapper/fit4ruby", "path": "lib/fit4ruby/Monitoring_B.rb", "func_name": "Fit4Ruby.Monitoring_B.check", "original_string": "def check\n last_timestamp = ts_16_offset = nil\n last_ts_16 = nil\n\n # The timestamp_16 is a 2 byte time stamp value that is used instead of\n # the 4 byte timestamp field for monitoring records that have\n # current_activity_type_intensity values with an activity type of 6. The\n # value seems to be in seconds, but the 0 value reference does not seem\n # to be included in the file. However, it can be approximated using the\n # surrounding timestamp values.\n @monitorings.each do |record|\n if last_ts_16 && ts_16_offset && record.timestamp_16 &&\n record.timestamp_16 < last_ts_16\n # Detect timestamp_16 wrap-arounds. timestamp_16 is a 16 bit value.\n # In case of a wrap-around we adjust the ts_16_offset accordingly.\n ts_16_offset += 2 ** 16\n end\n if ts_16_offset\n # We have already found the offset. Adjust all timestamps according\n # to 'offset + timestamp_16'\n if record.timestamp_16\n record.timestamp = ts_16_offset + record.timestamp_16\n last_ts_16 = record.timestamp_16\n end\n else\n # We are still looking for the offset.\n if record.timestamp_16 && last_timestamp\n # We have a previous timestamp and found the first record with a\n # timestamp_16 value set. We assume that the timestamp of this\n # record is one minute after the previously found timestamp.\n # That's just a guess. Who knows what the Garmin engineers were\n # thinking here?\n ts_16_offset = last_timestamp + 60 - record.timestamp_16\n record.timestamp = ts_16_offset + record.timestamp_16\n last_ts_16 = record.timestamp_16\n else\n # Just save the timestamp of the current record.\n last_timestamp = record.timestamp\n end\n end\n end\n end", "language": "ruby", "code": "def check\n last_timestamp = ts_16_offset = nil\n last_ts_16 = nil\n\n # The timestamp_16 is a 2 byte time stamp value that is used instead of\n # the 4 byte timestamp field for monitoring records that have\n # current_activity_type_intensity values with an activity type of 6. The\n # value seems to be in seconds, but the 0 value reference does not seem\n # to be included in the file. However, it can be approximated using the\n # surrounding timestamp values.\n @monitorings.each do |record|\n if last_ts_16 && ts_16_offset && record.timestamp_16 &&\n record.timestamp_16 < last_ts_16\n # Detect timestamp_16 wrap-arounds. timestamp_16 is a 16 bit value.\n # In case of a wrap-around we adjust the ts_16_offset accordingly.\n ts_16_offset += 2 ** 16\n end\n if ts_16_offset\n # We have already found the offset. Adjust all timestamps according\n # to 'offset + timestamp_16'\n if record.timestamp_16\n record.timestamp = ts_16_offset + record.timestamp_16\n last_ts_16 = record.timestamp_16\n end\n else\n # We are still looking for the offset.\n if record.timestamp_16 && last_timestamp\n # We have a previous timestamp and found the first record with a\n # timestamp_16 value set. We assume that the timestamp of this\n # record is one minute after the previously found timestamp.\n # That's just a guess. Who knows what the Garmin engineers were\n # thinking here?\n ts_16_offset = last_timestamp + 60 - record.timestamp_16\n record.timestamp = ts_16_offset + record.timestamp_16\n last_ts_16 = record.timestamp_16\n else\n # Just save the timestamp of the current record.\n last_timestamp = record.timestamp\n end\n end\n end\n end", "code_tokens": ["def", "check", "last_timestamp", "=", "ts_16_offset", "=", "nil", "last_ts_16", "=", "nil", "# The timestamp_16 is a 2 byte time stamp value that is used instead of", "# the 4 byte timestamp field for monitoring records that have", "# current_activity_type_intensity values with an activity type of 6. The", "# value seems to be in seconds, but the 0 value reference does not seem", "# to be included in the file. However, it can be approximated using the", "# surrounding timestamp values.", "@monitorings", ".", "each", "do", "|", "record", "|", "if", "last_ts_16", "&&", "ts_16_offset", "&&", "record", ".", "timestamp_16", "&&", "record", ".", "timestamp_16", "<", "last_ts_16", "# Detect timestamp_16 wrap-arounds. timestamp_16 is a 16 bit value.", "# In case of a wrap-around we adjust the ts_16_offset accordingly.", "ts_16_offset", "+=", "2", "**", "16", "end", "if", "ts_16_offset", "# We have already found the offset. Adjust all timestamps according", "# to 'offset + timestamp_16'", "if", "record", ".", "timestamp_16", "record", ".", "timestamp", "=", "ts_16_offset", "+", "record", ".", "timestamp_16", "last_ts_16", "=", "record", ".", "timestamp_16", "end", "else", "# We are still looking for the offset.", "if", "record", ".", "timestamp_16", "&&", "last_timestamp", "# We have a previous timestamp and found the first record with a", "# timestamp_16 value set. We assume that the timestamp of this", "# record is one minute after the previously found timestamp.", "# That's just a guess. Who knows what the Garmin engineers were", "# thinking here?", "ts_16_offset", "=", "last_timestamp", "+", "60", "-", "record", ".", "timestamp_16", "record", ".", "timestamp", "=", "ts_16_offset", "+", "record", ".", "timestamp_16", "last_ts_16", "=", "record", ".", "timestamp_16", "else", "# Just save the timestamp of the current record.", "last_timestamp", "=", "record", ".", "timestamp", "end", "end", "end", "end"], "docstring": "Create a new Monitoring_B object.\n @param field_values [Hash] A Hash that provides initial values for\n certain fields of the FitDataRecord.\n Perform some basic logical checks on the object and all references sub\n objects. Any errors will be reported via the Log object.", "docstring_tokens": ["Create", "a", "new", "Monitoring_B", "object", "."], "sha": "ec0781abad95c1fea8998640e49873186e9f67d9", "url": "https://github.com/scrapper/fit4ruby/blob/ec0781abad95c1fea8998640e49873186e9f67d9/lib/fit4ruby/Monitoring_B.rb#L48-L89", "partition": "test"} {"repo": "scrapper/fit4ruby", "path": "lib/fit4ruby/FieldDescription.rb", "func_name": "Fit4Ruby.FieldDescription.create_global_definition", "original_string": "def create_global_definition(fit_entity)\n messages = fit_entity.developer_fit_messages\n unless (gfm = GlobalFitMessages[@native_mesg_num])\n Log.error \"Developer field description references unknown global \" +\n \"message number #{@native_mesg_num}\"\n return\n end\n\n if @developer_data_index >=\n fit_entity.top_level_record.developer_data_ids.size\n Log.error \"Developer data index #{@developer_data_index} is too large\"\n return\n end\n\n msg = messages[@native_mesg_num] ||\n messages.message(@native_mesg_num, gfm.name)\n unless (@fit_base_type_id & 0x7F) < FIT_TYPE_DEFS.size\n Log.error \"fit_base_type_id #{@fit_base_type_id} is too large\"\n return\n end\n options = {}\n options[:scale] = @scale if @scale\n options[:offset] = @offset if @offset\n options[:array] = @array if @array\n options[:unit] = @units\n msg.field(@field_definition_number,\n FIT_TYPE_DEFS[@fit_base_type_id & 0x7F][1],\n \"_#{@developer_data_index}_#{@field_name}\", options)\n end", "language": "ruby", "code": "def create_global_definition(fit_entity)\n messages = fit_entity.developer_fit_messages\n unless (gfm = GlobalFitMessages[@native_mesg_num])\n Log.error \"Developer field description references unknown global \" +\n \"message number #{@native_mesg_num}\"\n return\n end\n\n if @developer_data_index >=\n fit_entity.top_level_record.developer_data_ids.size\n Log.error \"Developer data index #{@developer_data_index} is too large\"\n return\n end\n\n msg = messages[@native_mesg_num] ||\n messages.message(@native_mesg_num, gfm.name)\n unless (@fit_base_type_id & 0x7F) < FIT_TYPE_DEFS.size\n Log.error \"fit_base_type_id #{@fit_base_type_id} is too large\"\n return\n end\n options = {}\n options[:scale] = @scale if @scale\n options[:offset] = @offset if @offset\n options[:array] = @array if @array\n options[:unit] = @units\n msg.field(@field_definition_number,\n FIT_TYPE_DEFS[@fit_base_type_id & 0x7F][1],\n \"_#{@developer_data_index}_#{@field_name}\", options)\n end", "code_tokens": ["def", "create_global_definition", "(", "fit_entity", ")", "messages", "=", "fit_entity", ".", "developer_fit_messages", "unless", "(", "gfm", "=", "GlobalFitMessages", "[", "@native_mesg_num", "]", ")", "Log", ".", "error", "\"Developer field description references unknown global \"", "+", "\"message number #{@native_mesg_num}\"", "return", "end", "if", "@developer_data_index", ">=", "fit_entity", ".", "top_level_record", ".", "developer_data_ids", ".", "size", "Log", ".", "error", "\"Developer data index #{@developer_data_index} is too large\"", "return", "end", "msg", "=", "messages", "[", "@native_mesg_num", "]", "||", "messages", ".", "message", "(", "@native_mesg_num", ",", "gfm", ".", "name", ")", "unless", "(", "@fit_base_type_id", "&", "0x7F", ")", "<", "FIT_TYPE_DEFS", ".", "size", "Log", ".", "error", "\"fit_base_type_id #{@fit_base_type_id} is too large\"", "return", "end", "options", "=", "{", "}", "options", "[", ":scale", "]", "=", "@scale", "if", "@scale", "options", "[", ":offset", "]", "=", "@offset", "if", "@offset", "options", "[", ":array", "]", "=", "@array", "if", "@array", "options", "[", ":unit", "]", "=", "@units", "msg", ".", "field", "(", "@field_definition_number", ",", "FIT_TYPE_DEFS", "[", "@fit_base_type_id", "&", "0x7F", "]", "[", "1", "]", ",", "\"_#{@developer_data_index}_#{@field_name}\"", ",", "options", ")", "end"], "docstring": "Create a new FieldDescription object.\n @param field_values [Hash] Hash that provides initial values for certain\n fields.", "docstring_tokens": ["Create", "a", "new", "FieldDescription", "object", "."], "sha": "ec0781abad95c1fea8998640e49873186e9f67d9", "url": "https://github.com/scrapper/fit4ruby/blob/ec0781abad95c1fea8998640e49873186e9f67d9/lib/fit4ruby/FieldDescription.rb#L30-L58", "partition": "test"} {"repo": "scrapper/fit4ruby", "path": "lib/fit4ruby/DeviceInfo.rb", "func_name": "Fit4Ruby.DeviceInfo.check", "original_string": "def check(index)\n unless @device_index\n Log.fatal 'device info record must have a device_index'\n end\n if @device_index == 0\n unless @manufacturer\n Log.fatal 'device info record 0 must have a manufacturer field set'\n end\n if @manufacturer == 'garmin'\n unless @garmin_product\n Log.fatal 'device info record 0 must have a garman_product ' +\n 'field set'\n end\n else\n unless @product\n Log.fatal 'device info record 0 must have a product field set'\n end\n end\n if @serial_number.nil?\n Log.fatal 'device info record 0 must have a serial number set'\n end\n end\n end", "language": "ruby", "code": "def check(index)\n unless @device_index\n Log.fatal 'device info record must have a device_index'\n end\n if @device_index == 0\n unless @manufacturer\n Log.fatal 'device info record 0 must have a manufacturer field set'\n end\n if @manufacturer == 'garmin'\n unless @garmin_product\n Log.fatal 'device info record 0 must have a garman_product ' +\n 'field set'\n end\n else\n unless @product\n Log.fatal 'device info record 0 must have a product field set'\n end\n end\n if @serial_number.nil?\n Log.fatal 'device info record 0 must have a serial number set'\n end\n end\n end", "code_tokens": ["def", "check", "(", "index", ")", "unless", "@device_index", "Log", ".", "fatal", "'device info record must have a device_index'", "end", "if", "@device_index", "==", "0", "unless", "@manufacturer", "Log", ".", "fatal", "'device info record 0 must have a manufacturer field set'", "end", "if", "@manufacturer", "==", "'garmin'", "unless", "@garmin_product", "Log", ".", "fatal", "'device info record 0 must have a garman_product '", "+", "'field set'", "end", "else", "unless", "@product", "Log", ".", "fatal", "'device info record 0 must have a product field set'", "end", "end", "if", "@serial_number", ".", "nil?", "Log", ".", "fatal", "'device info record 0 must have a serial number set'", "end", "end", "end"], "docstring": "Ensure that FitDataRecords have a deterministic sequence. Device infos\n are sorted by device_index.", "docstring_tokens": ["Ensure", "that", "FitDataRecords", "have", "a", "deterministic", "sequence", ".", "Device", "infos", "are", "sorted", "by", "device_index", "."], "sha": "ec0781abad95c1fea8998640e49873186e9f67d9", "url": "https://github.com/scrapper/fit4ruby/blob/ec0781abad95c1fea8998640e49873186e9f67d9/lib/fit4ruby/DeviceInfo.rb#L35-L57", "partition": "test"} {"repo": "scrapper/fit4ruby", "path": "lib/fit4ruby/Log.rb", "func_name": "Fit4Ruby.ILogger.open", "original_string": "def open(io)\n begin\n @@logger = Logger.new(io)\n rescue => e\n @@logger = Logger.new($stderr)\n Log.fatal \"Cannot open log file: #{e.message}\"\n end\n end", "language": "ruby", "code": "def open(io)\n begin\n @@logger = Logger.new(io)\n rescue => e\n @@logger = Logger.new($stderr)\n Log.fatal \"Cannot open log file: #{e.message}\"\n end\n end", "code_tokens": ["def", "open", "(", "io", ")", "begin", "@@logger", "=", "Logger", ".", "new", "(", "io", ")", "rescue", "=>", "e", "@@logger", "=", "Logger", ".", "new", "(", "$stderr", ")", "Log", ".", "fatal", "\"Cannot open log file: #{e.message}\"", "end", "end"], "docstring": "Redirect all log messages to the given IO.\n @param io [IO] Output file descriptor", "docstring_tokens": ["Redirect", "all", "log", "messages", "to", "the", "given", "IO", "."], "sha": "ec0781abad95c1fea8998640e49873186e9f67d9", "url": "https://github.com/scrapper/fit4ruby/blob/ec0781abad95c1fea8998640e49873186e9f67d9/lib/fit4ruby/Log.rb#L39-L46", "partition": "test"} {"repo": "scrapper/fit4ruby", "path": "lib/fit4ruby/FitFileEntity.rb", "func_name": "Fit4Ruby.FitFileEntity.set_type", "original_string": "def set_type(type)\n if @top_level_record\n Log.fatal \"FIT file type has already been set to \" +\n \"#{@top_level_record.class}\"\n end\n case type\n when 4, 'activity'\n @top_level_record = Activity.new\n @type = 'activity'\n when 32, 'monitoring_b'\n @top_level_record = Monitoring_B.new\n @type = 'monitoring_b'\n when 44, 'metrics'\n @top_level_record = Metrics.new\n @type = 'metrics'\n else\n Log.error \"Unsupported FIT file type #{type}\"\n return nil\n end\n\n @top_level_record\n end", "language": "ruby", "code": "def set_type(type)\n if @top_level_record\n Log.fatal \"FIT file type has already been set to \" +\n \"#{@top_level_record.class}\"\n end\n case type\n when 4, 'activity'\n @top_level_record = Activity.new\n @type = 'activity'\n when 32, 'monitoring_b'\n @top_level_record = Monitoring_B.new\n @type = 'monitoring_b'\n when 44, 'metrics'\n @top_level_record = Metrics.new\n @type = 'metrics'\n else\n Log.error \"Unsupported FIT file type #{type}\"\n return nil\n end\n\n @top_level_record\n end", "code_tokens": ["def", "set_type", "(", "type", ")", "if", "@top_level_record", "Log", ".", "fatal", "\"FIT file type has already been set to \"", "+", "\"#{@top_level_record.class}\"", "end", "case", "type", "when", "4", ",", "'activity'", "@top_level_record", "=", "Activity", ".", "new", "@type", "=", "'activity'", "when", "32", ",", "'monitoring_b'", "@top_level_record", "=", "Monitoring_B", ".", "new", "@type", "=", "'monitoring_b'", "when", "44", ",", "'metrics'", "@top_level_record", "=", "Metrics", ".", "new", "@type", "=", "'metrics'", "else", "Log", ".", "error", "\"Unsupported FIT file type #{type}\"", "return", "nil", "end", "@top_level_record", "end"], "docstring": "Create a FitFileEntity.\n Set what kind of FIT file we are dealing with.\n @return The Ruby object that will hold the content of the FIT file. It's\n a derivative of FitDataRecord.", "docstring_tokens": ["Create", "a", "FitFileEntity", ".", "Set", "what", "kind", "of", "FIT", "file", "we", "are", "dealing", "with", "."], "sha": "ec0781abad95c1fea8998640e49873186e9f67d9", "url": "https://github.com/scrapper/fit4ruby/blob/ec0781abad95c1fea8998640e49873186e9f67d9/lib/fit4ruby/FitFileEntity.rb#L41-L62", "partition": "test"} {"repo": "scrapper/fit4ruby", "path": "lib/fit4ruby/Activity.rb", "func_name": "Fit4Ruby.Activity.check", "original_string": "def check\n unless @timestamp && @timestamp >= Time.parse('1990-01-01T00:00:00+00:00')\n Log.fatal \"Activity has no valid timestamp\"\n end\n unless @total_timer_time\n Log.fatal \"Activity has no valid total_timer_time\"\n end\n unless @device_infos.length > 0\n Log.fatal \"Activity must have at least one device_info section\"\n end\n @device_infos.each.with_index { |d, index| d.check(index) }\n @sensor_settings.each.with_index { |s, index| s.check(index) }\n unless @num_sessions == @sessions.count\n Log.fatal \"Activity record requires #{@num_sessions}, but \"\n \"#{@sessions.length} session records were found in the \"\n \"FIT file.\"\n end\n\n # Records must have consecutively growing timestamps and distances.\n ts = Time.parse('1989-12-31')\n distance = nil\n invalid_records = []\n @records.each_with_index do |r, idx|\n Log.fatal \"Record has no timestamp\" unless r.timestamp\n if r.timestamp < ts\n Log.fatal \"Record has earlier timestamp than previous record\"\n end\n if r.distance\n if distance && r.distance < distance\n # Normally this should be a fatal error as the FIT file is clearly\n # broken. Unfortunately, the Skiing/Boarding app in the Fenix3\n # produces such broken FIT files. So we just warn about this\n # problem and discard the earlier records.\n Log.error \"Record #{r.timestamp} has smaller distance \" +\n \"(#{r.distance}) than an earlier record (#{distance}).\"\n # Index of the list record to be discarded.\n (idx - 1).downto(0) do |i|\n if (ri = @records[i]).distance > r.distance\n # This is just an approximation. It looks like the app adds\n # records to the FIT file for runs that it meant to discard.\n # Maybe the two successive time start events are a better\n # criteria. But this workaround works for now.\n invalid_records << ri\n else\n # All broken records have been found.\n break\n end\n end\n end\n distance = r.distance\n end\n ts = r.timestamp\n end\n unless invalid_records.empty?\n # Delete all the broken records from the @records Array.\n Log.warn \"Discarding #{invalid_records.length} earlier records\"\n @records.delete_if { |r| invalid_records.include?(r) }\n end\n\n # Laps must have a consecutively growing message index.\n @laps.each.with_index do |lap, index|\n lap.check(index)\n # If we have heart rate zone records, there should be one for each\n # lap\n @heart_rate_zones[index].check(index) if @heart_rate_zones[index]\n end\n @sessions.each { |s| s.check(self) }\n end", "language": "ruby", "code": "def check\n unless @timestamp && @timestamp >= Time.parse('1990-01-01T00:00:00+00:00')\n Log.fatal \"Activity has no valid timestamp\"\n end\n unless @total_timer_time\n Log.fatal \"Activity has no valid total_timer_time\"\n end\n unless @device_infos.length > 0\n Log.fatal \"Activity must have at least one device_info section\"\n end\n @device_infos.each.with_index { |d, index| d.check(index) }\n @sensor_settings.each.with_index { |s, index| s.check(index) }\n unless @num_sessions == @sessions.count\n Log.fatal \"Activity record requires #{@num_sessions}, but \"\n \"#{@sessions.length} session records were found in the \"\n \"FIT file.\"\n end\n\n # Records must have consecutively growing timestamps and distances.\n ts = Time.parse('1989-12-31')\n distance = nil\n invalid_records = []\n @records.each_with_index do |r, idx|\n Log.fatal \"Record has no timestamp\" unless r.timestamp\n if r.timestamp < ts\n Log.fatal \"Record has earlier timestamp than previous record\"\n end\n if r.distance\n if distance && r.distance < distance\n # Normally this should be a fatal error as the FIT file is clearly\n # broken. Unfortunately, the Skiing/Boarding app in the Fenix3\n # produces such broken FIT files. So we just warn about this\n # problem and discard the earlier records.\n Log.error \"Record #{r.timestamp} has smaller distance \" +\n \"(#{r.distance}) than an earlier record (#{distance}).\"\n # Index of the list record to be discarded.\n (idx - 1).downto(0) do |i|\n if (ri = @records[i]).distance > r.distance\n # This is just an approximation. It looks like the app adds\n # records to the FIT file for runs that it meant to discard.\n # Maybe the two successive time start events are a better\n # criteria. But this workaround works for now.\n invalid_records << ri\n else\n # All broken records have been found.\n break\n end\n end\n end\n distance = r.distance\n end\n ts = r.timestamp\n end\n unless invalid_records.empty?\n # Delete all the broken records from the @records Array.\n Log.warn \"Discarding #{invalid_records.length} earlier records\"\n @records.delete_if { |r| invalid_records.include?(r) }\n end\n\n # Laps must have a consecutively growing message index.\n @laps.each.with_index do |lap, index|\n lap.check(index)\n # If we have heart rate zone records, there should be one for each\n # lap\n @heart_rate_zones[index].check(index) if @heart_rate_zones[index]\n end\n @sessions.each { |s| s.check(self) }\n end", "code_tokens": ["def", "check", "unless", "@timestamp", "&&", "@timestamp", ">=", "Time", ".", "parse", "(", "'1990-01-01T00:00:00+00:00'", ")", "Log", ".", "fatal", "\"Activity has no valid timestamp\"", "end", "unless", "@total_timer_time", "Log", ".", "fatal", "\"Activity has no valid total_timer_time\"", "end", "unless", "@device_infos", ".", "length", ">", "0", "Log", ".", "fatal", "\"Activity must have at least one device_info section\"", "end", "@device_infos", ".", "each", ".", "with_index", "{", "|", "d", ",", "index", "|", "d", ".", "check", "(", "index", ")", "}", "@sensor_settings", ".", "each", ".", "with_index", "{", "|", "s", ",", "index", "|", "s", ".", "check", "(", "index", ")", "}", "unless", "@num_sessions", "==", "@sessions", ".", "count", "Log", ".", "fatal", "\"Activity record requires #{@num_sessions}, but \"", "\"#{@sessions.length} session records were found in the \"", "\"FIT file.\"", "end", "# Records must have consecutively growing timestamps and distances.", "ts", "=", "Time", ".", "parse", "(", "'1989-12-31'", ")", "distance", "=", "nil", "invalid_records", "=", "[", "]", "@records", ".", "each_with_index", "do", "|", "r", ",", "idx", "|", "Log", ".", "fatal", "\"Record has no timestamp\"", "unless", "r", ".", "timestamp", "if", "r", ".", "timestamp", "<", "ts", "Log", ".", "fatal", "\"Record has earlier timestamp than previous record\"", "end", "if", "r", ".", "distance", "if", "distance", "&&", "r", ".", "distance", "<", "distance", "# Normally this should be a fatal error as the FIT file is clearly", "# broken. Unfortunately, the Skiing/Boarding app in the Fenix3", "# produces such broken FIT files. So we just warn about this", "# problem and discard the earlier records.", "Log", ".", "error", "\"Record #{r.timestamp} has smaller distance \"", "+", "\"(#{r.distance}) than an earlier record (#{distance}).\"", "# Index of the list record to be discarded.", "(", "idx", "-", "1", ")", ".", "downto", "(", "0", ")", "do", "|", "i", "|", "if", "(", "ri", "=", "@records", "[", "i", "]", ")", ".", "distance", ">", "r", ".", "distance", "# This is just an approximation. It looks like the app adds", "# records to the FIT file for runs that it meant to discard.", "# Maybe the two successive time start events are a better", "# criteria. But this workaround works for now.", "invalid_records", "<<", "ri", "else", "# All broken records have been found.", "break", "end", "end", "end", "distance", "=", "r", ".", "distance", "end", "ts", "=", "r", ".", "timestamp", "end", "unless", "invalid_records", ".", "empty?", "# Delete all the broken records from the @records Array.", "Log", ".", "warn", "\"Discarding #{invalid_records.length} earlier records\"", "@records", ".", "delete_if", "{", "|", "r", "|", "invalid_records", ".", "include?", "(", "r", ")", "}", "end", "# Laps must have a consecutively growing message index.", "@laps", ".", "each", ".", "with_index", "do", "|", "lap", ",", "index", "|", "lap", ".", "check", "(", "index", ")", "# If we have heart rate zone records, there should be one for each", "# lap", "@heart_rate_zones", "[", "index", "]", ".", "check", "(", "index", ")", "if", "@heart_rate_zones", "[", "index", "]", "end", "@sessions", ".", "each", "{", "|", "s", "|", "s", ".", "check", "(", "self", ")", "}", "end"], "docstring": "Create a new Activity object.\n @param field_values [Hash] A Hash that provides initial values for\n certain fields of the FitDataRecord.\n Perform some basic logical checks on the object and all references sub\n objects. Any errors will be reported via the Log object.", "docstring_tokens": ["Create", "a", "new", "Activity", "object", "."], "sha": "ec0781abad95c1fea8998640e49873186e9f67d9", "url": "https://github.com/scrapper/fit4ruby/blob/ec0781abad95c1fea8998640e49873186e9f67d9/lib/fit4ruby/Activity.rb#L83-L150", "partition": "test"} {"repo": "scrapper/fit4ruby", "path": "lib/fit4ruby/Activity.rb", "func_name": "Fit4Ruby.Activity.total_gps_distance", "original_string": "def total_gps_distance\n timer_stops = []\n # Generate a list of all timestamps where the timer was stopped.\n @events.each do |e|\n if e.event == 'timer' && e.event_type == 'stop_all'\n timer_stops << e.timestamp\n end\n end\n\n # The first record of a FIT file can already have a distance associated\n # with it. The GPS location of the first record is not where the start\n # button was pressed. This introduces a slight inaccurcy when computing\n # the total distance purely on the GPS coordinates found in the records.\n d = 0.0\n last_lat = last_long = nil\n last_timestamp = nil\n\n # Iterate over all the records and accumlate the distances between the\n # neiboring coordinates.\n @records.each do |r|\n if (lat = r.position_lat) && (long = r.position_long)\n if last_lat && last_long\n distance = Fit4Ruby::GeoMath.distance(last_lat, last_long,\n lat, long)\n d += distance\n end\n if last_timestamp\n speed = distance / (r.timestamp - last_timestamp)\n end\n if timer_stops[0] == r.timestamp\n # If a stop event was found for this record timestamp we clear the\n # last_* values so that the distance covered while being stopped\n # is not added to the total.\n last_lat = last_long = nil\n last_timestamp = nil\n timer_stops.shift\n else\n last_lat = lat\n last_long = long\n last_timestamp = r.timestamp\n end\n end\n end\n d\n end", "language": "ruby", "code": "def total_gps_distance\n timer_stops = []\n # Generate a list of all timestamps where the timer was stopped.\n @events.each do |e|\n if e.event == 'timer' && e.event_type == 'stop_all'\n timer_stops << e.timestamp\n end\n end\n\n # The first record of a FIT file can already have a distance associated\n # with it. The GPS location of the first record is not where the start\n # button was pressed. This introduces a slight inaccurcy when computing\n # the total distance purely on the GPS coordinates found in the records.\n d = 0.0\n last_lat = last_long = nil\n last_timestamp = nil\n\n # Iterate over all the records and accumlate the distances between the\n # neiboring coordinates.\n @records.each do |r|\n if (lat = r.position_lat) && (long = r.position_long)\n if last_lat && last_long\n distance = Fit4Ruby::GeoMath.distance(last_lat, last_long,\n lat, long)\n d += distance\n end\n if last_timestamp\n speed = distance / (r.timestamp - last_timestamp)\n end\n if timer_stops[0] == r.timestamp\n # If a stop event was found for this record timestamp we clear the\n # last_* values so that the distance covered while being stopped\n # is not added to the total.\n last_lat = last_long = nil\n last_timestamp = nil\n timer_stops.shift\n else\n last_lat = lat\n last_long = long\n last_timestamp = r.timestamp\n end\n end\n end\n d\n end", "code_tokens": ["def", "total_gps_distance", "timer_stops", "=", "[", "]", "# Generate a list of all timestamps where the timer was stopped.", "@events", ".", "each", "do", "|", "e", "|", "if", "e", ".", "event", "==", "'timer'", "&&", "e", ".", "event_type", "==", "'stop_all'", "timer_stops", "<<", "e", ".", "timestamp", "end", "end", "# The first record of a FIT file can already have a distance associated", "# with it. The GPS location of the first record is not where the start", "# button was pressed. This introduces a slight inaccurcy when computing", "# the total distance purely on the GPS coordinates found in the records.", "d", "=", "0.0", "last_lat", "=", "last_long", "=", "nil", "last_timestamp", "=", "nil", "# Iterate over all the records and accumlate the distances between the", "# neiboring coordinates.", "@records", ".", "each", "do", "|", "r", "|", "if", "(", "lat", "=", "r", ".", "position_lat", ")", "&&", "(", "long", "=", "r", ".", "position_long", ")", "if", "last_lat", "&&", "last_long", "distance", "=", "Fit4Ruby", "::", "GeoMath", ".", "distance", "(", "last_lat", ",", "last_long", ",", "lat", ",", "long", ")", "d", "+=", "distance", "end", "if", "last_timestamp", "speed", "=", "distance", "/", "(", "r", ".", "timestamp", "-", "last_timestamp", ")", "end", "if", "timer_stops", "[", "0", "]", "==", "r", ".", "timestamp", "# If a stop event was found for this record timestamp we clear the", "# last_* values so that the distance covered while being stopped", "# is not added to the total.", "last_lat", "=", "last_long", "=", "nil", "last_timestamp", "=", "nil", "timer_stops", ".", "shift", "else", "last_lat", "=", "lat", "last_long", "=", "long", "last_timestamp", "=", "r", ".", "timestamp", "end", "end", "end", "d", "end"], "docstring": "Total distance convered by this activity purely computed by the GPS\n coordinates. This may differ from the distance computed by the device as\n it can be based on a purely calibrated footpod.", "docstring_tokens": ["Total", "distance", "convered", "by", "this", "activity", "purely", "computed", "by", "the", "GPS", "coordinates", ".", "This", "may", "differ", "from", "the", "distance", "computed", "by", "the", "device", "as", "it", "can", "be", "based", "on", "a", "purely", "calibrated", "footpod", "."], "sha": "ec0781abad95c1fea8998640e49873186e9f67d9", "url": "https://github.com/scrapper/fit4ruby/blob/ec0781abad95c1fea8998640e49873186e9f67d9/lib/fit4ruby/Activity.rb#L163-L207", "partition": "test"} {"repo": "scrapper/fit4ruby", "path": "lib/fit4ruby/Activity.rb", "func_name": "Fit4Ruby.Activity.vo2max", "original_string": "def vo2max\n # First check the event log for a vo2max reporting event.\n @events.each do |e|\n return e.vo2max if e.event == 'vo2max'\n end\n # Then check the user_data entries for a metmax entry. METmax * 3.5\n # is same value as VO2max.\n @user_data.each do |u|\n return u.metmax * 3.5 if u.metmax\n end\n\n nil\n end", "language": "ruby", "code": "def vo2max\n # First check the event log for a vo2max reporting event.\n @events.each do |e|\n return e.vo2max if e.event == 'vo2max'\n end\n # Then check the user_data entries for a metmax entry. METmax * 3.5\n # is same value as VO2max.\n @user_data.each do |u|\n return u.metmax * 3.5 if u.metmax\n end\n\n nil\n end", "code_tokens": ["def", "vo2max", "# First check the event log for a vo2max reporting event.", "@events", ".", "each", "do", "|", "e", "|", "return", "e", ".", "vo2max", "if", "e", ".", "event", "==", "'vo2max'", "end", "# Then check the user_data entries for a metmax entry. METmax * 3.5", "# is same value as VO2max.", "@user_data", ".", "each", "do", "|", "u", "|", "return", "u", ".", "metmax", "*", "3.5", "if", "u", ".", "metmax", "end", "nil", "end"], "docstring": "Returns the computed VO2max value. This value is computed by the device\n based on multiple previous activities.", "docstring_tokens": ["Returns", "the", "computed", "VO2max", "value", ".", "This", "value", "is", "computed", "by", "the", "device", "based", "on", "multiple", "previous", "activities", "."], "sha": "ec0781abad95c1fea8998640e49873186e9f67d9", "url": "https://github.com/scrapper/fit4ruby/blob/ec0781abad95c1fea8998640e49873186e9f67d9/lib/fit4ruby/Activity.rb#L259-L271", "partition": "test"} {"repo": "scrapper/fit4ruby", "path": "lib/fit4ruby/Activity.rb", "func_name": "Fit4Ruby.Activity.write", "original_string": "def write(io, id_mapper)\n @file_id.write(io, id_mapper)\n @file_creator.write(io, id_mapper)\n\n (@field_descriptions + @developer_data_ids +\n @device_infos + @sensor_settings +\n @data_sources + @user_profiles +\n @physiological_metrics + @events +\n @sessions + @laps + @records + @heart_rate_zones +\n @personal_records).sort.each do |s|\n s.write(io, id_mapper)\n end\n super\n end", "language": "ruby", "code": "def write(io, id_mapper)\n @file_id.write(io, id_mapper)\n @file_creator.write(io, id_mapper)\n\n (@field_descriptions + @developer_data_ids +\n @device_infos + @sensor_settings +\n @data_sources + @user_profiles +\n @physiological_metrics + @events +\n @sessions + @laps + @records + @heart_rate_zones +\n @personal_records).sort.each do |s|\n s.write(io, id_mapper)\n end\n super\n end", "code_tokens": ["def", "write", "(", "io", ",", "id_mapper", ")", "@file_id", ".", "write", "(", "io", ",", "id_mapper", ")", "@file_creator", ".", "write", "(", "io", ",", "id_mapper", ")", "(", "@field_descriptions", "+", "@developer_data_ids", "+", "@device_infos", "+", "@sensor_settings", "+", "@data_sources", "+", "@user_profiles", "+", "@physiological_metrics", "+", "@events", "+", "@sessions", "+", "@laps", "+", "@records", "+", "@heart_rate_zones", "+", "@personal_records", ")", ".", "sort", ".", "each", "do", "|", "s", "|", "s", ".", "write", "(", "io", ",", "id_mapper", ")", "end", "super", "end"], "docstring": "Write the Activity data to a file.\n @param io [IO] File reference\n @param id_mapper [FitMessageIdMapper] Maps global FIT record types to\n local ones.", "docstring_tokens": ["Write", "the", "Activity", "data", "to", "a", "file", "."], "sha": "ec0781abad95c1fea8998640e49873186e9f67d9", "url": "https://github.com/scrapper/fit4ruby/blob/ec0781abad95c1fea8998640e49873186e9f67d9/lib/fit4ruby/Activity.rb#L287-L300", "partition": "test"} {"repo": "scrapper/fit4ruby", "path": "lib/fit4ruby/Activity.rb", "func_name": "Fit4Ruby.Activity.new_fit_data_record", "original_string": "def new_fit_data_record(record_type, field_values = {})\n case record_type\n when 'file_id'\n @file_id = (record = FileId.new(field_values))\n when 'field_description'\n @field_descriptions << (record = FieldDescription.new(field_values))\n when 'developer_data_id'\n @developer_data_ids << (record = DeveloperDataId.new(field_values))\n when 'epo_data'\n @epo_data = (record = EPO_Data.new(field_values))\n when 'file_creator'\n @file_creator = (record = FileCreator.new(field_values))\n when 'device_info'\n @device_infos << (record = DeviceInfo.new(field_values))\n when 'sensor_settings'\n @sensor_settings << (record = SensorSettings.new(field_values))\n when 'data_sources'\n @data_sources << (record = DataSources.new(field_values))\n when 'user_data'\n @user_data << (record = UserData.new(field_values))\n when 'user_profile'\n @user_profiles << (record = UserProfile.new(field_values))\n when 'physiological_metrics'\n @physiological_metrics <<\n (record = PhysiologicalMetrics.new(field_values))\n when 'event'\n @events << (record = Event.new(field_values))\n when 'session'\n unless @cur_lap_records.empty?\n # Copy selected fields from section to lap.\n lap_field_values = {}\n [ :timestamp, :sport ].each do |f|\n lap_field_values[f] = field_values[f] if field_values.include?(f)\n end\n # Ensure that all previous records have been assigned to a lap.\n record = create_new_lap(lap_field_values)\n end\n @num_sessions += 1\n @sessions << (record = Session.new(@cur_session_laps, @lap_counter,\n field_values))\n @cur_session_laps = []\n when 'lap'\n record = create_new_lap(field_values)\n when 'record'\n @cur_lap_records << (record = Record.new(field_values))\n @records << record\n when 'hrv'\n @hrv << (record = HRV.new(field_values))\n when 'heart_rate_zones'\n @heart_rate_zones << (record = HeartRateZones.new(field_values))\n when 'personal_records'\n @personal_records << (record = PersonalRecords.new(field_values))\n else\n record = nil\n end\n\n record\n end", "language": "ruby", "code": "def new_fit_data_record(record_type, field_values = {})\n case record_type\n when 'file_id'\n @file_id = (record = FileId.new(field_values))\n when 'field_description'\n @field_descriptions << (record = FieldDescription.new(field_values))\n when 'developer_data_id'\n @developer_data_ids << (record = DeveloperDataId.new(field_values))\n when 'epo_data'\n @epo_data = (record = EPO_Data.new(field_values))\n when 'file_creator'\n @file_creator = (record = FileCreator.new(field_values))\n when 'device_info'\n @device_infos << (record = DeviceInfo.new(field_values))\n when 'sensor_settings'\n @sensor_settings << (record = SensorSettings.new(field_values))\n when 'data_sources'\n @data_sources << (record = DataSources.new(field_values))\n when 'user_data'\n @user_data << (record = UserData.new(field_values))\n when 'user_profile'\n @user_profiles << (record = UserProfile.new(field_values))\n when 'physiological_metrics'\n @physiological_metrics <<\n (record = PhysiologicalMetrics.new(field_values))\n when 'event'\n @events << (record = Event.new(field_values))\n when 'session'\n unless @cur_lap_records.empty?\n # Copy selected fields from section to lap.\n lap_field_values = {}\n [ :timestamp, :sport ].each do |f|\n lap_field_values[f] = field_values[f] if field_values.include?(f)\n end\n # Ensure that all previous records have been assigned to a lap.\n record = create_new_lap(lap_field_values)\n end\n @num_sessions += 1\n @sessions << (record = Session.new(@cur_session_laps, @lap_counter,\n field_values))\n @cur_session_laps = []\n when 'lap'\n record = create_new_lap(field_values)\n when 'record'\n @cur_lap_records << (record = Record.new(field_values))\n @records << record\n when 'hrv'\n @hrv << (record = HRV.new(field_values))\n when 'heart_rate_zones'\n @heart_rate_zones << (record = HeartRateZones.new(field_values))\n when 'personal_records'\n @personal_records << (record = PersonalRecords.new(field_values))\n else\n record = nil\n end\n\n record\n end", "code_tokens": ["def", "new_fit_data_record", "(", "record_type", ",", "field_values", "=", "{", "}", ")", "case", "record_type", "when", "'file_id'", "@file_id", "=", "(", "record", "=", "FileId", ".", "new", "(", "field_values", ")", ")", "when", "'field_description'", "@field_descriptions", "<<", "(", "record", "=", "FieldDescription", ".", "new", "(", "field_values", ")", ")", "when", "'developer_data_id'", "@developer_data_ids", "<<", "(", "record", "=", "DeveloperDataId", ".", "new", "(", "field_values", ")", ")", "when", "'epo_data'", "@epo_data", "=", "(", "record", "=", "EPO_Data", ".", "new", "(", "field_values", ")", ")", "when", "'file_creator'", "@file_creator", "=", "(", "record", "=", "FileCreator", ".", "new", "(", "field_values", ")", ")", "when", "'device_info'", "@device_infos", "<<", "(", "record", "=", "DeviceInfo", ".", "new", "(", "field_values", ")", ")", "when", "'sensor_settings'", "@sensor_settings", "<<", "(", "record", "=", "SensorSettings", ".", "new", "(", "field_values", ")", ")", "when", "'data_sources'", "@data_sources", "<<", "(", "record", "=", "DataSources", ".", "new", "(", "field_values", ")", ")", "when", "'user_data'", "@user_data", "<<", "(", "record", "=", "UserData", ".", "new", "(", "field_values", ")", ")", "when", "'user_profile'", "@user_profiles", "<<", "(", "record", "=", "UserProfile", ".", "new", "(", "field_values", ")", ")", "when", "'physiological_metrics'", "@physiological_metrics", "<<", "(", "record", "=", "PhysiologicalMetrics", ".", "new", "(", "field_values", ")", ")", "when", "'event'", "@events", "<<", "(", "record", "=", "Event", ".", "new", "(", "field_values", ")", ")", "when", "'session'", "unless", "@cur_lap_records", ".", "empty?", "# Copy selected fields from section to lap.", "lap_field_values", "=", "{", "}", "[", ":timestamp", ",", ":sport", "]", ".", "each", "do", "|", "f", "|", "lap_field_values", "[", "f", "]", "=", "field_values", "[", "f", "]", "if", "field_values", ".", "include?", "(", "f", ")", "end", "# Ensure that all previous records have been assigned to a lap.", "record", "=", "create_new_lap", "(", "lap_field_values", ")", "end", "@num_sessions", "+=", "1", "@sessions", "<<", "(", "record", "=", "Session", ".", "new", "(", "@cur_session_laps", ",", "@lap_counter", ",", "field_values", ")", ")", "@cur_session_laps", "=", "[", "]", "when", "'lap'", "record", "=", "create_new_lap", "(", "field_values", ")", "when", "'record'", "@cur_lap_records", "<<", "(", "record", "=", "Record", ".", "new", "(", "field_values", ")", ")", "@records", "<<", "record", "when", "'hrv'", "@hrv", "<<", "(", "record", "=", "HRV", ".", "new", "(", "field_values", ")", ")", "when", "'heart_rate_zones'", "@heart_rate_zones", "<<", "(", "record", "=", "HeartRateZones", ".", "new", "(", "field_values", ")", ")", "when", "'personal_records'", "@personal_records", "<<", "(", "record", "=", "PersonalRecords", ".", "new", "(", "field_values", ")", ")", "else", "record", "=", "nil", "end", "record", "end"], "docstring": "Check if the current Activity is equal to the passed Activity.\n @param a [Activity] Activity to compare this Activity with.\n @return [TrueClass/FalseClass] true if both Activities are equal,\n otherwise false.\n Create a new FitDataRecord.\n @param record_type [String] Type that identifies the FitDataRecord\n derived class to create.\n @param field_values [Hash] A Hash that provides initial values for\n certain fields of the FitDataRecord.\n @return FitDataRecord", "docstring_tokens": ["Check", "if", "the", "current", "Activity", "is", "equal", "to", "the", "passed", "Activity", "."], "sha": "ec0781abad95c1fea8998640e49873186e9f67d9", "url": "https://github.com/scrapper/fit4ruby/blob/ec0781abad95c1fea8998640e49873186e9f67d9/lib/fit4ruby/Activity.rb#L456-L513", "partition": "test"} {"repo": "scrapper/fit4ruby", "path": "lib/fit4ruby/Session.rb", "func_name": "Fit4Ruby.Session.check", "original_string": "def check(activity)\n unless @first_lap_index\n Log.fatal 'first_lap_index is not set'\n end\n unless @num_laps\n Log.fatal 'num_laps is not set'\n end\n @first_lap_index.upto(@first_lap_index - @num_laps) do |i|\n if (lap = activity.lap[i])\n @laps << lap\n else\n Log.fatal \"Session references lap #{i} which is not contained in \"\n \"the FIT file.\"\n end\n end\n end", "language": "ruby", "code": "def check(activity)\n unless @first_lap_index\n Log.fatal 'first_lap_index is not set'\n end\n unless @num_laps\n Log.fatal 'num_laps is not set'\n end\n @first_lap_index.upto(@first_lap_index - @num_laps) do |i|\n if (lap = activity.lap[i])\n @laps << lap\n else\n Log.fatal \"Session references lap #{i} which is not contained in \"\n \"the FIT file.\"\n end\n end\n end", "code_tokens": ["def", "check", "(", "activity", ")", "unless", "@first_lap_index", "Log", ".", "fatal", "'first_lap_index is not set'", "end", "unless", "@num_laps", "Log", ".", "fatal", "'num_laps is not set'", "end", "@first_lap_index", ".", "upto", "(", "@first_lap_index", "-", "@num_laps", ")", "do", "|", "i", "|", "if", "(", "lap", "=", "activity", ".", "lap", "[", "i", "]", ")", "@laps", "<<", "lap", "else", "Log", ".", "fatal", "\"Session references lap #{i} which is not contained in \"", "\"the FIT file.\"", "end", "end", "end"], "docstring": "Create a new Session object.\n @param laps [Array of Laps] Laps to associate with the Session.\n @param first_lap_index [Fixnum] Index of the first Lap in this Session.\n @param field_values [Hash] Hash that provides initial values for certain\n fields.\n Perform some basic consistency and logical checks on the object. Errors\n are reported via the Log object.", "docstring_tokens": ["Create", "a", "new", "Session", "object", "."], "sha": "ec0781abad95c1fea8998640e49873186e9f67d9", "url": "https://github.com/scrapper/fit4ruby/blob/ec0781abad95c1fea8998640e49873186e9f67d9/lib/fit4ruby/Session.rb#L55-L70", "partition": "test"} {"repo": "scrapper/fit4ruby", "path": "lib/fit4ruby/GlobalFitMessage.rb", "func_name": "Fit4Ruby.GlobalFitMessage.field", "original_string": "def field(number, type, name, opts = {})\n field = Field.new(type, name, opts)\n register_field_by_name(field, name)\n register_field_by_number(field, number)\n end", "language": "ruby", "code": "def field(number, type, name, opts = {})\n field = Field.new(type, name, opts)\n register_field_by_name(field, name)\n register_field_by_number(field, number)\n end", "code_tokens": ["def", "field", "(", "number", ",", "type", ",", "name", ",", "opts", "=", "{", "}", ")", "field", "=", "Field", ".", "new", "(", "type", ",", "name", ",", "opts", ")", "register_field_by_name", "(", "field", ",", "name", ")", "register_field_by_number", "(", "field", ",", "number", ")", "end"], "docstring": "Create a new GlobalFitMessage definition.\n @param name [String] name of the FIT message\n @param number [Fixnum] global message number\n Two GlobalFitMessage objects are considered equal if they have the same\n number, name and list of named fields.\n Define a new Field for this message definition.", "docstring_tokens": ["Create", "a", "new", "GlobalFitMessage", "definition", "."], "sha": "ec0781abad95c1fea8998640e49873186e9f67d9", "url": "https://github.com/scrapper/fit4ruby/blob/ec0781abad95c1fea8998640e49873186e9f67d9/lib/fit4ruby/GlobalFitMessage.rb#L220-L224", "partition": "test"} {"repo": "scrapper/fit4ruby", "path": "lib/fit4ruby/GlobalFitMessage.rb", "func_name": "Fit4Ruby.GlobalFitMessage.alt_field", "original_string": "def alt_field(number, ref_field, &block)\n unless @fields_by_name.include?(ref_field)\n raise \"Unknown ref_field: #{ref_field}\"\n end\n\n field = AltField.new(self, ref_field, &block)\n register_field_by_number(field, number)\n end", "language": "ruby", "code": "def alt_field(number, ref_field, &block)\n unless @fields_by_name.include?(ref_field)\n raise \"Unknown ref_field: #{ref_field}\"\n end\n\n field = AltField.new(self, ref_field, &block)\n register_field_by_number(field, number)\n end", "code_tokens": ["def", "alt_field", "(", "number", ",", "ref_field", ",", "&", "block", ")", "unless", "@fields_by_name", ".", "include?", "(", "ref_field", ")", "raise", "\"Unknown ref_field: #{ref_field}\"", "end", "field", "=", "AltField", ".", "new", "(", "self", ",", "ref_field", ",", "block", ")", "register_field_by_number", "(", "field", ",", "number", ")", "end"], "docstring": "Define a new set of Field alternatives for this message definition.", "docstring_tokens": ["Define", "a", "new", "set", "of", "Field", "alternatives", "for", "this", "message", "definition", "."], "sha": "ec0781abad95c1fea8998640e49873186e9f67d9", "url": "https://github.com/scrapper/fit4ruby/blob/ec0781abad95c1fea8998640e49873186e9f67d9/lib/fit4ruby/GlobalFitMessage.rb#L227-L234", "partition": "test"} {"repo": "plataformatec/mail_form", "path": "lib/mail_form/delivery.rb", "func_name": "MailForm.Delivery.spam?", "original_string": "def spam?\n self.class.mail_captcha.each do |field|\n next if send(field).blank?\n\n if defined?(Rails) && Rails.env.development?\n raise ScriptError, \"The captcha field #{field} was supposed to be blank\"\n else\n return true\n end\n end\n\n false\n end", "language": "ruby", "code": "def spam?\n self.class.mail_captcha.each do |field|\n next if send(field).blank?\n\n if defined?(Rails) && Rails.env.development?\n raise ScriptError, \"The captcha field #{field} was supposed to be blank\"\n else\n return true\n end\n end\n\n false\n end", "code_tokens": ["def", "spam?", "self", ".", "class", ".", "mail_captcha", ".", "each", "do", "|", "field", "|", "next", "if", "send", "(", "field", ")", ".", "blank?", "if", "defined?", "(", "Rails", ")", "&&", "Rails", ".", "env", ".", "development?", "raise", "ScriptError", ",", "\"The captcha field #{field} was supposed to be blank\"", "else", "return", "true", "end", "end", "false", "end"], "docstring": "In development, raises an error if the captcha field is not blank. This is\n is good to remember that the field should be hidden with CSS and shown only\n to robots.\n\n In test and in production, it returns true if all captcha fields are blank,\n returns false otherwise.", "docstring_tokens": ["In", "development", "raises", "an", "error", "if", "the", "captcha", "field", "is", "not", "blank", ".", "This", "is", "is", "good", "to", "remember", "that", "the", "field", "should", "be", "hidden", "with", "CSS", "and", "shown", "only", "to", "robots", "."], "sha": "1cedd14e927c1695d0fe36e983dd001d7bba91b0", "url": "https://github.com/plataformatec/mail_form/blob/1cedd14e927c1695d0fe36e983dd001d7bba91b0/lib/mail_form/delivery.rb#L136-L148", "partition": "test"} {"repo": "plataformatec/mail_form", "path": "lib/mail_form/delivery.rb", "func_name": "MailForm.Delivery.deliver!", "original_string": "def deliver!\n mailer = MailForm::Notifier.contact(self)\n if mailer.respond_to?(:deliver_now)\n mailer.deliver_now\n else\n mailer.deliver\n end\n end", "language": "ruby", "code": "def deliver!\n mailer = MailForm::Notifier.contact(self)\n if mailer.respond_to?(:deliver_now)\n mailer.deliver_now\n else\n mailer.deliver\n end\n end", "code_tokens": ["def", "deliver!", "mailer", "=", "MailForm", "::", "Notifier", ".", "contact", "(", "self", ")", "if", "mailer", ".", "respond_to?", "(", ":deliver_now", ")", "mailer", ".", "deliver_now", "else", "mailer", ".", "deliver", "end", "end"], "docstring": "Deliver the resource without running any validation.", "docstring_tokens": ["Deliver", "the", "resource", "without", "running", "any", "validation", "."], "sha": "1cedd14e927c1695d0fe36e983dd001d7bba91b0", "url": "https://github.com/plataformatec/mail_form/blob/1cedd14e927c1695d0fe36e983dd001d7bba91b0/lib/mail_form/delivery.rb#L159-L166", "partition": "test"} {"repo": "plataformatec/mail_form", "path": "lib/mail_form/delivery.rb", "func_name": "MailForm.Delivery.mail_form_attributes", "original_string": "def mail_form_attributes\n self.class.mail_attributes.each_with_object({}) do |attr, hash|\n hash[attr.to_s] = send(attr)\n end\n end", "language": "ruby", "code": "def mail_form_attributes\n self.class.mail_attributes.each_with_object({}) do |attr, hash|\n hash[attr.to_s] = send(attr)\n end\n end", "code_tokens": ["def", "mail_form_attributes", "self", ".", "class", ".", "mail_attributes", ".", "each_with_object", "(", "{", "}", ")", "do", "|", "attr", ",", "hash", "|", "hash", "[", "attr", ".", "to_s", "]", "=", "send", "(", "attr", ")", "end", "end"], "docstring": "Returns a hash of attributes, according to the attributes existent in\n self.class.mail_attributes.", "docstring_tokens": ["Returns", "a", "hash", "of", "attributes", "according", "to", "the", "attributes", "existent", "in", "self", ".", "class", ".", "mail_attributes", "."], "sha": "1cedd14e927c1695d0fe36e983dd001d7bba91b0", "url": "https://github.com/plataformatec/mail_form/blob/1cedd14e927c1695d0fe36e983dd001d7bba91b0/lib/mail_form/delivery.rb#L170-L174", "partition": "test"} {"repo": "cbeer/solr_wrapper", "path": "lib/solr_wrapper/instance.rb", "func_name": "SolrWrapper.Instance.start", "original_string": "def start\n extract_and_configure\n if config.managed?\n exec('start', p: port, c: config.cloud)\n\n # Wait for solr to start\n unless status\n sleep config.poll_interval\n end\n\n after_start\n end\n end", "language": "ruby", "code": "def start\n extract_and_configure\n if config.managed?\n exec('start', p: port, c: config.cloud)\n\n # Wait for solr to start\n unless status\n sleep config.poll_interval\n end\n\n after_start\n end\n end", "code_tokens": ["def", "start", "extract_and_configure", "if", "config", ".", "managed?", "exec", "(", "'start'", ",", "p", ":", "port", ",", "c", ":", "config", ".", "cloud", ")", "# Wait for solr to start", "unless", "status", "sleep", "config", ".", "poll_interval", "end", "after_start", "end", "end"], "docstring": "Start Solr and wait for it to become available", "docstring_tokens": ["Start", "Solr", "and", "wait", "for", "it", "to", "become", "available"], "sha": "cd17e4908825d7dca3ca2ba8ab5d92dc02eb38c1", "url": "https://github.com/cbeer/solr_wrapper/blob/cd17e4908825d7dca3ca2ba8ab5d92dc02eb38c1/lib/solr_wrapper/instance.rb#L71-L83", "partition": "test"} {"repo": "cbeer/solr_wrapper", "path": "lib/solr_wrapper/instance.rb", "func_name": "SolrWrapper.Instance.restart", "original_string": "def restart\n if config.managed? && started?\n exec('restart', p: port, c: config.cloud)\n end\n end", "language": "ruby", "code": "def restart\n if config.managed? && started?\n exec('restart', p: port, c: config.cloud)\n end\n end", "code_tokens": ["def", "restart", "if", "config", ".", "managed?", "&&", "started?", "exec", "(", "'restart'", ",", "p", ":", "port", ",", "c", ":", "config", ".", "cloud", ")", "end", "end"], "docstring": "Stop Solr and wait for it to finish exiting", "docstring_tokens": ["Stop", "Solr", "and", "wait", "for", "it", "to", "finish", "exiting"], "sha": "cd17e4908825d7dca3ca2ba8ab5d92dc02eb38c1", "url": "https://github.com/cbeer/solr_wrapper/blob/cd17e4908825d7dca3ca2ba8ab5d92dc02eb38c1/lib/solr_wrapper/instance.rb#L96-L100", "partition": "test"} {"repo": "cbeer/solr_wrapper", "path": "lib/solr_wrapper/instance.rb", "func_name": "SolrWrapper.Instance.create", "original_string": "def create(options = {})\n options[:name] ||= SecureRandom.hex\n\n create_options = { p: port }\n create_options[:c] = options[:name] if options[:name]\n create_options[:n] = options[:config_name] if options[:config_name]\n create_options[:d] = options[:dir] if options[:dir]\n\n Retriable.retriable do\n raise \"Not started yet\" unless started?\n end\n\n # short-circuit if we're using persisted data with an existing core/collection\n return if options[:persist] && create_options[:c] && client.exists?(create_options[:c])\n\n exec(\"create\", create_options)\n\n options[:name]\n end", "language": "ruby", "code": "def create(options = {})\n options[:name] ||= SecureRandom.hex\n\n create_options = { p: port }\n create_options[:c] = options[:name] if options[:name]\n create_options[:n] = options[:config_name] if options[:config_name]\n create_options[:d] = options[:dir] if options[:dir]\n\n Retriable.retriable do\n raise \"Not started yet\" unless started?\n end\n\n # short-circuit if we're using persisted data with an existing core/collection\n return if options[:persist] && create_options[:c] && client.exists?(create_options[:c])\n\n exec(\"create\", create_options)\n\n options[:name]\n end", "code_tokens": ["def", "create", "(", "options", "=", "{", "}", ")", "options", "[", ":name", "]", "||=", "SecureRandom", ".", "hex", "create_options", "=", "{", "p", ":", "port", "}", "create_options", "[", ":c", "]", "=", "options", "[", ":name", "]", "if", "options", "[", ":name", "]", "create_options", "[", ":n", "]", "=", "options", "[", ":config_name", "]", "if", "options", "[", ":config_name", "]", "create_options", "[", ":d", "]", "=", "options", "[", ":dir", "]", "if", "options", "[", ":dir", "]", "Retriable", ".", "retriable", "do", "raise", "\"Not started yet\"", "unless", "started?", "end", "# short-circuit if we're using persisted data with an existing core/collection", "return", "if", "options", "[", ":persist", "]", "&&", "create_options", "[", ":c", "]", "&&", "client", ".", "exists?", "(", "create_options", "[", ":c", "]", ")", "exec", "(", "\"create\"", ",", "create_options", ")", "options", "[", ":name", "]", "end"], "docstring": "Create a new collection in solr\n @param [Hash] options\n @option options [String] :name\n @option options [String] :dir", "docstring_tokens": ["Create", "a", "new", "collection", "in", "solr"], "sha": "cd17e4908825d7dca3ca2ba8ab5d92dc02eb38c1", "url": "https://github.com/cbeer/solr_wrapper/blob/cd17e4908825d7dca3ca2ba8ab5d92dc02eb38c1/lib/solr_wrapper/instance.rb#L143-L161", "partition": "test"} {"repo": "cbeer/solr_wrapper", "path": "lib/solr_wrapper/instance.rb", "func_name": "SolrWrapper.Instance.upconfig", "original_string": "def upconfig(options = {})\n options[:name] ||= SecureRandom.hex\n options[:zkhost] ||= zkhost\n\n upconfig_options = { upconfig: true, n: options[:name] }\n upconfig_options[:d] = options[:dir] if options[:dir]\n upconfig_options[:z] = options[:zkhost] if options[:zkhost]\n\n exec 'zk', upconfig_options\n\n options[:name]\n end", "language": "ruby", "code": "def upconfig(options = {})\n options[:name] ||= SecureRandom.hex\n options[:zkhost] ||= zkhost\n\n upconfig_options = { upconfig: true, n: options[:name] }\n upconfig_options[:d] = options[:dir] if options[:dir]\n upconfig_options[:z] = options[:zkhost] if options[:zkhost]\n\n exec 'zk', upconfig_options\n\n options[:name]\n end", "code_tokens": ["def", "upconfig", "(", "options", "=", "{", "}", ")", "options", "[", ":name", "]", "||=", "SecureRandom", ".", "hex", "options", "[", ":zkhost", "]", "||=", "zkhost", "upconfig_options", "=", "{", "upconfig", ":", "true", ",", "n", ":", "options", "[", ":name", "]", "}", "upconfig_options", "[", ":d", "]", "=", "options", "[", ":dir", "]", "if", "options", "[", ":dir", "]", "upconfig_options", "[", ":z", "]", "=", "options", "[", ":zkhost", "]", "if", "options", "[", ":zkhost", "]", "exec", "'zk'", ",", "upconfig_options", "options", "[", ":name", "]", "end"], "docstring": "Update the collection configuration in zookeeper\n @param [Hash] options\n @option options [String] :config_name\n @option options [String] :dir", "docstring_tokens": ["Update", "the", "collection", "configuration", "in", "zookeeper"], "sha": "cd17e4908825d7dca3ca2ba8ab5d92dc02eb38c1", "url": "https://github.com/cbeer/solr_wrapper/blob/cd17e4908825d7dca3ca2ba8ab5d92dc02eb38c1/lib/solr_wrapper/instance.rb#L168-L179", "partition": "test"} {"repo": "cbeer/solr_wrapper", "path": "lib/solr_wrapper/instance.rb", "func_name": "SolrWrapper.Instance.downconfig", "original_string": "def downconfig(options = {})\n options[:name] ||= SecureRandom.hex\n options[:zkhost] ||= zkhost\n\n downconfig_options = { downconfig: true, n: options[:name] }\n downconfig_options[:d] = options[:dir] if options[:dir]\n downconfig_options[:z] = options[:zkhost] if options[:zkhost]\n\n exec 'zk', downconfig_options\n\n options[:name]\n end", "language": "ruby", "code": "def downconfig(options = {})\n options[:name] ||= SecureRandom.hex\n options[:zkhost] ||= zkhost\n\n downconfig_options = { downconfig: true, n: options[:name] }\n downconfig_options[:d] = options[:dir] if options[:dir]\n downconfig_options[:z] = options[:zkhost] if options[:zkhost]\n\n exec 'zk', downconfig_options\n\n options[:name]\n end", "code_tokens": ["def", "downconfig", "(", "options", "=", "{", "}", ")", "options", "[", ":name", "]", "||=", "SecureRandom", ".", "hex", "options", "[", ":zkhost", "]", "||=", "zkhost", "downconfig_options", "=", "{", "downconfig", ":", "true", ",", "n", ":", "options", "[", ":name", "]", "}", "downconfig_options", "[", ":d", "]", "=", "options", "[", ":dir", "]", "if", "options", "[", ":dir", "]", "downconfig_options", "[", ":z", "]", "=", "options", "[", ":zkhost", "]", "if", "options", "[", ":zkhost", "]", "exec", "'zk'", ",", "downconfig_options", "options", "[", ":name", "]", "end"], "docstring": "Copy the collection configuration from zookeeper to a local directory\n @param [Hash] options\n @option options [String] :config_name\n @option options [String] :dir", "docstring_tokens": ["Copy", "the", "collection", "configuration", "from", "zookeeper", "to", "a", "local", "directory"], "sha": "cd17e4908825d7dca3ca2ba8ab5d92dc02eb38c1", "url": "https://github.com/cbeer/solr_wrapper/blob/cd17e4908825d7dca3ca2ba8ab5d92dc02eb38c1/lib/solr_wrapper/instance.rb#L186-L197", "partition": "test"} {"repo": "cbeer/solr_wrapper", "path": "lib/solr_wrapper/instance.rb", "func_name": "SolrWrapper.Instance.with_collection", "original_string": "def with_collection(options = {})\n options = config.collection_options.merge(options)\n return yield if options.empty?\n\n name = create(options)\n begin\n yield name\n ensure\n delete name unless options[:persist]\n end\n end", "language": "ruby", "code": "def with_collection(options = {})\n options = config.collection_options.merge(options)\n return yield if options.empty?\n\n name = create(options)\n begin\n yield name\n ensure\n delete name unless options[:persist]\n end\n end", "code_tokens": ["def", "with_collection", "(", "options", "=", "{", "}", ")", "options", "=", "config", ".", "collection_options", ".", "merge", "(", "options", ")", "return", "yield", "if", "options", ".", "empty?", "name", "=", "create", "(", "options", ")", "begin", "yield", "name", "ensure", "delete", "name", "unless", "options", "[", ":persist", "]", "end", "end"], "docstring": "Create a new collection, run the block, and then clean up the collection\n @param [Hash] options\n @option options [String] :name\n @option options [String] :dir", "docstring_tokens": ["Create", "a", "new", "collection", "run", "the", "block", "and", "then", "clean", "up", "the", "collection"], "sha": "cd17e4908825d7dca3ca2ba8ab5d92dc02eb38c1", "url": "https://github.com/cbeer/solr_wrapper/blob/cd17e4908825d7dca3ca2ba8ab5d92dc02eb38c1/lib/solr_wrapper/instance.rb#L211-L221", "partition": "test"} {"repo": "cbeer/solr_wrapper", "path": "lib/solr_wrapper/instance.rb", "func_name": "SolrWrapper.Instance.clean!", "original_string": "def clean!\n stop\n remove_instance_dir!\n FileUtils.remove_entry(config.download_dir, true) if File.exist?(config.download_dir)\n FileUtils.remove_entry(config.tmp_save_dir, true) if File.exist? config.tmp_save_dir\n checksum_validator.clean!\n FileUtils.remove_entry(config.version_file) if File.exist? config.version_file\n end", "language": "ruby", "code": "def clean!\n stop\n remove_instance_dir!\n FileUtils.remove_entry(config.download_dir, true) if File.exist?(config.download_dir)\n FileUtils.remove_entry(config.tmp_save_dir, true) if File.exist? config.tmp_save_dir\n checksum_validator.clean!\n FileUtils.remove_entry(config.version_file) if File.exist? config.version_file\n end", "code_tokens": ["def", "clean!", "stop", "remove_instance_dir!", "FileUtils", ".", "remove_entry", "(", "config", ".", "download_dir", ",", "true", ")", "if", "File", ".", "exist?", "(", "config", ".", "download_dir", ")", "FileUtils", ".", "remove_entry", "(", "config", ".", "tmp_save_dir", ",", "true", ")", "if", "File", ".", "exist?", "config", ".", "tmp_save_dir", "checksum_validator", ".", "clean!", "FileUtils", ".", "remove_entry", "(", "config", ".", "version_file", ")", "if", "File", ".", "exist?", "config", ".", "version_file", "end"], "docstring": "Clean up any files solr_wrapper may have downloaded", "docstring_tokens": ["Clean", "up", "any", "files", "solr_wrapper", "may", "have", "downloaded"], "sha": "cd17e4908825d7dca3ca2ba8ab5d92dc02eb38c1", "url": "https://github.com/cbeer/solr_wrapper/blob/cd17e4908825d7dca3ca2ba8ab5d92dc02eb38c1/lib/solr_wrapper/instance.rb#L225-L232", "partition": "test"} {"repo": "ryanmelt/qtbindings", "path": "lib/Qt/qtruby4.rb", "func_name": "Qt.MetaInfo.get_signals", "original_string": "def get_signals\n all_signals = []\n current = @klass\n while current != Qt::Base\n meta = Meta[current.name]\n if !meta.nil?\n all_signals.concat meta.signals\n end\n current = current.superclass\n end\n return all_signals\n end", "language": "ruby", "code": "def get_signals\n all_signals = []\n current = @klass\n while current != Qt::Base\n meta = Meta[current.name]\n if !meta.nil?\n all_signals.concat meta.signals\n end\n current = current.superclass\n end\n return all_signals\n end", "code_tokens": ["def", "get_signals", "all_signals", "=", "[", "]", "current", "=", "@klass", "while", "current", "!=", "Qt", "::", "Base", "meta", "=", "Meta", "[", "current", ".", "name", "]", "if", "!", "meta", ".", "nil?", "all_signals", ".", "concat", "meta", ".", "signals", "end", "current", "=", "current", ".", "superclass", "end", "return", "all_signals", "end"], "docstring": "Return a list of signals, including inherited ones", "docstring_tokens": ["Return", "a", "list", "of", "signals", "including", "inherited", "ones"], "sha": "d5047fd54e7686fc9dae3845f0d573d4383dddcc", "url": "https://github.com/ryanmelt/qtbindings/blob/d5047fd54e7686fc9dae3845f0d573d4383dddcc/lib/Qt/qtruby4.rb#L3104-L3115", "partition": "test"} {"repo": "rubymotion/motion-support", "path": "motion/duration.rb", "func_name": "MotionSupport.Duration.+", "original_string": "def +(other)\n if Duration === other\n Duration.new(value + other.value, @parts + other.parts)\n else\n Duration.new(value + other, @parts + [[:seconds, other]])\n end\n end", "language": "ruby", "code": "def +(other)\n if Duration === other\n Duration.new(value + other.value, @parts + other.parts)\n else\n Duration.new(value + other, @parts + [[:seconds, other]])\n end\n end", "code_tokens": ["def", "+", "(", "other", ")", "if", "Duration", "===", "other", "Duration", ".", "new", "(", "value", "+", "other", ".", "value", ",", "@parts", "+", "other", ".", "parts", ")", "else", "Duration", ".", "new", "(", "value", "+", "other", ",", "@parts", "+", "[", "[", ":seconds", ",", "other", "]", "]", ")", "end", "end"], "docstring": "Adds another Duration or a Numeric to this Duration. Numeric values\n are treated as seconds.", "docstring_tokens": ["Adds", "another", "Duration", "or", "a", "Numeric", "to", "this", "Duration", ".", "Numeric", "values", "are", "treated", "as", "seconds", "."], "sha": "eb16b6f8d1c8c15bf01764cee9adf7c0e623ad39", "url": "https://github.com/rubymotion/motion-support/blob/eb16b6f8d1c8c15bf01764cee9adf7c0e623ad39/motion/duration.rb#L15-L21", "partition": "test"} {"repo": "rubymotion/motion-support", "path": "motion/core_ext/date_and_time/calculations.rb", "func_name": "DateAndTime.Calculations.days_to_week_start", "original_string": "def days_to_week_start(start_day = Date.beginning_of_week)\n start_day_number = DAYS_INTO_WEEK[start_day]\n current_day_number = wday != 0 ? wday - 1 : 6\n (current_day_number - start_day_number) % 7\n end", "language": "ruby", "code": "def days_to_week_start(start_day = Date.beginning_of_week)\n start_day_number = DAYS_INTO_WEEK[start_day]\n current_day_number = wday != 0 ? wday - 1 : 6\n (current_day_number - start_day_number) % 7\n end", "code_tokens": ["def", "days_to_week_start", "(", "start_day", "=", "Date", ".", "beginning_of_week", ")", "start_day_number", "=", "DAYS_INTO_WEEK", "[", "start_day", "]", "current_day_number", "=", "wday", "!=", "0", "?", "wday", "-", "1", ":", "6", "(", "current_day_number", "-", "start_day_number", ")", "%", "7", "end"], "docstring": "Returns the number of days to the start of the week on the given day.\n Week is assumed to start on +start_day+, default is\n +Date.beginning_of_week+ or +config.beginning_of_week+ when set.", "docstring_tokens": ["Returns", "the", "number", "of", "days", "to", "the", "start", "of", "the", "week", "on", "the", "given", "day", ".", "Week", "is", "assumed", "to", "start", "on", "+", "start_day", "+", "default", "is", "+", "Date", ".", "beginning_of_week", "+", "or", "+", "config", ".", "beginning_of_week", "+", "when", "set", "."], "sha": "eb16b6f8d1c8c15bf01764cee9adf7c0e623ad39", "url": "https://github.com/rubymotion/motion-support/blob/eb16b6f8d1c8c15bf01764cee9adf7c0e623ad39/motion/core_ext/date_and_time/calculations.rb#L164-L168", "partition": "test"} {"repo": "piotrmurach/tty-progressbar", "path": "lib/tty/progressbar.rb", "func_name": "TTY.ProgressBar.reset", "original_string": "def reset\n @width = 0 if no_width\n @render_period = frequency == 0 ? 0 : 1.0 / frequency\n @current = 0\n @last_render_time = Time.now\n @last_render_width = 0\n @done = false\n @stopped = false\n @start_at = Time.now\n @started = false\n @tokens = {}\n\n @meter.clear\n end", "language": "ruby", "code": "def reset\n @width = 0 if no_width\n @render_period = frequency == 0 ? 0 : 1.0 / frequency\n @current = 0\n @last_render_time = Time.now\n @last_render_width = 0\n @done = false\n @stopped = false\n @start_at = Time.now\n @started = false\n @tokens = {}\n\n @meter.clear\n end", "code_tokens": ["def", "reset", "@width", "=", "0", "if", "no_width", "@render_period", "=", "frequency", "==", "0", "?", "0", ":", "1.0", "/", "frequency", "@current", "=", "0", "@last_render_time", "=", "Time", ".", "now", "@last_render_width", "=", "0", "@done", "=", "false", "@stopped", "=", "false", "@start_at", "=", "Time", ".", "now", "@started", "=", "false", "@tokens", "=", "{", "}", "@meter", ".", "clear", "end"], "docstring": "Create progress bar\n\n @param [String] format\n the tokenized string that displays the output\n\n @param [Hash] options\n @option options [Numeric] :total\n the total number of steps to completion\n @option options [Numeric] :width\n the maximum width for the bars display including\n all formatting options\n @option options [Boolean] :no_width\n true when progression is unknown defaulting to false\n @option options [Boolean] :clear\n whether or not to clear the progress line\n @option options [Boolean] :hide_cursor\n display or hide cursor\n @option options [Object] :output\n the object that responds to print call defaulting to stderr\n @option options [Number] :frequency\n the frequency with which to display bars\n @option options [Number] :interval\n the period for sampling of speed measurement\n\n @api public\n Reset progress to default configuration\n\n @api public", "docstring_tokens": ["Create", "progress", "bar"], "sha": "ccd1499196628085a3ae929a6ae1349db6e16255", "url": "https://github.com/piotrmurach/tty-progressbar/blob/ccd1499196628085a3ae929a6ae1349db6e16255/lib/tty/progressbar.rb#L115-L128", "partition": "test"} {"repo": "piotrmurach/tty-progressbar", "path": "lib/tty/progressbar.rb", "func_name": "TTY.ProgressBar.advance", "original_string": "def advance(progress = 1, tokens = {})\n return if done?\n\n synchronize do\n emit(:progress, progress)\n if progress.respond_to?(:to_hash)\n tokens, progress = progress, 1\n end\n @start_at = Time.now if @current.zero? && !@started\n @current += progress\n @tokens = tokens\n @meter.sample(Time.now, progress)\n\n if !no_width && @current >= total\n finish && return\n end\n\n now = Time.now\n return if (now - @last_render_time) < @render_period\n render\n end\n end", "language": "ruby", "code": "def advance(progress = 1, tokens = {})\n return if done?\n\n synchronize do\n emit(:progress, progress)\n if progress.respond_to?(:to_hash)\n tokens, progress = progress, 1\n end\n @start_at = Time.now if @current.zero? && !@started\n @current += progress\n @tokens = tokens\n @meter.sample(Time.now, progress)\n\n if !no_width && @current >= total\n finish && return\n end\n\n now = Time.now\n return if (now - @last_render_time) < @render_period\n render\n end\n end", "code_tokens": ["def", "advance", "(", "progress", "=", "1", ",", "tokens", "=", "{", "}", ")", "return", "if", "done?", "synchronize", "do", "emit", "(", ":progress", ",", "progress", ")", "if", "progress", ".", "respond_to?", "(", ":to_hash", ")", "tokens", ",", "progress", "=", "progress", ",", "1", "end", "@start_at", "=", "Time", ".", "now", "if", "@current", ".", "zero?", "&&", "!", "@started", "@current", "+=", "progress", "@tokens", "=", "tokens", "@meter", ".", "sample", "(", "Time", ".", "now", ",", "progress", ")", "if", "!", "no_width", "&&", "@current", ">=", "total", "finish", "&&", "return", "end", "now", "=", "Time", ".", "now", "return", "if", "(", "now", "-", "@last_render_time", ")", "<", "@render_period", "render", "end", "end"], "docstring": "Advance the progress bar\n\n @param [Object|Number] progress\n\n @api public", "docstring_tokens": ["Advance", "the", "progress", "bar"], "sha": "ccd1499196628085a3ae929a6ae1349db6e16255", "url": "https://github.com/piotrmurach/tty-progressbar/blob/ccd1499196628085a3ae929a6ae1349db6e16255/lib/tty/progressbar.rb#L158-L179", "partition": "test"} {"repo": "piotrmurach/tty-progressbar", "path": "lib/tty/progressbar.rb", "func_name": "TTY.ProgressBar.iterate", "original_string": "def iterate(collection, progress = 1, &block)\n update(total: collection.count * progress) unless total\n progress_enum = Enumerator.new do |iter|\n collection.each do |elem|\n advance(progress)\n iter.yield(elem)\n end\n end\n block_given? ? progress_enum.each(&block) : progress_enum\n end", "language": "ruby", "code": "def iterate(collection, progress = 1, &block)\n update(total: collection.count * progress) unless total\n progress_enum = Enumerator.new do |iter|\n collection.each do |elem|\n advance(progress)\n iter.yield(elem)\n end\n end\n block_given? ? progress_enum.each(&block) : progress_enum\n end", "code_tokens": ["def", "iterate", "(", "collection", ",", "progress", "=", "1", ",", "&", "block", ")", "update", "(", "total", ":", "collection", ".", "count", "*", "progress", ")", "unless", "total", "progress_enum", "=", "Enumerator", ".", "new", "do", "|", "iter", "|", "collection", ".", "each", "do", "|", "elem", "|", "advance", "(", "progress", ")", "iter", ".", "yield", "(", "elem", ")", "end", "end", "block_given?", "?", "progress_enum", ".", "each", "(", "block", ")", ":", "progress_enum", "end"], "docstring": "Iterate over collection either yielding computation to block\n or provided Enumerator. If the bar's `total` was not set,\n it would be taken from `collection.count`, otherwise previously\n set `total` would be used. This allows using the progressbar\n with infinite, lazy, or slowly-calculated enumerators.\n\n @note\n If `total` is set, iteration will NOT stop after this number of\n iterations, only when provided Enumerable is finished. It may\n be convenient in \"unsure number of iterations\" situations\n (like downloading in chunks, when server may eventually send\n more chunks than predicted), but be careful to not pass infinite\n enumerators without previosly doing `.take(some_finite_number)`\n on them.\n\n @example\n bar.iterate(30.times) { ... }\n\n @param [Enumerable] collection\n the collection to iterate over\n\n @param [Integer] progress\n the amount to move progress bar by\n\n @return [Enumerator]\n\n @api public", "docstring_tokens": ["Iterate", "over", "collection", "either", "yielding", "computation", "to", "block", "or", "provided", "Enumerator", ".", "If", "the", "bar", "s", "total", "was", "not", "set", "it", "would", "be", "taken", "from", "collection", ".", "count", "otherwise", "previously", "set", "total", "would", "be", "used", ".", "This", "allows", "using", "the", "progressbar", "with", "infinite", "lazy", "or", "slowly", "-", "calculated", "enumerators", "."], "sha": "ccd1499196628085a3ae929a6ae1349db6e16255", "url": "https://github.com/piotrmurach/tty-progressbar/blob/ccd1499196628085a3ae929a6ae1349db6e16255/lib/tty/progressbar.rb#L208-L217", "partition": "test"} {"repo": "piotrmurach/tty-progressbar", "path": "lib/tty/progressbar.rb", "func_name": "TTY.ProgressBar.update", "original_string": "def update(options = {})\n synchronize do\n options.each do |name, val|\n if @configuration.respond_to?(\"#{name}=\")\n @configuration.public_send(\"#{name}=\", val)\n end\n end\n end\n end", "language": "ruby", "code": "def update(options = {})\n synchronize do\n options.each do |name, val|\n if @configuration.respond_to?(\"#{name}=\")\n @configuration.public_send(\"#{name}=\", val)\n end\n end\n end\n end", "code_tokens": ["def", "update", "(", "options", "=", "{", "}", ")", "synchronize", "do", "options", ".", "each", "do", "|", "name", ",", "val", "|", "if", "@configuration", ".", "respond_to?", "(", "\"#{name}=\"", ")", "@configuration", ".", "public_send", "(", "\"#{name}=\"", ",", "val", ")", "end", "end", "end", "end"], "docstring": "Update configuration options for this bar\n\n @param [Hash[Symbol]] options\n the configuration options to update\n\n @api public", "docstring_tokens": ["Update", "configuration", "options", "for", "this", "bar"], "sha": "ccd1499196628085a3ae929a6ae1349db6e16255", "url": "https://github.com/piotrmurach/tty-progressbar/blob/ccd1499196628085a3ae929a6ae1349db6e16255/lib/tty/progressbar.rb#L225-L233", "partition": "test"} {"repo": "piotrmurach/tty-progressbar", "path": "lib/tty/progressbar.rb", "func_name": "TTY.ProgressBar.render", "original_string": "def render\n return if done?\n if hide_cursor && @last_render_width == 0 && !(@current >= total)\n write(TTY::Cursor.hide)\n end\n\n if @multibar\n characters_in = @multibar.line_inset(self)\n update(inset: self.class.display_columns(characters_in))\n end\n\n formatted = @formatter.decorate(self, @format)\n @tokens.each do |token, val|\n formatted = formatted.gsub(\":#{token}\", val)\n end\n\n padded = padout(formatted)\n\n write(padded, true)\n\n @last_render_time = Time.now\n @last_render_width = self.class.display_columns(formatted)\n end", "language": "ruby", "code": "def render\n return if done?\n if hide_cursor && @last_render_width == 0 && !(@current >= total)\n write(TTY::Cursor.hide)\n end\n\n if @multibar\n characters_in = @multibar.line_inset(self)\n update(inset: self.class.display_columns(characters_in))\n end\n\n formatted = @formatter.decorate(self, @format)\n @tokens.each do |token, val|\n formatted = formatted.gsub(\":#{token}\", val)\n end\n\n padded = padout(formatted)\n\n write(padded, true)\n\n @last_render_time = Time.now\n @last_render_width = self.class.display_columns(formatted)\n end", "code_tokens": ["def", "render", "return", "if", "done?", "if", "hide_cursor", "&&", "@last_render_width", "==", "0", "&&", "!", "(", "@current", ">=", "total", ")", "write", "(", "TTY", "::", "Cursor", ".", "hide", ")", "end", "if", "@multibar", "characters_in", "=", "@multibar", ".", "line_inset", "(", "self", ")", "update", "(", "inset", ":", "self", ".", "class", ".", "display_columns", "(", "characters_in", ")", ")", "end", "formatted", "=", "@formatter", ".", "decorate", "(", "self", ",", "@format", ")", "@tokens", ".", "each", "do", "|", "token", ",", "val", "|", "formatted", "=", "formatted", ".", "gsub", "(", "\":#{token}\"", ",", "val", ")", "end", "padded", "=", "padout", "(", "formatted", ")", "write", "(", "padded", ",", "true", ")", "@last_render_time", "=", "Time", ".", "now", "@last_render_width", "=", "self", ".", "class", ".", "display_columns", "(", "formatted", ")", "end"], "docstring": "Render progress to the output\n\n @api private", "docstring_tokens": ["Render", "progress", "to", "the", "output"], "sha": "ccd1499196628085a3ae929a6ae1349db6e16255", "url": "https://github.com/piotrmurach/tty-progressbar/blob/ccd1499196628085a3ae929a6ae1349db6e16255/lib/tty/progressbar.rb#L273-L295", "partition": "test"} {"repo": "piotrmurach/tty-progressbar", "path": "lib/tty/progressbar.rb", "func_name": "TTY.ProgressBar.move_to_row", "original_string": "def move_to_row\n if @multibar\n CURSOR_LOCK.synchronize do\n if @first_render\n @row = @multibar.next_row\n yield if block_given?\n output.print \"\\n\"\n @first_render = false\n else\n lines_up = (@multibar.rows + 1) - @row\n output.print TTY::Cursor.save\n output.print TTY::Cursor.up(lines_up)\n yield if block_given?\n output.print TTY::Cursor.restore\n end\n end\n else\n yield if block_given?\n end\n end", "language": "ruby", "code": "def move_to_row\n if @multibar\n CURSOR_LOCK.synchronize do\n if @first_render\n @row = @multibar.next_row\n yield if block_given?\n output.print \"\\n\"\n @first_render = false\n else\n lines_up = (@multibar.rows + 1) - @row\n output.print TTY::Cursor.save\n output.print TTY::Cursor.up(lines_up)\n yield if block_given?\n output.print TTY::Cursor.restore\n end\n end\n else\n yield if block_given?\n end\n end", "code_tokens": ["def", "move_to_row", "if", "@multibar", "CURSOR_LOCK", ".", "synchronize", "do", "if", "@first_render", "@row", "=", "@multibar", ".", "next_row", "yield", "if", "block_given?", "output", ".", "print", "\"\\n\"", "@first_render", "=", "false", "else", "lines_up", "=", "(", "@multibar", ".", "rows", "+", "1", ")", "-", "@row", "output", ".", "print", "TTY", "::", "Cursor", ".", "save", "output", ".", "print", "TTY", "::", "Cursor", ".", "up", "(", "lines_up", ")", "yield", "if", "block_given?", "output", ".", "print", "TTY", "::", "Cursor", ".", "restore", "end", "end", "else", "yield", "if", "block_given?", "end", "end"], "docstring": "Move cursor to a row of the current bar if the bar is rendered\n under a multibar. Otherwise, do not move and yield on current row.\n\n @api private", "docstring_tokens": ["Move", "cursor", "to", "a", "row", "of", "the", "current", "bar", "if", "the", "bar", "is", "rendered", "under", "a", "multibar", ".", "Otherwise", "do", "not", "move", "and", "yield", "on", "current", "row", "."], "sha": "ccd1499196628085a3ae929a6ae1349db6e16255", "url": "https://github.com/piotrmurach/tty-progressbar/blob/ccd1499196628085a3ae929a6ae1349db6e16255/lib/tty/progressbar.rb#L301-L320", "partition": "test"} {"repo": "piotrmurach/tty-progressbar", "path": "lib/tty/progressbar.rb", "func_name": "TTY.ProgressBar.write", "original_string": "def write(data, clear_first = false)\n return unless tty? # write only to terminal\n\n move_to_row do\n output.print(TTY::Cursor.column(1)) if clear_first\n characters_in = @multibar.line_inset(self) if @multibar\n output.print(\"#{characters_in}#{data}\")\n output.flush\n end\n end", "language": "ruby", "code": "def write(data, clear_first = false)\n return unless tty? # write only to terminal\n\n move_to_row do\n output.print(TTY::Cursor.column(1)) if clear_first\n characters_in = @multibar.line_inset(self) if @multibar\n output.print(\"#{characters_in}#{data}\")\n output.flush\n end\n end", "code_tokens": ["def", "write", "(", "data", ",", "clear_first", "=", "false", ")", "return", "unless", "tty?", "# write only to terminal", "move_to_row", "do", "output", ".", "print", "(", "TTY", "::", "Cursor", ".", "column", "(", "1", ")", ")", "if", "clear_first", "characters_in", "=", "@multibar", ".", "line_inset", "(", "self", ")", "if", "@multibar", "output", ".", "print", "(", "\"#{characters_in}#{data}\"", ")", "output", ".", "flush", "end", "end"], "docstring": "Write out to the output\n\n @param [String] data\n\n @api private", "docstring_tokens": ["Write", "out", "to", "the", "output"], "sha": "ccd1499196628085a3ae929a6ae1349db6e16255", "url": "https://github.com/piotrmurach/tty-progressbar/blob/ccd1499196628085a3ae929a6ae1349db6e16255/lib/tty/progressbar.rb#L327-L336", "partition": "test"} {"repo": "piotrmurach/tty-progressbar", "path": "lib/tty/progressbar.rb", "func_name": "TTY.ProgressBar.finish", "original_string": "def finish\n return if done?\n @current = total unless no_width\n render\n clear ? clear_line : write(\"\\n\", false)\n ensure\n @meter.clear\n @done = true\n\n # reenable cursor if it is turned off\n if hide_cursor && @last_render_width != 0\n write(TTY::Cursor.show, false)\n end\n\n emit(:done)\n end", "language": "ruby", "code": "def finish\n return if done?\n @current = total unless no_width\n render\n clear ? clear_line : write(\"\\n\", false)\n ensure\n @meter.clear\n @done = true\n\n # reenable cursor if it is turned off\n if hide_cursor && @last_render_width != 0\n write(TTY::Cursor.show, false)\n end\n\n emit(:done)\n end", "code_tokens": ["def", "finish", "return", "if", "done?", "@current", "=", "total", "unless", "no_width", "render", "clear", "?", "clear_line", ":", "write", "(", "\"\\n\"", ",", "false", ")", "ensure", "@meter", ".", "clear", "@done", "=", "true", "# reenable cursor if it is turned off", "if", "hide_cursor", "&&", "@last_render_width", "!=", "0", "write", "(", "TTY", "::", "Cursor", ".", "show", ",", "false", ")", "end", "emit", "(", ":done", ")", "end"], "docstring": "End the progress\n\n @api public", "docstring_tokens": ["End", "the", "progress"], "sha": "ccd1499196628085a3ae929a6ae1349db6e16255", "url": "https://github.com/piotrmurach/tty-progressbar/blob/ccd1499196628085a3ae929a6ae1349db6e16255/lib/tty/progressbar.rb#L357-L372", "partition": "test"} {"repo": "piotrmurach/tty-progressbar", "path": "lib/tty/progressbar.rb", "func_name": "TTY.ProgressBar.stop", "original_string": "def stop\n # reenable cursor if it is turned off\n if hide_cursor && @last_render_width != 0\n write(TTY::Cursor.show, false)\n end\n return if done?\n render\n clear ? clear_line : write(\"\\n\", false)\n ensure\n @meter.clear\n @stopped = true\n emit(:stopped)\n end", "language": "ruby", "code": "def stop\n # reenable cursor if it is turned off\n if hide_cursor && @last_render_width != 0\n write(TTY::Cursor.show, false)\n end\n return if done?\n render\n clear ? clear_line : write(\"\\n\", false)\n ensure\n @meter.clear\n @stopped = true\n emit(:stopped)\n end", "code_tokens": ["def", "stop", "# reenable cursor if it is turned off", "if", "hide_cursor", "&&", "@last_render_width", "!=", "0", "write", "(", "TTY", "::", "Cursor", ".", "show", ",", "false", ")", "end", "return", "if", "done?", "render", "clear", "?", "clear_line", ":", "write", "(", "\"\\n\"", ",", "false", ")", "ensure", "@meter", ".", "clear", "@stopped", "=", "true", "emit", "(", ":stopped", ")", "end"], "docstring": "Stop and cancel the progress at the current position\n\n @api public", "docstring_tokens": ["Stop", "and", "cancel", "the", "progress", "at", "the", "current", "position"], "sha": "ccd1499196628085a3ae929a6ae1349db6e16255", "url": "https://github.com/piotrmurach/tty-progressbar/blob/ccd1499196628085a3ae929a6ae1349db6e16255/lib/tty/progressbar.rb#L377-L389", "partition": "test"} {"repo": "piotrmurach/tty-progressbar", "path": "lib/tty/progressbar.rb", "func_name": "TTY.ProgressBar.log", "original_string": "def log(message)\n sanitized_message = message.gsub(/\\r|\\n/, ' ')\n if done?\n write(sanitized_message + \"\\n\", false)\n return\n end\n sanitized_message = padout(sanitized_message)\n\n write(sanitized_message + \"\\n\", true)\n render\n end", "language": "ruby", "code": "def log(message)\n sanitized_message = message.gsub(/\\r|\\n/, ' ')\n if done?\n write(sanitized_message + \"\\n\", false)\n return\n end\n sanitized_message = padout(sanitized_message)\n\n write(sanitized_message + \"\\n\", true)\n render\n end", "code_tokens": ["def", "log", "(", "message", ")", "sanitized_message", "=", "message", ".", "gsub", "(", "/", "\\r", "\\n", "/", ",", "' '", ")", "if", "done?", "write", "(", "sanitized_message", "+", "\"\\n\"", ",", "false", ")", "return", "end", "sanitized_message", "=", "padout", "(", "sanitized_message", ")", "write", "(", "sanitized_message", "+", "\"\\n\"", ",", "true", ")", "render", "end"], "docstring": "Log message above the current progress bar\n\n @param [String] message\n the message to log out\n\n @api public", "docstring_tokens": ["Log", "message", "above", "the", "current", "progress", "bar"], "sha": "ccd1499196628085a3ae929a6ae1349db6e16255", "url": "https://github.com/piotrmurach/tty-progressbar/blob/ccd1499196628085a3ae929a6ae1349db6e16255/lib/tty/progressbar.rb#L447-L457", "partition": "test"} {"repo": "piotrmurach/tty-progressbar", "path": "lib/tty/progressbar.rb", "func_name": "TTY.ProgressBar.padout", "original_string": "def padout(message)\n message_length = self.class.display_columns(message)\n\n if @last_render_width > message_length\n remaining_width = @last_render_width - message_length\n message += ' ' * remaining_width\n end\n message\n end", "language": "ruby", "code": "def padout(message)\n message_length = self.class.display_columns(message)\n\n if @last_render_width > message_length\n remaining_width = @last_render_width - message_length\n message += ' ' * remaining_width\n end\n message\n end", "code_tokens": ["def", "padout", "(", "message", ")", "message_length", "=", "self", ".", "class", ".", "display_columns", "(", "message", ")", "if", "@last_render_width", ">", "message_length", "remaining_width", "=", "@last_render_width", "-", "message_length", "message", "+=", "' '", "*", "remaining_width", "end", "message", "end"], "docstring": "Pad message out with spaces\n\n @api private", "docstring_tokens": ["Pad", "message", "out", "with", "spaces"], "sha": "ccd1499196628085a3ae929a6ae1349db6e16255", "url": "https://github.com/piotrmurach/tty-progressbar/blob/ccd1499196628085a3ae929a6ae1349db6e16255/lib/tty/progressbar.rb#L490-L498", "partition": "test"} {"repo": "tobi/delayed_job", "path": "lib/delayed/job.rb", "func_name": "Delayed.Job.lock_exclusively!", "original_string": "def lock_exclusively!(max_run_time, worker = worker_name)\n now = self.class.db_time_now\n affected_rows = if locked_by != worker\n # We don't own this job so we will update the locked_by name and the locked_at\n self.class.update_all([\"locked_at = ?, locked_by = ?\", now, worker], [\"id = ? and (locked_at is null or locked_at < ?)\", id, (now - max_run_time.to_i)])\n else\n # We already own this job, this may happen if the job queue crashes.\n # Simply resume and update the locked_at\n self.class.update_all([\"locked_at = ?\", now], [\"id = ? and locked_by = ?\", id, worker])\n end\n if affected_rows == 1\n self.locked_at = now\n self.locked_by = worker\n return true\n else\n return false\n end\n end", "language": "ruby", "code": "def lock_exclusively!(max_run_time, worker = worker_name)\n now = self.class.db_time_now\n affected_rows = if locked_by != worker\n # We don't own this job so we will update the locked_by name and the locked_at\n self.class.update_all([\"locked_at = ?, locked_by = ?\", now, worker], [\"id = ? and (locked_at is null or locked_at < ?)\", id, (now - max_run_time.to_i)])\n else\n # We already own this job, this may happen if the job queue crashes.\n # Simply resume and update the locked_at\n self.class.update_all([\"locked_at = ?\", now], [\"id = ? and locked_by = ?\", id, worker])\n end\n if affected_rows == 1\n self.locked_at = now\n self.locked_by = worker\n return true\n else\n return false\n end\n end", "code_tokens": ["def", "lock_exclusively!", "(", "max_run_time", ",", "worker", "=", "worker_name", ")", "now", "=", "self", ".", "class", ".", "db_time_now", "affected_rows", "=", "if", "locked_by", "!=", "worker", "# We don't own this job so we will update the locked_by name and the locked_at", "self", ".", "class", ".", "update_all", "(", "[", "\"locked_at = ?, locked_by = ?\"", ",", "now", ",", "worker", "]", ",", "[", "\"id = ? and (locked_at is null or locked_at < ?)\"", ",", "id", ",", "(", "now", "-", "max_run_time", ".", "to_i", ")", "]", ")", "else", "# We already own this job, this may happen if the job queue crashes.", "# Simply resume and update the locked_at", "self", ".", "class", ".", "update_all", "(", "[", "\"locked_at = ?\"", ",", "now", "]", ",", "[", "\"id = ? and locked_by = ?\"", ",", "id", ",", "worker", "]", ")", "end", "if", "affected_rows", "==", "1", "self", ".", "locked_at", "=", "now", "self", ".", "locked_by", "=", "worker", "return", "true", "else", "return", "false", "end", "end"], "docstring": "Lock this job for this worker.\n Returns true if we have the lock, false otherwise.", "docstring_tokens": ["Lock", "this", "job", "for", "this", "worker", ".", "Returns", "true", "if", "we", "have", "the", "lock", "false", "otherwise", "."], "sha": "719b628bdd54566f80ae3a99c4a02dd39d386c07", "url": "https://github.com/tobi/delayed_job/blob/719b628bdd54566f80ae3a99c4a02dd39d386c07/lib/delayed/job.rb#L164-L181", "partition": "test"} {"repo": "theZacAttacks/elephrame", "path": "lib/elephrame/mix/tracery.rb", "func_name": "Elephrame.Trace.setup_tracery", "original_string": "def setup_tracery dir_path\n raise \"Provided path not a directory\" unless Dir.exist?(dir_path)\n\n @grammar = {}\n Dir.open(dir_path) do |dir|\n dir.each do |file|\n # skip our current and parent dir\n next if file =~ /^\\.\\.?$/\n\n # read the rule file into the files hash\n @grammar[file.split('.').first] =\n createGrammar(JSON.parse(File.read(\"#{dir_path}/#{file}\")))\n end\n end\n\n # go ahead and makes a default mention-handler\n # if we have a reply rule file\n unless @grammar['reply'].nil?\n on_reply { |bot|\n bot.reply_with_mentions('#default#', rules: 'reply')\n }\n end\n end", "language": "ruby", "code": "def setup_tracery dir_path\n raise \"Provided path not a directory\" unless Dir.exist?(dir_path)\n\n @grammar = {}\n Dir.open(dir_path) do |dir|\n dir.each do |file|\n # skip our current and parent dir\n next if file =~ /^\\.\\.?$/\n\n # read the rule file into the files hash\n @grammar[file.split('.').first] =\n createGrammar(JSON.parse(File.read(\"#{dir_path}/#{file}\")))\n end\n end\n\n # go ahead and makes a default mention-handler\n # if we have a reply rule file\n unless @grammar['reply'].nil?\n on_reply { |bot|\n bot.reply_with_mentions('#default#', rules: 'reply')\n }\n end\n end", "code_tokens": ["def", "setup_tracery", "dir_path", "raise", "\"Provided path not a directory\"", "unless", "Dir", ".", "exist?", "(", "dir_path", ")", "@grammar", "=", "{", "}", "Dir", ".", "open", "(", "dir_path", ")", "do", "|", "dir", "|", "dir", ".", "each", "do", "|", "file", "|", "# skip our current and parent dir", "next", "if", "file", "=~", "/", "\\.", "\\.", "/", "# read the rule file into the files hash", "@grammar", "[", "file", ".", "split", "(", "'.'", ")", ".", "first", "]", "=", "createGrammar", "(", "JSON", ".", "parse", "(", "File", ".", "read", "(", "\"#{dir_path}/#{file}\"", ")", ")", ")", "end", "end", "# go ahead and makes a default mention-handler", "# if we have a reply rule file", "unless", "@grammar", "[", "'reply'", "]", ".", "nil?", "on_reply", "{", "|", "bot", "|", "bot", ".", "reply_with_mentions", "(", "'#default#'", ",", "rules", ":", "'reply'", ")", "}", "end", "end"], "docstring": "loads all of our tracery files into our +files+ hash\n if a file is named 'default' then we load that into +grammar+\n\n @param dir [String] path to the directory containing the tracery rules", "docstring_tokens": ["loads", "all", "of", "our", "tracery", "files", "into", "our", "+", "files", "+", "hash", "if", "a", "file", "is", "named", "default", "then", "we", "load", "that", "into", "+", "grammar", "+"], "sha": "81477e51e5922c74cb379e7ce0529fec16eb37b9", "url": "https://github.com/theZacAttacks/elephrame/blob/81477e51e5922c74cb379e7ce0529fec16eb37b9/lib/elephrame/mix/tracery.rb#L17-L39", "partition": "test"} {"repo": "theZacAttacks/elephrame", "path": "lib/elephrame/mix/tracery.rb", "func_name": "Elephrame.Trace.expand_and_post", "original_string": "def expand_and_post(text, *options)\n opts = Hash[*options]\n rules = opts.fetch(:rules, 'default')\n actually_post(@grammar[rules].flatten(text),\n **opts.reject {|k|\n k == :rules\n })\n end", "language": "ruby", "code": "def expand_and_post(text, *options)\n opts = Hash[*options]\n rules = opts.fetch(:rules, 'default')\n actually_post(@grammar[rules].flatten(text),\n **opts.reject {|k|\n k == :rules\n })\n end", "code_tokens": ["def", "expand_and_post", "(", "text", ",", "*", "options", ")", "opts", "=", "Hash", "[", "options", "]", "rules", "=", "opts", ".", "fetch", "(", ":rules", ",", "'default'", ")", "actually_post", "(", "@grammar", "[", "rules", "]", ".", "flatten", "(", "text", ")", ",", "**", "opts", ".", "reject", "{", "|", "k", "|", "k", "==", ":rules", "}", ")", "end"], "docstring": "a shortcut fuction for expanding text with tracery before posting\n\n @param text [String] the tracery text to expand before posting\n @param options [Hash] a hash of arguments to pass to post\n @option options rules [String] the grammar rules to load\n @option options visibility [String] visibility level\n @option options spoiler [String] text to use as content warning\n @option options reply_id [String] id of post to reply to\n @option options hide_media [Bool] should we hide media?\n @option options media [Array] array of file paths", "docstring_tokens": ["a", "shortcut", "fuction", "for", "expanding", "text", "with", "tracery", "before", "posting"], "sha": "81477e51e5922c74cb379e7ce0529fec16eb37b9", "url": "https://github.com/theZacAttacks/elephrame/blob/81477e51e5922c74cb379e7ce0529fec16eb37b9/lib/elephrame/mix/tracery.rb#L54-L61", "partition": "test"} {"repo": "theZacAttacks/elephrame", "path": "lib/elephrame/streaming/interaction.rb", "func_name": "Elephrame.AllInteractions.run_interact", "original_string": "def run_interact\n @streamer.user do |update|\n if update.kind_of? Mastodon::Notification\n \n case update.type\n \n when 'mention'\n\n # this makes it so .content calls strip instead \n update.status.class.module_eval { alias_method :content, :strip } if @strip_html\n store_mention_data update.status\n @on_reply.call(self, update.status) unless @on_reply.nil?\n \n when 'reblog'\n @on_boost.call(self, update) unless @on_boost.nil?\n \n when 'favourite'\n @on_fave.call(self, update) unless @on_fave.nil?\n \n when 'follow'\n @on_follow.call(self, update) unless @on_follow.nil?\n \n end\n end\n end\n end", "language": "ruby", "code": "def run_interact\n @streamer.user do |update|\n if update.kind_of? Mastodon::Notification\n \n case update.type\n \n when 'mention'\n\n # this makes it so .content calls strip instead \n update.status.class.module_eval { alias_method :content, :strip } if @strip_html\n store_mention_data update.status\n @on_reply.call(self, update.status) unless @on_reply.nil?\n \n when 'reblog'\n @on_boost.call(self, update) unless @on_boost.nil?\n \n when 'favourite'\n @on_fave.call(self, update) unless @on_fave.nil?\n \n when 'follow'\n @on_follow.call(self, update) unless @on_follow.nil?\n \n end\n end\n end\n end", "code_tokens": ["def", "run_interact", "@streamer", ".", "user", "do", "|", "update", "|", "if", "update", ".", "kind_of?", "Mastodon", "::", "Notification", "case", "update", ".", "type", "when", "'mention'", "# this makes it so .content calls strip instead ", "update", ".", "status", ".", "class", ".", "module_eval", "{", "alias_method", ":content", ",", ":strip", "}", "if", "@strip_html", "store_mention_data", "update", ".", "status", "@on_reply", ".", "call", "(", "self", ",", "update", ".", "status", ")", "unless", "@on_reply", ".", "nil?", "when", "'reblog'", "@on_boost", ".", "call", "(", "self", ",", "update", ")", "unless", "@on_boost", ".", "nil?", "when", "'favourite'", "@on_fave", ".", "call", "(", "self", ",", "update", ")", "unless", "@on_fave", ".", "nil?", "when", "'follow'", "@on_follow", ".", "call", "(", "self", ",", "update", ")", "unless", "@on_follow", ".", "nil?", "end", "end", "end", "end"], "docstring": "Starts a loop that checks for any notifications for the authenticated\n user, running the appropriate stored proc when needed", "docstring_tokens": ["Starts", "a", "loop", "that", "checks", "for", "any", "notifications", "for", "the", "authenticated", "user", "running", "the", "appropriate", "stored", "proc", "when", "needed"], "sha": "81477e51e5922c74cb379e7ce0529fec16eb37b9", "url": "https://github.com/theZacAttacks/elephrame/blob/81477e51e5922c74cb379e7ce0529fec16eb37b9/lib/elephrame/streaming/interaction.rb#L31-L56", "partition": "test"} {"repo": "theZacAttacks/elephrame", "path": "lib/elephrame/streaming/reply.rb", "func_name": "Elephrame.Reply.reply", "original_string": "def reply(text, *options)\n options = Hash[*options]\n \n post(\"@#{@mention_data[:account].acct} #{text}\",\n **@mention_data.merge(options).reject { |k|\n k == :mentions or k == :account\n })\n end", "language": "ruby", "code": "def reply(text, *options)\n options = Hash[*options]\n \n post(\"@#{@mention_data[:account].acct} #{text}\",\n **@mention_data.merge(options).reject { |k|\n k == :mentions or k == :account\n })\n end", "code_tokens": ["def", "reply", "(", "text", ",", "*", "options", ")", "options", "=", "Hash", "[", "options", "]", "post", "(", "\"@#{@mention_data[:account].acct} #{text}\"", ",", "**", "@mention_data", ".", "merge", "(", "options", ")", ".", "reject", "{", "|", "k", "|", "k", "==", ":mentions", "or", "k", "==", ":account", "}", ")", "end"], "docstring": "Replies to the last mention the bot recieved using the mention's\n visibility and spoiler with +text+\n\n Automatically includes an @ for the account that mentioned the bot.\n Does not include any other @. See +reply_with_mentions+ if you want\n to automatically include all mentions\n\n @param text [String] text to post as a reply\n @param options [Hash] a hash of arguments to pass to post, overrides\n duplicating settings from last mention", "docstring_tokens": ["Replies", "to", "the", "last", "mention", "the", "bot", "recieved", "using", "the", "mention", "s", "visibility", "and", "spoiler", "with", "+", "text", "+"], "sha": "81477e51e5922c74cb379e7ce0529fec16eb37b9", "url": "https://github.com/theZacAttacks/elephrame/blob/81477e51e5922c74cb379e7ce0529fec16eb37b9/lib/elephrame/streaming/reply.rb#L24-L31", "partition": "test"} {"repo": "theZacAttacks/elephrame", "path": "lib/elephrame/streaming/reply.rb", "func_name": "Elephrame.Reply.run_reply", "original_string": "def run_reply\n @streamer.user do |update|\n next unless update.kind_of? Mastodon::Notification and update.type == 'mention'\n\n # this makes it so .content calls strip instead \n update.status.class.module_eval { alias_method :content, :strip } if @strip_html\n\n store_mention_data update.status\n \n if block_given?\n yield(self, update.status)\n else\n @on_reply.call(self, update.status)\n end\n end\n end", "language": "ruby", "code": "def run_reply\n @streamer.user do |update|\n next unless update.kind_of? Mastodon::Notification and update.type == 'mention'\n\n # this makes it so .content calls strip instead \n update.status.class.module_eval { alias_method :content, :strip } if @strip_html\n\n store_mention_data update.status\n \n if block_given?\n yield(self, update.status)\n else\n @on_reply.call(self, update.status)\n end\n end\n end", "code_tokens": ["def", "run_reply", "@streamer", ".", "user", "do", "|", "update", "|", "next", "unless", "update", ".", "kind_of?", "Mastodon", "::", "Notification", "and", "update", ".", "type", "==", "'mention'", "# this makes it so .content calls strip instead ", "update", ".", "status", ".", "class", ".", "module_eval", "{", "alias_method", ":content", ",", ":strip", "}", "if", "@strip_html", "store_mention_data", "update", ".", "status", "if", "block_given?", "yield", "(", "self", ",", "update", ".", "status", ")", "else", "@on_reply", ".", "call", "(", "self", ",", "update", ".", "status", ")", "end", "end", "end"], "docstring": "Starts a loop that checks for mentions from the authenticated user account\n running a supplied block or, if a block is not provided, on_reply", "docstring_tokens": ["Starts", "a", "loop", "that", "checks", "for", "mentions", "from", "the", "authenticated", "user", "account", "running", "a", "supplied", "block", "or", "if", "a", "block", "is", "not", "provided", "on_reply"], "sha": "81477e51e5922c74cb379e7ce0529fec16eb37b9", "url": "https://github.com/theZacAttacks/elephrame/blob/81477e51e5922c74cb379e7ce0529fec16eb37b9/lib/elephrame/streaming/reply.rb#L56-L71", "partition": "test"} {"repo": "theZacAttacks/elephrame", "path": "lib/elephrame/streaming/reply.rb", "func_name": "Elephrame.Reply.store_mention_data", "original_string": "def store_mention_data(mention)\n @mention_data = {\n reply_id: mention.id,\n visibility: mention.visibility,\n spoiler: mention.spoiler_text,\n hide_media: mention.sensitive?,\n mentions: mention.mentions,\n account: mention.account\n }\n end", "language": "ruby", "code": "def store_mention_data(mention)\n @mention_data = {\n reply_id: mention.id,\n visibility: mention.visibility,\n spoiler: mention.spoiler_text,\n hide_media: mention.sensitive?,\n mentions: mention.mentions,\n account: mention.account\n }\n end", "code_tokens": ["def", "store_mention_data", "(", "mention", ")", "@mention_data", "=", "{", "reply_id", ":", "mention", ".", "id", ",", "visibility", ":", "mention", ".", "visibility", ",", "spoiler", ":", "mention", ".", "spoiler_text", ",", "hide_media", ":", "mention", ".", "sensitive?", ",", "mentions", ":", "mention", ".", "mentions", ",", "account", ":", "mention", ".", "account", "}", "end"], "docstring": "Stores select data about a post into a hash for later use\n\n @param mention [Mastodon::Status] the most recent mention the bot received", "docstring_tokens": ["Stores", "select", "data", "about", "a", "post", "into", "a", "hash", "for", "later", "use"], "sha": "81477e51e5922c74cb379e7ce0529fec16eb37b9", "url": "https://github.com/theZacAttacks/elephrame/blob/81477e51e5922c74cb379e7ce0529fec16eb37b9/lib/elephrame/streaming/reply.rb#L82-L91", "partition": "test"} {"repo": "theZacAttacks/elephrame", "path": "lib/elephrame/streaming/streaming.rb", "func_name": "Elephrame.Streaming.setup_streaming", "original_string": "def setup_streaming\n stream_uri = @client.instance()\n .attributes['urls']['streaming_api'].gsub(/^wss?/, 'https')\n @streamer = Mastodon::Streaming::Client.new(base_url: stream_uri,\n bearer_token: ENV['TOKEN'])\n end", "language": "ruby", "code": "def setup_streaming\n stream_uri = @client.instance()\n .attributes['urls']['streaming_api'].gsub(/^wss?/, 'https')\n @streamer = Mastodon::Streaming::Client.new(base_url: stream_uri,\n bearer_token: ENV['TOKEN'])\n end", "code_tokens": ["def", "setup_streaming", "stream_uri", "=", "@client", ".", "instance", "(", ")", ".", "attributes", "[", "'urls'", "]", "[", "'streaming_api'", "]", ".", "gsub", "(", "/", "/", ",", "'https'", ")", "@streamer", "=", "Mastodon", "::", "Streaming", "::", "Client", ".", "new", "(", "base_url", ":", "stream_uri", ",", "bearer_token", ":", "ENV", "[", "'TOKEN'", "]", ")", "end"], "docstring": "Creates the stream client", "docstring_tokens": ["Creates", "the", "stream", "client"], "sha": "81477e51e5922c74cb379e7ce0529fec16eb37b9", "url": "https://github.com/theZacAttacks/elephrame/blob/81477e51e5922c74cb379e7ce0529fec16eb37b9/lib/elephrame/streaming/streaming.rb#L13-L18", "partition": "test"} {"repo": "poise/poise-service", "path": "lib/poise_service/utils.rb", "func_name": "PoiseService.Utils.parse_service_name", "original_string": "def parse_service_name(path)\n parts = Pathname.new(path).each_filename.to_a.reverse!\n # Find the last segment not in common segments, fall back to the last segment.\n parts.find {|seg| !COMMON_SEGMENTS[seg] } || parts.first\n end", "language": "ruby", "code": "def parse_service_name(path)\n parts = Pathname.new(path).each_filename.to_a.reverse!\n # Find the last segment not in common segments, fall back to the last segment.\n parts.find {|seg| !COMMON_SEGMENTS[seg] } || parts.first\n end", "code_tokens": ["def", "parse_service_name", "(", "path", ")", "parts", "=", "Pathname", ".", "new", "(", "path", ")", ".", "each_filename", ".", "to_a", ".", "reverse!", "# Find the last segment not in common segments, fall back to the last segment.", "parts", ".", "find", "{", "|", "seg", "|", "!", "COMMON_SEGMENTS", "[", "seg", "]", "}", "||", "parts", ".", "first", "end"], "docstring": "Parse the service name from a path. Look at the last component of the\n path, ignoring some common names.\n\n @param path [String] Path to parse.\n @return [String]\n @example\n attribute(:service_name, kind_of: String, default: lazy { PoiseService::Utils.parse_service_name(path) })", "docstring_tokens": ["Parse", "the", "service", "name", "from", "a", "path", ".", "Look", "at", "the", "last", "component", "of", "the", "path", "ignoring", "some", "common", "names", "."], "sha": "ea1d3c8fa780a22541cecfc3af96c81b87d0fabb", "url": "https://github.com/poise/poise-service/blob/ea1d3c8fa780a22541cecfc3af96c81b87d0fabb/lib/poise_service/utils.rb#L39-L43", "partition": "test"} {"repo": "rocketjob/net_tcp_client", "path": "lib/net/tcp_client/tcp_client.rb", "func_name": "Net.TCPClient.connect", "original_string": "def connect\n start_time = Time.now\n retries = 0\n close\n\n # Number of times to try\n begin\n connect_to_server(servers, policy)\n logger.info(message: \"Connected to #{address}\", duration: (Time.now - start_time) * 1000) if respond_to?(:logger)\n rescue ConnectionFailure, ConnectionTimeout => exception\n cause = exception.is_a?(ConnectionTimeout) ? exception : exception.cause\n # Retry-able?\n if self.class.reconnect_on_errors.include?(cause.class) && (retries < connect_retry_count.to_i)\n retries += 1\n logger.warn \"#connect Failed to connect to any of #{servers.join(',')}. Sleeping:#{connect_retry_interval}s. Retry: #{retries}\" if respond_to?(:logger)\n sleep(connect_retry_interval)\n retry\n else\n message = \"#connect Failed to connect to any of #{servers.join(',')} after #{retries} retries. #{exception.class}: #{exception.message}\"\n logger.benchmark_error(message, exception: exception, duration: (Time.now - start_time)) if respond_to?(:logger)\n raise ConnectionFailure.new(message, address.to_s, cause)\n end\n end\n end", "language": "ruby", "code": "def connect\n start_time = Time.now\n retries = 0\n close\n\n # Number of times to try\n begin\n connect_to_server(servers, policy)\n logger.info(message: \"Connected to #{address}\", duration: (Time.now - start_time) * 1000) if respond_to?(:logger)\n rescue ConnectionFailure, ConnectionTimeout => exception\n cause = exception.is_a?(ConnectionTimeout) ? exception : exception.cause\n # Retry-able?\n if self.class.reconnect_on_errors.include?(cause.class) && (retries < connect_retry_count.to_i)\n retries += 1\n logger.warn \"#connect Failed to connect to any of #{servers.join(',')}. Sleeping:#{connect_retry_interval}s. Retry: #{retries}\" if respond_to?(:logger)\n sleep(connect_retry_interval)\n retry\n else\n message = \"#connect Failed to connect to any of #{servers.join(',')} after #{retries} retries. #{exception.class}: #{exception.message}\"\n logger.benchmark_error(message, exception: exception, duration: (Time.now - start_time)) if respond_to?(:logger)\n raise ConnectionFailure.new(message, address.to_s, cause)\n end\n end\n end", "code_tokens": ["def", "connect", "start_time", "=", "Time", ".", "now", "retries", "=", "0", "close", "# Number of times to try", "begin", "connect_to_server", "(", "servers", ",", "policy", ")", "logger", ".", "info", "(", "message", ":", "\"Connected to #{address}\"", ",", "duration", ":", "(", "Time", ".", "now", "-", "start_time", ")", "*", "1000", ")", "if", "respond_to?", "(", ":logger", ")", "rescue", "ConnectionFailure", ",", "ConnectionTimeout", "=>", "exception", "cause", "=", "exception", ".", "is_a?", "(", "ConnectionTimeout", ")", "?", "exception", ":", "exception", ".", "cause", "# Retry-able?", "if", "self", ".", "class", ".", "reconnect_on_errors", ".", "include?", "(", "cause", ".", "class", ")", "&&", "(", "retries", "<", "connect_retry_count", ".", "to_i", ")", "retries", "+=", "1", "logger", ".", "warn", "\"#connect Failed to connect to any of #{servers.join(',')}. Sleeping:#{connect_retry_interval}s. Retry: #{retries}\"", "if", "respond_to?", "(", ":logger", ")", "sleep", "(", "connect_retry_interval", ")", "retry", "else", "message", "=", "\"#connect Failed to connect to any of #{servers.join(',')} after #{retries} retries. #{exception.class}: #{exception.message}\"", "logger", ".", "benchmark_error", "(", "message", ",", "exception", ":", "exception", ",", "duration", ":", "(", "Time", ".", "now", "-", "start_time", ")", ")", "if", "respond_to?", "(", ":logger", ")", "raise", "ConnectionFailure", ".", "new", "(", "message", ",", "address", ".", "to_s", ",", "cause", ")", "end", "end", "end"], "docstring": "Create a new TCP Client connection\n\n Parameters:\n :server [String]\n URL of the server to connect to with port number\n 'localhost:2000'\n '192.168.1.10:80'\n\n :servers [Array of String]\n Array of URL's of servers to connect to with port numbers\n ['server1:2000', 'server2:2000']\n\n The second server will only be attempted once the first server\n cannot be connected to or has timed out on connect\n A read failure or timeout will not result in switching to the second\n server, only a connection failure or during an automatic reconnect\n\n :connect_timeout [Float]\n Time in seconds to timeout when trying to connect to the server\n A value of -1 will cause the connect wait time to be infinite\n Default: 10 seconds\n\n :read_timeout [Float]\n Time in seconds to timeout on read\n Can be overridden by supplying a timeout in the read call\n Default: 60\n\n :write_timeout [Float]\n Time in seconds to timeout on write\n Can be overridden by supplying a timeout in the write call\n Default: 60\n\n :buffered [true|false]\n Whether to use Nagle's Buffering algorithm (http://en.wikipedia.org/wiki/Nagle's_algorithm)\n Recommend disabling for RPC style invocations where we don't want to wait for an\n ACK from the server before sending the last partial segment\n Buffering is recommended in a browser or file transfer style environment\n where multiple sends are expected during a single response.\n Also sets sync to true if buffered is false so that all data is sent immediately without\n internal buffering.\n Default: true\n\n :keepalive [true|false]\n Makes the OS check connections even when not in use, so that failed connections fail immediately\n upon use instead of possibly taking considerable time to fail.\n Default: true\n\n :connect_retry_count [Fixnum]\n Number of times to retry connecting when a connection fails\n Default: 10\n\n :connect_retry_interval [Float]\n Number of seconds between connection retry attempts after the first failed attempt\n Default: 0.5\n\n :retry_count [Fixnum]\n Number of times to retry when calling #retry_on_connection_failure\n This is independent of :connect_retry_count which still applies with\n connection failures. This retry controls upto how many times to retry the\n supplied block should a connection failure occur during the block\n Default: 3\n\n :on_connect [Proc]\n Directly after a connection is established and before it is made available\n for use this Block is invoked.\n Typical Use Cases:\n - Initialize per connection session sequence numbers.\n - Pass authentication information to the server.\n - Perform a handshake with the server.\n\n :policy [Symbol|Proc]\n Specify the policy to use when connecting to servers.\n :ordered\n Select a server in the order supplied in the array, with the first\n having the highest priority. The second server will only be connected\n to if the first server is unreachable\n :random\n Randomly select a server from the list every time a connection\n is established, including during automatic connection recovery.\n :ping_time\n FUTURE - Not implemented yet - Pull request anyone?\n The server with the lowest ping time will be tried first\n Proc:\n When a Proc is supplied, it will be called passing in the list\n of servers. The Proc must return one server name\n Example:\n :policy => Proc.new do |servers|\n servers.last\n end\n Default: :ordered\n\n :close_on_error [True|False]\n To prevent the connection from going into an inconsistent state\n automatically close the connection if an error occurs\n This includes a Read Timeout\n Default: true\n\n :proxy_server [String]\n The host name and port in the form of 'host_name:1234' to forward\n socket connections though.\n Default: nil ( none )\n\n SSL Options\n :ssl [true|false|Hash]\n true: SSL is enabled using the SSL context defaults.\n false: SSL is not used.\n Hash:\n Keys from OpenSSL::SSL::SSLContext:\n ca_file, ca_path, cert, cert_store, ciphers, key, ssl_timeout, ssl_version\n verify_callback, verify_depth, verify_mode\n handshake_timeout: [Float]\n The number of seconds to timeout the SSL Handshake.\n Default: connect_timeout\n Default: false.\n See OpenSSL::SSL::SSLContext::DEFAULT_PARAMS for the defaults.\n\n Example:\n client = Net::TCPClient.new(\n server: 'server:3300',\n connect_retry_interval: 0.1,\n connect_retry_count: 5\n )\n\n client.retry_on_connection_failure do\n client.write('Update the database')\n end\n\n # Read upto 20 characters from the server\n response = client.read(20)\n\n puts \"Received: #{response}\"\n client.close\n\n SSL Example:\n client = Net::TCPClient.new(\n server: 'server:3300',\n connect_retry_interval: 0.1,\n connect_retry_count: 5,\n ssl: true\n )\n\n SSL with options Example:\n client = Net::TCPClient.new(\n server: 'server:3300',\n connect_retry_interval: 0.1,\n connect_retry_count: 5,\n ssl: {\n verify_mode: OpenSSL::SSL::VERIFY_NONE\n }\n )\n Connect to the TCP server\n\n Raises Net::TCPClient::ConnectionTimeout when the time taken to create a connection\n exceeds the :connect_timeout\n Raises Net::TCPClient::ConnectionFailure whenever Socket raises an error such as Error::EACCESS etc, see Socket#connect for more information\n\n Error handling is implemented as follows:\n 1. TCP Socket Connect failure:\n Cannot reach server\n Server is being restarted, or is not running\n Retry 50 times every 100ms before raising a Net::TCPClient::ConnectionFailure\n - Means all calls to #connect will take at least 5 seconds before failing if the server is not running\n - Allows hot restart of server process if it restarts within 5 seconds\n\n 2. TCP Socket Connect timeout:\n Timed out after 5 seconds trying to connect to the server\n Usually means server is busy or the remote server disappeared off the network recently\n No retry, just raise a Net::TCPClient::ConnectionTimeout\n\n Note: When multiple servers are supplied it will only try to connect to\n the subsequent servers once the retry count has been exceeded\n\n Note: Calling #connect on an open connection will close the current connection\n and create a new connection", "docstring_tokens": ["Create", "a", "new", "TCP", "Client", "connection"], "sha": "201817e5532c4d94e27b1a50c0b02e4ee8babb05", "url": "https://github.com/rocketjob/net_tcp_client/blob/201817e5532c4d94e27b1a50c0b02e4ee8babb05/lib/net/tcp_client/tcp_client.rb#L303-L326", "partition": "test"} {"repo": "rocketjob/net_tcp_client", "path": "lib/net/tcp_client/tcp_client.rb", "func_name": "Net.TCPClient.write", "original_string": "def write(data, timeout = write_timeout)\n data = data.to_s\n if respond_to?(:logger)\n payload = {timeout: timeout}\n # With trace level also log the sent data\n payload[:data] = data if logger.trace?\n logger.benchmark_debug('#write', payload: payload) do\n payload[:bytes] = socket_write(data, timeout)\n end\n else\n socket_write(data, timeout)\n end\n rescue Exception => exc\n close if close_on_error\n raise exc\n end", "language": "ruby", "code": "def write(data, timeout = write_timeout)\n data = data.to_s\n if respond_to?(:logger)\n payload = {timeout: timeout}\n # With trace level also log the sent data\n payload[:data] = data if logger.trace?\n logger.benchmark_debug('#write', payload: payload) do\n payload[:bytes] = socket_write(data, timeout)\n end\n else\n socket_write(data, timeout)\n end\n rescue Exception => exc\n close if close_on_error\n raise exc\n end", "code_tokens": ["def", "write", "(", "data", ",", "timeout", "=", "write_timeout", ")", "data", "=", "data", ".", "to_s", "if", "respond_to?", "(", ":logger", ")", "payload", "=", "{", "timeout", ":", "timeout", "}", "# With trace level also log the sent data", "payload", "[", ":data", "]", "=", "data", "if", "logger", ".", "trace?", "logger", ".", "benchmark_debug", "(", "'#write'", ",", "payload", ":", "payload", ")", "do", "payload", "[", ":bytes", "]", "=", "socket_write", "(", "data", ",", "timeout", ")", "end", "else", "socket_write", "(", "data", ",", "timeout", ")", "end", "rescue", "Exception", "=>", "exc", "close", "if", "close_on_error", "raise", "exc", "end"], "docstring": "Write data to the server\n\n Use #with_retry to add resilience to the #write method\n\n Raises Net::TCPClient::ConnectionFailure whenever the write fails\n For a description of the errors, see Socket#write\n\n Parameters\n timeout [Float]\n Optional: Override the default write timeout for this write\n Number of seconds before raising Net::TCPClient::WriteTimeout when no data has\n been written.\n A value of -1 will wait forever\n Default: :write_timeout supplied to #initialize\n\n Note: After a Net::TCPClient::ReadTimeout #read can be called again on\n the same socket to read the response later.\n If the application no longer wants the connection after a\n Net::TCPClient::ReadTimeout, then the #close method _must_ be called\n before calling _connect_ or _retry_on_connection_failure_ to create\n a new connection", "docstring_tokens": ["Write", "data", "to", "the", "server"], "sha": "201817e5532c4d94e27b1a50c0b02e4ee8babb05", "url": "https://github.com/rocketjob/net_tcp_client/blob/201817e5532c4d94e27b1a50c0b02e4ee8babb05/lib/net/tcp_client/tcp_client.rb#L349-L364", "partition": "test"} {"repo": "rocketjob/net_tcp_client", "path": "lib/net/tcp_client/tcp_client.rb", "func_name": "Net.TCPClient.read", "original_string": "def read(length, buffer = nil, timeout = read_timeout)\n if respond_to?(:logger)\n payload = {bytes: length, timeout: timeout}\n logger.benchmark_debug('#read', payload: payload) do\n data = socket_read(length, buffer, timeout)\n # With trace level also log the received data\n payload[:data] = data if logger.trace?\n data\n end\n else\n socket_read(length, buffer, timeout)\n end\n rescue Exception => exc\n close if close_on_error\n raise exc\n end", "language": "ruby", "code": "def read(length, buffer = nil, timeout = read_timeout)\n if respond_to?(:logger)\n payload = {bytes: length, timeout: timeout}\n logger.benchmark_debug('#read', payload: payload) do\n data = socket_read(length, buffer, timeout)\n # With trace level also log the received data\n payload[:data] = data if logger.trace?\n data\n end\n else\n socket_read(length, buffer, timeout)\n end\n rescue Exception => exc\n close if close_on_error\n raise exc\n end", "code_tokens": ["def", "read", "(", "length", ",", "buffer", "=", "nil", ",", "timeout", "=", "read_timeout", ")", "if", "respond_to?", "(", ":logger", ")", "payload", "=", "{", "bytes", ":", "length", ",", "timeout", ":", "timeout", "}", "logger", ".", "benchmark_debug", "(", "'#read'", ",", "payload", ":", "payload", ")", "do", "data", "=", "socket_read", "(", "length", ",", "buffer", ",", "timeout", ")", "# With trace level also log the received data", "payload", "[", ":data", "]", "=", "data", "if", "logger", ".", "trace?", "data", "end", "else", "socket_read", "(", "length", ",", "buffer", ",", "timeout", ")", "end", "rescue", "Exception", "=>", "exc", "close", "if", "close_on_error", "raise", "exc", "end"], "docstring": "Returns a response from the server\n\n Raises Net::TCPClient::ConnectionTimeout when the time taken to create a connection\n exceeds the :connect_timeout\n Connection is closed\n Raises Net::TCPClient::ConnectionFailure whenever Socket raises an error such as\n Error::EACCESS etc, see Socket#connect for more information\n Connection is closed\n Raises Net::TCPClient::ReadTimeout if the timeout has been exceeded waiting for the\n requested number of bytes from the server\n Partial data will not be returned\n Connection is _not_ closed and #read can be called again later\n to read the response from the connection\n\n Parameters\n length [Fixnum]\n The number of bytes to return\n #read will not return until 'length' bytes have been received from\n the server\n\n buffer [String]\n Optional buffer into which to write the data that is read.\n\n timeout [Float]\n Optional: Override the default read timeout for this read\n Number of seconds before raising Net::TCPClient::ReadTimeout when no data has\n been returned\n A value of -1 will wait forever for a response on the socket\n Default: :read_timeout supplied to #initialize\n\n Note: After a Net::TCPClient::ReadTimeout #read can be called again on\n the same socket to read the response later.\n If the application no longer wants the connection after a\n Net::TCPClient::ReadTimeout, then the #close method _must_ be called\n before calling _connect_ or _retry_on_connection_failure_ to create\n a new connection", "docstring_tokens": ["Returns", "a", "response", "from", "the", "server"], "sha": "201817e5532c4d94e27b1a50c0b02e4ee8babb05", "url": "https://github.com/rocketjob/net_tcp_client/blob/201817e5532c4d94e27b1a50c0b02e4ee8babb05/lib/net/tcp_client/tcp_client.rb#L402-L417", "partition": "test"} {"repo": "rocketjob/net_tcp_client", "path": "lib/net/tcp_client/tcp_client.rb", "func_name": "Net.TCPClient.close", "original_string": "def close\n socket.close if socket && !socket.closed?\n @socket = nil\n @address = nil\n true\n rescue IOError => exception\n logger.warn \"IOError when attempting to close socket: #{exception.class}: #{exception.message}\" if respond_to?(:logger)\n false\n end", "language": "ruby", "code": "def close\n socket.close if socket && !socket.closed?\n @socket = nil\n @address = nil\n true\n rescue IOError => exception\n logger.warn \"IOError when attempting to close socket: #{exception.class}: #{exception.message}\" if respond_to?(:logger)\n false\n end", "code_tokens": ["def", "close", "socket", ".", "close", "if", "socket", "&&", "!", "socket", ".", "closed?", "@socket", "=", "nil", "@address", "=", "nil", "true", "rescue", "IOError", "=>", "exception", "logger", ".", "warn", "\"IOError when attempting to close socket: #{exception.class}: #{exception.message}\"", "if", "respond_to?", "(", ":logger", ")", "false", "end"], "docstring": "Close the socket only if it is not already closed\n\n Logs a warning if an error occurs trying to close the socket", "docstring_tokens": ["Close", "the", "socket", "only", "if", "it", "is", "not", "already", "closed"], "sha": "201817e5532c4d94e27b1a50c0b02e4ee8babb05", "url": "https://github.com/rocketjob/net_tcp_client/blob/201817e5532c4d94e27b1a50c0b02e4ee8babb05/lib/net/tcp_client/tcp_client.rb#L485-L493", "partition": "test"} {"repo": "rocketjob/net_tcp_client", "path": "lib/net/tcp_client/tcp_client.rb", "func_name": "Net.TCPClient.alive?", "original_string": "def alive?\n return false if socket.nil? || closed?\n\n if IO.select([socket], nil, nil, 0)\n !socket.eof? rescue false\n else\n true\n end\n rescue IOError\n false\n end", "language": "ruby", "code": "def alive?\n return false if socket.nil? || closed?\n\n if IO.select([socket], nil, nil, 0)\n !socket.eof? rescue false\n else\n true\n end\n rescue IOError\n false\n end", "code_tokens": ["def", "alive?", "return", "false", "if", "socket", ".", "nil?", "||", "closed?", "if", "IO", ".", "select", "(", "[", "socket", "]", ",", "nil", ",", "nil", ",", "0", ")", "!", "socket", ".", "eof?", "rescue", "false", "else", "true", "end", "rescue", "IOError", "false", "end"], "docstring": "Returns whether the connection to the server is alive\n\n It is useful to call this method before making a call to the server\n that would change data on the server\n\n Note: This method is only useful if the server closed the connection or\n if a previous connection failure occurred.\n If the server is hard killed this will still return true until one\n or more writes are attempted\n\n Note: In testing the overhead of this call is rather low, with the ability to\n make about 120,000 calls per second against an active connection.\n I.e. About 8.3 micro seconds per call", "docstring_tokens": ["Returns", "whether", "the", "connection", "to", "the", "server", "is", "alive"], "sha": "201817e5532c4d94e27b1a50c0b02e4ee8babb05", "url": "https://github.com/rocketjob/net_tcp_client/blob/201817e5532c4d94e27b1a50c0b02e4ee8babb05/lib/net/tcp_client/tcp_client.rb#L521-L531", "partition": "test"} {"repo": "rocketjob/net_tcp_client", "path": "lib/net/tcp_client/tcp_client.rb", "func_name": "Net.TCPClient.socket_connect", "original_string": "def socket_connect(socket, address, timeout)\n socket_address = Socket.pack_sockaddr_in(address.port, address.ip_address)\n\n # Timeout of -1 means wait forever for a connection\n return socket.connect(socket_address) if timeout == -1\n\n deadline = Time.now.utc + timeout\n begin\n non_blocking(socket, deadline) { socket.connect_nonblock(socket_address) }\n rescue Errno::EISCONN\n # Connection was successful.\n rescue NonBlockingTimeout\n raise ConnectionTimeout.new(\"Timed out after #{timeout} seconds trying to connect to #{address}\")\n rescue SystemCallError, IOError => exception\n message = \"#connect Connection failure connecting to '#{address.to_s}': #{exception.class}: #{exception.message}\"\n logger.error message if respond_to?(:logger)\n raise ConnectionFailure.new(message, address.to_s, exception)\n end\n end", "language": "ruby", "code": "def socket_connect(socket, address, timeout)\n socket_address = Socket.pack_sockaddr_in(address.port, address.ip_address)\n\n # Timeout of -1 means wait forever for a connection\n return socket.connect(socket_address) if timeout == -1\n\n deadline = Time.now.utc + timeout\n begin\n non_blocking(socket, deadline) { socket.connect_nonblock(socket_address) }\n rescue Errno::EISCONN\n # Connection was successful.\n rescue NonBlockingTimeout\n raise ConnectionTimeout.new(\"Timed out after #{timeout} seconds trying to connect to #{address}\")\n rescue SystemCallError, IOError => exception\n message = \"#connect Connection failure connecting to '#{address.to_s}': #{exception.class}: #{exception.message}\"\n logger.error message if respond_to?(:logger)\n raise ConnectionFailure.new(message, address.to_s, exception)\n end\n end", "code_tokens": ["def", "socket_connect", "(", "socket", ",", "address", ",", "timeout", ")", "socket_address", "=", "Socket", ".", "pack_sockaddr_in", "(", "address", ".", "port", ",", "address", ".", "ip_address", ")", "# Timeout of -1 means wait forever for a connection", "return", "socket", ".", "connect", "(", "socket_address", ")", "if", "timeout", "==", "-", "1", "deadline", "=", "Time", ".", "now", ".", "utc", "+", "timeout", "begin", "non_blocking", "(", "socket", ",", "deadline", ")", "{", "socket", ".", "connect_nonblock", "(", "socket_address", ")", "}", "rescue", "Errno", "::", "EISCONN", "# Connection was successful.", "rescue", "NonBlockingTimeout", "raise", "ConnectionTimeout", ".", "new", "(", "\"Timed out after #{timeout} seconds trying to connect to #{address}\"", ")", "rescue", "SystemCallError", ",", "IOError", "=>", "exception", "message", "=", "\"#connect Connection failure connecting to '#{address.to_s}': #{exception.class}: #{exception.message}\"", "logger", ".", "error", "message", "if", "respond_to?", "(", ":logger", ")", "raise", "ConnectionFailure", ".", "new", "(", "message", ",", "address", ".", "to_s", ",", "exception", ")", "end", "end"], "docstring": "Connect to server\n\n Raises Net::TCPClient::ConnectionTimeout when the connection timeout has been exceeded\n Raises Net::TCPClient::ConnectionFailure", "docstring_tokens": ["Connect", "to", "server"], "sha": "201817e5532c4d94e27b1a50c0b02e4ee8babb05", "url": "https://github.com/rocketjob/net_tcp_client/blob/201817e5532c4d94e27b1a50c0b02e4ee8babb05/lib/net/tcp_client/tcp_client.rb#L587-L605", "partition": "test"} {"repo": "rocketjob/net_tcp_client", "path": "lib/net/tcp_client/tcp_client.rb", "func_name": "Net.TCPClient.socket_write", "original_string": "def socket_write(data, timeout)\n if timeout < 0\n socket.write(data)\n else\n deadline = Time.now.utc + timeout\n length = data.bytesize\n total_count = 0\n non_blocking(socket, deadline) do\n loop do\n begin\n count = socket.write_nonblock(data)\n rescue Errno::EWOULDBLOCK\n retry\n end\n total_count += count\n return total_count if total_count >= length\n data = data.byteslice(count..-1)\n end\n end\n end\n rescue NonBlockingTimeout\n logger.warn \"#write Timeout after #{timeout} seconds\" if respond_to?(:logger)\n raise WriteTimeout.new(\"Timed out after #{timeout} seconds trying to write to #{address}\")\n rescue SystemCallError, IOError => exception\n message = \"#write Connection failure while writing to '#{address.to_s}': #{exception.class}: #{exception.message}\"\n logger.error message if respond_to?(:logger)\n raise ConnectionFailure.new(message, address.to_s, exception)\n end", "language": "ruby", "code": "def socket_write(data, timeout)\n if timeout < 0\n socket.write(data)\n else\n deadline = Time.now.utc + timeout\n length = data.bytesize\n total_count = 0\n non_blocking(socket, deadline) do\n loop do\n begin\n count = socket.write_nonblock(data)\n rescue Errno::EWOULDBLOCK\n retry\n end\n total_count += count\n return total_count if total_count >= length\n data = data.byteslice(count..-1)\n end\n end\n end\n rescue NonBlockingTimeout\n logger.warn \"#write Timeout after #{timeout} seconds\" if respond_to?(:logger)\n raise WriteTimeout.new(\"Timed out after #{timeout} seconds trying to write to #{address}\")\n rescue SystemCallError, IOError => exception\n message = \"#write Connection failure while writing to '#{address.to_s}': #{exception.class}: #{exception.message}\"\n logger.error message if respond_to?(:logger)\n raise ConnectionFailure.new(message, address.to_s, exception)\n end", "code_tokens": ["def", "socket_write", "(", "data", ",", "timeout", ")", "if", "timeout", "<", "0", "socket", ".", "write", "(", "data", ")", "else", "deadline", "=", "Time", ".", "now", ".", "utc", "+", "timeout", "length", "=", "data", ".", "bytesize", "total_count", "=", "0", "non_blocking", "(", "socket", ",", "deadline", ")", "do", "loop", "do", "begin", "count", "=", "socket", ".", "write_nonblock", "(", "data", ")", "rescue", "Errno", "::", "EWOULDBLOCK", "retry", "end", "total_count", "+=", "count", "return", "total_count", "if", "total_count", ">=", "length", "data", "=", "data", ".", "byteslice", "(", "count", "..", "-", "1", ")", "end", "end", "end", "rescue", "NonBlockingTimeout", "logger", ".", "warn", "\"#write Timeout after #{timeout} seconds\"", "if", "respond_to?", "(", ":logger", ")", "raise", "WriteTimeout", ".", "new", "(", "\"Timed out after #{timeout} seconds trying to write to #{address}\"", ")", "rescue", "SystemCallError", ",", "IOError", "=>", "exception", "message", "=", "\"#write Connection failure while writing to '#{address.to_s}': #{exception.class}: #{exception.message}\"", "logger", ".", "error", "message", "if", "respond_to?", "(", ":logger", ")", "raise", "ConnectionFailure", ".", "new", "(", "message", ",", "address", ".", "to_s", ",", "exception", ")", "end"], "docstring": "Write to the socket", "docstring_tokens": ["Write", "to", "the", "socket"], "sha": "201817e5532c4d94e27b1a50c0b02e4ee8babb05", "url": "https://github.com/rocketjob/net_tcp_client/blob/201817e5532c4d94e27b1a50c0b02e4ee8babb05/lib/net/tcp_client/tcp_client.rb#L608-L635", "partition": "test"} {"repo": "rocketjob/net_tcp_client", "path": "lib/net/tcp_client/tcp_client.rb", "func_name": "Net.TCPClient.ssl_connect", "original_string": "def ssl_connect(socket, address, timeout)\n ssl_context = OpenSSL::SSL::SSLContext.new\n ssl_context.set_params(ssl.is_a?(Hash) ? ssl : {})\n\n ssl_socket = OpenSSL::SSL::SSLSocket.new(socket, ssl_context)\n ssl_socket.hostname = address.host_name\n ssl_socket.sync_close = true\n\n begin\n if timeout == -1\n # Timeout of -1 means wait forever for a connection\n ssl_socket.connect\n else\n deadline = Time.now.utc + timeout\n begin\n non_blocking(socket, deadline) { ssl_socket.connect_nonblock }\n rescue Errno::EISCONN\n # Connection was successful.\n rescue NonBlockingTimeout\n raise ConnectionTimeout.new(\"SSL handshake Timed out after #{timeout} seconds trying to connect to #{address.to_s}\")\n end\n end\n rescue SystemCallError, OpenSSL::SSL::SSLError, IOError => exception\n message = \"#connect SSL handshake failure with '#{address.to_s}': #{exception.class}: #{exception.message}\"\n logger.error message if respond_to?(:logger)\n raise ConnectionFailure.new(message, address.to_s, exception)\n end\n\n # Verify Peer certificate\n ssl_verify(ssl_socket, address) if ssl_context.verify_mode != OpenSSL::SSL::VERIFY_NONE\n ssl_socket\n end", "language": "ruby", "code": "def ssl_connect(socket, address, timeout)\n ssl_context = OpenSSL::SSL::SSLContext.new\n ssl_context.set_params(ssl.is_a?(Hash) ? ssl : {})\n\n ssl_socket = OpenSSL::SSL::SSLSocket.new(socket, ssl_context)\n ssl_socket.hostname = address.host_name\n ssl_socket.sync_close = true\n\n begin\n if timeout == -1\n # Timeout of -1 means wait forever for a connection\n ssl_socket.connect\n else\n deadline = Time.now.utc + timeout\n begin\n non_blocking(socket, deadline) { ssl_socket.connect_nonblock }\n rescue Errno::EISCONN\n # Connection was successful.\n rescue NonBlockingTimeout\n raise ConnectionTimeout.new(\"SSL handshake Timed out after #{timeout} seconds trying to connect to #{address.to_s}\")\n end\n end\n rescue SystemCallError, OpenSSL::SSL::SSLError, IOError => exception\n message = \"#connect SSL handshake failure with '#{address.to_s}': #{exception.class}: #{exception.message}\"\n logger.error message if respond_to?(:logger)\n raise ConnectionFailure.new(message, address.to_s, exception)\n end\n\n # Verify Peer certificate\n ssl_verify(ssl_socket, address) if ssl_context.verify_mode != OpenSSL::SSL::VERIFY_NONE\n ssl_socket\n end", "code_tokens": ["def", "ssl_connect", "(", "socket", ",", "address", ",", "timeout", ")", "ssl_context", "=", "OpenSSL", "::", "SSL", "::", "SSLContext", ".", "new", "ssl_context", ".", "set_params", "(", "ssl", ".", "is_a?", "(", "Hash", ")", "?", "ssl", ":", "{", "}", ")", "ssl_socket", "=", "OpenSSL", "::", "SSL", "::", "SSLSocket", ".", "new", "(", "socket", ",", "ssl_context", ")", "ssl_socket", ".", "hostname", "=", "address", ".", "host_name", "ssl_socket", ".", "sync_close", "=", "true", "begin", "if", "timeout", "==", "-", "1", "# Timeout of -1 means wait forever for a connection", "ssl_socket", ".", "connect", "else", "deadline", "=", "Time", ".", "now", ".", "utc", "+", "timeout", "begin", "non_blocking", "(", "socket", ",", "deadline", ")", "{", "ssl_socket", ".", "connect_nonblock", "}", "rescue", "Errno", "::", "EISCONN", "# Connection was successful.", "rescue", "NonBlockingTimeout", "raise", "ConnectionTimeout", ".", "new", "(", "\"SSL handshake Timed out after #{timeout} seconds trying to connect to #{address.to_s}\"", ")", "end", "end", "rescue", "SystemCallError", ",", "OpenSSL", "::", "SSL", "::", "SSLError", ",", "IOError", "=>", "exception", "message", "=", "\"#connect SSL handshake failure with '#{address.to_s}': #{exception.class}: #{exception.message}\"", "logger", ".", "error", "message", "if", "respond_to?", "(", ":logger", ")", "raise", "ConnectionFailure", ".", "new", "(", "message", ",", "address", ".", "to_s", ",", "exception", ")", "end", "# Verify Peer certificate", "ssl_verify", "(", "ssl_socket", ",", "address", ")", "if", "ssl_context", ".", "verify_mode", "!=", "OpenSSL", "::", "SSL", "::", "VERIFY_NONE", "ssl_socket", "end"], "docstring": "Try connecting to a single server\n Returns the connected socket\n\n Raises Net::TCPClient::ConnectionTimeout when the connection timeout has been exceeded\n Raises Net::TCPClient::ConnectionFailure", "docstring_tokens": ["Try", "connecting", "to", "a", "single", "server", "Returns", "the", "connected", "socket"], "sha": "201817e5532c4d94e27b1a50c0b02e4ee8babb05", "url": "https://github.com/rocketjob/net_tcp_client/blob/201817e5532c4d94e27b1a50c0b02e4ee8babb05/lib/net/tcp_client/tcp_client.rb#L689-L720", "partition": "test"} {"repo": "gotwalt/sonos", "path": "lib/sonos/system.rb", "func_name": "Sonos.System.party_mode", "original_string": "def party_mode new_master = nil\n return nil unless speakers.length > 1\n\n new_master = find_party_master if new_master.nil?\n\n party_over\n speakers.each do |slave|\n next if slave.uid == new_master.uid\n slave.join new_master\n end\n rescan @topology\n end", "language": "ruby", "code": "def party_mode new_master = nil\n return nil unless speakers.length > 1\n\n new_master = find_party_master if new_master.nil?\n\n party_over\n speakers.each do |slave|\n next if slave.uid == new_master.uid\n slave.join new_master\n end\n rescan @topology\n end", "code_tokens": ["def", "party_mode", "new_master", "=", "nil", "return", "nil", "unless", "speakers", ".", "length", ">", "1", "new_master", "=", "find_party_master", "if", "new_master", ".", "nil?", "party_over", "speakers", ".", "each", "do", "|", "slave", "|", "next", "if", "slave", ".", "uid", "==", "new_master", ".", "uid", "slave", ".", "join", "new_master", "end", "rescan", "@topology", "end"], "docstring": "Party Mode! Join all speakers into a single group.", "docstring_tokens": ["Party", "Mode!", "Join", "all", "speakers", "into", "a", "single", "group", "."], "sha": "a8fed525e6920dd13ee29a0903f085c969f80e4e", "url": "https://github.com/gotwalt/sonos/blob/a8fed525e6920dd13ee29a0903f085c969f80e4e/lib/sonos/system.rb#L35-L46", "partition": "test"} {"repo": "gotwalt/sonos", "path": "lib/sonos/discovery.rb", "func_name": "Sonos.Discovery.discover", "original_string": "def discover\n result = SSDP::Consumer.new.search(service: 'urn:schemas-upnp-org:device:ZonePlayer:1', first_only: true, timeout: @timeout, filter: lambda {|r| r[:params][\"ST\"].match(/ZonePlayer/) })\n @first_device_ip = result[:address]\n end", "language": "ruby", "code": "def discover\n result = SSDP::Consumer.new.search(service: 'urn:schemas-upnp-org:device:ZonePlayer:1', first_only: true, timeout: @timeout, filter: lambda {|r| r[:params][\"ST\"].match(/ZonePlayer/) })\n @first_device_ip = result[:address]\n end", "code_tokens": ["def", "discover", "result", "=", "SSDP", "::", "Consumer", ".", "new", ".", "search", "(", "service", ":", "'urn:schemas-upnp-org:device:ZonePlayer:1'", ",", "first_only", ":", "true", ",", "timeout", ":", "@timeout", ",", "filter", ":", "lambda", "{", "|", "r", "|", "r", "[", ":params", "]", "[", "\"ST\"", "]", ".", "match", "(", "/", "/", ")", "}", ")", "@first_device_ip", "=", "result", "[", ":address", "]", "end"], "docstring": "Look for Sonos devices on the network and return the first IP address found\n @return [String] the IP address of the first Sonos device found", "docstring_tokens": ["Look", "for", "Sonos", "devices", "on", "the", "network", "and", "return", "the", "first", "IP", "address", "found"], "sha": "a8fed525e6920dd13ee29a0903f085c969f80e4e", "url": "https://github.com/gotwalt/sonos/blob/a8fed525e6920dd13ee29a0903f085c969f80e4e/lib/sonos/discovery.rb#L29-L32", "partition": "test"} {"repo": "gotwalt/sonos", "path": "lib/sonos/discovery.rb", "func_name": "Sonos.Discovery.topology", "original_string": "def topology\n self.discover unless @first_device_ip\n return [] unless @first_device_ip\n\n doc = Nokogiri::XML(open(\"http://#{@first_device_ip}:#{Sonos::PORT}/status/topology\"))\n doc.xpath('//ZonePlayers/ZonePlayer').map do |node|\n TopologyNode.new(node)\n end\n end", "language": "ruby", "code": "def topology\n self.discover unless @first_device_ip\n return [] unless @first_device_ip\n\n doc = Nokogiri::XML(open(\"http://#{@first_device_ip}:#{Sonos::PORT}/status/topology\"))\n doc.xpath('//ZonePlayers/ZonePlayer').map do |node|\n TopologyNode.new(node)\n end\n end", "code_tokens": ["def", "topology", "self", ".", "discover", "unless", "@first_device_ip", "return", "[", "]", "unless", "@first_device_ip", "doc", "=", "Nokogiri", "::", "XML", "(", "open", "(", "\"http://#{@first_device_ip}:#{Sonos::PORT}/status/topology\"", ")", ")", "doc", ".", "xpath", "(", "'//ZonePlayers/ZonePlayer'", ")", ".", "map", "do", "|", "node", "|", "TopologyNode", ".", "new", "(", "node", ")", "end", "end"], "docstring": "Find all of the Sonos devices on the network\n @return [Array] an array of TopologyNode objects", "docstring_tokens": ["Find", "all", "of", "the", "Sonos", "devices", "on", "the", "network"], "sha": "a8fed525e6920dd13ee29a0903f085c969f80e4e", "url": "https://github.com/gotwalt/sonos/blob/a8fed525e6920dd13ee29a0903f085c969f80e4e/lib/sonos/discovery.rb#L36-L44", "partition": "test"} {"repo": "MagicTheGathering/mtg-sdk-ruby", "path": "lib/mtg_sdk/query_builder.rb", "func_name": "MTG.QueryBuilder.find", "original_string": "def find(id)\n response = RestClient.get(\"#{@type.Resource}/#{id}\")\n singular_resource = @type.Resource[0...-1]\n if response.body[singular_resource].nil?\n raise ArgumentError, 'Resource not found'\n end\n \n type.new.from_json(response.body[singular_resource].to_json)\n end", "language": "ruby", "code": "def find(id)\n response = RestClient.get(\"#{@type.Resource}/#{id}\")\n singular_resource = @type.Resource[0...-1]\n if response.body[singular_resource].nil?\n raise ArgumentError, 'Resource not found'\n end\n \n type.new.from_json(response.body[singular_resource].to_json)\n end", "code_tokens": ["def", "find", "(", "id", ")", "response", "=", "RestClient", ".", "get", "(", "\"#{@type.Resource}/#{id}\"", ")", "singular_resource", "=", "@type", ".", "Resource", "[", "0", "...", "-", "1", "]", "if", "response", ".", "body", "[", "singular_resource", "]", ".", "nil?", "raise", "ArgumentError", ",", "'Resource not found'", "end", "type", ".", "new", ".", "from_json", "(", "response", ".", "body", "[", "singular_resource", "]", ".", "to_json", ")", "end"], "docstring": "Find a single resource by the resource id\n\n @param id [String] the resource id\n @return [Object] the Type object response", "docstring_tokens": ["Find", "a", "single", "resource", "by", "the", "resource", "id"], "sha": "fbe3503ad76d4ca0252d4130daa68e3d087a67cd", "url": "https://github.com/MagicTheGathering/mtg-sdk-ruby/blob/fbe3503ad76d4ca0252d4130daa68e3d087a67cd/lib/mtg_sdk/query_builder.rb#L24-L32", "partition": "test"} {"repo": "MagicTheGathering/mtg-sdk-ruby", "path": "lib/mtg_sdk/query_builder.rb", "func_name": "MTG.QueryBuilder.all", "original_string": "def all\n list = []\n page = 1\n fetch_all = true\n\n if @query.has_key?(:page)\n page = @query[:page]\n fetch_all = false\n end\n \n while true\n response = RestClient.get(@type.Resource, @query)\n data = response.body[@type.Resource] \n if !data.empty?\n data.each {|item| list << @type.new.from_json(item.to_json)}\n \n if !fetch_all\n break\n else\n where(page: page += 1)\n end\n else\n break\n end\n end\n\n return list\n end", "language": "ruby", "code": "def all\n list = []\n page = 1\n fetch_all = true\n\n if @query.has_key?(:page)\n page = @query[:page]\n fetch_all = false\n end\n \n while true\n response = RestClient.get(@type.Resource, @query)\n data = response.body[@type.Resource] \n if !data.empty?\n data.each {|item| list << @type.new.from_json(item.to_json)}\n \n if !fetch_all\n break\n else\n where(page: page += 1)\n end\n else\n break\n end\n end\n\n return list\n end", "code_tokens": ["def", "all", "list", "=", "[", "]", "page", "=", "1", "fetch_all", "=", "true", "if", "@query", ".", "has_key?", "(", ":page", ")", "page", "=", "@query", "[", ":page", "]", "fetch_all", "=", "false", "end", "while", "true", "response", "=", "RestClient", ".", "get", "(", "@type", ".", "Resource", ",", "@query", ")", "data", "=", "response", ".", "body", "[", "@type", ".", "Resource", "]", "if", "!", "data", ".", "empty?", "data", ".", "each", "{", "|", "item", "|", "list", "<<", "@type", ".", "new", ".", "from_json", "(", "item", ".", "to_json", ")", "}", "if", "!", "fetch_all", "break", "else", "where", "(", "page", ":", "page", "+=", "1", ")", "end", "else", "break", "end", "end", "return", "list", "end"], "docstring": "Get all resources from a query by paging through data\n\n @return [Array] Array of resources", "docstring_tokens": ["Get", "all", "resources", "from", "a", "query", "by", "paging", "through", "data"], "sha": "fbe3503ad76d4ca0252d4130daa68e3d087a67cd", "url": "https://github.com/MagicTheGathering/mtg-sdk-ruby/blob/fbe3503ad76d4ca0252d4130daa68e3d087a67cd/lib/mtg_sdk/query_builder.rb#L37-L64", "partition": "test"} {"repo": "trailblazer/reform-rails", "path": "lib/reform/form/orm.rb", "func_name": "Reform::Form::ORM.UniquenessValidator.validate", "original_string": "def validate(form)\n property = attributes.first\n\n # here is the thing: why does AM::UniquenessValidator require a filled-out record to work properly? also, why do we need to set\n # the class? it would be way easier to pass #validate a hash of attributes and get back an errors hash.\n # the class for the finder could either be infered from the record or set in the validator instance itself in the call to ::validates.\n record = form.model_for_property(property)\n record.send(\"#{property}=\", form.send(property))\n\n @klass = record.class # this is usually done in the super-sucky #setup method.\n super(record).tap do |res|\n form.errors.add(property, record.errors.first.last) if record.errors.present?\n end\n end", "language": "ruby", "code": "def validate(form)\n property = attributes.first\n\n # here is the thing: why does AM::UniquenessValidator require a filled-out record to work properly? also, why do we need to set\n # the class? it would be way easier to pass #validate a hash of attributes and get back an errors hash.\n # the class for the finder could either be infered from the record or set in the validator instance itself in the call to ::validates.\n record = form.model_for_property(property)\n record.send(\"#{property}=\", form.send(property))\n\n @klass = record.class # this is usually done in the super-sucky #setup method.\n super(record).tap do |res|\n form.errors.add(property, record.errors.first.last) if record.errors.present?\n end\n end", "code_tokens": ["def", "validate", "(", "form", ")", "property", "=", "attributes", ".", "first", "# here is the thing: why does AM::UniquenessValidator require a filled-out record to work properly? also, why do we need to set", "# the class? it would be way easier to pass #validate a hash of attributes and get back an errors hash.", "# the class for the finder could either be infered from the record or set in the validator instance itself in the call to ::validates.", "record", "=", "form", ".", "model_for_property", "(", "property", ")", "record", ".", "send", "(", "\"#{property}=\"", ",", "form", ".", "send", "(", "property", ")", ")", "@klass", "=", "record", ".", "class", "# this is usually done in the super-sucky #setup method.", "super", "(", "record", ")", ".", "tap", "do", "|", "res", "|", "form", ".", "errors", ".", "add", "(", "property", ",", "record", ".", "errors", ".", "first", ".", "last", ")", "if", "record", ".", "errors", ".", "present?", "end", "end"], "docstring": "when calling validates it should create the Vali instance already and set @klass there! # TODO: fix this in AM.", "docstring_tokens": ["when", "calling", "validates", "it", "should", "create", "the", "Vali", "instance", "already", "and", "set"], "sha": "4ad30a8042310c1f5fee75e24c047ae776c054de", "url": "https://github.com/trailblazer/reform-rails/blob/4ad30a8042310c1f5fee75e24c047ae776c054de/lib/reform/form/orm.rb#L11-L24", "partition": "test"} {"repo": "trailblazer/reform-rails", "path": "lib/reform/form/active_model.rb", "func_name": "Reform::Form::ActiveModel.ClassMethods.validates", "original_string": "def validates(*args, &block)\n validation(name: :default, inherit: true) { validates *args, &block }\n end", "language": "ruby", "code": "def validates(*args, &block)\n validation(name: :default, inherit: true) { validates *args, &block }\n end", "code_tokens": ["def", "validates", "(", "*", "args", ",", "&", "block", ")", "validation", "(", "name", ":", ":default", ",", "inherit", ":", "true", ")", "{", "validates", "args", ",", "block", "}", "end"], "docstring": "moved from reform as not applicable to dry", "docstring_tokens": ["moved", "from", "reform", "as", "not", "applicable", "to", "dry"], "sha": "4ad30a8042310c1f5fee75e24c047ae776c054de", "url": "https://github.com/trailblazer/reform-rails/blob/4ad30a8042310c1f5fee75e24c047ae776c054de/lib/reform/form/active_model.rb#L44-L46", "partition": "test"} {"repo": "Empact/roxml", "path": "lib/roxml/xml/references.rb", "func_name": "ROXML.XMLTextRef.update_xml", "original_string": "def update_xml(xml, value)\n wrap(xml).tap do |xml|\n if content?\n add(xml, value)\n elsif name?\n xml.name = value\n elsif array?\n value.each do |v|\n add(XML.add_node(xml, name), v)\n end\n else\n add(XML.add_node(xml, name), value)\n end\n end\n end", "language": "ruby", "code": "def update_xml(xml, value)\n wrap(xml).tap do |xml|\n if content?\n add(xml, value)\n elsif name?\n xml.name = value\n elsif array?\n value.each do |v|\n add(XML.add_node(xml, name), v)\n end\n else\n add(XML.add_node(xml, name), value)\n end\n end\n end", "code_tokens": ["def", "update_xml", "(", "xml", ",", "value", ")", "wrap", "(", "xml", ")", ".", "tap", "do", "|", "xml", "|", "if", "content?", "add", "(", "xml", ",", "value", ")", "elsif", "name?", "xml", ".", "name", "=", "value", "elsif", "array?", "value", ".", "each", "do", "|", "v", "|", "add", "(", "XML", ".", "add_node", "(", "xml", ",", "name", ")", ",", "v", ")", "end", "else", "add", "(", "XML", ".", "add_node", "(", "xml", ",", "name", ")", ",", "value", ")", "end", "end", "end"], "docstring": "Updates the text in the given _xml_ block to\n the _value_ provided.", "docstring_tokens": ["Updates", "the", "text", "in", "the", "given", "_xml_", "block", "to", "the", "_value_", "provided", "."], "sha": "0d6fd8eb3d6ae9710ba6f3ea5db06902b4a8568a", "url": "https://github.com/Empact/roxml/blob/0d6fd8eb3d6ae9710ba6f3ea5db06902b4a8568a/lib/roxml/xml/references.rb#L187-L201", "partition": "test"} {"repo": "noverde/exonio", "path": "lib/exonio/financial.rb", "func_name": "Exonio.Financial.ipmt", "original_string": "def ipmt(rate, per, nper, pv, fv = 0, end_or_beginning = 0)\n pmt = self.pmt(rate, nper, pv, fv, end_or_beginning)\n fv = self.fv(rate, (per - 1), pmt, pv, end_or_beginning) * rate\n temp = end_or_beginning == 1 ? fv / (1 + rate) : fv\n\n (per == 1 && end_or_beginning == 1) ? 0.0 : temp\n end", "language": "ruby", "code": "def ipmt(rate, per, nper, pv, fv = 0, end_or_beginning = 0)\n pmt = self.pmt(rate, nper, pv, fv, end_or_beginning)\n fv = self.fv(rate, (per - 1), pmt, pv, end_or_beginning) * rate\n temp = end_or_beginning == 1 ? fv / (1 + rate) : fv\n\n (per == 1 && end_or_beginning == 1) ? 0.0 : temp\n end", "code_tokens": ["def", "ipmt", "(", "rate", ",", "per", ",", "nper", ",", "pv", ",", "fv", "=", "0", ",", "end_or_beginning", "=", "0", ")", "pmt", "=", "self", ".", "pmt", "(", "rate", ",", "nper", ",", "pv", ",", "fv", ",", "end_or_beginning", ")", "fv", "=", "self", ".", "fv", "(", "rate", ",", "(", "per", "-", "1", ")", ",", "pmt", ",", "pv", ",", "end_or_beginning", ")", "*", "rate", "temp", "=", "end_or_beginning", "==", "1", "?", "fv", "/", "(", "1", "+", "rate", ")", ":", "fv", "(", "per", "==", "1", "&&", "end_or_beginning", "==", "1", ")", "?", "0.0", ":", "temp", "end"], "docstring": "Calculates the payment on interest for an investment based on\n constant-amount periodic payments and a constant interest rate.\n\n @param rate [Float] The interest rate as decimal (not per cent) per period\n @param per [Integer] The amortization period, in terms of number of periods\n @param nper [Integer] The number of payments to be made\n @param pv [Float] The present value\n @param fv [Float] The future value remaining after the final payment has been made\n @param end_or_begining [Integer] Whether payments are due at the end (0) or\n beggining (1) of each period\n\n @return [Float]\n\n @example\n Exonio.ipmt(0.075 / 12, 8, 12 * 2, 5000) # ==> -22.612926783996798", "docstring_tokens": ["Calculates", "the", "payment", "on", "interest", "for", "an", "investment", "based", "on", "constant", "-", "amount", "periodic", "payments", "and", "a", "constant", "interest", "rate", "."], "sha": "e0043557c403f392c48314830b3e527b3ae68eb2", "url": "https://github.com/noverde/exonio/blob/e0043557c403f392c48314830b3e527b3ae68eb2/lib/exonio/financial.rb#L41-L47", "partition": "test"} {"repo": "noverde/exonio", "path": "lib/exonio/financial.rb", "func_name": "Exonio.Financial.nper", "original_string": "def nper(rate, pmt, pv, fv = 0, end_or_beginning = 0)\n z = pmt * (1 + rate * end_or_beginning) / rate\n temp = Math.log((-fv + z) / (pv + z))\n\n temp / Math.log(1 + rate)\n end", "language": "ruby", "code": "def nper(rate, pmt, pv, fv = 0, end_or_beginning = 0)\n z = pmt * (1 + rate * end_or_beginning) / rate\n temp = Math.log((-fv + z) / (pv + z))\n\n temp / Math.log(1 + rate)\n end", "code_tokens": ["def", "nper", "(", "rate", ",", "pmt", ",", "pv", ",", "fv", "=", "0", ",", "end_or_beginning", "=", "0", ")", "z", "=", "pmt", "*", "(", "1", "+", "rate", "*", "end_or_beginning", ")", "/", "rate", "temp", "=", "Math", ".", "log", "(", "(", "-", "fv", "+", "z", ")", "/", "(", "pv", "+", "z", ")", ")", "temp", "/", "Math", ".", "log", "(", "1", "+", "rate", ")", "end"], "docstring": "Calculates the number of payment periods for an investment based on\n constant-amount periodic payments and a constant interest rate.\n\n @param rate [Float] The interest rate as decimal (not per cent) per period\n @param pmt [Float] The payment amount made each period\n @param pv [Float] The present value of the payments\n @param fv [Float] The future value remaining after the final payment has been made\n @param end_or_begining [Integer] Whether payments are due at the end (0) or\n beggining (1) of each period\n\n @return [Float]\n\n @example\n Exonio.nper(0.07 / 12, -150, 8000) # ==> 64.07334877066185", "docstring_tokens": ["Calculates", "the", "number", "of", "payment", "periods", "for", "an", "investment", "based", "on", "constant", "-", "amount", "periodic", "payments", "and", "a", "constant", "interest", "rate", "."], "sha": "e0043557c403f392c48314830b3e527b3ae68eb2", "url": "https://github.com/noverde/exonio/blob/e0043557c403f392c48314830b3e527b3ae68eb2/lib/exonio/financial.rb#L64-L69", "partition": "test"} {"repo": "noverde/exonio", "path": "lib/exonio/financial.rb", "func_name": "Exonio.Financial.pmt", "original_string": "def pmt(rate, nper, pv, fv = 0, end_or_beginning = 0)\n temp = (1 + rate) ** nper\n fact = (1 + rate * end_or_beginning) * (temp - 1) / rate\n\n -(fv + pv * temp) / fact\n end", "language": "ruby", "code": "def pmt(rate, nper, pv, fv = 0, end_or_beginning = 0)\n temp = (1 + rate) ** nper\n fact = (1 + rate * end_or_beginning) * (temp - 1) / rate\n\n -(fv + pv * temp) / fact\n end", "code_tokens": ["def", "pmt", "(", "rate", ",", "nper", ",", "pv", ",", "fv", "=", "0", ",", "end_or_beginning", "=", "0", ")", "temp", "=", "(", "1", "+", "rate", ")", "**", "nper", "fact", "=", "(", "1", "+", "rate", "*", "end_or_beginning", ")", "*", "(", "temp", "-", "1", ")", "/", "rate", "-", "(", "fv", "+", "pv", "*", "temp", ")", "/", "fact", "end"], "docstring": "Calculates the periodic payment for an annuity investment based on\n constant-amount periodic payments and a constant interest rate.\n\n @param rate [Float] The interest rate as decimal (not per cent) per period\n @param nper [Integer] The number of payments to be made (number of periods)\n @param pv [Float] The present value of the annuity\n @param fv [Float] The future value remaining after the final payment has been made\n @param end_or_begining [Integer] Whether payments are due at the end (0) or\n beggining (1) of each period\n\n @return [Float]\n\n @example\n Exonio.pmt(0.075/12, 12*15, 200_000) # ==> -1854.0247200054619", "docstring_tokens": ["Calculates", "the", "periodic", "payment", "for", "an", "annuity", "investment", "based", "on", "constant", "-", "amount", "periodic", "payments", "and", "a", "constant", "interest", "rate", "."], "sha": "e0043557c403f392c48314830b3e527b3ae68eb2", "url": "https://github.com/noverde/exonio/blob/e0043557c403f392c48314830b3e527b3ae68eb2/lib/exonio/financial.rb#L86-L91", "partition": "test"} {"repo": "noverde/exonio", "path": "lib/exonio/financial.rb", "func_name": "Exonio.Financial.rate", "original_string": "def rate(nper, pmt, pv, fv = 0, end_or_beginning = 0, rate_guess = 0.10)\n guess = rate_guess\n tolerancy = 1e-6\n close = false\n\n begin\n temp = newton_iter(guess, nper, pmt, pv, fv, end_or_beginning)\n next_guess = (guess - temp).round(20)\n diff = (next_guess - guess).abs\n close = diff < tolerancy\n guess = next_guess\n end while !close\n\n next_guess\n end", "language": "ruby", "code": "def rate(nper, pmt, pv, fv = 0, end_or_beginning = 0, rate_guess = 0.10)\n guess = rate_guess\n tolerancy = 1e-6\n close = false\n\n begin\n temp = newton_iter(guess, nper, pmt, pv, fv, end_or_beginning)\n next_guess = (guess - temp).round(20)\n diff = (next_guess - guess).abs\n close = diff < tolerancy\n guess = next_guess\n end while !close\n\n next_guess\n end", "code_tokens": ["def", "rate", "(", "nper", ",", "pmt", ",", "pv", ",", "fv", "=", "0", ",", "end_or_beginning", "=", "0", ",", "rate_guess", "=", "0.10", ")", "guess", "=", "rate_guess", "tolerancy", "=", "1e-6", "close", "=", "false", "begin", "temp", "=", "newton_iter", "(", "guess", ",", "nper", ",", "pmt", ",", "pv", ",", "fv", ",", "end_or_beginning", ")", "next_guess", "=", "(", "guess", "-", "temp", ")", ".", "round", "(", "20", ")", "diff", "=", "(", "next_guess", "-", "guess", ")", ".", "abs", "close", "=", "diff", "<", "tolerancy", "guess", "=", "next_guess", "end", "while", "!", "close", "next_guess", "end"], "docstring": "Calculates the interest rate of an annuity investment based on\n constant-amount periodic payments and the assumption of a constant interest rate.\n\n @param nper [Integer] The number of payments to be made (number of periods)\n @param pmt [Float] The amount per period to be paid\n @param pv [Float] The present value\n @param fv [Float] The future value remaining after the final payment has been made\n @param end_or_begining [Integer] Whether payments are due at the end (0) or\n beggining (1) of each period\n @param rate_guess [Float] An estimate for what the interest rate will be\n\n @return [Float]\n\n @example\n Exonio.rate(12, 363.78, -3056.00) # ==> 0.05963422268883278", "docstring_tokens": ["Calculates", "the", "interest", "rate", "of", "an", "annuity", "investment", "based", "on", "constant", "-", "amount", "periodic", "payments", "and", "the", "assumption", "of", "a", "constant", "interest", "rate", "."], "sha": "e0043557c403f392c48314830b3e527b3ae68eb2", "url": "https://github.com/noverde/exonio/blob/e0043557c403f392c48314830b3e527b3ae68eb2/lib/exonio/financial.rb#L131-L145", "partition": "test"} {"repo": "noverde/exonio", "path": "lib/exonio/financial.rb", "func_name": "Exonio.Financial.npv", "original_string": "def npv(discount, cashflows)\n total = 0\n\n cashflows.each_with_index do |cashflow, index|\n total += (cashflow.to_f / (1 + discount.to_f) ** (index + 1))\n end\n\n total\n end", "language": "ruby", "code": "def npv(discount, cashflows)\n total = 0\n\n cashflows.each_with_index do |cashflow, index|\n total += (cashflow.to_f / (1 + discount.to_f) ** (index + 1))\n end\n\n total\n end", "code_tokens": ["def", "npv", "(", "discount", ",", "cashflows", ")", "total", "=", "0", "cashflows", ".", "each_with_index", "do", "|", "cashflow", ",", "index", "|", "total", "+=", "(", "cashflow", ".", "to_f", "/", "(", "1", "+", "discount", ".", "to_f", ")", "**", "(", "index", "+", "1", ")", ")", "end", "total", "end"], "docstring": "Calculates the net present value of an investment based on a\n series of periodic cash flows and a discount rate.\n\n @param discount [Float] The discount rate of the investment over one period\n @param cashflows [Array] The first future cash flow + additional future cash flows\n\n @return [Float]\n\n @example\n Exonio.npv(0.281, [-100, 39, 59, 55, 20]) # ==> -0.00661872883563408", "docstring_tokens": ["Calculates", "the", "net", "present", "value", "of", "an", "investment", "based", "on", "a", "series", "of", "periodic", "cash", "flows", "and", "a", "discount", "rate", "."], "sha": "e0043557c403f392c48314830b3e527b3ae68eb2", "url": "https://github.com/noverde/exonio/blob/e0043557c403f392c48314830b3e527b3ae68eb2/lib/exonio/financial.rb#L158-L166", "partition": "test"} {"repo": "noverde/exonio", "path": "lib/exonio/financial.rb", "func_name": "Exonio.Financial.irr", "original_string": "def irr(values)\n func = Helpers::IrrHelper.new(values)\n guess = [ func.eps ]\n nlsolve( func, guess)\n guess[0]\n end", "language": "ruby", "code": "def irr(values)\n func = Helpers::IrrHelper.new(values)\n guess = [ func.eps ]\n nlsolve( func, guess)\n guess[0]\n end", "code_tokens": ["def", "irr", "(", "values", ")", "func", "=", "Helpers", "::", "IrrHelper", ".", "new", "(", "values", ")", "guess", "=", "[", "func", ".", "eps", "]", "nlsolve", "(", "func", ",", "guess", ")", "guess", "[", "0", "]", "end"], "docstring": "Calculates the internal rate of return on an investment based on a\n series of periodic cash flows.\n\n @param cashflows [Array] An array containing the income or payments\n associated with the investment\n\n @return [Float]\n\n @example\n Exonio.irr([-100, 39, 59, 55, 20]) # ==> 0.28094842116...", "docstring_tokens": ["Calculates", "the", "internal", "rate", "of", "return", "on", "an", "investment", "based", "on", "a", "series", "of", "periodic", "cash", "flows", "."], "sha": "e0043557c403f392c48314830b3e527b3ae68eb2", "url": "https://github.com/noverde/exonio/blob/e0043557c403f392c48314830b3e527b3ae68eb2/lib/exonio/financial.rb#L179-L184", "partition": "test"} {"repo": "noverde/exonio", "path": "lib/exonio/financial.rb", "func_name": "Exonio.Financial.newton_iter", "original_string": "def newton_iter(r, n, p, x, y, w)\n t1 = (r+1)**n\n t2 = (r+1)**(n-1)\n ((y + t1*x + p*(t1 - 1)*(r*w + 1)/r) / (n*t2*x - p*(t1 - 1)*(r*w + 1)/(r**2) + n*p*t2*(r*w + 1)/r + p*(t1 - 1)*w/r))\n end", "language": "ruby", "code": "def newton_iter(r, n, p, x, y, w)\n t1 = (r+1)**n\n t2 = (r+1)**(n-1)\n ((y + t1*x + p*(t1 - 1)*(r*w + 1)/r) / (n*t2*x - p*(t1 - 1)*(r*w + 1)/(r**2) + n*p*t2*(r*w + 1)/r + p*(t1 - 1)*w/r))\n end", "code_tokens": ["def", "newton_iter", "(", "r", ",", "n", ",", "p", ",", "x", ",", "y", ",", "w", ")", "t1", "=", "(", "r", "+", "1", ")", "**", "n", "t2", "=", "(", "r", "+", "1", ")", "**", "(", "n", "-", "1", ")", "(", "(", "y", "+", "t1", "x", "+", "p", "(", "t1", "-", "1", ")", "*", "(", "r", "w", "+", "1", ")", "/", "r", ")", "/", "(", "n", "t2", "x", "-", "p", "(", "t1", "-", "1", ")", "*", "(", "r", "w", "+", "1", ")", "/", "(", "r", "**", "2", ")", "+", "n", "p", "t2", "(", "r", "w", "+", "1", ")", "/", "r", "+", "p", "(", "t1", "-", "1", ")", "*", "w", "/", "r", ")", ")", "end"], "docstring": "This method was borrowed from the NumPy rate formula\n which was generated by Sage", "docstring_tokens": ["This", "method", "was", "borrowed", "from", "the", "NumPy", "rate", "formula", "which", "was", "generated", "by", "Sage"], "sha": "e0043557c403f392c48314830b3e527b3ae68eb2", "url": "https://github.com/noverde/exonio/blob/e0043557c403f392c48314830b3e527b3ae68eb2/lib/exonio/financial.rb#L191-L195", "partition": "test"} {"repo": "sensu-plugins/sensu-plugin", "path": "lib/sensu-handler.rb", "func_name": "Sensu.Handler.event_summary", "original_string": "def event_summary(trim_at = 100)\n summary = @event['check']['notification'] || @event['check']['description']\n if summary.nil?\n source = @event['check']['source'] || @event['client']['name']\n event_context = [source, @event['check']['name']].join('/')\n output = @event['check']['output'].chomp\n output = output.length > trim_at ? output[0..trim_at] + '...' : output\n summary = [event_context, output].join(' : ')\n end\n summary\n end", "language": "ruby", "code": "def event_summary(trim_at = 100)\n summary = @event['check']['notification'] || @event['check']['description']\n if summary.nil?\n source = @event['check']['source'] || @event['client']['name']\n event_context = [source, @event['check']['name']].join('/')\n output = @event['check']['output'].chomp\n output = output.length > trim_at ? output[0..trim_at] + '...' : output\n summary = [event_context, output].join(' : ')\n end\n summary\n end", "code_tokens": ["def", "event_summary", "(", "trim_at", "=", "100", ")", "summary", "=", "@event", "[", "'check'", "]", "[", "'notification'", "]", "||", "@event", "[", "'check'", "]", "[", "'description'", "]", "if", "summary", ".", "nil?", "source", "=", "@event", "[", "'check'", "]", "[", "'source'", "]", "||", "@event", "[", "'client'", "]", "[", "'name'", "]", "event_context", "=", "[", "source", ",", "@event", "[", "'check'", "]", "[", "'name'", "]", "]", ".", "join", "(", "'/'", ")", "output", "=", "@event", "[", "'check'", "]", "[", "'output'", "]", ".", "chomp", "output", "=", "output", ".", "length", ">", "trim_at", "?", "output", "[", "0", "..", "trim_at", "]", "+", "'...'", ":", "output", "summary", "=", "[", "event_context", ",", "output", "]", ".", "join", "(", "' : '", ")", "end", "summary", "end"], "docstring": "Helpers and filters.", "docstring_tokens": ["Helpers", "and", "filters", "."], "sha": "575ae8e9fecbb7c7ba8e962ac4dbb7c56b9b4ba7", "url": "https://github.com/sensu-plugins/sensu-plugin/blob/575ae8e9fecbb7c7ba8e962ac4dbb7c56b9b4ba7/lib/sensu-handler.rb#L97-L107", "partition": "test"} {"repo": "aquasync/ruby-ole", "path": "lib/ole/storage/base.rb", "func_name": "Ole.Storage.load", "original_string": "def load\n\t\t\t# we always read 512 for the header block. if the block size ends up being different,\n\t\t\t# what happens to the 109 fat entries. are there more/less entries?\n\t\t\t@io.rewind\n\t\t\theader_block = @io.read 512\n\t\t\t@header = Header.new header_block\n\n\t\t\t# create an empty bbat.\n\t\t\t@bbat = AllocationTable::Big.new self\n\t\t\tbbat_chain = header_block[Header::SIZE..-1].unpack 'V*'\n\t\t\tmbat_block = @header.mbat_start\n\t\t\t@header.num_mbat.times do\n\t\t\t\tblocks = @bbat.read([mbat_block]).unpack 'V*'\n\t\t\t\tmbat_block = blocks.pop\n\t\t\t\tbbat_chain += blocks\n\t\t\tend\n\t\t\t# am i using num_bat in the right way?\n\t\t\t@bbat.load @bbat.read(bbat_chain[0, @header.num_bat])\n\t\n\t\t\t# get block chain for directories, read it, then split it into chunks and load the\n\t\t\t# directory entries. semantics changed - used to cut at first dir where dir.type == 0\n\t\t\t@dirents = @bbat.read(@header.dirent_start).to_enum(:each_chunk, Dirent::SIZE).\n\t\t\t\tmap { |str| Dirent.new self, str }\n\n\t\t\t# now reorder from flat into a tree\n\t\t\t# links are stored in some kind of balanced binary tree\n\t\t\t# check that everything is visited at least, and at most once\n\t\t\t# similarly with the blocks of the file.\n\t\t\t# was thinking of moving this to Dirent.to_tree instead.\n\t\t\tclass << @dirents\n\t\t\t\tdef to_tree idx=0\n\t\t\t\t\treturn [] if idx == Dirent::EOT\n\t\t\t\t\td = self[idx]\n\t\t\t\t\tto_tree(d.child).each { |child| d << child }\n\t\t\t\t\traise FormatError, \"directory #{d.inspect} used twice\" if d.idx\n\t\t\t\t\td.idx = idx\n\t\t\t\t\tto_tree(d.prev) + [d] + to_tree(d.next)\n\t\t\t\tend\n\t\t\tend\n\n\t\t\t@root = @dirents.to_tree.first\n\t\t\t@dirents.reject! { |d| d.type_id == 0 }\n\t\t\t# silence this warning by default, its not really important (issue #5).\n\t\t\t# fairly common one appears to be \"R\" (from office OS X?) which smells\n\t\t\t# like some kind of UTF16 snafu, but scottwillson also has had some kanji...\n\t\t\t#Log.warn \"root name was #{@root.name.inspect}\" unless @root.name == 'Root Entry'\n\t\t\tunused = @dirents.reject(&:idx).length\n\t\t\tLog.warn \"#{unused} unused directories\" if unused > 0\n\n\t\t\t# FIXME i don't currently use @header.num_sbat which i should\n\t\t\t# hmm. nor do i write it. it means what exactly again?\n\t\t\t# which mode to use here?\n\t\t\t@sb_file = RangesIOResizeable.new @bbat, :first_block => @root.first_block, :size => @root.size\n\t\t\t@sbat = AllocationTable::Small.new self\n\t\t\t@sbat.load @bbat.read(@header.sbat_start)\n\t\tend", "language": "ruby", "code": "def load\n\t\t\t# we always read 512 for the header block. if the block size ends up being different,\n\t\t\t# what happens to the 109 fat entries. are there more/less entries?\n\t\t\t@io.rewind\n\t\t\theader_block = @io.read 512\n\t\t\t@header = Header.new header_block\n\n\t\t\t# create an empty bbat.\n\t\t\t@bbat = AllocationTable::Big.new self\n\t\t\tbbat_chain = header_block[Header::SIZE..-1].unpack 'V*'\n\t\t\tmbat_block = @header.mbat_start\n\t\t\t@header.num_mbat.times do\n\t\t\t\tblocks = @bbat.read([mbat_block]).unpack 'V*'\n\t\t\t\tmbat_block = blocks.pop\n\t\t\t\tbbat_chain += blocks\n\t\t\tend\n\t\t\t# am i using num_bat in the right way?\n\t\t\t@bbat.load @bbat.read(bbat_chain[0, @header.num_bat])\n\t\n\t\t\t# get block chain for directories, read it, then split it into chunks and load the\n\t\t\t# directory entries. semantics changed - used to cut at first dir where dir.type == 0\n\t\t\t@dirents = @bbat.read(@header.dirent_start).to_enum(:each_chunk, Dirent::SIZE).\n\t\t\t\tmap { |str| Dirent.new self, str }\n\n\t\t\t# now reorder from flat into a tree\n\t\t\t# links are stored in some kind of balanced binary tree\n\t\t\t# check that everything is visited at least, and at most once\n\t\t\t# similarly with the blocks of the file.\n\t\t\t# was thinking of moving this to Dirent.to_tree instead.\n\t\t\tclass << @dirents\n\t\t\t\tdef to_tree idx=0\n\t\t\t\t\treturn [] if idx == Dirent::EOT\n\t\t\t\t\td = self[idx]\n\t\t\t\t\tto_tree(d.child).each { |child| d << child }\n\t\t\t\t\traise FormatError, \"directory #{d.inspect} used twice\" if d.idx\n\t\t\t\t\td.idx = idx\n\t\t\t\t\tto_tree(d.prev) + [d] + to_tree(d.next)\n\t\t\t\tend\n\t\t\tend\n\n\t\t\t@root = @dirents.to_tree.first\n\t\t\t@dirents.reject! { |d| d.type_id == 0 }\n\t\t\t# silence this warning by default, its not really important (issue #5).\n\t\t\t# fairly common one appears to be \"R\" (from office OS X?) which smells\n\t\t\t# like some kind of UTF16 snafu, but scottwillson also has had some kanji...\n\t\t\t#Log.warn \"root name was #{@root.name.inspect}\" unless @root.name == 'Root Entry'\n\t\t\tunused = @dirents.reject(&:idx).length\n\t\t\tLog.warn \"#{unused} unused directories\" if unused > 0\n\n\t\t\t# FIXME i don't currently use @header.num_sbat which i should\n\t\t\t# hmm. nor do i write it. it means what exactly again?\n\t\t\t# which mode to use here?\n\t\t\t@sb_file = RangesIOResizeable.new @bbat, :first_block => @root.first_block, :size => @root.size\n\t\t\t@sbat = AllocationTable::Small.new self\n\t\t\t@sbat.load @bbat.read(@header.sbat_start)\n\t\tend", "code_tokens": ["def", "load", "# we always read 512 for the header block. if the block size ends up being different,", "# what happens to the 109 fat entries. are there more/less entries?", "@io", ".", "rewind", "header_block", "=", "@io", ".", "read", "512", "@header", "=", "Header", ".", "new", "header_block", "# create an empty bbat.", "@bbat", "=", "AllocationTable", "::", "Big", ".", "new", "self", "bbat_chain", "=", "header_block", "[", "Header", "::", "SIZE", "..", "-", "1", "]", ".", "unpack", "'V*'", "mbat_block", "=", "@header", ".", "mbat_start", "@header", ".", "num_mbat", ".", "times", "do", "blocks", "=", "@bbat", ".", "read", "(", "[", "mbat_block", "]", ")", ".", "unpack", "'V*'", "mbat_block", "=", "blocks", ".", "pop", "bbat_chain", "+=", "blocks", "end", "# am i using num_bat in the right way?", "@bbat", ".", "load", "@bbat", ".", "read", "(", "bbat_chain", "[", "0", ",", "@header", ".", "num_bat", "]", ")", "# get block chain for directories, read it, then split it into chunks and load the", "# directory entries. semantics changed - used to cut at first dir where dir.type == 0", "@dirents", "=", "@bbat", ".", "read", "(", "@header", ".", "dirent_start", ")", ".", "to_enum", "(", ":each_chunk", ",", "Dirent", "::", "SIZE", ")", ".", "map", "{", "|", "str", "|", "Dirent", ".", "new", "self", ",", "str", "}", "# now reorder from flat into a tree", "# links are stored in some kind of balanced binary tree", "# check that everything is visited at least, and at most once", "# similarly with the blocks of the file.", "# was thinking of moving this to Dirent.to_tree instead.", "class", "<<", "@dirents", "def", "to_tree", "idx", "=", "0", "return", "[", "]", "if", "idx", "==", "Dirent", "::", "EOT", "d", "=", "self", "[", "idx", "]", "to_tree", "(", "d", ".", "child", ")", ".", "each", "{", "|", "child", "|", "d", "<<", "child", "}", "raise", "FormatError", ",", "\"directory #{d.inspect} used twice\"", "if", "d", ".", "idx", "d", ".", "idx", "=", "idx", "to_tree", "(", "d", ".", "prev", ")", "+", "[", "d", "]", "+", "to_tree", "(", "d", ".", "next", ")", "end", "end", "@root", "=", "@dirents", ".", "to_tree", ".", "first", "@dirents", ".", "reject!", "{", "|", "d", "|", "d", ".", "type_id", "==", "0", "}", "# silence this warning by default, its not really important (issue #5).", "# fairly common one appears to be \"R\" (from office OS X?) which smells", "# like some kind of UTF16 snafu, but scottwillson also has had some kanji...", "#Log.warn \"root name was #{@root.name.inspect}\" unless @root.name == 'Root Entry'", "unused", "=", "@dirents", ".", "reject", "(", ":idx", ")", ".", "length", "Log", ".", "warn", "\"#{unused} unused directories\"", "if", "unused", ">", "0", "# FIXME i don't currently use @header.num_sbat which i should", "# hmm. nor do i write it. it means what exactly again?", "# which mode to use here?", "@sb_file", "=", "RangesIOResizeable", ".", "new", "@bbat", ",", ":first_block", "=>", "@root", ".", "first_block", ",", ":size", "=>", "@root", ".", "size", "@sbat", "=", "AllocationTable", "::", "Small", ".", "new", "self", "@sbat", ".", "load", "@bbat", ".", "read", "(", "@header", ".", "sbat_start", ")", "end"], "docstring": "load document from file.\n\n TODO: implement various allocationtable checks, maybe as a AllocationTable#fsck function :)\n\n 1. reterminate any chain not ending in EOC.\n compare file size with actually allocated blocks per file.\n 2. pass through all chain heads looking for collisions, and making sure nothing points to them\n (ie they are really heads). in both sbat and mbat\n 3. we know the locations of the bbat data, and mbat data. ensure that there are placeholder blocks\n in the bat for them.\n 4. maybe a check of excess data. if there is data outside the bbat.truncate.length + 1 * block_size,\n (eg what is used for truncate in #flush), then maybe add some sort of message about that. it\n will be automatically thrown away at close time.", "docstring_tokens": ["load", "document", "from", "file", "."], "sha": "f6e8155c0d81f6748d9d4e4836dadc251c73feea", "url": "https://github.com/aquasync/ruby-ole/blob/f6e8155c0d81f6748d9d4e4836dadc251c73feea/lib/ole/storage/base.rb#L107-L162", "partition": "test"} {"repo": "aquasync/ruby-ole", "path": "lib/ole/storage/base.rb", "func_name": "Ole.Storage.repack", "original_string": "def repack temp=:file\n\t\t\tcase temp\n\t\t\twhen :file\n\t\t\t\tTempfile.open 'ole-repack' do |io|\n\t\t\t\t\tio.binmode\n\t\t\t\t\trepack_using_io io\n\t\t\t\tend\n\t\t\twhen :mem; StringIO.open(''.dup, &method(:repack_using_io))\n\t\t\telse raise ArgumentError, \"unknown temp backing #{temp.inspect}\"\n\t\t\tend\n\t\tend", "language": "ruby", "code": "def repack temp=:file\n\t\t\tcase temp\n\t\t\twhen :file\n\t\t\t\tTempfile.open 'ole-repack' do |io|\n\t\t\t\t\tio.binmode\n\t\t\t\t\trepack_using_io io\n\t\t\t\tend\n\t\t\twhen :mem; StringIO.open(''.dup, &method(:repack_using_io))\n\t\t\telse raise ArgumentError, \"unknown temp backing #{temp.inspect}\"\n\t\t\tend\n\t\tend", "code_tokens": ["def", "repack", "temp", "=", ":file", "case", "temp", "when", ":file", "Tempfile", ".", "open", "'ole-repack'", "do", "|", "io", "|", "io", ".", "binmode", "repack_using_io", "io", "end", "when", ":mem", ";", "StringIO", ".", "open", "(", "''", ".", "dup", ",", "method", "(", ":repack_using_io", ")", ")", "else", "raise", "ArgumentError", ",", "\"unknown temp backing #{temp.inspect}\"", "end", "end"], "docstring": "could be useful with mis-behaving ole documents. or to just clean them up.", "docstring_tokens": ["could", "be", "useful", "with", "mis", "-", "behaving", "ole", "documents", ".", "or", "to", "just", "clean", "them", "up", "."], "sha": "f6e8155c0d81f6748d9d4e4836dadc251c73feea", "url": "https://github.com/aquasync/ruby-ole/blob/f6e8155c0d81f6748d9d4e4836dadc251c73feea/lib/ole/storage/base.rb#L311-L321", "partition": "test"} {"repo": "duncanjbrown/wp-api-client", "path": "lib/wp_api_client/relationship.rb", "func_name": "WpApiClient.Relationship.load_relation", "original_string": "def load_relation(relationship, position = nil)\n if objects = @resource.dig(\"_embedded\", relationship)\n location = position ? objects[position] : objects\n begin\n WpApiClient::Collection.new(location)\n rescue WpApiClient::ErrorResponse\n load_from_links(relationship, position)\n end\n else\n load_from_links(relationship, position)\n end\n end", "language": "ruby", "code": "def load_relation(relationship, position = nil)\n if objects = @resource.dig(\"_embedded\", relationship)\n location = position ? objects[position] : objects\n begin\n WpApiClient::Collection.new(location)\n rescue WpApiClient::ErrorResponse\n load_from_links(relationship, position)\n end\n else\n load_from_links(relationship, position)\n end\n end", "code_tokens": ["def", "load_relation", "(", "relationship", ",", "position", "=", "nil", ")", "if", "objects", "=", "@resource", ".", "dig", "(", "\"_embedded\"", ",", "relationship", ")", "location", "=", "position", "?", "objects", "[", "position", "]", ":", "objects", "begin", "WpApiClient", "::", "Collection", ".", "new", "(", "location", ")", "rescue", "WpApiClient", "::", "ErrorResponse", "load_from_links", "(", "relationship", ",", "position", ")", "end", "else", "load_from_links", "(", "relationship", ",", "position", ")", "end", "end"], "docstring": "try to load an embedded object; call out to the API if not", "docstring_tokens": ["try", "to", "load", "an", "embedded", "object", ";", "call", "out", "to", "the", "API", "if", "not"], "sha": "efdf39efc8176cfd054ea4a6e66fd37622d4f190", "url": "https://github.com/duncanjbrown/wp-api-client/blob/efdf39efc8176cfd054ea4a6e66fd37622d4f190/lib/wp_api_client/relationship.rb#L109-L120", "partition": "test"} {"repo": "duncanjbrown/wp-api-client", "path": "lib/wp_api_client/client.rb", "func_name": "WpApiClient.Client.native_representation_of", "original_string": "def native_representation_of(response_body)\n # Do we have a collection of objects?\n if response_body.is_a? Array\n WpApiClient::Collection.new(response_body, @headers)\n else\n WpApiClient::Entities::Base.build(response_body)\n end\n end", "language": "ruby", "code": "def native_representation_of(response_body)\n # Do we have a collection of objects?\n if response_body.is_a? Array\n WpApiClient::Collection.new(response_body, @headers)\n else\n WpApiClient::Entities::Base.build(response_body)\n end\n end", "code_tokens": ["def", "native_representation_of", "(", "response_body", ")", "# Do we have a collection of objects?", "if", "response_body", ".", "is_a?", "Array", "WpApiClient", "::", "Collection", ".", "new", "(", "response_body", ",", "@headers", ")", "else", "WpApiClient", "::", "Entities", "::", "Base", ".", "build", "(", "response_body", ")", "end", "end"], "docstring": "Take the API response and figure out what it is", "docstring_tokens": ["Take", "the", "API", "response", "and", "figure", "out", "what", "it", "is"], "sha": "efdf39efc8176cfd054ea4a6e66fd37622d4f190", "url": "https://github.com/duncanjbrown/wp-api-client/blob/efdf39efc8176cfd054ea4a6e66fd37622d4f190/lib/wp_api_client/client.rb#L33-L40", "partition": "test"} {"repo": "cryptape/cita-sdk-ruby", "path": "lib/cita/contract.rb", "func_name": "CITA.Contract.call_func", "original_string": "def call_func(method:, params: [], tx: {}) # rubocop:disable Naming/UncommunicativeMethodParamName\n data, output_types = function_data_with_ot(method, *params)\n resp = @rpc.call_rpc(:call, params: [tx.merge(data: data, to: address), \"latest\"])\n result = resp[\"result\"]\n\n data = [Utils.remove_hex_prefix(result)].pack(\"H*\")\n return if data.nil?\n\n re = decode_abi output_types, data\n re.length == 1 ? re.first : re\n end", "language": "ruby", "code": "def call_func(method:, params: [], tx: {}) # rubocop:disable Naming/UncommunicativeMethodParamName\n data, output_types = function_data_with_ot(method, *params)\n resp = @rpc.call_rpc(:call, params: [tx.merge(data: data, to: address), \"latest\"])\n result = resp[\"result\"]\n\n data = [Utils.remove_hex_prefix(result)].pack(\"H*\")\n return if data.nil?\n\n re = decode_abi output_types, data\n re.length == 1 ? re.first : re\n end", "code_tokens": ["def", "call_func", "(", "method", ":", ",", "params", ":", "[", "]", ",", "tx", ":", "{", "}", ")", "# rubocop:disable Naming/UncommunicativeMethodParamName", "data", ",", "output_types", "=", "function_data_with_ot", "(", "method", ",", "params", ")", "resp", "=", "@rpc", ".", "call_rpc", "(", ":call", ",", "params", ":", "[", "tx", ".", "merge", "(", "data", ":", "data", ",", "to", ":", "address", ")", ",", "\"latest\"", "]", ")", "result", "=", "resp", "[", "\"result\"", "]", "data", "=", "[", "Utils", ".", "remove_hex_prefix", "(", "result", ")", "]", ".", "pack", "(", "\"H*\"", ")", "return", "if", "data", ".", "nil?", "re", "=", "decode_abi", "output_types", ",", "data", "re", ".", "length", "==", "1", "?", "re", ".", "first", ":", "re", "end"], "docstring": "call contract functions by rpc `call` method\n\n @param method [Symbol | String] the method name you call\n @param params [Array] the method params you call\n @param tx [Hash] see rpc `call` doc for more info\n\n @return [any]", "docstring_tokens": ["call", "contract", "functions", "by", "rpc", "call", "method"], "sha": "47f4a9f0886c25a871ef785462b444e1d87dd397", "url": "https://github.com/cryptape/cita-sdk-ruby/blob/47f4a9f0886c25a871ef785462b444e1d87dd397/lib/cita/contract.rb#L43-L53", "partition": "test"} {"repo": "cryptape/cita-sdk-ruby", "path": "lib/cita/contract.rb", "func_name": "CITA.Contract.send_func", "original_string": "def send_func(tx:, private_key:, method:, params: []) # rubocop:disable Naming/UncommunicativeMethodParamName\n data, _output_types = function_data_with_ot(method, *params)\n transaction = if tx.is_a?(Hash)\n Transaction.from_hash(tx)\n else\n tx\n end\n transaction.data = data\n resp = @rpc.send_transaction(transaction, private_key)\n\n resp&.dig(\"result\")\n end", "language": "ruby", "code": "def send_func(tx:, private_key:, method:, params: []) # rubocop:disable Naming/UncommunicativeMethodParamName\n data, _output_types = function_data_with_ot(method, *params)\n transaction = if tx.is_a?(Hash)\n Transaction.from_hash(tx)\n else\n tx\n end\n transaction.data = data\n resp = @rpc.send_transaction(transaction, private_key)\n\n resp&.dig(\"result\")\n end", "code_tokens": ["def", "send_func", "(", "tx", ":", ",", "private_key", ":", ",", "method", ":", ",", "params", ":", "[", "]", ")", "# rubocop:disable Naming/UncommunicativeMethodParamName", "data", ",", "_output_types", "=", "function_data_with_ot", "(", "method", ",", "params", ")", "transaction", "=", "if", "tx", ".", "is_a?", "(", "Hash", ")", "Transaction", ".", "from_hash", "(", "tx", ")", "else", "tx", "end", "transaction", ".", "data", "=", "data", "resp", "=", "@rpc", ".", "send_transaction", "(", "transaction", ",", "private_key", ")", "resp", "&.", "dig", "(", "\"result\"", ")", "end"], "docstring": "call contract functions by sendRawTransaction\n\n @param tx [Hash | CITA::Transaction]\n @param private_key [String] hex string\n @param method [Symbol | String] method name you call\n @param *params [Array] your params\n\n @return [nil | Hash] {hash: \"\", status: \"\"}, sendRawTransactionResult", "docstring_tokens": ["call", "contract", "functions", "by", "sendRawTransaction"], "sha": "47f4a9f0886c25a871ef785462b444e1d87dd397", "url": "https://github.com/cryptape/cita-sdk-ruby/blob/47f4a9f0886c25a871ef785462b444e1d87dd397/lib/cita/contract.rb#L63-L74", "partition": "test"} {"repo": "cryptape/cita-sdk-ruby", "path": "lib/cita/contract.rb", "func_name": "CITA.Contract.parse_url", "original_string": "def parse_url\n uri = URI.parse(@url)\n @host = uri.host\n @port = uri.port\n @scheme = uri.scheme\n end", "language": "ruby", "code": "def parse_url\n uri = URI.parse(@url)\n @host = uri.host\n @port = uri.port\n @scheme = uri.scheme\n end", "code_tokens": ["def", "parse_url", "uri", "=", "URI", ".", "parse", "(", "@url", ")", "@host", "=", "uri", ".", "host", "@port", "=", "uri", ".", "port", "@scheme", "=", "uri", ".", "scheme", "end"], "docstring": "parse url to host, port and scheme", "docstring_tokens": ["parse", "url", "to", "host", "port", "and", "scheme"], "sha": "47f4a9f0886c25a871ef785462b444e1d87dd397", "url": "https://github.com/cryptape/cita-sdk-ruby/blob/47f4a9f0886c25a871ef785462b444e1d87dd397/lib/cita/contract.rb#L79-L84", "partition": "test"} {"repo": "cryptape/cita-sdk-ruby", "path": "lib/cita/http.rb", "func_name": "CITA.Http.call_rpc", "original_string": "def call_rpc(method, jsonrpc: DEFAULT_JSONRPC, params: DEFAULT_PARAMS, id: DEFAULT_ID)\n conn.post(\"/\", rpc_params(method, jsonrpc: jsonrpc, params: params, id: id))\n end", "language": "ruby", "code": "def call_rpc(method, jsonrpc: DEFAULT_JSONRPC, params: DEFAULT_PARAMS, id: DEFAULT_ID)\n conn.post(\"/\", rpc_params(method, jsonrpc: jsonrpc, params: params, id: id))\n end", "code_tokens": ["def", "call_rpc", "(", "method", ",", "jsonrpc", ":", "DEFAULT_JSONRPC", ",", "params", ":", "DEFAULT_PARAMS", ",", "id", ":", "DEFAULT_ID", ")", "conn", ".", "post", "(", "\"/\"", ",", "rpc_params", "(", "method", ",", "jsonrpc", ":", "jsonrpc", ",", "params", ":", "params", ",", "id", ":", "id", ")", ")", "end"], "docstring": "wrapper for call rpc method\n\n @param method [String] method you want to call\n @param jsonrpc [String] jsonrpc version\n @param params [Array] rpc params\n @param id [Integer] jsonrpc id\n\n @return [Faraday::Response]", "docstring_tokens": ["wrapper", "for", "call", "rpc", "method"], "sha": "47f4a9f0886c25a871ef785462b444e1d87dd397", "url": "https://github.com/cryptape/cita-sdk-ruby/blob/47f4a9f0886c25a871ef785462b444e1d87dd397/lib/cita/http.rb#L25-L27", "partition": "test"} {"repo": "cryptape/cita-sdk-ruby", "path": "lib/cita/http.rb", "func_name": "CITA.Http.rpc_params", "original_string": "def rpc_params(method, jsonrpc: DEFAULT_JSONRPC, params: DEFAULT_PARAMS, id: DEFAULT_ID)\n {\n jsonrpc: jsonrpc,\n id: id,\n method: method,\n params: params\n }.to_json\n end", "language": "ruby", "code": "def rpc_params(method, jsonrpc: DEFAULT_JSONRPC, params: DEFAULT_PARAMS, id: DEFAULT_ID)\n {\n jsonrpc: jsonrpc,\n id: id,\n method: method,\n params: params\n }.to_json\n end", "code_tokens": ["def", "rpc_params", "(", "method", ",", "jsonrpc", ":", "DEFAULT_JSONRPC", ",", "params", ":", "DEFAULT_PARAMS", ",", "id", ":", "DEFAULT_ID", ")", "{", "jsonrpc", ":", "jsonrpc", ",", "id", ":", "id", ",", "method", ":", "method", ",", "params", ":", "params", "}", ".", "to_json", "end"], "docstring": "wrapper for rpc params\n\n @param method [String] method you want to call\n @param jsonrpc [String] jsonrpc version\n @param params [Array] rpc params\n @param id [Integer] jsonrpc id\n\n @return [String] json string", "docstring_tokens": ["wrapper", "for", "rpc", "params"], "sha": "47f4a9f0886c25a871ef785462b444e1d87dd397", "url": "https://github.com/cryptape/cita-sdk-ruby/blob/47f4a9f0886c25a871ef785462b444e1d87dd397/lib/cita/http.rb#L37-L44", "partition": "test"} {"repo": "cryptape/cita-sdk-ruby", "path": "lib/cita/http.rb", "func_name": "CITA.Http.conn", "original_string": "def conn\n Faraday.new(url: url) do |faraday|\n faraday.headers[\"Content-Type\"] = \"application/json\"\n faraday.request :url_encoded # form-encode POST params\n faraday.adapter Faraday.default_adapter # make requests with Net::HTTP\n end\n end", "language": "ruby", "code": "def conn\n Faraday.new(url: url) do |faraday|\n faraday.headers[\"Content-Type\"] = \"application/json\"\n faraday.request :url_encoded # form-encode POST params\n faraday.adapter Faraday.default_adapter # make requests with Net::HTTP\n end\n end", "code_tokens": ["def", "conn", "Faraday", ".", "new", "(", "url", ":", "url", ")", "do", "|", "faraday", "|", "faraday", ".", "headers", "[", "\"Content-Type\"", "]", "=", "\"application/json\"", "faraday", ".", "request", ":url_encoded", "# form-encode POST params", "faraday", ".", "adapter", "Faraday", ".", "default_adapter", "# make requests with Net::HTTP", "end", "end"], "docstring": "wrapper faraday object with CITA URL and Content-Type\n\n @return [Faraday]", "docstring_tokens": ["wrapper", "faraday", "object", "with", "CITA", "URL", "and", "Content", "-", "Type"], "sha": "47f4a9f0886c25a871ef785462b444e1d87dd397", "url": "https://github.com/cryptape/cita-sdk-ruby/blob/47f4a9f0886c25a871ef785462b444e1d87dd397/lib/cita/http.rb#L49-L55", "partition": "test"} {"repo": "cryptape/cita-sdk-ruby", "path": "lib/cita/rpc.rb", "func_name": "CITA.RPC.transfer", "original_string": "def transfer(to:, private_key:, value:, quota: 30_000)\n valid_until_block = block_number[\"result\"].hex + 88\n meta_data = get_meta_data(\"latest\")[\"result\"]\n version = meta_data[\"version\"]\n chain_id = if version.zero?\n meta_data[\"chainId\"]\n elsif version == 1\n meta_data[\"chainIdV1\"]\n end\n transaction = Transaction.new(nonce: Utils.nonce, valid_until_block: valid_until_block, chain_id: chain_id, to: to, value: value, quota: quota, version: version)\n send_transaction(transaction, private_key)\n end", "language": "ruby", "code": "def transfer(to:, private_key:, value:, quota: 30_000)\n valid_until_block = block_number[\"result\"].hex + 88\n meta_data = get_meta_data(\"latest\")[\"result\"]\n version = meta_data[\"version\"]\n chain_id = if version.zero?\n meta_data[\"chainId\"]\n elsif version == 1\n meta_data[\"chainIdV1\"]\n end\n transaction = Transaction.new(nonce: Utils.nonce, valid_until_block: valid_until_block, chain_id: chain_id, to: to, value: value, quota: quota, version: version)\n send_transaction(transaction, private_key)\n end", "code_tokens": ["def", "transfer", "(", "to", ":", ",", "private_key", ":", ",", "value", ":", ",", "quota", ":", "30_000", ")", "valid_until_block", "=", "block_number", "[", "\"result\"", "]", ".", "hex", "+", "88", "meta_data", "=", "get_meta_data", "(", "\"latest\"", ")", "[", "\"result\"", "]", "version", "=", "meta_data", "[", "\"version\"", "]", "chain_id", "=", "if", "version", ".", "zero?", "meta_data", "[", "\"chainId\"", "]", "elsif", "version", "==", "1", "meta_data", "[", "\"chainIdV1\"", "]", "end", "transaction", "=", "Transaction", ".", "new", "(", "nonce", ":", "Utils", ".", "nonce", ",", "valid_until_block", ":", "valid_until_block", ",", "chain_id", ":", "chain_id", ",", "to", ":", "to", ",", "value", ":", "value", ",", "quota", ":", "quota", ",", "version", ":", "version", ")", "send_transaction", "(", "transaction", ",", "private_key", ")", "end"], "docstring": "easy to transfer tokens\n\n @param to [String] to address\n @param private_key [String]\n @param value [String | Integer] hex string or decimal integer\n @param quota [Integer] default to 30_000\n\n @return [Hash]", "docstring_tokens": ["easy", "to", "transfer", "tokens"], "sha": "47f4a9f0886c25a871ef785462b444e1d87dd397", "url": "https://github.com/cryptape/cita-sdk-ruby/blob/47f4a9f0886c25a871ef785462b444e1d87dd397/lib/cita/rpc.rb#L73-L84", "partition": "test"} {"repo": "opal/opal-browser", "path": "opal/browser/storage.rb", "func_name": "Browser.Storage.replace", "original_string": "def replace(new)\n if String === new\n @data.replace(JSON.parse(new))\n else\n @data.replace(new)\n end\n end", "language": "ruby", "code": "def replace(new)\n if String === new\n @data.replace(JSON.parse(new))\n else\n @data.replace(new)\n end\n end", "code_tokens": ["def", "replace", "(", "new", ")", "if", "String", "===", "new", "@data", ".", "replace", "(", "JSON", ".", "parse", "(", "new", ")", ")", "else", "@data", ".", "replace", "(", "new", ")", "end", "end"], "docstring": "Replace the current storage with the given one.\n\n @param new [Hash, String] if new is a {String} it will be parsed as JSON", "docstring_tokens": ["Replace", "the", "current", "storage", "with", "the", "given", "one", "."], "sha": "e3ec6928e43705db50741a38bd198f7aebaaf0f5", "url": "https://github.com/opal/opal-browser/blob/e3ec6928e43705db50741a38bd198f7aebaaf0f5/opal/browser/storage.rb#L108-L114", "partition": "test"} {"repo": "opal/opal-browser", "path": "opal/browser/storage.rb", "func_name": "Browser.Storage.to_json", "original_string": "def to_json\n io = StringIO.new(\"{\")\n\n io << JSON.create_id.to_json << \":\" << self.class.name.to_json << \",\"\n\n @data.each {|key, value|\n io << key.to_json.to_s << \":\" << value.to_json << \",\"\n }\n\n io.seek(-1, IO::SEEK_CUR)\n io << \"}\"\n\n io.string\n end", "language": "ruby", "code": "def to_json\n io = StringIO.new(\"{\")\n\n io << JSON.create_id.to_json << \":\" << self.class.name.to_json << \",\"\n\n @data.each {|key, value|\n io << key.to_json.to_s << \":\" << value.to_json << \",\"\n }\n\n io.seek(-1, IO::SEEK_CUR)\n io << \"}\"\n\n io.string\n end", "code_tokens": ["def", "to_json", "io", "=", "StringIO", ".", "new", "(", "\"{\"", ")", "io", "<<", "JSON", ".", "create_id", ".", "to_json", "<<", "\":\"", "<<", "self", ".", "class", ".", "name", ".", "to_json", "<<", "\",\"", "@data", ".", "each", "{", "|", "key", ",", "value", "|", "io", "<<", "key", ".", "to_json", ".", "to_s", "<<", "\":\"", "<<", "value", ".", "to_json", "<<", "\",\"", "}", "io", ".", "seek", "(", "-", "1", ",", "IO", "::", "SEEK_CUR", ")", "io", "<<", "\"}\"", "io", ".", "string", "end"], "docstring": "Convert the storage to JSON.\n\n @return [String] the JSON representation", "docstring_tokens": ["Convert", "the", "storage", "to", "JSON", "."], "sha": "e3ec6928e43705db50741a38bd198f7aebaaf0f5", "url": "https://github.com/opal/opal-browser/blob/e3ec6928e43705db50741a38bd198f7aebaaf0f5/opal/browser/storage.rb#L198-L211", "partition": "test"} {"repo": "opal/opal-browser", "path": "opal/browser/console.rb", "func_name": "Browser.Console.time", "original_string": "def time(label, &block)\n raise ArgumentError, \"no block given\" unless block\n\n `#@native.time(label)`\n\n begin\n if block.arity == 0\n instance_exec(&block)\n else\n block.call(self)\n end\n ensure\n `#@native.timeEnd()`\n end\n end", "language": "ruby", "code": "def time(label, &block)\n raise ArgumentError, \"no block given\" unless block\n\n `#@native.time(label)`\n\n begin\n if block.arity == 0\n instance_exec(&block)\n else\n block.call(self)\n end\n ensure\n `#@native.timeEnd()`\n end\n end", "code_tokens": ["def", "time", "(", "label", ",", "&", "block", ")", "raise", "ArgumentError", ",", "\"no block given\"", "unless", "block", "`", "`", "begin", "if", "block", ".", "arity", "==", "0", "instance_exec", "(", "block", ")", "else", "block", ".", "call", "(", "self", ")", "end", "ensure", "`", "`", "end", "end"], "docstring": "Time the given block with the given label.", "docstring_tokens": ["Time", "the", "given", "block", "with", "the", "given", "label", "."], "sha": "e3ec6928e43705db50741a38bd198f7aebaaf0f5", "url": "https://github.com/opal/opal-browser/blob/e3ec6928e43705db50741a38bd198f7aebaaf0f5/opal/browser/console.rb#L43-L57", "partition": "test"} {"repo": "opal/opal-browser", "path": "opal/browser/console.rb", "func_name": "Browser.Console.group", "original_string": "def group(*args, &block)\n raise ArgumentError, \"no block given\" unless block\n\n `#@native.group.apply(#@native, args)`\n\n begin\n if block.arity == 0\n instance_exec(&block)\n else\n block.call(self)\n end\n ensure\n `#@native.groupEnd()`\n end\n end", "language": "ruby", "code": "def group(*args, &block)\n raise ArgumentError, \"no block given\" unless block\n\n `#@native.group.apply(#@native, args)`\n\n begin\n if block.arity == 0\n instance_exec(&block)\n else\n block.call(self)\n end\n ensure\n `#@native.groupEnd()`\n end\n end", "code_tokens": ["def", "group", "(", "*", "args", ",", "&", "block", ")", "raise", "ArgumentError", ",", "\"no block given\"", "unless", "block", "`", "`", "begin", "if", "block", ".", "arity", "==", "0", "instance_exec", "(", "block", ")", "else", "block", ".", "call", "(", "self", ")", "end", "ensure", "`", "`", "end", "end"], "docstring": "Group the given block.", "docstring_tokens": ["Group", "the", "given", "block", "."], "sha": "e3ec6928e43705db50741a38bd198f7aebaaf0f5", "url": "https://github.com/opal/opal-browser/blob/e3ec6928e43705db50741a38bd198f7aebaaf0f5/opal/browser/console.rb#L60-L74", "partition": "test"} {"repo": "opal/opal-browser", "path": "opal/browser/console.rb", "func_name": "Browser.Console.group!", "original_string": "def group!(*args, &block)\n return unless block_given?\n\n `#@native.groupCollapsed.apply(#@native, args)`\n\n begin\n if block.arity == 0\n instance_exec(&block)\n else\n block.call(self)\n end\n ensure\n `#@native.groupEnd()`\n end\n end", "language": "ruby", "code": "def group!(*args, &block)\n return unless block_given?\n\n `#@native.groupCollapsed.apply(#@native, args)`\n\n begin\n if block.arity == 0\n instance_exec(&block)\n else\n block.call(self)\n end\n ensure\n `#@native.groupEnd()`\n end\n end", "code_tokens": ["def", "group!", "(", "*", "args", ",", "&", "block", ")", "return", "unless", "block_given?", "`", "`", "begin", "if", "block", ".", "arity", "==", "0", "instance_exec", "(", "block", ")", "else", "block", ".", "call", "(", "self", ")", "end", "ensure", "`", "`", "end", "end"], "docstring": "Group the given block but collapse it.", "docstring_tokens": ["Group", "the", "given", "block", "but", "collapse", "it", "."], "sha": "e3ec6928e43705db50741a38bd198f7aebaaf0f5", "url": "https://github.com/opal/opal-browser/blob/e3ec6928e43705db50741a38bd198f7aebaaf0f5/opal/browser/console.rb#L77-L91", "partition": "test"} {"repo": "ejholmes/metaforce", "path": "lib/metaforce/abstract_client.rb", "func_name": "Metaforce.AbstractClient.authenticate!", "original_string": "def authenticate!\n options = authentication_handler.call(self, @options)\n @options.merge!(options)\n client.config.soap_header = soap_headers\n end", "language": "ruby", "code": "def authenticate!\n options = authentication_handler.call(self, @options)\n @options.merge!(options)\n client.config.soap_header = soap_headers\n end", "code_tokens": ["def", "authenticate!", "options", "=", "authentication_handler", ".", "call", "(", "self", ",", "@options", ")", "@options", ".", "merge!", "(", "options", ")", "client", ".", "config", ".", "soap_header", "=", "soap_headers", "end"], "docstring": "Internal Calls the authentication handler, which should set @options to a new\n hash.", "docstring_tokens": ["Internal", "Calls", "the", "authentication", "handler", "which", "should", "set"], "sha": "2e13c1fb28bd4d0f181c63d9acbab6b3632f02e1", "url": "https://github.com/ejholmes/metaforce/blob/2e13c1fb28bd4d0f181c63d9acbab6b3632f02e1/lib/metaforce/abstract_client.rb#L60-L64", "partition": "test"} {"repo": "devxoul/CocoaSeeds", "path": "lib/cocoaseeds/xcodehelper.rb", "func_name": "Xcodeproj.Project.new_with_uuid", "original_string": "def new_with_uuid(klass, uuid)\n if klass.is_a?(String)\n klass = Object.const_get(klass)\n end\n object = klass.new(self, uuid)\n object.initialize_defaults\n object\n end", "language": "ruby", "code": "def new_with_uuid(klass, uuid)\n if klass.is_a?(String)\n klass = Object.const_get(klass)\n end\n object = klass.new(self, uuid)\n object.initialize_defaults\n object\n end", "code_tokens": ["def", "new_with_uuid", "(", "klass", ",", "uuid", ")", "if", "klass", ".", "is_a?", "(", "String", ")", "klass", "=", "Object", ".", "const_get", "(", "klass", ")", "end", "object", "=", "klass", ".", "new", "(", "self", ",", "uuid", ")", "object", ".", "initialize_defaults", "object", "end"], "docstring": "Creates a new object with given UUID.\n\n @param [String] uuid UUID of the object.", "docstring_tokens": ["Creates", "a", "new", "object", "with", "given", "UUID", "."], "sha": "c0fcc7b3fe0b039d3f25c95559f7cf8935774065", "url": "https://github.com/devxoul/CocoaSeeds/blob/c0fcc7b3fe0b039d3f25c95559f7cf8935774065/lib/cocoaseeds/xcodehelper.rb#L9-L16", "partition": "test"} {"repo": "devxoul/CocoaSeeds", "path": "lib/cocoaseeds/xcodehelper.rb", "func_name": "Xcodeproj::Project::Object.PBXGroup.new_reference_with_uuid", "original_string": "def new_reference_with_uuid(path, uuid, source_tree = :group)\n # customize `FileReferencesFactory.new_file_reference`\n path = Pathname.new(path)\n ref = self.project.new_with_uuid(PBXFileReference, uuid)\n self.children << ref\n GroupableHelper.set_path_with_source_tree(ref, path, source_tree)\n ref.set_last_known_file_type\n\n # customize `FileReferencesFactory.configure_defaults_for_file_reference`\n if ref.path.include?('/')\n ref.name = ref.path.split('/').last\n end\n if File.extname(ref.path).downcase == '.framework'\n ref.include_in_index = nil\n end\n\n ref\n end", "language": "ruby", "code": "def new_reference_with_uuid(path, uuid, source_tree = :group)\n # customize `FileReferencesFactory.new_file_reference`\n path = Pathname.new(path)\n ref = self.project.new_with_uuid(PBXFileReference, uuid)\n self.children << ref\n GroupableHelper.set_path_with_source_tree(ref, path, source_tree)\n ref.set_last_known_file_type\n\n # customize `FileReferencesFactory.configure_defaults_for_file_reference`\n if ref.path.include?('/')\n ref.name = ref.path.split('/').last\n end\n if File.extname(ref.path).downcase == '.framework'\n ref.include_in_index = nil\n end\n\n ref\n end", "code_tokens": ["def", "new_reference_with_uuid", "(", "path", ",", "uuid", ",", "source_tree", "=", ":group", ")", "# customize `FileReferencesFactory.new_file_reference`", "path", "=", "Pathname", ".", "new", "(", "path", ")", "ref", "=", "self", ".", "project", ".", "new_with_uuid", "(", "PBXFileReference", ",", "uuid", ")", "self", ".", "children", "<<", "ref", "GroupableHelper", ".", "set_path_with_source_tree", "(", "ref", ",", "path", ",", "source_tree", ")", "ref", ".", "set_last_known_file_type", "# customize `FileReferencesFactory.configure_defaults_for_file_reference`", "if", "ref", ".", "path", ".", "include?", "(", "'/'", ")", "ref", ".", "name", "=", "ref", ".", "path", ".", "split", "(", "'/'", ")", ".", "last", "end", "if", "File", ".", "extname", "(", "ref", ".", "path", ")", ".", "downcase", "==", "'.framework'", "ref", ".", "include_in_index", "=", "nil", "end", "ref", "end"], "docstring": "Creates a file reference with given UUID.\n\n @param [String] uuid UUID of the object.", "docstring_tokens": ["Creates", "a", "file", "reference", "with", "given", "UUID", "."], "sha": "c0fcc7b3fe0b039d3f25c95559f7cf8935774065", "url": "https://github.com/devxoul/CocoaSeeds/blob/c0fcc7b3fe0b039d3f25c95559f7cf8935774065/lib/cocoaseeds/xcodehelper.rb#L68-L85", "partition": "test"} {"repo": "devxoul/CocoaSeeds", "path": "lib/cocoaseeds/xcodehelper.rb", "func_name": "Xcodeproj::Project::Object.AbstractBuildPhase.add_file_reference_with_uuid", "original_string": "def add_file_reference_with_uuid(file_ref, uuid, avoid_duplicates = false)\n if avoid_duplicates && existing = build_file(file_ref)\n existing\n else\n build_file = project.new_with_uuid(PBXBuildFile, uuid)\n build_file.file_ref = file_ref\n files.insert(0, build_file)\n build_file\n end\n end", "language": "ruby", "code": "def add_file_reference_with_uuid(file_ref, uuid, avoid_duplicates = false)\n if avoid_duplicates && existing = build_file(file_ref)\n existing\n else\n build_file = project.new_with_uuid(PBXBuildFile, uuid)\n build_file.file_ref = file_ref\n files.insert(0, build_file)\n build_file\n end\n end", "code_tokens": ["def", "add_file_reference_with_uuid", "(", "file_ref", ",", "uuid", ",", "avoid_duplicates", "=", "false", ")", "if", "avoid_duplicates", "&&", "existing", "=", "build_file", "(", "file_ref", ")", "existing", "else", "build_file", "=", "project", ".", "new_with_uuid", "(", "PBXBuildFile", ",", "uuid", ")", "build_file", ".", "file_ref", "=", "file_ref", "files", ".", "insert", "(", "0", ",", "build_file", ")", "build_file", "end", "end"], "docstring": "Adds the file reference with given UUID.\n\n @param [String] uuid UUID of the object.", "docstring_tokens": ["Adds", "the", "file", "reference", "with", "given", "UUID", "."], "sha": "c0fcc7b3fe0b039d3f25c95559f7cf8935774065", "url": "https://github.com/devxoul/CocoaSeeds/blob/c0fcc7b3fe0b039d3f25c95559f7cf8935774065/lib/cocoaseeds/xcodehelper.rb#L123-L132", "partition": "test"} {"repo": "devxoul/CocoaSeeds", "path": "lib/cocoaseeds/core.rb", "func_name": "Seeds.Core.remove_seeds", "original_string": "def remove_seeds\n removings = self.locks.keys - self.seeds.keys\n removings.each do |name|\n say \"Removing #{name} (#{self.locks[name].version})\".red\n dirname = File.join(self.root_path, \"Seeds\", name)\n FileUtils.rm_rf(dirname)\n end\n end", "language": "ruby", "code": "def remove_seeds\n removings = self.locks.keys - self.seeds.keys\n removings.each do |name|\n say \"Removing #{name} (#{self.locks[name].version})\".red\n dirname = File.join(self.root_path, \"Seeds\", name)\n FileUtils.rm_rf(dirname)\n end\n end", "code_tokens": ["def", "remove_seeds", "removings", "=", "self", ".", "locks", ".", "keys", "-", "self", ".", "seeds", ".", "keys", "removings", ".", "each", "do", "|", "name", "|", "say", "\"Removing #{name} (#{self.locks[name].version})\"", ".", "red", "dirname", "=", "File", ".", "join", "(", "self", ".", "root_path", ",", "\"Seeds\"", ",", "name", ")", "FileUtils", ".", "rm_rf", "(", "dirname", ")", "end", "end"], "docstring": "Removes disused seeds.\n\n @!visibility private", "docstring_tokens": ["Removes", "disused", "seeds", "."], "sha": "c0fcc7b3fe0b039d3f25c95559f7cf8935774065", "url": "https://github.com/devxoul/CocoaSeeds/blob/c0fcc7b3fe0b039d3f25c95559f7cf8935774065/lib/cocoaseeds/core.rb#L394-L401", "partition": "test"} {"repo": "devxoul/CocoaSeeds", "path": "lib/cocoaseeds/core.rb", "func_name": "Seeds.Core.configure_phase", "original_string": "def configure_phase\n self.project.targets.each do |target|\n begin\n phase = target.sources_build_phase\n # support resources phase\n resource_phase = target.resources_build_phase\n next unless phase\n rescue NoMethodError\n next\n end\n\n # remove zombie build files\n phase.files_references.each do |file|\n begin\n file.real_path\n rescue\n phase.files.each do |build_file|\n phase.files.delete(build_file) if build_file.file_ref == file\n end\n end\n end\n\n resource_phase.files_references.each do |file|\n begin\n file.real_path\n rescue \n resource_phase.files.each do |build_file|\n resource_phase.files.delete(build_file) if build_file.file_ref == file\n end\n end\n end\n\n\n removings = [] # name of seeds going to be removed from the target\n addings = [] # name of seeds going to be added to the target\n\n self.targets.keys.sort.each do |seed_name|\n target_names = self.targets[seed_name]\n if not target_names.include?(target.name)\n removings << seed_name if not removings.include?(seed_name)\n else\n addings << seed_name if not addings.include?(seed_name)\n end\n end\n\n self.file_references.each do |file|\n removings.each do |seed_names|\n next if not seed_names.include?(file.parent.name)\n phase.files.each do |build_file|\n phase.files.delete(build_file) if build_file.file_ref == file\n end\n resource_phase.files.each do |build_file|\n resource_phase.files.delete(build_file) if build_file.file_ref == file\n end\n end\n\n addings.each do |seed_names|\n next if file.name.end_with? \".h\"\n next if not seed_names.include?(file.parent.name)\n uuid = Xcodeproj::uuid_with_name \"#{target.name}:#{file.name}\"\n # Treat a file as resource file unless confirm it can be compiled.\n if self.valid_source_file?(file)\n phase.add_file_reference_with_uuid(file, uuid, true)\n else\n resource_phase.add_file_reference_with_uuid(file, uuid, true)\n end\n\n end\n end\n end\n end", "language": "ruby", "code": "def configure_phase\n self.project.targets.each do |target|\n begin\n phase = target.sources_build_phase\n # support resources phase\n resource_phase = target.resources_build_phase\n next unless phase\n rescue NoMethodError\n next\n end\n\n # remove zombie build files\n phase.files_references.each do |file|\n begin\n file.real_path\n rescue\n phase.files.each do |build_file|\n phase.files.delete(build_file) if build_file.file_ref == file\n end\n end\n end\n\n resource_phase.files_references.each do |file|\n begin\n file.real_path\n rescue \n resource_phase.files.each do |build_file|\n resource_phase.files.delete(build_file) if build_file.file_ref == file\n end\n end\n end\n\n\n removings = [] # name of seeds going to be removed from the target\n addings = [] # name of seeds going to be added to the target\n\n self.targets.keys.sort.each do |seed_name|\n target_names = self.targets[seed_name]\n if not target_names.include?(target.name)\n removings << seed_name if not removings.include?(seed_name)\n else\n addings << seed_name if not addings.include?(seed_name)\n end\n end\n\n self.file_references.each do |file|\n removings.each do |seed_names|\n next if not seed_names.include?(file.parent.name)\n phase.files.each do |build_file|\n phase.files.delete(build_file) if build_file.file_ref == file\n end\n resource_phase.files.each do |build_file|\n resource_phase.files.delete(build_file) if build_file.file_ref == file\n end\n end\n\n addings.each do |seed_names|\n next if file.name.end_with? \".h\"\n next if not seed_names.include?(file.parent.name)\n uuid = Xcodeproj::uuid_with_name \"#{target.name}:#{file.name}\"\n # Treat a file as resource file unless confirm it can be compiled.\n if self.valid_source_file?(file)\n phase.add_file_reference_with_uuid(file, uuid, true)\n else\n resource_phase.add_file_reference_with_uuid(file, uuid, true)\n end\n\n end\n end\n end\n end", "code_tokens": ["def", "configure_phase", "self", ".", "project", ".", "targets", ".", "each", "do", "|", "target", "|", "begin", "phase", "=", "target", ".", "sources_build_phase", "# support resources phase", "resource_phase", "=", "target", ".", "resources_build_phase", "next", "unless", "phase", "rescue", "NoMethodError", "next", "end", "# remove zombie build files", "phase", ".", "files_references", ".", "each", "do", "|", "file", "|", "begin", "file", ".", "real_path", "rescue", "phase", ".", "files", ".", "each", "do", "|", "build_file", "|", "phase", ".", "files", ".", "delete", "(", "build_file", ")", "if", "build_file", ".", "file_ref", "==", "file", "end", "end", "end", "resource_phase", ".", "files_references", ".", "each", "do", "|", "file", "|", "begin", "file", ".", "real_path", "rescue", "resource_phase", ".", "files", ".", "each", "do", "|", "build_file", "|", "resource_phase", ".", "files", ".", "delete", "(", "build_file", ")", "if", "build_file", ".", "file_ref", "==", "file", "end", "end", "end", "removings", "=", "[", "]", "# name of seeds going to be removed from the target", "addings", "=", "[", "]", "# name of seeds going to be added to the target", "self", ".", "targets", ".", "keys", ".", "sort", ".", "each", "do", "|", "seed_name", "|", "target_names", "=", "self", ".", "targets", "[", "seed_name", "]", "if", "not", "target_names", ".", "include?", "(", "target", ".", "name", ")", "removings", "<<", "seed_name", "if", "not", "removings", ".", "include?", "(", "seed_name", ")", "else", "addings", "<<", "seed_name", "if", "not", "addings", ".", "include?", "(", "seed_name", ")", "end", "end", "self", ".", "file_references", ".", "each", "do", "|", "file", "|", "removings", ".", "each", "do", "|", "seed_names", "|", "next", "if", "not", "seed_names", ".", "include?", "(", "file", ".", "parent", ".", "name", ")", "phase", ".", "files", ".", "each", "do", "|", "build_file", "|", "phase", ".", "files", ".", "delete", "(", "build_file", ")", "if", "build_file", ".", "file_ref", "==", "file", "end", "resource_phase", ".", "files", ".", "each", "do", "|", "build_file", "|", "resource_phase", ".", "files", ".", "delete", "(", "build_file", ")", "if", "build_file", ".", "file_ref", "==", "file", "end", "end", "addings", ".", "each", "do", "|", "seed_names", "|", "next", "if", "file", ".", "name", ".", "end_with?", "\".h\"", "next", "if", "not", "seed_names", ".", "include?", "(", "file", ".", "parent", ".", "name", ")", "uuid", "=", "Xcodeproj", "::", "uuid_with_name", "\"#{target.name}:#{file.name}\"", "# Treat a file as resource file unless confirm it can be compiled.", "if", "self", ".", "valid_source_file?", "(", "file", ")", "phase", ".", "add_file_reference_with_uuid", "(", "file", ",", "uuid", ",", "true", ")", "else", "resource_phase", ".", "add_file_reference_with_uuid", "(", "file", ",", "uuid", ",", "true", ")", "end", "end", "end", "end", "end"], "docstring": "Adds file references to the 'Sources Build Phase'.\n\n @!visibility private", "docstring_tokens": ["Adds", "file", "references", "to", "the", "Sources", "Build", "Phase", "."], "sha": "c0fcc7b3fe0b039d3f25c95559f7cf8935774065", "url": "https://github.com/devxoul/CocoaSeeds/blob/c0fcc7b3fe0b039d3f25c95559f7cf8935774065/lib/cocoaseeds/core.rb#L626-L696", "partition": "test"} {"repo": "devxoul/CocoaSeeds", "path": "lib/cocoaseeds/core.rb", "func_name": "Seeds.Core.valid_source_file?", "original_string": "def valid_source_file? filename\n suffixs = [\".h\", \".c\", \".m\", \".mm\", \".swift\", \".cpp\"]\n suffixs.each do |suffix|\n return true if filename.name.end_with? suffix\n end\n return false\n end", "language": "ruby", "code": "def valid_source_file? filename\n suffixs = [\".h\", \".c\", \".m\", \".mm\", \".swift\", \".cpp\"]\n suffixs.each do |suffix|\n return true if filename.name.end_with? suffix\n end\n return false\n end", "code_tokens": ["def", "valid_source_file?", "filename", "suffixs", "=", "[", "\".h\"", ",", "\".c\"", ",", "\".m\"", ",", "\".mm\"", ",", "\".swift\"", ",", "\".cpp\"", "]", "suffixs", ".", "each", "do", "|", "suffix", "|", "return", "true", "if", "filename", ".", "name", ".", "end_with?", "suffix", "end", "return", "false", "end"], "docstring": "Determines whether there's a source file.\n\n @!visibility private", "docstring_tokens": ["Determines", "whether", "there", "s", "a", "source", "file", "."], "sha": "c0fcc7b3fe0b039d3f25c95559f7cf8935774065", "url": "https://github.com/devxoul/CocoaSeeds/blob/c0fcc7b3fe0b039d3f25c95559f7cf8935774065/lib/cocoaseeds/core.rb#L702-L708", "partition": "test"} {"repo": "yast/yast-rake", "path": "lib/tasks/spellcheck_task.rb", "func_name": "Yast.SpellcheckTask.speller", "original_string": "def speller\n return @speller if @speller\n # raspell is an optional dependency, handle the missing case nicely\n begin\n require \"raspell\"\n rescue LoadError\n $stderr.puts \"ERROR: Ruby gem \\\"raspell\\\" is not installed.\"\n exit 1\n end\n\n # initialize aspell\n @speller = Aspell.new(\"en_US\")\n @speller.suggestion_mode = Aspell::NORMAL\n # ignore the HTML tags in the text\n @speller.set_option(\"mode\", \"html\")\n\n @speller\n end", "language": "ruby", "code": "def speller\n return @speller if @speller\n # raspell is an optional dependency, handle the missing case nicely\n begin\n require \"raspell\"\n rescue LoadError\n $stderr.puts \"ERROR: Ruby gem \\\"raspell\\\" is not installed.\"\n exit 1\n end\n\n # initialize aspell\n @speller = Aspell.new(\"en_US\")\n @speller.suggestion_mode = Aspell::NORMAL\n # ignore the HTML tags in the text\n @speller.set_option(\"mode\", \"html\")\n\n @speller\n end", "code_tokens": ["def", "speller", "return", "@speller", "if", "@speller", "# raspell is an optional dependency, handle the missing case nicely", "begin", "require", "\"raspell\"", "rescue", "LoadError", "$stderr", ".", "puts", "\"ERROR: Ruby gem \\\"raspell\\\" is not installed.\"", "exit", "1", "end", "# initialize aspell", "@speller", "=", "Aspell", ".", "new", "(", "\"en_US\"", ")", "@speller", ".", "suggestion_mode", "=", "Aspell", "::", "NORMAL", "# ignore the HTML tags in the text", "@speller", ".", "set_option", "(", "\"mode\"", ",", "\"html\"", ")", "@speller", "end"], "docstring": "create an Aspell speller object\n @return [Aspell] the speller object", "docstring_tokens": ["create", "an", "Aspell", "speller", "object"], "sha": "ac8f5f03a110da31f6b5b141e0683f5455e1a31a", "url": "https://github.com/yast/yast-rake/blob/ac8f5f03a110da31f6b5b141e0683f5455e1a31a/lib/tasks/spellcheck_task.rb#L66-L83", "partition": "test"} {"repo": "yast/yast-rake", "path": "lib/tasks/spellcheck_task.rb", "func_name": "Yast.SpellcheckTask.files_to_check", "original_string": "def files_to_check\n files = config[\"check\"].reduce([]) { |a, e| a + Dir[e] }\n config[\"ignore\"].reduce(files) { |a, e| a - Dir[e] }\n end", "language": "ruby", "code": "def files_to_check\n files = config[\"check\"].reduce([]) { |a, e| a + Dir[e] }\n config[\"ignore\"].reduce(files) { |a, e| a - Dir[e] }\n end", "code_tokens": ["def", "files_to_check", "files", "=", "config", "[", "\"check\"", "]", ".", "reduce", "(", "[", "]", ")", "{", "|", "a", ",", "e", "|", "a", "+", "Dir", "[", "e", "]", "}", "config", "[", "\"ignore\"", "]", ".", "reduce", "(", "files", ")", "{", "|", "a", ",", "e", "|", "a", "-", "Dir", "[", "e", "]", "}", "end"], "docstring": "evaluate the files to check\n @return [Array] list of files", "docstring_tokens": ["evaluate", "the", "files", "to", "check"], "sha": "ac8f5f03a110da31f6b5b141e0683f5455e1a31a", "url": "https://github.com/yast/yast-rake/blob/ac8f5f03a110da31f6b5b141e0683f5455e1a31a/lib/tasks/spellcheck_task.rb#L87-L90", "partition": "test"} {"repo": "yast/yast-rake", "path": "lib/tasks/spellcheck_task.rb", "func_name": "Yast.SpellcheckTask.read_spell_config", "original_string": "def read_spell_config(file)\n return {} unless File.exist?(file)\n\n puts \"Loading config file (#{file})...\" if verbose == true\n require \"yaml\"\n YAML.load_file(file)\n end", "language": "ruby", "code": "def read_spell_config(file)\n return {} unless File.exist?(file)\n\n puts \"Loading config file (#{file})...\" if verbose == true\n require \"yaml\"\n YAML.load_file(file)\n end", "code_tokens": ["def", "read_spell_config", "(", "file", ")", "return", "{", "}", "unless", "File", ".", "exist?", "(", "file", ")", "puts", "\"Loading config file (#{file})...\"", "if", "verbose", "==", "true", "require", "\"yaml\"", "YAML", ".", "load_file", "(", "file", ")", "end"], "docstring": "read a Yaml config file", "docstring_tokens": ["read", "a", "Yaml", "config", "file"], "sha": "ac8f5f03a110da31f6b5b141e0683f5455e1a31a", "url": "https://github.com/yast/yast-rake/blob/ac8f5f03a110da31f6b5b141e0683f5455e1a31a/lib/tasks/spellcheck_task.rb#L93-L99", "partition": "test"} {"repo": "yast/yast-rake", "path": "lib/tasks/spellcheck_task.rb", "func_name": "Yast.SpellcheckTask.report_duplicates", "original_string": "def report_duplicates(dict1, dict2)\n duplicates = dict1 & dict2\n return if duplicates.empty?\n\n $stderr.puts \"Warning: Found dictionary duplicates in the local dictionary \" \\\n \"(#{CUSTOM_SPELL_CONFIG_FILE}):\\n\"\n duplicates.each { |duplicate| $stderr.puts \" #{duplicate}\" }\n $stderr.puts\n end", "language": "ruby", "code": "def report_duplicates(dict1, dict2)\n duplicates = dict1 & dict2\n return if duplicates.empty?\n\n $stderr.puts \"Warning: Found dictionary duplicates in the local dictionary \" \\\n \"(#{CUSTOM_SPELL_CONFIG_FILE}):\\n\"\n duplicates.each { |duplicate| $stderr.puts \" #{duplicate}\" }\n $stderr.puts\n end", "code_tokens": ["def", "report_duplicates", "(", "dict1", ",", "dict2", ")", "duplicates", "=", "dict1", "&", "dict2", "return", "if", "duplicates", ".", "empty?", "$stderr", ".", "puts", "\"Warning: Found dictionary duplicates in the local dictionary \"", "\"(#{CUSTOM_SPELL_CONFIG_FILE}):\\n\"", "duplicates", ".", "each", "{", "|", "duplicate", "|", "$stderr", ".", "puts", "\" #{duplicate}\"", "}", "$stderr", ".", "puts", "end"], "docstring": "print the duplicate dictionary entries\n @param dict1 [Array] the first dictionary\n @param dict2 [Array] the second dictionary", "docstring_tokens": ["print", "the", "duplicate", "dictionary", "entries"], "sha": "ac8f5f03a110da31f6b5b141e0683f5455e1a31a", "url": "https://github.com/yast/yast-rake/blob/ac8f5f03a110da31f6b5b141e0683f5455e1a31a/lib/tasks/spellcheck_task.rb#L104-L112", "partition": "test"} {"repo": "yast/yast-rake", "path": "lib/tasks/spellcheck_task.rb", "func_name": "Yast.SpellcheckTask.config", "original_string": "def config\n return @config if @config\n\n @config = read_spell_config(GLOBAL_SPELL_CONFIG_FILE)\n custom_config = read_spell_config(CUSTOM_SPELL_CONFIG_FILE)\n\n report_duplicates(config[\"dictionary\"], custom_config[\"dictionary\"].to_a)\n\n custom_config[\"dictionary\"] = @config[\"dictionary\"] + custom_config[\"dictionary\"].to_a\n custom_config[\"dictionary\"].uniq!\n\n # override the global values by the local if present\n @config.merge!(custom_config)\n\n @config\n end", "language": "ruby", "code": "def config\n return @config if @config\n\n @config = read_spell_config(GLOBAL_SPELL_CONFIG_FILE)\n custom_config = read_spell_config(CUSTOM_SPELL_CONFIG_FILE)\n\n report_duplicates(config[\"dictionary\"], custom_config[\"dictionary\"].to_a)\n\n custom_config[\"dictionary\"] = @config[\"dictionary\"] + custom_config[\"dictionary\"].to_a\n custom_config[\"dictionary\"].uniq!\n\n # override the global values by the local if present\n @config.merge!(custom_config)\n\n @config\n end", "code_tokens": ["def", "config", "return", "@config", "if", "@config", "@config", "=", "read_spell_config", "(", "GLOBAL_SPELL_CONFIG_FILE", ")", "custom_config", "=", "read_spell_config", "(", "CUSTOM_SPELL_CONFIG_FILE", ")", "report_duplicates", "(", "config", "[", "\"dictionary\"", "]", ",", "custom_config", "[", "\"dictionary\"", "]", ".", "to_a", ")", "custom_config", "[", "\"dictionary\"", "]", "=", "@config", "[", "\"dictionary\"", "]", "+", "custom_config", "[", "\"dictionary\"", "]", ".", "to_a", "custom_config", "[", "\"dictionary\"", "]", ".", "uniq!", "# override the global values by the local if present", "@config", ".", "merge!", "(", "custom_config", ")", "@config", "end"], "docstring": "return the merged global and the custom spell configs\n @return [Hash] the merged configuration to use", "docstring_tokens": ["return", "the", "merged", "global", "and", "the", "custom", "spell", "configs"], "sha": "ac8f5f03a110da31f6b5b141e0683f5455e1a31a", "url": "https://github.com/yast/yast-rake/blob/ac8f5f03a110da31f6b5b141e0683f5455e1a31a/lib/tasks/spellcheck_task.rb#L116-L131", "partition": "test"} {"repo": "yast/yast-rake", "path": "lib/tasks/spellcheck_task.rb", "func_name": "Yast.SpellcheckTask.check_file", "original_string": "def check_file(file)\n puts \"Checking #{file}...\" if verbose == true\n # spell check each line separately so we can report error locations properly\n lines = File.read(file).split(\"\\n\")\n\n success = true\n lines.each_with_index do |text, index|\n misspelled = misspelled_on_line(text)\n next if misspelled.empty?\n\n success = false\n print_misspelled(misspelled, index, text)\n end\n\n success\n end", "language": "ruby", "code": "def check_file(file)\n puts \"Checking #{file}...\" if verbose == true\n # spell check each line separately so we can report error locations properly\n lines = File.read(file).split(\"\\n\")\n\n success = true\n lines.each_with_index do |text, index|\n misspelled = misspelled_on_line(text)\n next if misspelled.empty?\n\n success = false\n print_misspelled(misspelled, index, text)\n end\n\n success\n end", "code_tokens": ["def", "check_file", "(", "file", ")", "puts", "\"Checking #{file}...\"", "if", "verbose", "==", "true", "# spell check each line separately so we can report error locations properly", "lines", "=", "File", ".", "read", "(", "file", ")", ".", "split", "(", "\"\\n\"", ")", "success", "=", "true", "lines", ".", "each_with_index", "do", "|", "text", ",", "index", "|", "misspelled", "=", "misspelled_on_line", "(", "text", ")", "next", "if", "misspelled", ".", "empty?", "success", "=", "false", "print_misspelled", "(", "misspelled", ",", "index", ",", "text", ")", "end", "success", "end"], "docstring": "check the file using the spellchecker\n @param file [String] file name\n @return [Boolean] true on success (no spelling error found)", "docstring_tokens": ["check", "the", "file", "using", "the", "spellchecker"], "sha": "ac8f5f03a110da31f6b5b141e0683f5455e1a31a", "url": "https://github.com/yast/yast-rake/blob/ac8f5f03a110da31f6b5b141e0683f5455e1a31a/lib/tasks/spellcheck_task.rb#L136-L151", "partition": "test"} {"repo": "wpscanteam/OptParseValidator", "path": "lib/opt_parse_validator/opts/path.rb", "func_name": "OptParseValidator.OptPath.check_writable", "original_string": "def check_writable(path)\n raise Error, \"'#{path}' is not writable\" if path.exist? && !path.writable? || !path.parent.writable?\n end", "language": "ruby", "code": "def check_writable(path)\n raise Error, \"'#{path}' is not writable\" if path.exist? && !path.writable? || !path.parent.writable?\n end", "code_tokens": ["def", "check_writable", "(", "path", ")", "raise", "Error", ",", "\"'#{path}' is not writable\"", "if", "path", ".", "exist?", "&&", "!", "path", ".", "writable?", "||", "!", "path", ".", "parent", ".", "writable?", "end"], "docstring": "If the path does not exist, it will check for the parent\n directory write permission\n\n @param [ Pathname ] path", "docstring_tokens": ["If", "the", "path", "does", "not", "exist", "it", "will", "check", "for", "the", "parent", "directory", "write", "permission"], "sha": "a9c0e912afa843e3ffe734286b78c35823ec970b", "url": "https://github.com/wpscanteam/OptParseValidator/blob/a9c0e912afa843e3ffe734286b78c35823ec970b/lib/opt_parse_validator/opts/path.rb#L64-L66", "partition": "test"} {"repo": "wpscanteam/OptParseValidator", "path": "lib/opt_parse_validator.rb", "func_name": "OptParseValidator.OptParser.check_option", "original_string": "def check_option(opt)\n raise Error, \"The option is not an OptBase, #{opt.class} supplied\" unless opt.is_a?(OptBase)\n raise Error, \"The option #{opt.to_sym} is already used !\" if @symbols_used.include?(opt.to_sym)\n end", "language": "ruby", "code": "def check_option(opt)\n raise Error, \"The option is not an OptBase, #{opt.class} supplied\" unless opt.is_a?(OptBase)\n raise Error, \"The option #{opt.to_sym} is already used !\" if @symbols_used.include?(opt.to_sym)\n end", "code_tokens": ["def", "check_option", "(", "opt", ")", "raise", "Error", ",", "\"The option is not an OptBase, #{opt.class} supplied\"", "unless", "opt", ".", "is_a?", "(", "OptBase", ")", "raise", "Error", ",", "\"The option #{opt.to_sym} is already used !\"", "if", "@symbols_used", ".", "include?", "(", "opt", ".", "to_sym", ")", "end"], "docstring": "Ensures the opt given is valid\n\n @param [ OptBase ] opt\n\n @return [ void ]", "docstring_tokens": ["Ensures", "the", "opt", "given", "is", "valid"], "sha": "a9c0e912afa843e3ffe734286b78c35823ec970b", "url": "https://github.com/wpscanteam/OptParseValidator/blob/a9c0e912afa843e3ffe734286b78c35823ec970b/lib/opt_parse_validator.rb#L101-L104", "partition": "test"} {"repo": "wpscanteam/OptParseValidator", "path": "lib/opt_parse_validator.rb", "func_name": "OptParseValidator.OptParser.post_processing", "original_string": "def post_processing\n @opts.each do |opt|\n raise NoRequiredOption, \"The option #{opt} is required\" if opt.required? && !@results.key?(opt.to_sym)\n\n next if opt.required_unless.empty? || @results.key?(opt.to_sym)\n\n fail_msg = \"One of the following options is required: #{opt}, #{opt.required_unless.join(', ')}\"\n\n raise NoRequiredOption, fail_msg unless opt.required_unless.any? do |sym|\n @results.key?(sym)\n end\n end\n end", "language": "ruby", "code": "def post_processing\n @opts.each do |opt|\n raise NoRequiredOption, \"The option #{opt} is required\" if opt.required? && !@results.key?(opt.to_sym)\n\n next if opt.required_unless.empty? || @results.key?(opt.to_sym)\n\n fail_msg = \"One of the following options is required: #{opt}, #{opt.required_unless.join(', ')}\"\n\n raise NoRequiredOption, fail_msg unless opt.required_unless.any? do |sym|\n @results.key?(sym)\n end\n end\n end", "code_tokens": ["def", "post_processing", "@opts", ".", "each", "do", "|", "opt", "|", "raise", "NoRequiredOption", ",", "\"The option #{opt} is required\"", "if", "opt", ".", "required?", "&&", "!", "@results", ".", "key?", "(", "opt", ".", "to_sym", ")", "next", "if", "opt", ".", "required_unless", ".", "empty?", "||", "@results", ".", "key?", "(", "opt", ".", "to_sym", ")", "fail_msg", "=", "\"One of the following options is required: #{opt}, #{opt.required_unless.join(', ')}\"", "raise", "NoRequiredOption", ",", "fail_msg", "unless", "opt", ".", "required_unless", ".", "any?", "do", "|", "sym", "|", "@results", ".", "key?", "(", "sym", ")", "end", "end", "end"], "docstring": "Ensure that all required options are supplied\n Should be overriden to modify the behavior\n\n @return [ Void ]", "docstring_tokens": ["Ensure", "that", "all", "required", "options", "are", "supplied", "Should", "be", "overriden", "to", "modify", "the", "behavior"], "sha": "a9c0e912afa843e3ffe734286b78c35823ec970b", "url": "https://github.com/wpscanteam/OptParseValidator/blob/a9c0e912afa843e3ffe734286b78c35823ec970b/lib/opt_parse_validator.rb#L141-L153", "partition": "test"} {"repo": "nekojarashi/zipping", "path": "lib/zipping.rb", "func_name": "Zipping.ZipBuilder.subdir_entities", "original_string": "def subdir_entities(dir = @current_dir)\n Dir.glob(dir[:path].gsub(/[*?\\\\\\[\\]{}]/, '\\\\\\\\\\0') + '/*').map!{|path| {path: path, time: File.mtime(path), name: File.basename(path)}}\n end", "language": "ruby", "code": "def subdir_entities(dir = @current_dir)\n Dir.glob(dir[:path].gsub(/[*?\\\\\\[\\]{}]/, '\\\\\\\\\\0') + '/*').map!{|path| {path: path, time: File.mtime(path), name: File.basename(path)}}\n end", "code_tokens": ["def", "subdir_entities", "(", "dir", "=", "@current_dir", ")", "Dir", ".", "glob", "(", "dir", "[", ":path", "]", ".", "gsub", "(", "/", "\\\\", "\\[", "\\]", "/", ",", "'\\\\\\\\\\0'", ")", "+", "'/*'", ")", ".", "map!", "{", "|", "path", "|", "{", "path", ":", "path", ",", "time", ":", "File", ".", "mtime", "(", "path", ")", ",", "name", ":", "File", ".", "basename", "(", "path", ")", "}", "}", "end"], "docstring": "Conversions\n Get entities of files in dir", "docstring_tokens": ["Conversions", "Get", "entities", "of", "files", "in", "dir"], "sha": "90e00610b820367913f0602cbe91211921b139ca", "url": "https://github.com/nekojarashi/zipping/blob/90e00610b820367913f0602cbe91211921b139ca/lib/zipping.rb#L155-L157", "partition": "test"} {"repo": "nekojarashi/zipping", "path": "lib/zipping.rb", "func_name": "Zipping.ZipBuilder.string_to_bytes", "original_string": "def string_to_bytes(str)\n unless @e.nil? || @e == :utf8\n if @e == :shift_jis\n begin\n str = str.gsub /[\\\\:*?\"<>|\\uff5e]/, '\uff1f'\n str.encode! 'Shift_JIS', :invalid => :replace, :undef => :replace, :replace => '\uff1f'\n rescue => e\n end\n end\n end\n [str].pack('a*')\n end", "language": "ruby", "code": "def string_to_bytes(str)\n unless @e.nil? || @e == :utf8\n if @e == :shift_jis\n begin\n str = str.gsub /[\\\\:*?\"<>|\\uff5e]/, '\uff1f'\n str.encode! 'Shift_JIS', :invalid => :replace, :undef => :replace, :replace => '\uff1f'\n rescue => e\n end\n end\n end\n [str].pack('a*')\n end", "code_tokens": ["def", "string_to_bytes", "(", "str", ")", "unless", "@e", ".", "nil?", "||", "@e", "==", ":utf8", "if", "@e", "==", ":shift_jis", "begin", "str", "=", "str", ".", "gsub", "/", "\\\\", "\\uff5e", "/", ",", "'\uff1f'", "str", ".", "encode!", "'Shift_JIS'", ",", ":invalid", "=>", ":replace", ",", ":undef", "=>", ":replace", ",", ":replace", "=>", "'\uff1f'", "rescue", "=>", "e", "end", "end", "end", "[", "str", "]", ".", "pack", "(", "'a*'", ")", "end"], "docstring": "Create ASCII-8bits string. Also convert encoding if needed.", "docstring_tokens": ["Create", "ASCII", "-", "8bits", "string", ".", "Also", "convert", "encoding", "if", "needed", "."], "sha": "90e00610b820367913f0602cbe91211921b139ca", "url": "https://github.com/nekojarashi/zipping/blob/90e00610b820367913f0602cbe91211921b139ca/lib/zipping.rb#L179-L190", "partition": "test"} {"repo": "nekojarashi/zipping", "path": "lib/zipping.rb", "func_name": "Zipping.ZipBuilder.pack", "original_string": "def pack(files)\n entities = Entity.entities_from files\n return if entities.empty?\n\n reset_state\n pack_entities entities\n while has_dir?\n cd next_dir\n pack_current_dir\n end\n end", "language": "ruby", "code": "def pack(files)\n entities = Entity.entities_from files\n return if entities.empty?\n\n reset_state\n pack_entities entities\n while has_dir?\n cd next_dir\n pack_current_dir\n end\n end", "code_tokens": ["def", "pack", "(", "files", ")", "entities", "=", "Entity", ".", "entities_from", "files", "return", "if", "entities", ".", "empty?", "reset_state", "pack_entities", "entities", "while", "has_dir?", "cd", "next_dir", "pack_current_dir", "end", "end"], "docstring": "Compression operations\n Pack file and directory entities and output to stream.", "docstring_tokens": ["Compression", "operations", "Pack", "file", "and", "directory", "entities", "and", "output", "to", "stream", "."], "sha": "90e00610b820367913f0602cbe91211921b139ca", "url": "https://github.com/nekojarashi/zipping/blob/90e00610b820367913f0602cbe91211921b139ca/lib/zipping.rb#L195-L205", "partition": "test"} {"repo": "nekojarashi/zipping", "path": "lib/zipping.rb", "func_name": "Zipping.ZipBuilder.pack_symlinks", "original_string": "def pack_symlinks\n reset_state\n @l.each do |link|\n if @w.path_exists? Entity.linked_path(link[:abs_path], File.readlink(link[:path]))\n link[:name] = link[:abs_path]\n pack_symbolic_link_entity link\n end\n end\n end", "language": "ruby", "code": "def pack_symlinks\n reset_state\n @l.each do |link|\n if @w.path_exists? Entity.linked_path(link[:abs_path], File.readlink(link[:path]))\n link[:name] = link[:abs_path]\n pack_symbolic_link_entity link\n end\n end\n end", "code_tokens": ["def", "pack_symlinks", "reset_state", "@l", ".", "each", "do", "|", "link", "|", "if", "@w", ".", "path_exists?", "Entity", ".", "linked_path", "(", "link", "[", ":abs_path", "]", ",", "File", ".", "readlink", "(", "link", "[", ":path", "]", ")", ")", "link", "[", ":name", "]", "=", "link", "[", ":abs_path", "]", "pack_symbolic_link_entity", "link", "end", "end", "end"], "docstring": "Pack symlinks if its link path exists in zip", "docstring_tokens": ["Pack", "symlinks", "if", "its", "link", "path", "exists", "in", "zip"], "sha": "90e00610b820367913f0602cbe91211921b139ca", "url": "https://github.com/nekojarashi/zipping/blob/90e00610b820367913f0602cbe91211921b139ca/lib/zipping.rb#L214-L222", "partition": "test"} {"repo": "nekojarashi/zipping", "path": "lib/zipping.rb", "func_name": "Zipping.ZipBuilder.pack_entities", "original_string": "def pack_entities(entities)\n entities.each do |entity|\n # ignore bad entities\n next unless entity.is_a?(Hash) && entity[:path]\n\n path = entity[:path]\n if File.symlink? path\n postpone_symlink entity\n elsif File.directory? path\n postpone_dir entity\n elsif File.file? path\n pack_file_entity entity\n end\n end\n end", "language": "ruby", "code": "def pack_entities(entities)\n entities.each do |entity|\n # ignore bad entities\n next unless entity.is_a?(Hash) && entity[:path]\n\n path = entity[:path]\n if File.symlink? path\n postpone_symlink entity\n elsif File.directory? path\n postpone_dir entity\n elsif File.file? path\n pack_file_entity entity\n end\n end\n end", "code_tokens": ["def", "pack_entities", "(", "entities", ")", "entities", ".", "each", "do", "|", "entity", "|", "# ignore bad entities", "next", "unless", "entity", ".", "is_a?", "(", "Hash", ")", "&&", "entity", "[", ":path", "]", "path", "=", "entity", "[", ":path", "]", "if", "File", ".", "symlink?", "path", "postpone_symlink", "entity", "elsif", "File", ".", "directory?", "path", "postpone_dir", "entity", "elsif", "File", ".", "file?", "path", "pack_file_entity", "entity", "end", "end", "end"], "docstring": "Pack file entities. Directory entities are queued, not packed in this method.", "docstring_tokens": ["Pack", "file", "entities", ".", "Directory", "entities", "are", "queued", "not", "packed", "in", "this", "method", "."], "sha": "90e00610b820367913f0602cbe91211921b139ca", "url": "https://github.com/nekojarashi/zipping/blob/90e00610b820367913f0602cbe91211921b139ca/lib/zipping.rb#L231-L245", "partition": "test"} {"repo": "thooams/Ui-Bibz", "path": "lib/ui_bibz/ui/core/lists/components/list.rb", "func_name": "UiBibz::Ui::Core::Lists::Components.List.header", "original_string": "def header content = nil, options = nil, html_options = nil, &block\n @header = UiBibz::Ui::Core::Lists::Components::ListHeader.new content, options, html_options, &block\n end", "language": "ruby", "code": "def header content = nil, options = nil, html_options = nil, &block\n @header = UiBibz::Ui::Core::Lists::Components::ListHeader.new content, options, html_options, &block\n end", "code_tokens": ["def", "header", "content", "=", "nil", ",", "options", "=", "nil", ",", "html_options", "=", "nil", ",", "&", "block", "@header", "=", "UiBibz", "::", "Ui", "::", "Core", "::", "Lists", "::", "Components", "::", "ListHeader", ".", "new", "content", ",", "options", ",", "html_options", ",", "block", "end"], "docstring": "Add header which is a component", "docstring_tokens": ["Add", "header", "which", "is", "a", "component"], "sha": "bc0a3238c1c8bfaa75fd56a4aa225f2cea6e319f", "url": "https://github.com/thooams/Ui-Bibz/blob/bc0a3238c1c8bfaa75fd56a4aa225f2cea6e319f/lib/ui_bibz/ui/core/lists/components/list.rb#L76-L78", "partition": "test"} {"repo": "thooams/Ui-Bibz", "path": "lib/ui_bibz/ui/core/lists/components/list.rb", "func_name": "UiBibz::Ui::Core::Lists::Components.List.body", "original_string": "def body content = nil, options = nil, html_options = nil, &block\n @body = UiBibz::Ui::Core::Lists::Components::ListBody.new content, options, html_options, &block\n end", "language": "ruby", "code": "def body content = nil, options = nil, html_options = nil, &block\n @body = UiBibz::Ui::Core::Lists::Components::ListBody.new content, options, html_options, &block\n end", "code_tokens": ["def", "body", "content", "=", "nil", ",", "options", "=", "nil", ",", "html_options", "=", "nil", ",", "&", "block", "@body", "=", "UiBibz", "::", "Ui", "::", "Core", "::", "Lists", "::", "Components", "::", "ListBody", ".", "new", "content", ",", "options", ",", "html_options", ",", "block", "end"], "docstring": "Add body which is a component", "docstring_tokens": ["Add", "body", "which", "is", "a", "component"], "sha": "bc0a3238c1c8bfaa75fd56a4aa225f2cea6e319f", "url": "https://github.com/thooams/Ui-Bibz/blob/bc0a3238c1c8bfaa75fd56a4aa225f2cea6e319f/lib/ui_bibz/ui/core/lists/components/list.rb#L81-L83", "partition": "test"} {"repo": "thooams/Ui-Bibz", "path": "lib/ui_bibz/ui/ux/tables/table.rb", "func_name": "UiBibz::Ui::Ux::Tables.Table.td_content", "original_string": "def td_content record, col\n content = col.count ? record.send(col.data_index).count : record.send(col.data_index)\n unless content.nil?\n content = content.strftime(col.date_format) unless col.date_format.nil?\n content = link_to content, action.inject_url(col.link, record) unless col.link.nil?\n content = col.format.call(@store.records, record) unless col.format.nil?\n end\n content = As.new(col, record, content, @options).render unless col.as.nil?\n content\n end", "language": "ruby", "code": "def td_content record, col\n content = col.count ? record.send(col.data_index).count : record.send(col.data_index)\n unless content.nil?\n content = content.strftime(col.date_format) unless col.date_format.nil?\n content = link_to content, action.inject_url(col.link, record) unless col.link.nil?\n content = col.format.call(@store.records, record) unless col.format.nil?\n end\n content = As.new(col, record, content, @options).render unless col.as.nil?\n content\n end", "code_tokens": ["def", "td_content", "record", ",", "col", "content", "=", "col", ".", "count", "?", "record", ".", "send", "(", "col", ".", "data_index", ")", ".", "count", ":", "record", ".", "send", "(", "col", ".", "data_index", ")", "unless", "content", ".", "nil?", "content", "=", "content", ".", "strftime", "(", "col", ".", "date_format", ")", "unless", "col", ".", "date_format", ".", "nil?", "content", "=", "link_to", "content", ",", "action", ".", "inject_url", "(", "col", ".", "link", ",", "record", ")", "unless", "col", ".", "link", ".", "nil?", "content", "=", "col", ".", "format", ".", "call", "(", "@store", ".", "records", ",", "record", ")", "unless", "col", ".", "format", ".", "nil?", "end", "content", "=", "As", ".", "new", "(", "col", ",", "record", ",", "content", ",", "@options", ")", ".", "render", "unless", "col", ".", "as", ".", "nil?", "content", "end"], "docstring": "Maybe create a class for td_content", "docstring_tokens": ["Maybe", "create", "a", "class", "for", "td_content"], "sha": "bc0a3238c1c8bfaa75fd56a4aa225f2cea6e319f", "url": "https://github.com/thooams/Ui-Bibz/blob/bc0a3238c1c8bfaa75fd56a4aa225f2cea6e319f/lib/ui_bibz/ui/ux/tables/table.rb#L181-L190", "partition": "test"} {"repo": "thooams/Ui-Bibz", "path": "lib/ui_bibz/ui/core/boxes/card.rb", "func_name": "UiBibz::Ui::Core::Boxes.Card.body", "original_string": "def body content = nil, options = nil, html_options = nil, &block\n options, content = inherit_options(content, options, block)\n if is_tap(content, options)\n content = (content || {}).merge(collapse: options.try(:[], :collapse), parent_collapse: @options[:parent_collapse] )\n @items << UiBibz::Ui::Core::Boxes::Components::CardBody.new(content, options, html_options).tap(&block).render\n else\n options = (options || {}).merge(collapse: options.try(:[], :collapse), parent_collapse: @options[:parent_collapse] )\n @items << UiBibz::Ui::Core::Boxes::Components::CardBody.new(content, options, html_options, &block).render\n end\n end", "language": "ruby", "code": "def body content = nil, options = nil, html_options = nil, &block\n options, content = inherit_options(content, options, block)\n if is_tap(content, options)\n content = (content || {}).merge(collapse: options.try(:[], :collapse), parent_collapse: @options[:parent_collapse] )\n @items << UiBibz::Ui::Core::Boxes::Components::CardBody.new(content, options, html_options).tap(&block).render\n else\n options = (options || {}).merge(collapse: options.try(:[], :collapse), parent_collapse: @options[:parent_collapse] )\n @items << UiBibz::Ui::Core::Boxes::Components::CardBody.new(content, options, html_options, &block).render\n end\n end", "code_tokens": ["def", "body", "content", "=", "nil", ",", "options", "=", "nil", ",", "html_options", "=", "nil", ",", "&", "block", "options", ",", "content", "=", "inherit_options", "(", "content", ",", "options", ",", "block", ")", "if", "is_tap", "(", "content", ",", "options", ")", "content", "=", "(", "content", "||", "{", "}", ")", ".", "merge", "(", "collapse", ":", "options", ".", "try", "(", ":[]", ",", ":collapse", ")", ",", "parent_collapse", ":", "@options", "[", ":parent_collapse", "]", ")", "@items", "<<", "UiBibz", "::", "Ui", "::", "Core", "::", "Boxes", "::", "Components", "::", "CardBody", ".", "new", "(", "content", ",", "options", ",", "html_options", ")", ".", "tap", "(", "block", ")", ".", "render", "else", "options", "=", "(", "options", "||", "{", "}", ")", ".", "merge", "(", "collapse", ":", "options", ".", "try", "(", ":[]", ",", ":collapse", ")", ",", "parent_collapse", ":", "@options", "[", ":parent_collapse", "]", ")", "@items", "<<", "UiBibz", "::", "Ui", "::", "Core", "::", "Boxes", "::", "Components", "::", "CardBody", ".", "new", "(", "content", ",", "options", ",", "html_options", ",", "block", ")", ".", "render", "end", "end"], "docstring": "Add Body div which is a component", "docstring_tokens": ["Add", "Body", "div", "which", "is", "a", "component"], "sha": "bc0a3238c1c8bfaa75fd56a4aa225f2cea6e319f", "url": "https://github.com/thooams/Ui-Bibz/blob/bc0a3238c1c8bfaa75fd56a4aa225f2cea6e319f/lib/ui_bibz/ui/core/boxes/card.rb#L108-L117", "partition": "test"} {"repo": "thooams/Ui-Bibz", "path": "lib/ui_bibz/ui/core/boxes/card.rb", "func_name": "UiBibz::Ui::Core::Boxes.Card.footer", "original_string": "def footer content = nil, options = nil, html_options = nil, &block\n options, content = inherit_options(content, options, block)\n @footer = UiBibz::Ui::Core::Boxes::Components::CardFooter.new(content, options, html_options, &block).render\n end", "language": "ruby", "code": "def footer content = nil, options = nil, html_options = nil, &block\n options, content = inherit_options(content, options, block)\n @footer = UiBibz::Ui::Core::Boxes::Components::CardFooter.new(content, options, html_options, &block).render\n end", "code_tokens": ["def", "footer", "content", "=", "nil", ",", "options", "=", "nil", ",", "html_options", "=", "nil", ",", "&", "block", "options", ",", "content", "=", "inherit_options", "(", "content", ",", "options", ",", "block", ")", "@footer", "=", "UiBibz", "::", "Ui", "::", "Core", "::", "Boxes", "::", "Components", "::", "CardFooter", ".", "new", "(", "content", ",", "options", ",", "html_options", ",", "block", ")", ".", "render", "end"], "docstring": "Add Footer which is a component", "docstring_tokens": ["Add", "Footer", "which", "is", "a", "component"], "sha": "bc0a3238c1c8bfaa75fd56a4aa225f2cea6e319f", "url": "https://github.com/thooams/Ui-Bibz/blob/bc0a3238c1c8bfaa75fd56a4aa225f2cea6e319f/lib/ui_bibz/ui/core/boxes/card.rb#L120-L123", "partition": "test"} {"repo": "thooams/Ui-Bibz", "path": "lib/ui_bibz/ui/core/boxes/card.rb", "func_name": "UiBibz::Ui::Core::Boxes.Card.list_group", "original_string": "def list_group content = nil, options = nil, html_options = nil, &block\n @items << UiBibz::Ui::Core::Boxes::Components::CardListGroup.new(content, options, html_options).tap(&block).render\n end", "language": "ruby", "code": "def list_group content = nil, options = nil, html_options = nil, &block\n @items << UiBibz::Ui::Core::Boxes::Components::CardListGroup.new(content, options, html_options).tap(&block).render\n end", "code_tokens": ["def", "list_group", "content", "=", "nil", ",", "options", "=", "nil", ",", "html_options", "=", "nil", ",", "&", "block", "@items", "<<", "UiBibz", "::", "Ui", "::", "Core", "::", "Boxes", "::", "Components", "::", "CardListGroup", ".", "new", "(", "content", ",", "options", ",", "html_options", ")", ".", "tap", "(", "block", ")", ".", "render", "end"], "docstring": "Add List group which is a component", "docstring_tokens": ["Add", "List", "group", "which", "is", "a", "component"], "sha": "bc0a3238c1c8bfaa75fd56a4aa225f2cea6e319f", "url": "https://github.com/thooams/Ui-Bibz/blob/bc0a3238c1c8bfaa75fd56a4aa225f2cea6e319f/lib/ui_bibz/ui/core/boxes/card.rb#L126-L128", "partition": "test"} {"repo": "thooams/Ui-Bibz", "path": "lib/ui_bibz/ui/core/boxes/card.rb", "func_name": "UiBibz::Ui::Core::Boxes.Card.image", "original_string": "def image content = nil, options = nil, html_options = nil, &block\n @items << UiBibz::Ui::Core::Boxes::Components::CardImage.new(content, options, html_options, &block).render\n end", "language": "ruby", "code": "def image content = nil, options = nil, html_options = nil, &block\n @items << UiBibz::Ui::Core::Boxes::Components::CardImage.new(content, options, html_options, &block).render\n end", "code_tokens": ["def", "image", "content", "=", "nil", ",", "options", "=", "nil", ",", "html_options", "=", "nil", ",", "&", "block", "@items", "<<", "UiBibz", "::", "Ui", "::", "Core", "::", "Boxes", "::", "Components", "::", "CardImage", ".", "new", "(", "content", ",", "options", ",", "html_options", ",", "block", ")", ".", "render", "end"], "docstring": "Add Image which is a component", "docstring_tokens": ["Add", "Image", "which", "is", "a", "component"], "sha": "bc0a3238c1c8bfaa75fd56a4aa225f2cea6e319f", "url": "https://github.com/thooams/Ui-Bibz/blob/bc0a3238c1c8bfaa75fd56a4aa225f2cea6e319f/lib/ui_bibz/ui/core/boxes/card.rb#L131-L133", "partition": "test"} {"repo": "thooams/Ui-Bibz", "path": "lib/ui_bibz/ui/core/forms/dropdowns/dropdown.rb", "func_name": "UiBibz::Ui::Core::Forms::Dropdowns.Dropdown.html", "original_string": "def html content = nil, &block\n if !block.nil?\n context = eval(\"self\", block.binding)\n @items << context.capture(&block)\n else\n @items << content\n end\n end", "language": "ruby", "code": "def html content = nil, &block\n if !block.nil?\n context = eval(\"self\", block.binding)\n @items << context.capture(&block)\n else\n @items << content\n end\n end", "code_tokens": ["def", "html", "content", "=", "nil", ",", "&", "block", "if", "!", "block", ".", "nil?", "context", "=", "eval", "(", "\"self\"", ",", "block", ".", "binding", ")", "@items", "<<", "context", ".", "capture", "(", "block", ")", "else", "@items", "<<", "content", "end", "end"], "docstring": "Add html component", "docstring_tokens": ["Add", "html", "component"], "sha": "bc0a3238c1c8bfaa75fd56a4aa225f2cea6e319f", "url": "https://github.com/thooams/Ui-Bibz/blob/bc0a3238c1c8bfaa75fd56a4aa225f2cea6e319f/lib/ui_bibz/ui/core/forms/dropdowns/dropdown.rb#L99-L106", "partition": "test"} {"repo": "thooams/Ui-Bibz", "path": "lib/ui_bibz/ui/core/forms/selects/abstract_select.rb", "func_name": "UiBibz::Ui::Core::Forms::Selects.AbstractSelect.component_html_options", "original_string": "def component_html_options\n super.merge({\n multiple: options[:multiple],\n disabled: options[:state] == :disabled,\n include_blank: options[:include_blank],\n prompt: options[:prompt]\n })\n end", "language": "ruby", "code": "def component_html_options\n super.merge({\n multiple: options[:multiple],\n disabled: options[:state] == :disabled,\n include_blank: options[:include_blank],\n prompt: options[:prompt]\n })\n end", "code_tokens": ["def", "component_html_options", "super", ".", "merge", "(", "{", "multiple", ":", "options", "[", ":multiple", "]", ",", "disabled", ":", "options", "[", ":state", "]", "==", ":disabled", ",", "include_blank", ":", "options", "[", ":include_blank", "]", ",", "prompt", ":", "options", "[", ":prompt", "]", "}", ")", "end"], "docstring": "Try to put it on a line", "docstring_tokens": ["Try", "to", "put", "it", "on", "a", "line"], "sha": "bc0a3238c1c8bfaa75fd56a4aa225f2cea6e319f", "url": "https://github.com/thooams/Ui-Bibz/blob/bc0a3238c1c8bfaa75fd56a4aa225f2cea6e319f/lib/ui_bibz/ui/core/forms/selects/abstract_select.rb#L89-L96", "partition": "test"} {"repo": "thooams/Ui-Bibz", "path": "lib/ui_bibz/ui/core/navigations/nav.rb", "func_name": "UiBibz::Ui::Core::Navigations.Nav.nav", "original_string": "def nav content = nil, options = {}, html_options = nil, &block\n @items << UiBibz::Ui::Core::Component.new(Nav.new(content, options).tap(&block).render, {}, html_options)\n end", "language": "ruby", "code": "def nav content = nil, options = {}, html_options = nil, &block\n @items << UiBibz::Ui::Core::Component.new(Nav.new(content, options).tap(&block).render, {}, html_options)\n end", "code_tokens": ["def", "nav", "content", "=", "nil", ",", "options", "=", "{", "}", ",", "html_options", "=", "nil", ",", "&", "block", "@items", "<<", "UiBibz", "::", "Ui", "::", "Core", "::", "Component", ".", "new", "(", "Nav", ".", "new", "(", "content", ",", "options", ")", ".", "tap", "(", "block", ")", ".", "render", ",", "{", "}", ",", "html_options", ")", "end"], "docstring": "Add nav in nav", "docstring_tokens": ["Add", "nav", "in", "nav"], "sha": "bc0a3238c1c8bfaa75fd56a4aa225f2cea6e319f", "url": "https://github.com/thooams/Ui-Bibz/blob/bc0a3238c1c8bfaa75fd56a4aa225f2cea6e319f/lib/ui_bibz/ui/core/navigations/nav.rb#L93-L95", "partition": "test"} {"repo": "thooams/Ui-Bibz", "path": "lib/ui_bibz/ui/core/notifications/alert.rb", "func_name": "UiBibz::Ui::Core::Notifications.Alert.body", "original_string": "def body content = nil, options = nil, html_options = nil, &block\n @body = UiBibz::Ui::Core::Notifications::Components::AlertBody.new(content, options, html_options, &block).render\n end", "language": "ruby", "code": "def body content = nil, options = nil, html_options = nil, &block\n @body = UiBibz::Ui::Core::Notifications::Components::AlertBody.new(content, options, html_options, &block).render\n end", "code_tokens": ["def", "body", "content", "=", "nil", ",", "options", "=", "nil", ",", "html_options", "=", "nil", ",", "&", "block", "@body", "=", "UiBibz", "::", "Ui", "::", "Core", "::", "Notifications", "::", "Components", "::", "AlertBody", ".", "new", "(", "content", ",", "options", ",", "html_options", ",", "block", ")", ".", "render", "end"], "docstring": "Add Body which is a component", "docstring_tokens": ["Add", "Body", "which", "is", "a", "component"], "sha": "bc0a3238c1c8bfaa75fd56a4aa225f2cea6e319f", "url": "https://github.com/thooams/Ui-Bibz/blob/bc0a3238c1c8bfaa75fd56a4aa225f2cea6e319f/lib/ui_bibz/ui/core/notifications/alert.rb#L77-L79", "partition": "test"} {"repo": "thooams/Ui-Bibz", "path": "lib/ui_bibz/ui/core/component.rb", "func_name": "UiBibz::Ui::Core.Component.is_tap", "original_string": "def is_tap content, options\n (content[:tap] if content.kind_of?(Hash)) || (options[:tap] unless options.nil?)\n end", "language": "ruby", "code": "def is_tap content, options\n (content[:tap] if content.kind_of?(Hash)) || (options[:tap] unless options.nil?)\n end", "code_tokens": ["def", "is_tap", "content", ",", "options", "(", "content", "[", ":tap", "]", "if", "content", ".", "kind_of?", "(", "Hash", ")", ")", "||", "(", "options", "[", ":tap", "]", "unless", "options", ".", "nil?", ")", "end"], "docstring": "Know if component is tapped or not", "docstring_tokens": ["Know", "if", "component", "is", "tapped", "or", "not"], "sha": "bc0a3238c1c8bfaa75fd56a4aa225f2cea6e319f", "url": "https://github.com/thooams/Ui-Bibz/blob/bc0a3238c1c8bfaa75fd56a4aa225f2cea6e319f/lib/ui_bibz/ui/core/component.rb#L92-L94", "partition": "test"} {"repo": "thooams/Ui-Bibz", "path": "lib/ui_bibz/ui/core/component.rb", "func_name": "UiBibz::Ui::Core.Component.component_html_data", "original_string": "def component_html_data\n # To stimulusjs\n data_target = html_options.try(:[], :data).try(:[], :target) || options.try(:delete, :target)\n add_html_data(:target, data_target) unless data_target.nil?\n\n data_controller = html_options.try(:[], :data).try(:[], :controller) || options.try(:delete, :controller)\n add_html_data(:controller, data_controller) unless data_controller.nil?\n\n data_action = html_options.try(:[], :data).try(:[], :action) || options.try(:delete, :action)\n add_html_data(:action, data_action) unless data_action.nil?\n\n # To turbolinks\n data_turbolinks = html_options.try(:[], :data).try(:[], :turbolinks) || options.try(:delete, :turbolinks)\n add_html_data(:turbolinks, data_turbolinks) unless data_turbolinks.nil?\n end", "language": "ruby", "code": "def component_html_data\n # To stimulusjs\n data_target = html_options.try(:[], :data).try(:[], :target) || options.try(:delete, :target)\n add_html_data(:target, data_target) unless data_target.nil?\n\n data_controller = html_options.try(:[], :data).try(:[], :controller) || options.try(:delete, :controller)\n add_html_data(:controller, data_controller) unless data_controller.nil?\n\n data_action = html_options.try(:[], :data).try(:[], :action) || options.try(:delete, :action)\n add_html_data(:action, data_action) unless data_action.nil?\n\n # To turbolinks\n data_turbolinks = html_options.try(:[], :data).try(:[], :turbolinks) || options.try(:delete, :turbolinks)\n add_html_data(:turbolinks, data_turbolinks) unless data_turbolinks.nil?\n end", "code_tokens": ["def", "component_html_data", "# To stimulusjs", "data_target", "=", "html_options", ".", "try", "(", ":[]", ",", ":data", ")", ".", "try", "(", ":[]", ",", ":target", ")", "||", "options", ".", "try", "(", ":delete", ",", ":target", ")", "add_html_data", "(", ":target", ",", "data_target", ")", "unless", "data_target", ".", "nil?", "data_controller", "=", "html_options", ".", "try", "(", ":[]", ",", ":data", ")", ".", "try", "(", ":[]", ",", ":controller", ")", "||", "options", ".", "try", "(", ":delete", ",", ":controller", ")", "add_html_data", "(", ":controller", ",", "data_controller", ")", "unless", "data_controller", ".", "nil?", "data_action", "=", "html_options", ".", "try", "(", ":[]", ",", ":data", ")", ".", "try", "(", ":[]", ",", ":action", ")", "||", "options", ".", "try", "(", ":delete", ",", ":action", ")", "add_html_data", "(", ":action", ",", "data_action", ")", "unless", "data_action", ".", "nil?", "# To turbolinks", "data_turbolinks", "=", "html_options", ".", "try", "(", ":[]", ",", ":data", ")", ".", "try", "(", ":[]", ",", ":turbolinks", ")", "||", "options", ".", "try", "(", ":delete", ",", ":turbolinks", ")", "add_html_data", "(", ":turbolinks", ",", "data_turbolinks", ")", "unless", "data_turbolinks", ".", "nil?", "end"], "docstring": "Override this method to add html data", "docstring_tokens": ["Override", "this", "method", "to", "add", "html", "data"], "sha": "bc0a3238c1c8bfaa75fd56a4aa225f2cea6e319f", "url": "https://github.com/thooams/Ui-Bibz/blob/bc0a3238c1c8bfaa75fd56a4aa225f2cea6e319f/lib/ui_bibz/ui/core/component.rb#L105-L119", "partition": "test"} {"repo": "thooams/Ui-Bibz", "path": "lib/ui_bibz/ui/core/component.rb", "func_name": "UiBibz::Ui::Core.Component.add_html_data", "original_string": "def add_html_data name, value = true\n html_options[:data] = {} if html_options[:data].nil?\n value = value.kind_of?(String) ? value.strip : value\n html_options[:data].update(Hash[name, value])\n end", "language": "ruby", "code": "def add_html_data name, value = true\n html_options[:data] = {} if html_options[:data].nil?\n value = value.kind_of?(String) ? value.strip : value\n html_options[:data].update(Hash[name, value])\n end", "code_tokens": ["def", "add_html_data", "name", ",", "value", "=", "true", "html_options", "[", ":data", "]", "=", "{", "}", "if", "html_options", "[", ":data", "]", ".", "nil?", "value", "=", "value", ".", "kind_of?", "(", "String", ")", "?", "value", ".", "strip", ":", "value", "html_options", "[", ":data", "]", ".", "update", "(", "Hash", "[", "name", ",", "value", "]", ")", "end"], "docstring": "Add html data arguments", "docstring_tokens": ["Add", "html", "data", "arguments"], "sha": "bc0a3238c1c8bfaa75fd56a4aa225f2cea6e319f", "url": "https://github.com/thooams/Ui-Bibz/blob/bc0a3238c1c8bfaa75fd56a4aa225f2cea6e319f/lib/ui_bibz/ui/core/component.rb#L139-L143", "partition": "test"} {"repo": "thooams/Ui-Bibz", "path": "lib/ui_bibz/ui/ux/tables/extensions/sortable.rb", "func_name": "UiBibz::Ui::Ux::Tables.Sortable.header", "original_string": "def header column, name = nil\n @column = column\n defaults = [translate_headers_by_defaults, translate_headers_by_defaults_active_record, translate_headers_by_active_record, header_name(name)]\n @name = UiBibz::Utils::Internationalization.new(translate_headers_by_model, default: defaults).translate\n sortable? ? sortable_link : title\n end", "language": "ruby", "code": "def header column, name = nil\n @column = column\n defaults = [translate_headers_by_defaults, translate_headers_by_defaults_active_record, translate_headers_by_active_record, header_name(name)]\n @name = UiBibz::Utils::Internationalization.new(translate_headers_by_model, default: defaults).translate\n sortable? ? sortable_link : title\n end", "code_tokens": ["def", "header", "column", ",", "name", "=", "nil", "@column", "=", "column", "defaults", "=", "[", "translate_headers_by_defaults", ",", "translate_headers_by_defaults_active_record", ",", "translate_headers_by_active_record", ",", "header_name", "(", "name", ")", "]", "@name", "=", "UiBibz", "::", "Utils", "::", "Internationalization", ".", "new", "(", "translate_headers_by_model", ",", "default", ":", "defaults", ")", ".", "translate", "sortable?", "?", "sortable_link", ":", "title", "end"], "docstring": "header use i18n", "docstring_tokens": ["header", "use", "i18n"], "sha": "bc0a3238c1c8bfaa75fd56a4aa225f2cea6e319f", "url": "https://github.com/thooams/Ui-Bibz/blob/bc0a3238c1c8bfaa75fd56a4aa225f2cea6e319f/lib/ui_bibz/ui/ux/tables/extensions/sortable.rb#L10-L15", "partition": "test"} {"repo": "thooams/Ui-Bibz", "path": "lib/ui_bibz/ui/ux/tables/components/columns.rb", "func_name": "UiBibz::Ui::Ux::Tables.Columns.column", "original_string": "def column data_index = nil, options = nil, html_options = nil, &block\n @columns << Column.new(data_index, options, html_options, &block)\n end", "language": "ruby", "code": "def column data_index = nil, options = nil, html_options = nil, &block\n @columns << Column.new(data_index, options, html_options, &block)\n end", "code_tokens": ["def", "column", "data_index", "=", "nil", ",", "options", "=", "nil", ",", "html_options", "=", "nil", ",", "&", "block", "@columns", "<<", "Column", ".", "new", "(", "data_index", ",", "options", ",", "html_options", ",", "block", ")", "end"], "docstring": "Add column in table", "docstring_tokens": ["Add", "column", "in", "table"], "sha": "bc0a3238c1c8bfaa75fd56a4aa225f2cea6e319f", "url": "https://github.com/thooams/Ui-Bibz/blob/bc0a3238c1c8bfaa75fd56a4aa225f2cea6e319f/lib/ui_bibz/ui/ux/tables/components/columns.rb#L9-L11", "partition": "test"} {"repo": "thooams/Ui-Bibz", "path": "lib/ui_bibz/ui/ux/tables/components/actions.rb", "func_name": "UiBibz::Ui::Ux::Tables.Actions.link", "original_string": "def link content = nil, options = nil, html_options = nil, &block\n @actions << UiBibz::Ui::Core::Forms::Dropdowns::Components::DropdownLink.new(content, options, html_options, &block).render\n end", "language": "ruby", "code": "def link content = nil, options = nil, html_options = nil, &block\n @actions << UiBibz::Ui::Core::Forms::Dropdowns::Components::DropdownLink.new(content, options, html_options, &block).render\n end", "code_tokens": ["def", "link", "content", "=", "nil", ",", "options", "=", "nil", ",", "html_options", "=", "nil", ",", "&", "block", "@actions", "<<", "UiBibz", "::", "Ui", "::", "Core", "::", "Forms", "::", "Dropdowns", "::", "Components", "::", "DropdownLink", ".", "new", "(", "content", ",", "options", ",", "html_options", ",", "block", ")", ".", "render", "end"], "docstring": "Add link action in table", "docstring_tokens": ["Add", "link", "action", "in", "table"], "sha": "bc0a3238c1c8bfaa75fd56a4aa225f2cea6e319f", "url": "https://github.com/thooams/Ui-Bibz/blob/bc0a3238c1c8bfaa75fd56a4aa225f2cea6e319f/lib/ui_bibz/ui/ux/tables/components/actions.rb#L14-L16", "partition": "test"} {"repo": "imathis/spark", "path": "lib/spark_engine/scaffold.rb", "func_name": "SparkEngine.Scaffold.engine_scaffold", "original_string": "def engine_scaffold\n FileUtils.mkdir_p(@gem_temp)\n Dir.chdir(@gem_temp) do\n response = Open3.capture3(\"rails plugin new #{gem} --mountable --dummy-path=site --skip-test-unit\")\n if !response[1].empty?\n puts response[1]\n abort \"FAILED: Please be sure you have the rails gem installed with `gem install rails`\"\n end\n\n # Remove files and directories that are unnecessary for the\n # light-weight Rails documentation site\n remove = %w(mailers models assets channels jobs views).map{ |f| File.join('app', f) }\n remove.concat %w(cable.yml storage.yml database.yml).map{ |f| File.join('config', f) }\n\n remove.each { |f| FileUtils.rm_rf File.join(@gem, 'site', f), secure: true }\n end\n \n\n engine_copy\n end", "language": "ruby", "code": "def engine_scaffold\n FileUtils.mkdir_p(@gem_temp)\n Dir.chdir(@gem_temp) do\n response = Open3.capture3(\"rails plugin new #{gem} --mountable --dummy-path=site --skip-test-unit\")\n if !response[1].empty?\n puts response[1]\n abort \"FAILED: Please be sure you have the rails gem installed with `gem install rails`\"\n end\n\n # Remove files and directories that are unnecessary for the\n # light-weight Rails documentation site\n remove = %w(mailers models assets channels jobs views).map{ |f| File.join('app', f) }\n remove.concat %w(cable.yml storage.yml database.yml).map{ |f| File.join('config', f) }\n\n remove.each { |f| FileUtils.rm_rf File.join(@gem, 'site', f), secure: true }\n end\n \n\n engine_copy\n end", "code_tokens": ["def", "engine_scaffold", "FileUtils", ".", "mkdir_p", "(", "@gem_temp", ")", "Dir", ".", "chdir", "(", "@gem_temp", ")", "do", "response", "=", "Open3", ".", "capture3", "(", "\"rails plugin new #{gem} --mountable --dummy-path=site --skip-test-unit\"", ")", "if", "!", "response", "[", "1", "]", ".", "empty?", "puts", "response", "[", "1", "]", "abort", "\"FAILED: Please be sure you have the rails gem installed with `gem install rails`\"", "end", "# Remove files and directories that are unnecessary for the", "# light-weight Rails documentation site", "remove", "=", "%w(", "mailers", "models", "assets", "channels", "jobs", "views", ")", ".", "map", "{", "|", "f", "|", "File", ".", "join", "(", "'app'", ",", "f", ")", "}", "remove", ".", "concat", "%w(", "cable.yml", "storage.yml", "database.yml", ")", ".", "map", "{", "|", "f", "|", "File", ".", "join", "(", "'config'", ",", "f", ")", "}", "remove", ".", "each", "{", "|", "f", "|", "FileUtils", ".", "rm_rf", "File", ".", "join", "(", "@gem", ",", "'site'", ",", "f", ")", ",", "secure", ":", "true", "}", "end", "engine_copy", "end"], "docstring": "Create an Rails plugin engine for documentation site", "docstring_tokens": ["Create", "an", "Rails", "plugin", "engine", "for", "documentation", "site"], "sha": "7a50c7136ba0ed0377020570a6a59314ef9c0a74", "url": "https://github.com/imathis/spark/blob/7a50c7136ba0ed0377020570a6a59314ef9c0a74/lib/spark_engine/scaffold.rb#L72-L91", "partition": "test"} {"repo": "imathis/spark", "path": "lib/spark_engine/scaffold.rb", "func_name": "SparkEngine.Scaffold.engine_copy", "original_string": "def engine_copy\n site_path = File.join path, 'site'\n FileUtils.mkdir_p site_path\n\n ## Copy Rails plugin files\n Dir.chdir \"#{@gem_temp}/#{gem}/site\" do\n %w(app config bin config.ru Rakefile public log).each do |item|\n target = File.join site_path, item\n\n FileUtils.cp_r item, target\n\n action_log \"create\", target.sub(@cwd+'/','')\n end\n\n end\n\n # Remove temp dir\n FileUtils.rm_rf @gem_temp\n end", "language": "ruby", "code": "def engine_copy\n site_path = File.join path, 'site'\n FileUtils.mkdir_p site_path\n\n ## Copy Rails plugin files\n Dir.chdir \"#{@gem_temp}/#{gem}/site\" do\n %w(app config bin config.ru Rakefile public log).each do |item|\n target = File.join site_path, item\n\n FileUtils.cp_r item, target\n\n action_log \"create\", target.sub(@cwd+'/','')\n end\n\n end\n\n # Remove temp dir\n FileUtils.rm_rf @gem_temp\n end", "code_tokens": ["def", "engine_copy", "site_path", "=", "File", ".", "join", "path", ",", "'site'", "FileUtils", ".", "mkdir_p", "site_path", "## Copy Rails plugin files", "Dir", ".", "chdir", "\"#{@gem_temp}/#{gem}/site\"", "do", "%w(", "app", "config", "bin", "config.ru", "Rakefile", "public", "log", ")", ".", "each", "do", "|", "item", "|", "target", "=", "File", ".", "join", "site_path", ",", "item", "FileUtils", ".", "cp_r", "item", ",", "target", "action_log", "\"create\"", ",", "target", ".", "sub", "(", "@cwd", "+", "'/'", ",", "''", ")", "end", "end", "# Remove temp dir", "FileUtils", ".", "rm_rf", "@gem_temp", "end"], "docstring": "Copy parts of the engine scaffold into site directory", "docstring_tokens": ["Copy", "parts", "of", "the", "engine", "scaffold", "into", "site", "directory"], "sha": "7a50c7136ba0ed0377020570a6a59314ef9c0a74", "url": "https://github.com/imathis/spark/blob/7a50c7136ba0ed0377020570a6a59314ef9c0a74/lib/spark_engine/scaffold.rb#L94-L112", "partition": "test"} {"repo": "imathis/spark", "path": "lib/spark_engine/sass/sass_yaml.rb", "func_name": "SassC.SassYaml.make_map", "original_string": "def make_map(item)\n '(' + item.map {|key, value| key.to_s + ':' + convert_to_sass_value(value) }.join(',') + ')'\n end", "language": "ruby", "code": "def make_map(item)\n '(' + item.map {|key, value| key.to_s + ':' + convert_to_sass_value(value) }.join(',') + ')'\n end", "code_tokens": ["def", "make_map", "(", "item", ")", "'('", "+", "item", ".", "map", "{", "|", "key", ",", "value", "|", "key", ".", "to_s", "+", "':'", "+", "convert_to_sass_value", "(", "value", ")", "}", ".", "join", "(", "','", ")", "+", "')'", "end"], "docstring": "Convert hashes to Sass map syntax", "docstring_tokens": ["Convert", "hashes", "to", "Sass", "map", "syntax"], "sha": "7a50c7136ba0ed0377020570a6a59314ef9c0a74", "url": "https://github.com/imathis/spark/blob/7a50c7136ba0ed0377020570a6a59314ef9c0a74/lib/spark_engine/sass/sass_yaml.rb#L86-L88", "partition": "test"} {"repo": "imathis/spark", "path": "lib/spark_engine/plugin.rb", "func_name": "SparkEngine.Plugin.add_files", "original_string": "def add_files(klass)\n ext = asset_ext klass\n find_files(ext).map do |path|\n klass.new(self, path)\n end\n end", "language": "ruby", "code": "def add_files(klass)\n ext = asset_ext klass\n find_files(ext).map do |path|\n klass.new(self, path)\n end\n end", "code_tokens": ["def", "add_files", "(", "klass", ")", "ext", "=", "asset_ext", "klass", "find_files", "(", "ext", ")", ".", "map", "do", "|", "path", "|", "klass", ".", "new", "(", "self", ",", "path", ")", "end", "end"], "docstring": "Find files based on class type and\n return an array of Classes for each file", "docstring_tokens": ["Find", "files", "based", "on", "class", "type", "and", "return", "an", "array", "of", "Classes", "for", "each", "file"], "sha": "7a50c7136ba0ed0377020570a6a59314ef9c0a74", "url": "https://github.com/imathis/spark/blob/7a50c7136ba0ed0377020570a6a59314ef9c0a74/lib/spark_engine/plugin.rb#L187-L192", "partition": "test"} {"repo": "imathis/spark", "path": "lib/spark_engine/plugin.rb", "func_name": "SparkEngine.Plugin.find_files", "original_string": "def find_files(ext)\n files = Dir[File.join(paths[ext.to_sym], asset_glob(ext))]\n\n # Filter out partials\n files.reject { |f| File.basename(f).start_with?('_') }\n end", "language": "ruby", "code": "def find_files(ext)\n files = Dir[File.join(paths[ext.to_sym], asset_glob(ext))]\n\n # Filter out partials\n files.reject { |f| File.basename(f).start_with?('_') }\n end", "code_tokens": ["def", "find_files", "(", "ext", ")", "files", "=", "Dir", "[", "File", ".", "join", "(", "paths", "[", "ext", ".", "to_sym", "]", ",", "asset_glob", "(", "ext", ")", ")", "]", "# Filter out partials", "files", ".", "reject", "{", "|", "f", "|", "File", ".", "basename", "(", "f", ")", ".", "start_with?", "(", "'_'", ")", "}", "end"], "docstring": "Find files by class type and extension", "docstring_tokens": ["Find", "files", "by", "class", "type", "and", "extension"], "sha": "7a50c7136ba0ed0377020570a6a59314ef9c0a74", "url": "https://github.com/imathis/spark/blob/7a50c7136ba0ed0377020570a6a59314ef9c0a74/lib/spark_engine/plugin.rb#L195-L200", "partition": "test"} {"repo": "imathis/spark", "path": "lib/spark_engine/command.rb", "func_name": "SparkEngine.Command.dispatch", "original_string": "def dispatch(command, *args)\n @threads = []\n send command, *args\n @threads.each { |thr| thr.join }\n end", "language": "ruby", "code": "def dispatch(command, *args)\n @threads = []\n send command, *args\n @threads.each { |thr| thr.join }\n end", "code_tokens": ["def", "dispatch", "(", "command", ",", "*", "args", ")", "@threads", "=", "[", "]", "send", "command", ",", "args", "@threads", ".", "each", "{", "|", "thr", "|", "thr", ".", "join", "}", "end"], "docstring": "Handles running threaded commands", "docstring_tokens": ["Handles", "running", "threaded", "commands"], "sha": "7a50c7136ba0ed0377020570a6a59314ef9c0a74", "url": "https://github.com/imathis/spark/blob/7a50c7136ba0ed0377020570a6a59314ef9c0a74/lib/spark_engine/command.rb#L122-L126", "partition": "test"} {"repo": "imathis/spark", "path": "lib/spark_engine/command.rb", "func_name": "SparkEngine.Command.watch", "original_string": "def watch(options={})\n build(options)\n require 'listen'\n\n trap(\"SIGINT\") {\n puts \"\\nspark_engine watcher stopped. Have a nice day!\"\n exit!\n }\n\n @threads.concat SparkEngine.load_plugin.watch(options)\n end", "language": "ruby", "code": "def watch(options={})\n build(options)\n require 'listen'\n\n trap(\"SIGINT\") {\n puts \"\\nspark_engine watcher stopped. Have a nice day!\"\n exit!\n }\n\n @threads.concat SparkEngine.load_plugin.watch(options)\n end", "code_tokens": ["def", "watch", "(", "options", "=", "{", "}", ")", "build", "(", "options", ")", "require", "'listen'", "trap", "(", "\"SIGINT\"", ")", "{", "puts", "\"\\nspark_engine watcher stopped. Have a nice day!\"", "exit!", "}", "@threads", ".", "concat", "SparkEngine", ".", "load_plugin", ".", "watch", "(", "options", ")", "end"], "docstring": "Watch assets for changes and build", "docstring_tokens": ["Watch", "assets", "for", "changes", "and", "build"], "sha": "7a50c7136ba0ed0377020570a6a59314ef9c0a74", "url": "https://github.com/imathis/spark/blob/7a50c7136ba0ed0377020570a6a59314ef9c0a74/lib/spark_engine/command.rb#L137-L147", "partition": "test"} {"repo": "sportdb/sport.db", "path": "sportdb-models/lib/sportdb/reader.rb", "func_name": "SportDb.ReaderBase.load_setup", "original_string": "def load_setup( name )\r\n reader = create_fixture_reader( name )\r\n\r\n reader.each do |fixture_name|\r\n load( fixture_name )\r\n end\r\n end", "language": "ruby", "code": "def load_setup( name )\r\n reader = create_fixture_reader( name )\r\n\r\n reader.each do |fixture_name|\r\n load( fixture_name )\r\n end\r\n end", "code_tokens": ["def", "load_setup", "(", "name", ")", "reader", "=", "create_fixture_reader", "(", "name", ")", "reader", ".", "each", "do", "|", "fixture_name", "|", "load", "(", "fixture_name", ")", "end", "end"], "docstring": "lets us use match_teams_for_country etc.", "docstring_tokens": ["lets", "us", "use", "match_teams_for_country", "etc", "."], "sha": "68a6d7ce7f31fc7dc74c8d6b74a6b542ff7d0396", "url": "https://github.com/sportdb/sport.db/blob/68a6d7ce7f31fc7dc74c8d6b74a6b542ff7d0396/sportdb-models/lib/sportdb/reader.rb#L16-L22", "partition": "test"} {"repo": "sandrods/odf-report", "path": "lib/odf-report/images.rb", "func_name": "ODFReport.Images.avoid_duplicate_image_names", "original_string": "def avoid_duplicate_image_names(content)\n\n nodes = content.xpath(\"//draw:frame[@draw:name]\")\n\n nodes.each_with_index do |node, i|\n node.attribute('name').value = \"pic_#{i}\"\n end\n\n end", "language": "ruby", "code": "def avoid_duplicate_image_names(content)\n\n nodes = content.xpath(\"//draw:frame[@draw:name]\")\n\n nodes.each_with_index do |node, i|\n node.attribute('name').value = \"pic_#{i}\"\n end\n\n end", "code_tokens": ["def", "avoid_duplicate_image_names", "(", "content", ")", "nodes", "=", "content", ".", "xpath", "(", "\"//draw:frame[@draw:name]\"", ")", "nodes", ".", "each_with_index", "do", "|", "node", ",", "i", "|", "node", ".", "attribute", "(", "'name'", ")", ".", "value", "=", "\"pic_#{i}\"", "end", "end"], "docstring": "replace_images\n newer versions of LibreOffice can't open files with duplicates image names", "docstring_tokens": ["replace_images", "newer", "versions", "of", "LibreOffice", "can", "t", "open", "files", "with", "duplicates", "image", "names"], "sha": "24550efb6493a4dd2eee4e35461929381884eeb7", "url": "https://github.com/sandrods/odf-report/blob/24550efb6493a4dd2eee4e35461929381884eeb7/lib/odf-report/images.rb#L32-L40", "partition": "test"} {"repo": "gomo/dynamic_scaffold", "path": "lib/dynamic_scaffold/controller_utilities.rb", "func_name": "DynamicScaffold.ControllerUtilities.scope_params", "original_string": "def scope_params\n return {} if dynamic_scaffold.scope.nil?\n\n case dynamic_scaffold.scope\n when Array then\n dynamic_scaffold.scope.each_with_object({}) do |val, res|\n if val.is_a? Hash\n val.each {|k, v| res[k] = v }\n else\n res[val] = params[val]\n end\n end\n when Hash then\n dynamic_scaffold.scope\n end\n end", "language": "ruby", "code": "def scope_params\n return {} if dynamic_scaffold.scope.nil?\n\n case dynamic_scaffold.scope\n when Array then\n dynamic_scaffold.scope.each_with_object({}) do |val, res|\n if val.is_a? Hash\n val.each {|k, v| res[k] = v }\n else\n res[val] = params[val]\n end\n end\n when Hash then\n dynamic_scaffold.scope\n end\n end", "code_tokens": ["def", "scope_params", "return", "{", "}", "if", "dynamic_scaffold", ".", "scope", ".", "nil?", "case", "dynamic_scaffold", ".", "scope", "when", "Array", "then", "dynamic_scaffold", ".", "scope", ".", "each_with_object", "(", "{", "}", ")", "do", "|", "val", ",", "res", "|", "if", "val", ".", "is_a?", "Hash", "val", ".", "each", "{", "|", "k", ",", "v", "|", "res", "[", "k", "]", "=", "v", "}", "else", "res", "[", "val", "]", "=", "params", "[", "val", "]", "end", "end", "when", "Hash", "then", "dynamic_scaffold", ".", "scope", "end", "end"], "docstring": "Get the hash of the key and value specified for the scope.", "docstring_tokens": ["Get", "the", "hash", "of", "the", "key", "and", "value", "specified", "for", "the", "scope", "."], "sha": "4a61d794deb234a49f842e96d055a10e57a4fb55", "url": "https://github.com/gomo/dynamic_scaffold/blob/4a61d794deb234a49f842e96d055a10e57a4fb55/lib/dynamic_scaffold/controller_utilities.rb#L6-L21", "partition": "test"} {"repo": "gomo/dynamic_scaffold", "path": "lib/dynamic_scaffold/controller_utilities.rb", "func_name": "DynamicScaffold.ControllerUtilities.pkey_string_to_hash", "original_string": "def pkey_string_to_hash(pkey)\n # https://github.com/gomo/dynamic_scaffold/pull/9/commits/ff5de0e38b3544347e82539c45ffd2efaf3410da\n # Stop support multiple pkey, on this commit.\n # Convert \"key:1,code:foo\" to {key: \"1\", code: \"foo\"}\n pkey.split(',').map {|v| v.split(':') }.each_with_object({}) {|v, res| res[v.first] = v.last }\n end", "language": "ruby", "code": "def pkey_string_to_hash(pkey)\n # https://github.com/gomo/dynamic_scaffold/pull/9/commits/ff5de0e38b3544347e82539c45ffd2efaf3410da\n # Stop support multiple pkey, on this commit.\n # Convert \"key:1,code:foo\" to {key: \"1\", code: \"foo\"}\n pkey.split(',').map {|v| v.split(':') }.each_with_object({}) {|v, res| res[v.first] = v.last }\n end", "code_tokens": ["def", "pkey_string_to_hash", "(", "pkey", ")", "# https://github.com/gomo/dynamic_scaffold/pull/9/commits/ff5de0e38b3544347e82539c45ffd2efaf3410da", "# Stop support multiple pkey, on this commit.", "# Convert \"key:1,code:foo\" to {key: \"1\", code: \"foo\"}", "pkey", ".", "split", "(", "','", ")", ".", "map", "{", "|", "v", "|", "v", ".", "split", "(", "':'", ")", "}", ".", "each_with_object", "(", "{", "}", ")", "{", "|", "v", ",", "res", "|", "res", "[", "v", ".", "first", "]", "=", "v", ".", "last", "}", "end"], "docstring": "Convert pkey_string value to hash.", "docstring_tokens": ["Convert", "pkey_string", "value", "to", "hash", "."], "sha": "4a61d794deb234a49f842e96d055a10e57a4fb55", "url": "https://github.com/gomo/dynamic_scaffold/blob/4a61d794deb234a49f842e96d055a10e57a4fb55/lib/dynamic_scaffold/controller_utilities.rb#L24-L29", "partition": "test"} {"repo": "gomo/dynamic_scaffold", "path": "lib/dynamic_scaffold/controller_utilities.rb", "func_name": "DynamicScaffold.ControllerUtilities.update_values", "original_string": "def update_values # rubocop:disable Metrics/AbcSize\n # set the parameters of carrierwave_image at the end for validates.\n permitting = []\n dynamic_scaffold.form.items.reject {|i| i.type?(:carrierwave_image) }.each do |item|\n item.extract_parameters(permitting)\n end\n permitting.concat(dynamic_scaffold.form.permit_params)\n dynamic_scaffold.form.items.select {|i| i.type?(:carrierwave_image) }.each do |item|\n item.extract_parameters(permitting)\n end\n\n values = params\n .require(dynamic_scaffold.model.name.underscore)\n .permit(*permitting)\n\n if dynamic_scaffold.scope && !valid_for_scope?(values)\n raise DynamicScaffold::Error::InvalidOperation, \"You can update only to #{scope_params} on this scope\"\n end\n\n values\n end", "language": "ruby", "code": "def update_values # rubocop:disable Metrics/AbcSize\n # set the parameters of carrierwave_image at the end for validates.\n permitting = []\n dynamic_scaffold.form.items.reject {|i| i.type?(:carrierwave_image) }.each do |item|\n item.extract_parameters(permitting)\n end\n permitting.concat(dynamic_scaffold.form.permit_params)\n dynamic_scaffold.form.items.select {|i| i.type?(:carrierwave_image) }.each do |item|\n item.extract_parameters(permitting)\n end\n\n values = params\n .require(dynamic_scaffold.model.name.underscore)\n .permit(*permitting)\n\n if dynamic_scaffold.scope && !valid_for_scope?(values)\n raise DynamicScaffold::Error::InvalidOperation, \"You can update only to #{scope_params} on this scope\"\n end\n\n values\n end", "code_tokens": ["def", "update_values", "# rubocop:disable Metrics/AbcSize", "# set the parameters of carrierwave_image at the end for validates.", "permitting", "=", "[", "]", "dynamic_scaffold", ".", "form", ".", "items", ".", "reject", "{", "|", "i", "|", "i", ".", "type?", "(", ":carrierwave_image", ")", "}", ".", "each", "do", "|", "item", "|", "item", ".", "extract_parameters", "(", "permitting", ")", "end", "permitting", ".", "concat", "(", "dynamic_scaffold", ".", "form", ".", "permit_params", ")", "dynamic_scaffold", ".", "form", ".", "items", ".", "select", "{", "|", "i", "|", "i", ".", "type?", "(", ":carrierwave_image", ")", "}", ".", "each", "do", "|", "item", "|", "item", ".", "extract_parameters", "(", "permitting", ")", "end", "values", "=", "params", ".", "require", "(", "dynamic_scaffold", ".", "model", ".", "name", ".", "underscore", ")", ".", "permit", "(", "permitting", ")", "if", "dynamic_scaffold", ".", "scope", "&&", "!", "valid_for_scope?", "(", "values", ")", "raise", "DynamicScaffold", "::", "Error", "::", "InvalidOperation", ",", "\"You can update only to #{scope_params} on this scope\"", "end", "values", "end"], "docstring": "Get paramters for update record.", "docstring_tokens": ["Get", "paramters", "for", "update", "record", "."], "sha": "4a61d794deb234a49f842e96d055a10e57a4fb55", "url": "https://github.com/gomo/dynamic_scaffold/blob/4a61d794deb234a49f842e96d055a10e57a4fb55/lib/dynamic_scaffold/controller_utilities.rb#L44-L64", "partition": "test"} {"repo": "gomo/dynamic_scaffold", "path": "lib/dynamic_scaffold/controller_utilities.rb", "func_name": "DynamicScaffold.ControllerUtilities.valid_for_scope?", "original_string": "def valid_for_scope?(update_params)\n return true if dynamic_scaffold.scope_options[:changeable]\n\n result = true\n scope_params.each do |key, value|\n if update_params.key?(key) && update_params[key] != value\n result = false\n break\n end\n end\n result\n end", "language": "ruby", "code": "def valid_for_scope?(update_params)\n return true if dynamic_scaffold.scope_options[:changeable]\n\n result = true\n scope_params.each do |key, value|\n if update_params.key?(key) && update_params[key] != value\n result = false\n break\n end\n end\n result\n end", "code_tokens": ["def", "valid_for_scope?", "(", "update_params", ")", "return", "true", "if", "dynamic_scaffold", ".", "scope_options", "[", ":changeable", "]", "result", "=", "true", "scope_params", ".", "each", "do", "|", "key", ",", "value", "|", "if", "update_params", ".", "key?", "(", "key", ")", "&&", "update_params", "[", "key", "]", "!=", "value", "result", "=", "false", "break", "end", "end", "result", "end"], "docstring": "Check if there are inconsistent scopes in update parameters", "docstring_tokens": ["Check", "if", "there", "are", "inconsistent", "scopes", "in", "update", "parameters"], "sha": "4a61d794deb234a49f842e96d055a10e57a4fb55", "url": "https://github.com/gomo/dynamic_scaffold/blob/4a61d794deb234a49f842e96d055a10e57a4fb55/lib/dynamic_scaffold/controller_utilities.rb#L67-L78", "partition": "test"} {"repo": "academia-edu/redis_locks", "path": "lib/redis_locks/semaphore.rb", "func_name": "RedisLocks.Semaphore.lock", "original_string": "def lock(timeout: nil, &block)\n ensure_exists_and_release_stale_locks!\n\n success = @redis.with do |conn|\n if timeout\n !conn.blpop(available_key, timeout.to_i).nil?\n else\n !conn.lpop(available_key).nil?\n end\n end\n\n return false unless success\n\n token = SecureRandom.hex(16)\n @tokens.push(token)\n @redis.with do |conn|\n conn.zadd(grabbed_key, epoch_f(conn), token)\n end\n\n return_or_yield(token, &block)\n end", "language": "ruby", "code": "def lock(timeout: nil, &block)\n ensure_exists_and_release_stale_locks!\n\n success = @redis.with do |conn|\n if timeout\n !conn.blpop(available_key, timeout.to_i).nil?\n else\n !conn.lpop(available_key).nil?\n end\n end\n\n return false unless success\n\n token = SecureRandom.hex(16)\n @tokens.push(token)\n @redis.with do |conn|\n conn.zadd(grabbed_key, epoch_f(conn), token)\n end\n\n return_or_yield(token, &block)\n end", "code_tokens": ["def", "lock", "(", "timeout", ":", "nil", ",", "&", "block", ")", "ensure_exists_and_release_stale_locks!", "success", "=", "@redis", ".", "with", "do", "|", "conn", "|", "if", "timeout", "!", "conn", ".", "blpop", "(", "available_key", ",", "timeout", ".", "to_i", ")", ".", "nil?", "else", "!", "conn", ".", "lpop", "(", "available_key", ")", ".", "nil?", "end", "end", "return", "false", "unless", "success", "token", "=", "SecureRandom", ".", "hex", "(", "16", ")", "@tokens", ".", "push", "(", "token", ")", "@redis", ".", "with", "do", "|", "conn", "|", "conn", ".", "zadd", "(", "grabbed_key", ",", "epoch_f", "(", "conn", ")", ",", "token", ")", "end", "return_or_yield", "(", "token", ",", "block", ")", "end"], "docstring": "Acquire a resource from the semaphore, if available. Returns false if no\n resources are available.\n\n `timeout` is how long to wait, blocking, until a resource is available.\n The default is nil, meaning don't block. A timeout of zero means block forever.\n (This is a bit weird, but corresponds to how blpop uses timeout values.)\n\n If passed a block, if a resource is available, runs the block and then\n unlocks.\n\n If called without a block, if a resource is available, returns a token.\n Caller is then responsible for unlocking the token.\n\n This isn't atomic--if the process dies, we could remove something from the\n available queue without adding it to the grabbed set--but that's ok, the\n semaphore will recover just as if this was a stale client that left its\n token in the grabbed set forever.", "docstring_tokens": ["Acquire", "a", "resource", "from", "the", "semaphore", "if", "available", ".", "Returns", "false", "if", "no", "resources", "are", "available", "."], "sha": "01c9c4b6c9a65613715325bcd0ed55bad53c484f", "url": "https://github.com/academia-edu/redis_locks/blob/01c9c4b6c9a65613715325bcd0ed55bad53c484f/lib/redis_locks/semaphore.rb#L104-L124", "partition": "test"} {"repo": "academia-edu/redis_locks", "path": "lib/redis_locks/semaphore.rb", "func_name": "RedisLocks.Semaphore.unlock", "original_string": "def unlock(token = @tokens.pop)\n return unless token\n\n removed = false\n\n @redis.with do |conn|\n removed = conn.zrem grabbed_key, token\n if removed\n conn.lpush available_key, 1\n end\n end\n\n removed\n end", "language": "ruby", "code": "def unlock(token = @tokens.pop)\n return unless token\n\n removed = false\n\n @redis.with do |conn|\n removed = conn.zrem grabbed_key, token\n if removed\n conn.lpush available_key, 1\n end\n end\n\n removed\n end", "code_tokens": ["def", "unlock", "(", "token", "=", "@tokens", ".", "pop", ")", "return", "unless", "token", "removed", "=", "false", "@redis", ".", "with", "do", "|", "conn", "|", "removed", "=", "conn", ".", "zrem", "grabbed_key", ",", "token", "if", "removed", "conn", ".", "lpush", "available_key", ",", "1", "end", "end", "removed", "end"], "docstring": "Release a resource back to the semaphore. Should normally be called with an\n explicit token.\n\n This isn't atomic--if the process dies, we could remove something from the\n blocked set without adding it to the available queue--but that's ok, the\n semaphore will recover just as if this was a stale client that left its\n token in the grabbed set forever.", "docstring_tokens": ["Release", "a", "resource", "back", "to", "the", "semaphore", ".", "Should", "normally", "be", "called", "with", "an", "explicit", "token", "."], "sha": "01c9c4b6c9a65613715325bcd0ed55bad53c484f", "url": "https://github.com/academia-edu/redis_locks/blob/01c9c4b6c9a65613715325bcd0ed55bad53c484f/lib/redis_locks/semaphore.rb#L147-L160", "partition": "test"} {"repo": "splattael/libnotify", "path": "lib/libnotify/api.rb", "func_name": "Libnotify.API.apply_options", "original_string": "def apply_options(options={})\n options.each { |key, value| send(\"#{key}=\", value) if respond_to?(key) }\n yield(self) if block_given?\n end", "language": "ruby", "code": "def apply_options(options={})\n options.each { |key, value| send(\"#{key}=\", value) if respond_to?(key) }\n yield(self) if block_given?\n end", "code_tokens": ["def", "apply_options", "(", "options", "=", "{", "}", ")", "options", ".", "each", "{", "|", "key", ",", "value", "|", "send", "(", "\"#{key}=\"", ",", "value", ")", "if", "respond_to?", "(", "key", ")", "}", "yield", "(", "self", ")", "if", "block_given?", "end"], "docstring": "Creates a notification object.\n\n @see Libnotify.new", "docstring_tokens": ["Creates", "a", "notification", "object", "."], "sha": "9d190bb8875039db4fa6d3cc63cb57cad49e8d7c", "url": "https://github.com/splattael/libnotify/blob/9d190bb8875039db4fa6d3cc63cb57cad49e8d7c/lib/libnotify/api.rb#L32-L35", "partition": "test"} {"repo": "splattael/libnotify", "path": "lib/libnotify/api.rb", "func_name": "Libnotify.API.show!", "original_string": "def show!\n notify_init(app_name) or raise \"notify_init failed\"\n raw_ptr = notify_notification_new(summary, body, icon_path, nil)\n @notification = ::FFI::AutoPointer.new(raw_ptr, method(:g_object_unref))\n show\n end", "language": "ruby", "code": "def show!\n notify_init(app_name) or raise \"notify_init failed\"\n raw_ptr = notify_notification_new(summary, body, icon_path, nil)\n @notification = ::FFI::AutoPointer.new(raw_ptr, method(:g_object_unref))\n show\n end", "code_tokens": ["def", "show!", "notify_init", "(", "app_name", ")", "or", "raise", "\"notify_init failed\"", "raw_ptr", "=", "notify_notification_new", "(", "summary", ",", "body", ",", "icon_path", ",", "nil", ")", "@notification", "=", "::", "FFI", "::", "AutoPointer", ".", "new", "(", "raw_ptr", ",", "method", "(", ":g_object_unref", ")", ")", "show", "end"], "docstring": "Shows a new notification.\n\n @see Libnotify.show", "docstring_tokens": ["Shows", "a", "new", "notification", "."], "sha": "9d190bb8875039db4fa6d3cc63cb57cad49e8d7c", "url": "https://github.com/splattael/libnotify/blob/9d190bb8875039db4fa6d3cc63cb57cad49e8d7c/lib/libnotify/api.rb#L51-L56", "partition": "test"} {"repo": "splattael/libnotify", "path": "lib/libnotify/api.rb", "func_name": "Libnotify.API.update", "original_string": "def update(options={}, &block)\n apply_options(options, &block)\n if @notification\n notify_notification_update(@notification, summary, body, icon_path, nil)\n show\n else\n show!\n end\n end", "language": "ruby", "code": "def update(options={}, &block)\n apply_options(options, &block)\n if @notification\n notify_notification_update(@notification, summary, body, icon_path, nil)\n show\n else\n show!\n end\n end", "code_tokens": ["def", "update", "(", "options", "=", "{", "}", ",", "&", "block", ")", "apply_options", "(", "options", ",", "block", ")", "if", "@notification", "notify_notification_update", "(", "@notification", ",", "summary", ",", "body", ",", "icon_path", ",", "nil", ")", "show", "else", "show!", "end", "end"], "docstring": "Updates a previously shown notification or creates a new one.", "docstring_tokens": ["Updates", "a", "previously", "shown", "notification", "or", "creates", "a", "new", "one", "."], "sha": "9d190bb8875039db4fa6d3cc63cb57cad49e8d7c", "url": "https://github.com/splattael/libnotify/blob/9d190bb8875039db4fa6d3cc63cb57cad49e8d7c/lib/libnotify/api.rb#L69-L77", "partition": "test"} {"repo": "layer8x/youtube-dl.rb", "path": "lib/youtube-dl/video.rb", "func_name": "YoutubeDL.Video.download", "original_string": "def download\n raise ArgumentError.new('url cannot be nil') if @url.nil?\n raise ArgumentError.new('url cannot be empty') if @url.empty?\n\n set_information_from_json(YoutubeDL::Runner.new(url, runner_options).run)\n end", "language": "ruby", "code": "def download\n raise ArgumentError.new('url cannot be nil') if @url.nil?\n raise ArgumentError.new('url cannot be empty') if @url.empty?\n\n set_information_from_json(YoutubeDL::Runner.new(url, runner_options).run)\n end", "code_tokens": ["def", "download", "raise", "ArgumentError", ".", "new", "(", "'url cannot be nil'", ")", "if", "@url", ".", "nil?", "raise", "ArgumentError", ".", "new", "(", "'url cannot be empty'", ")", "if", "@url", ".", "empty?", "set_information_from_json", "(", "YoutubeDL", "::", "Runner", ".", "new", "(", "url", ",", "runner_options", ")", ".", "run", ")", "end"], "docstring": "Instantiate new model\n\n @param url [String] URL to initialize with\n @param options [Hash] Options to populate the everything with\n Download the video.", "docstring_tokens": ["Instantiate", "new", "model"], "sha": "05cc66ae863ae4b946b29774b323a3e944cdf0ca", "url": "https://github.com/layer8x/youtube-dl.rb/blob/05cc66ae863ae4b946b29774b323a3e944cdf0ca/lib/youtube-dl/video.rb#L35-L40", "partition": "test"} {"repo": "layer8x/youtube-dl.rb", "path": "lib/youtube-dl/video.rb", "func_name": "YoutubeDL.Video.method_missing", "original_string": "def method_missing(method, *args, &block)\n value = information[method]\n\n if value.nil?\n super\n else\n value\n end\n end", "language": "ruby", "code": "def method_missing(method, *args, &block)\n value = information[method]\n\n if value.nil?\n super\n else\n value\n end\n end", "code_tokens": ["def", "method_missing", "(", "method", ",", "*", "args", ",", "&", "block", ")", "value", "=", "information", "[", "method", "]", "if", "value", ".", "nil?", "super", "else", "value", "end", "end"], "docstring": "Redirect methods for information getting\n\n @param method [Symbol] method name\n @param args [Array] method arguments\n @param block [Proc] explict block\n @return [Object] The value from @information", "docstring_tokens": ["Redirect", "methods", "for", "information", "getting"], "sha": "05cc66ae863ae4b946b29774b323a3e944cdf0ca", "url": "https://github.com/layer8x/youtube-dl.rb/blob/05cc66ae863ae4b946b29774b323a3e944cdf0ca/lib/youtube-dl/video.rb#L64-L72", "partition": "test"} {"repo": "layer8x/youtube-dl.rb", "path": "lib/youtube-dl/runner.rb", "func_name": "YoutubeDL.Runner.options_to_commands", "original_string": "def options_to_commands\n commands = []\n @options.sanitize_keys.each_paramized_key do |key, paramized_key|\n if @options[key].to_s == 'true'\n commands.push \"--#{paramized_key}\"\n elsif @options[key].to_s == 'false'\n commands.push \"--no-#{paramized_key}\"\n else\n commands.push \"--#{paramized_key} :#{key}\"\n end\n end\n commands.push quoted(url)\n commands.join(' ')\n end", "language": "ruby", "code": "def options_to_commands\n commands = []\n @options.sanitize_keys.each_paramized_key do |key, paramized_key|\n if @options[key].to_s == 'true'\n commands.push \"--#{paramized_key}\"\n elsif @options[key].to_s == 'false'\n commands.push \"--no-#{paramized_key}\"\n else\n commands.push \"--#{paramized_key} :#{key}\"\n end\n end\n commands.push quoted(url)\n commands.join(' ')\n end", "code_tokens": ["def", "options_to_commands", "commands", "=", "[", "]", "@options", ".", "sanitize_keys", ".", "each_paramized_key", "do", "|", "key", ",", "paramized_key", "|", "if", "@options", "[", "key", "]", ".", "to_s", "==", "'true'", "commands", ".", "push", "\"--#{paramized_key}\"", "elsif", "@options", "[", "key", "]", ".", "to_s", "==", "'false'", "commands", ".", "push", "\"--no-#{paramized_key}\"", "else", "commands", ".", "push", "\"--#{paramized_key} :#{key}\"", "end", "end", "commands", ".", "push", "quoted", "(", "url", ")", "commands", ".", "join", "(", "' '", ")", "end"], "docstring": "Parses options and converts them to Cocaine's syntax\n\n @return [String] commands ready to do cocaine", "docstring_tokens": ["Parses", "options", "and", "converts", "them", "to", "Cocaine", "s", "syntax"], "sha": "05cc66ae863ae4b946b29774b323a3e944cdf0ca", "url": "https://github.com/layer8x/youtube-dl.rb/blob/05cc66ae863ae4b946b29774b323a3e944cdf0ca/lib/youtube-dl/runner.rb#L81-L94", "partition": "test"} {"repo": "layer8x/youtube-dl.rb", "path": "lib/youtube-dl/options.rb", "func_name": "YoutubeDL.Options.with", "original_string": "def with(hash)\n merged = Options.new(@store.merge(hash.to_h))\n merged.banned_keys = @banned_keys\n merged.send(:remove_banned)\n merged\n end", "language": "ruby", "code": "def with(hash)\n merged = Options.new(@store.merge(hash.to_h))\n merged.banned_keys = @banned_keys\n merged.send(:remove_banned)\n merged\n end", "code_tokens": ["def", "with", "(", "hash", ")", "merged", "=", "Options", ".", "new", "(", "@store", ".", "merge", "(", "hash", ".", "to_h", ")", ")", "merged", ".", "banned_keys", "=", "@banned_keys", "merged", ".", "send", "(", ":remove_banned", ")", "merged", "end"], "docstring": "Merge options with given hash, removing banned keys, and returning a\n new instance of Options.\n\n @param hash [Hash] Hash to merge options with\n @return [YoutubeDL::Options] Merged Options instance", "docstring_tokens": ["Merge", "options", "with", "given", "hash", "removing", "banned", "keys", "and", "returning", "a", "new", "instance", "of", "Options", "."], "sha": "05cc66ae863ae4b946b29774b323a3e944cdf0ca", "url": "https://github.com/layer8x/youtube-dl.rb/blob/05cc66ae863ae4b946b29774b323a3e944cdf0ca/lib/youtube-dl/options.rb#L89-L94", "partition": "test"} {"repo": "layer8x/youtube-dl.rb", "path": "lib/youtube-dl/options.rb", "func_name": "YoutubeDL.Options.method_missing", "original_string": "def method_missing(method, *args, &_block)\n remove_banned\n if method.to_s.include? '='\n method = method.to_s.tr('=', '').to_sym\n return nil if banned? method\n @store[method] = args.first\n else\n return nil if banned? method\n @store[method]\n end\n end", "language": "ruby", "code": "def method_missing(method, *args, &_block)\n remove_banned\n if method.to_s.include? '='\n method = method.to_s.tr('=', '').to_sym\n return nil if banned? method\n @store[method] = args.first\n else\n return nil if banned? method\n @store[method]\n end\n end", "code_tokens": ["def", "method_missing", "(", "method", ",", "*", "args", ",", "&", "_block", ")", "remove_banned", "if", "method", ".", "to_s", ".", "include?", "'='", "method", "=", "method", ".", "to_s", ".", "tr", "(", "'='", ",", "''", ")", ".", "to_sym", "return", "nil", "if", "banned?", "method", "@store", "[", "method", "]", "=", "args", ".", "first", "else", "return", "nil", "if", "banned?", "method", "@store", "[", "method", "]", "end", "end"], "docstring": "Option getting and setting using ghost methods\n\n @param method [Symbol] method name\n @param args [Array] list of arguments passed\n @param block [Proc] implicit block given\n @return [Object] the value of method in the options store", "docstring_tokens": ["Option", "getting", "and", "setting", "using", "ghost", "methods"], "sha": "05cc66ae863ae4b946b29774b323a3e944cdf0ca", "url": "https://github.com/layer8x/youtube-dl.rb/blob/05cc66ae863ae4b946b29774b323a3e944cdf0ca/lib/youtube-dl/options.rb#L102-L112", "partition": "test"} {"repo": "layer8x/youtube-dl.rb", "path": "lib/youtube-dl/options.rb", "func_name": "YoutubeDL.Options.manipulate_keys!", "original_string": "def manipulate_keys!(&block)\n @store.keys.each do |old_name|\n new_name = block.call(old_name)\n unless new_name == old_name\n @store[new_name] = @store[old_name]\n @store.delete(old_name)\n end\n end\n end", "language": "ruby", "code": "def manipulate_keys!(&block)\n @store.keys.each do |old_name|\n new_name = block.call(old_name)\n unless new_name == old_name\n @store[new_name] = @store[old_name]\n @store.delete(old_name)\n end\n end\n end", "code_tokens": ["def", "manipulate_keys!", "(", "&", "block", ")", "@store", ".", "keys", ".", "each", "do", "|", "old_name", "|", "new_name", "=", "block", ".", "call", "(", "old_name", ")", "unless", "new_name", "==", "old_name", "@store", "[", "new_name", "]", "=", "@store", "[", "old_name", "]", "@store", ".", "delete", "(", "old_name", ")", "end", "end", "end"], "docstring": "Calls a block to do operations on keys\n See sanitize_keys! for examples\n\n @param block [Proc] Block with operations on keys\n @yieldparam key [Object] Original key\n @yieldreturn [Object] Manipulated key", "docstring_tokens": ["Calls", "a", "block", "to", "do", "operations", "on", "keys", "See", "sanitize_keys!", "for", "examples"], "sha": "05cc66ae863ae4b946b29774b323a3e944cdf0ca", "url": "https://github.com/layer8x/youtube-dl.rb/blob/05cc66ae863ae4b946b29774b323a3e944cdf0ca/lib/youtube-dl/options.rb#L120-L128", "partition": "test"} {"repo": "layer8x/youtube-dl.rb", "path": "lib/youtube-dl/options.rb", "func_name": "YoutubeDL.Options.sanitize_keys!", "original_string": "def sanitize_keys!\n # Symbolize\n manipulate_keys! { |key_name| key_name.is_a?(Symbol) ? key_name : key_name.to_sym }\n\n # Underscoreize (because Cocaine doesn't like hyphens)\n manipulate_keys! { |key_name| key_name.to_s.tr('-', '_').to_sym }\n end", "language": "ruby", "code": "def sanitize_keys!\n # Symbolize\n manipulate_keys! { |key_name| key_name.is_a?(Symbol) ? key_name : key_name.to_sym }\n\n # Underscoreize (because Cocaine doesn't like hyphens)\n manipulate_keys! { |key_name| key_name.to_s.tr('-', '_').to_sym }\n end", "code_tokens": ["def", "sanitize_keys!", "# Symbolize", "manipulate_keys!", "{", "|", "key_name", "|", "key_name", ".", "is_a?", "(", "Symbol", ")", "?", "key_name", ":", "key_name", ".", "to_sym", "}", "# Underscoreize (because Cocaine doesn't like hyphens)", "manipulate_keys!", "{", "|", "key_name", "|", "key_name", ".", "to_s", ".", "tr", "(", "'-'", ",", "'_'", ")", ".", "to_sym", "}", "end"], "docstring": "Symbolizes and sanitizes keys in the option store\n\n @return [Object] @store", "docstring_tokens": ["Symbolizes", "and", "sanitizes", "keys", "in", "the", "option", "store"], "sha": "05cc66ae863ae4b946b29774b323a3e944cdf0ca", "url": "https://github.com/layer8x/youtube-dl.rb/blob/05cc66ae863ae4b946b29774b323a3e944cdf0ca/lib/youtube-dl/options.rb#L133-L139", "partition": "test"} {"repo": "apotonick/roar-rails", "path": "lib/roar/rails/controller_additions.rb", "func_name": "Roar::Rails.ControllerAdditions.representer_for", "original_string": "def representer_for(format, model, options={})\n options.delete(:represent_with) || self.class.represents_options.for(format, model, controller_path)\n end", "language": "ruby", "code": "def representer_for(format, model, options={})\n options.delete(:represent_with) || self.class.represents_options.for(format, model, controller_path)\n end", "code_tokens": ["def", "representer_for", "(", "format", ",", "model", ",", "options", "=", "{", "}", ")", "options", ".", "delete", "(", ":represent_with", ")", "||", "self", ".", "class", ".", "represents_options", ".", "for", "(", "format", ",", "model", ",", "controller_path", ")", "end"], "docstring": "Central entry-point for finding the appropriate representer.", "docstring_tokens": ["Central", "entry", "-", "point", "for", "finding", "the", "appropriate", "representer", "."], "sha": "590a55545fc616254e45022c24d3fe2b65a56dcd", "url": "https://github.com/apotonick/roar-rails/blob/590a55545fc616254e45022c24d3fe2b65a56dcd/lib/roar/rails/controller_additions.rb#L46-L48", "partition": "test"} {"repo": "mgrigajtis/easyzpl", "path": "lib/easyzpl/label_template.rb", "func_name": "Easyzpl.LabelTemplate.variable_text_field", "original_string": "def variable_text_field(x, y, params = {})\n x = 0 unless numeric?(x)\n y = 0 unless numeric?(y)\n options = { height: 0.1, width: 0.1 }.merge!(params)\n\n # update the variable field count\n self.variable_fields_count += 1\n\n label_data.push('^FO' + Integer(x * printer_dpi).to_s + ',' +\n Integer(y * printer_dpi).to_s)\n\n if params[:orientation] == :landscape\n label_data.push('^A0N,')\n else\n label_data.push('^A0B,')\n end\n\n label_data.push(Integer(options[:height] * printer_dpi).to_s + ',' +\n Integer(options[:width] * printer_dpi).to_s +\n '^FN' + variable_fields_count.to_s + '^FS')\n\n # return unless label_height > 0 && label_width > 0\n # pdf.text_box '{Variable Field ' + variable_fields_count.to_s + '}',\n # at: [Integer(x * pdf_dpi), Integer(label_width * pdf_dpi) -\n # Integer(y * pdf_dpi) -\n # Integer(options[:height] / 10) * pdf_dpi],\n # size: Integer(options[:height] * pdf_dpi) if label_height &&\n # label_width\n end", "language": "ruby", "code": "def variable_text_field(x, y, params = {})\n x = 0 unless numeric?(x)\n y = 0 unless numeric?(y)\n options = { height: 0.1, width: 0.1 }.merge!(params)\n\n # update the variable field count\n self.variable_fields_count += 1\n\n label_data.push('^FO' + Integer(x * printer_dpi).to_s + ',' +\n Integer(y * printer_dpi).to_s)\n\n if params[:orientation] == :landscape\n label_data.push('^A0N,')\n else\n label_data.push('^A0B,')\n end\n\n label_data.push(Integer(options[:height] * printer_dpi).to_s + ',' +\n Integer(options[:width] * printer_dpi).to_s +\n '^FN' + variable_fields_count.to_s + '^FS')\n\n # return unless label_height > 0 && label_width > 0\n # pdf.text_box '{Variable Field ' + variable_fields_count.to_s + '}',\n # at: [Integer(x * pdf_dpi), Integer(label_width * pdf_dpi) -\n # Integer(y * pdf_dpi) -\n # Integer(options[:height] / 10) * pdf_dpi],\n # size: Integer(options[:height] * pdf_dpi) if label_height &&\n # label_width\n end", "code_tokens": ["def", "variable_text_field", "(", "x", ",", "y", ",", "params", "=", "{", "}", ")", "x", "=", "0", "unless", "numeric?", "(", "x", ")", "y", "=", "0", "unless", "numeric?", "(", "y", ")", "options", "=", "{", "height", ":", "0.1", ",", "width", ":", "0.1", "}", ".", "merge!", "(", "params", ")", "# update the variable field count", "self", ".", "variable_fields_count", "+=", "1", "label_data", ".", "push", "(", "'^FO'", "+", "Integer", "(", "x", "*", "printer_dpi", ")", ".", "to_s", "+", "','", "+", "Integer", "(", "y", "*", "printer_dpi", ")", ".", "to_s", ")", "if", "params", "[", ":orientation", "]", "==", ":landscape", "label_data", ".", "push", "(", "'^A0N,'", ")", "else", "label_data", ".", "push", "(", "'^A0B,'", ")", "end", "label_data", ".", "push", "(", "Integer", "(", "options", "[", ":height", "]", "*", "printer_dpi", ")", ".", "to_s", "+", "','", "+", "Integer", "(", "options", "[", ":width", "]", "*", "printer_dpi", ")", ".", "to_s", "+", "'^FN'", "+", "variable_fields_count", ".", "to_s", "+", "'^FS'", ")", "# return unless label_height > 0 && label_width > 0", "# pdf.text_box '{Variable Field ' + variable_fields_count.to_s + '}',", "# at: [Integer(x * pdf_dpi), Integer(label_width * pdf_dpi) -", "# Integer(y * pdf_dpi) -", "# Integer(options[:height] / 10) * pdf_dpi],", "# size: Integer(options[:height] * pdf_dpi) if label_height &&", "# label_width", "end"], "docstring": "Called when the new method is invoked\n Sets a variable field that can be recalled", "docstring_tokens": ["Called", "when", "the", "new", "method", "is", "invoked", "Sets", "a", "variable", "field", "that", "can", "be", "recalled"], "sha": "439dcb9fcf835652cb9d03ce529c009f2af92ac4", "url": "https://github.com/mgrigajtis/easyzpl/blob/439dcb9fcf835652cb9d03ce529c009f2af92ac4/lib/easyzpl/label_template.rb#L51-L79", "partition": "test"} {"repo": "mgrigajtis/easyzpl", "path": "lib/easyzpl/label.rb", "func_name": "Easyzpl.Label.home_position", "original_string": "def home_position(x, y)\n x = 0 unless numeric?(x)\n y = 0 unless numeric?(y)\n label_data.push('^LH' + x.to_s + ',' + y.to_s)\n end", "language": "ruby", "code": "def home_position(x, y)\n x = 0 unless numeric?(x)\n y = 0 unless numeric?(y)\n label_data.push('^LH' + x.to_s + ',' + y.to_s)\n end", "code_tokens": ["def", "home_position", "(", "x", ",", "y", ")", "x", "=", "0", "unless", "numeric?", "(", "x", ")", "y", "=", "0", "unless", "numeric?", "(", "y", ")", "label_data", ".", "push", "(", "'^LH'", "+", "x", ".", "to_s", "+", "','", "+", "y", ".", "to_s", ")", "end"], "docstring": "Set the home position of the label\n All other X and Y coordinates are\n relative to this", "docstring_tokens": ["Set", "the", "home", "position", "of", "the", "label", "All", "other", "X", "and", "Y", "coordinates", "are", "relative", "to", "this"], "sha": "439dcb9fcf835652cb9d03ce529c009f2af92ac4", "url": "https://github.com/mgrigajtis/easyzpl/blob/439dcb9fcf835652cb9d03ce529c009f2af92ac4/lib/easyzpl/label.rb#L70-L74", "partition": "test"} {"repo": "mgrigajtis/easyzpl", "path": "lib/easyzpl/label.rb", "func_name": "Easyzpl.Label.draw_border", "original_string": "def draw_border(x, y, height, width)\n return unless numeric?(height) && numeric?(width)\n x = 0 unless numeric?(x)\n y = 0 unless numeric?(y)\n\n label_data.push('^FO' + Integer(x * printer_dpi).to_s + ',' +\n Integer(y * printer_dpi).to_s + '^GB' +\n Integer(height * printer_dpi).to_s +\n ',' + Integer(width * printer_dpi).to_s + ',1^FS')\n\n # draw_rectangle(x * pdf_dpi, y * pdf_dpi, height * pdf_dpi, width * pdf_dpi)\n end", "language": "ruby", "code": "def draw_border(x, y, height, width)\n return unless numeric?(height) && numeric?(width)\n x = 0 unless numeric?(x)\n y = 0 unless numeric?(y)\n\n label_data.push('^FO' + Integer(x * printer_dpi).to_s + ',' +\n Integer(y * printer_dpi).to_s + '^GB' +\n Integer(height * printer_dpi).to_s +\n ',' + Integer(width * printer_dpi).to_s + ',1^FS')\n\n # draw_rectangle(x * pdf_dpi, y * pdf_dpi, height * pdf_dpi, width * pdf_dpi)\n end", "code_tokens": ["def", "draw_border", "(", "x", ",", "y", ",", "height", ",", "width", ")", "return", "unless", "numeric?", "(", "height", ")", "&&", "numeric?", "(", "width", ")", "x", "=", "0", "unless", "numeric?", "(", "x", ")", "y", "=", "0", "unless", "numeric?", "(", "y", ")", "label_data", ".", "push", "(", "'^FO'", "+", "Integer", "(", "x", "*", "printer_dpi", ")", ".", "to_s", "+", "','", "+", "Integer", "(", "y", "*", "printer_dpi", ")", ".", "to_s", "+", "'^GB'", "+", "Integer", "(", "height", "*", "printer_dpi", ")", ".", "to_s", "+", "','", "+", "Integer", "(", "width", "*", "printer_dpi", ")", ".", "to_s", "+", "',1^FS'", ")", "# draw_rectangle(x * pdf_dpi, y * pdf_dpi, height * pdf_dpi, width * pdf_dpi)", "end"], "docstring": "Draws a square border on dot in width", "docstring_tokens": ["Draws", "a", "square", "border", "on", "dot", "in", "width"], "sha": "439dcb9fcf835652cb9d03ce529c009f2af92ac4", "url": "https://github.com/mgrigajtis/easyzpl/blob/439dcb9fcf835652cb9d03ce529c009f2af92ac4/lib/easyzpl/label.rb#L77-L88", "partition": "test"} {"repo": "mgrigajtis/easyzpl", "path": "lib/easyzpl/label.rb", "func_name": "Easyzpl.Label.reset_barcode_fields_to_default", "original_string": "def reset_barcode_fields_to_default\n label_data.push('^BY' + Integer(self.barcode_default_module_width).to_s + ',' +\n Float(self.barcode_default_width_ratio).to_s + ',' +\n Integer(self.barcode_default_height).to_s)\n end", "language": "ruby", "code": "def reset_barcode_fields_to_default\n label_data.push('^BY' + Integer(self.barcode_default_module_width).to_s + ',' +\n Float(self.barcode_default_width_ratio).to_s + ',' +\n Integer(self.barcode_default_height).to_s)\n end", "code_tokens": ["def", "reset_barcode_fields_to_default", "label_data", ".", "push", "(", "'^BY'", "+", "Integer", "(", "self", ".", "barcode_default_module_width", ")", ".", "to_s", "+", "','", "+", "Float", "(", "self", ".", "barcode_default_width_ratio", ")", ".", "to_s", "+", "','", "+", "Integer", "(", "self", ".", "barcode_default_height", ")", ".", "to_s", ")", "end"], "docstring": "Some barcodes, such as QR codes may change document defaults. These may be reset\n to the document defaults.", "docstring_tokens": ["Some", "barcodes", "such", "as", "QR", "codes", "may", "change", "document", "defaults", ".", "These", "may", "be", "reset", "to", "the", "document", "defaults", "."], "sha": "439dcb9fcf835652cb9d03ce529c009f2af92ac4", "url": "https://github.com/mgrigajtis/easyzpl/blob/439dcb9fcf835652cb9d03ce529c009f2af92ac4/lib/easyzpl/label.rb#L205-L209", "partition": "test"} {"repo": "mgrigajtis/easyzpl", "path": "lib/easyzpl/label.rb", "func_name": "Easyzpl.Label.draw_bar_code_39", "original_string": "def draw_bar_code_39(bar_code_string, x, y, height)\n return unless label_height > 0 && label_width > 0\n pdf.bounding_box [x, Integer(label_width) - y - (height * pdf_dpi)],\n width: (height * pdf_dpi) do\n barcode = Barby::Code39.new(bar_code_string)\n barcode.annotate_pdf(pdf, height: (height * pdf_dpi))\n end\n end", "language": "ruby", "code": "def draw_bar_code_39(bar_code_string, x, y, height)\n return unless label_height > 0 && label_width > 0\n pdf.bounding_box [x, Integer(label_width) - y - (height * pdf_dpi)],\n width: (height * pdf_dpi) do\n barcode = Barby::Code39.new(bar_code_string)\n barcode.annotate_pdf(pdf, height: (height * pdf_dpi))\n end\n end", "code_tokens": ["def", "draw_bar_code_39", "(", "bar_code_string", ",", "x", ",", "y", ",", "height", ")", "return", "unless", "label_height", ">", "0", "&&", "label_width", ">", "0", "pdf", ".", "bounding_box", "[", "x", ",", "Integer", "(", "label_width", ")", "-", "y", "-", "(", "height", "*", "pdf_dpi", ")", "]", ",", "width", ":", "(", "height", "*", "pdf_dpi", ")", "do", "barcode", "=", "Barby", "::", "Code39", ".", "new", "(", "bar_code_string", ")", "barcode", ".", "annotate_pdf", "(", "pdf", ",", "height", ":", "(", "height", "*", "pdf_dpi", ")", ")", "end", "end"], "docstring": "Draws the PDF bar code 39", "docstring_tokens": ["Draws", "the", "PDF", "bar", "code", "39"], "sha": "439dcb9fcf835652cb9d03ce529c009f2af92ac4", "url": "https://github.com/mgrigajtis/easyzpl/blob/439dcb9fcf835652cb9d03ce529c009f2af92ac4/lib/easyzpl/label.rb#L263-L270", "partition": "test"} {"repo": "mgrigajtis/easyzpl", "path": "lib/easyzpl/stored_label.rb", "func_name": "Easyzpl.StoredLabel.add_field", "original_string": "def add_field(value)\n return if value.nil?\n return if value.strip.empty?\n\n # Increment the variable field count\n self.variable_fields_count += 1\n\n # Add the field\n label_data.push('^FN' + variable_fields_count.to_s +\n '^FD' + value + '^FS')\n end", "language": "ruby", "code": "def add_field(value)\n return if value.nil?\n return if value.strip.empty?\n\n # Increment the variable field count\n self.variable_fields_count += 1\n\n # Add the field\n label_data.push('^FN' + variable_fields_count.to_s +\n '^FD' + value + '^FS')\n end", "code_tokens": ["def", "add_field", "(", "value", ")", "return", "if", "value", ".", "nil?", "return", "if", "value", ".", "strip", ".", "empty?", "# Increment the variable field count", "self", ".", "variable_fields_count", "+=", "1", "# Add the field", "label_data", ".", "push", "(", "'^FN'", "+", "variable_fields_count", ".", "to_s", "+", "'^FD'", "+", "value", "+", "'^FS'", ")", "end"], "docstring": "Called when the new method is invoked\n Adds a variable that is to be applied to the saved template", "docstring_tokens": ["Called", "when", "the", "new", "method", "is", "invoked", "Adds", "a", "variable", "that", "is", "to", "be", "applied", "to", "the", "saved", "template"], "sha": "439dcb9fcf835652cb9d03ce529c009f2af92ac4", "url": "https://github.com/mgrigajtis/easyzpl/blob/439dcb9fcf835652cb9d03ce529c009f2af92ac4/lib/easyzpl/stored_label.rb#L28-L38", "partition": "test"} {"repo": "mongoid/mongoid-slug", "path": "lib/mongoid/slug.rb", "func_name": "Mongoid.Slug.build_slug", "original_string": "def build_slug\n if localized?\n begin\n orig_locale = I18n.locale\n all_locales.each do |target_locale|\n I18n.locale = target_locale\n apply_slug\n end\n ensure\n I18n.locale = orig_locale\n end\n else\n apply_slug\n end\n true\n end", "language": "ruby", "code": "def build_slug\n if localized?\n begin\n orig_locale = I18n.locale\n all_locales.each do |target_locale|\n I18n.locale = target_locale\n apply_slug\n end\n ensure\n I18n.locale = orig_locale\n end\n else\n apply_slug\n end\n true\n end", "code_tokens": ["def", "build_slug", "if", "localized?", "begin", "orig_locale", "=", "I18n", ".", "locale", "all_locales", ".", "each", "do", "|", "target_locale", "|", "I18n", ".", "locale", "=", "target_locale", "apply_slug", "end", "ensure", "I18n", ".", "locale", "=", "orig_locale", "end", "else", "apply_slug", "end", "true", "end"], "docstring": "Builds a new slug.\n\n @return [true]", "docstring_tokens": ["Builds", "a", "new", "slug", "."], "sha": "f732b7aad79c82dacc6c41629a1001a30d042da8", "url": "https://github.com/mongoid/mongoid-slug/blob/f732b7aad79c82dacc6c41629a1001a30d042da8/lib/mongoid/slug.rb#L162-L177", "partition": "test"} {"repo": "mongoid/mongoid-slug", "path": "lib/mongoid/slug.rb", "func_name": "Mongoid.Slug.new_with_slugs?", "original_string": "def new_with_slugs?\n if localized?\n # We need to check if slugs are present for the locale without falling back\n # to a default\n new_record? && _slugs_translations.fetch(I18n.locale.to_s, []).any?\n else\n new_record? && _slugs.present?\n end\n end", "language": "ruby", "code": "def new_with_slugs?\n if localized?\n # We need to check if slugs are present for the locale without falling back\n # to a default\n new_record? && _slugs_translations.fetch(I18n.locale.to_s, []).any?\n else\n new_record? && _slugs.present?\n end\n end", "code_tokens": ["def", "new_with_slugs?", "if", "localized?", "# We need to check if slugs are present for the locale without falling back", "# to a default", "new_record?", "&&", "_slugs_translations", ".", "fetch", "(", "I18n", ".", "locale", ".", "to_s", ",", "[", "]", ")", ".", "any?", "else", "new_record?", "&&", "_slugs", ".", "present?", "end", "end"], "docstring": "Returns true if object is a new record and slugs are present", "docstring_tokens": ["Returns", "true", "if", "object", "is", "a", "new", "record", "and", "slugs", "are", "present"], "sha": "f732b7aad79c82dacc6c41629a1001a30d042da8", "url": "https://github.com/mongoid/mongoid-slug/blob/f732b7aad79c82dacc6c41629a1001a30d042da8/lib/mongoid/slug.rb#L281-L289", "partition": "test"} {"repo": "mongoid/mongoid-slug", "path": "lib/mongoid/slug.rb", "func_name": "Mongoid.Slug.persisted_with_slug_changes?", "original_string": "def persisted_with_slug_changes?\n if localized?\n changes = _slugs_change\n return (persisted? && false) if changes.nil?\n\n # ensure we check for changes only between the same locale\n original = changes.first.try(:fetch, I18n.locale.to_s, nil)\n compare = changes.last.try(:fetch, I18n.locale.to_s, nil)\n persisted? && original != compare\n else\n persisted? && _slugs_changed?\n end\n end", "language": "ruby", "code": "def persisted_with_slug_changes?\n if localized?\n changes = _slugs_change\n return (persisted? && false) if changes.nil?\n\n # ensure we check for changes only between the same locale\n original = changes.first.try(:fetch, I18n.locale.to_s, nil)\n compare = changes.last.try(:fetch, I18n.locale.to_s, nil)\n persisted? && original != compare\n else\n persisted? && _slugs_changed?\n end\n end", "code_tokens": ["def", "persisted_with_slug_changes?", "if", "localized?", "changes", "=", "_slugs_change", "return", "(", "persisted?", "&&", "false", ")", "if", "changes", ".", "nil?", "# ensure we check for changes only between the same locale", "original", "=", "changes", ".", "first", ".", "try", "(", ":fetch", ",", "I18n", ".", "locale", ".", "to_s", ",", "nil", ")", "compare", "=", "changes", ".", "last", ".", "try", "(", ":fetch", ",", "I18n", ".", "locale", ".", "to_s", ",", "nil", ")", "persisted?", "&&", "original", "!=", "compare", "else", "persisted?", "&&", "_slugs_changed?", "end", "end"], "docstring": "Returns true if object has been persisted and has changes in the slug", "docstring_tokens": ["Returns", "true", "if", "object", "has", "been", "persisted", "and", "has", "changes", "in", "the", "slug"], "sha": "f732b7aad79c82dacc6c41629a1001a30d042da8", "url": "https://github.com/mongoid/mongoid-slug/blob/f732b7aad79c82dacc6c41629a1001a30d042da8/lib/mongoid/slug.rb#L292-L304", "partition": "test"} {"repo": "activewarehouse/activewarehouse-etl", "path": "lib/etl/util.rb", "func_name": "ETL.Util.distance_of_time_in_words", "original_string": "def distance_of_time_in_words(from_time, to_time=Time.now)\n from_time = from_time.to_time if from_time.respond_to?(:to_time)\n to_time = to_time.to_time if to_time.respond_to?(:to_time)\n seconds = (to_time - from_time).round\n distance_in_days = (seconds/(60*60*24)).round\n seconds = seconds % (60*60*24)\n distance_in_hours = (seconds/(60*60)).round\n seconds = seconds % (60*60)\n distance_in_minutes = (seconds/60).round\n seconds = seconds % 60\n distance_in_seconds = seconds\n \n s = ''\n s << \"#{distance_in_days} days,\" if distance_in_days > 0\n s << \"#{distance_in_hours} hours, \" if distance_in_hours > 0\n s << \"#{distance_in_minutes} minutes, \" if distance_in_minutes > 0\n s << \"#{distance_in_seconds} seconds\"\n s\n end", "language": "ruby", "code": "def distance_of_time_in_words(from_time, to_time=Time.now)\n from_time = from_time.to_time if from_time.respond_to?(:to_time)\n to_time = to_time.to_time if to_time.respond_to?(:to_time)\n seconds = (to_time - from_time).round\n distance_in_days = (seconds/(60*60*24)).round\n seconds = seconds % (60*60*24)\n distance_in_hours = (seconds/(60*60)).round\n seconds = seconds % (60*60)\n distance_in_minutes = (seconds/60).round\n seconds = seconds % 60\n distance_in_seconds = seconds\n \n s = ''\n s << \"#{distance_in_days} days,\" if distance_in_days > 0\n s << \"#{distance_in_hours} hours, \" if distance_in_hours > 0\n s << \"#{distance_in_minutes} minutes, \" if distance_in_minutes > 0\n s << \"#{distance_in_seconds} seconds\"\n s\n end", "code_tokens": ["def", "distance_of_time_in_words", "(", "from_time", ",", "to_time", "=", "Time", ".", "now", ")", "from_time", "=", "from_time", ".", "to_time", "if", "from_time", ".", "respond_to?", "(", ":to_time", ")", "to_time", "=", "to_time", ".", "to_time", "if", "to_time", ".", "respond_to?", "(", ":to_time", ")", "seconds", "=", "(", "to_time", "-", "from_time", ")", ".", "round", "distance_in_days", "=", "(", "seconds", "/", "(", "60", "*", "60", "*", "24", ")", ")", ".", "round", "seconds", "=", "seconds", "%", "(", "60", "*", "60", "*", "24", ")", "distance_in_hours", "=", "(", "seconds", "/", "(", "60", "*", "60", ")", ")", ".", "round", "seconds", "=", "seconds", "%", "(", "60", "*", "60", ")", "distance_in_minutes", "=", "(", "seconds", "/", "60", ")", ".", "round", "seconds", "=", "seconds", "%", "60", "distance_in_seconds", "=", "seconds", "s", "=", "''", "s", "<<", "\"#{distance_in_days} days,\"", "if", "distance_in_days", ">", "0", "s", "<<", "\"#{distance_in_hours} hours, \"", "if", "distance_in_hours", ">", "0", "s", "<<", "\"#{distance_in_minutes} minutes, \"", "if", "distance_in_minutes", ">", "0", "s", "<<", "\"#{distance_in_seconds} seconds\"", "s", "end"], "docstring": "Return the distance of time in words from the given from_time to the specified to_time. If to_time\n is not specified then Time.now is used. By default seconds are included...set the include_seconds\n argument to false to disable the seconds.", "docstring_tokens": ["Return", "the", "distance", "of", "time", "in", "words", "from", "the", "given", "from_time", "to", "the", "specified", "to_time", ".", "If", "to_time", "is", "not", "specified", "then", "Time", ".", "now", "is", "used", ".", "By", "default", "seconds", "are", "included", "...", "set", "the", "include_seconds", "argument", "to", "false", "to", "disable", "the", "seconds", "."], "sha": "0b0b50e140ed02081b3ed1de902f78308ed738a5", "url": "https://github.com/activewarehouse/activewarehouse-etl/blob/0b0b50e140ed02081b3ed1de902f78308ed738a5/lib/etl/util.rb#L6-L24", "partition": "test"} {"repo": "activewarehouse/activewarehouse-etl", "path": "lib/etl/util.rb", "func_name": "ETL.Util.approximate_distance_of_time_in_words", "original_string": "def approximate_distance_of_time_in_words(from_time, to_time=Time.now, include_seconds=true)\n from_time = from_time.to_time if from_time.respond_to?(:to_time)\n to_time = to_time.to_time if to_time.respond_to?(:to_time)\n distance_in_minutes = (((to_time - from_time).abs)/60).round\n distance_in_seconds = ((to_time - from_time).abs).round\n \n case distance_in_minutes\n when 0..1\n return (distance_in_minutes == 0) ? 'less than a minute' : '1 minute' unless include_seconds\n case distance_in_seconds\n when 0..4 then 'less than 5 seconds'\n when 5..9 then 'less than 10 seconds'\n when 10..19 then 'less than 20 seconds'\n when 20..39 then 'half a minute'\n when 40..59 then 'less than a minute'\n else '1 minute'\n end\n when 2..44 then \"#{distance_in_minutes} minutes\"\n when 45..89 then 'about 1 hour'\n when 90..1439 then \"about #{(distance_in_minutes.to_f / 60.0).round} hours\"\n when 1440..2879 then '1 day'\n when 2880..43199 then \"#{(distance_in_minutes / 1440).round} days\"\n when 43200..86399 then 'about 1 month'\n when 86400..525959 then \"#{(distance_in_minutes / 43200).round} months\"\n when 525960..1051919 then 'about 1 year'\n else \"over #{(distance_in_minutes / 525960).round} years\"\n end\n end", "language": "ruby", "code": "def approximate_distance_of_time_in_words(from_time, to_time=Time.now, include_seconds=true)\n from_time = from_time.to_time if from_time.respond_to?(:to_time)\n to_time = to_time.to_time if to_time.respond_to?(:to_time)\n distance_in_minutes = (((to_time - from_time).abs)/60).round\n distance_in_seconds = ((to_time - from_time).abs).round\n \n case distance_in_minutes\n when 0..1\n return (distance_in_minutes == 0) ? 'less than a minute' : '1 minute' unless include_seconds\n case distance_in_seconds\n when 0..4 then 'less than 5 seconds'\n when 5..9 then 'less than 10 seconds'\n when 10..19 then 'less than 20 seconds'\n when 20..39 then 'half a minute'\n when 40..59 then 'less than a minute'\n else '1 minute'\n end\n when 2..44 then \"#{distance_in_minutes} minutes\"\n when 45..89 then 'about 1 hour'\n when 90..1439 then \"about #{(distance_in_minutes.to_f / 60.0).round} hours\"\n when 1440..2879 then '1 day'\n when 2880..43199 then \"#{(distance_in_minutes / 1440).round} days\"\n when 43200..86399 then 'about 1 month'\n when 86400..525959 then \"#{(distance_in_minutes / 43200).round} months\"\n when 525960..1051919 then 'about 1 year'\n else \"over #{(distance_in_minutes / 525960).round} years\"\n end\n end", "code_tokens": ["def", "approximate_distance_of_time_in_words", "(", "from_time", ",", "to_time", "=", "Time", ".", "now", ",", "include_seconds", "=", "true", ")", "from_time", "=", "from_time", ".", "to_time", "if", "from_time", ".", "respond_to?", "(", ":to_time", ")", "to_time", "=", "to_time", ".", "to_time", "if", "to_time", ".", "respond_to?", "(", ":to_time", ")", "distance_in_minutes", "=", "(", "(", "(", "to_time", "-", "from_time", ")", ".", "abs", ")", "/", "60", ")", ".", "round", "distance_in_seconds", "=", "(", "(", "to_time", "-", "from_time", ")", ".", "abs", ")", ".", "round", "case", "distance_in_minutes", "when", "0", "..", "1", "return", "(", "distance_in_minutes", "==", "0", ")", "?", "'less than a minute'", ":", "'1 minute'", "unless", "include_seconds", "case", "distance_in_seconds", "when", "0", "..", "4", "then", "'less than 5 seconds'", "when", "5", "..", "9", "then", "'less than 10 seconds'", "when", "10", "..", "19", "then", "'less than 20 seconds'", "when", "20", "..", "39", "then", "'half a minute'", "when", "40", "..", "59", "then", "'less than a minute'", "else", "'1 minute'", "end", "when", "2", "..", "44", "then", "\"#{distance_in_minutes} minutes\"", "when", "45", "..", "89", "then", "'about 1 hour'", "when", "90", "..", "1439", "then", "\"about #{(distance_in_minutes.to_f / 60.0).round} hours\"", "when", "1440", "..", "2879", "then", "'1 day'", "when", "2880", "..", "43199", "then", "\"#{(distance_in_minutes / 1440).round} days\"", "when", "43200", "..", "86399", "then", "'about 1 month'", "when", "86400", "..", "525959", "then", "\"#{(distance_in_minutes / 43200).round} months\"", "when", "525960", "..", "1051919", "then", "'about 1 year'", "else", "\"over #{(distance_in_minutes / 525960).round} years\"", "end", "end"], "docstring": "Get the approximate disntance of time in words from the given from_time\n to the the given to_time. If to_time is not specified then it is set\n to Time.now. By default seconds are included...set the include_seconds\n argument to false to disable the seconds.", "docstring_tokens": ["Get", "the", "approximate", "disntance", "of", "time", "in", "words", "from", "the", "given", "from_time", "to", "the", "the", "given", "to_time", ".", "If", "to_time", "is", "not", "specified", "then", "it", "is", "set", "to", "Time", ".", "now", ".", "By", "default", "seconds", "are", "included", "...", "set", "the", "include_seconds", "argument", "to", "false", "to", "disable", "the", "seconds", "."], "sha": "0b0b50e140ed02081b3ed1de902f78308ed738a5", "url": "https://github.com/activewarehouse/activewarehouse-etl/blob/0b0b50e140ed02081b3ed1de902f78308ed738a5/lib/etl/util.rb#L30-L57", "partition": "test"} {"repo": "activewarehouse/activewarehouse-etl", "path": "lib/etl/engine.rb", "func_name": "ETL.Engine.track_error", "original_string": "def track_error(control, msg)\n errors << msg\n control.error_handlers.each do |handler|\n handler.call(msg)\n end\n end", "language": "ruby", "code": "def track_error(control, msg)\n errors << msg\n control.error_handlers.each do |handler|\n handler.call(msg)\n end\n end", "code_tokens": ["def", "track_error", "(", "control", ",", "msg", ")", "errors", "<<", "msg", "control", ".", "error_handlers", ".", "each", "do", "|", "handler", "|", "handler", ".", "call", "(", "msg", ")", "end", "end"], "docstring": "First attempt at centralizing error notifications", "docstring_tokens": ["First", "attempt", "at", "centralizing", "error", "notifications"], "sha": "0b0b50e140ed02081b3ed1de902f78308ed738a5", "url": "https://github.com/activewarehouse/activewarehouse-etl/blob/0b0b50e140ed02081b3ed1de902f78308ed738a5/lib/etl/engine.rb#L240-L245", "partition": "test"} {"repo": "activewarehouse/activewarehouse-etl", "path": "lib/etl/engine.rb", "func_name": "ETL.Engine.process_batch", "original_string": "def process_batch(batch)\n batch = ETL::Batch::Batch.resolve(batch, self)\n say \"Processing batch #{batch.file}\"\n \n ETL::Engine.batch = ETL::Execution::Batch.create!(\n :batch_file => batch.file,\n :status => 'executing'\n )\n \n batch.execute\n \n ETL::Engine.batch.completed_at = Time.now\n ETL::Engine.batch.status = (errors.length > 0 ? 'completed with errors' : 'completed')\n ETL::Engine.batch.save!\n end", "language": "ruby", "code": "def process_batch(batch)\n batch = ETL::Batch::Batch.resolve(batch, self)\n say \"Processing batch #{batch.file}\"\n \n ETL::Engine.batch = ETL::Execution::Batch.create!(\n :batch_file => batch.file,\n :status => 'executing'\n )\n \n batch.execute\n \n ETL::Engine.batch.completed_at = Time.now\n ETL::Engine.batch.status = (errors.length > 0 ? 'completed with errors' : 'completed')\n ETL::Engine.batch.save!\n end", "code_tokens": ["def", "process_batch", "(", "batch", ")", "batch", "=", "ETL", "::", "Batch", "::", "Batch", ".", "resolve", "(", "batch", ",", "self", ")", "say", "\"Processing batch #{batch.file}\"", "ETL", "::", "Engine", ".", "batch", "=", "ETL", "::", "Execution", "::", "Batch", ".", "create!", "(", ":batch_file", "=>", "batch", ".", "file", ",", ":status", "=>", "'executing'", ")", "batch", ".", "execute", "ETL", "::", "Engine", ".", "batch", ".", "completed_at", "=", "Time", ".", "now", "ETL", "::", "Engine", ".", "batch", ".", "status", "=", "(", "errors", ".", "length", ">", "0", "?", "'completed with errors'", ":", "'completed'", ")", "ETL", "::", "Engine", ".", "batch", ".", "save!", "end"], "docstring": "Process the specified batch file", "docstring_tokens": ["Process", "the", "specified", "batch", "file"], "sha": "0b0b50e140ed02081b3ed1de902f78308ed738a5", "url": "https://github.com/activewarehouse/activewarehouse-etl/blob/0b0b50e140ed02081b3ed1de902f78308ed738a5/lib/etl/engine.rb#L291-L305", "partition": "test"} {"repo": "activewarehouse/activewarehouse-etl", "path": "lib/etl/engine.rb", "func_name": "ETL.Engine.pre_process", "original_string": "def pre_process(control)\n Engine.logger.debug \"Pre-processing #{control.file}\"\n control.pre_processors.each do |processor|\n processor.process\n end\n Engine.logger.debug \"Pre-processing complete\"\n end", "language": "ruby", "code": "def pre_process(control)\n Engine.logger.debug \"Pre-processing #{control.file}\"\n control.pre_processors.each do |processor|\n processor.process\n end\n Engine.logger.debug \"Pre-processing complete\"\n end", "code_tokens": ["def", "pre_process", "(", "control", ")", "Engine", ".", "logger", ".", "debug", "\"Pre-processing #{control.file}\"", "control", ".", "pre_processors", ".", "each", "do", "|", "processor", "|", "processor", ".", "process", "end", "Engine", ".", "logger", ".", "debug", "\"Pre-processing complete\"", "end"], "docstring": "Execute all preprocessors", "docstring_tokens": ["Execute", "all", "preprocessors"], "sha": "0b0b50e140ed02081b3ed1de902f78308ed738a5", "url": "https://github.com/activewarehouse/activewarehouse-etl/blob/0b0b50e140ed02081b3ed1de902f78308ed738a5/lib/etl/engine.rb#L523-L529", "partition": "test"} {"repo": "activewarehouse/activewarehouse-etl", "path": "lib/etl/engine.rb", "func_name": "ETL.Engine.post_process", "original_string": "def post_process(control)\n say_on_own_line \"Executing post processes\"\n Engine.logger.debug \"Post-processing #{control.file}\"\n control.post_processors.each do |processor|\n processor.process\n end\n Engine.logger.debug \"Post-processing complete\"\n say \"Post-processing complete\"\n end", "language": "ruby", "code": "def post_process(control)\n say_on_own_line \"Executing post processes\"\n Engine.logger.debug \"Post-processing #{control.file}\"\n control.post_processors.each do |processor|\n processor.process\n end\n Engine.logger.debug \"Post-processing complete\"\n say \"Post-processing complete\"\n end", "code_tokens": ["def", "post_process", "(", "control", ")", "say_on_own_line", "\"Executing post processes\"", "Engine", ".", "logger", ".", "debug", "\"Post-processing #{control.file}\"", "control", ".", "post_processors", ".", "each", "do", "|", "processor", "|", "processor", ".", "process", "end", "Engine", ".", "logger", ".", "debug", "\"Post-processing complete\"", "say", "\"Post-processing complete\"", "end"], "docstring": "Execute all postprocessors", "docstring_tokens": ["Execute", "all", "postprocessors"], "sha": "0b0b50e140ed02081b3ed1de902f78308ed738a5", "url": "https://github.com/activewarehouse/activewarehouse-etl/blob/0b0b50e140ed02081b3ed1de902f78308ed738a5/lib/etl/engine.rb#L532-L540", "partition": "test"} {"repo": "activewarehouse/activewarehouse-etl", "path": "lib/etl/engine.rb", "func_name": "ETL.Engine.execute_dependencies", "original_string": "def execute_dependencies(control)\n Engine.logger.debug \"Executing dependencies\"\n control.dependencies.flatten.each do |dependency|\n case dependency\n when Symbol\n f = dependency.to_s + '.ctl'\n Engine.logger.debug \"Executing dependency: #{f}\"\n say \"Executing dependency: #{f}\"\n process(f)\n when String\n Engine.logger.debug \"Executing dependency: #{f}\"\n say \"Executing dependency: #{f}\"\n process(dependency)\n else\n raise \"Invalid dependency type: #{dependency.class}\"\n end\n end\n end", "language": "ruby", "code": "def execute_dependencies(control)\n Engine.logger.debug \"Executing dependencies\"\n control.dependencies.flatten.each do |dependency|\n case dependency\n when Symbol\n f = dependency.to_s + '.ctl'\n Engine.logger.debug \"Executing dependency: #{f}\"\n say \"Executing dependency: #{f}\"\n process(f)\n when String\n Engine.logger.debug \"Executing dependency: #{f}\"\n say \"Executing dependency: #{f}\"\n process(dependency)\n else\n raise \"Invalid dependency type: #{dependency.class}\"\n end\n end\n end", "code_tokens": ["def", "execute_dependencies", "(", "control", ")", "Engine", ".", "logger", ".", "debug", "\"Executing dependencies\"", "control", ".", "dependencies", ".", "flatten", ".", "each", "do", "|", "dependency", "|", "case", "dependency", "when", "Symbol", "f", "=", "dependency", ".", "to_s", "+", "'.ctl'", "Engine", ".", "logger", ".", "debug", "\"Executing dependency: #{f}\"", "say", "\"Executing dependency: #{f}\"", "process", "(", "f", ")", "when", "String", "Engine", ".", "logger", ".", "debug", "\"Executing dependency: #{f}\"", "say", "\"Executing dependency: #{f}\"", "process", "(", "dependency", ")", "else", "raise", "\"Invalid dependency type: #{dependency.class}\"", "end", "end", "end"], "docstring": "Execute all dependencies", "docstring_tokens": ["Execute", "all", "dependencies"], "sha": "0b0b50e140ed02081b3ed1de902f78308ed738a5", "url": "https://github.com/activewarehouse/activewarehouse-etl/blob/0b0b50e140ed02081b3ed1de902f78308ed738a5/lib/etl/engine.rb#L543-L560", "partition": "test"} {"repo": "activewarehouse/activewarehouse-etl", "path": "lib/etl/engine.rb", "func_name": "ETL.Engine.execute_screens", "original_string": "def execute_screens(control, timing = :before_post_process)\n screens = case timing\n when :after_post_process\n control.after_post_process_screens\n else # default to before post-process screens\n control.screens\n end\n [:fatal,:error,:warn].each do |type|\n screens[type].each do |block|\n begin\n block.call\n rescue => e\n case type\n when :fatal\n raise FatalScreenError, e\n when :error\n raise ScreenError, e\n when :warn\n say \"Screen warning: #{e}\"\n end\n end\n end\n end\n end", "language": "ruby", "code": "def execute_screens(control, timing = :before_post_process)\n screens = case timing\n when :after_post_process\n control.after_post_process_screens\n else # default to before post-process screens\n control.screens\n end\n [:fatal,:error,:warn].each do |type|\n screens[type].each do |block|\n begin\n block.call\n rescue => e\n case type\n when :fatal\n raise FatalScreenError, e\n when :error\n raise ScreenError, e\n when :warn\n say \"Screen warning: #{e}\"\n end\n end\n end\n end\n end", "code_tokens": ["def", "execute_screens", "(", "control", ",", "timing", "=", ":before_post_process", ")", "screens", "=", "case", "timing", "when", ":after_post_process", "control", ".", "after_post_process_screens", "else", "# default to before post-process screens", "control", ".", "screens", "end", "[", ":fatal", ",", ":error", ",", ":warn", "]", ".", "each", "do", "|", "type", "|", "screens", "[", "type", "]", ".", "each", "do", "|", "block", "|", "begin", "block", ".", "call", "rescue", "=>", "e", "case", "type", "when", ":fatal", "raise", "FatalScreenError", ",", "e", "when", ":error", "raise", "ScreenError", ",", "e", "when", ":warn", "say", "\"Screen warning: #{e}\"", "end", "end", "end", "end", "end"], "docstring": "Execute all screens", "docstring_tokens": ["Execute", "all", "screens"], "sha": "0b0b50e140ed02081b3ed1de902f78308ed738a5", "url": "https://github.com/activewarehouse/activewarehouse-etl/blob/0b0b50e140ed02081b3ed1de902f78308ed738a5/lib/etl/engine.rb#L563-L586", "partition": "test"} {"repo": "ondrejbartas/redis-model-extension", "path": "lib/redis-model-extension/initialize.rb", "func_name": "RedisModelExtension.ClassInitialize.redis_key", "original_string": "def redis_key *fields\n @redis_key_config = fields.flatten\n \n validate_redis_key\n \n #own specification of redis key - delete autoincrement\n remove_redis_autoincrement_key unless redis_user_field_config.include?(:id) || @redis_key_config.include?(:id)\n\n # automaticaly add all fields from key to validation\n # if any of fields in redis key is nil\n # then prevent to save it\n @redis_key_config.each do |field|\n validates field, :presence => :true if field != :id\n end\n end", "language": "ruby", "code": "def redis_key *fields\n @redis_key_config = fields.flatten\n \n validate_redis_key\n \n #own specification of redis key - delete autoincrement\n remove_redis_autoincrement_key unless redis_user_field_config.include?(:id) || @redis_key_config.include?(:id)\n\n # automaticaly add all fields from key to validation\n # if any of fields in redis key is nil\n # then prevent to save it\n @redis_key_config.each do |field|\n validates field, :presence => :true if field != :id\n end\n end", "code_tokens": ["def", "redis_key", "*", "fields", "@redis_key_config", "=", "fields", ".", "flatten", "validate_redis_key", "#own specification of redis key - delete autoincrement", "remove_redis_autoincrement_key", "unless", "redis_user_field_config", ".", "include?", "(", ":id", ")", "||", "@redis_key_config", ".", "include?", "(", ":id", ")", "# automaticaly add all fields from key to validation", "# if any of fields in redis key is nil", "# then prevent to save it", "@redis_key_config", ".", "each", "do", "|", "field", "|", "validates", "field", ",", ":presence", "=>", ":true", "if", "field", "!=", ":id", "end", "end"], "docstring": "set redis key which will be used for storing model", "docstring_tokens": ["set", "redis", "key", "which", "will", "be", "used", "for", "storing", "model"], "sha": "c52385a063a4126a7c82159317f16f638cef6532", "url": "https://github.com/ondrejbartas/redis-model-extension/blob/c52385a063a4126a7c82159317f16f638cef6532/lib/redis-model-extension/initialize.rb#L66-L80", "partition": "test"} {"repo": "ondrejbartas/redis-model-extension", "path": "lib/redis-model-extension/initialize.rb", "func_name": "RedisModelExtension.ClassInitialize.redis_key_normalize", "original_string": "def redis_key_normalize *metrics\n @redis_key_normalize_conf ||= []\n metrics.each do |metric|\n raise ArgumentError, \"Please provide valid normalization: #{VALID_NORMALIZATIONS.join(\", \")}\" unless VALID_NORMALIZATIONS.include?(metric)\n @redis_key_normalize_conf << metric\n end\n end", "language": "ruby", "code": "def redis_key_normalize *metrics\n @redis_key_normalize_conf ||= []\n metrics.each do |metric|\n raise ArgumentError, \"Please provide valid normalization: #{VALID_NORMALIZATIONS.join(\", \")}\" unless VALID_NORMALIZATIONS.include?(metric)\n @redis_key_normalize_conf << metric\n end\n end", "code_tokens": ["def", "redis_key_normalize", "*", "metrics", "@redis_key_normalize_conf", "||=", "[", "]", "metrics", ".", "each", "do", "|", "metric", "|", "raise", "ArgumentError", ",", "\"Please provide valid normalization: #{VALID_NORMALIZATIONS.join(\", \")}\"", "unless", "VALID_NORMALIZATIONS", ".", "include?", "(", "metric", ")", "@redis_key_normalize_conf", "<<", "metric", "end", "end"], "docstring": "set redis model to normalize redis keys", "docstring_tokens": ["set", "redis", "model", "to", "normalize", "redis", "keys"], "sha": "c52385a063a4126a7c82159317f16f638cef6532", "url": "https://github.com/ondrejbartas/redis-model-extension/blob/c52385a063a4126a7c82159317f16f638cef6532/lib/redis-model-extension/initialize.rb#L83-L89", "partition": "test"} {"repo": "ondrejbartas/redis-model-extension", "path": "lib/redis-model-extension/initialize.rb", "func_name": "RedisModelExtension.ClassInitialize.redis_alias", "original_string": "def redis_alias name, main_fields, name_of_field_for_order = nil, name_of_field_for_args = nil\n #set fields if they are not allready set!\n if name_of_field_for_order && name_of_field_for_args\n redis_field name_of_field_for_order, :array, [] unless redis_fields_config.has_key?(name_of_field_for_order)\n redis_field name_of_field_for_args, :hash, {} unless redis_fields_config.has_key?(name_of_field_for_args)\n end\n\n @redis_alias_config ||= {}\n #add specification of dynamic alias\n @redis_alias_config[name] = { \n main_fields: main_fields,\n order_field: name_of_field_for_order,\n args_field: name_of_field_for_args,\n }\n\n #create alias methods for find and get (find_by_name, get_by_name)\n create_class_alias_method(name)\n end", "language": "ruby", "code": "def redis_alias name, main_fields, name_of_field_for_order = nil, name_of_field_for_args = nil\n #set fields if they are not allready set!\n if name_of_field_for_order && name_of_field_for_args\n redis_field name_of_field_for_order, :array, [] unless redis_fields_config.has_key?(name_of_field_for_order)\n redis_field name_of_field_for_args, :hash, {} unless redis_fields_config.has_key?(name_of_field_for_args)\n end\n\n @redis_alias_config ||= {}\n #add specification of dynamic alias\n @redis_alias_config[name] = { \n main_fields: main_fields,\n order_field: name_of_field_for_order,\n args_field: name_of_field_for_args,\n }\n\n #create alias methods for find and get (find_by_name, get_by_name)\n create_class_alias_method(name)\n end", "code_tokens": ["def", "redis_alias", "name", ",", "main_fields", ",", "name_of_field_for_order", "=", "nil", ",", "name_of_field_for_args", "=", "nil", "#set fields if they are not allready set!", "if", "name_of_field_for_order", "&&", "name_of_field_for_args", "redis_field", "name_of_field_for_order", ",", ":array", ",", "[", "]", "unless", "redis_fields_config", ".", "has_key?", "(", "name_of_field_for_order", ")", "redis_field", "name_of_field_for_args", ",", ":hash", ",", "{", "}", "unless", "redis_fields_config", ".", "has_key?", "(", "name_of_field_for_args", ")", "end", "@redis_alias_config", "||=", "{", "}", "#add specification of dynamic alias", "@redis_alias_config", "[", "name", "]", "=", "{", "main_fields", ":", "main_fields", ",", "order_field", ":", "name_of_field_for_order", ",", "args_field", ":", "name_of_field_for_args", ",", "}", "#create alias methods for find and get (find_by_name, get_by_name)", "create_class_alias_method", "(", "name", ")", "end"], "docstring": "store informations about redis aliases", "docstring_tokens": ["store", "informations", "about", "redis", "aliases"], "sha": "c52385a063a4126a7c82159317f16f638cef6532", "url": "https://github.com/ondrejbartas/redis-model-extension/blob/c52385a063a4126a7c82159317f16f638cef6532/lib/redis-model-extension/initialize.rb#L92-L109", "partition": "test"} {"repo": "ondrejbartas/redis-model-extension", "path": "lib/redis-model-extension/store_keys.rb", "func_name": "RedisModelExtension.StoreKeys.store_redis_keys", "original_string": "def store_redis_keys\n args = to_arg\n #store main key\n redis_old_keys[:key] = self.class.generate_key(args) #store main key\n\n #store alias keys\n redis_old_keys[:aliases] = []\n redis_alias_config.each do |alias_name, fields|\n redis_old_keys[:aliases] << redis_alias_key(alias_name) if valid_alias_key? alias_name\n end\n end", "language": "ruby", "code": "def store_redis_keys\n args = to_arg\n #store main key\n redis_old_keys[:key] = self.class.generate_key(args) #store main key\n\n #store alias keys\n redis_old_keys[:aliases] = []\n redis_alias_config.each do |alias_name, fields|\n redis_old_keys[:aliases] << redis_alias_key(alias_name) if valid_alias_key? alias_name\n end\n end", "code_tokens": ["def", "store_redis_keys", "args", "=", "to_arg", "#store main key", "redis_old_keys", "[", ":key", "]", "=", "self", ".", "class", ".", "generate_key", "(", "args", ")", "#store main key", "#store alias keys", "redis_old_keys", "[", ":aliases", "]", "=", "[", "]", "redis_alias_config", ".", "each", "do", "|", "alias_name", ",", "fields", "|", "redis_old_keys", "[", ":aliases", "]", "<<", "redis_alias_key", "(", "alias_name", ")", "if", "valid_alias_key?", "alias_name", "end", "end"], "docstring": "set old arguments", "docstring_tokens": ["set", "old", "arguments"], "sha": "c52385a063a4126a7c82159317f16f638cef6532", "url": "https://github.com/ondrejbartas/redis-model-extension/blob/c52385a063a4126a7c82159317f16f638cef6532/lib/redis-model-extension/store_keys.rb#L16-L26", "partition": "test"} {"repo": "ondrejbartas/redis-model-extension", "path": "lib/redis-model-extension/old_initialize.rb", "func_name": "RedisModelExtension.ClassOldInitialize.conf", "original_string": "def conf\n fields = {}\n redis_fields_config.each do |key, type|\n fields[key] = TYPE_TRANSLATIONS[type] if TYPE_TRANSLATIONS.has_key?(type)\n end\n {\n fields: fields,\n required: @required_config.sort,\n redis_key: redis_key_config,\n redis_aliases: redis_alias_config.inject({}){|o,(k,v)| o[k] = v[:main_fields]; o},\n reject_nil_values: !redis_save_fields_with_nil_conf,\n }\n end", "language": "ruby", "code": "def conf\n fields = {}\n redis_fields_config.each do |key, type|\n fields[key] = TYPE_TRANSLATIONS[type] if TYPE_TRANSLATIONS.has_key?(type)\n end\n {\n fields: fields,\n required: @required_config.sort,\n redis_key: redis_key_config,\n redis_aliases: redis_alias_config.inject({}){|o,(k,v)| o[k] = v[:main_fields]; o},\n reject_nil_values: !redis_save_fields_with_nil_conf,\n }\n end", "code_tokens": ["def", "conf", "fields", "=", "{", "}", "redis_fields_config", ".", "each", "do", "|", "key", ",", "type", "|", "fields", "[", "key", "]", "=", "TYPE_TRANSLATIONS", "[", "type", "]", "if", "TYPE_TRANSLATIONS", ".", "has_key?", "(", "type", ")", "end", "{", "fields", ":", "fields", ",", "required", ":", "@required_config", ".", "sort", ",", "redis_key", ":", "redis_key_config", ",", "redis_aliases", ":", "redis_alias_config", ".", "inject", "(", "{", "}", ")", "{", "|", "o", ",", "(", "k", ",", "v", ")", "|", "o", "[", "k", "]", "=", "v", "[", ":main_fields", "]", ";", "o", "}", ",", "reject_nil_values", ":", "!", "redis_save_fields_with_nil_conf", ",", "}", "end"], "docstring": "get config hash", "docstring_tokens": ["get", "config", "hash"], "sha": "c52385a063a4126a7c82159317f16f638cef6532", "url": "https://github.com/ondrejbartas/redis-model-extension/blob/c52385a063a4126a7c82159317f16f638cef6532/lib/redis-model-extension/old_initialize.rb#L89-L101", "partition": "test"} {"repo": "ondrejbartas/redis-model-extension", "path": "lib/redis-model-extension/redis_key.rb", "func_name": "RedisModelExtension.ClassRedisKey.exists?", "original_string": "def exists? args = {}\n RedisModelExtension::Database.redis.exists(self.name.constantize.generate_key(args))\n end", "language": "ruby", "code": "def exists? args = {}\n RedisModelExtension::Database.redis.exists(self.name.constantize.generate_key(args))\n end", "code_tokens": ["def", "exists?", "args", "=", "{", "}", "RedisModelExtension", "::", "Database", ".", "redis", ".", "exists", "(", "self", ".", "name", ".", "constantize", ".", "generate_key", "(", "args", ")", ")", "end"], "docstring": "Check if key by arguments exists in db", "docstring_tokens": ["Check", "if", "key", "by", "arguments", "exists", "in", "db"], "sha": "c52385a063a4126a7c82159317f16f638cef6532", "url": "https://github.com/ondrejbartas/redis-model-extension/blob/c52385a063a4126a7c82159317f16f638cef6532/lib/redis-model-extension/redis_key.rb#L68-L70", "partition": "test"} {"repo": "ondrejbartas/redis-model-extension", "path": "lib/redis-model-extension/redis_key.rb", "func_name": "RedisModelExtension.ClassRedisKey.alias_exists?", "original_string": "def alias_exists? alias_name, args = {}\n RedisModelExtension::Database.redis.exists(self.name.constantize.generate_alias_key(alias_name, args))\n end", "language": "ruby", "code": "def alias_exists? alias_name, args = {}\n RedisModelExtension::Database.redis.exists(self.name.constantize.generate_alias_key(alias_name, args))\n end", "code_tokens": ["def", "alias_exists?", "alias_name", ",", "args", "=", "{", "}", "RedisModelExtension", "::", "Database", ".", "redis", ".", "exists", "(", "self", ".", "name", ".", "constantize", ".", "generate_alias_key", "(", "alias_name", ",", "args", ")", ")", "end"], "docstring": "Check if key by alias name and arguments exists in db", "docstring_tokens": ["Check", "if", "key", "by", "alias", "name", "and", "arguments", "exists", "in", "db"], "sha": "c52385a063a4126a7c82159317f16f638cef6532", "url": "https://github.com/ondrejbartas/redis-model-extension/blob/c52385a063a4126a7c82159317f16f638cef6532/lib/redis-model-extension/redis_key.rb#L73-L75", "partition": "test"} {"repo": "ondrejbartas/redis-model-extension", "path": "lib/redis-model-extension/validation.rb", "func_name": "RedisModelExtension.ClassValidations.valid_item_for_redis_key?", "original_string": "def valid_item_for_redis_key? args, key\n (args.has_key?(key) && !args[key].nil?) || redis_fields_config[key] == :autoincrement\n end", "language": "ruby", "code": "def valid_item_for_redis_key? args, key\n (args.has_key?(key) && !args[key].nil?) || redis_fields_config[key] == :autoincrement\n end", "code_tokens": ["def", "valid_item_for_redis_key?", "args", ",", "key", "(", "args", ".", "has_key?", "(", "key", ")", "&&", "!", "args", "[", "key", "]", ".", "nil?", ")", "||", "redis_fields_config", "[", "key", "]", "==", ":autoincrement", "end"], "docstring": "validate one item of redis key", "docstring_tokens": ["validate", "one", "item", "of", "redis", "key"], "sha": "c52385a063a4126a7c82159317f16f638cef6532", "url": "https://github.com/ondrejbartas/redis-model-extension/blob/c52385a063a4126a7c82159317f16f638cef6532/lib/redis-model-extension/validation.rb#L52-L54", "partition": "test"} {"repo": "ondrejbartas/redis-model-extension", "path": "lib/redis-model-extension/validation.rb", "func_name": "RedisModelExtension.ClassValidations.validate_redis_key", "original_string": "def validate_redis_key\n valid_fields = redis_fields_config.select{|k,v| v != :array && v != :hash }.keys\n bad_fields = redis_key_config - valid_fields\n raise ArgumentError, \"Sorry, but you cannot use as redis key [nonexisting | array | hash] fields: [#{bad_fields.join(\",\")}], availible are: #{valid_fields.join(\", \")}\" unless bad_fields.size == 0\n end", "language": "ruby", "code": "def validate_redis_key\n valid_fields = redis_fields_config.select{|k,v| v != :array && v != :hash }.keys\n bad_fields = redis_key_config - valid_fields\n raise ArgumentError, \"Sorry, but you cannot use as redis key [nonexisting | array | hash] fields: [#{bad_fields.join(\",\")}], availible are: #{valid_fields.join(\", \")}\" unless bad_fields.size == 0\n end", "code_tokens": ["def", "validate_redis_key", "valid_fields", "=", "redis_fields_config", ".", "select", "{", "|", "k", ",", "v", "|", "v", "!=", ":array", "&&", "v", "!=", ":hash", "}", ".", "keys", "bad_fields", "=", "redis_key_config", "-", "valid_fields", "raise", "ArgumentError", ",", "\"Sorry, but you cannot use as redis key [nonexisting | array | hash] fields: [#{bad_fields.join(\",\")}], availible are: #{valid_fields.join(\", \")}\"", "unless", "bad_fields", ".", "size", "==", "0", "end"], "docstring": "look for bad cofiguration in redis key and raise argument error", "docstring_tokens": ["look", "for", "bad", "cofiguration", "in", "redis", "key", "and", "raise", "argument", "error"], "sha": "c52385a063a4126a7c82159317f16f638cef6532", "url": "https://github.com/ondrejbartas/redis-model-extension/blob/c52385a063a4126a7c82159317f16f638cef6532/lib/redis-model-extension/validation.rb#L59-L63", "partition": "test"} {"repo": "ondrejbartas/redis-model-extension", "path": "lib/redis-model-extension/attributes.rb", "func_name": "RedisModelExtension.Attributes.to_arg", "original_string": "def to_arg\n redis_fields_config.inject({}) do |args, (key, type)|\n args[key] = self.send(key)\n args\n end\n end", "language": "ruby", "code": "def to_arg\n redis_fields_config.inject({}) do |args, (key, type)|\n args[key] = self.send(key)\n args\n end\n end", "code_tokens": ["def", "to_arg", "redis_fields_config", ".", "inject", "(", "{", "}", ")", "do", "|", "args", ",", "(", "key", ",", "type", ")", "|", "args", "[", "key", "]", "=", "self", ".", "send", "(", "key", ")", "args", "end", "end"], "docstring": "take all arguments and send them out", "docstring_tokens": ["take", "all", "arguments", "and", "send", "them", "out"], "sha": "c52385a063a4126a7c82159317f16f638cef6532", "url": "https://github.com/ondrejbartas/redis-model-extension/blob/c52385a063a4126a7c82159317f16f638cef6532/lib/redis-model-extension/attributes.rb#L10-L15", "partition": "test"} {"repo": "ondrejbartas/redis-model-extension", "path": "lib/redis-model-extension/get_find.rb", "func_name": "RedisModelExtension.ClassGetFind.find_by_alias", "original_string": "def find_by_alias(alias_name, args = {})\n #check if asked dynamic alias exists\n raise ArgumentError, \"Unknown dynamic alias: '#{alias_name}', use: #{redis_alias_config.keys.join(\", \")} \" unless redis_alias_config.has_key?(alias_name.to_sym)\n\n #normalize input hash of arguments\n args = HashWithIndifferentAccess.new(args)\n\n out = []\n klass = self.name.constantize\n search_key = klass.generate_alias_key(alias_name, args)\n #is key specified directly? -> no needs of looking for other keys! -> faster\n unless search_key =~ /\\*/\n out = klass.get_by_alias(alias_name, args) if klass.alias_exists?(alias_name, args)\n else\n RedisModelExtension::Database.redis.keys(search_key).each do |key|\n out << klass.get_by_alias_key(key)\n end\n end\n out.flatten\n end", "language": "ruby", "code": "def find_by_alias(alias_name, args = {})\n #check if asked dynamic alias exists\n raise ArgumentError, \"Unknown dynamic alias: '#{alias_name}', use: #{redis_alias_config.keys.join(\", \")} \" unless redis_alias_config.has_key?(alias_name.to_sym)\n\n #normalize input hash of arguments\n args = HashWithIndifferentAccess.new(args)\n\n out = []\n klass = self.name.constantize\n search_key = klass.generate_alias_key(alias_name, args)\n #is key specified directly? -> no needs of looking for other keys! -> faster\n unless search_key =~ /\\*/\n out = klass.get_by_alias(alias_name, args) if klass.alias_exists?(alias_name, args)\n else\n RedisModelExtension::Database.redis.keys(search_key).each do |key|\n out << klass.get_by_alias_key(key)\n end\n end\n out.flatten\n end", "code_tokens": ["def", "find_by_alias", "(", "alias_name", ",", "args", "=", "{", "}", ")", "#check if asked dynamic alias exists", "raise", "ArgumentError", ",", "\"Unknown dynamic alias: '#{alias_name}', use: #{redis_alias_config.keys.join(\", \")} \"", "unless", "redis_alias_config", ".", "has_key?", "(", "alias_name", ".", "to_sym", ")", "#normalize input hash of arguments", "args", "=", "HashWithIndifferentAccess", ".", "new", "(", "args", ")", "out", "=", "[", "]", "klass", "=", "self", ".", "name", ".", "constantize", "search_key", "=", "klass", ".", "generate_alias_key", "(", "alias_name", ",", "args", ")", "#is key specified directly? -> no needs of looking for other keys! -> faster", "unless", "search_key", "=~", "/", "\\*", "/", "out", "=", "klass", ".", "get_by_alias", "(", "alias_name", ",", "args", ")", "if", "klass", ".", "alias_exists?", "(", "alias_name", ",", "args", ")", "else", "RedisModelExtension", "::", "Database", ".", "redis", ".", "keys", "(", "search_key", ")", ".", "each", "do", "|", "key", "|", "out", "<<", "klass", ".", "get_by_alias_key", "(", "key", ")", "end", "end", "out", ".", "flatten", "end"], "docstring": "Find method for searching in redis", "docstring_tokens": ["Find", "method", "for", "searching", "in", "redis"], "sha": "c52385a063a4126a7c82159317f16f638cef6532", "url": "https://github.com/ondrejbartas/redis-model-extension/blob/c52385a063a4126a7c82159317f16f638cef6532/lib/redis-model-extension/get_find.rb#L41-L60", "partition": "test"} {"repo": "ondrejbartas/redis-model-extension", "path": "lib/redis-model-extension/get_find.rb", "func_name": "RedisModelExtension.ClassGetFind.get", "original_string": "def get(args = {})\n # when argument is integer - search by id\n args = { id: args } if args.is_a?(Integer)\n\n #normalize input hash of arguments\n args = HashWithIndifferentAccess.new(args)\n\n klass = self.name.constantize\n if klass.valid_key?(args) && klass.exists?(args)\n klass.new_by_key(klass.generate_key(args))\n else\n nil\n end\n end", "language": "ruby", "code": "def get(args = {})\n # when argument is integer - search by id\n args = { id: args } if args.is_a?(Integer)\n\n #normalize input hash of arguments\n args = HashWithIndifferentAccess.new(args)\n\n klass = self.name.constantize\n if klass.valid_key?(args) && klass.exists?(args)\n klass.new_by_key(klass.generate_key(args))\n else\n nil\n end\n end", "code_tokens": ["def", "get", "(", "args", "=", "{", "}", ")", "# when argument is integer - search by id", "args", "=", "{", "id", ":", "args", "}", "if", "args", ".", "is_a?", "(", "Integer", ")", "#normalize input hash of arguments", "args", "=", "HashWithIndifferentAccess", ".", "new", "(", "args", ")", "klass", "=", "self", ".", "name", ".", "constantize", "if", "klass", ".", "valid_key?", "(", "args", ")", "&&", "klass", ".", "exists?", "(", "args", ")", "klass", ".", "new_by_key", "(", "klass", ".", "generate_key", "(", "args", ")", ")", "else", "nil", "end", "end"], "docstring": "GET BY ARGUMENTS\n\nfastest method to get object from redis by getting it by arguments\n * args (Integer) - search by id\n * args (Hash) - search by arguments in redis_key", "docstring_tokens": ["GET", "BY", "ARGUMENTS"], "sha": "c52385a063a4126a7c82159317f16f638cef6532", "url": "https://github.com/ondrejbartas/redis-model-extension/blob/c52385a063a4126a7c82159317f16f638cef6532/lib/redis-model-extension/get_find.rb#L69-L82", "partition": "test"} {"repo": "ondrejbartas/redis-model-extension", "path": "lib/redis-model-extension/get_find.rb", "func_name": "RedisModelExtension.ClassGetFind.get_by_alias_key", "original_string": "def get_by_alias_key(alias_key)\n klass = self.name.constantize\n if RedisModelExtension::Database.redis.exists(alias_key)\n out = []\n RedisModelExtension::Database.redis.smembers(alias_key).each do |key|\n item = klass.new_by_key(key)\n out << item if item\n end\n return out\n end\n nil\n end", "language": "ruby", "code": "def get_by_alias_key(alias_key)\n klass = self.name.constantize\n if RedisModelExtension::Database.redis.exists(alias_key)\n out = []\n RedisModelExtension::Database.redis.smembers(alias_key).each do |key|\n item = klass.new_by_key(key)\n out << item if item\n end\n return out\n end\n nil\n end", "code_tokens": ["def", "get_by_alias_key", "(", "alias_key", ")", "klass", "=", "self", ".", "name", ".", "constantize", "if", "RedisModelExtension", "::", "Database", ".", "redis", ".", "exists", "(", "alias_key", ")", "out", "=", "[", "]", "RedisModelExtension", "::", "Database", ".", "redis", ".", "smembers", "(", "alias_key", ")", ".", "each", "do", "|", "key", "|", "item", "=", "klass", ".", "new_by_key", "(", "key", ")", "out", "<<", "item", "if", "item", "end", "return", "out", "end", "nil", "end"], "docstring": "fastest method to get object from redis by getting it by alias and arguments", "docstring_tokens": ["fastest", "method", "to", "get", "object", "from", "redis", "by", "getting", "it", "by", "alias", "and", "arguments"], "sha": "c52385a063a4126a7c82159317f16f638cef6532", "url": "https://github.com/ondrejbartas/redis-model-extension/blob/c52385a063a4126a7c82159317f16f638cef6532/lib/redis-model-extension/get_find.rb#L124-L135", "partition": "test"} {"repo": "ondrejbartas/redis-model-extension", "path": "lib/redis-model-extension/get_find.rb", "func_name": "RedisModelExtension.ClassGetFind.new_by_key", "original_string": "def new_by_key(key)\n args = RedisModelExtension::Database.redis.hgetall(key)\n return nil unless args && args.any?\n args.symbolize_keys!\n\n new_instance = new(args)\n new_instance.store_keys\n\n return new_instance\n end", "language": "ruby", "code": "def new_by_key(key)\n args = RedisModelExtension::Database.redis.hgetall(key)\n return nil unless args && args.any?\n args.symbolize_keys!\n\n new_instance = new(args)\n new_instance.store_keys\n\n return new_instance\n end", "code_tokens": ["def", "new_by_key", "(", "key", ")", "args", "=", "RedisModelExtension", "::", "Database", ".", "redis", ".", "hgetall", "(", "key", ")", "return", "nil", "unless", "args", "&&", "args", ".", "any?", "args", ".", "symbolize_keys!", "new_instance", "=", "new", "(", "args", ")", "new_instance", ".", "store_keys", "return", "new_instance", "end"], "docstring": "CREATE NEW OBJECT BY HASH VALUES\n\n read all data from redis and create new instance (used for Find & Get method)", "docstring_tokens": ["CREATE", "NEW", "OBJECT", "BY", "HASH", "VALUES"], "sha": "c52385a063a4126a7c82159317f16f638cef6532", "url": "https://github.com/ondrejbartas/redis-model-extension/blob/c52385a063a4126a7c82159317f16f638cef6532/lib/redis-model-extension/get_find.rb#L142-L151", "partition": "test"} {"repo": "ondrejbartas/redis-model-extension", "path": "lib/redis-model-extension/value_transform.rb", "func_name": "RedisModelExtension.ValueTransform.value_to_redis", "original_string": "def value_to_redis name, value\n if redis_fields_config.has_key?(name)\n value_transform value, redis_fields_config[name]\n else\n value\n end\n end", "language": "ruby", "code": "def value_to_redis name, value\n if redis_fields_config.has_key?(name)\n value_transform value, redis_fields_config[name]\n else\n value\n end\n end", "code_tokens": ["def", "value_to_redis", "name", ",", "value", "if", "redis_fields_config", ".", "has_key?", "(", "name", ")", "value_transform", "value", ",", "redis_fields_config", "[", "name", "]", "else", "value", "end", "end"], "docstring": "choose right type of value and then transform it for redis", "docstring_tokens": ["choose", "right", "type", "of", "value", "and", "then", "transform", "it", "for", "redis"], "sha": "c52385a063a4126a7c82159317f16f638cef6532", "url": "https://github.com/ondrejbartas/redis-model-extension/blob/c52385a063a4126a7c82159317f16f638cef6532/lib/redis-model-extension/value_transform.rb#L6-L12", "partition": "test"} {"repo": "ondrejbartas/redis-model-extension", "path": "lib/redis-model-extension/value_transform.rb", "func_name": "RedisModelExtension.ValueTransform.value_transform", "original_string": "def value_transform value, type\n return nil if value.nil? || value.to_s.size == 0\n case type\n when :integer then value.to_i\n when :autoincrement then value.to_i\n when :string then value.to_s\n when :float then value.to_f\n when :bool then value.to_s\n when :symbol then value.to_s\n when :marshal then Marshal.dump(value)\n when :array then Yajl::Encoder.encode(value)\n when :hash then Yajl::Encoder.encode(value)\n when :time then Time.parse(value.to_s).strftime(\"%Y.%m.%d %H:%M:%S\")\n when :date then Date.parse(value.to_s).strftime(\"%Y-%m-%d\")\n else value\n end\n end", "language": "ruby", "code": "def value_transform value, type\n return nil if value.nil? || value.to_s.size == 0\n case type\n when :integer then value.to_i\n when :autoincrement then value.to_i\n when :string then value.to_s\n when :float then value.to_f\n when :bool then value.to_s\n when :symbol then value.to_s\n when :marshal then Marshal.dump(value)\n when :array then Yajl::Encoder.encode(value)\n when :hash then Yajl::Encoder.encode(value)\n when :time then Time.parse(value.to_s).strftime(\"%Y.%m.%d %H:%M:%S\")\n when :date then Date.parse(value.to_s).strftime(\"%Y-%m-%d\")\n else value\n end\n end", "code_tokens": ["def", "value_transform", "value", ",", "type", "return", "nil", "if", "value", ".", "nil?", "||", "value", ".", "to_s", ".", "size", "==", "0", "case", "type", "when", ":integer", "then", "value", ".", "to_i", "when", ":autoincrement", "then", "value", ".", "to_i", "when", ":string", "then", "value", ".", "to_s", "when", ":float", "then", "value", ".", "to_f", "when", ":bool", "then", "value", ".", "to_s", "when", ":symbol", "then", "value", ".", "to_s", "when", ":marshal", "then", "Marshal", ".", "dump", "(", "value", ")", "when", ":array", "then", "Yajl", "::", "Encoder", ".", "encode", "(", "value", ")", "when", ":hash", "then", "Yajl", "::", "Encoder", ".", "encode", "(", "value", ")", "when", ":time", "then", "Time", ".", "parse", "(", "value", ".", "to_s", ")", ".", "strftime", "(", "\"%Y.%m.%d %H:%M:%S\"", ")", "when", ":date", "then", "Date", ".", "parse", "(", "value", ".", "to_s", ")", ".", "strftime", "(", "\"%Y-%m-%d\"", ")", "else", "value", "end", "end"], "docstring": "convert value for valid format which can be saved in redis", "docstring_tokens": ["convert", "value", "for", "valid", "format", "which", "can", "be", "saved", "in", "redis"], "sha": "c52385a063a4126a7c82159317f16f638cef6532", "url": "https://github.com/ondrejbartas/redis-model-extension/blob/c52385a063a4126a7c82159317f16f638cef6532/lib/redis-model-extension/value_transform.rb#L15-L31", "partition": "test"} {"repo": "ondrejbartas/redis-model-extension", "path": "lib/redis-model-extension/value_transform.rb", "func_name": "RedisModelExtension.ValueTransform.value_parse", "original_string": "def value_parse value, type\n return nil if value.nil? || value.to_s.size == 0\n case type\n when :integer then value.to_i\n when :autoincrement then value.to_i\n when :string then value.to_s\n when :float then value.to_f\n when :bool then value.to_s.to_bool\n when :symbol then value.to_s.to_sym\n when :marshal then value.is_a?(String) ? Marshal.load(value) : value\n when :array then value.is_a?(String) ? Yajl::Parser.parse(value) : value\n when :hash then value.is_a?(String) ? Hashr.new(Yajl::Parser.parse(value)) : Hashr.new(value)\n when :time then value.is_a?(String) ? Time.parse(value) : value\n when :date then value.is_a?(String) ? Date.parse(value) : value\n else value\n end\n end", "language": "ruby", "code": "def value_parse value, type\n return nil if value.nil? || value.to_s.size == 0\n case type\n when :integer then value.to_i\n when :autoincrement then value.to_i\n when :string then value.to_s\n when :float then value.to_f\n when :bool then value.to_s.to_bool\n when :symbol then value.to_s.to_sym\n when :marshal then value.is_a?(String) ? Marshal.load(value) : value\n when :array then value.is_a?(String) ? Yajl::Parser.parse(value) : value\n when :hash then value.is_a?(String) ? Hashr.new(Yajl::Parser.parse(value)) : Hashr.new(value)\n when :time then value.is_a?(String) ? Time.parse(value) : value\n when :date then value.is_a?(String) ? Date.parse(value) : value\n else value\n end\n end", "code_tokens": ["def", "value_parse", "value", ",", "type", "return", "nil", "if", "value", ".", "nil?", "||", "value", ".", "to_s", ".", "size", "==", "0", "case", "type", "when", ":integer", "then", "value", ".", "to_i", "when", ":autoincrement", "then", "value", ".", "to_i", "when", ":string", "then", "value", ".", "to_s", "when", ":float", "then", "value", ".", "to_f", "when", ":bool", "then", "value", ".", "to_s", ".", "to_bool", "when", ":symbol", "then", "value", ".", "to_s", ".", "to_sym", "when", ":marshal", "then", "value", ".", "is_a?", "(", "String", ")", "?", "Marshal", ".", "load", "(", "value", ")", ":", "value", "when", ":array", "then", "value", ".", "is_a?", "(", "String", ")", "?", "Yajl", "::", "Parser", ".", "parse", "(", "value", ")", ":", "value", "when", ":hash", "then", "value", ".", "is_a?", "(", "String", ")", "?", "Hashr", ".", "new", "(", "Yajl", "::", "Parser", ".", "parse", "(", "value", ")", ")", ":", "Hashr", ".", "new", "(", "value", ")", "when", ":time", "then", "value", ".", "is_a?", "(", "String", ")", "?", "Time", ".", "parse", "(", "value", ")", ":", "value", "when", ":date", "then", "value", ".", "is_a?", "(", "String", ")", "?", "Date", ".", "parse", "(", "value", ")", ":", "value", "else", "value", "end", "end"], "docstring": "convert value from redis into valid format in ruby", "docstring_tokens": ["convert", "value", "from", "redis", "into", "valid", "format", "in", "ruby"], "sha": "c52385a063a4126a7c82159317f16f638cef6532", "url": "https://github.com/ondrejbartas/redis-model-extension/blob/c52385a063a4126a7c82159317f16f638cef6532/lib/redis-model-extension/value_transform.rb#L34-L50", "partition": "test"} {"repo": "ondrejbartas/redis-model-extension", "path": "lib/redis-model-extension/save_destroy.rb", "func_name": "RedisModelExtension.SaveDestroy.update", "original_string": "def update args\n args.each do |key, value|\n method = \"#{key}=\".to_sym \n if self.respond_to? method\n self.send(method, value)\n end\n end\n end", "language": "ruby", "code": "def update args\n args.each do |key, value|\n method = \"#{key}=\".to_sym \n if self.respond_to? method\n self.send(method, value)\n end\n end\n end", "code_tokens": ["def", "update", "args", "args", ".", "each", "do", "|", "key", ",", "value", "|", "method", "=", "\"#{key}=\"", ".", "to_sym", "if", "self", ".", "respond_to?", "method", "self", ".", "send", "(", "method", ",", "value", ")", "end", "end", "end"], "docstring": "update multiple attrubutes at once", "docstring_tokens": ["update", "multiple", "attrubutes", "at", "once"], "sha": "c52385a063a4126a7c82159317f16f638cef6532", "url": "https://github.com/ondrejbartas/redis-model-extension/blob/c52385a063a4126a7c82159317f16f638cef6532/lib/redis-model-extension/save_destroy.rb#L74-L81", "partition": "test"} {"repo": "ondrejbartas/redis-model-extension", "path": "lib/redis-model-extension/save_destroy.rb", "func_name": "RedisModelExtension.SaveDestroy.destroy_aliases!", "original_string": "def destroy_aliases!\n #do it only if it is existing object!\n if redis_old_keys[:aliases].size > 0\n redis_old_keys[:aliases].each do |alias_key|\n RedisModelExtension::Database.redis.srem alias_key, redis_old_keys[:key]\n #delete alias with 0 keys\n RedisModelExtension::Database.redis.del(alias_key) if RedisModelExtension::Database.redis.scard(alias_key).to_i == 0\n end\n end\n end", "language": "ruby", "code": "def destroy_aliases!\n #do it only if it is existing object!\n if redis_old_keys[:aliases].size > 0\n redis_old_keys[:aliases].each do |alias_key|\n RedisModelExtension::Database.redis.srem alias_key, redis_old_keys[:key]\n #delete alias with 0 keys\n RedisModelExtension::Database.redis.del(alias_key) if RedisModelExtension::Database.redis.scard(alias_key).to_i == 0\n end\n end\n end", "code_tokens": ["def", "destroy_aliases!", "#do it only if it is existing object!", "if", "redis_old_keys", "[", ":aliases", "]", ".", "size", ">", "0", "redis_old_keys", "[", ":aliases", "]", ".", "each", "do", "|", "alias_key", "|", "RedisModelExtension", "::", "Database", ".", "redis", ".", "srem", "alias_key", ",", "redis_old_keys", "[", ":key", "]", "#delete alias with 0 keys", "RedisModelExtension", "::", "Database", ".", "redis", ".", "del", "(", "alias_key", ")", "if", "RedisModelExtension", "::", "Database", ".", "redis", ".", "scard", "(", "alias_key", ")", ".", "to_i", "==", "0", "end", "end", "end"], "docstring": "remove all aliases", "docstring_tokens": ["remove", "all", "aliases"], "sha": "c52385a063a4126a7c82159317f16f638cef6532", "url": "https://github.com/ondrejbartas/redis-model-extension/blob/c52385a063a4126a7c82159317f16f638cef6532/lib/redis-model-extension/save_destroy.rb#L97-L106", "partition": "test"} {"repo": "whlsxl/firim", "path": "lib/firim/commands_generator.rb", "func_name": "Firim.CommandsGenerator.add", "original_string": "def add(username, token)\n Firim::AccountManager.new(\n user: username,\n token: token\n ).add_to_keychain\n end", "language": "ruby", "code": "def add(username, token)\n Firim::AccountManager.new(\n user: username,\n token: token\n ).add_to_keychain\n end", "code_tokens": ["def", "add", "(", "username", ",", "token", ")", "Firim", "::", "AccountManager", ".", "new", "(", "user", ":", "username", ",", "token", ":", "token", ")", ".", "add_to_keychain", "end"], "docstring": "Add entry to Apple Keychain", "docstring_tokens": ["Add", "entry", "to", "Apple", "Keychain"], "sha": "34102fb47cbc782d1299342ac5058ccd38a53428", "url": "https://github.com/whlsxl/firim/blob/34102fb47cbc782d1299342ac5058ccd38a53428/lib/firim/commands_generator.rb#L103-L108", "partition": "test"} {"repo": "wistia/nsq-ruby", "path": "lib/nsq/discovery.rb", "func_name": "Nsq.Discovery.get_nsqds", "original_string": "def get_nsqds(lookupd, topic = nil)\n uri_scheme = 'http://' unless lookupd.match(%r(https?://))\n uri = URI.parse(\"#{uri_scheme}#{lookupd}\")\n\n uri.query = \"ts=#{Time.now.to_i}\"\n if topic\n uri.path = '/lookup'\n uri.query += \"&topic=#{URI.escape(topic)}\"\n else\n uri.path = '/nodes'\n end\n\n begin\n body = Net::HTTP.get(uri)\n data = JSON.parse(body)\n producers = data['producers'] || # v1.0.0-compat\n (data['data'] && data['data']['producers'])\n\n if producers\n producers.map do |producer|\n \"#{producer['broadcast_address']}:#{producer['tcp_port']}\"\n end\n else\n []\n end\n rescue Exception => e\n error \"Error during discovery for #{lookupd}: #{e}\"\n nil\n end\n end", "language": "ruby", "code": "def get_nsqds(lookupd, topic = nil)\n uri_scheme = 'http://' unless lookupd.match(%r(https?://))\n uri = URI.parse(\"#{uri_scheme}#{lookupd}\")\n\n uri.query = \"ts=#{Time.now.to_i}\"\n if topic\n uri.path = '/lookup'\n uri.query += \"&topic=#{URI.escape(topic)}\"\n else\n uri.path = '/nodes'\n end\n\n begin\n body = Net::HTTP.get(uri)\n data = JSON.parse(body)\n producers = data['producers'] || # v1.0.0-compat\n (data['data'] && data['data']['producers'])\n\n if producers\n producers.map do |producer|\n \"#{producer['broadcast_address']}:#{producer['tcp_port']}\"\n end\n else\n []\n end\n rescue Exception => e\n error \"Error during discovery for #{lookupd}: #{e}\"\n nil\n end\n end", "code_tokens": ["def", "get_nsqds", "(", "lookupd", ",", "topic", "=", "nil", ")", "uri_scheme", "=", "'http://'", "unless", "lookupd", ".", "match", "(", "%r(", ")", ")", "uri", "=", "URI", ".", "parse", "(", "\"#{uri_scheme}#{lookupd}\"", ")", "uri", ".", "query", "=", "\"ts=#{Time.now.to_i}\"", "if", "topic", "uri", ".", "path", "=", "'/lookup'", "uri", ".", "query", "+=", "\"&topic=#{URI.escape(topic)}\"", "else", "uri", ".", "path", "=", "'/nodes'", "end", "begin", "body", "=", "Net", "::", "HTTP", ".", "get", "(", "uri", ")", "data", "=", "JSON", ".", "parse", "(", "body", ")", "producers", "=", "data", "[", "'producers'", "]", "||", "# v1.0.0-compat", "(", "data", "[", "'data'", "]", "&&", "data", "[", "'data'", "]", "[", "'producers'", "]", ")", "if", "producers", "producers", ".", "map", "do", "|", "producer", "|", "\"#{producer['broadcast_address']}:#{producer['tcp_port']}\"", "end", "else", "[", "]", "end", "rescue", "Exception", "=>", "e", "error", "\"Error during discovery for #{lookupd}: #{e}\"", "nil", "end", "end"], "docstring": "Returns an array of nsqd addresses\n If there's an error, return nil", "docstring_tokens": ["Returns", "an", "array", "of", "nsqd", "addresses", "If", "there", "s", "an", "error", "return", "nil"], "sha": "88bf09cc9ee2ea8e3d41058afd5c88ceeba63228", "url": "https://github.com/wistia/nsq-ruby/blob/88bf09cc9ee2ea8e3d41058afd5c88ceeba63228/lib/nsq/discovery.rb#L66-L95", "partition": "test"} {"repo": "wistia/nsq-ruby", "path": "lib/nsq/client_base.rb", "func_name": "Nsq.ClientBase.discover_repeatedly", "original_string": "def discover_repeatedly(opts = {})\n @discovery_thread = Thread.new do\n\n @discovery = Discovery.new(opts[:nsqlookupds])\n\n loop do\n begin\n nsqds = nsqds_from_lookupd(opts[:topic])\n drop_and_add_connections(nsqds)\n rescue DiscoveryException\n # We can't connect to any nsqlookupds. That's okay, we'll just\n # leave our current nsqd connections alone and try again later.\n warn 'Could not connect to any nsqlookupd instances in discovery loop'\n end\n sleep opts[:interval]\n end\n\n end\n\n @discovery_thread.abort_on_exception = true\n end", "language": "ruby", "code": "def discover_repeatedly(opts = {})\n @discovery_thread = Thread.new do\n\n @discovery = Discovery.new(opts[:nsqlookupds])\n\n loop do\n begin\n nsqds = nsqds_from_lookupd(opts[:topic])\n drop_and_add_connections(nsqds)\n rescue DiscoveryException\n # We can't connect to any nsqlookupds. That's okay, we'll just\n # leave our current nsqd connections alone and try again later.\n warn 'Could not connect to any nsqlookupd instances in discovery loop'\n end\n sleep opts[:interval]\n end\n\n end\n\n @discovery_thread.abort_on_exception = true\n end", "code_tokens": ["def", "discover_repeatedly", "(", "opts", "=", "{", "}", ")", "@discovery_thread", "=", "Thread", ".", "new", "do", "@discovery", "=", "Discovery", ".", "new", "(", "opts", "[", ":nsqlookupds", "]", ")", "loop", "do", "begin", "nsqds", "=", "nsqds_from_lookupd", "(", "opts", "[", ":topic", "]", ")", "drop_and_add_connections", "(", "nsqds", ")", "rescue", "DiscoveryException", "# We can't connect to any nsqlookupds. That's okay, we'll just", "# leave our current nsqd connections alone and try again later.", "warn", "'Could not connect to any nsqlookupd instances in discovery loop'", "end", "sleep", "opts", "[", ":interval", "]", "end", "end", "@discovery_thread", ".", "abort_on_exception", "=", "true", "end"], "docstring": "discovers nsqds from an nsqlookupd repeatedly\n\n opts:\n nsqlookups: ['127.0.0.1:4161'],\n topic: 'topic-to-find-nsqds-for',\n interval: 60", "docstring_tokens": ["discovers", "nsqds", "from", "an", "nsqlookupd", "repeatedly"], "sha": "88bf09cc9ee2ea8e3d41058afd5c88ceeba63228", "url": "https://github.com/wistia/nsq-ruby/blob/88bf09cc9ee2ea8e3d41058afd5c88ceeba63228/lib/nsq/client_base.rb#L33-L53", "partition": "test"} {"repo": "wistia/nsq-ruby", "path": "lib/nsq/connection.rb", "func_name": "Nsq.Connection.with_retries", "original_string": "def with_retries(&block)\n base_sleep_seconds = 0.5\n max_sleep_seconds = 300 # 5 minutes\n\n # Let's do this thing\n attempts = 0\n\n begin\n attempts += 1\n return block.call(attempts)\n\n rescue Errno::ECONNREFUSED, Errno::ECONNRESET, Errno::EHOSTUNREACH,\n Errno::ENETDOWN, Errno::ENETUNREACH, Errno::ETIMEDOUT, Timeout::Error => ex\n\n raise ex if attempts >= 100\n\n # The sleep time is an exponentially-increasing function of base_sleep_seconds.\n # But, it never exceeds max_sleep_seconds.\n sleep_seconds = [base_sleep_seconds * (2 ** (attempts - 1)), max_sleep_seconds].min\n # Randomize to a random value in the range sleep_seconds/2 .. sleep_seconds\n sleep_seconds = sleep_seconds * (0.5 * (1 + rand()))\n # But never sleep less than base_sleep_seconds\n sleep_seconds = [base_sleep_seconds, sleep_seconds].max\n\n warn \"Failed to connect: #{ex}. Retrying in #{sleep_seconds.round(1)} seconds.\"\n\n snooze(sleep_seconds)\n\n retry\n end\n end", "language": "ruby", "code": "def with_retries(&block)\n base_sleep_seconds = 0.5\n max_sleep_seconds = 300 # 5 minutes\n\n # Let's do this thing\n attempts = 0\n\n begin\n attempts += 1\n return block.call(attempts)\n\n rescue Errno::ECONNREFUSED, Errno::ECONNRESET, Errno::EHOSTUNREACH,\n Errno::ENETDOWN, Errno::ENETUNREACH, Errno::ETIMEDOUT, Timeout::Error => ex\n\n raise ex if attempts >= 100\n\n # The sleep time is an exponentially-increasing function of base_sleep_seconds.\n # But, it never exceeds max_sleep_seconds.\n sleep_seconds = [base_sleep_seconds * (2 ** (attempts - 1)), max_sleep_seconds].min\n # Randomize to a random value in the range sleep_seconds/2 .. sleep_seconds\n sleep_seconds = sleep_seconds * (0.5 * (1 + rand()))\n # But never sleep less than base_sleep_seconds\n sleep_seconds = [base_sleep_seconds, sleep_seconds].max\n\n warn \"Failed to connect: #{ex}. Retrying in #{sleep_seconds.round(1)} seconds.\"\n\n snooze(sleep_seconds)\n\n retry\n end\n end", "code_tokens": ["def", "with_retries", "(", "&", "block", ")", "base_sleep_seconds", "=", "0.5", "max_sleep_seconds", "=", "300", "# 5 minutes", "# Let's do this thing", "attempts", "=", "0", "begin", "attempts", "+=", "1", "return", "block", ".", "call", "(", "attempts", ")", "rescue", "Errno", "::", "ECONNREFUSED", ",", "Errno", "::", "ECONNRESET", ",", "Errno", "::", "EHOSTUNREACH", ",", "Errno", "::", "ENETDOWN", ",", "Errno", "::", "ENETUNREACH", ",", "Errno", "::", "ETIMEDOUT", ",", "Timeout", "::", "Error", "=>", "ex", "raise", "ex", "if", "attempts", ">=", "100", "# The sleep time is an exponentially-increasing function of base_sleep_seconds.", "# But, it never exceeds max_sleep_seconds.", "sleep_seconds", "=", "[", "base_sleep_seconds", "*", "(", "2", "**", "(", "attempts", "-", "1", ")", ")", ",", "max_sleep_seconds", "]", ".", "min", "# Randomize to a random value in the range sleep_seconds/2 .. sleep_seconds", "sleep_seconds", "=", "sleep_seconds", "*", "(", "0.5", "*", "(", "1", "+", "rand", "(", ")", ")", ")", "# But never sleep less than base_sleep_seconds", "sleep_seconds", "=", "[", "base_sleep_seconds", ",", "sleep_seconds", "]", ".", "max", "warn", "\"Failed to connect: #{ex}. Retrying in #{sleep_seconds.round(1)} seconds.\"", "snooze", "(", "sleep_seconds", ")", "retry", "end", "end"], "docstring": "Retry the supplied block with exponential backoff.\n\n Borrowed liberally from:\n https://github.com/ooyala/retries/blob/master/lib/retries.rb", "docstring_tokens": ["Retry", "the", "supplied", "block", "with", "exponential", "backoff", "."], "sha": "88bf09cc9ee2ea8e3d41058afd5c88ceeba63228", "url": "https://github.com/wistia/nsq-ruby/blob/88bf09cc9ee2ea8e3d41058afd5c88ceeba63228/lib/nsq/connection.rb#L405-L435", "partition": "test"} {"repo": "mjpete3/x12", "path": "lib/x12/base.rb", "func_name": "X12.Base.show", "original_string": "def show(ind = '')\r\n count = 0\r\n self.to_a.each{|i|\r\n #puts \"#{ind}#{i.name} #{i.object_id} #{i.super.object_id} [#{count}]: #{i.parsed_str} #{i.super.class}\"\r\n puts \"#{ind}#{i.name} [#{count}]: #{i.to_s.sub(/^(.{30})(.*?)(.{30})$/, '\\1...\\3')}\"\r\n # Force parsing a segment\r\n if i.kind_of?(X12::Segment) && i.nodes[0]\r\n i.find_field(i.nodes[0].name)\r\n end\r\n i.nodes.each{|j|\r\n case \r\n when j.kind_of?(X12::Base) then j.show(ind+' ')\r\n when j.kind_of?(X12::Field) then puts \"#{ind+' '}#{j.name} -> '#{j.to_s}'\"\r\n end\r\n } \r\n count += 1\r\n }\r\n end", "language": "ruby", "code": "def show(ind = '')\r\n count = 0\r\n self.to_a.each{|i|\r\n #puts \"#{ind}#{i.name} #{i.object_id} #{i.super.object_id} [#{count}]: #{i.parsed_str} #{i.super.class}\"\r\n puts \"#{ind}#{i.name} [#{count}]: #{i.to_s.sub(/^(.{30})(.*?)(.{30})$/, '\\1...\\3')}\"\r\n # Force parsing a segment\r\n if i.kind_of?(X12::Segment) && i.nodes[0]\r\n i.find_field(i.nodes[0].name)\r\n end\r\n i.nodes.each{|j|\r\n case \r\n when j.kind_of?(X12::Base) then j.show(ind+' ')\r\n when j.kind_of?(X12::Field) then puts \"#{ind+' '}#{j.name} -> '#{j.to_s}'\"\r\n end\r\n } \r\n count += 1\r\n }\r\n end", "code_tokens": ["def", "show", "(", "ind", "=", "''", ")", "count", "=", "0", "self", ".", "to_a", ".", "each", "{", "|", "i", "|", "#puts \"#{ind}#{i.name} #{i.object_id} #{i.super.object_id} [#{count}]: #{i.parsed_str} #{i.super.class}\"\r", "puts", "\"#{ind}#{i.name} [#{count}]: #{i.to_s.sub(/^(.{30})(.*?)(.{30})$/, '\\1...\\3')}\"", "# Force parsing a segment\r", "if", "i", ".", "kind_of?", "(", "X12", "::", "Segment", ")", "&&", "i", ".", "nodes", "[", "0", "]", "i", ".", "find_field", "(", "i", ".", "nodes", "[", "0", "]", ".", "name", ")", "end", "i", ".", "nodes", ".", "each", "{", "|", "j", "|", "case", "when", "j", ".", "kind_of?", "(", "X12", "::", "Base", ")", "then", "j", ".", "show", "(", "ind", "+", "' '", ")", "when", "j", ".", "kind_of?", "(", "X12", "::", "Field", ")", "then", "puts", "\"#{ind+' '}#{j.name} -> '#{j.to_s}'\"", "end", "}", "count", "+=", "1", "}", "end"], "docstring": "Prints a tree-like representation of the element", "docstring_tokens": ["Prints", "a", "tree", "-", "like", "representation", "of", "the", "element"], "sha": "bb429e2914a42e63e96122695ecfb652a974e54f", "url": "https://github.com/mjpete3/x12/blob/bb429e2914a42e63e96122695ecfb652a974e54f/lib/x12/base.rb#L58-L75", "partition": "test"} {"repo": "mjpete3/x12", "path": "lib/x12/base.rb", "func_name": "X12.Base.do_repeats", "original_string": "def do_repeats(s)\r\n if self.repeats.end > 1\r\n possible_repeat = self.dup\r\n p_s = possible_repeat.parse(s)\r\n if p_s\r\n s = p_s\r\n self.next_repeat = possible_repeat\r\n end # if parsed\r\n end # more repeats\r\n s\r\n end", "language": "ruby", "code": "def do_repeats(s)\r\n if self.repeats.end > 1\r\n possible_repeat = self.dup\r\n p_s = possible_repeat.parse(s)\r\n if p_s\r\n s = p_s\r\n self.next_repeat = possible_repeat\r\n end # if parsed\r\n end # more repeats\r\n s\r\n end", "code_tokens": ["def", "do_repeats", "(", "s", ")", "if", "self", ".", "repeats", ".", "end", ">", "1", "possible_repeat", "=", "self", ".", "dup", "p_s", "=", "possible_repeat", ".", "parse", "(", "s", ")", "if", "p_s", "s", "=", "p_s", "self", ".", "next_repeat", "=", "possible_repeat", "end", "# if parsed\r", "end", "# more repeats\r", "s", "end"], "docstring": "Try to parse the current element one more time if required. Returns the rest of the string\n or the same string if no more repeats are found or required.", "docstring_tokens": ["Try", "to", "parse", "the", "current", "element", "one", "more", "time", "if", "required", ".", "Returns", "the", "rest", "of", "the", "string", "or", "the", "same", "string", "if", "no", "more", "repeats", "are", "found", "or", "required", "."], "sha": "bb429e2914a42e63e96122695ecfb652a974e54f", "url": "https://github.com/mjpete3/x12/blob/bb429e2914a42e63e96122695ecfb652a974e54f/lib/x12/base.rb#L79-L89", "partition": "test"} {"repo": "mjpete3/x12", "path": "lib/x12/base.rb", "func_name": "X12.Base.find", "original_string": "def find(e)\r\n #puts \"Finding [#{e}] in #{self.class} #{name}\"\r\n case self\r\n when X12::Loop\r\n # Breadth first\r\n res = nodes.find{|i| e==i.name }\r\n return res if res\r\n # Depth now\r\n nodes.each{|i| \r\n res = i.find(e) if i.kind_of?(X12::Loop)\r\n return res unless res.nil? or EMPTY==res # otherwise keep looping\r\n }\r\n when X12::Segment\r\n return find_field(e).to_s\r\n end # case\r\n return EMPTY\r\n end", "language": "ruby", "code": "def find(e)\r\n #puts \"Finding [#{e}] in #{self.class} #{name}\"\r\n case self\r\n when X12::Loop\r\n # Breadth first\r\n res = nodes.find{|i| e==i.name }\r\n return res if res\r\n # Depth now\r\n nodes.each{|i| \r\n res = i.find(e) if i.kind_of?(X12::Loop)\r\n return res unless res.nil? or EMPTY==res # otherwise keep looping\r\n }\r\n when X12::Segment\r\n return find_field(e).to_s\r\n end # case\r\n return EMPTY\r\n end", "code_tokens": ["def", "find", "(", "e", ")", "#puts \"Finding [#{e}] in #{self.class} #{name}\"\r", "case", "self", "when", "X12", "::", "Loop", "# Breadth first\r", "res", "=", "nodes", ".", "find", "{", "|", "i", "|", "e", "==", "i", ".", "name", "}", "return", "res", "if", "res", "# Depth now\r", "nodes", ".", "each", "{", "|", "i", "|", "res", "=", "i", ".", "find", "(", "e", ")", "if", "i", ".", "kind_of?", "(", "X12", "::", "Loop", ")", "return", "res", "unless", "res", ".", "nil?", "or", "EMPTY", "==", "res", "# otherwise keep looping\r", "}", "when", "X12", "::", "Segment", "return", "find_field", "(", "e", ")", ".", "to_s", "end", "# case\r", "return", "EMPTY", "end"], "docstring": "Make a deep copy of the element\n dup\n Recursively find a sub-element, which also has to be of type Base.", "docstring_tokens": ["Make", "a", "deep", "copy", "of", "the", "element", "dup", "Recursively", "find", "a", "sub", "-", "element", "which", "also", "has", "to", "be", "of", "type", "Base", "."], "sha": "bb429e2914a42e63e96122695ecfb652a974e54f", "url": "https://github.com/mjpete3/x12/blob/bb429e2914a42e63e96122695ecfb652a974e54f/lib/x12/base.rb#L112-L128", "partition": "test"} {"repo": "mjpete3/x12", "path": "lib/x12/base.rb", "func_name": "X12.Base.method_missing", "original_string": "def method_missing(meth, *args, &block)\r\n str = meth.id2name\r\n str = str[1..str.length] if str =~ /^_\\d+$/ # to avoid pure number names like 270, 997, etc.\r\n #puts \"Missing #{str}\"\r\n if str =~ /=$/\r\n # Assignment\r\n str.chop!\r\n #puts str\r\n case self\r\n when X12::Segment\r\n res = find_field(str)\r\n throw Exception.new(\"No field '#{str}' in segment '#{self.name}'\") if EMPTY == res\r\n res.content = args[0].to_s\r\n #puts res.inspect\r\n else\r\n throw Exception.new(\"Illegal assignment to #{meth} of #{self.class}\")\r\n end # case\r\n else\r\n # Retrieval\r\n res = find(str)\r\n yield res if block_given?\r\n res\r\n end # if assignment\r\n end", "language": "ruby", "code": "def method_missing(meth, *args, &block)\r\n str = meth.id2name\r\n str = str[1..str.length] if str =~ /^_\\d+$/ # to avoid pure number names like 270, 997, etc.\r\n #puts \"Missing #{str}\"\r\n if str =~ /=$/\r\n # Assignment\r\n str.chop!\r\n #puts str\r\n case self\r\n when X12::Segment\r\n res = find_field(str)\r\n throw Exception.new(\"No field '#{str}' in segment '#{self.name}'\") if EMPTY == res\r\n res.content = args[0].to_s\r\n #puts res.inspect\r\n else\r\n throw Exception.new(\"Illegal assignment to #{meth} of #{self.class}\")\r\n end # case\r\n else\r\n # Retrieval\r\n res = find(str)\r\n yield res if block_given?\r\n res\r\n end # if assignment\r\n end", "code_tokens": ["def", "method_missing", "(", "meth", ",", "*", "args", ",", "&", "block", ")", "str", "=", "meth", ".", "id2name", "str", "=", "str", "[", "1", "..", "str", ".", "length", "]", "if", "str", "=~", "/", "\\d", "/", "# to avoid pure number names like 270, 997, etc.\r", "#puts \"Missing #{str}\"\r", "if", "str", "=~", "/", "/", "# Assignment\r", "str", ".", "chop!", "#puts str\r", "case", "self", "when", "X12", "::", "Segment", "res", "=", "find_field", "(", "str", ")", "throw", "Exception", ".", "new", "(", "\"No field '#{str}' in segment '#{self.name}'\"", ")", "if", "EMPTY", "==", "res", "res", ".", "content", "=", "args", "[", "0", "]", ".", "to_s", "#puts res.inspect\r", "else", "throw", "Exception", ".", "new", "(", "\"Illegal assignment to #{meth} of #{self.class}\"", ")", "end", "# case\r", "else", "# Retrieval\r", "res", "=", "find", "(", "str", ")", "yield", "res", "if", "block_given?", "res", "end", "# if assignment\r", "end"], "docstring": "The main method implementing Ruby-like access methods for nested elements", "docstring_tokens": ["The", "main", "method", "implementing", "Ruby", "-", "like", "access", "methods", "for", "nested", "elements"], "sha": "bb429e2914a42e63e96122695ecfb652a974e54f", "url": "https://github.com/mjpete3/x12/blob/bb429e2914a42e63e96122695ecfb652a974e54f/lib/x12/base.rb#L147-L170", "partition": "test"} {"repo": "mjpete3/x12", "path": "lib/x12/segment.rb", "func_name": "X12.Segment.parse", "original_string": "def parse(str)\r\n s = str\r\n #puts \"Parsing segment #{name} from #{s} with regexp [#{regexp.source}]\"\r\n m = regexp.match(s)\r\n #puts \"Matched #{m ? m[0] : 'nothing'}\"\r\n \r\n return nil unless m\r\n\r\n s = m.post_match\r\n self.parsed_str = m[0]\r\n s = do_repeats(s)\r\n\r\n #puts \"Parsed segment \"+self.inspect\r\n return s\r\n end", "language": "ruby", "code": "def parse(str)\r\n s = str\r\n #puts \"Parsing segment #{name} from #{s} with regexp [#{regexp.source}]\"\r\n m = regexp.match(s)\r\n #puts \"Matched #{m ? m[0] : 'nothing'}\"\r\n \r\n return nil unless m\r\n\r\n s = m.post_match\r\n self.parsed_str = m[0]\r\n s = do_repeats(s)\r\n\r\n #puts \"Parsed segment \"+self.inspect\r\n return s\r\n end", "code_tokens": ["def", "parse", "(", "str", ")", "s", "=", "str", "#puts \"Parsing segment #{name} from #{s} with regexp [#{regexp.source}]\"\r", "m", "=", "regexp", ".", "match", "(", "s", ")", "#puts \"Matched #{m ? m[0] : 'nothing'}\"\r", "return", "nil", "unless", "m", "s", "=", "m", ".", "post_match", "self", ".", "parsed_str", "=", "m", "[", "0", "]", "s", "=", "do_repeats", "(", "s", ")", "#puts \"Parsed segment \"+self.inspect\r", "return", "s", "end"], "docstring": "Parses this segment out of a string, puts the match into value, returns the rest of the string - nil\n if cannot parse", "docstring_tokens": ["Parses", "this", "segment", "out", "of", "a", "string", "puts", "the", "match", "into", "value", "returns", "the", "rest", "of", "the", "string", "-", "nil", "if", "cannot", "parse"], "sha": "bb429e2914a42e63e96122695ecfb652a974e54f", "url": "https://github.com/mjpete3/x12/blob/bb429e2914a42e63e96122695ecfb652a974e54f/lib/x12/segment.rb#L34-L48", "partition": "test"} {"repo": "mjpete3/x12", "path": "lib/x12/segment.rb", "func_name": "X12.Segment.render", "original_string": "def render\r\n self.to_a.inject(''){|repeat_str, i|\r\n if i.repeats.begin < 1 and !i.has_content?\r\n # Skip optional empty segments\r\n repeat_str\r\n else\r\n # Have to render no matter how empty\r\n repeat_str += i.name+i.nodes.reverse.inject(''){|nodes_str, j|\r\n field = j.render\r\n (j.required or nodes_str != '' or field != '') ? field_separator+field+nodes_str : nodes_str\r\n } + segment_separator\r\n end\r\n }\r\n end", "language": "ruby", "code": "def render\r\n self.to_a.inject(''){|repeat_str, i|\r\n if i.repeats.begin < 1 and !i.has_content?\r\n # Skip optional empty segments\r\n repeat_str\r\n else\r\n # Have to render no matter how empty\r\n repeat_str += i.name+i.nodes.reverse.inject(''){|nodes_str, j|\r\n field = j.render\r\n (j.required or nodes_str != '' or field != '') ? field_separator+field+nodes_str : nodes_str\r\n } + segment_separator\r\n end\r\n }\r\n end", "code_tokens": ["def", "render", "self", ".", "to_a", ".", "inject", "(", "''", ")", "{", "|", "repeat_str", ",", "i", "|", "if", "i", ".", "repeats", ".", "begin", "<", "1", "and", "!", "i", ".", "has_content?", "# Skip optional empty segments\r", "repeat_str", "else", "# Have to render no matter how empty\r", "repeat_str", "+=", "i", ".", "name", "+", "i", ".", "nodes", ".", "reverse", ".", "inject", "(", "''", ")", "{", "|", "nodes_str", ",", "j", "|", "field", "=", "j", ".", "render", "(", "j", ".", "required", "or", "nodes_str", "!=", "''", "or", "field", "!=", "''", ")", "?", "field_separator", "+", "field", "+", "nodes_str", ":", "nodes_str", "}", "+", "segment_separator", "end", "}", "end"], "docstring": "parse\n Render all components of this segment as string suitable for EDI", "docstring_tokens": ["parse", "Render", "all", "components", "of", "this", "segment", "as", "string", "suitable", "for", "EDI"], "sha": "bb429e2914a42e63e96122695ecfb652a974e54f", "url": "https://github.com/mjpete3/x12/blob/bb429e2914a42e63e96122695ecfb652a974e54f/lib/x12/segment.rb#L51-L64", "partition": "test"} {"repo": "mjpete3/x12", "path": "lib/x12/segment.rb", "func_name": "X12.Segment.regexp", "original_string": "def regexp\r\n unless @regexp\r\n if self.nodes.find{|i| i.type =~ /^\".+\"$/ }\r\n # It's a very special regexp if there are constant fields\r\n re_str = self.nodes.inject(\"^#{name}#{Regexp.escape(field_separator)}\"){|s, i|\r\n field_re = i.simple_regexp(field_separator, segment_separator)+Regexp.escape(field_separator)+'?'\r\n field_re = \"(#{field_re})?\" unless i.required\r\n s+field_re\r\n } + Regexp.escape(segment_separator)\r\n @regexp = Regexp.new(re_str)\r\n else\r\n # Simple match\r\n @regexp = Regexp.new(\"^#{name}#{Regexp.escape(field_separator)}[^#{Regexp.escape(segment_separator)}]*#{Regexp.escape(segment_separator)}\")\r\n end\r\n #puts sprintf(\"%s %p\", name, @regexp)\r\n end\r\n @regexp\r\n end", "language": "ruby", "code": "def regexp\r\n unless @regexp\r\n if self.nodes.find{|i| i.type =~ /^\".+\"$/ }\r\n # It's a very special regexp if there are constant fields\r\n re_str = self.nodes.inject(\"^#{name}#{Regexp.escape(field_separator)}\"){|s, i|\r\n field_re = i.simple_regexp(field_separator, segment_separator)+Regexp.escape(field_separator)+'?'\r\n field_re = \"(#{field_re})?\" unless i.required\r\n s+field_re\r\n } + Regexp.escape(segment_separator)\r\n @regexp = Regexp.new(re_str)\r\n else\r\n # Simple match\r\n @regexp = Regexp.new(\"^#{name}#{Regexp.escape(field_separator)}[^#{Regexp.escape(segment_separator)}]*#{Regexp.escape(segment_separator)}\")\r\n end\r\n #puts sprintf(\"%s %p\", name, @regexp)\r\n end\r\n @regexp\r\n end", "code_tokens": ["def", "regexp", "unless", "@regexp", "if", "self", ".", "nodes", ".", "find", "{", "|", "i", "|", "i", ".", "type", "=~", "/", "/", "}", "# It's a very special regexp if there are constant fields\r", "re_str", "=", "self", ".", "nodes", ".", "inject", "(", "\"^#{name}#{Regexp.escape(field_separator)}\"", ")", "{", "|", "s", ",", "i", "|", "field_re", "=", "i", ".", "simple_regexp", "(", "field_separator", ",", "segment_separator", ")", "+", "Regexp", ".", "escape", "(", "field_separator", ")", "+", "'?'", "field_re", "=", "\"(#{field_re})?\"", "unless", "i", ".", "required", "s", "+", "field_re", "}", "+", "Regexp", ".", "escape", "(", "segment_separator", ")", "@regexp", "=", "Regexp", ".", "new", "(", "re_str", ")", "else", "# Simple match\r", "@regexp", "=", "Regexp", ".", "new", "(", "\"^#{name}#{Regexp.escape(field_separator)}[^#{Regexp.escape(segment_separator)}]*#{Regexp.escape(segment_separator)}\"", ")", "end", "#puts sprintf(\"%s %p\", name, @regexp)\r", "end", "@regexp", "end"], "docstring": "render\n Returns a regexp that matches this particular segment", "docstring_tokens": ["render", "Returns", "a", "regexp", "that", "matches", "this", "particular", "segment"], "sha": "bb429e2914a42e63e96122695ecfb652a974e54f", "url": "https://github.com/mjpete3/x12/blob/bb429e2914a42e63e96122695ecfb652a974e54f/lib/x12/segment.rb#L67-L84", "partition": "test"} {"repo": "mjpete3/x12", "path": "lib/x12/segment.rb", "func_name": "X12.Segment.find_field", "original_string": "def find_field(str)\r\n #puts \"Finding field [#{str}] in #{self.class} #{name}\"\r\n # If there is such a field to begin with\r\n field_num = nil\r\n self.nodes.each_index{|i|\r\n field_num = i if str == self.nodes[i].name\r\n }\r\n return EMPTY if field_num.nil?\r\n #puts field_num\r\n\r\n # Parse the segment if not parsed already\r\n unless @fields\r\n @fields = self.to_s.chop.split(Regexp.new(Regexp.escape(field_separator)))\r\n self.nodes.each_index{|i| self.nodes[i].content = @fields[i+1] }\r\n end\r\n #puts self.nodes[field_num].inspect\r\n return self.nodes[field_num]\r\n end", "language": "ruby", "code": "def find_field(str)\r\n #puts \"Finding field [#{str}] in #{self.class} #{name}\"\r\n # If there is such a field to begin with\r\n field_num = nil\r\n self.nodes.each_index{|i|\r\n field_num = i if str == self.nodes[i].name\r\n }\r\n return EMPTY if field_num.nil?\r\n #puts field_num\r\n\r\n # Parse the segment if not parsed already\r\n unless @fields\r\n @fields = self.to_s.chop.split(Regexp.new(Regexp.escape(field_separator)))\r\n self.nodes.each_index{|i| self.nodes[i].content = @fields[i+1] }\r\n end\r\n #puts self.nodes[field_num].inspect\r\n return self.nodes[field_num]\r\n end", "code_tokens": ["def", "find_field", "(", "str", ")", "#puts \"Finding field [#{str}] in #{self.class} #{name}\"\r", "# If there is such a field to begin with\r", "field_num", "=", "nil", "self", ".", "nodes", ".", "each_index", "{", "|", "i", "|", "field_num", "=", "i", "if", "str", "==", "self", ".", "nodes", "[", "i", "]", ".", "name", "}", "return", "EMPTY", "if", "field_num", ".", "nil?", "#puts field_num\r", "# Parse the segment if not parsed already\r", "unless", "@fields", "@fields", "=", "self", ".", "to_s", ".", "chop", ".", "split", "(", "Regexp", ".", "new", "(", "Regexp", ".", "escape", "(", "field_separator", ")", ")", ")", "self", ".", "nodes", ".", "each_index", "{", "|", "i", "|", "self", ".", "nodes", "[", "i", "]", ".", "content", "=", "@fields", "[", "i", "+", "1", "]", "}", "end", "#puts self.nodes[field_num].inspect\r", "return", "self", ".", "nodes", "[", "field_num", "]", "end"], "docstring": "Finds a field in the segment. Returns EMPTY if not found.", "docstring_tokens": ["Finds", "a", "field", "in", "the", "segment", ".", "Returns", "EMPTY", "if", "not", "found", "."], "sha": "bb429e2914a42e63e96122695ecfb652a974e54f", "url": "https://github.com/mjpete3/x12/blob/bb429e2914a42e63e96122695ecfb652a974e54f/lib/x12/segment.rb#L87-L104", "partition": "test"} {"repo": "mjpete3/x12", "path": "lib/x12/parser.rb", "func_name": "X12.Parser.parse", "original_string": "def parse(loop_name, str)\r\n loop = @x12_definition[X12::Loop][loop_name]\r\n #puts \"Loops to parse #{@x12_definition[X12::Loop].keys}\"\r\n throw Exception.new(\"Cannot find a definition for loop #{loop_name}\") unless loop\r\n loop = loop.dup\r\n loop.parse(str)\r\n return loop\r\n end", "language": "ruby", "code": "def parse(loop_name, str)\r\n loop = @x12_definition[X12::Loop][loop_name]\r\n #puts \"Loops to parse #{@x12_definition[X12::Loop].keys}\"\r\n throw Exception.new(\"Cannot find a definition for loop #{loop_name}\") unless loop\r\n loop = loop.dup\r\n loop.parse(str)\r\n return loop\r\n end", "code_tokens": ["def", "parse", "(", "loop_name", ",", "str", ")", "loop", "=", "@x12_definition", "[", "X12", "::", "Loop", "]", "[", "loop_name", "]", "#puts \"Loops to parse #{@x12_definition[X12::Loop].keys}\"\r", "throw", "Exception", ".", "new", "(", "\"Cannot find a definition for loop #{loop_name}\"", ")", "unless", "loop", "loop", "=", "loop", ".", "dup", "loop", ".", "parse", "(", "str", ")", "return", "loop", "end"], "docstring": "Creates a parser out of a definition\n initialize\n Parse a loop of a given name out of a string. Throws an exception if the loop name is not defined.", "docstring_tokens": ["Creates", "a", "parser", "out", "of", "a", "definition", "initialize", "Parse", "a", "loop", "of", "a", "given", "name", "out", "of", "a", "string", ".", "Throws", "an", "exception", "if", "the", "loop", "name", "is", "not", "defined", "."], "sha": "bb429e2914a42e63e96122695ecfb652a974e54f", "url": "https://github.com/mjpete3/x12/blob/bb429e2914a42e63e96122695ecfb652a974e54f/lib/x12/parser.rb#L75-L82", "partition": "test"} {"repo": "mjpete3/x12", "path": "lib/x12/parser.rb", "func_name": "X12.Parser.factory", "original_string": "def factory(loop_name)\r\n loop = @x12_definition[X12::Loop][loop_name]\r\n throw Exception.new(\"Cannot find a definition for loop #{loop_name}\") unless loop\r\n loop = loop.dup\r\n return loop\r\n end", "language": "ruby", "code": "def factory(loop_name)\r\n loop = @x12_definition[X12::Loop][loop_name]\r\n throw Exception.new(\"Cannot find a definition for loop #{loop_name}\") unless loop\r\n loop = loop.dup\r\n return loop\r\n end", "code_tokens": ["def", "factory", "(", "loop_name", ")", "loop", "=", "@x12_definition", "[", "X12", "::", "Loop", "]", "[", "loop_name", "]", "throw", "Exception", ".", "new", "(", "\"Cannot find a definition for loop #{loop_name}\"", ")", "unless", "loop", "loop", "=", "loop", ".", "dup", "return", "loop", "end"], "docstring": "parse\n Make an empty loop to be filled out with information", "docstring_tokens": ["parse", "Make", "an", "empty", "loop", "to", "be", "filled", "out", "with", "information"], "sha": "bb429e2914a42e63e96122695ecfb652a974e54f", "url": "https://github.com/mjpete3/x12/blob/bb429e2914a42e63e96122695ecfb652a974e54f/lib/x12/parser.rb#L85-L90", "partition": "test"} {"repo": "mjpete3/x12", "path": "lib/x12/parser.rb", "func_name": "X12.Parser.process_loop", "original_string": "def process_loop(loop)\r\n loop.nodes.each{|i|\r\n case i\r\n when X12::Loop then process_loop(i)\r\n when X12::Segment then process_segment(i) unless i.nodes.size > 0\r\n else return\r\n end\r\n }\r\n end", "language": "ruby", "code": "def process_loop(loop)\r\n loop.nodes.each{|i|\r\n case i\r\n when X12::Loop then process_loop(i)\r\n when X12::Segment then process_segment(i) unless i.nodes.size > 0\r\n else return\r\n end\r\n }\r\n end", "code_tokens": ["def", "process_loop", "(", "loop", ")", "loop", ".", "nodes", ".", "each", "{", "|", "i", "|", "case", "i", "when", "X12", "::", "Loop", "then", "process_loop", "(", "i", ")", "when", "X12", "::", "Segment", "then", "process_segment", "(", "i", ")", "unless", "i", ".", "nodes", ".", "size", ">", "0", "else", "return", "end", "}", "end"], "docstring": "Recursively scan the loop and instantiate fields' definitions for all its\n segments", "docstring_tokens": ["Recursively", "scan", "the", "loop", "and", "instantiate", "fields", "definitions", "for", "all", "its", "segments"], "sha": "bb429e2914a42e63e96122695ecfb652a974e54f", "url": "https://github.com/mjpete3/x12/blob/bb429e2914a42e63e96122695ecfb652a974e54f/lib/x12/parser.rb#L96-L104", "partition": "test"} {"repo": "mjpete3/x12", "path": "lib/x12/parser.rb", "func_name": "X12.Parser.process_segment", "original_string": "def process_segment(segment)\r\n #puts \"Trying to process segment #{segment.inspect}\"\r\n unless @x12_definition[X12::Segment] && @x12_definition[X12::Segment][segment.name]\r\n # Try to find it in a separate file if missing from the @x12_definition structure\r\n initialize(segment.name+'.xml')\r\n segment_definition = @x12_definition[X12::Segment][segment.name]\r\n throw Exception.new(\"Cannot find a definition for segment #{segment.name}\") unless segment_definition\r\n else\r\n segment_definition = @x12_definition[X12::Segment][segment.name]\r\n end\r\n segment_definition.nodes.each_index{|i|\r\n segment.nodes[i] = segment_definition.nodes[i] \r\n # Make sure we have the validation table if any for this field. Try to read one in if missing.\r\n table = segment.nodes[i].validation\r\n if table\r\n unless @x12_definition[X12::Table] && @x12_definition[X12::Table][table]\r\n initialize(table+'.xml')\r\n throw Exception.new(\"Cannot find a definition for table #{table}\") unless @x12_definition[X12::Table] && @x12_definition[X12::Table][table]\r\n end\r\n end\r\n }\r\n end", "language": "ruby", "code": "def process_segment(segment)\r\n #puts \"Trying to process segment #{segment.inspect}\"\r\n unless @x12_definition[X12::Segment] && @x12_definition[X12::Segment][segment.name]\r\n # Try to find it in a separate file if missing from the @x12_definition structure\r\n initialize(segment.name+'.xml')\r\n segment_definition = @x12_definition[X12::Segment][segment.name]\r\n throw Exception.new(\"Cannot find a definition for segment #{segment.name}\") unless segment_definition\r\n else\r\n segment_definition = @x12_definition[X12::Segment][segment.name]\r\n end\r\n segment_definition.nodes.each_index{|i|\r\n segment.nodes[i] = segment_definition.nodes[i] \r\n # Make sure we have the validation table if any for this field. Try to read one in if missing.\r\n table = segment.nodes[i].validation\r\n if table\r\n unless @x12_definition[X12::Table] && @x12_definition[X12::Table][table]\r\n initialize(table+'.xml')\r\n throw Exception.new(\"Cannot find a definition for table #{table}\") unless @x12_definition[X12::Table] && @x12_definition[X12::Table][table]\r\n end\r\n end\r\n }\r\n end", "code_tokens": ["def", "process_segment", "(", "segment", ")", "#puts \"Trying to process segment #{segment.inspect}\"\r", "unless", "@x12_definition", "[", "X12", "::", "Segment", "]", "&&", "@x12_definition", "[", "X12", "::", "Segment", "]", "[", "segment", ".", "name", "]", "# Try to find it in a separate file if missing from the @x12_definition structure\r", "initialize", "(", "segment", ".", "name", "+", "'.xml'", ")", "segment_definition", "=", "@x12_definition", "[", "X12", "::", "Segment", "]", "[", "segment", ".", "name", "]", "throw", "Exception", ".", "new", "(", "\"Cannot find a definition for segment #{segment.name}\"", ")", "unless", "segment_definition", "else", "segment_definition", "=", "@x12_definition", "[", "X12", "::", "Segment", "]", "[", "segment", ".", "name", "]", "end", "segment_definition", ".", "nodes", ".", "each_index", "{", "|", "i", "|", "segment", ".", "nodes", "[", "i", "]", "=", "segment_definition", ".", "nodes", "[", "i", "]", "# Make sure we have the validation table if any for this field. Try to read one in if missing.\r", "table", "=", "segment", ".", "nodes", "[", "i", "]", ".", "validation", "if", "table", "unless", "@x12_definition", "[", "X12", "::", "Table", "]", "&&", "@x12_definition", "[", "X12", "::", "Table", "]", "[", "table", "]", "initialize", "(", "table", "+", "'.xml'", ")", "throw", "Exception", ".", "new", "(", "\"Cannot find a definition for table #{table}\"", ")", "unless", "@x12_definition", "[", "X12", "::", "Table", "]", "&&", "@x12_definition", "[", "X12", "::", "Table", "]", "[", "table", "]", "end", "end", "}", "end"], "docstring": "Instantiate segment's fields as previously defined", "docstring_tokens": ["Instantiate", "segment", "s", "fields", "as", "previously", "defined"], "sha": "bb429e2914a42e63e96122695ecfb652a974e54f", "url": "https://github.com/mjpete3/x12/blob/bb429e2914a42e63e96122695ecfb652a974e54f/lib/x12/parser.rb#L107-L128", "partition": "test"} {"repo": "mjpete3/x12", "path": "lib/x12/loop.rb", "func_name": "X12.Loop.render", "original_string": "def render\r\n if self.has_content?\r\n self.to_a.inject(''){|loop_str, i|\r\n loop_str += i.nodes.inject(''){|nodes_str, j|\r\n nodes_str += j.render\r\n } \r\n }\r\n else\r\n ''\r\n end\r\n end", "language": "ruby", "code": "def render\r\n if self.has_content?\r\n self.to_a.inject(''){|loop_str, i|\r\n loop_str += i.nodes.inject(''){|nodes_str, j|\r\n nodes_str += j.render\r\n } \r\n }\r\n else\r\n ''\r\n end\r\n end", "code_tokens": ["def", "render", "if", "self", ".", "has_content?", "self", ".", "to_a", ".", "inject", "(", "''", ")", "{", "|", "loop_str", ",", "i", "|", "loop_str", "+=", "i", ".", "nodes", ".", "inject", "(", "''", ")", "{", "|", "nodes_str", ",", "j", "|", "nodes_str", "+=", "j", ".", "render", "}", "}", "else", "''", "end", "end"], "docstring": "parse\n Render all components of this loop as string suitable for EDI", "docstring_tokens": ["parse", "Render", "all", "components", "of", "this", "loop", "as", "string", "suitable", "for", "EDI"], "sha": "bb429e2914a42e63e96122695ecfb652a974e54f", "url": "https://github.com/mjpete3/x12/blob/bb429e2914a42e63e96122695ecfb652a974e54f/lib/x12/loop.rb#L64-L74", "partition": "test"} {"repo": "dobtco/formbuilder-rb", "path": "lib/formbuilder/entry.rb", "func_name": "Formbuilder.Entry.calculate_sortable_values", "original_string": "def calculate_sortable_values\n response_fieldable.input_fields.each do |response_field|\n if (x = response_value(response_field)).present?\n get_responses[\"#{response_field.id}_sortable_value\"] = response_field.sortable_value(x)\n end\n end\n\n mark_responses_as_changed!\n end", "language": "ruby", "code": "def calculate_sortable_values\n response_fieldable.input_fields.each do |response_field|\n if (x = response_value(response_field)).present?\n get_responses[\"#{response_field.id}_sortable_value\"] = response_field.sortable_value(x)\n end\n end\n\n mark_responses_as_changed!\n end", "code_tokens": ["def", "calculate_sortable_values", "response_fieldable", ".", "input_fields", ".", "each", "do", "|", "response_field", "|", "if", "(", "x", "=", "response_value", "(", "response_field", ")", ")", ".", "present?", "get_responses", "[", "\"#{response_field.id}_sortable_value\"", "]", "=", "response_field", ".", "sortable_value", "(", "x", ")", "end", "end", "mark_responses_as_changed!", "end"], "docstring": "for manual use, maybe when migrating", "docstring_tokens": ["for", "manual", "use", "maybe", "when", "migrating"], "sha": "e389b7d8778a5ef2b6bab4e2d732e311965a4f3f", "url": "https://github.com/dobtco/formbuilder-rb/blob/e389b7d8778a5ef2b6bab4e2d732e311965a4f3f/lib/formbuilder/entry.rb#L154-L162", "partition": "test"} {"repo": "dobtco/formbuilder-rb", "path": "lib/formbuilder/entry.rb", "func_name": "Formbuilder.Entry.normalize_responses", "original_string": "def normalize_responses\n return if form.blank?\n\n form.response_fields.each do |response_field|\n if (x = self.response_value(response_field))\n response_field.normalize_response(x, get_responses)\n end\n end\n\n mark_responses_as_changed!\n end", "language": "ruby", "code": "def normalize_responses\n return if form.blank?\n\n form.response_fields.each do |response_field|\n if (x = self.response_value(response_field))\n response_field.normalize_response(x, get_responses)\n end\n end\n\n mark_responses_as_changed!\n end", "code_tokens": ["def", "normalize_responses", "return", "if", "form", ".", "blank?", "form", ".", "response_fields", ".", "each", "do", "|", "response_field", "|", "if", "(", "x", "=", "self", ".", "response_value", "(", "response_field", ")", ")", "response_field", ".", "normalize_response", "(", "x", ",", "get_responses", ")", "end", "end", "mark_responses_as_changed!", "end"], "docstring": "Normalizations get run before validation.", "docstring_tokens": ["Normalizations", "get", "run", "before", "validation", "."], "sha": "e389b7d8778a5ef2b6bab4e2d732e311965a4f3f", "url": "https://github.com/dobtco/formbuilder-rb/blob/e389b7d8778a5ef2b6bab4e2d732e311965a4f3f/lib/formbuilder/entry.rb#L165-L175", "partition": "test"} {"repo": "dobtco/formbuilder-rb", "path": "lib/formbuilder/entry.rb", "func_name": "Formbuilder.Entry.audit_responses", "original_string": "def audit_responses\n form.response_fields.each do |response_field|\n response_field.audit_response(self.response_value(response_field), get_responses)\n end\n\n mark_responses_as_changed!\n end", "language": "ruby", "code": "def audit_responses\n form.response_fields.each do |response_field|\n response_field.audit_response(self.response_value(response_field), get_responses)\n end\n\n mark_responses_as_changed!\n end", "code_tokens": ["def", "audit_responses", "form", ".", "response_fields", ".", "each", "do", "|", "response_field", "|", "response_field", ".", "audit_response", "(", "self", ".", "response_value", "(", "response_field", ")", ",", "get_responses", ")", "end", "mark_responses_as_changed!", "end"], "docstring": "Audits get run explicitly.", "docstring_tokens": ["Audits", "get", "run", "explicitly", "."], "sha": "e389b7d8778a5ef2b6bab4e2d732e311965a4f3f", "url": "https://github.com/dobtco/formbuilder-rb/blob/e389b7d8778a5ef2b6bab4e2d732e311965a4f3f/lib/formbuilder/entry.rb#L178-L184", "partition": "test"} {"repo": "plexus/hexp", "path": "lib/hexp/builder.rb", "func_name": "Hexp.Builder.tag!", "original_string": "def tag!(tag, *args, &block)\n text, attributes = nil, {}\n args.each do |arg|\n case arg\n when ::Hash\n attributes.merge!(arg)\n when ::String\n text ||= ''\n text << arg\n end\n end\n @stack << [tag, attributes, text ? [text] : []]\n if block\n _process(&block)\n end\n if @stack.length > 1\n node = @stack.pop\n @stack.last[2] << node\n NodeBuilder.new(node, self)\n else\n NodeBuilder.new(@stack.last, self)\n end\n end", "language": "ruby", "code": "def tag!(tag, *args, &block)\n text, attributes = nil, {}\n args.each do |arg|\n case arg\n when ::Hash\n attributes.merge!(arg)\n when ::String\n text ||= ''\n text << arg\n end\n end\n @stack << [tag, attributes, text ? [text] : []]\n if block\n _process(&block)\n end\n if @stack.length > 1\n node = @stack.pop\n @stack.last[2] << node\n NodeBuilder.new(node, self)\n else\n NodeBuilder.new(@stack.last, self)\n end\n end", "code_tokens": ["def", "tag!", "(", "tag", ",", "*", "args", ",", "&", "block", ")", "text", ",", "attributes", "=", "nil", ",", "{", "}", "args", ".", "each", "do", "|", "arg", "|", "case", "arg", "when", "::", "Hash", "attributes", ".", "merge!", "(", "arg", ")", "when", "::", "String", "text", "||=", "''", "text", "<<", "arg", "end", "end", "@stack", "<<", "[", "tag", ",", "attributes", ",", "text", "?", "[", "text", "]", ":", "[", "]", "]", "if", "block", "_process", "(", "block", ")", "end", "if", "@stack", ".", "length", ">", "1", "node", "=", "@stack", ".", "pop", "@stack", ".", "last", "[", "2", "]", "<<", "node", "NodeBuilder", ".", "new", "(", "node", ",", "self", ")", "else", "NodeBuilder", ".", "new", "(", "@stack", ".", "last", ",", "self", ")", "end", "end"], "docstring": "Construct a new builder, and start building\n\n The recommended way to call this is through `Hexp.build`. If the block\n takes an argument, then builder methods need to be called on that variable.\n\n @example With an explicit builder\n hi = Hexp.build {|html| html.span \"Hello\" ; html.span \" World\"}\n\n @example Without a builder object\n hi = Hexp.build { span \"Hello\" ; span \" World\"}\n\n @param [Symbol] tag\n The tag of the outermost element (optional)\n @param [Array] args\n Extra arguments, a String for a text node, a Hash for attributes\n\n @yieldparam [Hexp::Builder]\n If the block takes an argument it will receive the builder object\n\n @api private\n\n Add a tag (HTML element)\n\n Typically this is called implicitly through method missing, but in case of\n name clashes or dynamically generated tags you can call this directly.\n\n @example\n hexp = Hexp.build :div do\n tag!(:p, \"Oh the code, such sweet joy it brings\")\n end\n hexp.to_html #=> \"

Oh the code, such sweet joy it brings

\"\n\n @param [Symbol] tag\n The tag name, like 'div' or 'head'\n @param [Array] args\n A hash of attributes, or a string to use inside the tag, or both. Multiple\n occurences of each can be specified\n @param [Proc] block\n Builder directives for the contents of the tag\n\n @return [nil]\n\n @api public", "docstring_tokens": ["Construct", "a", "new", "builder", "and", "start", "building"], "sha": "8d5387e00950337d7c0edef06989c876ef45b85d", "url": "https://github.com/plexus/hexp/blob/8d5387e00950337d7c0edef06989c876ef45b85d/lib/hexp/builder.rb#L59-L81", "partition": "test"} {"repo": "plexus/hexp", "path": "lib/hexp/builder.rb", "func_name": "Hexp.Builder.<<", "original_string": "def <<(*args)\n args.each do |arg|\n if arg.respond_to?(:to_hexp)\n @stack.last[2] << arg\n self\n else\n ::Kernel.raise ::Hexp::FormatError, \"Inserting literal HTML into a builder with << is deliberately not supported by Hexp\"\n end\n end\n end", "language": "ruby", "code": "def <<(*args)\n args.each do |arg|\n if arg.respond_to?(:to_hexp)\n @stack.last[2] << arg\n self\n else\n ::Kernel.raise ::Hexp::FormatError, \"Inserting literal HTML into a builder with << is deliberately not supported by Hexp\"\n end\n end\n end", "code_tokens": ["def", "<<", "(", "*", "args", ")", "args", ".", "each", "do", "|", "arg", "|", "if", "arg", ".", "respond_to?", "(", ":to_hexp", ")", "@stack", ".", "last", "[", "2", "]", "<<", "arg", "self", "else", "::", "Kernel", ".", "raise", "::", "Hexp", "::", "FormatError", ",", "\"Inserting literal HTML into a builder with << is deliberately not supported by Hexp\"", "end", "end", "end"], "docstring": "Add Hexp objects to the current tag\n\n Any Hexp::Node or other object implementing to_hexp can be added with\n this operator. Multiple objects can be specified in one call.\n\n Nokogiri and Builder allow inserting of strings containing HTML through\n this operator. Since this would violate the core philosophy of Hexp, and\n open the door for XSS vulnerabilities, we do not support that usage.\n\n If you really want to insert HTML that is already in serialized form,\n consider parsing it to Hexps first\n\n @example\n widget = H[:button, \"click me!\"]\n node = Hexp.build :div do |h|\n h << widget\n end\n node.to_html #=>
\n\n @param [Array<#to_hexp>] args\n Hexpable objects to add to the current tag\n\n @return [Hexp::Builder]\n\n @api public", "docstring_tokens": ["Add", "Hexp", "objects", "to", "the", "current", "tag"], "sha": "8d5387e00950337d7c0edef06989c876ef45b85d", "url": "https://github.com/plexus/hexp/blob/8d5387e00950337d7c0edef06989c876ef45b85d/lib/hexp/builder.rb#L132-L141", "partition": "test"} {"repo": "plexus/hexp", "path": "lib/hexp/node.rb", "func_name": "Hexp.Node.rewrite", "original_string": "def rewrite(css_selector = nil, &block)\n return Rewriter.new(self, block) if css_selector.nil?\n CssSelection.new(self, css_selector).rewrite(&block)\n end", "language": "ruby", "code": "def rewrite(css_selector = nil, &block)\n return Rewriter.new(self, block) if css_selector.nil?\n CssSelection.new(self, css_selector).rewrite(&block)\n end", "code_tokens": ["def", "rewrite", "(", "css_selector", "=", "nil", ",", "&", "block", ")", "return", "Rewriter", ".", "new", "(", "self", ",", "block", ")", "if", "css_selector", ".", "nil?", "CssSelection", ".", "new", "(", "self", ",", "css_selector", ")", ".", "rewrite", "(", "block", ")", "end"], "docstring": "Replace nodes in a tree\n\n With a CSS selector string like +\"form.checkout\"+ you specify the nodes\n you want to operate on. These will be passed one by one into the block.\n The block returns the {Hexp::Node} that will replace the old node, or it\n can replace an +Array+ of nodes to fill the place of the old node.\n\n Because of this you can add one or more nodes, or remove nodes by\n returning an empty array.\n\n @example Remove all script tags\n tree.replace('script') {|_| [] }\n\n @example Wrap each ++ tag into a +

+ tag\n tree.replace('input') do |input|\n H[:p, input]\n end\n\n @param [String] css_selector\n\n @yieldparam [Hexp::Node]\n The matching nodes\n\n @return [Hexp::Node]\n The rewritten tree\n\n @api public", "docstring_tokens": ["Replace", "nodes", "in", "a", "tree"], "sha": "8d5387e00950337d7c0edef06989c876ef45b85d", "url": "https://github.com/plexus/hexp/blob/8d5387e00950337d7c0edef06989c876ef45b85d/lib/hexp/node.rb#L264-L267", "partition": "test"} {"repo": "plexus/hexp", "path": "lib/hexp/node.rb", "func_name": "Hexp.Node.select", "original_string": "def select(css_selector = nil, &block)\n if css_selector\n CssSelection.new(self, css_selector).each(&block)\n else\n Selection.new(self, block)\n end\n end", "language": "ruby", "code": "def select(css_selector = nil, &block)\n if css_selector\n CssSelection.new(self, css_selector).each(&block)\n else\n Selection.new(self, block)\n end\n end", "code_tokens": ["def", "select", "(", "css_selector", "=", "nil", ",", "&", "block", ")", "if", "css_selector", "CssSelection", ".", "new", "(", "self", ",", "css_selector", ")", ".", "each", "(", "block", ")", "else", "Selection", ".", "new", "(", "self", ",", "block", ")", "end", "end"], "docstring": "Select nodes based on a css selector\n\n @param [String] css_selector\n @yieldparam [Hexp::Node]\n\n @return [Hexp::Selector,Hexp::CssSelector]\n\n @api public", "docstring_tokens": ["Select", "nodes", "based", "on", "a", "css", "selector"], "sha": "8d5387e00950337d7c0edef06989c876ef45b85d", "url": "https://github.com/plexus/hexp/blob/8d5387e00950337d7c0edef06989c876ef45b85d/lib/hexp/node.rb#L278-L284", "partition": "test"} {"repo": "TheClimateCorporation/iron_hide", "path": "lib/iron_hide/configuration.rb", "func_name": "IronHide.Configuration.add_configuration", "original_string": "def add_configuration(config_hash)\n config_hash.each do |key, val|\n instance_eval { instance_variable_set(\"@#{key}\",val) }\n self.class.instance_eval { attr_accessor key }\n end\n end", "language": "ruby", "code": "def add_configuration(config_hash)\n config_hash.each do |key, val|\n instance_eval { instance_variable_set(\"@#{key}\",val) }\n self.class.instance_eval { attr_accessor key }\n end\n end", "code_tokens": ["def", "add_configuration", "(", "config_hash", ")", "config_hash", ".", "each", "do", "|", "key", ",", "val", "|", "instance_eval", "{", "instance_variable_set", "(", "\"@#{key}\"", ",", "val", ")", "}", "self", ".", "class", ".", "instance_eval", "{", "attr_accessor", "key", "}", "end", "end"], "docstring": "Extend configuration variables\n\n @param config_hash [Hash]\n\n @example\n IronHide.configuration.add_configuration(couchdb_server: 'http://127.0.0.1:5984')\n IronHide.configuration.couchdb_server)\n #=> 'http://127.0.0.1:5984'\n\n IronHide.configuration.couchdb_server = 'other'\n #=> 'other'", "docstring_tokens": ["Extend", "configuration", "variables"], "sha": "128c08cd3157d6d95bc9b797759de2e35f275dac", "url": "https://github.com/TheClimateCorporation/iron_hide/blob/128c08cd3157d6d95bc9b797759de2e35f275dac/lib/iron_hide/configuration.rb#L28-L33", "partition": "test"} {"repo": "spacewander/posixpsutil", "path": "lib/posixpsutil/common.rb", "func_name": "PosixPsutil.POSIX.pid_exists", "original_string": "def pid_exists(pid)\n return false if pid < 0\n # According to \"man 2 kill\" PID 0 has a special meaning:\n # it refers to <> so we don't want to go any further.\n # If we get here it means this UNIX platform *does* have\n # a process with id 0.\n return true if pid == 0\n\n ::Process.kill(0, pid)\n return true\n rescue Errno::ESRCH # No such process\n return false\n rescue Errno::EPERM\n # EPERM clearly means there's a process to deny access to\n return true\n rescue RangeError # the given pid is invalid.\n return false\nend", "language": "ruby", "code": "def pid_exists(pid)\n return false if pid < 0\n # According to \"man 2 kill\" PID 0 has a special meaning:\n # it refers to <> so we don't want to go any further.\n # If we get here it means this UNIX platform *does* have\n # a process with id 0.\n return true if pid == 0\n\n ::Process.kill(0, pid)\n return true\n rescue Errno::ESRCH # No such process\n return false\n rescue Errno::EPERM\n # EPERM clearly means there's a process to deny access to\n return true\n rescue RangeError # the given pid is invalid.\n return false\nend", "code_tokens": ["def", "pid_exists", "(", "pid", ")", "return", "false", "if", "pid", "<", "0", "# According to \"man 2 kill\" PID 0 has a special meaning:", "# it refers to <> so we don't want to go any further.", "# If we get here it means this UNIX platform *does* have", "# a process with id 0.", "return", "true", "if", "pid", "==", "0", "::", "Process", ".", "kill", "(", "0", ",", "pid", ")", "return", "true", "rescue", "Errno", "::", "ESRCH", "# No such process", "return", "false", "rescue", "Errno", "::", "EPERM", "# EPERM clearly means there's a process to deny access to", "return", "true", "rescue", "RangeError", "# the given pid is invalid.", "return", "false", "end"], "docstring": "Check whether pid exists in the current process table.\"\"\"", "docstring_tokens": ["Check", "whether", "pid", "exists", "in", "the", "current", "process", "table", "."], "sha": "7fe3d1563ada454f46c6be6dc00aac087d389dc7", "url": "https://github.com/spacewander/posixpsutil/blob/7fe3d1563ada454f46c6be6dc00aac087d389dc7/lib/posixpsutil/common.rb#L94-L112", "partition": "test"} {"repo": "spacewander/posixpsutil", "path": "lib/posixpsutil/common.rb", "func_name": "PosixPsutil.POSIX.wait_pid", "original_string": "def wait_pid(pid, timeout=nil)\n\n def check_timeout(delay, stop_at, timeout)\n if timeout\n raise Timeout::Error.new(\"when waiting for (pid=#{pid})\") if Time.now >= stop_at\n end\n sleep(delay)\n delay * 2 < 0.04 ? delay * 2 : 0.04\n end\n\n if timeout\n waitcall = proc { ::Process.wait(pid, ::Process::WNOHANG)}\n stop_at = Time.now + timeout\n else\n waitcall = proc { ::Process.wait(pid)}\n end\n\n delay = 0.0001\n loop do\n begin\n retpid = waitcall.call()\n rescue Errno::EINTR\n delay = check_timeout(delay, stop_at, timeout)\n next\n rescue Errno::ECHILD\n # This has two meanings:\n # - pid is not a child of Process.pid in which case\n # we keep polling until it's gone\n # - pid never existed in the first place\n # In both cases we'll eventually return nil as we\n # can't determine its exit status code.\n loop do\n return nil unless pid_exists(pid)\n delay = check_timeout(delay, stop_at, timeout)\n end\n end\n\n unless retpid\n # WNOHANG was used, pid is still running\n delay = check_timeout(delay, stop_at, timeout)\n next\n end\n\n # process exited due to a signal; return the integer of\n # that signal\n if $?.signaled?\n return $?.termsig\n # process exited using exit(2) system call; return the\n # integer exit(2) system call has been called with\n elsif $?.exited?\n return $?.exitstatus\n else\n # should never happen\n raise RuntimeError.new(\"unknown process exit status\")\n end\n end\nend", "language": "ruby", "code": "def wait_pid(pid, timeout=nil)\n\n def check_timeout(delay, stop_at, timeout)\n if timeout\n raise Timeout::Error.new(\"when waiting for (pid=#{pid})\") if Time.now >= stop_at\n end\n sleep(delay)\n delay * 2 < 0.04 ? delay * 2 : 0.04\n end\n\n if timeout\n waitcall = proc { ::Process.wait(pid, ::Process::WNOHANG)}\n stop_at = Time.now + timeout\n else\n waitcall = proc { ::Process.wait(pid)}\n end\n\n delay = 0.0001\n loop do\n begin\n retpid = waitcall.call()\n rescue Errno::EINTR\n delay = check_timeout(delay, stop_at, timeout)\n next\n rescue Errno::ECHILD\n # This has two meanings:\n # - pid is not a child of Process.pid in which case\n # we keep polling until it's gone\n # - pid never existed in the first place\n # In both cases we'll eventually return nil as we\n # can't determine its exit status code.\n loop do\n return nil unless pid_exists(pid)\n delay = check_timeout(delay, stop_at, timeout)\n end\n end\n\n unless retpid\n # WNOHANG was used, pid is still running\n delay = check_timeout(delay, stop_at, timeout)\n next\n end\n\n # process exited due to a signal; return the integer of\n # that signal\n if $?.signaled?\n return $?.termsig\n # process exited using exit(2) system call; return the\n # integer exit(2) system call has been called with\n elsif $?.exited?\n return $?.exitstatus\n else\n # should never happen\n raise RuntimeError.new(\"unknown process exit status\")\n end\n end\nend", "code_tokens": ["def", "wait_pid", "(", "pid", ",", "timeout", "=", "nil", ")", "def", "check_timeout", "(", "delay", ",", "stop_at", ",", "timeout", ")", "if", "timeout", "raise", "Timeout", "::", "Error", ".", "new", "(", "\"when waiting for (pid=#{pid})\"", ")", "if", "Time", ".", "now", ">=", "stop_at", "end", "sleep", "(", "delay", ")", "delay", "*", "2", "<", "0.04", "?", "delay", "*", "2", ":", "0.04", "end", "if", "timeout", "waitcall", "=", "proc", "{", "::", "Process", ".", "wait", "(", "pid", ",", "::", "Process", "::", "WNOHANG", ")", "}", "stop_at", "=", "Time", ".", "now", "+", "timeout", "else", "waitcall", "=", "proc", "{", "::", "Process", ".", "wait", "(", "pid", ")", "}", "end", "delay", "=", "0.0001", "loop", "do", "begin", "retpid", "=", "waitcall", ".", "call", "(", ")", "rescue", "Errno", "::", "EINTR", "delay", "=", "check_timeout", "(", "delay", ",", "stop_at", ",", "timeout", ")", "next", "rescue", "Errno", "::", "ECHILD", "# This has two meanings:", "# - pid is not a child of Process.pid in which case", "# we keep polling until it's gone", "# - pid never existed in the first place", "# In both cases we'll eventually return nil as we", "# can't determine its exit status code.", "loop", "do", "return", "nil", "unless", "pid_exists", "(", "pid", ")", "delay", "=", "check_timeout", "(", "delay", ",", "stop_at", ",", "timeout", ")", "end", "end", "unless", "retpid", "# WNOHANG was used, pid is still running", "delay", "=", "check_timeout", "(", "delay", ",", "stop_at", ",", "timeout", ")", "next", "end", "# process exited due to a signal; return the integer of", "# that signal", "if", "$?", ".", "signaled?", "return", "$?", ".", "termsig", "# process exited using exit(2) system call; return the", "# integer exit(2) system call has been called with", "elsif", "$?", ".", "exited?", "return", "$?", ".", "exitstatus", "else", "# should never happen", "raise", "RuntimeError", ".", "new", "(", "\"unknown process exit status\"", ")", "end", "end", "end"], "docstring": "Wait for process with pid 'pid' to terminate and return its\n exit status code as an integer.\n\n If pid is not a children of Process.pid (current process) just\n waits until the process disappears and return nil.\n\n If pid does not exist at all return nil immediately.\n\n Raise Timeout::Error on timeout expired.", "docstring_tokens": ["Wait", "for", "process", "with", "pid", "pid", "to", "terminate", "and", "return", "its", "exit", "status", "code", "as", "an", "integer", "."], "sha": "7fe3d1563ada454f46c6be6dc00aac087d389dc7", "url": "https://github.com/spacewander/posixpsutil/blob/7fe3d1563ada454f46c6be6dc00aac087d389dc7/lib/posixpsutil/common.rb#L124-L180", "partition": "test"} {"repo": "esrlabs/esr-rim", "path": "lib/rim/upload_module_helper.rb", "func_name": "RIM.UploadModuleHelper.upload_module_changes", "original_string": "def upload_module_changes(parent_sha1, sha1s)\n remote_path = fetch_module\n # search for the first revision that is not \n tmp_git_path = clone_or_fetch_repository(remote_path, module_tmp_git_path(@remote_path))\n RIM::git_session(tmp_git_path) do |dest|\n local_branch = nil\n remote_branch = nil\n infos = nil\n if @module_info.subdir\n dest_path = File.join([tmp_git_path] + @module_info.subdir.split(\"/\"))\n else\n dest_path = tmp_git_path\n end\n RIM::git_session(@ws_root) do |src|\n infos = get_branches_and_revision_infos(src, dest, parent_sha1, sha1s)\n if infos.branches.size == 1\n remote_branch = infos.branches[0]\n if dest.has_remote_branch?(remote_branch)\n infos.rev_infos.each do |rev_info|\n local_branch = create_update_branch(dest, infos.parent_sha1, rev_info.src_sha1) if !local_branch\n copy_revision_files(\n src,\n rev_info.src_sha1,\n dest_path,\n rev_info.rim_info.ignores\n )\n commit_changes(dest, local_branch, rev_info.src_sha1, rev_info.message)\n end\n else\n raise RimException.new(\"The target revision '#{@module_info.target_revision}' of module #{@module_info.local_path} is not a branch. No push can be performed.\")\n end\n elsif infos.branches.size > 1\n raise RimException.new(\"There are commits for module #{@module_info.local_path} on multiple target revisions (#{infos.branches.join(\", \")}).\")\n end\n end\n # Finally we're done. Push the changes\n if local_branch && dest.rev_sha1(local_branch) != infos.parent_sha1 \n push_branch = @review && @module_info.remote_branch_format && !@module_info.remote_branch_format.empty? \\\n ? @module_info.remote_branch_format % remote_branch : remote_branch\n dest.execute(\"git push #{@remote_url} #{local_branch}:#{push_branch}\")\n dest.execute(\"git checkout --detach #{local_branch}\")\n dest.execute(\"git branch -D #{local_branch}\")\n @logger.info(\"Commited changes for module #{@module_info.local_path} to remote branch #{push_branch}.\")\n else\n @logger.info(\"No changes to module #{@module_info.local_path}.\")\n end \n end\n end", "language": "ruby", "code": "def upload_module_changes(parent_sha1, sha1s)\n remote_path = fetch_module\n # search for the first revision that is not \n tmp_git_path = clone_or_fetch_repository(remote_path, module_tmp_git_path(@remote_path))\n RIM::git_session(tmp_git_path) do |dest|\n local_branch = nil\n remote_branch = nil\n infos = nil\n if @module_info.subdir\n dest_path = File.join([tmp_git_path] + @module_info.subdir.split(\"/\"))\n else\n dest_path = tmp_git_path\n end\n RIM::git_session(@ws_root) do |src|\n infos = get_branches_and_revision_infos(src, dest, parent_sha1, sha1s)\n if infos.branches.size == 1\n remote_branch = infos.branches[0]\n if dest.has_remote_branch?(remote_branch)\n infos.rev_infos.each do |rev_info|\n local_branch = create_update_branch(dest, infos.parent_sha1, rev_info.src_sha1) if !local_branch\n copy_revision_files(\n src,\n rev_info.src_sha1,\n dest_path,\n rev_info.rim_info.ignores\n )\n commit_changes(dest, local_branch, rev_info.src_sha1, rev_info.message)\n end\n else\n raise RimException.new(\"The target revision '#{@module_info.target_revision}' of module #{@module_info.local_path} is not a branch. No push can be performed.\")\n end\n elsif infos.branches.size > 1\n raise RimException.new(\"There are commits for module #{@module_info.local_path} on multiple target revisions (#{infos.branches.join(\", \")}).\")\n end\n end\n # Finally we're done. Push the changes\n if local_branch && dest.rev_sha1(local_branch) != infos.parent_sha1 \n push_branch = @review && @module_info.remote_branch_format && !@module_info.remote_branch_format.empty? \\\n ? @module_info.remote_branch_format % remote_branch : remote_branch\n dest.execute(\"git push #{@remote_url} #{local_branch}:#{push_branch}\")\n dest.execute(\"git checkout --detach #{local_branch}\")\n dest.execute(\"git branch -D #{local_branch}\")\n @logger.info(\"Commited changes for module #{@module_info.local_path} to remote branch #{push_branch}.\")\n else\n @logger.info(\"No changes to module #{@module_info.local_path}.\")\n end \n end\n end", "code_tokens": ["def", "upload_module_changes", "(", "parent_sha1", ",", "sha1s", ")", "remote_path", "=", "fetch_module", "# search for the first revision that is not ", "tmp_git_path", "=", "clone_or_fetch_repository", "(", "remote_path", ",", "module_tmp_git_path", "(", "@remote_path", ")", ")", "RIM", "::", "git_session", "(", "tmp_git_path", ")", "do", "|", "dest", "|", "local_branch", "=", "nil", "remote_branch", "=", "nil", "infos", "=", "nil", "if", "@module_info", ".", "subdir", "dest_path", "=", "File", ".", "join", "(", "[", "tmp_git_path", "]", "+", "@module_info", ".", "subdir", ".", "split", "(", "\"/\"", ")", ")", "else", "dest_path", "=", "tmp_git_path", "end", "RIM", "::", "git_session", "(", "@ws_root", ")", "do", "|", "src", "|", "infos", "=", "get_branches_and_revision_infos", "(", "src", ",", "dest", ",", "parent_sha1", ",", "sha1s", ")", "if", "infos", ".", "branches", ".", "size", "==", "1", "remote_branch", "=", "infos", ".", "branches", "[", "0", "]", "if", "dest", ".", "has_remote_branch?", "(", "remote_branch", ")", "infos", ".", "rev_infos", ".", "each", "do", "|", "rev_info", "|", "local_branch", "=", "create_update_branch", "(", "dest", ",", "infos", ".", "parent_sha1", ",", "rev_info", ".", "src_sha1", ")", "if", "!", "local_branch", "copy_revision_files", "(", "src", ",", "rev_info", ".", "src_sha1", ",", "dest_path", ",", "rev_info", ".", "rim_info", ".", "ignores", ")", "commit_changes", "(", "dest", ",", "local_branch", ",", "rev_info", ".", "src_sha1", ",", "rev_info", ".", "message", ")", "end", "else", "raise", "RimException", ".", "new", "(", "\"The target revision '#{@module_info.target_revision}' of module #{@module_info.local_path} is not a branch. No push can be performed.\"", ")", "end", "elsif", "infos", ".", "branches", ".", "size", ">", "1", "raise", "RimException", ".", "new", "(", "\"There are commits for module #{@module_info.local_path} on multiple target revisions (#{infos.branches.join(\", \")}).\"", ")", "end", "end", "# Finally we're done. Push the changes", "if", "local_branch", "&&", "dest", ".", "rev_sha1", "(", "local_branch", ")", "!=", "infos", ".", "parent_sha1", "push_branch", "=", "@review", "&&", "@module_info", ".", "remote_branch_format", "&&", "!", "@module_info", ".", "remote_branch_format", ".", "empty?", "?", "@module_info", ".", "remote_branch_format", "%", "remote_branch", ":", "remote_branch", "dest", ".", "execute", "(", "\"git push #{@remote_url} #{local_branch}:#{push_branch}\"", ")", "dest", ".", "execute", "(", "\"git checkout --detach #{local_branch}\"", ")", "dest", ".", "execute", "(", "\"git branch -D #{local_branch}\"", ")", "@logger", ".", "info", "(", "\"Commited changes for module #{@module_info.local_path} to remote branch #{push_branch}.\"", ")", "else", "@logger", ".", "info", "(", "\"No changes to module #{@module_info.local_path}.\"", ")", "end", "end", "end"], "docstring": "upload the content of the module", "docstring_tokens": ["upload", "the", "content", "of", "the", "module"], "sha": "2a27ed5e3e0094f1705f6592e52547dd866387cf", "url": "https://github.com/esrlabs/esr-rim/blob/2a27ed5e3e0094f1705f6592e52547dd866387cf/lib/rim/upload_module_helper.rb#L25-L72", "partition": "test"} {"repo": "esrlabs/esr-rim", "path": "lib/rim/upload_module_helper.rb", "func_name": "RIM.UploadModuleHelper.get_branches_and_revision_infos", "original_string": "def get_branches_and_revision_infos(src_session, dest_session, parent_sha1, sha1s)\n infos = []\n branches = []\n dest_parent_sha1 = nil\n (sha1s.size() - 1).step(0, -1) do |i|\n info = get_revision_info(src_session, dest_session, sha1s[i])\n if !info.dest_sha1 && info.rim_info.target_revision\n infos.unshift(info)\n branches.push(info.rim_info.target_revision) if !branches.include?(info.rim_info.target_revision)\n else\n dest_parent_sha1 = info.dest_sha1\n break\n end\n end\n dest_parent_sha1 = get_riminfo_for_revision(src_session, parent_sha1).revision_sha1 if !dest_parent_sha1\n dest_parent_sha1 = infos.first.rim_info.revision_sha1 if !dest_parent_sha1 && !infos.empty?\n return Struct.new(:branches, :parent_sha1, :rev_infos).new(branches, dest_parent_sha1, infos) \n end", "language": "ruby", "code": "def get_branches_and_revision_infos(src_session, dest_session, parent_sha1, sha1s)\n infos = []\n branches = []\n dest_parent_sha1 = nil\n (sha1s.size() - 1).step(0, -1) do |i|\n info = get_revision_info(src_session, dest_session, sha1s[i])\n if !info.dest_sha1 && info.rim_info.target_revision\n infos.unshift(info)\n branches.push(info.rim_info.target_revision) if !branches.include?(info.rim_info.target_revision)\n else\n dest_parent_sha1 = info.dest_sha1\n break\n end\n end\n dest_parent_sha1 = get_riminfo_for_revision(src_session, parent_sha1).revision_sha1 if !dest_parent_sha1\n dest_parent_sha1 = infos.first.rim_info.revision_sha1 if !dest_parent_sha1 && !infos.empty?\n return Struct.new(:branches, :parent_sha1, :rev_infos).new(branches, dest_parent_sha1, infos) \n end", "code_tokens": ["def", "get_branches_and_revision_infos", "(", "src_session", ",", "dest_session", ",", "parent_sha1", ",", "sha1s", ")", "infos", "=", "[", "]", "branches", "=", "[", "]", "dest_parent_sha1", "=", "nil", "(", "sha1s", ".", "size", "(", ")", "-", "1", ")", ".", "step", "(", "0", ",", "-", "1", ")", "do", "|", "i", "|", "info", "=", "get_revision_info", "(", "src_session", ",", "dest_session", ",", "sha1s", "[", "i", "]", ")", "if", "!", "info", ".", "dest_sha1", "&&", "info", ".", "rim_info", ".", "target_revision", "infos", ".", "unshift", "(", "info", ")", "branches", ".", "push", "(", "info", ".", "rim_info", ".", "target_revision", ")", "if", "!", "branches", ".", "include?", "(", "info", ".", "rim_info", ".", "target_revision", ")", "else", "dest_parent_sha1", "=", "info", ".", "dest_sha1", "break", "end", "end", "dest_parent_sha1", "=", "get_riminfo_for_revision", "(", "src_session", ",", "parent_sha1", ")", ".", "revision_sha1", "if", "!", "dest_parent_sha1", "dest_parent_sha1", "=", "infos", ".", "first", ".", "rim_info", ".", "revision_sha1", "if", "!", "dest_parent_sha1", "&&", "!", "infos", ".", "empty?", "return", "Struct", ".", "new", "(", ":branches", ",", ":parent_sha1", ",", ":rev_infos", ")", ".", "new", "(", "branches", ",", "dest_parent_sha1", ",", "infos", ")", "end"], "docstring": "search backwards for all revision infos", "docstring_tokens": ["search", "backwards", "for", "all", "revision", "infos"], "sha": "2a27ed5e3e0094f1705f6592e52547dd866387cf", "url": "https://github.com/esrlabs/esr-rim/blob/2a27ed5e3e0094f1705f6592e52547dd866387cf/lib/rim/upload_module_helper.rb#L75-L92", "partition": "test"} {"repo": "esrlabs/esr-rim", "path": "lib/rim/upload_module_helper.rb", "func_name": "RIM.UploadModuleHelper.get_revision_info", "original_string": "def get_revision_info(src_session, dest_session, src_sha1)\n module_status = StatusBuilder.new.rev_module_status(src_session, src_sha1, @module_info.local_path)\n rim_info = get_riminfo_for_revision(src_session, src_sha1)\n dest_sha1 = dest_session.rev_sha1(\"rim-#{src_sha1}\")\n msg = src_session.execute(\"git show -s --format=%B #{src_sha1}\") \n RevisionInfo.new(module_status && module_status.dirty? ? dest_sha1 : rim_info.revision_sha1, src_sha1, rim_info, msg)\n end", "language": "ruby", "code": "def get_revision_info(src_session, dest_session, src_sha1)\n module_status = StatusBuilder.new.rev_module_status(src_session, src_sha1, @module_info.local_path)\n rim_info = get_riminfo_for_revision(src_session, src_sha1)\n dest_sha1 = dest_session.rev_sha1(\"rim-#{src_sha1}\")\n msg = src_session.execute(\"git show -s --format=%B #{src_sha1}\") \n RevisionInfo.new(module_status && module_status.dirty? ? dest_sha1 : rim_info.revision_sha1, src_sha1, rim_info, msg)\n end", "code_tokens": ["def", "get_revision_info", "(", "src_session", ",", "dest_session", ",", "src_sha1", ")", "module_status", "=", "StatusBuilder", ".", "new", ".", "rev_module_status", "(", "src_session", ",", "src_sha1", ",", "@module_info", ".", "local_path", ")", "rim_info", "=", "get_riminfo_for_revision", "(", "src_session", ",", "src_sha1", ")", "dest_sha1", "=", "dest_session", ".", "rev_sha1", "(", "\"rim-#{src_sha1}\"", ")", "msg", "=", "src_session", ".", "execute", "(", "\"git show -s --format=%B #{src_sha1}\"", ")", "RevisionInfo", ".", "new", "(", "module_status", "&&", "module_status", ".", "dirty?", "?", "dest_sha1", ":", "rim_info", ".", "revision_sha1", ",", "src_sha1", ",", "rim_info", ",", "msg", ")", "end"], "docstring": "collect infos for a revision", "docstring_tokens": ["collect", "infos", "for", "a", "revision"], "sha": "2a27ed5e3e0094f1705f6592e52547dd866387cf", "url": "https://github.com/esrlabs/esr-rim/blob/2a27ed5e3e0094f1705f6592e52547dd866387cf/lib/rim/upload_module_helper.rb#L97-L103", "partition": "test"} {"repo": "esrlabs/esr-rim", "path": "lib/rim/upload_module_helper.rb", "func_name": "RIM.UploadModuleHelper.commit_changes", "original_string": "def commit_changes(session, branch, sha1, msg)\n if session.status.lines.any?\n # add before commit because the path can be below a not yet added path\n session.execute(\"git add --all\")\n msg_file = Tempfile.new('message')\n begin\n msg_file << msg\n msg_file.close\n session.execute(\"git commit -F #{msg_file.path}\")\n ensure\n msg_file.close(true)\n end\n # create tag\n session.execute(\"git tag rim-#{sha1} refs/heads/#{branch}\")\n end\n end", "language": "ruby", "code": "def commit_changes(session, branch, sha1, msg)\n if session.status.lines.any?\n # add before commit because the path can be below a not yet added path\n session.execute(\"git add --all\")\n msg_file = Tempfile.new('message')\n begin\n msg_file << msg\n msg_file.close\n session.execute(\"git commit -F #{msg_file.path}\")\n ensure\n msg_file.close(true)\n end\n # create tag\n session.execute(\"git tag rim-#{sha1} refs/heads/#{branch}\")\n end\n end", "code_tokens": ["def", "commit_changes", "(", "session", ",", "branch", ",", "sha1", ",", "msg", ")", "if", "session", ".", "status", ".", "lines", ".", "any?", "# add before commit because the path can be below a not yet added path", "session", ".", "execute", "(", "\"git add --all\"", ")", "msg_file", "=", "Tempfile", ".", "new", "(", "'message'", ")", "begin", "msg_file", "<<", "msg", "msg_file", ".", "close", "session", ".", "execute", "(", "\"git commit -F #{msg_file.path}\"", ")", "ensure", "msg_file", ".", "close", "(", "true", ")", "end", "# create tag", "session", ".", "execute", "(", "\"git tag rim-#{sha1} refs/heads/#{branch}\"", ")", "end", "end"], "docstring": "commit changes to session", "docstring_tokens": ["commit", "changes", "to", "session"], "sha": "2a27ed5e3e0094f1705f6592e52547dd866387cf", "url": "https://github.com/esrlabs/esr-rim/blob/2a27ed5e3e0094f1705f6592e52547dd866387cf/lib/rim/upload_module_helper.rb#L106-L121", "partition": "test"} {"repo": "esrlabs/esr-rim", "path": "lib/rim/upload_module_helper.rb", "func_name": "RIM.UploadModuleHelper.get_riminfo_for_revision", "original_string": "def get_riminfo_for_revision(session, sha1)\n session.execute(\"git show #{sha1}:#{File.join(@module_info.local_path, RimInfo::InfoFileName)}\") do |out, e|\n return RimInfo.from_s(!e ? out : \"\")\n end\n end", "language": "ruby", "code": "def get_riminfo_for_revision(session, sha1)\n session.execute(\"git show #{sha1}:#{File.join(@module_info.local_path, RimInfo::InfoFileName)}\") do |out, e|\n return RimInfo.from_s(!e ? out : \"\")\n end\n end", "code_tokens": ["def", "get_riminfo_for_revision", "(", "session", ",", "sha1", ")", "session", ".", "execute", "(", "\"git show #{sha1}:#{File.join(@module_info.local_path, RimInfo::InfoFileName)}\"", ")", "do", "|", "out", ",", "e", "|", "return", "RimInfo", ".", "from_s", "(", "!", "e", "?", "out", ":", "\"\"", ")", "end", "end"], "docstring": "get target revision for this module for workspace revision", "docstring_tokens": ["get", "target", "revision", "for", "this", "module", "for", "workspace", "revision"], "sha": "2a27ed5e3e0094f1705f6592e52547dd866387cf", "url": "https://github.com/esrlabs/esr-rim/blob/2a27ed5e3e0094f1705f6592e52547dd866387cf/lib/rim/upload_module_helper.rb#L124-L128", "partition": "test"} {"repo": "esrlabs/esr-rim", "path": "lib/rim/upload_module_helper.rb", "func_name": "RIM.UploadModuleHelper.copy_revision_files", "original_string": "def copy_revision_files(src_session, src_sha1, dest_dir, ignores)\n Dir.mktmpdir do |tmp_dir|\n tmp_dir = Dir.glob(tmp_dir)[0]\n src_session.execute(\"git archive --format tar #{src_sha1} #{@module_info.local_path} | tar -C #{tmp_dir} -xf -\")\n tmp_module_dir = File.join(tmp_dir, @module_info.local_path)\n files = FileHelper.find_matching_files(tmp_module_dir, false, \"/**/*\", File::FNM_DOTMATCH)\n files.delete(\".\")\n files.delete(\"..\")\n files.delete(RimInfo::InfoFileName)\n files -= FileHelper.find_matching_files(tmp_module_dir, false, ignores)\n # have source files now. Now clear destination folder and copy\n prepare_empty_folder(dest_dir, \".git/**/*\")\n files.each do |f|\n src_path = File.join(tmp_module_dir, f)\n if File.file?(src_path)\n path = File.join(dest_dir, f)\n FileUtils.mkdir_p(File.dirname(path))\n FileUtils.cp(src_path, path)\n end \n end\n end \n end", "language": "ruby", "code": "def copy_revision_files(src_session, src_sha1, dest_dir, ignores)\n Dir.mktmpdir do |tmp_dir|\n tmp_dir = Dir.glob(tmp_dir)[0]\n src_session.execute(\"git archive --format tar #{src_sha1} #{@module_info.local_path} | tar -C #{tmp_dir} -xf -\")\n tmp_module_dir = File.join(tmp_dir, @module_info.local_path)\n files = FileHelper.find_matching_files(tmp_module_dir, false, \"/**/*\", File::FNM_DOTMATCH)\n files.delete(\".\")\n files.delete(\"..\")\n files.delete(RimInfo::InfoFileName)\n files -= FileHelper.find_matching_files(tmp_module_dir, false, ignores)\n # have source files now. Now clear destination folder and copy\n prepare_empty_folder(dest_dir, \".git/**/*\")\n files.each do |f|\n src_path = File.join(tmp_module_dir, f)\n if File.file?(src_path)\n path = File.join(dest_dir, f)\n FileUtils.mkdir_p(File.dirname(path))\n FileUtils.cp(src_path, path)\n end \n end\n end \n end", "code_tokens": ["def", "copy_revision_files", "(", "src_session", ",", "src_sha1", ",", "dest_dir", ",", "ignores", ")", "Dir", ".", "mktmpdir", "do", "|", "tmp_dir", "|", "tmp_dir", "=", "Dir", ".", "glob", "(", "tmp_dir", ")", "[", "0", "]", "src_session", ".", "execute", "(", "\"git archive --format tar #{src_sha1} #{@module_info.local_path} | tar -C #{tmp_dir} -xf -\"", ")", "tmp_module_dir", "=", "File", ".", "join", "(", "tmp_dir", ",", "@module_info", ".", "local_path", ")", "files", "=", "FileHelper", ".", "find_matching_files", "(", "tmp_module_dir", ",", "false", ",", "\"/**/*\"", ",", "File", "::", "FNM_DOTMATCH", ")", "files", ".", "delete", "(", "\".\"", ")", "files", ".", "delete", "(", "\"..\"", ")", "files", ".", "delete", "(", "RimInfo", "::", "InfoFileName", ")", "files", "-=", "FileHelper", ".", "find_matching_files", "(", "tmp_module_dir", ",", "false", ",", "ignores", ")", "# have source files now. Now clear destination folder and copy", "prepare_empty_folder", "(", "dest_dir", ",", "\".git/**/*\"", ")", "files", ".", "each", "do", "|", "f", "|", "src_path", "=", "File", ".", "join", "(", "tmp_module_dir", ",", "f", ")", "if", "File", ".", "file?", "(", "src_path", ")", "path", "=", "File", ".", "join", "(", "dest_dir", ",", "f", ")", "FileUtils", ".", "mkdir_p", "(", "File", ".", "dirname", "(", "path", ")", ")", "FileUtils", ".", "cp", "(", "src_path", ",", "path", ")", "end", "end", "end", "end"], "docstring": "copy files from given source revision into destination dir", "docstring_tokens": ["copy", "files", "from", "given", "source", "revision", "into", "destination", "dir"], "sha": "2a27ed5e3e0094f1705f6592e52547dd866387cf", "url": "https://github.com/esrlabs/esr-rim/blob/2a27ed5e3e0094f1705f6592e52547dd866387cf/lib/rim/upload_module_helper.rb#L138-L159", "partition": "test"} {"repo": "esrlabs/esr-rim", "path": "lib/rim/status_builder.rb", "func_name": "RIM.StatusBuilder.rev_history_status", "original_string": "def rev_history_status(git_session, rev, options={})\r\n stop_rev = options[:stop_rev]\r\n relevant_revs = {}\r\n if stop_rev\r\n git_session.execute(\"git rev-list #{rev} \\\"^#{stop_rev}\\\"\").split(\"\\n\").each do |r|\r\n relevant_revs[r] = true\r\n end\r\n elsif options[:gerrit]\r\n # in gerrit mode, stop on all known commits\r\n git_session.execute(\"git rev-list #{rev} --not --all --\").split(\"\\n\").each do |r|\r\n relevant_revs[r] = true\r\n end\r\n else\r\n # remote revs are where we stop traversal\r\n git_session.all_reachable_non_remote_revs(rev).each do |r| \r\n relevant_revs[r] = true\r\n end\r\n end\r\n # make sure we deal only with sha1s\r\n rev = git_session.rev_sha1(rev)\r\n build_rev_history_status(git_session, rev, relevant_revs, {}, :fast => options[:fast])\r\n end", "language": "ruby", "code": "def rev_history_status(git_session, rev, options={})\r\n stop_rev = options[:stop_rev]\r\n relevant_revs = {}\r\n if stop_rev\r\n git_session.execute(\"git rev-list #{rev} \\\"^#{stop_rev}\\\"\").split(\"\\n\").each do |r|\r\n relevant_revs[r] = true\r\n end\r\n elsif options[:gerrit]\r\n # in gerrit mode, stop on all known commits\r\n git_session.execute(\"git rev-list #{rev} --not --all --\").split(\"\\n\").each do |r|\r\n relevant_revs[r] = true\r\n end\r\n else\r\n # remote revs are where we stop traversal\r\n git_session.all_reachable_non_remote_revs(rev).each do |r| \r\n relevant_revs[r] = true\r\n end\r\n end\r\n # make sure we deal only with sha1s\r\n rev = git_session.rev_sha1(rev)\r\n build_rev_history_status(git_session, rev, relevant_revs, {}, :fast => options[:fast])\r\n end", "code_tokens": ["def", "rev_history_status", "(", "git_session", ",", "rev", ",", "options", "=", "{", "}", ")", "stop_rev", "=", "options", "[", ":stop_rev", "]", "relevant_revs", "=", "{", "}", "if", "stop_rev", "git_session", ".", "execute", "(", "\"git rev-list #{rev} \\\"^#{stop_rev}\\\"\"", ")", ".", "split", "(", "\"\\n\"", ")", ".", "each", "do", "|", "r", "|", "relevant_revs", "[", "r", "]", "=", "true", "end", "elsif", "options", "[", ":gerrit", "]", "# in gerrit mode, stop on all known commits\r", "git_session", ".", "execute", "(", "\"git rev-list #{rev} --not --all --\"", ")", ".", "split", "(", "\"\\n\"", ")", ".", "each", "do", "|", "r", "|", "relevant_revs", "[", "r", "]", "=", "true", "end", "else", "# remote revs are where we stop traversal\r", "git_session", ".", "all_reachable_non_remote_revs", "(", "rev", ")", ".", "each", "do", "|", "r", "|", "relevant_revs", "[", "r", "]", "=", "true", "end", "end", "# make sure we deal only with sha1s\r", "rev", "=", "git_session", ".", "rev_sha1", "(", "rev", ")", "build_rev_history_status", "(", "git_session", ",", "rev", ",", "relevant_revs", ",", "{", "}", ",", ":fast", "=>", "options", "[", ":fast", "]", ")", "end"], "docstring": "status object tree for revision rev\n returns the root status object which points to any parent status objects\n note that merge commits mean that the status tree branches\n at the point were the merged branch branched off, the status tree joins\n i.e. the parent status objects are the same at this point\n\n stops traversing a specific branch when a commit is found which is an ancestor\n of :stop_rev or any remote branch if :stop_rev is not provided;\n\n with the :gerrit option, stops traversing on any ancestor of any known commit;\n this is necessary since on gerrit there are no \"remote\" commits;\n at the same time, gerrit doesn't \"know\" commits pushed in the ref-update hook yet\n so the status will be built for the new commits pushed in the ref-update hook\n\n the leafs of the tree are the stop commits or commits which have no parents\n\n with the :fast option set to true, the leafs in the tree will not be checked\n but instead all modules present in those commits will assumed to be clean;\n be aware that this assumption might be wrong!\n if the leaves of the tree are remote commits, the fast check basically tells\n if any of the local commits is dirty or not", "docstring_tokens": ["status", "object", "tree", "for", "revision", "rev", "returns", "the", "root", "status", "object", "which", "points", "to", "any", "parent", "status", "objects", "note", "that", "merge", "commits", "mean", "that", "the", "status", "tree", "branches", "at", "the", "point", "were", "the", "merged", "branch", "branched", "off", "the", "status", "tree", "joins", "i", ".", "e", ".", "the", "parent", "status", "objects", "are", "the", "same", "at", "this", "point"], "sha": "2a27ed5e3e0094f1705f6592e52547dd866387cf", "url": "https://github.com/esrlabs/esr-rim/blob/2a27ed5e3e0094f1705f6592e52547dd866387cf/lib/rim/status_builder.rb#L31-L52", "partition": "test"} {"repo": "esrlabs/esr-rim", "path": "lib/rim/status_builder.rb", "func_name": "RIM.StatusBuilder.rev_status", "original_string": "def rev_status(git_session, rev)\r\n mod_dirs = module_dirs(git_session, rev)\r\n mod_stats = []\r\n # export all relevant modules at once\r\n # this makes status calculation significantly faster compared\r\n # to exporting each module separately \r\n # (e.g. 1.0s instead of 1.5s on linux for a commit with 20 modules)\r\n git_session.within_exported_rev(rev, mod_dirs) do |d|\r\n mod_dirs.each do |rel_path|\r\n mod_stats << build_module_status(d, d+\"/\"+rel_path)\r\n end\r\n end\r\n stat = RevStatus.new(mod_stats)\r\n stat.git_rev = git_session.rev_sha1(rev)\r\n stat\r\n end", "language": "ruby", "code": "def rev_status(git_session, rev)\r\n mod_dirs = module_dirs(git_session, rev)\r\n mod_stats = []\r\n # export all relevant modules at once\r\n # this makes status calculation significantly faster compared\r\n # to exporting each module separately \r\n # (e.g. 1.0s instead of 1.5s on linux for a commit with 20 modules)\r\n git_session.within_exported_rev(rev, mod_dirs) do |d|\r\n mod_dirs.each do |rel_path|\r\n mod_stats << build_module_status(d, d+\"/\"+rel_path)\r\n end\r\n end\r\n stat = RevStatus.new(mod_stats)\r\n stat.git_rev = git_session.rev_sha1(rev)\r\n stat\r\n end", "code_tokens": ["def", "rev_status", "(", "git_session", ",", "rev", ")", "mod_dirs", "=", "module_dirs", "(", "git_session", ",", "rev", ")", "mod_stats", "=", "[", "]", "# export all relevant modules at once\r", "# this makes status calculation significantly faster compared\r", "# to exporting each module separately \r", "# (e.g. 1.0s instead of 1.5s on linux for a commit with 20 modules)\r", "git_session", ".", "within_exported_rev", "(", "rev", ",", "mod_dirs", ")", "do", "|", "d", "|", "mod_dirs", ".", "each", "do", "|", "rel_path", "|", "mod_stats", "<<", "build_module_status", "(", "d", ",", "d", "+", "\"/\"", "+", "rel_path", ")", "end", "end", "stat", "=", "RevStatus", ".", "new", "(", "mod_stats", ")", "stat", ".", "git_rev", "=", "git_session", ".", "rev_sha1", "(", "rev", ")", "stat", "end"], "docstring": "status object for single revision +rev+ without status of ancestors", "docstring_tokens": ["status", "object", "for", "single", "revision", "+", "rev", "+", "without", "status", "of", "ancestors"], "sha": "2a27ed5e3e0094f1705f6592e52547dd866387cf", "url": "https://github.com/esrlabs/esr-rim/blob/2a27ed5e3e0094f1705f6592e52547dd866387cf/lib/rim/status_builder.rb#L55-L70", "partition": "test"} {"repo": "esrlabs/esr-rim", "path": "lib/rim/status_builder.rb", "func_name": "RIM.StatusBuilder.rev_module_status", "original_string": "def rev_module_status(git_session, rev, local_path)\r\n mod_stat = nil\r\n if git_session.execute(\"git ls-tree -r --name-only #{rev}\").split(\"\\n\").include?(File.join(local_path, \".riminfo\"))\r\n git_session.within_exported_rev(rev, [local_path]) do |d|\r\n mod_stat = build_module_status(d, File.join(d, local_path))\r\n end\r\n end\r\n mod_stat\r\n end", "language": "ruby", "code": "def rev_module_status(git_session, rev, local_path)\r\n mod_stat = nil\r\n if git_session.execute(\"git ls-tree -r --name-only #{rev}\").split(\"\\n\").include?(File.join(local_path, \".riminfo\"))\r\n git_session.within_exported_rev(rev, [local_path]) do |d|\r\n mod_stat = build_module_status(d, File.join(d, local_path))\r\n end\r\n end\r\n mod_stat\r\n end", "code_tokens": ["def", "rev_module_status", "(", "git_session", ",", "rev", ",", "local_path", ")", "mod_stat", "=", "nil", "if", "git_session", ".", "execute", "(", "\"git ls-tree -r --name-only #{rev}\"", ")", ".", "split", "(", "\"\\n\"", ")", ".", "include?", "(", "File", ".", "join", "(", "local_path", ",", "\".riminfo\"", ")", ")", "git_session", ".", "within_exported_rev", "(", "rev", ",", "[", "local_path", "]", ")", "do", "|", "d", "|", "mod_stat", "=", "build_module_status", "(", "d", ",", "File", ".", "join", "(", "d", ",", "local_path", ")", ")", "end", "end", "mod_stat", "end"], "docstring": "status object for a single module at +local_path+ in revision +rev+\n returns nil if there is no such module in this revision", "docstring_tokens": ["status", "object", "for", "a", "single", "module", "at", "+", "local_path", "+", "in", "revision", "+", "rev", "+", "returns", "nil", "if", "there", "is", "no", "such", "module", "in", "this", "revision"], "sha": "2a27ed5e3e0094f1705f6592e52547dd866387cf", "url": "https://github.com/esrlabs/esr-rim/blob/2a27ed5e3e0094f1705f6592e52547dd866387cf/lib/rim/status_builder.rb#L74-L82", "partition": "test"} {"repo": "esrlabs/esr-rim", "path": "lib/rim/status_builder.rb", "func_name": "RIM.StatusBuilder.fs_status", "original_string": "def fs_status(dir)\r\n RevStatus.new(\r\n fs_rim_dirs(dir).collect { |d|\r\n build_module_status(dir, d) \r\n })\r\n end", "language": "ruby", "code": "def fs_status(dir)\r\n RevStatus.new(\r\n fs_rim_dirs(dir).collect { |d|\r\n build_module_status(dir, d) \r\n })\r\n end", "code_tokens": ["def", "fs_status", "(", "dir", ")", "RevStatus", ".", "new", "(", "fs_rim_dirs", "(", "dir", ")", ".", "collect", "{", "|", "d", "|", "build_module_status", "(", "dir", ",", "d", ")", "}", ")", "end"], "docstring": "status object for the current file system content of dir\n this can by any directory even outside of any git working copy", "docstring_tokens": ["status", "object", "for", "the", "current", "file", "system", "content", "of", "dir", "this", "can", "by", "any", "directory", "even", "outside", "of", "any", "git", "working", "copy"], "sha": "2a27ed5e3e0094f1705f6592e52547dd866387cf", "url": "https://github.com/esrlabs/esr-rim/blob/2a27ed5e3e0094f1705f6592e52547dd866387cf/lib/rim/status_builder.rb#L86-L91", "partition": "test"} {"repo": "esrlabs/esr-rim", "path": "lib/rim/status_builder.rb", "func_name": "RIM.StatusBuilder.build_rev_history_status", "original_string": "def build_rev_history_status(gs, rev, relevant_revs, status_cache={}, options={})\r\n return status_cache[rev] if status_cache[rev]\r\n stat = nil\r\n if relevant_revs[rev]\r\n parent_revs = gs.parent_revs(rev)\r\n if parent_revs.size > 0\r\n # build status for all parent nodes\r\n parent_stats = parent_revs.collect do |p|\r\n build_rev_history_status(gs, p, relevant_revs, status_cache, options)\r\n end\r\n\r\n # if this is a merge commit with multiple parents\r\n # we decide to use the first commit (git primary parent)\r\n # note that it's not really important, which one we choose\r\n # just make sure to use the same commit when checking for changed files\r\n base_stat = parent_stats.first\r\n \r\n changed_files = gs.changed_files(rev, parent_revs.first)\r\n\r\n # build list of modules in this commit\r\n module_dirs = base_stat.modules.collect{|m| m.dir}\r\n changed_files.each do |f|\r\n if File.basename(f.path) == RimInfo::InfoFileName\r\n if f.kind == :added\r\n module_dirs << File.dirname(f.path)\r\n elsif f.kind == :deleted\r\n module_dirs.delete(File.dirname(f.path))\r\n end\r\n end\r\n end\r\n\r\n # a module needs to be checked if any of the files within were touched\r\n check_dirs = module_dirs.select{|d| changed_files.any?{|f| f.path.start_with?(d)} }\r\n\r\n module_stats = []\r\n # check out all modules to be checked at once\r\n if check_dirs.size > 0\r\n gs.within_exported_rev(rev, check_dirs) do |ws|\r\n check_dirs.each do |d|\r\n module_stats << build_module_status(ws, File.join(ws, d))\r\n end\r\n end\r\n end\r\n (module_dirs - check_dirs).each do |d|\r\n base_mod = base_stat.modules.find{|m| m.dir == d}\r\n module_stats << RevStatus::ModuleStatus.new(d, base_mod.rim_info, base_mod.dirty?)\r\n end\r\n\r\n stat = RevStatus.new(module_stats)\r\n stat.git_rev = gs.rev_sha1(rev)\r\n stat.parents.concat(parent_stats)\r\n else\r\n # no parents, need to do a full check\r\n if options[:fast]\r\n stat = rev_status_fast(gs, rev)\r\n else\r\n stat = rev_status(gs, rev)\r\n end\r\n end\r\n else\r\n # first \"non-relevant\", do the full check\r\n if options[:fast]\r\n stat = rev_status_fast(gs, rev)\r\n else\r\n stat = rev_status(gs, rev)\r\n end\r\n end\r\n status_cache[rev] = stat\r\n end", "language": "ruby", "code": "def build_rev_history_status(gs, rev, relevant_revs, status_cache={}, options={})\r\n return status_cache[rev] if status_cache[rev]\r\n stat = nil\r\n if relevant_revs[rev]\r\n parent_revs = gs.parent_revs(rev)\r\n if parent_revs.size > 0\r\n # build status for all parent nodes\r\n parent_stats = parent_revs.collect do |p|\r\n build_rev_history_status(gs, p, relevant_revs, status_cache, options)\r\n end\r\n\r\n # if this is a merge commit with multiple parents\r\n # we decide to use the first commit (git primary parent)\r\n # note that it's not really important, which one we choose\r\n # just make sure to use the same commit when checking for changed files\r\n base_stat = parent_stats.first\r\n \r\n changed_files = gs.changed_files(rev, parent_revs.first)\r\n\r\n # build list of modules in this commit\r\n module_dirs = base_stat.modules.collect{|m| m.dir}\r\n changed_files.each do |f|\r\n if File.basename(f.path) == RimInfo::InfoFileName\r\n if f.kind == :added\r\n module_dirs << File.dirname(f.path)\r\n elsif f.kind == :deleted\r\n module_dirs.delete(File.dirname(f.path))\r\n end\r\n end\r\n end\r\n\r\n # a module needs to be checked if any of the files within were touched\r\n check_dirs = module_dirs.select{|d| changed_files.any?{|f| f.path.start_with?(d)} }\r\n\r\n module_stats = []\r\n # check out all modules to be checked at once\r\n if check_dirs.size > 0\r\n gs.within_exported_rev(rev, check_dirs) do |ws|\r\n check_dirs.each do |d|\r\n module_stats << build_module_status(ws, File.join(ws, d))\r\n end\r\n end\r\n end\r\n (module_dirs - check_dirs).each do |d|\r\n base_mod = base_stat.modules.find{|m| m.dir == d}\r\n module_stats << RevStatus::ModuleStatus.new(d, base_mod.rim_info, base_mod.dirty?)\r\n end\r\n\r\n stat = RevStatus.new(module_stats)\r\n stat.git_rev = gs.rev_sha1(rev)\r\n stat.parents.concat(parent_stats)\r\n else\r\n # no parents, need to do a full check\r\n if options[:fast]\r\n stat = rev_status_fast(gs, rev)\r\n else\r\n stat = rev_status(gs, rev)\r\n end\r\n end\r\n else\r\n # first \"non-relevant\", do the full check\r\n if options[:fast]\r\n stat = rev_status_fast(gs, rev)\r\n else\r\n stat = rev_status(gs, rev)\r\n end\r\n end\r\n status_cache[rev] = stat\r\n end", "code_tokens": ["def", "build_rev_history_status", "(", "gs", ",", "rev", ",", "relevant_revs", ",", "status_cache", "=", "{", "}", ",", "options", "=", "{", "}", ")", "return", "status_cache", "[", "rev", "]", "if", "status_cache", "[", "rev", "]", "stat", "=", "nil", "if", "relevant_revs", "[", "rev", "]", "parent_revs", "=", "gs", ".", "parent_revs", "(", "rev", ")", "if", "parent_revs", ".", "size", ">", "0", "# build status for all parent nodes\r", "parent_stats", "=", "parent_revs", ".", "collect", "do", "|", "p", "|", "build_rev_history_status", "(", "gs", ",", "p", ",", "relevant_revs", ",", "status_cache", ",", "options", ")", "end", "# if this is a merge commit with multiple parents\r", "# we decide to use the first commit (git primary parent)\r", "# note that it's not really important, which one we choose\r", "# just make sure to use the same commit when checking for changed files\r", "base_stat", "=", "parent_stats", ".", "first", "changed_files", "=", "gs", ".", "changed_files", "(", "rev", ",", "parent_revs", ".", "first", ")", "# build list of modules in this commit\r", "module_dirs", "=", "base_stat", ".", "modules", ".", "collect", "{", "|", "m", "|", "m", ".", "dir", "}", "changed_files", ".", "each", "do", "|", "f", "|", "if", "File", ".", "basename", "(", "f", ".", "path", ")", "==", "RimInfo", "::", "InfoFileName", "if", "f", ".", "kind", "==", ":added", "module_dirs", "<<", "File", ".", "dirname", "(", "f", ".", "path", ")", "elsif", "f", ".", "kind", "==", ":deleted", "module_dirs", ".", "delete", "(", "File", ".", "dirname", "(", "f", ".", "path", ")", ")", "end", "end", "end", "# a module needs to be checked if any of the files within were touched\r", "check_dirs", "=", "module_dirs", ".", "select", "{", "|", "d", "|", "changed_files", ".", "any?", "{", "|", "f", "|", "f", ".", "path", ".", "start_with?", "(", "d", ")", "}", "}", "module_stats", "=", "[", "]", "# check out all modules to be checked at once\r", "if", "check_dirs", ".", "size", ">", "0", "gs", ".", "within_exported_rev", "(", "rev", ",", "check_dirs", ")", "do", "|", "ws", "|", "check_dirs", ".", "each", "do", "|", "d", "|", "module_stats", "<<", "build_module_status", "(", "ws", ",", "File", ".", "join", "(", "ws", ",", "d", ")", ")", "end", "end", "end", "(", "module_dirs", "-", "check_dirs", ")", ".", "each", "do", "|", "d", "|", "base_mod", "=", "base_stat", ".", "modules", ".", "find", "{", "|", "m", "|", "m", ".", "dir", "==", "d", "}", "module_stats", "<<", "RevStatus", "::", "ModuleStatus", ".", "new", "(", "d", ",", "base_mod", ".", "rim_info", ",", "base_mod", ".", "dirty?", ")", "end", "stat", "=", "RevStatus", ".", "new", "(", "module_stats", ")", "stat", ".", "git_rev", "=", "gs", ".", "rev_sha1", "(", "rev", ")", "stat", ".", "parents", ".", "concat", "(", "parent_stats", ")", "else", "# no parents, need to do a full check\r", "if", "options", "[", ":fast", "]", "stat", "=", "rev_status_fast", "(", "gs", ",", "rev", ")", "else", "stat", "=", "rev_status", "(", "gs", ",", "rev", ")", "end", "end", "else", "# first \"non-relevant\", do the full check\r", "if", "options", "[", ":fast", "]", "stat", "=", "rev_status_fast", "(", "gs", ",", "rev", ")", "else", "stat", "=", "rev_status", "(", "gs", ",", "rev", ")", "end", "end", "status_cache", "[", "rev", "]", "=", "stat", "end"], "docstring": "building of the status of an ancestor chain works by checking\n the dirty state of modules only when any files affecting some module\n were changed; otherwise the status of the module in the ancestor is assumed\n\n for this to work, the chain must be walked from older commit to newer ones\n\n at the end of the chain, the status must be calculated in the regular \"non-fast\" way", "docstring_tokens": ["building", "of", "the", "status", "of", "an", "ancestor", "chain", "works", "by", "checking", "the", "dirty", "state", "of", "modules", "only", "when", "any", "files", "affecting", "some", "module", "were", "changed", ";", "otherwise", "the", "status", "of", "the", "module", "in", "the", "ancestor", "is", "assumed"], "sha": "2a27ed5e3e0094f1705f6592e52547dd866387cf", "url": "https://github.com/esrlabs/esr-rim/blob/2a27ed5e3e0094f1705f6592e52547dd866387cf/lib/rim/status_builder.rb#L117-L185", "partition": "test"} {"repo": "esrlabs/esr-rim", "path": "lib/rim/status_builder.rb", "func_name": "RIM.StatusBuilder.rev_status_fast", "original_string": "def rev_status_fast(git_session, rev)\r\n mod_dirs = module_dirs(git_session, rev)\r\n mod_stats = []\r\n git_session.within_exported_rev(rev, mod_dirs.collect{|d| \"#{d}/#{RimInfo::InfoFileName}\"}) do |temp_dir|\r\n mod_dirs.each do |rel_path|\r\n mod_stats << RevStatus::ModuleStatus.new(\r\n rel_path,\r\n RimInfo.from_dir(\"#{temp_dir}/#{rel_path}\"),\r\n # never dirty\r\n false\r\n )\r\n end\r\n end\r\n stat = RevStatus.new(mod_stats)\r\n stat.git_rev = git_session.rev_sha1(rev)\r\n stat\r\n end", "language": "ruby", "code": "def rev_status_fast(git_session, rev)\r\n mod_dirs = module_dirs(git_session, rev)\r\n mod_stats = []\r\n git_session.within_exported_rev(rev, mod_dirs.collect{|d| \"#{d}/#{RimInfo::InfoFileName}\"}) do |temp_dir|\r\n mod_dirs.each do |rel_path|\r\n mod_stats << RevStatus::ModuleStatus.new(\r\n rel_path,\r\n RimInfo.from_dir(\"#{temp_dir}/#{rel_path}\"),\r\n # never dirty\r\n false\r\n )\r\n end\r\n end\r\n stat = RevStatus.new(mod_stats)\r\n stat.git_rev = git_session.rev_sha1(rev)\r\n stat\r\n end", "code_tokens": ["def", "rev_status_fast", "(", "git_session", ",", "rev", ")", "mod_dirs", "=", "module_dirs", "(", "git_session", ",", "rev", ")", "mod_stats", "=", "[", "]", "git_session", ".", "within_exported_rev", "(", "rev", ",", "mod_dirs", ".", "collect", "{", "|", "d", "|", "\"#{d}/#{RimInfo::InfoFileName}\"", "}", ")", "do", "|", "temp_dir", "|", "mod_dirs", ".", "each", "do", "|", "rel_path", "|", "mod_stats", "<<", "RevStatus", "::", "ModuleStatus", ".", "new", "(", "rel_path", ",", "RimInfo", ".", "from_dir", "(", "\"#{temp_dir}/#{rel_path}\"", ")", ",", "# never dirty\r", "false", ")", "end", "end", "stat", "=", "RevStatus", ".", "new", "(", "mod_stats", ")", "stat", ".", "git_rev", "=", "git_session", ".", "rev_sha1", "(", "rev", ")", "stat", "end"], "docstring": "creates a RevStatus object for +rev+ with all modules assumend to be clean", "docstring_tokens": ["creates", "a", "RevStatus", "object", "for", "+", "rev", "+", "with", "all", "modules", "assumend", "to", "be", "clean"], "sha": "2a27ed5e3e0094f1705f6592e52547dd866387cf", "url": "https://github.com/esrlabs/esr-rim/blob/2a27ed5e3e0094f1705f6592e52547dd866387cf/lib/rim/status_builder.rb#L199-L215", "partition": "test"} {"repo": "esrlabs/esr-rim", "path": "lib/rim/sync_helper.rb", "func_name": "RIM.SyncHelper.sync", "original_string": "def sync(message = nil, rebase = nil, split = true)\n # get the name of the current workspace branch\n RIM::git_session(@ws_root) do |s|\n branch = s.current_branch || ''\n rim_branch = \"rim/\" + branch\n branch_sha1 = nil\n changed_modules = nil\n if branch.empty?\n raise RimException.new(\"Not on a git branch.\")\n elsif branch.start_with?(\"rim/\")\n raise RimException.new(\"The current git branch '#{branch}' is a rim integration branch. Please switch to a non rim branch to proceed.\")\n else\n branch = \"refs/heads/#{branch}\"\n branch_sha1 = s.rev_sha1(rim_branch)\n remote_rev = get_latest_remote_revision(s, branch)\n rev = get_latest_clean_path_revision(s, branch, remote_rev)\n if !s.has_branch?(rim_branch) || has_ancestor?(s, branch, s.rev_sha1(rim_branch)) || !has_ancestor?(s, rim_branch, remote_rev)\n s.execute(\"git branch -f #{rim_branch} #{rev}\")\n branch_sha1 = s.rev_sha1(rim_branch)\n end\n remote_url = \"file://\" + @ws_root\n @logger.debug(\"Folder for temporary git repositories: #{@rim_path}\")\n tmpdir = clone_or_fetch_repository(remote_url, module_tmp_git_path(\".ws\"), \"Cloning workspace git...\")\n RIM::git_session(tmpdir) do |tmp_session|\n tmp_session.execute(\"git reset --hard\")\n tmp_session.execute(\"git clean -xdf\")\n # use -f here to prevent git checkout from checking for untracked files which might be overwritten. \n # this is safe since we removed any untracked files before.\n # this is a workaround for a name case problem on windows:\n # if a file's name changes case between the current head and the checkout target,\n # git checkout will report the file with the new name as untracked and will fail\n tmp_session.execute(\"git checkout -B #{rim_branch} -f remotes/origin/#{rim_branch}\")\n changed_modules = sync_modules(tmp_session, message)\n if !split\n tmp_session.execute(\"git reset --soft #{branch_sha1}\")\n commit(tmp_session, message ? message : get_commit_message(changed_modules)) if tmp_session.uncommited_changes?\n end\n tmp_session.execute(\"git push #{remote_url} #{rim_branch}:#{rim_branch}\")\n end\n end\n if !changed_modules.empty?\n if rebase\n s.execute(\"git rebase #{rim_branch}\")\n @logger.info(\"Changes have been commited to branch #{rim_branch} and workspace has been rebased successfully.\")\n else\n @logger.info(\"Changes have been commited to branch #{rim_branch}. Rebase to apply changes to workspace.\")\n end\n else\n @logger.info(\"No changes.\")\n end\n end\n end", "language": "ruby", "code": "def sync(message = nil, rebase = nil, split = true)\n # get the name of the current workspace branch\n RIM::git_session(@ws_root) do |s|\n branch = s.current_branch || ''\n rim_branch = \"rim/\" + branch\n branch_sha1 = nil\n changed_modules = nil\n if branch.empty?\n raise RimException.new(\"Not on a git branch.\")\n elsif branch.start_with?(\"rim/\")\n raise RimException.new(\"The current git branch '#{branch}' is a rim integration branch. Please switch to a non rim branch to proceed.\")\n else\n branch = \"refs/heads/#{branch}\"\n branch_sha1 = s.rev_sha1(rim_branch)\n remote_rev = get_latest_remote_revision(s, branch)\n rev = get_latest_clean_path_revision(s, branch, remote_rev)\n if !s.has_branch?(rim_branch) || has_ancestor?(s, branch, s.rev_sha1(rim_branch)) || !has_ancestor?(s, rim_branch, remote_rev)\n s.execute(\"git branch -f #{rim_branch} #{rev}\")\n branch_sha1 = s.rev_sha1(rim_branch)\n end\n remote_url = \"file://\" + @ws_root\n @logger.debug(\"Folder for temporary git repositories: #{@rim_path}\")\n tmpdir = clone_or_fetch_repository(remote_url, module_tmp_git_path(\".ws\"), \"Cloning workspace git...\")\n RIM::git_session(tmpdir) do |tmp_session|\n tmp_session.execute(\"git reset --hard\")\n tmp_session.execute(\"git clean -xdf\")\n # use -f here to prevent git checkout from checking for untracked files which might be overwritten. \n # this is safe since we removed any untracked files before.\n # this is a workaround for a name case problem on windows:\n # if a file's name changes case between the current head and the checkout target,\n # git checkout will report the file with the new name as untracked and will fail\n tmp_session.execute(\"git checkout -B #{rim_branch} -f remotes/origin/#{rim_branch}\")\n changed_modules = sync_modules(tmp_session, message)\n if !split\n tmp_session.execute(\"git reset --soft #{branch_sha1}\")\n commit(tmp_session, message ? message : get_commit_message(changed_modules)) if tmp_session.uncommited_changes?\n end\n tmp_session.execute(\"git push #{remote_url} #{rim_branch}:#{rim_branch}\")\n end\n end\n if !changed_modules.empty?\n if rebase\n s.execute(\"git rebase #{rim_branch}\")\n @logger.info(\"Changes have been commited to branch #{rim_branch} and workspace has been rebased successfully.\")\n else\n @logger.info(\"Changes have been commited to branch #{rim_branch}. Rebase to apply changes to workspace.\")\n end\n else\n @logger.info(\"No changes.\")\n end\n end\n end", "code_tokens": ["def", "sync", "(", "message", "=", "nil", ",", "rebase", "=", "nil", ",", "split", "=", "true", ")", "# get the name of the current workspace branch", "RIM", "::", "git_session", "(", "@ws_root", ")", "do", "|", "s", "|", "branch", "=", "s", ".", "current_branch", "||", "''", "rim_branch", "=", "\"rim/\"", "+", "branch", "branch_sha1", "=", "nil", "changed_modules", "=", "nil", "if", "branch", ".", "empty?", "raise", "RimException", ".", "new", "(", "\"Not on a git branch.\"", ")", "elsif", "branch", ".", "start_with?", "(", "\"rim/\"", ")", "raise", "RimException", ".", "new", "(", "\"The current git branch '#{branch}' is a rim integration branch. Please switch to a non rim branch to proceed.\"", ")", "else", "branch", "=", "\"refs/heads/#{branch}\"", "branch_sha1", "=", "s", ".", "rev_sha1", "(", "rim_branch", ")", "remote_rev", "=", "get_latest_remote_revision", "(", "s", ",", "branch", ")", "rev", "=", "get_latest_clean_path_revision", "(", "s", ",", "branch", ",", "remote_rev", ")", "if", "!", "s", ".", "has_branch?", "(", "rim_branch", ")", "||", "has_ancestor?", "(", "s", ",", "branch", ",", "s", ".", "rev_sha1", "(", "rim_branch", ")", ")", "||", "!", "has_ancestor?", "(", "s", ",", "rim_branch", ",", "remote_rev", ")", "s", ".", "execute", "(", "\"git branch -f #{rim_branch} #{rev}\"", ")", "branch_sha1", "=", "s", ".", "rev_sha1", "(", "rim_branch", ")", "end", "remote_url", "=", "\"file://\"", "+", "@ws_root", "@logger", ".", "debug", "(", "\"Folder for temporary git repositories: #{@rim_path}\"", ")", "tmpdir", "=", "clone_or_fetch_repository", "(", "remote_url", ",", "module_tmp_git_path", "(", "\".ws\"", ")", ",", "\"Cloning workspace git...\"", ")", "RIM", "::", "git_session", "(", "tmpdir", ")", "do", "|", "tmp_session", "|", "tmp_session", ".", "execute", "(", "\"git reset --hard\"", ")", "tmp_session", ".", "execute", "(", "\"git clean -xdf\"", ")", "# use -f here to prevent git checkout from checking for untracked files which might be overwritten. ", "# this is safe since we removed any untracked files before.", "# this is a workaround for a name case problem on windows:", "# if a file's name changes case between the current head and the checkout target,", "# git checkout will report the file with the new name as untracked and will fail", "tmp_session", ".", "execute", "(", "\"git checkout -B #{rim_branch} -f remotes/origin/#{rim_branch}\"", ")", "changed_modules", "=", "sync_modules", "(", "tmp_session", ",", "message", ")", "if", "!", "split", "tmp_session", ".", "execute", "(", "\"git reset --soft #{branch_sha1}\"", ")", "commit", "(", "tmp_session", ",", "message", "?", "message", ":", "get_commit_message", "(", "changed_modules", ")", ")", "if", "tmp_session", ".", "uncommited_changes?", "end", "tmp_session", ".", "execute", "(", "\"git push #{remote_url} #{rim_branch}:#{rim_branch}\"", ")", "end", "end", "if", "!", "changed_modules", ".", "empty?", "if", "rebase", "s", ".", "execute", "(", "\"git rebase #{rim_branch}\"", ")", "@logger", ".", "info", "(", "\"Changes have been commited to branch #{rim_branch} and workspace has been rebased successfully.\"", ")", "else", "@logger", ".", "info", "(", "\"Changes have been commited to branch #{rim_branch}. Rebase to apply changes to workspace.\"", ")", "end", "else", "@logger", ".", "info", "(", "\"No changes.\"", ")", "end", "end", "end"], "docstring": "sync all module changes into rim branch", "docstring_tokens": ["sync", "all", "module", "changes", "into", "rim", "branch"], "sha": "2a27ed5e3e0094f1705f6592e52547dd866387cf", "url": "https://github.com/esrlabs/esr-rim/blob/2a27ed5e3e0094f1705f6592e52547dd866387cf/lib/rim/sync_helper.rb#L22-L73", "partition": "test"} {"repo": "esrlabs/esr-rim", "path": "lib/rim/sync_helper.rb", "func_name": "RIM.SyncHelper.sync_modules", "original_string": "def sync_modules(session, message)\n module_helpers = []\n @module_infos.each do |module_info|\n module_helpers.push(SyncModuleHelper.new(session.execute_dir, @ws_root, module_info, @logger))\n end\n changed_modules = []\n module_helpers.each do |m|\n @logger.info(\"Synchronizing #{m.module_info.local_path}...\")\n if m.sync(message)\n changed_modules << m.module_info\n end\n end\n changed_modules\n end", "language": "ruby", "code": "def sync_modules(session, message)\n module_helpers = []\n @module_infos.each do |module_info|\n module_helpers.push(SyncModuleHelper.new(session.execute_dir, @ws_root, module_info, @logger))\n end\n changed_modules = []\n module_helpers.each do |m|\n @logger.info(\"Synchronizing #{m.module_info.local_path}...\")\n if m.sync(message)\n changed_modules << m.module_info\n end\n end\n changed_modules\n end", "code_tokens": ["def", "sync_modules", "(", "session", ",", "message", ")", "module_helpers", "=", "[", "]", "@module_infos", ".", "each", "do", "|", "module_info", "|", "module_helpers", ".", "push", "(", "SyncModuleHelper", ".", "new", "(", "session", ".", "execute_dir", ",", "@ws_root", ",", "module_info", ",", "@logger", ")", ")", "end", "changed_modules", "=", "[", "]", "module_helpers", ".", "each", "do", "|", "m", "|", "@logger", ".", "info", "(", "\"Synchronizing #{m.module_info.local_path}...\"", ")", "if", "m", ".", "sync", "(", "message", ")", "changed_modules", "<<", "m", ".", "module_info", "end", "end", "changed_modules", "end"], "docstring": "sync all modules", "docstring_tokens": ["sync", "all", "modules"], "sha": "2a27ed5e3e0094f1705f6592e52547dd866387cf", "url": "https://github.com/esrlabs/esr-rim/blob/2a27ed5e3e0094f1705f6592e52547dd866387cf/lib/rim/sync_helper.rb#L77-L90", "partition": "test"} {"repo": "esrlabs/esr-rim", "path": "lib/rim/sync_helper.rb", "func_name": "RIM.SyncHelper.has_ancestor?", "original_string": "def has_ancestor?(session, rev, ancestor)\n # make sure we deal only with sha1s\n rev = session.rev_sha1(rev)\n return rev == ancestor || session.is_ancestor?(ancestor, rev)\n end", "language": "ruby", "code": "def has_ancestor?(session, rev, ancestor)\n # make sure we deal only with sha1s\n rev = session.rev_sha1(rev)\n return rev == ancestor || session.is_ancestor?(ancestor, rev)\n end", "code_tokens": ["def", "has_ancestor?", "(", "session", ",", "rev", ",", "ancestor", ")", "# make sure we deal only with sha1s", "rev", "=", "session", ".", "rev_sha1", "(", "rev", ")", "return", "rev", "==", "ancestor", "||", "session", ".", "is_ancestor?", "(", "ancestor", ",", "rev", ")", "end"], "docstring": "check whether revision has a given ancestor", "docstring_tokens": ["check", "whether", "revision", "has", "a", "given", "ancestor"], "sha": "2a27ed5e3e0094f1705f6592e52547dd866387cf", "url": "https://github.com/esrlabs/esr-rim/blob/2a27ed5e3e0094f1705f6592e52547dd866387cf/lib/rim/sync_helper.rb#L124-L128", "partition": "test"} {"repo": "esrlabs/esr-rim", "path": "lib/rim/sync_helper.rb", "func_name": "RIM.SyncHelper.get_parent", "original_string": "def get_parent(session, rev)\n parents = session.parent_revs(rev)\n !parents.empty? ? parents.first : nil \n end", "language": "ruby", "code": "def get_parent(session, rev)\n parents = session.parent_revs(rev)\n !parents.empty? ? parents.first : nil \n end", "code_tokens": ["def", "get_parent", "(", "session", ",", "rev", ")", "parents", "=", "session", ".", "parent_revs", "(", "rev", ")", "!", "parents", ".", "empty?", "?", "parents", ".", "first", ":", "nil", "end"], "docstring": "get first parent node", "docstring_tokens": ["get", "first", "parent", "node"], "sha": "2a27ed5e3e0094f1705f6592e52547dd866387cf", "url": "https://github.com/esrlabs/esr-rim/blob/2a27ed5e3e0094f1705f6592e52547dd866387cf/lib/rim/sync_helper.rb#L131-L134", "partition": "test"} {"repo": "esrlabs/esr-rim", "path": "lib/rim/sync_helper.rb", "func_name": "RIM.SyncHelper.get_commit_message", "original_string": "def get_commit_message(changed_modules)\n StringIO.open do |s|\n s.puts \"rim sync.\"\n s.puts\n changed_modules.each do |m|\n s.puts m.local_path\n end\n s.string\n end\n end", "language": "ruby", "code": "def get_commit_message(changed_modules)\n StringIO.open do |s|\n s.puts \"rim sync.\"\n s.puts\n changed_modules.each do |m|\n s.puts m.local_path\n end\n s.string\n end\n end", "code_tokens": ["def", "get_commit_message", "(", "changed_modules", ")", "StringIO", ".", "open", "do", "|", "s", "|", "s", ".", "puts", "\"rim sync.\"", "s", ".", "puts", "changed_modules", ".", "each", "do", "|", "m", "|", "s", ".", "puts", "m", ".", "local_path", "end", "s", ".", "string", "end", "end"], "docstring": "create default commit message from array of changed modules", "docstring_tokens": ["create", "default", "commit", "message", "from", "array", "of", "changed", "modules"], "sha": "2a27ed5e3e0094f1705f6592e52547dd866387cf", "url": "https://github.com/esrlabs/esr-rim/blob/2a27ed5e3e0094f1705f6592e52547dd866387cf/lib/rim/sync_helper.rb#L137-L146", "partition": "test"} {"repo": "spacewander/posixpsutil", "path": "lib/posixpsutil/linux/process.rb", "func_name": "PosixPsutil.PlatformSpecificProcess.pmmap_ext", "original_string": "def pmmap_ext(data)\n pmmap_ext = ['addr', 'perms', 'path', 'rss', 'size', 'pss', \n 'shared_clean', 'shared_dirty', 'private_clean', \n 'private_dirty', 'referenced', 'anonymous', 'swap']\n os_list = []\n data.each do |datum|\n os = OpenStruct.new\n pmmap_ext.each_index {|i| os[pmmap_ext[i]] = datum[i]}\n os_list.push(os)\n end\n os_list\n end", "language": "ruby", "code": "def pmmap_ext(data)\n pmmap_ext = ['addr', 'perms', 'path', 'rss', 'size', 'pss', \n 'shared_clean', 'shared_dirty', 'private_clean', \n 'private_dirty', 'referenced', 'anonymous', 'swap']\n os_list = []\n data.each do |datum|\n os = OpenStruct.new\n pmmap_ext.each_index {|i| os[pmmap_ext[i]] = datum[i]}\n os_list.push(os)\n end\n os_list\n end", "code_tokens": ["def", "pmmap_ext", "(", "data", ")", "pmmap_ext", "=", "[", "'addr'", ",", "'perms'", ",", "'path'", ",", "'rss'", ",", "'size'", ",", "'pss'", ",", "'shared_clean'", ",", "'shared_dirty'", ",", "'private_clean'", ",", "'private_dirty'", ",", "'referenced'", ",", "'anonymous'", ",", "'swap'", "]", "os_list", "=", "[", "]", "data", ".", "each", "do", "|", "datum", "|", "os", "=", "OpenStruct", ".", "new", "pmmap_ext", ".", "each_index", "{", "|", "i", "|", "os", "[", "pmmap_ext", "[", "i", "]", "]", "=", "datum", "[", "i", "]", "}", "os_list", ".", "push", "(", "os", ")", "end", "os_list", "end"], "docstring": "data in pmmap_ext is an Array", "docstring_tokens": ["data", "in", "pmmap_ext", "is", "an", "Array"], "sha": "7fe3d1563ada454f46c6be6dc00aac087d389dc7", "url": "https://github.com/spacewander/posixpsutil/blob/7fe3d1563ada454f46c6be6dc00aac087d389dc7/lib/posixpsutil/linux/process.rb#L477-L488", "partition": "test"} {"repo": "spacewander/posixpsutil", "path": "lib/posixpsutil/linux/process.rb", "func_name": "PosixPsutil.PlatformSpecificProcess.pmmap_grouped", "original_string": "def pmmap_grouped(data)\n pmmap_grouped = ['rss', 'size', 'pss', 'shared_clean', \n 'shared_dirty', 'private_clean', 'private_dirty', \n 'referenced', 'anonymous', 'swap']\n os_list = []\n data.each do |k, v|\n os = OpenStruct.new\n os.path = k\n pmmap_grouped.each_index {|i| os[pmmap_grouped[i]] = v[i]}\n os_list.push(os)\n end\n os_list\n end", "language": "ruby", "code": "def pmmap_grouped(data)\n pmmap_grouped = ['rss', 'size', 'pss', 'shared_clean', \n 'shared_dirty', 'private_clean', 'private_dirty', \n 'referenced', 'anonymous', 'swap']\n os_list = []\n data.each do |k, v|\n os = OpenStruct.new\n os.path = k\n pmmap_grouped.each_index {|i| os[pmmap_grouped[i]] = v[i]}\n os_list.push(os)\n end\n os_list\n end", "code_tokens": ["def", "pmmap_grouped", "(", "data", ")", "pmmap_grouped", "=", "[", "'rss'", ",", "'size'", ",", "'pss'", ",", "'shared_clean'", ",", "'shared_dirty'", ",", "'private_clean'", ",", "'private_dirty'", ",", "'referenced'", ",", "'anonymous'", ",", "'swap'", "]", "os_list", "=", "[", "]", "data", ".", "each", "do", "|", "k", ",", "v", "|", "os", "=", "OpenStruct", ".", "new", "os", ".", "path", "=", "k", "pmmap_grouped", ".", "each_index", "{", "|", "i", "|", "os", "[", "pmmap_grouped", "[", "i", "]", "]", "=", "v", "[", "i", "]", "}", "os_list", ".", "push", "(", "os", ")", "end", "os_list", "end"], "docstring": "data in pmmap_grouped is a Hash", "docstring_tokens": ["data", "in", "pmmap_grouped", "is", "a", "Hash"], "sha": "7fe3d1563ada454f46c6be6dc00aac087d389dc7", "url": "https://github.com/spacewander/posixpsutil/blob/7fe3d1563ada454f46c6be6dc00aac087d389dc7/lib/posixpsutil/linux/process.rb#L491-L503", "partition": "test"} {"repo": "esrlabs/esr-rim", "path": "lib/rim/dirty_check.rb", "func_name": "RIM.DirtyCheck.calc_checksum", "original_string": "def calc_checksum(mi, dir)\r\n if check_required_attributes(mi)\r\n sha1 = Digest::SHA1.new\r\n # all files and directories within dir\r\n files = FileHelper.find_matching_files(dir, false, \"/**/*\", File::FNM_DOTMATCH)\r\n # Dir.glob with FNM_DOTMATCH might return . and ..\r\n files.delete(\".\")\r\n files.delete(\"..\")\r\n # ignore the info file itself\r\n files.delete(RimInfo::InfoFileName)\r\n # ignores defined by user\r\n files -= FileHelper.find_matching_files(dir, false, mi.ignores)\r\n # order of files makes a difference\r\n # sort to eliminate platform specific glob behavior\r\n files.sort!\r\n files.each do |fn|\r\n update_file(sha1, dir, fn)\r\n end\r\n ChecksumAttributes.each do |a|\r\n sha1.update(mi.send(a))\r\n end\r\n sha1.hexdigest\r\n else\r\n # can't calc checksum\r\n nil\r\n end\r\n end", "language": "ruby", "code": "def calc_checksum(mi, dir)\r\n if check_required_attributes(mi)\r\n sha1 = Digest::SHA1.new\r\n # all files and directories within dir\r\n files = FileHelper.find_matching_files(dir, false, \"/**/*\", File::FNM_DOTMATCH)\r\n # Dir.glob with FNM_DOTMATCH might return . and ..\r\n files.delete(\".\")\r\n files.delete(\"..\")\r\n # ignore the info file itself\r\n files.delete(RimInfo::InfoFileName)\r\n # ignores defined by user\r\n files -= FileHelper.find_matching_files(dir, false, mi.ignores)\r\n # order of files makes a difference\r\n # sort to eliminate platform specific glob behavior\r\n files.sort!\r\n files.each do |fn|\r\n update_file(sha1, dir, fn)\r\n end\r\n ChecksumAttributes.each do |a|\r\n sha1.update(mi.send(a))\r\n end\r\n sha1.hexdigest\r\n else\r\n # can't calc checksum\r\n nil\r\n end\r\n end", "code_tokens": ["def", "calc_checksum", "(", "mi", ",", "dir", ")", "if", "check_required_attributes", "(", "mi", ")", "sha1", "=", "Digest", "::", "SHA1", ".", "new", "# all files and directories within dir\r", "files", "=", "FileHelper", ".", "find_matching_files", "(", "dir", ",", "false", ",", "\"/**/*\"", ",", "File", "::", "FNM_DOTMATCH", ")", "# Dir.glob with FNM_DOTMATCH might return . and ..\r", "files", ".", "delete", "(", "\".\"", ")", "files", ".", "delete", "(", "\"..\"", ")", "# ignore the info file itself\r", "files", ".", "delete", "(", "RimInfo", "::", "InfoFileName", ")", "# ignores defined by user\r", "files", "-=", "FileHelper", ".", "find_matching_files", "(", "dir", ",", "false", ",", "mi", ".", "ignores", ")", "# order of files makes a difference\r", "# sort to eliminate platform specific glob behavior\r", "files", ".", "sort!", "files", ".", "each", "do", "|", "fn", "|", "update_file", "(", "sha1", ",", "dir", ",", "fn", ")", "end", "ChecksumAttributes", ".", "each", "do", "|", "a", "|", "sha1", ".", "update", "(", "mi", ".", "send", "(", "a", ")", ")", "end", "sha1", ".", "hexdigest", "else", "# can't calc checksum\r", "nil", "end", "end"], "docstring": "returns nil if checksum can't be calculated due to missing info", "docstring_tokens": ["returns", "nil", "if", "checksum", "can", "t", "be", "calculated", "due", "to", "missing", "info"], "sha": "2a27ed5e3e0094f1705f6592e52547dd866387cf", "url": "https://github.com/esrlabs/esr-rim/blob/2a27ed5e3e0094f1705f6592e52547dd866387cf/lib/rim/dirty_check.rb#L54-L80", "partition": "test"} {"repo": "esrlabs/esr-rim", "path": "lib/rim/git.rb", "func_name": "RIM.GitSession.current_branch", "original_string": "def current_branch\r\n out = execute \"git branch\"\r\n out.split(\"\\n\").each do |l| \r\n if !l.include?('(') && (l =~ /^\\*\\s+(\\S+)/)\r\n return $1\r\n end\r\n end\r\n nil\r\n end", "language": "ruby", "code": "def current_branch\r\n out = execute \"git branch\"\r\n out.split(\"\\n\").each do |l| \r\n if !l.include?('(') && (l =~ /^\\*\\s+(\\S+)/)\r\n return $1\r\n end\r\n end\r\n nil\r\n end", "code_tokens": ["def", "current_branch", "out", "=", "execute", "\"git branch\"", "out", ".", "split", "(", "\"\\n\"", ")", ".", "each", "do", "|", "l", "|", "if", "!", "l", ".", "include?", "(", "'('", ")", "&&", "(", "l", "=~", "/", "\\*", "\\s", "\\S", "/", ")", "return", "$1", "end", "end", "nil", "end"], "docstring": "returns the current branch", "docstring_tokens": ["returns", "the", "current", "branch"], "sha": "2a27ed5e3e0094f1705f6592e52547dd866387cf", "url": "https://github.com/esrlabs/esr-rim/blob/2a27ed5e3e0094f1705f6592e52547dd866387cf/lib/rim/git.rb#L92-L100", "partition": "test"} {"repo": "esrlabs/esr-rim", "path": "lib/rim/git.rb", "func_name": "RIM.GitSession.has_remote_branch?", "original_string": "def has_remote_branch?(branch)\r\n out = execute(\"git ls-remote --heads\")\r\n out.split(\"\\n\").each do |l|\r\n return true if l.split(/\\s+/)[1] == \"refs/heads/#{branch}\"\r\n end\r\n false\r\n end", "language": "ruby", "code": "def has_remote_branch?(branch)\r\n out = execute(\"git ls-remote --heads\")\r\n out.split(\"\\n\").each do |l|\r\n return true if l.split(/\\s+/)[1] == \"refs/heads/#{branch}\"\r\n end\r\n false\r\n end", "code_tokens": ["def", "has_remote_branch?", "(", "branch", ")", "out", "=", "execute", "(", "\"git ls-remote --heads\"", ")", "out", ".", "split", "(", "\"\\n\"", ")", ".", "each", "do", "|", "l", "|", "return", "true", "if", "l", ".", "split", "(", "/", "\\s", "/", ")", "[", "1", "]", "==", "\"refs/heads/#{branch}\"", "end", "false", "end"], "docstring": "check whether remote branch exists", "docstring_tokens": ["check", "whether", "remote", "branch", "exists"], "sha": "2a27ed5e3e0094f1705f6592e52547dd866387cf", "url": "https://github.com/esrlabs/esr-rim/blob/2a27ed5e3e0094f1705f6592e52547dd866387cf/lib/rim/git.rb#L110-L116", "partition": "test"} {"repo": "esrlabs/esr-rim", "path": "lib/rim/git.rb", "func_name": "RIM.GitSession.rev_sha1", "original_string": "def rev_sha1(rev)\r\n sha1 = nil\r\n execute \"git rev-list -n 1 #{rev} --\" do |out, e|\r\n sha1 = out.strip if !e\r\n end\r\n sha1\r\n end", "language": "ruby", "code": "def rev_sha1(rev)\r\n sha1 = nil\r\n execute \"git rev-list -n 1 #{rev} --\" do |out, e|\r\n sha1 = out.strip if !e\r\n end\r\n sha1\r\n end", "code_tokens": ["def", "rev_sha1", "(", "rev", ")", "sha1", "=", "nil", "execute", "\"git rev-list -n 1 #{rev} --\"", "do", "|", "out", ",", "e", "|", "sha1", "=", "out", ".", "strip", "if", "!", "e", "end", "sha1", "end"], "docstring": "returns the SHA-1 representation of rev", "docstring_tokens": ["returns", "the", "SHA", "-", "1", "representation", "of", "rev"], "sha": "2a27ed5e3e0094f1705f6592e52547dd866387cf", "url": "https://github.com/esrlabs/esr-rim/blob/2a27ed5e3e0094f1705f6592e52547dd866387cf/lib/rim/git.rb#L140-L146", "partition": "test"} {"repo": "esrlabs/esr-rim", "path": "lib/rim/git.rb", "func_name": "RIM.GitSession.rev_infos", "original_string": "def rev_infos(rev, desired)\r\n info = {}\r\n desired.each_pair do |key, value|\r\n execute \"git log -1 --format=#{value} #{rev} --\" do |out, e|\r\n info[key] = out.strip if !e\r\n end\r\n end\r\n info\r\n end", "language": "ruby", "code": "def rev_infos(rev, desired)\r\n info = {}\r\n desired.each_pair do |key, value|\r\n execute \"git log -1 --format=#{value} #{rev} --\" do |out, e|\r\n info[key] = out.strip if !e\r\n end\r\n end\r\n info\r\n end", "code_tokens": ["def", "rev_infos", "(", "rev", ",", "desired", ")", "info", "=", "{", "}", "desired", ".", "each_pair", "do", "|", "key", ",", "value", "|", "execute", "\"git log -1 --format=#{value} #{rev} --\"", "do", "|", "out", ",", "e", "|", "info", "[", "key", "]", "=", "out", ".", "strip", "if", "!", "e", "end", "end", "info", "end"], "docstring": "returns some informations about a revision", "docstring_tokens": ["returns", "some", "informations", "about", "a", "revision"], "sha": "2a27ed5e3e0094f1705f6592e52547dd866387cf", "url": "https://github.com/esrlabs/esr-rim/blob/2a27ed5e3e0094f1705f6592e52547dd866387cf/lib/rim/git.rb#L149-L157", "partition": "test"} {"repo": "esrlabs/esr-rim", "path": "lib/rim/git.rb", "func_name": "RIM.GitSession.remote_branch_revs", "original_string": "def remote_branch_revs\r\n out = execute \"git show-ref\"\r\n out.split(\"\\n\").collect { |l|\r\n if l =~ /refs\\/remotes\\//\r\n l.split[0]\r\n else\r\n nil\r\n end\r\n }.compact\r\n end", "language": "ruby", "code": "def remote_branch_revs\r\n out = execute \"git show-ref\"\r\n out.split(\"\\n\").collect { |l|\r\n if l =~ /refs\\/remotes\\//\r\n l.split[0]\r\n else\r\n nil\r\n end\r\n }.compact\r\n end", "code_tokens": ["def", "remote_branch_revs", "out", "=", "execute", "\"git show-ref\"", "out", ".", "split", "(", "\"\\n\"", ")", ".", "collect", "{", "|", "l", "|", "if", "l", "=~", "/", "\\/", "\\/", "/", "l", ".", "split", "[", "0", "]", "else", "nil", "end", "}", ".", "compact", "end"], "docstring": "returns the SHA-1 representations of the heads of all remote branches", "docstring_tokens": ["returns", "the", "SHA", "-", "1", "representations", "of", "the", "heads", "of", "all", "remote", "branches"], "sha": "2a27ed5e3e0094f1705f6592e52547dd866387cf", "url": "https://github.com/esrlabs/esr-rim/blob/2a27ed5e3e0094f1705f6592e52547dd866387cf/lib/rim/git.rb#L160-L169", "partition": "test"} {"repo": "esrlabs/esr-rim", "path": "lib/rim/git.rb", "func_name": "RIM.GitSession.export_rev", "original_string": "def export_rev(rev, dir, paths=[])\r\n paths = paths.dup\r\n loop do\r\n path_args = \"\"\r\n # max command line length on Windows XP and higher is 8191\r\n # consider the following extra characters which will be added:\r\n # up to 3 paths in execute, 1 path for tar, max path length 260 = 1040\r\n # plus some \"glue\" characters, plus the last path item with 260 max;\r\n # use 6000 to be on the safe side\r\n while !paths.empty? && path_args.size < 6000\r\n path_args << \" \"\r\n path_args << paths.shift\r\n end\r\n execute \"git archive --format tar #{rev} #{path_args} | tar -C #{dir} -xf -\"\r\n break if paths.empty?\r\n end\r\n end", "language": "ruby", "code": "def export_rev(rev, dir, paths=[])\r\n paths = paths.dup\r\n loop do\r\n path_args = \"\"\r\n # max command line length on Windows XP and higher is 8191\r\n # consider the following extra characters which will be added:\r\n # up to 3 paths in execute, 1 path for tar, max path length 260 = 1040\r\n # plus some \"glue\" characters, plus the last path item with 260 max;\r\n # use 6000 to be on the safe side\r\n while !paths.empty? && path_args.size < 6000\r\n path_args << \" \"\r\n path_args << paths.shift\r\n end\r\n execute \"git archive --format tar #{rev} #{path_args} | tar -C #{dir} -xf -\"\r\n break if paths.empty?\r\n end\r\n end", "code_tokens": ["def", "export_rev", "(", "rev", ",", "dir", ",", "paths", "=", "[", "]", ")", "paths", "=", "paths", ".", "dup", "loop", "do", "path_args", "=", "\"\"", "# max command line length on Windows XP and higher is 8191\r", "# consider the following extra characters which will be added:\r", "# up to 3 paths in execute, 1 path for tar, max path length 260 = 1040\r", "# plus some \"glue\" characters, plus the last path item with 260 max;\r", "# use 6000 to be on the safe side\r", "while", "!", "paths", ".", "empty?", "&&", "path_args", ".", "size", "<", "6000", "path_args", "<<", "\" \"", "path_args", "<<", "paths", ".", "shift", "end", "execute", "\"git archive --format tar #{rev} #{path_args} | tar -C #{dir} -xf -\"", "break", "if", "paths", ".", "empty?", "end", "end"], "docstring": "export file contents of rev to dir\n if +paths+ is given and non-empty, checks out only those parts of the filesystem tree\n does not remove any files from dir which existed before", "docstring_tokens": ["export", "file", "contents", "of", "rev", "to", "dir", "if", "+", "paths", "+", "is", "given", "and", "non", "-", "empty", "checks", "out", "only", "those", "parts", "of", "the", "filesystem", "tree", "does", "not", "remove", "any", "files", "from", "dir", "which", "existed", "before"], "sha": "2a27ed5e3e0094f1705f6592e52547dd866387cf", "url": "https://github.com/esrlabs/esr-rim/blob/2a27ed5e3e0094f1705f6592e52547dd866387cf/lib/rim/git.rb#L180-L196", "partition": "test"} {"repo": "esrlabs/esr-rim", "path": "lib/rim/git.rb", "func_name": "RIM.GitSession.within_exported_rev", "original_string": "def within_exported_rev(rev, paths=[])\r\n Dir.mktmpdir(\"rim\") do |d|\r\n d = Dir.glob(d)[0]\r\n c = File.join(d, \"content\")\r\n FileUtils.mkdir(c)\r\n export_rev(rev, c, paths)\r\n # return contents of yielded block\r\n # mktmpdir returns value return by our block\r\n yield c\r\n FileUtils.rm_rf(c)\r\n # retry to delete if it hasn't been deleted yet\r\n # this could be due to Windows keeping the files locked for some time\r\n # this is especially a problem if the machine is at its limits\r\n retries = 600\r\n while File.exist?(c) && retries > 0\r\n sleep(0.1)\r\n FileUtils.rm_rf(c)\r\n retries -= 1\r\n end\r\n if File.exist?(c)\r\n @logger.warn \"could not delete temp dir: #{c}\"\r\n end\r\n end\r\n end", "language": "ruby", "code": "def within_exported_rev(rev, paths=[])\r\n Dir.mktmpdir(\"rim\") do |d|\r\n d = Dir.glob(d)[0]\r\n c = File.join(d, \"content\")\r\n FileUtils.mkdir(c)\r\n export_rev(rev, c, paths)\r\n # return contents of yielded block\r\n # mktmpdir returns value return by our block\r\n yield c\r\n FileUtils.rm_rf(c)\r\n # retry to delete if it hasn't been deleted yet\r\n # this could be due to Windows keeping the files locked for some time\r\n # this is especially a problem if the machine is at its limits\r\n retries = 600\r\n while File.exist?(c) && retries > 0\r\n sleep(0.1)\r\n FileUtils.rm_rf(c)\r\n retries -= 1\r\n end\r\n if File.exist?(c)\r\n @logger.warn \"could not delete temp dir: #{c}\"\r\n end\r\n end\r\n end", "code_tokens": ["def", "within_exported_rev", "(", "rev", ",", "paths", "=", "[", "]", ")", "Dir", ".", "mktmpdir", "(", "\"rim\"", ")", "do", "|", "d", "|", "d", "=", "Dir", ".", "glob", "(", "d", ")", "[", "0", "]", "c", "=", "File", ".", "join", "(", "d", ",", "\"content\"", ")", "FileUtils", ".", "mkdir", "(", "c", ")", "export_rev", "(", "rev", ",", "c", ",", "paths", ")", "# return contents of yielded block\r", "# mktmpdir returns value return by our block\r", "yield", "c", "FileUtils", ".", "rm_rf", "(", "c", ")", "# retry to delete if it hasn't been deleted yet\r", "# this could be due to Windows keeping the files locked for some time\r", "# this is especially a problem if the machine is at its limits\r", "retries", "=", "600", "while", "File", ".", "exist?", "(", "c", ")", "&&", "retries", ">", "0", "sleep", "(", "0.1", ")", "FileUtils", ".", "rm_rf", "(", "c", ")", "retries", "-=", "1", "end", "if", "File", ".", "exist?", "(", "c", ")", "@logger", ".", "warn", "\"could not delete temp dir: #{c}\"", "end", "end", "end"], "docstring": "checks out rev to a temporary directory and yields this directory to the given block\n if +paths+ is given and non-empty, checks out only those parts of the filesystem tree\n returns the value returned by the block", "docstring_tokens": ["checks", "out", "rev", "to", "a", "temporary", "directory", "and", "yields", "this", "directory", "to", "the", "given", "block", "if", "+", "paths", "+", "is", "given", "and", "non", "-", "empty", "checks", "out", "only", "those", "parts", "of", "the", "filesystem", "tree", "returns", "the", "value", "returned", "by", "the", "block"], "sha": "2a27ed5e3e0094f1705f6592e52547dd866387cf", "url": "https://github.com/esrlabs/esr-rim/blob/2a27ed5e3e0094f1705f6592e52547dd866387cf/lib/rim/git.rb#L201-L224", "partition": "test"} {"repo": "esrlabs/esr-rim", "path": "lib/rim/upload_helper.rb", "func_name": "RIM.UploadHelper.upload", "original_string": "def upload\n # get the name of the current workspace branch\n RIM::git_session(@ws_root) do |s|\n branch = s.current_branch\n if branch.nil?\n raise RimException.new(\"Not on a git branch.\")\n elsif !branch.start_with?(\"rim/\")\n begin\n sha1 = s.rev_sha1(branch)\n @logger.info(\"Uploading modules...\")\n upload_modules(get_upload_revisions(s, sha1))\n ensure\n s.execute(\"git checkout -B #{branch}\")\n end\n else\n raise RimException.new(\"The current git branch '#{branch}' is a rim integration branch. Please switch to a non rim branch to proceed.\")\n end\n end\n end", "language": "ruby", "code": "def upload\n # get the name of the current workspace branch\n RIM::git_session(@ws_root) do |s|\n branch = s.current_branch\n if branch.nil?\n raise RimException.new(\"Not on a git branch.\")\n elsif !branch.start_with?(\"rim/\")\n begin\n sha1 = s.rev_sha1(branch)\n @logger.info(\"Uploading modules...\")\n upload_modules(get_upload_revisions(s, sha1))\n ensure\n s.execute(\"git checkout -B #{branch}\")\n end\n else\n raise RimException.new(\"The current git branch '#{branch}' is a rim integration branch. Please switch to a non rim branch to proceed.\")\n end\n end\n end", "code_tokens": ["def", "upload", "# get the name of the current workspace branch", "RIM", "::", "git_session", "(", "@ws_root", ")", "do", "|", "s", "|", "branch", "=", "s", ".", "current_branch", "if", "branch", ".", "nil?", "raise", "RimException", ".", "new", "(", "\"Not on a git branch.\"", ")", "elsif", "!", "branch", ".", "start_with?", "(", "\"rim/\"", ")", "begin", "sha1", "=", "s", ".", "rev_sha1", "(", "branch", ")", "@logger", ".", "info", "(", "\"Uploading modules...\"", ")", "upload_modules", "(", "get_upload_revisions", "(", "s", ",", "sha1", ")", ")", "ensure", "s", ".", "execute", "(", "\"git checkout -B #{branch}\"", ")", "end", "else", "raise", "RimException", ".", "new", "(", "\"The current git branch '#{branch}' is a rim integration branch. Please switch to a non rim branch to proceed.\"", ")", "end", "end", "end"], "docstring": "upload all module changes into corresponding remote repositories", "docstring_tokens": ["upload", "all", "module", "changes", "into", "corresponding", "remote", "repositories"], "sha": "2a27ed5e3e0094f1705f6592e52547dd866387cf", "url": "https://github.com/esrlabs/esr-rim/blob/2a27ed5e3e0094f1705f6592e52547dd866387cf/lib/rim/upload_helper.rb#L15-L33", "partition": "test"} {"repo": "esrlabs/esr-rim", "path": "lib/rim/upload_helper.rb", "func_name": "RIM.UploadHelper.upload_modules", "original_string": "def upload_modules(info)\n each_module_parallel(\"uploading\", @module_helpers) do |m|\n m.upload(info.parent, info.sha1s)\n end\n end", "language": "ruby", "code": "def upload_modules(info)\n each_module_parallel(\"uploading\", @module_helpers) do |m|\n m.upload(info.parent, info.sha1s)\n end\n end", "code_tokens": ["def", "upload_modules", "(", "info", ")", "each_module_parallel", "(", "\"uploading\"", ",", "@module_helpers", ")", "do", "|", "m", "|", "m", ".", "upload", "(", "info", ".", "parent", ",", "info", ".", "sha1s", ")", "end", "end"], "docstring": "upload all modules", "docstring_tokens": ["upload", "all", "modules"], "sha": "2a27ed5e3e0094f1705f6592e52547dd866387cf", "url": "https://github.com/esrlabs/esr-rim/blob/2a27ed5e3e0094f1705f6592e52547dd866387cf/lib/rim/upload_helper.rb#L42-L46", "partition": "test"} {"repo": "esrlabs/esr-rim", "path": "lib/rim/upload_helper.rb", "func_name": "RIM.UploadHelper.get_upload_revisions", "original_string": "def get_upload_revisions(session, rev)\n # remote revs are where we stop traversal\n non_remote_revs = {}\n session.all_reachable_non_remote_revs(rev).each do |r| \n non_remote_revs[r] = true\n end\n revisions = []\n # make sure we deal only with sha1s\n rev = session.rev_sha1(rev)\n while rev && non_remote_revs[rev]\n revisions.push(rev)\n parents = session.parent_revs(rev)\n rev = parents.size > 0 ? parents.first : nil\n end\n Struct.new(:parent, :sha1s).new(rev, revisions.reverse!)\n end", "language": "ruby", "code": "def get_upload_revisions(session, rev)\n # remote revs are where we stop traversal\n non_remote_revs = {}\n session.all_reachable_non_remote_revs(rev).each do |r| \n non_remote_revs[r] = true\n end\n revisions = []\n # make sure we deal only with sha1s\n rev = session.rev_sha1(rev)\n while rev && non_remote_revs[rev]\n revisions.push(rev)\n parents = session.parent_revs(rev)\n rev = parents.size > 0 ? parents.first : nil\n end\n Struct.new(:parent, :sha1s).new(rev, revisions.reverse!)\n end", "code_tokens": ["def", "get_upload_revisions", "(", "session", ",", "rev", ")", "# remote revs are where we stop traversal", "non_remote_revs", "=", "{", "}", "session", ".", "all_reachable_non_remote_revs", "(", "rev", ")", ".", "each", "do", "|", "r", "|", "non_remote_revs", "[", "r", "]", "=", "true", "end", "revisions", "=", "[", "]", "# make sure we deal only with sha1s", "rev", "=", "session", ".", "rev_sha1", "(", "rev", ")", "while", "rev", "&&", "non_remote_revs", "[", "rev", "]", "revisions", ".", "push", "(", "rev", ")", "parents", "=", "session", ".", "parent_revs", "(", "rev", ")", "rev", "=", "parents", ".", "size", ">", "0", "?", "parents", ".", "first", ":", "nil", "end", "Struct", ".", "new", "(", ":parent", ",", ":sha1s", ")", ".", "new", "(", "rev", ",", "revisions", ".", "reverse!", ")", "end"], "docstring": "get revisions to upload i.e. the revisions up to the last remote revision\n the function returns the revisions in order of appearal i.e. the oldest first", "docstring_tokens": ["get", "revisions", "to", "upload", "i", ".", "e", ".", "the", "revisions", "up", "to", "the", "last", "remote", "revision", "the", "function", "returns", "the", "revisions", "in", "order", "of", "appearal", "i", ".", "e", ".", "the", "oldest", "first"], "sha": "2a27ed5e3e0094f1705f6592e52547dd866387cf", "url": "https://github.com/esrlabs/esr-rim/blob/2a27ed5e3e0094f1705f6592e52547dd866387cf/lib/rim/upload_helper.rb#L50-L65", "partition": "test"} {"repo": "esrlabs/esr-rim", "path": "lib/rim/module_helper.rb", "func_name": "RIM.ModuleHelper.fetch_module", "original_string": "def fetch_module\n FileUtils.mkdir_p git_path\n RIM::git_session(git_path) do |s|\n if !File.exist?(git_path + \"/config\")\n s.execute(\"git clone --mirror #{@remote_url} #{git_path}\") do |out, e|\n raise RimException.new(\"Remote repository '#{@remote_url}' of module '#{@module_info.local_path}' not found.\") if e\n end\n else\n s.execute(\"git remote update\")\n end\n end\n git_path\n end", "language": "ruby", "code": "def fetch_module\n FileUtils.mkdir_p git_path\n RIM::git_session(git_path) do |s|\n if !File.exist?(git_path + \"/config\")\n s.execute(\"git clone --mirror #{@remote_url} #{git_path}\") do |out, e|\n raise RimException.new(\"Remote repository '#{@remote_url}' of module '#{@module_info.local_path}' not found.\") if e\n end\n else\n s.execute(\"git remote update\")\n end\n end\n git_path\n end", "code_tokens": ["def", "fetch_module", "FileUtils", ".", "mkdir_p", "git_path", "RIM", "::", "git_session", "(", "git_path", ")", "do", "|", "s", "|", "if", "!", "File", ".", "exist?", "(", "git_path", "+", "\"/config\"", ")", "s", ".", "execute", "(", "\"git clone --mirror #{@remote_url} #{git_path}\"", ")", "do", "|", "out", ",", "e", "|", "raise", "RimException", ".", "new", "(", "\"Remote repository '#{@remote_url}' of module '#{@module_info.local_path}' not found.\"", ")", "if", "e", "end", "else", "s", ".", "execute", "(", "\"git remote update\"", ")", "end", "end", "git_path", "end"], "docstring": "fetch module +mod+ into the .rim folder\n works both for initial fetch and updates", "docstring_tokens": ["fetch", "module", "+", "mod", "+", "into", "the", ".", "rim", "folder", "works", "both", "for", "initial", "fetch", "and", "updates"], "sha": "2a27ed5e3e0094f1705f6592e52547dd866387cf", "url": "https://github.com/esrlabs/esr-rim/blob/2a27ed5e3e0094f1705f6592e52547dd866387cf/lib/rim/module_helper.rb#L25-L37", "partition": "test"} {"repo": "ginty/cranky", "path": "lib/cranky/job.rb", "func_name": "Cranky.Job.assign", "original_string": "def assign(attribute, value)\n unless value == :skip || attribute == :class\n if item.respond_to?(\"#{attribute}=\")\n item.send(\"#{attribute}=\", value)\n elsif item.is_a?(Hash)\n item[attribute] = value\n end\n end\n end", "language": "ruby", "code": "def assign(attribute, value)\n unless value == :skip || attribute == :class\n if item.respond_to?(\"#{attribute}=\")\n item.send(\"#{attribute}=\", value)\n elsif item.is_a?(Hash)\n item[attribute] = value\n end\n end\n end", "code_tokens": ["def", "assign", "(", "attribute", ",", "value", ")", "unless", "value", "==", ":skip", "||", "attribute", "==", ":class", "if", "item", ".", "respond_to?", "(", "\"#{attribute}=\"", ")", "item", ".", "send", "(", "\"#{attribute}=\"", ",", "value", ")", "elsif", "item", ".", "is_a?", "(", "Hash", ")", "item", "[", "attribute", "]", "=", "value", "end", "end", "end"], "docstring": "Assign the value to the given attribute of the item", "docstring_tokens": ["Assign", "the", "value", "to", "the", "given", "attribute", "of", "the", "item"], "sha": "ca7176da2b8e69c37669afa03fee1a242338e690", "url": "https://github.com/ginty/cranky/blob/ca7176da2b8e69c37669afa03fee1a242338e690/lib/cranky/job.rb#L34-L42", "partition": "test"} {"repo": "ginty/cranky", "path": "lib/cranky/factory.rb", "func_name": "Cranky.FactoryBase.debug", "original_string": "def debug(*args)\n item = build(*args)\n invalid_item = Array(item).find(&:invalid?)\n if invalid_item\n if invalid_item.errors.respond_to?(:messages)\n errors = invalid_item.errors.messages\n else\n errors = invalid_item.errors\n end\n raise \"Oops, the #{invalid_item.class} created by the Factory has the following errors: #{errors}\"\n end\n item\n end", "language": "ruby", "code": "def debug(*args)\n item = build(*args)\n invalid_item = Array(item).find(&:invalid?)\n if invalid_item\n if invalid_item.errors.respond_to?(:messages)\n errors = invalid_item.errors.messages\n else\n errors = invalid_item.errors\n end\n raise \"Oops, the #{invalid_item.class} created by the Factory has the following errors: #{errors}\"\n end\n item\n end", "code_tokens": ["def", "debug", "(", "*", "args", ")", "item", "=", "build", "(", "args", ")", "invalid_item", "=", "Array", "(", "item", ")", ".", "find", "(", ":invalid?", ")", "if", "invalid_item", "if", "invalid_item", ".", "errors", ".", "respond_to?", "(", ":messages", ")", "errors", "=", "invalid_item", ".", "errors", ".", "messages", "else", "errors", "=", "invalid_item", ".", "errors", "end", "raise", "\"Oops, the #{invalid_item.class} created by the Factory has the following errors: #{errors}\"", "end", "item", "end"], "docstring": "Can be left in your tests as an alternative to build and to warn if your factory method\n ever starts producing invalid instances", "docstring_tokens": ["Can", "be", "left", "in", "your", "tests", "as", "an", "alternative", "to", "build", "and", "to", "warn", "if", "your", "factory", "method", "ever", "starts", "producing", "invalid", "instances"], "sha": "ca7176da2b8e69c37669afa03fee1a242338e690", "url": "https://github.com/ginty/cranky/blob/ca7176da2b8e69c37669afa03fee1a242338e690/lib/cranky/factory.rb#L55-L67", "partition": "test"} {"repo": "ginty/cranky", "path": "lib/cranky/factory.rb", "func_name": "Cranky.FactoryBase.crank_it", "original_string": "def crank_it(what, overrides)\n if what.to_s =~ /(.*)_attrs$/\n what = $1\n overrides = overrides.merge(:_return_attributes => true)\n end\n item = \"TBD\"\n new_job(what, overrides) do\n item = self.send(what) # Invoke the factory method\n item = apply_traits(what, item)\n end\n item\n end", "language": "ruby", "code": "def crank_it(what, overrides)\n if what.to_s =~ /(.*)_attrs$/\n what = $1\n overrides = overrides.merge(:_return_attributes => true)\n end\n item = \"TBD\"\n new_job(what, overrides) do\n item = self.send(what) # Invoke the factory method\n item = apply_traits(what, item)\n end\n item\n end", "code_tokens": ["def", "crank_it", "(", "what", ",", "overrides", ")", "if", "what", ".", "to_s", "=~", "/", "/", "what", "=", "$1", "overrides", "=", "overrides", ".", "merge", "(", ":_return_attributes", "=>", "true", ")", "end", "item", "=", "\"TBD\"", "new_job", "(", "what", ",", "overrides", ")", "do", "item", "=", "self", ".", "send", "(", "what", ")", "# Invoke the factory method", "item", "=", "apply_traits", "(", "what", ",", "item", ")", "end", "item", "end"], "docstring": "Execute the requested factory method, crank out the target object!", "docstring_tokens": ["Execute", "the", "requested", "factory", "method", "crank", "out", "the", "target", "object!"], "sha": "ca7176da2b8e69c37669afa03fee1a242338e690", "url": "https://github.com/ginty/cranky/blob/ca7176da2b8e69c37669afa03fee1a242338e690/lib/cranky/factory.rb#L138-L149", "partition": "test"} {"repo": "neighborland/pres", "path": "lib/pres/view_delegation.rb", "func_name": "Pres.ViewDelegation.method_missing", "original_string": "def method_missing(method, *args, &block)\n if view_context.respond_to?(method, true)\n view_context.send(method, *args, &block)\n else\n super\n end\n end", "language": "ruby", "code": "def method_missing(method, *args, &block)\n if view_context.respond_to?(method, true)\n view_context.send(method, *args, &block)\n else\n super\n end\n end", "code_tokens": ["def", "method_missing", "(", "method", ",", "*", "args", ",", "&", "block", ")", "if", "view_context", ".", "respond_to?", "(", "method", ",", "true", ")", "view_context", ".", "send", "(", "method", ",", "args", ",", "block", ")", "else", "super", "end", "end"], "docstring": "Send missing methods to view_context first", "docstring_tokens": ["Send", "missing", "methods", "to", "view_context", "first"], "sha": "62cb44ed5824b7ba86656529648f0266556b5cb7", "url": "https://github.com/neighborland/pres/blob/62cb44ed5824b7ba86656529648f0266556b5cb7/lib/pres/view_delegation.rb#L10-L16", "partition": "test"} {"repo": "neighborland/pres", "path": "lib/pres/presents.rb", "func_name": "Pres.Presents.present", "original_string": "def present(object, presenter: nil, **args)\n if object.respond_to?(:to_ary)\n object.map { |item| present(item, presenter: presenter, **args) }\n else\n presenter ||= presenter_klass(object)\n wrapper = presenter.new(object, view_context, **args)\n block_given? ? yield(wrapper) : wrapper\n end\n end", "language": "ruby", "code": "def present(object, presenter: nil, **args)\n if object.respond_to?(:to_ary)\n object.map { |item| present(item, presenter: presenter, **args) }\n else\n presenter ||= presenter_klass(object)\n wrapper = presenter.new(object, view_context, **args)\n block_given? ? yield(wrapper) : wrapper\n end\n end", "code_tokens": ["def", "present", "(", "object", ",", "presenter", ":", "nil", ",", "**", "args", ")", "if", "object", ".", "respond_to?", "(", ":to_ary", ")", "object", ".", "map", "{", "|", "item", "|", "present", "(", "item", ",", "presenter", ":", "presenter", ",", "**", "args", ")", "}", "else", "presenter", "||=", "presenter_klass", "(", "object", ")", "wrapper", "=", "presenter", ".", "new", "(", "object", ",", "view_context", ",", "**", "args", ")", "block_given?", "?", "yield", "(", "wrapper", ")", ":", "wrapper", "end", "end"], "docstring": "Wrap an object or collection of objects with a presenter class.\n\n object - A ruby object. May be nil.\n presenter - A Presenter class (optional)\n args - optional hash / kwargs passed to the presenter\n\n An instance of a presenter class is created. The class is\n one of the following:\n - the `presenter` argument\n - `Pres::Presenter` if object is nil\n - object.presenter_class (if that method is defined)\n - the default presenter class for the object\n (for example: User -> UserPresenter)\n\n Examples\n\n user = User.new\n present(user, cool: true)\n => # ...>\n\n user = User.new\n present(user) do |up|\n up.something\n end\n up => # ...>\n\n user = User.new\n present(user, presenter: NiceUserPresenter, cool: true)\n => # ...>\n\n class User\n def presenter_class\n MyPresenter\n end\n end\n user = User.new\n present(user)\n => # ...>\n\n present([user])\n => [# ...>]\n\n present(nil)\n => [#]\n\n Returns a new Presenter object or array of new Presenter objects\n Yields a new Presenter object if a block is given", "docstring_tokens": ["Wrap", "an", "object", "or", "collection", "of", "objects", "with", "a", "presenter", "class", "."], "sha": "62cb44ed5824b7ba86656529648f0266556b5cb7", "url": "https://github.com/neighborland/pres/blob/62cb44ed5824b7ba86656529648f0266556b5cb7/lib/pres/presents.rb#L54-L62", "partition": "test"} {"repo": "alphagov/gem_publisher", "path": "lib/gem_publisher/pusher.rb", "func_name": "GemPublisher.Pusher.push", "original_string": "def push(gem, method, options = {})\n push_command = PUSH_METHODS[method.to_s] or raise \"Unknown Gem push method #{method.inspect}.\"\n push_command += [gem]\n push_command += [\"--as\", options[:as]] if options[:as]\n @cli_facade.execute(*push_command)\n end", "language": "ruby", "code": "def push(gem, method, options = {})\n push_command = PUSH_METHODS[method.to_s] or raise \"Unknown Gem push method #{method.inspect}.\"\n push_command += [gem]\n push_command += [\"--as\", options[:as]] if options[:as]\n @cli_facade.execute(*push_command)\n end", "code_tokens": ["def", "push", "(", "gem", ",", "method", ",", "options", "=", "{", "}", ")", "push_command", "=", "PUSH_METHODS", "[", "method", ".", "to_s", "]", "or", "raise", "\"Unknown Gem push method #{method.inspect}.\"", "push_command", "+=", "[", "gem", "]", "push_command", "+=", "[", "\"--as\"", ",", "options", "[", ":as", "]", "]", "if", "options", "[", ":as", "]", "@cli_facade", ".", "execute", "(", "push_command", ")", "end"], "docstring": "Publish the gem.\n\n Supported options:\n :as - specify a shared account to publish the gem (Gemfury only)", "docstring_tokens": ["Publish", "the", "gem", "."], "sha": "a6d324cca69a123339fa25417db080b0e2691743", "url": "https://github.com/alphagov/gem_publisher/blob/a6d324cca69a123339fa25417db080b0e2691743/lib/gem_publisher/pusher.rb#L18-L23", "partition": "test"} {"repo": "v0dro/interpolation", "path": "lib/interpolation/one_dimensional.rb", "func_name": "Interpolation.OneDimensional.interpolate", "original_string": "def interpolate interpolant\n case @opts[:type]\n when :linear\n for_each (interpolant) { |x| linear_interpolation(x) }\n when :cubic\n cubic_spline_interpolation interpolant\n else\n raise ArgumentError, \"1 D interpolation of type #{@opts[:type]} not supported\"\n end\n end", "language": "ruby", "code": "def interpolate interpolant\n case @opts[:type]\n when :linear\n for_each (interpolant) { |x| linear_interpolation(x) }\n when :cubic\n cubic_spline_interpolation interpolant\n else\n raise ArgumentError, \"1 D interpolation of type #{@opts[:type]} not supported\"\n end\n end", "code_tokens": ["def", "interpolate", "interpolant", "case", "@opts", "[", ":type", "]", "when", ":linear", "for_each", "(", "interpolant", ")", "{", "|", "x", "|", "linear_interpolation", "(", "x", ")", "}", "when", ":cubic", "cubic_spline_interpolation", "interpolant", "else", "raise", "ArgumentError", ",", "\"1 D interpolation of type #{@opts[:type]} not supported\"", "end", "end"], "docstring": "Constructor for all One Dimensional interpolation operations.\n\n The function values to be supplied to this class are of the form y = f(x).\n\n Henceforth, y will be referred to as ordinate and x as absicca. If absicca\n and ordinate arrays are not of the same length, then the effective size used\n for interpolation will be MIN(x.size, y.size).\n\n ==== Arguments\n\n * +x+ - The collection of absiccas. Must be a 1 D NMatrix or ruby Array.\n\n * +y+ - The collection of ordinates corresponding to the absicca. 'y' can\n either be a 1D NMatrix or Array OR a 2D NMatrix. In case y contains\n multiple columns, the interpolation is carried out on each column,\n unless specified.\n\n * +opts+ - Various options for carrying out the interpolation.\n\n ==== Options\n\n * +:type+ - The kind of interpolation that the user wants to perform. Should be\n specified as a symbol. Defaults to linear. Only linear and cubic\n interpolation supported as of now. Cubic interpolation done with splines.\n\n * +:sorted+ - Set this option as *true* if the absicca collection is supplied in\n the arguments in a sorted manner. If not supplied, it will be assumed\n that absiccas are not sorted and they will sorted be sorted anyway.\n\n * +:axis+ - In case of a multidimensional ordinate matrix, specify the column over\n which interpolation must be performed. *axis* starts indexing from 0 and should be\n lower than the number of columns in the ordinate matrix.\n\n * +:precision+ - Specifies the precision of the interpolated values returned. Defaults\n to 3.\n\n * +:yp1+ - First derivative of the 0th point (cubic spline).\n\n * +:ypn+ - First derivative of the last (n-1)th point (cubic spline).\n\n == Usage\n\n x = (0..9).step(1).to_a\n y = x.map { |n| Math.exp(n) }\n f = Interpolation::OneDimensional.new x,y, type: :cubic\n f.interpolate 2.5\n #=> 12.287\n Performs the actual interpolation on the value passed as an argument. Kind of\n interpolation performed is determined according to what is specified in the\n constructor.\n\n ==== Arguments\n\n * +interpolant+ - The value for which the interpolation is to be performed. Can\n either be a Numeric, Array of Numerics or NMatrix. If multidimensional\n NMatrix is supplied then will flatten it and interpolate over\n all its values. Will return answer in the form of an NMatrix if\n *interpolant* is supplied as an NMatrix.", "docstring_tokens": ["Constructor", "for", "all", "One", "Dimensional", "interpolation", "operations", "."], "sha": "eec6b4e66083b88492406fc214fc085108057b96", "url": "https://github.com/v0dro/interpolation/blob/eec6b4e66083b88492406fc214fc085108057b96/lib/interpolation/one_dimensional.rb#L107-L116", "partition": "test"} {"repo": "jirutka/asciidoctor-include-ext", "path": "lib/asciidoctor/include_ext/include_processor.rb", "func_name": "Asciidoctor::IncludeExt.IncludeProcessor.lines_selector_for", "original_string": "def lines_selector_for(target, attributes)\n if (klass = @selectors.find { |s| s.handles? target, attributes })\n klass.new(target, attributes, logger: logger)\n end\n end", "language": "ruby", "code": "def lines_selector_for(target, attributes)\n if (klass = @selectors.find { |s| s.handles? target, attributes })\n klass.new(target, attributes, logger: logger)\n end\n end", "code_tokens": ["def", "lines_selector_for", "(", "target", ",", "attributes", ")", "if", "(", "klass", "=", "@selectors", ".", "find", "{", "|", "s", "|", "s", ".", "handles?", "target", ",", "attributes", "}", ")", "klass", ".", "new", "(", "target", ",", "attributes", ",", "logger", ":", "logger", ")", "end", "end"], "docstring": "Finds and initializes a lines selector that can handle the specified include.\n\n @param target (see #process)\n @param attributes (see #process)\n @return [#to_proc, nil] an instance of lines selector, or `nil` if not found.", "docstring_tokens": ["Finds", "and", "initializes", "a", "lines", "selector", "that", "can", "handle", "the", "specified", "include", "."], "sha": "f4a5ebed49df050fb9ea8f4c946983b63d479382", "url": "https://github.com/jirutka/asciidoctor-include-ext/blob/f4a5ebed49df050fb9ea8f4c946983b63d479382/lib/asciidoctor/include_ext/include_processor.rb#L127-L131", "partition": "test"} {"repo": "maratgaliev/bottleneck", "path": "lib/bottleneck/core.rb", "func_name": "Bottleneck.Core.run", "original_string": "def run\n client_ip = @ip\n key = \"request_count:#{client_ip}\"\n result = { status: Constants::SUCCESS_STATUS, message: Constants::OK_MESSAGE }\n requests_count = @storage.get(key)\n unless requests_count\n @storage.set(key, 0)\n @storage.expire(key, @limits[\"time_period_seconds\"])\n end\n if requests_count.to_i >= @limits[\"max_requests_count\"]\n result[:status] = Constants::EXPIRED_STATUS\n result[:message] = message(period(key))\n else\n @storage.incr(key)\n end\n result\n end", "language": "ruby", "code": "def run\n client_ip = @ip\n key = \"request_count:#{client_ip}\"\n result = { status: Constants::SUCCESS_STATUS, message: Constants::OK_MESSAGE }\n requests_count = @storage.get(key)\n unless requests_count\n @storage.set(key, 0)\n @storage.expire(key, @limits[\"time_period_seconds\"])\n end\n if requests_count.to_i >= @limits[\"max_requests_count\"]\n result[:status] = Constants::EXPIRED_STATUS\n result[:message] = message(period(key))\n else\n @storage.incr(key)\n end\n result\n end", "code_tokens": ["def", "run", "client_ip", "=", "@ip", "key", "=", "\"request_count:#{client_ip}\"", "result", "=", "{", "status", ":", "Constants", "::", "SUCCESS_STATUS", ",", "message", ":", "Constants", "::", "OK_MESSAGE", "}", "requests_count", "=", "@storage", ".", "get", "(", "key", ")", "unless", "requests_count", "@storage", ".", "set", "(", "key", ",", "0", ")", "@storage", ".", "expire", "(", "key", ",", "@limits", "[", "\"time_period_seconds\"", "]", ")", "end", "if", "requests_count", ".", "to_i", ">=", "@limits", "[", "\"max_requests_count\"", "]", "result", "[", ":status", "]", "=", "Constants", "::", "EXPIRED_STATUS", "result", "[", ":message", "]", "=", "message", "(", "period", "(", "key", ")", ")", "else", "@storage", ".", "incr", "(", "key", ")", "end", "result", "end"], "docstring": "Create a Core object.\n\n @param [String] ip A name to uniquely identify this rate limit. For example, '127.0.0.1'\n\n @return [Core] Core instance\n Run main logic initialization, set and read Redis keys and validation requests count and time limit.\n\n @return [Hash] Hash with :status and :message keys", "docstring_tokens": ["Create", "a", "Core", "object", "."], "sha": "0c503cd14e6009f46e1a80d04302031c42839e8f", "url": "https://github.com/maratgaliev/bottleneck/blob/0c503cd14e6009f46e1a80d04302031c42839e8f/lib/bottleneck/core.rb#L19-L35", "partition": "test"} {"repo": "alexreisner/informant", "path": "lib/informant.rb", "func_name": "Informant.Standard.date_select", "original_string": "def date_select(method, options = {})\n options[:include_blank] ||= false\n options[:start_year] ||= 1801\n options[:end_year] ||= Time.now.year\n options[:label_for] = \"#{object_name}_#{method}_1i\"\n build_shell(method, options) { super }\n end", "language": "ruby", "code": "def date_select(method, options = {})\n options[:include_blank] ||= false\n options[:start_year] ||= 1801\n options[:end_year] ||= Time.now.year\n options[:label_for] = \"#{object_name}_#{method}_1i\"\n build_shell(method, options) { super }\n end", "code_tokens": ["def", "date_select", "(", "method", ",", "options", "=", "{", "}", ")", "options", "[", ":include_blank", "]", "||=", "false", "options", "[", ":start_year", "]", "||=", "1801", "options", "[", ":end_year", "]", "||=", "Time", ".", "now", ".", "year", "options", "[", ":label_for", "]", "=", "\"#{object_name}_#{method}_1i\"", "build_shell", "(", "method", ",", "options", ")", "{", "super", "}", "end"], "docstring": "Standard Rails date selector.", "docstring_tokens": ["Standard", "Rails", "date", "selector", "."], "sha": "3d00329d9723fe18f771f5cc4399138f06f42437", "url": "https://github.com/alexreisner/informant/blob/3d00329d9723fe18f771f5cc4399138f06f42437/lib/informant.rb#L132-L138", "partition": "test"} {"repo": "alexreisner/informant", "path": "lib/informant.rb", "func_name": "Informant.Standard.label", "original_string": "def label(method, text = nil, options = {})\n colon = false if options[:colon].nil?\n options[:for] = options[:label_for]\n required = options[:required]\n\n # remove special options\n options.delete :colon\n options.delete :label_for\n options.delete :required\n\n text = @template.send(:h, text.blank?? method.to_s.humanize : text.to_s)\n text << ':'.html_safe if colon\n text << @template.content_tag(:span, \"*\", :class => \"required\") if required\n super\n end", "language": "ruby", "code": "def label(method, text = nil, options = {})\n colon = false if options[:colon].nil?\n options[:for] = options[:label_for]\n required = options[:required]\n\n # remove special options\n options.delete :colon\n options.delete :label_for\n options.delete :required\n\n text = @template.send(:h, text.blank?? method.to_s.humanize : text.to_s)\n text << ':'.html_safe if colon\n text << @template.content_tag(:span, \"*\", :class => \"required\") if required\n super\n end", "code_tokens": ["def", "label", "(", "method", ",", "text", "=", "nil", ",", "options", "=", "{", "}", ")", "colon", "=", "false", "if", "options", "[", ":colon", "]", ".", "nil?", "options", "[", ":for", "]", "=", "options", "[", ":label_for", "]", "required", "=", "options", "[", ":required", "]", "# remove special options", "options", ".", "delete", ":colon", "options", ".", "delete", ":label_for", "options", ".", "delete", ":required", "text", "=", "@template", ".", "send", "(", ":h", ",", "text", ".", "blank?", "?", "method", ".", "to_s", ".", "humanize", ":", "text", ".", "to_s", ")", "text", "<<", "':'", ".", "html_safe", "if", "colon", "text", "<<", "@template", ".", "content_tag", "(", ":span", ",", "\"*\"", ",", ":class", "=>", "\"required\"", ")", "if", "required", "super", "end"], "docstring": "Render a field label.", "docstring_tokens": ["Render", "a", "field", "label", "."], "sha": "3d00329d9723fe18f771f5cc4399138f06f42437", "url": "https://github.com/alexreisner/informant/blob/3d00329d9723fe18f771f5cc4399138f06f42437/lib/informant.rb#L199-L213", "partition": "test"} {"repo": "emonti/rstruct", "path": "lib/rstruct/base_types/packed_type.rb", "func_name": "Rstruct.Packable.read", "original_string": "def read(raw, predecessors=nil)\n if raw.respond_to?(:read)\n raw = raw.read(self.sizeof())\n end\n if raw.size < self.sizeof()\n raise(ReadError, \"Expected #{self.sizeof} bytes, but only got #{raw.size} bytes\")\n end\n\n vals = \n if @unpack_cb\n @unpack_cb.call(raw, predecessors)\n else\n raw.unpack(self.format)\n end\n return(self.claim_value(vals, predecessors))\n end", "language": "ruby", "code": "def read(raw, predecessors=nil)\n if raw.respond_to?(:read)\n raw = raw.read(self.sizeof())\n end\n if raw.size < self.sizeof()\n raise(ReadError, \"Expected #{self.sizeof} bytes, but only got #{raw.size} bytes\")\n end\n\n vals = \n if @unpack_cb\n @unpack_cb.call(raw, predecessors)\n else\n raw.unpack(self.format)\n end\n return(self.claim_value(vals, predecessors))\n end", "code_tokens": ["def", "read", "(", "raw", ",", "predecessors", "=", "nil", ")", "if", "raw", ".", "respond_to?", "(", ":read", ")", "raw", "=", "raw", ".", "read", "(", "self", ".", "sizeof", "(", ")", ")", "end", "if", "raw", ".", "size", "<", "self", ".", "sizeof", "(", ")", "raise", "(", "ReadError", ",", "\"Expected #{self.sizeof} bytes, but only got #{raw.size} bytes\"", ")", "end", "vals", "=", "if", "@unpack_cb", "@unpack_cb", ".", "call", "(", "raw", ",", "predecessors", ")", "else", "raw", ".", "unpack", "(", "self", ".", "format", ")", "end", "return", "(", "self", ".", "claim_value", "(", "vals", ",", "predecessors", ")", ")", "end"], "docstring": "Called when parsing. While you can override this in subclasses,\n in general it is probably better to use the 'on_unpack' method\n to define a proc to handle unpacking for special cases.", "docstring_tokens": ["Called", "when", "parsing", ".", "While", "you", "can", "override", "this", "in", "subclasses", "in", "general", "it", "is", "probably", "better", "to", "use", "the", "on_unpack", "method", "to", "define", "a", "proc", "to", "handle", "unpacking", "for", "special", "cases", "."], "sha": "0146955514ee53e5aff5e3b30ccf7d271cb47dac", "url": "https://github.com/emonti/rstruct/blob/0146955514ee53e5aff5e3b30ccf7d271cb47dac/lib/rstruct/base_types/packed_type.rb#L28-L43", "partition": "test"} {"repo": "emonti/rstruct", "path": "lib/rstruct/base_types/packed_type.rb", "func_name": "Rstruct.Packable.pack_value", "original_string": "def pack_value(val, obj=nil)\n begin\n if @pack_cb\n @pack_cb.call(val, obj)\n else\n varray = val.is_a?(Array) ? val : [val]\n varray.pack(self.format)\n end\n rescue => e\n raise(PackError, \"Error packing #{val.inspect} as type #{self.name.inspect} -- #{e.class} -> #{e}\")\n end\n end", "language": "ruby", "code": "def pack_value(val, obj=nil)\n begin\n if @pack_cb\n @pack_cb.call(val, obj)\n else\n varray = val.is_a?(Array) ? val : [val]\n varray.pack(self.format)\n end\n rescue => e\n raise(PackError, \"Error packing #{val.inspect} as type #{self.name.inspect} -- #{e.class} -> #{e}\")\n end\n end", "code_tokens": ["def", "pack_value", "(", "val", ",", "obj", "=", "nil", ")", "begin", "if", "@pack_cb", "@pack_cb", ".", "call", "(", "val", ",", "obj", ")", "else", "varray", "=", "val", ".", "is_a?", "(", "Array", ")", "?", "val", ":", "[", "val", "]", "varray", ".", "pack", "(", "self", ".", "format", ")", "end", "rescue", "=>", "e", "raise", "(", "PackError", ",", "\"Error packing #{val.inspect} as type #{self.name.inspect} -- #{e.class} -> #{e}\"", ")", "end", "end"], "docstring": "Called when composing raw data. While you can override this in\n subclasses, in general it is probably better to use the 'on_pack'\n method to define a proc to handle packing for special cases.", "docstring_tokens": ["Called", "when", "composing", "raw", "data", ".", "While", "you", "can", "override", "this", "in", "subclasses", "in", "general", "it", "is", "probably", "better", "to", "use", "the", "on_pack", "method", "to", "define", "a", "proc", "to", "handle", "packing", "for", "special", "cases", "."], "sha": "0146955514ee53e5aff5e3b30ccf7d271cb47dac", "url": "https://github.com/emonti/rstruct/blob/0146955514ee53e5aff5e3b30ccf7d271cb47dac/lib/rstruct/base_types/packed_type.rb#L48-L59", "partition": "test"} {"repo": "FrozenCanuck/Lebowski", "path": "lib/lebowski/rspec/matchers/method_missing.rb", "func_name": "RSpec.Matchers.method_missing", "original_string": "def method_missing(sym, *args, &block)\n #\n # Note: Be sure that the symbol does not contain the word \"test\". test\n # is a private method on Ruby objects and will cause the Be and Has\n # matches to fail.\n #\n return Lebowski::RSpec::Matchers::Be.new(sym, *args) if sym.to_s =~ /^be_/\n return Lebowski::RSpec::Matchers::Has.new(sym, *args) if sym.to_s =~ /^have_/\n return Lebowski::RSpec::Operators::That.new(sym, *args) if sym.to_s =~ /^that_/ \n super\n end", "language": "ruby", "code": "def method_missing(sym, *args, &block)\n #\n # Note: Be sure that the symbol does not contain the word \"test\". test\n # is a private method on Ruby objects and will cause the Be and Has\n # matches to fail.\n #\n return Lebowski::RSpec::Matchers::Be.new(sym, *args) if sym.to_s =~ /^be_/\n return Lebowski::RSpec::Matchers::Has.new(sym, *args) if sym.to_s =~ /^have_/\n return Lebowski::RSpec::Operators::That.new(sym, *args) if sym.to_s =~ /^that_/ \n super\n end", "code_tokens": ["def", "method_missing", "(", "sym", ",", "*", "args", ",", "&", "block", ")", "#", "# Note: Be sure that the symbol does not contain the word \"test\". test", "# is a private method on Ruby objects and will cause the Be and Has", "# matches to fail.", "#", "return", "Lebowski", "::", "RSpec", "::", "Matchers", "::", "Be", ".", "new", "(", "sym", ",", "args", ")", "if", "sym", ".", "to_s", "=~", "/", "/", "return", "Lebowski", "::", "RSpec", "::", "Matchers", "::", "Has", ".", "new", "(", "sym", ",", "args", ")", "if", "sym", ".", "to_s", "=~", "/", "/", "return", "Lebowski", "::", "RSpec", "::", "Operators", "::", "That", ".", "new", "(", "sym", ",", "args", ")", "if", "sym", ".", "to_s", "=~", "/", "/", "super", "end"], "docstring": "Replacing RSpec's default method_missing implementation so that we can\n include our own special default hooks that allows spec tests to look\n more readable.\n\n Ideally it would have been better if RSpec provided some nice hooks to\n try other default pattern matchers", "docstring_tokens": ["Replacing", "RSpec", "s", "default", "method_missing", "implementation", "so", "that", "we", "can", "include", "our", "own", "special", "default", "hooks", "that", "allows", "spec", "tests", "to", "look", "more", "readable", "."], "sha": "888feefc9208a4cc1e8f8497a65eb14c101d212a", "url": "https://github.com/FrozenCanuck/Lebowski/blob/888feefc9208a4cc1e8f8497a65eb14c101d212a/lib/lebowski/rspec/matchers/method_missing.rb#L17-L27", "partition": "test"} {"repo": "jektify/jektify", "path": "lib/jektify/main.rb", "func_name": "Jektify.Generator.static_files", "original_string": "def static_files\n source = File.dirname(ENGINE.assets_path)\n asset_files.map do |file|\n dir = File.dirname(file)\n file_name = File.basename(file)\n Jekyll::StaticFile.new @site, source, dir, file_name\n end\n end", "language": "ruby", "code": "def static_files\n source = File.dirname(ENGINE.assets_path)\n asset_files.map do |file|\n dir = File.dirname(file)\n file_name = File.basename(file)\n Jekyll::StaticFile.new @site, source, dir, file_name\n end\n end", "code_tokens": ["def", "static_files", "source", "=", "File", ".", "dirname", "(", "ENGINE", ".", "assets_path", ")", "asset_files", ".", "map", "do", "|", "file", "|", "dir", "=", "File", ".", "dirname", "(", "file", ")", "file_name", "=", "File", ".", "basename", "(", "file", ")", "Jekyll", "::", "StaticFile", ".", "new", "@site", ",", "source", ",", "dir", ",", "file_name", "end", "end"], "docstring": "This method searches for folders and files in the assets root directory.\n After searching all files stores in an array and then copying to\n the folder \"_site\".", "docstring_tokens": ["This", "method", "searches", "for", "folders", "and", "files", "in", "the", "assets", "root", "directory", ".", "After", "searching", "all", "files", "stores", "in", "an", "array", "and", "then", "copying", "to", "the", "folder", "_site", "."], "sha": "ee2c53244e5051581452bbed44f118da0f9ad7f8", "url": "https://github.com/jektify/jektify/blob/ee2c53244e5051581452bbed44f118da0f9ad7f8/lib/jektify/main.rb#L40-L47", "partition": "test"} {"repo": "jektify/jektify", "path": "lib/jektify/main.rb", "func_name": "Jektify.Generator.asset_files", "original_string": "def asset_files\n asset_files = []\n Find.find(ENGINE.assets_path).each do |path|\n next if File.directory?(path)\n next if path.include?(ENGINE.stylesheets_sass_path)\n asset_files << path.sub(ENGINE.assets_path, 'assets')\n end\n asset_files\n end", "language": "ruby", "code": "def asset_files\n asset_files = []\n Find.find(ENGINE.assets_path).each do |path|\n next if File.directory?(path)\n next if path.include?(ENGINE.stylesheets_sass_path)\n asset_files << path.sub(ENGINE.assets_path, 'assets')\n end\n asset_files\n end", "code_tokens": ["def", "asset_files", "asset_files", "=", "[", "]", "Find", ".", "find", "(", "ENGINE", ".", "assets_path", ")", ".", "each", "do", "|", "path", "|", "next", "if", "File", ".", "directory?", "(", "path", ")", "next", "if", "path", ".", "include?", "(", "ENGINE", ".", "stylesheets_sass_path", ")", "asset_files", "<<", "path", ".", "sub", "(", "ENGINE", ".", "assets_path", ",", "'assets'", ")", "end", "asset_files", "end"], "docstring": "Get paths and fils directory 'assets'", "docstring_tokens": ["Get", "paths", "and", "fils", "directory", "assets"], "sha": "ee2c53244e5051581452bbed44f118da0f9ad7f8", "url": "https://github.com/jektify/jektify/blob/ee2c53244e5051581452bbed44f118da0f9ad7f8/lib/jektify/main.rb#L50-L58", "partition": "test"} {"repo": "rngtng/paypal-report", "path": "lib/paypal/report.rb", "func_name": "Paypal.Report.daily", "original_string": "def daily(time = Date.today, page_size = 50)\n time = time.strftime(\"%Y-%m-%d\") unless time.is_a?(String)\n report_id = run_report_request('DailyActivityReport', {'report_date' => time}, page_size)\n\n meta_data = get_meta_data_request(report_id)\n\n data = []\n meta_data[\"numberOfPages\"].to_i.times do |page_num|\n data += get_data_request(report_id, page_num + 1) #it's zero indexed\n end\n data\n end", "language": "ruby", "code": "def daily(time = Date.today, page_size = 50)\n time = time.strftime(\"%Y-%m-%d\") unless time.is_a?(String)\n report_id = run_report_request('DailyActivityReport', {'report_date' => time}, page_size)\n\n meta_data = get_meta_data_request(report_id)\n\n data = []\n meta_data[\"numberOfPages\"].to_i.times do |page_num|\n data += get_data_request(report_id, page_num + 1) #it's zero indexed\n end\n data\n end", "code_tokens": ["def", "daily", "(", "time", "=", "Date", ".", "today", ",", "page_size", "=", "50", ")", "time", "=", "time", ".", "strftime", "(", "\"%Y-%m-%d\"", ")", "unless", "time", ".", "is_a?", "(", "String", ")", "report_id", "=", "run_report_request", "(", "'DailyActivityReport'", ",", "{", "'report_date'", "=>", "time", "}", ",", "page_size", ")", "meta_data", "=", "get_meta_data_request", "(", "report_id", ")", "data", "=", "[", "]", "meta_data", "[", "\"numberOfPages\"", "]", ".", "to_i", ".", "times", "do", "|", "page_num", "|", "data", "+=", "get_data_request", "(", "report_id", ",", "page_num", "+", "1", ")", "#it's zero indexed", "end", "data", "end"], "docstring": "high level functions", "docstring_tokens": ["high", "level", "functions"], "sha": "be3b2b897792f58af38e7af656c530f12a1f8d5c", "url": "https://github.com/rngtng/paypal-report/blob/be3b2b897792f58af38e7af656c530f12a1f8d5c/lib/paypal/report.rb#L16-L27", "partition": "test"} {"repo": "rngtng/paypal-report", "path": "lib/paypal/report.rb", "func_name": "Paypal.Report.run_report_request", "original_string": "def run_report_request(report_name, report_params = {}, page_size = 50)\n response = request 'runReportRequest' do |xml|\n xml.reportName report_name\n report_params.each do |name, value|\n xml.reportParam do\n xml.paramName name\n xml.paramValue value\n end\n end\n xml.pageSize page_size\n end\n\n response.elements[\"runReportResponse/reportId\"].get_text.value\n end", "language": "ruby", "code": "def run_report_request(report_name, report_params = {}, page_size = 50)\n response = request 'runReportRequest' do |xml|\n xml.reportName report_name\n report_params.each do |name, value|\n xml.reportParam do\n xml.paramName name\n xml.paramValue value\n end\n end\n xml.pageSize page_size\n end\n\n response.elements[\"runReportResponse/reportId\"].get_text.value\n end", "code_tokens": ["def", "run_report_request", "(", "report_name", ",", "report_params", "=", "{", "}", ",", "page_size", "=", "50", ")", "response", "=", "request", "'runReportRequest'", "do", "|", "xml", "|", "xml", ".", "reportName", "report_name", "report_params", ".", "each", "do", "|", "name", ",", "value", "|", "xml", ".", "reportParam", "do", "xml", ".", "paramName", "name", "xml", ".", "paramValue", "value", "end", "end", "xml", ".", "pageSize", "page_size", "end", "response", ".", "elements", "[", "\"runReportResponse/reportId\"", "]", ".", "get_text", ".", "value", "end"], "docstring": "low level functions", "docstring_tokens": ["low", "level", "functions"], "sha": "be3b2b897792f58af38e7af656c530f12a1f8d5c", "url": "https://github.com/rngtng/paypal-report/blob/be3b2b897792f58af38e7af656c530f12a1f8d5c/lib/paypal/report.rb#L60-L73", "partition": "test"} {"repo": "Sutto/unique_generator", "path": "lib/unique_generator.rb", "func_name": "UniqueGenerator.ClassMethods.generate_unique", "original_string": "def generate_unique(length = 32, &blk)\n unique = generate_random(length)\n unique = generate_random(length) until blk.call(unique)\n unique\n end", "language": "ruby", "code": "def generate_unique(length = 32, &blk)\n unique = generate_random(length)\n unique = generate_random(length) until blk.call(unique)\n unique\n end", "code_tokens": ["def", "generate_unique", "(", "length", "=", "32", ",", "&", "blk", ")", "unique", "=", "generate_random", "(", "length", ")", "unique", "=", "generate_random", "(", "length", ")", "until", "blk", ".", "call", "(", "unique", ")", "unique", "end"], "docstring": "Generate a unique field", "docstring_tokens": ["Generate", "a", "unique", "field"], "sha": "86afa05aa32b76963f8a996b01aa858b2820be86", "url": "https://github.com/Sutto/unique_generator/blob/86afa05aa32b76963f8a996b01aa858b2820be86/lib/unique_generator.rb#L51-L55", "partition": "test"} {"repo": "ab/paperback", "path": "lib/paperback/document.rb", "func_name": "Paperback.Document.draw_paperback", "original_string": "def draw_paperback(qr_code:, sixword_lines:, sixword_bytes:, labels:,\n passphrase_sha: nil, passphrase_len: nil,\n sixword_font_size: nil, base64_content: nil,\n base64_bytes: nil)\n unless qr_code.is_a?(RQRCode::QRCode)\n raise ArgumentError.new('qr_code must be RQRCode::QRCode')\n end\n\n # Header & QR code page\n pdf.font('Times-Roman')\n\n debug_draw_axes\n\n draw_header(labels: labels, passphrase_sha: passphrase_sha,\n passphrase_len: passphrase_len)\n\n add_newline\n\n draw_qr_code(qr_modules: qr_code.modules)\n\n pdf.stroke_color '000000'\n pdf.fill_color '000000'\n\n # Sixword page\n\n pdf.start_new_page\n\n draw_sixword(lines: sixword_lines, sixword_bytes: sixword_bytes,\n font_size: sixword_font_size,\n is_encrypted: passphrase_len)\n\n if base64_content\n draw_base64(b64_content: base64_content, b64_bytes: base64_bytes,\n is_encrypted: passphrase_len)\n end\n\n pdf.number_pages(' of ', align: :right,\n at: [pdf.bounds.right - 100, -2])\n end", "language": "ruby", "code": "def draw_paperback(qr_code:, sixword_lines:, sixword_bytes:, labels:,\n passphrase_sha: nil, passphrase_len: nil,\n sixword_font_size: nil, base64_content: nil,\n base64_bytes: nil)\n unless qr_code.is_a?(RQRCode::QRCode)\n raise ArgumentError.new('qr_code must be RQRCode::QRCode')\n end\n\n # Header & QR code page\n pdf.font('Times-Roman')\n\n debug_draw_axes\n\n draw_header(labels: labels, passphrase_sha: passphrase_sha,\n passphrase_len: passphrase_len)\n\n add_newline\n\n draw_qr_code(qr_modules: qr_code.modules)\n\n pdf.stroke_color '000000'\n pdf.fill_color '000000'\n\n # Sixword page\n\n pdf.start_new_page\n\n draw_sixword(lines: sixword_lines, sixword_bytes: sixword_bytes,\n font_size: sixword_font_size,\n is_encrypted: passphrase_len)\n\n if base64_content\n draw_base64(b64_content: base64_content, b64_bytes: base64_bytes,\n is_encrypted: passphrase_len)\n end\n\n pdf.number_pages(' of ', align: :right,\n at: [pdf.bounds.right - 100, -2])\n end", "code_tokens": ["def", "draw_paperback", "(", "qr_code", ":", ",", "sixword_lines", ":", ",", "sixword_bytes", ":", ",", "labels", ":", ",", "passphrase_sha", ":", "nil", ",", "passphrase_len", ":", "nil", ",", "sixword_font_size", ":", "nil", ",", "base64_content", ":", "nil", ",", "base64_bytes", ":", "nil", ")", "unless", "qr_code", ".", "is_a?", "(", "RQRCode", "::", "QRCode", ")", "raise", "ArgumentError", ".", "new", "(", "'qr_code must be RQRCode::QRCode'", ")", "end", "# Header & QR code page", "pdf", ".", "font", "(", "'Times-Roman'", ")", "debug_draw_axes", "draw_header", "(", "labels", ":", "labels", ",", "passphrase_sha", ":", "passphrase_sha", ",", "passphrase_len", ":", "passphrase_len", ")", "add_newline", "draw_qr_code", "(", "qr_modules", ":", "qr_code", ".", "modules", ")", "pdf", ".", "stroke_color", "'000000'", "pdf", ".", "fill_color", "'000000'", "# Sixword page", "pdf", ".", "start_new_page", "draw_sixword", "(", "lines", ":", "sixword_lines", ",", "sixword_bytes", ":", "sixword_bytes", ",", "font_size", ":", "sixword_font_size", ",", "is_encrypted", ":", "passphrase_len", ")", "if", "base64_content", "draw_base64", "(", "b64_content", ":", "base64_content", ",", "b64_bytes", ":", "base64_bytes", ",", "is_encrypted", ":", "passphrase_len", ")", "end", "pdf", ".", "number_pages", "(", "' of '", ",", "align", ":", ":right", ",", "at", ":", "[", "pdf", ".", "bounds", ".", "right", "-", "100", ",", "-", "2", "]", ")", "end"], "docstring": "High level method to draw the paperback content on the pdf document\n\n @param qr_code\n @param sixword_lines\n @param sixword_bytes\n @param labels\n @param passphrase_sha\n @param [Integer, nil] passphrase_len Length of the passphrase used to\n encrypt the original content. If this is not provided, then assume the\n original content was not encrypted and skip adding gpg -d instructions.\n @param [Integer] sixword_font_size The font size to use for Sixword text\n @param [String,nil] base64_content If provided, then append the original\n content (possibly encrypted) encoded using Base64.\n @param [Integer, nil] base64_bytes The length of the original content\n before encoding to base64. This is used for the informational header.", "docstring_tokens": ["High", "level", "method", "to", "draw", "the", "paperback", "content", "on", "the", "pdf", "document"], "sha": "f2bf7687041a71511afcc22325780dbcad3d8c8a", "url": "https://github.com/ab/paperback/blob/f2bf7687041a71511afcc22325780dbcad3d8c8a/lib/paperback/document.rb#L45-L83", "partition": "test"} {"repo": "nakiostudio/danger-xcov", "path": "lib/danger_plugin.rb", "func_name": "Danger.DangerXcov.produce_report", "original_string": "def produce_report(*args)\n # Check xcov availability, install it if needed\n `gem install xcov` unless xcov_available?\n unless xcov_available?\n puts \"xcov is not available on this machine\"\n return\n end\n\n require \"xcov\"\n require \"fastlane_core\"\n\n # Init Xcov\n config = FastlaneCore::Configuration.create(Xcov::Options.available_options, convert_options(args.first))\n Xcov.config = config\n Xcov.ignore_handler = Xcov::IgnoreHandler.new\n\n # Init project\n manager = Xcov::Manager.new(config)\n\n # Parse .xccoverage\n report_json = manager.parse_xccoverage\n\n # Map and process report\n process_report(Xcov::Report.map(report_json))\n end", "language": "ruby", "code": "def produce_report(*args)\n # Check xcov availability, install it if needed\n `gem install xcov` unless xcov_available?\n unless xcov_available?\n puts \"xcov is not available on this machine\"\n return\n end\n\n require \"xcov\"\n require \"fastlane_core\"\n\n # Init Xcov\n config = FastlaneCore::Configuration.create(Xcov::Options.available_options, convert_options(args.first))\n Xcov.config = config\n Xcov.ignore_handler = Xcov::IgnoreHandler.new\n\n # Init project\n manager = Xcov::Manager.new(config)\n\n # Parse .xccoverage\n report_json = manager.parse_xccoverage\n\n # Map and process report\n process_report(Xcov::Report.map(report_json))\n end", "code_tokens": ["def", "produce_report", "(", "*", "args", ")", "# Check xcov availability, install it if needed", "`", "`", "unless", "xcov_available?", "unless", "xcov_available?", "puts", "\"xcov is not available on this machine\"", "return", "end", "require", "\"xcov\"", "require", "\"fastlane_core\"", "# Init Xcov", "config", "=", "FastlaneCore", "::", "Configuration", ".", "create", "(", "Xcov", "::", "Options", ".", "available_options", ",", "convert_options", "(", "args", ".", "first", ")", ")", "Xcov", ".", "config", "=", "config", "Xcov", ".", "ignore_handler", "=", "Xcov", "::", "IgnoreHandler", ".", "new", "# Init project", "manager", "=", "Xcov", "::", "Manager", ".", "new", "(", "config", ")", "# Parse .xccoverage", "report_json", "=", "manager", ".", "parse_xccoverage", "# Map and process report", "process_report", "(", "Xcov", "::", "Report", ".", "map", "(", "report_json", ")", ")", "end"], "docstring": "Produces and processes a report for use in the report method\n It takes the same arguments as report, and returns the same\n object as process_report", "docstring_tokens": ["Produces", "and", "processes", "a", "report", "for", "use", "in", "the", "report", "method", "It", "takes", "the", "same", "arguments", "as", "report", "and", "returns", "the", "same", "object", "as", "process_report"], "sha": "47abc9592dfc8b138279f85878e13c96236c8b20", "url": "https://github.com/nakiostudio/danger-xcov/blob/47abc9592dfc8b138279f85878e13c96236c8b20/lib/danger_plugin.rb#L44-L68", "partition": "test"} {"repo": "nakiostudio/danger-xcov", "path": "lib/danger_plugin.rb", "func_name": "Danger.DangerXcov.output_report", "original_string": "def output_report(report)\n # Create markdown\n report_markdown = report.markdown_value\n\n # Send markdown\n markdown(report_markdown)\n\n # Notify failure if minimum coverage hasn't been reached\n threshold = Xcov.config[:minimum_coverage_percentage].to_i\n if !threshold.nil? && (report.coverage * 100) < threshold\n fail(\"Code coverage under minimum of #{threshold}%\")\n end\n end", "language": "ruby", "code": "def output_report(report)\n # Create markdown\n report_markdown = report.markdown_value\n\n # Send markdown\n markdown(report_markdown)\n\n # Notify failure if minimum coverage hasn't been reached\n threshold = Xcov.config[:minimum_coverage_percentage].to_i\n if !threshold.nil? && (report.coverage * 100) < threshold\n fail(\"Code coverage under minimum of #{threshold}%\")\n end\n end", "code_tokens": ["def", "output_report", "(", "report", ")", "# Create markdown", "report_markdown", "=", "report", ".", "markdown_value", "# Send markdown", "markdown", "(", "report_markdown", ")", "# Notify failure if minimum coverage hasn't been reached", "threshold", "=", "Xcov", ".", "config", "[", ":minimum_coverage_percentage", "]", ".", "to_i", "if", "!", "threshold", ".", "nil?", "&&", "(", "report", ".", "coverage", "*", "100", ")", "<", "threshold", "fail", "(", "\"Code coverage under minimum of #{threshold}%\"", ")", "end", "end"], "docstring": "Outputs a processed report with Danger", "docstring_tokens": ["Outputs", "a", "processed", "report", "with", "Danger"], "sha": "47abc9592dfc8b138279f85878e13c96236c8b20", "url": "https://github.com/nakiostudio/danger-xcov/blob/47abc9592dfc8b138279f85878e13c96236c8b20/lib/danger_plugin.rb#L71-L83", "partition": "test"} {"repo": "nakiostudio/danger-xcov", "path": "lib/danger_plugin.rb", "func_name": "Danger.DangerXcov.process_report", "original_string": "def process_report(report)\n file_names = @dangerfile.git.modified_files.map { |file| File.basename(file) }\n file_names += @dangerfile.git.added_files.map { |file| File.basename(file) }\n report.targets.each do |target|\n target.files = target.files.select { |file| file_names.include?(file.name) }\n end\n\n report\n end", "language": "ruby", "code": "def process_report(report)\n file_names = @dangerfile.git.modified_files.map { |file| File.basename(file) }\n file_names += @dangerfile.git.added_files.map { |file| File.basename(file) }\n report.targets.each do |target|\n target.files = target.files.select { |file| file_names.include?(file.name) }\n end\n\n report\n end", "code_tokens": ["def", "process_report", "(", "report", ")", "file_names", "=", "@dangerfile", ".", "git", ".", "modified_files", ".", "map", "{", "|", "file", "|", "File", ".", "basename", "(", "file", ")", "}", "file_names", "+=", "@dangerfile", ".", "git", ".", "added_files", ".", "map", "{", "|", "file", "|", "File", ".", "basename", "(", "file", ")", "}", "report", ".", "targets", ".", "each", "do", "|", "target", "|", "target", ".", "files", "=", "target", ".", "files", ".", "select", "{", "|", "file", "|", "file_names", ".", "include?", "(", "file", ".", "name", ")", "}", "end", "report", "end"], "docstring": "Filters the files that haven't been modified in the current PR", "docstring_tokens": ["Filters", "the", "files", "that", "haven", "t", "been", "modified", "in", "the", "current", "PR"], "sha": "47abc9592dfc8b138279f85878e13c96236c8b20", "url": "https://github.com/nakiostudio/danger-xcov/blob/47abc9592dfc8b138279f85878e13c96236c8b20/lib/danger_plugin.rb#L93-L101", "partition": "test"} {"repo": "postmodern/digest-crc", "path": "lib/digest/crc16_qt.rb", "func_name": "Digest.CRC16QT.update", "original_string": "def update(data)\n data.each_byte do |b|\n b = revert_byte(b) if REVERSE_DATA\n @crc = ((@table[((@crc >> 8) ^ b) & 0xff] ^ (@crc << 8)) & 0xffff)\n end\n\n return self\n end", "language": "ruby", "code": "def update(data)\n data.each_byte do |b|\n b = revert_byte(b) if REVERSE_DATA\n @crc = ((@table[((@crc >> 8) ^ b) & 0xff] ^ (@crc << 8)) & 0xffff)\n end\n\n return self\n end", "code_tokens": ["def", "update", "(", "data", ")", "data", ".", "each_byte", "do", "|", "b", "|", "b", "=", "revert_byte", "(", "b", ")", "if", "REVERSE_DATA", "@crc", "=", "(", "(", "@table", "[", "(", "(", "@crc", ">>", "8", ")", "^", "b", ")", "&", "0xff", "]", "^", "(", "@crc", "<<", "8", ")", ")", "&", "0xffff", ")", "end", "return", "self", "end"], "docstring": "Updates the CRC16 checksum.\n\n @param [String] data\n The data to update the checksum with.", "docstring_tokens": ["Updates", "the", "CRC16", "checksum", "."], "sha": "7de36753105ad5d974ba21c93e5e33ce10076a67", "url": "https://github.com/postmodern/digest-crc/blob/7de36753105ad5d974ba21c93e5e33ce10076a67/lib/digest/crc16_qt.rb#L22-L29", "partition": "test"} {"repo": "xing/xing_api", "path": "lib/xing_api/client.rb", "func_name": "XingApi.Client.request", "original_string": "def request(http_verb, url, options = {})\n full_url = url + hash_to_params(options)\n handle(access_token.request(http_verb, full_url))\n end", "language": "ruby", "code": "def request(http_verb, url, options = {})\n full_url = url + hash_to_params(options)\n handle(access_token.request(http_verb, full_url))\n end", "code_tokens": ["def", "request", "(", "http_verb", ",", "url", ",", "options", "=", "{", "}", ")", "full_url", "=", "url", "+", "hash_to_params", "(", "options", ")", "handle", "(", "access_token", ".", "request", "(", "http_verb", ",", "full_url", ")", ")", "end"], "docstring": "class << self", "docstring_tokens": ["class", "<<", "self"], "sha": "db40c4de849b5fd6d0c1c1c664c002196ae0f7da", "url": "https://github.com/xing/xing_api/blob/db40c4de849b5fd6d0c1c1c664c002196ae0f7da/lib/xing_api/client.rb#L26-L29", "partition": "test"} {"repo": "sonots/dummer", "path": "lib/dummer/random.rb", "func_name": "Dummer.Random.string", "original_string": "def string(opts = {})\n length, any, value = (opts[:length] || 8), opts[:any], opts[:value]\n if value\n string = value.to_s\n Proc.new { string }\n elsif any\n Proc.new { self.any(any) }\n else\n Proc.new { Array.new(length){@chars[rand(@chars.size-1)]}.join }\n end\n end", "language": "ruby", "code": "def string(opts = {})\n length, any, value = (opts[:length] || 8), opts[:any], opts[:value]\n if value\n string = value.to_s\n Proc.new { string }\n elsif any\n Proc.new { self.any(any) }\n else\n Proc.new { Array.new(length){@chars[rand(@chars.size-1)]}.join }\n end\n end", "code_tokens": ["def", "string", "(", "opts", "=", "{", "}", ")", "length", ",", "any", ",", "value", "=", "(", "opts", "[", ":length", "]", "||", "8", ")", ",", "opts", "[", ":any", "]", ",", "opts", "[", ":value", "]", "if", "value", "string", "=", "value", ".", "to_s", "Proc", ".", "new", "{", "string", "}", "elsif", "any", "Proc", ".", "new", "{", "self", ".", "any", "(", "any", ")", "}", "else", "Proc", ".", "new", "{", "Array", ".", "new", "(", "length", ")", "{", "@chars", "[", "rand", "(", "@chars", ".", "size", "-", "1", ")", "]", "}", ".", "join", "}", "end", "end"], "docstring": "belows are data types\n @return Proc object which returns a random generated value, or [formatted_value, raw_value]", "docstring_tokens": ["belows", "are", "data", "types"], "sha": "d0ce33a800cf176cfce9707dc5afbf3f0c3e3afa", "url": "https://github.com/sonots/dummer/blob/d0ce33a800cf176cfce9707dc5afbf3f0c3e3afa/lib/dummer/random.rb#L11-L21", "partition": "test"} {"repo": "janfri/multi_exiftool", "path": "lib/multi_exiftool/values.rb", "func_name": "MultiExiftool.Values.convert", "original_string": "def convert tag, val\n return val unless val.kind_of?(String)\n case tag\n when 'partofset', 'track'\n return val\n end\n case val\n when REGEXP_TIMESTAMP\n year, month, day, hour, minute = $~.captures[0,5].map {|cap| cap.to_i}\n if month == 0 || day == 0\n return nil\n end\n second = $6.to_f\n zone = $7\n zone = '+00:00' if zone == 'Z'\n Time.new(year, month, day, hour, minute, second, zone)\n when REGEXP_RATIONAL\n return val if $2.to_i == 0\n Rational($1, $2)\n else\n val\n end\n end", "language": "ruby", "code": "def convert tag, val\n return val unless val.kind_of?(String)\n case tag\n when 'partofset', 'track'\n return val\n end\n case val\n when REGEXP_TIMESTAMP\n year, month, day, hour, minute = $~.captures[0,5].map {|cap| cap.to_i}\n if month == 0 || day == 0\n return nil\n end\n second = $6.to_f\n zone = $7\n zone = '+00:00' if zone == 'Z'\n Time.new(year, month, day, hour, minute, second, zone)\n when REGEXP_RATIONAL\n return val if $2.to_i == 0\n Rational($1, $2)\n else\n val\n end\n end", "code_tokens": ["def", "convert", "tag", ",", "val", "return", "val", "unless", "val", ".", "kind_of?", "(", "String", ")", "case", "tag", "when", "'partofset'", ",", "'track'", "return", "val", "end", "case", "val", "when", "REGEXP_TIMESTAMP", "year", ",", "month", ",", "day", ",", "hour", ",", "minute", "=", "$~", ".", "captures", "[", "0", ",", "5", "]", ".", "map", "{", "|", "cap", "|", "cap", ".", "to_i", "}", "if", "month", "==", "0", "||", "day", "==", "0", "return", "nil", "end", "second", "=", "$6", ".", "to_f", "zone", "=", "$7", "zone", "=", "'+00:00'", "if", "zone", "==", "'Z'", "Time", ".", "new", "(", "year", ",", "month", ",", "day", ",", "hour", ",", "minute", ",", "second", ",", "zone", ")", "when", "REGEXP_RATIONAL", "return", "val", "if", "$2", ".", "to_i", "==", "0", "Rational", "(", "$1", ",", "$2", ")", "else", "val", "end", "end"], "docstring": "Converts values on the basis of unified tag name and value. It is called\n each time a value is fethed from a Values instance.\n @return (maybe) converted value", "docstring_tokens": ["Converts", "values", "on", "the", "basis", "of", "unified", "tag", "name", "and", "value", ".", "It", "is", "called", "each", "time", "a", "value", "is", "fethed", "from", "a", "Values", "instance", "."], "sha": "d1e11fad5d6a2f08d9d428a98798f4000cb9c4c5", "url": "https://github.com/janfri/multi_exiftool/blob/d1e11fad5d6a2f08d9d428a98798f4000cb9c4c5/lib/multi_exiftool/values.rb#L43-L65", "partition": "test"} {"repo": "janfri/multi_exiftool", "path": "lib/multi_exiftool/values.rb", "func_name": "MultiExiftool.Values.to_h", "original_string": "def to_h\n @values.inject(Hash.new) do |h, a|\n tag, val = a\n h[Values.tag_map[tag]] = convert(Values.unify_tag(tag), val)\n h\n end\n end", "language": "ruby", "code": "def to_h\n @values.inject(Hash.new) do |h, a|\n tag, val = a\n h[Values.tag_map[tag]] = convert(Values.unify_tag(tag), val)\n h\n end\n end", "code_tokens": ["def", "to_h", "@values", ".", "inject", "(", "Hash", ".", "new", ")", "do", "|", "h", ",", "a", "|", "tag", ",", "val", "=", "a", "h", "[", "Values", ".", "tag_map", "[", "tag", "]", "]", "=", "convert", "(", "Values", ".", "unify_tag", "(", "tag", ")", ",", "val", ")", "h", "end", "end"], "docstring": "Generates a hash representation of this instance\n with original tag names es keys and converted\n values as values", "docstring_tokens": ["Generates", "a", "hash", "representation", "of", "this", "instance", "with", "original", "tag", "names", "es", "keys", "and", "converted", "values", "as", "values"], "sha": "d1e11fad5d6a2f08d9d428a98798f4000cb9c4c5", "url": "https://github.com/janfri/multi_exiftool/blob/d1e11fad5d6a2f08d9d428a98798f4000cb9c4c5/lib/multi_exiftool/values.rb#L81-L87", "partition": "test"} {"repo": "hawx/guard-shell", "path": "lib/guard/shell.rb", "func_name": "Guard.Dsl.n", "original_string": "def n(msg, title='', image=nil)\n Compat::UI.notify(msg, :title => title, :image => image)\n end", "language": "ruby", "code": "def n(msg, title='', image=nil)\n Compat::UI.notify(msg, :title => title, :image => image)\n end", "code_tokens": ["def", "n", "(", "msg", ",", "title", "=", "''", ",", "image", "=", "nil", ")", "Compat", "::", "UI", ".", "notify", "(", "msg", ",", ":title", "=>", "title", ",", ":image", "=>", "image", ")", "end"], "docstring": "Easy method to display a notification", "docstring_tokens": ["Easy", "method", "to", "display", "a", "notification"], "sha": "0a8e1f5d14c4a3aad7f82170da1d0a9d82340627", "url": "https://github.com/hawx/guard-shell/blob/0a8e1f5d14c4a3aad7f82170da1d0a9d82340627/lib/guard/shell.rb#L30-L32", "partition": "test"} {"repo": "hawx/guard-shell", "path": "lib/guard/shell.rb", "func_name": "Guard.Dsl.eager", "original_string": "def eager(command)\n require 'pty'\n\n begin\n PTY.spawn command do |r, w, pid|\n begin\n $stdout.puts\n r.each {|line| print line }\n rescue Errno::EIO\n # the process has finished\n end\n end\n rescue PTY::ChildExited\n $stdout.puts \"The child process exited!\"\n end\n end", "language": "ruby", "code": "def eager(command)\n require 'pty'\n\n begin\n PTY.spawn command do |r, w, pid|\n begin\n $stdout.puts\n r.each {|line| print line }\n rescue Errno::EIO\n # the process has finished\n end\n end\n rescue PTY::ChildExited\n $stdout.puts \"The child process exited!\"\n end\n end", "code_tokens": ["def", "eager", "(", "command", ")", "require", "'pty'", "begin", "PTY", ".", "spawn", "command", "do", "|", "r", ",", "w", ",", "pid", "|", "begin", "$stdout", ".", "puts", "r", ".", "each", "{", "|", "line", "|", "print", "line", "}", "rescue", "Errno", "::", "EIO", "# the process has finished", "end", "end", "rescue", "PTY", "::", "ChildExited", "$stdout", ".", "puts", "\"The child process exited!\"", "end", "end"], "docstring": "Eager prints the result for stdout and stderr as it would be written when\n running the command from the terminal. This is useful for long running\n tasks.", "docstring_tokens": ["Eager", "prints", "the", "result", "for", "stdout", "and", "stderr", "as", "it", "would", "be", "written", "when", "running", "the", "command", "from", "the", "terminal", ".", "This", "is", "useful", "for", "long", "running", "tasks", "."], "sha": "0a8e1f5d14c4a3aad7f82170da1d0a9d82340627", "url": "https://github.com/hawx/guard-shell/blob/0a8e1f5d14c4a3aad7f82170da1d0a9d82340627/lib/guard/shell.rb#L37-L52", "partition": "test"} {"repo": "steventen/sql_tracker", "path": "lib/sql_tracker/report.rb", "func_name": "SqlTracker.Report.wrap_list", "original_string": "def wrap_list(list, width)\n list.map do |text|\n wrap_text(text, width)\n end.flatten\n end", "language": "ruby", "code": "def wrap_list(list, width)\n list.map do |text|\n wrap_text(text, width)\n end.flatten\n end", "code_tokens": ["def", "wrap_list", "(", "list", ",", "width", ")", "list", ".", "map", "do", "|", "text", "|", "wrap_text", "(", "text", ",", "width", ")", "end", ".", "flatten", "end"], "docstring": "an array of text", "docstring_tokens": ["an", "array", "of", "text"], "sha": "af1f527186b4a68a20c409b2e6bcf0f79c4284fd", "url": "https://github.com/steventen/sql_tracker/blob/af1f527186b4a68a20c409b2e6bcf0f79c4284fd/lib/sql_tracker/report.rb#L111-L115", "partition": "test"} {"repo": "steventen/sql_tracker", "path": "lib/sql_tracker/handler.rb", "func_name": "SqlTracker.Handler.save", "original_string": "def save\n return if @data.empty?\n output = {}\n output[:data] = @data\n output[:generated_at] = Time.now.to_s\n output[:started_at] = @started_at\n output[:format_version] = '1.0'\n output[:rails_version] = Rails.version\n output[:rails_path] = Rails.root.to_s\n\n FileUtils.mkdir_p(@config.output_path)\n filename = \"sql_tracker-#{Process.pid}-#{Time.now.to_i}.json\"\n\n File.open(File.join(@config.output_path, filename), 'w') do |f|\n f.write JSON.dump(output)\n end\n end", "language": "ruby", "code": "def save\n return if @data.empty?\n output = {}\n output[:data] = @data\n output[:generated_at] = Time.now.to_s\n output[:started_at] = @started_at\n output[:format_version] = '1.0'\n output[:rails_version] = Rails.version\n output[:rails_path] = Rails.root.to_s\n\n FileUtils.mkdir_p(@config.output_path)\n filename = \"sql_tracker-#{Process.pid}-#{Time.now.to_i}.json\"\n\n File.open(File.join(@config.output_path, filename), 'w') do |f|\n f.write JSON.dump(output)\n end\n end", "code_tokens": ["def", "save", "return", "if", "@data", ".", "empty?", "output", "=", "{", "}", "output", "[", ":data", "]", "=", "@data", "output", "[", ":generated_at", "]", "=", "Time", ".", "now", ".", "to_s", "output", "[", ":started_at", "]", "=", "@started_at", "output", "[", ":format_version", "]", "=", "'1.0'", "output", "[", ":rails_version", "]", "=", "Rails", ".", "version", "output", "[", ":rails_path", "]", "=", "Rails", ".", "root", ".", "to_s", "FileUtils", ".", "mkdir_p", "(", "@config", ".", "output_path", ")", "filename", "=", "\"sql_tracker-#{Process.pid}-#{Time.now.to_i}.json\"", "File", ".", "open", "(", "File", ".", "join", "(", "@config", ".", "output_path", ",", "filename", ")", ",", "'w'", ")", "do", "|", "f", "|", "f", ".", "write", "JSON", ".", "dump", "(", "output", ")", "end", "end"], "docstring": "save the data to file", "docstring_tokens": ["save", "the", "data", "to", "file"], "sha": "af1f527186b4a68a20c409b2e6bcf0f79c4284fd", "url": "https://github.com/steventen/sql_tracker/blob/af1f527186b4a68a20c409b2e6bcf0f79c4284fd/lib/sql_tracker/handler.rb#L94-L110", "partition": "test"} {"repo": "ruby-concurrency/ref", "path": "lib/ref/abstract_reference_value_map.rb", "func_name": "Ref.AbstractReferenceValueMap.delete", "original_string": "def delete(key)\n ref = @references.delete(key)\n if ref\n keys_to_id = @references_to_keys_map[ref.referenced_object_id]\n if keys_to_id\n keys_to_id.delete(key)\n @references_to_keys_map.delete(ref.referenced_object_id) if keys_to_id.empty?\n end\n ref.object\n else\n nil\n end\n end", "language": "ruby", "code": "def delete(key)\n ref = @references.delete(key)\n if ref\n keys_to_id = @references_to_keys_map[ref.referenced_object_id]\n if keys_to_id\n keys_to_id.delete(key)\n @references_to_keys_map.delete(ref.referenced_object_id) if keys_to_id.empty?\n end\n ref.object\n else\n nil\n end\n end", "code_tokens": ["def", "delete", "(", "key", ")", "ref", "=", "@references", ".", "delete", "(", "key", ")", "if", "ref", "keys_to_id", "=", "@references_to_keys_map", "[", "ref", ".", "referenced_object_id", "]", "if", "keys_to_id", "keys_to_id", ".", "delete", "(", "key", ")", "@references_to_keys_map", ".", "delete", "(", "ref", ".", "referenced_object_id", ")", "if", "keys_to_id", ".", "empty?", "end", "ref", ".", "object", "else", "nil", "end", "end"], "docstring": "Remove the entry associated with the key from the map.", "docstring_tokens": ["Remove", "the", "entry", "associated", "with", "the", "key", "from", "the", "map", "."], "sha": "7a3991fea598edfe41d4e3a9e37b344bc7b7570d", "url": "https://github.com/ruby-concurrency/ref/blob/7a3991fea598edfe41d4e3a9e37b344bc7b7570d/lib/ref/abstract_reference_value_map.rb#L59-L71", "partition": "test"} {"repo": "ruby-concurrency/ref", "path": "lib/ref/abstract_reference_value_map.rb", "func_name": "Ref.AbstractReferenceValueMap.merge", "original_string": "def merge(other_hash, &block)\n to_h.merge(other_hash, &block).reduce(self.class.new) do |map, pair|\n map[pair.first] = pair.last\n map\n end\n end", "language": "ruby", "code": "def merge(other_hash, &block)\n to_h.merge(other_hash, &block).reduce(self.class.new) do |map, pair|\n map[pair.first] = pair.last\n map\n end\n end", "code_tokens": ["def", "merge", "(", "other_hash", ",", "&", "block", ")", "to_h", ".", "merge", "(", "other_hash", ",", "block", ")", ".", "reduce", "(", "self", ".", "class", ".", "new", ")", "do", "|", "map", ",", "pair", "|", "map", "[", "pair", ".", "first", "]", "=", "pair", ".", "last", "map", "end", "end"], "docstring": "Returns a new struct containing the contents of `other` and the contents\n of `self`. If no block is specified, the value for entries with duplicate\n keys will be that of `other`. Otherwise the value for each duplicate key\n is determined by calling the block with the key, its value in `self` and\n its value in `other`.", "docstring_tokens": ["Returns", "a", "new", "struct", "containing", "the", "contents", "of", "other", "and", "the", "contents", "of", "self", ".", "If", "no", "block", "is", "specified", "the", "value", "for", "entries", "with", "duplicate", "keys", "will", "be", "that", "of", "other", ".", "Otherwise", "the", "value", "for", "each", "duplicate", "key", "is", "determined", "by", "calling", "the", "block", "with", "the", "key", "its", "value", "in", "self", "and", "its", "value", "in", "other", "."], "sha": "7a3991fea598edfe41d4e3a9e37b344bc7b7570d", "url": "https://github.com/ruby-concurrency/ref/blob/7a3991fea598edfe41d4e3a9e37b344bc7b7570d/lib/ref/abstract_reference_value_map.rb#L116-L121", "partition": "test"} {"repo": "ruby-concurrency/ref", "path": "lib/ref/soft_reference.rb", "func_name": "Ref.SoftReference.add_strong_reference", "original_string": "def add_strong_reference(obj) #:nodoc:\n @@lock.synchronize do\n @@strong_references.last[obj] = true\n unless @@gc_flag_set\n @@gc_flag_set = true\n ObjectSpace.define_finalizer(Object.new, @@finalizer)\n end\n end\n end", "language": "ruby", "code": "def add_strong_reference(obj) #:nodoc:\n @@lock.synchronize do\n @@strong_references.last[obj] = true\n unless @@gc_flag_set\n @@gc_flag_set = true\n ObjectSpace.define_finalizer(Object.new, @@finalizer)\n end\n end\n end", "code_tokens": ["def", "add_strong_reference", "(", "obj", ")", "#:nodoc:", "@@lock", ".", "synchronize", "do", "@@strong_references", ".", "last", "[", "obj", "]", "=", "true", "unless", "@@gc_flag_set", "@@gc_flag_set", "=", "true", "ObjectSpace", ".", "define_finalizer", "(", "Object", ".", "new", ",", "@@finalizer", ")", "end", "end", "end"], "docstring": "Create a strong reference to the object. This reference will live\n for three passes of the garbage collector.", "docstring_tokens": ["Create", "a", "strong", "reference", "to", "the", "object", ".", "This", "reference", "will", "live", "for", "three", "passes", "of", "the", "garbage", "collector", "."], "sha": "7a3991fea598edfe41d4e3a9e37b344bc7b7570d", "url": "https://github.com/ruby-concurrency/ref/blob/7a3991fea598edfe41d4e3a9e37b344bc7b7570d/lib/ref/soft_reference.rb#L57-L65", "partition": "test"} {"repo": "ruby-concurrency/ref", "path": "lib/ref/weak_reference/weak_ref.rb", "func_name": "Ref.WeakReference.object", "original_string": "def object #:nodoc:\n @ref.__getobj__\n rescue => e\n # Jruby implementation uses RefError while MRI uses WeakRef::RefError\n if (defined?(RefError) && e.is_a?(RefError)) || (defined?(::WeakRef::RefError) && e.is_a?(::WeakRef::RefError))\n nil\n else\n raise e\n end\n end", "language": "ruby", "code": "def object #:nodoc:\n @ref.__getobj__\n rescue => e\n # Jruby implementation uses RefError while MRI uses WeakRef::RefError\n if (defined?(RefError) && e.is_a?(RefError)) || (defined?(::WeakRef::RefError) && e.is_a?(::WeakRef::RefError))\n nil\n else\n raise e\n end\n end", "code_tokens": ["def", "object", "#:nodoc:", "@ref", ".", "__getobj__", "rescue", "=>", "e", "# Jruby implementation uses RefError while MRI uses WeakRef::RefError", "if", "(", "defined?", "(", "RefError", ")", "&&", "e", ".", "is_a?", "(", "RefError", ")", ")", "||", "(", "defined?", "(", "::", "WeakRef", "::", "RefError", ")", "&&", "e", ".", "is_a?", "(", "::", "WeakRef", "::", "RefError", ")", ")", "nil", "else", "raise", "e", "end", "end"], "docstring": "This implementation of a weak reference simply wraps the standard WeakRef implementation\n that comes with the Ruby standard library.", "docstring_tokens": ["This", "implementation", "of", "a", "weak", "reference", "simply", "wraps", "the", "standard", "WeakRef", "implementation", "that", "comes", "with", "the", "Ruby", "standard", "library", "."], "sha": "7a3991fea598edfe41d4e3a9e37b344bc7b7570d", "url": "https://github.com/ruby-concurrency/ref/blob/7a3991fea598edfe41d4e3a9e37b344bc7b7570d/lib/ref/weak_reference/weak_ref.rb#L12-L21", "partition": "test"} {"repo": "ruby-concurrency/ref", "path": "lib/ref/abstract_reference_key_map.rb", "func_name": "Ref.AbstractReferenceKeyMap.delete", "original_string": "def delete(key)\n @lock.synchronize do\n rkey = ref_key(key)\n if rkey\n @references_to_keys_map.delete(rkey)\n @values.delete(rkey)\n else\n nil\n end\n end\n end", "language": "ruby", "code": "def delete(key)\n @lock.synchronize do\n rkey = ref_key(key)\n if rkey\n @references_to_keys_map.delete(rkey)\n @values.delete(rkey)\n else\n nil\n end\n end\n end", "code_tokens": ["def", "delete", "(", "key", ")", "@lock", ".", "synchronize", "do", "rkey", "=", "ref_key", "(", "key", ")", "if", "rkey", "@references_to_keys_map", ".", "delete", "(", "rkey", ")", "@values", ".", "delete", "(", "rkey", ")", "else", "nil", "end", "end", "end"], "docstring": "Remove the value associated with the key from the map.", "docstring_tokens": ["Remove", "the", "value", "associated", "with", "the", "key", "from", "the", "map", "."], "sha": "7a3991fea598edfe41d4e3a9e37b344bc7b7570d", "url": "https://github.com/ruby-concurrency/ref/blob/7a3991fea598edfe41d4e3a9e37b344bc7b7570d/lib/ref/abstract_reference_key_map.rb#L51-L61", "partition": "test"} {"repo": "ruby-concurrency/ref", "path": "lib/ref/reference_queue.rb", "func_name": "Ref.ReferenceQueue.monitor", "original_string": "def monitor(reference)\n obj = reference.object\n if obj\n @lock.synchronize do\n @references[reference.referenced_object_id] = reference\n end\n ObjectSpace.define_finalizer(obj, @finalizer)\n else\n push(reference)\n end\n end", "language": "ruby", "code": "def monitor(reference)\n obj = reference.object\n if obj\n @lock.synchronize do\n @references[reference.referenced_object_id] = reference\n end\n ObjectSpace.define_finalizer(obj, @finalizer)\n else\n push(reference)\n end\n end", "code_tokens": ["def", "monitor", "(", "reference", ")", "obj", "=", "reference", ".", "object", "if", "obj", "@lock", ".", "synchronize", "do", "@references", "[", "reference", ".", "referenced_object_id", "]", "=", "reference", "end", "ObjectSpace", ".", "define_finalizer", "(", "obj", ",", "@finalizer", ")", "else", "push", "(", "reference", ")", "end", "end"], "docstring": "Monitor a reference. When the object the reference points to is garbage collected,\n the reference will be added to the queue.", "docstring_tokens": ["Monitor", "a", "reference", ".", "When", "the", "object", "the", "reference", "points", "to", "is", "garbage", "collected", "the", "reference", "will", "be", "added", "to", "the", "queue", "."], "sha": "7a3991fea598edfe41d4e3a9e37b344bc7b7570d", "url": "https://github.com/ruby-concurrency/ref/blob/7a3991fea598edfe41d4e3a9e37b344bc7b7570d/lib/ref/reference_queue.rb#L44-L54", "partition": "test"} {"repo": "nimbu/nimbu-api", "path": "lib/nimbu-api/authentication.rb", "func_name": "Nimbu.Authentication.client", "original_string": "def client(options={})\n @client ||= ::OAuth2::Client.new(client_id, client_secret,\n {\n :site => options.fetch(:site) { Nimbu.site },\n :authorize_url => 'login/oauth/authorize',\n :token_url => 'login/oauth/access_token',\n :ssl => { :verify => false }\n }\n )\n end", "language": "ruby", "code": "def client(options={})\n @client ||= ::OAuth2::Client.new(client_id, client_secret,\n {\n :site => options.fetch(:site) { Nimbu.site },\n :authorize_url => 'login/oauth/authorize',\n :token_url => 'login/oauth/access_token',\n :ssl => { :verify => false }\n }\n )\n end", "code_tokens": ["def", "client", "(", "options", "=", "{", "}", ")", "@client", "||=", "::", "OAuth2", "::", "Client", ".", "new", "(", "client_id", ",", "client_secret", ",", "{", ":site", "=>", "options", ".", "fetch", "(", ":site", ")", "{", "Nimbu", ".", "site", "}", ",", ":authorize_url", "=>", "'login/oauth/authorize'", ",", ":token_url", "=>", "'login/oauth/access_token'", ",", ":ssl", "=>", "{", ":verify", "=>", "false", "}", "}", ")", "end"], "docstring": "Setup OAuth2 instance", "docstring_tokens": ["Setup", "OAuth2", "instance"], "sha": "ed52a5250fb958c404de9d1c00532d1562faa00a", "url": "https://github.com/nimbu/nimbu-api/blob/ed52a5250fb958c404de9d1c00532d1562faa00a/lib/nimbu-api/authentication.rb#L9-L18", "partition": "test"} {"repo": "nimbu/nimbu-api", "path": "lib/nimbu-api/connection.rb", "func_name": "Nimbu.Connection.default_middleware", "original_string": "def default_middleware(options={})\n Proc.new do |builder|\n unless options[:with_attachments]\n builder.use Nimbu::Request::Json\n end\n builder.use Faraday::Request::Multipart\n builder.use Faraday::Request::UrlEncoded\n builder.use Nimbu::Request::OAuth2, oauth_token if oauth_token?\n builder.use Nimbu::Request::BasicAuth, authentication if basic_authed?\n builder.use Nimbu::Request::UserAgent\n builder.use Nimbu::Request::SiteHeader, subdomain\n builder.use Nimbu::Request::ContentLocale, content_locale\n\n builder.use Faraday::Response::Logger if ENV['DEBUG']\n builder.use Nimbu::Response::RaiseError\n unless options[:raw]\n builder.use Nimbu::Response::Mashify\n builder.use Nimbu::Response::Json\n end\n builder.adapter adapter\n end\n end", "language": "ruby", "code": "def default_middleware(options={})\n Proc.new do |builder|\n unless options[:with_attachments]\n builder.use Nimbu::Request::Json\n end\n builder.use Faraday::Request::Multipart\n builder.use Faraday::Request::UrlEncoded\n builder.use Nimbu::Request::OAuth2, oauth_token if oauth_token?\n builder.use Nimbu::Request::BasicAuth, authentication if basic_authed?\n builder.use Nimbu::Request::UserAgent\n builder.use Nimbu::Request::SiteHeader, subdomain\n builder.use Nimbu::Request::ContentLocale, content_locale\n\n builder.use Faraday::Response::Logger if ENV['DEBUG']\n builder.use Nimbu::Response::RaiseError\n unless options[:raw]\n builder.use Nimbu::Response::Mashify\n builder.use Nimbu::Response::Json\n end\n builder.adapter adapter\n end\n end", "code_tokens": ["def", "default_middleware", "(", "options", "=", "{", "}", ")", "Proc", ".", "new", "do", "|", "builder", "|", "unless", "options", "[", ":with_attachments", "]", "builder", ".", "use", "Nimbu", "::", "Request", "::", "Json", "end", "builder", ".", "use", "Faraday", "::", "Request", "::", "Multipart", "builder", ".", "use", "Faraday", "::", "Request", "::", "UrlEncoded", "builder", ".", "use", "Nimbu", "::", "Request", "::", "OAuth2", ",", "oauth_token", "if", "oauth_token?", "builder", ".", "use", "Nimbu", "::", "Request", "::", "BasicAuth", ",", "authentication", "if", "basic_authed?", "builder", ".", "use", "Nimbu", "::", "Request", "::", "UserAgent", "builder", ".", "use", "Nimbu", "::", "Request", "::", "SiteHeader", ",", "subdomain", "builder", ".", "use", "Nimbu", "::", "Request", "::", "ContentLocale", ",", "content_locale", "builder", ".", "use", "Faraday", "::", "Response", "::", "Logger", "if", "ENV", "[", "'DEBUG'", "]", "builder", ".", "use", "Nimbu", "::", "Response", "::", "RaiseError", "unless", "options", "[", ":raw", "]", "builder", ".", "use", "Nimbu", "::", "Response", "::", "Mashify", "builder", ".", "use", "Nimbu", "::", "Response", "::", "Json", "end", "builder", ".", "adapter", "adapter", "end", "end"], "docstring": "Default middleware stack that uses default adapter as specified at\n configuration stage.", "docstring_tokens": ["Default", "middleware", "stack", "that", "uses", "default", "adapter", "as", "specified", "at", "configuration", "stage", "."], "sha": "ed52a5250fb958c404de9d1c00532d1562faa00a", "url": "https://github.com/nimbu/nimbu-api/blob/ed52a5250fb958c404de9d1c00532d1562faa00a/lib/nimbu-api/connection.rb#L26-L47", "partition": "test"} {"repo": "andrearampin/smart_adapters", "path": "lib/smart_adapters/delegator.rb", "func_name": "SmartAdapters.Delegator.load", "original_string": "def load\n unless valid_params?\n raise SmartAdapters::Exceptions::InvalidRequestParamsException\n end\n unless valid_format?\n raise SmartAdapters::Exceptions::InvalidRequestFormatException\n end\n adapter_finder.new(request_manager)\n end", "language": "ruby", "code": "def load\n unless valid_params?\n raise SmartAdapters::Exceptions::InvalidRequestParamsException\n end\n unless valid_format?\n raise SmartAdapters::Exceptions::InvalidRequestFormatException\n end\n adapter_finder.new(request_manager)\n end", "code_tokens": ["def", "load", "unless", "valid_params?", "raise", "SmartAdapters", "::", "Exceptions", "::", "InvalidRequestParamsException", "end", "unless", "valid_format?", "raise", "SmartAdapters", "::", "Exceptions", "::", "InvalidRequestFormatException", "end", "adapter_finder", ".", "new", "(", "request_manager", ")", "end"], "docstring": "Initialise SmartAdapters delegator\n @param [ActionController]\n @param [ActionDispatch::Request]\n @return [SmartAdapters::Adapter::Delegator]\n Fetch Adatapter base on request\n @raise [SmartAdapters::Exceptions::InvalidRequestFormatException]\n @raise [SmartAdapters::Exceptions::InvalidRequestParamsException]\n @return [SmartAdapters::::::Adapter]", "docstring_tokens": ["Initialise", "SmartAdapters", "delegator"], "sha": "11267ac053b578ad82777eb562a02aee81807a95", "url": "https://github.com/andrearampin/smart_adapters/blob/11267ac053b578ad82777eb562a02aee81807a95/lib/smart_adapters/delegator.rb#L21-L29", "partition": "test"} {"repo": "xdougx/exceptions-resource", "path": "lib/exceptions.rb", "func_name": "Exceptions.Resource.error", "original_string": "def error\n {\n error: { \n model: self.object[\"model\"],\n model_human: self.object[\"model_human\"],\n attribute: self.object[\"attribute\"],\n attribute_human: self.object[\"attribute_human\"],\n field: self.object[\"field\"],\n message: self.object[\"message\"],\n full_message: \"#{self.object[\"full_message\"]}\"\n } \n }\n end", "language": "ruby", "code": "def error\n {\n error: { \n model: self.object[\"model\"],\n model_human: self.object[\"model_human\"],\n attribute: self.object[\"attribute\"],\n attribute_human: self.object[\"attribute_human\"],\n field: self.object[\"field\"],\n message: self.object[\"message\"],\n full_message: \"#{self.object[\"full_message\"]}\"\n } \n }\n end", "code_tokens": ["def", "error", "{", "error", ":", "{", "model", ":", "self", ".", "object", "[", "\"model\"", "]", ",", "model_human", ":", "self", ".", "object", "[", "\"model_human\"", "]", ",", "attribute", ":", "self", ".", "object", "[", "\"attribute\"", "]", ",", "attribute_human", ":", "self", ".", "object", "[", "\"attribute_human\"", "]", ",", "field", ":", "self", ".", "object", "[", "\"field\"", "]", ",", "message", ":", "self", ".", "object", "[", "\"message\"", "]", ",", "full_message", ":", "\"#{self.object[\"full_message\"]}\"", "}", "}", "end"], "docstring": "for standard errors this method build a hash\n @return [String] json string", "docstring_tokens": ["for", "standard", "errors", "this", "method", "build", "a", "hash"], "sha": "4cc6ae9083e815980028cfe859fb56cf20c3655a", "url": "https://github.com/xdougx/exceptions-resource/blob/4cc6ae9083e815980028cfe859fb56cf20c3655a/lib/exceptions.rb#L125-L137", "partition": "test"} {"repo": "nimbu/nimbu-api", "path": "lib/nimbu-api/endpoint.rb", "func_name": "Nimbu.Endpoint.setup", "original_string": "def setup(options={})\n options.each do |k,v|\n self.set(k,v,true)\n end\n options = Nimbu.options.merge(options)\n self.current_options = options\n Configuration.keys.each do |key|\n send(\"#{key}=\", options[key])\n end\n process_basic_auth(options[:basic_auth])\n end", "language": "ruby", "code": "def setup(options={})\n options.each do |k,v|\n self.set(k,v,true)\n end\n options = Nimbu.options.merge(options)\n self.current_options = options\n Configuration.keys.each do |key|\n send(\"#{key}=\", options[key])\n end\n process_basic_auth(options[:basic_auth])\n end", "code_tokens": ["def", "setup", "(", "options", "=", "{", "}", ")", "options", ".", "each", "do", "|", "k", ",", "v", "|", "self", ".", "set", "(", "k", ",", "v", ",", "true", ")", "end", "options", "=", "Nimbu", ".", "options", ".", "merge", "(", "options", ")", "self", ".", "current_options", "=", "options", "Configuration", ".", "keys", ".", "each", "do", "|", "key", "|", "send", "(", "\"#{key}=\"", ",", "options", "[", "key", "]", ")", "end", "process_basic_auth", "(", "options", "[", ":basic_auth", "]", ")", "end"], "docstring": "Configure options and process basic authorization", "docstring_tokens": ["Configure", "options", "and", "process", "basic", "authorization"], "sha": "ed52a5250fb958c404de9d1c00532d1562faa00a", "url": "https://github.com/nimbu/nimbu-api/blob/ed52a5250fb958c404de9d1c00532d1562faa00a/lib/nimbu-api/endpoint.rb#L84-L94", "partition": "test"} {"repo": "nimbu/nimbu-api", "path": "lib/nimbu-api/endpoint.rb", "func_name": "Nimbu.Endpoint.arguments", "original_string": "def arguments(args=(not_set = true), options={}, &block)\n if not_set\n @arguments\n else\n @arguments = Arguments.new(self, options).parse(*args, &block)\n end\n end", "language": "ruby", "code": "def arguments(args=(not_set = true), options={}, &block)\n if not_set\n @arguments\n else\n @arguments = Arguments.new(self, options).parse(*args, &block)\n end\n end", "code_tokens": ["def", "arguments", "(", "args", "=", "(", "not_set", "=", "true", ")", ",", "options", "=", "{", "}", ",", "&", "block", ")", "if", "not_set", "@arguments", "else", "@arguments", "=", "Arguments", ".", "new", "(", "self", ",", "options", ")", ".", "parse", "(", "args", ",", "block", ")", "end", "end"], "docstring": "Acts as setter and getter for api requests arguments parsing.\n\n Returns Arguments instance.", "docstring_tokens": ["Acts", "as", "setter", "and", "getter", "for", "api", "requests", "arguments", "parsing", "."], "sha": "ed52a5250fb958c404de9d1c00532d1562faa00a", "url": "https://github.com/nimbu/nimbu-api/blob/ed52a5250fb958c404de9d1c00532d1562faa00a/lib/nimbu-api/endpoint.rb#L124-L130", "partition": "test"} {"repo": "nimbu/nimbu-api", "path": "lib/nimbu-api/configuration.rb", "func_name": "Nimbu.Configuration.reset!", "original_string": "def reset!\n self.client_id = DEFAULT_CLIENT_ID\n self.client_secret = DEFAULT_CLIENT_SECRET\n self.oauth_token = DEFAULT_OAUTH_TOKEN\n self.endpoint = DEFAULT_ENDPOINT\n self.site = DEFAULT_SITE\n self.ssl = DEFAULT_SSL\n self.user_agent = DEFAULT_USER_AGENT\n self.connection_options = DEFAULT_CONNECTION_OPTIONS\n self.mime_type = DEFAULT_MIME_TYPE\n self.login = DEFAULT_LOGIN\n self.password = DEFAULT_PASSWORD\n self.basic_auth = DEFAULT_BASIC_AUTH\n self.auto_pagination = DEFAULT_AUTO_PAGINATION\n self.content_locale = DEFAULT_CONTENT_LOCALE\n self.adapter = DEFAULT_ADAPTER\n self.subdomain = DEFAULT_SUBDOMAIN\n self\n end", "language": "ruby", "code": "def reset!\n self.client_id = DEFAULT_CLIENT_ID\n self.client_secret = DEFAULT_CLIENT_SECRET\n self.oauth_token = DEFAULT_OAUTH_TOKEN\n self.endpoint = DEFAULT_ENDPOINT\n self.site = DEFAULT_SITE\n self.ssl = DEFAULT_SSL\n self.user_agent = DEFAULT_USER_AGENT\n self.connection_options = DEFAULT_CONNECTION_OPTIONS\n self.mime_type = DEFAULT_MIME_TYPE\n self.login = DEFAULT_LOGIN\n self.password = DEFAULT_PASSWORD\n self.basic_auth = DEFAULT_BASIC_AUTH\n self.auto_pagination = DEFAULT_AUTO_PAGINATION\n self.content_locale = DEFAULT_CONTENT_LOCALE\n self.adapter = DEFAULT_ADAPTER\n self.subdomain = DEFAULT_SUBDOMAIN\n self\n end", "code_tokens": ["def", "reset!", "self", ".", "client_id", "=", "DEFAULT_CLIENT_ID", "self", ".", "client_secret", "=", "DEFAULT_CLIENT_SECRET", "self", ".", "oauth_token", "=", "DEFAULT_OAUTH_TOKEN", "self", ".", "endpoint", "=", "DEFAULT_ENDPOINT", "self", ".", "site", "=", "DEFAULT_SITE", "self", ".", "ssl", "=", "DEFAULT_SSL", "self", ".", "user_agent", "=", "DEFAULT_USER_AGENT", "self", ".", "connection_options", "=", "DEFAULT_CONNECTION_OPTIONS", "self", ".", "mime_type", "=", "DEFAULT_MIME_TYPE", "self", ".", "login", "=", "DEFAULT_LOGIN", "self", ".", "password", "=", "DEFAULT_PASSWORD", "self", ".", "basic_auth", "=", "DEFAULT_BASIC_AUTH", "self", ".", "auto_pagination", "=", "DEFAULT_AUTO_PAGINATION", "self", ".", "content_locale", "=", "DEFAULT_CONTENT_LOCALE", "self", ".", "adapter", "=", "DEFAULT_ADAPTER", "self", ".", "subdomain", "=", "DEFAULT_SUBDOMAIN", "self", "end"], "docstring": "Reset configuration options to their defaults", "docstring_tokens": ["Reset", "configuration", "options", "to", "their", "defaults"], "sha": "ed52a5250fb958c404de9d1c00532d1562faa00a", "url": "https://github.com/nimbu/nimbu-api/blob/ed52a5250fb958c404de9d1c00532d1562faa00a/lib/nimbu-api/configuration.rb#L98-L116", "partition": "test"} {"repo": "OpenBEL/openbel-api", "path": "app/openbel/api/helpers/filters.rb", "func_name": "OpenBEL.Helpers.invalid_fts_filters", "original_string": "def invalid_fts_filters(filters)\n filters.select { |filter|\n category, name, value = filter.values_at('category', 'name', 'value')\n category == 'fts' && name == 'search' && value.to_s.length <= 1\n }.map { |invalid_fts_filter|\n error = <<-MSG.gsub(/^\\s+/, '').strip\n Full-text search filter values must be larger than one.\n MSG\n invalid_fts_filter.merge(:error => error)\n }\n end", "language": "ruby", "code": "def invalid_fts_filters(filters)\n filters.select { |filter|\n category, name, value = filter.values_at('category', 'name', 'value')\n category == 'fts' && name == 'search' && value.to_s.length <= 1\n }.map { |invalid_fts_filter|\n error = <<-MSG.gsub(/^\\s+/, '').strip\n Full-text search filter values must be larger than one.\n MSG\n invalid_fts_filter.merge(:error => error)\n }\n end", "code_tokens": ["def", "invalid_fts_filters", "(", "filters", ")", "filters", ".", "select", "{", "|", "filter", "|", "category", ",", "name", ",", "value", "=", "filter", ".", "values_at", "(", "'category'", ",", "'name'", ",", "'value'", ")", "category", "==", "'fts'", "&&", "name", "==", "'search'", "&&", "value", ".", "to_s", ".", "length", "<=", "1", "}", ".", "map", "{", "|", "invalid_fts_filter", "|", "error", "=", "<<-MSG", ".", "gsub", "(", "/", "\\s", "/", ",", "''", ")", ".", "strip", "MSG", "invalid_fts_filter", ".", "merge", "(", ":error", "=>", "error", ")", "}", "end"], "docstring": "Retrieve the filters that represent invalid full-text search values.\n\n The parsed, invalid full-text search filters will contain an +:error+ key\n that provides an error message intended for the user.\n\n @param [Array] filters an array of filter {Hash hashes}\n @return [Array] an array of invalid full-text search filter\n {Hash hashes} that contain a human-readable error at the\n +:error+ key", "docstring_tokens": ["Retrieve", "the", "filters", "that", "represent", "invalid", "full", "-", "text", "search", "values", "."], "sha": "54e2b27aa931791b945b01415a6a9bb106434e67", "url": "https://github.com/OpenBEL/openbel-api/blob/54e2b27aa931791b945b01415a6a9bb106434e67/app/openbel/api/helpers/filters.rb#L54-L64", "partition": "test"} {"repo": "postmodern/parameters", "path": "lib/parameters/module_methods.rb", "func_name": "Parameters.ModuleMethods.extended", "original_string": "def extended(object)\n each_param do |param|\n object.params[param.name] = param.to_instance(object)\n end\n end", "language": "ruby", "code": "def extended(object)\n each_param do |param|\n object.params[param.name] = param.to_instance(object)\n end\n end", "code_tokens": ["def", "extended", "(", "object", ")", "each_param", "do", "|", "param", "|", "object", ".", "params", "[", "param", ".", "name", "]", "=", "param", ".", "to_instance", "(", "object", ")", "end", "end"], "docstring": "Ensures that the module will initialize parameters, when extended\n into an Object.", "docstring_tokens": ["Ensures", "that", "the", "module", "will", "initialize", "parameters", "when", "extended", "into", "an", "Object", "."], "sha": "890763d802349de680cac37a8e589bffc46a1ca7", "url": "https://github.com/postmodern/parameters/blob/890763d802349de680cac37a8e589bffc46a1ca7/lib/parameters/module_methods.rb#L22-L26", "partition": "test"} {"repo": "postmodern/parameters", "path": "lib/parameters/class_methods.rb", "func_name": "Parameters.ClassMethods.params=", "original_string": "def params=(values)\n values.each do |name,value|\n if has_param?(name)\n get_param(name).value = case value\n when Parameters::ClassParam,\n Parameters::InstanceParam\n value.value\n else\n value\n end\n end\n end\n end", "language": "ruby", "code": "def params=(values)\n values.each do |name,value|\n if has_param?(name)\n get_param(name).value = case value\n when Parameters::ClassParam,\n Parameters::InstanceParam\n value.value\n else\n value\n end\n end\n end\n end", "code_tokens": ["def", "params", "=", "(", "values", ")", "values", ".", "each", "do", "|", "name", ",", "value", "|", "if", "has_param?", "(", "name", ")", "get_param", "(", "name", ")", ".", "value", "=", "case", "value", "when", "Parameters", "::", "ClassParam", ",", "Parameters", "::", "InstanceParam", "value", ".", "value", "else", "value", "end", "end", "end", "end"], "docstring": "Sets the values of the class parameters.\n\n @param [Hash] values\n The names and new values to set the class params to.\n\n @example\n Test.params = {:x => 5, :y => 2}\n # => {:x=>5, :y=>2}\n\n @api semipublic", "docstring_tokens": ["Sets", "the", "values", "of", "the", "class", "parameters", "."], "sha": "890763d802349de680cac37a8e589bffc46a1ca7", "url": "https://github.com/postmodern/parameters/blob/890763d802349de680cac37a8e589bffc46a1ca7/lib/parameters/class_methods.rb#L29-L41", "partition": "test"} {"repo": "postmodern/parameters", "path": "lib/parameters/class_methods.rb", "func_name": "Parameters.ClassMethods.parameter", "original_string": "def parameter(name,options={})\n name = name.to_sym\n\n # define the reader class method for the parameter\n meta_def(name) do\n get_param(name).value\n end\n\n # define the writer class method for the parameter\n meta_def(\"#{name}=\") do |value|\n get_param(name).value = value\n end\n\n # define the ? method, to determine if the parameter is set\n meta_def(\"#{name}?\") do\n !!get_param(name).value\n end\n\n # define the reader instance methods for the parameter\n define_method(name) do\n get_param(name).value\n end\n\n # define the writter instance methods for the parameter\n define_method(\"#{name}=\") do |value|\n get_param(name).value = value\n end\n\n # define the ? method, to determine if the parameter is set\n define_method(\"#{name}?\") do\n !!get_param(name).value\n end\n\n # create the new parameter\n new_param = Parameters::ClassParam.new(\n name,\n options[:type],\n options[:description],\n options[:default]\n )\n\n # add the parameter to the class params list\n params[name] = new_param\n return new_param\n end", "language": "ruby", "code": "def parameter(name,options={})\n name = name.to_sym\n\n # define the reader class method for the parameter\n meta_def(name) do\n get_param(name).value\n end\n\n # define the writer class method for the parameter\n meta_def(\"#{name}=\") do |value|\n get_param(name).value = value\n end\n\n # define the ? method, to determine if the parameter is set\n meta_def(\"#{name}?\") do\n !!get_param(name).value\n end\n\n # define the reader instance methods for the parameter\n define_method(name) do\n get_param(name).value\n end\n\n # define the writter instance methods for the parameter\n define_method(\"#{name}=\") do |value|\n get_param(name).value = value\n end\n\n # define the ? method, to determine if the parameter is set\n define_method(\"#{name}?\") do\n !!get_param(name).value\n end\n\n # create the new parameter\n new_param = Parameters::ClassParam.new(\n name,\n options[:type],\n options[:description],\n options[:default]\n )\n\n # add the parameter to the class params list\n params[name] = new_param\n return new_param\n end", "code_tokens": ["def", "parameter", "(", "name", ",", "options", "=", "{", "}", ")", "name", "=", "name", ".", "to_sym", "# define the reader class method for the parameter", "meta_def", "(", "name", ")", "do", "get_param", "(", "name", ")", ".", "value", "end", "# define the writer class method for the parameter", "meta_def", "(", "\"#{name}=\"", ")", "do", "|", "value", "|", "get_param", "(", "name", ")", ".", "value", "=", "value", "end", "# define the ? method, to determine if the parameter is set", "meta_def", "(", "\"#{name}?\"", ")", "do", "!", "!", "get_param", "(", "name", ")", ".", "value", "end", "# define the reader instance methods for the parameter", "define_method", "(", "name", ")", "do", "get_param", "(", "name", ")", ".", "value", "end", "# define the writter instance methods for the parameter", "define_method", "(", "\"#{name}=\"", ")", "do", "|", "value", "|", "get_param", "(", "name", ")", ".", "value", "=", "value", "end", "# define the ? method, to determine if the parameter is set", "define_method", "(", "\"#{name}?\"", ")", "do", "!", "!", "get_param", "(", "name", ")", ".", "value", "end", "# create the new parameter", "new_param", "=", "Parameters", "::", "ClassParam", ".", "new", "(", "name", ",", "options", "[", ":type", "]", ",", "options", "[", ":description", "]", ",", "options", "[", ":default", "]", ")", "# add the parameter to the class params list", "params", "[", "name", "]", "=", "new_param", "return", "new_param", "end"], "docstring": "Adds a new parameters to the class.\n\n @param [Symbol, String] name\n The name of the new parameter.\n\n @param [Hash] options\n Additional options.\n\n @option options [Class, Array[Class]] :type\n The type to enforce the parameter values to.\n\n @option options [Object, Proc] :default\n The default value for the new parameter.\n\n @option options [String] :description\n The description for the new parameter.\n\n @example\n parameter 'var'\n\n @example\n parameter 'var', :default => 3, :description => 'my variable'\n\n @api public", "docstring_tokens": ["Adds", "a", "new", "parameters", "to", "the", "class", "."], "sha": "890763d802349de680cac37a8e589bffc46a1ca7", "url": "https://github.com/postmodern/parameters/blob/890763d802349de680cac37a8e589bffc46a1ca7/lib/parameters/class_methods.rb#L69-L113", "partition": "test"} {"repo": "postmodern/parameters", "path": "lib/parameters/class_methods.rb", "func_name": "Parameters.ClassMethods.has_param?", "original_string": "def has_param?(name)\n name = name.to_sym\n\n ancestors.each do |ancestor|\n if ancestor.included_modules.include?(Parameters)\n return true if ancestor.params.has_key?(name)\n end\n end\n\n return false\n end", "language": "ruby", "code": "def has_param?(name)\n name = name.to_sym\n\n ancestors.each do |ancestor|\n if ancestor.included_modules.include?(Parameters)\n return true if ancestor.params.has_key?(name)\n end\n end\n\n return false\n end", "code_tokens": ["def", "has_param?", "(", "name", ")", "name", "=", "name", ".", "to_sym", "ancestors", ".", "each", "do", "|", "ancestor", "|", "if", "ancestor", ".", "included_modules", ".", "include?", "(", "Parameters", ")", "return", "true", "if", "ancestor", ".", "params", ".", "has_key?", "(", "name", ")", "end", "end", "return", "false", "end"], "docstring": "Determines if a class parameter exists with the given name.\n\n @return [Boolean]\n Specifies whether or not there is a class parameter with the\n specified name.\n\n @api semipublic", "docstring_tokens": ["Determines", "if", "a", "class", "parameter", "exists", "with", "the", "given", "name", "."], "sha": "890763d802349de680cac37a8e589bffc46a1ca7", "url": "https://github.com/postmodern/parameters/blob/890763d802349de680cac37a8e589bffc46a1ca7/lib/parameters/class_methods.rb#L124-L134", "partition": "test"} {"repo": "postmodern/parameters", "path": "lib/parameters/class_methods.rb", "func_name": "Parameters.ClassMethods.get_param", "original_string": "def get_param(name)\n name = name.to_sym\n\n ancestors.each do |ancestor|\n if ancestor.included_modules.include?(Parameters)\n if ancestor.params.has_key?(name)\n return ancestor.params[name]\n end\n end\n end\n\n raise(Parameters::ParamNotFound,\"parameter #{name.to_s.dump} was not found in class #{self}\")\n end", "language": "ruby", "code": "def get_param(name)\n name = name.to_sym\n\n ancestors.each do |ancestor|\n if ancestor.included_modules.include?(Parameters)\n if ancestor.params.has_key?(name)\n return ancestor.params[name]\n end\n end\n end\n\n raise(Parameters::ParamNotFound,\"parameter #{name.to_s.dump} was not found in class #{self}\")\n end", "code_tokens": ["def", "get_param", "(", "name", ")", "name", "=", "name", ".", "to_sym", "ancestors", ".", "each", "do", "|", "ancestor", "|", "if", "ancestor", ".", "included_modules", ".", "include?", "(", "Parameters", ")", "if", "ancestor", ".", "params", ".", "has_key?", "(", "name", ")", "return", "ancestor", ".", "params", "[", "name", "]", "end", "end", "end", "raise", "(", "Parameters", "::", "ParamNotFound", ",", "\"parameter #{name.to_s.dump} was not found in class #{self}\"", ")", "end"], "docstring": "Searches for the class parameter with the matching name.\n\n @param [Symbol, String] name\n The class parameter name to search for.\n\n @return [ClassParam]\n The class parameter with the matching name.\n\n @raise [ParamNotFound]\n No class parameter with the specified name could be found.\n\n @api semipublic", "docstring_tokens": ["Searches", "for", "the", "class", "parameter", "with", "the", "matching", "name", "."], "sha": "890763d802349de680cac37a8e589bffc46a1ca7", "url": "https://github.com/postmodern/parameters/blob/890763d802349de680cac37a8e589bffc46a1ca7/lib/parameters/class_methods.rb#L150-L162", "partition": "test"} {"repo": "postmodern/parameters", "path": "lib/parameters/class_methods.rb", "func_name": "Parameters.ClassMethods.set_param", "original_string": "def set_param(name,value)\n name = name.to_sym\n\n ancestors.each do |ancestor|\n if ancestor.included_modules.include?(Parameters)\n if ancestor.params.has_key?(name)\n return ancestor.params[name].set(value)\n end\n end\n end\n\n raise(Parameters::ParamNotFound,\"parameter #{name.to_s.dump} was not found in class #{self}\")\n end", "language": "ruby", "code": "def set_param(name,value)\n name = name.to_sym\n\n ancestors.each do |ancestor|\n if ancestor.included_modules.include?(Parameters)\n if ancestor.params.has_key?(name)\n return ancestor.params[name].set(value)\n end\n end\n end\n\n raise(Parameters::ParamNotFound,\"parameter #{name.to_s.dump} was not found in class #{self}\")\n end", "code_tokens": ["def", "set_param", "(", "name", ",", "value", ")", "name", "=", "name", ".", "to_sym", "ancestors", ".", "each", "do", "|", "ancestor", "|", "if", "ancestor", ".", "included_modules", ".", "include?", "(", "Parameters", ")", "if", "ancestor", ".", "params", ".", "has_key?", "(", "name", ")", "return", "ancestor", ".", "params", "[", "name", "]", ".", "set", "(", "value", ")", "end", "end", "end", "raise", "(", "Parameters", "::", "ParamNotFound", ",", "\"parameter #{name.to_s.dump} was not found in class #{self}\"", ")", "end"], "docstring": "Sets a class parameter.\n\n @param [Symbol, String] name\n The name of the class parameter.\n\n @param [Object] value\n The new value for the class parameter.\n\n @return [Object]\n The new value of the class parameter.\n\n @raise [ParamNotfound]\n No class parameter with the specified name could be found.\n\n @since 0.3.0\n\n @api semipublic", "docstring_tokens": ["Sets", "a", "class", "parameter", "."], "sha": "890763d802349de680cac37a8e589bffc46a1ca7", "url": "https://github.com/postmodern/parameters/blob/890763d802349de680cac37a8e589bffc46a1ca7/lib/parameters/class_methods.rb#L183-L195", "partition": "test"} {"repo": "postmodern/parameters", "path": "lib/parameters/class_methods.rb", "func_name": "Parameters.ClassMethods.each_param", "original_string": "def each_param(&block)\n ancestors.reverse_each do |ancestor|\n if ancestor.included_modules.include?(Parameters)\n ancestor.params.each_value(&block)\n end\n end\n\n return self\n end", "language": "ruby", "code": "def each_param(&block)\n ancestors.reverse_each do |ancestor|\n if ancestor.included_modules.include?(Parameters)\n ancestor.params.each_value(&block)\n end\n end\n\n return self\n end", "code_tokens": ["def", "each_param", "(", "&", "block", ")", "ancestors", ".", "reverse_each", "do", "|", "ancestor", "|", "if", "ancestor", ".", "included_modules", ".", "include?", "(", "Parameters", ")", "ancestor", ".", "params", ".", "each_value", "(", "block", ")", "end", "end", "return", "self", "end"], "docstring": "Iterates over the parameters of the class and it's ancestors.\n\n @yield [param]\n The block that will be passed each class parameter.\n\n @api semipublic", "docstring_tokens": ["Iterates", "over", "the", "parameters", "of", "the", "class", "and", "it", "s", "ancestors", "."], "sha": "890763d802349de680cac37a8e589bffc46a1ca7", "url": "https://github.com/postmodern/parameters/blob/890763d802349de680cac37a8e589bffc46a1ca7/lib/parameters/class_methods.rb#L205-L213", "partition": "test"} {"repo": "datamapper/dm-transactions", "path": "lib/dm-transactions.rb", "func_name": "DataMapper.Transaction.link", "original_string": "def link(*things)\n unless none?\n raise \"Illegal state for link: #{state}\"\n end\n\n things.each do |thing|\n case thing\n when DataMapper::Adapters::AbstractAdapter\n @adapters[thing] = :none\n when DataMapper::Repository\n link(thing.adapter)\n when DataMapper::Model\n link(*thing.repositories)\n when DataMapper::Resource\n link(thing.model)\n when Array\n link(*thing)\n else\n raise \"Unknown argument to #{self.class}#link: #{thing.inspect} (#{thing.class})\"\n end\n end\n\n if block_given?\n commit { |*block_args| yield(*block_args) }\n else\n self\n end\n end", "language": "ruby", "code": "def link(*things)\n unless none?\n raise \"Illegal state for link: #{state}\"\n end\n\n things.each do |thing|\n case thing\n when DataMapper::Adapters::AbstractAdapter\n @adapters[thing] = :none\n when DataMapper::Repository\n link(thing.adapter)\n when DataMapper::Model\n link(*thing.repositories)\n when DataMapper::Resource\n link(thing.model)\n when Array\n link(*thing)\n else\n raise \"Unknown argument to #{self.class}#link: #{thing.inspect} (#{thing.class})\"\n end\n end\n\n if block_given?\n commit { |*block_args| yield(*block_args) }\n else\n self\n end\n end", "code_tokens": ["def", "link", "(", "*", "things", ")", "unless", "none?", "raise", "\"Illegal state for link: #{state}\"", "end", "things", ".", "each", "do", "|", "thing", "|", "case", "thing", "when", "DataMapper", "::", "Adapters", "::", "AbstractAdapter", "@adapters", "[", "thing", "]", "=", ":none", "when", "DataMapper", "::", "Repository", "link", "(", "thing", ".", "adapter", ")", "when", "DataMapper", "::", "Model", "link", "(", "thing", ".", "repositories", ")", "when", "DataMapper", "::", "Resource", "link", "(", "thing", ".", "model", ")", "when", "Array", "link", "(", "thing", ")", "else", "raise", "\"Unknown argument to #{self.class}#link: #{thing.inspect} (#{thing.class})\"", "end", "end", "if", "block_given?", "commit", "{", "|", "*", "block_args", "|", "yield", "(", "block_args", ")", "}", "else", "self", "end", "end"], "docstring": "Create a new Transaction\n\n @see Transaction#link\n\n In fact, it just calls #link with the given arguments at the end of the\n constructor.\n\n @api public\n Associate this Transaction with some things.\n\n @param [Object] things\n the things you want this Transaction associated with:\n\n Adapters::AbstractAdapter subclasses will be added as\n adapters as is.\n Arrays will have their elements added.\n Repository will have it's own @adapters added.\n Resource subclasses will have all the repositories of all\n their properties added.\n Resource instances will have all repositories of all their\n properties added.\n\n @param [Proc] block\n a block (taking one argument, the Transaction) to execute within\n this transaction. The transaction will begin and commit around\n the block, and rollback if an exception is raised.\n\n @api private", "docstring_tokens": ["Create", "a", "new", "Transaction"], "sha": "0f00dd41a593ea06347c815fedd297b58c5d5d99", "url": "https://github.com/datamapper/dm-transactions/blob/0f00dd41a593ea06347c815fedd297b58c5d5d99/lib/dm-transactions.rb#L69-L96", "partition": "test"} {"repo": "datamapper/dm-transactions", "path": "lib/dm-transactions.rb", "func_name": "DataMapper.Transaction.commit", "original_string": "def commit\n if block_given?\n unless none?\n raise \"Illegal state for commit with block: #{state}\"\n end\n\n begin\n self.begin\n rval = within { |*block_args| yield(*block_args) }\n rescue Exception => exception\n if begin?\n rollback\n end\n raise exception\n ensure\n unless exception\n if begin?\n commit\n end\n return rval\n end\n end\n else\n unless begin?\n raise \"Illegal state for commit without block: #{state}\"\n end\n each_adapter(:commit_adapter, [:log_fatal_transaction_breakage])\n each_adapter(:close_adapter, [:log_fatal_transaction_breakage])\n self.state = :commit\n end\n end", "language": "ruby", "code": "def commit\n if block_given?\n unless none?\n raise \"Illegal state for commit with block: #{state}\"\n end\n\n begin\n self.begin\n rval = within { |*block_args| yield(*block_args) }\n rescue Exception => exception\n if begin?\n rollback\n end\n raise exception\n ensure\n unless exception\n if begin?\n commit\n end\n return rval\n end\n end\n else\n unless begin?\n raise \"Illegal state for commit without block: #{state}\"\n end\n each_adapter(:commit_adapter, [:log_fatal_transaction_breakage])\n each_adapter(:close_adapter, [:log_fatal_transaction_breakage])\n self.state = :commit\n end\n end", "code_tokens": ["def", "commit", "if", "block_given?", "unless", "none?", "raise", "\"Illegal state for commit with block: #{state}\"", "end", "begin", "self", ".", "begin", "rval", "=", "within", "{", "|", "*", "block_args", "|", "yield", "(", "block_args", ")", "}", "rescue", "Exception", "=>", "exception", "if", "begin?", "rollback", "end", "raise", "exception", "ensure", "unless", "exception", "if", "begin?", "commit", "end", "return", "rval", "end", "end", "else", "unless", "begin?", "raise", "\"Illegal state for commit without block: #{state}\"", "end", "each_adapter", "(", ":commit_adapter", ",", "[", ":log_fatal_transaction_breakage", "]", ")", "each_adapter", "(", ":close_adapter", ",", "[", ":log_fatal_transaction_breakage", "]", ")", "self", ".", "state", "=", ":commit", "end", "end"], "docstring": "Commit the transaction\n\n If no block is given, it will simply commit any changes made since the\n Transaction did #begin.\n\n @param block a block (taking the one argument, the Transaction) to\n execute within this transaction. The transaction will begin and commit\n around the block, and roll back if an exception is raised.\n\n @api private", "docstring_tokens": ["Commit", "the", "transaction"], "sha": "0f00dd41a593ea06347c815fedd297b58c5d5d99", "url": "https://github.com/datamapper/dm-transactions/blob/0f00dd41a593ea06347c815fedd297b58c5d5d99/lib/dm-transactions.rb#L123-L153", "partition": "test"} {"repo": "datamapper/dm-transactions", "path": "lib/dm-transactions.rb", "func_name": "DataMapper.Transaction.within", "original_string": "def within\n unless block_given?\n raise 'No block provided'\n end\n\n unless begin?\n raise \"Illegal state for within: #{state}\"\n end\n\n adapters = @adapters\n\n adapters.each_key do |adapter|\n adapter.push_transaction(self)\n end\n\n begin\n yield self\n ensure\n adapters.each_key do |adapter|\n adapter.pop_transaction\n end\n end\n end", "language": "ruby", "code": "def within\n unless block_given?\n raise 'No block provided'\n end\n\n unless begin?\n raise \"Illegal state for within: #{state}\"\n end\n\n adapters = @adapters\n\n adapters.each_key do |adapter|\n adapter.push_transaction(self)\n end\n\n begin\n yield self\n ensure\n adapters.each_key do |adapter|\n adapter.pop_transaction\n end\n end\n end", "code_tokens": ["def", "within", "unless", "block_given?", "raise", "'No block provided'", "end", "unless", "begin?", "raise", "\"Illegal state for within: #{state}\"", "end", "adapters", "=", "@adapters", "adapters", ".", "each_key", "do", "|", "adapter", "|", "adapter", ".", "push_transaction", "(", "self", ")", "end", "begin", "yield", "self", "ensure", "adapters", ".", "each_key", "do", "|", "adapter", "|", "adapter", ".", "pop_transaction", "end", "end", "end"], "docstring": "Execute a block within this Transaction.\n\n No #begin, #commit or #rollback is performed in #within, but this\n Transaction will pushed on the per thread stack of transactions for each\n adapter it is associated with, and it will ensures that it will pop the\n Transaction away again after the block is finished.\n\n @param block the block of code to execute.\n\n @api private", "docstring_tokens": ["Execute", "a", "block", "within", "this", "Transaction", "."], "sha": "0f00dd41a593ea06347c815fedd297b58c5d5d99", "url": "https://github.com/datamapper/dm-transactions/blob/0f00dd41a593ea06347c815fedd297b58c5d5d99/lib/dm-transactions.rb#L179-L201", "partition": "test"} {"repo": "afcapel/websocket_parser", "path": "lib/websocket/parser.rb", "func_name": "WebSocket.Parser.next_message", "original_string": "def next_message\n read_header if @state == :header\n read_payload_length if @state == :payload_length\n read_mask_key if @state == :mask\n read_payload if @state == :payload\n\n @state == :complete ? process_frame! : nil\n\n rescue StandardError => ex\n if @on_error\n @on_error.call(ex.message)\n else\n raise ex\n end\n end", "language": "ruby", "code": "def next_message\n read_header if @state == :header\n read_payload_length if @state == :payload_length\n read_mask_key if @state == :mask\n read_payload if @state == :payload\n\n @state == :complete ? process_frame! : nil\n\n rescue StandardError => ex\n if @on_error\n @on_error.call(ex.message)\n else\n raise ex\n end\n end", "code_tokens": ["def", "next_message", "read_header", "if", "@state", "==", ":header", "read_payload_length", "if", "@state", "==", ":payload_length", "read_mask_key", "if", "@state", "==", ":mask", "read_payload", "if", "@state", "==", ":payload", "@state", "==", ":complete", "?", "process_frame!", ":", "nil", "rescue", "StandardError", "=>", "ex", "if", "@on_error", "@on_error", ".", "call", "(", "ex", ".", "message", ")", "else", "raise", "ex", "end", "end"], "docstring": "Parse next message in buffer", "docstring_tokens": ["Parse", "next", "message", "in", "buffer"], "sha": "3b2c87a898319b87e83094415b6c1f5a046ecd0b", "url": "https://github.com/afcapel/websocket_parser/blob/3b2c87a898319b87e83094415b6c1f5a046ecd0b/lib/websocket/parser.rb#L79-L93", "partition": "test"} {"repo": "ashrafuzzaman/query_report", "path": "lib/query_report/helper.rb", "func_name": "QueryReport.Helper.reporter", "original_string": "def reporter(query, options={}, &block)\n @report ||= QueryReport::Report.new(params, view_context, options)\n @report.query = query\n @report.instance_eval &block\n render_report(options) unless options[:skip_rendering]\n @report\n end", "language": "ruby", "code": "def reporter(query, options={}, &block)\n @report ||= QueryReport::Report.new(params, view_context, options)\n @report.query = query\n @report.instance_eval &block\n render_report(options) unless options[:skip_rendering]\n @report\n end", "code_tokens": ["def", "reporter", "(", "query", ",", "options", "=", "{", "}", ",", "&", "block", ")", "@report", "||=", "QueryReport", "::", "Report", ".", "new", "(", "params", ",", "view_context", ",", "options", ")", "@report", ".", "query", "=", "query", "@report", ".", "instance_eval", "block", "render_report", "(", "options", ")", "unless", "options", "[", ":skip_rendering", "]", "@report", "end"], "docstring": "Generates the reports\n @param query The base query that the reporter with start with [filters will be applied on it]\n @option options [Integer] :per_page If given then overrides the default kaminari per page option\n @option options [Boolean] :custom_view by default false, if set to true then the reporter will look for the file to render\n @option options [Boolean] :skip_rendering by default false, if set to true then the reporter will not render any thing, you will have to implement the rendering", "docstring_tokens": ["Generates", "the", "reports"], "sha": "68d4fcb15143fda395344d238ac629d064b90e9f", "url": "https://github.com/ashrafuzzaman/query_report/blob/68d4fcb15143fda395344d238ac629d064b90e9f/lib/query_report/helper.rb#L18-L24", "partition": "test"} {"repo": "marnen/foundation_form_builder", "path": "lib/foundation_form_builder/rails.rb", "func_name": "FoundationFormBuilder.Rails.infer_type", "original_string": "def infer_type(field_name)\n case field_name\n when :email, :time_zone\n field_name\n when %r{(\\b|_)password(\\b|_)}\n :password\n else\n type_mappings = {text: :textarea}\n\n db_type = @object.column_for_attribute(field_name).type\n case db_type\n when :text\n :textarea\n when :decimal, :integer, :float\n :numeric\n else\n db_type\n end\n end\n end", "language": "ruby", "code": "def infer_type(field_name)\n case field_name\n when :email, :time_zone\n field_name\n when %r{(\\b|_)password(\\b|_)}\n :password\n else\n type_mappings = {text: :textarea}\n\n db_type = @object.column_for_attribute(field_name).type\n case db_type\n when :text\n :textarea\n when :decimal, :integer, :float\n :numeric\n else\n db_type\n end\n end\n end", "code_tokens": ["def", "infer_type", "(", "field_name", ")", "case", "field_name", "when", ":email", ",", ":time_zone", "field_name", "when", "%r{", "\\b", "\\b", "}", ":password", "else", "type_mappings", "=", "{", "text", ":", ":textarea", "}", "db_type", "=", "@object", ".", "column_for_attribute", "(", "field_name", ")", ".", "type", "case", "db_type", "when", ":text", ":textarea", "when", ":decimal", ",", ":integer", ",", ":float", ":numeric", "else", "db_type", "end", "end", "end"], "docstring": "Infers the type of field to render based on the field name.\n\n @param [String, Symbol] the name of the field\n @return [Symbol] the inferred type", "docstring_tokens": ["Infers", "the", "type", "of", "field", "to", "render", "based", "on", "the", "field", "name", "."], "sha": "5e5118609bf54f5e11d936b85ebedccb4b7502a6", "url": "https://github.com/marnen/foundation_form_builder/blob/5e5118609bf54f5e11d936b85ebedccb4b7502a6/lib/foundation_form_builder/rails.rb#L85-L104", "partition": "test"} {"repo": "butchmarshall/active_record_survey", "path": "lib/active_record_survey/node.rb", "func_name": "ActiveRecordSurvey.Node.validate_instance_node", "original_string": "def validate_instance_node(instance_node)\n\t\t\t# Basically this cache is messed up? Why? TODO.\n\t\t\t# Reloading in the spec seems to fix this... but... this could be a booby trap for others\n\t\t\t#self.node_validations(true)\n\n\t\t\t# Check the validations on this node against the instance_node\n\t\t\tvalidations_passed = !self.node_validations.collect { |node_validation|\n\t\t\t\tnode_validation.validate_instance_node(instance_node, self)\n\t\t\t}.include?(false)\n\n\t\t\t# More complex....\n\t\t\t# Recureses to the parent node to check\n\t\t\t# This is to validate Node::Question since they don't have instance_nodes directly to validate them\n\t\t\tparent_validations_passed = !self.survey.node_maps.select { |i| i.node == self}.collect { |node_map|\n\t\t\t\tif node_map.parent\n\t\t\t\t\tnode_map.parent.node.validate_parent_instance_node(instance_node, self)\n\t\t\t\t# Hit top node\n\t\t\t\telse\n\t\t\t\t\ttrue\n\t\t\t\tend\n\t\t\t}.include?(false)\n\n\t\t\tvalidations_passed && parent_validations_passed\n\t\tend", "language": "ruby", "code": "def validate_instance_node(instance_node)\n\t\t\t# Basically this cache is messed up? Why? TODO.\n\t\t\t# Reloading in the spec seems to fix this... but... this could be a booby trap for others\n\t\t\t#self.node_validations(true)\n\n\t\t\t# Check the validations on this node against the instance_node\n\t\t\tvalidations_passed = !self.node_validations.collect { |node_validation|\n\t\t\t\tnode_validation.validate_instance_node(instance_node, self)\n\t\t\t}.include?(false)\n\n\t\t\t# More complex....\n\t\t\t# Recureses to the parent node to check\n\t\t\t# This is to validate Node::Question since they don't have instance_nodes directly to validate them\n\t\t\tparent_validations_passed = !self.survey.node_maps.select { |i| i.node == self}.collect { |node_map|\n\t\t\t\tif node_map.parent\n\t\t\t\t\tnode_map.parent.node.validate_parent_instance_node(instance_node, self)\n\t\t\t\t# Hit top node\n\t\t\t\telse\n\t\t\t\t\ttrue\n\t\t\t\tend\n\t\t\t}.include?(false)\n\n\t\t\tvalidations_passed && parent_validations_passed\n\t\tend", "code_tokens": ["def", "validate_instance_node", "(", "instance_node", ")", "# Basically this cache is messed up? Why? TODO.", "# Reloading in the spec seems to fix this... but... this could be a booby trap for others", "#self.node_validations(true)", "# Check the validations on this node against the instance_node", "validations_passed", "=", "!", "self", ".", "node_validations", ".", "collect", "{", "|", "node_validation", "|", "node_validation", ".", "validate_instance_node", "(", "instance_node", ",", "self", ")", "}", ".", "include?", "(", "false", ")", "# More complex....", "# Recureses to the parent node to check", "# This is to validate Node::Question since they don't have instance_nodes directly to validate them", "parent_validations_passed", "=", "!", "self", ".", "survey", ".", "node_maps", ".", "select", "{", "|", "i", "|", "i", ".", "node", "==", "self", "}", ".", "collect", "{", "|", "node_map", "|", "if", "node_map", ".", "parent", "node_map", ".", "parent", ".", "node", ".", "validate_parent_instance_node", "(", "instance_node", ",", "self", ")", "# Hit top node", "else", "true", "end", "}", ".", "include?", "(", "false", ")", "validations_passed", "&&", "parent_validations_passed", "end"], "docstring": "Run all validations applied to this node", "docstring_tokens": ["Run", "all", "validations", "applied", "to", "this", "node"], "sha": "cd0df44863c6cb158d129365f874156ac1ea7b9d", "url": "https://github.com/butchmarshall/active_record_survey/blob/cd0df44863c6cb158d129365f874156ac1ea7b9d/lib/active_record_survey/node.rb#L72-L95", "partition": "test"} {"repo": "butchmarshall/active_record_survey", "path": "lib/active_record_survey/node.rb", "func_name": "ActiveRecordSurvey.Node.instance_node_path_to_root?", "original_string": "def instance_node_path_to_root?(instance_node)\n\t\t\tinstance_nodes = instance_node.instance.instance_nodes.select { |i| i.node == self }\n\n\t\t\t# if ::ActiveRecordSurvey::Node::Answer but no votes, not a valid path\n\t\t\tif self.class.ancestors.include?(::ActiveRecordSurvey::Node::Answer) &&\n\t\t\t\t(instance_nodes.length === 0)\n\t\t\t\treturn false\n\t\t\tend\n\n\t\t\t# if ::ActiveRecordSurvey::Node::Question but no answers, so needs at least one vote directly on itself\n\t\t\tif self.class.ancestors.include?(::ActiveRecordSurvey::Node::Question) &&\n\t\t\t\t(self.answers.length === 0) && \n\t\t\t\t(instance_nodes.length === 0)\n\t\t\t\treturn false\n\t\t\tend\n\n\t\t\t# Start at each node_map of this node\n\t\t\t# Find the parent node ma\n\t\t\tpaths = self.survey.node_maps.select { |i| i.node == self }.collect { |node_map|\n\t\t\t\t# There is another level to traverse\n\t\t\t\tif node_map.parent\n\t\t\t\t\tnode_map.parent.node.instance_node_path_to_root?(instance_node)\n\t\t\t\t# This is the root node - we made it!\n\t\t\t\telse\n\t\t\t\t\ttrue\n\t\t\t\tend\n\t\t\t}\n\n\t\t\t# If recursion reports back to have at least one valid path to root\n\t\t\tpaths.include?(true)\n\t\tend", "language": "ruby", "code": "def instance_node_path_to_root?(instance_node)\n\t\t\tinstance_nodes = instance_node.instance.instance_nodes.select { |i| i.node == self }\n\n\t\t\t# if ::ActiveRecordSurvey::Node::Answer but no votes, not a valid path\n\t\t\tif self.class.ancestors.include?(::ActiveRecordSurvey::Node::Answer) &&\n\t\t\t\t(instance_nodes.length === 0)\n\t\t\t\treturn false\n\t\t\tend\n\n\t\t\t# if ::ActiveRecordSurvey::Node::Question but no answers, so needs at least one vote directly on itself\n\t\t\tif self.class.ancestors.include?(::ActiveRecordSurvey::Node::Question) &&\n\t\t\t\t(self.answers.length === 0) && \n\t\t\t\t(instance_nodes.length === 0)\n\t\t\t\treturn false\n\t\t\tend\n\n\t\t\t# Start at each node_map of this node\n\t\t\t# Find the parent node ma\n\t\t\tpaths = self.survey.node_maps.select { |i| i.node == self }.collect { |node_map|\n\t\t\t\t# There is another level to traverse\n\t\t\t\tif node_map.parent\n\t\t\t\t\tnode_map.parent.node.instance_node_path_to_root?(instance_node)\n\t\t\t\t# This is the root node - we made it!\n\t\t\t\telse\n\t\t\t\t\ttrue\n\t\t\t\tend\n\t\t\t}\n\n\t\t\t# If recursion reports back to have at least one valid path to root\n\t\t\tpaths.include?(true)\n\t\tend", "code_tokens": ["def", "instance_node_path_to_root?", "(", "instance_node", ")", "instance_nodes", "=", "instance_node", ".", "instance", ".", "instance_nodes", ".", "select", "{", "|", "i", "|", "i", ".", "node", "==", "self", "}", "# if ::ActiveRecordSurvey::Node::Answer but no votes, not a valid path", "if", "self", ".", "class", ".", "ancestors", ".", "include?", "(", "::", "ActiveRecordSurvey", "::", "Node", "::", "Answer", ")", "&&", "(", "instance_nodes", ".", "length", "===", "0", ")", "return", "false", "end", "# if ::ActiveRecordSurvey::Node::Question but no answers, so needs at least one vote directly on itself", "if", "self", ".", "class", ".", "ancestors", ".", "include?", "(", "::", "ActiveRecordSurvey", "::", "Node", "::", "Question", ")", "&&", "(", "self", ".", "answers", ".", "length", "===", "0", ")", "&&", "(", "instance_nodes", ".", "length", "===", "0", ")", "return", "false", "end", "# Start at each node_map of this node", "# Find the parent node ma", "paths", "=", "self", ".", "survey", ".", "node_maps", ".", "select", "{", "|", "i", "|", "i", ".", "node", "==", "self", "}", ".", "collect", "{", "|", "node_map", "|", "# There is another level to traverse", "if", "node_map", ".", "parent", "node_map", ".", "parent", ".", "node", ".", "instance_node_path_to_root?", "(", "instance_node", ")", "# This is the root node - we made it!", "else", "true", "end", "}", "# If recursion reports back to have at least one valid path to root", "paths", ".", "include?", "(", "true", ")", "end"], "docstring": "Whether there is a valid answer path from this node to the root node for the instance", "docstring_tokens": ["Whether", "there", "is", "a", "valid", "answer", "path", "from", "this", "node", "to", "the", "root", "node", "for", "the", "instance"], "sha": "cd0df44863c6cb158d129365f874156ac1ea7b9d", "url": "https://github.com/butchmarshall/active_record_survey/blob/cd0df44863c6cb158d129365f874156ac1ea7b9d/lib/active_record_survey/node.rb#L98-L128", "partition": "test"} {"repo": "butchmarshall/active_record_survey", "path": "lib/active_record_survey/node.rb", "func_name": "ActiveRecordSurvey.Node.build_link", "original_string": "def build_link(to_node)\n\t\t\t# build_link only accepts a to_node that inherits from Question\n\t\t\tif !to_node.class.ancestors.include?(::ActiveRecordSurvey::Node::Question)\n\t\t\t\traise ArgumentError.new \"to_node must inherit from ::ActiveRecordSurvey::Node::Question\"\n\t\t\tend\n\n\t\t\tif self.survey.nil?\n\t\t\t\traise ArgumentError.new \"A survey is required before calling #build_link\"\n\t\t\tend\n\n\t\t\tfrom_node_maps = self.survey.node_maps.select { |i| i.node == self && !i.marked_for_destruction? }\n\n\t\t\t# Answer has already got a question - throw error\n\t\t\tif from_node_maps.select { |i|\n\t\t\t\ti.children.length > 0\n\t\t\t}.length > 0\n\t\t\t\traise RuntimeError.new \"This node has already been linked\" \n\t\t\tend\n\n\t\t\t# Because we need something to clone - filter this further below\n\t\t\tto_node_maps = self.survey.node_maps.select { |i| i.node == to_node && !i.marked_for_destruction? }\n\n\t\t\tif to_node_maps.first.nil?\n\t\t\t\tto_node_maps << self.survey.node_maps.build(:survey => self.survey, :node => to_node)\n\t\t\tend\n\n\t\t\t# Ensure we can through each possible path of getting to this answer\n\t\t\tto_node_map = to_node_maps.first\n\t\t\tto_node_map.survey = self.survey # required due to voodoo - we want to use the same survey with the same object_id\n\n\t\t\t# We only want node maps that aren't linked somewhere\n\t\t\tto_node_maps = to_node_maps.select { |i| i.parent.nil? }\n\t\t\twhile to_node_maps.length < from_node_maps.length do\n\t\t\t\tto_node_maps.push(to_node_map.recursive_clone)\n\t\t\tend\n\n\t\t\t# Link unused node_maps to the new parents\n\t\t\tfrom_node_maps.each_with_index { |from_node_map, index|\n\t\t\t\tfrom_node_map.children << to_node_maps[index]\n\t\t\t}\n\n\t\t\t# Ensure no infinite loops were created\n\t\t\tfrom_node_maps.each { |node_map|\n\t\t\t\t# There is a path from Q -> A that is a loop\n\t\t\t\tif node_map.has_infinite_loop?\n\t\t\t\t\traise RuntimeError.new \"Infinite loop detected\"\n\t\t\t\tend\n\t\t\t}\n\t\tend", "language": "ruby", "code": "def build_link(to_node)\n\t\t\t# build_link only accepts a to_node that inherits from Question\n\t\t\tif !to_node.class.ancestors.include?(::ActiveRecordSurvey::Node::Question)\n\t\t\t\traise ArgumentError.new \"to_node must inherit from ::ActiveRecordSurvey::Node::Question\"\n\t\t\tend\n\n\t\t\tif self.survey.nil?\n\t\t\t\traise ArgumentError.new \"A survey is required before calling #build_link\"\n\t\t\tend\n\n\t\t\tfrom_node_maps = self.survey.node_maps.select { |i| i.node == self && !i.marked_for_destruction? }\n\n\t\t\t# Answer has already got a question - throw error\n\t\t\tif from_node_maps.select { |i|\n\t\t\t\ti.children.length > 0\n\t\t\t}.length > 0\n\t\t\t\traise RuntimeError.new \"This node has already been linked\" \n\t\t\tend\n\n\t\t\t# Because we need something to clone - filter this further below\n\t\t\tto_node_maps = self.survey.node_maps.select { |i| i.node == to_node && !i.marked_for_destruction? }\n\n\t\t\tif to_node_maps.first.nil?\n\t\t\t\tto_node_maps << self.survey.node_maps.build(:survey => self.survey, :node => to_node)\n\t\t\tend\n\n\t\t\t# Ensure we can through each possible path of getting to this answer\n\t\t\tto_node_map = to_node_maps.first\n\t\t\tto_node_map.survey = self.survey # required due to voodoo - we want to use the same survey with the same object_id\n\n\t\t\t# We only want node maps that aren't linked somewhere\n\t\t\tto_node_maps = to_node_maps.select { |i| i.parent.nil? }\n\t\t\twhile to_node_maps.length < from_node_maps.length do\n\t\t\t\tto_node_maps.push(to_node_map.recursive_clone)\n\t\t\tend\n\n\t\t\t# Link unused node_maps to the new parents\n\t\t\tfrom_node_maps.each_with_index { |from_node_map, index|\n\t\t\t\tfrom_node_map.children << to_node_maps[index]\n\t\t\t}\n\n\t\t\t# Ensure no infinite loops were created\n\t\t\tfrom_node_maps.each { |node_map|\n\t\t\t\t# There is a path from Q -> A that is a loop\n\t\t\t\tif node_map.has_infinite_loop?\n\t\t\t\t\traise RuntimeError.new \"Infinite loop detected\"\n\t\t\t\tend\n\t\t\t}\n\t\tend", "code_tokens": ["def", "build_link", "(", "to_node", ")", "# build_link only accepts a to_node that inherits from Question", "if", "!", "to_node", ".", "class", ".", "ancestors", ".", "include?", "(", "::", "ActiveRecordSurvey", "::", "Node", "::", "Question", ")", "raise", "ArgumentError", ".", "new", "\"to_node must inherit from ::ActiveRecordSurvey::Node::Question\"", "end", "if", "self", ".", "survey", ".", "nil?", "raise", "ArgumentError", ".", "new", "\"A survey is required before calling #build_link\"", "end", "from_node_maps", "=", "self", ".", "survey", ".", "node_maps", ".", "select", "{", "|", "i", "|", "i", ".", "node", "==", "self", "&&", "!", "i", ".", "marked_for_destruction?", "}", "# Answer has already got a question - throw error", "if", "from_node_maps", ".", "select", "{", "|", "i", "|", "i", ".", "children", ".", "length", ">", "0", "}", ".", "length", ">", "0", "raise", "RuntimeError", ".", "new", "\"This node has already been linked\"", "end", "# Because we need something to clone - filter this further below", "to_node_maps", "=", "self", ".", "survey", ".", "node_maps", ".", "select", "{", "|", "i", "|", "i", ".", "node", "==", "to_node", "&&", "!", "i", ".", "marked_for_destruction?", "}", "if", "to_node_maps", ".", "first", ".", "nil?", "to_node_maps", "<<", "self", ".", "survey", ".", "node_maps", ".", "build", "(", ":survey", "=>", "self", ".", "survey", ",", ":node", "=>", "to_node", ")", "end", "# Ensure we can through each possible path of getting to this answer", "to_node_map", "=", "to_node_maps", ".", "first", "to_node_map", ".", "survey", "=", "self", ".", "survey", "# required due to voodoo - we want to use the same survey with the same object_id", "# We only want node maps that aren't linked somewhere", "to_node_maps", "=", "to_node_maps", ".", "select", "{", "|", "i", "|", "i", ".", "parent", ".", "nil?", "}", "while", "to_node_maps", ".", "length", "<", "from_node_maps", ".", "length", "do", "to_node_maps", ".", "push", "(", "to_node_map", ".", "recursive_clone", ")", "end", "# Link unused node_maps to the new parents", "from_node_maps", ".", "each_with_index", "{", "|", "from_node_map", ",", "index", "|", "from_node_map", ".", "children", "<<", "to_node_maps", "[", "index", "]", "}", "# Ensure no infinite loops were created", "from_node_maps", ".", "each", "{", "|", "node_map", "|", "# There is a path from Q -> A that is a loop", "if", "node_map", ".", "has_infinite_loop?", "raise", "RuntimeError", ".", "new", "\"Infinite loop detected\"", "end", "}", "end"], "docstring": "Build a link from this node to another node\n Building a link actually needs to throw off a whole new clone of all children nodes", "docstring_tokens": ["Build", "a", "link", "from", "this", "node", "to", "another", "node", "Building", "a", "link", "actually", "needs", "to", "throw", "off", "a", "whole", "new", "clone", "of", "all", "children", "nodes"], "sha": "cd0df44863c6cb158d129365f874156ac1ea7b9d", "url": "https://github.com/butchmarshall/active_record_survey/blob/cd0df44863c6cb158d129365f874156ac1ea7b9d/lib/active_record_survey/node.rb#L132-L180", "partition": "test"} {"repo": "butchmarshall/active_record_survey", "path": "lib/active_record_survey/node.rb", "func_name": "ActiveRecordSurvey.Node.before_destroy_rebuild_node_map", "original_string": "def before_destroy_rebuild_node_map\n\t\t\t\t# All the node_maps from this node\n\t\t\t\tself.survey.node_maps.select { |i|\n\t\t\t\t\ti.node == self\n\t\t\t\t}.each { |node_map|\n\t\t\t\t\t# Remap all of this nodes children to the parent\n\t\t\t\t\tnode_map.children.each { |child|\n\t\t\t\t\t\tnode_map.parent.children << child\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\ttrue\n\t\t\tend", "language": "ruby", "code": "def before_destroy_rebuild_node_map\n\t\t\t\t# All the node_maps from this node\n\t\t\t\tself.survey.node_maps.select { |i|\n\t\t\t\t\ti.node == self\n\t\t\t\t}.each { |node_map|\n\t\t\t\t\t# Remap all of this nodes children to the parent\n\t\t\t\t\tnode_map.children.each { |child|\n\t\t\t\t\t\tnode_map.parent.children << child\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\ttrue\n\t\t\tend", "code_tokens": ["def", "before_destroy_rebuild_node_map", "# All the node_maps from this node", "self", ".", "survey", ".", "node_maps", ".", "select", "{", "|", "i", "|", "i", ".", "node", "==", "self", "}", ".", "each", "{", "|", "node_map", "|", "# Remap all of this nodes children to the parent", "node_map", ".", "children", ".", "each", "{", "|", "child", "|", "node_map", ".", "parent", ".", "children", "<<", "child", "}", "}", "true", "end"], "docstring": "Before a node is destroyed, will re-build the node_map links from parent to child if they exist", "docstring_tokens": ["Before", "a", "node", "is", "destroyed", "will", "re", "-", "build", "the", "node_map", "links", "from", "parent", "to", "child", "if", "they", "exist"], "sha": "cd0df44863c6cb158d129365f874156ac1ea7b9d", "url": "https://github.com/butchmarshall/active_record_survey/blob/cd0df44863c6cb158d129365f874156ac1ea7b9d/lib/active_record_survey/node.rb#L184-L196", "partition": "test"} {"repo": "butchmarshall/active_record_survey", "path": "lib/active_record_survey/node/answer/scale.rb", "func_name": "ActiveRecordSurvey.Node::Answer::Scale.validate_instance_node", "original_string": "def validate_instance_node(instance_node)\n\t\t\t# super - all validations on this node pass\n\t\t\tsuper &&\n\t\t\t(instance_node.value.to_s.empty? || !instance_node.value.to_s.match(/^(\\d+(\\.\\d+)?)$/).nil?)\n\t\tend", "language": "ruby", "code": "def validate_instance_node(instance_node)\n\t\t\t# super - all validations on this node pass\n\t\t\tsuper &&\n\t\t\t(instance_node.value.to_s.empty? || !instance_node.value.to_s.match(/^(\\d+(\\.\\d+)?)$/).nil?)\n\t\tend", "code_tokens": ["def", "validate_instance_node", "(", "instance_node", ")", "# super - all validations on this node pass", "super", "&&", "(", "instance_node", ".", "value", ".", "to_s", ".", "empty?", "||", "!", "instance_node", ".", "value", ".", "to_s", ".", "match", "(", "/", "\\d", "\\.", "\\d", "/", ")", ".", "nil?", ")", "end"], "docstring": "Accept integer, float, or empty values", "docstring_tokens": ["Accept", "integer", "float", "or", "empty", "values"], "sha": "cd0df44863c6cb158d129365f874156ac1ea7b9d", "url": "https://github.com/butchmarshall/active_record_survey/blob/cd0df44863c6cb158d129365f874156ac1ea7b9d/lib/active_record_survey/node/answer/scale.rb#L8-L12", "partition": "test"} {"repo": "butchmarshall/active_record_survey", "path": "lib/active_record_survey/node/answer/scale.rb", "func_name": "ActiveRecordSurvey.Node::Answer::Scale.is_answered_for_instance?", "original_string": "def is_answered_for_instance?(instance)\n\t\t\tif instance_node = self.instance_node_for_instance(instance)\n\t\t\t\t# Answered if not empty and > 0\n\t\t\t\t!instance_node.value.to_s.empty? && instance_node.value.to_i >= 0\n\t\t\telse\n\t\t\t\tfalse\n\t\t\tend\n\t\tend", "language": "ruby", "code": "def is_answered_for_instance?(instance)\n\t\t\tif instance_node = self.instance_node_for_instance(instance)\n\t\t\t\t# Answered if not empty and > 0\n\t\t\t\t!instance_node.value.to_s.empty? && instance_node.value.to_i >= 0\n\t\t\telse\n\t\t\t\tfalse\n\t\t\tend\n\t\tend", "code_tokens": ["def", "is_answered_for_instance?", "(", "instance", ")", "if", "instance_node", "=", "self", ".", "instance_node_for_instance", "(", "instance", ")", "# Answered if not empty and > 0", "!", "instance_node", ".", "value", ".", "to_s", ".", "empty?", "&&", "instance_node", ".", "value", ".", "to_i", ">=", "0", "else", "false", "end", "end"], "docstring": "Scale answers are considered answered if they have a value of greater than \"0\"", "docstring_tokens": ["Scale", "answers", "are", "considered", "answered", "if", "they", "have", "a", "value", "of", "greater", "than", "0"], "sha": "cd0df44863c6cb158d129365f874156ac1ea7b9d", "url": "https://github.com/butchmarshall/active_record_survey/blob/cd0df44863c6cb158d129365f874156ac1ea7b9d/lib/active_record_survey/node/answer/scale.rb#L15-L22", "partition": "test"} {"repo": "butchmarshall/active_record_survey", "path": "lib/active_record_survey/node/answer/text.rb", "func_name": "ActiveRecordSurvey.Node::Answer::Text.is_answered_for_instance?", "original_string": "def is_answered_for_instance?(instance)\n\t\t\tif instance_node = self.instance_node_for_instance(instance)\n\t\t\t\t# Answered if has text\n\t\t\t\tinstance_node.value.to_s.strip.length > 0\n\t\t\telse\n\t\t\t\tfalse\n\t\t\tend\n\t\tend", "language": "ruby", "code": "def is_answered_for_instance?(instance)\n\t\t\tif instance_node = self.instance_node_for_instance(instance)\n\t\t\t\t# Answered if has text\n\t\t\t\tinstance_node.value.to_s.strip.length > 0\n\t\t\telse\n\t\t\t\tfalse\n\t\t\tend\n\t\tend", "code_tokens": ["def", "is_answered_for_instance?", "(", "instance", ")", "if", "instance_node", "=", "self", ".", "instance_node_for_instance", "(", "instance", ")", "# Answered if has text", "instance_node", ".", "value", ".", "to_s", ".", "strip", ".", "length", ">", "0", "else", "false", "end", "end"], "docstring": "Text answers are considered answered if they have text entered", "docstring_tokens": ["Text", "answers", "are", "considered", "answered", "if", "they", "have", "text", "entered"], "sha": "cd0df44863c6cb158d129365f874156ac1ea7b9d", "url": "https://github.com/butchmarshall/active_record_survey/blob/cd0df44863c6cb158d129365f874156ac1ea7b9d/lib/active_record_survey/node/answer/text.rb#L8-L15", "partition": "test"} {"repo": "butchmarshall/active_record_survey", "path": "lib/active_record_survey/node_map.rb", "func_name": "ActiveRecordSurvey.NodeMap.recursive_clone", "original_string": "def recursive_clone\n\t\t\tnode_map = self.survey.node_maps.build(:survey => self.survey, :node => self.node)\n\t\t\tself.survey.node_maps.select { |i| i.parent == self && !i.marked_for_destruction? }.each { |child_node|\n\t\t\t\tchild_node.survey = self.survey # required due to voodoo - we want to use the same survey with the same object_id\n\t\t\t\tnode_map.children << child_node.recursive_clone\n\t\t\t}\n\t\t\tnode_map\n\t\tend", "language": "ruby", "code": "def recursive_clone\n\t\t\tnode_map = self.survey.node_maps.build(:survey => self.survey, :node => self.node)\n\t\t\tself.survey.node_maps.select { |i| i.parent == self && !i.marked_for_destruction? }.each { |child_node|\n\t\t\t\tchild_node.survey = self.survey # required due to voodoo - we want to use the same survey with the same object_id\n\t\t\t\tnode_map.children << child_node.recursive_clone\n\t\t\t}\n\t\t\tnode_map\n\t\tend", "code_tokens": ["def", "recursive_clone", "node_map", "=", "self", ".", "survey", ".", "node_maps", ".", "build", "(", ":survey", "=>", "self", ".", "survey", ",", ":node", "=>", "self", ".", "node", ")", "self", ".", "survey", ".", "node_maps", ".", "select", "{", "|", "i", "|", "i", ".", "parent", "==", "self", "&&", "!", "i", ".", "marked_for_destruction?", "}", ".", "each", "{", "|", "child_node", "|", "child_node", ".", "survey", "=", "self", ".", "survey", "# required due to voodoo - we want to use the same survey with the same object_id", "node_map", ".", "children", "<<", "child_node", ".", "recursive_clone", "}", "node_map", "end"], "docstring": "Recursively creates a copy of this entire node_map", "docstring_tokens": ["Recursively", "creates", "a", "copy", "of", "this", "entire", "node_map"], "sha": "cd0df44863c6cb158d129365f874156ac1ea7b9d", "url": "https://github.com/butchmarshall/active_record_survey/blob/cd0df44863c6cb158d129365f874156ac1ea7b9d/lib/active_record_survey/node_map.rb#L11-L18", "partition": "test"} {"repo": "butchmarshall/active_record_survey", "path": "lib/active_record_survey/node_map.rb", "func_name": "ActiveRecordSurvey.NodeMap.ancestors_until_node_not_ancestor_of", "original_string": "def ancestors_until_node_not_ancestor_of(klass)\n\t\t\tif !self.parent || !self.node.class.ancestors.include?(klass)\n\t\t\t\treturn []\n\t\t\tend\n\n\t\t\t[self] + self.parent.ancestors_until_node_not_ancestor_of(klass)\n\t\tend", "language": "ruby", "code": "def ancestors_until_node_not_ancestor_of(klass)\n\t\t\tif !self.parent || !self.node.class.ancestors.include?(klass)\n\t\t\t\treturn []\n\t\t\tend\n\n\t\t\t[self] + self.parent.ancestors_until_node_not_ancestor_of(klass)\n\t\tend", "code_tokens": ["def", "ancestors_until_node_not_ancestor_of", "(", "klass", ")", "if", "!", "self", ".", "parent", "||", "!", "self", ".", "node", ".", "class", ".", "ancestors", ".", "include?", "(", "klass", ")", "return", "[", "]", "end", "[", "self", "]", "+", "self", ".", "parent", ".", "ancestors_until_node_not_ancestor_of", "(", "klass", ")", "end"], "docstring": "Gets all the ancestor nodes until one is not an ancestor of klass", "docstring_tokens": ["Gets", "all", "the", "ancestor", "nodes", "until", "one", "is", "not", "an", "ancestor", "of", "klass"], "sha": "cd0df44863c6cb158d129365f874156ac1ea7b9d", "url": "https://github.com/butchmarshall/active_record_survey/blob/cd0df44863c6cb158d129365f874156ac1ea7b9d/lib/active_record_survey/node_map.rb#L56-L62", "partition": "test"} {"repo": "butchmarshall/active_record_survey", "path": "lib/active_record_survey/node_map.rb", "func_name": "ActiveRecordSurvey.NodeMap.children_until_node_not_ancestor_of", "original_string": "def children_until_node_not_ancestor_of(klass)\n\t\t\tif !self.node.class.ancestors.include?(klass)\n\t\t\t\treturn []\n\t\t\tend\n\n\t\t\t[self] + self.children.collect { |i|\n\t\t\t\ti.children_until_node_not_ancestor_of(klass)\n\t\t\t}\n\t\tend", "language": "ruby", "code": "def children_until_node_not_ancestor_of(klass)\n\t\t\tif !self.node.class.ancestors.include?(klass)\n\t\t\t\treturn []\n\t\t\tend\n\n\t\t\t[self] + self.children.collect { |i|\n\t\t\t\ti.children_until_node_not_ancestor_of(klass)\n\t\t\t}\n\t\tend", "code_tokens": ["def", "children_until_node_not_ancestor_of", "(", "klass", ")", "if", "!", "self", ".", "node", ".", "class", ".", "ancestors", ".", "include?", "(", "klass", ")", "return", "[", "]", "end", "[", "self", "]", "+", "self", ".", "children", ".", "collect", "{", "|", "i", "|", "i", ".", "children_until_node_not_ancestor_of", "(", "klass", ")", "}", "end"], "docstring": "Gets all the child nodes until one is not an ancestor of klass", "docstring_tokens": ["Gets", "all", "the", "child", "nodes", "until", "one", "is", "not", "an", "ancestor", "of", "klass"], "sha": "cd0df44863c6cb158d129365f874156ac1ea7b9d", "url": "https://github.com/butchmarshall/active_record_survey/blob/cd0df44863c6cb158d129365f874156ac1ea7b9d/lib/active_record_survey/node_map.rb#L65-L73", "partition": "test"} {"repo": "butchmarshall/active_record_survey", "path": "lib/active_record_survey/node_map.rb", "func_name": "ActiveRecordSurvey.NodeMap.has_infinite_loop?", "original_string": "def has_infinite_loop?(path = [])\n\t\t\tself.survey.node_maps.select { |i| i.parent == self && !i.marked_for_destruction? }.each { |i|\n\t\t\t\t# Detect infinite loop\n\t\t\t\tif path.include?(self.node) || i.has_infinite_loop?(path.clone.push(self.node))\n\t\t\t\t\treturn true\n\t\t\t\tend\n\t\t\t}\n\t\t\tpath.include?(self.node)\n\t\tend", "language": "ruby", "code": "def has_infinite_loop?(path = [])\n\t\t\tself.survey.node_maps.select { |i| i.parent == self && !i.marked_for_destruction? }.each { |i|\n\t\t\t\t# Detect infinite loop\n\t\t\t\tif path.include?(self.node) || i.has_infinite_loop?(path.clone.push(self.node))\n\t\t\t\t\treturn true\n\t\t\t\tend\n\t\t\t}\n\t\t\tpath.include?(self.node)\n\t\tend", "code_tokens": ["def", "has_infinite_loop?", "(", "path", "=", "[", "]", ")", "self", ".", "survey", ".", "node_maps", ".", "select", "{", "|", "i", "|", "i", ".", "parent", "==", "self", "&&", "!", "i", ".", "marked_for_destruction?", "}", ".", "each", "{", "|", "i", "|", "# Detect infinite loop", "if", "path", ".", "include?", "(", "self", ".", "node", ")", "||", "i", ".", "has_infinite_loop?", "(", "path", ".", "clone", ".", "push", "(", "self", ".", "node", ")", ")", "return", "true", "end", "}", "path", ".", "include?", "(", "self", ".", "node", ")", "end"], "docstring": "Check to see whether there is an infinite loop from this node_map", "docstring_tokens": ["Check", "to", "see", "whether", "there", "is", "an", "infinite", "loop", "from", "this", "node_map"], "sha": "cd0df44863c6cb158d129365f874156ac1ea7b9d", "url": "https://github.com/butchmarshall/active_record_survey/blob/cd0df44863c6cb158d129365f874156ac1ea7b9d/lib/active_record_survey/node_map.rb#L76-L84", "partition": "test"} {"repo": "butchmarshall/active_record_survey", "path": "lib/active_record_survey/node_validation/minimum_value.rb", "func_name": "ActiveRecordSurvey.NodeValidation::MinimumValue.validate_instance_node", "original_string": "def validate_instance_node(instance_node, answer_node = nil)\n\t\t\tis_valid = (!instance_node.value.to_s.empty? && instance_node.value.to_f >= self.value.to_f)\n\n\t\t\tinstance_node.errors[:base] << { :nodes => { answer_node.id => [\"MINIMUM_VALUE\"] } } if !is_valid\n\n\t\t\tis_valid\n\t\tend", "language": "ruby", "code": "def validate_instance_node(instance_node, answer_node = nil)\n\t\t\tis_valid = (!instance_node.value.to_s.empty? && instance_node.value.to_f >= self.value.to_f)\n\n\t\t\tinstance_node.errors[:base] << { :nodes => { answer_node.id => [\"MINIMUM_VALUE\"] } } if !is_valid\n\n\t\t\tis_valid\n\t\tend", "code_tokens": ["def", "validate_instance_node", "(", "instance_node", ",", "answer_node", "=", "nil", ")", "is_valid", "=", "(", "!", "instance_node", ".", "value", ".", "to_s", ".", "empty?", "&&", "instance_node", ".", "value", ".", "to_f", ">=", "self", ".", "value", ".", "to_f", ")", "instance_node", ".", "errors", "[", ":base", "]", "<<", "{", ":nodes", "=>", "{", "answer_node", ".", "id", "=>", "[", "\"MINIMUM_VALUE\"", "]", "}", "}", "if", "!", "is_valid", "is_valid", "end"], "docstring": "Validate the instance_node value is greater than the minimum", "docstring_tokens": ["Validate", "the", "instance_node", "value", "is", "greater", "than", "the", "minimum"], "sha": "cd0df44863c6cb158d129365f874156ac1ea7b9d", "url": "https://github.com/butchmarshall/active_record_survey/blob/cd0df44863c6cb158d129365f874156ac1ea7b9d/lib/active_record_survey/node_validation/minimum_value.rb#L5-L11", "partition": "test"} {"repo": "butchmarshall/active_record_survey", "path": "lib/active_record_survey/node_validation/minimum_answer.rb", "func_name": "ActiveRecordSurvey.NodeValidation::MinimumAnswer.validate_instance_node", "original_string": "def validate_instance_node(instance_node, question_node = nil)\n\t\t\t# Only makes sense for questions to have minimum answers\n\t\t\tif !question_node.class.ancestors.include?(::ActiveRecordSurvey::Node::Question)\n\t\t\t\treturn false \n\t\t\tend\n\n\t\t\tinstance = instance_node.instance\n\n\t\t\t# Go through the node_map of this node\n\t\t\ttotal_answered = question_node.node_maps.collect { |question_node_map|\n\t\t\t\t# Get all children until a childs node isn't an answer\n\t\t\t\tquestion_node_map.children.collect { |i|\n\t\t\t\t\ti.children_until_node_not_ancestor_of(::ActiveRecordSurvey::Node::Answer)\n\t\t\t\t}.flatten.collect { |i|\n\t\t\t\t\ti.node.is_answered_for_instance?(instance)\n\t\t\t\t}\n\t\t\t}.flatten.select { |i| i }.count\n\n\t\t\tis_valid = (total_answered >= self.value.to_i)\n\n\t\t\tinstance_node.errors[:base] << { :nodes => { question_node.id => [\"MINIMUM_ANSWER\"] } } if !is_valid\n\n\t\t\tis_valid\n\t\tend", "language": "ruby", "code": "def validate_instance_node(instance_node, question_node = nil)\n\t\t\t# Only makes sense for questions to have minimum answers\n\t\t\tif !question_node.class.ancestors.include?(::ActiveRecordSurvey::Node::Question)\n\t\t\t\treturn false \n\t\t\tend\n\n\t\t\tinstance = instance_node.instance\n\n\t\t\t# Go through the node_map of this node\n\t\t\ttotal_answered = question_node.node_maps.collect { |question_node_map|\n\t\t\t\t# Get all children until a childs node isn't an answer\n\t\t\t\tquestion_node_map.children.collect { |i|\n\t\t\t\t\ti.children_until_node_not_ancestor_of(::ActiveRecordSurvey::Node::Answer)\n\t\t\t\t}.flatten.collect { |i|\n\t\t\t\t\ti.node.is_answered_for_instance?(instance)\n\t\t\t\t}\n\t\t\t}.flatten.select { |i| i }.count\n\n\t\t\tis_valid = (total_answered >= self.value.to_i)\n\n\t\t\tinstance_node.errors[:base] << { :nodes => { question_node.id => [\"MINIMUM_ANSWER\"] } } if !is_valid\n\n\t\t\tis_valid\n\t\tend", "code_tokens": ["def", "validate_instance_node", "(", "instance_node", ",", "question_node", "=", "nil", ")", "# Only makes sense for questions to have minimum answers", "if", "!", "question_node", ".", "class", ".", "ancestors", ".", "include?", "(", "::", "ActiveRecordSurvey", "::", "Node", "::", "Question", ")", "return", "false", "end", "instance", "=", "instance_node", ".", "instance", "# Go through the node_map of this node", "total_answered", "=", "question_node", ".", "node_maps", ".", "collect", "{", "|", "question_node_map", "|", "# Get all children until a childs node isn't an answer", "question_node_map", ".", "children", ".", "collect", "{", "|", "i", "|", "i", ".", "children_until_node_not_ancestor_of", "(", "::", "ActiveRecordSurvey", "::", "Node", "::", "Answer", ")", "}", ".", "flatten", ".", "collect", "{", "|", "i", "|", "i", ".", "node", ".", "is_answered_for_instance?", "(", "instance", ")", "}", "}", ".", "flatten", ".", "select", "{", "|", "i", "|", "i", "}", ".", "count", "is_valid", "=", "(", "total_answered", ">=", "self", ".", "value", ".", "to_i", ")", "instance_node", ".", "errors", "[", ":base", "]", "<<", "{", ":nodes", "=>", "{", "question_node", ".", "id", "=>", "[", "\"MINIMUM_ANSWER\"", "]", "}", "}", "if", "!", "is_valid", "is_valid", "end"], "docstring": "Validate the instance_node to ensure a minimum number of answers are made", "docstring_tokens": ["Validate", "the", "instance_node", "to", "ensure", "a", "minimum", "number", "of", "answers", "are", "made"], "sha": "cd0df44863c6cb158d129365f874156ac1ea7b9d", "url": "https://github.com/butchmarshall/active_record_survey/blob/cd0df44863c6cb158d129365f874156ac1ea7b9d/lib/active_record_survey/node_validation/minimum_answer.rb#L5-L28", "partition": "test"} {"repo": "butchmarshall/active_record_survey", "path": "lib/active_record_survey/node/answer.rb", "func_name": "ActiveRecordSurvey.Node::Answer.validate_node", "original_string": "def validate_node(instance)\n\t\t\t# Ensure each parent node to this node (the goal here is to hit a question node) is valid\n\t\t\t!self.survey.node_maps.select { |i|\n\t\t\t\ti.node == self\n\t\t\t}.collect { |node_map|\n\t\t\t\tnode_map.parent.node.validate_node(instance)\n\t\t\t}.include?(false)\n\t\tend", "language": "ruby", "code": "def validate_node(instance)\n\t\t\t# Ensure each parent node to this node (the goal here is to hit a question node) is valid\n\t\t\t!self.survey.node_maps.select { |i|\n\t\t\t\ti.node == self\n\t\t\t}.collect { |node_map|\n\t\t\t\tnode_map.parent.node.validate_node(instance)\n\t\t\t}.include?(false)\n\t\tend", "code_tokens": ["def", "validate_node", "(", "instance", ")", "# Ensure each parent node to this node (the goal here is to hit a question node) is valid", "!", "self", ".", "survey", ".", "node_maps", ".", "select", "{", "|", "i", "|", "i", ".", "node", "==", "self", "}", ".", "collect", "{", "|", "node_map", "|", "node_map", ".", "parent", ".", "node", ".", "validate_node", "(", "instance", ")", "}", ".", "include?", "(", "false", ")", "end"], "docstring": "Answer nodes are valid if their questions are valid!\n Validate this node against an instance", "docstring_tokens": ["Answer", "nodes", "are", "valid", "if", "their", "questions", "are", "valid!", "Validate", "this", "node", "against", "an", "instance"], "sha": "cd0df44863c6cb158d129365f874156ac1ea7b9d", "url": "https://github.com/butchmarshall/active_record_survey/blob/cd0df44863c6cb158d129365f874156ac1ea7b9d/lib/active_record_survey/node/answer.rb#L5-L12", "partition": "test"} {"repo": "butchmarshall/active_record_survey", "path": "lib/active_record_survey/node/answer.rb", "func_name": "ActiveRecordSurvey.Node::Answer.question", "original_string": "def question\n\t\t\tself.survey.node_maps.select { |i|\n\t\t\t\ti.node == self\n\t\t\t}.collect { |node_map|\n\t\t\t\tif node_map.parent && node_map.parent.node\n\t\t\t\t\t# Question is not the next parent - recurse!\n\t\t\t\t\tif node_map.parent.node.class.ancestors.include?(::ActiveRecordSurvey::Node::Answer)\n\t\t\t\t\t\tnode_map.parent.node.question\n\t\t\t\t\telse\n\t\t\t\t\t\tnode_map.parent.node\n\t\t\t\t\tend\n\t\t\t\t# Root already\n\t\t\t\telse\n\t\t\t\t\tnil\n\t\t\t\tend\n\t\t\t}.first\n\t\tend", "language": "ruby", "code": "def question\n\t\t\tself.survey.node_maps.select { |i|\n\t\t\t\ti.node == self\n\t\t\t}.collect { |node_map|\n\t\t\t\tif node_map.parent && node_map.parent.node\n\t\t\t\t\t# Question is not the next parent - recurse!\n\t\t\t\t\tif node_map.parent.node.class.ancestors.include?(::ActiveRecordSurvey::Node::Answer)\n\t\t\t\t\t\tnode_map.parent.node.question\n\t\t\t\t\telse\n\t\t\t\t\t\tnode_map.parent.node\n\t\t\t\t\tend\n\t\t\t\t# Root already\n\t\t\t\telse\n\t\t\t\t\tnil\n\t\t\t\tend\n\t\t\t}.first\n\t\tend", "code_tokens": ["def", "question", "self", ".", "survey", ".", "node_maps", ".", "select", "{", "|", "i", "|", "i", ".", "node", "==", "self", "}", ".", "collect", "{", "|", "node_map", "|", "if", "node_map", ".", "parent", "&&", "node_map", ".", "parent", ".", "node", "# Question is not the next parent - recurse!", "if", "node_map", ".", "parent", ".", "node", ".", "class", ".", "ancestors", ".", "include?", "(", "::", "ActiveRecordSurvey", "::", "Node", "::", "Answer", ")", "node_map", ".", "parent", ".", "node", ".", "question", "else", "node_map", ".", "parent", ".", "node", "end", "# Root already", "else", "nil", "end", "}", ".", "first", "end"], "docstring": "Returns the question that preceeds this answer", "docstring_tokens": ["Returns", "the", "question", "that", "preceeds", "this", "answer"], "sha": "cd0df44863c6cb158d129365f874156ac1ea7b9d", "url": "https://github.com/butchmarshall/active_record_survey/blob/cd0df44863c6cb158d129365f874156ac1ea7b9d/lib/active_record_survey/node/answer.rb#L15-L31", "partition": "test"} {"repo": "butchmarshall/active_record_survey", "path": "lib/active_record_survey/node/answer.rb", "func_name": "ActiveRecordSurvey.Node::Answer.next_question", "original_string": "def next_question\n\t\t\tself.survey.node_maps.select { |i|\n\t\t\t\ti.node == self && !i.marked_for_destruction?\n\t\t\t}.each { |answer_node_map|\n\t\t\t\tanswer_node_map.children.each { |child|\n\t\t\t\t\tif !child.node.nil? && !child.marked_for_destruction?\n\t\t\t\t\t\tif child.node.class.ancestors.include?(::ActiveRecordSurvey::Node::Question)\n\t\t\t\t\t\t\treturn child.node\n\t\t\t\t\t\telsif child.node.class.ancestors.include?(::ActiveRecordSurvey::Node::Answer)\n\t\t\t\t\t\t\treturn child.node.next_question \n\t\t\t\t\t\tend\n\t\t\t\t\telse\n\t\t\t\t\t\treturn nil\n\t\t\t\t\tend\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn nil\n\t\tend", "language": "ruby", "code": "def next_question\n\t\t\tself.survey.node_maps.select { |i|\n\t\t\t\ti.node == self && !i.marked_for_destruction?\n\t\t\t}.each { |answer_node_map|\n\t\t\t\tanswer_node_map.children.each { |child|\n\t\t\t\t\tif !child.node.nil? && !child.marked_for_destruction?\n\t\t\t\t\t\tif child.node.class.ancestors.include?(::ActiveRecordSurvey::Node::Question)\n\t\t\t\t\t\t\treturn child.node\n\t\t\t\t\t\telsif child.node.class.ancestors.include?(::ActiveRecordSurvey::Node::Answer)\n\t\t\t\t\t\t\treturn child.node.next_question \n\t\t\t\t\t\tend\n\t\t\t\t\telse\n\t\t\t\t\t\treturn nil\n\t\t\t\t\tend\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn nil\n\t\tend", "code_tokens": ["def", "next_question", "self", ".", "survey", ".", "node_maps", ".", "select", "{", "|", "i", "|", "i", ".", "node", "==", "self", "&&", "!", "i", ".", "marked_for_destruction?", "}", ".", "each", "{", "|", "answer_node_map", "|", "answer_node_map", ".", "children", ".", "each", "{", "|", "child", "|", "if", "!", "child", ".", "node", ".", "nil?", "&&", "!", "child", ".", "marked_for_destruction?", "if", "child", ".", "node", ".", "class", ".", "ancestors", ".", "include?", "(", "::", "ActiveRecordSurvey", "::", "Node", "::", "Question", ")", "return", "child", ".", "node", "elsif", "child", ".", "node", ".", "class", ".", "ancestors", ".", "include?", "(", "::", "ActiveRecordSurvey", "::", "Node", "::", "Answer", ")", "return", "child", ".", "node", ".", "next_question", "end", "else", "return", "nil", "end", "}", "}", "return", "nil", "end"], "docstring": "Returns the question that follows this answer", "docstring_tokens": ["Returns", "the", "question", "that", "follows", "this", "answer"], "sha": "cd0df44863c6cb158d129365f874156ac1ea7b9d", "url": "https://github.com/butchmarshall/active_record_survey/blob/cd0df44863c6cb158d129365f874156ac1ea7b9d/lib/active_record_survey/node/answer.rb#L34-L51", "partition": "test"} {"repo": "butchmarshall/active_record_survey", "path": "lib/active_record_survey/node/answer.rb", "func_name": "ActiveRecordSurvey.Node::Answer.remove_link", "original_string": "def remove_link\n\t\t\t# not linked to a question - nothing to remove!\n\t\t\treturn true if (question = self.next_question).nil?\n\n\t\t\tcount = 0\n\t\t\tto_remove = []\n\t\t\tself.survey.node_maps.each { |node_map|\n\t\t\t\tif node_map.node == question\n\t\t\t\t\tif count > 0\n\t\t\t\t\t\tto_remove.concat(node_map.self_and_descendants)\n\t\t\t\t\telse\n\t\t\t\t\t\tnode_map.parent = nil\n\t\t\t\t\t\tnode_map.move_to_root unless node_map.new_record?\n\t\t\t\t\tend\n\t\t\t\t\tcount = count + 1\n\t\t\t\tend\n\n\t\t\t\tif node_map.node == self\n\t\t\t\t\tnode_map.children = []\n\t\t\t\tend\n\t\t\t}\n\n\t\t\tself.survey.node_maps.each { |node_map|\n\t\t\t\tif to_remove.include?(node_map)\n\t\t\t\t\tnode_map.parent = nil\n\t\t\t\t\tnode_map.mark_for_destruction\n\t\t\t\tend\n\t\t\t}\n\t\tend", "language": "ruby", "code": "def remove_link\n\t\t\t# not linked to a question - nothing to remove!\n\t\t\treturn true if (question = self.next_question).nil?\n\n\t\t\tcount = 0\n\t\t\tto_remove = []\n\t\t\tself.survey.node_maps.each { |node_map|\n\t\t\t\tif node_map.node == question\n\t\t\t\t\tif count > 0\n\t\t\t\t\t\tto_remove.concat(node_map.self_and_descendants)\n\t\t\t\t\telse\n\t\t\t\t\t\tnode_map.parent = nil\n\t\t\t\t\t\tnode_map.move_to_root unless node_map.new_record?\n\t\t\t\t\tend\n\t\t\t\t\tcount = count + 1\n\t\t\t\tend\n\n\t\t\t\tif node_map.node == self\n\t\t\t\t\tnode_map.children = []\n\t\t\t\tend\n\t\t\t}\n\n\t\t\tself.survey.node_maps.each { |node_map|\n\t\t\t\tif to_remove.include?(node_map)\n\t\t\t\t\tnode_map.parent = nil\n\t\t\t\t\tnode_map.mark_for_destruction\n\t\t\t\tend\n\t\t\t}\n\t\tend", "code_tokens": ["def", "remove_link", "# not linked to a question - nothing to remove!", "return", "true", "if", "(", "question", "=", "self", ".", "next_question", ")", ".", "nil?", "count", "=", "0", "to_remove", "=", "[", "]", "self", ".", "survey", ".", "node_maps", ".", "each", "{", "|", "node_map", "|", "if", "node_map", ".", "node", "==", "question", "if", "count", ">", "0", "to_remove", ".", "concat", "(", "node_map", ".", "self_and_descendants", ")", "else", "node_map", ".", "parent", "=", "nil", "node_map", ".", "move_to_root", "unless", "node_map", ".", "new_record?", "end", "count", "=", "count", "+", "1", "end", "if", "node_map", ".", "node", "==", "self", "node_map", ".", "children", "=", "[", "]", "end", "}", "self", ".", "survey", ".", "node_maps", ".", "each", "{", "|", "node_map", "|", "if", "to_remove", ".", "include?", "(", "node_map", ")", "node_map", ".", "parent", "=", "nil", "node_map", ".", "mark_for_destruction", "end", "}", "end"], "docstring": "Removes the node_map from this answer to its next question", "docstring_tokens": ["Removes", "the", "node_map", "from", "this", "answer", "to", "its", "next", "question"], "sha": "cd0df44863c6cb158d129365f874156ac1ea7b9d", "url": "https://github.com/butchmarshall/active_record_survey/blob/cd0df44863c6cb158d129365f874156ac1ea7b9d/lib/active_record_survey/node/answer.rb#L54-L82", "partition": "test"} {"repo": "butchmarshall/active_record_survey", "path": "lib/active_record_survey/node/answer.rb", "func_name": "ActiveRecordSurvey.Node::Answer.sibling_index", "original_string": "def sibling_index\n\t\t\tnode_maps = self.survey.node_maps\n\n\t\t\tif node_map = node_maps.select { |i| i.node == self }.first\n\t\t\t\tparent = node_map.parent\n\n\t\t\t\tchildren = node_maps.select { |i| i.parent && i.parent.node === parent.node }\n\n\t\t\t\tchildren.each_with_index { |nm, i|\n\t\t\t\t\tif nm == node_map\n\t\t\t\t\t\treturn i\n\t\t\t\t\tend\n\t\t\t\t}\n\t\t\tend\n\t\tend", "language": "ruby", "code": "def sibling_index\n\t\t\tnode_maps = self.survey.node_maps\n\n\t\t\tif node_map = node_maps.select { |i| i.node == self }.first\n\t\t\t\tparent = node_map.parent\n\n\t\t\t\tchildren = node_maps.select { |i| i.parent && i.parent.node === parent.node }\n\n\t\t\t\tchildren.each_with_index { |nm, i|\n\t\t\t\t\tif nm == node_map\n\t\t\t\t\t\treturn i\n\t\t\t\t\tend\n\t\t\t\t}\n\t\t\tend\n\t\tend", "code_tokens": ["def", "sibling_index", "node_maps", "=", "self", ".", "survey", ".", "node_maps", "if", "node_map", "=", "node_maps", ".", "select", "{", "|", "i", "|", "i", ".", "node", "==", "self", "}", ".", "first", "parent", "=", "node_map", ".", "parent", "children", "=", "node_maps", ".", "select", "{", "|", "i", "|", "i", ".", "parent", "&&", "i", ".", "parent", ".", "node", "===", "parent", ".", "node", "}", "children", ".", "each_with_index", "{", "|", "nm", ",", "i", "|", "if", "nm", "==", "node_map", "return", "i", "end", "}", "end", "end"], "docstring": "Gets index in sibling relationship", "docstring_tokens": ["Gets", "index", "in", "sibling", "relationship"], "sha": "cd0df44863c6cb158d129365f874156ac1ea7b9d", "url": "https://github.com/butchmarshall/active_record_survey/blob/cd0df44863c6cb158d129365f874156ac1ea7b9d/lib/active_record_survey/node/answer.rb#L93-L107", "partition": "test"} {"repo": "butchmarshall/active_record_survey", "path": "lib/active_record_survey/node/answer.rb", "func_name": "ActiveRecordSurvey.Node::Answer.move_up", "original_string": "def move_up\n\t\t\tself.survey.node_maps.select { |i|\n\t\t\t\ti.node == self\n\t\t\t}.collect { |node_map|\n\t\t\t\tbegin\n\t\t\t\t\tnode_map.move_left\n\t\t\t\trescue\n\t\t\t\tend\n\t\t\t}\n\t\tend", "language": "ruby", "code": "def move_up\n\t\t\tself.survey.node_maps.select { |i|\n\t\t\t\ti.node == self\n\t\t\t}.collect { |node_map|\n\t\t\t\tbegin\n\t\t\t\t\tnode_map.move_left\n\t\t\t\trescue\n\t\t\t\tend\n\t\t\t}\n\t\tend", "code_tokens": ["def", "move_up", "self", ".", "survey", ".", "node_maps", ".", "select", "{", "|", "i", "|", "i", ".", "node", "==", "self", "}", ".", "collect", "{", "|", "node_map", "|", "begin", "node_map", ".", "move_left", "rescue", "end", "}", "end"], "docstring": "Moves answer up relative to other answers", "docstring_tokens": ["Moves", "answer", "up", "relative", "to", "other", "answers"], "sha": "cd0df44863c6cb158d129365f874156ac1ea7b9d", "url": "https://github.com/butchmarshall/active_record_survey/blob/cd0df44863c6cb158d129365f874156ac1ea7b9d/lib/active_record_survey/node/answer.rb#L120-L129", "partition": "test"} {"repo": "butchmarshall/active_record_survey", "path": "lib/active_record_survey/node/answer.rb", "func_name": "ActiveRecordSurvey.Node::Answer.move_down", "original_string": "def move_down\n\t\t\tself.survey.node_maps.select { |i|\n\t\t\t\ti.node == self\n\t\t\t}.collect { |node_map|\n\t\t\t\tbegin\n\t\t\t\t\tnode_map.move_right\n\t\t\t\trescue\n\t\t\t\tend\n\t\t\t}\n\t\tend", "language": "ruby", "code": "def move_down\n\t\t\tself.survey.node_maps.select { |i|\n\t\t\t\ti.node == self\n\t\t\t}.collect { |node_map|\n\t\t\t\tbegin\n\t\t\t\t\tnode_map.move_right\n\t\t\t\trescue\n\t\t\t\tend\n\t\t\t}\n\t\tend", "code_tokens": ["def", "move_down", "self", ".", "survey", ".", "node_maps", ".", "select", "{", "|", "i", "|", "i", ".", "node", "==", "self", "}", ".", "collect", "{", "|", "node_map", "|", "begin", "node_map", ".", "move_right", "rescue", "end", "}", "end"], "docstring": "Moves answer down relative to other answers", "docstring_tokens": ["Moves", "answer", "down", "relative", "to", "other", "answers"], "sha": "cd0df44863c6cb158d129365f874156ac1ea7b9d", "url": "https://github.com/butchmarshall/active_record_survey/blob/cd0df44863c6cb158d129365f874156ac1ea7b9d/lib/active_record_survey/node/answer.rb#L132-L141", "partition": "test"} {"repo": "butchmarshall/active_record_survey", "path": "lib/active_record_survey/node/answer/rank.rb", "func_name": "ActiveRecordSurvey.Node::Answer::Rank.validate_instance_node", "original_string": "def validate_instance_node(instance_node)\n\t\t\t# super - all validations on this node pass\n\t\t\tsuper &&\n\t\t\t(instance_node.value.to_s.empty? || !instance_node.value.to_s.match(/^\\d+$/).nil?) &&\n\t\t\t(instance_node.value.to_s.empty? || instance_node.value.to_i >= 1) &&\n\t\t\tinstance_node.value.to_i <= self.max_rank\n\t\tend", "language": "ruby", "code": "def validate_instance_node(instance_node)\n\t\t\t# super - all validations on this node pass\n\t\t\tsuper &&\n\t\t\t(instance_node.value.to_s.empty? || !instance_node.value.to_s.match(/^\\d+$/).nil?) &&\n\t\t\t(instance_node.value.to_s.empty? || instance_node.value.to_i >= 1) &&\n\t\t\tinstance_node.value.to_i <= self.max_rank\n\t\tend", "code_tokens": ["def", "validate_instance_node", "(", "instance_node", ")", "# super - all validations on this node pass", "super", "&&", "(", "instance_node", ".", "value", ".", "to_s", ".", "empty?", "||", "!", "instance_node", ".", "value", ".", "to_s", ".", "match", "(", "/", "\\d", "/", ")", ".", "nil?", ")", "&&", "(", "instance_node", ".", "value", ".", "to_s", ".", "empty?", "||", "instance_node", ".", "value", ".", "to_i", ">=", "1", ")", "&&", "instance_node", ".", "value", ".", "to_i", "<=", "self", ".", "max_rank", "end"], "docstring": "Accept integer or empty values\n Must be within range of the number of ranking nodes", "docstring_tokens": ["Accept", "integer", "or", "empty", "values", "Must", "be", "within", "range", "of", "the", "number", "of", "ranking", "nodes"], "sha": "cd0df44863c6cb158d129365f874156ac1ea7b9d", "url": "https://github.com/butchmarshall/active_record_survey/blob/cd0df44863c6cb158d129365f874156ac1ea7b9d/lib/active_record_survey/node/answer/rank.rb#L9-L15", "partition": "test"} {"repo": "butchmarshall/active_record_survey", "path": "lib/active_record_survey/node/answer/rank.rb", "func_name": "ActiveRecordSurvey.Node::Answer::Rank.num_above", "original_string": "def num_above\n\t\t\tcount = 0\n\t\t\tself.node_maps.each { |i|\n\t\t\t\t# Parent is one of us as well - include it and check its parents\n\t\t\t\tif i.parent.node.class.ancestors.include?(self.class)\n\t\t\t\t\tcount = count + 1 + i.parent.node.num_above\n\t\t\t\tend\n\t\t\t}\n\t\t\tcount\n\t\tend", "language": "ruby", "code": "def num_above\n\t\t\tcount = 0\n\t\t\tself.node_maps.each { |i|\n\t\t\t\t# Parent is one of us as well - include it and check its parents\n\t\t\t\tif i.parent.node.class.ancestors.include?(self.class)\n\t\t\t\t\tcount = count + 1 + i.parent.node.num_above\n\t\t\t\tend\n\t\t\t}\n\t\t\tcount\n\t\tend", "code_tokens": ["def", "num_above", "count", "=", "0", "self", ".", "node_maps", ".", "each", "{", "|", "i", "|", "# Parent is one of us as well - include it and check its parents", "if", "i", ".", "parent", ".", "node", ".", "class", ".", "ancestors", ".", "include?", "(", "self", ".", "class", ")", "count", "=", "count", "+", "1", "+", "i", ".", "parent", ".", "node", ".", "num_above", "end", "}", "count", "end"], "docstring": "Calculate the number of Rank nodes above this one", "docstring_tokens": ["Calculate", "the", "number", "of", "Rank", "nodes", "above", "this", "one"], "sha": "cd0df44863c6cb158d129365f874156ac1ea7b9d", "url": "https://github.com/butchmarshall/active_record_survey/blob/cd0df44863c6cb158d129365f874156ac1ea7b9d/lib/active_record_survey/node/answer/rank.rb#L28-L37", "partition": "test"} {"repo": "butchmarshall/active_record_survey", "path": "lib/active_record_survey/node/answer/rank.rb", "func_name": "ActiveRecordSurvey.Node::Answer::Rank.num_below", "original_string": "def num_below\n\t\t\tcount = 0\n\t\t\tself.node_maps.each { |node_map|\n\t\t\t\tnode_map.children.each { |child|\n\t\t\t\t\t# Child is one of us as well - include it and check its children\n\t\t\t\t\tif child.node.class.ancestors.include?(self.class)\n\t\t\t\t\t\tcount = count + 1 + child.node.num_below\n\t\t\t\t\tend\n\t\t\t\t}\n\t\t\t}\n\t\t\tcount\n\t\tend", "language": "ruby", "code": "def num_below\n\t\t\tcount = 0\n\t\t\tself.node_maps.each { |node_map|\n\t\t\t\tnode_map.children.each { |child|\n\t\t\t\t\t# Child is one of us as well - include it and check its children\n\t\t\t\t\tif child.node.class.ancestors.include?(self.class)\n\t\t\t\t\t\tcount = count + 1 + child.node.num_below\n\t\t\t\t\tend\n\t\t\t\t}\n\t\t\t}\n\t\t\tcount\n\t\tend", "code_tokens": ["def", "num_below", "count", "=", "0", "self", ".", "node_maps", ".", "each", "{", "|", "node_map", "|", "node_map", ".", "children", ".", "each", "{", "|", "child", "|", "# Child is one of us as well - include it and check its children", "if", "child", ".", "node", ".", "class", ".", "ancestors", ".", "include?", "(", "self", ".", "class", ")", "count", "=", "count", "+", "1", "+", "child", ".", "node", ".", "num_below", "end", "}", "}", "count", "end"], "docstring": "Calculate the number of Rank nodes below this one", "docstring_tokens": ["Calculate", "the", "number", "of", "Rank", "nodes", "below", "this", "one"], "sha": "cd0df44863c6cb158d129365f874156ac1ea7b9d", "url": "https://github.com/butchmarshall/active_record_survey/blob/cd0df44863c6cb158d129365f874156ac1ea7b9d/lib/active_record_survey/node/answer/rank.rb#L40-L51", "partition": "test"} {"repo": "butchmarshall/active_record_survey", "path": "lib/active_record_survey/node_validation/maximum_length.rb", "func_name": "ActiveRecordSurvey.NodeValidation::MaximumLength.validate_instance_node", "original_string": "def validate_instance_node(instance_node, answer_node = nil)\n\t\t\tis_valid = (self.value.to_i >= instance_node.value.to_s.length.to_i)\n\n\t\t\tinstance_node.errors[:base] << { :nodes => { answer_node.id => [\"MAXIMUM_LENGTH\"] } } if !is_valid\n\n\t\t\tis_valid\n\t\tend", "language": "ruby", "code": "def validate_instance_node(instance_node, answer_node = nil)\n\t\t\tis_valid = (self.value.to_i >= instance_node.value.to_s.length.to_i)\n\n\t\t\tinstance_node.errors[:base] << { :nodes => { answer_node.id => [\"MAXIMUM_LENGTH\"] } } if !is_valid\n\n\t\t\tis_valid\n\t\tend", "code_tokens": ["def", "validate_instance_node", "(", "instance_node", ",", "answer_node", "=", "nil", ")", "is_valid", "=", "(", "self", ".", "value", ".", "to_i", ">=", "instance_node", ".", "value", ".", "to_s", ".", "length", ".", "to_i", ")", "instance_node", ".", "errors", "[", ":base", "]", "<<", "{", ":nodes", "=>", "{", "answer_node", ".", "id", "=>", "[", "\"MAXIMUM_LENGTH\"", "]", "}", "}", "if", "!", "is_valid", "is_valid", "end"], "docstring": "Validate the instance_node value", "docstring_tokens": ["Validate", "the", "instance_node", "value"], "sha": "cd0df44863c6cb158d129365f874156ac1ea7b9d", "url": "https://github.com/butchmarshall/active_record_survey/blob/cd0df44863c6cb158d129365f874156ac1ea7b9d/lib/active_record_survey/node_validation/maximum_length.rb#L5-L11", "partition": "test"} {"repo": "butchmarshall/active_record_survey", "path": "lib/active_record_survey/survey.rb", "func_name": "ActiveRecordSurvey.Survey.build_first_question", "original_string": "def build_first_question(question_node)\n\t\t\tif !question_node.class.ancestors.include?(::ActiveRecordSurvey::Node::Question)\n\t\t\t\traise ArgumentError.new \"must inherit from ::ActiveRecordSurvey::Node::Question\"\n\t\t\tend\n\n\t\t\tquestion_node_maps = self.node_maps.select { |i| i.node == question_node && !i.marked_for_destruction? }\n\n\t\t\t# No node_maps exist yet from this question\n\t\t\tif question_node_maps.length === 0\n\t\t\t\t# Build our first node-map\n\t\t\t\tquestion_node_maps << self.node_maps.build(:node => question_node, :survey => self)\n\t\t\tend\n\t\tend", "language": "ruby", "code": "def build_first_question(question_node)\n\t\t\tif !question_node.class.ancestors.include?(::ActiveRecordSurvey::Node::Question)\n\t\t\t\traise ArgumentError.new \"must inherit from ::ActiveRecordSurvey::Node::Question\"\n\t\t\tend\n\n\t\t\tquestion_node_maps = self.node_maps.select { |i| i.node == question_node && !i.marked_for_destruction? }\n\n\t\t\t# No node_maps exist yet from this question\n\t\t\tif question_node_maps.length === 0\n\t\t\t\t# Build our first node-map\n\t\t\t\tquestion_node_maps << self.node_maps.build(:node => question_node, :survey => self)\n\t\t\tend\n\t\tend", "code_tokens": ["def", "build_first_question", "(", "question_node", ")", "if", "!", "question_node", ".", "class", ".", "ancestors", ".", "include?", "(", "::", "ActiveRecordSurvey", "::", "Node", "::", "Question", ")", "raise", "ArgumentError", ".", "new", "\"must inherit from ::ActiveRecordSurvey::Node::Question\"", "end", "question_node_maps", "=", "self", ".", "node_maps", ".", "select", "{", "|", "i", "|", "i", ".", "node", "==", "question_node", "&&", "!", "i", ".", "marked_for_destruction?", "}", "# No node_maps exist yet from this question", "if", "question_node_maps", ".", "length", "===", "0", "# Build our first node-map", "question_node_maps", "<<", "self", ".", "node_maps", ".", "build", "(", ":node", "=>", "question_node", ",", ":survey", "=>", "self", ")", "end", "end"], "docstring": "Builds first question", "docstring_tokens": ["Builds", "first", "question"], "sha": "cd0df44863c6cb158d129365f874156ac1ea7b9d", "url": "https://github.com/butchmarshall/active_record_survey/blob/cd0df44863c6cb158d129365f874156ac1ea7b9d/lib/active_record_survey/survey.rb#L13-L25", "partition": "test"} {"repo": "butchmarshall/active_record_survey", "path": "lib/active_record_survey/survey.rb", "func_name": "ActiveRecordSurvey.Survey.edges", "original_string": "def edges\n\t\t\tself.node_maps.select { |i| !i.marked_for_destruction? }.select { |i|\n\t\t\t\ti.node && i.parent\n\t\t\t}.collect { |i|\n\t\t\t\t{\n\t\t\t\t\t:source => i.parent.node.id,\n\t\t\t\t\t:target => i.node.id,\n\t\t\t\t}\n\t\t\t}.uniq\n\t\tend", "language": "ruby", "code": "def edges\n\t\t\tself.node_maps.select { |i| !i.marked_for_destruction? }.select { |i|\n\t\t\t\ti.node && i.parent\n\t\t\t}.collect { |i|\n\t\t\t\t{\n\t\t\t\t\t:source => i.parent.node.id,\n\t\t\t\t\t:target => i.node.id,\n\t\t\t\t}\n\t\t\t}.uniq\n\t\tend", "code_tokens": ["def", "edges", "self", ".", "node_maps", ".", "select", "{", "|", "i", "|", "!", "i", ".", "marked_for_destruction?", "}", ".", "select", "{", "|", "i", "|", "i", ".", "node", "&&", "i", ".", "parent", "}", ".", "collect", "{", "|", "i", "|", "{", ":source", "=>", "i", ".", "parent", ".", "node", ".", "id", ",", ":target", "=>", "i", ".", "node", ".", "id", ",", "}", "}", ".", "uniq", "end"], "docstring": "All the connective edges", "docstring_tokens": ["All", "the", "connective", "edges"], "sha": "cd0df44863c6cb158d129365f874156ac1ea7b9d", "url": "https://github.com/butchmarshall/active_record_survey/blob/cd0df44863c6cb158d129365f874156ac1ea7b9d/lib/active_record_survey/survey.rb#L28-L37", "partition": "test"} {"repo": "butchmarshall/active_record_survey", "path": "lib/active_record_survey/node/question.rb", "func_name": "ActiveRecordSurvey.Node::Question.validate_parent_instance_node", "original_string": "def validate_parent_instance_node(instance_node, child_node)\n\t\t\t!self.node_validations.collect { |node_validation|\n\t\t\t\tnode_validation.validate_instance_node(instance_node, self)\n\t\t\t}.include?(false)\n\t\tend", "language": "ruby", "code": "def validate_parent_instance_node(instance_node, child_node)\n\t\t\t!self.node_validations.collect { |node_validation|\n\t\t\t\tnode_validation.validate_instance_node(instance_node, self)\n\t\t\t}.include?(false)\n\t\tend", "code_tokens": ["def", "validate_parent_instance_node", "(", "instance_node", ",", "child_node", ")", "!", "self", ".", "node_validations", ".", "collect", "{", "|", "node_validation", "|", "node_validation", ".", "validate_instance_node", "(", "instance_node", ",", "self", ")", "}", ".", "include?", "(", "false", ")", "end"], "docstring": "Stop validating at the Question node", "docstring_tokens": ["Stop", "validating", "at", "the", "Question", "node"], "sha": "cd0df44863c6cb158d129365f874156ac1ea7b9d", "url": "https://github.com/butchmarshall/active_record_survey/blob/cd0df44863c6cb158d129365f874156ac1ea7b9d/lib/active_record_survey/node/question.rb#L4-L8", "partition": "test"} {"repo": "butchmarshall/active_record_survey", "path": "lib/active_record_survey/node/question.rb", "func_name": "ActiveRecordSurvey.Node::Question.update_question_type", "original_string": "def update_question_type(klass)\n\t\t\tif self.next_questions.length > 0\n\t\t\t\traise RuntimeError.new \"No questions can follow when changing the question type\" \n\t\t\tend\n\n\t\t\tnm = self.survey.node_maps\n\n\t\t\tanswers = self.answers.collect { |answer|\n\t\t\t\tnm.select { |i|\n\t\t\t\t\ti.node == answer\n\t\t\t\t}\n\t\t\t}.flatten.uniq.collect { |answer_node_map|\n\t\t\t\tnode = answer_node_map.node\n\t\t\t\tanswer_node_map.send((answer_node_map.new_record?)? :destroy : :mark_for_destruction)\n\t\t\t\tnode\n\t\t\t}.collect { |answer|\n\t\t\t\tanswer.type = klass.to_s\n\t\t\t\tanswer = answer.becomes(klass)\n\t\t\t\tanswer.save if !answer.new_record?\n\n\t\t\t\tanswer\n\t\t\t}.uniq\n\n\t\t\tanswers.each { |answer|\n\t\t\t\tanswer.survey = self.survey\n\n\t\t\t\tself.build_answer(answer)\n\t\t\t}\n\t\tend", "language": "ruby", "code": "def update_question_type(klass)\n\t\t\tif self.next_questions.length > 0\n\t\t\t\traise RuntimeError.new \"No questions can follow when changing the question type\" \n\t\t\tend\n\n\t\t\tnm = self.survey.node_maps\n\n\t\t\tanswers = self.answers.collect { |answer|\n\t\t\t\tnm.select { |i|\n\t\t\t\t\ti.node == answer\n\t\t\t\t}\n\t\t\t}.flatten.uniq.collect { |answer_node_map|\n\t\t\t\tnode = answer_node_map.node\n\t\t\t\tanswer_node_map.send((answer_node_map.new_record?)? :destroy : :mark_for_destruction)\n\t\t\t\tnode\n\t\t\t}.collect { |answer|\n\t\t\t\tanswer.type = klass.to_s\n\t\t\t\tanswer = answer.becomes(klass)\n\t\t\t\tanswer.save if !answer.new_record?\n\n\t\t\t\tanswer\n\t\t\t}.uniq\n\n\t\t\tanswers.each { |answer|\n\t\t\t\tanswer.survey = self.survey\n\n\t\t\t\tself.build_answer(answer)\n\t\t\t}\n\t\tend", "code_tokens": ["def", "update_question_type", "(", "klass", ")", "if", "self", ".", "next_questions", ".", "length", ">", "0", "raise", "RuntimeError", ".", "new", "\"No questions can follow when changing the question type\"", "end", "nm", "=", "self", ".", "survey", ".", "node_maps", "answers", "=", "self", ".", "answers", ".", "collect", "{", "|", "answer", "|", "nm", ".", "select", "{", "|", "i", "|", "i", ".", "node", "==", "answer", "}", "}", ".", "flatten", ".", "uniq", ".", "collect", "{", "|", "answer_node_map", "|", "node", "=", "answer_node_map", ".", "node", "answer_node_map", ".", "send", "(", "(", "answer_node_map", ".", "new_record?", ")", "?", ":destroy", ":", ":mark_for_destruction", ")", "node", "}", ".", "collect", "{", "|", "answer", "|", "answer", ".", "type", "=", "klass", ".", "to_s", "answer", "=", "answer", ".", "becomes", "(", "klass", ")", "answer", ".", "save", "if", "!", "answer", ".", "new_record?", "answer", "}", ".", "uniq", "answers", ".", "each", "{", "|", "answer", "|", "answer", ".", "survey", "=", "self", ".", "survey", "self", ".", "build_answer", "(", "answer", ")", "}", "end"], "docstring": "Updates the answers of this question to a different type", "docstring_tokens": ["Updates", "the", "answers", "of", "this", "question", "to", "a", "different", "type"], "sha": "cd0df44863c6cb158d129365f874156ac1ea7b9d", "url": "https://github.com/butchmarshall/active_record_survey/blob/cd0df44863c6cb158d129365f874156ac1ea7b9d/lib/active_record_survey/node/question.rb#L11-L39", "partition": "test"} {"repo": "butchmarshall/active_record_survey", "path": "lib/active_record_survey/node/question.rb", "func_name": "ActiveRecordSurvey.Node::Question.remove_answer", "original_string": "def remove_answer(answer_node)\n\t\t\t# A survey must either be passed or already present in self.node_maps\n\t\t\tif self.survey.nil?\n\t\t\t\traise ArgumentError.new \"A survey must be passed if ActiveRecordSurvey::Node::Question is not yet added to a survey\"\n\t\t\tend\n\n\t\t\tif !answer_node.class.ancestors.include?(::ActiveRecordSurvey::Node::Answer)\n\t\t\t\traise ArgumentError.new \"::ActiveRecordSurvey::Node::Answer not passed\"\n\t\t\tend\n\n\t\t\t# Cannot mix answer types\n\t\t\t# Check if not match existing - throw error\n\t\t\tif !self.answers.include?(answer_node)\n\t\t\t\traise ArgumentError.new \"Answer not linked to question\"\n\t\t\tend\n\n\t\t\tanswer_node.send(:remove_answer, self)\n\t\tend", "language": "ruby", "code": "def remove_answer(answer_node)\n\t\t\t# A survey must either be passed or already present in self.node_maps\n\t\t\tif self.survey.nil?\n\t\t\t\traise ArgumentError.new \"A survey must be passed if ActiveRecordSurvey::Node::Question is not yet added to a survey\"\n\t\t\tend\n\n\t\t\tif !answer_node.class.ancestors.include?(::ActiveRecordSurvey::Node::Answer)\n\t\t\t\traise ArgumentError.new \"::ActiveRecordSurvey::Node::Answer not passed\"\n\t\t\tend\n\n\t\t\t# Cannot mix answer types\n\t\t\t# Check if not match existing - throw error\n\t\t\tif !self.answers.include?(answer_node)\n\t\t\t\traise ArgumentError.new \"Answer not linked to question\"\n\t\t\tend\n\n\t\t\tanswer_node.send(:remove_answer, self)\n\t\tend", "code_tokens": ["def", "remove_answer", "(", "answer_node", ")", "# A survey must either be passed or already present in self.node_maps", "if", "self", ".", "survey", ".", "nil?", "raise", "ArgumentError", ".", "new", "\"A survey must be passed if ActiveRecordSurvey::Node::Question is not yet added to a survey\"", "end", "if", "!", "answer_node", ".", "class", ".", "ancestors", ".", "include?", "(", "::", "ActiveRecordSurvey", "::", "Node", "::", "Answer", ")", "raise", "ArgumentError", ".", "new", "\"::ActiveRecordSurvey::Node::Answer not passed\"", "end", "# Cannot mix answer types", "# Check if not match existing - throw error", "if", "!", "self", ".", "answers", ".", "include?", "(", "answer_node", ")", "raise", "ArgumentError", ".", "new", "\"Answer not linked to question\"", "end", "answer_node", ".", "send", "(", ":remove_answer", ",", "self", ")", "end"], "docstring": "Removes an answer", "docstring_tokens": ["Removes", "an", "answer"], "sha": "cd0df44863c6cb158d129365f874156ac1ea7b9d", "url": "https://github.com/butchmarshall/active_record_survey/blob/cd0df44863c6cb158d129365f874156ac1ea7b9d/lib/active_record_survey/node/question.rb#L42-L59", "partition": "test"} {"repo": "butchmarshall/active_record_survey", "path": "lib/active_record_survey/node/question.rb", "func_name": "ActiveRecordSurvey.Node::Question.build_answer", "original_string": "def build_answer(answer_node)\n\t\t\t# A survey must either be passed or already present in self.node_maps\n\t\t\tif self.survey.nil?\n\t\t\t\traise ArgumentError.new \"A survey must be passed if ActiveRecordSurvey::Node::Question is not yet added to a survey\"\n\t\t\tend\n\n\t\t\t# Cannot mix answer types\n\t\t\t# Check if not match existing - throw error\n\t\t\tif !self.answers.select { |answer|\n\t\t\t\tanswer.class != answer_node.class\n\t\t\t}.empty?\n\t\t\t\traise ArgumentError.new \"Cannot mix answer types on question\"\n\t\t\tend\n\n\t\t\t# Answers actually define how they're built off the parent node\n\t\t\tif answer_node.send(:build_answer, self)\n\n\t\t\t\t# If any questions existed directly following this question, insert after this answer\n\t\t\t\tself.survey.node_maps.select { |i|\n\t\t\t\t\ti.node == answer_node && !i.marked_for_destruction?\n\t\t\t\t}.each { |answer_node_map|\n\t\t\t\t\tself.survey.node_maps.select { |j|\n\t\t\t\t\t\t# Same parent\n\t\t\t\t\t\t# Is a question\n\t\t\t\t\t\t!j.marked_for_destruction? &&\n\t\t\t\t\t\tj.parent == answer_node_map.parent && j.node.class.ancestors.include?(::ActiveRecordSurvey::Node::Question)\n\t\t\t\t\t}.each { |j|\n\t\t\t\t\t\tanswer_node_map.survey = self.survey\n\t\t\t\t\t\tj.survey = self.survey\n\n\t\t\t\t\t\tanswer_node_map.children << j\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\ttrue\n\t\t\tend\n\t\tend", "language": "ruby", "code": "def build_answer(answer_node)\n\t\t\t# A survey must either be passed or already present in self.node_maps\n\t\t\tif self.survey.nil?\n\t\t\t\traise ArgumentError.new \"A survey must be passed if ActiveRecordSurvey::Node::Question is not yet added to a survey\"\n\t\t\tend\n\n\t\t\t# Cannot mix answer types\n\t\t\t# Check if not match existing - throw error\n\t\t\tif !self.answers.select { |answer|\n\t\t\t\tanswer.class != answer_node.class\n\t\t\t}.empty?\n\t\t\t\traise ArgumentError.new \"Cannot mix answer types on question\"\n\t\t\tend\n\n\t\t\t# Answers actually define how they're built off the parent node\n\t\t\tif answer_node.send(:build_answer, self)\n\n\t\t\t\t# If any questions existed directly following this question, insert after this answer\n\t\t\t\tself.survey.node_maps.select { |i|\n\t\t\t\t\ti.node == answer_node && !i.marked_for_destruction?\n\t\t\t\t}.each { |answer_node_map|\n\t\t\t\t\tself.survey.node_maps.select { |j|\n\t\t\t\t\t\t# Same parent\n\t\t\t\t\t\t# Is a question\n\t\t\t\t\t\t!j.marked_for_destruction? &&\n\t\t\t\t\t\tj.parent == answer_node_map.parent && j.node.class.ancestors.include?(::ActiveRecordSurvey::Node::Question)\n\t\t\t\t\t}.each { |j|\n\t\t\t\t\t\tanswer_node_map.survey = self.survey\n\t\t\t\t\t\tj.survey = self.survey\n\n\t\t\t\t\t\tanswer_node_map.children << j\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\ttrue\n\t\t\tend\n\t\tend", "code_tokens": ["def", "build_answer", "(", "answer_node", ")", "# A survey must either be passed or already present in self.node_maps", "if", "self", ".", "survey", ".", "nil?", "raise", "ArgumentError", ".", "new", "\"A survey must be passed if ActiveRecordSurvey::Node::Question is not yet added to a survey\"", "end", "# Cannot mix answer types", "# Check if not match existing - throw error", "if", "!", "self", ".", "answers", ".", "select", "{", "|", "answer", "|", "answer", ".", "class", "!=", "answer_node", ".", "class", "}", ".", "empty?", "raise", "ArgumentError", ".", "new", "\"Cannot mix answer types on question\"", "end", "# Answers actually define how they're built off the parent node", "if", "answer_node", ".", "send", "(", ":build_answer", ",", "self", ")", "# If any questions existed directly following this question, insert after this answer", "self", ".", "survey", ".", "node_maps", ".", "select", "{", "|", "i", "|", "i", ".", "node", "==", "answer_node", "&&", "!", "i", ".", "marked_for_destruction?", "}", ".", "each", "{", "|", "answer_node_map", "|", "self", ".", "survey", ".", "node_maps", ".", "select", "{", "|", "j", "|", "# Same parent", "# Is a question", "!", "j", ".", "marked_for_destruction?", "&&", "j", ".", "parent", "==", "answer_node_map", ".", "parent", "&&", "j", ".", "node", ".", "class", ".", "ancestors", ".", "include?", "(", "::", "ActiveRecordSurvey", "::", "Node", "::", "Question", ")", "}", ".", "each", "{", "|", "j", "|", "answer_node_map", ".", "survey", "=", "self", ".", "survey", "j", ".", "survey", "=", "self", ".", "survey", "answer_node_map", ".", "children", "<<", "j", "}", "}", "true", "end", "end"], "docstring": "Build an answer off this node", "docstring_tokens": ["Build", "an", "answer", "off", "this", "node"], "sha": "cd0df44863c6cb158d129365f874156ac1ea7b9d", "url": "https://github.com/butchmarshall/active_record_survey/blob/cd0df44863c6cb158d129365f874156ac1ea7b9d/lib/active_record_survey/node/question.rb#L62-L98", "partition": "test"} {"repo": "butchmarshall/active_record_survey", "path": "lib/active_record_survey/node/question.rb", "func_name": "ActiveRecordSurvey.Node::Question.remove_link", "original_string": "def remove_link\n\t\t\treturn true if (questions = self.next_questions).length === 0\n\n\t\t\t# Remove the link to any direct questions\n\t\t\tself.survey.node_maps.select { |i|\n\t\t\t\ti.node == self\n\t\t\t}.each { |node_map|\n\t\t\t\tself.survey.node_maps.select { |j|\n\t\t\t\t\tnode_map.children.include?(j) \n\t\t\t\t}.each { |child|\n\t\t\t\t\tif child.node.class.ancestors.include?(::ActiveRecordSurvey::Node::Question)\n\t\t\t\t\t\tchild.parent = nil\n\t\t\t\t\t\tchild.send((child.new_record?)? :destroy : :mark_for_destruction )\n\t\t\t\t\tend\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t# remove link any answeres that have questions\n\t\t\tself.answers.collect { |i|\n\t\t\t\ti.remove_link\n\t\t\t}\n\t\tend", "language": "ruby", "code": "def remove_link\n\t\t\treturn true if (questions = self.next_questions).length === 0\n\n\t\t\t# Remove the link to any direct questions\n\t\t\tself.survey.node_maps.select { |i|\n\t\t\t\ti.node == self\n\t\t\t}.each { |node_map|\n\t\t\t\tself.survey.node_maps.select { |j|\n\t\t\t\t\tnode_map.children.include?(j) \n\t\t\t\t}.each { |child|\n\t\t\t\t\tif child.node.class.ancestors.include?(::ActiveRecordSurvey::Node::Question)\n\t\t\t\t\t\tchild.parent = nil\n\t\t\t\t\t\tchild.send((child.new_record?)? :destroy : :mark_for_destruction )\n\t\t\t\t\tend\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t# remove link any answeres that have questions\n\t\t\tself.answers.collect { |i|\n\t\t\t\ti.remove_link\n\t\t\t}\n\t\tend", "code_tokens": ["def", "remove_link", "return", "true", "if", "(", "questions", "=", "self", ".", "next_questions", ")", ".", "length", "===", "0", "# Remove the link to any direct questions", "self", ".", "survey", ".", "node_maps", ".", "select", "{", "|", "i", "|", "i", ".", "node", "==", "self", "}", ".", "each", "{", "|", "node_map", "|", "self", ".", "survey", ".", "node_maps", ".", "select", "{", "|", "j", "|", "node_map", ".", "children", ".", "include?", "(", "j", ")", "}", ".", "each", "{", "|", "child", "|", "if", "child", ".", "node", ".", "class", ".", "ancestors", ".", "include?", "(", "::", "ActiveRecordSurvey", "::", "Node", "::", "Question", ")", "child", ".", "parent", "=", "nil", "child", ".", "send", "(", "(", "child", ".", "new_record?", ")", "?", ":destroy", ":", ":mark_for_destruction", ")", "end", "}", "}", "# remove link any answeres that have questions", "self", ".", "answers", ".", "collect", "{", "|", "i", "|", "i", ".", "remove_link", "}", "end"], "docstring": "Removes the node_map link from this question all of its next questions", "docstring_tokens": ["Removes", "the", "node_map", "link", "from", "this", "question", "all", "of", "its", "next", "questions"], "sha": "cd0df44863c6cb158d129365f874156ac1ea7b9d", "url": "https://github.com/butchmarshall/active_record_survey/blob/cd0df44863c6cb158d129365f874156ac1ea7b9d/lib/active_record_survey/node/question.rb#L101-L122", "partition": "test"} {"repo": "butchmarshall/active_record_survey", "path": "lib/active_record_survey/node/question.rb", "func_name": "ActiveRecordSurvey.Node::Question.before_destroy_rebuild_node_map", "original_string": "def before_destroy_rebuild_node_map\n\n\t\t\t\tself.survey.node_maps.select { |i|\n\t\t\t\t\ti.node == self\n\t\t\t\t}.each { |node_map|\n\t\t\t\t\t# Remap all of this nodes children to the parent\n\t\t\t\t\tnode_map.children.each { |child|\n\t\t\t\t\t\tif !child.node.class.ancestors.include?(::ActiveRecordSurvey::Node::Answer)\n\t\t\t\t\t\t\tnode_map.parent.children << child\n\t\t\t\t\t\tend\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\ttrue\n\t\t\tend", "language": "ruby", "code": "def before_destroy_rebuild_node_map\n\n\t\t\t\tself.survey.node_maps.select { |i|\n\t\t\t\t\ti.node == self\n\t\t\t\t}.each { |node_map|\n\t\t\t\t\t# Remap all of this nodes children to the parent\n\t\t\t\t\tnode_map.children.each { |child|\n\t\t\t\t\t\tif !child.node.class.ancestors.include?(::ActiveRecordSurvey::Node::Answer)\n\t\t\t\t\t\t\tnode_map.parent.children << child\n\t\t\t\t\t\tend\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\ttrue\n\t\t\tend", "code_tokens": ["def", "before_destroy_rebuild_node_map", "self", ".", "survey", ".", "node_maps", ".", "select", "{", "|", "i", "|", "i", ".", "node", "==", "self", "}", ".", "each", "{", "|", "node_map", "|", "# Remap all of this nodes children to the parent", "node_map", ".", "children", ".", "each", "{", "|", "child", "|", "if", "!", "child", ".", "node", ".", "class", ".", "ancestors", ".", "include?", "(", "::", "ActiveRecordSurvey", "::", "Node", "::", "Answer", ")", "node_map", ".", "parent", ".", "children", "<<", "child", "end", "}", "}", "true", "end"], "docstring": "Before a node is destroyed, will re-build the node_map links from parent to child if they exist\n If a question is being destroyed and it has answers - don't link its answers - only parent questions that follow it", "docstring_tokens": ["Before", "a", "node", "is", "destroyed", "will", "re", "-", "build", "the", "node_map", "links", "from", "parent", "to", "child", "if", "they", "exist", "If", "a", "question", "is", "being", "destroyed", "and", "it", "has", "answers", "-", "don", "t", "link", "its", "answers", "-", "only", "parent", "questions", "that", "follow", "it"], "sha": "cd0df44863c6cb158d129365f874156ac1ea7b9d", "url": "https://github.com/butchmarshall/active_record_survey/blob/cd0df44863c6cb158d129365f874156ac1ea7b9d/lib/active_record_survey/node/question.rb#L148-L162", "partition": "test"} {"repo": "jgdavey/tabletastic", "path": "lib/tabletastic/helper.rb", "func_name": "Tabletastic.Helper.table_for", "original_string": "def table_for(collection, *args, &block)\n block = Tabletastic.default_table_block unless block_given?\n klass = default_class_for(collection)\n options = args.extract_options!\n initialize_html_options(options, klass)\n result = capture { block.call(TableBuilder.new(collection, klass, self)) }\n content_tag(:table, result, options[:html])\n end", "language": "ruby", "code": "def table_for(collection, *args, &block)\n block = Tabletastic.default_table_block unless block_given?\n klass = default_class_for(collection)\n options = args.extract_options!\n initialize_html_options(options, klass)\n result = capture { block.call(TableBuilder.new(collection, klass, self)) }\n content_tag(:table, result, options[:html])\n end", "code_tokens": ["def", "table_for", "(", "collection", ",", "*", "args", ",", "&", "block", ")", "block", "=", "Tabletastic", ".", "default_table_block", "unless", "block_given?", "klass", "=", "default_class_for", "(", "collection", ")", "options", "=", "args", ".", "extract_options!", "initialize_html_options", "(", "options", ",", "klass", ")", "result", "=", "capture", "{", "block", ".", "call", "(", "TableBuilder", ".", "new", "(", "collection", ",", "klass", ",", "self", ")", ")", "}", "content_tag", "(", ":table", ",", "result", ",", "options", "[", ":html", "]", ")", "end"], "docstring": "returns and outputs a table for the given active record collection", "docstring_tokens": ["returns", "and", "outputs", "a", "table", "for", "the", "given", "active", "record", "collection"], "sha": "f134ec93705ca187c9b48652a34b22f78fe623ee", "url": "https://github.com/jgdavey/tabletastic/blob/f134ec93705ca187c9b48652a34b22f78fe623ee/lib/tabletastic/helper.rb#L4-L11", "partition": "test"} {"repo": "jgdavey/tabletastic", "path": "lib/tabletastic/helper.rb", "func_name": "Tabletastic.Helper.default_class_for", "original_string": "def default_class_for(collection)\n if collection.respond_to?(:klass) # ActiveRecord::Relation\n collection.klass\n elsif !collection.empty?\n collection.first.class\n end\n end", "language": "ruby", "code": "def default_class_for(collection)\n if collection.respond_to?(:klass) # ActiveRecord::Relation\n collection.klass\n elsif !collection.empty?\n collection.first.class\n end\n end", "code_tokens": ["def", "default_class_for", "(", "collection", ")", "if", "collection", ".", "respond_to?", "(", ":klass", ")", "# ActiveRecord::Relation", "collection", ".", "klass", "elsif", "!", "collection", ".", "empty?", "collection", ".", "first", ".", "class", "end", "end"], "docstring": "Finds the class representing the objects within the collection", "docstring_tokens": ["Finds", "the", "class", "representing", "the", "objects", "within", "the", "collection"], "sha": "f134ec93705ca187c9b48652a34b22f78fe623ee", "url": "https://github.com/jgdavey/tabletastic/blob/f134ec93705ca187c9b48652a34b22f78fe623ee/lib/tabletastic/helper.rb#L15-L21", "partition": "test"} {"repo": "burtlo/metro", "path": "lib/metro/events/event_dictionary.rb", "func_name": "Metro.EventDictionary.events_for_targets", "original_string": "def events_for_targets(*list)\n found_events = Array(list).flatten.compact.map {|s| events_for_target(s) }.flatten.compact\n found_events\n end", "language": "ruby", "code": "def events_for_targets(*list)\n found_events = Array(list).flatten.compact.map {|s| events_for_target(s) }.flatten.compact\n found_events\n end", "code_tokens": ["def", "events_for_targets", "(", "*", "list", ")", "found_events", "=", "Array", "(", "list", ")", ".", "flatten", ".", "compact", ".", "map", "{", "|", "s", "|", "events_for_target", "(", "s", ")", "}", ".", "flatten", ".", "compact", "found_events", "end"], "docstring": "Return all the events for all the specified targets.", "docstring_tokens": ["Return", "all", "the", "events", "for", "all", "the", "specified", "targets", "."], "sha": "5fd7d1fd433f3aece8451af8098b23bb14007227", "url": "https://github.com/burtlo/metro/blob/5fd7d1fd433f3aece8451af8098b23bb14007227/lib/metro/events/event_dictionary.rb#L29-L32", "partition": "test"} {"repo": "burtlo/metro", "path": "lib/metro/views/view.rb", "func_name": "Metro.View.writer", "original_string": "def writer\n @writer ||= begin\n writer_matching_existing_parser = supported_writers.find { |writer| writer.format == format }\n writer_matching_existing_parser || default_writer\n end\n end", "language": "ruby", "code": "def writer\n @writer ||= begin\n writer_matching_existing_parser = supported_writers.find { |writer| writer.format == format }\n writer_matching_existing_parser || default_writer\n end\n end", "code_tokens": ["def", "writer", "@writer", "||=", "begin", "writer_matching_existing_parser", "=", "supported_writers", ".", "find", "{", "|", "writer", "|", "writer", ".", "format", "==", "format", "}", "writer_matching_existing_parser", "||", "default_writer", "end", "end"], "docstring": "The writer for this view. If the view has already been parsed then use", "docstring_tokens": ["The", "writer", "for", "this", "view", ".", "If", "the", "view", "has", "already", "been", "parsed", "then", "use"], "sha": "5fd7d1fd433f3aece8451af8098b23bb14007227", "url": "https://github.com/burtlo/metro/blob/5fd7d1fd433f3aece8451af8098b23bb14007227/lib/metro/views/view.rb#L116-L121", "partition": "test"} {"repo": "burtlo/metro", "path": "lib/metro/animation/has_animations.rb", "func_name": "Metro.HasAnimations.animate", "original_string": "def animate(actor_or_actor_name,options,&block)\n options[:actor] = actor(actor_or_actor_name)\n options[:context] = self\n animation_group = SceneAnimation.build options, &block\n enqueue animation_group\n end", "language": "ruby", "code": "def animate(actor_or_actor_name,options,&block)\n options[:actor] = actor(actor_or_actor_name)\n options[:context] = self\n animation_group = SceneAnimation.build options, &block\n enqueue animation_group\n end", "code_tokens": ["def", "animate", "(", "actor_or_actor_name", ",", "options", ",", "&", "block", ")", "options", "[", ":actor", "]", "=", "actor", "(", "actor_or_actor_name", ")", "options", "[", ":context", "]", "=", "self", "animation_group", "=", "SceneAnimation", ".", "build", "options", ",", "block", "enqueue", "animation_group", "end"], "docstring": "Define an animation from within another animation block, an event block\n or a method.\n\n @example Defining an animation that fades out the hero when they have\n died.\n\n class HellScene\n draws :hero\n\n def update\n if hero.dead?\n animate :hero, to: { alpha: 0 }, interval: 60.ticks do\n transition_to :game_over\n end\n end\n end\n\n end", "docstring_tokens": ["Define", "an", "animation", "from", "within", "another", "animation", "block", "an", "event", "block", "or", "a", "method", "."], "sha": "5fd7d1fd433f3aece8451af8098b23bb14007227", "url": "https://github.com/burtlo/metro/blob/5fd7d1fd433f3aece8451af8098b23bb14007227/lib/metro/animation/has_animations.rb#L30-L35", "partition": "test"} {"repo": "burtlo/metro", "path": "lib/metro/events/event_relay.rb", "func_name": "Metro.EventRelay.on_mouse_movement", "original_string": "def on_mouse_movement(*args,&block)\n options = (args.last.is_a?(Hash) ? args.pop : {})\n @mouse_movement_actions << ( block || lambda { |instance| send(options[:do]) } )\n end", "language": "ruby", "code": "def on_mouse_movement(*args,&block)\n options = (args.last.is_a?(Hash) ? args.pop : {})\n @mouse_movement_actions << ( block || lambda { |instance| send(options[:do]) } )\n end", "code_tokens": ["def", "on_mouse_movement", "(", "*", "args", ",", "&", "block", ")", "options", "=", "(", "args", ".", "last", ".", "is_a?", "(", "Hash", ")", "?", "args", ".", "pop", ":", "{", "}", ")", "@mouse_movement_actions", "<<", "(", "block", "||", "lambda", "{", "|", "instance", "|", "send", "(", "options", "[", ":do", "]", ")", "}", ")", "end"], "docstring": "Register for mouse movements events. These events are fired each update\n providing an event which contains the current position of the mouse.\n\n @note mouse movement events fire with each update so it is up to the\n receiving object of the event to determine if the new mouse movement\n is a delta.\n\n @note mouse movement events require that the window be specified during initialization.\n\n @example Registering for button held events\n\n class ExampleScene\n\n draws :player\n\n event :on_mouse_movement do |event|\n player.position = event.mouse_point\n end\n end", "docstring_tokens": ["Register", "for", "mouse", "movements", "events", ".", "These", "events", "are", "fired", "each", "update", "providing", "an", "event", "which", "contains", "the", "current", "position", "of", "the", "mouse", "."], "sha": "5fd7d1fd433f3aece8451af8098b23bb14007227", "url": "https://github.com/burtlo/metro/blob/5fd7d1fd433f3aece8451af8098b23bb14007227/lib/metro/events/event_relay.rb#L205-L208", "partition": "test"} {"repo": "burtlo/metro", "path": "lib/metro/events/event_relay.rb", "func_name": "Metro.EventRelay.notification", "original_string": "def notification(param,&block)\n custom_notifications[param.to_sym] = custom_notifications[param.to_sym] + [ block ]\n end", "language": "ruby", "code": "def notification(param,&block)\n custom_notifications[param.to_sym] = custom_notifications[param.to_sym] + [ block ]\n end", "code_tokens": ["def", "notification", "(", "param", ",", "&", "block", ")", "custom_notifications", "[", "param", ".", "to_sym", "]", "=", "custom_notifications", "[", "param", ".", "to_sym", "]", "+", "[", "block", "]", "end"], "docstring": "Register for a custom notification event. These events are fired when\n another object within the game posts a notification with matching criteria.\n If there has indeed been a match, then the stored action block will be fired.\n\n When the action block is specified is defined with no parameters it is assumed that\n that the code should be executed within the context of the object that defined\n the action, the 'target'.\n\n @example Registering for a save complete event that would re-enable a menu.\n\n class ExampleScene\n event :notification, :save_complete do\n menu.enabled!\n end\n end\n\n The action block can also be specified with two parameters. In this case the code is\n no longer executed within the context of the object and is instead provided the\n the action target and the action source.\n\n @example Registering for a win game event that explicitly states the target and source.\n\n class ExampleScene\n\n event :notification, :win_game do |target,winner|\n target.declare_winner winner\n end\n\n def declare_winner(winning_player)\n # ...\n end\n end", "docstring_tokens": ["Register", "for", "a", "custom", "notification", "event", ".", "These", "events", "are", "fired", "when", "another", "object", "within", "the", "game", "posts", "a", "notification", "with", "matching", "criteria", ".", "If", "there", "has", "indeed", "been", "a", "match", "then", "the", "stored", "action", "block", "will", "be", "fired", "."], "sha": "5fd7d1fd433f3aece8451af8098b23bb14007227", "url": "https://github.com/burtlo/metro/blob/5fd7d1fd433f3aece8451af8098b23bb14007227/lib/metro/events/event_relay.rb#L244-L246", "partition": "test"} {"repo": "burtlo/metro", "path": "lib/metro/events/event_relay.rb", "func_name": "Metro.EventRelay.fire_events_for_held_buttons", "original_string": "def fire_events_for_held_buttons\n held_actions.each do |key,action|\n execute_block_for_target(&action) if window and window.button_down?(key)\n end\n end", "language": "ruby", "code": "def fire_events_for_held_buttons\n held_actions.each do |key,action|\n execute_block_for_target(&action) if window and window.button_down?(key)\n end\n end", "code_tokens": ["def", "fire_events_for_held_buttons", "held_actions", ".", "each", "do", "|", "key", ",", "action", "|", "execute_block_for_target", "(", "action", ")", "if", "window", "and", "window", ".", "button_down?", "(", "key", ")", "end", "end"], "docstring": "Fire the events mapped to the held buttons within the context\n of the specified target. This method is differently formatted because held buttons are not\n events but polling to see if the button is still being held.", "docstring_tokens": ["Fire", "the", "events", "mapped", "to", "the", "held", "buttons", "within", "the", "context", "of", "the", "specified", "target", ".", "This", "method", "is", "differently", "formatted", "because", "held", "buttons", "are", "not", "events", "but", "polling", "to", "see", "if", "the", "button", "is", "still", "being", "held", "."], "sha": "5fd7d1fd433f3aece8451af8098b23bb14007227", "url": "https://github.com/burtlo/metro/blob/5fd7d1fd433f3aece8451af8098b23bb14007227/lib/metro/events/event_relay.rb#L283-L287", "partition": "test"} {"repo": "burtlo/metro", "path": "lib/metro/events/event_relay.rb", "func_name": "Metro.EventRelay.fire_events_for_notification", "original_string": "def fire_events_for_notification(event,sender)\n notification_actions = custom_notifications[event]\n notification_actions.each do |action|\n _fire_event_for_notification(event,sender,action)\n end\n end", "language": "ruby", "code": "def fire_events_for_notification(event,sender)\n notification_actions = custom_notifications[event]\n notification_actions.each do |action|\n _fire_event_for_notification(event,sender,action)\n end\n end", "code_tokens": ["def", "fire_events_for_notification", "(", "event", ",", "sender", ")", "notification_actions", "=", "custom_notifications", "[", "event", "]", "notification_actions", ".", "each", "do", "|", "action", "|", "_fire_event_for_notification", "(", "event", ",", "sender", ",", "action", ")", "end", "end"], "docstring": "Fire all events mapped to the matching notification.", "docstring_tokens": ["Fire", "all", "events", "mapped", "to", "the", "matching", "notification", "."], "sha": "5fd7d1fd433f3aece8451af8098b23bb14007227", "url": "https://github.com/burtlo/metro/blob/5fd7d1fd433f3aece8451af8098b23bb14007227/lib/metro/events/event_relay.rb#L317-L322", "partition": "test"} {"repo": "burtlo/metro", "path": "lib/metro/events/event_relay.rb", "func_name": "Metro.EventRelay._fire_event_for_notification", "original_string": "def _fire_event_for_notification(event,sender,action)\n if action.arity == 2\n target.instance_exec(sender,event,&action)\n elsif action.arity == 1\n target.instance_exec(sender,&action)\n else\n target.instance_eval(&action)\n end\n end", "language": "ruby", "code": "def _fire_event_for_notification(event,sender,action)\n if action.arity == 2\n target.instance_exec(sender,event,&action)\n elsif action.arity == 1\n target.instance_exec(sender,&action)\n else\n target.instance_eval(&action)\n end\n end", "code_tokens": ["def", "_fire_event_for_notification", "(", "event", ",", "sender", ",", "action", ")", "if", "action", ".", "arity", "==", "2", "target", ".", "instance_exec", "(", "sender", ",", "event", ",", "action", ")", "elsif", "action", ".", "arity", "==", "1", "target", ".", "instance_exec", "(", "sender", ",", "action", ")", "else", "target", ".", "instance_eval", "(", "action", ")", "end", "end"], "docstring": "Fire a single event based on the matched notification.\n\n An action without any parameters is assumed to be executed within the contexxt\n of the target. If there are two parameters we will simply execute the action and\n pass it both the target and the sender.", "docstring_tokens": ["Fire", "a", "single", "event", "based", "on", "the", "matched", "notification", "."], "sha": "5fd7d1fd433f3aece8451af8098b23bb14007227", "url": "https://github.com/burtlo/metro/blob/5fd7d1fd433f3aece8451af8098b23bb14007227/lib/metro/events/event_relay.rb#L331-L339", "partition": "test"} {"repo": "burtlo/metro", "path": "lib/metro/models/models.rb", "func_name": "Metro.Models.add", "original_string": "def add(model)\n all_models_for(model).each do |model|\n models_hash[model.to_s] = model.to_s\n name_with_slashes = model.model_name\n models_hash[name_with_slashes] = model.to_s\n name_with_colons = name_with_slashes.gsub('/','::')\n models_hash[name_with_colons] = model.to_s\n end\n end", "language": "ruby", "code": "def add(model)\n all_models_for(model).each do |model|\n models_hash[model.to_s] = model.to_s\n name_with_slashes = model.model_name\n models_hash[name_with_slashes] = model.to_s\n name_with_colons = name_with_slashes.gsub('/','::')\n models_hash[name_with_colons] = model.to_s\n end\n end", "code_tokens": ["def", "add", "(", "model", ")", "all_models_for", "(", "model", ")", ".", "each", "do", "|", "model", "|", "models_hash", "[", "model", ".", "to_s", "]", "=", "model", ".", "to_s", "name_with_slashes", "=", "model", ".", "model_name", "models_hash", "[", "name_with_slashes", "]", "=", "model", ".", "to_s", "name_with_colons", "=", "name_with_slashes", ".", "gsub", "(", "'/'", ",", "'::'", ")", "models_hash", "[", "name_with_colons", "]", "=", "model", ".", "to_s", "end", "end"], "docstring": "Add a model, and all it's subclasses, to the list of available models.\n\n A model has several names added so that it accessible in many ways:\n\n * Model Class Name\n * Model Name\n * Model Name with slashes replaced with `::` separator", "docstring_tokens": ["Add", "a", "model", "and", "all", "it", "s", "subclasses", "to", "the", "list", "of", "available", "models", "."], "sha": "5fd7d1fd433f3aece8451af8098b23bb14007227", "url": "https://github.com/burtlo/metro/blob/5fd7d1fd433f3aece8451af8098b23bb14007227/lib/metro/models/models.rb#L16-L24", "partition": "test"} {"repo": "burtlo/metro", "path": "lib/metro/animation/implicit_animation.rb", "func_name": "Metro.ImplicitAnimation.after_initialize", "original_string": "def after_initialize\n to.each do |attribute,final|\n start = actor.send(attribute)\n animations.push build_animation_step(attribute,start,final)\n end\n end", "language": "ruby", "code": "def after_initialize\n to.each do |attribute,final|\n start = actor.send(attribute)\n animations.push build_animation_step(attribute,start,final)\n end\n end", "code_tokens": ["def", "after_initialize", "to", ".", "each", "do", "|", "attribute", ",", "final", "|", "start", "=", "actor", ".", "send", "(", "attribute", ")", "animations", ".", "push", "build_animation_step", "(", "attribute", ",", "start", ",", "final", ")", "end", "end"], "docstring": "Additional initializion is required to calculate the attributes\n that are going to be animated and to determine each of their deltas.", "docstring_tokens": ["Additional", "initializion", "is", "required", "to", "calculate", "the", "attributes", "that", "are", "going", "to", "be", "animated", "and", "to", "determine", "each", "of", "their", "deltas", "."], "sha": "5fd7d1fd433f3aece8451af8098b23bb14007227", "url": "https://github.com/burtlo/metro/blob/5fd7d1fd433f3aece8451af8098b23bb14007227/lib/metro/animation/implicit_animation.rb#L52-L57", "partition": "test"} {"repo": "burtlo/metro", "path": "lib/metro/events/event_state_manager.rb", "func_name": "Metro.EventStateManager.fire_events_for_notification", "original_string": "def fire_events_for_notification(event,sender)\n current_state.each {|cs| cs.fire_events_for_notification(event,sender) }\n end", "language": "ruby", "code": "def fire_events_for_notification(event,sender)\n current_state.each {|cs| cs.fire_events_for_notification(event,sender) }\n end", "code_tokens": ["def", "fire_events_for_notification", "(", "event", ",", "sender", ")", "current_state", ".", "each", "{", "|", "cs", "|", "cs", ".", "fire_events_for_notification", "(", "event", ",", "sender", ")", "}", "end"], "docstring": "Fire notification events within the current game state", "docstring_tokens": ["Fire", "notification", "events", "within", "the", "current", "game", "state"], "sha": "5fd7d1fd433f3aece8451af8098b23bb14007227", "url": "https://github.com/burtlo/metro/blob/5fd7d1fd433f3aece8451af8098b23bb14007227/lib/metro/events/event_state_manager.rb#L52-L54", "partition": "test"} {"repo": "burtlo/metro", "path": "lib/metro/events/event_state_manager.rb", "func_name": "Metro.EventStateManager.add_events_for_target", "original_string": "def add_events_for_target(target,events)\n relay = EventRelay.new(target,window)\n\n events.each do |target_event|\n relay.send target_event.event, *target_event.buttons, &target_event.block\n end\n\n current_state.push relay\n end", "language": "ruby", "code": "def add_events_for_target(target,events)\n relay = EventRelay.new(target,window)\n\n events.each do |target_event|\n relay.send target_event.event, *target_event.buttons, &target_event.block\n end\n\n current_state.push relay\n end", "code_tokens": ["def", "add_events_for_target", "(", "target", ",", "events", ")", "relay", "=", "EventRelay", ".", "new", "(", "target", ",", "window", ")", "events", ".", "each", "do", "|", "target_event", "|", "relay", ".", "send", "target_event", ".", "event", ",", "target_event", ".", "buttons", ",", "target_event", ".", "block", "end", "current_state", ".", "push", "relay", "end"], "docstring": "An an event relay to the current game state", "docstring_tokens": ["An", "an", "event", "relay", "to", "the", "current", "game", "state"], "sha": "5fd7d1fd433f3aece8451af8098b23bb14007227", "url": "https://github.com/burtlo/metro/blob/5fd7d1fd433f3aece8451af8098b23bb14007227/lib/metro/events/event_state_manager.rb#L59-L67", "partition": "test"} {"repo": "burtlo/metro", "path": "lib/metro/events/controls.rb", "func_name": "Metro.Controls.method_missing", "original_string": "def method_missing(name,*params,&block)\n options = params.find {|param| param.is_a? Hash }\n define_control(name,options)\n end", "language": "ruby", "code": "def method_missing(name,*params,&block)\n options = params.find {|param| param.is_a? Hash }\n define_control(name,options)\n end", "code_tokens": ["def", "method_missing", "(", "name", ",", "*", "params", ",", "&", "block", ")", "options", "=", "params", ".", "find", "{", "|", "param", "|", "param", ".", "is_a?", "Hash", "}", "define_control", "(", "name", ",", "options", ")", "end"], "docstring": "Creation through controls is usually done with an instance_eval\n of a block and this allows for a flexible interface.\n\n @param [String,Symbol] name the name or the alias of the control\n as it will be used within the course of the game.", "docstring_tokens": ["Creation", "through", "controls", "is", "usually", "done", "with", "an", "instance_eval", "of", "a", "block", "and", "this", "allows", "for", "a", "flexible", "interface", "."], "sha": "5fd7d1fd433f3aece8451af8098b23bb14007227", "url": "https://github.com/burtlo/metro/blob/5fd7d1fd433f3aece8451af8098b23bb14007227/lib/metro/events/controls.rb#L18-L21", "partition": "test"} {"repo": "burtlo/metro", "path": "lib/metro/game.rb", "func_name": "Metro.Game.start!", "original_string": "def start!\n @window = Window.new width, height, fullscreen?\n window.caption = name\n window.scene = Scenes.generate(first_scene)\n window.show\n end", "language": "ruby", "code": "def start!\n @window = Window.new width, height, fullscreen?\n window.caption = name\n window.scene = Scenes.generate(first_scene)\n window.show\n end", "code_tokens": ["def", "start!", "@window", "=", "Window", ".", "new", "width", ",", "height", ",", "fullscreen?", "window", ".", "caption", "=", "name", "window", ".", "scene", "=", "Scenes", ".", "generate", "(", "first_scene", ")", "window", ".", "show", "end"], "docstring": "Creates a window and starts the game with the game parameters.", "docstring_tokens": ["Creates", "a", "window", "and", "starts", "the", "game", "with", "the", "game", "parameters", "."], "sha": "5fd7d1fd433f3aece8451af8098b23bb14007227", "url": "https://github.com/burtlo/metro/blob/5fd7d1fd433f3aece8451af8098b23bb14007227/lib/metro/game.rb#L14-L19", "partition": "test"} {"repo": "burtlo/metro", "path": "lib/metro/transitions/fade_transition_scene.rb", "func_name": "Metro.FadeTransitionScene.show", "original_string": "def show\n rectangle.color = starting_color\n\n color = final_color\n\n animate :rectangle, to: { red: color.red,\n green: color.green,\n blue: color.blue,\n alpha: color.alpha },\n interval: interval do\n\n transition_to next_scene\n end\n end", "language": "ruby", "code": "def show\n rectangle.color = starting_color\n\n color = final_color\n\n animate :rectangle, to: { red: color.red,\n green: color.green,\n blue: color.blue,\n alpha: color.alpha },\n interval: interval do\n\n transition_to next_scene\n end\n end", "code_tokens": ["def", "show", "rectangle", ".", "color", "=", "starting_color", "color", "=", "final_color", "animate", ":rectangle", ",", "to", ":", "{", "red", ":", "color", ".", "red", ",", "green", ":", "color", ".", "green", ",", "blue", ":", "color", ".", "blue", ",", "alpha", ":", "color", ".", "alpha", "}", ",", "interval", ":", "interval", "do", "transition_to", "next_scene", "end", "end"], "docstring": "When the scene is shown set up the starting color for the rectangle\n and queue the animation to transition the color to the final color.", "docstring_tokens": ["When", "the", "scene", "is", "shown", "set", "up", "the", "starting", "color", "for", "the", "rectangle", "and", "queue", "the", "animation", "to", "transition", "the", "color", "to", "the", "final", "color", "."], "sha": "5fd7d1fd433f3aece8451af8098b23bb14007227", "url": "https://github.com/burtlo/metro/blob/5fd7d1fd433f3aece8451af8098b23bb14007227/lib/metro/transitions/fade_transition_scene.rb#L10-L23", "partition": "test"} {"repo": "jgdavey/tabletastic", "path": "lib/tabletastic/table_builder.rb", "func_name": "Tabletastic.TableBuilder.data", "original_string": "def data(*args, &block) # :yields: tablebody\n options = args.extract_options!\n if block_given?\n yield self\n else\n @table_fields = args.empty? ? orm_fields : args.collect {|f| TableField.new(f.to_sym)}\n end\n action_cells(options[:actions], options[:action_prefix])\n [\"\\n\", head, \"\\n\", body, \"\\n\"].join(\"\").html_safe\n end", "language": "ruby", "code": "def data(*args, &block) # :yields: tablebody\n options = args.extract_options!\n if block_given?\n yield self\n else\n @table_fields = args.empty? ? orm_fields : args.collect {|f| TableField.new(f.to_sym)}\n end\n action_cells(options[:actions], options[:action_prefix])\n [\"\\n\", head, \"\\n\", body, \"\\n\"].join(\"\").html_safe\n end", "code_tokens": ["def", "data", "(", "*", "args", ",", "&", "block", ")", "# :yields: tablebody", "options", "=", "args", ".", "extract_options!", "if", "block_given?", "yield", "self", "else", "@table_fields", "=", "args", ".", "empty?", "?", "orm_fields", ":", "args", ".", "collect", "{", "|", "f", "|", "TableField", ".", "new", "(", "f", ".", "to_sym", ")", "}", "end", "action_cells", "(", "options", "[", ":actions", "]", ",", "options", "[", ":action_prefix", "]", ")", "[", "\"\\n\"", ",", "head", ",", "\"\\n\"", ",", "body", ",", "\"\\n\"", "]", ".", "join", "(", "\"\"", ")", ".", "html_safe", "end"], "docstring": "builds up the fields that the table will include,\n returns table head and body with all data\n\n Can be used one of three ways:\n\n * Alone, which will try to detect all content columns on the resource\n * With an array of methods to call on each element in the collection\n * With a block, which assumes you will use +cell+ method to build up\n the table", "docstring_tokens": ["builds", "up", "the", "fields", "that", "the", "table", "will", "include", "returns", "table", "head", "and", "body", "with", "all", "data"], "sha": "f134ec93705ca187c9b48652a34b22f78fe623ee", "url": "https://github.com/jgdavey/tabletastic/blob/f134ec93705ca187c9b48652a34b22f78fe623ee/lib/tabletastic/table_builder.rb#L25-L34", "partition": "test"} {"repo": "jgdavey/tabletastic", "path": "lib/tabletastic/table_builder.rb", "func_name": "Tabletastic.TableBuilder.cell", "original_string": "def cell(*args, &proc)\n options = args.extract_options!\n options.merge!(:klass => klass)\n args << options\n @table_fields << TableField.new(*args, &proc)\n # Since this will likely be called with <%= %> (aka 'concat'), explicitly return an \n # empty string; this suppresses unwanted output\n return \"\"\n end", "language": "ruby", "code": "def cell(*args, &proc)\n options = args.extract_options!\n options.merge!(:klass => klass)\n args << options\n @table_fields << TableField.new(*args, &proc)\n # Since this will likely be called with <%= %> (aka 'concat'), explicitly return an \n # empty string; this suppresses unwanted output\n return \"\"\n end", "code_tokens": ["def", "cell", "(", "*", "args", ",", "&", "proc", ")", "options", "=", "args", ".", "extract_options!", "options", ".", "merge!", "(", ":klass", "=>", "klass", ")", "args", "<<", "options", "@table_fields", "<<", "TableField", ".", "new", "(", "args", ",", "proc", ")", "# Since this will likely be called with <%= %> (aka 'concat'), explicitly return an ", "# empty string; this suppresses unwanted output", "return", "\"\"", "end"], "docstring": "individually specify a column, which will build up the header,\n and method or block to call on each resource in the array\n\n Should always be called within the block of +data+\n\n For example:\n\n t.cell :blah\n\n will simply call +blah+ on each resource\n\n You can also provide a block, which allows for other helpers\n or custom formatting. Since by default erb will just call +to_s+\n on an any element output, you can more greatly control the output:\n\n t.cell(:price) {|resource| number_to_currency(resource)}\n\n would output something like:\n\n $1.50", "docstring_tokens": ["individually", "specify", "a", "column", "which", "will", "build", "up", "the", "header", "and", "method", "or", "block", "to", "call", "on", "each", "resource", "in", "the", "array"], "sha": "f134ec93705ca187c9b48652a34b22f78fe623ee", "url": "https://github.com/jgdavey/tabletastic/blob/f134ec93705ca187c9b48652a34b22f78fe623ee/lib/tabletastic/table_builder.rb#L57-L65", "partition": "test"} {"repo": "jgdavey/tabletastic", "path": "lib/tabletastic/table_builder.rb", "func_name": "Tabletastic.TableBuilder.action_cells", "original_string": "def action_cells(actions, prefix = nil)\n return if actions.blank?\n actions = [actions] if !actions.respond_to?(:each)\n actions = [:show, :edit, :destroy] if actions == [:all]\n actions.each do |action|\n action_link(action.to_sym, prefix)\n end\n end", "language": "ruby", "code": "def action_cells(actions, prefix = nil)\n return if actions.blank?\n actions = [actions] if !actions.respond_to?(:each)\n actions = [:show, :edit, :destroy] if actions == [:all]\n actions.each do |action|\n action_link(action.to_sym, prefix)\n end\n end", "code_tokens": ["def", "action_cells", "(", "actions", ",", "prefix", "=", "nil", ")", "return", "if", "actions", ".", "blank?", "actions", "=", "[", "actions", "]", "if", "!", "actions", ".", "respond_to?", "(", ":each", ")", "actions", "=", "[", ":show", ",", ":edit", ",", ":destroy", "]", "if", "actions", "==", "[", ":all", "]", "actions", ".", "each", "do", "|", "action", "|", "action_link", "(", "action", ".", "to_sym", ",", "prefix", ")", "end", "end"], "docstring": "Used internally to build up cells for common CRUD actions", "docstring_tokens": ["Used", "internally", "to", "build", "up", "cells", "for", "common", "CRUD", "actions"], "sha": "f134ec93705ca187c9b48652a34b22f78fe623ee", "url": "https://github.com/jgdavey/tabletastic/blob/f134ec93705ca187c9b48652a34b22f78fe623ee/lib/tabletastic/table_builder.rb#L95-L102", "partition": "test"} {"repo": "jgdavey/tabletastic", "path": "lib/tabletastic/table_builder.rb", "func_name": "Tabletastic.TableBuilder.action_link", "original_string": "def action_link(action, prefix)\n html_class = \"actions #{action.to_s}_link\"\n block = lambda do |resource|\n compound_resource = [prefix, resource].compact\n compound_resource.flatten! if prefix.kind_of?(Array)\n case action\n when :show\n @template.link_to(link_title(action), compound_resource)\n when :destroy\n @template.link_to(link_title(action), compound_resource,\n :method => :delete, :data => { :confirm => confirmation_message })\n else # edit, other resource GET actions\n @template.link_to(link_title(action),\n @template.polymorphic_path(compound_resource, :action => action))\n end\n end\n self.cell(action, :heading => \"\", :cell_html => {:class => html_class}, &block)\n end", "language": "ruby", "code": "def action_link(action, prefix)\n html_class = \"actions #{action.to_s}_link\"\n block = lambda do |resource|\n compound_resource = [prefix, resource].compact\n compound_resource.flatten! if prefix.kind_of?(Array)\n case action\n when :show\n @template.link_to(link_title(action), compound_resource)\n when :destroy\n @template.link_to(link_title(action), compound_resource,\n :method => :delete, :data => { :confirm => confirmation_message })\n else # edit, other resource GET actions\n @template.link_to(link_title(action),\n @template.polymorphic_path(compound_resource, :action => action))\n end\n end\n self.cell(action, :heading => \"\", :cell_html => {:class => html_class}, &block)\n end", "code_tokens": ["def", "action_link", "(", "action", ",", "prefix", ")", "html_class", "=", "\"actions #{action.to_s}_link\"", "block", "=", "lambda", "do", "|", "resource", "|", "compound_resource", "=", "[", "prefix", ",", "resource", "]", ".", "compact", "compound_resource", ".", "flatten!", "if", "prefix", ".", "kind_of?", "(", "Array", ")", "case", "action", "when", ":show", "@template", ".", "link_to", "(", "link_title", "(", "action", ")", ",", "compound_resource", ")", "when", ":destroy", "@template", ".", "link_to", "(", "link_title", "(", "action", ")", ",", "compound_resource", ",", ":method", "=>", ":delete", ",", ":data", "=>", "{", ":confirm", "=>", "confirmation_message", "}", ")", "else", "# edit, other resource GET actions", "@template", ".", "link_to", "(", "link_title", "(", "action", ")", ",", "@template", ".", "polymorphic_path", "(", "compound_resource", ",", ":action", "=>", "action", ")", ")", "end", "end", "self", ".", "cell", "(", "action", ",", ":heading", "=>", "\"\"", ",", ":cell_html", "=>", "{", ":class", "=>", "html_class", "}", ",", "block", ")", "end"], "docstring": "Dynamically builds links for the action", "docstring_tokens": ["Dynamically", "builds", "links", "for", "the", "action"], "sha": "f134ec93705ca187c9b48652a34b22f78fe623ee", "url": "https://github.com/jgdavey/tabletastic/blob/f134ec93705ca187c9b48652a34b22f78fe623ee/lib/tabletastic/table_builder.rb#L105-L122", "partition": "test"} {"repo": "burtlo/metro", "path": "lib/metro/scenes.rb", "func_name": "Metro.Scenes.add", "original_string": "def add(scene)\n all_scenes_for(scene).each { |scene| scenes_hash[scene.scene_name] = scene.to_s }\n end", "language": "ruby", "code": "def add(scene)\n all_scenes_for(scene).each { |scene| scenes_hash[scene.scene_name] = scene.to_s }\n end", "code_tokens": ["def", "add", "(", "scene", ")", "all_scenes_for", "(", "scene", ")", ".", "each", "{", "|", "scene", "|", "scenes_hash", "[", "scene", ".", "scene_name", "]", "=", "scene", ".", "to_s", "}", "end"], "docstring": "Add a scene to the hash of scenes with the scene name of the scene as the key\n to retrieving this scene.\n\n @param [Scene] scene the scene to be added to the hash of Scenes.", "docstring_tokens": ["Add", "a", "scene", "to", "the", "hash", "of", "scenes", "with", "the", "scene", "name", "of", "the", "scene", "as", "the", "key", "to", "retrieving", "this", "scene", "."], "sha": "5fd7d1fd433f3aece8451af8098b23bb14007227", "url": "https://github.com/burtlo/metro/blob/5fd7d1fd433f3aece8451af8098b23bb14007227/lib/metro/scenes.rb#L36-L38", "partition": "test"} {"repo": "burtlo/metro", "path": "lib/metro/scenes.rb", "func_name": "Metro.Scenes.apply_post_filters", "original_string": "def apply_post_filters(new_scene,options)\n post_filters.inject(new_scene) {|scene,post| post.filter(scene,options) }\n end", "language": "ruby", "code": "def apply_post_filters(new_scene,options)\n post_filters.inject(new_scene) {|scene,post| post.filter(scene,options) }\n end", "code_tokens": ["def", "apply_post_filters", "(", "new_scene", ",", "options", ")", "post_filters", ".", "inject", "(", "new_scene", ")", "{", "|", "scene", ",", "post", "|", "post", ".", "filter", "(", "scene", ",", "options", ")", "}", "end"], "docstring": "Apply all the post filtering to the specified scene with the given options\n\n @return a Scene object that has been filtered.", "docstring_tokens": ["Apply", "all", "the", "post", "filtering", "to", "the", "specified", "scene", "with", "the", "given", "options"], "sha": "5fd7d1fd433f3aece8451af8098b23bb14007227", "url": "https://github.com/burtlo/metro/blob/5fd7d1fd433f3aece8451af8098b23bb14007227/lib/metro/scenes.rb#L112-L114", "partition": "test"} {"repo": "burtlo/metro", "path": "lib/metro/scenes.rb", "func_name": "Metro.Scenes.hash_with_missing_scene_default", "original_string": "def hash_with_missing_scene_default\n hash = HashWithIndifferentAccess.new do |hash,key|\n missing_scene = hash[:missing_scene].constantize\n missing_scene.missing_scene = key.to_sym\n missing_scene\n end\n hash[:missing_scene] = \"Metro::MissingScene\"\n hash\n end", "language": "ruby", "code": "def hash_with_missing_scene_default\n hash = HashWithIndifferentAccess.new do |hash,key|\n missing_scene = hash[:missing_scene].constantize\n missing_scene.missing_scene = key.to_sym\n missing_scene\n end\n hash[:missing_scene] = \"Metro::MissingScene\"\n hash\n end", "code_tokens": ["def", "hash_with_missing_scene_default", "hash", "=", "HashWithIndifferentAccess", ".", "new", "do", "|", "hash", ",", "key", "|", "missing_scene", "=", "hash", "[", ":missing_scene", "]", ".", "constantize", "missing_scene", ".", "missing_scene", "=", "key", ".", "to_sym", "missing_scene", "end", "hash", "[", ":missing_scene", "]", "=", "\"Metro::MissingScene\"", "hash", "end"], "docstring": "Create a hash that will return a setup missing scene by default.", "docstring_tokens": ["Create", "a", "hash", "that", "will", "return", "a", "setup", "missing", "scene", "by", "default", "."], "sha": "5fd7d1fd433f3aece8451af8098b23bb14007227", "url": "https://github.com/burtlo/metro/blob/5fd7d1fd433f3aece8451af8098b23bb14007227/lib/metro/scenes.rb#L127-L135", "partition": "test"} {"repo": "burtlo/metro", "path": "lib/metro/scenes.rb", "func_name": "Metro.Scenes.all_scenes_for", "original_string": "def all_scenes_for(scenes)\n Array(scenes).map do |scene_class_name|\n scene = scene_class_name.constantize\n [ scene ] + all_scenes_for(scene.scenes)\n end.flatten.compact\n end", "language": "ruby", "code": "def all_scenes_for(scenes)\n Array(scenes).map do |scene_class_name|\n scene = scene_class_name.constantize\n [ scene ] + all_scenes_for(scene.scenes)\n end.flatten.compact\n end", "code_tokens": ["def", "all_scenes_for", "(", "scenes", ")", "Array", "(", "scenes", ")", ".", "map", "do", "|", "scene_class_name", "|", "scene", "=", "scene_class_name", ".", "constantize", "[", "scene", "]", "+", "all_scenes_for", "(", "scene", ".", "scenes", ")", "end", ".", "flatten", ".", "compact", "end"], "docstring": "Returns all subclassed scenes of the scene or scenes provided. This method is\n meant to be called recursively to generate the entire list of all the scenes.\n\n @param [Scene,Array] scenes a scene or scene subclass or an array of\n scene subclasses.", "docstring_tokens": ["Returns", "all", "subclassed", "scenes", "of", "the", "scene", "or", "scenes", "provided", ".", "This", "method", "is", "meant", "to", "be", "called", "recursively", "to", "generate", "the", "entire", "list", "of", "all", "the", "scenes", "."], "sha": "5fd7d1fd433f3aece8451af8098b23bb14007227", "url": "https://github.com/burtlo/metro/blob/5fd7d1fd433f3aece8451af8098b23bb14007227/lib/metro/scenes.rb#L144-L149", "partition": "test"} {"repo": "burtlo/metro", "path": "lib/metro/scene.rb", "func_name": "Metro.Scene.actor", "original_string": "def actor(actor_or_actor_name)\n if actor_or_actor_name.is_a? String or actor_or_actor_name.is_a? Symbol\n send(actor_or_actor_name)\n else\n actor_or_actor_name\n end\n end", "language": "ruby", "code": "def actor(actor_or_actor_name)\n if actor_or_actor_name.is_a? String or actor_or_actor_name.is_a? Symbol\n send(actor_or_actor_name)\n else\n actor_or_actor_name\n end\n end", "code_tokens": ["def", "actor", "(", "actor_or_actor_name", ")", "if", "actor_or_actor_name", ".", "is_a?", "String", "or", "actor_or_actor_name", ".", "is_a?", "Symbol", "send", "(", "actor_or_actor_name", ")", "else", "actor_or_actor_name", "end", "end"], "docstring": "When an actor is defined, through the class method `draw` a getter and setter method\n is defined. However, it is a better interface internally not to rely heavily on send\n and have this small amount of obfuscation in the event that this needs to change.\n\n @return the actor with the given name.", "docstring_tokens": ["When", "an", "actor", "is", "defined", "through", "the", "class", "method", "draw", "a", "getter", "and", "setter", "method", "is", "defined", ".", "However", "it", "is", "a", "better", "interface", "internally", "not", "to", "rely", "heavily", "on", "send", "and", "have", "this", "small", "amount", "of", "obfuscation", "in", "the", "event", "that", "this", "needs", "to", "change", "."], "sha": "5fd7d1fd433f3aece8451af8098b23bb14007227", "url": "https://github.com/burtlo/metro/blob/5fd7d1fd433f3aece8451af8098b23bb14007227/lib/metro/scene.rb#L91-L97", "partition": "test"} {"repo": "burtlo/metro", "path": "lib/metro/scene.rb", "func_name": "Metro.Scene.notification", "original_string": "def notification(event,sender=nil)\n sender = sender || UnknownSender\n state.fire_events_for_notification(event,sender)\n end", "language": "ruby", "code": "def notification(event,sender=nil)\n sender = sender || UnknownSender\n state.fire_events_for_notification(event,sender)\n end", "code_tokens": ["def", "notification", "(", "event", ",", "sender", "=", "nil", ")", "sender", "=", "sender", "||", "UnknownSender", "state", ".", "fire_events_for_notification", "(", "event", ",", "sender", ")", "end"], "docstring": "Post a custom notification event. This will trigger an event for all the\n objects that are registered for notification with the current state.", "docstring_tokens": ["Post", "a", "custom", "notification", "event", ".", "This", "will", "trigger", "an", "event", "for", "all", "the", "objects", "that", "are", "registered", "for", "notification", "with", "the", "current", "state", "."], "sha": "5fd7d1fd433f3aece8451af8098b23bb14007227", "url": "https://github.com/burtlo/metro/blob/5fd7d1fd433f3aece8451af8098b23bb14007227/lib/metro/scene.rb#L103-L106", "partition": "test"} {"repo": "burtlo/metro", "path": "lib/metro/scene.rb", "func_name": "Metro.Scene.after", "original_string": "def after(ticks,&block)\n tick = OnUpdateOperation.new interval: ticks, context: self\n tick.on_complete(&block)\n enqueue tick\n end", "language": "ruby", "code": "def after(ticks,&block)\n tick = OnUpdateOperation.new interval: ticks, context: self\n tick.on_complete(&block)\n enqueue tick\n end", "code_tokens": ["def", "after", "(", "ticks", ",", "&", "block", ")", "tick", "=", "OnUpdateOperation", ".", "new", "interval", ":", "ticks", ",", "context", ":", "self", "tick", ".", "on_complete", "(", "block", ")", "enqueue", "tick", "end"], "docstring": "Perform an operation after the specified interval.\n\n class ExampleScene\n\n draws :player\n\n def update\n if player.is_dead?\n after 2.seconds do\n transition_to :game_over\n end\n end\n end\n\n end", "docstring_tokens": ["Perform", "an", "operation", "after", "the", "specified", "interval", "."], "sha": "5fd7d1fd433f3aece8451af8098b23bb14007227", "url": "https://github.com/burtlo/metro/blob/5fd7d1fd433f3aece8451af8098b23bb14007227/lib/metro/scene.rb#L153-L157", "partition": "test"} {"repo": "burtlo/metro", "path": "lib/metro/scene.rb", "func_name": "Metro.Scene.add_actors_to_scene", "original_string": "def add_actors_to_scene\n self.class.actors.each do |scene_actor|\n actor_instance = scene_actor.create\n actor_instance.scene = self\n send \"#{scene_actor.name}=\", actor_instance\n end\n end", "language": "ruby", "code": "def add_actors_to_scene\n self.class.actors.each do |scene_actor|\n actor_instance = scene_actor.create\n actor_instance.scene = self\n send \"#{scene_actor.name}=\", actor_instance\n end\n end", "code_tokens": ["def", "add_actors_to_scene", "self", ".", "class", ".", "actors", ".", "each", "do", "|", "scene_actor", "|", "actor_instance", "=", "scene_actor", ".", "create", "actor_instance", ".", "scene", "=", "self", "send", "\"#{scene_actor.name}=\"", ",", "actor_instance", "end", "end"], "docstring": "Setups up the Actors for the Scene based on the ModelFactories that have been\n defined.\n\n @note this method should not be overriden, otherwise the actors will perish!\n @see #after_initialize", "docstring_tokens": ["Setups", "up", "the", "Actors", "for", "the", "Scene", "based", "on", "the", "ModelFactories", "that", "have", "been", "defined", "."], "sha": "5fd7d1fd433f3aece8451af8098b23bb14007227", "url": "https://github.com/burtlo/metro/blob/5fd7d1fd433f3aece8451af8098b23bb14007227/lib/metro/scene.rb#L171-L177", "partition": "test"} {"repo": "burtlo/metro", "path": "lib/metro/scene.rb", "func_name": "Metro.Scene.register_animations!", "original_string": "def register_animations!\n self.class.animations.each do |animation|\n animate animation.actor, animation.options, &animation.on_complete_block\n end\n end", "language": "ruby", "code": "def register_animations!\n self.class.animations.each do |animation|\n animate animation.actor, animation.options, &animation.on_complete_block\n end\n end", "code_tokens": ["def", "register_animations!", "self", ".", "class", ".", "animations", ".", "each", "do", "|", "animation", "|", "animate", "animation", ".", "actor", ",", "animation", ".", "options", ",", "animation", ".", "on_complete_block", "end", "end"], "docstring": "Register all the animations that were defined for this scene.", "docstring_tokens": ["Register", "all", "the", "animations", "that", "were", "defined", "for", "this", "scene", "."], "sha": "5fd7d1fd433f3aece8451af8098b23bb14007227", "url": "https://github.com/burtlo/metro/blob/5fd7d1fd433f3aece8451af8098b23bb14007227/lib/metro/scene.rb#L225-L229", "partition": "test"} {"repo": "burtlo/metro", "path": "lib/metro/scene.rb", "func_name": "Metro.Scene.register_actor", "original_string": "def register_actor(actor_factory)\n registering_actor = actor(actor_factory.name)\n registering_actor.window = window\n registering_actor.show\n\n drawers.push(registering_actor)\n updaters.push(registering_actor)\n\n register_events_for_target(registering_actor,registering_actor.class.events)\n end", "language": "ruby", "code": "def register_actor(actor_factory)\n registering_actor = actor(actor_factory.name)\n registering_actor.window = window\n registering_actor.show\n\n drawers.push(registering_actor)\n updaters.push(registering_actor)\n\n register_events_for_target(registering_actor,registering_actor.class.events)\n end", "code_tokens": ["def", "register_actor", "(", "actor_factory", ")", "registering_actor", "=", "actor", "(", "actor_factory", ".", "name", ")", "registering_actor", ".", "window", "=", "window", "registering_actor", ".", "show", "drawers", ".", "push", "(", "registering_actor", ")", "updaters", ".", "push", "(", "registering_actor", ")", "register_events_for_target", "(", "registering_actor", ",", "registering_actor", ".", "class", ".", "events", ")", "end"], "docstring": "Registering an actor involves setting up the actor within\n the window, adding them to the list of things that need to be\n drawn and then registering any eventst that they might have.", "docstring_tokens": ["Registering", "an", "actor", "involves", "setting", "up", "the", "actor", "within", "the", "window", "adding", "them", "to", "the", "list", "of", "things", "that", "need", "to", "be", "drawn", "and", "then", "registering", "any", "eventst", "that", "they", "might", "have", "."], "sha": "5fd7d1fd433f3aece8451af8098b23bb14007227", "url": "https://github.com/burtlo/metro/blob/5fd7d1fd433f3aece8451af8098b23bb14007227/lib/metro/scene.rb#L242-L251", "partition": "test"} {"repo": "burtlo/metro", "path": "lib/metro/scene.rb", "func_name": "Metro.Scene.base_update", "original_string": "def base_update\n updaters.each { |updater| updater.update }\n update\n updaters.reject! { |updater| updater.update_completed? }\n end", "language": "ruby", "code": "def base_update\n updaters.each { |updater| updater.update }\n update\n updaters.reject! { |updater| updater.update_completed? }\n end", "code_tokens": ["def", "base_update", "updaters", ".", "each", "{", "|", "updater", "|", "updater", ".", "update", "}", "update", "updaters", ".", "reject!", "{", "|", "updater", "|", "updater", ".", "update_completed?", "}", "end"], "docstring": "The `base_update` method is called by the Game Window. This is to allow for any\n special update needs to be handled before calling the traditional `update` method\n defined in the subclassed Scene.", "docstring_tokens": ["The", "base_update", "method", "is", "called", "by", "the", "Game", "Window", ".", "This", "is", "to", "allow", "for", "any", "special", "update", "needs", "to", "be", "handled", "before", "calling", "the", "traditional", "update", "method", "defined", "in", "the", "subclassed", "Scene", "."], "sha": "5fd7d1fd433f3aece8451af8098b23bb14007227", "url": "https://github.com/burtlo/metro/blob/5fd7d1fd433f3aece8451af8098b23bb14007227/lib/metro/scene.rb#L375-L379", "partition": "test"} {"repo": "burtlo/metro", "path": "lib/metro/scene.rb", "func_name": "Metro.Scene.base_draw", "original_string": "def base_draw\n drawers.each { |drawer| drawer.draw }\n draw\n drawers.reject! { |drawer| drawer.draw_completed? }\n end", "language": "ruby", "code": "def base_draw\n drawers.each { |drawer| drawer.draw }\n draw\n drawers.reject! { |drawer| drawer.draw_completed? }\n end", "code_tokens": ["def", "base_draw", "drawers", ".", "each", "{", "|", "drawer", "|", "drawer", ".", "draw", "}", "draw", "drawers", ".", "reject!", "{", "|", "drawer", "|", "drawer", ".", "draw_completed?", "}", "end"], "docstring": "The `base_draw` method is called by the Game Window. This is to allow for any\n special drawing needs to be handled before calling the traditional `draw` method\n defined in the subclassed Scene.", "docstring_tokens": ["The", "base_draw", "method", "is", "called", "by", "the", "Game", "Window", ".", "This", "is", "to", "allow", "for", "any", "special", "drawing", "needs", "to", "be", "handled", "before", "calling", "the", "traditional", "draw", "method", "defined", "in", "the", "subclassed", "Scene", "."], "sha": "5fd7d1fd433f3aece8451af8098b23bb14007227", "url": "https://github.com/burtlo/metro/blob/5fd7d1fd433f3aece8451af8098b23bb14007227/lib/metro/scene.rb#L394-L398", "partition": "test"} {"repo": "burtlo/metro", "path": "lib/metro/scene.rb", "func_name": "Metro.Scene.transition_to", "original_string": "def transition_to(scene_or_scene_name,options = {})\n new_scene = Scenes.generate(scene_or_scene_name,options)\n _prepare_transition(new_scene)\n window.scene = new_scene\n end", "language": "ruby", "code": "def transition_to(scene_or_scene_name,options = {})\n new_scene = Scenes.generate(scene_or_scene_name,options)\n _prepare_transition(new_scene)\n window.scene = new_scene\n end", "code_tokens": ["def", "transition_to", "(", "scene_or_scene_name", ",", "options", "=", "{", "}", ")", "new_scene", "=", "Scenes", ".", "generate", "(", "scene_or_scene_name", ",", "options", ")", "_prepare_transition", "(", "new_scene", ")", "window", ".", "scene", "=", "new_scene", "end"], "docstring": "`transition_to` performs the work of transitioning this scene\n to another scene.\n\n @param [String,Symbol,Object] scene_or_scene_name the name of the Scene which can\n be either the class or a string/symbol representation of the shortened scene name.\n This could also be an instance of scene.", "docstring_tokens": ["transition_to", "performs", "the", "work", "of", "transitioning", "this", "scene", "to", "another", "scene", "."], "sha": "5fd7d1fd433f3aece8451af8098b23bb14007227", "url": "https://github.com/burtlo/metro/blob/5fd7d1fd433f3aece8451af8098b23bb14007227/lib/metro/scene.rb#L411-L415", "partition": "test"} {"repo": "burtlo/metro", "path": "lib/metro/scene.rb", "func_name": "Metro.Scene._prepare_transition", "original_string": "def _prepare_transition(new_scene)\n log.debug \"Preparing to transition from scene #{self} to #{new_scene}\"\n\n new_scene.class.actors.find_all {|actor_factory| actor_factory.load_from_previous_scene? }.each do |actor_factory|\n new_actor = new_scene.actor(actor_factory.name)\n current_actor = actor(actor_factory.name)\n new_actor._load current_actor._save\n end\n\n prepare_transition_to(new_scene)\n new_scene.prepare_transition_from(self)\n end", "language": "ruby", "code": "def _prepare_transition(new_scene)\n log.debug \"Preparing to transition from scene #{self} to #{new_scene}\"\n\n new_scene.class.actors.find_all {|actor_factory| actor_factory.load_from_previous_scene? }.each do |actor_factory|\n new_actor = new_scene.actor(actor_factory.name)\n current_actor = actor(actor_factory.name)\n new_actor._load current_actor._save\n end\n\n prepare_transition_to(new_scene)\n new_scene.prepare_transition_from(self)\n end", "code_tokens": ["def", "_prepare_transition", "(", "new_scene", ")", "log", ".", "debug", "\"Preparing to transition from scene #{self} to #{new_scene}\"", "new_scene", ".", "class", ".", "actors", ".", "find_all", "{", "|", "actor_factory", "|", "actor_factory", ".", "load_from_previous_scene?", "}", ".", "each", "do", "|", "actor_factory", "|", "new_actor", "=", "new_scene", ".", "actor", "(", "actor_factory", ".", "name", ")", "current_actor", "=", "actor", "(", "actor_factory", ".", "name", ")", "new_actor", ".", "_load", "current_actor", ".", "_save", "end", "prepare_transition_to", "(", "new_scene", ")", "new_scene", ".", "prepare_transition_from", "(", "self", ")", "end"], "docstring": "Before a scene is transitioned away from to a new scene, this private method is\n here to allow for any housekeeping or other work that needs to be done before\n calling the subclasses implementation of `prepare_transition`.\n\n @param [Scene] new_scene this is the instance of the scene that is about to replace\n the current scene.", "docstring_tokens": ["Before", "a", "scene", "is", "transitioned", "away", "from", "to", "a", "new", "scene", "this", "private", "method", "is", "here", "to", "allow", "for", "any", "housekeeping", "or", "other", "work", "that", "needs", "to", "be", "done", "before", "calling", "the", "subclasses", "implementation", "of", "prepare_transition", "."], "sha": "5fd7d1fd433f3aece8451af8098b23bb14007227", "url": "https://github.com/burtlo/metro/blob/5fd7d1fd433f3aece8451af8098b23bb14007227/lib/metro/scene.rb#L425-L436", "partition": "test"} {"repo": "burtlo/metro", "path": "lib/metro/scene.rb", "func_name": "Metro.Scene.to_hash", "original_string": "def to_hash\n drawn = drawers.find_all{|draw| draw.saveable_to_view }.inject({}) do |hash,drawer|\n drawer_hash = drawer.to_hash\n hash.merge drawer_hash\n end\n\n drawn\n end", "language": "ruby", "code": "def to_hash\n drawn = drawers.find_all{|draw| draw.saveable_to_view }.inject({}) do |hash,drawer|\n drawer_hash = drawer.to_hash\n hash.merge drawer_hash\n end\n\n drawn\n end", "code_tokens": ["def", "to_hash", "drawn", "=", "drawers", ".", "find_all", "{", "|", "draw", "|", "draw", ".", "saveable_to_view", "}", ".", "inject", "(", "{", "}", ")", "do", "|", "hash", ",", "drawer", "|", "drawer_hash", "=", "drawer", ".", "to_hash", "hash", ".", "merge", "drawer_hash", "end", "drawn", "end"], "docstring": "A Scene represented as a hash currently only contains the drawers\n\n @return a hash of all the drawers", "docstring_tokens": ["A", "Scene", "represented", "as", "a", "hash", "currently", "only", "contains", "the", "drawers"], "sha": "5fd7d1fd433f3aece8451af8098b23bb14007227", "url": "https://github.com/burtlo/metro/blob/5fd7d1fd433f3aece8451af8098b23bb14007227/lib/metro/scene.rb#L468-L475", "partition": "test"} {"repo": "burtlo/metro", "path": "lib/metro/models/model.rb", "func_name": "Metro.Model.create", "original_string": "def create(model_name,options={})\n # @TODO: this is another path that parallels the ModelFactory\n model_class = Metro::Models.find(model_name)\n mc = model_class.new options\n mc.scene = scene\n mc.window = window\n mc\n end", "language": "ruby", "code": "def create(model_name,options={})\n # @TODO: this is another path that parallels the ModelFactory\n model_class = Metro::Models.find(model_name)\n mc = model_class.new options\n mc.scene = scene\n mc.window = window\n mc\n end", "code_tokens": ["def", "create", "(", "model_name", ",", "options", "=", "{", "}", ")", "# @TODO: this is another path that parallels the ModelFactory", "model_class", "=", "Metro", "::", "Models", ".", "find", "(", "model_name", ")", "mc", "=", "model_class", ".", "new", "options", "mc", ".", "scene", "=", "scene", "mc", ".", "window", "=", "window", "mc", "end"], "docstring": "A helper method that allows the current model to generate another model. This\n is useful as it allows for the current model to pass window and scene state\n to the created model.\n\n @param [String] model_name the name of the model to be created.\n @return [Metro::Model] the metro model instance", "docstring_tokens": ["A", "helper", "method", "that", "allows", "the", "current", "model", "to", "generate", "another", "model", ".", "This", "is", "useful", "as", "it", "allows", "for", "the", "current", "model", "to", "pass", "window", "and", "scene", "state", "to", "the", "created", "model", "."], "sha": "5fd7d1fd433f3aece8451af8098b23bb14007227", "url": "https://github.com/burtlo/metro/blob/5fd7d1fd433f3aece8451af8098b23bb14007227/lib/metro/models/model.rb#L146-L153", "partition": "test"} {"repo": "burtlo/metro", "path": "lib/metro/models/model.rb", "func_name": "Metro.Model._load", "original_string": "def _load(options = {})\n # Clean up and symbolize all the keys then merge that with the existing properties\n options.keys.each do |key|\n property_name = key.to_s.underscore.to_sym\n if respond_to? \"#{property_name}=\"\n send(\"#{property_name}=\",options.delete(key))\n else\n options[property_name] = options.delete(key)\n end\n end\n\n properties.merge! options\n end", "language": "ruby", "code": "def _load(options = {})\n # Clean up and symbolize all the keys then merge that with the existing properties\n options.keys.each do |key|\n property_name = key.to_s.underscore.to_sym\n if respond_to? \"#{property_name}=\"\n send(\"#{property_name}=\",options.delete(key))\n else\n options[property_name] = options.delete(key)\n end\n end\n\n properties.merge! options\n end", "code_tokens": ["def", "_load", "(", "options", "=", "{", "}", ")", "# Clean up and symbolize all the keys then merge that with the existing properties", "options", ".", "keys", ".", "each", "do", "|", "key", "|", "property_name", "=", "key", ".", "to_s", ".", "underscore", ".", "to_sym", "if", "respond_to?", "\"#{property_name}=\"", "send", "(", "\"#{property_name}=\"", ",", "options", ".", "delete", "(", "key", ")", ")", "else", "options", "[", "property_name", "]", "=", "options", ".", "delete", "(", "key", ")", "end", "end", "properties", ".", "merge!", "options", "end"], "docstring": "Create an instance of a model.\n\n @note Overridding initialize method should be avoided, using the {#aftter_initialize)\n method or done with care to ensure that functionality is preserved.\n\n\n Loads a hash of content into the model. This process will convert the hash\n of content into setter and getter methods with appropriate ruby style names.\n\n This is used internally when the model is created for the Scene. It is loaded\n with the contents of the view.", "docstring_tokens": ["Create", "an", "instance", "of", "a", "model", "."], "sha": "5fd7d1fd433f3aece8451af8098b23bb14007227", "url": "https://github.com/burtlo/metro/blob/5fd7d1fd433f3aece8451af8098b23bb14007227/lib/metro/models/model.rb#L181-L193", "partition": "test"} {"repo": "paulosman/withings-sdk", "path": "lib/withings-sdk/client.rb", "func_name": "WithingsSDK.Client.activities", "original_string": "def activities(user_id, options = {})\n perform_request(:get, '/v2/measure', WithingsSDK::Activity, 'activities', {\n action: 'getactivity',\n userid: user_id\n }.merge(options))\n end", "language": "ruby", "code": "def activities(user_id, options = {})\n perform_request(:get, '/v2/measure', WithingsSDK::Activity, 'activities', {\n action: 'getactivity',\n userid: user_id\n }.merge(options))\n end", "code_tokens": ["def", "activities", "(", "user_id", ",", "options", "=", "{", "}", ")", "perform_request", "(", ":get", ",", "'/v2/measure'", ",", "WithingsSDK", "::", "Activity", ",", "'activities'", ",", "{", "action", ":", "'getactivity'", ",", "userid", ":", "user_id", "}", ".", "merge", "(", "options", ")", ")", "end"], "docstring": "Get a list of activity measures for the specified user\n\n @param user_id [Integer]\n @param options [Hash]\n\n @return [Array]", "docstring_tokens": ["Get", "a", "list", "of", "activity", "measures", "for", "the", "specified", "user"], "sha": "57d91a5bb3e6d99da3286e72be33489b26575ae7", "url": "https://github.com/paulosman/withings-sdk/blob/57d91a5bb3e6d99da3286e72be33489b26575ae7/lib/withings-sdk/client.rb#L75-L80", "partition": "test"} {"repo": "paulosman/withings-sdk", "path": "lib/withings-sdk/client.rb", "func_name": "WithingsSDK.Client.body_measurements", "original_string": "def body_measurements(user_id, options = {})\n perform_request(:get, '/measure', WithingsSDK::MeasurementGroup, 'measuregrps', {\n action: 'getmeas',\n userid: user_id\n }.merge(options))\n end", "language": "ruby", "code": "def body_measurements(user_id, options = {})\n perform_request(:get, '/measure', WithingsSDK::MeasurementGroup, 'measuregrps', {\n action: 'getmeas',\n userid: user_id\n }.merge(options))\n end", "code_tokens": ["def", "body_measurements", "(", "user_id", ",", "options", "=", "{", "}", ")", "perform_request", "(", ":get", ",", "'/measure'", ",", "WithingsSDK", "::", "MeasurementGroup", ",", "'measuregrps'", ",", "{", "action", ":", "'getmeas'", ",", "userid", ":", "user_id", "}", ".", "merge", "(", "options", ")", ")", "end"], "docstring": "Get a list of body measurements taken by Withings devices\n\n @param user_id [Integer]\n @param options [Hash]\n\n @return [Array]", "docstring_tokens": ["Get", "a", "list", "of", "body", "measurements", "taken", "by", "Withings", "devices"], "sha": "57d91a5bb3e6d99da3286e72be33489b26575ae7", "url": "https://github.com/paulosman/withings-sdk/blob/57d91a5bb3e6d99da3286e72be33489b26575ae7/lib/withings-sdk/client.rb#L88-L93", "partition": "test"} {"repo": "paulosman/withings-sdk", "path": "lib/withings-sdk/client.rb", "func_name": "WithingsSDK.Client.weight", "original_string": "def weight(user_id, options = {})\n groups = body_measurements(user_id, options)\n groups.map do |group|\n group.measures.select { |m| m.is_a? WithingsSDK::Measure::Weight }.map do |m|\n WithingsSDK::Measure::Weight.new(m.attrs.merge('weighed_at' => group.date))\n end\n end.flatten\n end", "language": "ruby", "code": "def weight(user_id, options = {})\n groups = body_measurements(user_id, options)\n groups.map do |group|\n group.measures.select { |m| m.is_a? WithingsSDK::Measure::Weight }.map do |m|\n WithingsSDK::Measure::Weight.new(m.attrs.merge('weighed_at' => group.date))\n end\n end.flatten\n end", "code_tokens": ["def", "weight", "(", "user_id", ",", "options", "=", "{", "}", ")", "groups", "=", "body_measurements", "(", "user_id", ",", "options", ")", "groups", ".", "map", "do", "|", "group", "|", "group", ".", "measures", ".", "select", "{", "|", "m", "|", "m", ".", "is_a?", "WithingsSDK", "::", "Measure", "::", "Weight", "}", ".", "map", "do", "|", "m", "|", "WithingsSDK", "::", "Measure", "::", "Weight", ".", "new", "(", "m", ".", "attrs", ".", "merge", "(", "'weighed_at'", "=>", "group", ".", "date", ")", ")", "end", "end", ".", "flatten", "end"], "docstring": "Return a list of weight body measurements\n\n @param user_id [Integer]\n @param options [Hash]\n\n @return [Array]", "docstring_tokens": ["Return", "a", "list", "of", "weight", "body", "measurements"], "sha": "57d91a5bb3e6d99da3286e72be33489b26575ae7", "url": "https://github.com/paulosman/withings-sdk/blob/57d91a5bb3e6d99da3286e72be33489b26575ae7/lib/withings-sdk/client.rb#L101-L108", "partition": "test"} {"repo": "paulosman/withings-sdk", "path": "lib/withings-sdk/client.rb", "func_name": "WithingsSDK.Client.sleep_series", "original_string": "def sleep_series(user_id, options = {})\n perform_request(:get, '/v2/sleep', WithingsSDK::SleepSeries, 'series', {\n action: 'get',\n userid: user_id\n }.merge(options))\n end", "language": "ruby", "code": "def sleep_series(user_id, options = {})\n perform_request(:get, '/v2/sleep', WithingsSDK::SleepSeries, 'series', {\n action: 'get',\n userid: user_id\n }.merge(options))\n end", "code_tokens": ["def", "sleep_series", "(", "user_id", ",", "options", "=", "{", "}", ")", "perform_request", "(", ":get", ",", "'/v2/sleep'", ",", "WithingsSDK", "::", "SleepSeries", ",", "'series'", ",", "{", "action", ":", "'get'", ",", "userid", ":", "user_id", "}", ".", "merge", "(", "options", ")", ")", "end"], "docstring": "Get details about a user's sleep\n\n @param user_id [Integer]\n @param options [Hash]\n\n @return [Array]", "docstring_tokens": ["Get", "details", "about", "a", "user", "s", "sleep"], "sha": "57d91a5bb3e6d99da3286e72be33489b26575ae7", "url": "https://github.com/paulosman/withings-sdk/blob/57d91a5bb3e6d99da3286e72be33489b26575ae7/lib/withings-sdk/client.rb#L116-L121", "partition": "test"} {"repo": "paulosman/withings-sdk", "path": "lib/withings-sdk/client.rb", "func_name": "WithingsSDK.Client.perform_request", "original_string": "def perform_request(http_method, path, klass, key, options = {})\n if @consumer_key.nil? || @consumer_secret.nil?\n raise WithingsSDK::Error::ClientConfigurationError, \"Missing consumer_key or consumer_secret\"\n end\n options = WithingsSDK::Utils.normalize_date_params(options)\n request = WithingsSDK::HTTP::Request.new(@access_token, { 'User-Agent' => user_agent })\n response = request.send(http_method, path, options)\n if key.nil?\n klass.new(response)\n elsif response.has_key? key\n response[key].collect do |element|\n klass.new(element)\n end\n else\n [klass.new(response)]\n end\n end", "language": "ruby", "code": "def perform_request(http_method, path, klass, key, options = {})\n if @consumer_key.nil? || @consumer_secret.nil?\n raise WithingsSDK::Error::ClientConfigurationError, \"Missing consumer_key or consumer_secret\"\n end\n options = WithingsSDK::Utils.normalize_date_params(options)\n request = WithingsSDK::HTTP::Request.new(@access_token, { 'User-Agent' => user_agent })\n response = request.send(http_method, path, options)\n if key.nil?\n klass.new(response)\n elsif response.has_key? key\n response[key].collect do |element|\n klass.new(element)\n end\n else\n [klass.new(response)]\n end\n end", "code_tokens": ["def", "perform_request", "(", "http_method", ",", "path", ",", "klass", ",", "key", ",", "options", "=", "{", "}", ")", "if", "@consumer_key", ".", "nil?", "||", "@consumer_secret", ".", "nil?", "raise", "WithingsSDK", "::", "Error", "::", "ClientConfigurationError", ",", "\"Missing consumer_key or consumer_secret\"", "end", "options", "=", "WithingsSDK", "::", "Utils", ".", "normalize_date_params", "(", "options", ")", "request", "=", "WithingsSDK", "::", "HTTP", "::", "Request", ".", "new", "(", "@access_token", ",", "{", "'User-Agent'", "=>", "user_agent", "}", ")", "response", "=", "request", ".", "send", "(", "http_method", ",", "path", ",", "options", ")", "if", "key", ".", "nil?", "klass", ".", "new", "(", "response", ")", "elsif", "response", ".", "has_key?", "key", "response", "[", "key", "]", ".", "collect", "do", "|", "element", "|", "klass", ".", "new", "(", "element", ")", "end", "else", "[", "klass", ".", "new", "(", "response", ")", "]", "end", "end"], "docstring": "Helper function that handles all API requests\n\n @param http_method [Symbol]\n @param path [String]\n @param klass [Class]\n @param key [String]\n @param options [Hash]\n\n @return [Array]", "docstring_tokens": ["Helper", "function", "that", "handles", "all", "API", "requests"], "sha": "57d91a5bb3e6d99da3286e72be33489b26575ae7", "url": "https://github.com/paulosman/withings-sdk/blob/57d91a5bb3e6d99da3286e72be33489b26575ae7/lib/withings-sdk/client.rb#L201-L217", "partition": "test"} {"repo": "glebtv/carrierwave-magic", "path": "lib/carrierwave-magic.rb", "func_name": "CarrierWave.Magic.set_magic_content_type", "original_string": "def set_magic_content_type(override=false)\n if override || file.content_type.blank? || generic_content_type?(file.content_type)\n new_content_type = ::FileMagic.new(::FileMagic::MAGIC_MIME).file( file.path ).split(';').first\n\n if file.respond_to?(:content_type=)\n file.content_type = new_content_type\n else\n file.instance_variable_set(:@content_type, new_content_type)\n end\n end\n rescue ::Exception => e\n raise CarrierWave::ProcessingError, I18n.translate(:\"errors.messages.magic_mime_types_processing_error\", e: e, default: 'Failed to process file with FileMagic, Original Error: %{e}')\n end", "language": "ruby", "code": "def set_magic_content_type(override=false)\n if override || file.content_type.blank? || generic_content_type?(file.content_type)\n new_content_type = ::FileMagic.new(::FileMagic::MAGIC_MIME).file( file.path ).split(';').first\n\n if file.respond_to?(:content_type=)\n file.content_type = new_content_type\n else\n file.instance_variable_set(:@content_type, new_content_type)\n end\n end\n rescue ::Exception => e\n raise CarrierWave::ProcessingError, I18n.translate(:\"errors.messages.magic_mime_types_processing_error\", e: e, default: 'Failed to process file with FileMagic, Original Error: %{e}')\n end", "code_tokens": ["def", "set_magic_content_type", "(", "override", "=", "false", ")", "if", "override", "||", "file", ".", "content_type", ".", "blank?", "||", "generic_content_type?", "(", "file", ".", "content_type", ")", "new_content_type", "=", "::", "FileMagic", ".", "new", "(", "::", "FileMagic", "::", "MAGIC_MIME", ")", ".", "file", "(", "file", ".", "path", ")", ".", "split", "(", "';'", ")", ".", "first", "if", "file", ".", "respond_to?", "(", ":content_type=", ")", "file", ".", "content_type", "=", "new_content_type", "else", "file", ".", "instance_variable_set", "(", ":@content_type", ",", "new_content_type", ")", "end", "end", "rescue", "::", "Exception", "=>", "e", "raise", "CarrierWave", "::", "ProcessingError", ",", "I18n", ".", "translate", "(", ":\"", "\"", ",", "e", ":", "e", ",", "default", ":", "'Failed to process file with FileMagic, Original Error: %{e}'", ")", "end"], "docstring": "Changes the file content_type using the ruby-filemagic gem", "docstring_tokens": ["Changes", "the", "file", "content_type", "using", "the", "ruby", "-", "filemagic", "gem"], "sha": "ea38a004e0bb20a445c4a1b63f805f40e4d5e410", "url": "https://github.com/glebtv/carrierwave-magic/blob/ea38a004e0bb20a445c4a1b63f805f40e4d5e410/lib/carrierwave-magic.rb#L31-L43", "partition": "test"} {"repo": "jemc/ruby-rabbitmq", "path": "lib/rabbitmq/client.rb", "func_name": "RabbitMQ.Client.send_request", "original_string": "def send_request(channel_id, method, properties={})\n Util.error_check :\"sending a request\",\n @conn.send_method(Integer(channel_id), method.to_sym, properties)\n \n nil\n end", "language": "ruby", "code": "def send_request(channel_id, method, properties={})\n Util.error_check :\"sending a request\",\n @conn.send_method(Integer(channel_id), method.to_sym, properties)\n \n nil\n end", "code_tokens": ["def", "send_request", "(", "channel_id", ",", "method", ",", "properties", "=", "{", "}", ")", "Util", ".", "error_check", ":\"", "\"", ",", "@conn", ".", "send_method", "(", "Integer", "(", "channel_id", ")", ",", "method", ".", "to_sym", ",", "properties", ")", "nil", "end"], "docstring": "Send a request on the given channel with the given type and properties.\n\n @param channel_id [Integer] The channel number to send on.\n @param method [Symbol] The type of protocol method to send.\n @param properties [Hash] The properties to apply to the method.\n @raise [RabbitMQ::FFI::Error] if a library exception occurs.", "docstring_tokens": ["Send", "a", "request", "on", "the", "given", "channel", "with", "the", "given", "type", "and", "properties", "."], "sha": "967bd5597cf570b51187c2ac5a9d51764a986152", "url": "https://github.com/jemc/ruby-rabbitmq/blob/967bd5597cf570b51187c2ac5a9d51764a986152/lib/rabbitmq/client.rb#L105-L110", "partition": "test"} {"repo": "jemc/ruby-rabbitmq", "path": "lib/rabbitmq/client.rb", "func_name": "RabbitMQ.Client.fetch_response", "original_string": "def fetch_response(channel_id, method, timeout: protocol_timeout)\n methods = Array(method).map(&:to_sym)\n timeout = Float(timeout) if timeout\n fetch_response_internal(Integer(channel_id), methods, timeout)\n end", "language": "ruby", "code": "def fetch_response(channel_id, method, timeout: protocol_timeout)\n methods = Array(method).map(&:to_sym)\n timeout = Float(timeout) if timeout\n fetch_response_internal(Integer(channel_id), methods, timeout)\n end", "code_tokens": ["def", "fetch_response", "(", "channel_id", ",", "method", ",", "timeout", ":", "protocol_timeout", ")", "methods", "=", "Array", "(", "method", ")", ".", "map", "(", ":to_sym", ")", "timeout", "=", "Float", "(", "timeout", ")", "if", "timeout", "fetch_response_internal", "(", "Integer", "(", "channel_id", ")", ",", "methods", ",", "timeout", ")", "end"], "docstring": "Wait for a specific response on the given channel of the given type\n and return the event data for the response when it is received.\n Any other events received will be processed or stored internally.\n\n @param channel_id [Integer] The channel number to watch for.\n @param method [Symbol,Array] The protocol method(s) to watch for.\n @param timeout [Float] The maximum time to wait for a response in seconds;\n uses the value of {#protocol_timeout} by default.\n @raise [RabbitMQ::ServerError] if any error event is received.\n @raise [RabbitMQ::FFI::Error::Timeout] if no event is received.\n @raise [RabbitMQ::FFI::Error] if a library exception occurs.\n @return [Hash] the response data received.", "docstring_tokens": ["Wait", "for", "a", "specific", "response", "on", "the", "given", "channel", "of", "the", "given", "type", "and", "return", "the", "event", "data", "for", "the", "response", "when", "it", "is", "received", ".", "Any", "other", "events", "received", "will", "be", "processed", "or", "stored", "internally", "."], "sha": "967bd5597cf570b51187c2ac5a9d51764a986152", "url": "https://github.com/jemc/ruby-rabbitmq/blob/967bd5597cf570b51187c2ac5a9d51764a986152/lib/rabbitmq/client.rb#L125-L129", "partition": "test"} {"repo": "jemc/ruby-rabbitmq", "path": "lib/rabbitmq/client.rb", "func_name": "RabbitMQ.Client.on_event", "original_string": "def on_event(channel_id, method, callable=nil, &block)\n handler = block || callable\n raise ArgumentError, \"expected block or callable as the event handler\" \\\n unless handler.respond_to?(:call)\n \n @event_handlers[Integer(channel_id)][method.to_sym] = handler\n handler\n end", "language": "ruby", "code": "def on_event(channel_id, method, callable=nil, &block)\n handler = block || callable\n raise ArgumentError, \"expected block or callable as the event handler\" \\\n unless handler.respond_to?(:call)\n \n @event_handlers[Integer(channel_id)][method.to_sym] = handler\n handler\n end", "code_tokens": ["def", "on_event", "(", "channel_id", ",", "method", ",", "callable", "=", "nil", ",", "&", "block", ")", "handler", "=", "block", "||", "callable", "raise", "ArgumentError", ",", "\"expected block or callable as the event handler\"", "unless", "handler", ".", "respond_to?", "(", ":call", ")", "@event_handlers", "[", "Integer", "(", "channel_id", ")", "]", "[", "method", ".", "to_sym", "]", "=", "handler", "handler", "end"], "docstring": "Register a handler for events on the given channel of the given type.\n Only one handler for each event type may be registered at a time.\n If no callable or block is given, the handler will be cleared.\n\n @param channel_id [Integer] The channel number to watch for.\n @param method [Symbol] The type of protocol method to watch for.\n @param callable [#call,nil] The callable handler if no block is given.\n @param block [Proc,nil] The handler block to register.\n @return [Proc,#call,nil] The given block or callable.\n @yieldparam event [Hash] The event passed to the handler.", "docstring_tokens": ["Register", "a", "handler", "for", "events", "on", "the", "given", "channel", "of", "the", "given", "type", ".", "Only", "one", "handler", "for", "each", "event", "type", "may", "be", "registered", "at", "a", "time", ".", "If", "no", "callable", "or", "block", "is", "given", "the", "handler", "will", "be", "cleared", "."], "sha": "967bd5597cf570b51187c2ac5a9d51764a986152", "url": "https://github.com/jemc/ruby-rabbitmq/blob/967bd5597cf570b51187c2ac5a9d51764a986152/lib/rabbitmq/client.rb#L142-L149", "partition": "test"} {"repo": "sangster/gtfs_reader", "path": "lib/gtfs_reader/source_updater.rb", "func_name": "GtfsReader.SourceUpdater.download_source", "original_string": "def download_source\n Log.debug { \" Reading #{@source.url.green}\" }\n zip = Tempfile.new('gtfs')\n zip.binmode\n zip << open(@source.url).read\n zip.rewind\n\n extract_to_tempfiles(zip)\n\n Log.debug { \"Finished reading #{@source.url.green}\" }\n rescue StandardException => e\n Log.error(e.message)\n raise e\n ensure\n zip.try(:close)\n end", "language": "ruby", "code": "def download_source\n Log.debug { \" Reading #{@source.url.green}\" }\n zip = Tempfile.new('gtfs')\n zip.binmode\n zip << open(@source.url).read\n zip.rewind\n\n extract_to_tempfiles(zip)\n\n Log.debug { \"Finished reading #{@source.url.green}\" }\n rescue StandardException => e\n Log.error(e.message)\n raise e\n ensure\n zip.try(:close)\n end", "code_tokens": ["def", "download_source", "Log", ".", "debug", "{", "\" Reading #{@source.url.green}\"", "}", "zip", "=", "Tempfile", ".", "new", "(", "'gtfs'", ")", "zip", ".", "binmode", "zip", "<<", "open", "(", "@source", ".", "url", ")", ".", "read", "zip", ".", "rewind", "extract_to_tempfiles", "(", "zip", ")", "Log", ".", "debug", "{", "\"Finished reading #{@source.url.green}\"", "}", "rescue", "StandardException", "=>", "e", "Log", ".", "error", "(", "e", ".", "message", ")", "raise", "e", "ensure", "zip", ".", "try", "(", ":close", ")", "end"], "docstring": "Download the data from the remote server", "docstring_tokens": ["Download", "the", "data", "from", "the", "remote", "server"], "sha": "206864d09e03924930bfa766442eb2679f461442", "url": "https://github.com/sangster/gtfs_reader/blob/206864d09e03924930bfa766442eb2679f461442/lib/gtfs_reader/source_updater.rb#L28-L43", "partition": "test"} {"repo": "sangster/gtfs_reader", "path": "lib/gtfs_reader/source_updater.rb", "func_name": "GtfsReader.SourceUpdater.check_files", "original_string": "def check_files\n @found_files = []\n check_required_files\n check_optional_files\n # Add feed files of zip to the list of files to be processed\n @source.feed_definition.files.each do |req|\n @found_files << req if filenames.include?(req.filename)\n end\n end", "language": "ruby", "code": "def check_files\n @found_files = []\n check_required_files\n check_optional_files\n # Add feed files of zip to the list of files to be processed\n @source.feed_definition.files.each do |req|\n @found_files << req if filenames.include?(req.filename)\n end\n end", "code_tokens": ["def", "check_files", "@found_files", "=", "[", "]", "check_required_files", "check_optional_files", "# Add feed files of zip to the list of files to be processed", "@source", ".", "feed_definition", ".", "files", ".", "each", "do", "|", "req", "|", "@found_files", "<<", "req", "if", "filenames", ".", "include?", "(", "req", ".", "filename", ")", "end", "end"], "docstring": "Parse the filenames in the feed and check which required and optional\n files are present.\n @raise [RequiredFilenamesMissing] if the feed is missing a file which is\n marked as \"required\" in the [FeedDefinition]", "docstring_tokens": ["Parse", "the", "filenames", "in", "the", "feed", "and", "check", "which", "required", "and", "optional", "files", "are", "present", "."], "sha": "206864d09e03924930bfa766442eb2679f461442", "url": "https://github.com/sangster/gtfs_reader/blob/206864d09e03924930bfa766442eb2679f461442/lib/gtfs_reader/source_updater.rb#L53-L61", "partition": "test"} {"repo": "sangster/gtfs_reader", "path": "lib/gtfs_reader/source_updater.rb", "func_name": "GtfsReader.SourceUpdater.check_columns", "original_string": "def check_columns\n @found_files.each do |file|\n @temp_files[file.filename].open do |data|\n FileReader.new(data, file, validate: true)\n end\n end\n end", "language": "ruby", "code": "def check_columns\n @found_files.each do |file|\n @temp_files[file.filename].open do |data|\n FileReader.new(data, file, validate: true)\n end\n end\n end", "code_tokens": ["def", "check_columns", "@found_files", ".", "each", "do", "|", "file", "|", "@temp_files", "[", "file", ".", "filename", "]", ".", "open", "do", "|", "data", "|", "FileReader", ".", "new", "(", "data", ",", "file", ",", "validate", ":", "true", ")", "end", "end", "end"], "docstring": "Check that every file has its required columns", "docstring_tokens": ["Check", "that", "every", "file", "has", "its", "required", "columns"], "sha": "206864d09e03924930bfa766442eb2679f461442", "url": "https://github.com/sangster/gtfs_reader/blob/206864d09e03924930bfa766442eb2679f461442/lib/gtfs_reader/source_updater.rb#L64-L70", "partition": "test"} {"repo": "sangster/gtfs_reader", "path": "lib/gtfs_reader/source_updater.rb", "func_name": "GtfsReader.SourceUpdater.fetch_http_fallback_identifier", "original_string": "def fetch_http_fallback_identifier(head_request)\n if head_request.key?('last-modified')\n head_request['last-modified']\n elsif head_request.key?('content-length')\n head_request['content-length']\n else\n Time.now.to_s\n end\n end", "language": "ruby", "code": "def fetch_http_fallback_identifier(head_request)\n if head_request.key?('last-modified')\n head_request['last-modified']\n elsif head_request.key?('content-length')\n head_request['content-length']\n else\n Time.now.to_s\n end\n end", "code_tokens": ["def", "fetch_http_fallback_identifier", "(", "head_request", ")", "if", "head_request", ".", "key?", "(", "'last-modified'", ")", "head_request", "[", "'last-modified'", "]", "elsif", "head_request", ".", "key?", "(", "'content-length'", ")", "head_request", "[", "'content-length'", "]", "else", "Time", ".", "now", ".", "to_s", "end", "end"], "docstring": "Find a \"next best\" ID when the HEAD request does not return an \"ETag\"\n header.", "docstring_tokens": ["Find", "a", "next", "best", "ID", "when", "the", "HEAD", "request", "does", "not", "return", "an", "ETag", "header", "."], "sha": "206864d09e03924930bfa766442eb2679f461442", "url": "https://github.com/sangster/gtfs_reader/blob/206864d09e03924930bfa766442eb2679f461442/lib/gtfs_reader/source_updater.rb#L155-L163", "partition": "test"} {"repo": "sangster/gtfs_reader", "path": "lib/gtfs_reader/configuration.rb", "func_name": "GtfsReader.Configuration.parameter", "original_string": "def parameter(*names)\n names.each do |name|\n define_singleton_method(name) do |*values|\n if (value = values.first)\n instance_variable_set(\"@#{name}\", value)\n else\n instance_variable_get(\"@#{name}\")\n end\n end\n end\n end", "language": "ruby", "code": "def parameter(*names)\n names.each do |name|\n define_singleton_method(name) do |*values|\n if (value = values.first)\n instance_variable_set(\"@#{name}\", value)\n else\n instance_variable_get(\"@#{name}\")\n end\n end\n end\n end", "code_tokens": ["def", "parameter", "(", "*", "names", ")", "names", ".", "each", "do", "|", "name", "|", "define_singleton_method", "(", "name", ")", "do", "|", "*", "values", "|", "if", "(", "value", "=", "values", ".", "first", ")", "instance_variable_set", "(", "\"@#{name}\"", ",", "value", ")", "else", "instance_variable_get", "(", "\"@#{name}\"", ")", "end", "end", "end", "end"], "docstring": "Creates simple configuration parameters which may be set by the user\n @param names [Array] the names of the parameters to create", "docstring_tokens": ["Creates", "simple", "configuration", "parameters", "which", "may", "be", "set", "by", "the", "user"], "sha": "206864d09e03924930bfa766442eb2679f461442", "url": "https://github.com/sangster/gtfs_reader/blob/206864d09e03924930bfa766442eb2679f461442/lib/gtfs_reader/configuration.rb#L5-L15", "partition": "test"} {"repo": "sangster/gtfs_reader", "path": "lib/gtfs_reader/file_reader.rb", "func_name": "GtfsReader.FileReader.find_columns", "original_string": "def find_columns(validate)\n @found_columns = []\n prefix = \"#{filename.yellow}:\"\n\n required = @definition.required_columns\n unless required.empty?\n Log.info { \"#{prefix} #{'required columns'.magenta}\" } if validate\n\n missing = check_columns(validate, prefix, required, :green, :red)\n raise RequiredColumnsMissing, missing if validate && missing.present?\n end\n\n optional = @definition.optional_columns\n unless optional.empty?\n Log.info { \"#{prefix} #{'optional columns'.cyan}\" } if validate\n check_columns(validate, prefix, optional, :cyan, :light_yellow)\n end\n\n cols = @definition.columns.collect(&:name)\n headers = @csv_headers.select { |h| cols.include?(h) }\n\n @col_names ||= @found_columns.map(&:name)\n ::Hash[*headers.inject([]) { |list, c| list << c << @definition[c] }]\n end", "language": "ruby", "code": "def find_columns(validate)\n @found_columns = []\n prefix = \"#{filename.yellow}:\"\n\n required = @definition.required_columns\n unless required.empty?\n Log.info { \"#{prefix} #{'required columns'.magenta}\" } if validate\n\n missing = check_columns(validate, prefix, required, :green, :red)\n raise RequiredColumnsMissing, missing if validate && missing.present?\n end\n\n optional = @definition.optional_columns\n unless optional.empty?\n Log.info { \"#{prefix} #{'optional columns'.cyan}\" } if validate\n check_columns(validate, prefix, optional, :cyan, :light_yellow)\n end\n\n cols = @definition.columns.collect(&:name)\n headers = @csv_headers.select { |h| cols.include?(h) }\n\n @col_names ||= @found_columns.map(&:name)\n ::Hash[*headers.inject([]) { |list, c| list << c << @definition[c] }]\n end", "code_tokens": ["def", "find_columns", "(", "validate", ")", "@found_columns", "=", "[", "]", "prefix", "=", "\"#{filename.yellow}:\"", "required", "=", "@definition", ".", "required_columns", "unless", "required", ".", "empty?", "Log", ".", "info", "{", "\"#{prefix} #{'required columns'.magenta}\"", "}", "if", "validate", "missing", "=", "check_columns", "(", "validate", ",", "prefix", ",", "required", ",", ":green", ",", ":red", ")", "raise", "RequiredColumnsMissing", ",", "missing", "if", "validate", "&&", "missing", ".", "present?", "end", "optional", "=", "@definition", ".", "optional_columns", "unless", "optional", ".", "empty?", "Log", ".", "info", "{", "\"#{prefix} #{'optional columns'.cyan}\"", "}", "if", "validate", "check_columns", "(", "validate", ",", "prefix", ",", "optional", ",", ":cyan", ",", ":light_yellow", ")", "end", "cols", "=", "@definition", ".", "columns", ".", "collect", "(", ":name", ")", "headers", "=", "@csv_headers", ".", "select", "{", "|", "h", "|", "cols", ".", "include?", "(", "h", ")", "}", "@col_names", "||=", "@found_columns", ".", "map", "(", ":name", ")", "::", "Hash", "[", "headers", ".", "inject", "(", "[", "]", ")", "{", "|", "list", ",", "c", "|", "list", "<<", "c", "<<", "@definition", "[", "c", "]", "}", "]", "end"], "docstring": "Check the list of headers in the file against the expected columns in\n the definition", "docstring_tokens": ["Check", "the", "list", "of", "headers", "in", "the", "file", "against", "the", "expected", "columns", "in", "the", "definition"], "sha": "206864d09e03924930bfa766442eb2679f461442", "url": "https://github.com/sangster/gtfs_reader/blob/206864d09e03924930bfa766442eb2679f461442/lib/gtfs_reader/file_reader.rb#L65-L88", "partition": "test"} {"repo": "cknadler/nidyx", "path": "lib/nidyx/mapper.rb", "func_name": "Nidyx.Mapper.map", "original_string": "def map(models, options)\n models = models.values\n case options[:platform].downcase\n when \"objc\", \"obj-c\", \"objective-c\"\n Nidyx::ObjCMapper.map(models, options)\n end\n end", "language": "ruby", "code": "def map(models, options)\n models = models.values\n case options[:platform].downcase\n when \"objc\", \"obj-c\", \"objective-c\"\n Nidyx::ObjCMapper.map(models, options)\n end\n end", "code_tokens": ["def", "map", "(", "models", ",", "options", ")", "models", "=", "models", ".", "values", "case", "options", "[", ":platform", "]", ".", "downcase", "when", "\"objc\"", ",", "\"obj-c\"", ",", "\"objective-c\"", "Nidyx", "::", "ObjCMapper", ".", "map", "(", "models", ",", "options", ")", "end", "end"], "docstring": "Proxies model mapping to the proper platform mapper\n @param models [Hash] a hash with model name keys and Model values\n @param options [Hash] runtime options\n @return [Array] an array of models generated for a specific platform", "docstring_tokens": ["Proxies", "model", "mapping", "to", "the", "proper", "platform", "mapper"], "sha": "75150a165a1f125599fbcbb981d0382689edc98b", "url": "https://github.com/cknadler/nidyx/blob/75150a165a1f125599fbcbb981d0382689edc98b/lib/nidyx/mapper.rb#L11-L17", "partition": "test"} {"repo": "cknadler/nidyx", "path": "lib/nidyx/parser.rb", "func_name": "Nidyx.Parser.generate", "original_string": "def generate(path, name)\n object = get_object(path)\n\n type = object[TYPE_KEY]\n if type == OBJECT_TYPE\n generate_object(path, name)\n\n elsif type == ARRAY_TYPE\n generate_top_level_array(path)\n\n elsif type.is_a?(Array)\n if type.include?(OBJECT_TYPE)\n raise UnsupportedSchemaError if type.include?(ARRAY_TYPE)\n generate_object(path, name)\n\n elsif type.include?(ARRAY_TYPE)\n generate_top_leve_array(path)\n\n else raise UnsupportedSchemaError; end\n else raise UnsupportedSchemaError; end\n end", "language": "ruby", "code": "def generate(path, name)\n object = get_object(path)\n\n type = object[TYPE_KEY]\n if type == OBJECT_TYPE\n generate_object(path, name)\n\n elsif type == ARRAY_TYPE\n generate_top_level_array(path)\n\n elsif type.is_a?(Array)\n if type.include?(OBJECT_TYPE)\n raise UnsupportedSchemaError if type.include?(ARRAY_TYPE)\n generate_object(path, name)\n\n elsif type.include?(ARRAY_TYPE)\n generate_top_leve_array(path)\n\n else raise UnsupportedSchemaError; end\n else raise UnsupportedSchemaError; end\n end", "code_tokens": ["def", "generate", "(", "path", ",", "name", ")", "object", "=", "get_object", "(", "path", ")", "type", "=", "object", "[", "TYPE_KEY", "]", "if", "type", "==", "OBJECT_TYPE", "generate_object", "(", "path", ",", "name", ")", "elsif", "type", "==", "ARRAY_TYPE", "generate_top_level_array", "(", "path", ")", "elsif", "type", ".", "is_a?", "(", "Array", ")", "if", "type", ".", "include?", "(", "OBJECT_TYPE", ")", "raise", "UnsupportedSchemaError", "if", "type", ".", "include?", "(", "ARRAY_TYPE", ")", "generate_object", "(", "path", ",", "name", ")", "elsif", "type", ".", "include?", "(", "ARRAY_TYPE", ")", "generate_top_leve_array", "(", "path", ")", "else", "raise", "UnsupportedSchemaError", ";", "end", "else", "raise", "UnsupportedSchemaError", ";", "end", "end"], "docstring": "Generates a Model and adds it to the models array.\n @param path [Array] the path to an object in the schema\n @param name [String] raw model name", "docstring_tokens": ["Generates", "a", "Model", "and", "adds", "it", "to", "the", "models", "array", "."], "sha": "75150a165a1f125599fbcbb981d0382689edc98b", "url": "https://github.com/cknadler/nidyx/blob/75150a165a1f125599fbcbb981d0382689edc98b/lib/nidyx/parser.rb#L36-L56", "partition": "test"} {"repo": "cknadler/nidyx", "path": "lib/nidyx/parser.rb", "func_name": "Nidyx.Parser.resolve_array_refs", "original_string": "def resolve_array_refs(obj)\n items = obj[ITEMS_KEY]\n\n case items\n when Array\n return resolve_items_array(items)\n when Hash\n # handle a nested any of key\n any_of = items[ANY_OF_KEY]\n return resolve_items_array(any_of) if any_of.is_a?(Array)\n\n resolve_reference_string(items[REF_KEY])\n return [class_name_from_ref(items[REF_KEY])].compact\n else\n return []\n end\n end", "language": "ruby", "code": "def resolve_array_refs(obj)\n items = obj[ITEMS_KEY]\n\n case items\n when Array\n return resolve_items_array(items)\n when Hash\n # handle a nested any of key\n any_of = items[ANY_OF_KEY]\n return resolve_items_array(any_of) if any_of.is_a?(Array)\n\n resolve_reference_string(items[REF_KEY])\n return [class_name_from_ref(items[REF_KEY])].compact\n else\n return []\n end\n end", "code_tokens": ["def", "resolve_array_refs", "(", "obj", ")", "items", "=", "obj", "[", "ITEMS_KEY", "]", "case", "items", "when", "Array", "return", "resolve_items_array", "(", "items", ")", "when", "Hash", "# handle a nested any of key", "any_of", "=", "items", "[", "ANY_OF_KEY", "]", "return", "resolve_items_array", "(", "any_of", ")", "if", "any_of", ".", "is_a?", "(", "Array", ")", "resolve_reference_string", "(", "items", "[", "REF_KEY", "]", ")", "return", "[", "class_name_from_ref", "(", "items", "[", "REF_KEY", "]", ")", "]", ".", "compact", "else", "return", "[", "]", "end", "end"], "docstring": "Resolves any references buied in the `items` property of an array\n definition. Returns a list of collection types in the array.\n @param obj [Hash] the array property schema\n @return [Array] types contained in the array", "docstring_tokens": ["Resolves", "any", "references", "buied", "in", "the", "items", "property", "of", "an", "array", "definition", ".", "Returns", "a", "list", "of", "collection", "types", "in", "the", "array", "."], "sha": "75150a165a1f125599fbcbb981d0382689edc98b", "url": "https://github.com/cknadler/nidyx/blob/75150a165a1f125599fbcbb981d0382689edc98b/lib/nidyx/parser.rb#L136-L152", "partition": "test"} {"repo": "cknadler/nidyx", "path": "lib/nidyx/generator.rb", "func_name": "Nidyx.Generator.run", "original_string": "def run(schema_path, options)\n schema = Nidyx::Reader.read(schema_path)\n raw_models = Nidyx::Parser.parse(schema, options)\n models = Nidyx::Mapper.map(raw_models, options)\n Nidyx::Output.write(models, options[:output_directory])\n end", "language": "ruby", "code": "def run(schema_path, options)\n schema = Nidyx::Reader.read(schema_path)\n raw_models = Nidyx::Parser.parse(schema, options)\n models = Nidyx::Mapper.map(raw_models, options)\n Nidyx::Output.write(models, options[:output_directory])\n end", "code_tokens": ["def", "run", "(", "schema_path", ",", "options", ")", "schema", "=", "Nidyx", "::", "Reader", ".", "read", "(", "schema_path", ")", "raw_models", "=", "Nidyx", "::", "Parser", ".", "parse", "(", "schema", ",", "options", ")", "models", "=", "Nidyx", "::", "Mapper", ".", "map", "(", "raw_models", ",", "options", ")", "Nidyx", "::", "Output", ".", "write", "(", "models", ",", "options", "[", ":output_directory", "]", ")", "end"], "docstring": "The Nidyx model generator. Called by the Nidyx CLI. Parses the input\n schema, creates models and writes them to the output directory.\n @param schema_path [String] Path to the schema to generate models with.\n @param options [Hash] Model generation options hash.", "docstring_tokens": ["The", "Nidyx", "model", "generator", ".", "Called", "by", "the", "Nidyx", "CLI", ".", "Parses", "the", "input", "schema", "creates", "models", "and", "writes", "them", "to", "the", "output", "directory", "."], "sha": "75150a165a1f125599fbcbb981d0382689edc98b", "url": "https://github.com/cknadler/nidyx/blob/75150a165a1f125599fbcbb981d0382689edc98b/lib/nidyx/generator.rb#L14-L19", "partition": "test"} {"repo": "cknadler/nidyx", "path": "lib/nidyx/reader.rb", "func_name": "Nidyx.Reader.read", "original_string": "def read(path)\n schema = nil\n\n begin\n # TODO: validate this is legitimate JSON Schema\n schema = JSON.parse(IO.read(path))\n raise EmptySchemaError if empty_schema?(schema)\n rescue JSON::JSONError => e\n puts \"Encountered an error reading JSON from #{path}\"\n puts e.message\n exit 1\n rescue EmptySchemaError\n puts \"Schema read from #{path} is empty\"\n exit 1\n rescue StandardError => e\n puts e.message\n exit 1\n end\n\n schema\n end", "language": "ruby", "code": "def read(path)\n schema = nil\n\n begin\n # TODO: validate this is legitimate JSON Schema\n schema = JSON.parse(IO.read(path))\n raise EmptySchemaError if empty_schema?(schema)\n rescue JSON::JSONError => e\n puts \"Encountered an error reading JSON from #{path}\"\n puts e.message\n exit 1\n rescue EmptySchemaError\n puts \"Schema read from #{path} is empty\"\n exit 1\n rescue StandardError => e\n puts e.message\n exit 1\n end\n\n schema\n end", "code_tokens": ["def", "read", "(", "path", ")", "schema", "=", "nil", "begin", "# TODO: validate this is legitimate JSON Schema", "schema", "=", "JSON", ".", "parse", "(", "IO", ".", "read", "(", "path", ")", ")", "raise", "EmptySchemaError", "if", "empty_schema?", "(", "schema", ")", "rescue", "JSON", "::", "JSONError", "=>", "e", "puts", "\"Encountered an error reading JSON from #{path}\"", "puts", "e", ".", "message", "exit", "1", "rescue", "EmptySchemaError", "puts", "\"Schema read from #{path} is empty\"", "exit", "1", "rescue", "StandardError", "=>", "e", "puts", "e", ".", "message", "exit", "1", "end", "schema", "end"], "docstring": "Reads JSON from a file\n @param path [String] path of the file to read\n @return [Hash] the parsed JSON", "docstring_tokens": ["Reads", "JSON", "from", "a", "file"], "sha": "75150a165a1f125599fbcbb981d0382689edc98b", "url": "https://github.com/cknadler/nidyx/blob/75150a165a1f125599fbcbb981d0382689edc98b/lib/nidyx/reader.rb#L15-L35", "partition": "test"} {"repo": "feixionglee/wxpay", "path": "lib/wxpay/sign.rb", "func_name": "Wxpay.Sign.sign_package", "original_string": "def sign_package params\n params_str = create_sign_str params\n\n if params_str =~ /trade_type=APP/\n key = Wxpay.app_api_key\n else\n key = Wxpay.api_key\n end\n Digest::MD5.hexdigest(params_str+\"&key=#{key}\").upcase\n end", "language": "ruby", "code": "def sign_package params\n params_str = create_sign_str params\n\n if params_str =~ /trade_type=APP/\n key = Wxpay.app_api_key\n else\n key = Wxpay.api_key\n end\n Digest::MD5.hexdigest(params_str+\"&key=#{key}\").upcase\n end", "code_tokens": ["def", "sign_package", "params", "params_str", "=", "create_sign_str", "params", "if", "params_str", "=~", "/", "/", "key", "=", "Wxpay", ".", "app_api_key", "else", "key", "=", "Wxpay", ".", "api_key", "end", "Digest", "::", "MD5", ".", "hexdigest", "(", "params_str", "+", "\"&key=#{key}\"", ")", ".", "upcase", "end"], "docstring": "used in wechat pay api", "docstring_tokens": ["used", "in", "wechat", "pay", "api"], "sha": "93b77efdf05f40df71b8e6a1b16e939917f63047", "url": "https://github.com/feixionglee/wxpay/blob/93b77efdf05f40df71b8e6a1b16e939917f63047/lib/wxpay/sign.rb#L6-L15", "partition": "test"} {"repo": "enspirit/webspicy", "path": "lib/webspicy/scope.rb", "func_name": "Webspicy.Scope._each_resource_file", "original_string": "def _each_resource_file(config)\n folder = config.folder\n folder.glob(\"**/*.yml\").select(&to_filter_proc(config.file_filter)).each do |file|\n yield file, folder\n end\n end", "language": "ruby", "code": "def _each_resource_file(config)\n folder = config.folder\n folder.glob(\"**/*.yml\").select(&to_filter_proc(config.file_filter)).each do |file|\n yield file, folder\n end\n end", "code_tokens": ["def", "_each_resource_file", "(", "config", ")", "folder", "=", "config", ".", "folder", "folder", ".", "glob", "(", "\"**/*.yml\"", ")", ".", "select", "(", "to_filter_proc", "(", "config", ".", "file_filter", ")", ")", ".", "each", "do", "|", "file", "|", "yield", "file", ",", "folder", "end", "end"], "docstring": "Recursive implementation of `each_resource_file` for each\n folder in the configuration.", "docstring_tokens": ["Recursive", "implementation", "of", "each_resource_file", "for", "each", "folder", "in", "the", "configuration", "."], "sha": "59074e703c5366b089dea49f1b88fef16d11478e", "url": "https://github.com/enspirit/webspicy/blob/59074e703c5366b089dea49f1b88fef16d11478e/lib/webspicy/scope.rb#L29-L34", "partition": "test"} {"repo": "enspirit/webspicy", "path": "lib/webspicy/scope.rb", "func_name": "Webspicy.Scope.each_resource", "original_string": "def each_resource(&bl)\n return enum_for(:each_resource) unless block_given?\n each_resource_file do |file, folder|\n yield Webspicy.resource(file.load, file, self)\n end\n end", "language": "ruby", "code": "def each_resource(&bl)\n return enum_for(:each_resource) unless block_given?\n each_resource_file do |file, folder|\n yield Webspicy.resource(file.load, file, self)\n end\n end", "code_tokens": ["def", "each_resource", "(", "&", "bl", ")", "return", "enum_for", "(", ":each_resource", ")", "unless", "block_given?", "each_resource_file", "do", "|", "file", ",", "folder", "|", "yield", "Webspicy", ".", "resource", "(", "file", ".", "load", ",", "file", ",", "self", ")", "end", "end"], "docstring": "Yields each resource in the current scope in turn.", "docstring_tokens": ["Yields", "each", "resource", "in", "the", "current", "scope", "in", "turn", "."], "sha": "59074e703c5366b089dea49f1b88fef16d11478e", "url": "https://github.com/enspirit/webspicy/blob/59074e703c5366b089dea49f1b88fef16d11478e/lib/webspicy/scope.rb#L38-L43", "partition": "test"} {"repo": "enspirit/webspicy", "path": "lib/webspicy/scope.rb", "func_name": "Webspicy.Scope.to_real_url", "original_string": "def to_real_url(url, test_case = nil, &bl)\n case config.host\n when Proc\n config.host.call(url, test_case)\n when String\n url =~ /^http/ ? url : \"#{config.host}#{url}\"\n else\n return url if url =~ /^http/\n return yield(url) if block_given?\n raise \"Unable to resolve `#{url}` : no host resolver provided\\nSee `Configuration#host=\"\n end\n end", "language": "ruby", "code": "def to_real_url(url, test_case = nil, &bl)\n case config.host\n when Proc\n config.host.call(url, test_case)\n when String\n url =~ /^http/ ? url : \"#{config.host}#{url}\"\n else\n return url if url =~ /^http/\n return yield(url) if block_given?\n raise \"Unable to resolve `#{url}` : no host resolver provided\\nSee `Configuration#host=\"\n end\n end", "code_tokens": ["def", "to_real_url", "(", "url", ",", "test_case", "=", "nil", ",", "&", "bl", ")", "case", "config", ".", "host", "when", "Proc", "config", ".", "host", ".", "call", "(", "url", ",", "test_case", ")", "when", "String", "url", "=~", "/", "/", "?", "url", ":", "\"#{config.host}#{url}\"", "else", "return", "url", "if", "url", "=~", "/", "/", "return", "yield", "(", "url", ")", "if", "block_given?", "raise", "\"Unable to resolve `#{url}` : no host resolver provided\\nSee `Configuration#host=\"", "end", "end"], "docstring": "Convert an instantiated URL found in a webservice definition\n to a real URL, using the configuration host.\n\n When no host resolved on the configuration and the url is not\n already an absolute URL, yields the block if given, or raise\n an exception.", "docstring_tokens": ["Convert", "an", "instantiated", "URL", "found", "in", "a", "webservice", "definition", "to", "a", "real", "URL", "using", "the", "configuration", "host", "."], "sha": "59074e703c5366b089dea49f1b88fef16d11478e", "url": "https://github.com/enspirit/webspicy/blob/59074e703c5366b089dea49f1b88fef16d11478e/lib/webspicy/scope.rb#L107-L118", "partition": "test"} {"repo": "enspirit/webspicy", "path": "lib/webspicy/scope.rb", "func_name": "Webspicy.Scope.to_filter_proc", "original_string": "def to_filter_proc(filter)\n case ff = filter\n when NilClass then ->(f){ true }\n when Proc then ff\n when Regexp then ->(f){ ff =~ f.to_s }\n else\n ->(f){ ff === f }\n end\n end", "language": "ruby", "code": "def to_filter_proc(filter)\n case ff = filter\n when NilClass then ->(f){ true }\n when Proc then ff\n when Regexp then ->(f){ ff =~ f.to_s }\n else\n ->(f){ ff === f }\n end\n end", "code_tokens": ["def", "to_filter_proc", "(", "filter", ")", "case", "ff", "=", "filter", "when", "NilClass", "then", "->", "(", "f", ")", "{", "true", "}", "when", "Proc", "then", "ff", "when", "Regexp", "then", "->", "(", "f", ")", "{", "ff", "=~", "f", ".", "to_s", "}", "else", "->", "(", "f", ")", "{", "ff", "===", "f", "}", "end", "end"], "docstring": "Returns a proc that implements file_filter strategy according to the\n type of filter installed", "docstring_tokens": ["Returns", "a", "proc", "that", "implements", "file_filter", "strategy", "according", "to", "the", "type", "of", "filter", "installed"], "sha": "59074e703c5366b089dea49f1b88fef16d11478e", "url": "https://github.com/enspirit/webspicy/blob/59074e703c5366b089dea49f1b88fef16d11478e/lib/webspicy/scope.rb#L147-L155", "partition": "test"} {"repo": "enspirit/webspicy", "path": "lib/webspicy/configuration.rb", "func_name": "Webspicy.Configuration.folder", "original_string": "def folder(folder = nil, &bl)\n if folder.nil?\n @folder\n else\n folder = folder.is_a?(String) ? @folder/folder : Path(folder)\n raise \"Folder `#{folder}` does not exists\" unless folder.exists? && folder.directory?\n raise \"Folder must be a descendant\" unless folder.inside?(@folder)\n child = dup do |c|\n c.parent = self\n c.folder = folder\n end\n yield(child) if block_given?\n @children << child\n child\n end\n end", "language": "ruby", "code": "def folder(folder = nil, &bl)\n if folder.nil?\n @folder\n else\n folder = folder.is_a?(String) ? @folder/folder : Path(folder)\n raise \"Folder `#{folder}` does not exists\" unless folder.exists? && folder.directory?\n raise \"Folder must be a descendant\" unless folder.inside?(@folder)\n child = dup do |c|\n c.parent = self\n c.folder = folder\n end\n yield(child) if block_given?\n @children << child\n child\n end\n end", "code_tokens": ["def", "folder", "(", "folder", "=", "nil", ",", "&", "bl", ")", "if", "folder", ".", "nil?", "@folder", "else", "folder", "=", "folder", ".", "is_a?", "(", "String", ")", "?", "@folder", "/", "folder", ":", "Path", "(", "folder", ")", "raise", "\"Folder `#{folder}` does not exists\"", "unless", "folder", ".", "exists?", "&&", "folder", ".", "directory?", "raise", "\"Folder must be a descendant\"", "unless", "folder", ".", "inside?", "(", "@folder", ")", "child", "=", "dup", "do", "|", "c", "|", "c", ".", "parent", "=", "self", "c", ".", "folder", "=", "folder", "end", "yield", "(", "child", ")", "if", "block_given?", "@children", "<<", "child", "child", "end", "end"], "docstring": "Adds a folder to the list of folders where test case definitions are\n to be found.", "docstring_tokens": ["Adds", "a", "folder", "to", "the", "list", "of", "folders", "where", "test", "case", "definitions", "are", "to", "be", "found", "."], "sha": "59074e703c5366b089dea49f1b88fef16d11478e", "url": "https://github.com/enspirit/webspicy/blob/59074e703c5366b089dea49f1b88fef16d11478e/lib/webspicy/configuration.rb#L58-L73", "partition": "test"} {"repo": "enspirit/webspicy", "path": "lib/webspicy/configuration.rb", "func_name": "Webspicy.Configuration.data_system", "original_string": "def data_system\n schema = self.folder/\"schema.fio\"\n if schema.file?\n Finitio::DEFAULT_SYSTEM.parse(schema.read)\n elsif not(self.parent.nil?)\n self.parent.data_system\n else\n Finitio::DEFAULT_SYSTEM\n end\n end", "language": "ruby", "code": "def data_system\n schema = self.folder/\"schema.fio\"\n if schema.file?\n Finitio::DEFAULT_SYSTEM.parse(schema.read)\n elsif not(self.parent.nil?)\n self.parent.data_system\n else\n Finitio::DEFAULT_SYSTEM\n end\n end", "code_tokens": ["def", "data_system", "schema", "=", "self", ".", "folder", "/", "\"schema.fio\"", "if", "schema", ".", "file?", "Finitio", "::", "DEFAULT_SYSTEM", ".", "parse", "(", "schema", ".", "read", ")", "elsif", "not", "(", "self", ".", "parent", ".", "nil?", ")", "self", ".", "parent", ".", "data_system", "else", "Finitio", "::", "DEFAULT_SYSTEM", "end", "end"], "docstring": "Returns the Data system to use for parsing schemas\n\n The data system associated with a configuration is build when the\n configuration folder contains a `schema.fio` finitio file. When no\n such file can be found, the parent config is checked (if any). When\n no `schema.fio` file can be found, the method ends up returning the\n default Finition system.", "docstring_tokens": ["Returns", "the", "Data", "system", "to", "use", "for", "parsing", "schemas"], "sha": "59074e703c5366b089dea49f1b88fef16d11478e", "url": "https://github.com/enspirit/webspicy/blob/59074e703c5366b089dea49f1b88fef16d11478e/lib/webspicy/configuration.rb#L291-L300", "partition": "test"} {"repo": "ThomasAlxDmy/Exodus", "path": "lib/exodus/migrations/migration.rb", "func_name": "Exodus.Migration.run", "original_string": "def run(direction)\n self.status.direction = direction\n\n # reset the status if the job is rerunnable and has already be completed\n self.status.reset! if self.class.rerunnable_safe? && completed?(direction) \n self.status.execution_time = time_it { self.send(direction) }\n self.status.last_succesful_completion = Time.now\n end", "language": "ruby", "code": "def run(direction)\n self.status.direction = direction\n\n # reset the status if the job is rerunnable and has already be completed\n self.status.reset! if self.class.rerunnable_safe? && completed?(direction) \n self.status.execution_time = time_it { self.send(direction) }\n self.status.last_succesful_completion = Time.now\n end", "code_tokens": ["def", "run", "(", "direction", ")", "self", ".", "status", ".", "direction", "=", "direction", "# reset the status if the job is rerunnable and has already be completed", "self", ".", "status", ".", "reset!", "if", "self", ".", "class", ".", "rerunnable_safe?", "&&", "completed?", "(", "direction", ")", "self", ".", "status", ".", "execution_time", "=", "time_it", "{", "self", ".", "send", "(", "direction", ")", "}", "self", ".", "status", ".", "last_succesful_completion", "=", "Time", ".", "now", "end"], "docstring": "Makes sure status get instanciated on migration's instanciation\n Runs the migration following the direction\n sets the status, the execution time and the last succesful_completion date", "docstring_tokens": ["Makes", "sure", "status", "get", "instanciated", "on", "migration", "s", "instanciation", "Runs", "the", "migration", "following", "the", "direction", "sets", "the", "status", "the", "execution", "time", "and", "the", "last", "succesful_completion", "date"], "sha": "7c8283268647e270c14279d289f84a3d7bb89f8b", "url": "https://github.com/ThomasAlxDmy/Exodus/blob/7c8283268647e270c14279d289f84a3d7bb89f8b/lib/exodus/migrations/migration.rb#L114-L121", "partition": "test"} {"repo": "ThomasAlxDmy/Exodus", "path": "lib/exodus/migrations/migration.rb", "func_name": "Exodus.Migration.failure=", "original_string": "def failure=(exception)\n self.status.error = MigrationError.new(\n :error_message => exception.message, \n :error_class => exception.class, \n :error_backtrace => exception.backtrace)\n end", "language": "ruby", "code": "def failure=(exception)\n self.status.error = MigrationError.new(\n :error_message => exception.message, \n :error_class => exception.class, \n :error_backtrace => exception.backtrace)\n end", "code_tokens": ["def", "failure", "=", "(", "exception", ")", "self", ".", "status", ".", "error", "=", "MigrationError", ".", "new", "(", ":error_message", "=>", "exception", ".", "message", ",", ":error_class", "=>", "exception", ".", "class", ",", ":error_backtrace", "=>", "exception", ".", "backtrace", ")", "end"], "docstring": "Sets an error to migration status", "docstring_tokens": ["Sets", "an", "error", "to", "migration", "status"], "sha": "7c8283268647e270c14279d289f84a3d7bb89f8b", "url": "https://github.com/ThomasAlxDmy/Exodus/blob/7c8283268647e270c14279d289f84a3d7bb89f8b/lib/exodus/migrations/migration.rb#L124-L129", "partition": "test"} {"repo": "ThomasAlxDmy/Exodus", "path": "lib/exodus/migrations/migration.rb", "func_name": "Exodus.Migration.is_runnable?", "original_string": "def is_runnable?(direction)\n self.class.rerunnable_safe? || \n (direction == UP && status.current_status < status_complete) || \n (direction == DOWN && status.current_status > 0)\n end", "language": "ruby", "code": "def is_runnable?(direction)\n self.class.rerunnable_safe? || \n (direction == UP && status.current_status < status_complete) || \n (direction == DOWN && status.current_status > 0)\n end", "code_tokens": ["def", "is_runnable?", "(", "direction", ")", "self", ".", "class", ".", "rerunnable_safe?", "||", "(", "direction", "==", "UP", "&&", "status", ".", "current_status", "<", "status_complete", ")", "||", "(", "direction", "==", "DOWN", "&&", "status", ".", "current_status", ">", "0", ")", "end"], "docstring": "Checks if a migration can be run", "docstring_tokens": ["Checks", "if", "a", "migration", "can", "be", "run"], "sha": "7c8283268647e270c14279d289f84a3d7bb89f8b", "url": "https://github.com/ThomasAlxDmy/Exodus/blob/7c8283268647e270c14279d289f84a3d7bb89f8b/lib/exodus/migrations/migration.rb#L132-L136", "partition": "test"} {"repo": "ThomasAlxDmy/Exodus", "path": "lib/exodus/migrations/migration.rb", "func_name": "Exodus.Migration.completed?", "original_string": "def completed?(direction) \n return false if self.status.execution_time == 0\n (direction == UP && self.status.current_status == self.status_complete) || \n (direction == DOWN && self.status.current_status == 0)\n end", "language": "ruby", "code": "def completed?(direction) \n return false if self.status.execution_time == 0\n (direction == UP && self.status.current_status == self.status_complete) || \n (direction == DOWN && self.status.current_status == 0)\n end", "code_tokens": ["def", "completed?", "(", "direction", ")", "return", "false", "if", "self", ".", "status", ".", "execution_time", "==", "0", "(", "direction", "==", "UP", "&&", "self", ".", "status", ".", "current_status", "==", "self", ".", "status_complete", ")", "||", "(", "direction", "==", "DOWN", "&&", "self", ".", "status", ".", "current_status", "==", "0", ")", "end"], "docstring": "Checks if a migration as been completed", "docstring_tokens": ["Checks", "if", "a", "migration", "as", "been", "completed"], "sha": "7c8283268647e270c14279d289f84a3d7bb89f8b", "url": "https://github.com/ThomasAlxDmy/Exodus/blob/7c8283268647e270c14279d289f84a3d7bb89f8b/lib/exodus/migrations/migration.rb#L139-L143", "partition": "test"} {"repo": "ThomasAlxDmy/Exodus", "path": "lib/exodus/migrations/migration.rb", "func_name": "Exodus.Migration.step", "original_string": "def step(step_message = nil, step_status = 1)\n unless status.status_processed?(status.direction, step_status)\n self.status.message = step_message\n puts \"\\t #{step_message}\" \n\n yield if block_given?\n self.status.current_status += status.direction_to_i\n end\n end", "language": "ruby", "code": "def step(step_message = nil, step_status = 1)\n unless status.status_processed?(status.direction, step_status)\n self.status.message = step_message\n puts \"\\t #{step_message}\" \n\n yield if block_given?\n self.status.current_status += status.direction_to_i\n end\n end", "code_tokens": ["def", "step", "(", "step_message", "=", "nil", ",", "step_status", "=", "1", ")", "unless", "status", ".", "status_processed?", "(", "status", ".", "direction", ",", "step_status", ")", "self", ".", "status", ".", "message", "=", "step_message", "puts", "\"\\t #{step_message}\"", "yield", "if", "block_given?", "self", ".", "status", ".", "current_status", "+=", "status", ".", "direction_to_i", "end", "end"], "docstring": "Executes a given block if the status has not being processed\n Then update the status", "docstring_tokens": ["Executes", "a", "given", "block", "if", "the", "status", "has", "not", "being", "processed", "Then", "update", "the", "status"], "sha": "7c8283268647e270c14279d289f84a3d7bb89f8b", "url": "https://github.com/ThomasAlxDmy/Exodus/blob/7c8283268647e270c14279d289f84a3d7bb89f8b/lib/exodus/migrations/migration.rb#L161-L169", "partition": "test"} {"repo": "ThomasAlxDmy/Exodus", "path": "lib/exodus/migrations/migration.rb", "func_name": "Exodus.Migration.time_it", "original_string": "def time_it\n puts \"Running #{self.class}[#{self.status.arguments}](#{self.status.direction})\"\n\n start = Time.now\n yield if block_given?\n end_time = Time.now - start\n \n puts \"Tasks #{self.class} executed in #{end_time} seconds. \\n\\n\"\n end_time\n end", "language": "ruby", "code": "def time_it\n puts \"Running #{self.class}[#{self.status.arguments}](#{self.status.direction})\"\n\n start = Time.now\n yield if block_given?\n end_time = Time.now - start\n \n puts \"Tasks #{self.class} executed in #{end_time} seconds. \\n\\n\"\n end_time\n end", "code_tokens": ["def", "time_it", "puts", "\"Running #{self.class}[#{self.status.arguments}](#{self.status.direction})\"", "start", "=", "Time", ".", "now", "yield", "if", "block_given?", "end_time", "=", "Time", ".", "now", "-", "start", "puts", "\"Tasks #{self.class} executed in #{end_time} seconds. \\n\\n\"", "end_time", "end"], "docstring": "Executes a block and returns the time it took to be executed", "docstring_tokens": ["Executes", "a", "block", "and", "returns", "the", "time", "it", "took", "to", "be", "executed"], "sha": "7c8283268647e270c14279d289f84a3d7bb89f8b", "url": "https://github.com/ThomasAlxDmy/Exodus/blob/7c8283268647e270c14279d289f84a3d7bb89f8b/lib/exodus/migrations/migration.rb#L177-L186", "partition": "test"} {"repo": "ThomasAlxDmy/Exodus", "path": "lib/exodus/helpers/text_formatter.rb", "func_name": "Exodus.TextFormatter.super_print", "original_string": "def super_print(paragraphes, space_number = 50, title = true)\n puts format_paragraph(space_number, title, *paragraphes)\n end", "language": "ruby", "code": "def super_print(paragraphes, space_number = 50, title = true)\n puts format_paragraph(space_number, title, *paragraphes)\n end", "code_tokens": ["def", "super_print", "(", "paragraphes", ",", "space_number", "=", "50", ",", "title", "=", "true", ")", "puts", "format_paragraph", "(", "space_number", ",", "title", ",", "paragraphes", ")", "end"], "docstring": "Prints a paragraphes", "docstring_tokens": ["Prints", "a", "paragraphes"], "sha": "7c8283268647e270c14279d289f84a3d7bb89f8b", "url": "https://github.com/ThomasAlxDmy/Exodus/blob/7c8283268647e270c14279d289f84a3d7bb89f8b/lib/exodus/helpers/text_formatter.rb#L5-L7", "partition": "test"} {"repo": "kosmas58/compass-jquery-plugin", "path": "lib/jquery/gridify/grid.rb", "func_name": "Gridify.Grid.columns_hash", "original_string": "def columns_hash\n colModel.inject({}) { |h, col| h[col.name] = col; h }\n end", "language": "ruby", "code": "def columns_hash\n colModel.inject({}) { |h, col| h[col.name] = col; h }\n end", "code_tokens": ["def", "columns_hash", "colModel", ".", "inject", "(", "{", "}", ")", "{", "|", "h", ",", "col", "|", "h", "[", "col", ".", "name", "]", "=", "col", ";", "h", "}", "end"], "docstring": "normally we need to keep columns an ordered array, sometimes its convenient to have a hash", "docstring_tokens": ["normally", "we", "need", "to", "keep", "columns", "an", "ordered", "array", "sometimes", "its", "convenient", "to", "have", "a", "hash"], "sha": "110237f9ff80cbc481d32b1d8e88280a4ca84309", "url": "https://github.com/kosmas58/compass-jquery-plugin/blob/110237f9ff80cbc481d32b1d8e88280a4ca84309/lib/jquery/gridify/grid.rb#L98-L100", "partition": "test"} {"repo": "leapcode/amber", "path": "lib/amber/site.rb", "func_name": "Amber.Site.render", "original_string": "def render\n @page_list.each do |page|\n page.render_to_file(@config.dest_dir)\n putc '.'; $stdout.flush\n end\n @dir_list.each do |directory|\n src = File.join(@config.pages_dir, directory)\n dst = File.join(@config.dest_dir, directory)\n Render::Asset.render_dir(src, dst)\n putc '.'; $stdout.flush\n end\n if @config.short_paths\n render_short_path_symlinks\n end\n Render::Apache.write_htaccess(@config, @config.pages_dir, @config.dest_dir)\n puts\n end", "language": "ruby", "code": "def render\n @page_list.each do |page|\n page.render_to_file(@config.dest_dir)\n putc '.'; $stdout.flush\n end\n @dir_list.each do |directory|\n src = File.join(@config.pages_dir, directory)\n dst = File.join(@config.dest_dir, directory)\n Render::Asset.render_dir(src, dst)\n putc '.'; $stdout.flush\n end\n if @config.short_paths\n render_short_path_symlinks\n end\n Render::Apache.write_htaccess(@config, @config.pages_dir, @config.dest_dir)\n puts\n end", "code_tokens": ["def", "render", "@page_list", ".", "each", "do", "|", "page", "|", "page", ".", "render_to_file", "(", "@config", ".", "dest_dir", ")", "putc", "'.'", ";", "$stdout", ".", "flush", "end", "@dir_list", ".", "each", "do", "|", "directory", "|", "src", "=", "File", ".", "join", "(", "@config", ".", "pages_dir", ",", "directory", ")", "dst", "=", "File", ".", "join", "(", "@config", ".", "dest_dir", ",", "directory", ")", "Render", "::", "Asset", ".", "render_dir", "(", "src", ",", "dst", ")", "putc", "'.'", ";", "$stdout", ".", "flush", "end", "if", "@config", ".", "short_paths", "render_short_path_symlinks", "end", "Render", "::", "Apache", ".", "write_htaccess", "(", "@config", ",", "@config", ".", "pages_dir", ",", "@config", ".", "dest_dir", ")", "puts", "end"], "docstring": "def reload_pages_if_needed\n if @pages_by_path.nil? || @config.pages_changed?\n puts \"Reloading pages .................\"\n load_pages\n end\nend", "docstring_tokens": ["def", "reload_pages_if_needed", "if"], "sha": "09452da4c756f5edf5e15e19bb3b1079c5f16480", "url": "https://github.com/leapcode/amber/blob/09452da4c756f5edf5e15e19bb3b1079c5f16480/lib/amber/site.rb#L45-L61", "partition": "test"} {"repo": "leapcode/amber", "path": "lib/amber/site.rb", "func_name": "Amber.Site.add_page", "original_string": "def add_page(page)\n @pages_by_name[page.name] ||= page\n @pages_by_path[page.path.join('/')] = page\n add_aliases(I18n.default_locale, page, @pages_by_path)\n page.locales.each do |locale|\n next if locale == I18n.default_locale\n add_aliases(locale, page, @pages_by_locale_path[locale])\n end\n @page_list << page\n end", "language": "ruby", "code": "def add_page(page)\n @pages_by_name[page.name] ||= page\n @pages_by_path[page.path.join('/')] = page\n add_aliases(I18n.default_locale, page, @pages_by_path)\n page.locales.each do |locale|\n next if locale == I18n.default_locale\n add_aliases(locale, page, @pages_by_locale_path[locale])\n end\n @page_list << page\n end", "code_tokens": ["def", "add_page", "(", "page", ")", "@pages_by_name", "[", "page", ".", "name", "]", "||=", "page", "@pages_by_path", "[", "page", ".", "path", ".", "join", "(", "'/'", ")", "]", "=", "page", "add_aliases", "(", "I18n", ".", "default_locale", ",", "page", ",", "@pages_by_path", ")", "page", ".", "locales", ".", "each", "do", "|", "locale", "|", "next", "if", "locale", "==", "I18n", ".", "default_locale", "add_aliases", "(", "locale", ",", "page", ",", "@pages_by_locale_path", "[", "locale", "]", ")", "end", "@page_list", "<<", "page", "end"], "docstring": "registers a page with the site, indexing the page path in our various hashes", "docstring_tokens": ["registers", "a", "page", "with", "the", "site", "indexing", "the", "page", "path", "in", "our", "various", "hashes"], "sha": "09452da4c756f5edf5e15e19bb3b1079c5f16480", "url": "https://github.com/leapcode/amber/blob/09452da4c756f5edf5e15e19bb3b1079c5f16480/lib/amber/site.rb#L183-L192", "partition": "test"} {"repo": "leapcode/amber", "path": "lib/amber/site.rb", "func_name": "Amber.Site.add_aliases", "original_string": "def add_aliases(locale, page, path_hash)\n page.aliases(locale).each do |alias_path|\n alias_path_str = alias_path.join('/')\n if path_hash[alias_path_str]\n Amber.logger.warn \"WARNING: page `#{page.path.join('/')}` has alias `#{alias_path_str}`, but this path is already taken by `#{path_hash[alias_path_str].path.join('/')}` (locale = #{locale}).\"\n else\n path_hash[alias_path_str] = page\n end\n end\n end", "language": "ruby", "code": "def add_aliases(locale, page, path_hash)\n page.aliases(locale).each do |alias_path|\n alias_path_str = alias_path.join('/')\n if path_hash[alias_path_str]\n Amber.logger.warn \"WARNING: page `#{page.path.join('/')}` has alias `#{alias_path_str}`, but this path is already taken by `#{path_hash[alias_path_str].path.join('/')}` (locale = #{locale}).\"\n else\n path_hash[alias_path_str] = page\n end\n end\n end", "code_tokens": ["def", "add_aliases", "(", "locale", ",", "page", ",", "path_hash", ")", "page", ".", "aliases", "(", "locale", ")", ".", "each", "do", "|", "alias_path", "|", "alias_path_str", "=", "alias_path", ".", "join", "(", "'/'", ")", "if", "path_hash", "[", "alias_path_str", "]", "Amber", ".", "logger", ".", "warn", "\"WARNING: page `#{page.path.join('/')}` has alias `#{alias_path_str}`, but this path is already taken by `#{path_hash[alias_path_str].path.join('/')}` (locale = #{locale}).\"", "else", "path_hash", "[", "alias_path_str", "]", "=", "page", "end", "end", "end"], "docstring": "registers a page's aliases with the site", "docstring_tokens": ["registers", "a", "page", "s", "aliases", "with", "the", "site"], "sha": "09452da4c756f5edf5e15e19bb3b1079c5f16480", "url": "https://github.com/leapcode/amber/blob/09452da4c756f5edf5e15e19bb3b1079c5f16480/lib/amber/site.rb#L197-L206", "partition": "test"} {"repo": "leapcode/amber", "path": "lib/amber/static_page/filesystem.rb", "func_name": "Amber.StaticPage.parse_headers", "original_string": "def parse_headers(content_file)\n headers = []\n para1 = []\n para2 = []\n file_type = type_from_path(content_file)\n\n File.open(content_file, :encoding => 'UTF-8') do |f|\n while (line = f.gets) =~ /^(- |)@\\w/\n if line !~ /^-/\n line = '- ' + line\n end\n headers << line\n end\n # eat empty lines\n while line = f.gets\n break unless line =~ /^\\s*$/\n end\n # grab first two paragraphs\n para1 << line\n while line = f.gets\n break if line =~ /^\\s*$/\n para1 << line\n end\n while line = f.gets\n break if line =~ /^\\s*$/\n para2 << line\n end\n end\n\n headers = headers.join\n para1 = para1.join\n para2 = para2.join\n excerpt = \"\"\n\n # pick the first non-heading paragraph.\n # this is stupid, and chokes on nested headings.\n # but is also cheap and fast :)\n if file_type == :textile\n if para1 =~ /^h[1-5]\\. /\n excerpt = para2\n else\n excerpt = para1\n end\n elsif file_type == :markdown\n if para1 =~ /^#+ / || para1 =~ /^(===+|---+)\\s*$/m\n excerpt = para2\n else\n excerpt = para1\n end\n end\n return [headers, excerpt]\n end", "language": "ruby", "code": "def parse_headers(content_file)\n headers = []\n para1 = []\n para2 = []\n file_type = type_from_path(content_file)\n\n File.open(content_file, :encoding => 'UTF-8') do |f|\n while (line = f.gets) =~ /^(- |)@\\w/\n if line !~ /^-/\n line = '- ' + line\n end\n headers << line\n end\n # eat empty lines\n while line = f.gets\n break unless line =~ /^\\s*$/\n end\n # grab first two paragraphs\n para1 << line\n while line = f.gets\n break if line =~ /^\\s*$/\n para1 << line\n end\n while line = f.gets\n break if line =~ /^\\s*$/\n para2 << line\n end\n end\n\n headers = headers.join\n para1 = para1.join\n para2 = para2.join\n excerpt = \"\"\n\n # pick the first non-heading paragraph.\n # this is stupid, and chokes on nested headings.\n # but is also cheap and fast :)\n if file_type == :textile\n if para1 =~ /^h[1-5]\\. /\n excerpt = para2\n else\n excerpt = para1\n end\n elsif file_type == :markdown\n if para1 =~ /^#+ / || para1 =~ /^(===+|---+)\\s*$/m\n excerpt = para2\n else\n excerpt = para1\n end\n end\n return [headers, excerpt]\n end", "code_tokens": ["def", "parse_headers", "(", "content_file", ")", "headers", "=", "[", "]", "para1", "=", "[", "]", "para2", "=", "[", "]", "file_type", "=", "type_from_path", "(", "content_file", ")", "File", ".", "open", "(", "content_file", ",", ":encoding", "=>", "'UTF-8'", ")", "do", "|", "f", "|", "while", "(", "line", "=", "f", ".", "gets", ")", "=~", "/", "\\w", "/", "if", "line", "!~", "/", "/", "line", "=", "'- '", "+", "line", "end", "headers", "<<", "line", "end", "# eat empty lines", "while", "line", "=", "f", ".", "gets", "break", "unless", "line", "=~", "/", "\\s", "/", "end", "# grab first two paragraphs", "para1", "<<", "line", "while", "line", "=", "f", ".", "gets", "break", "if", "line", "=~", "/", "\\s", "/", "para1", "<<", "line", "end", "while", "line", "=", "f", ".", "gets", "break", "if", "line", "=~", "/", "\\s", "/", "para2", "<<", "line", "end", "end", "headers", "=", "headers", ".", "join", "para1", "=", "para1", ".", "join", "para2", "=", "para2", ".", "join", "excerpt", "=", "\"\"", "# pick the first non-heading paragraph.", "# this is stupid, and chokes on nested headings.", "# but is also cheap and fast :)", "if", "file_type", "==", ":textile", "if", "para1", "=~", "/", "\\.", "/", "excerpt", "=", "para2", "else", "excerpt", "=", "para1", "end", "elsif", "file_type", "==", ":markdown", "if", "para1", "=~", "/", "/", "||", "para1", "=~", "/", "\\s", "/m", "excerpt", "=", "para2", "else", "excerpt", "=", "para1", "end", "end", "return", "[", "headers", ",", "excerpt", "]", "end"], "docstring": "parses a content_file's property headers and tries to extract the\n first paragraph.", "docstring_tokens": ["parses", "a", "content_file", "s", "property", "headers", "and", "tries", "to", "extract", "the", "first", "paragraph", "."], "sha": "09452da4c756f5edf5e15e19bb3b1079c5f16480", "url": "https://github.com/leapcode/amber/blob/09452da4c756f5edf5e15e19bb3b1079c5f16480/lib/amber/static_page/filesystem.rb#L273-L324", "partition": "test"} {"repo": "leapcode/amber", "path": "lib/amber/static_page/filesystem.rb", "func_name": "Amber.StaticPage.variable_files", "original_string": "def variable_files\n if @simple_page\n directory = File.dirname(@file_path)\n regexp = SIMPLE_VAR_MATCH_RE.call(@name)\n else\n directory = @file_path\n regexp = VAR_FILE_MATCH_RE\n end\n hsh = {}\n Dir.foreach(directory) do |file|\n if file && match = regexp.match(file)\n locale = match['locale'] || I18n.default_locale\n hsh[locale.to_sym] = File.join(directory, file)\n end\n end\n hsh\n end", "language": "ruby", "code": "def variable_files\n if @simple_page\n directory = File.dirname(@file_path)\n regexp = SIMPLE_VAR_MATCH_RE.call(@name)\n else\n directory = @file_path\n regexp = VAR_FILE_MATCH_RE\n end\n hsh = {}\n Dir.foreach(directory) do |file|\n if file && match = regexp.match(file)\n locale = match['locale'] || I18n.default_locale\n hsh[locale.to_sym] = File.join(directory, file)\n end\n end\n hsh\n end", "code_tokens": ["def", "variable_files", "if", "@simple_page", "directory", "=", "File", ".", "dirname", "(", "@file_path", ")", "regexp", "=", "SIMPLE_VAR_MATCH_RE", ".", "call", "(", "@name", ")", "else", "directory", "=", "@file_path", "regexp", "=", "VAR_FILE_MATCH_RE", "end", "hsh", "=", "{", "}", "Dir", ".", "foreach", "(", "directory", ")", "do", "|", "file", "|", "if", "file", "&&", "match", "=", "regexp", ".", "match", "(", "file", ")", "locale", "=", "match", "[", "'locale'", "]", "||", "I18n", ".", "default_locale", "hsh", "[", "locale", ".", "to_sym", "]", "=", "File", ".", "join", "(", "directory", ",", "file", ")", "end", "end", "hsh", "end"], "docstring": "VARIABLES\n Variables are associated with a page, but unlike properties they are not\n inheritable. Variables are defined in a separate file.", "docstring_tokens": ["VARIABLES", "Variables", "are", "associated", "with", "a", "page", "but", "unlike", "properties", "they", "are", "not", "inheritable", ".", "Variables", "are", "defined", "in", "a", "separate", "file", "."], "sha": "09452da4c756f5edf5e15e19bb3b1079c5f16480", "url": "https://github.com/leapcode/amber/blob/09452da4c756f5edf5e15e19bb3b1079c5f16480/lib/amber/static_page/filesystem.rb#L331-L347", "partition": "test"} {"repo": "leapcode/amber", "path": "lib/amber/menu.rb", "func_name": "Amber.Menu.last_menu_at_depth", "original_string": "def last_menu_at_depth(depth)\n menu = self\n depth.times { menu = menu.children.last }\n menu\n end", "language": "ruby", "code": "def last_menu_at_depth(depth)\n menu = self\n depth.times { menu = menu.children.last }\n menu\n end", "code_tokens": ["def", "last_menu_at_depth", "(", "depth", ")", "menu", "=", "self", "depth", ".", "times", "{", "menu", "=", "menu", ".", "children", ".", "last", "}", "menu", "end"], "docstring": "returns the last list of children at the specified depth", "docstring_tokens": ["returns", "the", "last", "list", "of", "children", "at", "the", "specified", "depth"], "sha": "09452da4c756f5edf5e15e19bb3b1079c5f16480", "url": "https://github.com/leapcode/amber/blob/09452da4c756f5edf5e15e19bb3b1079c5f16480/lib/amber/menu.rb#L134-L138", "partition": "test"} {"repo": "leapcode/amber", "path": "lib/amber/render/table_of_contents.rb", "func_name": "Amber::Render.TableOfContents.nameize", "original_string": "def nameize(str)\n str = str.dup\n str.gsub!(/&(\\w{2,6}?|#[0-9A-Fa-f]{2,6});/,'') # remove html entitities\n str.gsub!(/[^- [[:word:]]]/u, '') # remove non-word characters (using unicode definition of a word char)\n str.strip!\n str.downcase! # upper case characters in urls are confusing\n str.gsub!(/\\ +/u, '-') # spaces to dashes, preferred separator char everywhere\n CGI.escape(str)\n end", "language": "ruby", "code": "def nameize(str)\n str = str.dup\n str.gsub!(/&(\\w{2,6}?|#[0-9A-Fa-f]{2,6});/,'') # remove html entitities\n str.gsub!(/[^- [[:word:]]]/u, '') # remove non-word characters (using unicode definition of a word char)\n str.strip!\n str.downcase! # upper case characters in urls are confusing\n str.gsub!(/\\ +/u, '-') # spaces to dashes, preferred separator char everywhere\n CGI.escape(str)\n end", "code_tokens": ["def", "nameize", "(", "str", ")", "str", "=", "str", ".", "dup", "str", ".", "gsub!", "(", "/", "\\w", "/", ",", "''", ")", "# remove html entitities", "str", ".", "gsub!", "(", "/", "/u", ",", "''", ")", "# remove non-word characters (using unicode definition of a word char)", "str", ".", "strip!", "str", ".", "downcase!", "# upper case characters in urls are confusing", "str", ".", "gsub!", "(", "/", "\\ ", "/u", ",", "'-'", ")", "# spaces to dashes, preferred separator char everywhere", "CGI", ".", "escape", "(", "str", ")", "end"], "docstring": "convert any string to one suitable for a url.\n resist the urge to translit non-ascii slugs to ascii.\n it is always much better to keep strings as utf8.", "docstring_tokens": ["convert", "any", "string", "to", "one", "suitable", "for", "a", "url", ".", "resist", "the", "urge", "to", "translit", "non", "-", "ascii", "slugs", "to", "ascii", ".", "it", "is", "always", "much", "better", "to", "keep", "strings", "as", "utf8", "."], "sha": "09452da4c756f5edf5e15e19bb3b1079c5f16480", "url": "https://github.com/leapcode/amber/blob/09452da4c756f5edf5e15e19bb3b1079c5f16480/lib/amber/render/table_of_contents.rb#L85-L93", "partition": "test"} {"repo": "leapcode/amber", "path": "lib/amber/render/table_of_contents.rb", "func_name": "Amber::Render.TableOfContents.strip_html_tags", "original_string": "def strip_html_tags(html)\n Nokogiri::HTML::DocumentFragment.parse(html, 'UTF-8').children.collect{|child| child.inner_text}.join\n end", "language": "ruby", "code": "def strip_html_tags(html)\n Nokogiri::HTML::DocumentFragment.parse(html, 'UTF-8').children.collect{|child| child.inner_text}.join\n end", "code_tokens": ["def", "strip_html_tags", "(", "html", ")", "Nokogiri", "::", "HTML", "::", "DocumentFragment", ".", "parse", "(", "html", ",", "'UTF-8'", ")", ".", "children", ".", "collect", "{", "|", "child", "|", "child", ".", "inner_text", "}", ".", "join", "end"], "docstring": "removes all html markup", "docstring_tokens": ["removes", "all", "html", "markup"], "sha": "09452da4c756f5edf5e15e19bb3b1079c5f16480", "url": "https://github.com/leapcode/amber/blob/09452da4c756f5edf5e15e19bb3b1079c5f16480/lib/amber/render/table_of_contents.rb#L96-L98", "partition": "test"} {"repo": "leapcode/amber", "path": "lib/amber/render/table_of_contents.rb", "func_name": "Amber::Render.TocItem.populate_node", "original_string": "def populate_node(node, options)\n @children.each do |item|\n li = node.document.create_element(\"li\")\n li.add_child(li.document.create_element(\"a\", item.text, :href => \"#{options[:href_base]}##{item.anchor}\"))\n if item.children.any?\n ul = li.document.create_element(options[:tag])\n item.populate_node(ul, options)\n li.add_child(ul)\n end\n node.add_child(li)\n end\n end", "language": "ruby", "code": "def populate_node(node, options)\n @children.each do |item|\n li = node.document.create_element(\"li\")\n li.add_child(li.document.create_element(\"a\", item.text, :href => \"#{options[:href_base]}##{item.anchor}\"))\n if item.children.any?\n ul = li.document.create_element(options[:tag])\n item.populate_node(ul, options)\n li.add_child(ul)\n end\n node.add_child(li)\n end\n end", "code_tokens": ["def", "populate_node", "(", "node", ",", "options", ")", "@children", ".", "each", "do", "|", "item", "|", "li", "=", "node", ".", "document", ".", "create_element", "(", "\"li\"", ")", "li", ".", "add_child", "(", "li", ".", "document", ".", "create_element", "(", "\"a\"", ",", "item", ".", "text", ",", ":href", "=>", "\"#{options[:href_base]}##{item.anchor}\"", ")", ")", "if", "item", ".", "children", ".", "any?", "ul", "=", "li", ".", "document", ".", "create_element", "(", "options", "[", ":tag", "]", ")", "item", ".", "populate_node", "(", "ul", ",", "options", ")", "li", ".", "add_child", "(", "ul", ")", "end", "node", ".", "add_child", "(", "li", ")", "end", "end"], "docstring": "generates nokogiri html node tree from this toc", "docstring_tokens": ["generates", "nokogiri", "html", "node", "tree", "from", "this", "toc"], "sha": "09452da4c756f5edf5e15e19bb3b1079c5f16480", "url": "https://github.com/leapcode/amber/blob/09452da4c756f5edf5e15e19bb3b1079c5f16480/lib/amber/render/table_of_contents.rb#L218-L229", "partition": "test"} {"repo": "leapcode/amber", "path": "lib/amber/render/table_of_contents.rb", "func_name": "Amber::Render.TocItem.to_html", "original_string": "def to_html(options={})\n html = []\n tag = options[:tag]\n indent = options[:indent] || 0\n str = options[:indent_str] || \" \"\n html << '%s<%s>' % [(str*indent), tag]\n @children.each do |item|\n html << '%s
  • ' % (str*(indent+1))\n html << '%s%s' % [str*(indent+2), options[:href_base], item.anchor, item.text]\n if item.children.any?\n html << item.to_html({\n :indent => indent+2,\n :indent_str => str,\n :tag => tag,\n :href_base => options[:href_base]\n })\n end\n html << '%s
  • ' % (str*(indent+1))\n end\n html << '%s' % [(str*indent), tag]\n html.join(\"\\n\")\n end", "language": "ruby", "code": "def to_html(options={})\n html = []\n tag = options[:tag]\n indent = options[:indent] || 0\n str = options[:indent_str] || \" \"\n html << '%s<%s>' % [(str*indent), tag]\n @children.each do |item|\n html << '%s
  • ' % (str*(indent+1))\n html << '%s%s' % [str*(indent+2), options[:href_base], item.anchor, item.text]\n if item.children.any?\n html << item.to_html({\n :indent => indent+2,\n :indent_str => str,\n :tag => tag,\n :href_base => options[:href_base]\n })\n end\n html << '%s
  • ' % (str*(indent+1))\n end\n html << '%s' % [(str*indent), tag]\n html.join(\"\\n\")\n end", "code_tokens": ["def", "to_html", "(", "options", "=", "{", "}", ")", "html", "=", "[", "]", "tag", "=", "options", "[", ":tag", "]", "indent", "=", "options", "[", ":indent", "]", "||", "0", "str", "=", "options", "[", ":indent_str", "]", "||", "\" \"", "html", "<<", "'%s<%s>'", "%", "[", "(", "str", "indent", ")", ",", "tag", "]", "@children", ".", "each", "do", "|", "item", "|", "html", "<<", "'%s
  • '", "%", "(", "str", "(", "indent", "+", "1", ")", ")", "html", "<<", "'%s%s'", "%", "[", "str", "(", "indent", "+", "2", ")", ",", "options", "[", ":href_base", "]", ",", "item", ".", "anchor", ",", "item", ".", "text", "]", "if", "item", ".", "children", ".", "any?", "html", "<<", "item", ".", "to_html", "(", "{", ":indent", "=>", "indent", "+", "2", ",", ":indent_str", "=>", "str", ",", ":tag", "=>", "tag", ",", ":href_base", "=>", "options", "[", ":href_base", "]", "}", ")", "end", "html", "<<", "'%s
  • '", "%", "(", "str", "(", "indent", "+", "1", ")", ")", "end", "html", "<<", "'%s'", "%", "[", "(", "str", "indent", ")", ",", "tag", "]", "html", ".", "join", "(", "\"\\n\"", ")", "end"], "docstring": "generates html string from this toc", "docstring_tokens": ["generates", "html", "string", "from", "this", "toc"], "sha": "09452da4c756f5edf5e15e19bb3b1079c5f16480", "url": "https://github.com/leapcode/amber/blob/09452da4c756f5edf5e15e19bb3b1079c5f16480/lib/amber/render/table_of_contents.rb#L234-L255", "partition": "test"} {"repo": "leapcode/amber", "path": "lib/amber/render/table_of_contents.rb", "func_name": "Amber::Render.TocItem.parent_for", "original_string": "def parent_for(heading)\n heading = heading[1].to_i if heading.is_a?(String)\n if children.any? && children.last.level < heading\n children.last.parent_for(heading)\n else\n self\n end\n end", "language": "ruby", "code": "def parent_for(heading)\n heading = heading[1].to_i if heading.is_a?(String)\n if children.any? && children.last.level < heading\n children.last.parent_for(heading)\n else\n self\n end\n end", "code_tokens": ["def", "parent_for", "(", "heading", ")", "heading", "=", "heading", "[", "1", "]", ".", "to_i", "if", "heading", ".", "is_a?", "(", "String", ")", "if", "children", ".", "any?", "&&", "children", ".", "last", ".", "level", "<", "heading", "children", ".", "last", ".", "parent_for", "(", "heading", ")", "else", "self", "end", "end"], "docstring": "Returns the appropriate TocItem for appending a new item\n at a particular heading level.", "docstring_tokens": ["Returns", "the", "appropriate", "TocItem", "for", "appending", "a", "new", "item", "at", "a", "particular", "heading", "level", "."], "sha": "09452da4c756f5edf5e15e19bb3b1079c5f16480", "url": "https://github.com/leapcode/amber/blob/09452da4c756f5edf5e15e19bb3b1079c5f16480/lib/amber/render/table_of_contents.rb#L261-L268", "partition": "test"} {"repo": "sinisterchipmunk/eve", "path": "lib/eve/javascript_helper.rb", "func_name": "Eve.JavascriptHelper.type_id", "original_string": "def type_id(which)\n which = which.to_s.humanize unless which.kind_of?(String)\n which.downcase!\n case which\n when 'alliance' then 16159\n when 'character' then 1377\n when 'corporation' then 2\n when 'constellation' then 4\n when 'region' then 3\n when 'solar system', 'solarsystem' then 5\n when 'station' then 3867\n else raise ArgumentError, \"Unknown type: #{which}\"\n end\n end", "language": "ruby", "code": "def type_id(which)\n which = which.to_s.humanize unless which.kind_of?(String)\n which.downcase!\n case which\n when 'alliance' then 16159\n when 'character' then 1377\n when 'corporation' then 2\n when 'constellation' then 4\n when 'region' then 3\n when 'solar system', 'solarsystem' then 5\n when 'station' then 3867\n else raise ArgumentError, \"Unknown type: #{which}\"\n end\n end", "code_tokens": ["def", "type_id", "(", "which", ")", "which", "=", "which", ".", "to_s", ".", "humanize", "unless", "which", ".", "kind_of?", "(", "String", ")", "which", ".", "downcase!", "case", "which", "when", "'alliance'", "then", "16159", "when", "'character'", "then", "1377", "when", "'corporation'", "then", "2", "when", "'constellation'", "then", "4", "when", "'region'", "then", "3", "when", "'solar system'", ",", "'solarsystem'", "then", "5", "when", "'station'", "then", "3867", "else", "raise", "ArgumentError", ",", "\"Unknown type: #{which}\"", "end", "end"], "docstring": "Returns the numeric type ID for a string, so you don't have to manage \"magic numbers\" in your application.\n The argument can be a string or a symbol, and is case insensitive. Underscores will be converted to spaces.\n\n Examples:\n type_id('alliance') # => 16159\n type_id('character') # => 1377\n type_id('corporation') # => 2\n type_id('constellation') # => 4\n type_id('region') # => 3\n type_id('Solar System') # => 5\n type_id(:solar_system) # => 5\n type_id(:station) # => 3867", "docstring_tokens": ["Returns", "the", "numeric", "type", "ID", "for", "a", "string", "so", "you", "don", "t", "have", "to", "manage", "magic", "numbers", "in", "your", "application", ".", "The", "argument", "can", "be", "a", "string", "or", "a", "symbol", "and", "is", "case", "insensitive", ".", "Underscores", "will", "be", "converted", "to", "spaces", "."], "sha": "e473a0d7b1a6991d2c4afbd07ce39d8b88dfba2c", "url": "https://github.com/sinisterchipmunk/eve/blob/e473a0d7b1a6991d2c4afbd07ce39d8b88dfba2c/lib/eve/javascript_helper.rb#L18-L31", "partition": "test"} {"repo": "sinisterchipmunk/eve", "path": "lib/eve/javascript_helper.rb", "func_name": "Eve.JavascriptHelper.link_to_info", "original_string": "def link_to_info(text, type_id, item_id = nil, *args)\n function = \"CCPEVE.showInfo(#{type_id.inspect}\"\n function.concat \", #{item_id.inspect}\" if item_id\n function.concat \")\"\n link_to_function text, function, *args\n end", "language": "ruby", "code": "def link_to_info(text, type_id, item_id = nil, *args)\n function = \"CCPEVE.showInfo(#{type_id.inspect}\"\n function.concat \", #{item_id.inspect}\" if item_id\n function.concat \")\"\n link_to_function text, function, *args\n end", "code_tokens": ["def", "link_to_info", "(", "text", ",", "type_id", ",", "item_id", "=", "nil", ",", "*", "args", ")", "function", "=", "\"CCPEVE.showInfo(#{type_id.inspect}\"", "function", ".", "concat", "\", #{item_id.inspect}\"", "if", "item_id", "function", ".", "concat", "\")\"", "link_to_function", "text", ",", "function", ",", "args", "end"], "docstring": "Creates a hyperlink that results in the \"show info\" dialog being displayed on the client's screen.\n If item_id is given, the show info window will open for that item.\n\n type_id (Number)\n Type ID of item to show info on.\n item_id (Number)\n Optional item ID of specific item of type type_id to show info on. This is required for specific types of\n items, such as solar systems, stations, regions, and constellations.", "docstring_tokens": ["Creates", "a", "hyperlink", "that", "results", "in", "the", "show", "info", "dialog", "being", "displayed", "on", "the", "client", "s", "screen", ".", "If", "item_id", "is", "given", "the", "show", "info", "window", "will", "open", "for", "that", "item", "."], "sha": "e473a0d7b1a6991d2c4afbd07ce39d8b88dfba2c", "url": "https://github.com/sinisterchipmunk/eve/blob/e473a0d7b1a6991d2c4afbd07ce39d8b88dfba2c/lib/eve/javascript_helper.rb#L47-L52", "partition": "test"} {"repo": "sinisterchipmunk/eve", "path": "lib/eve/javascript_helper.rb", "func_name": "Eve.JavascriptHelper.link_to_route", "original_string": "def link_to_route(text, destination_id, source_id = nil, *args)\n function = \"CCPEVE.showRouteTo(#{destination_id.inspect}\"\n function.concat \", #{source_id.inspect}\" if source_id\n function.concat \")\"\n link_to_function text, function, *args\n end", "language": "ruby", "code": "def link_to_route(text, destination_id, source_id = nil, *args)\n function = \"CCPEVE.showRouteTo(#{destination_id.inspect}\"\n function.concat \", #{source_id.inspect}\" if source_id\n function.concat \")\"\n link_to_function text, function, *args\n end", "code_tokens": ["def", "link_to_route", "(", "text", ",", "destination_id", ",", "source_id", "=", "nil", ",", "*", "args", ")", "function", "=", "\"CCPEVE.showRouteTo(#{destination_id.inspect}\"", "function", ".", "concat", "\", #{source_id.inspect}\"", "if", "source_id", "function", ".", "concat", "\")\"", "link_to_function", "text", ",", "function", ",", "args", "end"], "docstring": "Creates a hyperlink that results in showing the route to the destination_id from the source_id.\n If source_id is not given, the source system is taken to be the system the user is currently in.", "docstring_tokens": ["Creates", "a", "hyperlink", "that", "results", "in", "showing", "the", "route", "to", "the", "destination_id", "from", "the", "source_id", ".", "If", "source_id", "is", "not", "given", "the", "source", "system", "is", "taken", "to", "be", "the", "system", "the", "user", "is", "currently", "in", "."], "sha": "e473a0d7b1a6991d2c4afbd07ce39d8b88dfba2c", "url": "https://github.com/sinisterchipmunk/eve/blob/e473a0d7b1a6991d2c4afbd07ce39d8b88dfba2c/lib/eve/javascript_helper.rb#L66-L71", "partition": "test"} {"repo": "sinisterchipmunk/eve", "path": "lib/eve/javascript_helper.rb", "func_name": "Eve.JavascriptHelper.link_to_trust_request", "original_string": "def link_to_trust_request(text, trust_url = \"http://#{request.host}/\", *args)\n trust_url = url_for(trust_url.merge(:only_path => false)) if trust_url.kind_of?(Hash)\n link_to_function text, \"CCPEVE.requestTrust(#{trust_url.inspect})\", *args\n end", "language": "ruby", "code": "def link_to_trust_request(text, trust_url = \"http://#{request.host}/\", *args)\n trust_url = url_for(trust_url.merge(:only_path => false)) if trust_url.kind_of?(Hash)\n link_to_function text, \"CCPEVE.requestTrust(#{trust_url.inspect})\", *args\n end", "code_tokens": ["def", "link_to_trust_request", "(", "text", ",", "trust_url", "=", "\"http://#{request.host}/\"", ",", "*", "args", ")", "trust_url", "=", "url_for", "(", "trust_url", ".", "merge", "(", ":only_path", "=>", "false", ")", ")", "if", "trust_url", ".", "kind_of?", "(", "Hash", ")", "link_to_function", "text", ",", "\"CCPEVE.requestTrust(#{trust_url.inspect})\"", ",", "args", "end"], "docstring": "Produces a hyperlink that will result in a pop-up a trust prompt in the client, allowing the user to either\n grant the trust request, ignore it, or always ignore trust requests from your site.\n\n trust_url (String)\n This is a fully-qualified domain name and path (e.g. http://wiki.eveonline.com/w/) to which your site would\n like the user to grant trust.\n\n The page will not be automatically refreshed if the user grants the trust request. Trust will take effect the\n next time the user refreshes the page, or navigates within the site.\n\n Note that trust_url is processed and only the protocol, domain and path will be used from it. If you supply a\n query string or anchor, they will be discarded. It is recommended that you primarily pass in only\n fully-qualified domain names without paths (e.g. http://wiki.eveonline.com instead of\n http://wiki.eveonline.com/w/index.php), as this avoids pestering the user for trust on every page.", "docstring_tokens": ["Produces", "a", "hyperlink", "that", "will", "result", "in", "a", "pop", "-", "up", "a", "trust", "prompt", "in", "the", "client", "allowing", "the", "user", "to", "either", "grant", "the", "trust", "request", "ignore", "it", "or", "always", "ignore", "trust", "requests", "from", "your", "site", "."], "sha": "e473a0d7b1a6991d2c4afbd07ce39d8b88dfba2c", "url": "https://github.com/sinisterchipmunk/eve/blob/e473a0d7b1a6991d2c4afbd07ce39d8b88dfba2c/lib/eve/javascript_helper.rb#L129-L132", "partition": "test"} {"repo": "sinisterchipmunk/eve", "path": "lib/eve/javascript_helper.rb", "func_name": "Eve.JavascriptHelper.request_trust", "original_string": "def request_trust(trust_url = \"http://#{request.host}/\", *args)\n trust_url = url_for(trust_url.merge(:only_path => false)) if trust_url.kind_of?(Hash)\n javascript_tag \"CCPEVE.requestTrust(#{trust_url.inspect});\", *args\n end", "language": "ruby", "code": "def request_trust(trust_url = \"http://#{request.host}/\", *args)\n trust_url = url_for(trust_url.merge(:only_path => false)) if trust_url.kind_of?(Hash)\n javascript_tag \"CCPEVE.requestTrust(#{trust_url.inspect});\", *args\n end", "code_tokens": ["def", "request_trust", "(", "trust_url", "=", "\"http://#{request.host}/\"", ",", "*", "args", ")", "trust_url", "=", "url_for", "(", "trust_url", ".", "merge", "(", ":only_path", "=>", "false", ")", ")", "if", "trust_url", ".", "kind_of?", "(", "Hash", ")", "javascript_tag", "\"CCPEVE.requestTrust(#{trust_url.inspect});\"", ",", "args", "end"], "docstring": "This will generate a method call that produces a pop-up a trust prompt in the client, allowing the user to\n either grant the trust request, ignore it, or always ignore trust requests from your site.\n\n trust_url (String)\n This is a fully-qualified domain name and path (e.g. http://wiki.eveonline.com/w/) to which your site would\n like the user to grant trust.\n\n The page will not be automatically refreshed if the user grants the trust request. Trust will take effect the\n next time the user refreshes the page, or navigates within the site.\n\n Note that trust_url is processed and only the protocol, domain and path will be used from it. If you supply a\n query string or anchor, they will be discarded. It is recommended that you primarily pass in only\n fully-qualified domain names without paths (e.g. http://wiki.eveonline.com instead of\n http://wiki.eveonline.com/w/index.php), as this avoids pestering the user for trust on every page.", "docstring_tokens": ["This", "will", "generate", "a", "method", "call", "that", "produces", "a", "pop", "-", "up", "a", "trust", "prompt", "in", "the", "client", "allowing", "the", "user", "to", "either", "grant", "the", "trust", "request", "ignore", "it", "or", "always", "ignore", "trust", "requests", "from", "your", "site", "."], "sha": "e473a0d7b1a6991d2c4afbd07ce39d8b88dfba2c", "url": "https://github.com/sinisterchipmunk/eve/blob/e473a0d7b1a6991d2c4afbd07ce39d8b88dfba2c/lib/eve/javascript_helper.rb#L149-L152", "partition": "test"} {"repo": "leapcode/amber", "path": "lib/amber/static_page/render.rb", "func_name": "Amber.StaticPage.render_to_file", "original_string": "def render_to_file(dest_dir, options={})\n render_content_files(dest_dir, options)\n render_assets(dest_dir)\n @props.locales.each do |locale|\n if aliases(locale).any?\n link_page_aliases(dest_dir, aliases(locale), locale)\n end\n end\n end", "language": "ruby", "code": "def render_to_file(dest_dir, options={})\n render_content_files(dest_dir, options)\n render_assets(dest_dir)\n @props.locales.each do |locale|\n if aliases(locale).any?\n link_page_aliases(dest_dir, aliases(locale), locale)\n end\n end\n end", "code_tokens": ["def", "render_to_file", "(", "dest_dir", ",", "options", "=", "{", "}", ")", "render_content_files", "(", "dest_dir", ",", "options", ")", "render_assets", "(", "dest_dir", ")", "@props", ".", "locales", ".", "each", "do", "|", "locale", "|", "if", "aliases", "(", "locale", ")", ".", "any?", "link_page_aliases", "(", "dest_dir", ",", "aliases", "(", "locale", ")", ",", "locale", ")", "end", "end", "end"], "docstring": "render without layout, possibly with via a rails request\n\n RAILS\n def render_to_string(renderer=nil)\n begin\n render_locale(renderer, I18n.locale)\n rescue ActionView::MissingTemplate, MissingTemplate => exc\n begin\n render_locale(renderer, I18n.default_locale)\n rescue\n Amber.logger.error \"ERROR: could not file template path #{self.template_path}\"\n raise exc\n end\n end\n end\n\n render a static copy\n\n dest_dir - e.g. amber_root/public/", "docstring_tokens": ["render", "without", "layout", "possibly", "with", "via", "a", "rails", "request"], "sha": "09452da4c756f5edf5e15e19bb3b1079c5f16480", "url": "https://github.com/leapcode/amber/blob/09452da4c756f5edf5e15e19bb3b1079c5f16480/lib/amber/static_page/render.rb#L34-L42", "partition": "test"} {"repo": "leapcode/amber", "path": "lib/amber/static_page/render.rb", "func_name": "Amber.StaticPage.symlink", "original_string": "def symlink(from_path, to_path)\n to_path = realpath(to_path)\n target = from_path.relative_path_from(to_path).to_s.sub(/^\\.\\.\\//, '')\n if !to_path.dirname.directory?\n Amber.logger.warn { \"On page `#{@file_path}`, the parent directories for alias name `#{to_path}` don't exist. Skipping alias.\" }\n return\n end\n if to_path.exist? && to_path.symlink?\n File.unlink(to_path)\n end\n if !to_path.exist?\n Amber.logger.debug { \"Symlink #{to_path} => #{target}\" }\n FileUtils.ln_s(target, to_path)\n end\n end", "language": "ruby", "code": "def symlink(from_path, to_path)\n to_path = realpath(to_path)\n target = from_path.relative_path_from(to_path).to_s.sub(/^\\.\\.\\//, '')\n if !to_path.dirname.directory?\n Amber.logger.warn { \"On page `#{@file_path}`, the parent directories for alias name `#{to_path}` don't exist. Skipping alias.\" }\n return\n end\n if to_path.exist? && to_path.symlink?\n File.unlink(to_path)\n end\n if !to_path.exist?\n Amber.logger.debug { \"Symlink #{to_path} => #{target}\" }\n FileUtils.ln_s(target, to_path)\n end\n end", "code_tokens": ["def", "symlink", "(", "from_path", ",", "to_path", ")", "to_path", "=", "realpath", "(", "to_path", ")", "target", "=", "from_path", ".", "relative_path_from", "(", "to_path", ")", ".", "to_s", ".", "sub", "(", "/", "\\.", "\\.", "\\/", "/", ",", "''", ")", "if", "!", "to_path", ".", "dirname", ".", "directory?", "Amber", ".", "logger", ".", "warn", "{", "\"On page `#{@file_path}`, the parent directories for alias name `#{to_path}` don't exist. Skipping alias.\"", "}", "return", "end", "if", "to_path", ".", "exist?", "&&", "to_path", ".", "symlink?", "File", ".", "unlink", "(", "to_path", ")", "end", "if", "!", "to_path", ".", "exist?", "Amber", ".", "logger", ".", "debug", "{", "\"Symlink #{to_path} => #{target}\"", "}", "FileUtils", ".", "ln_s", "(", "target", ",", "to_path", ")", "end", "end"], "docstring": "create a symlink. arguments must be of type Pathname.", "docstring_tokens": ["create", "a", "symlink", ".", "arguments", "must", "be", "of", "type", "Pathname", "."], "sha": "09452da4c756f5edf5e15e19bb3b1079c5f16480", "url": "https://github.com/leapcode/amber/blob/09452da4c756f5edf5e15e19bb3b1079c5f16480/lib/amber/static_page/render.rb#L93-L107", "partition": "test"} {"repo": "leapcode/amber", "path": "lib/amber/static_page/render.rb", "func_name": "Amber.StaticPage.render_content_files", "original_string": "def render_content_files(dest_dir, options)\n view = Render::View.new(self, @config)\n @config.locales.each do |file_locale|\n content_file = content_file(file_locale)\n next unless content_file\n dest = destination_file(dest_dir, file_locale)\n unless Dir.exist?(File.dirname(dest))\n FileUtils.mkdir_p(File.dirname(dest))\n end\n if options[:force] || !File.exist?(dest) || File.mtime(content_file) > File.mtime(dest)\n File.open(dest, 'w') do |f|\n layout = @props.layout || 'default'\n f.write view.render({page: self, layout: layout}, {locale: file_locale})\n end\n end\n end\n end", "language": "ruby", "code": "def render_content_files(dest_dir, options)\n view = Render::View.new(self, @config)\n @config.locales.each do |file_locale|\n content_file = content_file(file_locale)\n next unless content_file\n dest = destination_file(dest_dir, file_locale)\n unless Dir.exist?(File.dirname(dest))\n FileUtils.mkdir_p(File.dirname(dest))\n end\n if options[:force] || !File.exist?(dest) || File.mtime(content_file) > File.mtime(dest)\n File.open(dest, 'w') do |f|\n layout = @props.layout || 'default'\n f.write view.render({page: self, layout: layout}, {locale: file_locale})\n end\n end\n end\n end", "code_tokens": ["def", "render_content_files", "(", "dest_dir", ",", "options", ")", "view", "=", "Render", "::", "View", ".", "new", "(", "self", ",", "@config", ")", "@config", ".", "locales", ".", "each", "do", "|", "file_locale", "|", "content_file", "=", "content_file", "(", "file_locale", ")", "next", "unless", "content_file", "dest", "=", "destination_file", "(", "dest_dir", ",", "file_locale", ")", "unless", "Dir", ".", "exist?", "(", "File", ".", "dirname", "(", "dest", ")", ")", "FileUtils", ".", "mkdir_p", "(", "File", ".", "dirname", "(", "dest", ")", ")", "end", "if", "options", "[", ":force", "]", "||", "!", "File", ".", "exist?", "(", "dest", ")", "||", "File", ".", "mtime", "(", "content_file", ")", ">", "File", ".", "mtime", "(", "dest", ")", "File", ".", "open", "(", "dest", ",", "'w'", ")", "do", "|", "f", "|", "layout", "=", "@props", ".", "layout", "||", "'default'", "f", ".", "write", "view", ".", "render", "(", "{", "page", ":", "self", ",", "layout", ":", "layout", "}", ",", "{", "locale", ":", "file_locale", "}", ")", "end", "end", "end", "end"], "docstring": "called only by render_to_file", "docstring_tokens": ["called", "only", "by", "render_to_file"], "sha": "09452da4c756f5edf5e15e19bb3b1079c5f16480", "url": "https://github.com/leapcode/amber/blob/09452da4c756f5edf5e15e19bb3b1079c5f16480/lib/amber/static_page/render.rb#L119-L135", "partition": "test"} {"repo": "paradox460/snoo", "path": "lib/snoo/users.rb", "func_name": "Snoo.User.friend", "original_string": "def friend name, friend_id, note = nil\n friend_wrapper(api_name = name, api_container = @userid, api_note = note, api_type = \"friend\")\n end", "language": "ruby", "code": "def friend name, friend_id, note = nil\n friend_wrapper(api_name = name, api_container = @userid, api_note = note, api_type = \"friend\")\n end", "code_tokens": ["def", "friend", "name", ",", "friend_id", ",", "note", "=", "nil", "friend_wrapper", "(", "api_name", "=", "name", ",", "api_container", "=", "@userid", ",", "api_note", "=", "note", ",", "api_type", "=", "\"friend\"", ")", "end"], "docstring": "Friend a user\n\n @param name [String] The username to target\n @param note [String] A friend tag. Requires reddit gold.\n @return (see #clear_sessions)", "docstring_tokens": ["Friend", "a", "user"], "sha": "83cbfe4973eeff5a0c7426f4a23457a420273261", "url": "https://github.com/paradox460/snoo/blob/83cbfe4973eeff5a0c7426f4a23457a420273261/lib/snoo/users.rb#L12-L14", "partition": "test"} {"repo": "paradox460/snoo", "path": "lib/snoo/users.rb", "func_name": "Snoo.User.get_user_listing", "original_string": "def get_user_listing username, opts = {}\n opts[:type] = 'overview' if opts[:type].nil?\n url = \"/user/%s%s.json\" % [username, ('/' + opts[:type] if opts[:type] != 'overview')]\n opts.delete :type\n query = opts\n get(url, query: query)\n end", "language": "ruby", "code": "def get_user_listing username, opts = {}\n opts[:type] = 'overview' if opts[:type].nil?\n url = \"/user/%s%s.json\" % [username, ('/' + opts[:type] if opts[:type] != 'overview')]\n opts.delete :type\n query = opts\n get(url, query: query)\n end", "code_tokens": ["def", "get_user_listing", "username", ",", "opts", "=", "{", "}", "opts", "[", ":type", "]", "=", "'overview'", "if", "opts", "[", ":type", "]", ".", "nil?", "url", "=", "\"/user/%s%s.json\"", "%", "[", "username", ",", "(", "'/'", "+", "opts", "[", ":type", "]", "if", "opts", "[", ":type", "]", "!=", "'overview'", ")", "]", "opts", ".", "delete", ":type", "query", "=", "opts", "get", "(", "url", ",", "query", ":", "query", ")", "end"], "docstring": "Get a listing of user posts. Some options may be restricted\n\n @param (see #get_user_info)\n @param (see LinksComments#info)\n @option opts [overview, submitted, comments, liked, disliked, hidden, saved] :type Type of post to return. Most users only allow the first 3 types.\n @option opts [new, hot, top, controversial] :sort The sort order\n @option opts [String] :after Return things *after* this id\n @option opts [String] :before Return things *before* this id\n @option opts [1..100] :limit Number of results to return\n @return (see #clear_sessions)", "docstring_tokens": ["Get", "a", "listing", "of", "user", "posts", ".", "Some", "options", "may", "be", "restricted"], "sha": "83cbfe4973eeff5a0c7426f4a23457a420273261", "url": "https://github.com/paradox460/snoo/blob/83cbfe4973eeff5a0c7426f4a23457a420273261/lib/snoo/users.rb#L49-L55", "partition": "test"} {"repo": "paradox460/snoo", "path": "lib/snoo/links_comments.rb", "func_name": "Snoo.LinksComments.comment", "original_string": "def comment text, id\n logged_in?\n post('/api/comment', body: { text: text, thing_id: id, uh: @modhash, api_type: 'json'})\n end", "language": "ruby", "code": "def comment text, id\n logged_in?\n post('/api/comment', body: { text: text, thing_id: id, uh: @modhash, api_type: 'json'})\n end", "code_tokens": ["def", "comment", "text", ",", "id", "logged_in?", "post", "(", "'/api/comment'", ",", "body", ":", "{", "text", ":", "text", ",", "thing_id", ":", "id", ",", "uh", ":", "@modhash", ",", "api_type", ":", "'json'", "}", ")", "end"], "docstring": "Posts a comment to the site\n\n @param text [String] The comment text, formatted as markdown\n @param id [String] The parent object id. Should be a comment or link\n @return (see #clear_sessions)", "docstring_tokens": ["Posts", "a", "comment", "to", "the", "site"], "sha": "83cbfe4973eeff5a0c7426f4a23457a420273261", "url": "https://github.com/paradox460/snoo/blob/83cbfe4973eeff5a0c7426f4a23457a420273261/lib/snoo/links_comments.rb#L12-L15", "partition": "test"} {"repo": "paradox460/snoo", "path": "lib/snoo/links_comments.rb", "func_name": "Snoo.LinksComments.submit", "original_string": "def submit title, subreddit, opts = {}\n logged_in?\n post = {\n title: title,\n sr: subreddit,\n uh: @modhash,\n kind: (opts[:url] ? \"link\" : \"self\"),\n api_type: 'json'\n }\n post.merge! opts\n post('/api/submit', body: post)\n end", "language": "ruby", "code": "def submit title, subreddit, opts = {}\n logged_in?\n post = {\n title: title,\n sr: subreddit,\n uh: @modhash,\n kind: (opts[:url] ? \"link\" : \"self\"),\n api_type: 'json'\n }\n post.merge! opts\n post('/api/submit', body: post)\n end", "code_tokens": ["def", "submit", "title", ",", "subreddit", ",", "opts", "=", "{", "}", "logged_in?", "post", "=", "{", "title", ":", "title", ",", "sr", ":", "subreddit", ",", "uh", ":", "@modhash", ",", "kind", ":", "(", "opts", "[", ":url", "]", "?", "\"link\"", ":", "\"self\"", ")", ",", "api_type", ":", "'json'", "}", "post", ".", "merge!", "opts", "post", "(", "'/api/submit'", ",", "body", ":", "post", ")", "end"], "docstring": "Submit a link or self post\n\n @param title [String] Title of the post\n @param subreddit [String] The subreddit in which we are posting\n @param (see #info)\n @option opts [String] :url The url for the post. If this is specified, it will not be a self post, and `text` will be ignored\n @option opts [String] :text The self-post text. Can be formatted in markdown\n @return (see #clear_sessions)", "docstring_tokens": ["Submit", "a", "link", "or", "self", "post"], "sha": "83cbfe4973eeff5a0c7426f4a23457a420273261", "url": "https://github.com/paradox460/snoo/blob/83cbfe4973eeff5a0c7426f4a23457a420273261/lib/snoo/links_comments.rb#L95-L106", "partition": "test"} {"repo": "paradox460/snoo", "path": "lib/snoo/links_comments.rb", "func_name": "Snoo.LinksComments.vote", "original_string": "def vote direction, id\n logged_in?\n post('/api/vote', body: {id: id, dir: direction, uh: @modhash, api_type: 'json'})\n end", "language": "ruby", "code": "def vote direction, id\n logged_in?\n post('/api/vote', body: {id: id, dir: direction, uh: @modhash, api_type: 'json'})\n end", "code_tokens": ["def", "vote", "direction", ",", "id", "logged_in?", "post", "(", "'/api/vote'", ",", "body", ":", "{", "id", ":", "id", ",", "dir", ":", "direction", ",", "uh", ":", "@modhash", ",", "api_type", ":", "'json'", "}", ")", "end"], "docstring": "Vote on a comment or link\n\n @param direction [-1, 0, 1] The direction to vote in. -1 is a downvote, 1 is an upvote, 0 cancels any vote\n @param id [String] The thing to target.\n @return (see #clear_sessions)", "docstring_tokens": ["Vote", "on", "a", "comment", "or", "link"], "sha": "83cbfe4973eeff5a0c7426f4a23457a420273261", "url": "https://github.com/paradox460/snoo/blob/83cbfe4973eeff5a0c7426f4a23457a420273261/lib/snoo/links_comments.rb#L141-L144", "partition": "test"} {"repo": "seejohnrun/gotcha", "path": "lib/gotcha/base.rb", "func_name": "Gotcha.Base.correct?", "original_string": "def correct?(str)\n str = str.is_a?(String) ? str : str.to_s\n str == (@answer.is_a?(String) ? @answer : @answer.to_s) # don't change @answer type\n end", "language": "ruby", "code": "def correct?(str)\n str = str.is_a?(String) ? str : str.to_s\n str == (@answer.is_a?(String) ? @answer : @answer.to_s) # don't change @answer type\n end", "code_tokens": ["def", "correct?", "(", "str", ")", "str", "=", "str", ".", "is_a?", "(", "String", ")", "?", "str", ":", "str", ".", "to_s", "str", "==", "(", "@answer", ".", "is_a?", "(", "String", ")", "?", "@answer", ":", "@answer", ".", "to_s", ")", "# don't change @answer type", "end"], "docstring": "Determine whether or not an answer is correct", "docstring_tokens": ["Determine", "whether", "or", "not", "an", "answer", "is", "correct"], "sha": "ce250df5ecba7789ba6ea81807c28d59d761439c", "url": "https://github.com/seejohnrun/gotcha/blob/ce250df5ecba7789ba6ea81807c28d59d761439c/lib/gotcha/base.rb#L8-L11", "partition": "test"} {"repo": "seejohnrun/gotcha", "path": "lib/gotcha/form_helpers.rb", "func_name": "Gotcha.FormHelpers.gotcha", "original_string": "def gotcha(options = {})\n options[:label_options] ||= {}\n options[:text_field_options] ||= {}\n if gotcha = Gotcha.random\n field = \"gotcha_response[#{gotcha.class.name.to_s}-#{Digest::MD5.hexdigest(gotcha.class.down_transform(gotcha.answer))}]\"\n (label_tag field, gotcha.question, options[:label_options]) + \"\\n\" + (text_field_tag field, nil, options[:text_field_options])\n else\n raise \"No Gotchas Installed\"\n end\n end", "language": "ruby", "code": "def gotcha(options = {})\n options[:label_options] ||= {}\n options[:text_field_options] ||= {}\n if gotcha = Gotcha.random\n field = \"gotcha_response[#{gotcha.class.name.to_s}-#{Digest::MD5.hexdigest(gotcha.class.down_transform(gotcha.answer))}]\"\n (label_tag field, gotcha.question, options[:label_options]) + \"\\n\" + (text_field_tag field, nil, options[:text_field_options])\n else\n raise \"No Gotchas Installed\"\n end\n end", "code_tokens": ["def", "gotcha", "(", "options", "=", "{", "}", ")", "options", "[", ":label_options", "]", "||=", "{", "}", "options", "[", ":text_field_options", "]", "||=", "{", "}", "if", "gotcha", "=", "Gotcha", ".", "random", "field", "=", "\"gotcha_response[#{gotcha.class.name.to_s}-#{Digest::MD5.hexdigest(gotcha.class.down_transform(gotcha.answer))}]\"", "(", "label_tag", "field", ",", "gotcha", ".", "question", ",", "options", "[", ":label_options", "]", ")", "+", "\"\\n\"", "+", "(", "text_field_tag", "field", ",", "nil", ",", "options", "[", ":text_field_options", "]", ")", "else", "raise", "\"No Gotchas Installed\"", "end", "end"], "docstring": "Propose a gotcha to the user - question and answer hash", "docstring_tokens": ["Propose", "a", "gotcha", "to", "the", "user", "-", "question", "and", "answer", "hash"], "sha": "ce250df5ecba7789ba6ea81807c28d59d761439c", "url": "https://github.com/seejohnrun/gotcha/blob/ce250df5ecba7789ba6ea81807c28d59d761439c/lib/gotcha/form_helpers.rb#L6-L15", "partition": "test"} {"repo": "paradox460/snoo", "path": "lib/snoo/subreddits.rb", "func_name": "Snoo.Subreddit.delete_image", "original_string": "def delete_image subreddit, image_name\n logged_in?\n post('/api/delete_sr_image', body: {r: subreddit, img_name: image_name, uh: @modhash, api_type: 'json'})\n end", "language": "ruby", "code": "def delete_image subreddit, image_name\n logged_in?\n post('/api/delete_sr_image', body: {r: subreddit, img_name: image_name, uh: @modhash, api_type: 'json'})\n end", "code_tokens": ["def", "delete_image", "subreddit", ",", "image_name", "logged_in?", "post", "(", "'/api/delete_sr_image'", ",", "body", ":", "{", "r", ":", "subreddit", ",", "img_name", ":", "image_name", ",", "uh", ":", "@modhash", ",", "api_type", ":", "'json'", "}", ")", "end"], "docstring": "Deletes an image from a subreddit. This is for css, not removing posts\n\n @param (see #delete_header)\n @param image_name [String] the image to delete from the subreddit. Can be obtained via {#get_stylesheet}\n @return (see #clear_sessions)", "docstring_tokens": ["Deletes", "an", "image", "from", "a", "subreddit", ".", "This", "is", "for", "css", "not", "removing", "posts"], "sha": "83cbfe4973eeff5a0c7426f4a23457a420273261", "url": "https://github.com/paradox460/snoo/blob/83cbfe4973eeff5a0c7426f4a23457a420273261/lib/snoo/subreddits.rb#L21-L24", "partition": "test"} {"repo": "paradox460/snoo", "path": "lib/snoo/subreddits.rb", "func_name": "Snoo.Subreddit.set_stylesheet", "original_string": "def set_stylesheet stylesheet, subreddit\n logged_in?\n post('/api/subreddit_stylesheet', body: {op: 'save', r: subreddit, stylesheet_contents: stylesheet, uh: @modhash, api_type: 'json'})\n end", "language": "ruby", "code": "def set_stylesheet stylesheet, subreddit\n logged_in?\n post('/api/subreddit_stylesheet', body: {op: 'save', r: subreddit, stylesheet_contents: stylesheet, uh: @modhash, api_type: 'json'})\n end", "code_tokens": ["def", "set_stylesheet", "stylesheet", ",", "subreddit", "logged_in?", "post", "(", "'/api/subreddit_stylesheet'", ",", "body", ":", "{", "op", ":", "'save'", ",", "r", ":", "subreddit", ",", "stylesheet_contents", ":", "stylesheet", ",", "uh", ":", "@modhash", ",", "api_type", ":", "'json'", "}", ")", "end"], "docstring": "Set the subreddit stylesheet\n\n @param stylesheet [String] The stylesheet for the subreddit. Overwrites the current one\n @param (see #delete_header)\n @return (see #clear_sessions)", "docstring_tokens": ["Set", "the", "subreddit", "stylesheet"], "sha": "83cbfe4973eeff5a0c7426f4a23457a420273261", "url": "https://github.com/paradox460/snoo/blob/83cbfe4973eeff5a0c7426f4a23457a420273261/lib/snoo/subreddits.rb#L72-L75", "partition": "test"} {"repo": "paradox460/snoo", "path": "lib/snoo/subreddits.rb", "func_name": "Snoo.Subreddit.subscribe", "original_string": "def subscribe subreddit, action = \"sub\"\n logged_in?\n post('/api/subscribe', body: {action: action, sr: subreddit, uh: @modhash, api_type: 'json'})\n end", "language": "ruby", "code": "def subscribe subreddit, action = \"sub\"\n logged_in?\n post('/api/subscribe', body: {action: action, sr: subreddit, uh: @modhash, api_type: 'json'})\n end", "code_tokens": ["def", "subscribe", "subreddit", ",", "action", "=", "\"sub\"", "logged_in?", "post", "(", "'/api/subscribe'", ",", "body", ":", "{", "action", ":", "action", ",", "sr", ":", "subreddit", ",", "uh", ":", "@modhash", ",", "api_type", ":", "'json'", "}", ")", "end"], "docstring": "Subscribe to a subreddit\n\n @param (see #delete_header)\n @param action [sub, unsub] Subscribe or unsubscribe\n @return (see #clear_sessions)", "docstring_tokens": ["Subscribe", "to", "a", "subreddit"], "sha": "83cbfe4973eeff5a0c7426f4a23457a420273261", "url": "https://github.com/paradox460/snoo/blob/83cbfe4973eeff5a0c7426f4a23457a420273261/lib/snoo/subreddits.rb#L82-L85", "partition": "test"} {"repo": "paradox460/snoo", "path": "lib/snoo/subreddits.rb", "func_name": "Snoo.Subreddit.my_reddits", "original_string": "def my_reddits opts = {}\n logged_in?\n url = \"/reddits/mine/%s.json\" % (opts[:condition] if opts[:condition])\n opts.delete :condition\n query = opts\n get(url, query: query)\n end", "language": "ruby", "code": "def my_reddits opts = {}\n logged_in?\n url = \"/reddits/mine/%s.json\" % (opts[:condition] if opts[:condition])\n opts.delete :condition\n query = opts\n get(url, query: query)\n end", "code_tokens": ["def", "my_reddits", "opts", "=", "{", "}", "logged_in?", "url", "=", "\"/reddits/mine/%s.json\"", "%", "(", "opts", "[", ":condition", "]", "if", "opts", "[", ":condition", "]", ")", "opts", ".", "delete", ":condition", "query", "=", "opts", "get", "(", "url", ",", "query", ":", "query", ")", "end"], "docstring": "Get subreddits I have\n\n @param (see LinksComments#info)\n @option opts [subscriber, contributor, moderator] :condition The permission level to return subreddits from\n @option opts [1..100] :limit The number of results to return\n @option opts [String] :after Return subreddits *after* this id\n @option opts [String] :before Return subreddits *before* this id\n @return (see #clear_sessions)", "docstring_tokens": ["Get", "subreddits", "I", "have"], "sha": "83cbfe4973eeff5a0c7426f4a23457a420273261", "url": "https://github.com/paradox460/snoo/blob/83cbfe4973eeff5a0c7426f4a23457a420273261/lib/snoo/subreddits.rb#L122-L128", "partition": "test"} {"repo": "paradox460/snoo", "path": "lib/snoo/subreddits.rb", "func_name": "Snoo.Subreddit.get_reddits", "original_string": "def get_reddits opts = {}\n url = \"/reddits/%s.json\" % (opts[:condition] if opts[:condition])\n opts.delete :condition\n query = opts\n\n get(url, query: query)\n end", "language": "ruby", "code": "def get_reddits opts = {}\n url = \"/reddits/%s.json\" % (opts[:condition] if opts[:condition])\n opts.delete :condition\n query = opts\n\n get(url, query: query)\n end", "code_tokens": ["def", "get_reddits", "opts", "=", "{", "}", "url", "=", "\"/reddits/%s.json\"", "%", "(", "opts", "[", ":condition", "]", "if", "opts", "[", ":condition", "]", ")", "opts", ".", "delete", ":condition", "query", "=", "opts", "get", "(", "url", ",", "query", ":", "query", ")", "end"], "docstring": "Get a list of subreddits\n\n @param (see LinksComments#info)\n @option opts [popular, new, banned] :condition The type of subreddits to return\n @option opts [1..100] :limit The number of results to return\n @option opts [String] :after Return subreddits *after* this id.\n @option opts [String] :before Return subreddits *before* this id.\n @return (see #clear_sessions)", "docstring_tokens": ["Get", "a", "list", "of", "subreddits"], "sha": "83cbfe4973eeff5a0c7426f4a23457a420273261", "url": "https://github.com/paradox460/snoo/blob/83cbfe4973eeff5a0c7426f4a23457a420273261/lib/snoo/subreddits.rb#L138-L144", "partition": "test"} {"repo": "paradox460/snoo", "path": "lib/snoo/subreddits.rb", "func_name": "Snoo.Subreddit.add_moderator", "original_string": "def add_moderator container, user, subreddit\n friend_wrapper container: container, name: user, r: subreddit, type: \"moderator\"\n end", "language": "ruby", "code": "def add_moderator container, user, subreddit\n friend_wrapper container: container, name: user, r: subreddit, type: \"moderator\"\n end", "code_tokens": ["def", "add_moderator", "container", ",", "user", ",", "subreddit", "friend_wrapper", "container", ":", "container", ",", "name", ":", "user", ",", "r", ":", "subreddit", ",", "type", ":", "\"moderator\"", "end"], "docstring": "Add a moderator to the subreddit\n\n @param container [String] The subreddit id. Must be a subreddit id (begins with t5_)\n @param user [String] The user\n @param (see #delete_header)\n @return (see #clear_sessions)", "docstring_tokens": ["Add", "a", "moderator", "to", "the", "subreddit"], "sha": "83cbfe4973eeff5a0c7426f4a23457a420273261", "url": "https://github.com/paradox460/snoo/blob/83cbfe4973eeff5a0c7426f4a23457a420273261/lib/snoo/subreddits.rb#L166-L168", "partition": "test"} {"repo": "paradox460/snoo", "path": "lib/snoo/subreddits.rb", "func_name": "Snoo.Subreddit.add_contributor", "original_string": "def add_contributor container, user, subreddit\n friend_wrapper container: container, name: user, r: subreddit, type: \"contributor\"\n end", "language": "ruby", "code": "def add_contributor container, user, subreddit\n friend_wrapper container: container, name: user, r: subreddit, type: \"contributor\"\n end", "code_tokens": ["def", "add_contributor", "container", ",", "user", ",", "subreddit", "friend_wrapper", "container", ":", "container", ",", "name", ":", "user", ",", "r", ":", "subreddit", ",", "type", ":", "\"contributor\"", "end"], "docstring": "Add a contributor to the subreddit\n\n @param (see #add_moderator)\n @return (see #clear_sessions)", "docstring_tokens": ["Add", "a", "contributor", "to", "the", "subreddit"], "sha": "83cbfe4973eeff5a0c7426f4a23457a420273261", "url": "https://github.com/paradox460/snoo/blob/83cbfe4973eeff5a0c7426f4a23457a420273261/lib/snoo/subreddits.rb#L174-L176", "partition": "test"} {"repo": "paradox460/snoo", "path": "lib/snoo/subreddits.rb", "func_name": "Snoo.Subreddit.ban_user", "original_string": "def ban_user container, user, subreddit\n friend_wrapper container: container, name: user, r: subreddit, type: \"banned\"\n end", "language": "ruby", "code": "def ban_user container, user, subreddit\n friend_wrapper container: container, name: user, r: subreddit, type: \"banned\"\n end", "code_tokens": ["def", "ban_user", "container", ",", "user", ",", "subreddit", "friend_wrapper", "container", ":", "container", ",", "name", ":", "user", ",", "r", ":", "subreddit", ",", "type", ":", "\"banned\"", "end"], "docstring": "Ban a user from a subreddit\n\n @param (see #add_moderator)\n @return (see #clear_sessions)", "docstring_tokens": ["Ban", "a", "user", "from", "a", "subreddit"], "sha": "83cbfe4973eeff5a0c7426f4a23457a420273261", "url": "https://github.com/paradox460/snoo/blob/83cbfe4973eeff5a0c7426f4a23457a420273261/lib/snoo/subreddits.rb#L182-L184", "partition": "test"} {"repo": "paradox460/snoo", "path": "lib/snoo/subreddits.rb", "func_name": "Snoo.Subreddit.remove_moderator", "original_string": "def remove_moderator container, user, subreddit\n unfriend_wrapper container: container, name: user, r: subreddit, type: \"moderator\"\n end", "language": "ruby", "code": "def remove_moderator container, user, subreddit\n unfriend_wrapper container: container, name: user, r: subreddit, type: \"moderator\"\n end", "code_tokens": ["def", "remove_moderator", "container", ",", "user", ",", "subreddit", "unfriend_wrapper", "container", ":", "container", ",", "name", ":", "user", ",", "r", ":", "subreddit", ",", "type", ":", "\"moderator\"", "end"], "docstring": "Remove a moderator from a subreddit\n\n @param (see #add_moderator)\n @return (see #clear_sessions)", "docstring_tokens": ["Remove", "a", "moderator", "from", "a", "subreddit"], "sha": "83cbfe4973eeff5a0c7426f4a23457a420273261", "url": "https://github.com/paradox460/snoo/blob/83cbfe4973eeff5a0c7426f4a23457a420273261/lib/snoo/subreddits.rb#L190-L192", "partition": "test"} {"repo": "paradox460/snoo", "path": "lib/snoo/subreddits.rb", "func_name": "Snoo.Subreddit.remove_contributor", "original_string": "def remove_contributor container, user, subreddit\n unfriend_wrapper container: container, name: user, r: subreddit, type: \"contributor\"\n end", "language": "ruby", "code": "def remove_contributor container, user, subreddit\n unfriend_wrapper container: container, name: user, r: subreddit, type: \"contributor\"\n end", "code_tokens": ["def", "remove_contributor", "container", ",", "user", ",", "subreddit", "unfriend_wrapper", "container", ":", "container", ",", "name", ":", "user", ",", "r", ":", "subreddit", ",", "type", ":", "\"contributor\"", "end"], "docstring": "Remove a contributor from a subreddit\n\n @param (see #remove_moderator)\n @return (see #clear_sessions)", "docstring_tokens": ["Remove", "a", "contributor", "from", "a", "subreddit"], "sha": "83cbfe4973eeff5a0c7426f4a23457a420273261", "url": "https://github.com/paradox460/snoo/blob/83cbfe4973eeff5a0c7426f4a23457a420273261/lib/snoo/subreddits.rb#L198-L200", "partition": "test"} {"repo": "paradox460/snoo", "path": "lib/snoo/subreddits.rb", "func_name": "Snoo.Subreddit.unban_user", "original_string": "def unban_user container, user, subreddit\n unfriend_wrapper container: container, name: user, r: subreddit, type: \"banned\"\n end", "language": "ruby", "code": "def unban_user container, user, subreddit\n unfriend_wrapper container: container, name: user, r: subreddit, type: \"banned\"\n end", "code_tokens": ["def", "unban_user", "container", ",", "user", ",", "subreddit", "unfriend_wrapper", "container", ":", "container", ",", "name", ":", "user", ",", "r", ":", "subreddit", ",", "type", ":", "\"banned\"", "end"], "docstring": "Unban a user from a subreddit\n\n @param (see #remove_moderator)\n @return (see #clear_sessions)", "docstring_tokens": ["Unban", "a", "user", "from", "a", "subreddit"], "sha": "83cbfe4973eeff5a0c7426f4a23457a420273261", "url": "https://github.com/paradox460/snoo/blob/83cbfe4973eeff5a0c7426f4a23457a420273261/lib/snoo/subreddits.rb#L206-L208", "partition": "test"} {"repo": "paradox460/snoo", "path": "lib/snoo/utilities.rb", "func_name": "Snoo.Utilities.get", "original_string": "def get *args, &block\n response = self.class.get *args, &block\n raise WebserverError, response.code unless response.code == 200\n response\n end", "language": "ruby", "code": "def get *args, &block\n response = self.class.get *args, &block\n raise WebserverError, response.code unless response.code == 200\n response\n end", "code_tokens": ["def", "get", "*", "args", ",", "&", "block", "response", "=", "self", ".", "class", ".", "get", "args", ",", "block", "raise", "WebserverError", ",", "response", ".", "code", "unless", "response", ".", "code", "==", "200", "response", "end"], "docstring": "HTTParty get wrapper. This serves to clean up code, as well as throw webserver errors wherever needed", "docstring_tokens": ["HTTParty", "get", "wrapper", ".", "This", "serves", "to", "clean", "up", "code", "as", "well", "as", "throw", "webserver", "errors", "wherever", "needed"], "sha": "83cbfe4973eeff5a0c7426f4a23457a420273261", "url": "https://github.com/paradox460/snoo/blob/83cbfe4973eeff5a0c7426f4a23457a420273261/lib/snoo/utilities.rb#L18-L22", "partition": "test"} {"repo": "paradox460/snoo", "path": "lib/snoo/account.rb", "func_name": "Snoo.Account.log_in", "original_string": "def log_in username, password\n login = post(\"/api/login\", :body => {user: username, passwd: password, api_type: 'json'})\n errors = login['json']['errors']\n raise errors[0][1] unless errors.size == 0\n set_cookies login.headers['set-cookie']\n @modhash = login['json']['data']['modhash']\n @username = username\n @userid = 't2_' + get('/api/me.json')['data']['id']\n return login\n end", "language": "ruby", "code": "def log_in username, password\n login = post(\"/api/login\", :body => {user: username, passwd: password, api_type: 'json'})\n errors = login['json']['errors']\n raise errors[0][1] unless errors.size == 0\n set_cookies login.headers['set-cookie']\n @modhash = login['json']['data']['modhash']\n @username = username\n @userid = 't2_' + get('/api/me.json')['data']['id']\n return login\n end", "code_tokens": ["def", "log_in", "username", ",", "password", "login", "=", "post", "(", "\"/api/login\"", ",", ":body", "=>", "{", "user", ":", "username", ",", "passwd", ":", "password", ",", "api_type", ":", "'json'", "}", ")", "errors", "=", "login", "[", "'json'", "]", "[", "'errors'", "]", "raise", "errors", "[", "0", "]", "[", "1", "]", "unless", "errors", ".", "size", "==", "0", "set_cookies", "login", ".", "headers", "[", "'set-cookie'", "]", "@modhash", "=", "login", "[", "'json'", "]", "[", "'data'", "]", "[", "'modhash'", "]", "@username", "=", "username", "@userid", "=", "'t2_'", "+", "get", "(", "'/api/me.json'", ")", "[", "'data'", "]", "[", "'id'", "]", "return", "login", "end"], "docstring": "Log into a reddit account. You need to do this to use any restricted or write APIs\n\n @param username [String] The reddit account's username you wish to log in as\n @param password [String] The password of the reddit account\n @return [HTTParty::Response] The httparty request object.", "docstring_tokens": ["Log", "into", "a", "reddit", "account", ".", "You", "need", "to", "do", "this", "to", "use", "any", "restricted", "or", "write", "APIs"], "sha": "83cbfe4973eeff5a0c7426f4a23457a420273261", "url": "https://github.com/paradox460/snoo/blob/83cbfe4973eeff5a0c7426f4a23457a420273261/lib/snoo/account.rb#L12-L21", "partition": "test"} {"repo": "paradox460/snoo", "path": "lib/snoo/account.rb", "func_name": "Snoo.Account.auth", "original_string": "def auth modhash, cookies\n set_cookies cookies\n @modhash = modhash\n meinfo = get(\"/api/me.json\")\n @username = meinfo['data']['name']\n @userid = 't2_' + meinfo['data']['id']\n end", "language": "ruby", "code": "def auth modhash, cookies\n set_cookies cookies\n @modhash = modhash\n meinfo = get(\"/api/me.json\")\n @username = meinfo['data']['name']\n @userid = 't2_' + meinfo['data']['id']\n end", "code_tokens": ["def", "auth", "modhash", ",", "cookies", "set_cookies", "cookies", "@modhash", "=", "modhash", "meinfo", "=", "get", "(", "\"/api/me.json\"", ")", "@username", "=", "meinfo", "[", "'data'", "]", "[", "'name'", "]", "@userid", "=", "'t2_'", "+", "meinfo", "[", "'data'", "]", "[", "'id'", "]", "end"], "docstring": "Auth into reddit via modhash and cookie. This has the advantage of not throttling you if you call it a lot\n\n @param modhash [String] The modhash to use\n @param cookies [String] The cookies string to give to the header", "docstring_tokens": ["Auth", "into", "reddit", "via", "modhash", "and", "cookie", ".", "This", "has", "the", "advantage", "of", "not", "throttling", "you", "if", "you", "call", "it", "a", "lot"], "sha": "83cbfe4973eeff5a0c7426f4a23457a420273261", "url": "https://github.com/paradox460/snoo/blob/83cbfe4973eeff5a0c7426f4a23457a420273261/lib/snoo/account.rb#L27-L33", "partition": "test"} {"repo": "paradox460/snoo", "path": "lib/snoo/account.rb", "func_name": "Snoo.Account.delete_user", "original_string": "def delete_user password, reason = \"deleted by script command\"\n logged_in?\n delete = post('/api/delete_user', body: {\n confirm: true,\n delete_message: reason,\n passwd: password,\n uh: @modhash,\n user: @username,\n api_type: 'json'\n })\n return delete\n end", "language": "ruby", "code": "def delete_user password, reason = \"deleted by script command\"\n logged_in?\n delete = post('/api/delete_user', body: {\n confirm: true,\n delete_message: reason,\n passwd: password,\n uh: @modhash,\n user: @username,\n api_type: 'json'\n })\n return delete\n end", "code_tokens": ["def", "delete_user", "password", ",", "reason", "=", "\"deleted by script command\"", "logged_in?", "delete", "=", "post", "(", "'/api/delete_user'", ",", "body", ":", "{", "confirm", ":", "true", ",", "delete_message", ":", "reason", ",", "passwd", ":", "password", ",", "uh", ":", "@modhash", ",", "user", ":", "@username", ",", "api_type", ":", "'json'", "}", ")", "return", "delete", "end"], "docstring": "Deletes the current user. This requires a password for security reasons.\n\n @note (see #clear_sessions)\n @param password [String] The password for the current user\n @param reason [String] The reason the current user account is being deleted.\n @return (see #clear_sessions)", "docstring_tokens": ["Deletes", "the", "current", "user", ".", "This", "requires", "a", "password", "for", "security", "reasons", "."], "sha": "83cbfe4973eeff5a0c7426f4a23457a420273261", "url": "https://github.com/paradox460/snoo/blob/83cbfe4973eeff5a0c7426f4a23457a420273261/lib/snoo/account.rb#L63-L74", "partition": "test"} {"repo": "paradox460/snoo", "path": "lib/snoo/pms.rb", "func_name": "Snoo.PM.get_messages", "original_string": "def get_messages where = \"inbox\", opts = {}\n query = {\n mark: false\n }\n query.merge! opts\n get(\"/message/#{where}.json\", query: query)\n end", "language": "ruby", "code": "def get_messages where = \"inbox\", opts = {}\n query = {\n mark: false\n }\n query.merge! opts\n get(\"/message/#{where}.json\", query: query)\n end", "code_tokens": ["def", "get_messages", "where", "=", "\"inbox\"", ",", "opts", "=", "{", "}", "query", "=", "{", "mark", ":", "false", "}", "query", ".", "merge!", "opts", "get", "(", "\"/message/#{where}.json\"", ",", "query", ":", "query", ")", "end"], "docstring": "Gets a listing of PMs\n\n @param where [inbox, unread, sent] Where to get messages from\n @param (see LinksComments#info)\n @option opts [true, false] :mark (false) Mark the messages requested as read?\n @option opts [1..100] :limit The total number of messages to get\n @option opts [String] :before Get all comments *before* this id\n @option opts [String] :after Get all comments *after* this\n @return (see #clear_sessions)", "docstring_tokens": ["Gets", "a", "listing", "of", "PMs"], "sha": "83cbfe4973eeff5a0c7426f4a23457a420273261", "url": "https://github.com/paradox460/snoo/blob/83cbfe4973eeff5a0c7426f4a23457a420273261/lib/snoo/pms.rb#L55-L61", "partition": "test"} {"repo": "paradox460/snoo", "path": "lib/snoo/flair.rb", "func_name": "Snoo.Flair.clear_flair_templates", "original_string": "def clear_flair_templates type, subreddit\n logged_in?\n post('/api/clearflairtemplates', body: { flair_type: type, r: subreddit, uh: @modhash, api_type: 'json'})\n end", "language": "ruby", "code": "def clear_flair_templates type, subreddit\n logged_in?\n post('/api/clearflairtemplates', body: { flair_type: type, r: subreddit, uh: @modhash, api_type: 'json'})\n end", "code_tokens": ["def", "clear_flair_templates", "type", ",", "subreddit", "logged_in?", "post", "(", "'/api/clearflairtemplates'", ",", "body", ":", "{", "flair_type", ":", "type", ",", "r", ":", "subreddit", ",", "uh", ":", "@modhash", ",", "api_type", ":", "'json'", "}", ")", "end"], "docstring": "Clear all the flair templates of a particular type\n\n @param type [USER_FLAIR, LINK_FLAIR] The type of template to clear.\n @param subreddit [String] The subreddit targeted.\n @return (see #clear_sessions)", "docstring_tokens": ["Clear", "all", "the", "flair", "templates", "of", "a", "particular", "type"], "sha": "83cbfe4973eeff5a0c7426f4a23457a420273261", "url": "https://github.com/paradox460/snoo/blob/83cbfe4973eeff5a0c7426f4a23457a420273261/lib/snoo/flair.rb#L13-L16", "partition": "test"} {"repo": "paradox460/snoo", "path": "lib/snoo/flair.rb", "func_name": "Snoo.Flair.delete_user_flair", "original_string": "def delete_user_flair user, subreddit\n logged_in?\n post('/api/deleteflair', body: {name: user, r: subreddit, uh: @modhash, api_type: 'json'})\n end", "language": "ruby", "code": "def delete_user_flair user, subreddit\n logged_in?\n post('/api/deleteflair', body: {name: user, r: subreddit, uh: @modhash, api_type: 'json'})\n end", "code_tokens": ["def", "delete_user_flair", "user", ",", "subreddit", "logged_in?", "post", "(", "'/api/deleteflair'", ",", "body", ":", "{", "name", ":", "user", ",", "r", ":", "subreddit", ",", "uh", ":", "@modhash", ",", "api_type", ":", "'json'", "}", ")", "end"], "docstring": "Deletes a user's flair\n\n @param user [String] The user who'se flair is affected\n @param subreddit [String] The subreddit targeted.\n @return (see #clear_sessions)", "docstring_tokens": ["Deletes", "a", "user", "s", "flair"], "sha": "83cbfe4973eeff5a0c7426f4a23457a420273261", "url": "https://github.com/paradox460/snoo/blob/83cbfe4973eeff5a0c7426f4a23457a420273261/lib/snoo/flair.rb#L23-L26", "partition": "test"} {"repo": "paradox460/snoo", "path": "lib/snoo/flair.rb", "func_name": "Snoo.Flair.delete_flair_template", "original_string": "def delete_flair_template id, subreddit\n logged_in?\n post('/api/deleteflairtemplate', body: {flair_template_id: id, r: subreddit, uh: @modhash, api_type: 'json'})\n end", "language": "ruby", "code": "def delete_flair_template id, subreddit\n logged_in?\n post('/api/deleteflairtemplate', body: {flair_template_id: id, r: subreddit, uh: @modhash, api_type: 'json'})\n end", "code_tokens": ["def", "delete_flair_template", "id", ",", "subreddit", "logged_in?", "post", "(", "'/api/deleteflairtemplate'", ",", "body", ":", "{", "flair_template_id", ":", "id", ",", "r", ":", "subreddit", ",", "uh", ":", "@modhash", ",", "api_type", ":", "'json'", "}", ")", "end"], "docstring": "Deletes a flair template by ID.\n\n @param id [String] The flair template's ID to delete.\n @param subreddit [String] The subreddit targeted.", "docstring_tokens": ["Deletes", "a", "flair", "template", "by", "ID", "."], "sha": "83cbfe4973eeff5a0c7426f4a23457a420273261", "url": "https://github.com/paradox460/snoo/blob/83cbfe4973eeff5a0c7426f4a23457a420273261/lib/snoo/flair.rb#L32-L35", "partition": "test"} {"repo": "paradox460/snoo", "path": "lib/snoo/flair.rb", "func_name": "Snoo.Flair.flair_config", "original_string": "def flair_config subreddit, opts = {}\n logged_in?\n options = {\n flair_enabled: true,\n flair_position: 'right',\n flair_self_assign_enabled: false,\n link_flair_position: 'right',\n link_flair_self_assign_enabled: false,\n uh: @modhash,\n r: subreddit,\n api_type: 'json'\n }\n options.merge! opts\n\n post('/api/flairconfig', body: options)\n end", "language": "ruby", "code": "def flair_config subreddit, opts = {}\n logged_in?\n options = {\n flair_enabled: true,\n flair_position: 'right',\n flair_self_assign_enabled: false,\n link_flair_position: 'right',\n link_flair_self_assign_enabled: false,\n uh: @modhash,\n r: subreddit,\n api_type: 'json'\n }\n options.merge! opts\n\n post('/api/flairconfig', body: options)\n end", "code_tokens": ["def", "flair_config", "subreddit", ",", "opts", "=", "{", "}", "logged_in?", "options", "=", "{", "flair_enabled", ":", "true", ",", "flair_position", ":", "'right'", ",", "flair_self_assign_enabled", ":", "false", ",", "link_flair_position", ":", "'right'", ",", "link_flair_self_assign_enabled", ":", "false", ",", "uh", ":", "@modhash", ",", "r", ":", "subreddit", ",", "api_type", ":", "'json'", "}", "options", ".", "merge!", "opts", "post", "(", "'/api/flairconfig'", ",", "body", ":", "options", ")", "end"], "docstring": "Configures flair options for a subreddit. All options are required\n\n @param subreddit [String] The subreddit targeted.\n @param opts [Hash] An options hash\n @option opts [true, false] :flair_enabled (true) Flair enabled?\n @option opts [left, right] :flair_position ('right') Position of user flair.\n @option opts [true, false] :flair_self_assign_enabled (false) Allow users to assign their own flair from templates\n @option opts [none, left, right] :link_flair_position ('right') The position of link flair. Set to `none` to disable\n @option opts [true, false] :link_flair_self_assign_enabled (false) Allow a submitter to assign their own link flair\n @return (see #clear_sessions)", "docstring_tokens": ["Configures", "flair", "options", "for", "a", "subreddit", ".", "All", "options", "are", "required"], "sha": "83cbfe4973eeff5a0c7426f4a23457a420273261", "url": "https://github.com/paradox460/snoo/blob/83cbfe4973eeff5a0c7426f4a23457a420273261/lib/snoo/flair.rb#L68-L83", "partition": "test"} {"repo": "paradox460/snoo", "path": "lib/snoo/flair.rb", "func_name": "Snoo.Flair.flair_csv", "original_string": "def flair_csv csv, subreddit\n logged_in?\n post('/api/flaircsv.json', body: {flair_csv: csv, r: subreddit, uh: @modhash})\n end", "language": "ruby", "code": "def flair_csv csv, subreddit\n logged_in?\n post('/api/flaircsv.json', body: {flair_csv: csv, r: subreddit, uh: @modhash})\n end", "code_tokens": ["def", "flair_csv", "csv", ",", "subreddit", "logged_in?", "post", "(", "'/api/flaircsv.json'", ",", "body", ":", "{", "flair_csv", ":", "csv", ",", "r", ":", "subreddit", ",", "uh", ":", "@modhash", "}", ")", "end"], "docstring": "Post flair in a CSV file to reddit\n\n @param csv [String] A string, in CSV format, of `user,flair-text,css_class` per line, with no more than 100 flairs, and **no header line**.\n @param subreddit [String] The subreddit targeted.\n @return [HTTParty::Response] The request object. Note that this request object contains a json confirming the status of each line of the CSV", "docstring_tokens": ["Post", "flair", "in", "a", "CSV", "file", "to", "reddit"], "sha": "83cbfe4973eeff5a0c7426f4a23457a420273261", "url": "https://github.com/paradox460/snoo/blob/83cbfe4973eeff5a0c7426f4a23457a420273261/lib/snoo/flair.rb#L90-L93", "partition": "test"} {"repo": "paradox460/snoo", "path": "lib/snoo/flair.rb", "func_name": "Snoo.Flair.flair_template", "original_string": "def flair_template subreddit, opts = {}\n logged_in?\n params = {\n flair_type: 'USER_FLAIR',\n text_editable: false,\n uh: @modhash,\n r: subreddit,\n api_type: 'json'\n }\n params.merge! opts\n\n post('/api/flairtemplate', body: params)\n end", "language": "ruby", "code": "def flair_template subreddit, opts = {}\n logged_in?\n params = {\n flair_type: 'USER_FLAIR',\n text_editable: false,\n uh: @modhash,\n r: subreddit,\n api_type: 'json'\n }\n params.merge! opts\n\n post('/api/flairtemplate', body: params)\n end", "code_tokens": ["def", "flair_template", "subreddit", ",", "opts", "=", "{", "}", "logged_in?", "params", "=", "{", "flair_type", ":", "'USER_FLAIR'", ",", "text_editable", ":", "false", ",", "uh", ":", "@modhash", ",", "r", ":", "subreddit", ",", "api_type", ":", "'json'", "}", "params", ".", "merge!", "opts", "post", "(", "'/api/flairtemplate'", ",", "body", ":", "params", ")", "end"], "docstring": "Create or edit a flair template.\n\n @param subreddit [String] The subreddit targeted.ate allows users to specify their own text\n @param opts [Hash] An options hash\n @option opts [String] css_class The list of css classes applied to this style, space separated\n @option opts [USER_FLAIR, LINK_FLAIR] flair_type ('USER_FLAIR') The type of flair template.\n @option opts [String] text The flair template's text.\n @option opts [true, false] text_editable (false) If the user is allowed to edit their flair text\n @option opts [String] template_id The flair template ID, for editing.\n @return (see #clear_sessions)", "docstring_tokens": ["Create", "or", "edit", "a", "flair", "template", "."], "sha": "83cbfe4973eeff5a0c7426f4a23457a420273261", "url": "https://github.com/paradox460/snoo/blob/83cbfe4973eeff5a0c7426f4a23457a420273261/lib/snoo/flair.rb#L123-L135", "partition": "test"} {"repo": "paradox460/snoo", "path": "lib/snoo/flair.rb", "func_name": "Snoo.Flair.select_flair_template", "original_string": "def select_flair_template template_id, subreddit, opts = {}\n logged_in?\n params = {\n flair_template_id: template_id,\n uh: @modhash,\n r: subreddit,\n api_type: 'json'\n }\n params.merge! opts\n post('/api/selectflair', body: params)\n end", "language": "ruby", "code": "def select_flair_template template_id, subreddit, opts = {}\n logged_in?\n params = {\n flair_template_id: template_id,\n uh: @modhash,\n r: subreddit,\n api_type: 'json'\n }\n params.merge! opts\n post('/api/selectflair', body: params)\n end", "code_tokens": ["def", "select_flair_template", "template_id", ",", "subreddit", ",", "opts", "=", "{", "}", "logged_in?", "params", "=", "{", "flair_template_id", ":", "template_id", ",", "uh", ":", "@modhash", ",", "r", ":", "subreddit", ",", "api_type", ":", "'json'", "}", "params", ".", "merge!", "opts", "post", "(", "'/api/selectflair'", ",", "body", ":", "params", ")", "end"], "docstring": "Select a flair template and apply it to a user or link\n\n @param template_id [String] The template id to apply.\n @param subreddit [String] The subreddit targeted.\n @param (see LinksComments#info)\n @option opts [String] :link The link id to apply to\n @option opts [String] :user The username to apply flair to\n @option opts [String] :text The flair text\n @return (see #clear_sessions)", "docstring_tokens": ["Select", "a", "flair", "template", "and", "apply", "it", "to", "a", "user", "or", "link"], "sha": "83cbfe4973eeff5a0c7426f4a23457a420273261", "url": "https://github.com/paradox460/snoo/blob/83cbfe4973eeff5a0c7426f4a23457a420273261/lib/snoo/flair.rb#L146-L156", "partition": "test"} {"repo": "paradox460/snoo", "path": "lib/snoo/flair.rb", "func_name": "Snoo.Flair.flair_toggle", "original_string": "def flair_toggle enabled, subreddit\n logged_in?\n post('/api/setflairenabled', body: {flair_enabled: enabled, uh: @modhash, r: subreddit, api_type: 'json'})\n end", "language": "ruby", "code": "def flair_toggle enabled, subreddit\n logged_in?\n post('/api/setflairenabled', body: {flair_enabled: enabled, uh: @modhash, r: subreddit, api_type: 'json'})\n end", "code_tokens": ["def", "flair_toggle", "enabled", ",", "subreddit", "logged_in?", "post", "(", "'/api/setflairenabled'", ",", "body", ":", "{", "flair_enabled", ":", "enabled", ",", "uh", ":", "@modhash", ",", "r", ":", "subreddit", ",", "api_type", ":", "'json'", "}", ")", "end"], "docstring": "Toggle flair on and off for a subreddit\n\n @param enabled [true, false] Enable/disable flair\n @param subreddit [String] The subreddit targeted.\n @return (see #clear_sessions)", "docstring_tokens": ["Toggle", "flair", "on", "and", "off", "for", "a", "subreddit"], "sha": "83cbfe4973eeff5a0c7426f4a23457a420273261", "url": "https://github.com/paradox460/snoo/blob/83cbfe4973eeff5a0c7426f4a23457a420273261/lib/snoo/flair.rb#L163-L166", "partition": "test"} {"repo": "paradox460/snoo", "path": "lib/snoo/listings.rb", "func_name": "Snoo.Listings.get_comments", "original_string": "def get_comments opts = {}\n query = { limit: 100 }\n query.merge! opts\n url = \"%s/comments/%s%s.json\" % [('/r/' + opts[:subreddit] if opts[:subreddit]), opts[:link_id], ('/blah/' + opts[:comment_id] if opts[:comment_id])]\n get(url, query: query)\n end", "language": "ruby", "code": "def get_comments opts = {}\n query = { limit: 100 }\n query.merge! opts\n url = \"%s/comments/%s%s.json\" % [('/r/' + opts[:subreddit] if opts[:subreddit]), opts[:link_id], ('/blah/' + opts[:comment_id] if opts[:comment_id])]\n get(url, query: query)\n end", "code_tokens": ["def", "get_comments", "opts", "=", "{", "}", "query", "=", "{", "limit", ":", "100", "}", "query", ".", "merge!", "opts", "url", "=", "\"%s/comments/%s%s.json\"", "%", "[", "(", "'/r/'", "+", "opts", "[", ":subreddit", "]", "if", "opts", "[", ":subreddit", "]", ")", ",", "opts", "[", ":link_id", "]", ",", "(", "'/blah/'", "+", "opts", "[", ":comment_id", "]", "if", "opts", "[", ":comment_id", "]", ")", "]", "get", "(", "url", ",", "query", ":", "query", ")", "end"], "docstring": "Get a comment listing from the site\n\n @param (see LinksComments#info)\n @option opts [String] :subreddit The subreddit to fetch the comments of\n @option opts [String] :link_id The link to get the comments of\n @option opts [String] :comment_id The parent comment of a thread.\n @option opts [Fixnum] :context The context of the thread, that is, how far above the `comment_id` to return\n @option opts [Fixnum] :limit (100) The total number of comments to return. If you have gold this can include the whole thread, but is buggy. Recommend no more than 1000\n @option opts [Fixnum] :depth How deep to render a comment thread.\n @option opts [old, new, hot, top, controversial, best] :sort The sort used.\n @return (see #clear_sessions)", "docstring_tokens": ["Get", "a", "comment", "listing", "from", "the", "site"], "sha": "83cbfe4973eeff5a0c7426f4a23457a420273261", "url": "https://github.com/paradox460/snoo/blob/83cbfe4973eeff5a0c7426f4a23457a420273261/lib/snoo/listings.rb#L18-L23", "partition": "test"} {"repo": "paradox460/snoo", "path": "lib/snoo/listings.rb", "func_name": "Snoo.Listings.get_listing", "original_string": "def get_listing opts = {}\n # Build the basic url\n url = \"%s/%s.json\" % [('/r/' + opts[:subreddit] if opts[:subreddit] ), (opts[:page] if opts[:page])]\n # Delete subreddit and page from the hash, they dont belong in the query\n [:subreddit, :page].each {|k| opts.delete k}\n query = opts\n # Make the request\n get(url, query: query)\n end", "language": "ruby", "code": "def get_listing opts = {}\n # Build the basic url\n url = \"%s/%s.json\" % [('/r/' + opts[:subreddit] if opts[:subreddit] ), (opts[:page] if opts[:page])]\n # Delete subreddit and page from the hash, they dont belong in the query\n [:subreddit, :page].each {|k| opts.delete k}\n query = opts\n # Make the request\n get(url, query: query)\n end", "code_tokens": ["def", "get_listing", "opts", "=", "{", "}", "# Build the basic url", "url", "=", "\"%s/%s.json\"", "%", "[", "(", "'/r/'", "+", "opts", "[", ":subreddit", "]", "if", "opts", "[", ":subreddit", "]", ")", ",", "(", "opts", "[", ":page", "]", "if", "opts", "[", ":page", "]", ")", "]", "# Delete subreddit and page from the hash, they dont belong in the query", "[", ":subreddit", ",", ":page", "]", ".", "each", "{", "|", "k", "|", "opts", ".", "delete", "k", "}", "query", "=", "opts", "# Make the request", "get", "(", "url", ",", "query", ":", "query", ")", "end"], "docstring": "Gets a listing of links from reddit.\n\n @param (see LinksComments#info)\n @option opts [String] :subreddit The subreddit targeted. Can be psuedo-subreddits like `all` or `mod`. If blank, the front page\n @option opts [new, controversial, top, saved] :page The page to view.\n @option opts [new, rising] :sort The sorting method. Only relevant on the `new` page\n @option opts [hour, day, week, month, year] :t The timeframe. Only relevant on some pages, such as `top`. Leave empty for all time\n @option opts [1..100] :limit The number of things to return.\n @option opts [String] :after Get things *after* this thing id\n @option opts [String] :before Get things *before* this thing id\n @return (see #clear_sessions)", "docstring_tokens": ["Gets", "a", "listing", "of", "links", "from", "reddit", "."], "sha": "83cbfe4973eeff5a0c7426f4a23457a420273261", "url": "https://github.com/paradox460/snoo/blob/83cbfe4973eeff5a0c7426f4a23457a420273261/lib/snoo/listings.rb#L36-L44", "partition": "test"} {"repo": "paradox460/snoo", "path": "lib/snoo/moderation.rb", "func_name": "Snoo.Moderation.distinguish", "original_string": "def distinguish id, how = \"yes\"\n logged_in?\n hows = %w{yes no admin special}\n post('/api/distinguish', body: {id: id, how: how, uh: @modhash, api_type: 'json'})\n end", "language": "ruby", "code": "def distinguish id, how = \"yes\"\n logged_in?\n hows = %w{yes no admin special}\n post('/api/distinguish', body: {id: id, how: how, uh: @modhash, api_type: 'json'})\n end", "code_tokens": ["def", "distinguish", "id", ",", "how", "=", "\"yes\"", "logged_in?", "hows", "=", "%w{", "yes", "no", "admin", "special", "}", "post", "(", "'/api/distinguish'", ",", "body", ":", "{", "id", ":", "id", ",", "how", ":", "how", ",", "uh", ":", "@modhash", ",", "api_type", ":", "'json'", "}", ")", "end"], "docstring": "Distinguish a thing\n\n @param (see #approve)\n @param how [yes, no, admin, special] (yes) Determines how to distinguish something. Only works for the permissions you have.\n @return (see #clear_sessions)", "docstring_tokens": ["Distinguish", "a", "thing"], "sha": "83cbfe4973eeff5a0c7426f4a23457a420273261", "url": "https://github.com/paradox460/snoo/blob/83cbfe4973eeff5a0c7426f4a23457a420273261/lib/snoo/moderation.rb#L21-L25", "partition": "test"} {"repo": "paradox460/snoo", "path": "lib/snoo/moderation.rb", "func_name": "Snoo.Moderation.remove", "original_string": "def remove id, spam = false\n logged_in?\n post('/api/remove', body: {id: id, spam: spam, uh: @modhash, api_type: 'json'})\n end", "language": "ruby", "code": "def remove id, spam = false\n logged_in?\n post('/api/remove', body: {id: id, spam: spam, uh: @modhash, api_type: 'json'})\n end", "code_tokens": ["def", "remove", "id", ",", "spam", "=", "false", "logged_in?", "post", "(", "'/api/remove'", ",", "body", ":", "{", "id", ":", "id", ",", "spam", ":", "spam", ",", "uh", ":", "@modhash", ",", "api_type", ":", "'json'", "}", ")", "end"], "docstring": "Removes a thing\n\n @param (see #approve)\n @param spam [true, false] Mark this removal as a spam removal (and train the spamfilter)\n @return (see #clear_sessions)", "docstring_tokens": ["Removes", "a", "thing"], "sha": "83cbfe4973eeff5a0c7426f4a23457a420273261", "url": "https://github.com/paradox460/snoo/blob/83cbfe4973eeff5a0c7426f4a23457a420273261/lib/snoo/moderation.rb#L52-L55", "partition": "test"} {"repo": "paradox460/snoo", "path": "lib/snoo/moderation.rb", "func_name": "Snoo.Moderation.get_modlog", "original_string": "def get_modlog subreddit, opts = {}\n logged_in?\n options = {\n limit: 100\n }.merge opts\n data = Nokogiri::HTML.parse(get(\"/r/#{subreddit}/about/log\", query: options).body).css('.modactionlisting tr')\n processed = {\n data: [],\n first: data[0]['data-fullname'],\n first_date: Time.parse(data[0].children[0].child['datetime']),\n last: data[-1]['data-fullname'],\n last_date: Time.parse(data[-1].children[0].child['datetime']),\n }\n data.each do |tr|\n processed[:data] << {\n fullname: tr['data-fullname'],\n time: Time.parse(tr.children[0].child['datetime']),\n author: tr.children[1].child.content,\n action: tr.children[2].child['class'].split[1],\n description: tr.children[3].content,\n href: tr.children[3].css('a').count == 0 ? nil : tr.children[3].css('a')[0]['href']\n }\n end\n return processed\n end", "language": "ruby", "code": "def get_modlog subreddit, opts = {}\n logged_in?\n options = {\n limit: 100\n }.merge opts\n data = Nokogiri::HTML.parse(get(\"/r/#{subreddit}/about/log\", query: options).body).css('.modactionlisting tr')\n processed = {\n data: [],\n first: data[0]['data-fullname'],\n first_date: Time.parse(data[0].children[0].child['datetime']),\n last: data[-1]['data-fullname'],\n last_date: Time.parse(data[-1].children[0].child['datetime']),\n }\n data.each do |tr|\n processed[:data] << {\n fullname: tr['data-fullname'],\n time: Time.parse(tr.children[0].child['datetime']),\n author: tr.children[1].child.content,\n action: tr.children[2].child['class'].split[1],\n description: tr.children[3].content,\n href: tr.children[3].css('a').count == 0 ? nil : tr.children[3].css('a')[0]['href']\n }\n end\n return processed\n end", "code_tokens": ["def", "get_modlog", "subreddit", ",", "opts", "=", "{", "}", "logged_in?", "options", "=", "{", "limit", ":", "100", "}", ".", "merge", "opts", "data", "=", "Nokogiri", "::", "HTML", ".", "parse", "(", "get", "(", "\"/r/#{subreddit}/about/log\"", ",", "query", ":", "options", ")", ".", "body", ")", ".", "css", "(", "'.modactionlisting tr'", ")", "processed", "=", "{", "data", ":", "[", "]", ",", "first", ":", "data", "[", "0", "]", "[", "'data-fullname'", "]", ",", "first_date", ":", "Time", ".", "parse", "(", "data", "[", "0", "]", ".", "children", "[", "0", "]", ".", "child", "[", "'datetime'", "]", ")", ",", "last", ":", "data", "[", "-", "1", "]", "[", "'data-fullname'", "]", ",", "last_date", ":", "Time", ".", "parse", "(", "data", "[", "-", "1", "]", ".", "children", "[", "0", "]", ".", "child", "[", "'datetime'", "]", ")", ",", "}", "data", ".", "each", "do", "|", "tr", "|", "processed", "[", ":data", "]", "<<", "{", "fullname", ":", "tr", "[", "'data-fullname'", "]", ",", "time", ":", "Time", ".", "parse", "(", "tr", ".", "children", "[", "0", "]", ".", "child", "[", "'datetime'", "]", ")", ",", "author", ":", "tr", ".", "children", "[", "1", "]", ".", "child", ".", "content", ",", "action", ":", "tr", ".", "children", "[", "2", "]", ".", "child", "[", "'class'", "]", ".", "split", "[", "1", "]", ",", "description", ":", "tr", ".", "children", "[", "3", "]", ".", "content", ",", "href", ":", "tr", ".", "children", "[", "3", "]", ".", "css", "(", "'a'", ")", ".", "count", "==", "0", "?", "nil", ":", "tr", ".", "children", "[", "3", "]", ".", "css", "(", "'a'", ")", "[", "0", "]", "[", "'href'", "]", "}", "end", "return", "processed", "end"], "docstring": "Gets a moderation log\n This is a tricky function, and may break a lot.\n Blame the lack of a real api\n\n @param subreddit [String] The subreddit to fetch from\n @param opts [Hash] Options to pass to reddit\n @option opts [Fixnum] :limit (100) The number to get. Can't be higher than 100\n @option opts [String] :before The \"fullname\" to fetch before.\n @option opts [String] :after The \"fullname\" to fetch after (older than).\n @option opts [String] :type See [reddit API docs](http://www.reddit.com/dev/api#GET_moderationlog)\n @option opts [String] :mod The moderator to get. Name, not ID\n @return [Hash] A hash consisting of the data, first fullname, last fullname, first date, and last date", "docstring_tokens": ["Gets", "a", "moderation", "log", "This", "is", "a", "tricky", "function", "and", "may", "break", "a", "lot", ".", "Blame", "the", "lack", "of", "a", "real", "api"], "sha": "83cbfe4973eeff5a0c7426f4a23457a420273261", "url": "https://github.com/paradox460/snoo/blob/83cbfe4973eeff5a0c7426f4a23457a420273261/lib/snoo/moderation.rb#L69-L93", "partition": "test"} {"repo": "adam12/maxmind", "path": "lib/maxmind/chargeback_request.rb", "func_name": "Maxmind.ChargebackRequest.post", "original_string": "def post(query_params)\n servers ||= SERVERS.map{|hostname| \"https://#{hostname}/minfraud/chargeback\"}\n url = URI.parse(servers.shift)\n\n req = Net::HTTP::Post.new(url.path, initheader = {'Content-Type' =>'application/json'})\n req.basic_auth Maxmind::user_id, Maxmind::license_key\n req.body = query_params\n\n h = Net::HTTP.new(url.host, url.port)\n h.use_ssl = true\n h.verify_mode = OpenSSL::SSL::VERIFY_NONE\n\n # set some timeouts\n h.open_timeout = 60 # this blocks forever by default, lets be a bit less crazy.\n h.read_timeout = self.class.timeout || DefaultTimeout\n h.ssl_timeout = self.class.timeout || DefaultTimeout\n\n h.start { |http| http.request(req) }\n\n rescue Exception => e\n retry if servers.size > 0\n raise e\n end", "language": "ruby", "code": "def post(query_params)\n servers ||= SERVERS.map{|hostname| \"https://#{hostname}/minfraud/chargeback\"}\n url = URI.parse(servers.shift)\n\n req = Net::HTTP::Post.new(url.path, initheader = {'Content-Type' =>'application/json'})\n req.basic_auth Maxmind::user_id, Maxmind::license_key\n req.body = query_params\n\n h = Net::HTTP.new(url.host, url.port)\n h.use_ssl = true\n h.verify_mode = OpenSSL::SSL::VERIFY_NONE\n\n # set some timeouts\n h.open_timeout = 60 # this blocks forever by default, lets be a bit less crazy.\n h.read_timeout = self.class.timeout || DefaultTimeout\n h.ssl_timeout = self.class.timeout || DefaultTimeout\n\n h.start { |http| http.request(req) }\n\n rescue Exception => e\n retry if servers.size > 0\n raise e\n end", "code_tokens": ["def", "post", "(", "query_params", ")", "servers", "||=", "SERVERS", ".", "map", "{", "|", "hostname", "|", "\"https://#{hostname}/minfraud/chargeback\"", "}", "url", "=", "URI", ".", "parse", "(", "servers", ".", "shift", ")", "req", "=", "Net", "::", "HTTP", "::", "Post", ".", "new", "(", "url", ".", "path", ",", "initheader", "=", "{", "'Content-Type'", "=>", "'application/json'", "}", ")", "req", ".", "basic_auth", "Maxmind", "::", "user_id", ",", "Maxmind", "::", "license_key", "req", ".", "body", "=", "query_params", "h", "=", "Net", "::", "HTTP", ".", "new", "(", "url", ".", "host", ",", "url", ".", "port", ")", "h", ".", "use_ssl", "=", "true", "h", ".", "verify_mode", "=", "OpenSSL", "::", "SSL", "::", "VERIFY_NONE", "# set some timeouts", "h", ".", "open_timeout", "=", "60", "# this blocks forever by default, lets be a bit less crazy.", "h", ".", "read_timeout", "=", "self", ".", "class", ".", "timeout", "||", "DefaultTimeout", "h", ".", "ssl_timeout", "=", "self", ".", "class", ".", "timeout", "||", "DefaultTimeout", "h", ".", "start", "{", "|", "http", "|", "http", ".", "request", "(", "req", ")", "}", "rescue", "Exception", "=>", "e", "retry", "if", "servers", ".", "size", ">", "0", "raise", "e", "end"], "docstring": "Upon a failure at the first URL, will automatically retry with the\n second & third ones before finally raising an exception\n Returns an HTTPResponse object", "docstring_tokens": ["Upon", "a", "failure", "at", "the", "first", "URL", "will", "automatically", "retry", "with", "the", "second", "&", "third", "ones", "before", "finally", "raising", "an", "exception", "Returns", "an", "HTTPResponse", "object"], "sha": "db0b53ac203bdc219536a7972623ac06cbda0c5c", "url": "https://github.com/adam12/maxmind/blob/db0b53ac203bdc219536a7972623ac06cbda0c5c/lib/maxmind/chargeback_request.rb#L62-L84", "partition": "test"} {"repo": "kwbock/clipster", "path": "app/models/clipster/clip.rb", "func_name": "Clipster.Clip.lifespan=", "original_string": "def lifespan=(lifespan)\n @lifespan = lifespan\n @@lifespans.each_with_index do |span, index|\n if span[0] == lifespan && lifespan != \"Forever\"\n self.expires = DateTime.now.advance(@@lifespans[index][1])\n end\n end\n end", "language": "ruby", "code": "def lifespan=(lifespan)\n @lifespan = lifespan\n @@lifespans.each_with_index do |span, index|\n if span[0] == lifespan && lifespan != \"Forever\"\n self.expires = DateTime.now.advance(@@lifespans[index][1])\n end\n end\n end", "code_tokens": ["def", "lifespan", "=", "(", "lifespan", ")", "@lifespan", "=", "lifespan", "@@lifespans", ".", "each_with_index", "do", "|", "span", ",", "index", "|", "if", "span", "[", "0", "]", "==", "lifespan", "&&", "lifespan", "!=", "\"Forever\"", "self", ".", "expires", "=", "DateTime", ".", "now", ".", "advance", "(", "@@lifespans", "[", "index", "]", "[", "1", "]", ")", "end", "end", "end"], "docstring": "Setter to convert user's choice of 'A Week', etc. to an actual DateTime", "docstring_tokens": ["Setter", "to", "convert", "user", "s", "choice", "of", "A", "Week", "etc", ".", "to", "an", "actual", "DateTime"], "sha": "212a7da5e13baaa0ef82b8006a05f672e6604600", "url": "https://github.com/kwbock/clipster/blob/212a7da5e13baaa0ef82b8006a05f672e6604600/app/models/clipster/clip.rb#L61-L68", "partition": "test"} {"repo": "kwbock/clipster", "path": "app/models/clipster/clip.rb", "func_name": "Clipster.Clip.div", "original_string": "def div\n cr_scanner = CodeRay.scan(self.clip, self.language)\n # Only show line numbers if its greater than 1\n if cr_scanner.loc <= 1\n return cr_scanner.div\n else\n return cr_scanner.div(:line_numbers => :table)\n end\n end", "language": "ruby", "code": "def div\n cr_scanner = CodeRay.scan(self.clip, self.language)\n # Only show line numbers if its greater than 1\n if cr_scanner.loc <= 1\n return cr_scanner.div\n else\n return cr_scanner.div(:line_numbers => :table)\n end\n end", "code_tokens": ["def", "div", "cr_scanner", "=", "CodeRay", ".", "scan", "(", "self", ".", "clip", ",", "self", ".", "language", ")", "# Only show line numbers if its greater than 1", "if", "cr_scanner", ".", "loc", "<=", "1", "return", "cr_scanner", ".", "div", "else", "return", "cr_scanner", ".", "div", "(", ":line_numbers", "=>", ":table", ")", "end", "end"], "docstring": "Creates the div for the clip", "docstring_tokens": ["Creates", "the", "div", "for", "the", "clip"], "sha": "212a7da5e13baaa0ef82b8006a05f672e6604600", "url": "https://github.com/kwbock/clipster/blob/212a7da5e13baaa0ef82b8006a05f672e6604600/app/models/clipster/clip.rb#L89-L97", "partition": "test"} {"repo": "pitr-ch/htmless", "path": "lib/htmless/abstract.rb", "func_name": "Htmless.Abstract.set_variables", "original_string": "def set_variables(instance_variables)\n instance_variables.each { |name, value| instance_variable_set(\"@#{name}\", value) }\n yield(self)\n instance_variables.each { |name, _| remove_instance_variable(\"@#{name}\") }\n self\n end", "language": "ruby", "code": "def set_variables(instance_variables)\n instance_variables.each { |name, value| instance_variable_set(\"@#{name}\", value) }\n yield(self)\n instance_variables.each { |name, _| remove_instance_variable(\"@#{name}\") }\n self\n end", "code_tokens": ["def", "set_variables", "(", "instance_variables", ")", "instance_variables", ".", "each", "{", "|", "name", ",", "value", "|", "instance_variable_set", "(", "\"@#{name}\"", ",", "value", ")", "}", "yield", "(", "self", ")", "instance_variables", ".", "each", "{", "|", "name", ",", "_", "|", "remove_instance_variable", "(", "\"@#{name}\"", ")", "}", "self", "end"], "docstring": "sets instance variables when block is yielded\n @param [Hash{String => Object}] instance_variables hash of names and values to set\n @yield block when variables are set, variables are cleaned up afterwards", "docstring_tokens": ["sets", "instance", "variables", "when", "block", "is", "yielded"], "sha": "d7ff6c6cd8cad3ea53911a391b73b0cbd2d98ff4", "url": "https://github.com/pitr-ch/htmless/blob/d7ff6c6cd8cad3ea53911a391b73b0cbd2d98ff4/lib/htmless/abstract.rb#L186-L191", "partition": "test"} {"repo": "pitr-ch/htmless", "path": "lib/htmless/abstract.rb", "func_name": "Htmless.Abstract.render", "original_string": "def render(object, method, *args, &block)\n object.__send__ method, self, *args, &block\n self\n end", "language": "ruby", "code": "def render(object, method, *args, &block)\n object.__send__ method, self, *args, &block\n self\n end", "code_tokens": ["def", "render", "(", "object", ",", "method", ",", "*", "args", ",", "&", "block", ")", "object", ".", "__send__", "method", ",", "self", ",", "args", ",", "block", "self", "end"], "docstring": "renders +object+ with +method+\n @param [Object] object an object to render\n @param [Symbol] method a method name which is used for rendering\n @param args arguments passed to rendering method\n @yield block passed to rendering method", "docstring_tokens": ["renders", "+", "object", "+", "with", "+", "method", "+"], "sha": "d7ff6c6cd8cad3ea53911a391b73b0cbd2d98ff4", "url": "https://github.com/pitr-ch/htmless/blob/d7ff6c6cd8cad3ea53911a391b73b0cbd2d98ff4/lib/htmless/abstract.rb#L213-L216", "partition": "test"} {"repo": "pitr-ch/htmless", "path": "lib/htmless/abstract.rb", "func_name": "Htmless.Abstract.join", "original_string": "def join(collection, glue = nil, &it)\n # TODO as helper? two block method call #join(collection, &item).with(&glue)\n glue_block = case glue\n when String\n lambda { text glue }\n when Proc\n glue\n else\n lambda {}\n end\n\n collection.each_with_index do |obj, i|\n glue_block.call() if i > 0\n obj.is_a?(Proc) ? obj.call : it.call(obj)\n end\n end", "language": "ruby", "code": "def join(collection, glue = nil, &it)\n # TODO as helper? two block method call #join(collection, &item).with(&glue)\n glue_block = case glue\n when String\n lambda { text glue }\n when Proc\n glue\n else\n lambda {}\n end\n\n collection.each_with_index do |obj, i|\n glue_block.call() if i > 0\n obj.is_a?(Proc) ? obj.call : it.call(obj)\n end\n end", "code_tokens": ["def", "join", "(", "collection", ",", "glue", "=", "nil", ",", "&", "it", ")", "# TODO as helper? two block method call #join(collection, &item).with(&glue)", "glue_block", "=", "case", "glue", "when", "String", "lambda", "{", "text", "glue", "}", "when", "Proc", "glue", "else", "lambda", "{", "}", "end", "collection", ".", "each_with_index", "do", "|", "obj", ",", "i", "|", "glue_block", ".", "call", "(", ")", "if", "i", ">", "0", "obj", ".", "is_a?", "(", "Proc", ")", "?", "obj", ".", "call", ":", "it", ".", "call", "(", "obj", ")", "end", "end"], "docstring": "joins and renders +collection+ with +glue+\n @param [Array] collection of objects or lambdas\n @param [Proc, String] glue can be String which is rendered with #text or block to render\n @yield how to render objects from +collection+, Proc in collection does not use this block\n @example\n join([1, 1.2], lambda { text ', ' }) {|o| text o } # => \"1, 1.2\"\n join([1, 1.2], ', ') {|o| text o } # => \"1, 1.2\"\n join([->{ text 1 }, 1.2], ', ') {|o| text o } # => \"1, 1.2\"", "docstring_tokens": ["joins", "and", "renders", "+", "collection", "+", "with", "+", "glue", "+"], "sha": "d7ff6c6cd8cad3ea53911a391b73b0cbd2d98ff4", "url": "https://github.com/pitr-ch/htmless/blob/d7ff6c6cd8cad3ea53911a391b73b0cbd2d98ff4/lib/htmless/abstract.rb#L237-L252", "partition": "test"} {"repo": "assetricity/isbm_adaptor", "path": "lib/isbm_adaptor/provider_publication.rb", "func_name": "IsbmAdaptor.ProviderPublication.open_session", "original_string": "def open_session(uri)\n validate_presence_of uri, 'Channel URI'\n\n response = @client.call(:open_publication_session, message: { 'ChannelURI' => uri })\n\n response.to_hash[:open_publication_session_response][:session_id].to_s\n end", "language": "ruby", "code": "def open_session(uri)\n validate_presence_of uri, 'Channel URI'\n\n response = @client.call(:open_publication_session, message: { 'ChannelURI' => uri })\n\n response.to_hash[:open_publication_session_response][:session_id].to_s\n end", "code_tokens": ["def", "open_session", "(", "uri", ")", "validate_presence_of", "uri", ",", "'Channel URI'", "response", "=", "@client", ".", "call", "(", ":open_publication_session", ",", "message", ":", "{", "'ChannelURI'", "=>", "uri", "}", ")", "response", ".", "to_hash", "[", ":open_publication_session_response", "]", "[", ":session_id", "]", ".", "to_s", "end"], "docstring": "Creates a new ISBM ProviderPublication client.\n\n @param endpoint [String] the SOAP endpoint URI\n @option options [Array] :wsse_auth username and password, i.e. [username, password]\n @option options [Object] :logger (Rails.logger or $stdout) location where log should be output\n @option options [Boolean] :log (true) specify whether requests are logged\n @option options [Boolean] :pretty_print_xml (false) specify whether request and response XML are formatted\n Opens a publication session for a channel.\n\n @param uri [String] the channel URI\n @return [String] the session id\n @raise [ArgumentError] if uri is blank", "docstring_tokens": ["Creates", "a", "new", "ISBM", "ProviderPublication", "client", "."], "sha": "67847351bbff3a1538c3ba141fe260e4de59676a", "url": "https://github.com/assetricity/isbm_adaptor/blob/67847351bbff3a1538c3ba141fe260e4de59676a/lib/isbm_adaptor/provider_publication.rb#L23-L29", "partition": "test"} {"repo": "assetricity/isbm_adaptor", "path": "lib/isbm_adaptor/provider_publication.rb", "func_name": "IsbmAdaptor.ProviderPublication.post_publication", "original_string": "def post_publication(session_id, content, topics, expiry = nil)\n validate_presence_of session_id, 'Session Id'\n validate_presence_of content, 'Content'\n validate_presence_of topics, 'Topics'\n validate_xml content\n\n topics = [topics].flatten\n\n # Use Builder to generate XML body as we need to concatenate XML message content\n xml = Builder::XmlMarkup.new\n xml.isbm :SessionID, session_id\n xml.isbm :MessageContent do\n xml << content\n end\n topics.each do |topic|\n xml.isbm :Topic, topic\n end\n duration = expiry.to_s\n xml.isbm :Expiry, duration unless duration.nil?\n\n response = @client.call(:post_publication, message: xml.target!)\n\n response.to_hash[:post_publication_response][:message_id].to_s\n end", "language": "ruby", "code": "def post_publication(session_id, content, topics, expiry = nil)\n validate_presence_of session_id, 'Session Id'\n validate_presence_of content, 'Content'\n validate_presence_of topics, 'Topics'\n validate_xml content\n\n topics = [topics].flatten\n\n # Use Builder to generate XML body as we need to concatenate XML message content\n xml = Builder::XmlMarkup.new\n xml.isbm :SessionID, session_id\n xml.isbm :MessageContent do\n xml << content\n end\n topics.each do |topic|\n xml.isbm :Topic, topic\n end\n duration = expiry.to_s\n xml.isbm :Expiry, duration unless duration.nil?\n\n response = @client.call(:post_publication, message: xml.target!)\n\n response.to_hash[:post_publication_response][:message_id].to_s\n end", "code_tokens": ["def", "post_publication", "(", "session_id", ",", "content", ",", "topics", ",", "expiry", "=", "nil", ")", "validate_presence_of", "session_id", ",", "'Session Id'", "validate_presence_of", "content", ",", "'Content'", "validate_presence_of", "topics", ",", "'Topics'", "validate_xml", "content", "topics", "=", "[", "topics", "]", ".", "flatten", "# Use Builder to generate XML body as we need to concatenate XML message content", "xml", "=", "Builder", "::", "XmlMarkup", ".", "new", "xml", ".", "isbm", ":SessionID", ",", "session_id", "xml", ".", "isbm", ":MessageContent", "do", "xml", "<<", "content", "end", "topics", ".", "each", "do", "|", "topic", "|", "xml", ".", "isbm", ":Topic", ",", "topic", "end", "duration", "=", "expiry", ".", "to_s", "xml", ".", "isbm", ":Expiry", ",", "duration", "unless", "duration", ".", "nil?", "response", "=", "@client", ".", "call", "(", ":post_publication", ",", "message", ":", "xml", ".", "target!", ")", "response", ".", "to_hash", "[", ":post_publication_response", "]", "[", ":message_id", "]", ".", "to_s", "end"], "docstring": "Posts a publication message.\n\n @param session_id [String] the session id\n @param content [String] a valid XML string as message contents\n @param topics [Array, String] a collection of topics or single topic\n @param expiry [Duration] when the message should expire\n @return [String] the message id\n @raise [ArgumentError] if session_id, content or topics are blank, or\n content is not valid XML", "docstring_tokens": ["Posts", "a", "publication", "message", "."], "sha": "67847351bbff3a1538c3ba141fe260e4de59676a", "url": "https://github.com/assetricity/isbm_adaptor/blob/67847351bbff3a1538c3ba141fe260e4de59676a/lib/isbm_adaptor/provider_publication.rb#L40-L63", "partition": "test"} {"repo": "assetricity/isbm_adaptor", "path": "lib/isbm_adaptor/provider_publication.rb", "func_name": "IsbmAdaptor.ProviderPublication.expire_publication", "original_string": "def expire_publication(session_id, message_id)\n validate_presence_of session_id, 'Session Id'\n validate_presence_of message_id, 'Message Id'\n\n @client.call(:expire_publication, message: { 'SessionID' => session_id, 'MessageID' => message_id })\n\n return true\n end", "language": "ruby", "code": "def expire_publication(session_id, message_id)\n validate_presence_of session_id, 'Session Id'\n validate_presence_of message_id, 'Message Id'\n\n @client.call(:expire_publication, message: { 'SessionID' => session_id, 'MessageID' => message_id })\n\n return true\n end", "code_tokens": ["def", "expire_publication", "(", "session_id", ",", "message_id", ")", "validate_presence_of", "session_id", ",", "'Session Id'", "validate_presence_of", "message_id", ",", "'Message Id'", "@client", ".", "call", "(", ":expire_publication", ",", "message", ":", "{", "'SessionID'", "=>", "session_id", ",", "'MessageID'", "=>", "message_id", "}", ")", "return", "true", "end"], "docstring": "Expires a posted publication message.\n\n @param session_id [String] the session id used to post the publication\n @param message_id [String] the message id received after posting the publication\n @return [void]\n @raise [ArgumentError] if session_id or message_id are blank", "docstring_tokens": ["Expires", "a", "posted", "publication", "message", "."], "sha": "67847351bbff3a1538c3ba141fe260e4de59676a", "url": "https://github.com/assetricity/isbm_adaptor/blob/67847351bbff3a1538c3ba141fe260e4de59676a/lib/isbm_adaptor/provider_publication.rb#L71-L78", "partition": "test"} {"repo": "assetricity/isbm_adaptor", "path": "lib/isbm_adaptor/client.rb", "func_name": "IsbmAdaptor.Client.validate_presence_of", "original_string": "def validate_presence_of(value, name)\n if value.respond_to?(:each)\n value.each do |v|\n if v.blank?\n raise ArgumentError, \"Values in #{name} must not be blank\"\n end\n end\n else\n if value.blank?\n raise ArgumentError, \"#{name} must not be blank\"\n end\n end\n end", "language": "ruby", "code": "def validate_presence_of(value, name)\n if value.respond_to?(:each)\n value.each do |v|\n if v.blank?\n raise ArgumentError, \"Values in #{name} must not be blank\"\n end\n end\n else\n if value.blank?\n raise ArgumentError, \"#{name} must not be blank\"\n end\n end\n end", "code_tokens": ["def", "validate_presence_of", "(", "value", ",", "name", ")", "if", "value", ".", "respond_to?", "(", ":each", ")", "value", ".", "each", "do", "|", "v", "|", "if", "v", ".", "blank?", "raise", "ArgumentError", ",", "\"Values in #{name} must not be blank\"", "end", "end", "else", "if", "value", ".", "blank?", "raise", "ArgumentError", ",", "\"#{name} must not be blank\"", "end", "end", "end"], "docstring": "Creates a new ISBM client.\n\n @param wsdl_file [String] the filename of the WSDL\n @param endpoint [String] the SOAP endpoint URI\n @option options [Object] :logger (Rails.logger or $stdout) location where log should be output\n @option options [Boolean] :log (true) specify whether requests are logged\n @option options [Boolean] :pretty_print_xml (false) specify whether request and response XML are formatted\n Validates the presence of the passed value.\n\n @param value [Object] object to validate presence\n @param name [String] name of value to include in error message if not present\n @return [void]\n @raise [ArgumentError] if value is not present", "docstring_tokens": ["Creates", "a", "new", "ISBM", "client", "."], "sha": "67847351bbff3a1538c3ba141fe260e4de59676a", "url": "https://github.com/assetricity/isbm_adaptor/blob/67847351bbff3a1538c3ba141fe260e4de59676a/lib/isbm_adaptor/client.rb#L25-L37", "partition": "test"} {"repo": "assetricity/isbm_adaptor", "path": "lib/isbm_adaptor/client.rb", "func_name": "IsbmAdaptor.Client.validate_xml", "original_string": "def validate_xml(xml)\n doc = Nokogiri.XML(xml)\n raise ArgumentError, \"XML is not well formed: #{xml}\" unless doc.errors.empty?\n end", "language": "ruby", "code": "def validate_xml(xml)\n doc = Nokogiri.XML(xml)\n raise ArgumentError, \"XML is not well formed: #{xml}\" unless doc.errors.empty?\n end", "code_tokens": ["def", "validate_xml", "(", "xml", ")", "doc", "=", "Nokogiri", ".", "XML", "(", "xml", ")", "raise", "ArgumentError", ",", "\"XML is not well formed: #{xml}\"", "unless", "doc", ".", "errors", ".", "empty?", "end"], "docstring": "Validates the well formedness of the XML string and raises an error if\n any errors are encountered.\n\n @param xml [String] the XML string to parse\n @return [void]", "docstring_tokens": ["Validates", "the", "well", "formedness", "of", "the", "XML", "string", "and", "raises", "an", "error", "if", "any", "errors", "are", "encountered", "."], "sha": "67847351bbff3a1538c3ba141fe260e4de59676a", "url": "https://github.com/assetricity/isbm_adaptor/blob/67847351bbff3a1538c3ba141fe260e4de59676a/lib/isbm_adaptor/client.rb#L57-L60", "partition": "test"} {"repo": "assetricity/isbm_adaptor", "path": "lib/isbm_adaptor/client.rb", "func_name": "IsbmAdaptor.Client.default_savon_options", "original_string": "def default_savon_options(options)\n options[:logger] = Rails.logger if options[:logger].nil? && defined?(Rails)\n options[:log] = false if options[:log].nil?\n options[:pretty_print_xml] = true if options[:pretty_print_xml].nil?\n end", "language": "ruby", "code": "def default_savon_options(options)\n options[:logger] = Rails.logger if options[:logger].nil? && defined?(Rails)\n options[:log] = false if options[:log].nil?\n options[:pretty_print_xml] = true if options[:pretty_print_xml].nil?\n end", "code_tokens": ["def", "default_savon_options", "(", "options", ")", "options", "[", ":logger", "]", "=", "Rails", ".", "logger", "if", "options", "[", ":logger", "]", ".", "nil?", "&&", "defined?", "(", "Rails", ")", "options", "[", ":log", "]", "=", "false", "if", "options", "[", ":log", "]", ".", "nil?", "options", "[", ":pretty_print_xml", "]", "=", "true", "if", "options", "[", ":pretty_print_xml", "]", ".", "nil?", "end"], "docstring": "Sets default values for certain Savon options.\n\n @param options [Hash] the options to set defaults on\n @return [Hash] options hash with defaults set", "docstring_tokens": ["Sets", "default", "values", "for", "certain", "Savon", "options", "."], "sha": "67847351bbff3a1538c3ba141fe260e4de59676a", "url": "https://github.com/assetricity/isbm_adaptor/blob/67847351bbff3a1538c3ba141fe260e4de59676a/lib/isbm_adaptor/client.rb#L109-L113", "partition": "test"} {"repo": "assetricity/isbm_adaptor", "path": "lib/isbm_adaptor/consumer_publication.rb", "func_name": "IsbmAdaptor.ConsumerPublication.read_publication", "original_string": "def read_publication(session_id)\n validate_presence_of session_id, 'Session Id'\n\n response = @client.call(:read_publication, message: { 'SessionID' => session_id })\n\n extract_message(response)\n end", "language": "ruby", "code": "def read_publication(session_id)\n validate_presence_of session_id, 'Session Id'\n\n response = @client.call(:read_publication, message: { 'SessionID' => session_id })\n\n extract_message(response)\n end", "code_tokens": ["def", "read_publication", "(", "session_id", ")", "validate_presence_of", "session_id", ",", "'Session Id'", "response", "=", "@client", ".", "call", "(", ":read_publication", ",", "message", ":", "{", "'SessionID'", "=>", "session_id", "}", ")", "extract_message", "(", "response", ")", "end"], "docstring": "Reads the first message, if any, in the session queue.\n\n @param session_id [String] the session id\n @return [Message] first message in session queue. nil if no message.\n @raise [ArgumentError] if session_id is blank", "docstring_tokens": ["Reads", "the", "first", "message", "if", "any", "in", "the", "session", "queue", "."], "sha": "67847351bbff3a1538c3ba141fe260e4de59676a", "url": "https://github.com/assetricity/isbm_adaptor/blob/67847351bbff3a1538c3ba141fe260e4de59676a/lib/isbm_adaptor/consumer_publication.rb#L60-L66", "partition": "test"} {"repo": "assetricity/isbm_adaptor", "path": "lib/isbm_adaptor/consumer_request.rb", "func_name": "IsbmAdaptor.ConsumerRequest.open_session", "original_string": "def open_session(uri, listener_url = nil)\n validate_presence_of uri, 'Channel URI'\n\n message = { 'ChannelURI' => uri }\n message['ListenerURL'] = listener_url if listener_url\n\n response = @client.call(:open_consumer_request_session, message: message)\n\n response.to_hash[:open_consumer_request_session_response][:session_id].to_s\n end", "language": "ruby", "code": "def open_session(uri, listener_url = nil)\n validate_presence_of uri, 'Channel URI'\n\n message = { 'ChannelURI' => uri }\n message['ListenerURL'] = listener_url if listener_url\n\n response = @client.call(:open_consumer_request_session, message: message)\n\n response.to_hash[:open_consumer_request_session_response][:session_id].to_s\n end", "code_tokens": ["def", "open_session", "(", "uri", ",", "listener_url", "=", "nil", ")", "validate_presence_of", "uri", ",", "'Channel URI'", "message", "=", "{", "'ChannelURI'", "=>", "uri", "}", "message", "[", "'ListenerURL'", "]", "=", "listener_url", "if", "listener_url", "response", "=", "@client", ".", "call", "(", ":open_consumer_request_session", ",", "message", ":", "message", ")", "response", ".", "to_hash", "[", ":open_consumer_request_session_response", "]", "[", ":session_id", "]", ".", "to_s", "end"], "docstring": "Creates a new ISBM ConsumerRequest client.\n\n @param endpoint [String] the SOAP endpoint URI\n @option options [Array] :wsse_auth username and password, i.e. [username, password]\n @option options [Object] :logger (Rails.logger or $stdout) location where log should be output\n @option options [Boolean] :log (true) specify whether requests are logged\n @option options [Boolean] :pretty_print_xml (false) specify whether request and response XML are formatted\n Opens a consumer request session for a channel for posting requests and\n reading responses.\n\n @param uri [String] the channel URI\n @param listener_url [String] the URL for notification callbacks\n @return [String] the session id\n @raise [ArgumentError] if uri is blank", "docstring_tokens": ["Creates", "a", "new", "ISBM", "ConsumerRequest", "client", "."], "sha": "67847351bbff3a1538c3ba141fe260e4de59676a", "url": "https://github.com/assetricity/isbm_adaptor/blob/67847351bbff3a1538c3ba141fe260e4de59676a/lib/isbm_adaptor/consumer_request.rb#L24-L33", "partition": "test"} {"repo": "assetricity/isbm_adaptor", "path": "lib/isbm_adaptor/consumer_request.rb", "func_name": "IsbmAdaptor.ConsumerRequest.post_request", "original_string": "def post_request(session_id, content, topic, expiry = nil)\n validate_presence_of session_id, 'Session Id'\n validate_presence_of content, 'Content'\n validate_presence_of topic, 'Topic'\n validate_xml content\n\n # Use Builder to generate XML body as we need to concatenate XML message content\n xml = Builder::XmlMarkup.new\n xml.isbm :SessionID, session_id\n xml.isbm :MessageContent do\n xml << content\n end\n xml.isbm :Topic, topic\n duration = expiry.to_s\n xml.isbm :Expiry, duration unless duration.nil?\n\n response = @client.call(:post_request, message: xml.target!)\n\n response.to_hash[:post_request_response][:message_id].to_s\n end", "language": "ruby", "code": "def post_request(session_id, content, topic, expiry = nil)\n validate_presence_of session_id, 'Session Id'\n validate_presence_of content, 'Content'\n validate_presence_of topic, 'Topic'\n validate_xml content\n\n # Use Builder to generate XML body as we need to concatenate XML message content\n xml = Builder::XmlMarkup.new\n xml.isbm :SessionID, session_id\n xml.isbm :MessageContent do\n xml << content\n end\n xml.isbm :Topic, topic\n duration = expiry.to_s\n xml.isbm :Expiry, duration unless duration.nil?\n\n response = @client.call(:post_request, message: xml.target!)\n\n response.to_hash[:post_request_response][:message_id].to_s\n end", "code_tokens": ["def", "post_request", "(", "session_id", ",", "content", ",", "topic", ",", "expiry", "=", "nil", ")", "validate_presence_of", "session_id", ",", "'Session Id'", "validate_presence_of", "content", ",", "'Content'", "validate_presence_of", "topic", ",", "'Topic'", "validate_xml", "content", "# Use Builder to generate XML body as we need to concatenate XML message content", "xml", "=", "Builder", "::", "XmlMarkup", ".", "new", "xml", ".", "isbm", ":SessionID", ",", "session_id", "xml", ".", "isbm", ":MessageContent", "do", "xml", "<<", "content", "end", "xml", ".", "isbm", ":Topic", ",", "topic", "duration", "=", "expiry", ".", "to_s", "xml", ".", "isbm", ":Expiry", ",", "duration", "unless", "duration", ".", "nil?", "response", "=", "@client", ".", "call", "(", ":post_request", ",", "message", ":", "xml", ".", "target!", ")", "response", ".", "to_hash", "[", ":post_request_response", "]", "[", ":message_id", "]", ".", "to_s", "end"], "docstring": "Posts a request message on a channel.\n\n @param session_id [String] the session id\n @param content [String] a valid XML string as message contents\n @param topic [String] the topic\n @param expiry [Duration] when the message should expire\n @return [String] the request message id\n @raise [ArgumentError] if session_id, content or topics are blank, or\n content is not valid XML", "docstring_tokens": ["Posts", "a", "request", "message", "on", "a", "channel", "."], "sha": "67847351bbff3a1538c3ba141fe260e4de59676a", "url": "https://github.com/assetricity/isbm_adaptor/blob/67847351bbff3a1538c3ba141fe260e4de59676a/lib/isbm_adaptor/consumer_request.rb#L44-L63", "partition": "test"} {"repo": "assetricity/isbm_adaptor", "path": "lib/isbm_adaptor/consumer_request.rb", "func_name": "IsbmAdaptor.ConsumerRequest.expire_request", "original_string": "def expire_request(session_id, message_id)\n validate_presence_of session_id, 'Session Id'\n validate_presence_of message_id, 'Message Id'\n\n @client.call(:expire_request, message: { 'SessionID' => session_id, 'MessageID' => message_id })\n\n return true\n end", "language": "ruby", "code": "def expire_request(session_id, message_id)\n validate_presence_of session_id, 'Session Id'\n validate_presence_of message_id, 'Message Id'\n\n @client.call(:expire_request, message: { 'SessionID' => session_id, 'MessageID' => message_id })\n\n return true\n end", "code_tokens": ["def", "expire_request", "(", "session_id", ",", "message_id", ")", "validate_presence_of", "session_id", ",", "'Session Id'", "validate_presence_of", "message_id", ",", "'Message Id'", "@client", ".", "call", "(", ":expire_request", ",", "message", ":", "{", "'SessionID'", "=>", "session_id", ",", "'MessageID'", "=>", "message_id", "}", ")", "return", "true", "end"], "docstring": "Expires a posted request message.\n\n @param session_id [String] the session id used to post the request\n @param message_id [String] the message id received after posting the request\n @return [void]\n @raise [ArgumentError] if session_id or message_id are blank", "docstring_tokens": ["Expires", "a", "posted", "request", "message", "."], "sha": "67847351bbff3a1538c3ba141fe260e4de59676a", "url": "https://github.com/assetricity/isbm_adaptor/blob/67847351bbff3a1538c3ba141fe260e4de59676a/lib/isbm_adaptor/consumer_request.rb#L71-L78", "partition": "test"} {"repo": "assetricity/isbm_adaptor", "path": "lib/isbm_adaptor/consumer_request.rb", "func_name": "IsbmAdaptor.ConsumerRequest.read_response", "original_string": "def read_response(session_id, request_message_id)\n validate_presence_of session_id, 'Session Id'\n validate_presence_of request_message_id, 'Request Message Id'\n\n message = { 'SessionID' => session_id, 'RequestMessageID' => request_message_id }\n response = @client.call(:read_response, message: message)\n\n extract_message(response)\n end", "language": "ruby", "code": "def read_response(session_id, request_message_id)\n validate_presence_of session_id, 'Session Id'\n validate_presence_of request_message_id, 'Request Message Id'\n\n message = { 'SessionID' => session_id, 'RequestMessageID' => request_message_id }\n response = @client.call(:read_response, message: message)\n\n extract_message(response)\n end", "code_tokens": ["def", "read_response", "(", "session_id", ",", "request_message_id", ")", "validate_presence_of", "session_id", ",", "'Session Id'", "validate_presence_of", "request_message_id", ",", "'Request Message Id'", "message", "=", "{", "'SessionID'", "=>", "session_id", ",", "'RequestMessageID'", "=>", "request_message_id", "}", "response", "=", "@client", ".", "call", "(", ":read_response", ",", "message", ":", "message", ")", "extract_message", "(", "response", ")", "end"], "docstring": "Returns the first response message, if any, in the message queue\n associated with the request.\n\n @param session_id [String] the session id\n @param request_message_id [String] the id of the original request message\n @return [Message] the first message in the queue for the session.\n nil if no message.\n @raise [ArgumentError] if session_id or request_message_id are blank", "docstring_tokens": ["Returns", "the", "first", "response", "message", "if", "any", "in", "the", "message", "queue", "associated", "with", "the", "request", "."], "sha": "67847351bbff3a1538c3ba141fe260e4de59676a", "url": "https://github.com/assetricity/isbm_adaptor/blob/67847351bbff3a1538c3ba141fe260e4de59676a/lib/isbm_adaptor/consumer_request.rb#L88-L96", "partition": "test"} {"repo": "assetricity/isbm_adaptor", "path": "lib/isbm_adaptor/consumer_request.rb", "func_name": "IsbmAdaptor.ConsumerRequest.remove_response", "original_string": "def remove_response(session_id, request_message_id)\n validate_presence_of session_id, 'Session Id'\n validate_presence_of request_message_id, 'Request Message Id'\n\n message = { 'SessionID' => session_id, 'RequestMessageID' => request_message_id }\n @client.call(:remove_response, message: message)\n\n return true\n end", "language": "ruby", "code": "def remove_response(session_id, request_message_id)\n validate_presence_of session_id, 'Session Id'\n validate_presence_of request_message_id, 'Request Message Id'\n\n message = { 'SessionID' => session_id, 'RequestMessageID' => request_message_id }\n @client.call(:remove_response, message: message)\n\n return true\n end", "code_tokens": ["def", "remove_response", "(", "session_id", ",", "request_message_id", ")", "validate_presence_of", "session_id", ",", "'Session Id'", "validate_presence_of", "request_message_id", ",", "'Request Message Id'", "message", "=", "{", "'SessionID'", "=>", "session_id", ",", "'RequestMessageID'", "=>", "request_message_id", "}", "@client", ".", "call", "(", ":remove_response", ",", "message", ":", "message", ")", "return", "true", "end"], "docstring": "Deletes the first response message, if any, in the message queue\n associated with the request.\n\n @param session_id [String] the session id\n @param request_message_id [String] the id of the original request message\n @return [void]\n @raise [ArgumentError] if session_id is blank", "docstring_tokens": ["Deletes", "the", "first", "response", "message", "if", "any", "in", "the", "message", "queue", "associated", "with", "the", "request", "."], "sha": "67847351bbff3a1538c3ba141fe260e4de59676a", "url": "https://github.com/assetricity/isbm_adaptor/blob/67847351bbff3a1538c3ba141fe260e4de59676a/lib/isbm_adaptor/consumer_request.rb#L105-L113", "partition": "test"} {"repo": "assetricity/isbm_adaptor", "path": "lib/isbm_adaptor/provider_request.rb", "func_name": "IsbmAdaptor.ProviderRequest.open_session", "original_string": "def open_session(uri, topics, listener_url = nil, xpath_expression = nil, xpath_namespaces = [])\n validate_presence_of uri, 'Channel URI'\n validate_presence_of topics, 'Topics'\n validate_presence_of xpath_expression, 'XPath Expression' if xpath_namespaces.present?\n\n topics = [topics].flatten\n\n # Use Builder to generate XML body as we may have multiple Topic elements\n xml = Builder::XmlMarkup.new\n xml.isbm :ChannelURI, uri\n topics.each do |topic|\n xml.isbm :Topic, topic\n end\n xml.isbm :ListenerURL, listener_url unless listener_url.nil?\n xml.isbm :XPathExpression, xpath_expression unless xpath_expression.nil?\n xpath_namespaces.each do |prefix, name|\n xml.isbm :XPathNamespace do\n xml.isbm :NamespacePrefix, prefix\n xml.isbm :NamespaceName, name\n end\n end\n\n response = @client.call(:open_provider_request_session, message: xml.target!)\n\n response.to_hash[:open_provider_request_session_response][:session_id].to_s\n end", "language": "ruby", "code": "def open_session(uri, topics, listener_url = nil, xpath_expression = nil, xpath_namespaces = [])\n validate_presence_of uri, 'Channel URI'\n validate_presence_of topics, 'Topics'\n validate_presence_of xpath_expression, 'XPath Expression' if xpath_namespaces.present?\n\n topics = [topics].flatten\n\n # Use Builder to generate XML body as we may have multiple Topic elements\n xml = Builder::XmlMarkup.new\n xml.isbm :ChannelURI, uri\n topics.each do |topic|\n xml.isbm :Topic, topic\n end\n xml.isbm :ListenerURL, listener_url unless listener_url.nil?\n xml.isbm :XPathExpression, xpath_expression unless xpath_expression.nil?\n xpath_namespaces.each do |prefix, name|\n xml.isbm :XPathNamespace do\n xml.isbm :NamespacePrefix, prefix\n xml.isbm :NamespaceName, name\n end\n end\n\n response = @client.call(:open_provider_request_session, message: xml.target!)\n\n response.to_hash[:open_provider_request_session_response][:session_id].to_s\n end", "code_tokens": ["def", "open_session", "(", "uri", ",", "topics", ",", "listener_url", "=", "nil", ",", "xpath_expression", "=", "nil", ",", "xpath_namespaces", "=", "[", "]", ")", "validate_presence_of", "uri", ",", "'Channel URI'", "validate_presence_of", "topics", ",", "'Topics'", "validate_presence_of", "xpath_expression", ",", "'XPath Expression'", "if", "xpath_namespaces", ".", "present?", "topics", "=", "[", "topics", "]", ".", "flatten", "# Use Builder to generate XML body as we may have multiple Topic elements", "xml", "=", "Builder", "::", "XmlMarkup", ".", "new", "xml", ".", "isbm", ":ChannelURI", ",", "uri", "topics", ".", "each", "do", "|", "topic", "|", "xml", ".", "isbm", ":Topic", ",", "topic", "end", "xml", ".", "isbm", ":ListenerURL", ",", "listener_url", "unless", "listener_url", ".", "nil?", "xml", ".", "isbm", ":XPathExpression", ",", "xpath_expression", "unless", "xpath_expression", ".", "nil?", "xpath_namespaces", ".", "each", "do", "|", "prefix", ",", "name", "|", "xml", ".", "isbm", ":XPathNamespace", "do", "xml", ".", "isbm", ":NamespacePrefix", ",", "prefix", "xml", ".", "isbm", ":NamespaceName", ",", "name", "end", "end", "response", "=", "@client", ".", "call", "(", ":open_provider_request_session", ",", "message", ":", "xml", ".", "target!", ")", "response", ".", "to_hash", "[", ":open_provider_request_session_response", "]", "[", ":session_id", "]", ".", "to_s", "end"], "docstring": "Creates a new ISBM ProviderRequest client.\n\n @param endpoint [String] the SOAP endpoint URI\n @option options [Array] :wsse_auth username and password, i.e. [username, password]\n @option options [Object] :logger (Rails.logger or $stdout) location where log should be output\n @option options [Boolean] :log (true) specify whether requests are logged\n @option options [Boolean] :pretty_print_xml (false) specify whether request and response XML are formatted\n Opens a provider request session for a channel for reading requests and\n posting responses.\n\n @param uri [String] the channel URI\n @param topics [Array, String] a collection of topics or single topic\n @param listener_url [String] the URL for notification callbacks\n @param xpath_expression [String] the XPath filter expression\n @param xpath_namespaces [Array] the prefixes and namespaces used by the XPath expression. The hash key\n represents the namespace prefix while the value represents the namespace name. For example,\n [\"xs\" => \"http://www.w3.org/2001/XMLSchema\", \"isbm\" => \"http://www.openoandm.org/xml/ISBM/\"]\n @return [String] the session id\n @raise [ArgumentError] if uri or topics are blank", "docstring_tokens": ["Creates", "a", "new", "ISBM", "ProviderRequest", "client", "."], "sha": "67847351bbff3a1538c3ba141fe260e4de59676a", "url": "https://github.com/assetricity/isbm_adaptor/blob/67847351bbff3a1538c3ba141fe260e4de59676a/lib/isbm_adaptor/provider_request.rb#L29-L54", "partition": "test"} {"repo": "assetricity/isbm_adaptor", "path": "lib/isbm_adaptor/provider_request.rb", "func_name": "IsbmAdaptor.ProviderRequest.post_response", "original_string": "def post_response(session_id, request_message_id, content)\n validate_presence_of session_id, 'Session Id'\n validate_presence_of request_message_id, 'Request Message Id'\n validate_presence_of content, 'Content'\n validate_xml content\n\n # Use Builder to generate XML body as we need to concatenate XML message content\n xml = Builder::XmlMarkup.new\n xml.isbm :SessionID, session_id\n xml.isbm :RequestMessageID, request_message_id\n xml.isbm :MessageContent do\n xml << content\n end\n\n response = @client.call(:post_response, message: xml.target!)\n\n response.to_hash[:post_response_response][:message_id].to_s\n end", "language": "ruby", "code": "def post_response(session_id, request_message_id, content)\n validate_presence_of session_id, 'Session Id'\n validate_presence_of request_message_id, 'Request Message Id'\n validate_presence_of content, 'Content'\n validate_xml content\n\n # Use Builder to generate XML body as we need to concatenate XML message content\n xml = Builder::XmlMarkup.new\n xml.isbm :SessionID, session_id\n xml.isbm :RequestMessageID, request_message_id\n xml.isbm :MessageContent do\n xml << content\n end\n\n response = @client.call(:post_response, message: xml.target!)\n\n response.to_hash[:post_response_response][:message_id].to_s\n end", "code_tokens": ["def", "post_response", "(", "session_id", ",", "request_message_id", ",", "content", ")", "validate_presence_of", "session_id", ",", "'Session Id'", "validate_presence_of", "request_message_id", ",", "'Request Message Id'", "validate_presence_of", "content", ",", "'Content'", "validate_xml", "content", "# Use Builder to generate XML body as we need to concatenate XML message content", "xml", "=", "Builder", "::", "XmlMarkup", ".", "new", "xml", ".", "isbm", ":SessionID", ",", "session_id", "xml", ".", "isbm", ":RequestMessageID", ",", "request_message_id", "xml", ".", "isbm", ":MessageContent", "do", "xml", "<<", "content", "end", "response", "=", "@client", ".", "call", "(", ":post_response", ",", "message", ":", "xml", ".", "target!", ")", "response", ".", "to_hash", "[", ":post_response_response", "]", "[", ":message_id", "]", ".", "to_s", "end"], "docstring": "Posts a response message on a channel.\n\n @param session_id [String] the session id\n @param request_message_id [String] the id of the original request message\n @param content [String] a valid XML string as message contents\n @return [String] the response message id\n @raise [ArgumentError] if session_id, request_message_id or content are\n blank, or content is not valid XML", "docstring_tokens": ["Posts", "a", "response", "message", "on", "a", "channel", "."], "sha": "67847351bbff3a1538c3ba141fe260e4de59676a", "url": "https://github.com/assetricity/isbm_adaptor/blob/67847351bbff3a1538c3ba141fe260e4de59676a/lib/isbm_adaptor/provider_request.rb#L93-L110", "partition": "test"} {"repo": "assetricity/isbm_adaptor", "path": "lib/isbm_adaptor/channel_management.rb", "func_name": "IsbmAdaptor.ChannelManagement.create_channel", "original_string": "def create_channel(uri, type, description = nil, tokens = {})\n validate_presence_of uri, 'Channel URI'\n validate_presence_of type, 'Channel Type'\n channel_type = type.to_s.downcase.capitalize\n validate_inclusion_in channel_type, IsbmAdaptor::Channel::TYPES, 'Channel Type'\n\n message = { 'ChannelURI' => uri,\n 'ChannelType' => channel_type }\n message['ChannelDescription'] = description unless description.nil?\n message['SecurityToken'] = security_token_hash(tokens) if tokens.any?\n\n @client.call(:create_channel, message: message)\n\n return true\n end", "language": "ruby", "code": "def create_channel(uri, type, description = nil, tokens = {})\n validate_presence_of uri, 'Channel URI'\n validate_presence_of type, 'Channel Type'\n channel_type = type.to_s.downcase.capitalize\n validate_inclusion_in channel_type, IsbmAdaptor::Channel::TYPES, 'Channel Type'\n\n message = { 'ChannelURI' => uri,\n 'ChannelType' => channel_type }\n message['ChannelDescription'] = description unless description.nil?\n message['SecurityToken'] = security_token_hash(tokens) if tokens.any?\n\n @client.call(:create_channel, message: message)\n\n return true\n end", "code_tokens": ["def", "create_channel", "(", "uri", ",", "type", ",", "description", "=", "nil", ",", "tokens", "=", "{", "}", ")", "validate_presence_of", "uri", ",", "'Channel URI'", "validate_presence_of", "type", ",", "'Channel Type'", "channel_type", "=", "type", ".", "to_s", ".", "downcase", ".", "capitalize", "validate_inclusion_in", "channel_type", ",", "IsbmAdaptor", "::", "Channel", "::", "TYPES", ",", "'Channel Type'", "message", "=", "{", "'ChannelURI'", "=>", "uri", ",", "'ChannelType'", "=>", "channel_type", "}", "message", "[", "'ChannelDescription'", "]", "=", "description", "unless", "description", ".", "nil?", "message", "[", "'SecurityToken'", "]", "=", "security_token_hash", "(", "tokens", ")", "if", "tokens", ".", "any?", "@client", ".", "call", "(", ":create_channel", ",", "message", ":", "message", ")", "return", "true", "end"], "docstring": "Creates a new ISBM ChannelManagement client.\n\n @param endpoint [String] the SOAP endpoint URI\n @option options [Array] :wsse_auth username and password, i.e. [username, password]\n @option options [Object] :logger (Rails.logger or $stdout) location where log should be output\n @option options [Boolean] :log (true) specify whether requests are logged\n @option options [Boolean] :pretty_print_xml (false) specify whether request and response XML are formatted\n Creates a new channel.\n\n @param uri [String] the channel URI\n @param type [Symbol] the channel type, either publication or request (symbol or titleized string)\n @param description [String] the channel description, defaults to nil\n @param tokens [Hash] username password pairs, e.g. {'u1' => 'p1', 'u2' => 'p2'}\n @return [void]\n @raise [ArgumentError] if uri or type are blank or type is not a valid Symbol", "docstring_tokens": ["Creates", "a", "new", "ISBM", "ChannelManagement", "client", "."], "sha": "67847351bbff3a1538c3ba141fe260e4de59676a", "url": "https://github.com/assetricity/isbm_adaptor/blob/67847351bbff3a1538c3ba141fe260e4de59676a/lib/isbm_adaptor/channel_management.rb#L25-L39", "partition": "test"} {"repo": "assetricity/isbm_adaptor", "path": "lib/isbm_adaptor/channel_management.rb", "func_name": "IsbmAdaptor.ChannelManagement.add_security_tokens", "original_string": "def add_security_tokens(uri, tokens = {})\n validate_presence_of uri, 'Channel URI'\n validate_presence_of tokens, 'Security Tokens'\n\n message = { 'ChannelURI' => uri,\n 'SecurityToken' => security_token_hash(tokens) }\n\n @client.call(:add_security_tokens, message: message)\n\n return true\n end", "language": "ruby", "code": "def add_security_tokens(uri, tokens = {})\n validate_presence_of uri, 'Channel URI'\n validate_presence_of tokens, 'Security Tokens'\n\n message = { 'ChannelURI' => uri,\n 'SecurityToken' => security_token_hash(tokens) }\n\n @client.call(:add_security_tokens, message: message)\n\n return true\n end", "code_tokens": ["def", "add_security_tokens", "(", "uri", ",", "tokens", "=", "{", "}", ")", "validate_presence_of", "uri", ",", "'Channel URI'", "validate_presence_of", "tokens", ",", "'Security Tokens'", "message", "=", "{", "'ChannelURI'", "=>", "uri", ",", "'SecurityToken'", "=>", "security_token_hash", "(", "tokens", ")", "}", "@client", ".", "call", "(", ":add_security_tokens", ",", "message", ":", "message", ")", "return", "true", "end"], "docstring": "Adds security tokens to a channel.\n\n @param uri [String] the channel URI\n @param tokens [Hash] username password pairs, e.g. {'u1' => 'p1', 'u2' => 'p2'}\n @return [void]\n @raise [ArgumentError] if uri is blank or no tokens are provided", "docstring_tokens": ["Adds", "security", "tokens", "to", "a", "channel", "."], "sha": "67847351bbff3a1538c3ba141fe260e4de59676a", "url": "https://github.com/assetricity/isbm_adaptor/blob/67847351bbff3a1538c3ba141fe260e4de59676a/lib/isbm_adaptor/channel_management.rb#L47-L57", "partition": "test"} {"repo": "assetricity/isbm_adaptor", "path": "lib/isbm_adaptor/channel_management.rb", "func_name": "IsbmAdaptor.ChannelManagement.remove_security_tokens", "original_string": "def remove_security_tokens(uri, tokens = {})\n validate_presence_of uri, 'Channel URI'\n validate_presence_of tokens, 'Security Tokens'\n\n message = { 'ChannelURI' => uri,\n 'SecurityToken' => security_token_hash(tokens) }\n\n @client.call(:remove_security_tokens, message: message)\n\n return true\n end", "language": "ruby", "code": "def remove_security_tokens(uri, tokens = {})\n validate_presence_of uri, 'Channel URI'\n validate_presence_of tokens, 'Security Tokens'\n\n message = { 'ChannelURI' => uri,\n 'SecurityToken' => security_token_hash(tokens) }\n\n @client.call(:remove_security_tokens, message: message)\n\n return true\n end", "code_tokens": ["def", "remove_security_tokens", "(", "uri", ",", "tokens", "=", "{", "}", ")", "validate_presence_of", "uri", ",", "'Channel URI'", "validate_presence_of", "tokens", ",", "'Security Tokens'", "message", "=", "{", "'ChannelURI'", "=>", "uri", ",", "'SecurityToken'", "=>", "security_token_hash", "(", "tokens", ")", "}", "@client", ".", "call", "(", ":remove_security_tokens", ",", "message", ":", "message", ")", "return", "true", "end"], "docstring": "Removes security tokens from a channel.\n\n @param uri [String] the channel URI\n @param tokens [Hash] username password pairs, e.g. {'u1' => 'p1', 'u2' => 'p2'}\n @return [void]\n @raise [ArgumentError] if uri is blank or no tokens are provided", "docstring_tokens": ["Removes", "security", "tokens", "from", "a", "channel", "."], "sha": "67847351bbff3a1538c3ba141fe260e4de59676a", "url": "https://github.com/assetricity/isbm_adaptor/blob/67847351bbff3a1538c3ba141fe260e4de59676a/lib/isbm_adaptor/channel_management.rb#L65-L75", "partition": "test"} {"repo": "assetricity/isbm_adaptor", "path": "lib/isbm_adaptor/channel_management.rb", "func_name": "IsbmAdaptor.ChannelManagement.get_channel", "original_string": "def get_channel(uri, &block)\n validate_presence_of uri, 'Channel URI'\n\n response = @client.call(:get_channel, message: { 'ChannelURI' => uri }, &block)\n\n hash = response.to_hash[:get_channel_response][:channel]\n IsbmAdaptor::Channel.from_hash(hash)\n end", "language": "ruby", "code": "def get_channel(uri, &block)\n validate_presence_of uri, 'Channel URI'\n\n response = @client.call(:get_channel, message: { 'ChannelURI' => uri }, &block)\n\n hash = response.to_hash[:get_channel_response][:channel]\n IsbmAdaptor::Channel.from_hash(hash)\n end", "code_tokens": ["def", "get_channel", "(", "uri", ",", "&", "block", ")", "validate_presence_of", "uri", ",", "'Channel URI'", "response", "=", "@client", ".", "call", "(", ":get_channel", ",", "message", ":", "{", "'ChannelURI'", "=>", "uri", "}", ",", "block", ")", "hash", "=", "response", ".", "to_hash", "[", ":get_channel_response", "]", "[", ":channel", "]", "IsbmAdaptor", "::", "Channel", ".", "from_hash", "(", "hash", ")", "end"], "docstring": "Gets information about the specified channel.\n\n @param uri [String] the channel URI\n @yield locals local options, including :wsse_auth\n @return [Channel] the queried channel\n @raise [ArgumentError] if uri is blank", "docstring_tokens": ["Gets", "information", "about", "the", "specified", "channel", "."], "sha": "67847351bbff3a1538c3ba141fe260e4de59676a", "url": "https://github.com/assetricity/isbm_adaptor/blob/67847351bbff3a1538c3ba141fe260e4de59676a/lib/isbm_adaptor/channel_management.rb#L96-L103", "partition": "test"} {"repo": "assetricity/isbm_adaptor", "path": "lib/isbm_adaptor/channel_management.rb", "func_name": "IsbmAdaptor.ChannelManagement.get_channels", "original_string": "def get_channels(&block)\n response = @client.call(:get_channels, {}, &block)\n\n channels = response.to_hash[:get_channels_response][:channel]\n channels = [channels].compact unless channels.is_a?(Array)\n channels.map do |hash|\n IsbmAdaptor::Channel.from_hash(hash)\n end\n end", "language": "ruby", "code": "def get_channels(&block)\n response = @client.call(:get_channels, {}, &block)\n\n channels = response.to_hash[:get_channels_response][:channel]\n channels = [channels].compact unless channels.is_a?(Array)\n channels.map do |hash|\n IsbmAdaptor::Channel.from_hash(hash)\n end\n end", "code_tokens": ["def", "get_channels", "(", "&", "block", ")", "response", "=", "@client", ".", "call", "(", ":get_channels", ",", "{", "}", ",", "block", ")", "channels", "=", "response", ".", "to_hash", "[", ":get_channels_response", "]", "[", ":channel", "]", "channels", "=", "[", "channels", "]", ".", "compact", "unless", "channels", ".", "is_a?", "(", "Array", ")", "channels", ".", "map", "do", "|", "hash", "|", "IsbmAdaptor", "::", "Channel", ".", "from_hash", "(", "hash", ")", "end", "end"], "docstring": "Gets information about all channels.\n\n @yield locals local options, including :wsse_auth\n @return [Array] all authorized channels on the ISBM", "docstring_tokens": ["Gets", "information", "about", "all", "channels", "."], "sha": "67847351bbff3a1538c3ba141fe260e4de59676a", "url": "https://github.com/assetricity/isbm_adaptor/blob/67847351bbff3a1538c3ba141fe260e4de59676a/lib/isbm_adaptor/channel_management.rb#L109-L117", "partition": "test"} {"repo": "leighhalliday/idioma", "path": "app/models/idioma/phrase.rb", "func_name": "Idioma.Phrase.update_backend", "original_string": "def update_backend\n if Idioma.configuration.redis_backend\n if i18n_value.present?\n Idioma::RedisBackend.update_phrase(self)\n else\n Idioma::RedisBackend.delete_phrase(self)\n end\n end\n end", "language": "ruby", "code": "def update_backend\n if Idioma.configuration.redis_backend\n if i18n_value.present?\n Idioma::RedisBackend.update_phrase(self)\n else\n Idioma::RedisBackend.delete_phrase(self)\n end\n end\n end", "code_tokens": ["def", "update_backend", "if", "Idioma", ".", "configuration", ".", "redis_backend", "if", "i18n_value", ".", "present?", "Idioma", "::", "RedisBackend", ".", "update_phrase", "(", "self", ")", "else", "Idioma", "::", "RedisBackend", ".", "delete_phrase", "(", "self", ")", "end", "end", "end"], "docstring": "Will update the i18n backend if it has been configured", "docstring_tokens": ["Will", "update", "the", "i18n", "backend", "if", "it", "has", "been", "configured"], "sha": "05dcce9799a6bea229cb1a7e4ef3e477afd2f256", "url": "https://github.com/leighhalliday/idioma/blob/05dcce9799a6bea229cb1a7e4ef3e477afd2f256/app/models/idioma/phrase.rb#L83-L91", "partition": "test"} {"repo": "leighhalliday/idioma", "path": "app/controllers/idioma/phrases_controller.rb", "func_name": "Idioma.PhrasesController.set_phrase", "original_string": "def set_phrase\n @phrase = Phrase.find(params[:id])\n rescue ActiveRecord::RecordNotFound\n respond_to do |format|\n format.json { render json: {}.to_json, status: :not_found }\n format.html {\n flash[:error] = t('idioma.record_not_found')\n redirect_to phrases_path\n }\n end\n end", "language": "ruby", "code": "def set_phrase\n @phrase = Phrase.find(params[:id])\n rescue ActiveRecord::RecordNotFound\n respond_to do |format|\n format.json { render json: {}.to_json, status: :not_found }\n format.html {\n flash[:error] = t('idioma.record_not_found')\n redirect_to phrases_path\n }\n end\n end", "code_tokens": ["def", "set_phrase", "@phrase", "=", "Phrase", ".", "find", "(", "params", "[", ":id", "]", ")", "rescue", "ActiveRecord", "::", "RecordNotFound", "respond_to", "do", "|", "format", "|", "format", ".", "json", "{", "render", "json", ":", "{", "}", ".", "to_json", ",", "status", ":", ":not_found", "}", "format", ".", "html", "{", "flash", "[", ":error", "]", "=", "t", "(", "'idioma.record_not_found'", ")", "redirect_to", "phrases_path", "}", "end", "end"], "docstring": "Use callbacks to share common setup or constraints between actions.", "docstring_tokens": ["Use", "callbacks", "to", "share", "common", "setup", "or", "constraints", "between", "actions", "."], "sha": "05dcce9799a6bea229cb1a7e4ef3e477afd2f256", "url": "https://github.com/leighhalliday/idioma/blob/05dcce9799a6bea229cb1a7e4ef3e477afd2f256/app/controllers/idioma/phrases_controller.rb#L78-L88", "partition": "test"} {"repo": "assetricity/isbm_adaptor", "path": "lib/isbm_adaptor/duration.rb", "func_name": "IsbmAdaptor.Duration.to_s", "original_string": "def to_s\n date = []\n date << \"#{@years}Y\" unless @years.nil?\n date << \"#{@months}M\" unless @months.nil?\n date << \"#{@days}D\" unless @days.nil?\n\n time = []\n time << \"#{@hours}H\" unless @hours.nil?\n time << \"#{@minutes}M\" unless @minutes.nil?\n time << \"#{@seconds}S\" unless @seconds.nil?\n\n result = nil\n\n if !date.empty? || !time.empty?\n result = 'P'\n result += date.join unless date.empty?\n result += 'T' + time.join unless time.empty?\n end\n\n result\n end", "language": "ruby", "code": "def to_s\n date = []\n date << \"#{@years}Y\" unless @years.nil?\n date << \"#{@months}M\" unless @months.nil?\n date << \"#{@days}D\" unless @days.nil?\n\n time = []\n time << \"#{@hours}H\" unless @hours.nil?\n time << \"#{@minutes}M\" unless @minutes.nil?\n time << \"#{@seconds}S\" unless @seconds.nil?\n\n result = nil\n\n if !date.empty? || !time.empty?\n result = 'P'\n result += date.join unless date.empty?\n result += 'T' + time.join unless time.empty?\n end\n\n result\n end", "code_tokens": ["def", "to_s", "date", "=", "[", "]", "date", "<<", "\"#{@years}Y\"", "unless", "@years", ".", "nil?", "date", "<<", "\"#{@months}M\"", "unless", "@months", ".", "nil?", "date", "<<", "\"#{@days}D\"", "unless", "@days", ".", "nil?", "time", "=", "[", "]", "time", "<<", "\"#{@hours}H\"", "unless", "@hours", ".", "nil?", "time", "<<", "\"#{@minutes}M\"", "unless", "@minutes", ".", "nil?", "time", "<<", "\"#{@seconds}S\"", "unless", "@seconds", ".", "nil?", "result", "=", "nil", "if", "!", "date", ".", "empty?", "||", "!", "time", ".", "empty?", "result", "=", "'P'", "result", "+=", "date", ".", "join", "unless", "date", ".", "empty?", "result", "+=", "'T'", "+", "time", ".", "join", "unless", "time", ".", "empty?", "end", "result", "end"], "docstring": "Creates a new Duration based on specified time components.\n\n @option duration [Numeric] :years duration in years\n @option duration [Numeric] :months duration in months\n @option duration [Numeric] :days duration in days\n @option duration [Numeric] :hours duration in hours\n @option duration [Numeric] :minutes duration in minutes\n @option duration [Numeric] :seconds duration in seconds\n @return [String] ISO 8601 formatted duration", "docstring_tokens": ["Creates", "a", "new", "Duration", "based", "on", "specified", "time", "components", "."], "sha": "67847351bbff3a1538c3ba141fe260e4de59676a", "url": "https://github.com/assetricity/isbm_adaptor/blob/67847351bbff3a1538c3ba141fe260e4de59676a/lib/isbm_adaptor/duration.rb#L47-L67", "partition": "test"} {"repo": "kristianmandrup/geo_calc", "path": "lib/geo_calc/pretty_print.rb", "func_name": "GeoCalc.PrettyPrint.to_lat", "original_string": "def to_lat format = :dms, dp = 0\n return lat if !format\n GeoUnits::Converter.to_lat lat, format, dp\n end", "language": "ruby", "code": "def to_lat format = :dms, dp = 0\n return lat if !format\n GeoUnits::Converter.to_lat lat, format, dp\n end", "code_tokens": ["def", "to_lat", "format", "=", ":dms", ",", "dp", "=", "0", "return", "lat", "if", "!", "format", "GeoUnits", "::", "Converter", ".", "to_lat", "lat", ",", "format", ",", "dp", "end"], "docstring": "Returns the latitude of this point; signed numeric degrees if no format, otherwise format & dp\n\n @param [String] format: Return value as 'd', 'dm', 'dms'\n @param [Numeric] dp: No of decimal places to display (0|2|4)\n\n @return [Numeric|String]: Numeric degrees if no format specified, otherwise deg/min/sec", "docstring_tokens": ["Returns", "the", "latitude", "of", "this", "point", ";", "signed", "numeric", "degrees", "if", "no", "format", "otherwise", "format", "&", "dp"], "sha": "8f9697015329269a1e25b4ae5026986e6dfe9e42", "url": "https://github.com/kristianmandrup/geo_calc/blob/8f9697015329269a1e25b4ae5026986e6dfe9e42/lib/geo_calc/pretty_print.rb#L13-L16", "partition": "test"} {"repo": "MartijnSch/optimizely-gem", "path": "lib/optimizely/engine.rb", "func_name": "Optimizely.Engine.projects", "original_string": "def projects\n if @projects.nil?\n response = self.get(\"projects\")\n @projects = response.collect { |project_json| Project.new(project_json) }\n end\n @projects\n end", "language": "ruby", "code": "def projects\n if @projects.nil?\n response = self.get(\"projects\")\n @projects = response.collect { |project_json| Project.new(project_json) }\n end\n @projects\n end", "code_tokens": ["def", "projects", "if", "@projects", ".", "nil?", "response", "=", "self", ".", "get", "(", "\"projects\"", ")", "@projects", "=", "response", ".", "collect", "{", "|", "project_json", "|", "Project", ".", "new", "(", "project_json", ")", "}", "end", "@projects", "end"], "docstring": "Returns the list of projects available to the authenticated user.\n\n == Usage\n optimizely = Optimizely.new({ api_token: 'oauth2_token' })\n projects = optimizely.projects # Look up all projects.", "docstring_tokens": ["Returns", "the", "list", "of", "projects", "available", "to", "the", "authenticated", "user", "."], "sha": "069396020262fac12b3fed0e0992cb72db02e59f", "url": "https://github.com/MartijnSch/optimizely-gem/blob/069396020262fac12b3fed0e0992cb72db02e59f/lib/optimizely/engine.rb#L32-L38", "partition": "test"} {"repo": "MartijnSch/optimizely-gem", "path": "lib/optimizely/engine.rb", "func_name": "Optimizely.Engine.project", "original_string": "def project(id)\n @url = \"projects/#{id}\"\n raise OptimizelyError::NoProjectID, \"A Project ID is required to retrieve the project.\" if id.nil?\n\n response = self.get(@url)\n Project.new(response)\n end", "language": "ruby", "code": "def project(id)\n @url = \"projects/#{id}\"\n raise OptimizelyError::NoProjectID, \"A Project ID is required to retrieve the project.\" if id.nil?\n\n response = self.get(@url)\n Project.new(response)\n end", "code_tokens": ["def", "project", "(", "id", ")", "@url", "=", "\"projects/#{id}\"", "raise", "OptimizelyError", "::", "NoProjectID", ",", "\"A Project ID is required to retrieve the project.\"", "if", "id", ".", "nil?", "response", "=", "self", ".", "get", "(", "@url", ")", "Project", ".", "new", "(", "response", ")", "end"], "docstring": "Returns the details for a specific project.\n\n == Usage\n optimizely = Optimizely.new({ api_token: 'oauth2_token' })\n project = optimizely.project(12345) # Look up the project.", "docstring_tokens": ["Returns", "the", "details", "for", "a", "specific", "project", "."], "sha": "069396020262fac12b3fed0e0992cb72db02e59f", "url": "https://github.com/MartijnSch/optimizely-gem/blob/069396020262fac12b3fed0e0992cb72db02e59f/lib/optimizely/engine.rb#L46-L52", "partition": "test"} {"repo": "MartijnSch/optimizely-gem", "path": "lib/optimizely/engine.rb", "func_name": "Optimizely.Engine.experiments", "original_string": "def experiments(project_id)\n raise OptimizelyError::NoProjectID, \"A Project ID is required to retrieve experiments.\" if project_id.nil?\n\n response = self.get(\"projects/#{project_id}/experiments\")\n response.collect { |response_json| Experiment.new(response_json) }\n end", "language": "ruby", "code": "def experiments(project_id)\n raise OptimizelyError::NoProjectID, \"A Project ID is required to retrieve experiments.\" if project_id.nil?\n\n response = self.get(\"projects/#{project_id}/experiments\")\n response.collect { |response_json| Experiment.new(response_json) }\n end", "code_tokens": ["def", "experiments", "(", "project_id", ")", "raise", "OptimizelyError", "::", "NoProjectID", ",", "\"A Project ID is required to retrieve experiments.\"", "if", "project_id", ".", "nil?", "response", "=", "self", ".", "get", "(", "\"projects/#{project_id}/experiments\"", ")", "response", ".", "collect", "{", "|", "response_json", "|", "Experiment", ".", "new", "(", "response_json", ")", "}", "end"], "docstring": "Returns the list of experiments for a specified project.\n\n == Usage\n optimizely = Optimizely.new({ api_token: 'oauth2_token' })\n experiments = optimizely.experiments(12345) # Look up all experiments for a project.", "docstring_tokens": ["Returns", "the", "list", "of", "experiments", "for", "a", "specified", "project", "."], "sha": "069396020262fac12b3fed0e0992cb72db02e59f", "url": "https://github.com/MartijnSch/optimizely-gem/blob/069396020262fac12b3fed0e0992cb72db02e59f/lib/optimizely/engine.rb#L60-L65", "partition": "test"} {"repo": "MartijnSch/optimizely-gem", "path": "lib/optimizely/engine.rb", "func_name": "Optimizely.Engine.experiment", "original_string": "def experiment(id)\n @url = \"experiments/#{id}\"\n raise OptimizelyError::NoExperimentID, \"An Experiment ID is required to retrieve the experiment.\" if id.nil?\n\n response = self.get(@url)\n Experiment.new(response)\n end", "language": "ruby", "code": "def experiment(id)\n @url = \"experiments/#{id}\"\n raise OptimizelyError::NoExperimentID, \"An Experiment ID is required to retrieve the experiment.\" if id.nil?\n\n response = self.get(@url)\n Experiment.new(response)\n end", "code_tokens": ["def", "experiment", "(", "id", ")", "@url", "=", "\"experiments/#{id}\"", "raise", "OptimizelyError", "::", "NoExperimentID", ",", "\"An Experiment ID is required to retrieve the experiment.\"", "if", "id", ".", "nil?", "response", "=", "self", ".", "get", "(", "@url", ")", "Experiment", ".", "new", "(", "response", ")", "end"], "docstring": "Returns the details for a specific experiment.\n\n == Usage\n optimizely = Optimizely.new({ api_token: 'oauth2_token' })\n experiment = optimizely.experiment(12345) # Look up the experiment.", "docstring_tokens": ["Returns", "the", "details", "for", "a", "specific", "experiment", "."], "sha": "069396020262fac12b3fed0e0992cb72db02e59f", "url": "https://github.com/MartijnSch/optimizely-gem/blob/069396020262fac12b3fed0e0992cb72db02e59f/lib/optimizely/engine.rb#L73-L79", "partition": "test"} {"repo": "MartijnSch/optimizely-gem", "path": "lib/optimizely/engine.rb", "func_name": "Optimizely.Engine.stats", "original_string": "def stats(experiment_id)\n @url = \"experiments/#{experiment_id}/stats\"\n raise OptimizelyError::NoExperimentID, \"An Experiment ID is required to retrieve the stats.\" if experiment_id.nil?\n\n response = self.get(@url)\n response.collect { |response_json| Stat.new(response_json) }\n end", "language": "ruby", "code": "def stats(experiment_id)\n @url = \"experiments/#{experiment_id}/stats\"\n raise OptimizelyError::NoExperimentID, \"An Experiment ID is required to retrieve the stats.\" if experiment_id.nil?\n\n response = self.get(@url)\n response.collect { |response_json| Stat.new(response_json) }\n end", "code_tokens": ["def", "stats", "(", "experiment_id", ")", "@url", "=", "\"experiments/#{experiment_id}/stats\"", "raise", "OptimizelyError", "::", "NoExperimentID", ",", "\"An Experiment ID is required to retrieve the stats.\"", "if", "experiment_id", ".", "nil?", "response", "=", "self", ".", "get", "(", "@url", ")", "response", ".", "collect", "{", "|", "response_json", "|", "Stat", ".", "new", "(", "response_json", ")", "}", "end"], "docstring": "Returns the stats for a specific experiment.\n\n == Usage\n optimizely = Optimizely.new({ api_token: 'oauth2_token' })\n stats = optimizely.stats(12345) # Look up the stats with the specific experiment.", "docstring_tokens": ["Returns", "the", "stats", "for", "a", "specific", "experiment", "."], "sha": "069396020262fac12b3fed0e0992cb72db02e59f", "url": "https://github.com/MartijnSch/optimizely-gem/blob/069396020262fac12b3fed0e0992cb72db02e59f/lib/optimizely/engine.rb#L87-L93", "partition": "test"} {"repo": "MartijnSch/optimizely-gem", "path": "lib/optimizely/engine.rb", "func_name": "Optimizely.Engine.variations", "original_string": "def variations(experiment_id)\n raise OptimizelyError::NoExperimentID, \"An Experiment ID is required to retrieve variations.\" if experiment_id.nil?\n\n response = self.get(\"experiments/#{experiment_id}/variations\")\n response.collect { |variation_json| Variation.new(variation_json) }\n end", "language": "ruby", "code": "def variations(experiment_id)\n raise OptimizelyError::NoExperimentID, \"An Experiment ID is required to retrieve variations.\" if experiment_id.nil?\n\n response = self.get(\"experiments/#{experiment_id}/variations\")\n response.collect { |variation_json| Variation.new(variation_json) }\n end", "code_tokens": ["def", "variations", "(", "experiment_id", ")", "raise", "OptimizelyError", "::", "NoExperimentID", ",", "\"An Experiment ID is required to retrieve variations.\"", "if", "experiment_id", ".", "nil?", "response", "=", "self", ".", "get", "(", "\"experiments/#{experiment_id}/variations\"", ")", "response", ".", "collect", "{", "|", "variation_json", "|", "Variation", ".", "new", "(", "variation_json", ")", "}", "end"], "docstring": "Returns the list of variations for a specified experiment.\n\n == Usage\n optimizely = Optimizely.new({ api_token: 'oauth2_token' })\n variations = optimizely.variations(12345) # Look up all variations for an experiment.", "docstring_tokens": ["Returns", "the", "list", "of", "variations", "for", "a", "specified", "experiment", "."], "sha": "069396020262fac12b3fed0e0992cb72db02e59f", "url": "https://github.com/MartijnSch/optimizely-gem/blob/069396020262fac12b3fed0e0992cb72db02e59f/lib/optimizely/engine.rb#L101-L106", "partition": "test"} {"repo": "MartijnSch/optimizely-gem", "path": "lib/optimizely/engine.rb", "func_name": "Optimizely.Engine.variation", "original_string": "def variation(id)\n @url = \"variations/#{id}\"\n raise OptimizelyError::NoVariationID, \"A Variation ID is required to retrieve the variation.\" if id.nil?\n\n response = self.get(@url)\n Variation.new(response)\n end", "language": "ruby", "code": "def variation(id)\n @url = \"variations/#{id}\"\n raise OptimizelyError::NoVariationID, \"A Variation ID is required to retrieve the variation.\" if id.nil?\n\n response = self.get(@url)\n Variation.new(response)\n end", "code_tokens": ["def", "variation", "(", "id", ")", "@url", "=", "\"variations/#{id}\"", "raise", "OptimizelyError", "::", "NoVariationID", ",", "\"A Variation ID is required to retrieve the variation.\"", "if", "id", ".", "nil?", "response", "=", "self", ".", "get", "(", "@url", ")", "Variation", ".", "new", "(", "response", ")", "end"], "docstring": "Returns the details for a specific variation.\n\n == Usage\n optimizely = Optimizely.new({ api_token: 'oauth2_token' })\n variation = optimizely.variation(12345) # Look up the variation.", "docstring_tokens": ["Returns", "the", "details", "for", "a", "specific", "variation", "."], "sha": "069396020262fac12b3fed0e0992cb72db02e59f", "url": "https://github.com/MartijnSch/optimizely-gem/blob/069396020262fac12b3fed0e0992cb72db02e59f/lib/optimizely/engine.rb#L114-L120", "partition": "test"} {"repo": "MartijnSch/optimizely-gem", "path": "lib/optimizely/engine.rb", "func_name": "Optimizely.Engine.audiences", "original_string": "def audiences(project_id)\n raise OptimizelyError::NoProjectID, \"A Project ID is required to retrieve audiences.\" if project_id.nil?\n\n response = self.get(\"projects/#{project_id}/audiences\")\n response.collect { |audience_json| Audience.new(audience_json) }\n end", "language": "ruby", "code": "def audiences(project_id)\n raise OptimizelyError::NoProjectID, \"A Project ID is required to retrieve audiences.\" if project_id.nil?\n\n response = self.get(\"projects/#{project_id}/audiences\")\n response.collect { |audience_json| Audience.new(audience_json) }\n end", "code_tokens": ["def", "audiences", "(", "project_id", ")", "raise", "OptimizelyError", "::", "NoProjectID", ",", "\"A Project ID is required to retrieve audiences.\"", "if", "project_id", ".", "nil?", "response", "=", "self", ".", "get", "(", "\"projects/#{project_id}/audiences\"", ")", "response", ".", "collect", "{", "|", "audience_json", "|", "Audience", ".", "new", "(", "audience_json", ")", "}", "end"], "docstring": "Returns the list of audiences for a specified project.\n\n == Usage\n optimizely = Optimizely.new({ api_token: 'oauth2_token' })\n audiences = optimizely.audiences(12345) # Look up all audiences for a project.", "docstring_tokens": ["Returns", "the", "list", "of", "audiences", "for", "a", "specified", "project", "."], "sha": "069396020262fac12b3fed0e0992cb72db02e59f", "url": "https://github.com/MartijnSch/optimizely-gem/blob/069396020262fac12b3fed0e0992cb72db02e59f/lib/optimizely/engine.rb#L128-L133", "partition": "test"} {"repo": "MartijnSch/optimizely-gem", "path": "lib/optimizely/engine.rb", "func_name": "Optimizely.Engine.audience", "original_string": "def audience(id)\n @url = \"audiences/#{id}\"\n raise OptimizelyError::NoAudienceID, \"An Audience ID is required to retrieve the audience.\" if id.nil?\n\n response = self.get(@url)\n Audience.new(response)\n end", "language": "ruby", "code": "def audience(id)\n @url = \"audiences/#{id}\"\n raise OptimizelyError::NoAudienceID, \"An Audience ID is required to retrieve the audience.\" if id.nil?\n\n response = self.get(@url)\n Audience.new(response)\n end", "code_tokens": ["def", "audience", "(", "id", ")", "@url", "=", "\"audiences/#{id}\"", "raise", "OptimizelyError", "::", "NoAudienceID", ",", "\"An Audience ID is required to retrieve the audience.\"", "if", "id", ".", "nil?", "response", "=", "self", ".", "get", "(", "@url", ")", "Audience", ".", "new", "(", "response", ")", "end"], "docstring": "Returns the details for a specific audience.\n\n == Usage\n optimizely = Optimizely.new({ api_token: 'oauth2_token' })\n audience = optimizely.audience(12345) # Look up the audience.", "docstring_tokens": ["Returns", "the", "details", "for", "a", "specific", "audience", "."], "sha": "069396020262fac12b3fed0e0992cb72db02e59f", "url": "https://github.com/MartijnSch/optimizely-gem/blob/069396020262fac12b3fed0e0992cb72db02e59f/lib/optimizely/engine.rb#L141-L147", "partition": "test"} {"repo": "MartijnSch/optimizely-gem", "path": "lib/optimizely/engine.rb", "func_name": "Optimizely.Engine.get", "original_string": "def get(url)\n uri = URI.parse(\"#{BASE_URL}#{url}/\")\n https = Net::HTTP.new(uri.host, uri.port)\n https.read_timeout = @options[:timeout] if @options[:timeout]\n https.verify_mode = OpenSSL::SSL::VERIFY_NONE\n https.use_ssl = true\n request = Net::HTTP::Get.new(uri.request_uri, @headers)\n response = https.request(request)\n\n # Response code error checking\n if response.code != '200'\n check_response(response.code, response.body)\n else\n parse_json(response.body)\n end\n end", "language": "ruby", "code": "def get(url)\n uri = URI.parse(\"#{BASE_URL}#{url}/\")\n https = Net::HTTP.new(uri.host, uri.port)\n https.read_timeout = @options[:timeout] if @options[:timeout]\n https.verify_mode = OpenSSL::SSL::VERIFY_NONE\n https.use_ssl = true\n request = Net::HTTP::Get.new(uri.request_uri, @headers)\n response = https.request(request)\n\n # Response code error checking\n if response.code != '200'\n check_response(response.code, response.body)\n else\n parse_json(response.body)\n end\n end", "code_tokens": ["def", "get", "(", "url", ")", "uri", "=", "URI", ".", "parse", "(", "\"#{BASE_URL}#{url}/\"", ")", "https", "=", "Net", "::", "HTTP", ".", "new", "(", "uri", ".", "host", ",", "uri", ".", "port", ")", "https", ".", "read_timeout", "=", "@options", "[", ":timeout", "]", "if", "@options", "[", ":timeout", "]", "https", ".", "verify_mode", "=", "OpenSSL", "::", "SSL", "::", "VERIFY_NONE", "https", ".", "use_ssl", "=", "true", "request", "=", "Net", "::", "HTTP", "::", "Get", ".", "new", "(", "uri", ".", "request_uri", ",", "@headers", ")", "response", "=", "https", ".", "request", "(", "request", ")", "# Response code error checking", "if", "response", ".", "code", "!=", "'200'", "check_response", "(", "response", ".", "code", ",", "response", ".", "body", ")", "else", "parse_json", "(", "response", ".", "body", ")", "end", "end"], "docstring": "Return the parsed JSON data for a request that is done to the Optimizely REST API.", "docstring_tokens": ["Return", "the", "parsed", "JSON", "data", "for", "a", "request", "that", "is", "done", "to", "the", "Optimizely", "REST", "API", "."], "sha": "069396020262fac12b3fed0e0992cb72db02e59f", "url": "https://github.com/MartijnSch/optimizely-gem/blob/069396020262fac12b3fed0e0992cb72db02e59f/lib/optimizely/engine.rb#L150-L165", "partition": "test"} {"repo": "jmettraux/rufus-tokyo", "path": "lib/rufus/edo/ntyrant/table.rb", "func_name": "Rufus::Edo.NetTyrantTable.lget", "original_string": "def lget (*keys)\n\n h = keys.flatten.inject({}) { |hh, k| hh[k] = nil; hh }\n r = @db.mget(h)\n\n raise 'lget failure' if r == -1\n\n h\n end", "language": "ruby", "code": "def lget (*keys)\n\n h = keys.flatten.inject({}) { |hh, k| hh[k] = nil; hh }\n r = @db.mget(h)\n\n raise 'lget failure' if r == -1\n\n h\n end", "code_tokens": ["def", "lget", "(", "*", "keys", ")", "h", "=", "keys", ".", "flatten", ".", "inject", "(", "{", "}", ")", "{", "|", "hh", ",", "k", "|", "hh", "[", "k", "]", "=", "nil", ";", "hh", "}", "r", "=", "@db", ".", "mget", "(", "h", ")", "raise", "'lget failure'", "if", "r", "==", "-", "1", "h", "end"], "docstring": "Connects to the Tyrant table listening at the given host and port.\n\n You start such a Tyrant with :\n\n ttserver -port 44502 data.tct\n\n and then :\n\n require 'rufus/edo/ntyrant'\n t = Rufus::Edo::NetTyrantTable.new('127.0.0.1', 44502)\n t['client0'] = { 'name' => 'Heike no Kyomori', 'country' => 'jp' }\n t.close\n\n\n You can start a Tokyo Tyrant and make it listen to a unix socket (not TCP)\n with :\n\n ttserver -host /tmp/table_socket -port 0 data.tct\n\n then :\n\n require 'rufus/edo/ntyrant'\n t = Rufus::Edo::NetTyrantTable.new('/tmp/table_socket')\n t['client0'] = { 'name' => 'Theodore Roosevelt', 'country' => 'usa' }\n t.close\n\n Gets multiple records in one sweep.", "docstring_tokens": ["Connects", "to", "the", "Tyrant", "table", "listening", "at", "the", "given", "host", "and", "port", "."], "sha": "910413a982ed501e03d0c16f755929ce54d84644", "url": "https://github.com/jmettraux/rufus-tokyo/blob/910413a982ed501e03d0c16f755929ce54d84644/lib/rufus/edo/ntyrant/table.rb#L105-L113", "partition": "test"} {"repo": "grempe/secretsharing", "path": "lib/secretsharing/shamir.rb", "func_name": "SecretSharing.Shamir.get_random_number", "original_string": "def get_random_number(bytes)\n RbNaCl::Util.bin2hex(RbNaCl::Random.random_bytes(bytes).to_s).to_i(16)\n end", "language": "ruby", "code": "def get_random_number(bytes)\n RbNaCl::Util.bin2hex(RbNaCl::Random.random_bytes(bytes).to_s).to_i(16)\n end", "code_tokens": ["def", "get_random_number", "(", "bytes", ")", "RbNaCl", "::", "Util", ".", "bin2hex", "(", "RbNaCl", "::", "Random", ".", "random_bytes", "(", "bytes", ")", ".", "to_s", ")", ".", "to_i", "(", "16", ")", "end"], "docstring": "Create a random number of a specified Byte length\n returns Bignum", "docstring_tokens": ["Create", "a", "random", "number", "of", "a", "specified", "Byte", "length", "returns", "Bignum"], "sha": "39ec186ab2ba5fcae576e7e569a77ec8dde0c915", "url": "https://github.com/grempe/secretsharing/blob/39ec186ab2ba5fcae576e7e569a77ec8dde0c915/lib/secretsharing/shamir.rb#L22-L24", "partition": "test"} {"repo": "grempe/secretsharing", "path": "lib/secretsharing/shamir.rb", "func_name": "SecretSharing.Shamir.get_random_number_with_bitlength", "original_string": "def get_random_number_with_bitlength(bits)\n byte_length = (bits / 8.0).ceil + 10\n random_num = get_random_number(byte_length)\n random_num_bin_str = random_num.to_s(2) # Get 1's and 0's\n\n # Slice off only the bits we require, convert Bits to Numeric (Bignum)\n random_num_bin_str.slice(0, bits).to_i(2)\n end", "language": "ruby", "code": "def get_random_number_with_bitlength(bits)\n byte_length = (bits / 8.0).ceil + 10\n random_num = get_random_number(byte_length)\n random_num_bin_str = random_num.to_s(2) # Get 1's and 0's\n\n # Slice off only the bits we require, convert Bits to Numeric (Bignum)\n random_num_bin_str.slice(0, bits).to_i(2)\n end", "code_tokens": ["def", "get_random_number_with_bitlength", "(", "bits", ")", "byte_length", "=", "(", "bits", "/", "8.0", ")", ".", "ceil", "+", "10", "random_num", "=", "get_random_number", "(", "byte_length", ")", "random_num_bin_str", "=", "random_num", ".", "to_s", "(", "2", ")", "# Get 1's and 0's", "# Slice off only the bits we require, convert Bits to Numeric (Bignum)", "random_num_bin_str", ".", "slice", "(", "0", ",", "bits", ")", ".", "to_i", "(", "2", ")", "end"], "docstring": "Creates a random number of a exact bitlength\n returns Bignum", "docstring_tokens": ["Creates", "a", "random", "number", "of", "a", "exact", "bitlength", "returns", "Bignum"], "sha": "39ec186ab2ba5fcae576e7e569a77ec8dde0c915", "url": "https://github.com/grempe/secretsharing/blob/39ec186ab2ba5fcae576e7e569a77ec8dde0c915/lib/secretsharing/shamir.rb#L28-L35", "partition": "test"} {"repo": "jmettraux/rufus-tokyo", "path": "lib/rufus/edo/tabcore.rb", "func_name": "Rufus::Edo.TableQuery.add", "original_string": "def add (colname, operator, val, affirmative=true, no_index=false)\n\n colname = colname.to_s\n val = val.to_s\n\n op = operator.is_a?(Fixnum) ? operator : OPERATORS[operator]\n op = op | TDBQCNEGATE unless affirmative\n op = op | TDBQCNOIDX if no_index\n\n @query.addcond(colname, op, val)\n end", "language": "ruby", "code": "def add (colname, operator, val, affirmative=true, no_index=false)\n\n colname = colname.to_s\n val = val.to_s\n\n op = operator.is_a?(Fixnum) ? operator : OPERATORS[operator]\n op = op | TDBQCNEGATE unless affirmative\n op = op | TDBQCNOIDX if no_index\n\n @query.addcond(colname, op, val)\n end", "code_tokens": ["def", "add", "(", "colname", ",", "operator", ",", "val", ",", "affirmative", "=", "true", ",", "no_index", "=", "false", ")", "colname", "=", "colname", ".", "to_s", "val", "=", "val", ".", "to_s", "op", "=", "operator", ".", "is_a?", "(", "Fixnum", ")", "?", "operator", ":", "OPERATORS", "[", "operator", "]", "op", "=", "op", "|", "TDBQCNEGATE", "unless", "affirmative", "op", "=", "op", "|", "TDBQCNOIDX", "if", "no_index", "@query", ".", "addcond", "(", "colname", ",", "op", ",", "val", ")", "end"], "docstring": "Adds a condition\n\n table.query { |q|\n q.add 'name', :equals, 'Oppenheimer'\n q.add 'age', :numgt, 35\n }\n\n Understood 'operators' :\n\n :streq # string equality\n :eq\n :eql\n :equals\n\n :strinc # string include\n :inc # string include\n :includes # string include\n\n :strbw # string begins with\n :bw\n :starts_with\n :strew # string ends with\n :ew\n :ends_with\n\n :strand # string which include all the tokens in the given exp\n :and\n\n :stror # string which include at least one of the tokens\n :or\n\n :stroreq # string which is equal to at least one token\n\n :strorrx # string which matches the given regex\n :regex\n :matches\n\n # numbers...\n\n :numeq # equal\n :numequals\n :numgt # greater than\n :gt\n :numge # greater or equal\n :ge\n :gte\n :numlt # greater or equal\n :lt\n :numle # greater or equal\n :le\n :lte\n :numbt # a number between two tokens in the given exp\n :bt\n :between\n\n :numoreq # number which is equal to at least one token\n\n :ftsph # full-text phrase search\n :ftsphrase\n :phrase\n :ftsand # full-text AND\n :ftsor # full-text OR\n :ftsex # full-text with 'compound' expression", "docstring_tokens": ["Adds", "a", "condition"], "sha": "910413a982ed501e03d0c16f755929ce54d84644", "url": "https://github.com/jmettraux/rufus-tokyo/blob/910413a982ed501e03d0c16f755929ce54d84644/lib/rufus/edo/tabcore.rb#L516-L526", "partition": "test"} {"repo": "jmettraux/rufus-tokyo", "path": "lib/rufus/edo/cabcore.rb", "func_name": "Rufus::Edo.CabinetCore.keys", "original_string": "def keys (options={})\n\n if @db.respond_to? :fwmkeys\n pref = options.fetch(:prefix, \"\")\n\n @db.fwmkeys(pref, options[:limit] || -1)\n elsif @db.respond_to? :range\n @db.range(\"[min,max]\", nil)\n else\n raise NotImplementedError, \"Database does not support keys()\"\n end\n end", "language": "ruby", "code": "def keys (options={})\n\n if @db.respond_to? :fwmkeys\n pref = options.fetch(:prefix, \"\")\n\n @db.fwmkeys(pref, options[:limit] || -1)\n elsif @db.respond_to? :range\n @db.range(\"[min,max]\", nil)\n else\n raise NotImplementedError, \"Database does not support keys()\"\n end\n end", "code_tokens": ["def", "keys", "(", "options", "=", "{", "}", ")", "if", "@db", ".", "respond_to?", ":fwmkeys", "pref", "=", "options", ".", "fetch", "(", ":prefix", ",", "\"\"", ")", "@db", ".", "fwmkeys", "(", "pref", ",", "options", "[", ":limit", "]", "||", "-", "1", ")", "elsif", "@db", ".", "respond_to?", ":range", "@db", ".", "range", "(", "\"[min,max]\"", ",", "nil", ")", "else", "raise", "NotImplementedError", ",", "\"Database does not support keys()\"", "end", "end"], "docstring": "Returns an array of all the primary keys in the db.\n\n With no options given, this method will return all the keys (strings)\n in a Ruby array.\n\n :prefix --> returns only the keys who match a given string prefix\n\n :limit --> returns a limited number of keys", "docstring_tokens": ["Returns", "an", "array", "of", "all", "the", "primary", "keys", "in", "the", "db", "."], "sha": "910413a982ed501e03d0c16f755929ce54d84644", "url": "https://github.com/jmettraux/rufus-tokyo/blob/910413a982ed501e03d0c16f755929ce54d84644/lib/rufus/edo/cabcore.rb#L179-L190", "partition": "test"} {"repo": "reformgroup/dynamic_nested_forms", "path": "lib/dynamic_nested_forms/view_helpers.rb", "func_name": "DynamicNestedForms.ViewHelpers.autocomplete_to_add_item", "original_string": "def autocomplete_to_add_item(name, f, association, source, options = {})\n new_object = f.object.send(association).klass.new\n options[:class] = [\"autocomplete add-item\", options[:class]].compact.join \" \"\n options[:data] ||= {}\n options[:data][:id] = new_object.object_id\n options[:data][:source] = source\n options[:data][:item] = f.fields_for(association, new_object, child_index: options[:data][:id]) do |builder|\n render(association.to_s.singularize + \"_item\", f: builder).gsub \"\\n\", \"\"\n end\n \n text_field_tag \"autocomplete_nested_content\", nil, options\n end", "language": "ruby", "code": "def autocomplete_to_add_item(name, f, association, source, options = {})\n new_object = f.object.send(association).klass.new\n options[:class] = [\"autocomplete add-item\", options[:class]].compact.join \" \"\n options[:data] ||= {}\n options[:data][:id] = new_object.object_id\n options[:data][:source] = source\n options[:data][:item] = f.fields_for(association, new_object, child_index: options[:data][:id]) do |builder|\n render(association.to_s.singularize + \"_item\", f: builder).gsub \"\\n\", \"\"\n end\n \n text_field_tag \"autocomplete_nested_content\", nil, options\n end", "code_tokens": ["def", "autocomplete_to_add_item", "(", "name", ",", "f", ",", "association", ",", "source", ",", "options", "=", "{", "}", ")", "new_object", "=", "f", ".", "object", ".", "send", "(", "association", ")", ".", "klass", ".", "new", "options", "[", ":class", "]", "=", "[", "\"autocomplete add-item\"", ",", "options", "[", ":class", "]", "]", ".", "compact", ".", "join", "\" \"", "options", "[", ":data", "]", "||=", "{", "}", "options", "[", ":data", "]", "[", ":id", "]", "=", "new_object", ".", "object_id", "options", "[", ":data", "]", "[", ":source", "]", "=", "source", "options", "[", ":data", "]", "[", ":item", "]", "=", "f", ".", "fields_for", "(", "association", ",", "new_object", ",", "child_index", ":", "options", "[", ":data", "]", "[", ":id", "]", ")", "do", "|", "builder", "|", "render", "(", "association", ".", "to_s", ".", "singularize", "+", "\"_item\"", ",", "f", ":", "builder", ")", ".", "gsub", "\"\\n\"", ",", "\"\"", "end", "text_field_tag", "\"autocomplete_nested_content\"", ",", "nil", ",", "options", "end"], "docstring": ".nested-container\n .nested-autocomplete\n .nested-items\n .nested-item\n .nested-content\n .nested-value\n .remove-item", "docstring_tokens": [".", "nested", "-", "container", ".", "nested", "-", "autocomplete", ".", "nested", "-", "items", ".", "nested", "-", "item", ".", "nested", "-", "content", ".", "nested", "-", "value", ".", "remove", "-", "item"], "sha": "14c4318d7a9cd6585480538cfc08bd7475768315", "url": "https://github.com/reformgroup/dynamic_nested_forms/blob/14c4318d7a9cd6585480538cfc08bd7475768315/lib/dynamic_nested_forms/view_helpers.rb#L10-L21", "partition": "test"} {"repo": "jmettraux/rufus-tokyo", "path": "lib/rufus/tokyo/dystopia/core.rb", "func_name": "Rufus::Tokyo::Dystopia.Core.fetch", "original_string": "def fetch( id )\n r = nil\n begin\n r = lib.tcidbget( @db, id )\n rescue => e\n # if we have 'no record found' then return nil\n if lib.tcidbecode( @db ) == 22 then\n return nil\n else\n raise_error\n end\n end\n return r\n end", "language": "ruby", "code": "def fetch( id )\n r = nil\n begin\n r = lib.tcidbget( @db, id )\n rescue => e\n # if we have 'no record found' then return nil\n if lib.tcidbecode( @db ) == 22 then\n return nil\n else\n raise_error\n end\n end\n return r\n end", "code_tokens": ["def", "fetch", "(", "id", ")", "r", "=", "nil", "begin", "r", "=", "lib", ".", "tcidbget", "(", "@db", ",", "id", ")", "rescue", "=>", "e", "# if we have 'no record found' then return nil", "if", "lib", ".", "tcidbecode", "(", "@db", ")", "==", "22", "then", "return", "nil", "else", "raise_error", "end", "end", "return", "r", "end"], "docstring": "Return the document at the specified index", "docstring_tokens": ["Return", "the", "document", "at", "the", "specified", "index"], "sha": "910413a982ed501e03d0c16f755929ce54d84644", "url": "https://github.com/jmettraux/rufus-tokyo/blob/910413a982ed501e03d0c16f755929ce54d84644/lib/rufus/tokyo/dystopia/core.rb#L123-L136", "partition": "test"} {"repo": "jmettraux/rufus-tokyo", "path": "lib/rufus/tokyo/dystopia/core.rb", "func_name": "Rufus::Tokyo::Dystopia.Core.search", "original_string": "def search( expression )\n out_count = ::FFI::MemoryPointer.new :pointer\n out_list = ::FFI::MemoryPointer.new :pointer\n out_list = lib.tcidbsearch2( @db, expression, out_count )\n\n count = out_count.read_int\n results = out_list.get_array_of_uint64(0, count )\n return results\n end", "language": "ruby", "code": "def search( expression )\n out_count = ::FFI::MemoryPointer.new :pointer\n out_list = ::FFI::MemoryPointer.new :pointer\n out_list = lib.tcidbsearch2( @db, expression, out_count )\n\n count = out_count.read_int\n results = out_list.get_array_of_uint64(0, count )\n return results\n end", "code_tokens": ["def", "search", "(", "expression", ")", "out_count", "=", "::", "FFI", "::", "MemoryPointer", ".", "new", ":pointer", "out_list", "=", "::", "FFI", "::", "MemoryPointer", ".", "new", ":pointer", "out_list", "=", "lib", ".", "tcidbsearch2", "(", "@db", ",", "expression", ",", "out_count", ")", "count", "=", "out_count", ".", "read_int", "results", "=", "out_list", ".", "get_array_of_uint64", "(", "0", ",", "count", ")", "return", "results", "end"], "docstring": "Return the document ids of the documents that matche the search expression\n\n http://tokyocabinet.sourceforge.net/dystopiadoc/#dystopiaapi and scroll\n down to 'Compound Expression of Search'", "docstring_tokens": ["Return", "the", "document", "ids", "of", "the", "documents", "that", "matche", "the", "search", "expression"], "sha": "910413a982ed501e03d0c16f755929ce54d84644", "url": "https://github.com/jmettraux/rufus-tokyo/blob/910413a982ed501e03d0c16f755929ce54d84644/lib/rufus/tokyo/dystopia/core.rb#L144-L152", "partition": "test"} {"repo": "andymeneely/game_icons", "path": "lib/game_icons/did_you_mean.rb", "func_name": "GameIcons.DidYouMean.char_freq", "original_string": "def char_freq(str)\n freqs = Hash.new(0)\n (1..4).each do |i|\n str.chars.each_cons(i).inject(freqs) do |freq, ngram|\n ngram = ngram.join\n freq[ngram] = freq[ngram] + 1\n freq\n end\n end\n freqs\n end", "language": "ruby", "code": "def char_freq(str)\n freqs = Hash.new(0)\n (1..4).each do |i|\n str.chars.each_cons(i).inject(freqs) do |freq, ngram|\n ngram = ngram.join\n freq[ngram] = freq[ngram] + 1\n freq\n end\n end\n freqs\n end", "code_tokens": ["def", "char_freq", "(", "str", ")", "freqs", "=", "Hash", ".", "new", "(", "0", ")", "(", "1", "..", "4", ")", ".", "each", "do", "|", "i", "|", "str", ".", "chars", ".", "each_cons", "(", "i", ")", ".", "inject", "(", "freqs", ")", "do", "|", "freq", ",", "ngram", "|", "ngram", "=", "ngram", ".", "join", "freq", "[", "ngram", "]", "=", "freq", "[", "ngram", "]", "+", "1", "freq", "end", "end", "freqs", "end"], "docstring": "Computes a hash of each character", "docstring_tokens": ["Computes", "a", "hash", "of", "each", "character"], "sha": "f108e7211e4b860292487bcbee79ce1640a3ec02", "url": "https://github.com/andymeneely/game_icons/blob/f108e7211e4b860292487bcbee79ce1640a3ec02/lib/game_icons/did_you_mean.rb#L28-L38", "partition": "test"} {"repo": "andymeneely/game_icons", "path": "lib/game_icons/did_you_mean.rb", "func_name": "GameIcons.DidYouMean.top", "original_string": "def top(n, scores)\n scores.sort {|a,b| a[1] <=> b[1]}.map{|x| x[0]}.first(n)\n end", "language": "ruby", "code": "def top(n, scores)\n scores.sort {|a,b| a[1] <=> b[1]}.map{|x| x[0]}.first(n)\n end", "code_tokens": ["def", "top", "(", "n", ",", "scores", ")", "scores", ".", "sort", "{", "|", "a", ",", "b", "|", "a", "[", "1", "]", "<=>", "b", "[", "1", "]", "}", ".", "map", "{", "|", "x", "|", "x", "[", "0", "]", "}", ".", "first", "(", "n", ")", "end"], "docstring": "Return top scoring, sorted by lowest", "docstring_tokens": ["Return", "top", "scoring", "sorted", "by", "lowest"], "sha": "f108e7211e4b860292487bcbee79ce1640a3ec02", "url": "https://github.com/andymeneely/game_icons/blob/f108e7211e4b860292487bcbee79ce1640a3ec02/lib/game_icons/did_you_mean.rb#L59-L61", "partition": "test"} {"repo": "andymeneely/game_icons", "path": "lib/game_icons/icon.rb", "func_name": "GameIcons.Icon.recolor", "original_string": "def recolor(bg: '#000', fg: '#fff', bg_opacity: \"1.0\", fg_opacity: \"1.0\")\r\n OptionalDeps.require_nokogiri\r\n bg.prepend('#') unless bg.start_with? '#'\r\n fg.prepend('#') unless fg.start_with? '#'\r\n doc = Nokogiri::XML(self.string)\r\n doc.css('path')[0]['fill'] = bg # dark backdrop\r\n doc.css('path')[1]['fill'] = fg # light drawing\r\n doc.css('path')[0]['fill-opacity'] = bg_opacity.to_s # dark backdrop\r\n doc.css('path')[1]['fill-opacity'] = fg_opacity.to_s # light drawing\r\n @svgstr = doc.to_xml\r\n self\r\n end", "language": "ruby", "code": "def recolor(bg: '#000', fg: '#fff', bg_opacity: \"1.0\", fg_opacity: \"1.0\")\r\n OptionalDeps.require_nokogiri\r\n bg.prepend('#') unless bg.start_with? '#'\r\n fg.prepend('#') unless fg.start_with? '#'\r\n doc = Nokogiri::XML(self.string)\r\n doc.css('path')[0]['fill'] = bg # dark backdrop\r\n doc.css('path')[1]['fill'] = fg # light drawing\r\n doc.css('path')[0]['fill-opacity'] = bg_opacity.to_s # dark backdrop\r\n doc.css('path')[1]['fill-opacity'] = fg_opacity.to_s # light drawing\r\n @svgstr = doc.to_xml\r\n self\r\n end", "code_tokens": ["def", "recolor", "(", "bg", ":", "'#000'", ",", "fg", ":", "'#fff'", ",", "bg_opacity", ":", "\"1.0\"", ",", "fg_opacity", ":", "\"1.0\"", ")", "OptionalDeps", ".", "require_nokogiri", "bg", ".", "prepend", "(", "'#'", ")", "unless", "bg", ".", "start_with?", "'#'", "fg", ".", "prepend", "(", "'#'", ")", "unless", "fg", ".", "start_with?", "'#'", "doc", "=", "Nokogiri", "::", "XML", "(", "self", ".", "string", ")", "doc", ".", "css", "(", "'path'", ")", "[", "0", "]", "[", "'fill'", "]", "=", "bg", "# dark backdrop\r", "doc", ".", "css", "(", "'path'", ")", "[", "1", "]", "[", "'fill'", "]", "=", "fg", "# light drawing\r", "doc", ".", "css", "(", "'path'", ")", "[", "0", "]", "[", "'fill-opacity'", "]", "=", "bg_opacity", ".", "to_s", "# dark backdrop\r", "doc", ".", "css", "(", "'path'", ")", "[", "1", "]", "[", "'fill-opacity'", "]", "=", "fg_opacity", ".", "to_s", "# light drawing\r", "@svgstr", "=", "doc", ".", "to_xml", "self", "end"], "docstring": "Modify the background and foreground colors and their opacities", "docstring_tokens": ["Modify", "the", "background", "and", "foreground", "colors", "and", "their", "opacities"], "sha": "f108e7211e4b860292487bcbee79ce1640a3ec02", "url": "https://github.com/andymeneely/game_icons/blob/f108e7211e4b860292487bcbee79ce1640a3ec02/lib/game_icons/icon.rb#L16-L27", "partition": "test"} {"repo": "jmettraux/rufus-tokyo", "path": "lib/rufus/tokyo/cabinet/abstract.rb", "func_name": "Rufus::Tokyo.Cabinet.compact_copy", "original_string": "def compact_copy (target_path)\n\n @other_db = Cabinet.new(target_path)\n self.each { |k, v| @other_db[k] = v }\n @other_db.close\n end", "language": "ruby", "code": "def compact_copy (target_path)\n\n @other_db = Cabinet.new(target_path)\n self.each { |k, v| @other_db[k] = v }\n @other_db.close\n end", "code_tokens": ["def", "compact_copy", "(", "target_path", ")", "@other_db", "=", "Cabinet", ".", "new", "(", "target_path", ")", "self", ".", "each", "{", "|", "k", ",", "v", "|", "@other_db", "[", "k", "]", "=", "v", "}", "@other_db", ".", "close", "end"], "docstring": "Copies the current cabinet to a new file.\n\n Does it by copying each entry afresh to the target file. Spares some\n space, hence the 'compact' label...", "docstring_tokens": ["Copies", "the", "current", "cabinet", "to", "a", "new", "file", "."], "sha": "910413a982ed501e03d0c16f755929ce54d84644", "url": "https://github.com/jmettraux/rufus-tokyo/blob/910413a982ed501e03d0c16f755929ce54d84644/lib/rufus/tokyo/cabinet/abstract.rb#L363-L368", "partition": "test"} {"repo": "jmettraux/rufus-tokyo", "path": "lib/rufus/tokyo/cabinet/abstract.rb", "func_name": "Rufus::Tokyo.Cabinet.keys", "original_string": "def keys (options={})\n\n if @type == \"tcf\"\n min, max = \"min\", \"max\"\n l = lib.tcfdbrange2( as_fixed, min, Rufus::Tokyo.blen(min),\n max, Rufus::Tokyo.blen(max), -1)\n else\n pre = options.fetch(:prefix, \"\")\n\n l = lib.abs_fwmkeys(\n @db, pre, Rufus::Tokyo.blen(pre), options[:limit] || -1)\n end\n\n l = Rufus::Tokyo::List.new(l)\n\n options[:native] ? l : l.release\n end", "language": "ruby", "code": "def keys (options={})\n\n if @type == \"tcf\"\n min, max = \"min\", \"max\"\n l = lib.tcfdbrange2( as_fixed, min, Rufus::Tokyo.blen(min),\n max, Rufus::Tokyo.blen(max), -1)\n else\n pre = options.fetch(:prefix, \"\")\n\n l = lib.abs_fwmkeys(\n @db, pre, Rufus::Tokyo.blen(pre), options[:limit] || -1)\n end\n\n l = Rufus::Tokyo::List.new(l)\n\n options[:native] ? l : l.release\n end", "code_tokens": ["def", "keys", "(", "options", "=", "{", "}", ")", "if", "@type", "==", "\"tcf\"", "min", ",", "max", "=", "\"min\"", ",", "\"max\"", "l", "=", "lib", ".", "tcfdbrange2", "(", "as_fixed", ",", "min", ",", "Rufus", "::", "Tokyo", ".", "blen", "(", "min", ")", ",", "max", ",", "Rufus", "::", "Tokyo", ".", "blen", "(", "max", ")", ",", "-", "1", ")", "else", "pre", "=", "options", ".", "fetch", "(", ":prefix", ",", "\"\"", ")", "l", "=", "lib", ".", "abs_fwmkeys", "(", "@db", ",", "pre", ",", "Rufus", "::", "Tokyo", ".", "blen", "(", "pre", ")", ",", "options", "[", ":limit", "]", "||", "-", "1", ")", "end", "l", "=", "Rufus", "::", "Tokyo", "::", "List", ".", "new", "(", "l", ")", "options", "[", ":native", "]", "?", "l", ":", "l", ".", "release", "end"], "docstring": "Returns an array with all the keys in the databse\n\n With no options given, this method will return all the keys (strings)\n in a Ruby array.\n\n :prefix --> returns only the keys who match a given string prefix\n\n :limit --> returns a limited number of keys\n\n :native --> returns an instance of Rufus::Tokyo::List instead of\n a Ruby Hash, you have to call #free on that List when done with it !\n Else you're exposing yourself to a memory leak.", "docstring_tokens": ["Returns", "an", "array", "with", "all", "the", "keys", "in", "the", "databse"], "sha": "910413a982ed501e03d0c16f755929ce54d84644", "url": "https://github.com/jmettraux/rufus-tokyo/blob/910413a982ed501e03d0c16f755929ce54d84644/lib/rufus/tokyo/cabinet/abstract.rb#L391-L407", "partition": "test"} {"repo": "jmettraux/rufus-tokyo", "path": "lib/rufus/tokyo/cabinet/abstract.rb", "func_name": "Rufus::Tokyo.Cabinet.get4", "original_string": "def get4 (k)\n\n l = lib.tcbdbget4(as_btree, k, Rufus::Tokyo.blen(k))\n Rufus::Tokyo::List.new(l).release\n end", "language": "ruby", "code": "def get4 (k)\n\n l = lib.tcbdbget4(as_btree, k, Rufus::Tokyo.blen(k))\n Rufus::Tokyo::List.new(l).release\n end", "code_tokens": ["def", "get4", "(", "k", ")", "l", "=", "lib", ".", "tcbdbget4", "(", "as_btree", ",", "k", ",", "Rufus", "::", "Tokyo", ".", "blen", "(", "k", ")", ")", "Rufus", "::", "Tokyo", "::", "List", ".", "new", "(", "l", ")", ".", "release", "end"], "docstring": "This is a B+ Tree method only, returns all the values for a given\n key.", "docstring_tokens": ["This", "is", "a", "B", "+", "Tree", "method", "only", "returns", "all", "the", "values", "for", "a", "given", "key", "."], "sha": "910413a982ed501e03d0c16f755929ce54d84644", "url": "https://github.com/jmettraux/rufus-tokyo/blob/910413a982ed501e03d0c16f755929ce54d84644/lib/rufus/tokyo/cabinet/abstract.rb#L562-L566", "partition": "test"} {"repo": "jmettraux/rufus-tokyo", "path": "lib/rufus/tokyo/cabinet/util.rb", "func_name": "Rufus::Tokyo.Map.[]=", "original_string": "def []= (k, v)\n\n clib.tcmapput(pointer, k, Rufus::Tokyo::blen(k), v, Rufus::Tokyo::blen(v))\n\n v\n end", "language": "ruby", "code": "def []= (k, v)\n\n clib.tcmapput(pointer, k, Rufus::Tokyo::blen(k), v, Rufus::Tokyo::blen(v))\n\n v\n end", "code_tokens": ["def", "[]=", "(", "k", ",", "v", ")", "clib", ".", "tcmapput", "(", "pointer", ",", "k", ",", "Rufus", "::", "Tokyo", "::", "blen", "(", "k", ")", ",", "v", ",", "Rufus", "::", "Tokyo", "::", "blen", "(", "v", ")", ")", "v", "end"], "docstring": "Creates an empty instance of a Tokyo Cabinet in-memory map\n\n (It's OK to pass the pointer of a C map directly, this is in fact\n used in rufus/tokyo/table when retrieving entries)\n\n Inserts key/value pair", "docstring_tokens": ["Creates", "an", "empty", "instance", "of", "a", "Tokyo", "Cabinet", "in", "-", "memory", "map"], "sha": "910413a982ed501e03d0c16f755929ce54d84644", "url": "https://github.com/jmettraux/rufus-tokyo/blob/910413a982ed501e03d0c16f755929ce54d84644/lib/rufus/tokyo/cabinet/util.rb#L101-L106", "partition": "test"} {"repo": "jmettraux/rufus-tokyo", "path": "lib/rufus/tokyo/cabinet/util.rb", "func_name": "Rufus::Tokyo.Map.delete", "original_string": "def delete (k)\n\n v = self[k]\n return nil unless v\n\n clib.tcmapout(pointer_or_raise, k, Rufus::Tokyo::blen(k)) ||\n raise(\"failed to remove key '#{k}'\")\n\n v\n end", "language": "ruby", "code": "def delete (k)\n\n v = self[k]\n return nil unless v\n\n clib.tcmapout(pointer_or_raise, k, Rufus::Tokyo::blen(k)) ||\n raise(\"failed to remove key '#{k}'\")\n\n v\n end", "code_tokens": ["def", "delete", "(", "k", ")", "v", "=", "self", "[", "k", "]", "return", "nil", "unless", "v", "clib", ".", "tcmapout", "(", "pointer_or_raise", ",", "k", ",", "Rufus", "::", "Tokyo", "::", "blen", "(", "k", ")", ")", "||", "raise", "(", "\"failed to remove key '#{k}'\"", ")", "v", "end"], "docstring": "Deletes an entry", "docstring_tokens": ["Deletes", "an", "entry"], "sha": "910413a982ed501e03d0c16f755929ce54d84644", "url": "https://github.com/jmettraux/rufus-tokyo/blob/910413a982ed501e03d0c16f755929ce54d84644/lib/rufus/tokyo/cabinet/util.rb#L110-L119", "partition": "test"} {"repo": "jmettraux/rufus-tokyo", "path": "lib/rufus/tokyo/cabinet/util.rb", "func_name": "Rufus::Tokyo.Map.keys", "original_string": "def keys\n\n clib.tcmapiterinit(pointer_or_raise)\n a = []\n\n klen = FFI::MemoryPointer.new(:int)\n\n loop do\n k = clib.tcmapiternext(@pointer, klen)\n break if k.address == 0\n a << k.get_bytes(0, klen.get_int(0))\n end\n\n return a\n\n ensure\n\n klen.free\n end", "language": "ruby", "code": "def keys\n\n clib.tcmapiterinit(pointer_or_raise)\n a = []\n\n klen = FFI::MemoryPointer.new(:int)\n\n loop do\n k = clib.tcmapiternext(@pointer, klen)\n break if k.address == 0\n a << k.get_bytes(0, klen.get_int(0))\n end\n\n return a\n\n ensure\n\n klen.free\n end", "code_tokens": ["def", "keys", "clib", ".", "tcmapiterinit", "(", "pointer_or_raise", ")", "a", "=", "[", "]", "klen", "=", "FFI", "::", "MemoryPointer", ".", "new", "(", ":int", ")", "loop", "do", "k", "=", "clib", ".", "tcmapiternext", "(", "@pointer", ",", "klen", ")", "break", "if", "k", ".", "address", "==", "0", "a", "<<", "k", ".", "get_bytes", "(", "0", ",", "klen", ".", "get_int", "(", "0", ")", ")", "end", "return", "a", "ensure", "klen", ".", "free", "end"], "docstring": "Returns an array of all the keys in the map", "docstring_tokens": ["Returns", "an", "array", "of", "all", "the", "keys", "in", "the", "map"], "sha": "910413a982ed501e03d0c16f755929ce54d84644", "url": "https://github.com/jmettraux/rufus-tokyo/blob/910413a982ed501e03d0c16f755929ce54d84644/lib/rufus/tokyo/cabinet/util.rb#L138-L156", "partition": "test"} {"repo": "jmettraux/rufus-tokyo", "path": "lib/rufus/tokyo/cabinet/util.rb", "func_name": "Rufus::Tokyo.List.[]=", "original_string": "def []= (a, b, c=nil)\n\n i, s = c.nil? ? [ a, b ] : [ [a, b], c ]\n\n range = if i.is_a?(Range)\n i\n elsif i.is_a?(Array)\n start, count = i\n (start..start + count - 1)\n else\n [ i ]\n end\n\n range = norm(range)\n\n values = s.is_a?(Array) ? s : [ s ]\n # not \"values = Array(s)\"\n\n range.each_with_index do |offset, index|\n val = values[index]\n if val\n clib.tclistover(@pointer, offset, val, Rufus::Tokyo.blen(val))\n else\n outlen_op(:tclistremove, values.size)\n end\n end\n\n self\n end", "language": "ruby", "code": "def []= (a, b, c=nil)\n\n i, s = c.nil? ? [ a, b ] : [ [a, b], c ]\n\n range = if i.is_a?(Range)\n i\n elsif i.is_a?(Array)\n start, count = i\n (start..start + count - 1)\n else\n [ i ]\n end\n\n range = norm(range)\n\n values = s.is_a?(Array) ? s : [ s ]\n # not \"values = Array(s)\"\n\n range.each_with_index do |offset, index|\n val = values[index]\n if val\n clib.tclistover(@pointer, offset, val, Rufus::Tokyo.blen(val))\n else\n outlen_op(:tclistremove, values.size)\n end\n end\n\n self\n end", "code_tokens": ["def", "[]=", "(", "a", ",", "b", ",", "c", "=", "nil", ")", "i", ",", "s", "=", "c", ".", "nil?", "?", "[", "a", ",", "b", "]", ":", "[", "[", "a", ",", "b", "]", ",", "c", "]", "range", "=", "if", "i", ".", "is_a?", "(", "Range", ")", "i", "elsif", "i", ".", "is_a?", "(", "Array", ")", "start", ",", "count", "=", "i", "(", "start", "..", "start", "+", "count", "-", "1", ")", "else", "[", "i", "]", "end", "range", "=", "norm", "(", "range", ")", "values", "=", "s", ".", "is_a?", "(", "Array", ")", "?", "s", ":", "[", "s", "]", "# not \"values = Array(s)\"", "range", ".", "each_with_index", "do", "|", "offset", ",", "index", "|", "val", "=", "values", "[", "index", "]", "if", "val", "clib", ".", "tclistover", "(", "@pointer", ",", "offset", ",", "val", ",", "Rufus", "::", "Tokyo", ".", "blen", "(", "val", ")", ")", "else", "outlen_op", "(", ":tclistremove", ",", "values", ".", "size", ")", "end", "end", "self", "end"], "docstring": "The put operation.", "docstring_tokens": ["The", "put", "operation", "."], "sha": "910413a982ed501e03d0c16f755929ce54d84644", "url": "https://github.com/jmettraux/rufus-tokyo/blob/910413a982ed501e03d0c16f755929ce54d84644/lib/rufus/tokyo/cabinet/util.rb#L282-L310", "partition": "test"} {"repo": "jmettraux/rufus-tokyo", "path": "lib/rufus/tokyo/cabinet/table.rb", "func_name": "Rufus::Tokyo.Table.keys", "original_string": "def keys (options={})\n\n pre = options.fetch(:prefix, \"\")\n\n l = lib.tab_fwmkeys(\n @db, pre, Rufus::Tokyo.blen(pre), options[:limit] || -1)\n\n l = Rufus::Tokyo::List.new(l)\n\n options[:native] ? l : l.release\n end", "language": "ruby", "code": "def keys (options={})\n\n pre = options.fetch(:prefix, \"\")\n\n l = lib.tab_fwmkeys(\n @db, pre, Rufus::Tokyo.blen(pre), options[:limit] || -1)\n\n l = Rufus::Tokyo::List.new(l)\n\n options[:native] ? l : l.release\n end", "code_tokens": ["def", "keys", "(", "options", "=", "{", "}", ")", "pre", "=", "options", ".", "fetch", "(", ":prefix", ",", "\"\"", ")", "l", "=", "lib", ".", "tab_fwmkeys", "(", "@db", ",", "pre", ",", "Rufus", "::", "Tokyo", ".", "blen", "(", "pre", ")", ",", "options", "[", ":limit", "]", "||", "-", "1", ")", "l", "=", "Rufus", "::", "Tokyo", "::", "List", ".", "new", "(", "l", ")", "options", "[", ":native", "]", "?", "l", ":", "l", ".", "release", "end"], "docstring": "Returns an array of all the primary keys in the table\n\n With no options given, this method will return all the keys (strings)\n in a Ruby array.\n\n :prefix --> returns only the keys who match a given string prefix\n\n :limit --> returns a limited number of keys\n\n :native --> returns an instance of Rufus::Tokyo::List instead of\n a Ruby Hash, you have to call #free on that List when done with it !\n Else you're exposing yourself to a memory leak.", "docstring_tokens": ["Returns", "an", "array", "of", "all", "the", "primary", "keys", "in", "the", "table"], "sha": "910413a982ed501e03d0c16f755929ce54d84644", "url": "https://github.com/jmettraux/rufus-tokyo/blob/910413a982ed501e03d0c16f755929ce54d84644/lib/rufus/tokyo/cabinet/table.rb#L298-L308", "partition": "test"} {"repo": "jmettraux/rufus-tokyo", "path": "lib/rufus/tokyo/cabinet/table.rb", "func_name": "Rufus::Tokyo.Table.lget", "original_string": "def lget (*keys)\n\n keys.flatten.inject({}) { |h, k|\n k = k.to_s\n v = self[k]\n h[k] = v if v\n h\n }\n end", "language": "ruby", "code": "def lget (*keys)\n\n keys.flatten.inject({}) { |h, k|\n k = k.to_s\n v = self[k]\n h[k] = v if v\n h\n }\n end", "code_tokens": ["def", "lget", "(", "*", "keys", ")", "keys", ".", "flatten", ".", "inject", "(", "{", "}", ")", "{", "|", "h", ",", "k", "|", "k", "=", "k", ".", "to_s", "v", "=", "self", "[", "k", "]", "h", "[", "k", "]", "=", "v", "if", "v", "h", "}", "end"], "docstring": "No 'misc' methods for the table library, so this lget is equivalent\n to calling get for each key. Hoping later versions of TC will provide\n a mget method.", "docstring_tokens": ["No", "misc", "methods", "for", "the", "table", "library", "so", "this", "lget", "is", "equivalent", "to", "calling", "get", "for", "each", "key", ".", "Hoping", "later", "versions", "of", "TC", "will", "provide", "a", "mget", "method", "."], "sha": "910413a982ed501e03d0c16f755929ce54d84644", "url": "https://github.com/jmettraux/rufus-tokyo/blob/910413a982ed501e03d0c16f755929ce54d84644/lib/rufus/tokyo/cabinet/table.rb#L321-L329", "partition": "test"} {"repo": "jmettraux/rufus-tokyo", "path": "lib/rufus/tokyo/cabinet/table.rb", "func_name": "Rufus::Tokyo.Table.raise_error", "original_string": "def raise_error\n\n err_code = lib.tab_ecode(@db)\n err_msg = lib.tab_errmsg(err_code)\n\n raise TokyoError.new(\"(err #{err_code}) #{err_msg}\")\n end", "language": "ruby", "code": "def raise_error\n\n err_code = lib.tab_ecode(@db)\n err_msg = lib.tab_errmsg(err_code)\n\n raise TokyoError.new(\"(err #{err_code}) #{err_msg}\")\n end", "code_tokens": ["def", "raise_error", "err_code", "=", "lib", ".", "tab_ecode", "(", "@db", ")", "err_msg", "=", "lib", ".", "tab_errmsg", "(", "err_code", ")", "raise", "TokyoError", ".", "new", "(", "\"(err #{err_code}) #{err_msg}\"", ")", "end"], "docstring": "Obviously something got wrong, let's ask the db about it and raise\n a TokyoError", "docstring_tokens": ["Obviously", "something", "got", "wrong", "let", "s", "ask", "the", "db", "about", "it", "and", "raise", "a", "TokyoError"], "sha": "910413a982ed501e03d0c16f755929ce54d84644", "url": "https://github.com/jmettraux/rufus-tokyo/blob/910413a982ed501e03d0c16f755929ce54d84644/lib/rufus/tokyo/cabinet/table.rb#L587-L593", "partition": "test"} {"repo": "jmettraux/rufus-tokyo", "path": "lib/rufus/tokyo/cabinet/table.rb", "func_name": "Rufus::Tokyo.TableResultSet.each", "original_string": "def each\n\n (0..size-1).each do |i|\n pk = @list[i]\n if @opts[:pk_only]\n yield(pk)\n else\n val = @table[pk]\n val[:pk] = pk unless @opts[:no_pk]\n yield(val)\n end\n end\n end", "language": "ruby", "code": "def each\n\n (0..size-1).each do |i|\n pk = @list[i]\n if @opts[:pk_only]\n yield(pk)\n else\n val = @table[pk]\n val[:pk] = pk unless @opts[:no_pk]\n yield(val)\n end\n end\n end", "code_tokens": ["def", "each", "(", "0", "..", "size", "-", "1", ")", ".", "each", "do", "|", "i", "|", "pk", "=", "@list", "[", "i", "]", "if", "@opts", "[", ":pk_only", "]", "yield", "(", "pk", ")", "else", "val", "=", "@table", "[", "pk", "]", "val", "[", ":pk", "]", "=", "pk", "unless", "@opts", "[", ":no_pk", "]", "yield", "(", "val", ")", "end", "end", "end"], "docstring": "The classical each", "docstring_tokens": ["The", "classical", "each"], "sha": "910413a982ed501e03d0c16f755929ce54d84644", "url": "https://github.com/jmettraux/rufus-tokyo/blob/910413a982ed501e03d0c16f755929ce54d84644/lib/rufus/tokyo/cabinet/table.rb#L877-L889", "partition": "test"} {"repo": "andymeneely/game_icons", "path": "lib/game_icons/finder.rb", "func_name": "GameIcons.Finder.find", "original_string": "def find(icon)\r\n str = icon.to_s.downcase\r\n file = DB.files[str] ||\r\n DB.files[str.sub(/\\.svg$/,'')] ||\r\n not_found(str, icon)\r\n Icon.new(file)\r\n end", "language": "ruby", "code": "def find(icon)\r\n str = icon.to_s.downcase\r\n file = DB.files[str] ||\r\n DB.files[str.sub(/\\.svg$/,'')] ||\r\n not_found(str, icon)\r\n Icon.new(file)\r\n end", "code_tokens": ["def", "find", "(", "icon", ")", "str", "=", "icon", ".", "to_s", ".", "downcase", "file", "=", "DB", ".", "files", "[", "str", "]", "||", "DB", ".", "files", "[", "str", ".", "sub", "(", "/", "\\.", "/", ",", "''", ")", "]", "||", "not_found", "(", "str", ",", "icon", ")", "Icon", ".", "new", "(", "file", ")", "end"], "docstring": "Find the icon, possibly without the extension.\n @example Finder.new.find('glass-heart')\n Raises an error if the icon could not be found.", "docstring_tokens": ["Find", "the", "icon", "possibly", "without", "the", "extension", "."], "sha": "f108e7211e4b860292487bcbee79ce1640a3ec02", "url": "https://github.com/andymeneely/game_icons/blob/f108e7211e4b860292487bcbee79ce1640a3ec02/lib/game_icons/finder.rb#L11-L17", "partition": "test"} {"repo": "dhrubomoy/to-arff", "path": "lib/to-arff/sqlitedb.rb", "func_name": "ToARFF.SQLiteDB.get_columns", "original_string": "def get_columns(table_name)\n\t\t\tcolumns_arr = []\n\t\t pst = @db.prepare \"SELECT * FROM #{table_name} LIMIT 6\"\n\t\t pst.columns.each do |c|\n\t\t \tcolumns_arr.push(c)\n\t\t end\n\t\t columns_arr\n\t\tend", "language": "ruby", "code": "def get_columns(table_name)\n\t\t\tcolumns_arr = []\n\t\t pst = @db.prepare \"SELECT * FROM #{table_name} LIMIT 6\"\n\t\t pst.columns.each do |c|\n\t\t \tcolumns_arr.push(c)\n\t\t end\n\t\t columns_arr\n\t\tend", "code_tokens": ["def", "get_columns", "(", "table_name", ")", "columns_arr", "=", "[", "]", "pst", "=", "@db", ".", "prepare", "\"SELECT * FROM #{table_name} LIMIT 6\"", "pst", ".", "columns", ".", "each", "do", "|", "c", "|", "columns_arr", ".", "push", "(", "c", ")", "end", "columns_arr", "end"], "docstring": "Get all colums for a given table.", "docstring_tokens": ["Get", "all", "colums", "for", "a", "given", "table", "."], "sha": "b34e4b85cab4c19007144ccee1e6562f4974ab89", "url": "https://github.com/dhrubomoy/to-arff/blob/b34e4b85cab4c19007144ccee1e6562f4974ab89/lib/to-arff/sqlitedb.rb#L46-L53", "partition": "test"} {"repo": "dhrubomoy/to-arff", "path": "lib/to-arff/sqlitedb.rb", "func_name": "ToARFF.SQLiteDB.is_numeric", "original_string": "def is_numeric(table_name, column_name)\n\t\t\tif @db.execute(\"SELECT #{column_name} from #{table_name} LIMIT 1\").first.first.is_a? Numeric\n\t\t\t\treturn true\n\t\t\telse\n\t\t\t\treturn false\n\t\t\tend\n\t\tend", "language": "ruby", "code": "def is_numeric(table_name, column_name)\n\t\t\tif @db.execute(\"SELECT #{column_name} from #{table_name} LIMIT 1\").first.first.is_a? Numeric\n\t\t\t\treturn true\n\t\t\telse\n\t\t\t\treturn false\n\t\t\tend\n\t\tend", "code_tokens": ["def", "is_numeric", "(", "table_name", ",", "column_name", ")", "if", "@db", ".", "execute", "(", "\"SELECT #{column_name} from #{table_name} LIMIT 1\"", ")", ".", "first", ".", "first", ".", "is_a?", "Numeric", "return", "true", "else", "return", "false", "end", "end"], "docstring": "If the column type is nominal return true.", "docstring_tokens": ["If", "the", "column", "type", "is", "nominal", "return", "true", "."], "sha": "b34e4b85cab4c19007144ccee1e6562f4974ab89", "url": "https://github.com/dhrubomoy/to-arff/blob/b34e4b85cab4c19007144ccee1e6562f4974ab89/lib/to-arff/sqlitedb.rb#L62-L68", "partition": "test"} {"repo": "dhrubomoy/to-arff", "path": "lib/to-arff/sqlitedb.rb", "func_name": "ToARFF.SQLiteDB.deal_with_valid_option", "original_string": "def deal_with_valid_option(temp_tables, temp_columns, temp_column_types, res)\n\t\t\tif !temp_tables.empty?\n\t\t\t\tcheck_given_tables_validity(temp_tables)\n\t\t\t\ttemp_tables.each do |t|\n\t\t\t\t\tres << convert_table(t)\n\t\t\t\tend\n\t\t\telsif !temp_columns.keys.empty?\n\t\t\t\tcheck_given_columns_validity(temp_columns)\n\t\t\t\tres << convert_from_columns_hash(temp_columns)\n\t\t\telsif !temp_column_types.empty?\n\t\t\t\tcheck_given_columns_validity(temp_column_types)\n\t\t\t\tres << convert_from_column_types_hash(temp_column_types)\n\t\t\tend\n\t\tend", "language": "ruby", "code": "def deal_with_valid_option(temp_tables, temp_columns, temp_column_types, res)\n\t\t\tif !temp_tables.empty?\n\t\t\t\tcheck_given_tables_validity(temp_tables)\n\t\t\t\ttemp_tables.each do |t|\n\t\t\t\t\tres << convert_table(t)\n\t\t\t\tend\n\t\t\telsif !temp_columns.keys.empty?\n\t\t\t\tcheck_given_columns_validity(temp_columns)\n\t\t\t\tres << convert_from_columns_hash(temp_columns)\n\t\t\telsif !temp_column_types.empty?\n\t\t\t\tcheck_given_columns_validity(temp_column_types)\n\t\t\t\tres << convert_from_column_types_hash(temp_column_types)\n\t\t\tend\n\t\tend", "code_tokens": ["def", "deal_with_valid_option", "(", "temp_tables", ",", "temp_columns", ",", "temp_column_types", ",", "res", ")", "if", "!", "temp_tables", ".", "empty?", "check_given_tables_validity", "(", "temp_tables", ")", "temp_tables", ".", "each", "do", "|", "t", "|", "res", "<<", "convert_table", "(", "t", ")", "end", "elsif", "!", "temp_columns", ".", "keys", ".", "empty?", "check_given_columns_validity", "(", "temp_columns", ")", "res", "<<", "convert_from_columns_hash", "(", "temp_columns", ")", "elsif", "!", "temp_column_types", ".", "empty?", "check_given_columns_validity", "(", "temp_column_types", ")", "res", "<<", "convert_from_column_types_hash", "(", "temp_column_types", ")", "end", "end"], "docstring": "If valid option was provided in convert method", "docstring_tokens": ["If", "valid", "option", "was", "provided", "in", "convert", "method"], "sha": "b34e4b85cab4c19007144ccee1e6562f4974ab89", "url": "https://github.com/dhrubomoy/to-arff/blob/b34e4b85cab4c19007144ccee1e6562f4974ab89/lib/to-arff/sqlitedb.rb#L180-L193", "partition": "test"} {"repo": "northwoodspd/dryspec", "path": "lib/dryspec/helpers.rb", "func_name": "DRYSpec.Helpers.let_context", "original_string": "def let_context(*args, &block)\n context_string, hash =\n case args.map(&:class)\n when [String, Hash] then [\"#{args[0]} #{args[1]}\", args[1]]\n when [Hash] then [args[0].inspect, args[0]]\n end\n\n context(context_string) do\n hash.each { |var, value| let(var) { value } }\n\n instance_eval(&block)\n end\n end", "language": "ruby", "code": "def let_context(*args, &block)\n context_string, hash =\n case args.map(&:class)\n when [String, Hash] then [\"#{args[0]} #{args[1]}\", args[1]]\n when [Hash] then [args[0].inspect, args[0]]\n end\n\n context(context_string) do\n hash.each { |var, value| let(var) { value } }\n\n instance_eval(&block)\n end\n end", "code_tokens": ["def", "let_context", "(", "*", "args", ",", "&", "block", ")", "context_string", ",", "hash", "=", "case", "args", ".", "map", "(", ":class", ")", "when", "[", "String", ",", "Hash", "]", "then", "[", "\"#{args[0]} #{args[1]}\"", ",", "args", "[", "1", "]", "]", "when", "[", "Hash", "]", "then", "[", "args", "[", "0", "]", ".", "inspect", ",", "args", "[", "0", "]", "]", "end", "context", "(", "context_string", ")", "do", "hash", ".", "each", "{", "|", "var", ",", "value", "|", "let", "(", "var", ")", "{", "value", "}", "}", "instance_eval", "(", "block", ")", "end", "end"], "docstring": "This allows us to simplify the case where we want to\n have a context which contains one or more `let` statements\n\n Supports giving either a Hash or a String and a Hash as arguments\n In both cases the Hash will be used to define `let` statements\n When a String is specified that becomes the context description\n If String isn't specified, Hash#inspect becomes the context description\n\n @example Defining a simple let variable\n # Before\n subject { a + 1 }\n context('a is 1') do\n let(:a) { 1 }\n it { should eq 2 }\n end\n\n # After\n subject { a + 1 }\n let_context(a: 1) { it { should eq 2 } }\n\n @example Giving a descriptive string\n subject { a + 1 }\n let_context('Negative number', a: -1) { it { should eq 0 } }\n\n @example Multiple variables\n subject { a + b }\n let_context(a: 1, b: 2) { it { should eq 3 } }", "docstring_tokens": ["This", "allows", "us", "to", "simplify", "the", "case", "where", "we", "want", "to", "have", "a", "context", "which", "contains", "one", "or", "more", "let", "statements"], "sha": "1072a9714c24dc82fd8ea5c88c3ce7ca3f97dcca", "url": "https://github.com/northwoodspd/dryspec/blob/1072a9714c24dc82fd8ea5c88c3ce7ca3f97dcca/lib/dryspec/helpers.rb#L30-L42", "partition": "test"} {"repo": "northwoodspd/dryspec", "path": "lib/dryspec/helpers.rb", "func_name": "DRYSpec.Helpers.subject_should_raise", "original_string": "def subject_should_raise(*args)\n error, message = args\n it_string = \"subject should raise #{error}\"\n it_string += \" (#{message.inspect})\" if message\n\n it it_string do\n expect { subject }.to raise_error error, message\n end\n end", "language": "ruby", "code": "def subject_should_raise(*args)\n error, message = args\n it_string = \"subject should raise #{error}\"\n it_string += \" (#{message.inspect})\" if message\n\n it it_string do\n expect { subject }.to raise_error error, message\n end\n end", "code_tokens": ["def", "subject_should_raise", "(", "*", "args", ")", "error", ",", "message", "=", "args", "it_string", "=", "\"subject should raise #{error}\"", "it_string", "+=", "\" (#{message.inspect})\"", "if", "message", "it", "it_string", "do", "expect", "{", "subject", "}", ".", "to", "raise_error", "error", ",", "message", "end", "end"], "docstring": "Allows you to simply specify that the subject should raise an exception\n Takes no arguments or arguments of an exception class, a string, or both.\n\n As with RSpec's basic `to raise_error` matcher, if you don't give an error\n then the an unexpected error may cause your test to pass incorrectly\n\n @example Raising a string\n # Before\n subject { fail 'Test' }\n it \"should raise 'Test'\" do\n expect { subject }.to raise_error 'Test'\n end\n\n # After\n subject { fail 'Test' }\n subject_should_raise 'Test'\n\n @example Raising an exception class\n subject { fail ArgumentError }\n subject_should_raise ArgumentError\n\n @example Raising an exception class and string\n subject { fail ArgumentError, 'Test' }\n subject_should_raise ArgumentError, 'Test'", "docstring_tokens": ["Allows", "you", "to", "simply", "specify", "that", "the", "subject", "should", "raise", "an", "exception", "Takes", "no", "arguments", "or", "arguments", "of", "an", "exception", "class", "a", "string", "or", "both", "."], "sha": "1072a9714c24dc82fd8ea5c88c3ce7ca3f97dcca", "url": "https://github.com/northwoodspd/dryspec/blob/1072a9714c24dc82fd8ea5c88c3ce7ca3f97dcca/lib/dryspec/helpers.rb#L68-L76", "partition": "test"} {"repo": "northwoodspd/dryspec", "path": "lib/dryspec/helpers.rb", "func_name": "DRYSpec.Helpers.subject_should_not_raise", "original_string": "def subject_should_not_raise(*args)\n error, message = args\n it_string = \"subject should not raise #{error}\"\n it_string += \" (#{message.inspect})\" if message\n\n it it_string do\n expect { subject }.not_to raise_error error, message\n end\n end", "language": "ruby", "code": "def subject_should_not_raise(*args)\n error, message = args\n it_string = \"subject should not raise #{error}\"\n it_string += \" (#{message.inspect})\" if message\n\n it it_string do\n expect { subject }.not_to raise_error error, message\n end\n end", "code_tokens": ["def", "subject_should_not_raise", "(", "*", "args", ")", "error", ",", "message", "=", "args", "it_string", "=", "\"subject should not raise #{error}\"", "it_string", "+=", "\" (#{message.inspect})\"", "if", "message", "it", "it_string", "do", "expect", "{", "subject", "}", ".", "not_to", "raise_error", "error", ",", "message", "end", "end"], "docstring": "Allows you to simply specify that the subject should not raise an exception.\n Takes no arguments or arguments of an exception class, a string, or both.\n\n As with RSpec's basic `not_to raise_error` matcher, if you give a specific error, other\n unexpected errors may be swallowed silently\n\n @example Subject does not raise an error\n # Before\n subject { 1 }\n it 'should not raise an exception' do\n expect { subject }.not_to raise_error\n end\n\n # After\n subject { 1 }\n subject_should_not_raise", "docstring_tokens": ["Allows", "you", "to", "simply", "specify", "that", "the", "subject", "should", "not", "raise", "an", "exception", ".", "Takes", "no", "arguments", "or", "arguments", "of", "an", "exception", "class", "a", "string", "or", "both", "."], "sha": "1072a9714c24dc82fd8ea5c88c3ce7ca3f97dcca", "url": "https://github.com/northwoodspd/dryspec/blob/1072a9714c24dc82fd8ea5c88c3ce7ca3f97dcca/lib/dryspec/helpers.rb#L94-L102", "partition": "test"} {"repo": "ysbaddaden/janus", "path": "lib/janus/manager.rb", "func_name": "Janus.Manager.login", "original_string": "def login(user, options = {})\n options[:scope] ||= Janus.scope_for(user)\n set_user(user, options)\n Janus::Manager.run_callbacks(:login, user, self, options)\n end", "language": "ruby", "code": "def login(user, options = {})\n options[:scope] ||= Janus.scope_for(user)\n set_user(user, options)\n Janus::Manager.run_callbacks(:login, user, self, options)\n end", "code_tokens": ["def", "login", "(", "user", ",", "options", "=", "{", "}", ")", "options", "[", ":scope", "]", "||=", "Janus", ".", "scope_for", "(", "user", ")", "set_user", "(", "user", ",", "options", ")", "Janus", "::", "Manager", ".", "run_callbacks", "(", ":login", ",", "user", ",", "self", ",", "options", ")", "end"], "docstring": "Logs a user in.\n\n FIXME: what should happen when a user signs in but a user is already signed in for the same scope?!", "docstring_tokens": ["Logs", "a", "user", "in", "."], "sha": "a4d1f9705b48e765377b7296765ffeff8d35f771", "url": "https://github.com/ysbaddaden/janus/blob/a4d1f9705b48e765377b7296765ffeff8d35f771/lib/janus/manager.rb#L38-L42", "partition": "test"} {"repo": "ysbaddaden/janus", "path": "lib/janus/manager.rb", "func_name": "Janus.Manager.logout", "original_string": "def logout(*scopes)\n scopes = janus_sessions.keys if scopes.empty?\n\n scopes.each do |scope|\n _user = user(scope)\n unset_user(scope)\n Janus::Manager.run_callbacks(:logout, _user, self, :scope => scope)\n end\n\n request.reset_session if janus_sessions.empty?\n end", "language": "ruby", "code": "def logout(*scopes)\n scopes = janus_sessions.keys if scopes.empty?\n\n scopes.each do |scope|\n _user = user(scope)\n unset_user(scope)\n Janus::Manager.run_callbacks(:logout, _user, self, :scope => scope)\n end\n\n request.reset_session if janus_sessions.empty?\n end", "code_tokens": ["def", "logout", "(", "*", "scopes", ")", "scopes", "=", "janus_sessions", ".", "keys", "if", "scopes", ".", "empty?", "scopes", ".", "each", "do", "|", "scope", "|", "_user", "=", "user", "(", "scope", ")", "unset_user", "(", "scope", ")", "Janus", "::", "Manager", ".", "run_callbacks", "(", ":logout", ",", "_user", ",", "self", ",", ":scope", "=>", "scope", ")", "end", "request", ".", "reset_session", "if", "janus_sessions", ".", "empty?", "end"], "docstring": "Logs a user out from the given scopes or from all scopes at once\n if no scope is defined. If no scope is left after logout, then the\n whole session will be resetted.", "docstring_tokens": ["Logs", "a", "user", "out", "from", "the", "given", "scopes", "or", "from", "all", "scopes", "at", "once", "if", "no", "scope", "is", "defined", ".", "If", "no", "scope", "is", "left", "after", "logout", "then", "the", "whole", "session", "will", "be", "resetted", "."], "sha": "a4d1f9705b48e765377b7296765ffeff8d35f771", "url": "https://github.com/ysbaddaden/janus/blob/a4d1f9705b48e765377b7296765ffeff8d35f771/lib/janus/manager.rb#L47-L57", "partition": "test"} {"repo": "ysbaddaden/janus", "path": "lib/janus/manager.rb", "func_name": "Janus.Manager.set_user", "original_string": "def set_user(user, options = {})\n scope = options[:scope] || Janus.scope_for(user)\n janus_sessions[scope.to_s] = { 'user_class' => user.class.name, 'user_id' => user.id }\n end", "language": "ruby", "code": "def set_user(user, options = {})\n scope = options[:scope] || Janus.scope_for(user)\n janus_sessions[scope.to_s] = { 'user_class' => user.class.name, 'user_id' => user.id }\n end", "code_tokens": ["def", "set_user", "(", "user", ",", "options", "=", "{", "}", ")", "scope", "=", "options", "[", ":scope", "]", "||", "Janus", ".", "scope_for", "(", "user", ")", "janus_sessions", "[", "scope", ".", "to_s", "]", "=", "{", "'user_class'", "=>", "user", ".", "class", ".", "name", ",", "'user_id'", "=>", "user", ".", "id", "}", "end"], "docstring": "Manually sets a user without going throught the whole login or\n authenticate process.", "docstring_tokens": ["Manually", "sets", "a", "user", "without", "going", "throught", "the", "whole", "login", "or", "authenticate", "process", "."], "sha": "a4d1f9705b48e765377b7296765ffeff8d35f771", "url": "https://github.com/ysbaddaden/janus/blob/a4d1f9705b48e765377b7296765ffeff8d35f771/lib/janus/manager.rb#L61-L64", "partition": "test"} {"repo": "ysbaddaden/janus", "path": "lib/janus/manager.rb", "func_name": "Janus.Manager.unset_user", "original_string": "def unset_user(scope)\n janus_sessions.delete(scope.to_s)\n @users.delete(scope.to_sym) unless @users.nil?\n end", "language": "ruby", "code": "def unset_user(scope)\n janus_sessions.delete(scope.to_s)\n @users.delete(scope.to_sym) unless @users.nil?\n end", "code_tokens": ["def", "unset_user", "(", "scope", ")", "janus_sessions", ".", "delete", "(", "scope", ".", "to_s", ")", "@users", ".", "delete", "(", "scope", ".", "to_sym", ")", "unless", "@users", ".", "nil?", "end"], "docstring": "Manually removes the user without going throught the whole logout process.", "docstring_tokens": ["Manually", "removes", "the", "user", "without", "going", "throught", "the", "whole", "logout", "process", "."], "sha": "a4d1f9705b48e765377b7296765ffeff8d35f771", "url": "https://github.com/ysbaddaden/janus/blob/a4d1f9705b48e765377b7296765ffeff8d35f771/lib/janus/manager.rb#L67-L70", "partition": "test"} {"repo": "ysbaddaden/janus", "path": "lib/janus/manager.rb", "func_name": "Janus.Manager.user", "original_string": "def user(scope)\n scope = scope.to_sym\n @users ||= {}\n\n if authenticated?(scope)\n if @users[scope].nil?\n begin\n @users[scope] = user_class(scope).find(session(scope)['user_id'])\n rescue ActiveRecord::RecordNotFound\n unset_user(scope)\n else\n Janus::Manager.run_callbacks(:fetch, @users[scope], self, :scope => scope)\n end\n end\n\n @users[scope]\n end\n end", "language": "ruby", "code": "def user(scope)\n scope = scope.to_sym\n @users ||= {}\n\n if authenticated?(scope)\n if @users[scope].nil?\n begin\n @users[scope] = user_class(scope).find(session(scope)['user_id'])\n rescue ActiveRecord::RecordNotFound\n unset_user(scope)\n else\n Janus::Manager.run_callbacks(:fetch, @users[scope], self, :scope => scope)\n end\n end\n\n @users[scope]\n end\n end", "code_tokens": ["def", "user", "(", "scope", ")", "scope", "=", "scope", ".", "to_sym", "@users", "||=", "{", "}", "if", "authenticated?", "(", "scope", ")", "if", "@users", "[", "scope", "]", ".", "nil?", "begin", "@users", "[", "scope", "]", "=", "user_class", "(", "scope", ")", ".", "find", "(", "session", "(", "scope", ")", "[", "'user_id'", "]", ")", "rescue", "ActiveRecord", "::", "RecordNotFound", "unset_user", "(", "scope", ")", "else", "Janus", "::", "Manager", ".", "run_callbacks", "(", ":fetch", ",", "@users", "[", "scope", "]", ",", "self", ",", ":scope", "=>", "scope", ")", "end", "end", "@users", "[", "scope", "]", "end", "end"], "docstring": "Returns the currently connected user.", "docstring_tokens": ["Returns", "the", "currently", "connected", "user", "."], "sha": "a4d1f9705b48e765377b7296765ffeff8d35f771", "url": "https://github.com/ysbaddaden/janus/blob/a4d1f9705b48e765377b7296765ffeff8d35f771/lib/janus/manager.rb#L73-L90", "partition": "test"} {"repo": "translationexchange/tml-ruby", "path": "lib/tml/cache.rb", "func_name": "Tml.Cache.namespace", "original_string": "def namespace\n return '#' if Tml.config.disabled?\n @namespace || Tml.config.cache[:namespace] || Tml.config.application[:key][0..5]\n end", "language": "ruby", "code": "def namespace\n return '#' if Tml.config.disabled?\n @namespace || Tml.config.cache[:namespace] || Tml.config.application[:key][0..5]\n end", "code_tokens": ["def", "namespace", "return", "'#'", "if", "Tml", ".", "config", ".", "disabled?", "@namespace", "||", "Tml", ".", "config", ".", "cache", "[", ":namespace", "]", "||", "Tml", ".", "config", ".", "application", "[", ":key", "]", "[", "0", "..", "5", "]", "end"], "docstring": "namespace of each cache key", "docstring_tokens": ["namespace", "of", "each", "cache", "key"], "sha": "e82b8768b36a2d2d4eb1493205784555151e741e", "url": "https://github.com/translationexchange/tml-ruby/blob/e82b8768b36a2d2d4eb1493205784555151e741e/lib/tml/cache.rb#L103-L106", "partition": "test"} {"repo": "translationexchange/tml-ruby", "path": "lib/tml/cache.rb", "func_name": "Tml.Cache.extract_version", "original_string": "def extract_version(app, version = nil)\n if version\n Tml.cache.version.set(version.to_s)\n else\n version_data = app.api_client.get_from_cdn('version', {t: Time.now.to_i}, {uncompressed: true})\n\n unless version_data\n Tml.logger.debug('No releases have been generated yet. Please visit your Dashboard and publish translations.')\n return\n end\n\n Tml.cache.version.set(version_data['version'])\n end\n end", "language": "ruby", "code": "def extract_version(app, version = nil)\n if version\n Tml.cache.version.set(version.to_s)\n else\n version_data = app.api_client.get_from_cdn('version', {t: Time.now.to_i}, {uncompressed: true})\n\n unless version_data\n Tml.logger.debug('No releases have been generated yet. Please visit your Dashboard and publish translations.')\n return\n end\n\n Tml.cache.version.set(version_data['version'])\n end\n end", "code_tokens": ["def", "extract_version", "(", "app", ",", "version", "=", "nil", ")", "if", "version", "Tml", ".", "cache", ".", "version", ".", "set", "(", "version", ".", "to_s", ")", "else", "version_data", "=", "app", ".", "api_client", ".", "get_from_cdn", "(", "'version'", ",", "{", "t", ":", "Time", ".", "now", ".", "to_i", "}", ",", "{", "uncompressed", ":", "true", "}", ")", "unless", "version_data", "Tml", ".", "logger", ".", "debug", "(", "'No releases have been generated yet. Please visit your Dashboard and publish translations.'", ")", "return", "end", "Tml", ".", "cache", ".", "version", ".", "set", "(", "version_data", "[", "'version'", "]", ")", "end", "end"], "docstring": "Pulls cache version from CDN", "docstring_tokens": ["Pulls", "cache", "version", "from", "CDN"], "sha": "e82b8768b36a2d2d4eb1493205784555151e741e", "url": "https://github.com/translationexchange/tml-ruby/blob/e82b8768b36a2d2d4eb1493205784555151e741e/lib/tml/cache.rb#L140-L153", "partition": "test"} {"repo": "translationexchange/tml-ruby", "path": "lib/tml/cache.rb", "func_name": "Tml.Cache.warmup", "original_string": "def warmup(version = nil, cache_path = nil)\n if cache_path.nil?\n warmup_from_cdn(version)\n else\n warmup_from_files(version, cache_path)\n end\n end", "language": "ruby", "code": "def warmup(version = nil, cache_path = nil)\n if cache_path.nil?\n warmup_from_cdn(version)\n else\n warmup_from_files(version, cache_path)\n end\n end", "code_tokens": ["def", "warmup", "(", "version", "=", "nil", ",", "cache_path", "=", "nil", ")", "if", "cache_path", ".", "nil?", "warmup_from_cdn", "(", "version", ")", "else", "warmup_from_files", "(", "version", ",", "cache_path", ")", "end", "end"], "docstring": "Warms up cache from CDN or local files", "docstring_tokens": ["Warms", "up", "cache", "from", "CDN", "or", "local", "files"], "sha": "e82b8768b36a2d2d4eb1493205784555151e741e", "url": "https://github.com/translationexchange/tml-ruby/blob/e82b8768b36a2d2d4eb1493205784555151e741e/lib/tml/cache.rb#L156-L162", "partition": "test"} {"repo": "translationexchange/tml-ruby", "path": "lib/tml/cache.rb", "func_name": "Tml.Cache.warmup_from_files", "original_string": "def warmup_from_files(version = nil, cache_path = nil)\n t0 = Time.now\n Tml.logger = Logger.new(STDOUT)\n\n Tml.logger.debug('Starting cache warmup from local files...')\n version ||= Tml.config.cache[:version]\n cache_path ||= Tml.config.cache[:path]\n cache_path = \"#{cache_path}/#{version}\"\n\n Tml.cache.version.set(version.to_s)\n Tml.logger.debug(\"Warming Up Version: #{Tml.cache.version}\")\n\n application = JSON.parse(File.read(\"#{cache_path}/application.json\"))\n Tml.cache.store(Tml::Application.cache_key, application)\n\n sources = JSON.parse(File.read(\"#{cache_path}/sources.json\"))\n\n application['languages'].each do |lang|\n locale = lang['locale']\n\n language = JSON.parse(File.read(\"#{cache_path}/#{locale}/language.json\"))\n Tml.cache.store(Tml::Language.cache_key(locale), language)\n\n sources.each do |src|\n source = JSON.parse(File.read(\"#{cache_path}/#{locale}/sources/#{src}.json\"))\n Tml.cache.store(Tml::Source.cache_key(locale, src), source)\n end\n end\n\n t1 = Time.now\n Tml.logger.debug(\"Cache warmup took #{t1-t0}s\")\n end", "language": "ruby", "code": "def warmup_from_files(version = nil, cache_path = nil)\n t0 = Time.now\n Tml.logger = Logger.new(STDOUT)\n\n Tml.logger.debug('Starting cache warmup from local files...')\n version ||= Tml.config.cache[:version]\n cache_path ||= Tml.config.cache[:path]\n cache_path = \"#{cache_path}/#{version}\"\n\n Tml.cache.version.set(version.to_s)\n Tml.logger.debug(\"Warming Up Version: #{Tml.cache.version}\")\n\n application = JSON.parse(File.read(\"#{cache_path}/application.json\"))\n Tml.cache.store(Tml::Application.cache_key, application)\n\n sources = JSON.parse(File.read(\"#{cache_path}/sources.json\"))\n\n application['languages'].each do |lang|\n locale = lang['locale']\n\n language = JSON.parse(File.read(\"#{cache_path}/#{locale}/language.json\"))\n Tml.cache.store(Tml::Language.cache_key(locale), language)\n\n sources.each do |src|\n source = JSON.parse(File.read(\"#{cache_path}/#{locale}/sources/#{src}.json\"))\n Tml.cache.store(Tml::Source.cache_key(locale, src), source)\n end\n end\n\n t1 = Time.now\n Tml.logger.debug(\"Cache warmup took #{t1-t0}s\")\n end", "code_tokens": ["def", "warmup_from_files", "(", "version", "=", "nil", ",", "cache_path", "=", "nil", ")", "t0", "=", "Time", ".", "now", "Tml", ".", "logger", "=", "Logger", ".", "new", "(", "STDOUT", ")", "Tml", ".", "logger", ".", "debug", "(", "'Starting cache warmup from local files...'", ")", "version", "||=", "Tml", ".", "config", ".", "cache", "[", ":version", "]", "cache_path", "||=", "Tml", ".", "config", ".", "cache", "[", ":path", "]", "cache_path", "=", "\"#{cache_path}/#{version}\"", "Tml", ".", "cache", ".", "version", ".", "set", "(", "version", ".", "to_s", ")", "Tml", ".", "logger", ".", "debug", "(", "\"Warming Up Version: #{Tml.cache.version}\"", ")", "application", "=", "JSON", ".", "parse", "(", "File", ".", "read", "(", "\"#{cache_path}/application.json\"", ")", ")", "Tml", ".", "cache", ".", "store", "(", "Tml", "::", "Application", ".", "cache_key", ",", "application", ")", "sources", "=", "JSON", ".", "parse", "(", "File", ".", "read", "(", "\"#{cache_path}/sources.json\"", ")", ")", "application", "[", "'languages'", "]", ".", "each", "do", "|", "lang", "|", "locale", "=", "lang", "[", "'locale'", "]", "language", "=", "JSON", ".", "parse", "(", "File", ".", "read", "(", "\"#{cache_path}/#{locale}/language.json\"", ")", ")", "Tml", ".", "cache", ".", "store", "(", "Tml", "::", "Language", ".", "cache_key", "(", "locale", ")", ",", "language", ")", "sources", ".", "each", "do", "|", "src", "|", "source", "=", "JSON", ".", "parse", "(", "File", ".", "read", "(", "\"#{cache_path}/#{locale}/sources/#{src}.json\"", ")", ")", "Tml", ".", "cache", ".", "store", "(", "Tml", "::", "Source", ".", "cache_key", "(", "locale", ",", "src", ")", ",", "source", ")", "end", "end", "t1", "=", "Time", ".", "now", "Tml", ".", "logger", ".", "debug", "(", "\"Cache warmup took #{t1-t0}s\"", ")", "end"], "docstring": "Warms up cache from local files", "docstring_tokens": ["Warms", "up", "cache", "from", "local", "files"], "sha": "e82b8768b36a2d2d4eb1493205784555151e741e", "url": "https://github.com/translationexchange/tml-ruby/blob/e82b8768b36a2d2d4eb1493205784555151e741e/lib/tml/cache.rb#L165-L196", "partition": "test"} {"repo": "translationexchange/tml-ruby", "path": "lib/tml/cache.rb", "func_name": "Tml.Cache.warmup_from_cdn", "original_string": "def warmup_from_cdn(version = nil)\n t0 = Time.now\n Tml.logger = Logger.new(STDOUT)\n\n Tml.logger.debug('Starting cache warmup from CDN...')\n app = Tml::Application.new(key: Tml.config.application[:key], cdn_host: Tml.config.application[:cdn_host])\n extract_version(app, version)\n\n Tml.logger.debug(\"Warming Up Version: #{Tml.cache.version}\")\n\n application = app.api_client.get_from_cdn('application', {t: Time.now.to_i})\n Tml.cache.store(Tml::Application.cache_key, application)\n\n sources = app.api_client.get_from_cdn('sources', {t: Time.now.to_i}, {uncompressed: true})\n\n application['languages'].each do |lang|\n locale = lang['locale']\n language = app.api_client.get_from_cdn(\"#{locale}/language\", {t: Time.now.to_i})\n Tml.cache.store(Tml::Language.cache_key(locale), language)\n\n sources.each do |src|\n source = app.api_client.get_from_cdn(\"#{locale}/sources/#{src}\", {t: Time.now.to_i})\n Tml.cache.store(Tml::Source.cache_key(locale, src), source)\n end\n end\n\n t1 = Time.now\n Tml.logger.debug(\"Cache warmup took #{t1-t0}s\")\n end", "language": "ruby", "code": "def warmup_from_cdn(version = nil)\n t0 = Time.now\n Tml.logger = Logger.new(STDOUT)\n\n Tml.logger.debug('Starting cache warmup from CDN...')\n app = Tml::Application.new(key: Tml.config.application[:key], cdn_host: Tml.config.application[:cdn_host])\n extract_version(app, version)\n\n Tml.logger.debug(\"Warming Up Version: #{Tml.cache.version}\")\n\n application = app.api_client.get_from_cdn('application', {t: Time.now.to_i})\n Tml.cache.store(Tml::Application.cache_key, application)\n\n sources = app.api_client.get_from_cdn('sources', {t: Time.now.to_i}, {uncompressed: true})\n\n application['languages'].each do |lang|\n locale = lang['locale']\n language = app.api_client.get_from_cdn(\"#{locale}/language\", {t: Time.now.to_i})\n Tml.cache.store(Tml::Language.cache_key(locale), language)\n\n sources.each do |src|\n source = app.api_client.get_from_cdn(\"#{locale}/sources/#{src}\", {t: Time.now.to_i})\n Tml.cache.store(Tml::Source.cache_key(locale, src), source)\n end\n end\n\n t1 = Time.now\n Tml.logger.debug(\"Cache warmup took #{t1-t0}s\")\n end", "code_tokens": ["def", "warmup_from_cdn", "(", "version", "=", "nil", ")", "t0", "=", "Time", ".", "now", "Tml", ".", "logger", "=", "Logger", ".", "new", "(", "STDOUT", ")", "Tml", ".", "logger", ".", "debug", "(", "'Starting cache warmup from CDN...'", ")", "app", "=", "Tml", "::", "Application", ".", "new", "(", "key", ":", "Tml", ".", "config", ".", "application", "[", ":key", "]", ",", "cdn_host", ":", "Tml", ".", "config", ".", "application", "[", ":cdn_host", "]", ")", "extract_version", "(", "app", ",", "version", ")", "Tml", ".", "logger", ".", "debug", "(", "\"Warming Up Version: #{Tml.cache.version}\"", ")", "application", "=", "app", ".", "api_client", ".", "get_from_cdn", "(", "'application'", ",", "{", "t", ":", "Time", ".", "now", ".", "to_i", "}", ")", "Tml", ".", "cache", ".", "store", "(", "Tml", "::", "Application", ".", "cache_key", ",", "application", ")", "sources", "=", "app", ".", "api_client", ".", "get_from_cdn", "(", "'sources'", ",", "{", "t", ":", "Time", ".", "now", ".", "to_i", "}", ",", "{", "uncompressed", ":", "true", "}", ")", "application", "[", "'languages'", "]", ".", "each", "do", "|", "lang", "|", "locale", "=", "lang", "[", "'locale'", "]", "language", "=", "app", ".", "api_client", ".", "get_from_cdn", "(", "\"#{locale}/language\"", ",", "{", "t", ":", "Time", ".", "now", ".", "to_i", "}", ")", "Tml", ".", "cache", ".", "store", "(", "Tml", "::", "Language", ".", "cache_key", "(", "locale", ")", ",", "language", ")", "sources", ".", "each", "do", "|", "src", "|", "source", "=", "app", ".", "api_client", ".", "get_from_cdn", "(", "\"#{locale}/sources/#{src}\"", ",", "{", "t", ":", "Time", ".", "now", ".", "to_i", "}", ")", "Tml", ".", "cache", ".", "store", "(", "Tml", "::", "Source", ".", "cache_key", "(", "locale", ",", "src", ")", ",", "source", ")", "end", "end", "t1", "=", "Time", ".", "now", "Tml", ".", "logger", ".", "debug", "(", "\"Cache warmup took #{t1-t0}s\"", ")", "end"], "docstring": "Warms up cache from CDN", "docstring_tokens": ["Warms", "up", "cache", "from", "CDN"], "sha": "e82b8768b36a2d2d4eb1493205784555151e741e", "url": "https://github.com/translationexchange/tml-ruby/blob/e82b8768b36a2d2d4eb1493205784555151e741e/lib/tml/cache.rb#L199-L227", "partition": "test"} {"repo": "translationexchange/tml-ruby", "path": "lib/tml/cache.rb", "func_name": "Tml.Cache.default_cache_path", "original_string": "def default_cache_path\n @cache_path ||= begin\n path = Tml.config.cache[:path]\n path ||= 'config/tml'\n FileUtils.mkdir_p(path)\n FileUtils.chmod(0777, path)\n path\n end\n end", "language": "ruby", "code": "def default_cache_path\n @cache_path ||= begin\n path = Tml.config.cache[:path]\n path ||= 'config/tml'\n FileUtils.mkdir_p(path)\n FileUtils.chmod(0777, path)\n path\n end\n end", "code_tokens": ["def", "default_cache_path", "@cache_path", "||=", "begin", "path", "=", "Tml", ".", "config", ".", "cache", "[", ":path", "]", "path", "||=", "'config/tml'", "FileUtils", ".", "mkdir_p", "(", "path", ")", "FileUtils", ".", "chmod", "(", "0777", ",", "path", ")", "path", "end", "end"], "docstring": "default cache path", "docstring_tokens": ["default", "cache", "path"], "sha": "e82b8768b36a2d2d4eb1493205784555151e741e", "url": "https://github.com/translationexchange/tml-ruby/blob/e82b8768b36a2d2d4eb1493205784555151e741e/lib/tml/cache.rb#L230-L238", "partition": "test"} {"repo": "translationexchange/tml-ruby", "path": "lib/tml/cache.rb", "func_name": "Tml.Cache.download", "original_string": "def download(cache_path = default_cache_path, version = nil)\n t0 = Time.now\n Tml.logger = Logger.new(STDOUT)\n\n Tml.logger.debug('Starting cache download...')\n app = Tml::Application.new(key: Tml.config.application[:key], cdn_host: Tml.config.application[:cdn_host])\n extract_version(app, version)\n\n Tml.logger.debug(\"Downloading Version: #{Tml.cache.version}\")\n\n archive_name = \"#{Tml.cache.version}.tar.gz\"\n path = \"#{cache_path}/#{archive_name}\"\n url = \"#{app.cdn_host}/#{Tml.config.application[:key]}/#{archive_name}\"\n\n Tml.logger.debug(\"Downloading cache file: #{url}\")\n open(path, 'wb') do |file|\n file << open(url).read\n end\n\n Tml.logger.debug('Extracting cache file...')\n version_path = \"#{cache_path}/#{Tml.cache.version}\"\n Tml::Utils.untar(Tml::Utils.ungzip(File.new(path)), version_path)\n Tml.logger.debug(\"Cache has been stored in #{version_path}\")\n\n File.unlink(path)\n\n begin\n current_path = 'current'\n FileUtils.chdir(cache_path)\n FileUtils.rm(current_path) if File.exist?(current_path)\n FileUtils.ln_s(Tml.cache.version.to_s, current_path)\n Tml.logger.debug(\"The new version #{Tml.cache.version} has been marked as current\")\n rescue Exception => ex\n Tml.logger.debug(\"Could not generate current symlink to the cache path: #{ex.message}\")\n end\n\n t1 = Time.now\n Tml.logger.debug(\"Cache download took #{t1-t0}s\")\n end", "language": "ruby", "code": "def download(cache_path = default_cache_path, version = nil)\n t0 = Time.now\n Tml.logger = Logger.new(STDOUT)\n\n Tml.logger.debug('Starting cache download...')\n app = Tml::Application.new(key: Tml.config.application[:key], cdn_host: Tml.config.application[:cdn_host])\n extract_version(app, version)\n\n Tml.logger.debug(\"Downloading Version: #{Tml.cache.version}\")\n\n archive_name = \"#{Tml.cache.version}.tar.gz\"\n path = \"#{cache_path}/#{archive_name}\"\n url = \"#{app.cdn_host}/#{Tml.config.application[:key]}/#{archive_name}\"\n\n Tml.logger.debug(\"Downloading cache file: #{url}\")\n open(path, 'wb') do |file|\n file << open(url).read\n end\n\n Tml.logger.debug('Extracting cache file...')\n version_path = \"#{cache_path}/#{Tml.cache.version}\"\n Tml::Utils.untar(Tml::Utils.ungzip(File.new(path)), version_path)\n Tml.logger.debug(\"Cache has been stored in #{version_path}\")\n\n File.unlink(path)\n\n begin\n current_path = 'current'\n FileUtils.chdir(cache_path)\n FileUtils.rm(current_path) if File.exist?(current_path)\n FileUtils.ln_s(Tml.cache.version.to_s, current_path)\n Tml.logger.debug(\"The new version #{Tml.cache.version} has been marked as current\")\n rescue Exception => ex\n Tml.logger.debug(\"Could not generate current symlink to the cache path: #{ex.message}\")\n end\n\n t1 = Time.now\n Tml.logger.debug(\"Cache download took #{t1-t0}s\")\n end", "code_tokens": ["def", "download", "(", "cache_path", "=", "default_cache_path", ",", "version", "=", "nil", ")", "t0", "=", "Time", ".", "now", "Tml", ".", "logger", "=", "Logger", ".", "new", "(", "STDOUT", ")", "Tml", ".", "logger", ".", "debug", "(", "'Starting cache download...'", ")", "app", "=", "Tml", "::", "Application", ".", "new", "(", "key", ":", "Tml", ".", "config", ".", "application", "[", ":key", "]", ",", "cdn_host", ":", "Tml", ".", "config", ".", "application", "[", ":cdn_host", "]", ")", "extract_version", "(", "app", ",", "version", ")", "Tml", ".", "logger", ".", "debug", "(", "\"Downloading Version: #{Tml.cache.version}\"", ")", "archive_name", "=", "\"#{Tml.cache.version}.tar.gz\"", "path", "=", "\"#{cache_path}/#{archive_name}\"", "url", "=", "\"#{app.cdn_host}/#{Tml.config.application[:key]}/#{archive_name}\"", "Tml", ".", "logger", ".", "debug", "(", "\"Downloading cache file: #{url}\"", ")", "open", "(", "path", ",", "'wb'", ")", "do", "|", "file", "|", "file", "<<", "open", "(", "url", ")", ".", "read", "end", "Tml", ".", "logger", ".", "debug", "(", "'Extracting cache file...'", ")", "version_path", "=", "\"#{cache_path}/#{Tml.cache.version}\"", "Tml", "::", "Utils", ".", "untar", "(", "Tml", "::", "Utils", ".", "ungzip", "(", "File", ".", "new", "(", "path", ")", ")", ",", "version_path", ")", "Tml", ".", "logger", ".", "debug", "(", "\"Cache has been stored in #{version_path}\"", ")", "File", ".", "unlink", "(", "path", ")", "begin", "current_path", "=", "'current'", "FileUtils", ".", "chdir", "(", "cache_path", ")", "FileUtils", ".", "rm", "(", "current_path", ")", "if", "File", ".", "exist?", "(", "current_path", ")", "FileUtils", ".", "ln_s", "(", "Tml", ".", "cache", ".", "version", ".", "to_s", ",", "current_path", ")", "Tml", ".", "logger", ".", "debug", "(", "\"The new version #{Tml.cache.version} has been marked as current\"", ")", "rescue", "Exception", "=>", "ex", "Tml", ".", "logger", ".", "debug", "(", "\"Could not generate current symlink to the cache path: #{ex.message}\"", ")", "end", "t1", "=", "Time", ".", "now", "Tml", ".", "logger", ".", "debug", "(", "\"Cache download took #{t1-t0}s\"", ")", "end"], "docstring": "downloads cache from the CDN", "docstring_tokens": ["downloads", "cache", "from", "the", "CDN"], "sha": "e82b8768b36a2d2d4eb1493205784555151e741e", "url": "https://github.com/translationexchange/tml-ruby/blob/e82b8768b36a2d2d4eb1493205784555151e741e/lib/tml/cache.rb#L241-L279", "partition": "test"} {"repo": "kmalakoff/couchwatcher-gem", "path": "lib/couchwatcher/database_listener.rb", "func_name": "CouchWatcher.DatabaseListener.say", "original_string": "def say(message, color=nil)\n @shell ||= Thor::Shell::Basic.new\n @shell.say message, color\n end", "language": "ruby", "code": "def say(message, color=nil)\n @shell ||= Thor::Shell::Basic.new\n @shell.say message, color\n end", "code_tokens": ["def", "say", "(", "message", ",", "color", "=", "nil", ")", "@shell", "||=", "Thor", "::", "Shell", "::", "Basic", ".", "new", "@shell", ".", "say", "message", ",", "color", "end"], "docstring": "shortcut to say", "docstring_tokens": ["shortcut", "to", "say"], "sha": "50e83d2a7ad855b3a34d4afdc094f896272930e2", "url": "https://github.com/kmalakoff/couchwatcher-gem/blob/50e83d2a7ad855b3a34d4afdc094f896272930e2/lib/couchwatcher/database_listener.rb#L9-L12", "partition": "test"} {"repo": "translationexchange/tml-ruby", "path": "lib/tml/cache_version.rb", "func_name": "Tml.CacheVersion.validate_cache_version", "original_string": "def validate_cache_version(version)\n # if cache version is hardcoded, use it\n if Tml.config.cache[:version]\n return Tml.config.cache[:version]\n end\n\n return version unless version.is_a?(Hash)\n return 'undefined' unless version['t'].is_a?(Numeric)\n return version['version'] if cache.read_only?\n\n # if version check interval is disabled, don't try to check for the new\n # cache version on the CDN\n if version_check_interval == -1\n Tml.logger.debug('Cache version check is disabled')\n return version['version']\n end\n\n expires_at = version['t'] + version_check_interval\n if expires_at < Time.now.to_i\n Tml.logger.debug('Cache version is outdated, needs refresh')\n return 'undefined'\n end\n\n delta = expires_at - Time.now.to_i\n Tml.logger.debug(\"Cache version is up to date, expires in #{delta}s\")\n version['version']\n end", "language": "ruby", "code": "def validate_cache_version(version)\n # if cache version is hardcoded, use it\n if Tml.config.cache[:version]\n return Tml.config.cache[:version]\n end\n\n return version unless version.is_a?(Hash)\n return 'undefined' unless version['t'].is_a?(Numeric)\n return version['version'] if cache.read_only?\n\n # if version check interval is disabled, don't try to check for the new\n # cache version on the CDN\n if version_check_interval == -1\n Tml.logger.debug('Cache version check is disabled')\n return version['version']\n end\n\n expires_at = version['t'] + version_check_interval\n if expires_at < Time.now.to_i\n Tml.logger.debug('Cache version is outdated, needs refresh')\n return 'undefined'\n end\n\n delta = expires_at - Time.now.to_i\n Tml.logger.debug(\"Cache version is up to date, expires in #{delta}s\")\n version['version']\n end", "code_tokens": ["def", "validate_cache_version", "(", "version", ")", "# if cache version is hardcoded, use it", "if", "Tml", ".", "config", ".", "cache", "[", ":version", "]", "return", "Tml", ".", "config", ".", "cache", "[", ":version", "]", "end", "return", "version", "unless", "version", ".", "is_a?", "(", "Hash", ")", "return", "'undefined'", "unless", "version", "[", "'t'", "]", ".", "is_a?", "(", "Numeric", ")", "return", "version", "[", "'version'", "]", "if", "cache", ".", "read_only?", "# if version check interval is disabled, don't try to check for the new", "# cache version on the CDN", "if", "version_check_interval", "==", "-", "1", "Tml", ".", "logger", ".", "debug", "(", "'Cache version check is disabled'", ")", "return", "version", "[", "'version'", "]", "end", "expires_at", "=", "version", "[", "'t'", "]", "+", "version_check_interval", "if", "expires_at", "<", "Time", ".", "now", ".", "to_i", "Tml", ".", "logger", ".", "debug", "(", "'Cache version is outdated, needs refresh'", ")", "return", "'undefined'", "end", "delta", "=", "expires_at", "-", "Time", ".", "now", ".", "to_i", "Tml", ".", "logger", ".", "debug", "(", "\"Cache version is up to date, expires in #{delta}s\"", ")", "version", "[", "'version'", "]", "end"], "docstring": "validate that current cache version hasn't expired", "docstring_tokens": ["validate", "that", "current", "cache", "version", "hasn", "t", "expired"], "sha": "e82b8768b36a2d2d4eb1493205784555151e741e", "url": "https://github.com/translationexchange/tml-ruby/blob/e82b8768b36a2d2d4eb1493205784555151e741e/lib/tml/cache_version.rb#L63-L89", "partition": "test"} {"repo": "translationexchange/tml-ruby", "path": "lib/tml/cache_version.rb", "func_name": "Tml.CacheVersion.fetch", "original_string": "def fetch\n self.version = begin\n ver = cache.fetch(CACHE_VERSION_KEY) do\n {'version' => Tml.config.cache[:version] || 'undefined', 't' => cache_timestamp}\n end\n validate_cache_version(ver)\n end\n end", "language": "ruby", "code": "def fetch\n self.version = begin\n ver = cache.fetch(CACHE_VERSION_KEY) do\n {'version' => Tml.config.cache[:version] || 'undefined', 't' => cache_timestamp}\n end\n validate_cache_version(ver)\n end\n end", "code_tokens": ["def", "fetch", "self", ".", "version", "=", "begin", "ver", "=", "cache", ".", "fetch", "(", "CACHE_VERSION_KEY", ")", "do", "{", "'version'", "=>", "Tml", ".", "config", ".", "cache", "[", ":version", "]", "||", "'undefined'", ",", "'t'", "=>", "cache_timestamp", "}", "end", "validate_cache_version", "(", "ver", ")", "end", "end"], "docstring": "fetches the version from the cache", "docstring_tokens": ["fetches", "the", "version", "from", "the", "cache"], "sha": "e82b8768b36a2d2d4eb1493205784555151e741e", "url": "https://github.com/translationexchange/tml-ruby/blob/e82b8768b36a2d2d4eb1493205784555151e741e/lib/tml/cache_version.rb#L92-L99", "partition": "test"} {"repo": "ruby-bdb/sbdb", "path": "lib/sbdb/environment.rb", "func_name": "SBDB.Environment.[]", "original_string": "def [] file, *ps, &exe\n\t\t\topts = ::Hash === ps.last ? ps.pop : {}\n\t\t\topts[:env] = self\n\t\t\tname, type, flg = ps[0] || opts[:name], ps[1] || opts[:type], ps[2] || opts[:flags]\n\t\t\tps.push opts\n\t\t\t@dbs[ [file, name, flg | CREATE]] ||= (type || SBDB::Unknown).new file, *ps, &exe\n\t\tend", "language": "ruby", "code": "def [] file, *ps, &exe\n\t\t\topts = ::Hash === ps.last ? ps.pop : {}\n\t\t\topts[:env] = self\n\t\t\tname, type, flg = ps[0] || opts[:name], ps[1] || opts[:type], ps[2] || opts[:flags]\n\t\t\tps.push opts\n\t\t\t@dbs[ [file, name, flg | CREATE]] ||= (type || SBDB::Unknown).new file, *ps, &exe\n\t\tend", "code_tokens": ["def", "[]", "file", ",", "*", "ps", ",", "&", "exe", "opts", "=", "::", "Hash", "===", "ps", ".", "last", "?", "ps", ".", "pop", ":", "{", "}", "opts", "[", ":env", "]", "=", "self", "name", ",", "type", ",", "flg", "=", "ps", "[", "0", "]", "||", "opts", "[", ":name", "]", ",", "ps", "[", "1", "]", "||", "opts", "[", ":type", "]", ",", "ps", "[", "2", "]", "||", "opts", "[", ":flags", "]", "ps", ".", "push", "opts", "@dbs", "[", "[", "file", ",", "name", ",", "flg", "|", "CREATE", "]", "]", "||=", "(", "type", "||", "SBDB", "::", "Unknown", ")", ".", "new", "file", ",", "ps", ",", "exe", "end"], "docstring": "Returns the DB like open, but if it's already opened,\n it returns the old instance.\n If you use this, never use close. It's possible somebody else use it too.\n The Databases, which are opened, will close, if the Environment will close.", "docstring_tokens": ["Returns", "the", "DB", "like", "open", "but", "if", "it", "s", "already", "opened", "it", "returns", "the", "old", "instance", ".", "If", "you", "use", "this", "never", "use", "close", ".", "It", "s", "possible", "somebody", "else", "use", "it", "too", ".", "The", "Databases", "which", "are", "opened", "will", "close", "if", "the", "Environment", "will", "close", "."], "sha": "50e2fbe843d63f48b4919c9a768771926a3171cd", "url": "https://github.com/ruby-bdb/sbdb/blob/50e2fbe843d63f48b4919c9a768771926a3171cd/lib/sbdb/environment.rb#L107-L113", "partition": "test"} {"repo": "ysbaddaden/janus", "path": "lib/janus/strategies.rb", "func_name": "Janus.Strategies.run_strategies", "original_string": "def run_strategies(scope)\n Janus::Manager.strategies.each { |name| break if run_strategy(name, scope) }\n end", "language": "ruby", "code": "def run_strategies(scope)\n Janus::Manager.strategies.each { |name| break if run_strategy(name, scope) }\n end", "code_tokens": ["def", "run_strategies", "(", "scope", ")", "Janus", "::", "Manager", ".", "strategies", ".", "each", "{", "|", "name", "|", "break", "if", "run_strategy", "(", "name", ",", "scope", ")", "}", "end"], "docstring": "Runs authentication strategies to log a user in.", "docstring_tokens": ["Runs", "authentication", "strategies", "to", "log", "a", "user", "in", "."], "sha": "a4d1f9705b48e765377b7296765ffeff8d35f771", "url": "https://github.com/ysbaddaden/janus/blob/a4d1f9705b48e765377b7296765ffeff8d35f771/lib/janus/strategies.rb#L6-L8", "partition": "test"} {"repo": "ysbaddaden/janus", "path": "lib/janus/strategies.rb", "func_name": "Janus.Strategies.run_strategy", "original_string": "def run_strategy(name, scope)\n strategy = \"Janus::Strategies::#{name.to_s.camelize}\".constantize.new(scope, self)\n\n if strategy.valid?\n strategy.authenticate!\n\n if strategy.success?\n send(strategy.auth_method, strategy.user, :scope => scope)\n Janus::Manager.run_callbacks(:authenticate, strategy.user, self, :scope => scope)\n end\n end\n\n strategy.success?\n end", "language": "ruby", "code": "def run_strategy(name, scope)\n strategy = \"Janus::Strategies::#{name.to_s.camelize}\".constantize.new(scope, self)\n\n if strategy.valid?\n strategy.authenticate!\n\n if strategy.success?\n send(strategy.auth_method, strategy.user, :scope => scope)\n Janus::Manager.run_callbacks(:authenticate, strategy.user, self, :scope => scope)\n end\n end\n\n strategy.success?\n end", "code_tokens": ["def", "run_strategy", "(", "name", ",", "scope", ")", "strategy", "=", "\"Janus::Strategies::#{name.to_s.camelize}\"", ".", "constantize", ".", "new", "(", "scope", ",", "self", ")", "if", "strategy", ".", "valid?", "strategy", ".", "authenticate!", "if", "strategy", ".", "success?", "send", "(", "strategy", ".", "auth_method", ",", "strategy", ".", "user", ",", ":scope", "=>", "scope", ")", "Janus", "::", "Manager", ".", "run_callbacks", "(", ":authenticate", ",", "strategy", ".", "user", ",", "self", ",", ":scope", "=>", "scope", ")", "end", "end", "strategy", ".", "success?", "end"], "docstring": "Runs a given strategy and returns true if it succeeded.", "docstring_tokens": ["Runs", "a", "given", "strategy", "and", "returns", "true", "if", "it", "succeeded", "."], "sha": "a4d1f9705b48e765377b7296765ffeff8d35f771", "url": "https://github.com/ysbaddaden/janus/blob/a4d1f9705b48e765377b7296765ffeff8d35f771/lib/janus/strategies.rb#L11-L24", "partition": "test"} {"repo": "sue445/paraduct", "path": "lib/paraduct/runner.rb", "func_name": "Paraduct.Runner.perform", "original_string": "def perform(script)\n export_variables = @params.reverse_merge(\"PARADUCT_JOB_ID\" => @job_id, \"PARADUCT_JOB_NAME\" => job_name)\n variable_string = export_variables.map { |key, value| %(export #{key}=\"#{value}\";) }.join(\" \")\n\n Array.wrap(script).inject(\"\") do |stdout, command|\n stdout << run_command(\"#{variable_string} #{command}\")\n stdout\n end\n end", "language": "ruby", "code": "def perform(script)\n export_variables = @params.reverse_merge(\"PARADUCT_JOB_ID\" => @job_id, \"PARADUCT_JOB_NAME\" => job_name)\n variable_string = export_variables.map { |key, value| %(export #{key}=\"#{value}\";) }.join(\" \")\n\n Array.wrap(script).inject(\"\") do |stdout, command|\n stdout << run_command(\"#{variable_string} #{command}\")\n stdout\n end\n end", "code_tokens": ["def", "perform", "(", "script", ")", "export_variables", "=", "@params", ".", "reverse_merge", "(", "\"PARADUCT_JOB_ID\"", "=>", "@job_id", ",", "\"PARADUCT_JOB_NAME\"", "=>", "job_name", ")", "variable_string", "=", "export_variables", ".", "map", "{", "|", "key", ",", "value", "|", "%(export #{key}=\"#{value}\";)", "}", ".", "join", "(", "\" \"", ")", "Array", ".", "wrap", "(", "script", ")", ".", "inject", "(", "\"\"", ")", "do", "|", "stdout", ",", "command", "|", "stdout", "<<", "run_command", "(", "\"#{variable_string} #{command}\"", ")", "stdout", "end", "end"], "docstring": "run script with params\n @param script [String, Array] script file, script(s)\n @return [String] stdout\n @raise [Paraduct::Errors::ProcessError] command exited error status", "docstring_tokens": ["run", "script", "with", "params"], "sha": "4d42641a7dbe1d801304ea41131699392d6c5884", "url": "https://github.com/sue445/paraduct/blob/4d42641a7dbe1d801304ea41131699392d6c5884/lib/paraduct/runner.rb#L26-L34", "partition": "test"} {"repo": "ab/sixword", "path": "lib/sixword/cli.rb", "func_name": "Sixword.CLI.print_hex", "original_string": "def print_hex(data, chunk_index, cols=80)\n case hex_style\n when 'lower', 'lowercase'\n # encode to lowercase hex with no newlines\n print Sixword::Hex.encode(data)\n when 'finger', 'fingerprint'\n # encode to GPG fingerprint like hex with newlines\n newlines_every = cols / 5\n if chunk_index != 0\n if chunk_index % newlines_every == 0\n print \"\\n\"\n else\n print ' '\n end\n end\n print Sixword::Hex.encode_fingerprint(data)\n when 'colon', 'colons'\n # encode to SSL/SSH fingerprint like hex with colons\n print ':' unless chunk_index == 0\n print Sixword::Hex.encode_colons(data)\n end\n end", "language": "ruby", "code": "def print_hex(data, chunk_index, cols=80)\n case hex_style\n when 'lower', 'lowercase'\n # encode to lowercase hex with no newlines\n print Sixword::Hex.encode(data)\n when 'finger', 'fingerprint'\n # encode to GPG fingerprint like hex with newlines\n newlines_every = cols / 5\n if chunk_index != 0\n if chunk_index % newlines_every == 0\n print \"\\n\"\n else\n print ' '\n end\n end\n print Sixword::Hex.encode_fingerprint(data)\n when 'colon', 'colons'\n # encode to SSL/SSH fingerprint like hex with colons\n print ':' unless chunk_index == 0\n print Sixword::Hex.encode_colons(data)\n end\n end", "code_tokens": ["def", "print_hex", "(", "data", ",", "chunk_index", ",", "cols", "=", "80", ")", "case", "hex_style", "when", "'lower'", ",", "'lowercase'", "# encode to lowercase hex with no newlines", "print", "Sixword", "::", "Hex", ".", "encode", "(", "data", ")", "when", "'finger'", ",", "'fingerprint'", "# encode to GPG fingerprint like hex with newlines", "newlines_every", "=", "cols", "/", "5", "if", "chunk_index", "!=", "0", "if", "chunk_index", "%", "newlines_every", "==", "0", "print", "\"\\n\"", "else", "print", "' '", "end", "end", "print", "Sixword", "::", "Hex", ".", "encode_fingerprint", "(", "data", ")", "when", "'colon'", ",", "'colons'", "# encode to SSL/SSH fingerprint like hex with colons", "print", "':'", "unless", "chunk_index", "==", "0", "print", "Sixword", "::", "Hex", ".", "encode_colons", "(", "data", ")", "end", "end"], "docstring": "Format data as hex in various styles.", "docstring_tokens": ["Format", "data", "as", "hex", "in", "various", "styles", "."], "sha": "4d7b831923a92798e44bbd1edba73fff285bd3db", "url": "https://github.com/ab/sixword/blob/4d7b831923a92798e44bbd1edba73fff285bd3db/lib/sixword/cli.rb#L72-L93", "partition": "test"} {"repo": "ab/sixword", "path": "lib/sixword/cli.rb", "func_name": "Sixword.CLI.read_input_by_6_words", "original_string": "def read_input_by_6_words\n word_arr = []\n\n while true\n line = stream.gets\n if line.nil?\n break # EOF\n end\n\n line.scan(/\\S+/) do |word|\n word_arr << word\n\n # return the array if we have accumulated 6 words\n if word_arr.length == 6\n yield word_arr\n word_arr.clear\n end\n end\n end\n\n # yield whatever we have left, if anything\n if !word_arr.empty?\n yield word_arr\n end\n end", "language": "ruby", "code": "def read_input_by_6_words\n word_arr = []\n\n while true\n line = stream.gets\n if line.nil?\n break # EOF\n end\n\n line.scan(/\\S+/) do |word|\n word_arr << word\n\n # return the array if we have accumulated 6 words\n if word_arr.length == 6\n yield word_arr\n word_arr.clear\n end\n end\n end\n\n # yield whatever we have left, if anything\n if !word_arr.empty?\n yield word_arr\n end\n end", "code_tokens": ["def", "read_input_by_6_words", "word_arr", "=", "[", "]", "while", "true", "line", "=", "stream", ".", "gets", "if", "line", ".", "nil?", "break", "# EOF", "end", "line", ".", "scan", "(", "/", "\\S", "/", ")", "do", "|", "word", "|", "word_arr", "<<", "word", "# return the array if we have accumulated 6 words", "if", "word_arr", ".", "length", "==", "6", "yield", "word_arr", "word_arr", ".", "clear", "end", "end", "end", "# yield whatever we have left, if anything", "if", "!", "word_arr", ".", "empty?", "yield", "word_arr", "end", "end"], "docstring": "Yield data 6 words at a time until EOF", "docstring_tokens": ["Yield", "data", "6", "words", "at", "a", "time", "until", "EOF"], "sha": "4d7b831923a92798e44bbd1edba73fff285bd3db", "url": "https://github.com/ab/sixword/blob/4d7b831923a92798e44bbd1edba73fff285bd3db/lib/sixword/cli.rb#L187-L211", "partition": "test"} {"repo": "d11wtq/oedipus", "path": "lib/oedipus/query_builder.rb", "func_name": "Oedipus.QueryBuilder.select", "original_string": "def select(query, filters)\n where, *bind_values = conditions(query, filters)\n [\n [\n from(filters),\n where,\n order_by(filters),\n limits(filters)\n ].join(\" \"),\n *bind_values\n ]\n end", "language": "ruby", "code": "def select(query, filters)\n where, *bind_values = conditions(query, filters)\n [\n [\n from(filters),\n where,\n order_by(filters),\n limits(filters)\n ].join(\" \"),\n *bind_values\n ]\n end", "code_tokens": ["def", "select", "(", "query", ",", "filters", ")", "where", ",", "*", "bind_values", "=", "conditions", "(", "query", ",", "filters", ")", "[", "[", "from", "(", "filters", ")", ",", "where", ",", "order_by", "(", "filters", ")", ",", "limits", "(", "filters", ")", "]", ".", "join", "(", "\" \"", ")", ",", "bind_values", "]", "end"], "docstring": "Initialize a new QueryBuilder for +index_name+.\n\n @param [Symbol] index_name\n the name of the index being queried\n Build a SphinxQL query for the fulltext search +query+ and filters in +filters+.\n\n @param [String] query\n the fulltext query to execute (may be empty)\n\n @param [Hash] filters\n additional attribute filters and other options\n\n @return [String]\n a SphinxQL query", "docstring_tokens": ["Initialize", "a", "new", "QueryBuilder", "for", "+", "index_name", "+", "."], "sha": "37af27d0e5cd7d23896fd0d8f61134a962fc290f", "url": "https://github.com/d11wtq/oedipus/blob/37af27d0e5cd7d23896fd0d8f61134a962fc290f/lib/oedipus/query_builder.rb#L31-L42", "partition": "test"} {"repo": "d11wtq/oedipus", "path": "lib/oedipus/query_builder.rb", "func_name": "Oedipus.QueryBuilder.update", "original_string": "def update(id, attributes)\n set_attrs, *bind_values = update_attributes(attributes)\n [\n [\n \"UPDATE #{@index_name} SET\",\n set_attrs,\n \"WHERE id = ?\"\n ].join(\" \"),\n *bind_values.push(id)\n ]\n end", "language": "ruby", "code": "def update(id, attributes)\n set_attrs, *bind_values = update_attributes(attributes)\n [\n [\n \"UPDATE #{@index_name} SET\",\n set_attrs,\n \"WHERE id = ?\"\n ].join(\" \"),\n *bind_values.push(id)\n ]\n end", "code_tokens": ["def", "update", "(", "id", ",", "attributes", ")", "set_attrs", ",", "*", "bind_values", "=", "update_attributes", "(", "attributes", ")", "[", "[", "\"UPDATE #{@index_name} SET\"", ",", "set_attrs", ",", "\"WHERE id = ?\"", "]", ".", "join", "(", "\" \"", ")", ",", "bind_values", ".", "push", "(", "id", ")", "]", "end"], "docstring": "Build a SphinxQL query to update the record identified by +id+ with the given attributes.\n\n @param [Fixnum] id\n the unique ID of the document to update\n\n @param [Hash] attributes\n a Hash of attributes\n\n @return [String]\n the SphinxQL to update the record", "docstring_tokens": ["Build", "a", "SphinxQL", "query", "to", "update", "the", "record", "identified", "by", "+", "id", "+", "with", "the", "given", "attributes", "."], "sha": "37af27d0e5cd7d23896fd0d8f61134a962fc290f", "url": "https://github.com/d11wtq/oedipus/blob/37af27d0e5cd7d23896fd0d8f61134a962fc290f/lib/oedipus/query_builder.rb#L68-L78", "partition": "test"} {"repo": "d11wtq/oedipus", "path": "lib/oedipus/connection.rb", "func_name": "Oedipus.Connection.query", "original_string": "def query(sql, *bind_values)\n @pool.acquire { |conn| conn.query(sql, *bind_values).first }\n end", "language": "ruby", "code": "def query(sql, *bind_values)\n @pool.acquire { |conn| conn.query(sql, *bind_values).first }\n end", "code_tokens": ["def", "query", "(", "sql", ",", "*", "bind_values", ")", "@pool", ".", "acquire", "{", "|", "conn", "|", "conn", ".", "query", "(", "sql", ",", "bind_values", ")", ".", "first", "}", "end"], "docstring": "Execute a single read query.\n\n @param [String] sql\n a single SphinxQL statement\n\n @param [Object...] bind_values\n values to be substituted in place of '?' in the query\n\n @return [Array]\n an array of Hashes containing the matched records\n\n Note that SphinxQL does not support prepared statements.", "docstring_tokens": ["Execute", "a", "single", "read", "query", "."], "sha": "37af27d0e5cd7d23896fd0d8f61134a962fc290f", "url": "https://github.com/d11wtq/oedipus/blob/37af27d0e5cd7d23896fd0d8f61134a962fc290f/lib/oedipus/connection.rb#L90-L92", "partition": "test"} {"repo": "mboeh/woodhouse", "path": "lib/woodhouse/worker.rb", "func_name": "Woodhouse::Worker.ClassMethods.method_missing", "original_string": "def method_missing(method, *args, &block)\n if method.to_s =~ /^asynch?_(.*)/\n if instance_methods(false).detect{|meth| meth.to_s == $1 }\n Woodhouse.dispatch(@worker_name, $1, args.first)\n else\n super\n end\n else\n super\n end\n end", "language": "ruby", "code": "def method_missing(method, *args, &block)\n if method.to_s =~ /^asynch?_(.*)/\n if instance_methods(false).detect{|meth| meth.to_s == $1 }\n Woodhouse.dispatch(@worker_name, $1, args.first)\n else\n super\n end\n else\n super\n end\n end", "code_tokens": ["def", "method_missing", "(", "method", ",", "*", "args", ",", "&", "block", ")", "if", "method", ".", "to_s", "=~", "/", "/", "if", "instance_methods", "(", "false", ")", ".", "detect", "{", "|", "meth", "|", "meth", ".", "to_s", "==", "$1", "}", "Woodhouse", ".", "dispatch", "(", "@worker_name", ",", "$1", ",", "args", ".", "first", ")", "else", "super", "end", "else", "super", "end", "end"], "docstring": "You can dispatch a job +baz+ on class +FooBar+ by calling FooBar.async_baz.", "docstring_tokens": ["You", "can", "dispatch", "a", "job", "+", "baz", "+", "on", "class", "+", "FooBar", "+", "by", "calling", "FooBar", ".", "async_baz", "."], "sha": "ae19cf88a5da6901f62fd860a761615eccc705d0", "url": "https://github.com/mboeh/woodhouse/blob/ae19cf88a5da6901f62fd860a761615eccc705d0/lib/woodhouse/worker.rb#L84-L94", "partition": "test"} {"repo": "mboeh/woodhouse", "path": "lib/woodhouse/layout.rb", "func_name": "Woodhouse.Layout.add_node", "original_string": "def add_node(node)\n if node.respond_to?(:to_sym)\n node = Woodhouse::Layout::Node.new(node.to_sym) \n end\n expect_arg :node, Woodhouse::Layout::Node, node\n @nodes << node\n node\n end", "language": "ruby", "code": "def add_node(node)\n if node.respond_to?(:to_sym)\n node = Woodhouse::Layout::Node.new(node.to_sym) \n end\n expect_arg :node, Woodhouse::Layout::Node, node\n @nodes << node\n node\n end", "code_tokens": ["def", "add_node", "(", "node", ")", "if", "node", ".", "respond_to?", "(", ":to_sym", ")", "node", "=", "Woodhouse", "::", "Layout", "::", "Node", ".", "new", "(", "node", ".", "to_sym", ")", "end", "expect_arg", ":node", ",", "Woodhouse", "::", "Layout", "::", "Node", ",", "node", "@nodes", "<<", "node", "node", "end"], "docstring": "Adds a Node to this layout. If +node+ is a Symbol, a Node will be\n automatically created with that name.\n\n # Example:\n\n layout.add_node Woodhouse::Layout::Node.new(:isis)\n\n # Is equivalent to\n\n layout.add_node :isis", "docstring_tokens": ["Adds", "a", "Node", "to", "this", "layout", ".", "If", "+", "node", "+", "is", "a", "Symbol", "a", "Node", "will", "be", "automatically", "created", "with", "that", "name", "."], "sha": "ae19cf88a5da6901f62fd860a761615eccc705d0", "url": "https://github.com/mboeh/woodhouse/blob/ae19cf88a5da6901f62fd860a761615eccc705d0/lib/woodhouse/layout.rb#L46-L53", "partition": "test"} {"repo": "mboeh/woodhouse", "path": "lib/woodhouse/layout.rb", "func_name": "Woodhouse.Layout.node", "original_string": "def node(name)\n name = name.to_sym\n @nodes.detect{|node|\n node.name == name\n }\n end", "language": "ruby", "code": "def node(name)\n name = name.to_sym\n @nodes.detect{|node|\n node.name == name\n }\n end", "code_tokens": ["def", "node", "(", "name", ")", "name", "=", "name", ".", "to_sym", "@nodes", ".", "detect", "{", "|", "node", "|", "node", ".", "name", "==", "name", "}", "end"], "docstring": "Looks up a Node by name and returns it.", "docstring_tokens": ["Looks", "up", "a", "Node", "by", "name", "and", "returns", "it", "."], "sha": "ae19cf88a5da6901f62fd860a761615eccc705d0", "url": "https://github.com/mboeh/woodhouse/blob/ae19cf88a5da6901f62fd860a761615eccc705d0/lib/woodhouse/layout.rb#L56-L61", "partition": "test"} {"repo": "marcandre/scheherazade", "path": "lib/scheherazade/character_builder.rb", "func_name": "Scheherazade.CharacterBuilder.canonical", "original_string": "def canonical(attribute_list)\n case attribute_list\n when nil then {}\n when Hash then attribute_list\n when Array\n attribute_list.map do |attributes|\n case attributes\n when Symbol\n {attributes => AUTO}\n when Hash\n attributes\n else\n raise \"Unexpected attributes #{attributes}\"\n end\n end\n .inject({}, :merge)\n else\n raise \"Unexpected attribute_list #{attribute_list}\"\n end\n end", "language": "ruby", "code": "def canonical(attribute_list)\n case attribute_list\n when nil then {}\n when Hash then attribute_list\n when Array\n attribute_list.map do |attributes|\n case attributes\n when Symbol\n {attributes => AUTO}\n when Hash\n attributes\n else\n raise \"Unexpected attributes #{attributes}\"\n end\n end\n .inject({}, :merge)\n else\n raise \"Unexpected attribute_list #{attribute_list}\"\n end\n end", "code_tokens": ["def", "canonical", "(", "attribute_list", ")", "case", "attribute_list", "when", "nil", "then", "{", "}", "when", "Hash", "then", "attribute_list", "when", "Array", "attribute_list", ".", "map", "do", "|", "attributes", "|", "case", "attributes", "when", "Symbol", "{", "attributes", "=>", "AUTO", "}", "when", "Hash", "attributes", "else", "raise", "\"Unexpected attributes #{attributes}\"", "end", "end", ".", "inject", "(", "{", "}", ",", ":merge", ")", "else", "raise", "\"Unexpected attribute_list #{attribute_list}\"", "end", "end"], "docstring": "Converts an attribute_list to a single Hash;\n some of the values may be set to AUTO.\n\n canonical [:foo, {:bar => 42}]\n # => {:foo => AUTO, :bar => 42}", "docstring_tokens": ["Converts", "an", "attribute_list", "to", "a", "single", "Hash", ";", "some", "of", "the", "values", "may", "be", "set", "to", "AUTO", "."], "sha": "321e8e5f9f84c777168de10de8df6075141be215", "url": "https://github.com/marcandre/scheherazade/blob/321e8e5f9f84c777168de10de8df6075141be215/lib/scheherazade/character_builder.rb#L144-L163", "partition": "test"} {"repo": "marcandre/scheherazade", "path": "lib/scheherazade/story.rb", "func_name": "Scheherazade.Story.imagine", "original_string": "def imagine(character_or_model, attributes = nil)\n character = to_character(character_or_model)\n prev, @building = @building, [] # because method might be re-entrant\n CharacterBuilder.new(character).build(attributes) do |ar|\n ar.save!\n # While errors on records associated with :has_many will prevent records\n # from being saved, they won't for :belongs_to, so:\n @building.each do |built|\n raise ActiveRecord::RecordInvalid, built unless built.persisted? || built.valid?\n end\n Scheherazade.log(:saving, character, ar)\n handle_callbacks(@building)\n end\n ensure\n @built.concat(@building)\n @building = prev\n end", "language": "ruby", "code": "def imagine(character_or_model, attributes = nil)\n character = to_character(character_or_model)\n prev, @building = @building, [] # because method might be re-entrant\n CharacterBuilder.new(character).build(attributes) do |ar|\n ar.save!\n # While errors on records associated with :has_many will prevent records\n # from being saved, they won't for :belongs_to, so:\n @building.each do |built|\n raise ActiveRecord::RecordInvalid, built unless built.persisted? || built.valid?\n end\n Scheherazade.log(:saving, character, ar)\n handle_callbacks(@building)\n end\n ensure\n @built.concat(@building)\n @building = prev\n end", "code_tokens": ["def", "imagine", "(", "character_or_model", ",", "attributes", "=", "nil", ")", "character", "=", "to_character", "(", "character_or_model", ")", "prev", ",", "@building", "=", "@building", ",", "[", "]", "# because method might be re-entrant", "CharacterBuilder", ".", "new", "(", "character", ")", ".", "build", "(", "attributes", ")", "do", "|", "ar", "|", "ar", ".", "save!", "# While errors on records associated with :has_many will prevent records", "# from being saved, they won't for :belongs_to, so:", "@building", ".", "each", "do", "|", "built", "|", "raise", "ActiveRecord", "::", "RecordInvalid", ",", "built", "unless", "built", ".", "persisted?", "||", "built", ".", "valid?", "end", "Scheherazade", ".", "log", "(", ":saving", ",", "character", ",", "ar", ")", "handle_callbacks", "(", "@building", ")", "end", "ensure", "@built", ".", "concat", "(", "@building", ")", "@building", "=", "prev", "end"], "docstring": "Creates a character with the given attributes\n\n A character can be designated either by the model (e.g. `User`), the corresponding\n symbol (`:user`) or the symbol for a specialized type of character, defined using +fill+\n (e.g. `:admin`).\n\n The attributes can be nil, a list of symbols, a hash or a combination of both\n These, along with attributes passed to +fill+ for the current stories\n and the mandatory attributes for the model will be provided.\n\n If some fields generate validation errors, they will be provided also.\n\n For associations, the values can also be a character (Symbol or Model),\n integers (meaning the default Model * that integer) or arrays of characters.\n\n imagine(:user, :account, :company => :fortune_500_company, :emails => 3)\n\n Similarly:\n\n User.imagine(...)\n :user.imagine(...)\n\n This record (and any other imagined through associations) will become the\n current character in the current story:\n\n story.current[User] # => nil\n story.tell do\n :admin.imagine # => A User record\n story.current[:admin] # => same\n story.current[User] # => same\n end\n story.current[User] # => nil", "docstring_tokens": ["Creates", "a", "character", "with", "the", "given", "attributes"], "sha": "321e8e5f9f84c777168de10de8df6075141be215", "url": "https://github.com/marcandre/scheherazade/blob/321e8e5f9f84c777168de10de8df6075141be215/lib/scheherazade/story.rb#L117-L133", "partition": "test"} {"repo": "marcandre/scheherazade", "path": "lib/scheherazade/story.rb", "func_name": "Scheherazade.Story.with", "original_string": "def with(temp_current)\n keys = temp_current.keys.map{|k| to_character(k)}\n previous_values = current.values_at(*keys)\n current.merge!(Hash[keys.zip(temp_current.values)])\n yield\n ensure\n current.merge!(Hash[keys.zip(previous_values)])\n end", "language": "ruby", "code": "def with(temp_current)\n keys = temp_current.keys.map{|k| to_character(k)}\n previous_values = current.values_at(*keys)\n current.merge!(Hash[keys.zip(temp_current.values)])\n yield\n ensure\n current.merge!(Hash[keys.zip(previous_values)])\n end", "code_tokens": ["def", "with", "(", "temp_current", ")", "keys", "=", "temp_current", ".", "keys", ".", "map", "{", "|", "k", "|", "to_character", "(", "k", ")", "}", "previous_values", "=", "current", ".", "values_at", "(", "keys", ")", "current", ".", "merge!", "(", "Hash", "[", "keys", ".", "zip", "(", "temp_current", ".", "values", ")", "]", ")", "yield", "ensure", "current", ".", "merge!", "(", "Hash", "[", "keys", ".", "zip", "(", "previous_values", ")", "]", ")", "end"], "docstring": "Allows one to temporarily override the current characters while\n the given block executes", "docstring_tokens": ["Allows", "one", "to", "temporarily", "override", "the", "current", "characters", "while", "the", "given", "block", "executes"], "sha": "321e8e5f9f84c777168de10de8df6075141be215", "url": "https://github.com/marcandre/scheherazade/blob/321e8e5f9f84c777168de10de8df6075141be215/lib/scheherazade/story.rb#L142-L149", "partition": "test"} {"repo": "samstokes/deferrable_gratification", "path": "lib/deferrable_gratification/primitives.rb", "func_name": "DeferrableGratification.Primitives.failure", "original_string": "def failure(exception_class_or_message, message_or_nil = nil)\n blank.tap do |d|\n d.fail(\n case exception_class_or_message\n when Exception\n raise ArgumentError, \"can't specify both exception and message\" if message_or_nil\n exception_class_or_message\n when Class\n exception_class_or_message.new(message_or_nil)\n else\n RuntimeError.new(exception_class_or_message.to_s)\n end)\n end\n end", "language": "ruby", "code": "def failure(exception_class_or_message, message_or_nil = nil)\n blank.tap do |d|\n d.fail(\n case exception_class_or_message\n when Exception\n raise ArgumentError, \"can't specify both exception and message\" if message_or_nil\n exception_class_or_message\n when Class\n exception_class_or_message.new(message_or_nil)\n else\n RuntimeError.new(exception_class_or_message.to_s)\n end)\n end\n end", "code_tokens": ["def", "failure", "(", "exception_class_or_message", ",", "message_or_nil", "=", "nil", ")", "blank", ".", "tap", "do", "|", "d", "|", "d", ".", "fail", "(", "case", "exception_class_or_message", "when", "Exception", "raise", "ArgumentError", ",", "\"can't specify both exception and message\"", "if", "message_or_nil", "exception_class_or_message", "when", "Class", "exception_class_or_message", ".", "new", "(", "message_or_nil", ")", "else", "RuntimeError", ".", "new", "(", "exception_class_or_message", ".", "to_s", ")", "end", ")", "end", "end"], "docstring": "Return a Deferrable which immediately fails with an exception.\n\n @overload failure(message)\n Passes +RuntimeError.new(message)+ to errbacks.\n @overload failure(exception_class)\n Passes +exception_class.new+ to errbacks.\n @overload failure(exception_class, message)\n Passes +exception_class.new(message)+ to errbacks.\n @overload failure(exception)\n Passes +exception+ to errbacks.", "docstring_tokens": ["Return", "a", "Deferrable", "which", "immediately", "fails", "with", "an", "exception", "."], "sha": "254d72b5c65e4d2a264013420036a9012d7d8425", "url": "https://github.com/samstokes/deferrable_gratification/blob/254d72b5c65e4d2a264013420036a9012d7d8425/lib/deferrable_gratification/primitives.rb#L37-L50", "partition": "test"} {"repo": "odarriba/fantastic_robot", "path": "lib/fantastic_robot/request/send_audio.rb", "func_name": "FantasticRobot.Request::SendAudio.file_length", "original_string": "def file_length\n if self.audio.is_a?(File) && self.audio.size > MAX_FILE_SIZE\n self.errors.add :audio, \"It's length is excesive. #{MAX_FILE_SIZE} is the limit.\"\n return false\n end\n\n return true\n end", "language": "ruby", "code": "def file_length\n if self.audio.is_a?(File) && self.audio.size > MAX_FILE_SIZE\n self.errors.add :audio, \"It's length is excesive. #{MAX_FILE_SIZE} is the limit.\"\n return false\n end\n\n return true\n end", "code_tokens": ["def", "file_length", "if", "self", ".", "audio", ".", "is_a?", "(", "File", ")", "&&", "self", ".", "audio", ".", "size", ">", "MAX_FILE_SIZE", "self", ".", "errors", ".", "add", ":audio", ",", "\"It's length is excesive. #{MAX_FILE_SIZE} is the limit.\"", "return", "false", "end", "return", "true", "end"], "docstring": "Function to check that the file size isn't excesive.", "docstring_tokens": ["Function", "to", "check", "that", "the", "file", "size", "isn", "t", "excesive", "."], "sha": "5922d8d3a759a47a21ab9ac62ebc8759ad97495a", "url": "https://github.com/odarriba/fantastic_robot/blob/5922d8d3a759a47a21ab9ac62ebc8759ad97495a/lib/fantastic_robot/request/send_audio.rb#L23-L30", "partition": "test"} {"repo": "odarriba/fantastic_robot", "path": "lib/fantastic_robot/connection.rb", "func_name": "FantasticRobot.Connection.api_call", "original_string": "def api_call method, payload\n raise ArgumentError, \"API method not specified.\" if method.blank?\n\n payload ||= {}\n\n res = @conn.post method.to_s, payload\n\n raise Faraday::Error, \"Wrong response: #{res.inspect}\" if (res.status != 200)\n\n return res\n end", "language": "ruby", "code": "def api_call method, payload\n raise ArgumentError, \"API method not specified.\" if method.blank?\n\n payload ||= {}\n\n res = @conn.post method.to_s, payload\n\n raise Faraday::Error, \"Wrong response: #{res.inspect}\" if (res.status != 200)\n\n return res\n end", "code_tokens": ["def", "api_call", "method", ",", "payload", "raise", "ArgumentError", ",", "\"API method not specified.\"", "if", "method", ".", "blank?", "payload", "||=", "{", "}", "res", "=", "@conn", ".", "post", "method", ".", "to_s", ",", "payload", "raise", "Faraday", "::", "Error", ",", "\"Wrong response: #{res.inspect}\"", "if", "(", "res", ".", "status", "!=", "200", ")", "return", "res", "end"], "docstring": "Function to call API passing a payload", "docstring_tokens": ["Function", "to", "call", "API", "passing", "a", "payload"], "sha": "5922d8d3a759a47a21ab9ac62ebc8759ad97495a", "url": "https://github.com/odarriba/fantastic_robot/blob/5922d8d3a759a47a21ab9ac62ebc8759ad97495a/lib/fantastic_robot/connection.rb#L19-L29", "partition": "test"} {"repo": "d11wtq/oedipus", "path": "lib/oedipus/index.rb", "func_name": "Oedipus.Index.multi_search", "original_string": "def multi_search(queries)\n unless queries.kind_of?(Hash)\n raise ArgumentError, \"Argument must be a Hash of named queries (#{queries.class} given)\"\n end\n\n stmts = []\n bind_values = []\n\n queries.each do |key, args|\n str, *values = @builder.select(*extract_query_data(args))\n stmts.push(str, \"SHOW META\")\n bind_values.push(*values)\n end\n\n rs = @conn.multi_query(stmts.join(\";\\n\"), *bind_values)\n\n Hash[].tap do |result|\n queries.keys.each do |key|\n records, meta = rs.shift, rs.shift\n result[key] = meta_to_hash(meta).tap do |r|\n r[:records] = records.map { |hash|\n hash.inject({}) { |o, (k, v)| o.merge!(k.to_sym => v) }\n }\n end\n end\n end\n end", "language": "ruby", "code": "def multi_search(queries)\n unless queries.kind_of?(Hash)\n raise ArgumentError, \"Argument must be a Hash of named queries (#{queries.class} given)\"\n end\n\n stmts = []\n bind_values = []\n\n queries.each do |key, args|\n str, *values = @builder.select(*extract_query_data(args))\n stmts.push(str, \"SHOW META\")\n bind_values.push(*values)\n end\n\n rs = @conn.multi_query(stmts.join(\";\\n\"), *bind_values)\n\n Hash[].tap do |result|\n queries.keys.each do |key|\n records, meta = rs.shift, rs.shift\n result[key] = meta_to_hash(meta).tap do |r|\n r[:records] = records.map { |hash|\n hash.inject({}) { |o, (k, v)| o.merge!(k.to_sym => v) }\n }\n end\n end\n end\n end", "code_tokens": ["def", "multi_search", "(", "queries", ")", "unless", "queries", ".", "kind_of?", "(", "Hash", ")", "raise", "ArgumentError", ",", "\"Argument must be a Hash of named queries (#{queries.class} given)\"", "end", "stmts", "=", "[", "]", "bind_values", "=", "[", "]", "queries", ".", "each", "do", "|", "key", ",", "args", "|", "str", ",", "*", "values", "=", "@builder", ".", "select", "(", "extract_query_data", "(", "args", ")", ")", "stmts", ".", "push", "(", "str", ",", "\"SHOW META\"", ")", "bind_values", ".", "push", "(", "values", ")", "end", "rs", "=", "@conn", ".", "multi_query", "(", "stmts", ".", "join", "(", "\";\\n\"", ")", ",", "bind_values", ")", "Hash", "[", "]", ".", "tap", "do", "|", "result", "|", "queries", ".", "keys", ".", "each", "do", "|", "key", "|", "records", ",", "meta", "=", "rs", ".", "shift", ",", "rs", ".", "shift", "result", "[", "key", "]", "=", "meta_to_hash", "(", "meta", ")", ".", "tap", "do", "|", "r", "|", "r", "[", ":records", "]", "=", "records", ".", "map", "{", "|", "hash", "|", "hash", ".", "inject", "(", "{", "}", ")", "{", "|", "o", ",", "(", "k", ",", "v", ")", "|", "o", ".", "merge!", "(", "k", ".", "to_sym", "=>", "v", ")", "}", "}", "end", "end", "end", "end"], "docstring": "Perform a a batch search on the index.\n\n A Hash of queries is passed, whose keys are used to collate the results in\n the return value.\n\n Each query may either by a string (fulltext search), a Hash (attribute search)\n or an array containing both. In other words, the same arguments accepted by\n the #search method.\n\n @example\n index.multi_search(\n cat_results: [\"cats\", { author_id: 57 }],\n dog_results: [\"dogs\", { author_id: 57 }]\n )\n\n @param [Hash] queries\n a hash whose keys map to queries\n\n @return [Hash]\n a Hash whose keys map 1:1 with the input Hash, each element containing the\n same results as those returned by the #search method.", "docstring_tokens": ["Perform", "a", "a", "batch", "search", "on", "the", "index", "."], "sha": "37af27d0e5cd7d23896fd0d8f61134a962fc290f", "url": "https://github.com/d11wtq/oedipus/blob/37af27d0e5cd7d23896fd0d8f61134a962fc290f/lib/oedipus/index.rb#L218-L244", "partition": "test"} {"repo": "yrgoldteeth/whereabouts", "path": "lib/whereabouts_methods.rb", "func_name": "Whereabouts.ClassMethods.has_whereabouts", "original_string": "def has_whereabouts klass=:address, *args\n options = args.extract_options!\n # extend Address with class name if not defined.\n unless klass == :address || Object.const_defined?(klass.to_s.camelize)\n create_address_class(klass.to_s.camelize)\n end\n\n # Set the has_one relationship and accepts_nested_attributes_for. \n has_one klass, :as => :addressable, :dependent => :destroy\n accepts_nested_attributes_for klass\n\n # Define a singleton on the class that returns an array\n # that includes the address fields to validate presence of \n # or an empty array\n if options[:validate] && options[:validate].is_a?(Array)\n validators = options[:validate]\n set_validators(klass, validators)\n else\n validators = []\n end\n define_singleton_method validate_singleton_for(klass) do validators end\n\n # Check for geocode in options and confirm geocoder is defined.\n # Also defines a singleton to return a boolean about geocoding.\n if options[:geocode] && options[:geocode] == true && defined?(Geocoder)\n geocode = true\n set_geocoding(klass)\n else\n geocode = false\n end\n define_singleton_method geocode_singleton_for(klass) do geocode end\n end", "language": "ruby", "code": "def has_whereabouts klass=:address, *args\n options = args.extract_options!\n # extend Address with class name if not defined.\n unless klass == :address || Object.const_defined?(klass.to_s.camelize)\n create_address_class(klass.to_s.camelize)\n end\n\n # Set the has_one relationship and accepts_nested_attributes_for. \n has_one klass, :as => :addressable, :dependent => :destroy\n accepts_nested_attributes_for klass\n\n # Define a singleton on the class that returns an array\n # that includes the address fields to validate presence of \n # or an empty array\n if options[:validate] && options[:validate].is_a?(Array)\n validators = options[:validate]\n set_validators(klass, validators)\n else\n validators = []\n end\n define_singleton_method validate_singleton_for(klass) do validators end\n\n # Check for geocode in options and confirm geocoder is defined.\n # Also defines a singleton to return a boolean about geocoding.\n if options[:geocode] && options[:geocode] == true && defined?(Geocoder)\n geocode = true\n set_geocoding(klass)\n else\n geocode = false\n end\n define_singleton_method geocode_singleton_for(klass) do geocode end\n end", "code_tokens": ["def", "has_whereabouts", "klass", "=", ":address", ",", "*", "args", "options", "=", "args", ".", "extract_options!", "# extend Address with class name if not defined.", "unless", "klass", "==", ":address", "||", "Object", ".", "const_defined?", "(", "klass", ".", "to_s", ".", "camelize", ")", "create_address_class", "(", "klass", ".", "to_s", ".", "camelize", ")", "end", "# Set the has_one relationship and accepts_nested_attributes_for. ", "has_one", "klass", ",", ":as", "=>", ":addressable", ",", ":dependent", "=>", ":destroy", "accepts_nested_attributes_for", "klass", "# Define a singleton on the class that returns an array", "# that includes the address fields to validate presence of ", "# or an empty array", "if", "options", "[", ":validate", "]", "&&", "options", "[", ":validate", "]", ".", "is_a?", "(", "Array", ")", "validators", "=", "options", "[", ":validate", "]", "set_validators", "(", "klass", ",", "validators", ")", "else", "validators", "=", "[", "]", "end", "define_singleton_method", "validate_singleton_for", "(", "klass", ")", "do", "validators", "end", "# Check for geocode in options and confirm geocoder is defined.", "# Also defines a singleton to return a boolean about geocoding.", "if", "options", "[", ":geocode", "]", "&&", "options", "[", ":geocode", "]", "==", "true", "&&", "defined?", "(", "Geocoder", ")", "geocode", "=", "true", "set_geocoding", "(", "klass", ")", "else", "geocode", "=", "false", "end", "define_singleton_method", "geocode_singleton_for", "(", "klass", ")", "do", "geocode", "end", "end"], "docstring": "Accepts a symbol that will define the inherited\n type of Address. Defaults to the parent class.", "docstring_tokens": ["Accepts", "a", "symbol", "that", "will", "define", "the", "inherited", "type", "of", "Address", ".", "Defaults", "to", "the", "parent", "class", "."], "sha": "2b56ca4fb7e0298b78c30d51605986096863606d", "url": "https://github.com/yrgoldteeth/whereabouts/blob/2b56ca4fb7e0298b78c30d51605986096863606d/lib/whereabouts_methods.rb#L7-L38", "partition": "test"} {"repo": "yrgoldteeth/whereabouts", "path": "lib/whereabouts_methods.rb", "func_name": "Whereabouts.ClassMethods.set_validators", "original_string": "def set_validators klass, fields=[]\n _single = validate_singleton_for(klass)\n klass.to_s.camelize.constantize.class_eval do\n fields.each do |f|\n validates_presence_of f, \n :if => lambda {|a| a.addressable_type.constantize.send(_single).include?(f)}\n end\n end\n end", "language": "ruby", "code": "def set_validators klass, fields=[]\n _single = validate_singleton_for(klass)\n klass.to_s.camelize.constantize.class_eval do\n fields.each do |f|\n validates_presence_of f, \n :if => lambda {|a| a.addressable_type.constantize.send(_single).include?(f)}\n end\n end\n end", "code_tokens": ["def", "set_validators", "klass", ",", "fields", "=", "[", "]", "_single", "=", "validate_singleton_for", "(", "klass", ")", "klass", ".", "to_s", ".", "camelize", ".", "constantize", ".", "class_eval", "do", "fields", ".", "each", "do", "|", "f", "|", "validates_presence_of", "f", ",", ":if", "=>", "lambda", "{", "|", "a", "|", "a", ".", "addressable_type", ".", "constantize", ".", "send", "(", "_single", ")", ".", "include?", "(", "f", ")", "}", "end", "end", "end"], "docstring": "Sets validates_presence_of fields for the Address based on the\n singleton method created on the Address addressable_type class.", "docstring_tokens": ["Sets", "validates_presence_of", "fields", "for", "the", "Address", "based", "on", "the", "singleton", "method", "created", "on", "the", "Address", "addressable_type", "class", "."], "sha": "2b56ca4fb7e0298b78c30d51605986096863606d", "url": "https://github.com/yrgoldteeth/whereabouts/blob/2b56ca4fb7e0298b78c30d51605986096863606d/lib/whereabouts_methods.rb#L57-L65", "partition": "test"} {"repo": "yrgoldteeth/whereabouts", "path": "lib/whereabouts_methods.rb", "func_name": "Whereabouts.ClassMethods.create_address_class", "original_string": "def create_address_class(class_name, &block)\n klass = Class.new Address, &block\n Object.const_set class_name, klass\n end", "language": "ruby", "code": "def create_address_class(class_name, &block)\n klass = Class.new Address, &block\n Object.const_set class_name, klass\n end", "code_tokens": ["def", "create_address_class", "(", "class_name", ",", "&", "block", ")", "klass", "=", "Class", ".", "new", "Address", ",", "block", "Object", ".", "const_set", "class_name", ",", "klass", "end"], "docstring": "Generate a new class using Address as the superclass.\n Accepts a string defining the inherited type.", "docstring_tokens": ["Generate", "a", "new", "class", "using", "Address", "as", "the", "superclass", ".", "Accepts", "a", "string", "defining", "the", "inherited", "type", "."], "sha": "2b56ca4fb7e0298b78c30d51605986096863606d", "url": "https://github.com/yrgoldteeth/whereabouts/blob/2b56ca4fb7e0298b78c30d51605986096863606d/lib/whereabouts_methods.rb#L81-L84", "partition": "test"} {"repo": "bpardee/qwirk", "path": "lib/qwirk/worker.rb", "func_name": "Qwirk.Worker.event_loop", "original_string": "def event_loop\n Qwirk.logger.debug \"#{self}: Starting receive loop\"\n @start_worker_time = Time.now\n until @stopped || (config.stopped? && @impl.ready_to_stop?)\n Qwirk.logger.debug \"#{self}: Waiting for read\"\n @start_read_time = Time.now\n msg = @impl.receive_message\n if msg\n @start_processing_time = Time.now\n Qwirk.logger.debug {\"#{self}: Done waiting for read in #{@start_processing_time - @start_read_time} seconds\"}\n delta = config.timer.measure do\n @processing_mutex.synchronize do\n on_message(msg)\n @impl.acknowledge_message(msg)\n end\n end\n Qwirk.logger.info {\"#{self}::on_message (#{'%.1f' % delta}ms)\"} if self.config.log_times\n Qwirk.logger.flush if Qwirk.logger.respond_to?(:flush)\n end\n end\n Qwirk.logger.info \"#{self}: Exiting\"\n rescue Exception => e\n @status = \"Terminated: #{e.message}\"\n Qwirk.logger.error \"#{self}: Exception, thread terminating: #{e.message}\\n\\t#{e.backtrace.join(\"\\n\\t\")}\"\n ensure\n @status = 'Stopped'\n Qwirk.logger.flush if Qwirk.logger.respond_to?(:flush)\n config.worker_stopped(self)\n end", "language": "ruby", "code": "def event_loop\n Qwirk.logger.debug \"#{self}: Starting receive loop\"\n @start_worker_time = Time.now\n until @stopped || (config.stopped? && @impl.ready_to_stop?)\n Qwirk.logger.debug \"#{self}: Waiting for read\"\n @start_read_time = Time.now\n msg = @impl.receive_message\n if msg\n @start_processing_time = Time.now\n Qwirk.logger.debug {\"#{self}: Done waiting for read in #{@start_processing_time - @start_read_time} seconds\"}\n delta = config.timer.measure do\n @processing_mutex.synchronize do\n on_message(msg)\n @impl.acknowledge_message(msg)\n end\n end\n Qwirk.logger.info {\"#{self}::on_message (#{'%.1f' % delta}ms)\"} if self.config.log_times\n Qwirk.logger.flush if Qwirk.logger.respond_to?(:flush)\n end\n end\n Qwirk.logger.info \"#{self}: Exiting\"\n rescue Exception => e\n @status = \"Terminated: #{e.message}\"\n Qwirk.logger.error \"#{self}: Exception, thread terminating: #{e.message}\\n\\t#{e.backtrace.join(\"\\n\\t\")}\"\n ensure\n @status = 'Stopped'\n Qwirk.logger.flush if Qwirk.logger.respond_to?(:flush)\n config.worker_stopped(self)\n end", "code_tokens": ["def", "event_loop", "Qwirk", ".", "logger", ".", "debug", "\"#{self}: Starting receive loop\"", "@start_worker_time", "=", "Time", ".", "now", "until", "@stopped", "||", "(", "config", ".", "stopped?", "&&", "@impl", ".", "ready_to_stop?", ")", "Qwirk", ".", "logger", ".", "debug", "\"#{self}: Waiting for read\"", "@start_read_time", "=", "Time", ".", "now", "msg", "=", "@impl", ".", "receive_message", "if", "msg", "@start_processing_time", "=", "Time", ".", "now", "Qwirk", ".", "logger", ".", "debug", "{", "\"#{self}: Done waiting for read in #{@start_processing_time - @start_read_time} seconds\"", "}", "delta", "=", "config", ".", "timer", ".", "measure", "do", "@processing_mutex", ".", "synchronize", "do", "on_message", "(", "msg", ")", "@impl", ".", "acknowledge_message", "(", "msg", ")", "end", "end", "Qwirk", ".", "logger", ".", "info", "{", "\"#{self}::on_message (#{'%.1f' % delta}ms)\"", "}", "if", "self", ".", "config", ".", "log_times", "Qwirk", ".", "logger", ".", "flush", "if", "Qwirk", ".", "logger", ".", "respond_to?", "(", ":flush", ")", "end", "end", "Qwirk", ".", "logger", ".", "info", "\"#{self}: Exiting\"", "rescue", "Exception", "=>", "e", "@status", "=", "\"Terminated: #{e.message}\"", "Qwirk", ".", "logger", ".", "error", "\"#{self}: Exception, thread terminating: #{e.message}\\n\\t#{e.backtrace.join(\"\\n\\t\")}\"", "ensure", "@status", "=", "'Stopped'", "Qwirk", ".", "logger", ".", "flush", "if", "Qwirk", ".", "logger", ".", "respond_to?", "(", ":flush", ")", "config", ".", "worker_stopped", "(", "self", ")", "end"], "docstring": "Start the event loop for handling messages off the queue", "docstring_tokens": ["Start", "the", "event", "loop", "for", "handling", "messages", "off", "the", "queue"], "sha": "5fb9700cff5511a01181be8ff9cfa9172036a531", "url": "https://github.com/bpardee/qwirk/blob/5fb9700cff5511a01181be8ff9cfa9172036a531/lib/qwirk/worker.rb#L174-L202", "partition": "test"} {"repo": "jtvjt/activerecord-postgres-hstore-core", "path": "lib/activerecord_postgres_hstore_core/activerecord.rb", "func_name": "ActiveRecord.Base.arel_attributes_values", "original_string": "def arel_attributes_values(include_primary_key = true, include_readonly_attributes = true, attribute_names = @attributes.keys)\n attrs = {}\n attribute_names.each do |name|\n if (column = column_for_attribute(name)) && (include_primary_key || !column.primary)\n if include_readonly_attributes || (!include_readonly_attributes && !self.class.readonly_attributes.include?(name))\n value = read_attribute(name)\n if self.class.columns_hash[name].type == :hstore && value && value.is_a?(Hash)\n value = value.to_hstore # Done!\n elsif value && self.class.serialized_attributes.has_key?(name) && (value.acts_like?(:date) || value.acts_like?(:time) || value.is_a?(Hash) || value.is_a?(Array))\n value = value.to_yaml\n end\n attrs[self.class.arel_table[name]] = value\n end\n end\n end\n attrs\n end", "language": "ruby", "code": "def arel_attributes_values(include_primary_key = true, include_readonly_attributes = true, attribute_names = @attributes.keys)\n attrs = {}\n attribute_names.each do |name|\n if (column = column_for_attribute(name)) && (include_primary_key || !column.primary)\n if include_readonly_attributes || (!include_readonly_attributes && !self.class.readonly_attributes.include?(name))\n value = read_attribute(name)\n if self.class.columns_hash[name].type == :hstore && value && value.is_a?(Hash)\n value = value.to_hstore # Done!\n elsif value && self.class.serialized_attributes.has_key?(name) && (value.acts_like?(:date) || value.acts_like?(:time) || value.is_a?(Hash) || value.is_a?(Array))\n value = value.to_yaml\n end\n attrs[self.class.arel_table[name]] = value\n end\n end\n end\n attrs\n end", "code_tokens": ["def", "arel_attributes_values", "(", "include_primary_key", "=", "true", ",", "include_readonly_attributes", "=", "true", ",", "attribute_names", "=", "@attributes", ".", "keys", ")", "attrs", "=", "{", "}", "attribute_names", ".", "each", "do", "|", "name", "|", "if", "(", "column", "=", "column_for_attribute", "(", "name", ")", ")", "&&", "(", "include_primary_key", "||", "!", "column", ".", "primary", ")", "if", "include_readonly_attributes", "||", "(", "!", "include_readonly_attributes", "&&", "!", "self", ".", "class", ".", "readonly_attributes", ".", "include?", "(", "name", ")", ")", "value", "=", "read_attribute", "(", "name", ")", "if", "self", ".", "class", ".", "columns_hash", "[", "name", "]", ".", "type", "==", ":hstore", "&&", "value", "&&", "value", ".", "is_a?", "(", "Hash", ")", "value", "=", "value", ".", "to_hstore", "# Done!", "elsif", "value", "&&", "self", ".", "class", ".", "serialized_attributes", ".", "has_key?", "(", "name", ")", "&&", "(", "value", ".", "acts_like?", "(", ":date", ")", "||", "value", ".", "acts_like?", "(", ":time", ")", "||", "value", ".", "is_a?", "(", "Hash", ")", "||", "value", ".", "is_a?", "(", "Array", ")", ")", "value", "=", "value", ".", "to_yaml", "end", "attrs", "[", "self", ".", "class", ".", "arel_table", "[", "name", "]", "]", "=", "value", "end", "end", "end", "attrs", "end"], "docstring": "This method is replaced for Rails 3 compatibility.\n All I do is add the condition when the field is a hash that converts the value\n to hstore format.\n IMHO this should be delegated to the column, so it won't be necessary to rewrite all\n this method.", "docstring_tokens": ["This", "method", "is", "replaced", "for", "Rails", "3", "compatibility", ".", "All", "I", "do", "is", "add", "the", "condition", "when", "the", "field", "is", "a", "hash", "that", "converts", "the", "value", "to", "hstore", "format", ".", "IMHO", "this", "should", "be", "delegated", "to", "the", "column", "so", "it", "won", "t", "be", "necessary", "to", "rewrite", "all", "this", "method", "."], "sha": "053a9c006da4d3d7a1f0e9f530c0ea966cc17b82", "url": "https://github.com/jtvjt/activerecord-postgres-hstore-core/blob/053a9c006da4d3d7a1f0e9f530c0ea966cc17b82/lib/activerecord_postgres_hstore_core/activerecord.rb#L75-L91", "partition": "test"} {"repo": "vpereira/bugzilla", "path": "lib/bugzilla/bugzilla.rb", "func_name": "Bugzilla.Bugzilla.requires_version", "original_string": "def requires_version(cmd, version_)\n v = check_version(version_)\n raise NoMethodError, format('%s is not supported in Bugzilla %s', cmd, v[1]) unless v[0]\n end", "language": "ruby", "code": "def requires_version(cmd, version_)\n v = check_version(version_)\n raise NoMethodError, format('%s is not supported in Bugzilla %s', cmd, v[1]) unless v[0]\n end", "code_tokens": ["def", "requires_version", "(", "cmd", ",", "version_", ")", "v", "=", "check_version", "(", "version_", ")", "raise", "NoMethodError", ",", "format", "(", "'%s is not supported in Bugzilla %s'", ",", "cmd", ",", "v", "[", "1", "]", ")", "unless", "v", "[", "0", "]", "end"], "docstring": "def check_version\n rdoc\n\n ==== Bugzilla::Bugzilla#requires_version(cmd, version_)\n\n Raise an exception if the Bugzilla doesn't satisfy\n the requirement of the _version_.", "docstring_tokens": ["def", "check_version", "rdoc"], "sha": "6832b6741adacbff7d177467325822dd90424a9d", "url": "https://github.com/vpereira/bugzilla/blob/6832b6741adacbff7d177467325822dd90424a9d/lib/bugzilla/bugzilla.rb#L60-L63", "partition": "test"} {"repo": "itrp/clacks", "path": "lib/clacks/service.rb", "func_name": "Clacks.Service.run", "original_string": "def run\n begin\n Clacks.logger.info \"Clacks v#{Clacks::VERSION} started\"\n if Clacks.config[:pop3]\n run_pop3\n elsif Clacks.config[:imap]\n run_imap\n else\n raise \"Either a POP3 or an IMAP server must be configured\"\n end\n rescue Exception => e\n fatal(e)\n end\n end", "language": "ruby", "code": "def run\n begin\n Clacks.logger.info \"Clacks v#{Clacks::VERSION} started\"\n if Clacks.config[:pop3]\n run_pop3\n elsif Clacks.config[:imap]\n run_imap\n else\n raise \"Either a POP3 or an IMAP server must be configured\"\n end\n rescue Exception => e\n fatal(e)\n end\n end", "code_tokens": ["def", "run", "begin", "Clacks", ".", "logger", ".", "info", "\"Clacks v#{Clacks::VERSION} started\"", "if", "Clacks", ".", "config", "[", ":pop3", "]", "run_pop3", "elsif", "Clacks", ".", "config", "[", ":imap", "]", "run_imap", "else", "raise", "\"Either a POP3 or an IMAP server must be configured\"", "end", "rescue", "Exception", "=>", "e", "fatal", "(", "e", ")", "end", "end"], "docstring": "default 10 minutes", "docstring_tokens": ["default", "10", "minutes"], "sha": "54714facb9cc5290246fe562c107b058a683f91d", "url": "https://github.com/itrp/clacks/blob/54714facb9cc5290246fe562c107b058a683f91d/lib/clacks/service.rb#L16-L29", "partition": "test"} {"repo": "itrp/clacks", "path": "lib/clacks/service.rb", "func_name": "Clacks.Service.imap_validate_options", "original_string": "def imap_validate_options(options)\n options ||= {}\n options[:mailbox] ||= 'INBOX'\n options[:count] ||= 5\n options[:order] ||= :asc\n options[:what] ||= :first\n options[:keys] ||= 'ALL'\n options[:delete_after_find] ||= false\n options[:mailbox] = Net::IMAP.encode_utf7(options[:mailbox])\n if options[:archivebox]\n options[:archivebox] = Net::IMAP.encode_utf7(options[:archivebox])\n end\n options\n end", "language": "ruby", "code": "def imap_validate_options(options)\n options ||= {}\n options[:mailbox] ||= 'INBOX'\n options[:count] ||= 5\n options[:order] ||= :asc\n options[:what] ||= :first\n options[:keys] ||= 'ALL'\n options[:delete_after_find] ||= false\n options[:mailbox] = Net::IMAP.encode_utf7(options[:mailbox])\n if options[:archivebox]\n options[:archivebox] = Net::IMAP.encode_utf7(options[:archivebox])\n end\n options\n end", "code_tokens": ["def", "imap_validate_options", "(", "options", ")", "options", "||=", "{", "}", "options", "[", ":mailbox", "]", "||=", "'INBOX'", "options", "[", ":count", "]", "||=", "5", "options", "[", ":order", "]", "||=", ":asc", "options", "[", ":what", "]", "||=", ":first", "options", "[", ":keys", "]", "||=", "'ALL'", "options", "[", ":delete_after_find", "]", "||=", "false", "options", "[", ":mailbox", "]", "=", "Net", "::", "IMAP", ".", "encode_utf7", "(", "options", "[", ":mailbox", "]", ")", "if", "options", "[", ":archivebox", "]", "options", "[", ":archivebox", "]", "=", "Net", "::", "IMAP", ".", "encode_utf7", "(", "options", "[", ":archivebox", "]", ")", "end", "options", "end"], "docstring": "Follows mostly the defaults from the Mail gem", "docstring_tokens": ["Follows", "mostly", "the", "defaults", "from", "the", "Mail", "gem"], "sha": "54714facb9cc5290246fe562c107b058a683f91d", "url": "https://github.com/itrp/clacks/blob/54714facb9cc5290246fe562c107b058a683f91d/lib/clacks/service.rb#L73-L86", "partition": "test"} {"repo": "itrp/clacks", "path": "lib/clacks/service.rb", "func_name": "Clacks.Service.imap_find", "original_string": "def imap_find(imap)\n options = Clacks.config[:find_options]\n delete_after_find = options[:delete_after_find]\n begin\n break if stopping?\n uids = imap.uid_search(options[:keys] || 'ALL')\n uids.reverse! if options[:what].to_sym == :last\n uids = uids.first(options[:count]) if options[:count].is_a?(Integer)\n uids.reverse! if (options[:what].to_sym == :last && options[:order].to_sym == :asc) ||\n (options[:what].to_sym != :last && options[:order].to_sym == :desc)\n processed = 0\n expunge = false\n uids.each do |uid|\n break if stopping?\n source = imap.uid_fetch(uid, ['RFC822']).first.attr['RFC822']\n mail = nil\n begin\n mail = Mail.new(source)\n mail.mark_for_delete = true if delete_after_find\n Clacks.config[:on_mail].call(mail)\n rescue StandardError => e\n Clacks.logger.error(e.message)\n Clacks.logger.error(e.backtrace)\n end\n begin\n imap.uid_copy(uid, options[:archivebox]) if options[:archivebox]\n if delete_after_find && (mail.nil? || mail.is_marked_for_delete?)\n expunge = true\n imap.uid_store(uid, \"+FLAGS\", [Net::IMAP::DELETED])\n end\n rescue StandardError => e\n Clacks.logger.error(e.message)\n end\n processed += 1\n end\n imap.expunge if expunge\n end while uids.any? && processed == uids.length\n end", "language": "ruby", "code": "def imap_find(imap)\n options = Clacks.config[:find_options]\n delete_after_find = options[:delete_after_find]\n begin\n break if stopping?\n uids = imap.uid_search(options[:keys] || 'ALL')\n uids.reverse! if options[:what].to_sym == :last\n uids = uids.first(options[:count]) if options[:count].is_a?(Integer)\n uids.reverse! if (options[:what].to_sym == :last && options[:order].to_sym == :asc) ||\n (options[:what].to_sym != :last && options[:order].to_sym == :desc)\n processed = 0\n expunge = false\n uids.each do |uid|\n break if stopping?\n source = imap.uid_fetch(uid, ['RFC822']).first.attr['RFC822']\n mail = nil\n begin\n mail = Mail.new(source)\n mail.mark_for_delete = true if delete_after_find\n Clacks.config[:on_mail].call(mail)\n rescue StandardError => e\n Clacks.logger.error(e.message)\n Clacks.logger.error(e.backtrace)\n end\n begin\n imap.uid_copy(uid, options[:archivebox]) if options[:archivebox]\n if delete_after_find && (mail.nil? || mail.is_marked_for_delete?)\n expunge = true\n imap.uid_store(uid, \"+FLAGS\", [Net::IMAP::DELETED])\n end\n rescue StandardError => e\n Clacks.logger.error(e.message)\n end\n processed += 1\n end\n imap.expunge if expunge\n end while uids.any? && processed == uids.length\n end", "code_tokens": ["def", "imap_find", "(", "imap", ")", "options", "=", "Clacks", ".", "config", "[", ":find_options", "]", "delete_after_find", "=", "options", "[", ":delete_after_find", "]", "begin", "break", "if", "stopping?", "uids", "=", "imap", ".", "uid_search", "(", "options", "[", ":keys", "]", "||", "'ALL'", ")", "uids", ".", "reverse!", "if", "options", "[", ":what", "]", ".", "to_sym", "==", ":last", "uids", "=", "uids", ".", "first", "(", "options", "[", ":count", "]", ")", "if", "options", "[", ":count", "]", ".", "is_a?", "(", "Integer", ")", "uids", ".", "reverse!", "if", "(", "options", "[", ":what", "]", ".", "to_sym", "==", ":last", "&&", "options", "[", ":order", "]", ".", "to_sym", "==", ":asc", ")", "||", "(", "options", "[", ":what", "]", ".", "to_sym", "!=", ":last", "&&", "options", "[", ":order", "]", ".", "to_sym", "==", ":desc", ")", "processed", "=", "0", "expunge", "=", "false", "uids", ".", "each", "do", "|", "uid", "|", "break", "if", "stopping?", "source", "=", "imap", ".", "uid_fetch", "(", "uid", ",", "[", "'RFC822'", "]", ")", ".", "first", ".", "attr", "[", "'RFC822'", "]", "mail", "=", "nil", "begin", "mail", "=", "Mail", ".", "new", "(", "source", ")", "mail", ".", "mark_for_delete", "=", "true", "if", "delete_after_find", "Clacks", ".", "config", "[", ":on_mail", "]", ".", "call", "(", "mail", ")", "rescue", "StandardError", "=>", "e", "Clacks", ".", "logger", ".", "error", "(", "e", ".", "message", ")", "Clacks", ".", "logger", ".", "error", "(", "e", ".", "backtrace", ")", "end", "begin", "imap", ".", "uid_copy", "(", "uid", ",", "options", "[", ":archivebox", "]", ")", "if", "options", "[", ":archivebox", "]", "if", "delete_after_find", "&&", "(", "mail", ".", "nil?", "||", "mail", ".", "is_marked_for_delete?", ")", "expunge", "=", "true", "imap", ".", "uid_store", "(", "uid", ",", "\"+FLAGS\"", ",", "[", "Net", "::", "IMAP", "::", "DELETED", "]", ")", "end", "rescue", "StandardError", "=>", "e", "Clacks", ".", "logger", ".", "error", "(", "e", ".", "message", ")", "end", "processed", "+=", "1", "end", "imap", ".", "expunge", "if", "expunge", "end", "while", "uids", ".", "any?", "&&", "processed", "==", "uids", ".", "length", "end"], "docstring": "Keep processing emails until nothing is found anymore,\n or until a QUIT signal is received to stop the process.", "docstring_tokens": ["Keep", "processing", "emails", "until", "nothing", "is", "found", "anymore", "or", "until", "a", "QUIT", "signal", "is", "received", "to", "stop", "the", "process", "."], "sha": "54714facb9cc5290246fe562c107b058a683f91d", "url": "https://github.com/itrp/clacks/blob/54714facb9cc5290246fe562c107b058a683f91d/lib/clacks/service.rb#L154-L191", "partition": "test"} {"repo": "palladius/ric", "path": "lib/ric/colors.rb", "func_name": "Ric.Colors.rainbow", "original_string": "def rainbow(str)\n i=0\n ret = '' \n str=str.to_s\n while(i < str.length)\n ch = str[i]\n palette = $color_db[0][i % $color_db[0].length ]\n ret << (colora(palette,str[i,1]))\n i += 1\n end\n ret\n end", "language": "ruby", "code": "def rainbow(str)\n i=0\n ret = '' \n str=str.to_s\n while(i < str.length)\n ch = str[i]\n palette = $color_db[0][i % $color_db[0].length ]\n ret << (colora(palette,str[i,1]))\n i += 1\n end\n ret\n end", "code_tokens": ["def", "rainbow", "(", "str", ")", "i", "=", "0", "ret", "=", "''", "str", "=", "str", ".", "to_s", "while", "(", "i", "<", "str", ".", "length", ")", "ch", "=", "str", "[", "i", "]", "palette", "=", "$color_db", "[", "0", "]", "[", "i", "%", "$color_db", "[", "0", "]", ".", "length", "]", "ret", "<<", "(", "colora", "(", "palette", ",", "str", "[", "i", ",", "1", "]", ")", ")", "i", "+=", "1", "end", "ret", "end"], "docstring": "carattere per carattere...", "docstring_tokens": ["carattere", "per", "carattere", "..."], "sha": "3078a1d917ffbc96a87cc5090485ca948631ddfb", "url": "https://github.com/palladius/ric/blob/3078a1d917ffbc96a87cc5090485ca948631ddfb/lib/ric/colors.rb#L123-L134", "partition": "test"} {"repo": "duse-io/secret_sharing_ruby", "path": "lib/secret_sharing/prime.rb", "func_name": "SecretSharing.Prime.large_enough_prime", "original_string": "def large_enough_prime(input)\n standard_primes.each do |prime|\n return prime if prime > input\n end\n fail CannotFindLargeEnoughPrime, \"Input too large\"\n end", "language": "ruby", "code": "def large_enough_prime(input)\n standard_primes.each do |prime|\n return prime if prime > input\n end\n fail CannotFindLargeEnoughPrime, \"Input too large\"\n end", "code_tokens": ["def", "large_enough_prime", "(", "input", ")", "standard_primes", ".", "each", "do", "|", "prime", "|", "return", "prime", "if", "prime", ">", "input", "end", "fail", "CannotFindLargeEnoughPrime", ",", "\"Input too large\"", "end"], "docstring": "Retrieves the next largest prime for the largest number in batch\n\n Example\n\n Prime.large_enough_prime 4\n # => 7\n\n @param input [Integer] the integer to find the next largest prime for\n @return [Integer] the next largest prime\n @raise [CannotFindLargeEnoughPrime] raised when input is too large and\n no large enough prime can be found", "docstring_tokens": ["Retrieves", "the", "next", "largest", "prime", "for", "the", "largest", "number", "in", "batch"], "sha": "a5e4202427f0b566dc0cd157b94d2e9f4c3bc4b6", "url": "https://github.com/duse-io/secret_sharing_ruby/blob/a5e4202427f0b566dc0cd157b94d2e9f4c3bc4b6/lib/secret_sharing/prime.rb#L19-L24", "partition": "test"} {"repo": "ebsaral/sentence-builder", "path": "lib/sentence_builder/sentence_node.rb", "func_name": "SentenceBuilder.SentenceNode.enhance_content", "original_string": "def enhance_content(value, separator = ', ')\n value.is_a?(Array) ? value.join(separator) : value\n end", "language": "ruby", "code": "def enhance_content(value, separator = ', ')\n value.is_a?(Array) ? value.join(separator) : value\n end", "code_tokens": ["def", "enhance_content", "(", "value", ",", "separator", "=", "', '", ")", "value", ".", "is_a?", "(", "Array", ")", "?", "value", ".", "join", "(", "separator", ")", ":", "value", "end"], "docstring": "Combines array into a string with given separator", "docstring_tokens": ["Combines", "array", "into", "a", "string", "with", "given", "separator"], "sha": "4f3691323dbbcf370f7b2530ae0967f4ec16a3e9", "url": "https://github.com/ebsaral/sentence-builder/blob/4f3691323dbbcf370f7b2530ae0967f4ec16a3e9/lib/sentence_builder/sentence_node.rb#L116-L118", "partition": "test"} {"repo": "duse-io/secret_sharing_ruby", "path": "lib/secret_sharing/charset.rb", "func_name": "SecretSharing.Charset.i_to_s", "original_string": "def i_to_s(input)\n if !input.is_a?(Integer) || input < 0\n fail NotPositiveInteger, \"input must be a non-negative integer\"\n end\n\n output = \"\"\n while input > 0\n input, codepoint = input.divmod(charset.length)\n output.prepend(codepoint_to_char(codepoint))\n end\n output\n end", "language": "ruby", "code": "def i_to_s(input)\n if !input.is_a?(Integer) || input < 0\n fail NotPositiveInteger, \"input must be a non-negative integer\"\n end\n\n output = \"\"\n while input > 0\n input, codepoint = input.divmod(charset.length)\n output.prepend(codepoint_to_char(codepoint))\n end\n output\n end", "code_tokens": ["def", "i_to_s", "(", "input", ")", "if", "!", "input", ".", "is_a?", "(", "Integer", ")", "||", "input", "<", "0", "fail", "NotPositiveInteger", ",", "\"input must be a non-negative integer\"", "end", "output", "=", "\"\"", "while", "input", ">", "0", "input", ",", "codepoint", "=", "input", ".", "divmod", "(", "charset", ".", "length", ")", "output", ".", "prepend", "(", "codepoint_to_char", "(", "codepoint", ")", ")", "end", "output", "end"], "docstring": "The \"null-byte\" character is prepended to be the first character in the\n charset to avoid loosing the first character of the charset when it is\n also the first character in a string to convert.\n\n Example\n\n SecretSharing::Charset::DynamicCharset.new [\"a\", \"b\", \"c\"] # =>\n #\n\n @param charset [Array] array of characters to use for the charset.\n Calculate a string from an integer.\n\n Example\n\n charset = SecretSharing::Charset.by_charset_string \"abc\"\n charset.i_to_s 6\n # => \"ab\"\n\n @param input [Integer] integer to convert to string\n @return [String] converted string", "docstring_tokens": ["The", "null", "-", "byte", "character", "is", "prepended", "to", "be", "the", "first", "character", "in", "the", "charset", "to", "avoid", "loosing", "the", "first", "character", "of", "the", "charset", "when", "it", "is", "also", "the", "first", "character", "in", "a", "string", "to", "convert", "."], "sha": "a5e4202427f0b566dc0cd157b94d2e9f4c3bc4b6", "url": "https://github.com/duse-io/secret_sharing_ruby/blob/a5e4202427f0b566dc0cd157b94d2e9f4c3bc4b6/lib/secret_sharing/charset.rb#L37-L48", "partition": "test"} {"repo": "duse-io/secret_sharing_ruby", "path": "lib/secret_sharing/charset.rb", "func_name": "SecretSharing.Charset.s_to_i", "original_string": "def s_to_i(string)\n string.chars.reduce(0) do |output, char|\n output * charset.length + char_to_codepoint(char)\n end\n end", "language": "ruby", "code": "def s_to_i(string)\n string.chars.reduce(0) do |output, char|\n output * charset.length + char_to_codepoint(char)\n end\n end", "code_tokens": ["def", "s_to_i", "(", "string", ")", "string", ".", "chars", ".", "reduce", "(", "0", ")", "do", "|", "output", ",", "char", "|", "output", "*", "charset", ".", "length", "+", "char_to_codepoint", "(", "char", ")", "end", "end"], "docstring": "Calculate an integer from a string.\n\n Example\n\n charset = SecretSharing::Charset.by_charset_string \"abc\"\n charset.s_to_i \"ab\"\n # => 6\n\n @param string [Integer] integer to convert to string\n @return [String] converted string", "docstring_tokens": ["Calculate", "an", "integer", "from", "a", "string", "."], "sha": "a5e4202427f0b566dc0cd157b94d2e9f4c3bc4b6", "url": "https://github.com/duse-io/secret_sharing_ruby/blob/a5e4202427f0b566dc0cd157b94d2e9f4c3bc4b6/lib/secret_sharing/charset.rb#L60-L64", "partition": "test"} {"repo": "duse-io/secret_sharing_ruby", "path": "lib/secret_sharing/charset.rb", "func_name": "SecretSharing.Charset.char_to_codepoint", "original_string": "def char_to_codepoint(c)\n codepoint = charset.index c\n if codepoint.nil?\n fail NotInCharset, \"Char \\\"#{c}\\\" not part of the supported charset\"\n end\n codepoint\n end", "language": "ruby", "code": "def char_to_codepoint(c)\n codepoint = charset.index c\n if codepoint.nil?\n fail NotInCharset, \"Char \\\"#{c}\\\" not part of the supported charset\"\n end\n codepoint\n end", "code_tokens": ["def", "char_to_codepoint", "(", "c", ")", "codepoint", "=", "charset", ".", "index", "c", "if", "codepoint", ".", "nil?", "fail", "NotInCharset", ",", "\"Char \\\"#{c}\\\" not part of the supported charset\"", "end", "codepoint", "end"], "docstring": "Convert a single character into its integer representation according to\n the charset.\n\n Example\n\n charset = SecretSharing::Charset.by_charset_string \"abc\"\n charset.char_to_codepoint \"a\"\n # => 1\n\n @param c [String] Character to retrieve its codepoint in the charset\n @return [Integer] Codepoint within the charset", "docstring_tokens": ["Convert", "a", "single", "character", "into", "its", "integer", "representation", "according", "to", "the", "charset", "."], "sha": "a5e4202427f0b566dc0cd157b94d2e9f4c3bc4b6", "url": "https://github.com/duse-io/secret_sharing_ruby/blob/a5e4202427f0b566dc0cd157b94d2e9f4c3bc4b6/lib/secret_sharing/charset.rb#L95-L101", "partition": "test"} {"repo": "duse-io/secret_sharing_ruby", "path": "lib/secret_sharing/charset.rb", "func_name": "SecretSharing.Charset.subset?", "original_string": "def subset?(string)\n (Set.new(string.chars) - Set.new(charset)).empty?\n end", "language": "ruby", "code": "def subset?(string)\n (Set.new(string.chars) - Set.new(charset)).empty?\n end", "code_tokens": ["def", "subset?", "(", "string", ")", "(", "Set", ".", "new", "(", "string", ".", "chars", ")", "-", "Set", ".", "new", "(", "charset", ")", ")", ".", "empty?", "end"], "docstring": "Check if the provided string can be represented by the charset.\n\n Example\n\n charset = SecretSharing::Charset.by_charset_string \"abc\"\n charset.subset? \"d\"\n # => false\n charset.subset? \"a\"\n # => true\n\n @param string [String] Character to retrieve the for codepoint\n @return [TrueClass|FalseClass]", "docstring_tokens": ["Check", "if", "the", "provided", "string", "can", "be", "represented", "by", "the", "charset", "."], "sha": "a5e4202427f0b566dc0cd157b94d2e9f4c3bc4b6", "url": "https://github.com/duse-io/secret_sharing_ruby/blob/a5e4202427f0b566dc0cd157b94d2e9f4c3bc4b6/lib/secret_sharing/charset.rb#L115-L117", "partition": "test"} {"repo": "duse-io/secret_sharing_ruby", "path": "lib/secret_sharing/polynomial.rb", "func_name": "SecretSharing.Polynomial.points", "original_string": "def points(num_points, prime)\n intercept = @coefficients[0] # the first coefficient is the intercept\n (1..num_points).map do |x|\n y = intercept\n (1...@coefficients.length).each do |i|\n y = (y + @coefficients[i] * x ** i) % prime\n end\n Point.new(x, y)\n end\n end", "language": "ruby", "code": "def points(num_points, prime)\n intercept = @coefficients[0] # the first coefficient is the intercept\n (1..num_points).map do |x|\n y = intercept\n (1...@coefficients.length).each do |i|\n y = (y + @coefficients[i] * x ** i) % prime\n end\n Point.new(x, y)\n end\n end", "code_tokens": ["def", "points", "(", "num_points", ",", "prime", ")", "intercept", "=", "@coefficients", "[", "0", "]", "# the first coefficient is the intercept", "(", "1", "..", "num_points", ")", ".", "map", "do", "|", "x", "|", "y", "=", "intercept", "(", "1", "...", "@coefficients", ".", "length", ")", ".", "each", "do", "|", "i", "|", "y", "=", "(", "y", "+", "@coefficients", "[", "i", "]", "*", "x", "**", "i", ")", "%", "prime", "end", "Point", ".", "new", "(", "x", ",", "y", ")", "end", "end"], "docstring": "Create a new instance of a Polynomial with n coefficients, when having\n the polynomial in standard polynomial form.\n\n Example\n\n For the polynomial f(x) = a0 + a1 * x + a2 * x^2 + ... + an * x^n the\n coefficients are [a0, a1, a2, ..., an]\n\n Polynomial.new [1, 2, 3]\n # => #\n\n @param coefficients [Array] an array of integers as the coefficients\n Generate points on the polynomial, that can be used to reconstruct the\n polynomial with.\n\n Example\n\n SecretSharing::Polynomial.new([1, 2, 3, 4]).points(3, 7)\n # => [#, #, #]\n\n @param num_points [Integer] number of points to generate\n @param prime [Integer] prime for calculation in finite field\n @return [Array] array of calculated points", "docstring_tokens": ["Create", "a", "new", "instance", "of", "a", "Polynomial", "with", "n", "coefficients", "when", "having", "the", "polynomial", "in", "standard", "polynomial", "form", "."], "sha": "a5e4202427f0b566dc0cd157b94d2e9f4c3bc4b6", "url": "https://github.com/duse-io/secret_sharing_ruby/blob/a5e4202427f0b566dc0cd157b94d2e9f4c3bc4b6/lib/secret_sharing/polynomial.rb#L41-L50", "partition": "test"} {"repo": "jronallo/mead", "path": "lib/mead/ead_validator.rb", "func_name": "Mead.EadValidator.validate!", "original_string": "def validate!\n files = Dir.glob(File.join(@directory, '*.xml')).sort\n threads = []\n files.map do |path|\n threads << Thread.new(path) do |path_t|\n eadid = File.basename(path_t, '.xml')\n begin\n ead = Mead::Ead.new({:file => File.open(path_t), :eadid => eadid})\n rescue => e\n record_invalid(eadid, ead, e)\n next\n end\n if ead.valid?\n @valid << eadid\n else\n record_invalid(eadid, ead)\n end\n end\n end\n threads.each { |thread| thread.join }\n metadata\n end", "language": "ruby", "code": "def validate!\n files = Dir.glob(File.join(@directory, '*.xml')).sort\n threads = []\n files.map do |path|\n threads << Thread.new(path) do |path_t|\n eadid = File.basename(path_t, '.xml')\n begin\n ead = Mead::Ead.new({:file => File.open(path_t), :eadid => eadid})\n rescue => e\n record_invalid(eadid, ead, e)\n next\n end\n if ead.valid?\n @valid << eadid\n else\n record_invalid(eadid, ead)\n end\n end\n end\n threads.each { |thread| thread.join }\n metadata\n end", "code_tokens": ["def", "validate!", "files", "=", "Dir", ".", "glob", "(", "File", ".", "join", "(", "@directory", ",", "'*.xml'", ")", ")", ".", "sort", "threads", "=", "[", "]", "files", ".", "map", "do", "|", "path", "|", "threads", "<<", "Thread", ".", "new", "(", "path", ")", "do", "|", "path_t", "|", "eadid", "=", "File", ".", "basename", "(", "path_t", ",", "'.xml'", ")", "begin", "ead", "=", "Mead", "::", "Ead", ".", "new", "(", "{", ":file", "=>", "File", ".", "open", "(", "path_t", ")", ",", ":eadid", "=>", "eadid", "}", ")", "rescue", "=>", "e", "record_invalid", "(", "eadid", ",", "ead", ",", "e", ")", "next", "end", "if", "ead", ".", "valid?", "@valid", "<<", "eadid", "else", "record_invalid", "(", "eadid", ",", "ead", ")", "end", "end", "end", "threads", ".", "each", "{", "|", "thread", "|", "thread", ".", "join", "}", "metadata", "end"], "docstring": "Creates a new EadValidator when given the path to a directory as a String", "docstring_tokens": ["Creates", "a", "new", "EadValidator", "when", "given", "the", "path", "to", "a", "directory", "as", "a", "String"], "sha": "119e25d762d228a17612afe327ac13227aa9825b", "url": "https://github.com/jronallo/mead/blob/119e25d762d228a17612afe327ac13227aa9825b/lib/mead/ead_validator.rb#L13-L34", "partition": "test"} {"repo": "bys-control/action_cable_notifications", "path": "lib/action_cable_notifications/model.rb", "func_name": "ActionCableNotifications.Model.notify_create", "original_string": "def notify_create\n self.ChannelPublications.each do |publication, options|\n if options[:actions].include? :create\n # Checks if records is within scope before broadcasting\n records = self.class.scoped_collection(options[:scope])\n\n if options[:scope]==:all or record_within_scope(records)\n ActionCable.server.broadcast publication,\n msg: 'create',\n id: self.id,\n data: self\n end\n end\n end\n end", "language": "ruby", "code": "def notify_create\n self.ChannelPublications.each do |publication, options|\n if options[:actions].include? :create\n # Checks if records is within scope before broadcasting\n records = self.class.scoped_collection(options[:scope])\n\n if options[:scope]==:all or record_within_scope(records)\n ActionCable.server.broadcast publication,\n msg: 'create',\n id: self.id,\n data: self\n end\n end\n end\n end", "code_tokens": ["def", "notify_create", "self", ".", "ChannelPublications", ".", "each", "do", "|", "publication", ",", "options", "|", "if", "options", "[", ":actions", "]", ".", "include?", ":create", "# Checks if records is within scope before broadcasting", "records", "=", "self", ".", "class", ".", "scoped_collection", "(", "options", "[", ":scope", "]", ")", "if", "options", "[", ":scope", "]", "==", ":all", "or", "record_within_scope", "(", "records", ")", "ActionCable", ".", "server", ".", "broadcast", "publication", ",", "msg", ":", "'create'", ",", "id", ":", "self", ".", "id", ",", "data", ":", "self", "end", "end", "end", "end"], "docstring": "Broadcast notifications when a new record is created", "docstring_tokens": ["Broadcast", "notifications", "when", "a", "new", "record", "is", "created"], "sha": "dc455e690ce87d4864a0833c89b77438da48da65", "url": "https://github.com/bys-control/action_cable_notifications/blob/dc455e690ce87d4864a0833c89b77438da48da65/lib/action_cable_notifications/model.rb#L84-L98", "partition": "test"} {"repo": "bys-control/action_cable_notifications", "path": "lib/action_cable_notifications/model.rb", "func_name": "ActionCableNotifications.Model.notify_update", "original_string": "def notify_update\n # Get model changes\n if self.respond_to?(:saved_changes) # For Rails >= 5.1\n changes = self.saved_changes.transform_values(&:second)\n else # For Rails < 5.1\n changes = self.changes.transform_values(&:second)\n end\n\n # Checks if there are changes in the model\n if !changes.empty?\n self.ChannelPublications.each do |publication, options|\n if options[:actions].include? :update\n # Checks if previous record was within scope\n record = record_within_scope(options[:records])\n was_in_scope = record.present?\n\n options[:records].delete(record) if was_in_scope\n\n # Checks if current record is within scope\n if options[:track_scope_changes]==true\n is_in_scope = false\n if options[:scope]==:all\n record = self\n is_in_scope = true\n else\n record = record_within_scope(self.class.scoped_collection(options[:scope]))\n if record.present?\n is_in_scope = true\n end\n end\n else\n is_in_scope = was_in_scope\n end\n\n # Broadcasts notifications about model changes\n if is_in_scope\n if was_in_scope\n # Get model changes and applies them to the scoped collection record\n changes.select!{|k,v| record.respond_to?(k)}\n\n if !changes.empty?\n ActionCable.server.broadcast publication,\n msg: 'update',\n id: self.id,\n data: changes\n end\n else\n ActionCable.server.broadcast publication,\n msg: 'create',\n id: record.id,\n data: record\n end\n elsif was_in_scope # checks if needs to delete the record if its no longer in scope\n ActionCable.server.broadcast publication,\n msg: 'destroy',\n id: self.id\n end\n end\n end\n end\n end", "language": "ruby", "code": "def notify_update\n # Get model changes\n if self.respond_to?(:saved_changes) # For Rails >= 5.1\n changes = self.saved_changes.transform_values(&:second)\n else # For Rails < 5.1\n changes = self.changes.transform_values(&:second)\n end\n\n # Checks if there are changes in the model\n if !changes.empty?\n self.ChannelPublications.each do |publication, options|\n if options[:actions].include? :update\n # Checks if previous record was within scope\n record = record_within_scope(options[:records])\n was_in_scope = record.present?\n\n options[:records].delete(record) if was_in_scope\n\n # Checks if current record is within scope\n if options[:track_scope_changes]==true\n is_in_scope = false\n if options[:scope]==:all\n record = self\n is_in_scope = true\n else\n record = record_within_scope(self.class.scoped_collection(options[:scope]))\n if record.present?\n is_in_scope = true\n end\n end\n else\n is_in_scope = was_in_scope\n end\n\n # Broadcasts notifications about model changes\n if is_in_scope\n if was_in_scope\n # Get model changes and applies them to the scoped collection record\n changes.select!{|k,v| record.respond_to?(k)}\n\n if !changes.empty?\n ActionCable.server.broadcast publication,\n msg: 'update',\n id: self.id,\n data: changes\n end\n else\n ActionCable.server.broadcast publication,\n msg: 'create',\n id: record.id,\n data: record\n end\n elsif was_in_scope # checks if needs to delete the record if its no longer in scope\n ActionCable.server.broadcast publication,\n msg: 'destroy',\n id: self.id\n end\n end\n end\n end\n end", "code_tokens": ["def", "notify_update", "# Get model changes", "if", "self", ".", "respond_to?", "(", ":saved_changes", ")", "# For Rails >= 5.1", "changes", "=", "self", ".", "saved_changes", ".", "transform_values", "(", ":second", ")", "else", "# For Rails < 5.1", "changes", "=", "self", ".", "changes", ".", "transform_values", "(", ":second", ")", "end", "# Checks if there are changes in the model", "if", "!", "changes", ".", "empty?", "self", ".", "ChannelPublications", ".", "each", "do", "|", "publication", ",", "options", "|", "if", "options", "[", ":actions", "]", ".", "include?", ":update", "# Checks if previous record was within scope", "record", "=", "record_within_scope", "(", "options", "[", ":records", "]", ")", "was_in_scope", "=", "record", ".", "present?", "options", "[", ":records", "]", ".", "delete", "(", "record", ")", "if", "was_in_scope", "# Checks if current record is within scope", "if", "options", "[", ":track_scope_changes", "]", "==", "true", "is_in_scope", "=", "false", "if", "options", "[", ":scope", "]", "==", ":all", "record", "=", "self", "is_in_scope", "=", "true", "else", "record", "=", "record_within_scope", "(", "self", ".", "class", ".", "scoped_collection", "(", "options", "[", ":scope", "]", ")", ")", "if", "record", ".", "present?", "is_in_scope", "=", "true", "end", "end", "else", "is_in_scope", "=", "was_in_scope", "end", "# Broadcasts notifications about model changes", "if", "is_in_scope", "if", "was_in_scope", "# Get model changes and applies them to the scoped collection record", "changes", ".", "select!", "{", "|", "k", ",", "v", "|", "record", ".", "respond_to?", "(", "k", ")", "}", "if", "!", "changes", ".", "empty?", "ActionCable", ".", "server", ".", "broadcast", "publication", ",", "msg", ":", "'update'", ",", "id", ":", "self", ".", "id", ",", "data", ":", "changes", "end", "else", "ActionCable", ".", "server", ".", "broadcast", "publication", ",", "msg", ":", "'create'", ",", "id", ":", "record", ".", "id", ",", "data", ":", "record", "end", "elsif", "was_in_scope", "# checks if needs to delete the record if its no longer in scope", "ActionCable", ".", "server", ".", "broadcast", "publication", ",", "msg", ":", "'destroy'", ",", "id", ":", "self", ".", "id", "end", "end", "end", "end", "end"], "docstring": "Broadcast notifications when a record is updated. Only changed fields will be sent\n if they are within configured scope", "docstring_tokens": ["Broadcast", "notifications", "when", "a", "record", "is", "updated", ".", "Only", "changed", "fields", "will", "be", "sent", "if", "they", "are", "within", "configured", "scope"], "sha": "dc455e690ce87d4864a0833c89b77438da48da65", "url": "https://github.com/bys-control/action_cable_notifications/blob/dc455e690ce87d4864a0833c89b77438da48da65/lib/action_cable_notifications/model.rb#L119-L179", "partition": "test"} {"repo": "bys-control/action_cable_notifications", "path": "lib/action_cable_notifications/model.rb", "func_name": "ActionCableNotifications.Model.notify_destroy", "original_string": "def notify_destroy\n self.ChannelPublications.each do |publication, options|\n if options[:scope]==:all or options[:actions].include? :destroy\n # Checks if record is within scope before broadcasting\n if options[:scope]==:all or record_within_scope(self.class.scoped_collection(options[:scope])).present?\n ActionCable.server.broadcast publication,\n msg: 'destroy',\n id: self.id\n end\n end\n end\n end", "language": "ruby", "code": "def notify_destroy\n self.ChannelPublications.each do |publication, options|\n if options[:scope]==:all or options[:actions].include? :destroy\n # Checks if record is within scope before broadcasting\n if options[:scope]==:all or record_within_scope(self.class.scoped_collection(options[:scope])).present?\n ActionCable.server.broadcast publication,\n msg: 'destroy',\n id: self.id\n end\n end\n end\n end", "code_tokens": ["def", "notify_destroy", "self", ".", "ChannelPublications", ".", "each", "do", "|", "publication", ",", "options", "|", "if", "options", "[", ":scope", "]", "==", ":all", "or", "options", "[", ":actions", "]", ".", "include?", ":destroy", "# Checks if record is within scope before broadcasting", "if", "options", "[", ":scope", "]", "==", ":all", "or", "record_within_scope", "(", "self", ".", "class", ".", "scoped_collection", "(", "options", "[", ":scope", "]", ")", ")", ".", "present?", "ActionCable", ".", "server", ".", "broadcast", "publication", ",", "msg", ":", "'destroy'", ",", "id", ":", "self", ".", "id", "end", "end", "end", "end"], "docstring": "Broadcast notifications when a record is destroyed.", "docstring_tokens": ["Broadcast", "notifications", "when", "a", "record", "is", "destroyed", "."], "sha": "dc455e690ce87d4864a0833c89b77438da48da65", "url": "https://github.com/bys-control/action_cable_notifications/blob/dc455e690ce87d4864a0833c89b77438da48da65/lib/action_cable_notifications/model.rb#L184-L195", "partition": "test"} {"repo": "itrp/clacks", "path": "lib/clacks/configurator.rb", "func_name": "Clacks.Configurator.logger", "original_string": "def logger(obj)\n %w(debug info warn error fatal level).each do |m|\n next if obj.respond_to?(m)\n raise ArgumentError, \"logger #{obj} does not respond to method #{m}\"\n end\n map[:logger] = obj\n end", "language": "ruby", "code": "def logger(obj)\n %w(debug info warn error fatal level).each do |m|\n next if obj.respond_to?(m)\n raise ArgumentError, \"logger #{obj} does not respond to method #{m}\"\n end\n map[:logger] = obj\n end", "code_tokens": ["def", "logger", "(", "obj", ")", "%w(", "debug", "info", "warn", "error", "fatal", "level", ")", ".", "each", "do", "|", "m", "|", "next", "if", "obj", ".", "respond_to?", "(", "m", ")", "raise", "ArgumentError", ",", "\"logger #{obj} does not respond to method #{m}\"", "end", "map", "[", ":logger", "]", "=", "obj", "end"], "docstring": "Sets the Logger-like object.\n The default Logger will log its output to Rails.logger if\n you're running within a rails environment, otherwise it will\n output to the path specified by +stdout_path+.", "docstring_tokens": ["Sets", "the", "Logger", "-", "like", "object", ".", "The", "default", "Logger", "will", "log", "its", "output", "to", "Rails", ".", "logger", "if", "you", "re", "running", "within", "a", "rails", "environment", "otherwise", "it", "will", "output", "to", "the", "path", "specified", "by", "+", "stdout_path", "+", "."], "sha": "54714facb9cc5290246fe562c107b058a683f91d", "url": "https://github.com/itrp/clacks/blob/54714facb9cc5290246fe562c107b058a683f91d/lib/clacks/configurator.rb#L37-L43", "partition": "test"} {"repo": "lbadura/currency_spy", "path": "lib/currency_spy/scraper_base.rb", "func_name": "CurrencySpy.ScraperBase.fetch_rates", "original_string": "def fetch_rates\n if self.class.superclass.eql?(Object)\n raise Exception.new(\"This method should be invoked from CurrencySpy::Scraper sub class\")\n else\n check_currency_code_validity\n rate_results = {}\n RATE_DATA.each do |rate|\n symbol = rate.to_sym\n if self.class.instance_methods.include?(symbol)\n value = self.send(symbol)\n rate_results[symbol] = value unless value.nil?\n end\n end\n rate_results\n end\n end", "language": "ruby", "code": "def fetch_rates\n if self.class.superclass.eql?(Object)\n raise Exception.new(\"This method should be invoked from CurrencySpy::Scraper sub class\")\n else\n check_currency_code_validity\n rate_results = {}\n RATE_DATA.each do |rate|\n symbol = rate.to_sym\n if self.class.instance_methods.include?(symbol)\n value = self.send(symbol)\n rate_results[symbol] = value unless value.nil?\n end\n end\n rate_results\n end\n end", "code_tokens": ["def", "fetch_rates", "if", "self", ".", "class", ".", "superclass", ".", "eql?", "(", "Object", ")", "raise", "Exception", ".", "new", "(", "\"This method should be invoked from CurrencySpy::Scraper sub class\"", ")", "else", "check_currency_code_validity", "rate_results", "=", "{", "}", "RATE_DATA", ".", "each", "do", "|", "rate", "|", "symbol", "=", "rate", ".", "to_sym", "if", "self", ".", "class", ".", "instance_methods", ".", "include?", "(", "symbol", ")", "value", "=", "self", ".", "send", "(", "symbol", ")", "rate_results", "[", "symbol", "]", "=", "value", "unless", "value", ".", "nil?", "end", "end", "rate_results", "end", "end"], "docstring": "Method which calls all rate fetching methods from the sub class and returns\n a Hash with appropriate values.", "docstring_tokens": ["Method", "which", "calls", "all", "rate", "fetching", "methods", "from", "the", "sub", "class", "and", "returns", "a", "Hash", "with", "appropriate", "values", "."], "sha": "be0689715649ff952d3d797a4b3f087793580924", "url": "https://github.com/lbadura/currency_spy/blob/be0689715649ff952d3d797a4b3f087793580924/lib/currency_spy/scraper_base.rb#L40-L55", "partition": "test"} {"repo": "PeterCamilleri/format_engine", "path": "lib/format_engine/spec_info.rb", "func_name": "FormatEngine.SpecInfo.parse", "original_string": "def parse(target)\r\n #Handle the width option if specified.\r\n if (width = fmt.width) > 0\r\n head, tail = src[0...width], src[width..-1] || \"\"\r\n else\r\n head, tail = src, \"\"\r\n end\r\n\r\n #Do the parse on the input string or regex.\r\n @prematch, @match, @postmatch = head.partition(target)\r\n\r\n #Analyze the results.\r\n if found?\r\n @src = @postmatch + tail\r\n @match\r\n else\r\n nil\r\n end\r\n end", "language": "ruby", "code": "def parse(target)\r\n #Handle the width option if specified.\r\n if (width = fmt.width) > 0\r\n head, tail = src[0...width], src[width..-1] || \"\"\r\n else\r\n head, tail = src, \"\"\r\n end\r\n\r\n #Do the parse on the input string or regex.\r\n @prematch, @match, @postmatch = head.partition(target)\r\n\r\n #Analyze the results.\r\n if found?\r\n @src = @postmatch + tail\r\n @match\r\n else\r\n nil\r\n end\r\n end", "code_tokens": ["def", "parse", "(", "target", ")", "#Handle the width option if specified.\r", "if", "(", "width", "=", "fmt", ".", "width", ")", ">", "0", "head", ",", "tail", "=", "src", "[", "0", "...", "width", "]", ",", "src", "[", "width", "..", "-", "1", "]", "||", "\"\"", "else", "head", ",", "tail", "=", "src", ",", "\"\"", "end", "#Do the parse on the input string or regex.\r", "@prematch", ",", "@match", ",", "@postmatch", "=", "head", ".", "partition", "(", "target", ")", "#Analyze the results.\r", "if", "found?", "@src", "=", "@postmatch", "+", "tail", "@match", "else", "nil", "end", "end"], "docstring": "Parse the source string for a target string or regex or return nil.", "docstring_tokens": ["Parse", "the", "source", "string", "for", "a", "target", "string", "or", "regex", "or", "return", "nil", "."], "sha": "f8df6e44895a0bf223882cf7526d5770c8a26d03", "url": "https://github.com/PeterCamilleri/format_engine/blob/f8df6e44895a0bf223882cf7526d5770c8a26d03/lib/format_engine/spec_info.rb#L47-L65", "partition": "test"} {"repo": "PeterCamilleri/format_engine", "path": "lib/format_engine/spec_info.rb", "func_name": "FormatEngine.SpecInfo.grab", "original_string": "def grab\r\n width = fmt.width\r\n\r\n if width > 0\r\n result, @src = src[0...width], src[width..-1] || \"\"\r\n elsif width == 0\r\n result, @src = src[0...1], src[1..-1] || \"\"\r\n elsif width == -1\r\n result, @src = src, \"\"\r\n else\r\n result, @src = src[0..width], src[(width+1)..-1] || \"\"\r\n end\r\n\r\n result\r\n end", "language": "ruby", "code": "def grab\r\n width = fmt.width\r\n\r\n if width > 0\r\n result, @src = src[0...width], src[width..-1] || \"\"\r\n elsif width == 0\r\n result, @src = src[0...1], src[1..-1] || \"\"\r\n elsif width == -1\r\n result, @src = src, \"\"\r\n else\r\n result, @src = src[0..width], src[(width+1)..-1] || \"\"\r\n end\r\n\r\n result\r\n end", "code_tokens": ["def", "grab", "width", "=", "fmt", ".", "width", "if", "width", ">", "0", "result", ",", "@src", "=", "src", "[", "0", "...", "width", "]", ",", "src", "[", "width", "..", "-", "1", "]", "||", "\"\"", "elsif", "width", "==", "0", "result", ",", "@src", "=", "src", "[", "0", "...", "1", "]", ",", "src", "[", "1", "..", "-", "1", "]", "||", "\"\"", "elsif", "width", "==", "-", "1", "result", ",", "@src", "=", "src", ",", "\"\"", "else", "result", ",", "@src", "=", "src", "[", "0", "..", "width", "]", ",", "src", "[", "(", "width", "+", "1", ")", "..", "-", "1", "]", "||", "\"\"", "end", "result", "end"], "docstring": "Grab some text", "docstring_tokens": ["Grab", "some", "text"], "sha": "f8df6e44895a0bf223882cf7526d5770c8a26d03", "url": "https://github.com/PeterCamilleri/format_engine/blob/f8df6e44895a0bf223882cf7526d5770c8a26d03/lib/format_engine/spec_info.rb#L74-L88", "partition": "test"} {"repo": "vpereira/bugzilla", "path": "lib/bugzilla/bug.rb", "func_name": "Bugzilla.Bug.get_comments", "original_string": "def get_comments(bugs)\n\n params = {}\n\n # TODO\n # this construction should be refactored to a method\n params['ids'] = case bugs\n when Array\n bugs\n when Integer || String\n [bugs]\n else\n raise ArgumentError, format('Unknown type of arguments: %s', bugs.class)\n end\n\n result = comments(params)\n\n # not supporting comment_ids. so drop \"comments\".\n ret = result['bugs']\n # creation_time was added in Bugzilla 4.4. copy the 'time' value to creation_time if not available for compatibility.\n unless check_version(4.4)[0]\n ret.each do |_id, o|\n o['comments'].each do |c|\n c['creation_time'] = c['time'] unless c.include?('creation_time')\n end\n end\n end\n\n ret\n end", "language": "ruby", "code": "def get_comments(bugs)\n\n params = {}\n\n # TODO\n # this construction should be refactored to a method\n params['ids'] = case bugs\n when Array\n bugs\n when Integer || String\n [bugs]\n else\n raise ArgumentError, format('Unknown type of arguments: %s', bugs.class)\n end\n\n result = comments(params)\n\n # not supporting comment_ids. so drop \"comments\".\n ret = result['bugs']\n # creation_time was added in Bugzilla 4.4. copy the 'time' value to creation_time if not available for compatibility.\n unless check_version(4.4)[0]\n ret.each do |_id, o|\n o['comments'].each do |c|\n c['creation_time'] = c['time'] unless c.include?('creation_time')\n end\n end\n end\n\n ret\n end", "code_tokens": ["def", "get_comments", "(", "bugs", ")", "params", "=", "{", "}", "# TODO", "# this construction should be refactored to a method", "params", "[", "'ids'", "]", "=", "case", "bugs", "when", "Array", "bugs", "when", "Integer", "||", "String", "[", "bugs", "]", "else", "raise", "ArgumentError", ",", "format", "(", "'Unknown type of arguments: %s'", ",", "bugs", ".", "class", ")", "end", "result", "=", "comments", "(", "params", ")", "# not supporting comment_ids. so drop \"comments\".", "ret", "=", "result", "[", "'bugs'", "]", "# creation_time was added in Bugzilla 4.4. copy the 'time' value to creation_time if not available for compatibility.", "unless", "check_version", "(", "4.4", ")", "[", "0", "]", "ret", ".", "each", "do", "|", "_id", ",", "o", "|", "o", "[", "'comments'", "]", ".", "each", "do", "|", "c", "|", "c", "[", "'creation_time'", "]", "=", "c", "[", "'time'", "]", "unless", "c", ".", "include?", "(", "'creation_time'", ")", "end", "end", "end", "ret", "end"], "docstring": "def get_bugs\n rdoc\n\n ==== Bugzilla::Bug#get_comments(bugs)", "docstring_tokens": ["def", "get_bugs", "rdoc"], "sha": "6832b6741adacbff7d177467325822dd90424a9d", "url": "https://github.com/vpereira/bugzilla/blob/6832b6741adacbff7d177467325822dd90424a9d/lib/bugzilla/bug.rb#L102-L131", "partition": "test"} {"repo": "bpardee/qwirk", "path": "lib/qwirk/manager.rb", "func_name": "Qwirk.Manager.save_persist_state", "original_string": "def save_persist_state\n return unless @persist_file\n new_persist_options = {}\n BaseWorker.worker_classes.each do |worker_class|\n worker_class.each_config(@adapter_factory.worker_config_class) do |config_name, ignored_extended_worker_config_class, default_options|\n static_options = default_options.merge(@worker_options[config_name] || {})\n worker_config = self[config_name]\n hash = {}\n # Only store off the config values that are specifically different from default values or values set in the workers.yml file\n # Then updates to these values will be allowed w/o being hardcoded to an old default value.\n worker_config.bean_get_attributes do |attribute_info|\n if attribute_info.attribute[:config_item] && attribute_info.ancestry.size == 1\n param_name = attribute_info.ancestry[0].to_sym\n value = attribute_info.value\n hash[param_name] = value if static_options[param_name] != value\n end\n end\n new_persist_options[config_name] = hash unless hash.empty?\n end\n end\n if new_persist_options != @persist_options\n @persist_options = new_persist_options\n File.open(@persist_file, 'w') do |out|\n YAML.dump(@persist_options, out )\n end\n end\n end", "language": "ruby", "code": "def save_persist_state\n return unless @persist_file\n new_persist_options = {}\n BaseWorker.worker_classes.each do |worker_class|\n worker_class.each_config(@adapter_factory.worker_config_class) do |config_name, ignored_extended_worker_config_class, default_options|\n static_options = default_options.merge(@worker_options[config_name] || {})\n worker_config = self[config_name]\n hash = {}\n # Only store off the config values that are specifically different from default values or values set in the workers.yml file\n # Then updates to these values will be allowed w/o being hardcoded to an old default value.\n worker_config.bean_get_attributes do |attribute_info|\n if attribute_info.attribute[:config_item] && attribute_info.ancestry.size == 1\n param_name = attribute_info.ancestry[0].to_sym\n value = attribute_info.value\n hash[param_name] = value if static_options[param_name] != value\n end\n end\n new_persist_options[config_name] = hash unless hash.empty?\n end\n end\n if new_persist_options != @persist_options\n @persist_options = new_persist_options\n File.open(@persist_file, 'w') do |out|\n YAML.dump(@persist_options, out )\n end\n end\n end", "code_tokens": ["def", "save_persist_state", "return", "unless", "@persist_file", "new_persist_options", "=", "{", "}", "BaseWorker", ".", "worker_classes", ".", "each", "do", "|", "worker_class", "|", "worker_class", ".", "each_config", "(", "@adapter_factory", ".", "worker_config_class", ")", "do", "|", "config_name", ",", "ignored_extended_worker_config_class", ",", "default_options", "|", "static_options", "=", "default_options", ".", "merge", "(", "@worker_options", "[", "config_name", "]", "||", "{", "}", ")", "worker_config", "=", "self", "[", "config_name", "]", "hash", "=", "{", "}", "# Only store off the config values that are specifically different from default values or values set in the workers.yml file", "# Then updates to these values will be allowed w/o being hardcoded to an old default value.", "worker_config", ".", "bean_get_attributes", "do", "|", "attribute_info", "|", "if", "attribute_info", ".", "attribute", "[", ":config_item", "]", "&&", "attribute_info", ".", "ancestry", ".", "size", "==", "1", "param_name", "=", "attribute_info", ".", "ancestry", "[", "0", "]", ".", "to_sym", "value", "=", "attribute_info", ".", "value", "hash", "[", "param_name", "]", "=", "value", "if", "static_options", "[", "param_name", "]", "!=", "value", "end", "end", "new_persist_options", "[", "config_name", "]", "=", "hash", "unless", "hash", ".", "empty?", "end", "end", "if", "new_persist_options", "!=", "@persist_options", "@persist_options", "=", "new_persist_options", "File", ".", "open", "(", "@persist_file", ",", "'w'", ")", "do", "|", "out", "|", "YAML", ".", "dump", "(", "@persist_options", ",", "out", ")", "end", "end", "end"], "docstring": "Store off any options that are no longer set to default", "docstring_tokens": ["Store", "off", "any", "options", "that", "are", "no", "longer", "set", "to", "default"], "sha": "5fb9700cff5511a01181be8ff9cfa9172036a531", "url": "https://github.com/bpardee/qwirk/blob/5fb9700cff5511a01181be8ff9cfa9172036a531/lib/qwirk/manager.rb#L100-L126", "partition": "test"} {"repo": "Dahie/caramelize", "path": "lib/caramelize/wiki/redmine_wiki.rb", "func_name": "Caramelize.RedmineWiki.read_pages", "original_string": "def read_pages\n # get all projects\n results_projects = database.query(\"SELECT id, identifier, name FROM projects;\")\n results_projects.each do |row_project|\n #collect all namespaces\n namespaces << OpenStruct.new(identifier: row_project[\"identifier\"], name: row_project[\"name\"])\n end\n\n # get all wikis\n results_wikis = database.query(\"SELECT id, project_id FROM wikis;\")\n\n # get all lemmas\n results_pages = database.query(\"SELECT id, title, wiki_id FROM wiki_pages;\")\n results_pages.each do |row_page|\n results_contents = database.query(\"SELECT * FROM wiki_content_versions WHERE page_id='#{row_page[\"id\"]}' ORDER BY updated_on;\")\n\n # get wiki for page\n wiki_row = nil\n project_row = nil\n results_wikis.each do |wiki|\n wiki_row = wiki if wiki[\"id\"] == row_page[\"wiki_id\"]\n end\n\n if wiki_row\n # get project from wiki-id\n results_projects.each do |project|\n project_row = project if project[\"id\"] == wiki_row[\"project_id\"]\n end\n end\n\n project_identifier = project_row ? project_row[\"identifier\"] + '/' : \"\"\n\n title = project_identifier + row_page[\"title\"]\n titles << title\n\n @latest_revisions = {}\n results_contents.each do |row_content|\n author = authors[row_content[\"author_id\"]] ? @authors[row_content[\"author_id\"]] : nil\n page = Page.new({:id => row_content[\"id\"],\n :title => title,\n :body => row_content[\"data\"],\n :markup => :textile,\n :latest => false,\n :time => row_content[\"updated_on\"],\n :message => row_content[\"comments\"],\n :author => author,\n :author_name => author.name})\n revisions << page\n @latest_revisions[title] = page\n end\n end\n titles.uniq!\n @latest_revisions.each { |rev| rev[1].set_latest }\n revisions.sort! { |a,b| a.time <=> b.time }\n\n # TODO find latest revision for each limit\n\n revisions\n end", "language": "ruby", "code": "def read_pages\n # get all projects\n results_projects = database.query(\"SELECT id, identifier, name FROM projects;\")\n results_projects.each do |row_project|\n #collect all namespaces\n namespaces << OpenStruct.new(identifier: row_project[\"identifier\"], name: row_project[\"name\"])\n end\n\n # get all wikis\n results_wikis = database.query(\"SELECT id, project_id FROM wikis;\")\n\n # get all lemmas\n results_pages = database.query(\"SELECT id, title, wiki_id FROM wiki_pages;\")\n results_pages.each do |row_page|\n results_contents = database.query(\"SELECT * FROM wiki_content_versions WHERE page_id='#{row_page[\"id\"]}' ORDER BY updated_on;\")\n\n # get wiki for page\n wiki_row = nil\n project_row = nil\n results_wikis.each do |wiki|\n wiki_row = wiki if wiki[\"id\"] == row_page[\"wiki_id\"]\n end\n\n if wiki_row\n # get project from wiki-id\n results_projects.each do |project|\n project_row = project if project[\"id\"] == wiki_row[\"project_id\"]\n end\n end\n\n project_identifier = project_row ? project_row[\"identifier\"] + '/' : \"\"\n\n title = project_identifier + row_page[\"title\"]\n titles << title\n\n @latest_revisions = {}\n results_contents.each do |row_content|\n author = authors[row_content[\"author_id\"]] ? @authors[row_content[\"author_id\"]] : nil\n page = Page.new({:id => row_content[\"id\"],\n :title => title,\n :body => row_content[\"data\"],\n :markup => :textile,\n :latest => false,\n :time => row_content[\"updated_on\"],\n :message => row_content[\"comments\"],\n :author => author,\n :author_name => author.name})\n revisions << page\n @latest_revisions[title] = page\n end\n end\n titles.uniq!\n @latest_revisions.each { |rev| rev[1].set_latest }\n revisions.sort! { |a,b| a.time <=> b.time }\n\n # TODO find latest revision for each limit\n\n revisions\n end", "code_tokens": ["def", "read_pages", "# get all projects", "results_projects", "=", "database", ".", "query", "(", "\"SELECT id, identifier, name FROM projects;\"", ")", "results_projects", ".", "each", "do", "|", "row_project", "|", "#collect all namespaces", "namespaces", "<<", "OpenStruct", ".", "new", "(", "identifier", ":", "row_project", "[", "\"identifier\"", "]", ",", "name", ":", "row_project", "[", "\"name\"", "]", ")", "end", "# get all wikis", "results_wikis", "=", "database", ".", "query", "(", "\"SELECT id, project_id FROM wikis;\"", ")", "# get all lemmas", "results_pages", "=", "database", ".", "query", "(", "\"SELECT id, title, wiki_id FROM wiki_pages;\"", ")", "results_pages", ".", "each", "do", "|", "row_page", "|", "results_contents", "=", "database", ".", "query", "(", "\"SELECT * FROM wiki_content_versions WHERE page_id='#{row_page[\"id\"]}' ORDER BY updated_on;\"", ")", "# get wiki for page", "wiki_row", "=", "nil", "project_row", "=", "nil", "results_wikis", ".", "each", "do", "|", "wiki", "|", "wiki_row", "=", "wiki", "if", "wiki", "[", "\"id\"", "]", "==", "row_page", "[", "\"wiki_id\"", "]", "end", "if", "wiki_row", "# get project from wiki-id", "results_projects", ".", "each", "do", "|", "project", "|", "project_row", "=", "project", "if", "project", "[", "\"id\"", "]", "==", "wiki_row", "[", "\"project_id\"", "]", "end", "end", "project_identifier", "=", "project_row", "?", "project_row", "[", "\"identifier\"", "]", "+", "'/'", ":", "\"\"", "title", "=", "project_identifier", "+", "row_page", "[", "\"title\"", "]", "titles", "<<", "title", "@latest_revisions", "=", "{", "}", "results_contents", ".", "each", "do", "|", "row_content", "|", "author", "=", "authors", "[", "row_content", "[", "\"author_id\"", "]", "]", "?", "@authors", "[", "row_content", "[", "\"author_id\"", "]", "]", ":", "nil", "page", "=", "Page", ".", "new", "(", "{", ":id", "=>", "row_content", "[", "\"id\"", "]", ",", ":title", "=>", "title", ",", ":body", "=>", "row_content", "[", "\"data\"", "]", ",", ":markup", "=>", ":textile", ",", ":latest", "=>", "false", ",", ":time", "=>", "row_content", "[", "\"updated_on\"", "]", ",", ":message", "=>", "row_content", "[", "\"comments\"", "]", ",", ":author", "=>", "author", ",", ":author_name", "=>", "author", ".", "name", "}", ")", "revisions", "<<", "page", "@latest_revisions", "[", "title", "]", "=", "page", "end", "end", "titles", ".", "uniq!", "@latest_revisions", ".", "each", "{", "|", "rev", "|", "rev", "[", "1", "]", ".", "set_latest", "}", "revisions", ".", "sort!", "{", "|", "a", ",", "b", "|", "a", ".", "time", "<=>", "b", ".", "time", "}", "# TODO find latest revision for each limit", "revisions", "end"], "docstring": "after calling this action, I expect the titles and revisions to be filled", "docstring_tokens": ["after", "calling", "this", "action", "I", "expect", "the", "titles", "and", "revisions", "to", "be", "filled"], "sha": "6bb93b65924edaaf071a8b3947d0545d5759bc5d", "url": "https://github.com/Dahie/caramelize/blob/6bb93b65924edaaf071a8b3947d0545d5759bc5d/lib/caramelize/wiki/redmine_wiki.rb#L18-L76", "partition": "test"} {"repo": "bpardee/qwirk", "path": "lib/qwirk/publish_handle.rb", "func_name": "Qwirk.PublishHandle.read_response", "original_string": "def read_response(timeout, &block)\n raise \"Invalid call to read_response for #{@producer}, not setup for responding\" unless @producer.response_options\n # Creates a block for reading the responses for a given message_id (adapter_info). The block will be passed an object\n # that responds to timeout_read(timeout) with a [original_message_id, response_message, worker_name] tri or nil if no message is read.\n # This is used in the RPC mechanism where a publish might wait for 1 or more workers to respond.\n @producer.impl.with_response(@adapter_info) do |consumer|\n if block_given?\n return read_multiple_response(consumer, timeout, &block)\n else\n tri = read_single_response(consumer, timeout)\n if tri\n response = tri[1]\n raise response if response.kind_of?(Qwirk::RemoteException)\n return response\n else\n @timeout = !tri\n return nil\n end\n end\n end\n end", "language": "ruby", "code": "def read_response(timeout, &block)\n raise \"Invalid call to read_response for #{@producer}, not setup for responding\" unless @producer.response_options\n # Creates a block for reading the responses for a given message_id (adapter_info). The block will be passed an object\n # that responds to timeout_read(timeout) with a [original_message_id, response_message, worker_name] tri or nil if no message is read.\n # This is used in the RPC mechanism where a publish might wait for 1 or more workers to respond.\n @producer.impl.with_response(@adapter_info) do |consumer|\n if block_given?\n return read_multiple_response(consumer, timeout, &block)\n else\n tri = read_single_response(consumer, timeout)\n if tri\n response = tri[1]\n raise response if response.kind_of?(Qwirk::RemoteException)\n return response\n else\n @timeout = !tri\n return nil\n end\n end\n end\n end", "code_tokens": ["def", "read_response", "(", "timeout", ",", "&", "block", ")", "raise", "\"Invalid call to read_response for #{@producer}, not setup for responding\"", "unless", "@producer", ".", "response_options", "# Creates a block for reading the responses for a given message_id (adapter_info). The block will be passed an object", "# that responds to timeout_read(timeout) with a [original_message_id, response_message, worker_name] tri or nil if no message is read.", "# This is used in the RPC mechanism where a publish might wait for 1 or more workers to respond.", "@producer", ".", "impl", ".", "with_response", "(", "@adapter_info", ")", "do", "|", "consumer", "|", "if", "block_given?", "return", "read_multiple_response", "(", "consumer", ",", "timeout", ",", "block", ")", "else", "tri", "=", "read_single_response", "(", "consumer", ",", "timeout", ")", "if", "tri", "response", "=", "tri", "[", "1", "]", "raise", "response", "if", "response", ".", "kind_of?", "(", "Qwirk", "::", "RemoteException", ")", "return", "response", "else", "@timeout", "=", "!", "tri", "return", "nil", "end", "end", "end", "end"], "docstring": "Waits the given timeout for a response message on the queue.\n\n If called w/o a block:\n Returns the message\n Returns nil on timeout\n Raises RemoteException on a remote exception\n\n If called with a block, for instance:\n handle.read_response(timeout) do |response|\n response.on_message 'CharCount' do |hash|\n puts \"CharCount returned #{hash.inspect}\"\n end\n response.on_message 'Length', 'Reverse' do |val|\n puts \"#{response.name} returned #{val}\"\n end\n response.on_message 'ExceptionRaiser' do |val|\n puts \"#{response.name} didn't raise an exception but returned #{val}\"\n end\n response.on_timeout 'Reverse' do\n puts \"Reverse has it's own timeout handler\"\n end\n response.on_timeout do\n puts \"#{response.name} did not respond in time\"\n end\n response.on_remote_exception 'ExceptionRaiser' do\n puts \"It figures that ExceptionRaiser would raise an exception\"\n end\n response.on_remote_exception do |e|\n puts \"#{response.name} raised an exception #{e.message}\\n\\t#{e.backtrace.join(\"\\n\\t\")}\"\n end\n end\n\n The specified blocks will be called for each response. For instance, LengthWorker#request\n might return 4 and \"Length returned 4\" would be displayed. If it failed to respond within the\n timeout, then \"Length did no respond in time\" would be displayed.\n For Workers that raise an exception, they will either be handled by their specific handler if it exists or\n the default exception handler. If that doesn't exist either, then the RemoteException will be raised for the\n whole read_response call. Timeouts will also be handled by the default timeout handler unless a specific one\n is specified. All messages must have a specific handler specified because the call won't return until all\n specified handlers either return, timeout, or return an exception.", "docstring_tokens": ["Waits", "the", "given", "timeout", "for", "a", "response", "message", "on", "the", "queue", "."], "sha": "5fb9700cff5511a01181be8ff9cfa9172036a531", "url": "https://github.com/bpardee/qwirk/blob/5fb9700cff5511a01181be8ff9cfa9172036a531/lib/qwirk/publish_handle.rb#L57-L77", "partition": "test"} {"repo": "chrisjones-tripletri/rake_command_filter", "path": "lib/command_definition.rb", "func_name": "RakeCommandFilter.CommandDefinition.add_filter", "original_string": "def add_filter(id, pattern, &block)\n filter = LineFilter.new(id, pattern, block)\n @filters << filter\n end", "language": "ruby", "code": "def add_filter(id, pattern, &block)\n filter = LineFilter.new(id, pattern, block)\n @filters << filter\n end", "code_tokens": ["def", "add_filter", "(", "id", ",", "pattern", ",", "&", "block", ")", "filter", "=", "LineFilter", ".", "new", "(", "id", ",", "pattern", ",", "block", ")", "@filters", "<<", "filter", "end"], "docstring": "if a line doesn't match any of the patterns, then\n @param name a name used to identify the command in ouput\n add a new filter for output from this command\n @param id [Symbol] an identifier for the filter within the command\n @param pattern [RegEx] a regular expression which matches a pattern in a line\n @yield yields back an array of matches from the pattern. The block should return\n a CommmandDefinition#result_... variant", "docstring_tokens": ["if", "a", "line", "doesn", "t", "match", "any", "of", "the", "patterns", "then"], "sha": "0c55e58f261b088d5ba67ea3bf28e6ad8b2be68f", "url": "https://github.com/chrisjones-tripletri/rake_command_filter/blob/0c55e58f261b088d5ba67ea3bf28e6ad8b2be68f/lib/command_definition.rb#L23-L26", "partition": "test"} {"repo": "jochenseeber/mixml", "path": "lib/mixml/selection.rb", "func_name": "Mixml.Selection.write", "original_string": "def write(template = nil)\n if not template.nil? then\n template = template.to_mixml_template\n end\n\n each_node do |node|\n if template.nil? then\n node.write_xml_to($stdout)\n puts\n else\n puts template.evaluate(node)\n end\n end\n end", "language": "ruby", "code": "def write(template = nil)\n if not template.nil? then\n template = template.to_mixml_template\n end\n\n each_node do |node|\n if template.nil? then\n node.write_xml_to($stdout)\n puts\n else\n puts template.evaluate(node)\n end\n end\n end", "code_tokens": ["def", "write", "(", "template", "=", "nil", ")", "if", "not", "template", ".", "nil?", "then", "template", "=", "template", ".", "to_mixml_template", "end", "each_node", "do", "|", "node", "|", "if", "template", ".", "nil?", "then", "node", ".", "write_xml_to", "(", "$stdout", ")", "puts", "else", "puts", "template", ".", "evaluate", "(", "node", ")", "end", "end", "end"], "docstring": "Print selected nodes to stdout\n\n @param template [Template::Base] Template to evaluate and print", "docstring_tokens": ["Print", "selected", "nodes", "to", "stdout"], "sha": "0cf20b995a5d050ff533b6dec2f6fa1ddd0e3214", "url": "https://github.com/jochenseeber/mixml/blob/0cf20b995a5d050ff533b6dec2f6fa1ddd0e3214/lib/mixml/selection.rb#L27-L40", "partition": "test"} {"repo": "jochenseeber/mixml", "path": "lib/mixml/selection.rb", "func_name": "Mixml.Selection.replace", "original_string": "def replace(template)\n template = template.to_mixml_template\n\n each_node do |node|\n value = template.evaluate(node)\n node.replace(value)\n end\n end", "language": "ruby", "code": "def replace(template)\n template = template.to_mixml_template\n\n each_node do |node|\n value = template.evaluate(node)\n node.replace(value)\n end\n end", "code_tokens": ["def", "replace", "(", "template", ")", "template", "=", "template", ".", "to_mixml_template", "each_node", "do", "|", "node", "|", "value", "=", "template", ".", "evaluate", "(", "node", ")", "node", ".", "replace", "(", "value", ")", "end", "end"], "docstring": "Replace selected nodes with a template\n\n @param template [Template::Base] Template to replace nodes with", "docstring_tokens": ["Replace", "selected", "nodes", "with", "a", "template"], "sha": "0cf20b995a5d050ff533b6dec2f6fa1ddd0e3214", "url": "https://github.com/jochenseeber/mixml/blob/0cf20b995a5d050ff533b6dec2f6fa1ddd0e3214/lib/mixml/selection.rb#L45-L52", "partition": "test"} {"repo": "jochenseeber/mixml", "path": "lib/mixml/selection.rb", "func_name": "Mixml.Selection.rename", "original_string": "def rename(template)\n template = template.to_mixml_template\n\n each_node do |node|\n value = template.evaluate(node)\n node.name = value\n end\n end", "language": "ruby", "code": "def rename(template)\n template = template.to_mixml_template\n\n each_node do |node|\n value = template.evaluate(node)\n node.name = value\n end\n end", "code_tokens": ["def", "rename", "(", "template", ")", "template", "=", "template", ".", "to_mixml_template", "each_node", "do", "|", "node", "|", "value", "=", "template", ".", "evaluate", "(", "node", ")", "node", ".", "name", "=", "value", "end", "end"], "docstring": "Rename selected nodes with a template\n\n @param template [Template::Base] Template for new name", "docstring_tokens": ["Rename", "selected", "nodes", "with", "a", "template"], "sha": "0cf20b995a5d050ff533b6dec2f6fa1ddd0e3214", "url": "https://github.com/jochenseeber/mixml/blob/0cf20b995a5d050ff533b6dec2f6fa1ddd0e3214/lib/mixml/selection.rb#L81-L88", "partition": "test"} {"repo": "Dahie/caramelize", "path": "lib/caramelize/gollum_output.rb", "func_name": "Caramelize.GollumOutput.commit_revision", "original_string": "def commit_revision(page, markup)\n gollum_page = gollum.page(page.title)\n if gollum_page\n gollum.update_page(gollum_page, gollum_page.name, gollum_page.format, page.body, build_commit(page))\n else\n gollum.write_page(page.title, markup, page.body, build_commit(page))\n end\n end", "language": "ruby", "code": "def commit_revision(page, markup)\n gollum_page = gollum.page(page.title)\n if gollum_page\n gollum.update_page(gollum_page, gollum_page.name, gollum_page.format, page.body, build_commit(page))\n else\n gollum.write_page(page.title, markup, page.body, build_commit(page))\n end\n end", "code_tokens": ["def", "commit_revision", "(", "page", ",", "markup", ")", "gollum_page", "=", "gollum", ".", "page", "(", "page", ".", "title", ")", "if", "gollum_page", "gollum", ".", "update_page", "(", "gollum_page", ",", "gollum_page", ".", "name", ",", "gollum_page", ".", "format", ",", "page", ".", "body", ",", "build_commit", "(", "page", ")", ")", "else", "gollum", ".", "write_page", "(", "page", ".", "title", ",", "markup", ",", "page", ".", "body", ",", "build_commit", "(", "page", ")", ")", "end", "end"], "docstring": "Commit the given page into the gollum-wiki-repository.\n Make sure the target markup is correct before calling this method.", "docstring_tokens": ["Commit", "the", "given", "page", "into", "the", "gollum", "-", "wiki", "-", "repository", ".", "Make", "sure", "the", "target", "markup", "is", "correct", "before", "calling", "this", "method", "."], "sha": "6bb93b65924edaaf071a8b3947d0545d5759bc5d", "url": "https://github.com/Dahie/caramelize/blob/6bb93b65924edaaf071a8b3947d0545d5759bc5d/lib/caramelize/gollum_output.rb#L22-L29", "partition": "test"} {"repo": "Dahie/caramelize", "path": "lib/caramelize/gollum_output.rb", "func_name": "Caramelize.GollumOutput.commit_history", "original_string": "def commit_history(revisions, options = {}, &block)\n options[:markup] = :markdown if !options[:markup] # target markup\n revisions.each_with_index do |page, index|\n # call debug output from outside\n block.call(page, index) if block_given?\n commit_revision(page, options[:markup])\n end\n end", "language": "ruby", "code": "def commit_history(revisions, options = {}, &block)\n options[:markup] = :markdown if !options[:markup] # target markup\n revisions.each_with_index do |page, index|\n # call debug output from outside\n block.call(page, index) if block_given?\n commit_revision(page, options[:markup])\n end\n end", "code_tokens": ["def", "commit_history", "(", "revisions", ",", "options", "=", "{", "}", ",", "&", "block", ")", "options", "[", ":markup", "]", "=", ":markdown", "if", "!", "options", "[", ":markup", "]", "# target markup", "revisions", ".", "each_with_index", "do", "|", "page", ",", "index", "|", "# call debug output from outside", "block", ".", "call", "(", "page", ",", "index", ")", "if", "block_given?", "commit_revision", "(", "page", ",", "options", "[", ":markup", "]", ")", "end", "end"], "docstring": "Commit all revisions of the given history into this gollum-wiki-repository.", "docstring_tokens": ["Commit", "all", "revisions", "of", "the", "given", "history", "into", "this", "gollum", "-", "wiki", "-", "repository", "."], "sha": "6bb93b65924edaaf071a8b3947d0545d5759bc5d", "url": "https://github.com/Dahie/caramelize/blob/6bb93b65924edaaf071a8b3947d0545d5759bc5d/lib/caramelize/gollum_output.rb#L32-L39", "partition": "test"} {"repo": "PeterCamilleri/format_engine", "path": "lib/format_engine/format_spec.rb", "func_name": "FormatEngine.FormatSpec.scan_spec", "original_string": "def scan_spec(fmt_string)\r\n until fmt_string.empty?\r\n if (match_data = PARSE_REGEX.match(fmt_string))\r\n mid = match_data.to_s\r\n pre = match_data.pre_match\r\n\r\n @specs << FormatLiteral.new(pre) unless pre.empty?\r\n @specs << case\r\n when match_data[:var] then FormatVariable.new(mid)\r\n when match_data[:set] then FormatSet.new(mid)\r\n when match_data[:rgx] then FormatRgx.new(mid)\r\n when match_data[:per] then FormatLiteral.new(\"\\%\")\r\n else fail \"Impossible case in scan_spec.\"\r\n end\r\n fmt_string = match_data.post_match\r\n else\r\n @specs << FormatLiteral.new(fmt_string)\r\n fmt_string = \"\"\r\n end\r\n end\r\n end", "language": "ruby", "code": "def scan_spec(fmt_string)\r\n until fmt_string.empty?\r\n if (match_data = PARSE_REGEX.match(fmt_string))\r\n mid = match_data.to_s\r\n pre = match_data.pre_match\r\n\r\n @specs << FormatLiteral.new(pre) unless pre.empty?\r\n @specs << case\r\n when match_data[:var] then FormatVariable.new(mid)\r\n when match_data[:set] then FormatSet.new(mid)\r\n when match_data[:rgx] then FormatRgx.new(mid)\r\n when match_data[:per] then FormatLiteral.new(\"\\%\")\r\n else fail \"Impossible case in scan_spec.\"\r\n end\r\n fmt_string = match_data.post_match\r\n else\r\n @specs << FormatLiteral.new(fmt_string)\r\n fmt_string = \"\"\r\n end\r\n end\r\n end", "code_tokens": ["def", "scan_spec", "(", "fmt_string", ")", "until", "fmt_string", ".", "empty?", "if", "(", "match_data", "=", "PARSE_REGEX", ".", "match", "(", "fmt_string", ")", ")", "mid", "=", "match_data", ".", "to_s", "pre", "=", "match_data", ".", "pre_match", "@specs", "<<", "FormatLiteral", ".", "new", "(", "pre", ")", "unless", "pre", ".", "empty?", "@specs", "<<", "case", "when", "match_data", "[", ":var", "]", "then", "FormatVariable", ".", "new", "(", "mid", ")", "when", "match_data", "[", ":set", "]", "then", "FormatSet", ".", "new", "(", "mid", ")", "when", "match_data", "[", ":rgx", "]", "then", "FormatRgx", ".", "new", "(", "mid", ")", "when", "match_data", "[", ":per", "]", "then", "FormatLiteral", ".", "new", "(", "\"\\%\"", ")", "else", "fail", "\"Impossible case in scan_spec.\"", "end", "fmt_string", "=", "match_data", ".", "post_match", "else", "@specs", "<<", "FormatLiteral", ".", "new", "(", "fmt_string", ")", "fmt_string", "=", "\"\"", "end", "end", "end"], "docstring": "Scan the format string extracting literals and variables.", "docstring_tokens": ["Scan", "the", "format", "string", "extracting", "literals", "and", "variables", "."], "sha": "f8df6e44895a0bf223882cf7526d5770c8a26d03", "url": "https://github.com/PeterCamilleri/format_engine/blob/f8df6e44895a0bf223882cf7526d5770c8a26d03/lib/format_engine/format_spec.rb#L30-L50", "partition": "test"} {"repo": "Dahie/caramelize", "path": "lib/caramelize/wiki/trac_converter.rb", "func_name": "Caramelize.TracConverter.to_textile", "original_string": "def to_textile str\n body = body.dup\n body.gsub!(/\\r/, '')\n body.gsub!(/\\{\\{\\{([^\\n]+?)\\}\\}\\}/, '@\\1@')\n body.gsub!(/\\{\\{\\{\\n#!([^\\n]+?)(.+?)\\}\\}\\}/m, '
    \\2
    ')\n body.gsub!(/\\{\\{\\{(.+?)\\}\\}\\}/m, '
    \\1
    ')\n # macro\n body.gsub!(/\\[\\[BR\\]\\]/, '')\n body.gsub!(/\\[\\[PageOutline.*\\]\\]/, '{{toc}}')\n body.gsub!(/\\[\\[Image\\((.+?)\\)\\]\\]/, '!\\1!')\n # header\n body.gsub!(/=====\\s(.+?)\\s=====/, \"h5. #{'\\1'} \\n\\n\")\n body.gsub!(/====\\s(.+?)\\s====/, \"h4. #{'\\1'} \\n\\n\")\n body.gsub!(/===\\s(.+?)\\s===/, \"h3. #{'\\1'} \\n\\n\")\n body.gsub!(/==\\s(.+?)\\s==/, \"h2. #{'\\1'} \\n\\n\")\n body.gsub!(/=\\s(.+?)\\s=[\\s\\n]*/, \"h1. #{'\\1'} \\n\\n\")\n # table\n body.gsub!(/\\|\\|/, \"|\")\n # link\n body.gsub!(/\\[(http[^\\s\\[\\]]+)\\s([^\\[\\]]+)\\]/, ' \"\\2\":\\1' )\n body.gsub!(/\\[([^\\s]+)\\s(.+)\\]/, ' [[\\1 | \\2]] ')\n body.gsub!(/([^\"\\/\\!])(([A-Z][a-z0-9]+){2,})/, ' \\1[[\\2]] ')\n body.gsub!(/\\!(([A-Z][a-z0-9]+){2,})/, '\\1')\n # text decoration\n body.gsub!(/'''(.+)'''/, '*\\1*')\n body.gsub!(/''(.+)''/, '_\\1_')\n body.gsub!(/`(.+)`/, '@\\1@')\n # itemize\n body.gsub!(/^\\s\\s\\s\\*/, '***')\n body.gsub!(/^\\s\\s\\*/, '**')\n body.gsub!(/^\\s\\*/, '*')\n body.gsub!(/^\\s\\s\\s\\d\\./, '###')\n body.gsub!(/^\\s\\s\\d\\./, '##')\n body.gsub!(/^\\s\\d\\./, '#')\n body\n end", "language": "ruby", "code": "def to_textile str\n body = body.dup\n body.gsub!(/\\r/, '')\n body.gsub!(/\\{\\{\\{([^\\n]+?)\\}\\}\\}/, '@\\1@')\n body.gsub!(/\\{\\{\\{\\n#!([^\\n]+?)(.+?)\\}\\}\\}/m, '
    \\2
    ')\n body.gsub!(/\\{\\{\\{(.+?)\\}\\}\\}/m, '
    \\1
    ')\n # macro\n body.gsub!(/\\[\\[BR\\]\\]/, '')\n body.gsub!(/\\[\\[PageOutline.*\\]\\]/, '{{toc}}')\n body.gsub!(/\\[\\[Image\\((.+?)\\)\\]\\]/, '!\\1!')\n # header\n body.gsub!(/=====\\s(.+?)\\s=====/, \"h5. #{'\\1'} \\n\\n\")\n body.gsub!(/====\\s(.+?)\\s====/, \"h4. #{'\\1'} \\n\\n\")\n body.gsub!(/===\\s(.+?)\\s===/, \"h3. #{'\\1'} \\n\\n\")\n body.gsub!(/==\\s(.+?)\\s==/, \"h2. #{'\\1'} \\n\\n\")\n body.gsub!(/=\\s(.+?)\\s=[\\s\\n]*/, \"h1. #{'\\1'} \\n\\n\")\n # table\n body.gsub!(/\\|\\|/, \"|\")\n # link\n body.gsub!(/\\[(http[^\\s\\[\\]]+)\\s([^\\[\\]]+)\\]/, ' \"\\2\":\\1' )\n body.gsub!(/\\[([^\\s]+)\\s(.+)\\]/, ' [[\\1 | \\2]] ')\n body.gsub!(/([^\"\\/\\!])(([A-Z][a-z0-9]+){2,})/, ' \\1[[\\2]] ')\n body.gsub!(/\\!(([A-Z][a-z0-9]+){2,})/, '\\1')\n # text decoration\n body.gsub!(/'''(.+)'''/, '*\\1*')\n body.gsub!(/''(.+)''/, '_\\1_')\n body.gsub!(/`(.+)`/, '@\\1@')\n # itemize\n body.gsub!(/^\\s\\s\\s\\*/, '***')\n body.gsub!(/^\\s\\s\\*/, '**')\n body.gsub!(/^\\s\\*/, '*')\n body.gsub!(/^\\s\\s\\s\\d\\./, '###')\n body.gsub!(/^\\s\\s\\d\\./, '##')\n body.gsub!(/^\\s\\d\\./, '#')\n body\n end", "code_tokens": ["def", "to_textile", "str", "body", "=", "body", ".", "dup", "body", ".", "gsub!", "(", "/", "\\r", "/", ",", "''", ")", "body", ".", "gsub!", "(", "/", "\\{", "\\{", "\\{", "\\n", "\\}", "\\}", "\\}", "/", ",", "'@\\1@'", ")", "body", ".", "gsub!", "(", "/", "\\{", "\\{", "\\{", "\\n", "\\n", "\\}", "\\}", "\\}", "/m", ",", "'
    \\2
    '", ")", "body", ".", "gsub!", "(", "/", "\\{", "\\{", "\\{", "\\}", "\\}", "\\}", "/m", ",", "'
    \\1
    '", ")", "# macro", "body", ".", "gsub!", "(", "/", "\\[", "\\[", "\\]", "\\]", "/", ",", "''", ")", "body", ".", "gsub!", "(", "/", "\\[", "\\[", "\\]", "\\]", "/", ",", "'{{toc}}'", ")", "body", ".", "gsub!", "(", "/", "\\[", "\\[", "\\(", "\\)", "\\]", "\\]", "/", ",", "'!\\1!'", ")", "# header", "body", ".", "gsub!", "(", "/", "\\s", "\\s", "/", ",", "\"h5. #{'\\1'} \\n\\n\"", ")", "body", ".", "gsub!", "(", "/", "\\s", "\\s", "/", ",", "\"h4. #{'\\1'} \\n\\n\"", ")", "body", ".", "gsub!", "(", "/", "\\s", "\\s", "/", ",", "\"h3. #{'\\1'} \\n\\n\"", ")", "body", ".", "gsub!", "(", "/", "\\s", "\\s", "/", ",", "\"h2. #{'\\1'} \\n\\n\"", ")", "body", ".", "gsub!", "(", "/", "\\s", "\\s", "\\s", "\\n", "/", ",", "\"h1. #{'\\1'} \\n\\n\"", ")", "# table", "body", ".", "gsub!", "(", "/", "\\|", "\\|", "/", ",", "\"|\"", ")", "# link", "body", ".", "gsub!", "(", "/", "\\[", "\\s", "\\[", "\\]", "\\s", "\\[", "\\]", "\\]", "/", ",", "' \"\\2\":\\1'", ")", "body", ".", "gsub!", "(", "/", "\\[", "\\s", "\\s", "\\]", "/", ",", "' [[\\1 | \\2]] '", ")", "body", ".", "gsub!", "(", "/", "\\/", "\\!", "/", ",", "' \\1[[\\2]] '", ")", "body", ".", "gsub!", "(", "/", "\\!", "/", ",", "'\\1'", ")", "# text decoration", "body", ".", "gsub!", "(", "/", "/", ",", "'*\\1*'", ")", "body", ".", "gsub!", "(", "/", "/", ",", "'_\\1_'", ")", "body", ".", "gsub!", "(", "/", "/", ",", "'@\\1@'", ")", "# itemize", "body", ".", "gsub!", "(", "/", "\\s", "\\s", "\\s", "\\*", "/", ",", "'***'", ")", "body", ".", "gsub!", "(", "/", "\\s", "\\s", "\\*", "/", ",", "'**'", ")", "body", ".", "gsub!", "(", "/", "\\s", "\\*", "/", ",", "'*'", ")", "body", ".", "gsub!", "(", "/", "\\s", "\\s", "\\s", "\\d", "\\.", "/", ",", "'###'", ")", "body", ".", "gsub!", "(", "/", "\\s", "\\s", "\\d", "\\.", "/", ",", "'##'", ")", "body", ".", "gsub!", "(", "/", "\\s", "\\d", "\\.", "/", ",", "'#'", ")", "body", "end"], "docstring": "take an input stream and convert all wikka syntax to markdown syntax\n taken from 'trac_wiki_to_textile' at", "docstring_tokens": ["take", "an", "input", "stream", "and", "convert", "all", "wikka", "syntax", "to", "markdown", "syntax", "taken", "from", "trac_wiki_to_textile", "at"], "sha": "6bb93b65924edaaf071a8b3947d0545d5759bc5d", "url": "https://github.com/Dahie/caramelize/blob/6bb93b65924edaaf071a8b3947d0545d5759bc5d/lib/caramelize/wiki/trac_converter.rb#L6-L41", "partition": "test"} {"repo": "palladius/ric", "path": "lib/ric/debug.rb", "func_name": "Ric.Debug.debug2", "original_string": "def debug2(s, opts = {} )\n out = opts.fetch(:out, $stdout)\n tag = opts.fetch(:tag, '_DFLT_')\n really_write = opts.fetch(:really_write, true) # you can prevent ANY debug setting this to false\n write_always = opts.fetch(:write_always, false)\n \n raise \"ERROR: ':tags' must be an array in debug(), maybe you meant to use :tag?\" if ( opts[:tags] && opts[:tags].class != Array )\n final_str = \"#RDeb#{write_always ? '!' : ''}[#{opts[:tag] || '-'}] #{s}\"\n final_str = \"\\033[1;30m\" +final_str + \"\\033[0m\" if opts.fetch(:coloured_debug, true) # color by gray by default\n if (debug_tags_enabled? ) # tags\n puts( final_str ) if debug_tag_include?( opts )\n else # normal behaviour: if NOT tag\n puts( final_str ) if ((really_write && $DEBUG) || write_always) && ! opts[:tag]\n end\n end", "language": "ruby", "code": "def debug2(s, opts = {} )\n out = opts.fetch(:out, $stdout)\n tag = opts.fetch(:tag, '_DFLT_')\n really_write = opts.fetch(:really_write, true) # you can prevent ANY debug setting this to false\n write_always = opts.fetch(:write_always, false)\n \n raise \"ERROR: ':tags' must be an array in debug(), maybe you meant to use :tag?\" if ( opts[:tags] && opts[:tags].class != Array )\n final_str = \"#RDeb#{write_always ? '!' : ''}[#{opts[:tag] || '-'}] #{s}\"\n final_str = \"\\033[1;30m\" +final_str + \"\\033[0m\" if opts.fetch(:coloured_debug, true) # color by gray by default\n if (debug_tags_enabled? ) # tags\n puts( final_str ) if debug_tag_include?( opts )\n else # normal behaviour: if NOT tag\n puts( final_str ) if ((really_write && $DEBUG) || write_always) && ! opts[:tag]\n end\n end", "code_tokens": ["def", "debug2", "(", "s", ",", "opts", "=", "{", "}", ")", "out", "=", "opts", ".", "fetch", "(", ":out", ",", "$stdout", ")", "tag", "=", "opts", ".", "fetch", "(", ":tag", ",", "'_DFLT_'", ")", "really_write", "=", "opts", ".", "fetch", "(", ":really_write", ",", "true", ")", "# you can prevent ANY debug setting this to false", "write_always", "=", "opts", ".", "fetch", "(", ":write_always", ",", "false", ")", "raise", "\"ERROR: ':tags' must be an array in debug(), maybe you meant to use :tag?\"", "if", "(", "opts", "[", ":tags", "]", "&&", "opts", "[", ":tags", "]", ".", "class", "!=", "Array", ")", "final_str", "=", "\"#RDeb#{write_always ? '!' : ''}[#{opts[:tag] || '-'}] #{s}\"", "final_str", "=", "\"\\033[1;30m\"", "+", "final_str", "+", "\"\\033[0m\"", "if", "opts", ".", "fetch", "(", ":coloured_debug", ",", "true", ")", "# color by gray by default", "if", "(", "debug_tags_enabled?", ")", "# tags", "puts", "(", "final_str", ")", "if", "debug_tag_include?", "(", "opts", ")", "else", "# normal behaviour: if NOT tag", "puts", "(", "final_str", ")", "if", "(", "(", "really_write", "&&", "$DEBUG", ")", "||", "write_always", ")", "&&", "!", "opts", "[", ":tag", "]", "end", "end"], "docstring": "shouldnt work right now yet..", "docstring_tokens": ["shouldnt", "work", "right", "now", "yet", ".."], "sha": "3078a1d917ffbc96a87cc5090485ca948631ddfb", "url": "https://github.com/palladius/ric/blob/3078a1d917ffbc96a87cc5090485ca948631ddfb/lib/ric/debug.rb#L16-L30", "partition": "test"} {"repo": "barkerest/barkest_ssh", "path": "lib/barkest_ssh/secure_shell.rb", "func_name": "BarkestSsh.SecureShell.exec", "original_string": "def exec(command, options={}, &block)\n raise ConnectionClosed.new('Connection is closed.') unless @channel\n\n options = {\n on_non_zero_exit_code: :default\n }.merge(options || {})\n\n options[:on_non_zero_exit_code] = @options[:on_non_zero_exit_code] if options[:on_non_zero_exit_code] == :default\n\n push_buffer # store the current buffer and start a fresh buffer\n\n # buffer while also passing data to the supplied block.\n if block_given?\n buffer_input( &block )\n end\n\n # send the command and wait for the prompt to return.\n @channel.send_data command + \"\\n\"\n wait_for_prompt\n\n # return buffering to normal.\n if block_given?\n buffer_input\n end\n\n # get the output from the command, minus the trailing prompt.\n ret = command_output(command)\n\n # restore the original buffer and merge the output from the command.\n pop_merge_buffer\n\n if @options[:retrieve_exit_code]\n # get the exit code for the command.\n push_buffer\n retrieve_command = 'echo $?'\n @channel.send_data retrieve_command + \"\\n\"\n wait_for_prompt\n @last_exit_code = command_output(retrieve_command).strip.to_i\n # restore the original buffer and discard the output from this command.\n pop_discard_buffer\n\n # if we are expected to raise an error, do so.\n if options[:on_non_zero_exit_code] == :raise_error\n raise NonZeroExitCode.new(\"Exit code was #{@last_exit_code}.\") unless @last_exit_code == 0\n end\n end\n\n ret\n end", "language": "ruby", "code": "def exec(command, options={}, &block)\n raise ConnectionClosed.new('Connection is closed.') unless @channel\n\n options = {\n on_non_zero_exit_code: :default\n }.merge(options || {})\n\n options[:on_non_zero_exit_code] = @options[:on_non_zero_exit_code] if options[:on_non_zero_exit_code] == :default\n\n push_buffer # store the current buffer and start a fresh buffer\n\n # buffer while also passing data to the supplied block.\n if block_given?\n buffer_input( &block )\n end\n\n # send the command and wait for the prompt to return.\n @channel.send_data command + \"\\n\"\n wait_for_prompt\n\n # return buffering to normal.\n if block_given?\n buffer_input\n end\n\n # get the output from the command, minus the trailing prompt.\n ret = command_output(command)\n\n # restore the original buffer and merge the output from the command.\n pop_merge_buffer\n\n if @options[:retrieve_exit_code]\n # get the exit code for the command.\n push_buffer\n retrieve_command = 'echo $?'\n @channel.send_data retrieve_command + \"\\n\"\n wait_for_prompt\n @last_exit_code = command_output(retrieve_command).strip.to_i\n # restore the original buffer and discard the output from this command.\n pop_discard_buffer\n\n # if we are expected to raise an error, do so.\n if options[:on_non_zero_exit_code] == :raise_error\n raise NonZeroExitCode.new(\"Exit code was #{@last_exit_code}.\") unless @last_exit_code == 0\n end\n end\n\n ret\n end", "code_tokens": ["def", "exec", "(", "command", ",", "options", "=", "{", "}", ",", "&", "block", ")", "raise", "ConnectionClosed", ".", "new", "(", "'Connection is closed.'", ")", "unless", "@channel", "options", "=", "{", "on_non_zero_exit_code", ":", ":default", "}", ".", "merge", "(", "options", "||", "{", "}", ")", "options", "[", ":on_non_zero_exit_code", "]", "=", "@options", "[", ":on_non_zero_exit_code", "]", "if", "options", "[", ":on_non_zero_exit_code", "]", "==", ":default", "push_buffer", "# store the current buffer and start a fresh buffer", "# buffer while also passing data to the supplied block.", "if", "block_given?", "buffer_input", "(", "block", ")", "end", "# send the command and wait for the prompt to return.", "@channel", ".", "send_data", "command", "+", "\"\\n\"", "wait_for_prompt", "# return buffering to normal.", "if", "block_given?", "buffer_input", "end", "# get the output from the command, minus the trailing prompt.", "ret", "=", "command_output", "(", "command", ")", "# restore the original buffer and merge the output from the command.", "pop_merge_buffer", "if", "@options", "[", ":retrieve_exit_code", "]", "# get the exit code for the command.", "push_buffer", "retrieve_command", "=", "'echo $?'", "@channel", ".", "send_data", "retrieve_command", "+", "\"\\n\"", "wait_for_prompt", "@last_exit_code", "=", "command_output", "(", "retrieve_command", ")", ".", "strip", ".", "to_i", "# restore the original buffer and discard the output from this command.", "pop_discard_buffer", "# if we are expected to raise an error, do so.", "if", "options", "[", ":on_non_zero_exit_code", "]", "==", ":raise_error", "raise", "NonZeroExitCode", ".", "new", "(", "\"Exit code was #{@last_exit_code}.\"", ")", "unless", "@last_exit_code", "==", "0", "end", "end", "ret", "end"], "docstring": "Executes a command during the shell session.\n\n If called outside of the +new+ block, this will raise an error.\n\n The +command+ is the command to execute in the shell.\n\n The +options+ parameter can include the following keys.\n * The :on_non_zero_exit_code option can be :default, :ignore, or :raise_error.\n\n If provided, the +block+ is a chunk of code that will be processed every time the\n shell receives output from the program. If the block returns a string, the string\n will be sent to the shell. This can be used to monitor processes or monitor and\n interact with processes. The +block+ is optional.\n\n shell.exec('sudo -p \"password:\" nginx restart') do |data,type|\n return 'super-secret' if /password:$/.match(data)\n nil\n end", "docstring_tokens": ["Executes", "a", "command", "during", "the", "shell", "session", "."], "sha": "605f8dc697a7ad0794949054f6fc360c00b2e54e", "url": "https://github.com/barkerest/barkest_ssh/blob/605f8dc697a7ad0794949054f6fc360c00b2e54e/lib/barkest_ssh/secure_shell.rb#L224-L272", "partition": "test"} {"repo": "barkerest/barkest_ssh", "path": "lib/barkest_ssh/secure_shell.rb", "func_name": "BarkestSsh.SecureShell.upload", "original_string": "def upload(local_file, remote_file)\n raise ConnectionClosed.new('Connection is closed.') unless @ssh\n sftp.upload!(local_file, remote_file)\n end", "language": "ruby", "code": "def upload(local_file, remote_file)\n raise ConnectionClosed.new('Connection is closed.') unless @ssh\n sftp.upload!(local_file, remote_file)\n end", "code_tokens": ["def", "upload", "(", "local_file", ",", "remote_file", ")", "raise", "ConnectionClosed", ".", "new", "(", "'Connection is closed.'", ")", "unless", "@ssh", "sftp", ".", "upload!", "(", "local_file", ",", "remote_file", ")", "end"], "docstring": "Uses SFTP to upload a single file to the host.", "docstring_tokens": ["Uses", "SFTP", "to", "upload", "a", "single", "file", "to", "the", "host", "."], "sha": "605f8dc697a7ad0794949054f6fc360c00b2e54e", "url": "https://github.com/barkerest/barkest_ssh/blob/605f8dc697a7ad0794949054f6fc360c00b2e54e/lib/barkest_ssh/secure_shell.rb#L322-L325", "partition": "test"} {"repo": "barkerest/barkest_ssh", "path": "lib/barkest_ssh/secure_shell.rb", "func_name": "BarkestSsh.SecureShell.download", "original_string": "def download(remote_file, local_file)\n raise ConnectionClosed.new('Connection is closed.') unless @ssh\n sftp.download!(remote_file, local_file)\n end", "language": "ruby", "code": "def download(remote_file, local_file)\n raise ConnectionClosed.new('Connection is closed.') unless @ssh\n sftp.download!(remote_file, local_file)\n end", "code_tokens": ["def", "download", "(", "remote_file", ",", "local_file", ")", "raise", "ConnectionClosed", ".", "new", "(", "'Connection is closed.'", ")", "unless", "@ssh", "sftp", ".", "download!", "(", "remote_file", ",", "local_file", ")", "end"], "docstring": "Uses SFTP to download a single file from the host.", "docstring_tokens": ["Uses", "SFTP", "to", "download", "a", "single", "file", "from", "the", "host", "."], "sha": "605f8dc697a7ad0794949054f6fc360c00b2e54e", "url": "https://github.com/barkerest/barkest_ssh/blob/605f8dc697a7ad0794949054f6fc360c00b2e54e/lib/barkest_ssh/secure_shell.rb#L329-L332", "partition": "test"} {"repo": "barkerest/barkest_ssh", "path": "lib/barkest_ssh/secure_shell.rb", "func_name": "BarkestSsh.SecureShell.write_file", "original_string": "def write_file(remote_file, data)\n raise ConnectionClosed.new('Connection is closed.') unless @ssh\n sftp.file.open(remote_file, 'w') do |f|\n f.write data\n end\n end", "language": "ruby", "code": "def write_file(remote_file, data)\n raise ConnectionClosed.new('Connection is closed.') unless @ssh\n sftp.file.open(remote_file, 'w') do |f|\n f.write data\n end\n end", "code_tokens": ["def", "write_file", "(", "remote_file", ",", "data", ")", "raise", "ConnectionClosed", ".", "new", "(", "'Connection is closed.'", ")", "unless", "@ssh", "sftp", ".", "file", ".", "open", "(", "remote_file", ",", "'w'", ")", "do", "|", "f", "|", "f", ".", "write", "data", "end", "end"], "docstring": "Uses SFTP to write data to a single file.", "docstring_tokens": ["Uses", "SFTP", "to", "write", "data", "to", "a", "single", "file", "."], "sha": "605f8dc697a7ad0794949054f6fc360c00b2e54e", "url": "https://github.com/barkerest/barkest_ssh/blob/605f8dc697a7ad0794949054f6fc360c00b2e54e/lib/barkest_ssh/secure_shell.rb#L345-L350", "partition": "test"} {"repo": "megamoose/gpsutils", "path": "lib/gpsutils.rb", "func_name": "GpsUtils.Point.distance", "original_string": "def distance(other)\n\t\t\tunless other.is_a? Point\n\t\t\t\traise ArgumentError.new 'other must be a Point.'\n\t\t\tend\n\n\t\t\tdlng = GpsUtils::to_radians(other.lng - @lng)\n\t\t\tdlat = GpsUtils::to_radians(other.lat - @lat)\n\n\t\t\tx = dlng * Math.cos(dlat / 2)\n\t\t\ty = GpsUtils::to_radians(other.lat - @lat)\n\n\t\t\tMath.sqrt(x**2 + y**2) * GpsUtils::R\n\t\tend", "language": "ruby", "code": "def distance(other)\n\t\t\tunless other.is_a? Point\n\t\t\t\traise ArgumentError.new 'other must be a Point.'\n\t\t\tend\n\n\t\t\tdlng = GpsUtils::to_radians(other.lng - @lng)\n\t\t\tdlat = GpsUtils::to_radians(other.lat - @lat)\n\n\t\t\tx = dlng * Math.cos(dlat / 2)\n\t\t\ty = GpsUtils::to_radians(other.lat - @lat)\n\n\t\t\tMath.sqrt(x**2 + y**2) * GpsUtils::R\n\t\tend", "code_tokens": ["def", "distance", "(", "other", ")", "unless", "other", ".", "is_a?", "Point", "raise", "ArgumentError", ".", "new", "'other must be a Point.'", "end", "dlng", "=", "GpsUtils", "::", "to_radians", "(", "other", ".", "lng", "-", "@lng", ")", "dlat", "=", "GpsUtils", "::", "to_radians", "(", "other", ".", "lat", "-", "@lat", ")", "x", "=", "dlng", "*", "Math", ".", "cos", "(", "dlat", "/", "2", ")", "y", "=", "GpsUtils", "::", "to_radians", "(", "other", ".", "lat", "-", "@lat", ")", "Math", ".", "sqrt", "(", "x", "**", "2", "+", "y", "**", "2", ")", "*", "GpsUtils", "::", "R", "end"], "docstring": "Measure the distance between this point and another.\n\n Distance is calculated using equirectangular projection.\n @see https://en.wikipedia.org/wiki/Equirectangular_projection\n\n @param other [Point]\n @return [Float]\n @raise [ArgumentError] if other is not a Point", "docstring_tokens": ["Measure", "the", "distance", "between", "this", "point", "and", "another", "."], "sha": "77db6e2c47c1237a687abe05e52f1717fed364b1", "url": "https://github.com/megamoose/gpsutils/blob/77db6e2c47c1237a687abe05e52f1717fed364b1/lib/gpsutils.rb#L52-L64", "partition": "test"} {"repo": "megamoose/gpsutils", "path": "lib/gpsutils.rb", "func_name": "GpsUtils.BoundingBox.cover?", "original_string": "def cover?(point)\n\t\t\tp = [point.lat - @nw.lat, point.lng - @se.lng]\n\n\t\t\tp21x = p[0] * @p21\n\t\t\tp41x = p[1] * @p41\n\n\t\t\t0 < p21x and p21x < @p21ms and 0 <= p41x and p41x <= @p41ms\n\t\tend", "language": "ruby", "code": "def cover?(point)\n\t\t\tp = [point.lat - @nw.lat, point.lng - @se.lng]\n\n\t\t\tp21x = p[0] * @p21\n\t\t\tp41x = p[1] * @p41\n\n\t\t\t0 < p21x and p21x < @p21ms and 0 <= p41x and p41x <= @p41ms\n\t\tend", "code_tokens": ["def", "cover?", "(", "point", ")", "p", "=", "[", "point", ".", "lat", "-", "@nw", ".", "lat", ",", "point", ".", "lng", "-", "@se", ".", "lng", "]", "p21x", "=", "p", "[", "0", "]", "*", "@p21", "p41x", "=", "p", "[", "1", "]", "*", "@p41", "0", "<", "p21x", "and", "p21x", "<", "@p21ms", "and", "0", "<=", "p41x", "and", "p41x", "<=", "@p41ms", "end"], "docstring": "Initialize BoundingBox.\n\n @param nw_point [Point] North-West corner\n @param se_point [Point] South-East corner\n Determine whether point is inside bounding box.\n\n @param point [Point]", "docstring_tokens": ["Initialize", "BoundingBox", "."], "sha": "77db6e2c47c1237a687abe05e52f1717fed364b1", "url": "https://github.com/megamoose/gpsutils/blob/77db6e2c47c1237a687abe05e52f1717fed364b1/lib/gpsutils.rb#L103-L110", "partition": "test"} {"repo": "dcu/mongomapper_ext", "path": "lib/mongomapper_ext/paginator.rb", "func_name": "MongoMapperExt.Paginator.send", "original_string": "def send(method, *args, &block)\n if respond_to?(method)\n super\n else\n subject.send(method, *args, &block)\n end\n end", "language": "ruby", "code": "def send(method, *args, &block)\n if respond_to?(method)\n super\n else\n subject.send(method, *args, &block)\n end\n end", "code_tokens": ["def", "send", "(", "method", ",", "*", "args", ",", "&", "block", ")", "if", "respond_to?", "(", "method", ")", "super", "else", "subject", ".", "send", "(", "method", ",", "args", ",", "block", ")", "end", "end"], "docstring": "for will paginate support", "docstring_tokens": ["for", "will", "paginate", "support"], "sha": "ef82e95339cd039b3146a86a763053f89f9aef10", "url": "https://github.com/dcu/mongomapper_ext/blob/ef82e95339cd039b3146a86a763053f89f9aef10/lib/mongomapper_ext/paginator.rb#L37-L43", "partition": "test"} {"repo": "chrisjones-tripletri/rake_command_filter", "path": "lib/line_filter_result.rb", "func_name": "RakeCommandFilter.LineFilterResult.output", "original_string": "def output(elapsed)\n case @result\n when MATCH_SUCCESS\n color = :green\n header = 'OK'\n when MATCH_FAILURE\n color = :red\n header = 'FAIL'\n when MATCH_WARNING\n color = :light_red\n header = 'WARN'\n end\n header = header.ljust(12).colorize(color)\n str_elapsed = \"#{elapsed.round(2)}s\"\n name = @name.to_s[0..17]\n puts \"#{header} #{name.ljust(20)} #{str_elapsed.ljust(9)} #{@message}\"\n end", "language": "ruby", "code": "def output(elapsed)\n case @result\n when MATCH_SUCCESS\n color = :green\n header = 'OK'\n when MATCH_FAILURE\n color = :red\n header = 'FAIL'\n when MATCH_WARNING\n color = :light_red\n header = 'WARN'\n end\n header = header.ljust(12).colorize(color)\n str_elapsed = \"#{elapsed.round(2)}s\"\n name = @name.to_s[0..17]\n puts \"#{header} #{name.ljust(20)} #{str_elapsed.ljust(9)} #{@message}\"\n end", "code_tokens": ["def", "output", "(", "elapsed", ")", "case", "@result", "when", "MATCH_SUCCESS", "color", "=", ":green", "header", "=", "'OK'", "when", "MATCH_FAILURE", "color", "=", ":red", "header", "=", "'FAIL'", "when", "MATCH_WARNING", "color", "=", ":light_red", "header", "=", "'WARN'", "end", "header", "=", "header", ".", "ljust", "(", "12", ")", ".", "colorize", "(", "color", ")", "str_elapsed", "=", "\"#{elapsed.round(2)}s\"", "name", "=", "@name", ".", "to_s", "[", "0", "..", "17", "]", "puts", "\"#{header} #{name.ljust(20)} #{str_elapsed.ljust(9)} #{@message}\"", "end"], "docstring": "Called to output the result to the console.\n @param elapsed the time running the command so far\n rubocop:disable MethodLength", "docstring_tokens": ["Called", "to", "output", "the", "result", "to", "the", "console", "."], "sha": "0c55e58f261b088d5ba67ea3bf28e6ad8b2be68f", "url": "https://github.com/chrisjones-tripletri/rake_command_filter/blob/0c55e58f261b088d5ba67ea3bf28e6ad8b2be68f/lib/line_filter_result.rb#L52-L68", "partition": "test"} {"repo": "vpereira/bugzilla", "path": "lib/bugzilla/user.rb", "func_name": "Bugzilla.User.get_userinfo", "original_string": "def get_userinfo(user)\n p = {}\n ids = []\n names = []\n\n if user.is_a?(Array)\n user.each do |u|\n names << u if u.is_a?(String)\n id << u if u.is_a?(Integer)\n end\n elsif user.is_a?(String)\n names << user\n elsif user.is_a?(Integer)\n ids << user\n else\n raise ArgumentError, format('Unknown type of arguments: %s', user.class)\n end\n\n result = get('ids' => ids, 'names' => names)\n\n result['users']\n end", "language": "ruby", "code": "def get_userinfo(user)\n p = {}\n ids = []\n names = []\n\n if user.is_a?(Array)\n user.each do |u|\n names << u if u.is_a?(String)\n id << u if u.is_a?(Integer)\n end\n elsif user.is_a?(String)\n names << user\n elsif user.is_a?(Integer)\n ids << user\n else\n raise ArgumentError, format('Unknown type of arguments: %s', user.class)\n end\n\n result = get('ids' => ids, 'names' => names)\n\n result['users']\n end", "code_tokens": ["def", "get_userinfo", "(", "user", ")", "p", "=", "{", "}", "ids", "=", "[", "]", "names", "=", "[", "]", "if", "user", ".", "is_a?", "(", "Array", ")", "user", ".", "each", "do", "|", "u", "|", "names", "<<", "u", "if", "u", ".", "is_a?", "(", "String", ")", "id", "<<", "u", "if", "u", ".", "is_a?", "(", "Integer", ")", "end", "elsif", "user", ".", "is_a?", "(", "String", ")", "names", "<<", "user", "elsif", "user", ".", "is_a?", "(", "Integer", ")", "ids", "<<", "user", "else", "raise", "ArgumentError", ",", "format", "(", "'Unknown type of arguments: %s'", ",", "user", ".", "class", ")", "end", "result", "=", "get", "(", "'ids'", "=>", "ids", ",", "'names'", "=>", "names", ")", "result", "[", "'users'", "]", "end"], "docstring": "def session\n rdoc\n\n ==== Bugzilla::User#get_userinfo(params)", "docstring_tokens": ["def", "session", "rdoc"], "sha": "6832b6741adacbff7d177467325822dd90424a9d", "url": "https://github.com/vpereira/bugzilla/blob/6832b6741adacbff7d177467325822dd90424a9d/lib/bugzilla/user.rb#L78-L99", "partition": "test"} {"repo": "avillafiorita/dreader", "path": "lib/dreader.rb", "func_name": "Dreader.Engine.options", "original_string": "def options &block\n options = Options.new\n options.instance_eval(&block)\n\n @options = options.to_hash\n end", "language": "ruby", "code": "def options &block\n options = Options.new\n options.instance_eval(&block)\n\n @options = options.to_hash\n end", "code_tokens": ["def", "options", "&", "block", "options", "=", "Options", ".", "new", "options", ".", "instance_eval", "(", "block", ")", "@options", "=", "options", ".", "to_hash", "end"], "docstring": "define a DSL for options\n any string is processed as an option and it ends up in the\n @options hash", "docstring_tokens": ["define", "a", "DSL", "for", "options", "any", "string", "is", "processed", "as", "an", "option", "and", "it", "ends", "up", "in", "the"], "sha": "d2ed928ccaa1e35d34404a63cb65c17862aaf4ac", "url": "https://github.com/avillafiorita/dreader/blob/d2ed928ccaa1e35d34404a63cb65c17862aaf4ac/lib/dreader.rb#L120-L125", "partition": "test"} {"repo": "avillafiorita/dreader", "path": "lib/dreader.rb", "func_name": "Dreader.Engine.column", "original_string": "def column name, &block\n column = Column.new\n column.instance_eval(&block)\n\n @colspec << column.to_hash.merge({name: name})\n end", "language": "ruby", "code": "def column name, &block\n column = Column.new\n column.instance_eval(&block)\n\n @colspec << column.to_hash.merge({name: name})\n end", "code_tokens": ["def", "column", "name", ",", "&", "block", "column", "=", "Column", ".", "new", "column", ".", "instance_eval", "(", "block", ")", "@colspec", "<<", "column", ".", "to_hash", ".", "merge", "(", "{", "name", ":", "name", "}", ")", "end"], "docstring": "define a DSL for column specification\n - `name` is the name of the column\n - `block` contains two declarations, `process` and `check`, which are\n used, respectively, to make a cell into the desired data and to check\n whether the desired data is ok", "docstring_tokens": ["define", "a", "DSL", "for", "column", "specification", "-", "name", "is", "the", "name", "of", "the", "column", "-", "block", "contains", "two", "declarations", "process", "and", "check", "which", "are", "used", "respectively", "to", "make", "a", "cell", "into", "the", "desired", "data", "and", "to", "check", "whether", "the", "desired", "data", "is", "ok"], "sha": "d2ed928ccaa1e35d34404a63cb65c17862aaf4ac", "url": "https://github.com/avillafiorita/dreader/blob/d2ed928ccaa1e35d34404a63cb65c17862aaf4ac/lib/dreader.rb#L132-L137", "partition": "test"} {"repo": "avillafiorita/dreader", "path": "lib/dreader.rb", "func_name": "Dreader.Engine.bulk_declare", "original_string": "def bulk_declare hash, &block \n hash.keys.each do |key|\n column = Column.new\n column.colref hash[key]\n if block\n column.instance_eval(&block)\n end\n @colspec << column.to_hash.merge({name: key})\n end\n end", "language": "ruby", "code": "def bulk_declare hash, &block \n hash.keys.each do |key|\n column = Column.new\n column.colref hash[key]\n if block\n column.instance_eval(&block)\n end\n @colspec << column.to_hash.merge({name: key})\n end\n end", "code_tokens": ["def", "bulk_declare", "hash", ",", "&", "block", "hash", ".", "keys", ".", "each", "do", "|", "key", "|", "column", "=", "Column", ".", "new", "column", ".", "colref", "hash", "[", "key", "]", "if", "block", "column", ".", "instance_eval", "(", "block", ")", "end", "@colspec", "<<", "column", ".", "to_hash", ".", "merge", "(", "{", "name", ":", "key", "}", ")", "end", "end"], "docstring": "bulk declare columns we intend to read\n\n - hash is a hash in the form { symbolic_name: colref }\n\n i.bulk_declare {name: 'B', age: 'C'} is equivalent to:\n\n i.column :name do\n colref 'B'\n end\n i.column :age do\n colref 'C'\n end\n\n i.bulk_declare {name: 'B', age: 'C'} do\n process do |cell|\n cell.strip\n end\n end\n\n is equivalent to:\n\n i.column :name do\n colref 'B'\n process do |cell|\n cell.strip\n end\n end\n i.column :age do\n colref 'C'\n process do |cell|\n cell.strip\n end\n end", "docstring_tokens": ["bulk", "declare", "columns", "we", "intend", "to", "read"], "sha": "d2ed928ccaa1e35d34404a63cb65c17862aaf4ac", "url": "https://github.com/avillafiorita/dreader/blob/d2ed928ccaa1e35d34404a63cb65c17862aaf4ac/lib/dreader.rb#L172-L181", "partition": "test"} {"repo": "avillafiorita/dreader", "path": "lib/dreader.rb", "func_name": "Dreader.Engine.read", "original_string": "def read args = {}\n if args.class == Hash\n hash = @options.merge(args)\n else\n puts \"dreader error at #{__callee__}: this function takes a Hash as input\"\n exit\n end\n\n spreadsheet = Dreader::Engine.open_spreadsheet (hash[:filename])\n sheet = spreadsheet.sheet(hash[:sheet] || 0)\n\n @table = Array.new\n @errors = Array.new\n\n first_row = hash[:first_row] || 1\n last_row = hash[:last_row] || sheet.last_row\n\n (first_row..last_row).each do |row_number|\n r = Hash.new\n @colspec.each_with_index do |colspec, index|\n cell = sheet.cell(row_number, colspec[:colref])\n \n colname = colspec[:name]\n\n r[colname] = Hash.new\n r[colname][:row_number] = row_number\n r[colname][:col_number] = colspec[:colref]\n\n begin\n r[colname][:value] = value = colspec[:process] ? colspec[:process].call(cell) : cell\n rescue => e\n puts \"dreader error at #{__callee__}: 'process' specification for :#{colname} raised an exception at row #{row_number} (col #{index + 1}, value: #{cell})\"\n raise e\n end\n\n begin\n if colspec[:check] and not colspec[:check].call(value) then\n r[colname][:error] = true\n @errors << \"dreader error at #{__callee__}: value \\\"#{cell}\\\" for #{colname} at row #{row_number} (col #{index + 1}) does not pass the check function\"\n else\n r[colname][:error] = false\n end\n rescue => e\n puts \"dreader error at #{__callee__}: 'check' specification for :#{colname} raised an exception at row #{row_number} (col #{index + 1}, value: #{cell})\"\n raise e\n end\n end\n\n @table << r\n end\n\n @table\n end", "language": "ruby", "code": "def read args = {}\n if args.class == Hash\n hash = @options.merge(args)\n else\n puts \"dreader error at #{__callee__}: this function takes a Hash as input\"\n exit\n end\n\n spreadsheet = Dreader::Engine.open_spreadsheet (hash[:filename])\n sheet = spreadsheet.sheet(hash[:sheet] || 0)\n\n @table = Array.new\n @errors = Array.new\n\n first_row = hash[:first_row] || 1\n last_row = hash[:last_row] || sheet.last_row\n\n (first_row..last_row).each do |row_number|\n r = Hash.new\n @colspec.each_with_index do |colspec, index|\n cell = sheet.cell(row_number, colspec[:colref])\n \n colname = colspec[:name]\n\n r[colname] = Hash.new\n r[colname][:row_number] = row_number\n r[colname][:col_number] = colspec[:colref]\n\n begin\n r[colname][:value] = value = colspec[:process] ? colspec[:process].call(cell) : cell\n rescue => e\n puts \"dreader error at #{__callee__}: 'process' specification for :#{colname} raised an exception at row #{row_number} (col #{index + 1}, value: #{cell})\"\n raise e\n end\n\n begin\n if colspec[:check] and not colspec[:check].call(value) then\n r[colname][:error] = true\n @errors << \"dreader error at #{__callee__}: value \\\"#{cell}\\\" for #{colname} at row #{row_number} (col #{index + 1}) does not pass the check function\"\n else\n r[colname][:error] = false\n end\n rescue => e\n puts \"dreader error at #{__callee__}: 'check' specification for :#{colname} raised an exception at row #{row_number} (col #{index + 1}, value: #{cell})\"\n raise e\n end\n end\n\n @table << r\n end\n\n @table\n end", "code_tokens": ["def", "read", "args", "=", "{", "}", "if", "args", ".", "class", "==", "Hash", "hash", "=", "@options", ".", "merge", "(", "args", ")", "else", "puts", "\"dreader error at #{__callee__}: this function takes a Hash as input\"", "exit", "end", "spreadsheet", "=", "Dreader", "::", "Engine", ".", "open_spreadsheet", "(", "hash", "[", ":filename", "]", ")", "sheet", "=", "spreadsheet", ".", "sheet", "(", "hash", "[", ":sheet", "]", "||", "0", ")", "@table", "=", "Array", ".", "new", "@errors", "=", "Array", ".", "new", "first_row", "=", "hash", "[", ":first_row", "]", "||", "1", "last_row", "=", "hash", "[", ":last_row", "]", "||", "sheet", ".", "last_row", "(", "first_row", "..", "last_row", ")", ".", "each", "do", "|", "row_number", "|", "r", "=", "Hash", ".", "new", "@colspec", ".", "each_with_index", "do", "|", "colspec", ",", "index", "|", "cell", "=", "sheet", ".", "cell", "(", "row_number", ",", "colspec", "[", ":colref", "]", ")", "colname", "=", "colspec", "[", ":name", "]", "r", "[", "colname", "]", "=", "Hash", ".", "new", "r", "[", "colname", "]", "[", ":row_number", "]", "=", "row_number", "r", "[", "colname", "]", "[", ":col_number", "]", "=", "colspec", "[", ":colref", "]", "begin", "r", "[", "colname", "]", "[", ":value", "]", "=", "value", "=", "colspec", "[", ":process", "]", "?", "colspec", "[", ":process", "]", ".", "call", "(", "cell", ")", ":", "cell", "rescue", "=>", "e", "puts", "\"dreader error at #{__callee__}: 'process' specification for :#{colname} raised an exception at row #{row_number} (col #{index + 1}, value: #{cell})\"", "raise", "e", "end", "begin", "if", "colspec", "[", ":check", "]", "and", "not", "colspec", "[", ":check", "]", ".", "call", "(", "value", ")", "then", "r", "[", "colname", "]", "[", ":error", "]", "=", "true", "@errors", "<<", "\"dreader error at #{__callee__}: value \\\"#{cell}\\\" for #{colname} at row #{row_number} (col #{index + 1}) does not pass the check function\"", "else", "r", "[", "colname", "]", "[", ":error", "]", "=", "false", "end", "rescue", "=>", "e", "puts", "\"dreader error at #{__callee__}: 'check' specification for :#{colname} raised an exception at row #{row_number} (col #{index + 1}, value: #{cell})\"", "raise", "e", "end", "end", "@table", "<<", "r", "end", "@table", "end"], "docstring": "read a file and store it internally\n\n @param hash, a hash, possibly overriding any of the parameters\n set in the initial options. This allows you, for\n instance, to apply the same column specification to\n different files and different sheets\n\n @return the data read from filename, in the form of an array of\n hashes", "docstring_tokens": ["read", "a", "file", "and", "store", "it", "internally"], "sha": "d2ed928ccaa1e35d34404a63cb65c17862aaf4ac", "url": "https://github.com/avillafiorita/dreader/blob/d2ed928ccaa1e35d34404a63cb65c17862aaf4ac/lib/dreader.rb#L215-L267", "partition": "test"} {"repo": "jiaola/omelette", "path": "lib/omelette/util.rb", "func_name": "Omelette.Util.backtrace_lineno_for_config", "original_string": "def backtrace_lineno_for_config(file_path, exception)\n # For a SyntaxError, we really need to grep it from the\n # exception message, it really appears to be nowhere else. Ugh.\n if exception.kind_of? SyntaxError\n if m = /:(\\d+):/.match(exception.message)\n return m[1].to_i\n end\n end\n\n # Otherwise we try to fish it out of the backtrace, first\n # line matching the config file path.\n\n # exception.backtrace_locations exists in MRI 2.1+, which makes\n # our task a lot easier. But not yet in JRuby 1.7.x, so we got to\n # handle the old way of having to parse the strings in backtrace too.\n if (exception.respond_to?(:backtrace_locations) &&\n exception.backtrace_locations &&\n exception.backtrace_locations.length > 0)\n location = exception.backtrace_locations.find do |bt|\n bt.path == file_path\n end\n return location ? location.lineno : nil\n else # have to parse string backtrace\n exception.backtrace.each do |line|\n if line.start_with?(file_path)\n if m = /\\A.*\\:(\\d+)\\:in/.match(line)\n return m[1].to_i\n break\n end\n end\n end\n # if we got here, we have nothing\n return nil\n end\n end", "language": "ruby", "code": "def backtrace_lineno_for_config(file_path, exception)\n # For a SyntaxError, we really need to grep it from the\n # exception message, it really appears to be nowhere else. Ugh.\n if exception.kind_of? SyntaxError\n if m = /:(\\d+):/.match(exception.message)\n return m[1].to_i\n end\n end\n\n # Otherwise we try to fish it out of the backtrace, first\n # line matching the config file path.\n\n # exception.backtrace_locations exists in MRI 2.1+, which makes\n # our task a lot easier. But not yet in JRuby 1.7.x, so we got to\n # handle the old way of having to parse the strings in backtrace too.\n if (exception.respond_to?(:backtrace_locations) &&\n exception.backtrace_locations &&\n exception.backtrace_locations.length > 0)\n location = exception.backtrace_locations.find do |bt|\n bt.path == file_path\n end\n return location ? location.lineno : nil\n else # have to parse string backtrace\n exception.backtrace.each do |line|\n if line.start_with?(file_path)\n if m = /\\A.*\\:(\\d+)\\:in/.match(line)\n return m[1].to_i\n break\n end\n end\n end\n # if we got here, we have nothing\n return nil\n end\n end", "code_tokens": ["def", "backtrace_lineno_for_config", "(", "file_path", ",", "exception", ")", "# For a SyntaxError, we really need to grep it from the", "# exception message, it really appears to be nowhere else. Ugh.", "if", "exception", ".", "kind_of?", "SyntaxError", "if", "m", "=", "/", "\\d", "/", ".", "match", "(", "exception", ".", "message", ")", "return", "m", "[", "1", "]", ".", "to_i", "end", "end", "# Otherwise we try to fish it out of the backtrace, first", "# line matching the config file path.", "# exception.backtrace_locations exists in MRI 2.1+, which makes", "# our task a lot easier. But not yet in JRuby 1.7.x, so we got to", "# handle the old way of having to parse the strings in backtrace too.", "if", "(", "exception", ".", "respond_to?", "(", ":backtrace_locations", ")", "&&", "exception", ".", "backtrace_locations", "&&", "exception", ".", "backtrace_locations", ".", "length", ">", "0", ")", "location", "=", "exception", ".", "backtrace_locations", ".", "find", "do", "|", "bt", "|", "bt", ".", "path", "==", "file_path", "end", "return", "location", "?", "location", ".", "lineno", ":", "nil", "else", "# have to parse string backtrace", "exception", ".", "backtrace", ".", "each", "do", "|", "line", "|", "if", "line", ".", "start_with?", "(", "file_path", ")", "if", "m", "=", "/", "\\A", "\\:", "\\d", "\\:", "/", ".", "match", "(", "line", ")", "return", "m", "[", "1", "]", ".", "to_i", "break", "end", "end", "end", "# if we got here, we have nothing", "return", "nil", "end", "end"], "docstring": "Provide a config source file path, and an exception.\n\n Returns the line number from the first line in the stack\n trace of the exception that matches your file path.\n of the first line in the backtrace matching that file_path.\n\n Returns `nil` if no suitable backtrace line can be found.\n\n Has special logic to try and grep the info out of a SyntaxError, bah.", "docstring_tokens": ["Provide", "a", "config", "source", "file", "path", "and", "an", "exception", "."], "sha": "4faa44c21350fa2ae7415c66cdf11c541564a975", "url": "https://github.com/jiaola/omelette/blob/4faa44c21350fa2ae7415c66cdf11c541564a975/lib/omelette/util.rb#L39-L73", "partition": "test"} {"repo": "jiaola/omelette", "path": "lib/omelette/util.rb", "func_name": "Omelette.Util.backtrace_from_config", "original_string": "def backtrace_from_config(file_path, exception)\n filtered_trace = []\n found = false\n\n # MRI 2.1+ has exception.backtrace_locations which makes\n # this a lot easier, but JRuby 1.7.x doesn't yet, so we\n # need to do it both ways.\n if (exception.respond_to?(:backtrace_locations) &&\n exception.backtrace_locations &&\n exception.backtrace_locations.length > 0)\n\n exception.backtrace_locations.each do |location|\n filtered_trace << location\n (found=true and break) if location.path == file_path\n end\n else\n filtered_trace = []\n exception.backtrace.each do |line|\n filtered_trace << line\n (found=true and break) if line.start_with?(file_path)\n end\n end\n\n return found ? filtered_trace : []\n end", "language": "ruby", "code": "def backtrace_from_config(file_path, exception)\n filtered_trace = []\n found = false\n\n # MRI 2.1+ has exception.backtrace_locations which makes\n # this a lot easier, but JRuby 1.7.x doesn't yet, so we\n # need to do it both ways.\n if (exception.respond_to?(:backtrace_locations) &&\n exception.backtrace_locations &&\n exception.backtrace_locations.length > 0)\n\n exception.backtrace_locations.each do |location|\n filtered_trace << location\n (found=true and break) if location.path == file_path\n end\n else\n filtered_trace = []\n exception.backtrace.each do |line|\n filtered_trace << line\n (found=true and break) if line.start_with?(file_path)\n end\n end\n\n return found ? filtered_trace : []\n end", "code_tokens": ["def", "backtrace_from_config", "(", "file_path", ",", "exception", ")", "filtered_trace", "=", "[", "]", "found", "=", "false", "# MRI 2.1+ has exception.backtrace_locations which makes", "# this a lot easier, but JRuby 1.7.x doesn't yet, so we", "# need to do it both ways.", "if", "(", "exception", ".", "respond_to?", "(", ":backtrace_locations", ")", "&&", "exception", ".", "backtrace_locations", "&&", "exception", ".", "backtrace_locations", ".", "length", ">", "0", ")", "exception", ".", "backtrace_locations", ".", "each", "do", "|", "location", "|", "filtered_trace", "<<", "location", "(", "found", "=", "true", "and", "break", ")", "if", "location", ".", "path", "==", "file_path", "end", "else", "filtered_trace", "=", "[", "]", "exception", ".", "backtrace", ".", "each", "do", "|", "line", "|", "filtered_trace", "<<", "line", "(", "found", "=", "true", "and", "break", ")", "if", "line", ".", "start_with?", "(", "file_path", ")", "end", "end", "return", "found", "?", "filtered_trace", ":", "[", "]", "end"], "docstring": "Extract just the part of the backtrace that is \"below\"\n the config file mentioned. If we can't find the config file\n in the stack trace, we might return empty array.\n\n If the ruby supports Exception#backtrace_locations, the\n returned array will actually be of Thread::Backtrace::Location elements.", "docstring_tokens": ["Extract", "just", "the", "part", "of", "the", "backtrace", "that", "is", "below", "the", "config", "file", "mentioned", ".", "If", "we", "can", "t", "find", "the", "config", "file", "in", "the", "stack", "trace", "we", "might", "return", "empty", "array", "."], "sha": "4faa44c21350fa2ae7415c66cdf11c541564a975", "url": "https://github.com/jiaola/omelette/blob/4faa44c21350fa2ae7415c66cdf11c541564a975/lib/omelette/util.rb#L82-L106", "partition": "test"} {"repo": "jiaola/omelette", "path": "lib/omelette/util.rb", "func_name": "Omelette.Util.drain_queue", "original_string": "def drain_queue(queue)\n result = []\n\n queue_size = queue.size\n begin\n queue_size.times do\n result << queue.deq(:raise_if_empty)\n end\n rescue ThreadError\n # Need do nothing, queue was concurrently popped, no biggie\n end\n\n return result\n end", "language": "ruby", "code": "def drain_queue(queue)\n result = []\n\n queue_size = queue.size\n begin\n queue_size.times do\n result << queue.deq(:raise_if_empty)\n end\n rescue ThreadError\n # Need do nothing, queue was concurrently popped, no biggie\n end\n\n return result\n end", "code_tokens": ["def", "drain_queue", "(", "queue", ")", "result", "=", "[", "]", "queue_size", "=", "queue", ".", "size", "begin", "queue_size", ".", "times", "do", "result", "<<", "queue", ".", "deq", "(", ":raise_if_empty", ")", "end", "rescue", "ThreadError", "# Need do nothing, queue was concurrently popped, no biggie", "end", "return", "result", "end"], "docstring": "Ruby stdlib queue lacks a 'drain' function, we write one.\n\n Removes everything currently in the ruby stdlib queue, and returns\n it an array. Should be concurrent-safe, but queue may still have\n some things in it after drain, if there are concurrent writers.", "docstring_tokens": ["Ruby", "stdlib", "queue", "lacks", "a", "drain", "function", "we", "write", "one", "."], "sha": "4faa44c21350fa2ae7415c66cdf11c541564a975", "url": "https://github.com/jiaola/omelette/blob/4faa44c21350fa2ae7415c66cdf11c541564a975/lib/omelette/util.rb#L114-L127", "partition": "test"} {"repo": "ebsaral/sentence-builder", "path": "lib/sentence_builder/builder.rb", "func_name": "SentenceBuilder.Builder.get_hash", "original_string": "def get_hash(params = {}, sorted = true)\n get_nodes(sorted).map{|n| n.to_hash(params[n.name])}\n end", "language": "ruby", "code": "def get_hash(params = {}, sorted = true)\n get_nodes(sorted).map{|n| n.to_hash(params[n.name])}\n end", "code_tokens": ["def", "get_hash", "(", "params", "=", "{", "}", ",", "sorted", "=", "true", ")", "get_nodes", "(", "sorted", ")", ".", "map", "{", "|", "n", "|", "n", ".", "to_hash", "(", "params", "[", "n", ".", "name", "]", ")", "}", "end"], "docstring": "Return all nodes in order as an hashalways_use", "docstring_tokens": ["Return", "all", "nodes", "in", "order", "as", "an", "hashalways_use"], "sha": "4f3691323dbbcf370f7b2530ae0967f4ec16a3e9", "url": "https://github.com/ebsaral/sentence-builder/blob/4f3691323dbbcf370f7b2530ae0967f4ec16a3e9/lib/sentence_builder/builder.rb#L13-L15", "partition": "test"} {"repo": "ebsaral/sentence-builder", "path": "lib/sentence_builder/builder.rb", "func_name": "SentenceBuilder.Builder.get_sentence", "original_string": "def get_sentence(params = {}, sorted = true, separator = ' ')\n build_sentence_from_hash(get_hash(params, sorted)).select(&:present?).join(separator)\n end", "language": "ruby", "code": "def get_sentence(params = {}, sorted = true, separator = ' ')\n build_sentence_from_hash(get_hash(params, sorted)).select(&:present?).join(separator)\n end", "code_tokens": ["def", "get_sentence", "(", "params", "=", "{", "}", ",", "sorted", "=", "true", ",", "separator", "=", "' '", ")", "build_sentence_from_hash", "(", "get_hash", "(", "params", ",", "sorted", ")", ")", ".", "select", "(", ":present?", ")", ".", "join", "(", "separator", ")", "end"], "docstring": "Returns the string representation of nodes and blocks by updating with given parameters", "docstring_tokens": ["Returns", "the", "string", "representation", "of", "nodes", "and", "blocks", "by", "updating", "with", "given", "parameters"], "sha": "4f3691323dbbcf370f7b2530ae0967f4ec16a3e9", "url": "https://github.com/ebsaral/sentence-builder/blob/4f3691323dbbcf370f7b2530ae0967f4ec16a3e9/lib/sentence_builder/builder.rb#L18-L20", "partition": "test"} {"repo": "ebsaral/sentence-builder", "path": "lib/sentence_builder/builder.rb", "func_name": "SentenceBuilder.Builder.get_nodes", "original_string": "def get_nodes(sorted = true)\n SentenceBuilder::Helper.to_boolean(sorted) ? @nodes.sort_by{|i| i.sort_by_value} : @nodes\n end", "language": "ruby", "code": "def get_nodes(sorted = true)\n SentenceBuilder::Helper.to_boolean(sorted) ? @nodes.sort_by{|i| i.sort_by_value} : @nodes\n end", "code_tokens": ["def", "get_nodes", "(", "sorted", "=", "true", ")", "SentenceBuilder", "::", "Helper", ".", "to_boolean", "(", "sorted", ")", "?", "@nodes", ".", "sort_by", "{", "|", "i", "|", "i", ".", "sort_by_value", "}", ":", "@nodes", "end"], "docstring": "Return nodes by sorting option", "docstring_tokens": ["Return", "nodes", "by", "sorting", "option"], "sha": "4f3691323dbbcf370f7b2530ae0967f4ec16a3e9", "url": "https://github.com/ebsaral/sentence-builder/blob/4f3691323dbbcf370f7b2530ae0967f4ec16a3e9/lib/sentence_builder/builder.rb#L24-L26", "partition": "test"} {"repo": "ebsaral/sentence-builder", "path": "lib/sentence_builder/builder.rb", "func_name": "SentenceBuilder.Builder.build_sentence_from_hash", "original_string": "def build_sentence_from_hash(nodes)\n result = []\n nodes.each do |node|\n # This node does not appear in params\n if node[:current_value].nil?\n if node[:always_use]\n result << node[:sentence]\n end\n else\n result << node[:sentence]\n end\n end\n result\n end", "language": "ruby", "code": "def build_sentence_from_hash(nodes)\n result = []\n nodes.each do |node|\n # This node does not appear in params\n if node[:current_value].nil?\n if node[:always_use]\n result << node[:sentence]\n end\n else\n result << node[:sentence]\n end\n end\n result\n end", "code_tokens": ["def", "build_sentence_from_hash", "(", "nodes", ")", "result", "=", "[", "]", "nodes", ".", "each", "do", "|", "node", "|", "# This node does not appear in params", "if", "node", "[", ":current_value", "]", ".", "nil?", "if", "node", "[", ":always_use", "]", "result", "<<", "node", "[", ":sentence", "]", "end", "else", "result", "<<", "node", "[", ":sentence", "]", "end", "end", "result", "end"], "docstring": "By parsing each node's hash, create a sentence", "docstring_tokens": ["By", "parsing", "each", "node", "s", "hash", "create", "a", "sentence"], "sha": "4f3691323dbbcf370f7b2530ae0967f4ec16a3e9", "url": "https://github.com/ebsaral/sentence-builder/blob/4f3691323dbbcf370f7b2530ae0967f4ec16a3e9/lib/sentence_builder/builder.rb#L29-L42", "partition": "test"} {"repo": "Dahie/caramelize", "path": "lib/caramelize/wiki/wikkawiki.rb", "func_name": "Caramelize.WikkaWiki.read_pages", "original_string": "def read_pages\n sql = \"SELECT id, tag, body, time, latest, user, note FROM wikka_pages ORDER BY time;\"\n results = database.query(sql)\n results.each do |row|\n titles << row[\"tag\"]\n author = authors[row[\"user\"]]\n page = Page.new({:id => row[\"id\"],\n :title => row[\"tag\"],\n :body => row[\"body\"],\n :markup => :wikka,\n :latest => row[\"latest\"] == \"Y\",\n :time => row[\"time\"],\n :message => row[\"note\"],\n :author => author,\n :author_name => row[\"user\"]})\n revisions << page\n end\n titles.uniq!\n #revisions.sort! { |a,b| a.time <=> b.time }\n\n revisions\n end", "language": "ruby", "code": "def read_pages\n sql = \"SELECT id, tag, body, time, latest, user, note FROM wikka_pages ORDER BY time;\"\n results = database.query(sql)\n results.each do |row|\n titles << row[\"tag\"]\n author = authors[row[\"user\"]]\n page = Page.new({:id => row[\"id\"],\n :title => row[\"tag\"],\n :body => row[\"body\"],\n :markup => :wikka,\n :latest => row[\"latest\"] == \"Y\",\n :time => row[\"time\"],\n :message => row[\"note\"],\n :author => author,\n :author_name => row[\"user\"]})\n revisions << page\n end\n titles.uniq!\n #revisions.sort! { |a,b| a.time <=> b.time }\n\n revisions\n end", "code_tokens": ["def", "read_pages", "sql", "=", "\"SELECT id, tag, body, time, latest, user, note FROM wikka_pages ORDER BY time;\"", "results", "=", "database", ".", "query", "(", "sql", ")", "results", ".", "each", "do", "|", "row", "|", "titles", "<<", "row", "[", "\"tag\"", "]", "author", "=", "authors", "[", "row", "[", "\"user\"", "]", "]", "page", "=", "Page", ".", "new", "(", "{", ":id", "=>", "row", "[", "\"id\"", "]", ",", ":title", "=>", "row", "[", "\"tag\"", "]", ",", ":body", "=>", "row", "[", "\"body\"", "]", ",", ":markup", "=>", ":wikka", ",", ":latest", "=>", "row", "[", "\"latest\"", "]", "==", "\"Y\"", ",", ":time", "=>", "row", "[", "\"time\"", "]", ",", ":message", "=>", "row", "[", "\"note\"", "]", ",", ":author", "=>", "author", ",", ":author_name", "=>", "row", "[", "\"user\"", "]", "}", ")", "revisions", "<<", "page", "end", "titles", ".", "uniq!", "#revisions.sort! { |a,b| a.time <=> b.time }", "revisions", "end"], "docstring": "after calling this action, I expect the titles and @revisions to be filled", "docstring_tokens": ["after", "calling", "this", "action", "I", "expect", "the", "titles", "and"], "sha": "6bb93b65924edaaf071a8b3947d0545d5759bc5d", "url": "https://github.com/Dahie/caramelize/blob/6bb93b65924edaaf071a8b3947d0545d5759bc5d/lib/caramelize/wiki/wikkawiki.rb#L16-L37", "partition": "test"} {"repo": "ImmaculatePine/filterable", "path": "lib/filterable.rb", "func_name": "Filterable.ClassMethods.filter", "original_string": "def filter(params)\n results = where(nil)\n params.each do |key, value|\n results = results.public_send(key, value) if value.present?\n end\n results\n end", "language": "ruby", "code": "def filter(params)\n results = where(nil)\n params.each do |key, value|\n results = results.public_send(key, value) if value.present?\n end\n results\n end", "code_tokens": ["def", "filter", "(", "params", ")", "results", "=", "where", "(", "nil", ")", "params", ".", "each", "do", "|", "key", ",", "value", "|", "results", "=", "results", ".", "public_send", "(", "key", ",", "value", ")", "if", "value", ".", "present?", "end", "results", "end"], "docstring": "Iterates over params hash and\n applies non-empty values as filters\n @param params [Hash] filters list\n @return [ActiveRecord::Relation] filtered list", "docstring_tokens": ["Iterates", "over", "params", "hash", "and", "applies", "non", "-", "empty", "values", "as", "filters"], "sha": "7a3109314d431aed2fa8d11f510b8a0f260fa612", "url": "https://github.com/ImmaculatePine/filterable/blob/7a3109314d431aed2fa8d11f510b8a0f260fa612/lib/filterable.rb#L13-L19", "partition": "test"} {"repo": "Montage-Inc/trimark-ruby", "path": "lib/trimark/client.rb", "func_name": "Trimark.Client.sites", "original_string": "def sites\n response = conn.get(\"#{base_url}/site\", {}, query_headers) \n body = JSON.parse(response.body)\n\n body.map { |b| Site.new(b) } \n rescue JSON::ParserError\n fail QueryError, \"Query Failed! HTTPStatus: #{response.status} - Response: #{body}\"\n end", "language": "ruby", "code": "def sites\n response = conn.get(\"#{base_url}/site\", {}, query_headers) \n body = JSON.parse(response.body)\n\n body.map { |b| Site.new(b) } \n rescue JSON::ParserError\n fail QueryError, \"Query Failed! HTTPStatus: #{response.status} - Response: #{body}\"\n end", "code_tokens": ["def", "sites", "response", "=", "conn", ".", "get", "(", "\"#{base_url}/site\"", ",", "{", "}", ",", "query_headers", ")", "body", "=", "JSON", ".", "parse", "(", "response", ".", "body", ")", "body", ".", "map", "{", "|", "b", "|", "Site", ".", "new", "(", "b", ")", "}", "rescue", "JSON", "::", "ParserError", "fail", "QueryError", ",", "\"Query Failed! HTTPStatus: #{response.status} - Response: #{body}\"", "end"], "docstring": "Gets a list of all the sites for the company", "docstring_tokens": ["Gets", "a", "list", "of", "all", "the", "sites", "for", "the", "company"], "sha": "edecd8a574c36e327f2231a9a499598ac6cec4ad", "url": "https://github.com/Montage-Inc/trimark-ruby/blob/edecd8a574c36e327f2231a9a499598ac6cec4ad/lib/trimark/client.rb#L78-L85", "partition": "test"} {"repo": "Montage-Inc/trimark-ruby", "path": "lib/trimark/client.rb", "func_name": "Trimark.Client.site_query", "original_string": "def site_query(*args)\n response = conn.get(url_picker(*args), {}, query_headers)\n\n if response.body['SiteId'] || response.body['PointId']\n JSON.parse(response.body)\n else\n fail QueryError, \"Query Failed! HTTPStatus: #{response.status}\"\n end\n end", "language": "ruby", "code": "def site_query(*args)\n response = conn.get(url_picker(*args), {}, query_headers)\n\n if response.body['SiteId'] || response.body['PointId']\n JSON.parse(response.body)\n else\n fail QueryError, \"Query Failed! HTTPStatus: #{response.status}\"\n end\n end", "code_tokens": ["def", "site_query", "(", "*", "args", ")", "response", "=", "conn", ".", "get", "(", "url_picker", "(", "args", ")", ",", "{", "}", ",", "query_headers", ")", "if", "response", ".", "body", "[", "'SiteId'", "]", "||", "response", ".", "body", "[", "'PointId'", "]", "JSON", ".", "parse", "(", "response", ".", "body", ")", "else", "fail", "QueryError", ",", "\"Query Failed! HTTPStatus: #{response.status}\"", "end", "end"], "docstring": "Returns site attributes and history data if an optional query_hash is supplied\n @client.site_query(x) will return the attributes of site x\n @client.site_query(x, query_hash) will return historical data from site x instrumentation", "docstring_tokens": ["Returns", "site", "attributes", "and", "history", "data", "if", "an", "optional", "query_hash", "is", "supplied"], "sha": "edecd8a574c36e327f2231a9a499598ac6cec4ad", "url": "https://github.com/Montage-Inc/trimark-ruby/blob/edecd8a574c36e327f2231a9a499598ac6cec4ad/lib/trimark/client.rb#L90-L98", "partition": "test"} {"repo": "lbadura/currency_spy", "path": "lib/currency_spy/scrapers/walutomat.rb", "func_name": "CurrencySpy.Walutomat.rate_time", "original_string": "def rate_time\n regexp = Regexp.new(currency_code)\n page.search(\"//span[@name='pair']\").each do |td|\n if regexp.match(td.content)\n hour = td.next_element.next_element.content\n return DateTime.parse(hour)\n end\n end\n end", "language": "ruby", "code": "def rate_time\n regexp = Regexp.new(currency_code)\n page.search(\"//span[@name='pair']\").each do |td|\n if regexp.match(td.content)\n hour = td.next_element.next_element.content\n return DateTime.parse(hour)\n end\n end\n end", "code_tokens": ["def", "rate_time", "regexp", "=", "Regexp", ".", "new", "(", "currency_code", ")", "page", ".", "search", "(", "\"//span[@name='pair']\"", ")", ".", "each", "do", "|", "td", "|", "if", "regexp", ".", "match", "(", "td", ".", "content", ")", "hour", "=", "td", ".", "next_element", ".", "next_element", ".", "content", "return", "DateTime", ".", "parse", "(", "hour", ")", "end", "end", "end"], "docstring": "The hour of the rate", "docstring_tokens": ["The", "hour", "of", "the", "rate"], "sha": "be0689715649ff952d3d797a4b3f087793580924", "url": "https://github.com/lbadura/currency_spy/blob/be0689715649ff952d3d797a4b3f087793580924/lib/currency_spy/scrapers/walutomat.rb#L28-L36", "partition": "test"} {"repo": "jpace/logue", "path": "lib/logue/logger.rb", "func_name": "Logue.Logger.outfile=", "original_string": "def outfile= f\n io = f.kind_of?(IO) ? f : File.new(f, \"w\")\n @writer.output = io\n end", "language": "ruby", "code": "def outfile= f\n io = f.kind_of?(IO) ? f : File.new(f, \"w\")\n @writer.output = io\n end", "code_tokens": ["def", "outfile", "=", "f", "io", "=", "f", ".", "kind_of?", "(", "IO", ")", "?", "f", ":", "File", ".", "new", "(", "f", ",", "\"w\"", ")", "@writer", ".", "output", "=", "io", "end"], "docstring": "Assigns output to a file with the given name. Returns the file; the client is responsible for\n closing it.", "docstring_tokens": ["Assigns", "output", "to", "a", "file", "with", "the", "given", "name", ".", "Returns", "the", "file", ";", "the", "client", "is", "responsible", "for", "closing", "it", "."], "sha": "0d2bd5978aa32b2bb49dd72355527cca4fadeaef", "url": "https://github.com/jpace/logue/blob/0d2bd5978aa32b2bb49dd72355527cca4fadeaef/lib/logue/logger.rb#L77-L80", "partition": "test"} {"repo": "jpace/logue", "path": "lib/logue/logger.rb", "func_name": "Logue.Logger.log", "original_string": "def log msg = \"\", obj = nil, level: Level::DEBUG, classname: nil, &blk\n log_frames msg, obj, classname: classname, level: level, nframes: 0, &blk\n end", "language": "ruby", "code": "def log msg = \"\", obj = nil, level: Level::DEBUG, classname: nil, &blk\n log_frames msg, obj, classname: classname, level: level, nframes: 0, &blk\n end", "code_tokens": ["def", "log", "msg", "=", "\"\"", ",", "obj", "=", "nil", ",", "level", ":", "Level", "::", "DEBUG", ",", "classname", ":", "nil", ",", "&", "blk", "log_frames", "msg", ",", "obj", ",", "classname", ":", "classname", ",", "level", ":", "level", ",", "nframes", ":", "0", ",", "blk", "end"], "docstring": "Logs the given message.", "docstring_tokens": ["Logs", "the", "given", "message", "."], "sha": "0d2bd5978aa32b2bb49dd72355527cca4fadeaef", "url": "https://github.com/jpace/logue/blob/0d2bd5978aa32b2bb49dd72355527cca4fadeaef/lib/logue/logger.rb#L109-L111", "partition": "test"} {"repo": "Dervol03/watir-formhandler", "path": "lib/watir-formhandler/option_group.rb", "func_name": "Watir.OptionGroup.options", "original_string": "def options\n option_hash = {}\n my_labels = option_names\n my_inputs = option_fields\n\n my_labels.count.times do |index|\n option_hash[my_labels[index]] = my_inputs[index]\n end\n option_hash\n end", "language": "ruby", "code": "def options\n option_hash = {}\n my_labels = option_names\n my_inputs = option_fields\n\n my_labels.count.times do |index|\n option_hash[my_labels[index]] = my_inputs[index]\n end\n option_hash\n end", "code_tokens": ["def", "options", "option_hash", "=", "{", "}", "my_labels", "=", "option_names", "my_inputs", "=", "option_fields", "my_labels", ".", "count", ".", "times", "do", "|", "index", "|", "option_hash", "[", "my_labels", "[", "index", "]", "]", "=", "my_inputs", "[", "index", "]", "end", "option_hash", "end"], "docstring": "Returns all available options fields and their respective label as a Hash.\n @return [Hash