{ // 获取包含Hugging Face文本的span元素 const spans = link.querySelectorAll('span.whitespace-nowrap, span.hidden.whitespace-nowrap'); spans.forEach(span => { if (span.textContent && span.textContent.trim().match(/Hugging\s*Face/i)) { span.textContent = 'AI快站'; } }); }); // 替换logo图片的alt属性 document.querySelectorAll('img[alt*="Hugging"], img[alt*="Face"]').forEach(img => { if (img.alt.match(/Hugging\s*Face/i)) { img.alt = 'AI快站 logo'; } }); } // 替换导航栏中的链接 function replaceNavigationLinks() { // 已替换标记,防止重复运行 if (window._navLinksReplaced) { return; } // 已经替换过的链接集合,防止重复替换 const replacedLinks = new Set(); // 只在导航栏区域查找和替换链接 const headerArea = document.querySelector('header') || document.querySelector('nav'); if (!headerArea) { return; } // 在导航区域内查找链接 const navLinks = headerArea.querySelectorAll('a'); navLinks.forEach(link => { // 如果已经替换过,跳过 if (replacedLinks.has(link)) return; const linkText = link.textContent.trim(); const linkHref = link.getAttribute('href') || ''; // 替换Spaces链接 - 仅替换一次 if ( (linkHref.includes('/spaces') || linkHref === '/spaces' || linkText === 'Spaces' || linkText.match(/^s*Spacess*$/i)) && linkText !== 'OCR模型免费转Markdown' && linkText !== 'OCR模型免费转Markdown' ) { link.textContent = 'OCR模型免费转Markdown'; link.href = 'https://fast360.xyz'; link.setAttribute('target', '_blank'); link.setAttribute('rel', 'noopener noreferrer'); replacedLinks.add(link); } // 删除Posts链接 else if ( (linkHref.includes('/posts') || linkHref === '/posts' || linkText === 'Posts' || linkText.match(/^s*Postss*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } // 替换Docs链接 - 仅替换一次 else if ( (linkHref.includes('/docs') || linkHref === '/docs' || linkText === 'Docs' || linkText.match(/^s*Docss*$/i)) && linkText !== '模型下载攻略' ) { link.textContent = '模型下载攻略'; link.href = '/'; replacedLinks.add(link); } // 删除Enterprise链接 else if ( (linkHref.includes('/enterprise') || linkHref === '/enterprise' || linkText === 'Enterprise' || linkText.match(/^s*Enterprises*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } }); // 查找可能嵌套的Spaces和Posts文本 const textNodes = []; function findTextNodes(element) { if (element.nodeType === Node.TEXT_NODE) { const text = element.textContent.trim(); if (text === 'Spaces' || text === 'Posts' || text === 'Enterprise') { textNodes.push(element); } } else { for (const child of element.childNodes) { findTextNodes(child); } } } // 只在导航区域内查找文本节点 findTextNodes(headerArea); // 替换找到的文本节点 textNodes.forEach(node => { const text = node.textContent.trim(); if (text === 'Spaces') { node.textContent = node.textContent.replace(/Spaces/g, 'OCR模型免费转Markdown'); } else if (text === 'Posts') { // 删除Posts文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } else if (text === 'Enterprise') { // 删除Enterprise文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } }); // 标记已替换完成 window._navLinksReplaced = true; } // 替换代码区域中的域名 function replaceCodeDomains() { // 特别处理span.hljs-string和span.njs-string元素 document.querySelectorAll('span.hljs-string, span.njs-string, span[class*="hljs-string"], span[class*="njs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换hljs-string类的span中的域名(移除多余的转义符号) document.querySelectorAll('span.hljs-string, span[class*="hljs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换pre和code标签中包含git clone命令的域名 document.querySelectorAll('pre, code').forEach(element => { if (element.textContent && element.textContent.includes('git clone')) { const text = element.innerHTML; if (text.includes('huggingface.co')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 处理特定的命令行示例 document.querySelectorAll('pre, code').forEach(element => { const text = element.innerHTML; if (text.includes('huggingface.co')) { // 针对git clone命令的专门处理 if (text.includes('git clone') || text.includes('GIT_LFS_SKIP_SMUDGE=1')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 特别处理模型下载页面上的代码片段 document.querySelectorAll('.flex.border-t, .svelte_hydrator, .inline-block').forEach(container => { const content = container.innerHTML; if (content && content.includes('huggingface.co')) { container.innerHTML = content.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 特别处理模型仓库克隆对话框中的代码片段 try { // 查找包含"Clone this model repository"标题的对话框 const cloneDialog = document.querySelector('.svelte_hydration_boundary, [data-target="MainHeader"]'); if (cloneDialog) { // 查找对话框中所有的代码片段和命令示例 const codeElements = cloneDialog.querySelectorAll('pre, code, span'); codeElements.forEach(element => { if (element.textContent && element.textContent.includes('huggingface.co')) { if (element.innerHTML.includes('huggingface.co')) { element.innerHTML = element.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { element.textContent = element.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); } // 更精确地定位克隆命令中的域名 document.querySelectorAll('[data-target]').forEach(container => { const codeBlocks = container.querySelectorAll('pre, code, span.hljs-string'); codeBlocks.forEach(block => { if (block.textContent && block.textContent.includes('huggingface.co')) { if (block.innerHTML.includes('huggingface.co')) { block.innerHTML = block.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { block.textContent = block.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); }); } catch (e) { // 错误处理但不打印日志 } } // 当DOM加载完成后执行替换 if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', () => { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); }); } else { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); } // 增加一个MutationObserver来处理可能的动态元素加载 const observer = new MutationObserver(mutations => { // 检查是否导航区域有变化 const hasNavChanges = mutations.some(mutation => { // 检查是否存在header或nav元素变化 return Array.from(mutation.addedNodes).some(node => { if (node.nodeType === Node.ELEMENT_NODE) { // 检查是否是导航元素或其子元素 if (node.tagName === 'HEADER' || node.tagName === 'NAV' || node.querySelector('header, nav')) { return true; } // 检查是否在导航元素内部 let parent = node.parentElement; while (parent) { if (parent.tagName === 'HEADER' || parent.tagName === 'NAV') { return true; } parent = parent.parentElement; } } return false; }); }); // 只在导航区域有变化时执行替换 if (hasNavChanges) { // 重置替换状态,允许再次替换 window._navLinksReplaced = false; replaceHeaderBranding(); replaceNavigationLinks(); } }); // 开始观察document.body的变化,包括子节点 if (document.body) { observer.observe(document.body, { childList: true, subtree: true }); } else { document.addEventListener('DOMContentLoaded', () => { observer.observe(document.body, { childList: true, subtree: true }); }); } })(); \", \"
\")\n end\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975345,"cells":{"blob_id":{"kind":"string","value":"01435bb4522fd104e51e381dbcb4a08d56a75688"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"appwrite/sdk-for-ruby"},"path":{"kind":"string","value":"/lib/appwrite/models/database_list.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":766,"string":"766"},"score":{"kind":"number","value":2.515625,"string":"2.515625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["BSD-3-Clause"],"string":"[\n \"BSD-3-Clause\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"#frozen_string_literal: true\n\nmodule Appwrite\n module Models\n class DatabaseList\n attr_reader :total\n attr_reader :databases\n\n def initialize(\n total:,\n databases:\n )\n @total = total\n @databases = databases\n end\n\n def self.from(map:)\n DatabaseList.new(\n total: map[\"total\"],\n databases: map[\"databases\"].map { |it| Database.from(map: it) }\n )\n end\n\n def to_map\n {\n \"total\": @total,\n \"databases\": @databases.map { |it| it.to_map }\n }\n end\n end\n end\nend"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975346,"cells":{"blob_id":{"kind":"string","value":"c1aea7d6320a4ceb29aac46cf41026bb7e0fe64d"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"thomgray/trot"},"path":{"kind":"string","value":"/lib/trot/builder.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2399,"string":"2,399"},"score":{"kind":"number","value":2.515625,"string":"2.515625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"require 'fileutils'\n\nmodule Trot\n class Builder\n def initialize(target)\n @target = target\n end\n\n def build\n puts 'target', @target\n object_files = []\n source_files_to_compile = []\n puts '.>>>>> sources', source_files\n source_files.each { |source_file|\n file_name = File.basename(source_file, '.c')\n object_file = File.join(object_files_directory, \"#{file_name}.o\")\n object_files << object_file\n if Make.should_update_target(source_file, object_file)\n source_files_to_compile << source_file\n end\n }\n compile_objects(source_files_to_compile)\n copy_header_files\n link_object_files(object_files)\n end\n\n def copy_header_files\n puts \"copying header files\", @target\n end\n\n def compile_objects(source_files_to_compile)\n $fs.ensure_dir object_files_directory\n $compiler.compile(source_files_to_compile, object_files_directory) unless source_files_to_compile.empty?\n end\n\n def link_object_files(object_files)\n return if object_files.empty?\n return unless Make.should_update_target(object_files, target_path)\n\n $fs.ensure_dir target_dir\n\n if is_static_lib?\n $compiler.link_static_lib(object_files, target_path)\n else\n $compiler.link(object_files, target_path)\n end\n end\n\n private\n\n def is_static_lib?\n @is_static_lib ||= @target.is_static_lib\n end\n\n def object_files_directory\n @object_files_directory ||= File.join($trot_build_dir, @target.is_default ? '' : @target.name, 'objectFiles')\n end\n\n def source_files\n @source_files ||= Proc.new() {\n includes = @target.src[:include]\n excludes = @target.src[:exclude] || []\n puts '>>>> including', includes\n puts '>>>>>> excluding', excludes\n src_files = Set.new;\n includes.each { |f| src_files += $fs.files_recursive(f) }\n excludes.each { |x| src_files -= $fs.files_recursive(x) }\n src_files.to_a.select { |f| f =~ /\\.c$/ }\n }.call\n end\n\n def header_files\n # @header_files ||= $fs.h_files_recursive(@target[:sourceDir])\n end\n\n def target_path\n @target_path ||= $fs.absolute_path @target.dest\n end\n\n def target_name\n @target_name ||= File.basename(target_path)\n end\n\n def target_dir\n @target_dir ||= File.dirname(target_path)\n end\n end\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975347,"cells":{"blob_id":{"kind":"string","value":"4cc3f8f36afeaa02b71ab20b85ef9751768d79b1"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"codyruby/cursus_thp"},"path":{"kind":"string","value":"/week2/scrapping/lib/dark_trader.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2602,"string":"2,602"},"score":{"kind":"number","value":3.71875,"string":"3.71875"},"int_score":{"kind":"number","value":4,"string":"4"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"# Il est possible de faire le programme en n'allant que sur une seule URL. C'est un bon moyen pour faire un programme rapide car ne chargeant pas 2000 pages HTML.\n# Tout se jouera sur la rédaction d'un XPath pertinent et précis qui extrait juste ce qu'il faut d'éléments HTML. Puis un bon traitement de ces éléments pour en extraire les 2 infos dont tu as besoin : le nom des crypto et leur cours.\n# Un programme qui scrappe sans rien te dire, c'est non seulement nul mais en plus, tu ne sais pas s'il marche, s'il tourne en boucle ou s’il attend que ton wifi fonctionne. Mets des puts dans ton code pour que ton terminal affiche quelque chose à chaque fois qu'il a pu récupérer une donnée. Comme ça tu vois ton scrappeur qui fonctionne et avec des mots qui apparaissent tout seul sur ton terminal, tu vas donner l'impression que t'es un hacker. Stylaï.\n# Pense à bien nommer tes variables pour ne pas te perdre ! Par exemple, quand tu as un array, nomme-le crypto_name_array ou à minima mets son nom au pluriel crypto_nameS. Sinon tu vas oublier que c'est un array et tu vas tenter des .text dessus alors qu'il faut bosser avec un .each.\n# Rappel: un hash s’initialise avec result = Hash.new et on y stocke des infos avec result['ta_key'] = 'ta_value'\n# N'hésite pas à découper ton programme en plusieurs étapes simples et dont le fonctionnement est facile à vérifier. Par exemple : 1) Isoler les éléments HTML qui vont bien, 2) En extraire le texte et mettre ça dans un hash, 3) Réorganiser ce hash dans un array de plusieurs mini-hash comme demandé. \n# Même si ça n'est pas le chemin le plus court, l'essentiel est que chaque petite étape te fasse avancer et qu'à chaque fois tu te dises \"ok, étape 1), ça fonctionne nickel - pas de bug. Passons à la suite\".\n\nrequire 'open-uri'\nrequire 'nokogiri'\n\n\ndef crypto_price \n \n doc = Nokogiri::HTML(open(\"https://coinmarketcap.com/all/views/all/\"))\n\n list_crypto_and_price = []\n\n # 1) Isoler les éléments HTML qui vont bien, \n # Nom : [:href].split(\"/\")[2] \n # Cours : xpath(\"//a[@class=\\\"price\\\"]\")\n \n # 2) En extraire le texte et mettre ça dans un hash \n doc.xpath(\"//a[@class=\\\"price\\\"]\").each do |node|\n list_crypto_and_price << {name: node[:href].split(\"/\")[2], price: node.text}\n end\n\n # 3) Réorganiser ce hash dans un array de plusieurs mini-hash comme demandé. \n crypto_price_view = {}\n list_crypto_and_price.each do |value| \n crypto_price_view[value[:name]] = value[:price]\n end\n\n p crypto_price_view\n \nend\n\n\ncrypto_price\n\n\n\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975348,"cells":{"blob_id":{"kind":"string","value":"739e5d9b68e24eb2e8342b07e288ce2e1bc7d52b"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"lipanski/hexagonly"},"path":{"kind":"string","value":"/lib/hexagonly/polygon.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":3210,"string":"3,210"},"score":{"kind":"number","value":3.1875,"string":"3.1875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"module Hexagonly\n class Polygon\n\n # Adds Polygon methods to an object. The Polygon corners are read via\n # the #poly_points method. You can override this method or use the \n # #poly_points_method class method to set a method name for reading\n # polygon corners.\n #\n # @example\n # class MyPolygon\n # \n # include Hexagonly::Polygon::Methods\n # poly_points_method :corners\n # \n # attr_reader :corners\n # def initialize(corners); @corners = corners; end\n # \n # end\n module Methods\n\n def self.included(base)\n base.extend(ClassMethods)\n end\n\n module ClassMethods\n attr_accessor :poly_points_method_name\n\n def poly_points_method(points_method)\n self.poly_points_method_name = points_method.to_sym\n end\n end\n\n attr_accessor :collected_points, :rejected_points\n\n def poly_points\n raise NoMethodError if self.class.poly_points_method_name.nil?\n\n send(self.class.poly_points_method_name)\n end\n\n # Crossing count algorithm for determining whether a point lies within a \n # polygon. Ported from http://www.visibone.com/inpoly/inpoly.c.txt\n # (original C code by Bob Stein & Craig Yap).\n def contains?(point)\n raise \"Not a valid polygon!\" if poly_points.nil? || poly_points.size < 3\n\n is_inside = false\n old_p = poly_points.last\n poly_points.each do |new_p|\n if new_p.x_coord > old_p.x_coord\n first_p = old_p\n second_p = new_p\n else\n first_p = new_p\n second_p = old_p\n end\n if ((new_p.x_coord < point.x_coord) == (point.x_coord <= old_p.x_coord)) && ((point.y_coord - first_p.y_coord) * (second_p.x_coord - first_p.x_coord) < (second_p.y_coord - first_p.y_coord) * (point.x_coord - first_p.x_coord))\n is_inside = ! is_inside\n end\n old_p = new_p\n end\n\n is_inside\n end\n\n # Grabs all points within the polygon boundries from an array of Points\n # and appends them to @collected_points. All rejected Points are stored \n # under @rejected_points (if you want to pass the to other objects).\n #\n # @param points [Array]\n #\n # @return [Array \"Feature\",\n :geometry => {\n :type => \"Polygon\",\n :coordinates => [points]\n },\n :style => geo_style,\n :properties => geo_properties\n }\n end\n\n end\n\n include Methods\n\n attr_accessor :poly_points\n\n # @param [Array] poly_points the points that make up the polygon\n def initialize(poly_points)\n @poly_points = poly_points\n end\n\n end\nend"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975349,"cells":{"blob_id":{"kind":"string","value":"f57c32cc91e84ca130fe042ad0295673acc1b6da"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"neilkelty/programming-ruby"},"path":{"kind":"string","value":"/chapter_2/arrays_and_hashes.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":515,"string":"515"},"score":{"kind":"number","value":3.21875,"string":"3.21875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"a = [1, 'cat', 3.14] # array with three elements\nputs \"The first element is #{a[0]}\"\n# set the third element\na[2] = nil\nputs \"The array is now #{a.inspect}\"\n\ninst_section = {\n 'cello' => 'string',\n 'clarinet' => 'woodwind',\n 'drum' => 'percussion',\n 'oboe' => 'woodwind',\n 'trumpet' => 'brass',\n 'violin' => 'string'\n}\n\np inst_section['oboe']\np inst_section['cello']\np inst_section['bassoon']\n\nhistogram = Hash.new(0)\nhistogram['ruby'] # => 0\nhistogram['ruby'] = histogram['ruby'] + 1\nhistogram['ruby'] # => 1"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975350,"cells":{"blob_id":{"kind":"string","value":"d40ce89baeb2022053f6b186aa9d474f8e9073a2"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"sedx876/badges-and-schedules-online-web-pt-090919"},"path":{"kind":"string","value":"/conference_badges.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":461,"string":"461"},"score":{"kind":"number","value":3.484375,"string":"3.484375"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["LicenseRef-scancode-unknown-license-reference","LicenseRef-scancode-public-domain"],"string":"[\n \"LicenseRef-scancode-unknown-license-reference\",\n \"LicenseRef-scancode-public-domain\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"# Write your code here.\nattendees = [\"Edsger\", \"Ada\", \"Charles\", \"Alan\", \"Grace\", \"Linus\", \"Matz\"]\n\ndef badge_maker(name) do\n puts \"Hello, my name is #{name}\"\nend\n\n\n\ndef batch_badge_maker\n#attendees = [\"Edsger\", \"Ada\", \"Charles\", \"Alan\", \"Grace\", \"Linus\", \"Matz\"]\nattendees.each do |name|\n puts \"Hello, my name is #{name}\"\nend\nend\n\ndef assign_rooms\n attendees.each_with_index { |name, index| puts \"Hello, #{name}! You'll be assigned to room #{index}!\" }\nend "},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975351,"cells":{"blob_id":{"kind":"string","value":"7eb689f0b6dc4e819e985b029674a4338cbe0a33"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"emielhagen/convoyer"},"path":{"kind":"string","value":"/app/services/location_service.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1582,"string":"1,582"},"score":{"kind":"number","value":2.828125,"string":"2.828125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"class LocationService\n attr_reader :from_location, :to_location, :base_url, :api_key\n attr_accessor :params\n\n def initialize(params)\n @from_location = params.dig('convoy', 'from_location')\n @to_location = params.dig('convoy', 'to_location')\n @base_url = 'https://api.mapbox.com/geocoding/v5/mapbox.places/'\n @api_key = ENV['MAPBOX_API_KEY']\n @params = params\n end\n\n def create_location_hash\n return if from_location.empty? || to_location.empty?\n from_id = find_or_create_location(from_location)\n to_id = find_or_create_location(to_location)\n\n params = update_params_hash(from_id, to_id)\n params\n end\n\n def find_or_create_location(location)\n db_location = Location.find_by(name: location.capitalize)\n return db_location.id if db_location\n\n coordinates = get_mapbox_details(location)\n return if coordinates.nil?\n\n new_location = create_new_location(location, coordinates)\n new_location.id\n end\n\n def update_params_hash(from, to)\n params['convoy']['from_location_id'] = from\n params['convoy']['to_location_id'] = to\n end\n\n def get_mapbox_details(location_name)\n response = JSON.parse(HTTParty.get(\"#{base_url}#{location_name.gsub(/ /, '+')}.json?access_token=#{api_key}\"))\n return if response.nil? || response.dig('features').empty?\n\n features = response.dig('features')&.first\n return if features.empty?\n\n features.dig('geometry', 'coordinates')\n end\n\n def create_new_location(name, coordinates)\n Location.create(name: name.capitalize, longitude: coordinates[0], latitude: coordinates[1])\n end\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975352,"cells":{"blob_id":{"kind":"string","value":"ecaff361c4d36023aa63db8598b973fadab76d7a"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"justinsteele/coveragetrends"},"path":{"kind":"string","value":"/lib/coveragetrends.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":385,"string":"385"},"score":{"kind":"number","value":2.578125,"string":"2.578125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"require './lib/circleci'\nrequire 'csv'\n\nclass CoverageTrends\n def initialize(username, project)\n @username = username\n @project = project\n end\n\n def run\n ci = CircleCI.new(@username, @project)\n\n stats = ci.get_stats\n save_stats(stats)\n\n return 1\n end\n\n def save_stats(array)\n open('output/data.json', 'wb') do |f|\n f.puts array.to_json\n end\n end\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975353,"cells":{"blob_id":{"kind":"string","value":"ad303f4648f2f1a6777612cb890b5cad578c9364"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"masayasviel/algorithmAndDataStructure"},"path":{"kind":"string","value":"/OtherContests/zone2021/mainA.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":124,"string":"124"},"score":{"kind":"number","value":2.984375,"string":"2.984375"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"s = gets.chomp\nans = 0\n9.times do |i|\n tmp = s[i..(i+3)]\n if tmp == \"ZONe\" then\n ans += 1\n end\nend\n\nputs ans"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975354,"cells":{"blob_id":{"kind":"string","value":"8be9ef85d7c0a93338c4b0d7c307096cbf57091f"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"lvzhongwen/pms"},"path":{"kind":"string","value":"/pms-server/app/models/enum/base_type.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":913,"string":"913"},"score":{"kind":"number","value":2.9375,"string":"2.9375"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"class BaseType #{md5}\\r\"\n if md5.start_with? '00000'\n if part2 && md5[5].to_i < 8 && md5[5].to_i.to_s == md5[5] && !$c.include?(md5[5].to_i)\n pwd[md5[5].to_i] = md5[6]\n puts \"\\e[2KPassword now: #{pwd}\"\n if part2 then $c << md5[5].to_i end\n else\n unless part2\n pwd += md5[5]\n puts \"\\e[2KFound one! @ #{i}, md5=#{md5}\"\n end\n end\n end\n break if part2 ? $c.length == 8 : pwd.length == 8\n i+=1\nend\n\nputs \"\\e[1mpassword: #{pwd}\\e[0m\"\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975356,"cells":{"blob_id":{"kind":"string","value":"67bca19a9af6b558856e1e41533d40e7ebb62ef7"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"kaiks/unobot"},"path":{"kind":"string","value":"/lib/misc.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1188,"string":"1,188"},"score":{"kind":"number","value":2.5625,"string":"2.5625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"# TODO: separate logger from the rest\n# require 'extend_logger.rb'\nrequire 'logger'\n\n$logger = Logger.new('logs/unobot.log', 'daily', 10)\n$logger_queue = Queue.new\n$logger.datetime_format = '%H:%M:%S'\n\n$logger_thread = Thread.new do\n loop do\n while $DEBUG == true && $bot && $bot.config.engine.busy == false\n $logger.add(Logger::INFO, $logger_queue.pop)\n end\n sleep(0.5)\n end\nend\n\ndef log(text)\n $logger_queue << ('\\n' << text)\nend\n\ndef bot_debug(text, detail = 1)\n log(text)\n\n if $DEBUG_LEVEL >= detail\n puts \"#{detail >= 3 ? '' : caller[0]} #{text}\"\n end\nend\n\ndef set_debug(level)\n $DEBUG = true\n $DEBUG_LEVEL = level.to_i\nend\n\ndef unset_debug\n $DEBUG = false\n $DEBUG_LEVEL = 0\nend\n\nclass Array\n # array exists and has nth element (1=array start) not null\n def exists_and_has(n)\n size >= n && !at(n - 1).nil?\n end\n\n def equal_partial?(array)\n each_with_index.all? { |a, i| a == :_ || array[i] == :_ || a == array[i] }\n end\nend\n\nclass NilClass\n def exists_and_has(_n)\n false\n end\nend\n\nmodule Misc\n NICK_REGEX = /([a-z_\\-\\[\\]\\\\^{}|`][a-z0-9_\\-\\[\\]\\\\^{}|`]{1,15})'s/i\n NICK_REGEX_PURE = /([a-z_\\-\\[\\]\\\\^{}|`][a-z0-9_\\-\\[\\]\\\\^{}|`]{1,15})/i\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975357,"cells":{"blob_id":{"kind":"string","value":"f058f9161f4811e53e651d66fdcc132612299588"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"pelensky/lrthw"},"path":{"kind":"string","value":"/ex34.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":471,"string":"471"},"score":{"kind":"number","value":4.03125,"string":"4.03125"},"int_score":{"kind":"number","value":4,"string":"4"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"animals = [\"bear\", \"ruby\", \"peacock\", \"kangaroo\", \"whale\", \"platypus\"]\n\nputs \"The animal at 1 is ruby\"\nputs animals[1]\nputs \"The third animal is peacock\"\nputs animals[3-1]\nputs \"The first animal is bear\"\nputs animals[0]\nputs \"The animal at 3 is kangaroo\"\nputs animals[3]\nputs \"The fifth animal whale\"\nputs animals[5-1]\nputs \"The animal at 2 is peacock\"\nputs animals[2]\nputs \"The sixth animal is platypus\"\nputs animals[6-1]\nputs \"the animal at 4 is whale\"\nputs animals[4]\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975358,"cells":{"blob_id":{"kind":"string","value":"80878e5d6076dca59107ace39240663a11ee1ac8"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"shumShum/libgdx-tanks"},"path":{"kind":"string","value":"/bin/src/config/sound_storage.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":451,"string":"451"},"score":{"kind":"number","value":2.5625,"string":"2.5625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"class SoundStorage\n \n SOUND_PATH_BASE = {\n fire: 'res/sounds/fire.wav',\n damage: 'res/sounds/damage.wav',\n explosion: 'res/sounds/explosion1.wav',\n }\n\n attr_reader :sound_base\n\n def initialize\n @sound_base = {}\n SOUND_PATH_BASE.each_pair do |name, path|\n @sound_base[name] = Gdx.audio.newSound(Gdx.files.internal(RELATIVE_ROOT + path)) \n end\n end\n\n def get_by_name(sound_name)\n @sound_base[sound_name.to_sym]\n end\nend"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975359,"cells":{"blob_id":{"kind":"string","value":"e0876c35e82f5f6cb841924662bc35f3a818849d"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"alexgh123/ruby_projects"},"path":{"kind":"string","value":"/sorting.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":395,"string":"395"},"score":{"kind":"number","value":3.9375,"string":"3.9375"},"int_score":{"kind":"number","value":4,"string":"4"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"def bubble_sort(array)\n n = array.length\n p \"hey n = #{n}\"\n loop do\n swapped = false\n\n (n-1).times do |i|\n p \"hey i is changing... it is: #{i}\"\n p \"swapped is: #{swapped}\"\n if array[i] > array[i+1]\n array[i], array[i+1] = array[i+1], array[i]\n swapped = true\n end\n end\n break if not swapped\n end\n array\nend\n\np bubble_sort([1,99,20,13,4,566,11])"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975360,"cells":{"blob_id":{"kind":"string","value":"5bd2846dce2e47b7098eccbc9c4d7f3ed5dcfef3"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"eltonsantos/ruby-simple-files"},"path":{"kind":"string","value":"/rot13.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1046,"string":"1,046"},"score":{"kind":"number","value":3.15625,"string":"3.15625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"secret = {\" \"=>\" \", \"A\"=>\"N\", \"B\"=>\"O\", \"C\"=>\"P\", \"D\"=>\"Q\", \"E\"=>\"R\", \"F\"=>\"S\", \"G\"=>\"T\", \"H\"=>\"U\", \"I\"=>\"V\", \"J\"=>\"W\", \"K\"=>\"X\", \"L\"=>\"Y\", \"M\"=>\"Z\", \"N\"=>\"A\", \"O\"=>\"B\", \"P\"=>\"C\", \"Q\"=>\"D\", \"R\"=>\"E\", \"S\"=>\"F\", \"T\"=>\"G\", \"U\"=>\"H\", \"V\"=>\"I\", \"W\"=>\"J\", \"X\"=>\"K\", \"Y\"=>\"L\", \"Z\"=>\"M\", \"a\"=>\"n\", \"b\"=>\"o\", \"c\"=>\"p\", \"d\"=>\"q\", \"e\"=>\"r\", \"f\"=>\"s\", \"g\"=>\"t\", \"h\"=>\"u\", \"i\"=>\"v\", \"j\"=>\"w\", \"k\"=>\"x\", \"l\"=>\"y\", \"m\"=>\"z\", \"n\"=>\"a\", \"o\"=>\"b\", \"p\"=>\"c\", \"q\"=>\"d\", \"r\"=>\"e\", \"s\"=>\"f\", \"t\"=>\"g\", \"u\"=>\"h\", \"v\"=>\"i\", \"w\"=>\"j\", \"x\"=>\"k\", \"y\"=>\"l\", \"z\"=>\"m\", \"!\"=>\"!\", \"?\"=>\"?\"}\n\npergunta = \"Por que a galinha atravessou a estrada?\"\nresposta = \"Para chegar do outro lado!\"\n\npergunta_codificada = String.new\npergunta.each_char { |char| pergunta_codificada << secret[char] }\n\nresposta_codificada = String.new\nresposta.each_char { |char| resposta_codificada << secret[char] }\n\nputs pergunta\nputs resposta_codificada\n\nputs \"\\n\"\n\nputs pergunta_codificada\nputs resposta\n\nputs \"\\n\"\n\nputs pergunta_codificada\nputs resposta_codificada\n\nputs \"\\n\"\n\nputs pergunta\nputs resposta"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975361,"cells":{"blob_id":{"kind":"string","value":"108757892c14d44adcf7648aa8117ef40bbfa3b4"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"youssefbenlemlih/ruby-practice"},"path":{"kind":"string","value":"/ptp1/classes/text_editor.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1586,"string":"1,586"},"score":{"kind":"number","value":3.90625,"string":"3.90625"},"int_score":{"kind":"number","value":4,"string":"4"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"# A class used to read text files\n# Author:: Youssef Benlemlih\n# Author:: Jonas Krukenberg\nclass TextEditor\n attr_reader :content\n # Initialize a new instance of *TextEditor*\n # with String @content\n # @param path: The path to the text file\n def initialize(path)\n File.open(path) { |f| @content = f.read }\n end\n\n # Returns an array of each word in @param\n def words_to_array\n words = @content.split\n word_list = []\n # filter the words list\n words.each do |word|\n # replace all upcase characters with downcase ones\n w = word.downcase\n # remove all non-letters characters\n w.gsub!(/\\W/, '')\n # remove all whitespaces\n w.gsub!(/\\s+/, '')\n # only all non-empty word to the filtered list\n word_list.push(w) unless w.empty?\n end\n @content = word_list\n nil\n end\n\n # Returns the words list as an array, where each word is inverted\n def reverse_words\n reversed_word_list = []\n @content.each { |word| reversed_word_list.push(word.reverse) }\n # return the reversed word list\n @content = reversed_word_list\n nil\n end\n\n # Saves the given wordlist in a file in the given path wit one word per line\n def to_file(filepath)\n text = @content.join(\"\\n\")\n File.open(filepath, 'w') { |f| f.write text }\n nil\n end\n\n # Returns a Hash where:\n # * *key* is the word\n # * *value* is the occurrence of the usage of the word in the words list\n def words_occurrences\n # the default value of the occurrence of a word is 0\n word_count = Hash.new(0)\n @content.each { |word| word_count[word] += 1 }\n word_count\n end\n\nend"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975362,"cells":{"blob_id":{"kind":"string","value":"6ff71a3aadac96fef685e6c47fb1597b57bd7ab1"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"ranjanisrini/guvi"},"path":{"kind":"string","value":"/compare.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":79,"string":"79"},"score":{"kind":"number","value":3.28125,"string":"3.28125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"def helo\n n = gets.chomp\n y = gets.chomp\nif (n==y)\n true\n else\n false\n end\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975363,"cells":{"blob_id":{"kind":"string","value":"45fd67c15721c85ba3d778629a49bfc48f927462"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"jolohaga/imap_model"},"path":{"kind":"string","value":"/app/models/mail_server.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":3918,"string":"3,918"},"score":{"kind":"number","value":2.53125,"string":"2.53125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["LicenseRef-scancode-unknown-license-reference","MIT"],"string":"[\n \"LicenseRef-scancode-unknown-license-reference\",\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"require 'core_extensions'\nmodule MailServer\n class IMAP\n # Mail::IMAP\n #\n # Description:\n # Wrapper around Net::IMAP\n #\n require 'net/imap'\n attr_accessor :settings, :connection, :query, :authenticated, :messages\n attr_reader :access, :folder, :before, :body, :cc, :from, :on, :since, :subject, :to\n \n # Initialize an IMAP object.\n #\n # Options:\n # :address # string, server's address\n # :username # string, user mail account to connect with\n # :password # string, user password\n # :authentication # string, authentication protocol, options {'login', 'cram-md5'}\n # :enable_ssl # boolean, default false\n #\n # Example:\n # imap = Mail::IMAP.new(:address => '',:username => '',:password => '',:authentication => 'CRAM-MD5')\n #\n def initialize(values = {})\n self.settings = {\n :address => 'localhost',\n :port => 143,\n :username => nil,\n :password => nil,\n :authentication => 'LOGIN',\n :enable_ssl => false,\n :folder => nil,\n :access => nil\n }.merge!(values)\n @authenticated = false\n @query = []\n end\n \n # Open IMAP session.\n #\n # Accepts a hash of options.\n # Options:\n # :folder # string, default 'inbox'\n # :access # string, options: {'read-only', 'read-write'}, default 'read-only'\n #\n # Example:\n # imap.open :folder => 'Sent Messages' do |mailbox|\n # mailbox.search(['from', 'some user').each do |msg_id|\n # puts msg_id\n # end\n # end\n #\n def open(args = {:folder => 'INBOX', :access => 'read-only'})\n self.settings.merge!(args)\n connect\n if settings[:access] == 'read-write'\n @connection.select(settings[:folder])\n else\n @connection.examine(settings[:folder])\n end\n yield(self) if block_given?\n end\n \n def connect\n @connection ||= Net::IMAP.new(settings[:address])\n begin\n @connection.authenticate(settings[:authentication],settings[:username],settings[:password]) unless authenticated\n @authenticated = true\n rescue Net::IMAP::NoResponseError\n \"Failed to authenticate\"\n end\n at_exit {\n begin\n disconnect\n rescue Exception => e\n \"Error closing connection: #{e.class}: #{e.message}.\"\n end\n }\n end\n \n def disconnect\n @connection.disconnect\n @connection = nil\n @authenticated = false\n end\n \n def connected?\n ! connection.nil? && ! connection.disconnected?\n end\n \n def access(access = 'read-only')\n @access = access\n self\n end\n \n def folder(folder = 'INBOX')\n @folder = folder\n end\n \n def before(date = Date.today)\n query.push('BEFORE',date.to_imap)\n self\n end\n \n def body(string)\n query.push('BODY',string)\n self\n end\n \n def cc(string)\n query.push('CC',string)\n self\n end\n \n def from(string)\n query.push('FROM',string)\n self\n end\n \n def update\n self\n end\n \n def on(date = Date.today)\n query.push('ON',date.to_imap)\n self\n end\n \n def since(date = Date.today - 14)\n query.push('SINCE',date.to_imap)\n self\n end\n \n def subject(string)\n query.push('SUBJECT',string)\n self\n end\n \n def to(string)\n query.push('TO',string)\n self\n end\n \n def search(criteria = nil)\n scratch = criteria.nil? ? query.clone : criteria\n clear_query\n connection.search(scratch)\n end\n \n def clear_query\n @query = []\n end\n \n def fetch(seq_nos = [],attributes = 'BODY')\n @messages = connection.fetch(seq_nos,attributes) unless seq_nos.empty?\n end\n \n def uid_fetch(arr = [])\n \n end\n end\nend"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975364,"cells":{"blob_id":{"kind":"string","value":"7ba612ede0baf65d596ecbaa27293ddb047251d9"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"arvidnilber/standard-biblioteket"},"path":{"kind":"string","value":"/lib/power.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":134,"string":"134"},"score":{"kind":"number","value":3.1875,"string":"3.1875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"def power(num1,up)\n i = 0 \n output = 1 \n while i < up\n output *= num1 \n i += 1 \n end\n return output\nend\n\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975365,"cells":{"blob_id":{"kind":"string","value":"a1cbb184cdf6a1b80139e28fb575699de359feb1"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"anners/ruby"},"path":{"kind":"string","value":"/reverse-string"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":360,"string":"360"},"score":{"kind":"number","value":3.59375,"string":"3.59375"},"int_score":{"kind":"number","value":4,"string":"4"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"#!/usr/bin/env ruby\n\nstring = \"beer\"\n\nputs string\n\nputs string.reverse\n\narray = [\"b\", \"e\", \"e\", \"r\"]\n\narray.reverse.each do |a|\n\tprint a\nend\n\nyarra = Array.new\nyarra << array.pop until array.empty?\n\nprint yarra\n\n\n\narray = [\"b\", \"e\", \"e\", \"r\"]\n\ndef rev(array)\n x = array.pop\n rev(array) if array.length > 0\n array.unshift x\nend\n\nputs rev(array).inspect \n\n\n\n\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975366,"cells":{"blob_id":{"kind":"string","value":"9b053de63a29dde735ff362986c2605dc97703aa"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"alexharv074/puppet-strings"},"path":{"kind":"string","value":"/lib/puppet-strings/yard/util.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1265,"string":"1,265"},"score":{"kind":"number","value":2.546875,"string":"2.546875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["Apache-2.0"],"string":"[\n \"Apache-2.0\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"require 'puppet/util'\n\n# The module for various puppet-strings utility helpers.\nmodule PuppetStrings::Yard::Util\n # Trims indentation from trailing whitespace and removes ruby literal quotation\n # syntax `%Q{}` and `%{q}` from parsed strings.\n # @param [String] str The string to scrub.\n # @return [String] A scrubbed string.\n def self.scrub_string(str)\n match = str.match(/^%[Qq]{(.*)}$/m)\n if match\n return Puppet::Util::Docs.scrub(match[1])\n end\n\n Puppet::Util::Docs.scrub(str)\n end\n\n # hacksville, usa\n # YARD creates ids in the html with with the style of \"label-Module+description\", where the markdown\n # we use in the README involves the GitHub-style, which is #module-description. This takes our GitHub-style\n # links and converts them to reference the YARD-style ids.\n # @see https://github.com/octokit/octokit.rb/blob/0f13944e8dbb0210d1e266addd3335c6dc9fe36a/yard/default/layout/html/setup.rb#L5-L14\n # @param [String] data HTML document to convert\n # @return [String] HTML document with links converted\n def self.github_to_yard_links(data)\n data.scan(/href\\=\\\"\\#(.+)\\\"/).each do |bad_link|\n data.gsub!(\"=\\\"##{bad_link.first}\\\"\", \"=\\\"#label-#{bad_link.first.capitalize.gsub('-', '+')}\\\"\")\n end\n data\n end\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975367,"cells":{"blob_id":{"kind":"string","value":"f4b9571473abeb92a0888911b7929c6e44c8f417"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"asiandcs/baseballbot_discord"},"path":{"kind":"string","value":"/baseball_discord/commands/links.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":847,"string":"847"},"score":{"kind":"number","value":2.515625,"string":"2.515625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"# frozen_string_literal: true\n\nmodule BaseballDiscord\n module Commands\n # Basic debug commands that should log to the output file\n module Links\n extend Discordrb::Commands::CommandContainer\n\n command(:bbref, help_available: false) do |event, *args|\n LinksCommand.new(event, *args).bbref\n end\n\n command(:fangraphs, help_available: false) do |event, *args|\n LinksCommand.new(event, *args).fangraphs\n end\n\n # Prints some basic info to the log file\n class LinksCommand < Command\n def bbref\n 'https://www.baseball-reference.com/search/search.fcgi?search=' +\n CGI.escape(args.join(' '))\n end\n\n def fangraphs\n 'https://www.fangraphs.com/players.aspx?new=y&lastname=' +\n CGI.escape(args.join(' '))\n end\n end\n end\n end\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975368,"cells":{"blob_id":{"kind":"string","value":"a1a97dff36f7bc6a6f21e474242bbc46da973d40"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"kmbhuvanprasad/ruby_set4"},"path":{"kind":"string","value":"/modules/1.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":211,"string":"211"},"score":{"kind":"number","value":3.390625,"string":"3.390625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"module W4\n\n\tdef z1\n\t\tputs \"I am number 1\"\n\tend\n\n\tdef z3\n\t\tputs \"I am number 3\"\n\tend\n\n\tdef nUMBER_4\n\t\tputs \"I am number 4\"\n\tend\n\nend\n\n\nclass Q4\n\tinclude W4\nend\n\nnumber = Q4.new\nnumber.z1\nnumber.z3\nnumber.nUMBER_4"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975369,"cells":{"blob_id":{"kind":"string","value":"f7f5a843c92857a0a41cdbf62c91496cfb9c7c10"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"anukin/game_of_life-9_07"},"path":{"kind":"string","value":"/spec/gameoflife/board_spec.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":686,"string":"686"},"score":{"kind":"number","value":2.671875,"string":"2.671875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"require 'spec_helper'\n\nmodule Gameoflife\n describe \"Cell\" do\n it \"should generate the next generation\" do\n board = Board.new(3, 4)\n curr_gen = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]\n nex_gen = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]\n board.set_current_generation(curr_gen)\n expect(board.next_generation).to eq(nex_gen)\n end\n\n it \"should generate the next generation based on current generation\" do\n board = Board.new(3, 3)\n curr_gen = [[0, 1, 0], [0, 0, 1], [1, 0, 0]]\n nex_gen = [[0, 1, 0], [0, 1, 1], [1, 0, 0]]\n board.set_current_generation(curr_gen)\n expect(board.next_generation).to eq(nex_gen)\n end\n end\nend\n\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975370,"cells":{"blob_id":{"kind":"string","value":"033355d4596a85c44409c9b1a2c837dda5c3c0b3"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"JRSoftware92/Android-Class-Generator"},"path":{"kind":"string","value":"/AXMLGenerator/src/main/android_sqlite_reader.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":4269,"string":"4,269"},"score":{"kind":"number","value":3.015625,"string":"3.015625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"require_relative 'sqlite_reader.rb'\nrequire_relative 'sqlite_model.rb'\n\n#Class for reading DDL and DML SQLite files\n#TODO Rewrite to export generic xml data for template generation and utilize generic regex parser\n#CAN BE DONE FOR BOTH DDL AND DML\nclass ASqliteReader# < SqliteParser\n\tinclude Sqlite\n\t\n\t#DDL_REGEX = /[a-zA-Z0-9_]+\\({1}(?:[\\s\\,]*[a-zA-Z]+\\s*)+(?:\\)\\;){1}/\n\tTABLE_REGEX = /(?[a-zA-Z0-9_]+)\\({1}(?(?:[\\s\\,]*[a-zA-Z]+\\s*)+)(?:\\)\\;){1}/\n\n\tdef initialize\n\t\t#super\n\t\t@select_queries = []\n\t\t@insert_queries = []\n\t\t@update_queries = []\n\t\t@delete_queries = []\n\t\t@tables = []\n\tend\n\t\n\t#Reads in queries\n\tdef read_ddl_file(filename)\n\t\tFile.foreach(filename) do |line|\n\t\t\textract_table_from line\n\t\tend\n\tend\n\t\n\t#Reads in queries\n\tdef read_dml_file(filename)\n\t\tFile.foreach(filename) do |line|\n\t\t\textract_query_from line\n\t\tend\n\tend\n\t\n\t#Extracts table declarations from the given line and extracts the data as table objects into the local table array\n\tdef extract_table_from(line)\n\t\tmatchdata = line.scan(TABLE_REGEX)\n\t\tmatchdata.each do |name, param_str|\n\t\t\tparameters = extract_table_parameters_from param_str\n\t\t\ttable = Sqlite::Table.new(name, parameters)\n\t\t\t@tables << table\n\t\tend\n\tend\n\t\n\t#Extracts the table parameters from a given string and outputs them as an array\n\tdef extract_table_parameters_from(str)\n\t\tif str.nil? || str.size < 1 then\n\t\t\treturn []\n\t\tend\n\t\t\n\t\tif !str.include? ',' then\n\t\t\treturn str\n\t\telse\n\t\t\treturn str.split ','\n\t\tend\n\t\t\n\tend\n\t\n\t#Extracts a Sqlite Query object from the sql string\n\tdef extract_query_from(line)\n\t\t#Remove leading and trailing whitespace\n\t\ttemp = line.upcase.strip\n\t\t#Retrieve the index of the name-query delimiter\n\t\tindex = temp.index(':')\n\t\t\n\t\tif !index.nil? && index > -1 then\n\t\t\t#Function name of the query\n\t\t\tname = line[0,index]\n\t\t\t#SQLite query\n\t\t\tstatement = line[index + 1, temp.length]\n\t\t\t#Parametric arguments of the query\n\t\t\targs = extract_parameters_from statement\n\t\t\t\n\t\t\tif statement.include? 'SELECT' then\n\t\t\t\t@select_queries << Sqlite::Query.new(name, statement, args, 'SELECT')\n\t\t\tend\n\t\t\t\n\t\t\tif statement.include? 'INSERT' then\n\t\t\t\t@insert_queries << Sqlite::Query.new(name, statement, args, 'INSERT')\n\t\t\tend\n\t\t\t\n\t\t\tif statement.include? 'UPDATE' then\n\t\t\t\t@update_queries << Sqlite::Query.new(name, statement, args, 'UPDATE')\n\t\t\tend\n\t\t\t\n\t\t\tif statement.include? 'DELETE' then\n\t\t\t\t@delete_queries << Sqlite::Query.new(name, statement, args, 'DELETE')\n\t\t\tend\n\t\tend\n\tend\n\t\n\tdef queries\n\t\treturn select_queries + insert_queries + update_queries + delete_queries\n\tend\n\t\n\tdef select_queries\n\t\treturn @select_queries\n\tend\n\t\n\tdef select_queries_sql\n\t\treturn objects_to_sql @select_queries\n\tend\n\t\n\tdef select_queries_xml\n\t\treturn objects_to_xml @select_queries\n\tend\n\t\n\tdef insert_queries\n\t\treturn @insert_queries\n\tend\n\t\n\tdef insert_queries_sql\n\t\treturn objects_to_sql @insert_queries\n\tend\n\t\n\tdef insert_queries_xml\n\t\treturn objects_to_xml @insert_queries\n\tend\n\t\n\tdef update_queries\n\t\treturn @update_queries\n\tend\n\t\n\tdef update_queries_sql\n\t\treturn objects_to_sql @update_queries\n\tend\n\t\n\tdef update_queries_xml\n\t\treturn objects_to_xml @update_queries\n\tend\n\t\n\tdef delete_queries\n\t\treturn @delete_queries\n\tend\n\t\n\tdef delete_queries_sql\n\t\treturn objects_to_sql @delete_queries\n\tend\n\t\n\tdef delete_queries_xml\n\t\treturn objects_to_xml @delete_queries\n\tend\n\t\n\tdef tables\n\t\treturn @tables\n\tend\n\t\n\tdef table_statements_sql\n\t\treturn objects_to_sql @tables\n\tend\n\t\n\tdef table_statements_xml\n\t\treturn objects_to_xml @tables\n\tend\n\t\n\t#Converts an array of query objects to an array of sql strings\n\tdef objects_to_sql(objects)\n\t\tif objects.nil? || objects.size < 1 then\n\t\t\treturn []\n\t\tend\n\t\n\t\tobjects.each do |object|\n\t\t\toutput << object.to_sql\n\t\tend\n\t\t\n\t\treturn output\n\tend\n\t\n\t#Converts an array of query objects to an array of android xml string resources\n\tdef objects_to_xml(objects)\t\t\n\t\tif objects.nil? || objects.size < 1 then\n\t\t\treturn []\n\t\tend\n\t\n\t\toutput = []\n\t\t\n\t\tobjects.each do |object|\n\t\t\toutput << object.to_xml\n\t\tend\n\t\t\n\t\treturn output\n\tend\n\t\n\tdef print_debug\n\t\tputs 'Tables: '\n\t\ttemp = @tables\n\t\tif !temp.nil? then\n\t\t\ttemp.each do |table|\n\t\t\t\ttable.print_debug\n\t\t\tend\n\t\tend\n\t\t\n\t\tputs 'Queries: '\n\t\ttemp = queries\n\t\tif !temp.nil? then\n\t\t\ttemp.each do |query|\n\t\t\t\tquery.print_debug\n\t\t\tend\n\t\tend\n\tend\nend"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975371,"cells":{"blob_id":{"kind":"string","value":"a59f73504c05ebe1bf845f2206ff7dab503c3876"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"steve-alex/anagram-detector-london-web-082619"},"path":{"kind":"string","value":"/lib/anagram.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":361,"string":"361"},"score":{"kind":"number","value":3.6875,"string":"3.6875"},"int_score":{"kind":"number","value":4,"string":"4"},"detected_licenses":{"kind":"list like","value":["LicenseRef-scancode-public-domain","LicenseRef-scancode-unknown-license-reference"],"string":"[\n \"LicenseRef-scancode-public-domain\",\n \"LicenseRef-scancode-unknown-license-reference\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"# Your code goes here!\nclass Anagram\n\n @@all=[]\n\n attr_accessor\n\n def initialize(word)\n @word = word\n @@all << self\n end\n\n def self.all\n @@all\n end\n\n def sort_word(word)\n word.chars.sort!.to_s\n end\n\n def match(anagram)\n anagram.each.select{ |word| sort_word(word) == sort_word(@word) }\n end\n\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975372,"cells":{"blob_id":{"kind":"string","value":"326e7c03b5c2b4c9ecdd6aacc7bf20329cc18896"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"xababafr/RubyPFE"},"path":{"kind":"string","value":"/implementation/resl_compiler.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2976,"string":"2,976"},"score":{"kind":"number","value":3.015625,"string":"3.015625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"# the compiler takes ruby code as an input, and can :\n# - add probes\n# - generate the ast\n# - simulate the code to infer types\n# - do all those 3 and create a systemC code\n\nrequire \"./resl_data\"\nrequire \"./resl_objects\"\nrequire \"./resl_objectifier\"\nrequire \"./resl_dsl\"\nrequire \"./resl_simulator\"\nrequire \"./visitors/systemc\"\nrequire \"./visitors/prettyprinter\"\nrequire \"./visitors/addprobes\"\n\nmodule RubyESL\n\n\n class Compiler\n def initialize\n\n end\n\n def get_ast filename, convert = false\n objectifier = Objectifier.new filename, convert\n ret = objectifier.methods_objects\n ret[:sys] = objectifier.sys_ast\n\n puts \"\\n\\n\"\n pp ret[[:Sourcer,:source]]\n\n ret\n # .methods_ast would give the original non objectified ast\n end\n\n def add_probes filename\n add_probes = AddProbes.new filename\n add_probes.generate_file\n end\n\n def eval_dsl filename\n rcode=IO.read(filename)\n eval(rcode)\n end\n\n def deep_copy(o)\n Marshal.load(Marshal.dump(o))\n end\n\n\n def simulate sys\n sys.ordered_actors.each do |actor|\n actor_threads = Actor.get_threads[actor.class.get_klass()]\n actor_threads.each do |thread|\n fiber = Fiber.new do\n actor.method(thread).call\n end\n DATA.simulator.add_fiber(\"#{actor.class.get_klass}.#{thread}\" , fiber)\n end\n end\n DATA.simulator.run\n end\n\n def get_init_params sys\n initParams = {}\n sys.ordered_actors.each do |actor|\n key = [actor.class.get_klass(), actor.name]\n initParams[key] = actor.method(:initialize).parameters\n\n if actor.initArgs.size > 0\n actor.initArgs.each_with_index do |argHash, i|\n initParams[key][i+1] << argHash\n end\n end\n end\n initParams\n end\n\n def generate_systemc filename\n puts \"\\n\\n\\n\"\n puts \"[STEP 1 : GET INPUT'S CODE AST]\".center(80,\"=\")\n puts \"\\n\\n\\n\"\n ast = get_ast filename\n s_ast = get_ast filename, true\n\n puts \"\\n\\n\\n\"\n puts \"[STEP 2 :ADD PROBES TO THE CODE]\".center(80,\"=\")\n puts \"\\n\\n\\n\"\n root = Root.new ast, {}, Actor.get_threads() # + it collects the data from DATA\n root.accept AddProbes.new\n\n File.open(\"P_#{filename}\",'w'){|f| f.puts(root.sourceCode)}\n\n sys = eval_dsl ( \"P_\" + filename )\n\n puts \"\\n\\n\\n\"\n puts \"[STEP 3 : SIMULATE THE CODE TO INFER TYPES]\".center(80,\"=\")\n puts \"\\n\\n\\n\"\n simulate sys\n\n puts \"\\n\\n\"\n pp DATA.instance_vars\n puts \"\\n\\n\"\n pp DATA.local_vars\n puts \"\\n\\n\"\n\n initParams = get_init_params sys\n\n puts \"\\n\\n\\n\"\n puts \"[STEP 4 : GENERATE THE SYSTEMC CODE]\".center(80,\"=\")\n puts \"\\n\\n\\n\"\n root = Root.new s_ast, initParams, Actor.get_threads()\n root.accept SystemC.new\n end\n\n end #Compiler\n\n\nend #MTS\n\n\n\n\n\nif $PROGRAM_NAME == __FILE__\n compiler = RubyESL::Compiler.new\n compiler.generate_systemc \"#{ARGV[0]}\"\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975373,"cells":{"blob_id":{"kind":"string","value":"f8f56633de925adf7bf5615ee7191495e5b55e43"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"viing937/codeforces"},"path":{"kind":"string","value":"/src/400B.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":223,"string":"223"},"score":{"kind":"number","value":2.953125,"string":"2.953125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"n, m = gets.split.collect{|i| i.to_i}\nans = Array.new(n)\nn.times do |i|\n s = gets.chomp\n d = s.index(\"G\")\n c = s.index(\"S\")\n if d > c\n puts -1\n exit\n end\n ans[i] = c-d\nend\nputs ans.uniq.size\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975374,"cells":{"blob_id":{"kind":"string","value":"f6531a107f9053c1e75a359c8917322bf5c90a82"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"somalipirat3/GameTracker"},"path":{"kind":"string","value":"/lib/modules/consume_api/tracker_data_only.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1615,"string":"1,615"},"score":{"kind":"number","value":2.640625,"string":"2.640625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"# Tracker.gg api\n# Full profile requests \nclass ConsumeApi::TrackerDataOnly\n include HTTParty\n\n def initialize(options = {})\n @data = options\n @api_key = Rails.application.credentials.api_keys[:tracker_gg][:key]\n endpoint = Rails.application.credentials.api_keys[:tracker_gg][:endpoint]\n @endpoint = \"#{endpoint}apex/standard/profile/#{@data[:platform]}/#{@data[:username]}\"\n @response = self.class.get(@endpoint, headers: {\"TRN-Api-Key\": @api_key})\n end\n\n def player\n return @response['data']['platformInfo']\n end\n\n def segments\n segments = []\n @response['data']['segments'].each do |segment|\n if segment['type'] == \"legend\"\n segments << {\n legendName: legend(segment),\n stat: stats(segment)\n }\n end\n end\n return segments\n end\n\n private\n\n def stats(stats)\n new_stats = []\n stats['stats'].each do |stat|\n new_stats.push({\n rank: stat[1]['rank'],\n percentile: stat[1]['percentile'],\n displayName: stat[1]['displayName'],\n displayCategory: stat[1]['displayCategory'],\n category: stat[1]['category'],\n metadata: stat[1]['metadata'],\n value: stat[1]['value'],\n displayValue: stat[1]['displayValue'],\n displayType: stat[1]['displayType']\n })\n end\n return new_stats\n end\n\n def legend (segment)\n segment['metadata']['name']\n end\n\n\nend"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975375,"cells":{"blob_id":{"kind":"string","value":"738af5499acde1463b603abd941ef9d77787dd23"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"omajul85/oystercard"},"path":{"kind":"string","value":"/spec/journey_spec.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":991,"string":"991"},"score":{"kind":"number","value":2.65625,"string":"2.65625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"require \"journey\"\n\ndescribe Journey do\n\tsubject(:journey) { described_class.new }\n\tlet(:station) { double :station, zone: 1 }\n\n\tit \"journey should not be completed\" do\n\t\texpect(journey).not_to be_completed\n\tend\n\n\tit 'has a penalty fare by default' do\n expect(subject.fare).to eq described_class::PENALTY_FEE\n end\n\n\tcontext \"given an entry station\" do\n\n\t before do\n\t journey.start(station)\n\t end\n\n\t it \"has an entry station\" do\n\t\t\texpect(journey.entry_station).to eq station\n\t\tend\n\n\t\tit \"returns a penalty fee if no exit station given\" do\n expect(journey.fare).to eq described_class::PENALTY_FEE\n end\n\n context \"and an exit station\" do\n let(:exit_station) { double :station, zone: 1 }\n\n before do\n journey.finish(exit_station)\n end\n\n it \"calculates a fare\" do\n expect(journey.fare).to eq described_class::MINIMUM_FARE\n end\n\n it \"knows if a journey is completed\" do\n expect(journey).to be_completed\n end\n end\n\tend\nend"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975376,"cells":{"blob_id":{"kind":"string","value":"f6622987eefcd67dfc0fb13290b667f403aa48ab"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"tetetratra/contest"},"path":{"kind":"string","value":"/leetcode/6_16/3.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":237,"string":"237"},"score":{"kind":"number","value":3.328125,"string":"3.328125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"# https://leetcode.com/problems/rotate-function/\n\ndef max_rotate_function(nums)\n nums.size.times.map { |n| nums.rotate(n) }.map { |arr|\n arr.map.with_index { |a, i| a * i }.sum\n }.max\nend\nnums = [4,3,2,6]\nmax_rotate_function(nums)\n\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975377,"cells":{"blob_id":{"kind":"string","value":"2e23550093914cb6290721de13f2f996a0c514cd"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"milesstanfield/whats-for-lunch"},"path":{"kind":"string","value":"/spec/services/time_formatter_spec.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":646,"string":"646"},"score":{"kind":"number","value":2.5625,"string":"2.5625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"require 'spec_helper'\n\ndescribe TimeFormatter do\n describe '.visit_time(time)' do\n it 'formats time' do\n expect(TimeFormatter.visit_time(now_time)).to eq '02/09/2016'\n end\n end\n\n describe '.days_ago(formatted_time)' do\n it 'returns days since time argument' do\n control_time = Time.parse('2016-02-11 08:53:34 -0500')\n expect(TimeFormatter.days_ago('02/05/2016', control_time)).to eq 6\n end\n end\n\n describe '.parsed_visit_time(visited_time)' do\n it 'returns time object from strftime string' do\n expect(TimeFormatter.parsed_visit_time('02/05/2016').to_s).to eq '2016-02-05 00:00:00 -0500'\n end\n end\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975378,"cells":{"blob_id":{"kind":"string","value":"713714e42caa50fe0c0d22b1e6661582214e88a1"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"Bielfla27/gerenciamento-servicos"},"path":{"kind":"string","value":"/test/models/usuario_test.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1502,"string":"1,502"},"score":{"kind":"number","value":2.625,"string":"2.625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"require \"test_helper\"\n\nclass UsuarioTest < ActiveSupport::TestCase\n \n\n test \"deve salvar Usuario criado corretamente\" do\n usuario = Usuario.new nome: 'Usuario Teste',\n cpf: '39775387485',\n funcao: 'Confeiteiro',\n password: 'password1'\n\n assert usuario.save\n end\n\n test \"nao deve salvar Usuario com password menor que 8 caracteres\" do\n usuario = Usuario.new nome: 'Usuario Teste',\n cpf: '39775387485',\n funcao: 'Confeiteiro',\n password: 'passw'\n\n assert_not usuario.save\n end\n\n test \"nao deve salvar Usuario criado com cpf com letras\" do\n usuario = Usuario.new nome: 'Usuario Teste',\n cpf: 'sda397753aa',\n funcao: 'Confeiteiro',\n password: 'password01'\n\n assert_not usuario.save\n end\n #terceira iteração---------------------------------------------\n test \"nao deve salvar Usuario criado com cpf invalido\" do\n usuario = Usuario.new nome: 'Usuario Teste',\n cpf: '00000000000',\n funcao: 'Confeiteiro',\n password: 'password01'\n\n assert_not usuario.save\n end\n test \"nao deve salvar Usuario sem funcao\" do\n usuario = Usuario.new nome: 'Usuario Teste',\n cpf: '39775387485',\n funcao: '',\n password: 'password01'\n\n assert_not usuario.save\n end\n test \"nao deve salvar Usuario com nome maior que 35 caracteres\" do\n usuario = Usuario.new nome: 'Maria Raphaela Gonzaga da Rocha e Silva',\n cpf: '39775387485',\n funcao: 'Vendedora',\n password: 'password01'\n\n assert_not usuario.save\n end\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975379,"cells":{"blob_id":{"kind":"string","value":"70fdac1013f6b45b05ed53415f50f4c25c9f56b5"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"schazbot/oo-relationships-practice-london-web-career-021819"},"path":{"kind":"string","value":"/app/models/user.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1420,"string":"1,420"},"score":{"kind":"number","value":3,"string":"3"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"class User\n\n attr_reader :name\n\n @@all = []\n\n def self.all\n @@all\n end\n\n def initialize(name)\n @name = name\n @@all << self\n end\n\n\n def make_pledge(project, amount)\n Pledge.new(self, project, amount)\n end\n\n def make_project(project_name, goal_amount)\n Project.new(project_name, self, goal_amount)\n end\n\n def pledges\n Pledge.all.select {|pledge| pledge.user == self}\n end\n\n def pledges_count\n pledges.count\n end\n\n def projects_made\n Pledge.all.select {|pledge| pledge.project.created_by == self}\n end\n\n def projects_made_count\n Pledge.all.select {|pledge| pledge.project.created_by == self}.count\n end\n\n def self.all_pledge_amounts_sort\n highest = Pledge.all.map {|pledge| pledge.amount}.sort!\n highest.last\n end\n\n def self.highest_pledge\n Pledge.all.find {|pledge| pledge.amount == all_pledge_amounts_sort}.user.name\n end\n\n def self.pledger_names\n Pledge.all.map {|pledge| pledge.user.name}\n end\n\n def self.multi_pledger\n # returns all users who have pledged to multiple projects\n @@all.select {|user_instance| user_instance.pledges_count > 1}\n end\n\n def self.project_creator\n @@all.select{|user_instance| user_instance.projects_made_count > 0}\n #returns all users who have created a project\n end\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975380,"cells":{"blob_id":{"kind":"string","value":"0173a501f107144afd808149940aa2f7d2d113f8"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"bethanyr/RubyFall2013"},"path":{"kind":"string","value":"/week4/exercises/timer_spec.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":663,"string":"663"},"score":{"kind":"number","value":2.96875,"string":"2.96875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["Apache-2.0"],"string":"[\n \"Apache-2.0\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"require './code_timer.rb'\n\ndescribe CodeTimer do \n\n it \"should run our code\" do\n flag = false\n\n CodeTimer.time_code do\n flag = true\n end\n\n flag.should eq true\n \n end\n\n it \"should time our code\" do\n Time.stub(:now).and_return(0,3)\n run_time = CodeTimer.time_code do\n end\n\n run_time.should be_within(0.1).of(3.0)\n\n end\n\n it \"should run our code multiple times \" do\n i = 0\n CodeTimer.time_code(10){ i+=1 }\n i.should eq 10\n end\n\n it \"should give us the average time\" do\n Time.stub(:now).and_return(0,10)\n run_time = CodeTimer.time_code(10) {\n }\n run_time.should be_within(0.1).of(1.0)\n end\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nend"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975381,"cells":{"blob_id":{"kind":"string","value":"2854882d1c23783acb0566f985cf0822107445ae"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"marshallshen/bootcamp"},"path":{"kind":"string","value":"/ruby/closest_palindrome.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2453,"string":"2,453"},"score":{"kind":"number","value":3.6875,"string":"3.6875"},"int_score":{"kind":"number","value":4,"string":"4"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"# @param {String} n\n# @return {String}\n# https://leetcode.com/problems/find-the-closest-palindrome/description/\ndef nearest_palindromic(n)\n nums = n.split(\"\")\n\n if nums.size == 1\n return (n.to_i - 1).to_s\n end\n\n cand1 = palindrom_by_mirror(nums)\n cand2 = palindrom_by_increment(nums)\n cand3 = palindrom_by_decrement(nums)\n cand4 = palindrom_for_palindrom_decrement(nums)\n cand5 = palindrom_for_palindrom_increment(nums)\n\n puts \"cands: #{[cand1, cand2, cand3, cand4, cand5]}, n: #{n}\"\n\n cands = [cand1, cand2, cand3, cand4, cand5].compact.group_by{|c| (c.to_i - n.to_i).abs }.min.last\n cands.map(&:to_i).min.to_s\nend\n\ndef palindrom_for_palindrom_decrement(nums)\n first_half, second_half = nums.each_slice((nums.size / 2.0).round).to_a\n first_half = (first_half.join(\"\").to_i - 1).to_s.split(\"\")\n second_half = first_half[0, second_half.size].reverse\n\n return (first_half + second_half).join(\"\")\nend\n\ndef palindrom_for_palindrom_increment(nums)\n first_half, second_half = nums.each_slice((nums.size / 2.0).round).to_a\n first_half = (first_half.join(\"\").to_i + 1).to_s.split(\"\")\n second_half = first_half[0, second_half.size].reverse\n\n return (first_half + second_half).join(\"\")\nend\n\ndef palindrom_by_mirror(nums)\n local_nums = nums.clone\n iter, mid = 0, local_nums.size / 2\n while(iter < mid)\n local_nums[local_nums.size - 1 - iter] = local_nums[iter]\n iter += 1\n end\n\n return nil if local_nums == nums\n\n return local_nums.join(\"\")\nend\n\ndef palindrom_by_increment(nums)\n local_nums = nums.clone\n mid = local_nums.size / 2\n if local_nums[mid].to_i == 9\n first_half, second_half = nums.each_slice((nums.size / 2.0).round).to_a\n first_half = (first_half.join(\"\").to_i + 1).to_s.split(\"\")\n second_half = first_half[0, second_half.size].reverse\n local_nums = first_half + second_half\n return local_nums.join(\"\")\n end\n\n return nil\nend\n\ndef palindrom_by_decrement(nums)\n local_nums = nums.clone\n mid = local_nums.size / 2\n\n first_half, second_half = nums.each_slice((nums.size / 2.0).round).to_a\n return \"9\" if first_half == [\"1\"]\n\n if local_nums[mid].to_i == 0\n first_half = (first_half.join(\"\").to_i - 1).to_s.split(\"\")\n\n second_half = first_half[0, second_half.size].reverse\n if nums.size % 2 == 0\n local_nums = first_half + [\"9\"] + second_half\n else\n local_nums = first_half + second_half\n end\n\n return local_nums.join(\"\")\n end\n\n return nil\nend"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975382,"cells":{"blob_id":{"kind":"string","value":"3fa56c9a5165d35b68462214dab0800008978225"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"moqingxinai/pujara-emnlp17"},"path":{"kind":"string","value":"/scripts/data-processing/psl/prep.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":12278,"string":"12,278"},"score":{"kind":"number","value":2.75,"string":"2.75"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"# Create the files that PSL will use.\n# Processing:\n# - Copy over the id mapping files (not necessary, but convenient).\n# - Convert all ids in triple files from string identifiers to int identifiers.\n# - List out all the possible targets (test triples and their corruptions).\n# - Compute and output all the energy of all triples (targets).\n#\n# To save space (since there are typically > 400M targets), we will only write out energies\n# that are less than some threshold.\n# To signify an energy value that should not be included, the respective tripleEnergy() methods\n# will return first return a value of false and then the actual energy value.\n# We still return the actual energy so we can log it for later statistics.\n#\n# We make no strides to be overly efficient here, just keeping it simple.\n# We will check to see if a file exists before creating it and skip that step.\n# If you want a full re-run, just delete the offending directory.\n\nrequire_relative '../../lib/constants'\nrequire_relative '../../lib/embedding/energies'\nrequire_relative '../../lib/embedding/load'\nrequire_relative '../../lib/load'\n\nrequire 'etc'\nrequire 'fileutils'\nrequire 'set'\n\n# gem install thread\nrequire 'thread/channel'\nrequire 'thread/pool'\n\nNUM_THREADS = Etc.nprocessors - 1\nSKIP_BAD_ENERGY = false\nMIN_WORK_PER_THREAD = 50\nWORK_DONE_MSG = '__DONE__'\n\nTARGETS_FILE = 'targets.txt'\nENERGY_FILE = 'energies.txt'\nENERGY_STATS_FILE = 'energyStats.txt'\n\ndef copyMappings(datasetDir, outDir)\n if (!File.exists?(File.join(outDir, Constants::RAW_ENTITY_MAPPING_FILENAME)))\n FileUtils.cp(File.join(datasetDir, Constants::RAW_ENTITY_MAPPING_FILENAME), File.join(outDir, Constants::RAW_ENTITY_MAPPING_FILENAME))\n end\n\n if (!File.exists?(File.join(outDir, Constants::RAW_RELATION_MAPPING_FILENAME)))\n FileUtils.cp(File.join(datasetDir, Constants::RAW_RELATION_MAPPING_FILENAME), File.join(outDir, Constants::RAW_RELATION_MAPPING_FILENAME))\n end\nend\n\ndef loadIdTriples(path)\n triples = []\n\n File.open(path, 'r'){|file|\n file.each{|line|\n triples << line.split(\"\\t\").map{|part| part.strip().to_i()}\n }\n }\n\n return triples\nend\n\ndef convertIdFile(inPath, outPath, entityMapping, relationMapping)\n if (File.exists?(outPath))\n return\n end\n\n triples = []\n\n File.open(inPath, 'r'){|file|\n file.each{|line|\n parts = line.split(\"\\t\").map{|part| part.strip()}\n\n parts[Constants::HEAD] = entityMapping[parts[Constants::HEAD]]\n parts[Constants::RELATION] = relationMapping[parts[Constants::RELATION]]\n parts[Constants::TAIL] = entityMapping[parts[Constants::TAIL]]\n\n triples << parts\n }\n }\n\n File.open(outPath, 'w'){|file|\n file.puts(triples.map{|triple| triple.join(\"\\t\")}.join(\"\\n\"))\n }\nend\n\ndef convertIds(datasetDir, outDir, entityMapping, relationMapping)\n convertIdFile(File.join(datasetDir, Constants::RAW_TEST_FILENAME), File.join(outDir, Constants::RAW_TEST_FILENAME), entityMapping, relationMapping)\n convertIdFile(File.join(datasetDir, Constants::RAW_TRAIN_FILENAME), File.join(outDir, Constants::RAW_TRAIN_FILENAME), entityMapping, relationMapping)\n convertIdFile(File.join(datasetDir, Constants::RAW_VALID_FILENAME), File.join(outDir, Constants::RAW_VALID_FILENAME), entityMapping, relationMapping)\nend\n\n# Generate each target and compute the energy for each target.\n# We do target generation and energy computation in the same step so we do not urite\n# targets that have too high energy.\ndef computeTargetEnergies(datasetDir, embeddingDir, outDir, energyMethod, maxEnergy, entityMapping, relationMapping)\n if (File.exists?(File.join(outDir, ENERGY_FILE)))\n return\n end\n\n targetsOutFile = File.open(File.join(outDir, TARGETS_FILE), 'w')\n energyOutFile = File.open(File.join(outDir, ENERGY_FILE), 'w')\n\n entityEmbeddings, relationEmbeddings = LoadEmbedding.vectors(embeddingDir)\n targets = loadIdTriples(File.join(outDir, Constants::RAW_TEST_FILENAME))\n\n # The number of corruptions written to disk.\n # We need to keep track so we can assign surrogate keys.\n targetsWritten = 0\n\n # All the corruptions we have seen for a specific relation.\n # This is to avoid recomputation.\n # This will hold the cantor pairing of the head and tail.\n seenCorruptions = Set.new()\n\n # To reduce memory consumption, we will only look at one relation at a time.\n relations = targets.map{|target| target[Constants::RELATION]}.uniq()\n\n # The entities (and relations) have already been assigned surrogate keys that start at 0 and have\n # no holes.\n # So, instead of looking at actual entities, we can just start and zero and count up.\n numEntities = entityMapping.size()\n\n # [[id, energy], ...]\n energies = []\n corruptions = []\n\n # We will keep track of all the calculated energies so that we can analyze it later.\n # {energy.round(2) => count, ...}\n energyHistogram = Hash.new{|hash, key| hash[key] = 0}\n\n relations.each_index{|relationIndex|\n relation = relations[relationIndex]\n\n seenCorruptions.clear()\n seenCorruptions = Set.new()\n GC.start()\n\n # Only triples that are using the current relation.\n validTargets = targets.select(){|target| target[Constants::RELATION] == relation}\n\n validTargets.each{|target|\n # These are already cleared, but I want to make it explicit that we\n # are batching every valid target.\n energies.clear()\n corruptions.clear()\n\n # Corrupt the head and tail for each triple.\n [Constants::HEAD, Constants::TAIL].each{|corruptionTarget|\n for i in 0...numEntities\n if (corruptionTarget == Constants::HEAD)\n head = i\n tail = target[Constants::TAIL]\n else\n head = target[Constants::HEAD]\n tail = i\n end\n\n id = MathUtils.cantorPairing(head, tail)\n if (seenCorruptions.include?(id))\n next\n end\n\n seenCorruptions << id\n\n corruption = Array.new(3, 0)\n corruption[Constants::HEAD] = head\n corruption[Constants::TAIL] = tail\n corruption[Constants::RELATION] = relation\n\n corruptions << corruption\n end\n }\n\n energies = Energies.computeEnergies(\n corruptions,\n nil, nil,\n entityEmbeddings, relationEmbeddings, energyMethod,\n false, true\n )\n corruptions.clear()\n\n # Log all the energies in the histogram.\n energies.values().each{|energy|\n energyHistogram[energy.round(2)] += 1\n }\n\n # Remove all energies over the threshold.\n energies.delete_if{|id, energy|\n energy > maxEnergy\n }\n\n # Right now the energies are in a map with string key, turn into a list with a surrogate key.\n # [[index, [head, tail, relation], energy], ...]\n # No need to convert the keys to ints now, since we will just write them out.\n energies = energies.to_a().each_with_index().map{|mapEntry, index|\n head, tail = mapEntry[0].split(':')\n [index + targetsWritten, [head, tail, relation], mapEntry[1]]\n }\n targetsWritten += energies.size()\n\n if (energies.size() > 0)\n targetsOutFile.puts(energies.map{|energy| \"#{energy[0]}\\t#{energy[1].join(\"\\t\")}\"}.join(\"\\n\"))\n energyOutFile.puts(energies.map{|energy| \"#{energy[0]}\\t#{energy[2]}\"}.join(\"\\n\"))\n end\n\n energies.clear()\n }\n }\n\n energyOutFile.close()\n targetsOutFile.close()\n\n writeEnergyStats(energyHistogram, outDir)\nend\n\ndef writeEnergyStats(energyHistogram, outDir)\n tripleCount = energyHistogram.values().reduce(0, :+)\n mean = energyHistogram.each_pair().map{|energy, count| energy * count}.reduce(0, :+) / tripleCount.to_f()\n variance = energyHistogram.each_pair().map{|energy, count| count * ((energy - mean) ** 2)}.reduce(0, :+) / tripleCount.to_f()\n stdDev = Math.sqrt(variance)\n min = energyHistogram.keys().min()\n max = energyHistogram.keys().max()\n range = max - min\n\n # Keep track of the counts in each quartile.\n quartileCounts = [0, 0, 0, 0]\n energyHistogram.each_pair().each{|energy, count|\n # The small subtraction is to offset the max.\n quartile = (((energy - min - 0.0000001).to_f() / range) * 100).to_i() / 25\n quartileCounts[quartile] += count\n }\n\n # Calculate the median.\n # HACK(eriq): This is slighty off if there is an even number of triples and the\n # two median values are on a break, but it is not worth the extra effort.\n median = -1\n totalCount = 0\n energyHistogram.each_pair().sort().each{|energy, count|\n totalCount += count\n\n if (totalCount >= (tripleCount / 2))\n median = energy\n break\n end\n }\n\n File.open(File.join(outDir, ENERGY_STATS_FILE), 'w'){|file|\n file.puts \"Num Triples: #{energyHistogram.size()}\"\n file.puts \"Num Unique Energies: #{tripleCount}\"\n file.puts \"Min Energy: #{energyHistogram.keys().min()}\"\n file.puts \"Max Energy: #{energyHistogram.keys().max()}\"\n file.puts \"Quartile Counts: #{quartileCounts}\"\n file.puts \"Quartile Percentages: #{quartileCounts.map{|count| (count / tripleCount.to_f()).round(2)}}\"\n file.puts \"Mean Energy: #{mean}\"\n file.puts \"Median Energy: #{median}\"\n file.puts \"Energy Variance: #{variance}\"\n file.puts \"Energy StdDev: #{stdDev}\"\n file.puts \"---\"\n file.puts energyHistogram.each_pair().sort().map{|pair| pair.join(\"\\t\")}.join(\"\\n\")\n }\nend\n\ndef parseArgs(args)\n embeddingDir = nil\n outDir = nil\n datasetDir = nil\n embeddingMethod = nil\n distanceType = nil\n\n if (args.size() < 1 || args.size() > 5 || args.map{|arg| arg.downcase().gsub('-', '')}.include?('help'))\n puts \"USAGE: ruby #{$0} embedding dir [output dir [dataset dir [embedding method [distance type]]]]\"\n puts \"Defaults:\"\n puts \" output dir = inferred\"\n puts \" dataset dir = inferred\"\n puts \" embedding method = inferred\"\n puts \" distance type = inferred\"\n puts \"\"\n puts \"All the inferred aguments relies on the emebedding directory\"\n puts \"being formatted by the scripts/embeddings/computeEmbeddings.rb script.\"\n puts \"The directory that the inferred output directory will be put in is: #{Constants::PSL_DATA_PATH}.\"\n exit(2)\n end\n\n if (args.size() > 0)\n embeddingDir = args[0]\n end\n\n if (args.size() > 1)\n outDir = args[1]\n else\n outDir = File.join(Constants::PSL_DATA_PATH, File.basename(embeddingDir))\n end\n\n if (args.size() > 2)\n datasetDir = args[2]\n else\n dataset = File.basename(embeddingDir).match(/^[^_]+_(\\S+)_\\[size:/)[1]\n datasetDir = File.join(Constants::RAW_DATA_PATH, File.join(dataset))\n end\n\n if (args.size() > 3)\n embeddingMethod = args[3]\n else\n embeddingMethod = File.basename(embeddingDir).match(/^([^_]+)_/)[1]\n end\n\n if (args.size() > 4)\n distanceType = args[4]\n else\n # TODO(eriq): This may be a little off for TransR.\n if (embeddingDir.include?(\"distance:#{Distance::L1_ID_INT}\"))\n distanceType = Distance::L1_ID_STRING\n elsif (embeddingDir.include?(\"distance:#{Distance::L2_ID_INT}\"))\n distanceType = Distance::L2_ID_STRING\n end\n end\n\n energyMethod = Energies.getEnergyMethod(embeddingMethod, distanceType, embeddingDir)\n maxEnergy = Energies.getMaxEnergy(embeddingMethod, distanceType, embeddingDir)\n\n return datasetDir, embeddingDir, outDir, energyMethod, maxEnergy\nend\n\ndef prepForPSL(args)\n datasetDir, embeddingDir, outDir, energyMethod, maxEnergy = parseArgs(args)\n\n FileUtils.mkdir_p(outDir)\n\n entityMapping = Load.idMapping(File.join(datasetDir, Constants::RAW_ENTITY_MAPPING_FILENAME))\n relationMapping = Load.idMapping(File.join(datasetDir, Constants::RAW_RELATION_MAPPING_FILENAME))\n\n copyMappings(datasetDir, outDir)\n convertIds(datasetDir, outDir, entityMapping, relationMapping)\n computeTargetEnergies(datasetDir, embeddingDir, outDir, energyMethod, maxEnergy, entityMapping, relationMapping)\nend\n\nif (__FILE__ == $0)\n prepForPSL(ARGV)\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975383,"cells":{"blob_id":{"kind":"string","value":"1b8ef115b9d9f9894628ddf6d8c4866acfaf962c"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"mcruger/HW2office_directory"},"path":{"kind":"string","value":"/s3uploadfile.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":823,"string":"823"},"score":{"kind":"number","value":2.703125,"string":"2.703125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"require File.expand_path(File.dirname(__FILE__) + '/proj_config')\n\n(bucket_name, file_name) = ARGV\nunless bucket_name\n puts \"Usage: s3uploadfile.rb \"\n exit 1\nend\n\n# get an instance of the S3 interface using the default configuration\ns3 = AWS::S3.new\n\n#init bucket object\nbucket = s3.buckets[bucket_name]\n\n#check if file exists\nif !File.exist?(file_name)\n\tputs \"File '#{file_name}' does not exist. Please correct file path.\"\nelse\n\tif bucket.exists?\n\t\t# upload a file\n\t\tbasename = File.basename(file_name)\n\t\to = bucket.objects[basename]\n\t\to.write(:file => file_name)\n\n\t\tputs \"Uploaded #{file_name} to:\"\n\t\tputs o.public_url\n\n\t\t#generate a presigned URL\n\t\tputs \"\\nURL to download the file:\"\n\t\tputs o.url_for(:read)\n\telse\n\t\tputs \"Bucket '#{bucket_name}' does not exist. Cannot upload file.\"\n\tend\nend\n\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975384,"cells":{"blob_id":{"kind":"string","value":"72866b79a4b4a3748c2eacc5960250b17af636e7"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"matt5342/Leetcode"},"path":{"kind":"string","value":"/find-all-numbers-disappeared-in-an-array/find-all-numbers-disappeared-in-an-array.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":242,"string":"242"},"score":{"kind":"number","value":3.171875,"string":"3.171875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"# @param {Integer[]} nums\n# @return {Integer[]}\ndef find_disappeared_numbers(nums)\n \n obj = nums.to_h{|c| [c,0]}\n result = []\n i = 1\n nums.length.times do \n result.push(i) if !obj[i]\n i += 1\n end\n result\nend"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975385,"cells":{"blob_id":{"kind":"string","value":"8eab21a69b5bba49a4119a1f166d04ee77a40ef8"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"mesh1nek0x0/resolve-yukicoder"},"path":{"kind":"string","value":"/no296/snooze.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":210,"string":"210"},"score":{"kind":"number","value":3.046875,"string":"3.046875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"#!/bin/ruby\ninput = gets.chomp.split(' ')\nN = input[0].to_i \nH = input[1].to_i \nM = input[2].to_i \nT = input[3].to_i \n\nadd_minutes = T * (N - 1)\ntmp = M + add_minutes + (H * 60)\nputs tmp / 60 % 24\nputs tmp % 60"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975386,"cells":{"blob_id":{"kind":"string","value":"27b96c25fe9cc8806ed47ae8464bc1e60effa58d"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"hanami/view"},"path":{"kind":"string","value":"/spec/integration/helpers_spec.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1543,"string":"1,543"},"score":{"kind":"number","value":2.640625,"string":"2.640625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"# frozen_string_literal: true\n\nRSpec.describe \"helpers\" do\n let(:dir) { make_tmp_directory }\n\n describe \"in templates\" do\n before do\n with_directory(dir) do\n write \"template.html.erb\", <<~ERB\n <%= format_number(number) %>\n ERB\n end\n end\n\n let(:view) {\n dir = self.dir\n scope_class = self.scope_class\n\n Class.new(Hanami::View) do\n config.paths = dir\n config.template = \"template\"\n config.scope_class = scope_class\n\n expose :number\n end.new\n }\n\n let(:scope_class) {\n Class.new(Hanami::View::Scope) {\n include Hanami::View::Helpers::NumberFormattingHelper\n }\n }\n\n specify do\n expect(view.(number: 12_300).to_s.strip).to eq \"12,300\"\n end\n end\n\n describe \"in parts\" do\n before do\n with_directory(dir) do\n write \"template.html.erb\", <<~ERB\n <%= city.population_text %>\n ERB\n end\n end\n\n let(:part_class) {\n Class.new(Hanami::View::Part) {\n include Hanami::View::Helpers::NumberFormattingHelper\n\n def population_text\n format_number(population)\n end\n }\n }\n\n let(:view) {\n dir = self.dir\n part_class = self.part_class\n\n Class.new(Hanami::View) {\n config.paths = dir\n config.template = \"template\"\n\n expose :city, as: part_class\n }.new\n }\n\n specify do\n canberra = Struct.new(:population).new(463_000)\n\n expect(view.(city: canberra).to_s.strip).to eq \"463,000\"\n end\n end\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975387,"cells":{"blob_id":{"kind":"string","value":"237d01e22dc69e0e5524e10205aaeefd341595fc"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"MrRogerino/dbc-whiteboarding"},"path":{"kind":"string","value":"/August_9/example_solutions/two_sum.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":602,"string":"602"},"score":{"kind":"number","value":3.421875,"string":"3.421875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"def two_sum(array, target) #returns true or false\n map = {}\n i = 0\n while i < array.length\n difference = target - array[i]\n if map[difference]\n return true\n end\n map[array[i]] = 1\n i += 1\n end\n return false\nend\n\ndef two_sum_positions(array, target) #returns the position of the two numbers\n map = {}\n found = false\n i = 0\n while i < array.length\n difference = target - array[i]\n if map[difference]\n position1 = array.find_index(difference)\n position2 = i\n return [position1, position2]\n end\n map[array[i]] = 1\n i += 1\n end\n return false\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975388,"cells":{"blob_id":{"kind":"string","value":"2cf0ee197dbe7397b073e444bab51ca96641a5cd"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"svallero/vaf-storage"},"path":{"kind":"string","value":"/bin/af-create-deps.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":3669,"string":"3,669"},"score":{"kind":"number","value":2.9375,"string":"2.9375"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"#!/usr/bin/ruby\n\n#\n# af-create-deps.rb -- by Dario Berzano \n#\n# Creates the dependency file for AliRoot versions. The following environment\n# variables are needed:\n#\n# AF_DEP_URL => HTTP URL containing the list of AliEn packages for ALICE\n# AF_DEP_FILE => destination file on the local filesystem\n# AF_PACK_DIR => local AliEn Packman repository\n#\n\nrequire 'net/http'\nrequire 'pp'\nrequire 'optparse'\n\ndef get_ali_packages(url, pack_dir)\n\n if (url.kind_of?(URI::HTTP) === false)\n raise URI::InvalidURIError.new('Invalid URL: only http URLs are supported')\n end\n\n packages = []\n\n Net::HTTP.start(url.host, url.port) do |http|\n\n http.request_get(url.request_uri) do |resp|\n\n # Generic HTTP error\n if (resp.code.to_i != 200)\n raise Exception.new(\"Invalid HTTP response: #{resp.code}\")\n return false\n end\n\n resp.body.split(\"\\n\").each do |line|\n\n # 0=>pkg.tar.gz, 1=>type, 2=>rev, 3=>platf, 4=>name, 5=>deps\n ary = line.split(\" \")\n\n # Consider only AliRoot packages\n next unless (ary[1] == 'AliRoot')\n\n # Get the VO name (like VO_ALICE, for instance)\n vo_name = ary[4].split('@').first\n\n # Check integrity of line format\n deps = ary[5].split(',')\n dep_root = nil\n dep_geant3 = nil\n deps.each do |d|\n if (d.include?('@ROOT::'))\n dep_root = d\n elsif (d.include?('@GEANT3'))\n dep_geant3 = d\n end\n end\n next unless (dep_root && dep_geant3)\n\n # Check if package is installed for real\n if (pack_dir &&\n !File.exists?(\"#{pack_dir}/#{vo_name}/AliRoot/#{ary[2]}/#{ary[2]}\"))\n next\n end\n\n # Push package hash\n packages << {\n :aliroot => ary[4],\n :root => dep_root,\n :geant3 => dep_geant3,\n }\n\n end # |line|\n\n end # |resp|\n\n end # |http|\n\n return packages\n\nend\n\ndef main\n\n # Check if envvars are set\n begin\n dep_url = URI(ENV['AF_DEP_URL'])\n rescue URI::InvalidURIError => e\n warn 'Environment variable AF_DEP_URL should be set to a valid URL'\n exit 3\n end\n\n if ((dep_file = ENV['AF_DEP_FILE']) == nil)\n warn 'Environment variable AF_DEP_FILE should be set to a local filename'\n exit 3\n end\n\n if ((pack_dir = ENV['AF_PACK_DIR']) == nil)\n warn 'Environment variable AF_PACK_DIR should be set to a local directory'\n exit 3\n end\n\n # Options\n opts = {\n :checkexists => true,\n }\n\n # Define and parse options\n OptionParser.new do |op|\n\n op.on('-h', '--help', 'shows usage') do\n puts op\n exit 4\n end\n\n op.on('-c', '--[no-]check-exists',\n \"include only installed packages (default: #{opts[:checkexists]})\") do |v|\n opts[:checkexists] = v\n end\n\n # Custom banner\n prog = File.basename($0)\n op.banner = \"#{prog} -- by Dario Berzano \\n\" +\n \"Creates a dependency file for AliRoot packages\\n\\n\" +\n \"Usage: #{prog} [options]\"\n\n begin\n op.parse!\n rescue OptionParser::ParseError => e\n warn \"#{prog}: arguments error: #{e.message}\"\n exit 5\n end\n\n end\n\n begin\n packages = get_ali_packages(dep_url, opts[:checkexists] ? pack_dir : nil)\n\n begin\n\n File.open(dep_file, 'w') do |f|\n packages.each do |pack|\n f << pack[:aliroot] << '|' << pack[:root] << '|' <<\n pack[:geant3] << \"\\n\"\n end\n end\n\n rescue Exception => e\n warn \"Can not write #{dep_file}: #{e.message}\"\n exit 2\n end\n\n rescue Exception => e\n warn \"Error fetching dependencies: #{e.message}\"\n exit 1\n end\n\n warn \"#{dep_file} written\"\n exit 0\n\nend\n\n#\n# Entry point\n#\n\nmain\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975389,"cells":{"blob_id":{"kind":"string","value":"73fec8add9f7fc3b3f90d635deeab38f8f8ce2fb"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"plapicola/enigma"},"path":{"kind":"string","value":"/test/key_test.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":954,"string":"954"},"score":{"kind":"number","value":2.859375,"string":"2.859375"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"require_relative 'test_helper'\n\nclass KeyTest < Minitest::Test\n\n def setup\n @key = Key.new(\"02715\")\n end\n\n def test_it_exists\n # skip\n assert_instance_of Key, @key\n end\n\n def test_it_can_return_the_key_as_a_string\n # skip\n assert_equal \"02715\", @key.key\n end\n\n def test_it_can_generate_a_random_key\n # skip\n random_key = Key.random\n\n assert_instance_of Key, random_key\n assert_equal 5, random_key.key.length\n end\n\n def test_it_can_return_the_next_sequential_key\n # skip\n assert_equal \"02716\", @key.next_key\n assert_equal \"02717\", @key.next_key\n end\n\n def test_it_can_return_the_array_of_keys\n # skip\n assert_equal [2, 27, 71, 15], @key.parse_keys\n end\n\n def test_it_can_generate_date_offsets\n # skip\n assert_equal [1, 0, 2, 5], @key.generate_offsets(\"040895\")\n end\n\n def test_it_can_return_shifts_if_given_a_date\n # skip\n assert_equal [3, 27, 73, 20], @key.shifts(\"040895\")\n end\n\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975390,"cells":{"blob_id":{"kind":"string","value":"c84950ef5553d61ae6abaac695b46429810d6e38"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"pshussain/Backup"},"path":{"kind":"string","value":"/unlock.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":541,"string":"541"},"score":{"kind":"number","value":2.640625,"string":"2.640625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"require 'time'\nfor i in 0..100 do\n puts i.to_s\n start_time=Time.now\n (file = File.new('shared_file','r')).flock(File::LOCK_EX)\n end_time=Time.now\n diff=end_time-start_time\n puts diff\n lines = file.readlines\n #if(lines[0]!=\"line1\\\\n\")\n puts lines\n if lines != nil and lines != \"\" and !lines.empty?\n puts lines.inspect\n \n \n for i in 0..10\n puts \"Read Mode :: Data is #{lines[0]}\"\n end\n end\n \n sleep(ARGV[0].to_i)\n #exit\n #end\n file.flock(File::LOCK_UN)\n file.close\nend"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975391,"cells":{"blob_id":{"kind":"string","value":"236c175cc2d7245974204337cb1a9c0ae341dd2f"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"amosjyng/UAS-Website"},"path":{"kind":"string","value":"/app/models/event.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1944,"string":"1,944"},"score":{"kind":"number","value":2.890625,"string":"2.890625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"class Event < ActiveRecord::Base\n attr_accessible :content, :time, :title, :date, :day_time\n\n validates :title, :date, :day_time, :content, :presence => true\n validates :content, :length => {:minimum => 5}\n validate :date_valid\n validate :time_valid\n\n def date\n if time.nil?\n return Time.now.strftime('%m/%d/%Y')\n else\n time.strftime('%m/%d/%Y')\n end\n end\n\n def date=(day)\n begin\n current_time = Time.now.to_datetime\n unless time.nil?\n current_time = time\n end\n d = Date.strptime(day, '%m/%d/%Y')\n self.time = DateTime.new(d.year, d.month, d.day, current_time.hour,\n current_time.min, current_time.sec,\n current_time.zone).strftime '%Y-%m-%d %H:%M'\n @date_success = true\n rescue\n @date_success = false\n end\n end\n\n def day_time\n if time.nil?\n return Time.now.beginning_of_hour.strftime('%I:%M %p')\n else\n return time.strftime('%I:%M %p')\n end\n end\n\n def day_time=(dt)\n begin\n current_time = Time.now.to_datetime\n unless time.nil?\n current_time = time\n end\n t = DateTime.strptime(current_time.strftime('%Y %m %d ') + dt, '%Y %m %d %I:%M %p')\n self.time = DateTime.new(current_time.year, current_time.month,\n current_time.day, t.hour, t.min, 0,\n current_time.zone).strftime '%Y-%m-%d %H:%M'\n @time_success = true\n rescue\n @time_success = false\n end\n end\n\n def summary\n max_length = 300\n if content.length > max_length\n return content[0..max_length] + '...'\n else\n return content\n end\n end\n\n def human_time\n time.strftime('%A, %B %e at %l:%M %p')\n end\n\n private\n def date_valid\n errors.add(:date, 'format not valid!') unless @date_success\n end\n\n def time_valid\n errors.add(:day_time, 'format not valid!') unless @time_success\n end\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975392,"cells":{"blob_id":{"kind":"string","value":"3b15db27fd5fd3aca4620217f2e5c04372312895"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"alejandro-medici/retrospectiva"},"path":{"kind":"string","value":"/extensions/retro_wiki/ext/project.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1241,"string":"1,241"},"score":{"kind":"number","value":2.53125,"string":"2.53125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"Project.class_eval do\n\n has_many :wiki_pages, :dependent => :destroy do\n \n def find_or_build(title)\n record = find_by_title(title)\n unless record\n record = build\n record.title = title\n end\n record\n end\n \n end\n \n has_many :wiki_files, :dependent => :destroy do\n \n def find_readable(title)\n file = find_by_wiki_title(title)\n file and file.readable? ? file : nil\n end\n\n def find_readable_image(title)\n file = find_readable(title)\n file and file.image? ? file : nil\n end\n \n end\n \n serialize :existing_wiki_page_titles, Array\n before_update :update_main_wiki_page_title\n \n def wiki_title(name = self.name)\n name.gsub(/[\\.\\?\\/;,]/, '-').gsub(/-{2,}/, '-')\n end\n\n def existing_wiki_page_titles\n value = read_attribute(:existing_wiki_page_titles)\n value.is_a?(Array) ? value : []\n end\n\n def reset_existing_wiki_page_titles!\n update_attribute :existing_wiki_page_titles, wiki_pages.map(&:title)\n end\n\n protected\n \n def update_main_wiki_page_title\n if name_changed?\n page = wiki_pages.find_by_title(wiki_title(name_was))\n page.update_attribute(:title, wiki_title) if page\n end\n true\n end\n\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975393,"cells":{"blob_id":{"kind":"string","value":"f5347127a5641b42dc75136a45e2bb514ab9fbb0"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"siwS/theysaidsocli"},"path":{"kind":"string","value":"/lib/quote_terminal_printer.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":542,"string":"542"},"score":{"kind":"number","value":3.203125,"string":"3.203125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"require 'hirb'\n\nclass QuoteTerminalPrinter\n\n def initialize(quote)\n @quote = quote\n @print_text = \"#{@quote.author} said: \\\"#{@quote.quote}\\\"\"\n @width = @print_text.size\n end\n\n def print\n puts\n print_separator\n print_quote\n print_separator\n puts\n end\n\n private\n\n def print_quote\n puts \"~ #{@print_text} ~\"\n end\n\n def print_separator\n puts \"*\" * separator_width\n end\n\n def separator_width\n [@width + 4, terminal_width].min\n end\n\n def terminal_width\n Hirb::Util.detect_terminal_size[0]\n end\n\nend"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975394,"cells":{"blob_id":{"kind":"string","value":"9cc6e2334547b5b9d1323c688d7b94efc9045855"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"seanwbrooks/blackjack"},"path":{"kind":"string","value":"/spec/lib/hand_spec.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1204,"string":"1,204"},"score":{"kind":"number","value":3.15625,"string":"3.15625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"require \"spec_helper\"\n\nRSpec.describe Hand do\n let(:hand) { Hand.new }\n let(:card) { Card.new(\"♦\", \"2\") }\n let(:ace) { Card.new(\"A\", \"♦\") }\n let(:four_ace) { [Card.new(\"A\", \"♦\"), Card.new(\"A\", \"♥\"), Card.new(\"A\",\"♦\"), Card.new(\"A\",\"♥\")] }\n\n\n describe '#initialize' do\n it 'should take no arguments and create an instance of Hand' do\n expect(hand).to be_a(Hand)\n end\n\n it 'is an empty array of cards' do\n expect(hand.hand_of_cards).to eq([])\n end\n end\n\n describe '#add_card' do\n it 'should add another card to hand' do\n hand.add_card(card)\n expect(hand.hand_of_cards).to include(card)\n end\n end\n\n describe \"#calculate_hand\" do\n context \"with some cards\" do\n it \"should add these cards\" do\n expect(hand.calculate).to eq(0)\n end\n end\n\n context \"with two aces\" do\n it \"should return a score of 12\" do\n hand.add_card(ace)\n hand.add_card(ace)\n expect(hand.calculate).to eq(12)\n end\n end\n\n context \"with four aces\" do\n it \"should return a score of 14\" do\n 4.times do\n hand.add_card(ace)\n end\n expect(hand.calculate).to eq(14)\n end\n end\n end\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975395,"cells":{"blob_id":{"kind":"string","value":"5f8dee8f9cc482fd533ba7dbf88ab20648f2b355"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"popkorn96/ruby-music-library-cli-onl01-seng-ft-072720"},"path":{"kind":"string","value":"/lib/artist.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":588,"string":"588"},"score":{"kind":"number","value":2.953125,"string":"2.953125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["LicenseRef-scancode-unknown-license-reference","LicenseRef-scancode-public-domain"],"string":"[\n \"LicenseRef-scancode-unknown-license-reference\",\n \"LicenseRef-scancode-public-domain\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"class Artist\n extend Concerns::Findable\n\tattr_accessor :name, :songs\n\t\t@@all = []\n\tdef initialize(name)\n\t\t@name = name\n\t\t@songs = []\n\t\t@@all << self \n\tend \n\tdef name\n\t\t@name \n\tend\n\tdef self.all\n\t\t@@all\n\tend\n\tdef self.destroy_all \n\t\t@@all.clear\n\tend\n\t def save\n\t\t@@all << self\n\tend\n\tdef self.create(name)\n\t new_artist = self.new(name)\n new_artist.save\n new_artist\n end\n def songs \n @songs\n end \n def add_song(song)\n song.artist = self unless song.artist\n songs << song unless songs.include?(song)\n end\n def genres\n songs.map{|song| song.genre}.uniq\n end\n\nend"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975396,"cells":{"blob_id":{"kind":"string","value":"af9a8a9417a8cbff7f48db3a093a3827283d16a7"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"achiurizo/boson"},"path":{"kind":"string","value":"/lib/boson/inspector.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":3687,"string":"3,687"},"score":{"kind":"number","value":2.703125,"string":"2.703125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"module Boson\n # Scrapes and processes method attributes with the inspectors (MethodInspector, CommentInspector\n # and ArgumentInspector) and hands off the data to FileLibrary objects.\n #\n # === Method Attributes\n # Method attributes refer to (commented) Module methods placed before a command's method\n # in a FileLibrary module:\n # module SomeMod\n # # @render_options :fields=>%w{one two}\n # # @config :alias=>'so'\n # options :verbose=>:boolean\n # # Something descriptive perhaps\n # def some_method(opts)\n # # ...\n # end\n # end\n #\n # Method attributes serve as configuration for a method's command. Available method attributes:\n # * config: Hash to define any command attributes (see Command.new).\n # * desc: String to define a command's description for a command. Defaults to first commented line above a method.\n # * options: Hash to define an OptionParser object for a command's options.\n # * render_options: Hash to define an OptionParser object for a command's local/global render options (see View).\n #\n # When deciding whether to use commented or normal Module methods, remember that commented Module methods allow\n # independence from Boson (useful for testing). See CommentInspector for more about commented method attributes.\n module Inspector\n extend self\n attr_reader :enabled\n\n # Enable scraping by overridding method_added to snoop on a library while it's\n # loading its methods.\n def enable\n @enabled = true\n body = MethodInspector::METHODS.map {|e|\n %[def #{e}(val)\n Boson::MethodInspector.#{e}(self, val)\n end]\n }.join(\"\\n\") +\n %[\n def new_method_added(method)\n Boson::MethodInspector.new_method_added(self, method)\n end\n\n alias_method :_old_method_added, :method_added\n alias_method :method_added, :new_method_added\n ]\n ::Module.module_eval body\n end\n\n # Disable scraping method data.\n def disable\n ::Module.module_eval %[\n Boson::MethodInspector::METHODS.each {|e| remove_method e }\n alias_method :method_added, :_old_method_added\n ]\n @enabled = false\n end\n\n # Adds method attributes scraped for the library's module to the library's commands.\n def add_method_data_to_library(library)\n @commands_hash = library.commands_hash\n @library_file = library.library_file\n MethodInspector.current_module = library.module\n @store = MethodInspector.store\n add_method_scraped_data\n add_comment_scraped_data\n end\n\n #:stopdoc:\n def add_method_scraped_data\n (MethodInspector::METHODS + [:args]).each do |key|\n (@store[key] || []).each do |cmd, val|\n @commands_hash[cmd] ||= {}\n add_scraped_data_to_config(key, val, cmd)\n end\n end\n end\n\n def add_scraped_data_to_config(key, value, cmd)\n if value.is_a?(Hash)\n if key == :config\n @commands_hash[cmd] = Util.recursive_hash_merge value, @commands_hash[cmd]\n else\n @commands_hash[cmd][key] = Util.recursive_hash_merge value, @commands_hash[cmd][key] || {}\n end\n else\n @commands_hash[cmd][key] ||= value\n end\n end\n\n def add_comment_scraped_data\n (@store[:method_locations] || []).select {|k,(f,l)| f == @library_file }.each do |cmd, (file, lineno)|\n scraped = CommentInspector.scrape(FileLibrary.read_library_file(file), lineno, MethodInspector.current_module)\n @commands_hash[cmd] ||= {}\n MethodInspector::METHODS.each do |e|\n add_scraped_data_to_config(e, scraped[e], cmd)\n end\n end\n end\n #:startdoc:\n end\nend"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975397,"cells":{"blob_id":{"kind":"string","value":"571521803896c418306191cafeeeb3f89307ace3"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"MuhammadTamzid/framgia_crb_v2"},"path":{"kind":"string","value":"/app/validators/name_validator.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":608,"string":"608"},"score":{"kind":"number","value":2.953125,"string":"2.953125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"class NameValidator < ActiveModel::Validator\n def validate record\n # name may only contain alphanumeric characters or single hyphens, and cannot begin or end with a hyphen\n if !(record.name =~ /^(?!-)(?!.*--)[A-Za-z0-9-]+(? 39\n record.errors[:name] << \"is too long (maximum is 39 characters)\"\n elsif record.new_record? && Person.names.include?(record.name)\n record.errors[:name] << \"is already taken\"\n end\n end\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975398,"cells":{"blob_id":{"kind":"string","value":"ca567f6ac7bc9ac5ce370db9c43c015bd867c5d5"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"mdixon47/Codewars-Ruby"},"path":{"kind":"string","value":"/8-kyu/Basic Fizz Buzz.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":649,"string":"649"},"score":{"kind":"number","value":4.6875,"string":"4.6875"},"int_score":{"kind":"number","value":5,"string":"5"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"#Description:\n#FizzBuzz is probably the second most popular way to introduce beginners to the art of coding\n#(the first probably being the ancient Fibonacci sequence, the grandfather of all the algorithm theory).\n\n#In this very basic kata you will have to create a function that \n#returns the same numbers that is given as a parameter, with the following exceptions:\n\n#If number divides evenly with 3 - returns string \"fizz\"\n#If number divides evenly with 5 - returns string \"buzz\"\n#If number divides evenly with 3 and 5 - returns string \"fizz buzz\"\n\ndef fizzbuzz(n)\n n % 3 == 0 ? (n % 5 == 0 ? \"fizz buzz\" : \"fizz\") : (n % 5 == 0 ? \"buzz\" : n)\nend"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975399,"cells":{"blob_id":{"kind":"string","value":"49bfaf32b0b1dbf85829fa22fbe3a7ca4eff7b00"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"sebatapiaoviedo/dibujandoasteriscosypuntos"},"path":{"kind":"string","value":"/asteriscos_y_puntos.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":145,"string":"145"},"score":{"kind":"number","value":3.015625,"string":"3.015625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"aux = \"\"\nnumero = ARGV[0].to_i\nfor i in (1..numero)\n#i%2 == 0\n if i.even?\n aux += \".\"\n else \n aux += \"*\"\n end\nend\nputs aux"},"download_success":{"kind":"bool","value":true,"string":"true"}}}],"truncated":false,"partial":false},"paginationData":{"pageIndex":29753,"numItemsPerPage":100,"numTotalItems":2976874,"offset":2975300,"length":100}},"jwt":"eyJhbGciOiJFZERTQSJ9.eyJyZWFkIjp0cnVlLCJwZXJtaXNzaW9ucyI6eyJyZXBvLmNvbnRlbnQucmVhZCI6dHJ1ZX0sImlhdCI6MTc1NjY4OTMzMSwic3ViIjoiL2RhdGFzZXRzL2hvbmdsaXU5OTAzL3N0YWNrX2VkdV9ydWJ5IiwiZXhwIjoxNzU2NjkyOTMxLCJpc3MiOiJodHRwczovL2h1Z2dpbmdmYWNlLmNvIn0.uZSylXhiN5u1-seGIBCXQzFv7-LbnLv98QcQeaCjekfRVTFm7O7evninMwyLF6LVTbmGZCMg7EUVI02gdcIXDw","displayUrls":true},"discussionsStats":{"closed":0,"open":0,"total":0},"fullWidth":true,"hasGatedAccess":true,"hasFullAccess":true,"isEmbedded":false,"savedQueries":{"community":[],"user":[]}}">
blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
4
137
path
stringlengths
2
355
src_encoding
stringclasses
31 values
length_bytes
int64
11
3.9M
score
float64
2.52
5.47
int_score
int64
3
5
detected_licenses
listlengths
0
49
license_type
stringclasses
2 values
text
stringlengths
11
3.93M
download_success
bool
1 class
26a87ccaef2dca6057e30ee5bb2f0e5d8a3bd8ea
Ruby
thrasher-redhat/shiftzilla
/lib/shiftzilla/release.rb
UTF-8
808
2.59375
3
[]
no_license
require 'shiftzilla/milestones' module Shiftzilla class Release attr_reader :name, :targets, :milestones, :default, :token def initialize(release,builtin=false) @name = release['name'].to_s @token = @name.tr(' .', '_') @targets = release['targets'] @default = release.has_key?('default') ? release['default'] : false @builtin = builtin @milestones = nil if release.has_key?('milestones') @milestones = Shiftzilla::Milestones.new(release['milestones']) end end def uses_milestones? return @milestones.nil? ? false : true end def built_in? @builtin end def no_tgt_rel? if @targets.length == 1 and @targets[0] == '---' return true end false end end end
true
6217361e38817a758da4ab6ed9fe850aaca8b549
Ruby
dgriego/bgc_admin
/app/models/trip.rb
UTF-8
1,061
2.671875
3
[]
no_license
# == Schema Information # # Table name: trips # # id :integer not null, primary key # title :string # location :string # seats :integer # alt_seats :integer # start_date :date # start_time :time # end_time :time # published :boolean default("false") # class Trip < ActiveRecord::Base MAX_SEATS = 60 MAX_ALT_SEATS = 30 has_many :participant_trips has_many :participants, through: :participant_trips validates :title, presence: true validates :alt_seats, presence: true validates :seats, presence: true validates :start_date, presence: true validates :start_time, presence: true validates :end_time, presence: true scope :published, -> { where(published: true) } def self.max_seats (1..MAX_SEATS).to_a end def self.max_alt_seats (1..MAX_ALT_SEATS).to_a end def seats_left count = participant_trips.where(primary: true).count seats - count end def alt_seats_left count = participant_trips.where(primary: false).count alt_seats - count end end
true
26639b9cefc838730594db39edfee8ddf650bf90
Ruby
ga-wolf/WDI10-Homework
/robinson-lam/week_04/exercise_01/array.rb
UTF-8
446
3.53125
4
[]
no_license
days_of_the_week = %w/ Monday Tuesday Wednesday Thursday Friday Saturday Sunday / days_of_the_week.unshift(days_of_the_week.pop) weekends = [] weekdays = [] days_of_the_week.each do |day| if day == "Saturday" || day == "Sunday" weekends.push(day) else weekdays.push(day) end end print weekends print weekdays puts "Removing Weekdays so we always have weekends forever" days_of_the_week -= weekdays print days_of_the_week.sort
true
4c9b0f3d544ee41961c648d98ff5a0119171415e
Ruby
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/ruby/hamming/ed195c6874e84025a588bfaf661c7450.rb
UTF-8
341
3.515625
4
[]
no_license
class Hamming def self.compute(nucleotide_a, nucleotide_b) #return nucleotide_a == nucleotide_b ? 0 : 1 b_arr = nucleotide_b.split('') counter = 0 nucleotide_a.split('').each_with_index do |item, index| break if index > b_arr.length - 1 counter = counter + 1 if item != b_arr[index] end counter end end
true
31ff3ec0629724dba52f054504ff78129e9ce7da
Ruby
f-meloni/vulcano
/lib/vulcano/parsed_class.rb
UTF-8
929
2.6875
3
[ "MIT" ]
permissive
require "vulcano/codable_key" module Vulcano class ParsedClass attr_reader :name attr_reader :variables attr_reader :codable_keys attr_reader :is_public attr_reader :is_struct def initialize(name, variables, is_public, is_struct) @is_public = is_public @name = name @variables = variables @codable_keys = codable_keys @is_struct = is_struct end def class_binding binding end private def codable_keys codable_keys = [] has_codable_keys = false variables.each do |variable| if variable.name == variable.original_name codable_keys.push(CodableKey.new(variable.original_name)) else codable_keys.push(CodableKey.new(variable.original_name, variable.name)) has_codable_keys = true end end return nil unless has_codable_keys codable_keys end end end
true
78676dac76c6d71c36b8aa9af4dd7168a1349abe
Ruby
foxed/Learn-To-Program
/7-deafgram.rb
UTF-8
593
3.8125
4
[]
no_license
#First Deaf Grandma Exercise puts '' while true input = gets.chomp if input != input.upcase puts 'SPEAK UP!!' else input == input.upcase year = 1920 + rand(18) puts 'OH NO, NOT SINCE, ' + year.to_s + '!' if input == 'BYE' break end end end #Second Deaf Grandma Exercise puts '' while true input = gets.chomp if input != input.upcase puts 'SPEAK UP!!' else input == input.upcase year = 1920 + rand(18) puts 'OH NO, NOT SINCE, ' + year.to_s + '!' if input == 'BYE ' * 3 break end end end
true
1ccae9c8974bee15b9480a34c3076c6d4efcc7f0
Ruby
rubyworks/shomen-model
/work/deprecated/core_ext/times.rb
UTF-8
2,976
3.890625
4
[ "BSD-2-Clause", "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
# Extend Numeric with time constants class Numeric # :nodoc: # Time constants # # TODO: Use RichUnits instead (?) # module Times # :nodoc: MINUTES = 60 HOURS = 60 * MINUTES DAYS = 24 * HOURS WEEKS = 7 * DAYS MONTHS = 30 * DAYS YEARS = 365.25 * DAYS # Number of seconds (returns receiver unmodified) def seconds return self end alias_method :second, :seconds # Returns number of seconds in <receiver> minutes def minutes MINUTES end alias_method :minute, :minutes # Returns the number of seconds in <receiver> hours def hours HOURS end alias_method :hour, :hours # Returns the number of seconds in <receiver> days def days DAYS end alias_method :day, :days # Return the number of seconds in <receiver> weeks def weeks WEEKS end alias_method :week, :weeks # Returns the number of seconds in <receiver> fortnights def fortnights return self * 2.weeks end alias_method :fortnight, :fortnights # Returns the number of seconds in <receiver> months (approximate) def months MONTHS end alias_method :month, :months # Returns the number of seconds in <receiver> years (approximate) def years YEARS #return (self * 365.25.days).to_i end alias_method :year, :years # Returns the Time <receiver> number of seconds before the # specified +time+. E.g., 2.hours.before( header.expiration ) def before( time ) return time - self end # Returns the Time <receiver> number of seconds ago. (e.g., # expiration > 2.hours.ago ) def ago return self.before( ::Time.now ) end # Returns the Time <receiver> number of seconds after the given +time+. # E.g., 10.minutes.after( header.expiration ) def after( time ) return time + self end # Reads best without arguments: 10.minutes.from_now def from_now return self.after( ::Time.now ) end # Return a string describing the amount of time in the given number of # seconds in terms a human can understand easily. def time_delta_string seconds = self return 'less than a minute' if seconds < MINUTES return (seconds / MINUTES).to_s + ' minute' + (seconds/60 == 1 ? '' : 's') if seconds < (50 * MINUTES) return 'about one hour' if seconds < (90 * MINUTES) return (seconds / HOURS).to_s + ' hours' if seconds < (18 * HOURS) return 'one day' if seconds < DAYS return 'about one day' if seconds < (2 * DAYS) return (seconds / DAYS).to_s + ' days' if seconds < WEEKS return 'about one week' if seconds < (2 * WEEKS) return (seconds / WEEKS).to_s + ' weeks' if seconds < (3 * MONTHS) return (seconds / MONTHS).to_s + ' months' if seconds < YEARS return (seconds / YEARS).to_s + ' years' end end # module TimeConstantMethods include Times end
true
f2685a8663d700159eac2357e5b877d1bc78a8f1
Ruby
dlbirch/rubyPOS
/spec/right_t_padder_spec.rb
UTF-8
657
2.703125
3
[]
no_license
require 'rspec' require 'right_t_padder' describe RightTPadder do before(:each) do @rtp = RightTPadder.new() end it 'should return an instance' do expect(@rtp).to be_truthy end it 'should handle data longer than max length without throwing an exception' do expect(@rtp.pad("1234567890123456789", 10)).to eq("1234567890") end it 'should handle data that requires padding' do expect(@rtp.pad("12345678901234567890", 25)).to eq("12345678901234567890 ") end it 'should handle data that requires no padding and no truncation' do expect(@rtp.pad("12345678901234567890", 20)).to eq("12345678901234567890") end end
true
d5e68b52cbccdc46c64e86b23335652caceddd04
Ruby
mlyubarskyy/leetcode
/362_design_hit_counter.rb
UTF-8
984
3.875
4
[]
no_license
class HitCounter =begin Initialize your data structure here. =end def initialize() @q = [[0, 0]] * 300 end =begin Record a hit. @param timestamp - The current timestamp (in seconds granularity). :type timestamp: Integer :rtype: Void =end def hit(timestamp) idx = timestamp % 300 time, hits = @q[idx] @q[idx] = if time != timestamp [timestamp, 1] else [time, hits + 1] end end =begin Return the number of hits in the past 5 minutes. @param timestamp - The current timestamp (in seconds granularity). :type timestamp: Integer :rtype: Integer =end def get_hits(timestamp) ans = 0 300.times do |i| time, hit = @q[i] ans += hit if timestamp - time < 300 end ans end end # Your HitCounter object will be instantiated and called as such: # obj = HitCounter.new() # obj.hit(timestamp) # param_2 = obj.get_hits(timestamp)
true
9c39bfa9b8d125738c859c1a01629d49a305d4c6
Ruby
h4hany/yeet-the-leet
/algorithms/Medium/62.unique-paths.rb
UTF-8
1,177
3.515625
4
[]
no_license
# # @lc app=leetcode id=62 lang=ruby # # [62] Unique Paths # # https://leetcode.com/problems/unique-paths/description/ # # algorithms # Medium (54.32%) # Total Accepted: 514.5K # Total Submissions: 947.2K # Testcase Example: '3\n2' # # A robot is located at the top-left corner of a m x n grid (marked 'Start' in # the diagram below). # # The robot can only move either down or right at any point in time. The robot # is trying to reach the bottom-right corner of the grid (marked 'Finish' in # the diagram below). # # How many possible unique paths are there? # # # Above is a 7 x 3 grid. How many possible unique paths are there? # # # Example 1: # # # Input: m = 3, n = 2 # Output: 3 # Explanation: # From the top-left corner, there are a total of 3 ways to reach the # bottom-right corner: # 1. Right -> Right -> Down # 2. Right -> Down -> Right # 3. Down -> Right -> Right # # # Example 2: # # # Input: m = 7, n = 3 # Output: 28 # # # # Constraints: # # # 1 <= m, n <= 100 # It's guaranteed that the answer will be less than or equal to 2 * 10 ^ 9. # # # # @param {Integer} m # @param {Integer} n # @return {Integer} def unique_paths(m, n) end
true
22efedbebd5394d900d6aba08047d758718c7a2a
Ruby
oshou/procon
/AC/ARC/arc014a.rb
UTF-8
64
3.28125
3
[]
no_license
n = gets.to_i if n % 2 == 0 puts "Blue" else puts "Red" end
true
49fbe07d8e92b01d61a2ef1e517eae2735cfde2f
Ruby
martom87/workshops_tennis
/spec/tennis/player_spec.rb
UTF-8
390
2.5625
3
[]
no_license
# frozen_string_literal: true require_relative '../../lib/tennis/player.rb' RSpec.describe Player do subject { described_class.new(points_amount, name)} let(:points_amount) {15} let(:name){'Edek'} it 'returns players points amount' do expect(subject.points_amount).to eq(points_amount) end it 'returns player\'s name' do expect(subject.name).to eq(name) end end
true
dfbf6fa4bd7c1bd441808f8a60ee29f5e6ecb7d5
Ruby
jvanderhoof/you_got_listed
/lib/you_got_listed/response.rb
UTF-8
679
2.734375
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
module YouGotListed class Response attr_accessor :ygl_response def initialize(response, raise_error = true) rash = Hashie::Rash.new(response) self.ygl_response = rash.ygl_response raise Error.new(self.ygl_response.response_code, self.ygl_response.error) if !success? && raise_error end def success? self.ygl_response && self.ygl_response.respond_to?(:response_code) && self.ygl_response.response_code.to_i < 300 end def method_missing(method_name, *args) if self.ygl_response.respond_to?(method_name) self.ygl_response.send(method_name) else super end end end end
true
5a0d571f30ce7de852d7ba05e260256f15d46eb7
Ruby
SocialCentivPublic/cheftacular
/lib/cheftacular/stateless_actions/cloud.rb
UTF-8
7,804
2.640625
3
[ "MIT" ]
permissive
class Cheftacular class StatelessActionDocumentation def cloud @config['documentation']['stateless_action'][__method__] ||= {} @config['documentation']['stateless_action'][__method__]['long_description'] = [ "`cft cloud <FIRST_LEVEL_ARG> [<SECOND_LEVEL_ARG>[:<SECOND_LEVEL_ARG_QUERY>]*] ` this command handles talking to various cloud APIs. " + "If no args are passed nothing will happen.", [ " 1. `domain` first level argument for interacting with cloud domains", " 1. `list` default behavior", " 2. `read:TOP_LEVEL_DOMAIN` returns detailed information about all subdomains attached to the TOP_LEVEL_DOMAIN", " 3. `read_record:TOP_LEVEL_DOMAIN:QUERY_STRING` queries the top level domain for all subdomains that have the QUERY_STRING in them.", " 4. `create:TOP_LEVEL_DOMAIN` creates the top level domain on rackspace", " 5. `create_record:TOP_LEVEL_DOMAIN:SUBDOMAIN_NAME:IP_ADDRESS[:RECORD_TYPE[:TTL]]` " + "IE: `cft cloud domain create:mydomain.com:myfirstserver:1.2.3.4` will create the subdomain 'myfirstserver' on the mydomain.com domain.", " 6. `destroy:TOP_LEVEL_DOMAIN` destroys the top level domain and all of its subdomains", " 7. `destroy_record:TOP_LEVEL_DOMAIN:SUBDOMAIN_NAME` deletes the subdomain record for TOP_LEVEL_DOMAIN if it exists.", " 8. `update:TOP_LEVEL_DOMAIN` takes the value of the email in the authentication data bag for your specified cloud and updates the TLD.", " 9. `update_record:TOP_LEVEL_DOMAIN:SUBDOMAIN_NAME:IP_ADDRESS[:RECORD_TYPE[:TTL]]` similar to `create_record`.", " 2. `server` first level argument for interacting with cloud servers, " + "if no additional args are passed the command will return a list of all servers on the preferred cloud.", " 1. `list` default behavior", " 2. `read:SERVER_NAME` returns all servers that have SERVER_NAME in them (you want to be as specific as possible for single matches)", " 3. `create:SERVER_NAME:FLAVOR_ALIAS` IE: `cft cloud server \"create:myserver:1 GB Performance\"` " + "will create a server with the name myserver and the flavor \"1 GB Performance\". Please see flavors section.", " 1. NOTE! If you forget to pass in a flavor alias the script will not error! It will attempt to create a 512MB Standard Instance!", " 2. NOTE! Most flavors have spaces in them, you must use quotes at the command line to utilize them!", " 4. `destroy:SERVER_NAME` destroys the server on the cloud. This must be an exact match of the server's actual name or the script will error.", " 5. `poll:SERVER_NAME` polls the cloud's server for the status of the SERVER_NAME. This command " + "will stop polling if / when the status of the server is ACTIVE and its build progress is 100%.", " 6. `attach_volume:SERVER_NAME:VOLUME_NAME[:VOLUME_SIZE[:DEVICE_LOCATION]]` " + "If VOLUME_NAME exists it will attach it if it is unattached otherwise it will create it", " 1. NOTE! If the system creates a volume the default size is 100 GB!", " 2. DEVICE_LOCATION refers to the place the volume will be mounted on, a place like `/dev/xvdb`, " + "from here it must be added to the filesystem to be used.", " 3. If you want to specify a location, you must specify a size, if the volume already exists it wont be resized but will be attached at that location!", " 4. If DEVICE_LOCATION is blank the volume will be attached to the first available slot.", " 7. `detach_volume:SERVER_NAME:VOLUME_NAME` Removes the volume from the server if it is attached. " + "If this operation is performed while the volume is mounted it could corrupt the volume! Do not do this unless you know exactly what you're doing!", " 8. `list_volumes:SERVER_NAME` lists all volumes attached to a server", " 9. `read_volume:SERVER_NAME:VOLUME_NAME` returns the data of VOLUME_NAME if it is attached to the server.", " 3. `volume` first level argument for interacting with cloud storage volumes, if no additional args are passed the command will return a list of all cloud storage containers.", " 1. `list` default behavior", " 2. `read:VOLUME_NAME` returns the details for a specific volume.", " 3. `create:VOLUME_NAME:VOLUME_SIZE` IE `cft rax volume create:staging_db:256`", " 4. `destroy:VOLUME_NAME` destroys the volume. This operation will not work if the volume is attached to a server.", " 4. `flavor` first level argument for listing the flavors available on the cloud service", " 1. `list` default behavior", " 2. `read:FLAVOR SIZE` behaves the same as list unless a flavor size is supplied.", " 1. Standard servers are listed as XGB with no spaces in their size, performance servers are listed as X GB with " + "a space in their size. If you are about to create a server and are unsure, query flavors first.", " 5. `image` first level argument for listing the images available on the cloud service", " 1. `list` default behavior", " 2. `read:NAME` behaves the same as list unless a specific image name is supplied", " 6. `region` first level argument for listing the regions available on the cloud service (only supported by DigitalOcean)", " 1. `list` default behavior", " 2. `read:REGION` behaves the same as list unless a specific region name is supplied", " 7. `sshkey` first level argument for listing the sshkeys added to the cloud service (only supported by DigitalOcean)", " 1. `list` default behavior", " 2. `read:KEY_NAME` behaves the same as list unless a specific sshkey name is supplied", " 3. `\"create:KEY_NAME:KEY_STRING\"` creates an sshkey object. KEY_STRING must contain the entire value of the ssh public key file. " + "The command must be enclosed in quotes.", " 4. `destroy:KEY_NAME` destroys the sshkey object", " 5. `bootstrap` captures the current computer's hostname and checks to see if a key matching this hostname exists on the cloud service. " + "If the key does not exist, the command attempts to read the contents of the ~/.ssh/id_rsa.pub file and create a new key with that data and the " + "hostname of the current computer. Run automatically when creating DigitalOcean servers. It's worth noting that if the computer's key already " + "exists on DigitalOcean under a different name, this specific command will fail with a generic error. Please check your keys." ] ] @config['documentation']['stateless_action'][__method__]['short_description'] = 'Retrieves useful information about cloud services being used' end end class StatelessAction def cloud *args raise "This action can only be performed if the mode is set to devops" if !@config['helper'].running_in_mode?('devops') && !@options['in_scaling'] args = ARGV[1..ARGV.length] if args.empty? @config['cloud_interactor'] ||= CloudInteractor.new(@config['cheftacular'], @options) @config['cloud_interactor'].run args end alias_method :aws, :cloud alias_method :rax, :cloud end end
true
99146c4bc4b64653b3822888c77848f5046503ee
Ruby
golovanov1512/golovanov1512.github.io
/ruby_practice/ruby.rb
UTF-8
684
3.671875
4
[]
no_license
class PasswordGen def initialize(count_symbol) @count_symbol = count_symbol @vowel = %w(a e i y o u) @consonant = %w(q w r t p s d f g h j k l m n b v c x z) end def vowel_or_consonant(index) if index.even? to_large_letter(@vowel[rand(@vowel.size)], index) else @consonant[rand(@consonant.size)] end end def generate password = "" @count_symbol.times{ |index| password << vowel_or_consonant(index) } password end def to_large_letter(letter, index) index > 5 ? letter.upcase : letter end end p 'Enter password length' password_gen = PasswordGen.new(gets.chomp.to_i) p "Your password : #{ password_gen.generate }"
true
fc99120ceae42dad870f23ab836aea3c7515e294
Ruby
KarlaRobinson/Learning_Ruby_basics
/TablasDeMultiplicar.rb
UTF-8
273
3.34375
3
[]
no_license
def multiplication_tables(num) arr = Array(1..num) range = Array(1..10) arr.each do |arrElem| range.each do |rangeElem| value = arrElem * rangeElem print "#{value}\t" end print "\n" end end multiplication_tables(5) multiplication_tables(7)
true
6f737db76ae1aa152f008f92748f78227cf709c4
Ruby
thelazyfox/euler
/p023/solution.rb
UTF-8
1,337
3.875
4
[]
no_license
class Array def sum self.inject {|a,b| a+b} end end def factor(n) if n == 0 [0] elsif n == 1 [1] else i = 2 while n % i > 0 i += 1 end if i == n [n] else factor(i) + factor(n/i) end end end def divisors(n) primes = Hash.new(0) factor(n).each do |value| primes[value] += 1 end factors = [1] primes.each do |prime,count| factors.collect! do |factor| list = [] (count+1).times do |power| list << factor * (prime**power) end list end factors.flatten! end factors.flatten end abundant_numbers = [] puts "Checking Abundant Numbers..." (1..28123).each do |n| puts n if n % 100 == 0 divs = divisors(n) divs.sort! divs.pop if divs.uniq.sum > n abundant_numbers << n end end puts "Done. Found #{abundant_numbers.size} numbers" puts abundant_numbers puts "" abundant_sums = Hash.new(false) puts "Finding abundant number sums..." abundant_numbers.each_index do |i| puts i if i % 100 == 0 (i..(abundant_numbers.size-1)).each do |j| sum = abundant_numbers[i] + abundant_numbers[j] abundant_sums[sum] = true unless sum > 28123 end end puts "Done." puts "Summing up the result" sum = 0 (1..28123).each do |n| sum += n unless abundant_sums[n] end puts "Done" puts "Solution: #{sum}"
true
ea0265e2cdc8c93a05feb1a30614b6d39f6a5d95
Ruby
ahawkins/chassis-example
/app/utils.rb
UTF-8
523
2.625
3
[]
no_license
class PhoneNumbersValidator include ActiveModel::Validations include Enumerable validate do |phone_numbers| phone_numbers.each do |number| begin UserRepo.find_by_phone_number! number rescue UserRepo::UnknownPhoneNumber => ex phone_numbers.errors.add :phone_numbers, ex.message end end end def initialize(numbers) @numbers = numbers end def validate! raise ValidationError, errors unless valid? end def each(&block) @numbers.each(&block) end end
true
13ea2ff883d92ce54ddf96396ae60a71b35ba372
Ruby
AnyPresence/do_sqlserver-tinytds
/lib/do_sqlserver_tinytds/tiny_tds_extension.rb
UTF-8
3,168
3.0625
3
[ "MIT" ]
permissive
require 'tiny_tds' module TinyTds class Client #raw_execute - freetds does not support dynamic sql so #we're going to translate dynamic sql statements into a plain #sql statement def raw_execute(text , *var_list) dynamic_sql = text.clone flat_sql = var_list.empty? ? dynamic_sql : process_questioned_sql(dynamic_sql , *var_list) execute(flat_sql) end :private def process_questioned_sql(sql , *vars) sql_type = classify_sql(sql) result = substitute_quoted_questions(sql) _sql = result[:sql] vars.each do |var| _sql.sub!("?" , convert_type_to_s(var , sql_type)) end #place back strings in the sql that contained "?" result[:container].each do |k,v| _sql.gsub!(k , v) end _sql end def substitute_quoted_questions(sql) container = {} #collect strings in the sql that contains a question_mark qstrings = sql.scan(/"[^"]*"/).select{|s| s.include?("?")} #temporarily replace quoted values counter = 0 qstrings.each do |qstring| key = "(((####{counter}###)))" sql.gsub!(qstring, key) container[key] = qstring counter += 1 end {:sql => sql, :container => container} end #convert_type_to_s - convert Ruby collection objects fed into the query into #sql strings def convert_type_to_s(arg , sql_type) case sql_type when :between case arg when Range , Array "#{sql_stringify_value(arg.first)} AND #{sql_stringify_value(arg.last)}" else raise "Type not found..." end when :in case arg when Range , Array " (#{arg.collect{|e| "#{sql_stringify_value(e)}"}.join(" , ")}) " else raise "Type not found..." end else case arg when Range , Array arg.collect{|e| "#{sql_stringify_value(e)}"}.join(" , ") else sql_stringify_value(arg) end end end #convert_type_to_s - convert Ruby object fed into the query into #sql string def sql_stringify_value(value) case when value.is_a?(String) "N'#{value.gsub(/\'/, "''")}'" when value.is_a?(Numeric) value.to_s when value.is_a?(NilClass) "NULL" when value.is_a?(DateTime) value.strftime("'%m/%d/%Y %I:%M:%S %p'") when value.is_a?(Time) DateTime.new(value.year, value.month, value.day, value.hour, value.min, value.sec, Rational(value.gmt_offset / 3600, 24)).strftime("'%m/%d/%Y %I:%M:%S %p'") else "N'#{value.to_s}'" end end #classify_sql - determine if this sql has a between or in def classify_sql(sql) case when sql[/between.+\?/i] #var should be an array :between when sql[/\sin\s+\?/i] :in end end end class Error alias :to_str :to_s def errstr @errstr ||= [] @errstr end end end
true
653a4efe08d00b0cb3279b4d784e4416a4871e55
Ruby
czuger/nyog-sothep
/app/models/game_core/dices.rb
UTF-8
405
3.0625
3
[ "MIT" ]
permissive
class GameCore::Dices def self.method_missing( method_name, amount = 1 ) # puts method_name.inspect dice_amount_match = method_name.to_s.match( /d(\d+)/ ) raise "Method mising : #{method_name}" unless dice_amount_match # puts dice_amount_match.inspect dice_amount = dice_amount_match[1].to_i (1..amount).inject(0) { |sum, _| sum + Kernel.rand( 1..dice_amount ) } end end
true
d8af0ce17477b182e399e903d19e4a611299e0c6
Ruby
RobinBailey84/PDA
/Static_and_Dynamic_Task_A/specs/card_game_spec.rb
UTF-8
745
3.21875
3
[]
no_license
require('minitest/autorun') require('minitest/rg') require_relative('../card_game.rb') require_relative('../card.rb') class CardGameTest < MiniTest::Test def setup() @card1 = Card.new("spade", 5) @card2 = Card.new("spade", 3) @card3 = Card.new("diamonds", 9) @card4 = Card.new("clubs", 1) @card5 = Card.new("hearts", 5) end def test_check_for_ace() result = CardGame.check_for_ace(@card4) assert_equal(true, result) end def test_highest_card() result = CardGame.highest_card(@card3, @card5) assert_equal(@card3, result) end def test_cards_total() cards = [@card1, @card2, @card3] result = CardGame.cards_total(cards) assert_equal("You have a total of 17", result) end end
true
3f9efc9319d9fb4d95b15f3027f199a7f8177880
Ruby
mochizuki-pg/ruby_types
/app.rb
UTF-8
1,193
3.296875
3
[]
no_license
require_relative 'lib/recipe' require_relative 'lib/ingredient' require_relative 'lib/instruction' title = 'いちごで作る サンタクロース' ingredients = [ Ingredient.new(name: 'いちご', quantity: 2, unit: '個'), Ingredient.new(name: 'ホイップクリーム', quantity: 10, unit: 'g'), Ingredient.new(name: 'チョコレートペン (黒)', quantity: 1, unit: '本') ] instructions = [ Instruction.new(text: 'チョコレートペンは湯煎にかけて溶かしておきます。 ホイップクリームは絞り袋に入れておきます。'), Instruction.new(text: 'いちごはヘタを切り落とします。'), Instruction.new(text: 'ヘタの部分から2/3のところを切ります。'), Instruction.new(text: 'ヘタの部分を下にして切り口にホイップクリームを絞り、挟みます。上にホイップクリームを直径5mm程絞り、帽子をつくります。'), Instruction.new(text: 'チョコレートペンで顔とボタンを描いて完成です。') ] recipe = Recipe.new(title: title, ingredients: ingredients, instructions: instructions) puts recipe.title puts recipe.ingredients puts recipe.instructions
true
fd8cbf2f5a10aa0dabad352a69923e26de61c4be
Ruby
foood/codebreaker
/lib/codebreaker/game.rb
UTF-8
1,691
3.65625
4
[ "MIT" ]
permissive
module Codebreaker class Game attr_reader :secret, :player, :attempts, :hints SECRET_SIZE = 4 MAX_ATTEMPTS = 4 def initialize(player) @player = player @secret = "" @attempts = 0 @hints = 0 generate_secret end def generate_secret SECRET_SIZE.times do @secret << (Random.rand(6)+1).to_s end end def guess(suspect) result = "" SECRET_SIZE.times do |i| if @secret[i] == suspect.value[i] result << "+" elsif @secret.include? suspect.value[i] result << "-" else result << "X" end end result end def can_use_hint? @hints < 1? true : false end def take_hint if can_use_hint? position = rand(3) @hints += 1 "в этом числе присутствует цифра #{uncover(position).chr} " end end def uncover(position) secret[position] end def result(suspect) @attempts += 1 string = guess(suspect) if string == "++++" p "Поздравляю #{@player.name} Вы угадали число!!!" save_game_result("../../tmp/results.txt") elsif @attempts < MAX_ATTEMPTS p "Вы использовали #{@attempts} из #{MAX_ATTEMPTS} попыток" elsif @attempts == MAX_ATTEMPTS p "игра закончена загаданое число #{@secret}" end end def save_game_result(file) File.open(file, 'a') { |f| f.puts("#{@player.name} угадал число.\n за #{@attempts} попытки\n подсказок использованно: #{@hints}\n-------") } end def answer p @secret end end end
true
fd1975c2fb770019f2d71886f8cc9bc1def2eac8
Ruby
Scott2bReal/intro-to-programming-with-ruby
/the-basics/4.rb
UTF-8
272
3.875
4
[]
no_license
=begin Use the dates from the previous example and store them in an array. Then make your program output the same thing as exercise 3. =end movies = {"Jurassic Park" => 1995, "Forrest Gump" => 1992} dates = [] movies.each { |k, v| dates.push(v) } dates.each { |date| puts date }
true
975641d1484ae3d61f9dd23d0d7762fe21c65011
Ruby
jaswanthJeenu/Ruby-to-MIPS-Compiler
/project/test/pointer2.rb
UTF-8
32
2.703125
3
[]
no_license
a = [] a[1]=2 b = a+4 puts b[0]
true
e983ea42be36d6713b012ab81411405881ae3fc6
Ruby
goldstar/blackbeard
/lib/blackbeard/metric_date.rb
UTF-8
376
2.625
3
[ "MIT" ]
permissive
module Blackbeard class MetricDate #TODO refactor with MetricHour to be compaosed attr_reader :date, :result def initialize(date, result) @date = date @result = result end def results_for(segments) segments.map{|s| result[s].to_f } end def result_rows(segments) [@date.to_s] + results_for(segments) end end end
true
9333388773173d9b3d6f89fc31ec9f9a63e30672
Ruby
SiCuellar/Code_Wars
/Ruby/decode_morse/algo.rb
UTF-8
240
3.0625
3
[]
no_license
require 'pry' #test/Hash Provided class Algo morse_letters = morseCode.split morse_letters.map do |let| MORSE_CODE[let] end end # morseCode.strip.split(" ").map { |w| w.split(" ").map { |c| MORSE_CODE[c] }.join }.join(" ")
true
7805b4ac1ac858a049a9a170c059cb545f4e640a
Ruby
MadayAlcala/Ruby-Training
/Slide4/flight/boarding.rb
UTF-8
1,719
3.953125
4
[]
no_license
require './flight' require './passenger' class Boarding def passenger_data puts "What is your name:" name = gets.chomp puts "What is your lastname:" lastname = gets.chomp puts "What is your address:" address = gets.chomp puts "What is your phone:" phone = gets.chomp puts "What is your age:" years = gets.chomp return name, lastname, address, phone, years end def boarding_passengers flight1 = Flight.new("La Paz", "Oruro", 123) flight2 = Flight.new("Oruro", "Cochabamba", 345) flight3 = Flight.new("Potosí", "Tarija", 89) flights = {flight1 => 0, flight2 => 0, flight3 => 0} puts flights.values puts "¿What type of flight did you need?" puts "1: Flight1 \n2: Flight2 \n3: Flight3 " flight_type = gets.chomp.to_i if flight_type == 1 unless flight1.passengers_number >= 3 flights[flight1] = flight1.passengers_number += 1 name, lastname, address, phone, years = passenger_data passenger = Passenger.new(name, lastname, address, phone, years) end elsif flight_type == 2 unless flight2.passengers_number >= 3 flights[flight2] = flight2.passengers_number += 1 name, lastname, address, phone, years = passenger_data passenger = Passenger.new(name, lastname, address, phone, years) end elsif flight_type == 3 if flight3.passengers_number < 3 flights[flight3] = flight3.passengers_number +=1 name, lastname, address, phone, years = passenger_data passenger = Passenger.new(name, lastname, address, phone, years) end else "That type of flight does not exist." end end end Boarding.new.boarding_passengers
true
5309a40f02e9830afe718a639562a2a57784b914
Ruby
olistik/website-template
/app/models/cell_registry.rb
UTF-8
1,504
2.625
3
[ "MIT" ]
permissive
# cell_class = Cell::Base::class_from_cell_name(cell) # use cell_class.instance_methods(false) # to obtain the cell's list of available actions class CellRegistry @@registry = [] def self.registry register_all if @@registry.empty? @@registry end def self.registry=(r) @@registry = r end def self.register(cell) @@registry.push(cell) end def self.unregister(cell = nil) return @@registry.pop unless cell @@registry.delete(cell) end def self.actions_by_cell(cell) Cell::Base::class_from_cell_name(cell).instance_methods(false) end def self.register_all cells_paths = RAILS_ROOT + "/app/cells" @possible_cells = [] paths = cells_paths.select { |path| File.directory?(path) && path != "." } seen_paths = Hash.new {|h, k| h[k] = true; false} ActionController::Routing::normalize_paths(paths).each do |load_path| Dir["#{load_path}/**/*_cell.rb"].collect do |path| next if seen_paths[path.gsub(%r{^\.[/\\]}, "")] cell_name = path[(load_path.length + 1)..-1] cell_name.gsub!(/_cell\.rb\Z/, '') @possible_cells << cell_name end end @possible_cells.uniq! #TODO register only some kind of cells for cell in @possible_cells do # cell_class = Cell::Base::class_from_cell_name(cell) register(cell) end end end
true
dafe6a7c4c703637a3bd095c9ffff4e52d26edf3
Ruby
nax2uk/decorating-command-line
/lib/example_lolize.rb
UTF-8
1,889
3.484375
3
[]
no_license
# shows how to use lolize to selectively display rainbow coloured fonts. require 'lolize' colorizer = Lolize::Colorizer.new puts " ████████╗██╗░█████╗░  ████████╗░█████╗░░█████╗░  ████████╗░█████╗░███████╗ ╚══██╔══╝██║██╔══██╗  ╚══██╔══╝██╔══██╗██╔══██╗  ╚══██╔══╝██╔══██╗██╔════╝ ░░░██║░░░██║██║░░╚═╝  ░░░██║░░░███████║██║░░╚═╝  ░░░██║░░░██║░░██║█████╗░░ ░░░██║░░░██║██║░░██╗  ░░░██║░░░██╔══██║██║░░██╗  ░░░██║░░░██║░░██║██╔══╝░░ ░░░██║░░░██║╚█████╔╝  ░░░██║░░░██║░░██║╚█████╔╝  ░░░██║░░░╚█████╔╝███████╗ ░░░╚═╝░░░╚═╝░╚════╝░  ░░░╚═╝░░░╚═╝░░╚═╝░╚════╝░  ░░░╚═╝░░░░╚════╝░╚══════╝\n\n" colorizer.write " Welcome to Tic Tac Toe!\n\n" colorizer.write "Instructions:\n\nThe game is played on a 3x3 grid.\nYou are X, your opponent is O. Players take turns putting their marks in empty squares.\nThe first player to get 3 of their marks in a row (up, down, across, or diagonally) is the winner.\nIf all 9 squares are full and no player has 3 marks in a row, the game is over.\n\n\n"
true
b8f01eaca138d1b613db2351f0e4aef00243f977
Ruby
steinuil/yubiyubi
/vtuber_handler.rb
UTF-8
679
2.609375
3
[ "Unlicense" ]
permissive
require 'yaml' require_relative 'lib/irc' class VtuberHandler def initialize file @file = file reload_list end def reload_list @list = YAML.safe_load(File.read @file) @last_mtime = File.mtime(@file) end def handle msg return unless msg.command == "PRIVMSG" && msg.params[1].strip == "'chuuba" if File.mtime(@file) != @last_mtime reload_list end vtuber = @list.sample IRC::Protocol.privmsg( msg.params[0], if vtuber["agency"] "#{msg.prefix.nick}, your vtuber is #{vtuber["name"]} (#{vtuber["agency"]})" else "#{msg.prefix.nick}, your vtuber is #{vtuber["name"]}" end ) end end
true
f9a7fa2d333e6d807009212ea8a0eae32c8adf10
Ruby
radu-constantin/small-problems
/easy7/swap_case.rb
UTF-8
426
3.59375
4
[]
no_license
UPPERCASE = ('A'..'Z').to_a LOWERCASE = ('a'..'z').to_a def swapcase (string) new_string = '' string.each_char do |char| if UPPERCASE.include?(char) new_string << char.downcase elsif LOWERCASE.include?(char) new_string << char.upcase else new_string << char end end new_string end puts swapcase('CamelCase') == 'cAMELcASE' puts swapcase('Tonight on XYZ-TV') == 'tONIGHT ON xyz-tv'
true
ef569a58b15051a3db6ec336cbf887c4405f66a2
Ruby
tilmitt11191/mtg
/lib/decklists/read-operate-write-deckfiles.rb
UTF-8
1,139
2.53125
3
[]
no_license
#ruby require "logger" require '../../lib/util/deck.rb' require '../../lib/util/store.rb' log = Logger.new("../../log", 5, 10 * 1024 * 1024) log.info "" log.info "read-operate-write-deckfiles start." log.info "" deckname = "BG_Con_JF" hareruya = Hareruya.new #### read deck #from file deck = hareruya.read_deckfile("../../decks/" + deckname.to_s + ".csv", "card_type,cardname,quantity,manacost,generating_mana_type,price,store_url,price.date", "with_info") #from web #deck = Deck.new(deckname.to_s, "hareruya", "http://www.hareruyamtg.com/jp/k/kD08241S/") #deck.create_cardlist("full") #### operate deck hareruya.convert_all_cardname_from_jp_to_eng(deck) deck.get_sum_of_generationg_manas deck.get_contents #calculate price of each_card_type, #such as land,creatures,spells,MainboardCards,sideboardCards #using card.price already set. deck.calc_price_of_each_card_type #calculate total price of this deck. deck.calc_price_of_all_deck #### write deck deck.view_deck_list #deck.create_deckfile("../../decks/" + deckname.to_s + ".csv", "card_type,name,quantity,manacost,generating_mana_type,price,store_url,price.date", "with_info")
true
15110b65550bf6d741f3dcae793b7792c141f4d8
Ruby
enonnai/lrthw
/ex04/drill_02.rb
UTF-8
168
3.4375
3
[]
no_license
x = 5 i = 3 sum = x + i subtraction = x - i multiplication = x * i division = (x.to_f / i.to_f).round(2) puts sum puts subtraction puts multiplication puts division
true
f9ebbc7600073dd48d1d489d148b9006bfe6f9f7
Ruby
naathyn/workspace_management
/app/models/folder.rb
UTF-8
584
2.515625
3
[]
no_license
class Folder < ActiveRecord::Base attr_accessible :name, :directory_id, :subfolder_id belongs_to :directory belongs_to :subfolder, foreign_key: "subfolder_id", class_name: "Folder" has_many :documents, dependent: :destroy has_many :subfolders, foreign_key: "subfolder_id", class_name: "Folder", dependent: :destroy validates_presence_of :name def path begin File.join(directory.name, name).gsub(/\s/, '_').downcase rescue NoMethodError File.join(subfolder.directory.name, subfolder.name, name). gsub(/\s/, '_').downcase end end end
true
6169acb5a550f238064b3d508c1c0416de6b770e
Ruby
liyijie/huanct
/app/models/comment.rb
UTF-8
1,917
2.703125
3
[]
no_license
class Comment < ActiveRecord::Base attr_accessible :dianping, :gongxian, :last_time, :member, :name, :qiandao, :reg_time # 分页显示的默认值 self.per_page = 10 def self.create_by_member member comment = Comment.new comment.member = member url = "http://www.dianping.com/member/#{member}" params = { :headers => { "User-Agent" => "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.116 Safari/537.36" } } response = HTTParty.get(url, params) # puts response.body nodes = Nokogiri::XML(response.body).xpath("//h2") nodes.each do |node| text = node.get_attribute "class" next if text.nil? if (text == "name") comment.name = node.text end end nodes = Nokogiri::XML(response.body).xpath("//a") nodes.each do |node| text = node.text next if text.nil? if (text.start_with? "点评(") comment.dianping = text.sub("点评(","").sub(")","") elsif (text.start_with? "签到(") comment.qiandao = text.sub("签到(","").sub(")","") end end nodes = Nokogiri::XML(response.body).xpath("//span") nodes.each do |node| text = node.get_attribute "title" if text if (text.start_with? "贡献值") comment.gongxian = text.sub("贡献值","") end elsif (node.text.start_with? "注册时间") comment.reg_time = node.parent.text.sub("注册时间:","") elsif (node.text.start_with? "最后登录") comment.last_time = node.parent.text.sub("最后登录:","") end end comment end def merge other @member = other.member @name = other.name @dianping = other.dianping @gongxian = other.gongxian @qiandao = other.qiandao @reg_time = other.reg_time @last_time = other.last_time end end
true
ec51717a567eaa7196298caa45045348010e5eb6
Ruby
emarcha/scuba_shop_app
/app/models/tour.rb
UTF-8
1,078
2.84375
3
[]
no_license
class Tour < ActiveRecord::Base has_many :bookings, before_add: :check_available_seats, dependent: :destroy before_create :populate_available_seats before_create :parse_time_input validates :title, presence: true, length: { maximum: 100 } validates :tour_date, presence: true validates :total_seats, presence: true, numericality: { only_integer: true, greater_than_or_equal_to: 1 } validates :price_cents, presence: true, numericality: { only_integer: true, greater_than_or_equal_to: 0} validates :duration_before_typecast, presence: true private def populate_available_seats self.available_seats = self.total_seats end def parse_time_input self.duration = ChronicDuration.parse(self.duration_before_typecast) end def check_available_seats(booking) if self.available_seats <= 0 raise 'No seats available' end end end
true
61e75895925e9a0e0101fd060a8a77520017221d
Ruby
shiratsu/shoppingrails
/lib/tasks/amazon_crawl.rb
UTF-8
2,162
2.53125
3
[]
no_license
# coding: utf-8 require 'open-uri' require 'json' require "date" require 'amazon/ecs' class Tasks::AmazonCrawl #変数初期化 @@api_url = 'http://ecs.amazonaws.com/onca/xml' # メイン処理 def self.execute(category_id) Amazon::Ecs.options = { :associate_tag => 'shiratsu2014-22', :AWS_access_key_id => '14GKTW6QN5G14DGTNFG2', :AWS_secret_key => 'wZJovZno6tiy0SgOHP6kZEtPp3HbkMNaltp/5Ir7' } #まずは、DBから値を取得 now = d.strftime("%Y-%m-%d %H:%M:%S") products = Products.find(:all, :conditions => {:api_type => 1,:created_at => now}) products.each do |item| self.main(item.product_name) end end def self.main(name) res = Amazon::Ecs.item_search('ruby', :search_index => 'All',:response_group => 'ItemAttributes,Offers, Images ,Reviews', :country => 'jp') products_list = [] if(res.items.length > 0) res.items.each do |item| puts("asin: #{item.get('ASIN')}") puts("url: #{item.get('DetailPageURL')}") puts("title: #{item.get('ItemAttributes/Title')}") puts("price: #{item.get('ItemAttributes/ListPrice/FormattedPrice')}") puts("price: #{item.get('ItemAttributes/ListPrice/Amount').to_s}") puts("image: #{item.get('MediumImage/URL')}") puts("image: #{item.get('SmallImage/URL')}") puts("中古在庫 : #{item.get('OfferSummary/TotalUsed')}") puts("中古価格 : #{item.get('OfferSummary/LowestUsedPrice/Amount').to_s}") puts item products_list << Products.new(api_type:1, product_name: item.get('ItemAttributes/Title'), category_name: '', description: '', url: item.get('DetailPageURL'), image_small_url: item.get('SmallImage/URL'), image_medium_url: item.get('MediumImage/URL'), product_id: item.get('ASIN'), fixed_price: item.get('ItemAttributes/ListPrice/Amount'), used_price: item.get('OfferSummary/LowestUsedPrice/Amount'), total_used: item.get('OfferSummary/TotalUsed') ) end else puts("#{ARGV[0]}: products not found") end Products.import products_list @@start += return_count end end
true
0d528387539bb61d3ebe386340304d8130f40caa
Ruby
arthurgeek/nyane
/lib/nyane.rb
UTF-8
1,065
2.6875
3
[ "MIT" ]
permissive
require "rack" class Nyane attr_reader :request, :response def initialize(&block) @actions = [] @root = File.dirname(eval("__FILE__", block.binding)) @app = self instance_eval(&block) end def get(route, &block) @actions << [route, :get, block] end def post(route, &block) @actions << [route, :post, block] end def redirect_to(path) @response.status = 302 @response.headers["Location"] = path end def load(file) path = File.join(@root, file) + ".rb" eval(File.read(path), binding, path) end def call(env) @request = Rack::Request.new(env) @response = Rack::Response.new @params = @request.params path_info = nil action = @actions.detect { |route, method, block| @request.request_method == method.to_s.upcase! && path_info = @request.path_info.match(Regexp.new("^\/?#{route}\/?$")) } if action @response.write(action.last.call(path_info[1..-1])) else @response.write("Not found") @response.status = 404 end @response.finish end end
true
1b0d83e49b368417aa9311a3271b2fee8c29037f
Ruby
mariecain27/key-for-min-value-v-000
/key_for_min.rb
UTF-8
387
3.359375
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
# prereqs: iterators, hashes, conditional logic # Given a hash with numeric values, return the key for the smallest value def key_for_min_value(name_hash) min_key = nil start_zero_compare_value = 0 name_hash.each do |key, value| if start_zero_compare_value == 0 || value < start_zero_compare_value start_zero_compare_value = value min_key = key end end min_key end
true
ff53c895da85ee18364cff388c06413a3533f5bd
Ruby
kkchu791/coding-challenge-kkchu791
/pop_growth/app/services/csv_parser.rb
UTF-8
1,866
2.984375
3
[]
no_license
require 'csv' class CSVParser attr_reader :file, :type def initialize(file, type) @file = file @type = type end def process_file if type == "zip_codes" process_zip_codes else process_core_based_stat_areas_file end end def process_zip_codes CSV.foreach(file, headers: true) do |row| zip_code = row.to_h zip_attr = zip_code.keys[0] ZipCode.find_or_create_by!( zip_code: zip_code[zip_attr], cbsa: zip_code["CBSA"] ) end end def process_core_based_stat_areas_file CSV.foreach(file, headers: true, encoding:'iso-8859-1:utf-8') do |row| data = row.to_h cbsa_attr = data.keys[0] cbsa_record = create_cbsa_record(data, cbsa_attr) population_stat_record = create_population_stat_record(data, cbsa_record) create_population_estimate_records(data, population_stat_record) end end private def create_cbsa_record(data, cbsa_attr) CoreBasedStatArea.find_or_create_by!( cbsa: data[cbsa_attr], mdiv: data["MDIV"] ) end def create_population_stat_record(data, cbsa_record) PopulationStat.find_or_create_by!( name: data["NAME"], lsad: data["LSAD"], core_based_stat_area_id: cbsa_record.id ) end def create_population_estimate_records(data, population_stat_record) data.each do |attr, value| if attr.include?("POPESTIMATE") && value.present? year = attr[-4..-1] PopulationEstimate.find_or_create_by!(year: year, estimate: value.to_i, population_stat_id: population_stat_record.id) end end end end
true
0b0f08bc99f2f12867e208c569f46e0aeefb598b
Ruby
ricardo39985/square_array-online-web-ft-120919
/square_array.rb
UTF-8
115
2.953125
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def square_array(array) # your code here new_array = [] array.each { |n| new_array.push(n * n )} new_array end
true
79a95adc93347a5505ec2ae33a6ab1a87c9b1ae3
Ruby
rabbitz/TryRuby
/test/unit/output_test.rb
UTF-8
1,497
2.734375
3
[]
no_license
require 'test_helper' # tests if the TryRubyOutput translation, for use with mouseapp_2.js and similar # is working correctly class OutputTest < Test::Unit::TestCase def test_simple_result t = TryRuby::Output.standard(result: [12,24]) assert_equal("=> \033[1;20m[12, 24]", t.format) end def test_result_and_output t = TryRuby::Output.standard(result: 333, output: "hello") assert_equal("hello=> \033[1;20m333", t.format) end def test_error begin 40.reverse rescue Exception => e t = TryRuby::Output.error(error: e) end assert_equal("\033[1;33mNoMethodError: undefined method `reverse' for 40:Fixnum", t.format) end def test_error_with_output begin 40.reverse rescue Exception => e t = TryRuby::Output.error(error: e, output: "hello\nworld") end assert_equal("hello\nworld\033[1;33mNoMethodError: undefined method `reverse' for 40:Fixnum", t.format) end def test_illegal t = TryRuby::Output.illegal assert_equal("\033[1;33mYou aren't allowed to run that command!", t.format) end def test_line_continuation t = TryRuby::Output.line_continuation(3) assert_equal(".." * 3, t.format) end def xtest_javascript t = TryRuby::Output.javascript(javascript: 'alert("hello")') # expected ends in a space to stop a visual problem in mouseapp assert_equal("\033[1;JSmalert(\"hello\")\033[m ", t.format) end end
true
5ad69a1732ec39a48e25e1609b0c19ad86054171
Ruby
ghostlambdax/recognizeapp
/app/queries/streamable_recognitions.rb
UTF-8
3,418
2.640625
3
[]
no_license
class StreamableRecognitions # Order of badge is important because it is referenced in some places. BADGE_FILTERS = %w[anniversary recognition] attr_reader :current_user, :network, :company, :team_id, :filter_by def self.call(args) new(args).query end def initialize(args) extract_args args end def query scoped = filter_by_network_and_parameters scoped = scoped.approved.not_private scoped = scoped.includes(:badge) if company.settings.hide_disabled_users_from_recognitions? # When both recipients_active and sender_active scope applied, it fetched the recognitions having sender # active and at least one recipient active. scoped = scoped.recipients_active.sender_active end scoped.distinct end private def extract_args(args) @current_user = args[:user] @network = args[:network] @company = args[:company] @team_id = args[:team_id] @filter_by = (Array(args[:filter_by]) & badge_filters) || [] end def filter_by_network_and_parameters # special handling for Recognize network or admins # there is a quirk when you view stream page as a non admin user on recognizeapp.com domain # we enter this conditional and will see all the system recognitions sent by the system user # to have consistency, and to not freak me out in the future when i log in as another recognizeapp # user, have a special condition for this records = recognitions_for_recognize_network_or_admins if is_admin_or_recognize_network? filter_by_parameters records end def filter_by_parameters(default_records) records = if team_id_present_and_valid? find_by_team_id else default_records || default_recognitions end records = find_by_badge(records) if filter_by.any? records end def find_by_team_id find_team&.recognitions end def find_by_badge(records) return records if filter_by.length == badge_filters.length records = records.includes(:badge) is_anniversary_query = filter_by.include?(badge_filters.first) records.where(badges: { is_anniversary: is_anniversary_query }) end def recognitions_for_recognize_network_or_admins return find_by_user_company if is_same_network? find_by_network end # FIXME: Admin or Director can type any network in url and access the stream page but all the rendered links # on that page point to the different company. Network verification has to be done to fix it. # Note: This query is used for recognize_network_or_admins only def find_by_network Company.where(domain: network).first.recognitions end # Note: This query is used for recognize_network_or_admins only def find_by_user_company current_user.company.recognitions end def is_admin_or_recognize_network? current_user && (current_user.admin? || network == "recognizeapp.com") end def is_same_network? network.casecmp?(current_user.network) end def default_recognitions Recognition.for_company(company) || Recognition.none end # FIXME: team_id could be any company's team. Need special handeling for team verification # so that to fetch recognitions from authoritative company's team only. def team_id_present_and_valid? team_id.present? end def find_team Team.find_from_recognize_hashid(team_id) end def badge_filters self.class::BADGE_FILTERS end end
true
44312f2669ca82b411ebd4affc6923254d100f01
Ruby
petejkim/skeleton
/spec/support/fixture_saver.rb
UTF-8
1,996
2.515625
3
[]
no_license
module FixtureSaver # Saves the markup to a fixture file using the given name def save_fixture(markup, name) fixture_path = File.join(Rails.root, '/tmp/js_dom_fixtures') Dir.mkdir(fixture_path) unless File.exists?(fixture_path) fixture_file = File.join(fixture_path, "#{name}.fixture.html") File.open(fixture_file, 'w') do |file| file.puts(markup) end end def all_html response.body end # From the controller spec response body, extracts html identified # by the css selector. def html_for(selector = 'body') doc = Nokogiri::HTML(response.body) prepare_html(doc) content = doc.css(selector).first.to_s convert_body_tag_to_div(content) end def prepare_html(doc) set_sources_to_nothing(doc) remove_third_party_scripts(doc) remove_iframes(doc) end def set_sources_to_nothing(doc) blank_png = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAADCAIAAAA7ljmRAAAAGElEQVQIW2P4DwcMDAxAfBvMAhEQMYgcACEHG8ELxtbPAAAAAElFTkSuQmCC' images = doc.search('img') images.each{ |img| img['src'] = blank_png } images = doc.search('*[style*="background"]') images.each do |el| el['style'] = el['style'].gsub(/url\([^\)]*\)/,"url(#{blank_png})") end end def remove_third_party_scripts(doc) scripts = doc.search('.third_party_script') + doc.search('script[src]') + doc.search('script:contains("fbAsyncInit")') scripts.remove if scripts end def remove_iframes(doc) iframes = doc.search('iframe') iframes.remove if iframes end # Many of our css and jQuery selectors rely on a class attribute we # normally embed in the <body>. For example: # # <body class="workspaces show"> # # Here we convert the body tag to a div so that we can load it into # the document running js specs without embedding a <body> within a <body>. def convert_body_tag_to_div(markup) markup.gsub("<body", '<div').gsub("</body>", "</div>") end end
true
01435bb4522fd104e51e381dbcb4a08d56a75688
Ruby
appwrite/sdk-for-ruby
/lib/appwrite/models/database_list.rb
UTF-8
766
2.515625
3
[ "BSD-3-Clause" ]
permissive
#frozen_string_literal: true module Appwrite module Models class DatabaseList attr_reader :total attr_reader :databases def initialize( total:, databases: ) @total = total @databases = databases end def self.from(map:) DatabaseList.new( total: map["total"], databases: map["databases"].map { |it| Database.from(map: it) } ) end def to_map { "total": @total, "databases": @databases.map { |it| it.to_map } } end end end end
true
c1aea7d6320a4ceb29aac46cf41026bb7e0fe64d
Ruby
thomgray/trot
/lib/trot/builder.rb
UTF-8
2,399
2.515625
3
[ "MIT" ]
permissive
require 'fileutils' module Trot class Builder def initialize(target) @target = target end def build puts 'target', @target object_files = [] source_files_to_compile = [] puts '.>>>>> sources', source_files source_files.each { |source_file| file_name = File.basename(source_file, '.c') object_file = File.join(object_files_directory, "#{file_name}.o") object_files << object_file if Make.should_update_target(source_file, object_file) source_files_to_compile << source_file end } compile_objects(source_files_to_compile) copy_header_files link_object_files(object_files) end def copy_header_files puts "copying header files", @target end def compile_objects(source_files_to_compile) $fs.ensure_dir object_files_directory $compiler.compile(source_files_to_compile, object_files_directory) unless source_files_to_compile.empty? end def link_object_files(object_files) return if object_files.empty? return unless Make.should_update_target(object_files, target_path) $fs.ensure_dir target_dir if is_static_lib? $compiler.link_static_lib(object_files, target_path) else $compiler.link(object_files, target_path) end end private def is_static_lib? @is_static_lib ||= @target.is_static_lib end def object_files_directory @object_files_directory ||= File.join($trot_build_dir, @target.is_default ? '' : @target.name, 'objectFiles') end def source_files @source_files ||= Proc.new() { includes = @target.src[:include] excludes = @target.src[:exclude] || [] puts '>>>> including', includes puts '>>>>>> excluding', excludes src_files = Set.new; includes.each { |f| src_files += $fs.files_recursive(f) } excludes.each { |x| src_files -= $fs.files_recursive(x) } src_files.to_a.select { |f| f =~ /\.c$/ } }.call end def header_files # @header_files ||= $fs.h_files_recursive(@target[:sourceDir]) end def target_path @target_path ||= $fs.absolute_path @target.dest end def target_name @target_name ||= File.basename(target_path) end def target_dir @target_dir ||= File.dirname(target_path) end end end
true
4cc3f8f36afeaa02b71ab20b85ef9751768d79b1
Ruby
codyruby/cursus_thp
/week2/scrapping/lib/dark_trader.rb
UTF-8
2,602
3.71875
4
[]
no_license
# Il est possible de faire le programme en n'allant que sur une seule URL. C'est un bon moyen pour faire un programme rapide car ne chargeant pas 2000 pages HTML. # Tout se jouera sur la rédaction d'un XPath pertinent et précis qui extrait juste ce qu'il faut d'éléments HTML. Puis un bon traitement de ces éléments pour en extraire les 2 infos dont tu as besoin : le nom des crypto et leur cours. # Un programme qui scrappe sans rien te dire, c'est non seulement nul mais en plus, tu ne sais pas s'il marche, s'il tourne en boucle ou s’il attend que ton wifi fonctionne. Mets des puts dans ton code pour que ton terminal affiche quelque chose à chaque fois qu'il a pu récupérer une donnée. Comme ça tu vois ton scrappeur qui fonctionne et avec des mots qui apparaissent tout seul sur ton terminal, tu vas donner l'impression que t'es un hacker. Stylaï. # Pense à bien nommer tes variables pour ne pas te perdre ! Par exemple, quand tu as un array, nomme-le crypto_name_array ou à minima mets son nom au pluriel crypto_nameS. Sinon tu vas oublier que c'est un array et tu vas tenter des .text dessus alors qu'il faut bosser avec un .each. # Rappel: un hash s’initialise avec result = Hash.new et on y stocke des infos avec result['ta_key'] = 'ta_value' # N'hésite pas à découper ton programme en plusieurs étapes simples et dont le fonctionnement est facile à vérifier. Par exemple : 1) Isoler les éléments HTML qui vont bien, 2) En extraire le texte et mettre ça dans un hash, 3) Réorganiser ce hash dans un array de plusieurs mini-hash comme demandé. # Même si ça n'est pas le chemin le plus court, l'essentiel est que chaque petite étape te fasse avancer et qu'à chaque fois tu te dises "ok, étape 1), ça fonctionne nickel - pas de bug. Passons à la suite". require 'open-uri' require 'nokogiri' def crypto_price doc = Nokogiri::HTML(open("https://coinmarketcap.com/all/views/all/")) list_crypto_and_price = [] # 1) Isoler les éléments HTML qui vont bien, # Nom : [:href].split("/")[2] # Cours : xpath("//a[@class=\"price\"]") # 2) En extraire le texte et mettre ça dans un hash doc.xpath("//a[@class=\"price\"]").each do |node| list_crypto_and_price << {name: node[:href].split("/")[2], price: node.text} end # 3) Réorganiser ce hash dans un array de plusieurs mini-hash comme demandé. crypto_price_view = {} list_crypto_and_price.each do |value| crypto_price_view[value[:name]] = value[:price] end p crypto_price_view end crypto_price
true
739e5d9b68e24eb2e8342b07e288ce2e1bc7d52b
Ruby
lipanski/hexagonly
/lib/hexagonly/polygon.rb
UTF-8
3,210
3.1875
3
[ "MIT" ]
permissive
module Hexagonly class Polygon # Adds Polygon methods to an object. The Polygon corners are read via # the #poly_points method. You can override this method or use the # #poly_points_method class method to set a method name for reading # polygon corners. # # @example # class MyPolygon # # include Hexagonly::Polygon::Methods # poly_points_method :corners # # attr_reader :corners # def initialize(corners); @corners = corners; end # # end module Methods def self.included(base) base.extend(ClassMethods) end module ClassMethods attr_accessor :poly_points_method_name def poly_points_method(points_method) self.poly_points_method_name = points_method.to_sym end end attr_accessor :collected_points, :rejected_points def poly_points raise NoMethodError if self.class.poly_points_method_name.nil? send(self.class.poly_points_method_name) end # Crossing count algorithm for determining whether a point lies within a # polygon. Ported from http://www.visibone.com/inpoly/inpoly.c.txt # (original C code by Bob Stein & Craig Yap). def contains?(point) raise "Not a valid polygon!" if poly_points.nil? || poly_points.size < 3 is_inside = false old_p = poly_points.last poly_points.each do |new_p| if new_p.x_coord > old_p.x_coord first_p = old_p second_p = new_p else first_p = new_p second_p = old_p end if ((new_p.x_coord < point.x_coord) == (point.x_coord <= old_p.x_coord)) && ((point.y_coord - first_p.y_coord) * (second_p.x_coord - first_p.x_coord) < (second_p.y_coord - first_p.y_coord) * (point.x_coord - first_p.x_coord)) is_inside = ! is_inside end old_p = new_p end is_inside end # Grabs all points within the polygon boundries from an array of Points # and appends them to @collected_points. All rejected Points are stored # under @rejected_points (if you want to pass the to other objects). # # @param points [Array<Hexagonly::Point>] # # @return [Array<Hexagonly::Point] the grabed points def grab(points) parts = points.partition{ |p| contains?(p) } @collected_points ||= [] @collected_points += parts[0] @rejected_points = parts[1] parts[0] end attr_accessor :geo_properties attr_accessor :geo_style def to_geojson points = poly_points.map{ |p| [p.x_coord, p.y_coord] } points << points.last { :type => "Feature", :geometry => { :type => "Polygon", :coordinates => [points] }, :style => geo_style, :properties => geo_properties } end end include Methods attr_accessor :poly_points # @param [Array<Hexagonly::Point>] poly_points the points that make up the polygon def initialize(poly_points) @poly_points = poly_points end end end
true
f57c32cc91e84ca130fe042ad0295673acc1b6da
Ruby
neilkelty/programming-ruby
/chapter_2/arrays_and_hashes.rb
UTF-8
515
3.21875
3
[]
no_license
a = [1, 'cat', 3.14] # array with three elements puts "The first element is #{a[0]}" # set the third element a[2] = nil puts "The array is now #{a.inspect}" inst_section = { 'cello' => 'string', 'clarinet' => 'woodwind', 'drum' => 'percussion', 'oboe' => 'woodwind', 'trumpet' => 'brass', 'violin' => 'string' } p inst_section['oboe'] p inst_section['cello'] p inst_section['bassoon'] histogram = Hash.new(0) histogram['ruby'] # => 0 histogram['ruby'] = histogram['ruby'] + 1 histogram['ruby'] # => 1
true
d40ce89baeb2022053f6b186aa9d474f8e9073a2
Ruby
sedx876/badges-and-schedules-online-web-pt-090919
/conference_badges.rb
UTF-8
461
3.484375
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
# Write your code here. attendees = ["Edsger", "Ada", "Charles", "Alan", "Grace", "Linus", "Matz"] def badge_maker(name) do puts "Hello, my name is #{name}" end def batch_badge_maker #attendees = ["Edsger", "Ada", "Charles", "Alan", "Grace", "Linus", "Matz"] attendees.each do |name| puts "Hello, my name is #{name}" end end def assign_rooms attendees.each_with_index { |name, index| puts "Hello, #{name}! You'll be assigned to room #{index}!" } end
true
7eb689f0b6dc4e819e985b029674a4338cbe0a33
Ruby
emielhagen/convoyer
/app/services/location_service.rb
UTF-8
1,582
2.828125
3
[]
no_license
class LocationService attr_reader :from_location, :to_location, :base_url, :api_key attr_accessor :params def initialize(params) @from_location = params.dig('convoy', 'from_location') @to_location = params.dig('convoy', 'to_location') @base_url = 'https://api.mapbox.com/geocoding/v5/mapbox.places/' @api_key = ENV['MAPBOX_API_KEY'] @params = params end def create_location_hash return if from_location.empty? || to_location.empty? from_id = find_or_create_location(from_location) to_id = find_or_create_location(to_location) params = update_params_hash(from_id, to_id) params end def find_or_create_location(location) db_location = Location.find_by(name: location.capitalize) return db_location.id if db_location coordinates = get_mapbox_details(location) return if coordinates.nil? new_location = create_new_location(location, coordinates) new_location.id end def update_params_hash(from, to) params['convoy']['from_location_id'] = from params['convoy']['to_location_id'] = to end def get_mapbox_details(location_name) response = JSON.parse(HTTParty.get("#{base_url}#{location_name.gsub(/ /, '+')}.json?access_token=#{api_key}")) return if response.nil? || response.dig('features').empty? features = response.dig('features')&.first return if features.empty? features.dig('geometry', 'coordinates') end def create_new_location(name, coordinates) Location.create(name: name.capitalize, longitude: coordinates[0], latitude: coordinates[1]) end end
true
ecaff361c4d36023aa63db8598b973fadab76d7a
Ruby
justinsteele/coveragetrends
/lib/coveragetrends.rb
UTF-8
385
2.578125
3
[]
no_license
require './lib/circleci' require 'csv' class CoverageTrends def initialize(username, project) @username = username @project = project end def run ci = CircleCI.new(@username, @project) stats = ci.get_stats save_stats(stats) return 1 end def save_stats(array) open('output/data.json', 'wb') do |f| f.puts array.to_json end end end
true
ad303f4648f2f1a6777612cb890b5cad578c9364
Ruby
masayasviel/algorithmAndDataStructure
/OtherContests/zone2021/mainA.rb
UTF-8
124
2.984375
3
[]
no_license
s = gets.chomp ans = 0 9.times do |i| tmp = s[i..(i+3)] if tmp == "ZONe" then ans += 1 end end puts ans
true
8be9ef85d7c0a93338c4b0d7c307096cbf57091f
Ruby
lvzhongwen/pms
/pms-server/app/models/enum/base_type.rb
UTF-8
913
2.9375
3
[]
no_license
class BaseType<BaseClass def self.method_missing(method_name, *args, &block) mn=method_name.to_s.sub(/\?/, '') if /\w+\?/.match(method_name.to_s) begin self.const_get(mn.upcase)==args[0].to_i rescue super end else super end end class<<self define_method(:has_value?) { |s| self.constants.map { |c| self.const_get(c.to_s) }.include?(s) } end def self.get_type(type) const_get(type.upcase) end def self.display(v) constant_by_value(v) end def self.include_value?(v) constants.collect{|c|const_get(c.to_s)}.include?(v.to_i) end def self.key(v) constant_by_value(v).downcase end def self.to_select select_options = [] constants.each do |c| v = const_get(c.to_s) select_options << SelectOption.new(display: self.display(v), value: v, key: self.key(v)) end select_options end end
true
8d31576108cf12c70df5f17b43b77ba4654f8212
Ruby
broad-well/aoc2016
/day5.rb
UTF-8
815
3.0625
3
[ "Unlicense" ]
permissive
# Day 5 of Advent Of Code, 2016 INPUT = 'ojvtpuvg' require 'digest' require 'set' part2 = ARGV.include? 'part2' fast = ARGV.include? 'fast' i = 0 $c = Set.new if part2 pwd = part2 ? '00000000' : '' loop do md5 = Digest::MD5.hexdigest INPUT + i.to_s if !fast && i % 50 == 0 then print "Fresh MD5: #{md5}\r" end #print "#{INPUT + i.to_s} => #{md5}\r" if md5.start_with? '00000' if part2 && md5[5].to_i < 8 && md5[5].to_i.to_s == md5[5] && !$c.include?(md5[5].to_i) pwd[md5[5].to_i] = md5[6] puts "\e[2KPassword now: #{pwd}" if part2 then $c << md5[5].to_i end else unless part2 pwd += md5[5] puts "\e[2KFound one! @ #{i}, md5=#{md5}" end end end break if part2 ? $c.length == 8 : pwd.length == 8 i+=1 end puts "\e[1mpassword: #{pwd}\e[0m"
true
67bca19a9af6b558856e1e41533d40e7ebb62ef7
Ruby
kaiks/unobot
/lib/misc.rb
UTF-8
1,188
2.5625
3
[]
no_license
# TODO: separate logger from the rest # require 'extend_logger.rb' require 'logger' $logger = Logger.new('logs/unobot.log', 'daily', 10) $logger_queue = Queue.new $logger.datetime_format = '%H:%M:%S' $logger_thread = Thread.new do loop do while $DEBUG == true && $bot && $bot.config.engine.busy == false $logger.add(Logger::INFO, $logger_queue.pop) end sleep(0.5) end end def log(text) $logger_queue << ('\n' << text) end def bot_debug(text, detail = 1) log(text) if $DEBUG_LEVEL >= detail puts "#{detail >= 3 ? '' : caller[0]} #{text}" end end def set_debug(level) $DEBUG = true $DEBUG_LEVEL = level.to_i end def unset_debug $DEBUG = false $DEBUG_LEVEL = 0 end class Array # array exists and has nth element (1=array start) not null def exists_and_has(n) size >= n && !at(n - 1).nil? end def equal_partial?(array) each_with_index.all? { |a, i| a == :_ || array[i] == :_ || a == array[i] } end end class NilClass def exists_and_has(_n) false end end module Misc NICK_REGEX = /([a-z_\-\[\]\\^{}|`][a-z0-9_\-\[\]\\^{}|`]{1,15})'s/i NICK_REGEX_PURE = /([a-z_\-\[\]\\^{}|`][a-z0-9_\-\[\]\\^{}|`]{1,15})/i end
true
f058f9161f4811e53e651d66fdcc132612299588
Ruby
pelensky/lrthw
/ex34.rb
UTF-8
471
4.03125
4
[]
no_license
animals = ["bear", "ruby", "peacock", "kangaroo", "whale", "platypus"] puts "The animal at 1 is ruby" puts animals[1] puts "The third animal is peacock" puts animals[3-1] puts "The first animal is bear" puts animals[0] puts "The animal at 3 is kangaroo" puts animals[3] puts "The fifth animal whale" puts animals[5-1] puts "The animal at 2 is peacock" puts animals[2] puts "The sixth animal is platypus" puts animals[6-1] puts "the animal at 4 is whale" puts animals[4]
true
80878e5d6076dca59107ace39240663a11ee1ac8
Ruby
shumShum/libgdx-tanks
/bin/src/config/sound_storage.rb
UTF-8
451
2.5625
3
[]
no_license
class SoundStorage SOUND_PATH_BASE = { fire: 'res/sounds/fire.wav', damage: 'res/sounds/damage.wav', explosion: 'res/sounds/explosion1.wav', } attr_reader :sound_base def initialize @sound_base = {} SOUND_PATH_BASE.each_pair do |name, path| @sound_base[name] = Gdx.audio.newSound(Gdx.files.internal(RELATIVE_ROOT + path)) end end def get_by_name(sound_name) @sound_base[sound_name.to_sym] end end
true
e0876c35e82f5f6cb841924662bc35f3a818849d
Ruby
alexgh123/ruby_projects
/sorting.rb
UTF-8
395
3.9375
4
[]
no_license
def bubble_sort(array) n = array.length p "hey n = #{n}" loop do swapped = false (n-1).times do |i| p "hey i is changing... it is: #{i}" p "swapped is: #{swapped}" if array[i] > array[i+1] array[i], array[i+1] = array[i+1], array[i] swapped = true end end break if not swapped end array end p bubble_sort([1,99,20,13,4,566,11])
true
5bd2846dce2e47b7098eccbc9c4d7f3ed5dcfef3
Ruby
eltonsantos/ruby-simple-files
/rot13.rb
UTF-8
1,046
3.15625
3
[]
no_license
secret = {" "=>" ", "A"=>"N", "B"=>"O", "C"=>"P", "D"=>"Q", "E"=>"R", "F"=>"S", "G"=>"T", "H"=>"U", "I"=>"V", "J"=>"W", "K"=>"X", "L"=>"Y", "M"=>"Z", "N"=>"A", "O"=>"B", "P"=>"C", "Q"=>"D", "R"=>"E", "S"=>"F", "T"=>"G", "U"=>"H", "V"=>"I", "W"=>"J", "X"=>"K", "Y"=>"L", "Z"=>"M", "a"=>"n", "b"=>"o", "c"=>"p", "d"=>"q", "e"=>"r", "f"=>"s", "g"=>"t", "h"=>"u", "i"=>"v", "j"=>"w", "k"=>"x", "l"=>"y", "m"=>"z", "n"=>"a", "o"=>"b", "p"=>"c", "q"=>"d", "r"=>"e", "s"=>"f", "t"=>"g", "u"=>"h", "v"=>"i", "w"=>"j", "x"=>"k", "y"=>"l", "z"=>"m", "!"=>"!", "?"=>"?"} pergunta = "Por que a galinha atravessou a estrada?" resposta = "Para chegar do outro lado!" pergunta_codificada = String.new pergunta.each_char { |char| pergunta_codificada << secret[char] } resposta_codificada = String.new resposta.each_char { |char| resposta_codificada << secret[char] } puts pergunta puts resposta_codificada puts "\n" puts pergunta_codificada puts resposta puts "\n" puts pergunta_codificada puts resposta_codificada puts "\n" puts pergunta puts resposta
true
108757892c14d44adcf7648aa8117ef40bbfa3b4
Ruby
youssefbenlemlih/ruby-practice
/ptp1/classes/text_editor.rb
UTF-8
1,586
3.90625
4
[]
no_license
# A class used to read text files # Author:: Youssef Benlemlih # Author:: Jonas Krukenberg class TextEditor attr_reader :content # Initialize a new instance of *TextEditor* # with String @content # @param path: The path to the text file def initialize(path) File.open(path) { |f| @content = f.read } end # Returns an array of each word in @param def words_to_array words = @content.split word_list = [] # filter the words list words.each do |word| # replace all upcase characters with downcase ones w = word.downcase # remove all non-letters characters w.gsub!(/\W/, '') # remove all whitespaces w.gsub!(/\s+/, '') # only all non-empty word to the filtered list word_list.push(w) unless w.empty? end @content = word_list nil end # Returns the words list as an array, where each word is inverted def reverse_words reversed_word_list = [] @content.each { |word| reversed_word_list.push(word.reverse) } # return the reversed word list @content = reversed_word_list nil end # Saves the given wordlist in a file in the given path wit one word per line def to_file(filepath) text = @content.join("\n") File.open(filepath, 'w') { |f| f.write text } nil end # Returns a Hash where: # * *key* is the word # * *value* is the occurrence of the usage of the word in the words list def words_occurrences # the default value of the occurrence of a word is 0 word_count = Hash.new(0) @content.each { |word| word_count[word] += 1 } word_count end end
true
6ff71a3aadac96fef685e6c47fb1597b57bd7ab1
Ruby
ranjanisrini/guvi
/compare.rb
UTF-8
79
3.28125
3
[]
no_license
def helo n = gets.chomp y = gets.chomp if (n==y) true else false end end
true
45fd67c15721c85ba3d778629a49bfc48f927462
Ruby
jolohaga/imap_model
/app/models/mail_server.rb
UTF-8
3,918
2.53125
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
require 'core_extensions' module MailServer class IMAP # Mail::IMAP # # Description: # Wrapper around Net::IMAP # require 'net/imap' attr_accessor :settings, :connection, :query, :authenticated, :messages attr_reader :access, :folder, :before, :body, :cc, :from, :on, :since, :subject, :to # Initialize an IMAP object. # # Options: # :address # string, server's address # :username # string, user mail account to connect with # :password # string, user password # :authentication # string, authentication protocol, options {'login', 'cram-md5'} # :enable_ssl # boolean, default false # # Example: # imap = Mail::IMAP.new(:address => '<mailserver>',:username => '<username>',:password => '<password>',:authentication => 'CRAM-MD5') # def initialize(values = {}) self.settings = { :address => 'localhost', :port => 143, :username => nil, :password => nil, :authentication => 'LOGIN', :enable_ssl => false, :folder => nil, :access => nil }.merge!(values) @authenticated = false @query = [] end # Open IMAP session. # # Accepts a hash of options. # Options: # :folder # string, default 'inbox' # :access # string, options: {'read-only', 'read-write'}, default 'read-only' # # Example: # imap.open :folder => 'Sent Messages' do |mailbox| # mailbox.search(['from', 'some user').each do |msg_id| # puts msg_id # end # end # def open(args = {:folder => 'INBOX', :access => 'read-only'}) self.settings.merge!(args) connect if settings[:access] == 'read-write' @connection.select(settings[:folder]) else @connection.examine(settings[:folder]) end yield(self) if block_given? end def connect @connection ||= Net::IMAP.new(settings[:address]) begin @connection.authenticate(settings[:authentication],settings[:username],settings[:password]) unless authenticated @authenticated = true rescue Net::IMAP::NoResponseError "Failed to authenticate" end at_exit { begin disconnect rescue Exception => e "Error closing connection: #{e.class}: #{e.message}." end } end def disconnect @connection.disconnect @connection = nil @authenticated = false end def connected? ! connection.nil? && ! connection.disconnected? end def access(access = 'read-only') @access = access self end def folder(folder = 'INBOX') @folder = folder end def before(date = Date.today) query.push('BEFORE',date.to_imap) self end def body(string) query.push('BODY',string) self end def cc(string) query.push('CC',string) self end def from(string) query.push('FROM',string) self end def update self end def on(date = Date.today) query.push('ON',date.to_imap) self end def since(date = Date.today - 14) query.push('SINCE',date.to_imap) self end def subject(string) query.push('SUBJECT',string) self end def to(string) query.push('TO',string) self end def search(criteria = nil) scratch = criteria.nil? ? query.clone : criteria clear_query connection.search(scratch) end def clear_query @query = [] end def fetch(seq_nos = [],attributes = 'BODY') @messages = connection.fetch(seq_nos,attributes) unless seq_nos.empty? end def uid_fetch(arr = []) end end end
true
7ba612ede0baf65d596ecbaa27293ddb047251d9
Ruby
arvidnilber/standard-biblioteket
/lib/power.rb
UTF-8
134
3.1875
3
[]
no_license
def power(num1,up) i = 0 output = 1 while i < up output *= num1 i += 1 end return output end
true
a1cbb184cdf6a1b80139e28fb575699de359feb1
Ruby
anners/ruby
/reverse-string
UTF-8
360
3.59375
4
[]
no_license
#!/usr/bin/env ruby string = "beer" puts string puts string.reverse array = ["b", "e", "e", "r"] array.reverse.each do |a| print a end yarra = Array.new yarra << array.pop until array.empty? print yarra array = ["b", "e", "e", "r"] def rev(array) x = array.pop rev(array) if array.length > 0 array.unshift x end puts rev(array).inspect
true
9b053de63a29dde735ff362986c2605dc97703aa
Ruby
alexharv074/puppet-strings
/lib/puppet-strings/yard/util.rb
UTF-8
1,265
2.546875
3
[ "Apache-2.0" ]
permissive
require 'puppet/util' # The module for various puppet-strings utility helpers. module PuppetStrings::Yard::Util # Trims indentation from trailing whitespace and removes ruby literal quotation # syntax `%Q{}` and `%{q}` from parsed strings. # @param [String] str The string to scrub. # @return [String] A scrubbed string. def self.scrub_string(str) match = str.match(/^%[Qq]{(.*)}$/m) if match return Puppet::Util::Docs.scrub(match[1]) end Puppet::Util::Docs.scrub(str) end # hacksville, usa # YARD creates ids in the html with with the style of "label-Module+description", where the markdown # we use in the README involves the GitHub-style, which is #module-description. This takes our GitHub-style # links and converts them to reference the YARD-style ids. # @see https://github.com/octokit/octokit.rb/blob/0f13944e8dbb0210d1e266addd3335c6dc9fe36a/yard/default/layout/html/setup.rb#L5-L14 # @param [String] data HTML document to convert # @return [String] HTML document with links converted def self.github_to_yard_links(data) data.scan(/href\=\"\#(.+)\"/).each do |bad_link| data.gsub!("=\"##{bad_link.first}\"", "=\"#label-#{bad_link.first.capitalize.gsub('-', '+')}\"") end data end end
true
f4b9571473abeb92a0888911b7929c6e44c8f417
Ruby
asiandcs/baseballbot_discord
/baseball_discord/commands/links.rb
UTF-8
847
2.515625
3
[ "MIT" ]
permissive
# frozen_string_literal: true module BaseballDiscord module Commands # Basic debug commands that should log to the output file module Links extend Discordrb::Commands::CommandContainer command(:bbref, help_available: false) do |event, *args| LinksCommand.new(event, *args).bbref end command(:fangraphs, help_available: false) do |event, *args| LinksCommand.new(event, *args).fangraphs end # Prints some basic info to the log file class LinksCommand < Command def bbref 'https://www.baseball-reference.com/search/search.fcgi?search=' + CGI.escape(args.join(' ')) end def fangraphs 'https://www.fangraphs.com/players.aspx?new=y&lastname=' + CGI.escape(args.join(' ')) end end end end end
true
a1a97dff36f7bc6a6f21e474242bbc46da973d40
Ruby
kmbhuvanprasad/ruby_set4
/modules/1.rb
UTF-8
211
3.390625
3
[]
no_license
module W4 def z1 puts "I am number 1" end def z3 puts "I am number 3" end def nUMBER_4 puts "I am number 4" end end class Q4 include W4 end number = Q4.new number.z1 number.z3 number.nUMBER_4
true
f7f5a843c92857a0a41cdbf62c91496cfb9c7c10
Ruby
anukin/game_of_life-9_07
/spec/gameoflife/board_spec.rb
UTF-8
686
2.671875
3
[]
no_license
require 'spec_helper' module Gameoflife describe "Cell" do it "should generate the next generation" do board = Board.new(3, 4) curr_gen = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] nex_gen = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] board.set_current_generation(curr_gen) expect(board.next_generation).to eq(nex_gen) end it "should generate the next generation based on current generation" do board = Board.new(3, 3) curr_gen = [[0, 1, 0], [0, 0, 1], [1, 0, 0]] nex_gen = [[0, 1, 0], [0, 1, 1], [1, 0, 0]] board.set_current_generation(curr_gen) expect(board.next_generation).to eq(nex_gen) end end end
true
033355d4596a85c44409c9b1a2c837dda5c3c0b3
Ruby
JRSoftware92/Android-Class-Generator
/AXMLGenerator/src/main/android_sqlite_reader.rb
UTF-8
4,269
3.015625
3
[]
no_license
require_relative 'sqlite_reader.rb' require_relative 'sqlite_model.rb' #Class for reading DDL and DML SQLite files #TODO Rewrite to export generic xml data for template generation and utilize generic regex parser #CAN BE DONE FOR BOTH DDL AND DML class ASqliteReader# < SqliteParser include Sqlite #DDL_REGEX = /[a-zA-Z0-9_]+\({1}(?:[\s\,]*[a-zA-Z]+\s*)+(?:\)\;){1}/ TABLE_REGEX = /(?<name>[a-zA-Z0-9_]+)\({1}(?<parameters>(?:[\s\,]*[a-zA-Z]+\s*)+)(?:\)\;){1}/ def initialize #super @select_queries = [] @insert_queries = [] @update_queries = [] @delete_queries = [] @tables = [] end #Reads in queries def read_ddl_file(filename) File.foreach(filename) do |line| extract_table_from line end end #Reads in queries def read_dml_file(filename) File.foreach(filename) do |line| extract_query_from line end end #Extracts table declarations from the given line and extracts the data as table objects into the local table array def extract_table_from(line) matchdata = line.scan(TABLE_REGEX) matchdata.each do |name, param_str| parameters = extract_table_parameters_from param_str table = Sqlite::Table.new(name, parameters) @tables << table end end #Extracts the table parameters from a given string and outputs them as an array def extract_table_parameters_from(str) if str.nil? || str.size < 1 then return [] end if !str.include? ',' then return str else return str.split ',' end end #Extracts a Sqlite Query object from the sql string def extract_query_from(line) #Remove leading and trailing whitespace temp = line.upcase.strip #Retrieve the index of the name-query delimiter index = temp.index(':') if !index.nil? && index > -1 then #Function name of the query name = line[0,index] #SQLite query statement = line[index + 1, temp.length] #Parametric arguments of the query args = extract_parameters_from statement if statement.include? 'SELECT' then @select_queries << Sqlite::Query.new(name, statement, args, 'SELECT') end if statement.include? 'INSERT' then @insert_queries << Sqlite::Query.new(name, statement, args, 'INSERT') end if statement.include? 'UPDATE' then @update_queries << Sqlite::Query.new(name, statement, args, 'UPDATE') end if statement.include? 'DELETE' then @delete_queries << Sqlite::Query.new(name, statement, args, 'DELETE') end end end def queries return select_queries + insert_queries + update_queries + delete_queries end def select_queries return @select_queries end def select_queries_sql return objects_to_sql @select_queries end def select_queries_xml return objects_to_xml @select_queries end def insert_queries return @insert_queries end def insert_queries_sql return objects_to_sql @insert_queries end def insert_queries_xml return objects_to_xml @insert_queries end def update_queries return @update_queries end def update_queries_sql return objects_to_sql @update_queries end def update_queries_xml return objects_to_xml @update_queries end def delete_queries return @delete_queries end def delete_queries_sql return objects_to_sql @delete_queries end def delete_queries_xml return objects_to_xml @delete_queries end def tables return @tables end def table_statements_sql return objects_to_sql @tables end def table_statements_xml return objects_to_xml @tables end #Converts an array of query objects to an array of sql strings def objects_to_sql(objects) if objects.nil? || objects.size < 1 then return [] end objects.each do |object| output << object.to_sql end return output end #Converts an array of query objects to an array of android xml string resources def objects_to_xml(objects) if objects.nil? || objects.size < 1 then return [] end output = [] objects.each do |object| output << object.to_xml end return output end def print_debug puts 'Tables: ' temp = @tables if !temp.nil? then temp.each do |table| table.print_debug end end puts 'Queries: ' temp = queries if !temp.nil? then temp.each do |query| query.print_debug end end end end
true
a59f73504c05ebe1bf845f2206ff7dab503c3876
Ruby
steve-alex/anagram-detector-london-web-082619
/lib/anagram.rb
UTF-8
361
3.6875
4
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
# Your code goes here! class Anagram @@all=[] attr_accessor def initialize(word) @word = word @@all << self end def self.all @@all end def sort_word(word) word.chars.sort!.to_s end def match(anagram) anagram.each.select{ |word| sort_word(word) == sort_word(@word) } end end
true
326e7c03b5c2b4c9ecdd6aacc7bf20329cc18896
Ruby
xababafr/RubyPFE
/implementation/resl_compiler.rb
UTF-8
2,976
3.015625
3
[ "MIT" ]
permissive
# the compiler takes ruby code as an input, and can : # - add probes # - generate the ast # - simulate the code to infer types # - do all those 3 and create a systemC code require "./resl_data" require "./resl_objects" require "./resl_objectifier" require "./resl_dsl" require "./resl_simulator" require "./visitors/systemc" require "./visitors/prettyprinter" require "./visitors/addprobes" module RubyESL class Compiler def initialize end def get_ast filename, convert = false objectifier = Objectifier.new filename, convert ret = objectifier.methods_objects ret[:sys] = objectifier.sys_ast puts "\n\n" pp ret[[:Sourcer,:source]] ret # .methods_ast would give the original non objectified ast end def add_probes filename add_probes = AddProbes.new filename add_probes.generate_file end def eval_dsl filename rcode=IO.read(filename) eval(rcode) end def deep_copy(o) Marshal.load(Marshal.dump(o)) end def simulate sys sys.ordered_actors.each do |actor| actor_threads = Actor.get_threads[actor.class.get_klass()] actor_threads.each do |thread| fiber = Fiber.new do actor.method(thread).call end DATA.simulator.add_fiber("#{actor.class.get_klass}.#{thread}" , fiber) end end DATA.simulator.run end def get_init_params sys initParams = {} sys.ordered_actors.each do |actor| key = [actor.class.get_klass(), actor.name] initParams[key] = actor.method(:initialize).parameters if actor.initArgs.size > 0 actor.initArgs.each_with_index do |argHash, i| initParams[key][i+1] << argHash end end end initParams end def generate_systemc filename puts "\n\n\n" puts "[STEP 1 : GET INPUT'S CODE AST]".center(80,"=") puts "\n\n\n" ast = get_ast filename s_ast = get_ast filename, true puts "\n\n\n" puts "[STEP 2 :ADD PROBES TO THE CODE]".center(80,"=") puts "\n\n\n" root = Root.new ast, {}, Actor.get_threads() # + it collects the data from DATA root.accept AddProbes.new File.open("P_#{filename}",'w'){|f| f.puts(root.sourceCode)} sys = eval_dsl ( "P_" + filename ) puts "\n\n\n" puts "[STEP 3 : SIMULATE THE CODE TO INFER TYPES]".center(80,"=") puts "\n\n\n" simulate sys puts "\n\n" pp DATA.instance_vars puts "\n\n" pp DATA.local_vars puts "\n\n" initParams = get_init_params sys puts "\n\n\n" puts "[STEP 4 : GENERATE THE SYSTEMC CODE]".center(80,"=") puts "\n\n\n" root = Root.new s_ast, initParams, Actor.get_threads() root.accept SystemC.new end end #Compiler end #MTS if $PROGRAM_NAME == __FILE__ compiler = RubyESL::Compiler.new compiler.generate_systemc "#{ARGV[0]}" end
true
f8f56633de925adf7bf5615ee7191495e5b55e43
Ruby
viing937/codeforces
/src/400B.rb
UTF-8
223
2.953125
3
[ "MIT" ]
permissive
n, m = gets.split.collect{|i| i.to_i} ans = Array.new(n) n.times do |i| s = gets.chomp d = s.index("G") c = s.index("S") if d > c puts -1 exit end ans[i] = c-d end puts ans.uniq.size
true
f6531a107f9053c1e75a359c8917322bf5c90a82
Ruby
somalipirat3/GameTracker
/lib/modules/consume_api/tracker_data_only.rb
UTF-8
1,615
2.640625
3
[]
no_license
# Tracker.gg api # Full profile requests class ConsumeApi::TrackerDataOnly include HTTParty def initialize(options = {}) @data = options @api_key = Rails.application.credentials.api_keys[:tracker_gg][:key] endpoint = Rails.application.credentials.api_keys[:tracker_gg][:endpoint] @endpoint = "#{endpoint}apex/standard/profile/#{@data[:platform]}/#{@data[:username]}" @response = self.class.get(@endpoint, headers: {"TRN-Api-Key": @api_key}) end def player return @response['data']['platformInfo'] end def segments segments = [] @response['data']['segments'].each do |segment| if segment['type'] == "legend" segments << { legendName: legend(segment), stat: stats(segment) } end end return segments end private def stats(stats) new_stats = [] stats['stats'].each do |stat| new_stats.push({ rank: stat[1]['rank'], percentile: stat[1]['percentile'], displayName: stat[1]['displayName'], displayCategory: stat[1]['displayCategory'], category: stat[1]['category'], metadata: stat[1]['metadata'], value: stat[1]['value'], displayValue: stat[1]['displayValue'], displayType: stat[1]['displayType'] }) end return new_stats end def legend (segment) segment['metadata']['name'] end end
true
738af5499acde1463b603abd941ef9d77787dd23
Ruby
omajul85/oystercard
/spec/journey_spec.rb
UTF-8
991
2.65625
3
[]
no_license
require "journey" describe Journey do subject(:journey) { described_class.new } let(:station) { double :station, zone: 1 } it "journey should not be completed" do expect(journey).not_to be_completed end it 'has a penalty fare by default' do expect(subject.fare).to eq described_class::PENALTY_FEE end context "given an entry station" do before do journey.start(station) end it "has an entry station" do expect(journey.entry_station).to eq station end it "returns a penalty fee if no exit station given" do expect(journey.fare).to eq described_class::PENALTY_FEE end context "and an exit station" do let(:exit_station) { double :station, zone: 1 } before do journey.finish(exit_station) end it "calculates a fare" do expect(journey.fare).to eq described_class::MINIMUM_FARE end it "knows if a journey is completed" do expect(journey).to be_completed end end end end
true
f6622987eefcd67dfc0fb13290b667f403aa48ab
Ruby
tetetratra/contest
/leetcode/6_16/3.rb
UTF-8
237
3.328125
3
[]
no_license
# https://leetcode.com/problems/rotate-function/ def max_rotate_function(nums) nums.size.times.map { |n| nums.rotate(n) }.map { |arr| arr.map.with_index { |a, i| a * i }.sum }.max end nums = [4,3,2,6] max_rotate_function(nums)
true
2e23550093914cb6290721de13f2f996a0c514cd
Ruby
milesstanfield/whats-for-lunch
/spec/services/time_formatter_spec.rb
UTF-8
646
2.5625
3
[]
no_license
require 'spec_helper' describe TimeFormatter do describe '.visit_time(time)' do it 'formats time' do expect(TimeFormatter.visit_time(now_time)).to eq '02/09/2016' end end describe '.days_ago(formatted_time)' do it 'returns days since time argument' do control_time = Time.parse('2016-02-11 08:53:34 -0500') expect(TimeFormatter.days_ago('02/05/2016', control_time)).to eq 6 end end describe '.parsed_visit_time(visited_time)' do it 'returns time object from strftime string' do expect(TimeFormatter.parsed_visit_time('02/05/2016').to_s).to eq '2016-02-05 00:00:00 -0500' end end end
true
713714e42caa50fe0c0d22b1e6661582214e88a1
Ruby
Bielfla27/gerenciamento-servicos
/test/models/usuario_test.rb
UTF-8
1,502
2.625
3
[]
no_license
require "test_helper" class UsuarioTest < ActiveSupport::TestCase test "deve salvar Usuario criado corretamente" do usuario = Usuario.new nome: 'Usuario Teste', cpf: '39775387485', funcao: 'Confeiteiro', password: 'password1' assert usuario.save end test "nao deve salvar Usuario com password menor que 8 caracteres" do usuario = Usuario.new nome: 'Usuario Teste', cpf: '39775387485', funcao: 'Confeiteiro', password: 'passw' assert_not usuario.save end test "nao deve salvar Usuario criado com cpf com letras" do usuario = Usuario.new nome: 'Usuario Teste', cpf: 'sda397753aa', funcao: 'Confeiteiro', password: 'password01' assert_not usuario.save end #terceira iteração--------------------------------------------- test "nao deve salvar Usuario criado com cpf invalido" do usuario = Usuario.new nome: 'Usuario Teste', cpf: '00000000000', funcao: 'Confeiteiro', password: 'password01' assert_not usuario.save end test "nao deve salvar Usuario sem funcao" do usuario = Usuario.new nome: 'Usuario Teste', cpf: '39775387485', funcao: '', password: 'password01' assert_not usuario.save end test "nao deve salvar Usuario com nome maior que 35 caracteres" do usuario = Usuario.new nome: 'Maria Raphaela Gonzaga da Rocha e Silva', cpf: '39775387485', funcao: 'Vendedora', password: 'password01' assert_not usuario.save end end
true
70fdac1013f6b45b05ed53415f50f4c25c9f56b5
Ruby
schazbot/oo-relationships-practice-london-web-career-021819
/app/models/user.rb
UTF-8
1,420
3
3
[]
no_license
class User attr_reader :name @@all = [] def self.all @@all end def initialize(name) @name = name @@all << self end def make_pledge(project, amount) Pledge.new(self, project, amount) end def make_project(project_name, goal_amount) Project.new(project_name, self, goal_amount) end def pledges Pledge.all.select {|pledge| pledge.user == self} end def pledges_count pledges.count end def projects_made Pledge.all.select {|pledge| pledge.project.created_by == self} end def projects_made_count Pledge.all.select {|pledge| pledge.project.created_by == self}.count end def self.all_pledge_amounts_sort highest = Pledge.all.map {|pledge| pledge.amount}.sort! highest.last end def self.highest_pledge Pledge.all.find {|pledge| pledge.amount == all_pledge_amounts_sort}.user.name end def self.pledger_names Pledge.all.map {|pledge| pledge.user.name} end def self.multi_pledger # returns all users who have pledged to multiple projects @@all.select {|user_instance| user_instance.pledges_count > 1} end def self.project_creator @@all.select{|user_instance| user_instance.projects_made_count > 0} #returns all users who have created a project end end
true
0173a501f107144afd808149940aa2f7d2d113f8
Ruby
bethanyr/RubyFall2013
/week4/exercises/timer_spec.rb
UTF-8
663
2.96875
3
[ "Apache-2.0" ]
permissive
require './code_timer.rb' describe CodeTimer do it "should run our code" do flag = false CodeTimer.time_code do flag = true end flag.should eq true end it "should time our code" do Time.stub(:now).and_return(0,3) run_time = CodeTimer.time_code do end run_time.should be_within(0.1).of(3.0) end it "should run our code multiple times " do i = 0 CodeTimer.time_code(10){ i+=1 } i.should eq 10 end it "should give us the average time" do Time.stub(:now).and_return(0,10) run_time = CodeTimer.time_code(10) { } run_time.should be_within(0.1).of(1.0) end end
true
2854882d1c23783acb0566f985cf0822107445ae
Ruby
marshallshen/bootcamp
/ruby/closest_palindrome.rb
UTF-8
2,453
3.6875
4
[]
no_license
# @param {String} n # @return {String} # https://leetcode.com/problems/find-the-closest-palindrome/description/ def nearest_palindromic(n) nums = n.split("") if nums.size == 1 return (n.to_i - 1).to_s end cand1 = palindrom_by_mirror(nums) cand2 = palindrom_by_increment(nums) cand3 = palindrom_by_decrement(nums) cand4 = palindrom_for_palindrom_decrement(nums) cand5 = palindrom_for_palindrom_increment(nums) puts "cands: #{[cand1, cand2, cand3, cand4, cand5]}, n: #{n}" cands = [cand1, cand2, cand3, cand4, cand5].compact.group_by{|c| (c.to_i - n.to_i).abs }.min.last cands.map(&:to_i).min.to_s end def palindrom_for_palindrom_decrement(nums) first_half, second_half = nums.each_slice((nums.size / 2.0).round).to_a first_half = (first_half.join("").to_i - 1).to_s.split("") second_half = first_half[0, second_half.size].reverse return (first_half + second_half).join("") end def palindrom_for_palindrom_increment(nums) first_half, second_half = nums.each_slice((nums.size / 2.0).round).to_a first_half = (first_half.join("").to_i + 1).to_s.split("") second_half = first_half[0, second_half.size].reverse return (first_half + second_half).join("") end def palindrom_by_mirror(nums) local_nums = nums.clone iter, mid = 0, local_nums.size / 2 while(iter < mid) local_nums[local_nums.size - 1 - iter] = local_nums[iter] iter += 1 end return nil if local_nums == nums return local_nums.join("") end def palindrom_by_increment(nums) local_nums = nums.clone mid = local_nums.size / 2 if local_nums[mid].to_i == 9 first_half, second_half = nums.each_slice((nums.size / 2.0).round).to_a first_half = (first_half.join("").to_i + 1).to_s.split("") second_half = first_half[0, second_half.size].reverse local_nums = first_half + second_half return local_nums.join("") end return nil end def palindrom_by_decrement(nums) local_nums = nums.clone mid = local_nums.size / 2 first_half, second_half = nums.each_slice((nums.size / 2.0).round).to_a return "9" if first_half == ["1"] if local_nums[mid].to_i == 0 first_half = (first_half.join("").to_i - 1).to_s.split("") second_half = first_half[0, second_half.size].reverse if nums.size % 2 == 0 local_nums = first_half + ["9"] + second_half else local_nums = first_half + second_half end return local_nums.join("") end return nil end
true
3fa56c9a5165d35b68462214dab0800008978225
Ruby
moqingxinai/pujara-emnlp17
/scripts/data-processing/psl/prep.rb
UTF-8
12,278
2.75
3
[]
no_license
# Create the files that PSL will use. # Processing: # - Copy over the id mapping files (not necessary, but convenient). # - Convert all ids in triple files from string identifiers to int identifiers. # - List out all the possible targets (test triples and their corruptions). # - Compute and output all the energy of all triples (targets). # # To save space (since there are typically > 400M targets), we will only write out energies # that are less than some threshold. # To signify an energy value that should not be included, the respective tripleEnergy() methods # will return first return a value of false and then the actual energy value. # We still return the actual energy so we can log it for later statistics. # # We make no strides to be overly efficient here, just keeping it simple. # We will check to see if a file exists before creating it and skip that step. # If you want a full re-run, just delete the offending directory. require_relative '../../lib/constants' require_relative '../../lib/embedding/energies' require_relative '../../lib/embedding/load' require_relative '../../lib/load' require 'etc' require 'fileutils' require 'set' # gem install thread require 'thread/channel' require 'thread/pool' NUM_THREADS = Etc.nprocessors - 1 SKIP_BAD_ENERGY = false MIN_WORK_PER_THREAD = 50 WORK_DONE_MSG = '__DONE__' TARGETS_FILE = 'targets.txt' ENERGY_FILE = 'energies.txt' ENERGY_STATS_FILE = 'energyStats.txt' def copyMappings(datasetDir, outDir) if (!File.exists?(File.join(outDir, Constants::RAW_ENTITY_MAPPING_FILENAME))) FileUtils.cp(File.join(datasetDir, Constants::RAW_ENTITY_MAPPING_FILENAME), File.join(outDir, Constants::RAW_ENTITY_MAPPING_FILENAME)) end if (!File.exists?(File.join(outDir, Constants::RAW_RELATION_MAPPING_FILENAME))) FileUtils.cp(File.join(datasetDir, Constants::RAW_RELATION_MAPPING_FILENAME), File.join(outDir, Constants::RAW_RELATION_MAPPING_FILENAME)) end end def loadIdTriples(path) triples = [] File.open(path, 'r'){|file| file.each{|line| triples << line.split("\t").map{|part| part.strip().to_i()} } } return triples end def convertIdFile(inPath, outPath, entityMapping, relationMapping) if (File.exists?(outPath)) return end triples = [] File.open(inPath, 'r'){|file| file.each{|line| parts = line.split("\t").map{|part| part.strip()} parts[Constants::HEAD] = entityMapping[parts[Constants::HEAD]] parts[Constants::RELATION] = relationMapping[parts[Constants::RELATION]] parts[Constants::TAIL] = entityMapping[parts[Constants::TAIL]] triples << parts } } File.open(outPath, 'w'){|file| file.puts(triples.map{|triple| triple.join("\t")}.join("\n")) } end def convertIds(datasetDir, outDir, entityMapping, relationMapping) convertIdFile(File.join(datasetDir, Constants::RAW_TEST_FILENAME), File.join(outDir, Constants::RAW_TEST_FILENAME), entityMapping, relationMapping) convertIdFile(File.join(datasetDir, Constants::RAW_TRAIN_FILENAME), File.join(outDir, Constants::RAW_TRAIN_FILENAME), entityMapping, relationMapping) convertIdFile(File.join(datasetDir, Constants::RAW_VALID_FILENAME), File.join(outDir, Constants::RAW_VALID_FILENAME), entityMapping, relationMapping) end # Generate each target and compute the energy for each target. # We do target generation and energy computation in the same step so we do not urite # targets that have too high energy. def computeTargetEnergies(datasetDir, embeddingDir, outDir, energyMethod, maxEnergy, entityMapping, relationMapping) if (File.exists?(File.join(outDir, ENERGY_FILE))) return end targetsOutFile = File.open(File.join(outDir, TARGETS_FILE), 'w') energyOutFile = File.open(File.join(outDir, ENERGY_FILE), 'w') entityEmbeddings, relationEmbeddings = LoadEmbedding.vectors(embeddingDir) targets = loadIdTriples(File.join(outDir, Constants::RAW_TEST_FILENAME)) # The number of corruptions written to disk. # We need to keep track so we can assign surrogate keys. targetsWritten = 0 # All the corruptions we have seen for a specific relation. # This is to avoid recomputation. # This will hold the cantor pairing of the head and tail. seenCorruptions = Set.new() # To reduce memory consumption, we will only look at one relation at a time. relations = targets.map{|target| target[Constants::RELATION]}.uniq() # The entities (and relations) have already been assigned surrogate keys that start at 0 and have # no holes. # So, instead of looking at actual entities, we can just start and zero and count up. numEntities = entityMapping.size() # [[id, energy], ...] energies = [] corruptions = [] # We will keep track of all the calculated energies so that we can analyze it later. # {energy.round(2) => count, ...} energyHistogram = Hash.new{|hash, key| hash[key] = 0} relations.each_index{|relationIndex| relation = relations[relationIndex] seenCorruptions.clear() seenCorruptions = Set.new() GC.start() # Only triples that are using the current relation. validTargets = targets.select(){|target| target[Constants::RELATION] == relation} validTargets.each{|target| # These are already cleared, but I want to make it explicit that we # are batching every valid target. energies.clear() corruptions.clear() # Corrupt the head and tail for each triple. [Constants::HEAD, Constants::TAIL].each{|corruptionTarget| for i in 0...numEntities if (corruptionTarget == Constants::HEAD) head = i tail = target[Constants::TAIL] else head = target[Constants::HEAD] tail = i end id = MathUtils.cantorPairing(head, tail) if (seenCorruptions.include?(id)) next end seenCorruptions << id corruption = Array.new(3, 0) corruption[Constants::HEAD] = head corruption[Constants::TAIL] = tail corruption[Constants::RELATION] = relation corruptions << corruption end } energies = Energies.computeEnergies( corruptions, nil, nil, entityEmbeddings, relationEmbeddings, energyMethod, false, true ) corruptions.clear() # Log all the energies in the histogram. energies.values().each{|energy| energyHistogram[energy.round(2)] += 1 } # Remove all energies over the threshold. energies.delete_if{|id, energy| energy > maxEnergy } # Right now the energies are in a map with string key, turn into a list with a surrogate key. # [[index, [head, tail, relation], energy], ...] # No need to convert the keys to ints now, since we will just write them out. energies = energies.to_a().each_with_index().map{|mapEntry, index| head, tail = mapEntry[0].split(':') [index + targetsWritten, [head, tail, relation], mapEntry[1]] } targetsWritten += energies.size() if (energies.size() > 0) targetsOutFile.puts(energies.map{|energy| "#{energy[0]}\t#{energy[1].join("\t")}"}.join("\n")) energyOutFile.puts(energies.map{|energy| "#{energy[0]}\t#{energy[2]}"}.join("\n")) end energies.clear() } } energyOutFile.close() targetsOutFile.close() writeEnergyStats(energyHistogram, outDir) end def writeEnergyStats(energyHistogram, outDir) tripleCount = energyHistogram.values().reduce(0, :+) mean = energyHistogram.each_pair().map{|energy, count| energy * count}.reduce(0, :+) / tripleCount.to_f() variance = energyHistogram.each_pair().map{|energy, count| count * ((energy - mean) ** 2)}.reduce(0, :+) / tripleCount.to_f() stdDev = Math.sqrt(variance) min = energyHistogram.keys().min() max = energyHistogram.keys().max() range = max - min # Keep track of the counts in each quartile. quartileCounts = [0, 0, 0, 0] energyHistogram.each_pair().each{|energy, count| # The small subtraction is to offset the max. quartile = (((energy - min - 0.0000001).to_f() / range) * 100).to_i() / 25 quartileCounts[quartile] += count } # Calculate the median. # HACK(eriq): This is slighty off if there is an even number of triples and the # two median values are on a break, but it is not worth the extra effort. median = -1 totalCount = 0 energyHistogram.each_pair().sort().each{|energy, count| totalCount += count if (totalCount >= (tripleCount / 2)) median = energy break end } File.open(File.join(outDir, ENERGY_STATS_FILE), 'w'){|file| file.puts "Num Triples: #{energyHistogram.size()}" file.puts "Num Unique Energies: #{tripleCount}" file.puts "Min Energy: #{energyHistogram.keys().min()}" file.puts "Max Energy: #{energyHistogram.keys().max()}" file.puts "Quartile Counts: #{quartileCounts}" file.puts "Quartile Percentages: #{quartileCounts.map{|count| (count / tripleCount.to_f()).round(2)}}" file.puts "Mean Energy: #{mean}" file.puts "Median Energy: #{median}" file.puts "Energy Variance: #{variance}" file.puts "Energy StdDev: #{stdDev}" file.puts "---" file.puts energyHistogram.each_pair().sort().map{|pair| pair.join("\t")}.join("\n") } end def parseArgs(args) embeddingDir = nil outDir = nil datasetDir = nil embeddingMethod = nil distanceType = nil if (args.size() < 1 || args.size() > 5 || args.map{|arg| arg.downcase().gsub('-', '')}.include?('help')) puts "USAGE: ruby #{$0} embedding dir [output dir [dataset dir [embedding method [distance type]]]]" puts "Defaults:" puts " output dir = inferred" puts " dataset dir = inferred" puts " embedding method = inferred" puts " distance type = inferred" puts "" puts "All the inferred aguments relies on the emebedding directory" puts "being formatted by the scripts/embeddings/computeEmbeddings.rb script." puts "The directory that the inferred output directory will be put in is: #{Constants::PSL_DATA_PATH}." exit(2) end if (args.size() > 0) embeddingDir = args[0] end if (args.size() > 1) outDir = args[1] else outDir = File.join(Constants::PSL_DATA_PATH, File.basename(embeddingDir)) end if (args.size() > 2) datasetDir = args[2] else dataset = File.basename(embeddingDir).match(/^[^_]+_(\S+)_\[size:/)[1] datasetDir = File.join(Constants::RAW_DATA_PATH, File.join(dataset)) end if (args.size() > 3) embeddingMethod = args[3] else embeddingMethod = File.basename(embeddingDir).match(/^([^_]+)_/)[1] end if (args.size() > 4) distanceType = args[4] else # TODO(eriq): This may be a little off for TransR. if (embeddingDir.include?("distance:#{Distance::L1_ID_INT}")) distanceType = Distance::L1_ID_STRING elsif (embeddingDir.include?("distance:#{Distance::L2_ID_INT}")) distanceType = Distance::L2_ID_STRING end end energyMethod = Energies.getEnergyMethod(embeddingMethod, distanceType, embeddingDir) maxEnergy = Energies.getMaxEnergy(embeddingMethod, distanceType, embeddingDir) return datasetDir, embeddingDir, outDir, energyMethod, maxEnergy end def prepForPSL(args) datasetDir, embeddingDir, outDir, energyMethod, maxEnergy = parseArgs(args) FileUtils.mkdir_p(outDir) entityMapping = Load.idMapping(File.join(datasetDir, Constants::RAW_ENTITY_MAPPING_FILENAME)) relationMapping = Load.idMapping(File.join(datasetDir, Constants::RAW_RELATION_MAPPING_FILENAME)) copyMappings(datasetDir, outDir) convertIds(datasetDir, outDir, entityMapping, relationMapping) computeTargetEnergies(datasetDir, embeddingDir, outDir, energyMethod, maxEnergy, entityMapping, relationMapping) end if (__FILE__ == $0) prepForPSL(ARGV) end
true
1b8ef115b9d9f9894628ddf6d8c4866acfaf962c
Ruby
mcruger/HW2office_directory
/s3uploadfile.rb
UTF-8
823
2.703125
3
[]
no_license
require File.expand_path(File.dirname(__FILE__) + '/proj_config') (bucket_name, file_name) = ARGV unless bucket_name puts "Usage: s3uploadfile.rb <BUCKET_NAME> <FILE_NAME>" exit 1 end # get an instance of the S3 interface using the default configuration s3 = AWS::S3.new #init bucket object bucket = s3.buckets[bucket_name] #check if file exists if !File.exist?(file_name) puts "File '#{file_name}' does not exist. Please correct file path." else if bucket.exists? # upload a file basename = File.basename(file_name) o = bucket.objects[basename] o.write(:file => file_name) puts "Uploaded #{file_name} to:" puts o.public_url #generate a presigned URL puts "\nURL to download the file:" puts o.url_for(:read) else puts "Bucket '#{bucket_name}' does not exist. Cannot upload file." end end
true
72866b79a4b4a3748c2eacc5960250b17af636e7
Ruby
matt5342/Leetcode
/find-all-numbers-disappeared-in-an-array/find-all-numbers-disappeared-in-an-array.rb
UTF-8
242
3.171875
3
[]
no_license
# @param {Integer[]} nums # @return {Integer[]} def find_disappeared_numbers(nums) obj = nums.to_h{|c| [c,0]} result = [] i = 1 nums.length.times do result.push(i) if !obj[i] i += 1 end result end
true
8eab21a69b5bba49a4119a1f166d04ee77a40ef8
Ruby
mesh1nek0x0/resolve-yukicoder
/no296/snooze.rb
UTF-8
210
3.046875
3
[]
no_license
#!/bin/ruby input = gets.chomp.split(' ') N = input[0].to_i H = input[1].to_i M = input[2].to_i T = input[3].to_i add_minutes = T * (N - 1) tmp = M + add_minutes + (H * 60) puts tmp / 60 % 24 puts tmp % 60
true
27b96c25fe9cc8806ed47ae8464bc1e60effa58d
Ruby
hanami/view
/spec/integration/helpers_spec.rb
UTF-8
1,543
2.640625
3
[ "MIT" ]
permissive
# frozen_string_literal: true RSpec.describe "helpers" do let(:dir) { make_tmp_directory } describe "in templates" do before do with_directory(dir) do write "template.html.erb", <<~ERB <%= format_number(number) %> ERB end end let(:view) { dir = self.dir scope_class = self.scope_class Class.new(Hanami::View) do config.paths = dir config.template = "template" config.scope_class = scope_class expose :number end.new } let(:scope_class) { Class.new(Hanami::View::Scope) { include Hanami::View::Helpers::NumberFormattingHelper } } specify do expect(view.(number: 12_300).to_s.strip).to eq "12,300" end end describe "in parts" do before do with_directory(dir) do write "template.html.erb", <<~ERB <%= city.population_text %> ERB end end let(:part_class) { Class.new(Hanami::View::Part) { include Hanami::View::Helpers::NumberFormattingHelper def population_text format_number(population) end } } let(:view) { dir = self.dir part_class = self.part_class Class.new(Hanami::View) { config.paths = dir config.template = "template" expose :city, as: part_class }.new } specify do canberra = Struct.new(:population).new(463_000) expect(view.(city: canberra).to_s.strip).to eq "463,000" end end end
true
237d01e22dc69e0e5524e10205aaeefd341595fc
Ruby
MrRogerino/dbc-whiteboarding
/August_9/example_solutions/two_sum.rb
UTF-8
602
3.421875
3
[ "MIT" ]
permissive
def two_sum(array, target) #returns true or false map = {} i = 0 while i < array.length difference = target - array[i] if map[difference] return true end map[array[i]] = 1 i += 1 end return false end def two_sum_positions(array, target) #returns the position of the two numbers map = {} found = false i = 0 while i < array.length difference = target - array[i] if map[difference] position1 = array.find_index(difference) position2 = i return [position1, position2] end map[array[i]] = 1 i += 1 end return false end
true
2cf0ee197dbe7397b073e444bab51ca96641a5cd
Ruby
svallero/vaf-storage
/bin/af-create-deps.rb
UTF-8
3,669
2.9375
3
[]
no_license
#!/usr/bin/ruby # # af-create-deps.rb -- by Dario Berzano <[email protected]> # # Creates the dependency file for AliRoot versions. The following environment # variables are needed: # # AF_DEP_URL => HTTP URL containing the list of AliEn packages for ALICE # AF_DEP_FILE => destination file on the local filesystem # AF_PACK_DIR => local AliEn Packman repository # require 'net/http' require 'pp' require 'optparse' def get_ali_packages(url, pack_dir) if (url.kind_of?(URI::HTTP) === false) raise URI::InvalidURIError.new('Invalid URL: only http URLs are supported') end packages = [] Net::HTTP.start(url.host, url.port) do |http| http.request_get(url.request_uri) do |resp| # Generic HTTP error if (resp.code.to_i != 200) raise Exception.new("Invalid HTTP response: #{resp.code}") return false end resp.body.split("\n").each do |line| # 0=>pkg.tar.gz, 1=>type, 2=>rev, 3=>platf, 4=>name, 5=>deps ary = line.split(" ") # Consider only AliRoot packages next unless (ary[1] == 'AliRoot') # Get the VO name (like VO_ALICE, for instance) vo_name = ary[4].split('@').first # Check integrity of line format deps = ary[5].split(',') dep_root = nil dep_geant3 = nil deps.each do |d| if (d.include?('@ROOT::')) dep_root = d elsif (d.include?('@GEANT3')) dep_geant3 = d end end next unless (dep_root && dep_geant3) # Check if package is installed for real if (pack_dir && !File.exists?("#{pack_dir}/#{vo_name}/AliRoot/#{ary[2]}/#{ary[2]}")) next end # Push package hash packages << { :aliroot => ary[4], :root => dep_root, :geant3 => dep_geant3, } end # |line| end # |resp| end # |http| return packages end def main # Check if envvars are set begin dep_url = URI(ENV['AF_DEP_URL']) rescue URI::InvalidURIError => e warn 'Environment variable AF_DEP_URL should be set to a valid URL' exit 3 end if ((dep_file = ENV['AF_DEP_FILE']) == nil) warn 'Environment variable AF_DEP_FILE should be set to a local filename' exit 3 end if ((pack_dir = ENV['AF_PACK_DIR']) == nil) warn 'Environment variable AF_PACK_DIR should be set to a local directory' exit 3 end # Options opts = { :checkexists => true, } # Define and parse options OptionParser.new do |op| op.on('-h', '--help', 'shows usage') do puts op exit 4 end op.on('-c', '--[no-]check-exists', "include only installed packages (default: #{opts[:checkexists]})") do |v| opts[:checkexists] = v end # Custom banner prog = File.basename($0) op.banner = "#{prog} -- by Dario Berzano <[email protected]>\n" + "Creates a dependency file for AliRoot packages\n\n" + "Usage: #{prog} [options]" begin op.parse! rescue OptionParser::ParseError => e warn "#{prog}: arguments error: #{e.message}" exit 5 end end begin packages = get_ali_packages(dep_url, opts[:checkexists] ? pack_dir : nil) begin File.open(dep_file, 'w') do |f| packages.each do |pack| f << pack[:aliroot] << '|' << pack[:root] << '|' << pack[:geant3] << "\n" end end rescue Exception => e warn "Can not write #{dep_file}: #{e.message}" exit 2 end rescue Exception => e warn "Error fetching dependencies: #{e.message}" exit 1 end warn "#{dep_file} written" exit 0 end # # Entry point # main
true
73fec8add9f7fc3b3f90d635deeab38f8f8ce2fb
Ruby
plapicola/enigma
/test/key_test.rb
UTF-8
954
2.859375
3
[]
no_license
require_relative 'test_helper' class KeyTest < Minitest::Test def setup @key = Key.new("02715") end def test_it_exists # skip assert_instance_of Key, @key end def test_it_can_return_the_key_as_a_string # skip assert_equal "02715", @key.key end def test_it_can_generate_a_random_key # skip random_key = Key.random assert_instance_of Key, random_key assert_equal 5, random_key.key.length end def test_it_can_return_the_next_sequential_key # skip assert_equal "02716", @key.next_key assert_equal "02717", @key.next_key end def test_it_can_return_the_array_of_keys # skip assert_equal [2, 27, 71, 15], @key.parse_keys end def test_it_can_generate_date_offsets # skip assert_equal [1, 0, 2, 5], @key.generate_offsets("040895") end def test_it_can_return_shifts_if_given_a_date # skip assert_equal [3, 27, 73, 20], @key.shifts("040895") end end
true
c84950ef5553d61ae6abaac695b46429810d6e38
Ruby
pshussain/Backup
/unlock.rb
UTF-8
541
2.640625
3
[]
no_license
require 'time' for i in 0..100 do puts i.to_s start_time=Time.now (file = File.new('shared_file','r')).flock(File::LOCK_EX) end_time=Time.now diff=end_time-start_time puts diff lines = file.readlines #if(lines[0]!="line1\\n") puts lines if lines != nil and lines != "" and !lines.empty? puts lines.inspect for i in 0..10 puts "Read Mode :: Data is #{lines[0]}" end end sleep(ARGV[0].to_i) #exit #end file.flock(File::LOCK_UN) file.close end
true
236c175cc2d7245974204337cb1a9c0ae341dd2f
Ruby
amosjyng/UAS-Website
/app/models/event.rb
UTF-8
1,944
2.890625
3
[]
no_license
class Event < ActiveRecord::Base attr_accessible :content, :time, :title, :date, :day_time validates :title, :date, :day_time, :content, :presence => true validates :content, :length => {:minimum => 5} validate :date_valid validate :time_valid def date if time.nil? return Time.now.strftime('%m/%d/%Y') else time.strftime('%m/%d/%Y') end end def date=(day) begin current_time = Time.now.to_datetime unless time.nil? current_time = time end d = Date.strptime(day, '%m/%d/%Y') self.time = DateTime.new(d.year, d.month, d.day, current_time.hour, current_time.min, current_time.sec, current_time.zone).strftime '%Y-%m-%d %H:%M' @date_success = true rescue @date_success = false end end def day_time if time.nil? return Time.now.beginning_of_hour.strftime('%I:%M %p') else return time.strftime('%I:%M %p') end end def day_time=(dt) begin current_time = Time.now.to_datetime unless time.nil? current_time = time end t = DateTime.strptime(current_time.strftime('%Y %m %d ') + dt, '%Y %m %d %I:%M %p') self.time = DateTime.new(current_time.year, current_time.month, current_time.day, t.hour, t.min, 0, current_time.zone).strftime '%Y-%m-%d %H:%M' @time_success = true rescue @time_success = false end end def summary max_length = 300 if content.length > max_length return content[0..max_length] + '...' else return content end end def human_time time.strftime('%A, %B %e at %l:%M %p') end private def date_valid errors.add(:date, 'format not valid!') unless @date_success end def time_valid errors.add(:day_time, 'format not valid!') unless @time_success end end
true
3b15db27fd5fd3aca4620217f2e5c04372312895
Ruby
alejandro-medici/retrospectiva
/extensions/retro_wiki/ext/project.rb
UTF-8
1,241
2.53125
3
[ "MIT" ]
permissive
Project.class_eval do has_many :wiki_pages, :dependent => :destroy do def find_or_build(title) record = find_by_title(title) unless record record = build record.title = title end record end end has_many :wiki_files, :dependent => :destroy do def find_readable(title) file = find_by_wiki_title(title) file and file.readable? ? file : nil end def find_readable_image(title) file = find_readable(title) file and file.image? ? file : nil end end serialize :existing_wiki_page_titles, Array before_update :update_main_wiki_page_title def wiki_title(name = self.name) name.gsub(/[\.\?\/;,]/, '-').gsub(/-{2,}/, '-') end def existing_wiki_page_titles value = read_attribute(:existing_wiki_page_titles) value.is_a?(Array) ? value : [] end def reset_existing_wiki_page_titles! update_attribute :existing_wiki_page_titles, wiki_pages.map(&:title) end protected def update_main_wiki_page_title if name_changed? page = wiki_pages.find_by_title(wiki_title(name_was)) page.update_attribute(:title, wiki_title) if page end true end end
true
f5347127a5641b42dc75136a45e2bb514ab9fbb0
Ruby
siwS/theysaidsocli
/lib/quote_terminal_printer.rb
UTF-8
542
3.203125
3
[ "MIT" ]
permissive
require 'hirb' class QuoteTerminalPrinter def initialize(quote) @quote = quote @print_text = "#{@quote.author} said: \"#{@quote.quote}\"" @width = @print_text.size end def print puts print_separator print_quote print_separator puts end private def print_quote puts "~ #{@print_text} ~" end def print_separator puts "*" * separator_width end def separator_width [@width + 4, terminal_width].min end def terminal_width Hirb::Util.detect_terminal_size[0] end end
true
9cc6e2334547b5b9d1323c688d7b94efc9045855
Ruby
seanwbrooks/blackjack
/spec/lib/hand_spec.rb
UTF-8
1,204
3.15625
3
[]
no_license
require "spec_helper" RSpec.describe Hand do let(:hand) { Hand.new } let(:card) { Card.new("♦", "2") } let(:ace) { Card.new("A", "♦") } let(:four_ace) { [Card.new("A", "♦"), Card.new("A", "♥"), Card.new("A","♦"), Card.new("A","♥")] } describe '#initialize' do it 'should take no arguments and create an instance of Hand' do expect(hand).to be_a(Hand) end it 'is an empty array of cards' do expect(hand.hand_of_cards).to eq([]) end end describe '#add_card' do it 'should add another card to hand' do hand.add_card(card) expect(hand.hand_of_cards).to include(card) end end describe "#calculate_hand" do context "with some cards" do it "should add these cards" do expect(hand.calculate).to eq(0) end end context "with two aces" do it "should return a score of 12" do hand.add_card(ace) hand.add_card(ace) expect(hand.calculate).to eq(12) end end context "with four aces" do it "should return a score of 14" do 4.times do hand.add_card(ace) end expect(hand.calculate).to eq(14) end end end end
true
5f8dee8f9cc482fd533ba7dbf88ab20648f2b355
Ruby
popkorn96/ruby-music-library-cli-onl01-seng-ft-072720
/lib/artist.rb
UTF-8
588
2.953125
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class Artist extend Concerns::Findable attr_accessor :name, :songs @@all = [] def initialize(name) @name = name @songs = [] @@all << self end def name @name end def self.all @@all end def self.destroy_all @@all.clear end def save @@all << self end def self.create(name) new_artist = self.new(name) new_artist.save new_artist end def songs @songs end def add_song(song) song.artist = self unless song.artist songs << song unless songs.include?(song) end def genres songs.map{|song| song.genre}.uniq end end
true
af9a8a9417a8cbff7f48db3a093a3827283d16a7
Ruby
achiurizo/boson
/lib/boson/inspector.rb
UTF-8
3,687
2.703125
3
[ "MIT" ]
permissive
module Boson # Scrapes and processes method attributes with the inspectors (MethodInspector, CommentInspector # and ArgumentInspector) and hands off the data to FileLibrary objects. # # === Method Attributes # Method attributes refer to (commented) Module methods placed before a command's method # in a FileLibrary module: # module SomeMod # # @render_options :fields=>%w{one two} # # @config :alias=>'so' # options :verbose=>:boolean # # Something descriptive perhaps # def some_method(opts) # # ... # end # end # # Method attributes serve as configuration for a method's command. Available method attributes: # * config: Hash to define any command attributes (see Command.new). # * desc: String to define a command's description for a command. Defaults to first commented line above a method. # * options: Hash to define an OptionParser object for a command's options. # * render_options: Hash to define an OptionParser object for a command's local/global render options (see View). # # When deciding whether to use commented or normal Module methods, remember that commented Module methods allow # independence from Boson (useful for testing). See CommentInspector for more about commented method attributes. module Inspector extend self attr_reader :enabled # Enable scraping by overridding method_added to snoop on a library while it's # loading its methods. def enable @enabled = true body = MethodInspector::METHODS.map {|e| %[def #{e}(val) Boson::MethodInspector.#{e}(self, val) end] }.join("\n") + %[ def new_method_added(method) Boson::MethodInspector.new_method_added(self, method) end alias_method :_old_method_added, :method_added alias_method :method_added, :new_method_added ] ::Module.module_eval body end # Disable scraping method data. def disable ::Module.module_eval %[ Boson::MethodInspector::METHODS.each {|e| remove_method e } alias_method :method_added, :_old_method_added ] @enabled = false end # Adds method attributes scraped for the library's module to the library's commands. def add_method_data_to_library(library) @commands_hash = library.commands_hash @library_file = library.library_file MethodInspector.current_module = library.module @store = MethodInspector.store add_method_scraped_data add_comment_scraped_data end #:stopdoc: def add_method_scraped_data (MethodInspector::METHODS + [:args]).each do |key| (@store[key] || []).each do |cmd, val| @commands_hash[cmd] ||= {} add_scraped_data_to_config(key, val, cmd) end end end def add_scraped_data_to_config(key, value, cmd) if value.is_a?(Hash) if key == :config @commands_hash[cmd] = Util.recursive_hash_merge value, @commands_hash[cmd] else @commands_hash[cmd][key] = Util.recursive_hash_merge value, @commands_hash[cmd][key] || {} end else @commands_hash[cmd][key] ||= value end end def add_comment_scraped_data (@store[:method_locations] || []).select {|k,(f,l)| f == @library_file }.each do |cmd, (file, lineno)| scraped = CommentInspector.scrape(FileLibrary.read_library_file(file), lineno, MethodInspector.current_module) @commands_hash[cmd] ||= {} MethodInspector::METHODS.each do |e| add_scraped_data_to_config(e, scraped[e], cmd) end end end #:startdoc: end end
true
571521803896c418306191cafeeeb3f89307ace3
Ruby
MuhammadTamzid/framgia_crb_v2
/app/validators/name_validator.rb
UTF-8
608
2.953125
3
[]
no_license
class NameValidator < ActiveModel::Validator def validate record # name may only contain alphanumeric characters or single hyphens, and cannot begin or end with a hyphen if !(record.name =~ /^(?!-)(?!.*--)[A-Za-z0-9-]+(?<!-)$/i) record.errors[:name] << "may only contain alphanumeric characters or single hyphens, and cannot begin or end with a hyphen" elsif record.name.length > 39 record.errors[:name] << "is too long (maximum is 39 characters)" elsif record.new_record? && Person.names.include?(record.name) record.errors[:name] << "is already taken" end end end
true
ca567f6ac7bc9ac5ce370db9c43c015bd867c5d5
Ruby
mdixon47/Codewars-Ruby
/8-kyu/Basic Fizz Buzz.rb
UTF-8
649
4.6875
5
[]
no_license
#Description: #FizzBuzz is probably the second most popular way to introduce beginners to the art of coding #(the first probably being the ancient Fibonacci sequence, the grandfather of all the algorithm theory). #In this very basic kata you will have to create a function that #returns the same numbers that is given as a parameter, with the following exceptions: #If number divides evenly with 3 - returns string "fizz" #If number divides evenly with 5 - returns string "buzz" #If number divides evenly with 3 and 5 - returns string "fizz buzz" def fizzbuzz(n) n % 3 == 0 ? (n % 5 == 0 ? "fizz buzz" : "fizz") : (n % 5 == 0 ? "buzz" : n) end
true
49bfaf32b0b1dbf85829fa22fbe3a7ca4eff7b00
Ruby
sebatapiaoviedo/dibujandoasteriscosypuntos
/asteriscos_y_puntos.rb
UTF-8
145
3.015625
3
[]
no_license
aux = "" numero = ARGV[0].to_i for i in (1..numero) #i%2 == 0 if i.even? aux += "." else aux += "*" end end puts aux
true