{ // 获取包含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 !== 'PDF TO Markdown' && linkText !== 'PDF TO Markdown' ) { link.textContent = 'PDF TO 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 !== 'Voice Cloning' ) { link.textContent = 'Voice Cloning'; link.href = 'https://vibevoice.info/'; 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, 'PDF TO 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\t\tcontent.each do |line|\n\t\t\tputs(\"

#{line}

\")\n\t\tend\n\t\tputs('\t')\n\t\tputs('')\n\tend\nend\n\nclass PlainTextFormatter < Formatter\n\tdef output_report(title, text)\n\t\tputs(\"***** #{title} *****\")\n\t\ttext.each do |line|\n\t\t\tputs(line)\n\t\tend\n\tend\nend\n\nclass Report \n\tattr_reader :title, :content\n\tattr_accessor :formatter\n\n\tdef initialize(formatter)\n\t\t@title = 'Monthly Report'\n\t\t@content = [ 'Things are going', 'really, really well.']\n\t\t@formatter = formatter\n\tend\n\n\tdef output_report\n\t\t@formatter.output_report(@title, @content)\n\tend\nend\nreport = Report.new(HTMLFormatter.new)\nreport.output_report\n# \n# \n# Monthly Report \n# \n# \t\n#

Things are going

\n#

really, really well.

\n# \t\n# "},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2972910,"cells":{"blob_id":{"kind":"string","value":"58f12cf64c1adc27327c2b99c035acda9ac9f1de"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"jinhale/viper"},"path":{"kind":"string","value":"/spec/make_bindings_spec.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":3201,"string":"3,201"},"score":{"kind":"number","value":2.640625,"string":"2.640625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"# make_bindings_spec.rb - specs for make_bindings\n\nrequire_relative 'spec_helper'\n\ndescribe 'make_bindings returns a key inserter proc for letters' do\n let(:buf) { Buffer.new '' }\n let(:bind) { make_bindings }\n let(:prc) { bind[:key_p] }\n subject { prc.call(buf); buf.to_s }\n\n specify { subject.must_equal 'p' }\nend\n\ndescribe 'inserter for caps' do\n let(:buf) { Buffer.new '' }\n let(:bind) { make_bindings }\n let(:prc) { bind[:key_A] }\n subject { prc.call(buf); buf.to_s }\n\n specify { subject.must_equal 'A' }\nend\n\ndescribe 'inserter 0' do\n let(:buf) { Buffer.new '' }\n let(:bind) { make_bindings }\n let(:prc) { bind[:key_0] }\n subject { prc.call(buf); buf.to_s }\n\n specify { subject.must_equal '0' }\nend\n\ndescribe 'special chars :space' do\n let(:buf) { Buffer.new '' }\n let(:bind) { make_bindings }\n let(:prc) { bind[:space] }\n subject { prc.call(buf); buf.to_s }\n\n specify { subject.must_equal ' ' }\nend\n\ndescribe 'ctrl_z cannot undo' do\n let(:buf) { ReadOnlyBuffer.new 'yyy' }\n let(:bind) { make_bindings }\n let(:prc) { bind[:ctrl_z] }\n subject { buf.ins 'xxx'; prc.call(buf); buf.to_s }\n\n specify { subject.must_equal 'yyy' }\nend\n\ndescribe 'Can undo insert' do\n let(:buf) { ScratchBuffer.new }\n let(:bind) { make_bindings }\n let(:prc) { bind[:ctrl_z] }\n subject { buf.ins 'xxx'; prc.call(buf); buf.to_s }\n\n specify { subject.must_equal '' }\nend\n\nclass CannotRecordMe < Buffer\n include NonRecordable\nend\n\ndescribe 'ReadOnlyBuffer cannot redo from ctrl_u' do\n let(:buf) { CannotRecordMe.new '' }\n let(:bind) { make_bindings }\n let(:prc) { bind[:ctrl_u] }\n subject { buf.ins 'xxx'; buf.undo; prc.call(buf); buf.to_s }\n\n specify { subject.must_equal 'xxx' }\nend\n\ndescribe 'Can redo undon action from proc in bindings' do\n let(:buf) { ScratchBuffer.new }\n let(:bind) { make_bindings }\n let(:prc) { bind[:ctrl_u] }\n subject { buf.ins 'xxx'; buf.undo; prc.call(buf); buf.to_s }\n\n specify { subject.must_equal 'xxx' }\nend\n\ndescribe 'backspace if mark set' do\n let(:buf) { ScratchBuffer.new }\n let(:bind) { make_bindings }\n let(:prc) { bind[:backspace] }\n subject { buf.ins 'xxxxx'; buf.beg; buf.set_mark; buf.fwd 3; prc.call(buf); $clipboard }\n\n specify { subject.must_equal 'xxx' }\nend\n\ndescribe 'backspace when no mark set' do\n let(:buf) { ScratchBuffer.new }\n let(:bind) { make_bindings }\n let(:prc) { bind[:backspace] }\n subject { buf.ins 'xyz'; prc.call(buf); buf.to_s }\n\n specify { subject.must_equal 'xy' }\nend\n\ndescribe 'fn_4 sets mark when not set' do\n let(:buf) { ScratchBuffer.new }\n let(:bind) { make_bindings }\n let(:prc) { bind[:fn_4] }\n subject { buf.ins 'zzz'; buf.beg; prc.call(buf); buf.mark_set? }\n\n specify { subject.must_equal true }\nend\n\ndescribe 'fn_4 unsets mark when set' do\n let(:buf) { ScratchBuffer.new }\n let(:bind) { make_bindings }\n let(:prc) { bind[:fn_4] }\n subject { buf.ins 'zzz'; buf.beg; buf.set_mark; buf.fwd; prc.call(buf); buf.mark_set? }\n\n specify { subject.must_equal false }\nend\n\ndescribe 'ctrl_w move word fwd' do\n let(:buf) { Buffer.new '0123 4567' }\n let(:bind) { make_bindings }\n let(:prc) { bind[:ctrl_w] }\n subject { prc.call buf; buf.word_fwd }\n\n specify { subject.must_equal '4567' }\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2972911,"cells":{"blob_id":{"kind":"string","value":"bbf2df7fd953a34af26d3bd6dcf2081f9997dece"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"GaronHock/Homework"},"path":{"kind":"string","value":"/octopus problems/octopus.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2094,"string":"2,094"},"score":{"kind":"number","value":4.3125,"string":"4.3125"},"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 Very Hungry Octopus wants to eat the longest fish in an array of fish.\n\n\n# ['fish', 'fiiish', 'fiiiiish', 'fiiiish', 'fffish', 'ffiiiiisshh', 'fsh', 'fiiiissshhhhhh']\n# => \"fiiiissshhhhhh\"\n\n\n# Sluggish Octopus\n# Find the longest fish in O(n^2) time. Do this by comparing all fish lengths to all other fish lengths\n\ndef sluggish_octopus(arr)\n longest = Hash.new(0)\n arr.each_with_index do |ele, i| \n longest[ele] = arr[i].length\n end\n sorted = longest.sort_by{|k,v| v}\n sorted[-1][0]\nend\n\n# fish = ['fish', 'fiiish', 'fiiiiish', 'fiiiish', 'fffish', 'ffiiiiisshh', 'fsh', 'fiiiissshhhhhh']\n\n# p sluggish_octopus(fish)\n\n\n# Dominant Octopus\n# Find the longest fish in O(n log n) time. Hint: You saw a sorting algorithm that runs \n# in O(n log n) in the Sorting Complexity Demo. Remember that Big O is classified by the dominant term\n\nclass Array\n\n # Write an Array#merge_sort method; it should not modify the original array.\n\n def dominant_octopus_merge_sort(&prc)\n prc ||= Proc.new{|a,b| a<=>b}\n return self if self.length < 2 \n mid = self.length / 2 \n left = self.take(mid)\n right = self.drop(mid)\n\n sorted_left = left.dominant_octopus_merge_sort(&prc)\n sorted_right = right.dominant_octopus_merge_sort(&prc)\n\n Array.merge(sorted_left,sorted_right, &prc)\n\n end\n\n private\n \n def self.merge(left, right, &prc)\n sorted = [] \n\n until left.empty? || right.empty? \n if prc.call(left.first.length, right.first.length) == -1 \n sorted << left.shift \n else\n sorted << right.shift \n end\n end\n sorted + left + right\n\n end\nend\n\nfish = ['fish', 'fiiish', 'fiiiiish', 'fiiiish', 'fffish', 'ffiiiiisshh', 'fsh', 'fiiiissshhhhhh']\np fish.dominant_octopus_merge_sort\n\n\n# Clever Octopus\n# Find the longest fish in O(n) time. \n# The octopus can hold on to the longest fish that you have found so far\n# while stepping through the array only once.\n\ndef clever_octopus(arr)\n longest = \"\"\n arr.each do |ele|\n if ele.length > ele.length - 1 \n longest = ele \n end\n end\n longest\n\nend\np clever_octopus(fish)\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2972912,"cells":{"blob_id":{"kind":"string","value":"0db0691ddf25e2d2defd21cdc610a551066fa4ba"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"nekokat/codewars"},"path":{"kind":"string","value":"/8 kyu_1/grasshopper-make-change.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":184,"string":"184"},"score":{"kind":"number","value":2.90625,"string":"2.90625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["Unlicense"],"string":"[\n \"Unlicense\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"#Kata: Grasshopper - Make change\r\n#URL: https://www.codewars.com/kata/560dab9f8b50f89fd6000070\r\n\r\nmoney = 10\r\ncandy = 1.42\r\nchips = 2.4\r\nsoda = 1\r\nchange = money - candy - chips - soda"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2972913,"cells":{"blob_id":{"kind":"string","value":"c34128da13a2d380e31235d24fd7b329eda8608e"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"denisson/BibliaSocial"},"path":{"kind":"string","value":"/config/initializers/integer.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":86,"string":"86"},"score":{"kind":"number","value":2.6875,"string":"2.6875"},"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 Integer\n def quantos()\n return self.to_s if self > 0\n return \"\"\n end\nend"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2972914,"cells":{"blob_id":{"kind":"string","value":"2ddeb8f002933e7714a4b2c0a1679aadf627540e"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"DiegoSalazar/template_parsing_challenge"},"path":{"kind":"string","value":"/template_parser.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1587,"string":"1,587"},"score":{"kind":"number","value":3.5,"string":"3.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":"# Given a template and an environment, fill the template with correct values.\nclass TemplateParser\n IF_TAG = ?# # prefix for if tags\n UNLESS_TAG = ?^ # prefix for unless tags\n NIL_VAR = ''\n TAG_CAPTURE = /\n {(.+)} # capture an opening tag\n (.+) # capture content after opening tag\n {(\\1)} # capture tag matching first capture\n | # or\n {(.+)} # capture just a tag\n /x\n\n # @param environment\n # a hash of values to interpolate into templates\n def initialize(environment)\n @environment = environment\n end\n\n # @param template\n # a string template\n # @return an interpolated string\n def parse(template)\n @template = template.dup\n interpolate_environment while contains_tags?\n @template\n end\n\n private\n\n def contains_tags?\n @template =~ TAG_CAPTURE\n end\n\n def interpolate_environment\n match, tag, content, _, variable = TAG_CAPTURE.match(@template).to_a\n return if match.nil?\n\n interpolate_variable match, variable if variable\n interpolate_tags match, tag, content if tag\n end\n\n def interpolate_variable(match, variable)\n @template.gsub! match, @environment.fetch(variable.downcase.to_sym, NIL_VAR)\n end\n\n def interpolate_tags(match, tag, content)\n symbol = tag.sub(/[#{IF_TAG}#{UNLESS_TAG}]/, NIL_VAR).downcase.to_sym\n\n @template.gsub! match, if tag =~ /#{IF_TAG}/\n @environment[symbol] ? content : NIL_VAR\n elsif tag =~ /#{UNLESS_TAG}/\n @environment[symbol] ? NIL_VAR : content\n end.strip\n end\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2972915,"cells":{"blob_id":{"kind":"string","value":"d2d00f06487a04f9ba0670fcdddac562085fae68"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"juanlfr/tests-ruby"},"path":{"kind":"string","value":"/lib/03_basics.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":484,"string":"484"},"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":"def who_is_bigger(a,b,c)\n\tif a==nil || b==nil || c==nil then return \"nil detected\"\n\telsif a==[a,b,c].max then return(\"a is bigger\")\n\telsif b==[a,b,c].max then return(\"b is bigger\")\n\telse return(\"c is bigger\")\n\tend\nend\n\n\ndef reverse_upcase_noLTA(string)\n\treturn string.reverse.upcase.delete 'LTA'\nend\n\n\ndef array_42(array)\n\tif array.count(42)>0 then return true else return false\n\tend\nend\n\ndef magic_array(array)\n\treturn array.flatten.sort.map{|x| x*=2}.reject{|x| x%3==0}.uniq\nend\n\n\n\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2972916,"cells":{"blob_id":{"kind":"string","value":"8c307273ee2e549fec139bae0c9ab6e6bcdf8620"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"narayana1208/git-review"},"path":{"kind":"string","value":"/lib/git-review/local.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":7733,"string":"7,733"},"score":{"kind":"number","value":2.65625,"string":"2.65625"},"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 GitReview\n\n # The local repository is where the git-review command is being called\n # by default. It is (supposedly) able to handle systems other than Github.\n # TODO: remove Github-dependency\n class Local\n\n include ::GitReview::Internals\n\n attr_accessor :config\n\n # acts like a singleton class but it's actually not\n # use ::GitReview::Local.instance everywhere except in tests\n def self.instance\n @instance ||= new\n end\n\n def initialize\n # find root git directory if currently in subdirectory\n if git_call('rev-parse --show-toplevel').strip.empty?\n raise ::GitReview::InvalidGitRepositoryError\n else\n add_pull_refspec\n load_config\n end\n end\n\n # @return [Array] all existing branches\n def all_branches\n git_call('branch -a').split(\"\\n\").collect { |s| s.strip }\n end\n\n # @return [Array] all open requests' branches shouldn't be deleted\n def protected_branches\n github.current_requests.collect { |r| r.head.ref }\n end\n\n # @return [Array] all review branches with 'review_' prefix\n def review_branches\n all_branches.collect { |branch|\n # only use uniq branch names (no matter if local or remote)\n branch.split('/').last if branch.include?('review_')\n }.compact.uniq\n end\n\n # clean a single request's obsolete branch\n def clean_single(number, force=false)\n request = github.pull_request(source_repo, number)\n if request && request.state == 'closed'\n # ensure there are no unmerged commits or '--force' flag has been set\n branch_name = request.head.ref\n if unmerged_commits?(branch_name) && !force\n puts \"Won't delete branches that contain unmerged commits.\"\n puts \"Use '--force' to override.\"\n else\n delete_branch(branch_name)\n end\n end\n rescue Octokit::NotFound\n false\n end\n\n # clean all obsolete branches\n def clean_all\n (review_branches - protected_branches).each do |branch_name|\n # only clean up obsolete branches.\n delete_branch(branch_name) unless unmerged_commits?(branch_name, false)\n end\n end\n\n # delete local and remote branches that match a given name\n # @param branch_name [String] name of the branch to delete\n def delete_branch(branch_name)\n delete_local_branch(branch_name)\n delete_remote_branch(branch_name)\n end\n\n # delete local branch if it exists.\n # @param (see #delete_branch)\n def delete_local_branch(branch_name)\n if branch_exists?(:local, branch_name)\n git_call(\"branch -D #{branch_name}\", true)\n end\n end\n\n # delete remote branch if it exists.\n # @param (see #delete_branch)\n def delete_remote_branch(branch_name)\n if branch_exists?(:remote, branch_name)\n git_call(\"push origin :#{branch_name}\", true)\n end\n end\n\n # @param location [Symbol] location of the branch, `:remote` or `:local`\n # @param branch_name [String] name of the branch\n # @return [Boolean] whether a branch exists in a specified location\n def branch_exists?(location, branch_name)\n return false unless [:remote, :local].include?(location)\n prefix = location == :remote ? 'remotes/origin/' : ''\n all_branches.include?(prefix + branch_name)\n end\n\n # @return [Boolean] whether there are local changes not committed\n def uncommitted_changes?\n !git_call('diff HEAD').empty?\n end\n\n # @param branch_name [String] name of the branch\n # @param verbose [Boolean] if verbose output\n # @return [Boolean] whether there are unmerged commits on the local or\n # remote branch.\n def unmerged_commits?(branch_name, verbose=true)\n locations = []\n locations << '' if branch_exists?(:local, branch_name)\n locations << 'origin/' if branch_exists?(:remote, branch_name)\n locations = locations.repeated_permutation(2).to_a\n if locations.empty?\n puts 'Nothing to do. All cleaned up already.' if verbose\n return false\n end\n # compare remote and local branch with remote and local master\n responses = locations.collect { |loc|\n git_call \"cherry #{loc.first}#{target_branch} #{loc.last}#{branch_name}\"\n }\n # select commits (= non empty, not just an error message and not only\n # duplicate commits staring with '-').\n unmerged_commits = responses.reject { |response|\n response.empty? or response.include?('fatal: Unknown commit') or\n response.split(\"\\n\").reject { |x| x.index('-') == 0 }.empty?\n }\n # if the array ain't empty, we got unmerged commits\n if unmerged_commits.empty?\n false\n else\n puts \"Unmerged commits on branch '#{branch_name}'.\"\n true\n end\n end\n\n # @return [Boolean] whether there are commits not in target branch yet\n def new_commits?(upstream=false)\n target = upstream ? 'upstream/master' : target_branch\n not git_call(\"cherry #{target}\").empty?\n end\n\n # @return [Boolean] whether a specified commit has already been merged.\n def merged?(sha)\n branches = git_call(\"branch --contains #{sha} 2>&1\").split(\"\\n\").\n collect { |b| b.delete('*').strip }\n branches.include?(target_branch)\n end\n\n # @return [String] the source repo\n def source_repo\n github.source_repo\n end\n\n # @return [String] the current source branch\n def source_branch\n git_call('branch').chomp.match(/\\*(.*)/)[0][2..-1]\n end\n\n # @return [String] combine source repo and branch\n def source\n \"#{source_repo}/#{source_branch}\"\n end\n\n # @return [String] the name of the target branch\n def target_branch\n # TODO: Manually override this and set arbitrary branches\n ENV['TARGET_BRANCH'] || 'master'\n end\n\n # if to send a pull request to upstream repo, get the parent as target\n # @return [String] the name of the target repo\n def target_repo(upstream=false)\n # TODO: Manually override this and set arbitrary repositories\n if upstream\n github.repository(source_repo).parent.full_name\n else\n source_repo\n end\n end\n\n # @return [String] combine target repo and branch\n def target\n \"#{target_repo}/#{target_branch}\"\n end\n\n # @return [String] the head string used for pull requests\n def head\n # in the form of 'user:branch'\n \"#{source_repo.split('/').first}:#{source_branch}\"\n end\n\n # @return [Boolean] whether already on a feature branch\n def on_feature_branch?\n # If current and target are the same, we are not on a feature branch.\n # If they are different, but we are on master, we should still to switch\n # to a separate branch (since master makes for a poor feature branch).\n source_branch != target_branch && source_branch != 'master'\n end\n\n # add remote.origin.fetch to check out pull request locally\n # see {https://help.github.com/articles/checking-out-pull-requests-locally}\n def add_pull_refspec\n refspec = '+refs/pull/*/head:refs/remotes/origin/pr/*'\n fetch_config = \"config --local --add remote.origin.fetch #{refspec}\"\n git_call(fetch_config, false) unless config_list.include?(refspec)\n end\n\n def load_config\n @config = {}\n config_list.split(\"\\n\").each do |line|\n key, value = line.split(/=/, 2)\n if @config[key] && @config[key] != value\n @config[key] = [@config[key]].flatten << value\n else\n @config[key] = value\n end\n end\n @config\n end\n\n def config_list\n git_call('config --list', false)\n end\n\n def github\n @github ||= ::GitReview::Github.instance\n end\n\n end\n\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2972917,"cells":{"blob_id":{"kind":"string","value":"a7bfa377d2cfb9f91d417b9ca3f1e819cfe876ec"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"awesome/coffeelint-ruby"},"path":{"kind":"string","value":"/lib/coffeelint.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2640,"string":"2,640"},"score":{"kind":"number","value":2.640625,"string":"2.640625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"require \"coffeelint/version\"\nrequire 'execjs'\nrequire 'coffee-script'\nrequire 'json'\n\nmodule Coffeelint\n require 'coffeelint/railtie' if defined?(Rails::Railtie)\n\n def self.path()\n @path ||= File.expand_path('../../coffeelint/lib/coffeelint.js', __FILE__)\n end\n\n def self.colorize(str, color_code)\n \"\\e[#{color_code}m#{str}\\e[0m\"\n end\n\n def self.red(str, pretty_output = true)\n pretty_output ? Coffeelint.colorize(str, 31) : str\n end\n\n def self.green(str, pretty_output = true)\n pretty_output ? Coffeelint.colorize(str, 32) : str\n end\n\n def self.context\n coffeescriptSource = File.read(CoffeeScript::Source.path)\n bootstrap = <<-EOF\n window = {\n CoffeeScript: CoffeeScript,\n coffeelint: {}\n };\n EOF\n coffeelintSource = File.read(Coffeelint.path)\n ExecJS.compile(coffeescriptSource + bootstrap + coffeelintSource)\n end\n\n def self.lint(script, config = {})\n if !config[:config_file].nil?\n fname = config.delete(:config_file)\n config.merge!(JSON.parse(File.read(fname)))\n end\n Coffeelint.context.call('window.coffeelint.lint', script, config)\n end\n\n def self.lint_file(filename, config = {})\n Coffeelint.lint(File.read(filename), config)\n end\n\n def self.lint_dir(directory, config = {})\n retval = {}\n Dir.glob(\"#{directory}/**/*.coffee\") do |name|\n retval[name] = Coffeelint.lint_file(name, config)\n yield name, retval[name] if block_given?\n end\n retval\n end\n\n def self.display_test_results(name, errors, pretty_output = true)\n good = pretty_output ? \"\\u2713\" : 'Passed'\n bad = pretty_output ? \"\\u2717\" : 'Failed'\n\n if errors.length == 0\n puts \" #{good} \" + Coffeelint.green(name, pretty_output)\n return true\n else\n puts \" #{bad} \" + Coffeelint.red(name, pretty_output)\n errors.each do |error|\n print \" #{bad} \"\n print Coffeelint.red(error[\"lineNumber\"], pretty_output)\n puts \": #{error[\"message\"]}, #{error[\"context\"]}.\"\n end\n return false\n end\n end\n\n def self.run_test(file, config = {})\n pretty_output = config.has_key?(:pretty_output) ? config.delete(:pretty_output) : true\n result = Coffeelint.lint_file(file, config)\n Coffeelint.display_test_results(file, result, pretty_output)\n end\n\n def self.run_test_suite(directory, config = {})\n pretty_output = config.has_key?(:pretty_output) ? config.delete(:pretty_output) : true\n success = true\n Coffeelint.lint_dir(directory, config) do |name, errors|\n result = Coffeelint.display_test_results(name, errors, pretty_output)\n success = false if not result\n end\n success\n end\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2972918,"cells":{"blob_id":{"kind":"string","value":"effb7076c4fbcdc3d9008231e1b1515d0720ca05"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"Maikon/learn_ruby_hard_zed"},"path":{"kind":"string","value":"/ex9.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":652,"string":"652"},"score":{"kind":"number","value":4,"string":"4"},"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":"# Here's some new strange stuff, remember type it exaxctly.\n\ndays = \"Mon Tue Wed Thu Fri Sat Sun\"\nmonths = \"Jan\\nFeb\\nMar\\nApr\\nMay\\nJun\\nJul\\nAug\"\n\nputs \"Here are the days: \", days # will print the list of days in a row\nputs \"Here are the months: \", months # will print the list of months each one on its own line, \n\t\t\t\t\t\t\t\t\t # because of the \\n (newline) character\n\nputs <\np /(\\d+)年(\\d+)月(\\d+)日/.match('honnouji')\n# nil\n\nm = text.match(/(\\d+)年(\\d+)月(\\d+)日/)\np m\n# #\n\n\ntext1 = 'ペリーは1853年7月8日に浦賀沖に来航しました。'\ntext2 = '聖徳太子は574年に生まれました。'\ndef ymd(text)\n if m = /(\\d+)年(\\d+)月(\\d+)日/.match(text)\n 'マッチしました'\n else\n 'マッチしませんでした'\n end\nend\n\nputs ymd(text1)\n# マッチしました\nputs ymd(text2)\n# マッチしませんでした"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2972920,"cells":{"blob_id":{"kind":"string","value":"1ff0aa7efb560a26e4bd3aeb701915f6f27f284d"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"clone18476/ghibli_cli"},"path":{"kind":"string","value":"/lib/api.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1237,"string":"1,237"},"score":{"kind":"number","value":3.5,"string":"3.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":"class API \n\n # NOTE: all of your API methods should be class methods\n\n def self.fetch_films\n url = \"https://ghibliapi.herokuapp.com/films/\"\n uri = URI(url)\n response = Net::HTTP.get(uri)\n films_array = JSON.parse(response)\n\n # each hash represents a film, and we want to initialize a new drink for each hash\n\n # !!!! it's important that we're making objects (instances) with our api data\n\n # access one hash at a time to make an instance out of one hash at a time by ITERATING (as seen below)\n\n films_array.each do |film_hash| \n film = Film.new # THIS IS WHERE WE MAKE A NEW 'film' INSTANCE\n film.title = film_hash[\"title\"] # assigning the title of the film as a part of our film object \n film.director = film_hash[\"director\"] # and so on, and so forth\n film.producer = film_hash[\"producer\"]\n film.release_date = film_hash[\"release_date\"]\n film.run_time = film_hash[\"running_time\"]\n film.characters = film_hash[\"people\"]\n film.species = film_hash[\"species\"]\n film.location = film_hash[\"location\"]\n film.vehicles = film_hash[\"vehicles\"]\n end \n\n end \n\nend "},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2972921,"cells":{"blob_id":{"kind":"string","value":"de2951aac31a02c0994cf3ae0c3c48b1e1669b8f"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"HMJospeh/ruby-gets-input-v-000"},"path":{"kind":"string","value":"/bin/greeting"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":266,"string":"266"},"score":{"kind":"number","value":3.515625,"string":"3.515625"},"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":"#!/usr/bin/env ruby\n\nrequire_relative '../lib/hello_ruby_programmer.rb'\n\nputs \"What's happening! Welcome to the wonderful world of Ruby programming.\"\nputs \"Let's get this game started!! Type in your name so we can get things going:\"\nname = gets.strip\ngreeting(name)\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2972922,"cells":{"blob_id":{"kind":"string","value":"c6d5d74f9e4289dbaf42af53dbce87f80124107d"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"MattStopa/Coding-Casts-Code"},"path":{"kind":"string","value":"/modules/2_organizing/modules.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":689,"string":"689"},"score":{"kind":"number","value":3.828125,"string":"3.828125"},"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 Loan\n attr_accessor :balance_owed, :maturity_months, :interest_rate\n\n def owed_by_month\n balance_owed / maturity_months\n end\n\n def print_balance\n \"Your balance is: #{balance_owed}\"\n end\n\n def years_left_to_maturity\n maturity_months / 12\n end\n\n def print_estimated_cost_per_day\n \"The cost per day of your loan is roughly: $#{owed_by_month / 30}\"\n end\n\n def cost_of_interest\n owed_by_month * interest_rate\n end\nend\n\nloan = Loan.new\nloan.balance_owed = 2000\nloan.maturity_months = 10\nloan.interest_rate = 0.01\n\nputs loan.owed_by_month\nputs loan.years_left_to_maturity\nputs loan.cost_of_interest\n\nputs loan.print_balance\nputs loan.print_estimated_cost_per_day\n\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2972923,"cells":{"blob_id":{"kind":"string","value":"becf18b0371e36657b66589b78d47bb33a8a557b"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"thallam/odin_ruby"},"path":{"kind":"string","value":"/advanced_building_blocks/lib/bubble_sort.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":585,"string":"585"},"score":{"kind":"number","value":3.640625,"string":"3.640625"},"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":"require 'pry'\n\ndef bubble_sort(arr)\nbinding.pry\n arr.length.times do\n arr.each_with_index do |item, index|\n next_item = arr[index+1]\n if next_item < item\n temp = item\n item = next_item\n next_item = temp\n # because a,b = b,a doesn't work\n end\n end\n end\nend\n\n\n=begin\n For each element in the list look at the next element.\n If it's a lower value, swap them around\n Continue until it is ordered\n\nNotes: Idiomatic switch below doesn't work. Next val gets nil.. Why?\n next_item, value = value, next_value if next_item < item\n\n=end\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2972924,"cells":{"blob_id":{"kind":"string","value":"6157a36f3bbae3622f42217ae9a5909ce5bafb41"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"justJosh1004/AcademyPGH"},"path":{"kind":"string","value":"/Template Engine/Mad Libs.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":518,"string":"518"},"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 './lib/template_engine'\n#require './Star Wars.txt'\n\nmad_lib = Template_reader.new\nmad_lib.set_template(File.read('.\\Star Wars.txt'))\n\nget_template = []\nuser_answers = []\nget_template = mad_lib.get_template_fields\n\ni = 0\nwhile i < get_template.length\n puts \"Type in a #{get_template[i]}: \"\n user_answers << gets.chomp\n i += 1\nend\np get_template\np user_answers\n\n\ncompleted_hash = mad_lib.make_hash(get_template, user_answers)\np completed_hash\nmadlib_done = mad_lib.run_template(completed_hash)\n\np madlib_done\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2972925,"cells":{"blob_id":{"kind":"string","value":"1b404bb086eacad4bea7e6eb9915d54c469a4dcf"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"Sancbella/jumpstart-app"},"path":{"kind":"string","value":"/Basics/orangetree.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1841,"string":"1,841"},"score":{"kind":"number","value":4.03125,"string":"4.03125"},"int_score":{"kind":"number","value":4,"string":"4"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"class OrangeTree\n def initialize\n @height = 120\n @age = 0\n @name = 'Mr.Orange'\n @orangeProduction = 0\n puts 'Mr.Orange is born'\n end\n def oneYearPasses number\n if number <= 0\n puts 'no time has passed'\n elsif\n @age = @age + (1*number)\n @height = @height + (30*number)\n puts 'Orangie is now ' + @age.to_s + ' years old'\n \n if @age >= 15\n puts 'Mr. Orange is dead, RIP Mr.Orange, but say hello to Baby Orange'\n @age = 0\n @height = 0\n elsif @age == 2\n puts 'Baby Orange is now Mr. Orange and produced 1 orange!'\n @orangeProduction = 1\n elsif @age >= 3 and @age <= 15\n @orangeProduction = @orangeProduction + 1 + rand(6) * number\n puts 'This year Mr. Orange produced ' + @orangeProduction.to_s + ' oranges!'\n end\n end\n end\n def countTheOranges\n if @orangeProduction == 0 \n puts 'There are no oranges, he\\'s just a baby!'\n elsif @orangeProduction == 1\n puts 'Mr.Orange produced 1 oranges'\n elsif @orangeProduction > 1\n puts 'There are ' + @orangeProduction.to_s + 'Oranges'\n end\n end\n def pickAnOrange number\n puts 'There were ' + @orangeProduction.to_s + ' Oranges. It was super delicious!'\n puts 'You\\'ve picked ' + number.to_s + ' oranges'\n puts 'Now there are ' + (@orangeProduction - number).to_s + ' left'\n @orangeProduction - number\n end\nend\norangie = OrangeTree.new\norangie.oneYearPasses(1)\norangie.oneYearPasses(1)\norangie.oneYearPasses(3)\norangie.oneYearPasses(4)\norangie.oneYearPasses(2)\norangie.oneYearPasses(100)\norangie.oneYearPasses(0)\norangie.oneYearPasses(14)\norangie.pickAnOrange(5)\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2972926,"cells":{"blob_id":{"kind":"string","value":"2243b12cf8463297ae639c97f2d7ba15a780e2c3"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"slague/night_writer"},"path":{"kind":"string","value":"/lib/night_reader.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1322,"string":"1,322"},"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":"require_relative 'file_reader'\nrequire_relative 'letters'\nrequire 'pry'\n\nclass NightReader\n attr_reader :file_reader\n\n def initialize\n @reader = FileReader.new\n end\n\n def decode_file_to_english\n \n braille = @reader.open_the_file\n char_count = braille.chomp.length\n braille_out = zip_input(scan_input(split_array_at_new_lines(braille)))\n message_text = characters_equal_english_letter(braille_out)\n\n File.write(ARGV[1], message_text)\n p \"Created '#{ARGV[1]}' containing #{char_count} characters\"\n\n end\n\n def split_array_at_new_lines(braille)\n braille.split(\"\\n\")\n end\n\n def scan_input(split_array_at_new_lines)\n scanned_braille = split_array_at_new_lines.map do |line|\n line.scan(/../)\n end\n scanned_braille\n end\n\n def zip_input(scanned_braille)\n zipped_input = []\n until scanned_braille.empty? do\n zipped_input << scanned_braille[0].zip(scanned_braille[1], scanned_braille[2])\n scanned_braille.shift(3)\n end\n zipped_input.flatten(1)\n end\n\n def characters_equal_english_letter(zipped_input)\n new_line = \"\"\n zipped_input.each do |character|\n # binding.pry\n english = LETTERS.key(character)\n new_line << english.to_s\n end\n new_line\n end\nend\n\n\nif __FILE__==$0\n result_1 = NightReader.new\n result_1.decode_file_to_english\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2972927,"cells":{"blob_id":{"kind":"string","value":"e5e0ec2b01e23b428f6b1a809c65374d3d45905f"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"grimesjm/clean_arch_rb"},"path":{"kind":"string","value":"/core/lib/core/gateways/user/fake_user_repository.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":257,"string":"257"},"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":"class FakeUserRepository\n def initialize\n @users = []\n end\n\n def save(user)\n require 'securerandom'\n user.id = SecureRandom.uuid\n @users << user\n end\n\n def find_by_username(username)\n @users.find { |u| u.username == username }\n end\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2972928,"cells":{"blob_id":{"kind":"string","value":"699519c3036ec4ba95f88a6dcc4517832a02e5ff"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"access-watch/logstash-filter-accesswatch"},"path":{"kind":"string","value":"/test.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2917,"string":"2,917"},"score":{"kind":"number","value":2.578125,"string":"2.578125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["Apache-2.0"],"string":"[\n \"Apache-2.0\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"require \"manticore\"\nrequire \"json\"\nrequire \"digest\"\nrequire \"lru_redux\"\nrequire 'net/http'\n\nclass AccessWatchClient\n\n def initialize(api_key, cache_size=10000)\n @client = Manticore::Client.new ssl: {ca_file: \"cert.pem\"}\n @api_key = api_key\n if cache_size > 0\n @cache = LruRedux::ThreadSafeCache.new(cache_size)\n end\n end\n\n def handle_response(response)\n data = JSON.parse(response.body)\n if response.code == 200\n {:status => :success,\n :data => data}\n else\n {:status => :error,\n :code => data[\"code\"],\n :message => data[\"message\"]}\n end\n end\n\n def url(path)\n \"https://api.access.watch#{path}\"\n end\n\n def submit(&block)\n begin\n block.call\n rescue => e\n {:status => :error,\n :error => e,\n :message => e.message}\n end\n end\n\n def get_json(path)\n self.submit {\n self.handle_response(@client.get(self.url(path),\n headers: {\"Api-Key\" => @api_key,\n \"Accept\" => \"application/json\",\n \"User-Agent\" => \"Access Watch Logstash Plugin/0.2.0\"}))\n }\n end\n\n def post_json(path, data)\n self.submit {\n self.handle_response(@client.post(self.url(path),\n headers: {\"Api-Key\" => @api_key,\n \"Accept\" => \"application/json\",\n \"Content-Type\" => \"application/json\",\n \"User-Agent\" => \"Access Watch Logstash Plugin/0.2.0\"},\n body: JSON.generate(data)))\n }\n end\n\n def with_cache(id, &block)\n if @cache\n @cache.getset(id) { block.call }\n else\n block.call\n end\n end\n\n def fetch_address(ip)\n self.with_cache(\"ip-#{ip}\") {\n self.get_json(\"/1.1/address/#{ip}\")\n }\n end\n\n def fetch_user_agent(user_agent)\n self.with_cache(\"ua-#{Digest::MD5.hexdigest(user_agent)}\") {\n self.post_json(\"/1.1/user-agent\", {:value => user_agent})\n }\n end\n\n def fetch_identity(ip, user_agent)\n ip = ip || ''\n user_agent = user_agent || ''\n self.with_cache(\"identity-#{Digest::MD5.hexdigest(ip)}-#{Digest::MD5.hexdigest(user_agent)}\") {\n self.post_json(\"/1.1/identity\", {:address => ip, :user_agent => user_agent})\n }\n end\n\n def test\n p self.fetch_address(\"127.0.0.1\")\n p \"---\"\n p self.fetch_user_agent(\"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.125 Safari/537.36\")\n p \"---\"\n p self.fetch_identity(\"77.123.68.232\", \"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.125 Safari/537.36\")\n end\n\nend\n\nclient = AccessWatchClient.new(\"94bbc755f5b8aa96cfd40ce97faad568\")\np client.fetch_address(\"127.0.0.1\")\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2972929,"cells":{"blob_id":{"kind":"string","value":"a4eccd11808ed943efe5f6a2489d45704adacfde"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"whastings/coding_practice"},"path":{"kind":"string","value":"/problems/exponent_rec.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":251,"string":"251"},"score":{"kind":"number","value":3.375,"string":"3.375"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"def exponent_rec(base, power)\n return 1 if power == 0\n return 1.0 / exponent_rec(base, power * -1) if power < 0\n return base * exponent_rec(base, power - 1) if power.odd?\n\n # Power is even.\n half = exponent_rec(base, power / 2)\n half * half\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2972930,"cells":{"blob_id":{"kind":"string","value":"0bfd318d1bc5197dc4f0dfda4516b70712976cd5"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"n-flint/brownfield-of-dreams-2"},"path":{"kind":"string","value":"/app/services/github_api_service.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":721,"string":"721"},"score":{"kind":"number","value":2.6875,"string":"2.6875"},"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 GithubApiService\n def initialize(token)\n @token = token\n end\n\n def user_email(handle)\n parsed_response(conn.get(\"/users/#{handle}\"))\n end\n\n def followers\n parsed_response(conn.get('/user/followers'))\n end\n\n def repos(limit = 5)\n response = conn.get('/user/repos')\n new_response = parsed_response(response)\n new_response.take(limit)\n end\n\n def following\n parsed_response(conn.get('/user/following'))\n end\n\n private\n\n def parsed_response(response)\n JSON.parse(response.body, symbolize_names: true)\n end\n\n def conn\n Faraday.new(url: 'https://api.github.com') do |f|\n f.headers['Authorization'] = \"token #{@token}\"\n f.adapter Faraday.default_adapter\n end\n end\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2972931,"cells":{"blob_id":{"kind":"string","value":"b91b3ee8e6378a51b1618a16a1464d02f62a76f9"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"fertech/csv_decision"},"path":{"kind":"string","value":"/lib/csv_decision/validate.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":3100,"string":"3,100"},"score":{"kind":"number","value":2.90625,"string":"2.90625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"# frozen_string_literal: true\n\n# CSV Decision: CSV based Ruby decision tables.\n# Created December 2017.\n# @author Brett Vickers \n# See LICENSE and README.md for details.\nmodule CSVDecision\n # Parse and validate the column names in the header row.\n # These methods are only required at table load time.\n # @api private\n module Validate\n # These column types do not need a name.\n COLUMN_TYPE_ANONYMOUS = Set.new(%i[guard if path]).freeze\n private_constant :COLUMN_TYPE_ANONYMOUS\n\n # Validate a column header cell and return its type and name.\n #\n # @param cell [String] Header cell.\n # @param index [Integer] The header column's index.\n # @return [Array<(Symbol, Symbol)>] Column type and column name symbols.\n def self.column(cell:, index:)\n match = Header::COLUMN_TYPE.match(cell)\n raise CellValidationError, 'column name is not well formed' unless match\n\n column_type = match['type']&.downcase&.to_sym\n column_name = column_name(type: column_type, name: match['name'], index: index)\n\n [column_type, column_name]\n rescue CellValidationError => exp\n raise CellValidationError, \"header column '#{cell}' is not valid as the #{exp.message}\"\n end\n\n # Validate the column name against the dictionary of column names.\n #\n # @param columns [Symbol=>[false, Integer]] Column name dictionary.\n # @param name [Symbol] Column name.\n # @param out [false, Integer] False if an input column, otherwise the column index of\n # the output column.\n # @return [void]\n # @raise [CellValidationError] Column name invalid.\n def self.name(columns:, name:, out:)\n return unless (in_out = columns[name])\n\n return validate_out_name(in_out: in_out, name: name) if out\n validate_in_name(in_out: in_out, name: name)\n end\n\n def self.column_name(type:, name:, index:)\n # if: columns are named after their index, which is an integer and so cannot\n # clash with other column name types, which are symbols.\n return index if type == :if\n\n return format_column_name(name) if name.present?\n\n return if COLUMN_TYPE_ANONYMOUS.member?(type)\n raise CellValidationError, 'column name is missing'\n end\n private_class_method :column_name\n\n def self.format_column_name(name)\n column_name = name.strip.tr(\"\\s\", '_')\n\n return column_name.to_sym if Header.column_name?(column_name)\n raise CellValidationError, \"column name '#{name}' contains invalid characters\"\n end\n private_class_method :format_column_name\n\n def self.validate_out_name(in_out:, name:)\n if in_out == :in\n raise CellValidationError, \"output column name '#{name}' is also an input column\"\n end\n\n raise CellValidationError, \"output column name '#{name}' is duplicated\"\n end\n private_class_method :validate_out_name\n\n def self.validate_in_name(in_out:, name:)\n # in: columns may be duped\n return if in_out == :in\n\n raise CellValidationError, \"output column name '#{name}' is also an input column\"\n end\n private_class_method :validate_in_name\n end\nend"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2972932,"cells":{"blob_id":{"kind":"string","value":"ca5b3e486034511b4a1ef883f7f293755885341a"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"Fabian-tapia7/ruby"},"path":{"kind":"string","value":"/arreglos/sesion_online/aumento_precios.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":177,"string":"177"},"score":{"kind":"number","value":3,"string":"3"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"def promedio(notas)\n n= notas.count\n n.times do |i|\n if notas[i]=='N.A'\n notas[i] = 2\n end\n end\n print notas.sum/notas.count\nend\n\npromedio([5, 5, 20])\nprint \"\\n\"\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2972933,"cells":{"blob_id":{"kind":"string","value":"a6f2ba7435c679956e4b574d20eccff8ab983fac"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"p/lonely_coder"},"path":{"kind":"string","value":"/lib/lonely_coder/profile.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":7573,"string":"7,573"},"score":{"kind":"number","value":2.53125,"string":"2.53125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"# encoding: UTF-8\n\nclass OKCupid\n\n def profile_for(username)\n Profile.by_username(username, @browser)\n end\n\n def visitors_for(username, previous_timestamp = 0)\n Profile.get_new_visitors(username, previous_timestamp, @browser)\n end\n\n def likes_for(username)\n Profile.get_new_likes(username, @browser)\n end\n\n def update_section(section, text)\n Profile.update_profile_section(section, text, @browser)\n end\n\n def upload_pic(file, caption)\n Profile.upload_picture(file, caption, @browser)\n end\n \n class Profile\n attr_accessor :username, :match, :friend, :enemy, :location,\n :age, :sex, :orientation, :relationship_status,\n :small_avatar_url, :relationship_type\n\n # extended profile details\n attr_accessor :last_online, :ethnicity, :height, :body_type, :diet, :smokes,\n :drinks, :drugs, :religion, :sign, :education, :job, :income,\n :offspring, :pets, :speaks, :profile_thumb_urls, :essays\n\n\n # Scraping is never pretty.\n def self.from_search_result(html)\n\n username = html.search('span.username').text\n age, sex, orientation, relationship_status = html.search('p.aso').text.split('/')\n\n percents = html.search('div.percentages')\n match = percents.search('p.match .percentage').text.to_i\n friend = percents.search('p.friend .percentage').text.to_i\n enemy = percents.search('p.enemy .percentage').text.to_i\n\n location = html.search('p.location').text\n small_avatar_url = html.search('a.user_image img').attribute('src').value\n\n OKCupid::Profile.new({\n username: username,\n age: OKCupid.strip(age),\n sex: OKCupid.strip(sex),\n orientation: OKCupid.strip(orientation),\n relationship_status: OKCupid.strip(relationship_status),\n match: match,\n friend: friend,\n enemy: enemy,\n location: location,\n small_avatar_url: small_avatar_url,\n relationship_type: relationship_type,\n })\n end\n\n def Profile.get_new_likes(username, browser)\n html = browser.get(\"http://www.okcupid.com/who-likes-you\")\n text = html.search('#whosIntoYouUpgrade .title').text\n index = text.index(' people')\n likes = text[0, index].to_i\n\n return likes\n end\n\n def Profile.get_new_visitors(username, previous_timestamp = 1393545600, browser)\n html = browser.get(\"http://www.okcupid.com/visitors\")\n visitors = html.search(\".user_list .user_row_item\")\n\n new_visitors = 0\n # previous_timestamp = 1393545600\n\n visitors.each { |visitor|\n begin\n timestamp_script = visitor.search(\".timestamp script\")\n timestamp_search = timestamp_script.text.match(/FancyDate\\.add\\([^,]+?,\\s*(\\d+)\\s*,/)\n timestamp = timestamp_search[1]\n timestamp = timestamp.to_i\n rescue\n next\n end\n if (timestamp > previous_timestamp)\n new_visitors += 1\n end\n }\n\n return new_visitors\n end\n\n def Profile.by_username(username, browser)\n html = browser.get(\"http://www.okcupid.com/profile/#{username}\")\n\n percents = html.search('#percentages')\n match = percents.search('span.match').text.to_i\n friend = percents.search('span.friend').text.to_i\n enemy = percents.search('span.enemy').text.to_i\n\n basic = html.search('#aso_loc')\n age = basic.search('#ajax_age').text\n sex = basic.search('#ajax_gender').text\n orientation = basic.search('#ajax_orientation').text\n relationship_status = basic.search('#ajax_status').text\n location = basic.search('#ajax_location').text\n relationship_type = basic.search('#ajax_monogamous').text\n profile_thumb_urls = html.search('#profile_thumbs img').collect {|img| img.attribute('src').value}\n\n essays = []\n 10.times do |i|\n essays[i] = html.search('#essay_text_' + i.to_s).text.strip!\n end\n\n attributes = {\n username: username,\n match: match,\n friend: friend,\n enemy: enemy,\n age: age,\n sex: sex,\n orientation: orientation,\n location: location,\n relationship_status: relationship_status,\n profile_thumb_urls: profile_thumb_urls,\n relationship_type: relationship_type,\n essays: essays,\n }\n\n details_div = html.search('#profile_details dl')\n\n details_div.each do |node|\n value = OKCupid.strip(node.search('dd').text)\n next if value == '—'\n\n attr_name = node.search('dt').text.downcase.gsub(' ','_')\n attributes[attr_name] = value\n end\n\n self.new(attributes)\n end\n\n def Profile.update_profile_section(section, text, browser)\n section_titles = [\n \"My self-summary\",\n \"What I’m doing with my life\",\n \"I’m really good at\",\n \"The first things people usually notice about me\",\n \"Favorite books, movies, shows, music, and food\",\n \"The six things I could never do without\",\n \"I spend a lot of time thinking about\",\n \"On a typical Friday night I am\",\n \"The most private thing I’m willing to admit\",\n \"You should message me if\"\n ]\n\n section_titles_hash = {\n :self_summary => 0,\n :im_doing => 1,\n :good_at => 2,\n :first_thing => 3,\n :favorites => 4,\n :six_things => 5,\n :think_about => 6,\n :private => 7,\n :message_me => 8\n }\n\n if section.class == Symbol\n section = section_titles_hash[section]\n end\n \n profile = browser.get('http://www.okcupid.com/profile')\n\n authcode = profile.body.match(/authcode['\"]?\\s*:\\s*['\"]([\\w,;]+?)['\"]/)[1]\n\n section_response = browser.post('http://www.okcupid.com/profileedit2', {\n :authcode => authcode,\n :essay_body => text,\n :essay_id => section,\n :change_summary => \"[title:start]#{section_titles[section]}[title:end][add:start]#{text}[add:end]\",\n :okc_api => 1\n })\n end\n\n def Profile.upload_picture(file, caption, browser)\n\n file_dimensions = Dimensions.dimensions(file)\n\n profile = browser.get('http://www.okcupid.com/profile')\n\n authcode = profile.body.match(/authcode['\"]?\\s*:\\s*['\"]([\\w,;]+?)['\"]/)[1]\n userid = profile.body.match(/userid['\"]?\\s*:\\s*['\"]?(\\d+)['\"]?/)[1]\n\n upload_response = browser.post('http://www.okcupid.com/ajaxuploader', {\n 'file' => File.new(file)\n })\n\n picid = upload_response.body.match(/id'\\s*:\\s*'(\\d+)/)[1]\n\n uri = Addressable::URI.parse('http://www.okcupid.com/photoupload')\n uri.query_values = {\n :authcode => authcode,\n :userid => userid,\n :picid => picid,\n :width => file_dimensions[0],\n :height => file_dimensions[1],\n :tn_upper_left_x => 0,\n :tn_upper_left_y => 0,\n :tn_lower_right_x => file_dimensions[0],\n :tn_lower_right_y => file_dimensions[1],\n\n :caption => caption,\n :albumid => 0,\n :use_new_upload => 1,\n :okc_api => 1,\n :'picture.add_ajax' => 1,\n }\n \n uri.to_s\n\n create_photo = browser.get(uri.to_s)\n\n end\n \n def initialize(attributes)\n attributes.each do |attr,val|\n self.send(\"#{attr}=\", val)\n end\n end\n\n def ==(other)\n self.username == other.username\n end\n\n def eql?(other)\n self.username == other.username\n end\n\n def hash\n if self.username\n self.username.hash\n else\n super\n end\n end\n end\nend\n\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2972934,"cells":{"blob_id":{"kind":"string","value":"ced90e8a6e3f67406ceab2ebfec2406ab0987fa7"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"anotherminh/ruby_chess_game"},"path":{"kind":"string","value":"/player.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2114,"string":"2,114"},"score":{"kind":"number","value":3.71875,"string":"3.71875"},"int_score":{"kind":"number","value":4,"string":"4"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"require_relative 'display'\n\nclass HumanPlayer\n # Reads keypresses from the user including 2 and 3 escape character sequences.\n def self.read_char\n STDIN.echo = false\n STDIN.raw!\n\n input = STDIN.getc.chr\n if input == \"\\e\" then\n input << STDIN.read_nonblock(3) rescue nil\n input << STDIN.read_nonblock(2) rescue nil\n end\n ensure\n STDIN.echo = true\n STDIN.cooked!\n\n return input\n end\n\n def self.get_key(cursor_pos)\n c = read_char\n new_pos = cursor_pos.dup\n case c\n when \"\\e[A\"\n # puts \"UP ARROW\"\n new_pos[0] -= 1\n when \"\\e[B\"\n # puts \"DOWN ARROW\"\n new_pos[0] += 1\n when \"\\e[C\"\n # puts \"RIGHT ARROW\"\n new_pos[1] += 1\n when \"\\e[D\"\n # puts \"LEFT ARROW\"\n new_pos[1] -= 1\n when \"\\r\"\n new_pos = false\n when \"\\e\"\n Kernel.abort\n end\n new_pos\n end\n\n attr_reader :color\n\n def initialize(color)\n @color = color\n end\n\n def show_display(display)\n @display = display\n end\n\n def make_move(board)\n @board = board\n @selected = false\n @moved = false\n choose_piece\n move_piece\n end\n\n def choose_piece\n selected_pos = nil\n until @selected\n display.print_board\n\n new_input = HumanPlayer.get_key(display.cursor_pos)\n\n if new_input\n display.update_cursor(new_input) if board.on_board?(new_input)\n else\n @selected_pos = display.cursor_pos\n @selected = true if board.valid_selection?(color, @selected_pos)\n end\n end\n selected_pos\n end\n\n def move_piece\n until @moved\n display.print_board(selected_pos)\n new_input = HumanPlayer.get_key(display.cursor_pos)\n\n if new_input\n display.update_cursor(new_input) if board.on_board?(new_input)\n else\n new_pos = display.cursor_pos\n if new_pos == @selected_pos\n @selected = false\n choose_piece\n elsif board.valid_move?(@selected_pos, new_pos, color)\n @moved = true\n board.move_piece(@selected_pos, new_pos)\n end\n end\n end\n end\n\n private\n attr_accessor :display, :board, :selected_pos\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2972935,"cells":{"blob_id":{"kind":"string","value":"a52b6da4d4f5193ea16476b80e088d33588a6e9e"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"tidorisan/ruby"},"path":{"kind":"string","value":"/2-8/2-8.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1660,"string":"1,660"},"score":{"kind":"number","value":4.03125,"string":"4.03125"},"int_score":{"kind":"number","value":4,"string":"4"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"# puts \"aaa\"\n# input_key = gets\n# puts \"入力された内容は\"+input_key\n\n# puts \"hello\"\n# input_key = gets\n# puts \"入力された内容は\"+input_key\n\n# a=gets.to_i\n# b=gets.to_i\n# puts \"a+b=#{a+b}\"\n\n# a=gets.to_i\n# b=gets.to_i\n# puts \"a+b=#{a+b}\"\n\n# puts \"キーボードで数字「2」と数字「3」を入力してください\"\n# a=gets.to_i\n# b=gets.to_i\n# puts \"a+b=#{a+b}\"\n\n# dice = 0 # diceに0を代入し、初期値を設定する\n# while dice != 6 do\n# \tdice = rand(1.6)\n# \tputs dic\n# end\n\n\n\n# dice = 0 # diceに0を代入し、初期値を設定する\n# while dice != 6 do #サイコロの目が6ではない間、diceの初期値は0なので条件を満たす。以降はdiceに代入される数によって結果が異なる\n# dice = rand(1..6) #1~6の数字がランダムに出力される\n# puts dice \n# end\n\n# for in do\n\n# for i in 1..10 do\n# \tputs i\n# end\n\n\n# for i in 1..10 do # 1..10は、1~10までの範囲を表す\n# puts i\n# end\n\n# (範囲、ハッシュ、配列などを指定).each do |変数|\n# 実行する処理\n# end\n\n# {\"apple\"=>130,\"strawberry\"=>180, \"orange\"=>100} .each do |frute,price|\n# \tputs \"#{fruit}は#{price}円です。\" #変数展開\n# end\n\n# {\"apple\"=>130, \"strawberry\"=>180, \"orange\"=>100}.each do |fruit, price| #ハッシュの内容を順にキーをfruit、値をpriceに代入して繰り返す\n# puts \"#{fruit}は#{price}円です。\" #変数展開\n# end\n\n# # 1 = 0\n# while i <= 10 do\n# \tif i >5\n# \t\tbreak \n# \tend\n# \tputs i\n# \ti += 1\n# end\n\n\ni = 0\nwhile i <= 10 do\n if i >5\n break #iが5より大きくなると繰り返しから抜ける\n end\n puts i\n i += 1\nend\n\n\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2972936,"cells":{"blob_id":{"kind":"string","value":"85cbd2d91e8e1e56a72765cebb1e897e6e891966"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"SALIM-UsseF/DEPIC"},"path":{"kind":"string","value":"/back-end/app/controllers/questionchoixes_controller.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1972,"string":"1,972"},"score":{"kind":"number","value":2.90625,"string":"2.90625"},"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# Question choix Controller\n# #############################\n#\n# Expose des services REST sous format Json:\n# - Afficher la liste des questions choix \n# - Afficher une question choix par ID\n# - Creer une nouvelle question choix \n# - Modifier une question choix\n# - Supprimer une question choix par ID\n\nrequire 'QuestionChoixService'\n\nclass QuestionchoixesController < ApplicationController\n\n \n # Afficher la liste des questions choix\n def index\n questions = QuestionChoixService.instance.listeDesQuestions\n render json: questions, status: :ok\n end\n\n\n # Afficher une QuestionChoix par ID\n def show\n question = QuestionChoixService.instance.afficherQuestionParId(params[:id])\n (question != nil) ? (render json: question, status: :ok) : (render json: nil, status: :not_found)\n end\n\n # Creer une nouvelle QuestionChoix\n def create\n params.permit(:intitule, :estObligatoire, :estUnique, :ordre, :sondage_id)\n ajout = QuestionChoixService.instance.creerQuestionChoix(params[:intitule], params[:estObligatoire], params[:estUnique], params[:ordre], params[:sondage_id])\n (ajout != nil) ? (render json: ajout, status: :ok) : (render json: nil, status: :not_found)\n end\n\n # Modifier une QuestionChoix\n def update\n modifier = QuestionChoixService.instance.modifierQuestion(params[:id], params[:intitule], params[:estObligatoire], params[:estUnique], params[:ordre])\n (modifier != nil) ? (render json: modifier, status: :ok) : (render json: nil, status: :not_found) \n end\n\n # Supprimer une QuestionChoix par ID\n def delete\n supprimer = QuestionChoixService.instance.supprimerQuestion(params[:id])\n (supprimer) ? (render json: true, status: :ok) : (render json: false, status: :not_found)\n end\n\n # Liste des parametres à fournir\n private\n\n # parametres d'ajout\n def question_params\n params.permit(:intitule, :estObligatoire, :estUnique, :nombreChoix, :ordre, :sondage_id)\n end\n\nend"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2972937,"cells":{"blob_id":{"kind":"string","value":"e7c9018c91fd455d3c8b3dcc676535ecd54ee0f0"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"TwilioDevEd/api-snippets"},"path":{"kind":"string","value":"/quickstart/ruby/autopilot/create-first-task/create_hello_world_task.6.x.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1068,"string":"1,068"},"score":{"kind":"number","value":2.5625,"string":"2.5625"},"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":"# Download the helper library from https://www.twilio.com/docs/ruby/install\nrequire 'rubygems'\nrequire 'twilio-ruby'\n\n# Your Account Sid and Auth Token from twilio.com/console\n# To set up environmental variables, see http://twil.io/secure\naccount_sid = ENV['TWILIO_ACCOUNT_SID']\nauth_token = ENV['TWILIO_AUTH_TOKEN']\n@client = Twilio::REST::Client.new(account_sid, auth_token)\n\n# Build task actions that say something and listens for a repsonse.\nhello_world_task_actions = {\n \"actions\" => [\n { \"say\": \"Hi there, I'm your virtual assistant! How can I help you?\" },\n { \"listen\": true }\n ]\n}\n\n# Create the hello_world task\n# Replace 'UAXXX...' with your Assistant's unique SID https://www.twilio.com/console/autopilot/list\ntask = @client.autopilot.assistants('UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')\n .tasks\n .create(\n unique_name: \"hello-world\",\n actions: hello_world_task_actions\n )\n\nputs \"Hello-world task has been created!\"\nputs task.sid\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2972938,"cells":{"blob_id":{"kind":"string","value":"dc048a66e078f93adb0e21533d99cb691f8fd371"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"jordansissel/experiments"},"path":{"kind":"string","value":"/ruby/octokit/migrate-issue.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":3235,"string":"3,235"},"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":"#!/usr/bin/env ruby\n# encoding: utf-8\n\nrequire \"clamp\"\nrequire_relative \"mixins/github\"\nrequire_relative \"mixins/logger\"\nrequire_relative \"mixins/cla\"\n\nclass GithubIssueMigrator < Clamp::Command\n include Mixin::GitHub\n include Mixin::Logger\n include Mixin::ElasticCLA\n\n parameter \"SOURCE\", \"The github issue to migrate.\"\n parameter \"DESTINATION\", \"The destination to migrate to\"\n\n def execute\n issue = github.issue(source_project, source_issue)\n if issue[:pull_request]\n migrate_pull(issue)\n else\n migrate_issue(issue)\n end\n end\n\n def migrate_issue(issue)\n annotated_body = \"(This issue was originally filed by @#{issue.user.login} at #{source})\\n\\n---\\n\\n\" + issue.body\n\n if issue.state == \"closed\"\n puts \"This issue is already closed. Nothing to migrate.\"\n return 1\n end\n\n # Create the new issue\n new_issue = github.create_issue(destination_project, issue.title, annotated_body)\n\n # Comment on the old issue about the migration, and close it.\n github.add_comment(source_project, source_issue, \"For Logstash 1.5.0, we've moved all plugins to individual repositories, so I have moved this issue to #{new_issue.html_url}. Let's continue the discussion there! :)\")\n github.close_issue(source_project, source_issue)\n\n puts \"Successfully migrated to: #{new_issue.html_url}\"\n nil\n end # def execute\n\n def migrate_pull(issue)\n if cla_uri.nil?\n puts \"Missing --cla-uri. Cannot migrate a PR without this.\"\n return 1\n end\n\n comment = <<-COMMENT\nFor Logstash 1.5.0, we've moved all plugins (and grok patterns) to individual repositories. Can you move this pull request to https://github.com/#{destination_project}?\n\nThis sequence of steps _may_ help you do this migration:\n\n1. Fork this repository\n2. Clone your fork\n\n ```shell\n git clone #{issue.user.html_url}/#{source_project.split(\"/\")[1]}.git\n ```\n\n3. Create a branch:\n\n ```shell\n git checkout -b my-branch-name\n ```\n\n4. Apply the patches from this PR into your branch:\n\n ```shell\n curl -s #{source}.patch | git am\n ```\n\n This should take your commits from this PR and commit them to your new local branch.\n\n5. Push!\n\n ```shell\n git push origin my-branch-name\n ```\n\n6. Open a new PR against https://github.com/#{destination_project}\n COMMENT\n\n cla_ok, cla_message = cla_status(source_project, source_issue, cla_uri)\n cla_message = cla_message[0,1].downcase + cla_message[1..-1]\n\n if !cla_ok\n comment << <<-COMMENT\n7. Sign the CLA\n\n Our CLA check indicates that #{cla_message}. See our [contributor agreement](http://www.elasticsearch.org/contributor-agreement/) for more details. :)\n COMMENT\n end\n\n github.add_comment(source_project, source_issue, comment)\n github.close_issue(source_project, source_issue)\n puts \"Added note to contributor for migration to #{destination_project}\"\n end\n\n def source_project\n @source_project ||= source.gsub(%r{^https?://github.com/}, \"\").gsub(%r{(issues|pull)/\\d+$}, \"\")\n end\n\n def source_issue\n @source_issue ||= source[/\\d+$/].to_i\n end\n\n def destination_project\n @destination_project ||= destination.gsub(%r{^https?://github.com/}, \"\")\n end\n\nend # class GithubIssueMigrator\n\nGithubIssueMigrator.run\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2972939,"cells":{"blob_id":{"kind":"string","value":"189706c51143988a519b4b309dd2095bc69fd0ab"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"hirataya/fatechan"},"path":{"kind":"string","value":"/lib/google_calc.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":718,"string":"718"},"score":{"kind":"number","value":2.84375,"string":"2.84375"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["BSD-2-Clause"],"string":"[\n \"BSD-2-Clause\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"require \"uri\"\nrequire \"cgi\"\nrequire \"open-uri\"\nrequire \"nokogiri\"\n\nmodule GoogleCalc\n def self.calc(expr, &block)\n uri = sprintf(\"http://www.google.com/search?hl=ja&q=%s\", CGI.escape(expr))\n #p uri\n\n result = nil\n open(uri, \"r:utf-8\", \"User-Agent\" => \"Mozilla/5.0\") do |fp|\n content = fp.read\n #p content\n doc = Nokogiri::HTML(content)\n result = doc.xpath(\"//h2[@class='r']\").first\n end\n\n return nil if not result\n\n #result = result.text\n result = result.inner_html\n result.gsub!(%r{(.*?)}) { \"^#{$1}\" }\n result.gsub!(%r{ }, \"\")\n result.strip!\n result.gsub!(/\\s{2,}/, \" \")\n\n block.call(result) if block\n result\n end\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2972940,"cells":{"blob_id":{"kind":"string","value":"a20133fe9d6b00be177d6c28e91a9df4606b22ea"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"tcrane20/AdvanceWarsEngine"},"path":{"kind":"string","value":"/Advance Wars Edit/Scripts_Old/[191]Sea.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":485,"string":"485"},"score":{"kind":"number","value":2.5625,"string":"2.5625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"class Sea < Tile\n def initialize\n super\n @name = 'sea'\n @id = TILE_SEA\n end\n \n def move_cost_chart(move_type)\n return case move_type \n when MOVE_FOOT then return [0]\n when MOVE_MECH then return [0]\n when MOVE_TIRE then return [0]\n when MOVE_TREAD then return [0]\n when MOVE_AIR then return [1,2]\n when MOVE_TRANS then return [1,2]\n when MOVE_SEA then return [1,2]\n when MOVE_TIRE_B then return [0]\n end\n end\nend"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2972941,"cells":{"blob_id":{"kind":"string","value":"44fa8a998fd2bedd52a5c0cd2c1433880fee6d78"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"rubenpazch/ruby-algorithms"},"path":{"kind":"string","value":"/strings/practice.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1135,"string":"1,135"},"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":"# p \"abcdef\" <=> \"abcde\" #=> 1\n# p \"abcdef\" <=> \"abcdef\" #=> 0\n# p \"abcdef\" <=> \"abcdefg\" #=> -1\n# p \"abcdef\" <=> \"ABCDEF\" #=> 1\n# p \"abcdef\" <=> 1 #=> nil\n\n# str1 = 'aa'\n# str2 = 'bb'\n# ar1 = str1.squeeze.each_char.to_a\n# ar2 = str2.squeeze.each_char.to_a\n#\n# p ar1 - ar2\n# p ar2 - ar1\n#\n## str1.each_char{|x| x - }\n#\n# p str1 <=> str2\n#\n# puts 3 / 2\n\n# #cantidadACambiar = 1211\n# cantidadACambiar = 1000\n# cantidadACambiar = 100\n# cantidadACambiar = 10\n# cantidadACambiar = 1\n# cantidadACambiar = 0\n# cantidadACambiar = 1123\ncantidadACambiar = 15\n\ndef totalBilletesMonedas(retirar)\n billete200 = 200.0\n\n arr = [100.0, 50.0, 20.0, 10.0, 5.0, 2.0, 1.0, 0.5, 0.2, 0.1]\n\n minimo = 0.0\n\n if retirar > billete200\n division = retirar / billete200\n residuo = retirar % billete200\n minimo += division\n else\n residuo = retirar\n end\n\n return minimo if residuo == 0.0\n\n i = 0\n while residuo != 0.0\n if residuo >= arr[i]\n division = residuo / arr[i]\n residuo = residuo % arr[i]\n minimo += division\n end\n i += 1\n end\n\n minimo\nend\n\np totalBilletesMonedas(cantidadACambiar)\n\ntest\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2972942,"cells":{"blob_id":{"kind":"string","value":"8ff2fc70915edfa5036c00ea783412436103f2c3"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"Chrispolanco/debugging-with-pry-online-web-prework"},"path":{"kind":"string","value":"/lib/pry_debugging.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":53,"string":"53"},"score":{"kind":"number","value":2.546875,"string":"2.546875"},"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 plus_two(num)\n\tnum + 2\n\tnew_total = num + 2 \n\tend"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2972943,"cells":{"blob_id":{"kind":"string","value":"c04a746ca13e22a7a5723f1b35cf6d9a68fc2136"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"vuhailuyen1991/rails"},"path":{"kind":"string","value":"/activesupport/lib/active_support/core_ext/date_and_time/compatibility.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":601,"string":"601"},"score":{"kind":"number","value":2.640625,"string":"2.640625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT","Ruby"],"string":"[\n \"MIT\",\n \"Ruby\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"module DateAndTime\n module Compatibility\n # If true, +to_time+ preserves the the timezone offset.\n #\n # NOTE: With Ruby 2.4+ the default for +to_time+ changed from\n # converting to the local system time to preserving the offset\n # of the receiver. For backwards compatibility we're overriding\n # this behavior but new apps will have an initializer that sets\n # this to true because the new behavior is preferred.\n mattr_accessor(:preserve_timezone, instance_writer: false) { false }\n\n def to_time\n preserve_timezone ? getlocal(utc_offset) : getlocal\n end\n end\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2972944,"cells":{"blob_id":{"kind":"string","value":"6d99066e7787e4dc54923f4ed69a22b4e6192fc8"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"sbasnyat/cosi166b"},"path":{"kind":"string","value":"/PA2/MovieData.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":6995,"string":"6,995"},"score":{"kind":"number","value":3.359375,"string":"3.359375"},"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 MovieData\n\n\t# constructor, if one parameter is passed, it takes path to the folder containing the movie data,\n\t# optionally if two arguments are passed, the first is taken as path to folder and second symbol to specify a particular training/test pair \n\tdef initialize(*args)\n\t\ttrain_test_h = {:u1 => [\"u1.base\",\"u1.test\"], \n\t\t\t\t\t\t:u2 => [\"u2.base\",\"u2.test\"],\n\t\t\t\t\t\t:u3 => [\"u3.base\",\"u3.test\"],\n\t\t\t\t\t\t:u4 => [\"u4.base\",\"u4.test\"],\n\t\t\t\t\t\t:u5 => [\"u5.base\",\"u5.test\"],\n\t\t\t\t\t\t:ua => [\"ua.base\",\"ua.test\"],\n\t\t\t\t\t\t:ub => [\"ub.base\",\"ub.test\"] }\n\t\tfoldername = args[0]\n\n\t\t# @train_umr_h stands for training user movie rating hash and is a hash table that stores each line of data of training set in the form user_id as key and its \n\t\t# value is another hash table with key movie id and value rating\n\t\t# @train_mur_h stands for training movie user rating hash and is a hash table that stores each line of data in the training set in the form movie-id as key and its \n\t\t# value is another hash table with key user_id and value rating\n\t\t# @test_umr_arr stands for test user movie rating array and is 2D array i.e. an array of arrays in the form [user_id, movie_id, rating] for each line of test data\n\n\t\tif args.length == 1\n\t\t\ttrain_filename = File.join(foldername,\"u.data\")\n\t\t\t@test_umr_arr = nil\n\t\telse\n\t\t\ttrain_test_pair = train_test_h[args[1]]\n\t\t\ttrain_filename = File.join(foldername,train_test_pair[0])\n\t\t\ttest_filename = File.join(foldername,train_test_pair[1])\n\t\t\t@test_umr_arr = load_test(test_filename)\n\t\tend\n\n\t\t@train_umr_h, @train_mur_h = load_train(train_filename)\n\tend\n\n\t# this method reads the training dataset line by line, stores it in two hash table forms and returns the two hash tables\n\tdef load_train(train_filename)\n\t\ttrain_data = open(train_filename).read\n\t\t\n\t\tumr_h = Hash.new\n\t\tmur_h = Hash.new\n\n\t\ttrain_data.each_line do |line|\n\t\t\tdata = line.split(\" \")\n\t\t\tuser_id = data[0].to_i\n\t\t\tmovie_id = data[1].to_i\n\t\t\trate = data[2].to_i\n\n\t\t\t# for a particular key, it checks if it exists, if not creates a new hash table at that key\n\t\t\tif !umr_h.has_key?(user_id)\n\t\t\t\tumr_h[user_id] = Hash.new\n\t\t\tend\n\n\t\t\tumr_h [user_id] [movie_id] = rate\n\n\t\t\t# for a particular key, it checks if it exists, if not creates a new hash table at that key\n\t\t\tif !mur_h.has_key?(movie_id)\n\t\t\t\tmur_h[movie_id] = Hash.new\n\t\t\tend\n\n\t\t\tmur_h [movie_id][user_id] = rate\n\t\tend\n\n\t\treturn umr_h, mur_h\n\tend\n\n\t# this method reads the test dataset and stores each line in a 2D array i.e an array of arrays in the form [user_id, movie_id, rating] and returns it\n\tdef load_test(test_filename)\n\t\ttest_data = open(test_filename).read\n\t\tumr_arr = Array.new\n\t\ttest_data.each_line do |line|\n\t\t\tdata=line.split(\" \")\n\t\t\tuser_id=data[0].to_i\n\t\t\tmovie_id=data[1].to_i\n\t\t\trate=data[2].to_i\n\t\t\tumr_arr.push([user_id, movie_id, rate])\n\t\tend\n\t\treturn umr_arr\n\tend\n\n\t# this method returns the rating that user u gave movie m in the training set, and 0 if user u did not rate movie m\n\tdef rating(u,m) \n\n\t\tif @train_umr_h.has_key?(u) && @train_umr_h[u].has_key?(m) \n\t\t\t\treturn @train_umr_h[u][m]\n\t\telse\n\t\t\treturn 0\n\t\tend\n\n\tend\n\n\t# this method returns the array of movies that user u has watched and 0 if the user id cannot be found in the dataset\n\tdef movies(u)\n\n\t\tif @train_umr_h.has_key?(u)\n\t\t\treturn @train_umr_h[u].keys\n\t\telse\n\t\t\treturn 0\n\t\tend\n\n\tend\n\n\t# this method returns the array of users that have seen movie m and 0 if the movie id cannot be found in the dataset\n\tdef viewers(m)\n\n\t\tif @train_mur_h.has_key?(m)\n\t\t\treturn @train_mur_h[m].keys\n\t\telse\n\t\t\treturn 0\n\t\tend\n\n\tend\n\n\t# this method returns a floating point number between 1.0 and 5.0 as an estimate of what user u would rate movie m\n\t# prediction algorithm sees 10 the users who have watched the movie and checks which of them have watched the most \n\t# common movies among the first 20 movies watched by the users with user u, and then returns the rating the user gave the movie m \n\tdef predict(u,m)\n\t\thash=Hash.new\n\t\tviewers_m = viewers(m)\n\t\tmovies_u = movies(u)\n\n\t\tif (viewers_m == 0 || viewers_m.length < 20) && (movies_u == 0 || movies_u.length < 20)\n\t\t\treturn 0\n\t\telsif viewers_m == 0 || viewers_m.length < 20 \n\t\t\tsum = 0\n\t\t\tmovies(u)[0..29].each do |mov|\n\t\t\t\tsum += rating(u,mov)\n\t\t\tend\n\t\t\treturn sum/20\n\t\telse\n\t\t\tten_viewers=Array.new(viewers_m[0..9])\n\n\t\t\tten_viewers.each do |user|\n\t\t\t\n\t\t\t\tif user!=u && movies(user).length >= 50\n\t\t\t\t\tnum_common_movies=(movies_u & movies(user)[0..49]).length\n\t\t\t\t\thash[num_common_movies]=user\n\t\t\t\tend\n\n\t\t\tend \n\n\t\t#finds the user out of the viewers who has the maximum number of movies watched in common with our user u and returns the rating that user gave to movie m\n\t\t\treturn rating(hash[hash.keys.max],m)\n\t\tend\n\n\tend\n\n\t# runs the predict method on the first something number of ratings in the test set as specified in the parameter and returns a MovieTest object containing the results.\n\t# If the parameter is omitted, all of the tests will be run.\n\tdef run_test(*args)\n\n\t\tif args.length == 1\n\t\t\tk = args[0]\n\t\t\tratinglist=Array.new(@test_umr_arr[0...k])\n\t\telse\n\t\t\tratinglist=Array.new(@test_umr_arr)\n\t\tend\n\n\t\t# now finds the prediction rating from the predict function and pushes it into the array \n\t\tratinglist.each do |line|\t\t\n \t\t\tpredicted= predict(line[0],line[1])\n\t\t\tline.push(predicted)\n \t\tend\n\n \t\t# creates an instance of class MovieTest and passes the ratinglist as parameter\t\n \t\treturn MovieTest.new(ratinglist)\n\tend\n\nend\n\n\nclass MovieTest\n\n\t# takes ratinglist i.e. an array of arrays with each element in the form [user_id, movie_id, rating, predicted rating]\n\t# @error is an array whoese elements are the difference between predicted rating and actual rating for each element on the ratinglist \n\tdef initialize(ratinglist)\n\t\t@ratinglist=ratinglist\n\t\t@error=find_error\n\t\t@length=ratinglist.length\n\tend\t\n\n\t# this method goes through each element of the rating list i.e. each array and finds the difference between the actual and \n\t# predicted rating for each and stores the value in an array and returns it\n\tdef find_error\n\t\terror=[]\n\n\t\t\t@ratinglist.each do |result|\n\t\t\t\terror.push((result[2]-result[3]).abs)\n\t\t\tend\n\n\t\treturn error\n\tend\t\n\n\n\t# this method returns the average predication error\n\tdef mean\n\t\tsumm = @error.inject(0) {|sum, i| sum + i }\n\t\treturn (summ.to_f/@length)\n\tend\n\n\t# this method returns the standard deviation of the error\n\tdef stddev\n\t\tmean_ = mean\n\t\tsum=0\n\n\t\t@error.each do |error|\n\t\t\tsum += ((error - mean_ ) ** 2)\n\t\tend\n\n\t\treturn Math.sqrt(sum.to_f/@length)\n\tend\n\n\t# this method returns the root mean square error of the prediction\n\tdef rms\n\t\tsum=0\n\n\t\t@error.each do |error|\n\t\t\tsum += (error) ** 2\n\t\tend\n\n\t\treturn Math.sqrt(sum.to_f/@length)\n\tend\n\n\t# this method returns an array of the predictions in the form [u,m,r,p].\n\tdef to_a\n\t\tprint @ratinglist\n\t\tputs\n\tend\n\t\t\t\n\nend\n\n\n\n\n\nobj=MovieData.new(\"ml-100k\", :u2)\n\n#puts obj.similarity(1,126)\n#puts obj.most_similar(1)\n\n\n#puts obj.viewers(100)\n\n#t=obj.run_test(2500)\n#puts t.mean\n#puts t.stddev\n#puts t.rms\n#t.to_a\n#puts t.rms\n\n\n\n\n\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2972945,"cells":{"blob_id":{"kind":"string","value":"784cddaa14b24afa3245d7908e6aaad22e17de9e"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"higepon/misc"},"path":{"kind":"string","value":"/count-and-say.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":507,"string":"507"},"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":"# @param {Integer} n\n# @return {String}\ndef count_and_say(n)\n if n == 1\n return \"1\"\n end\n prev = count_and_say(n - 1)\n ret = ''\n currentVal = 0\n num = 0\n for i in 0...prev.size\n ch = prev[i]\n if num == 0\n currentVal = ch\n num = 1\n elsif ch == currentVal\n num = num + 1\n else\n ret = \"#{ret}#{num}#{currentVal}\"\n num = 1\n currentVal = ch\n end\n if i == prev.size - 1\n ret = \"#{ret}#{num}#{currentVal}\"\n num = 0\n end\n end\n return ret\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2972946,"cells":{"blob_id":{"kind":"string","value":"291f200ff99145d88b75bbab9dd6a581f73fed95"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"sogbdn/ar-exercises"},"path":{"kind":"string","value":"/exercises/exercise_7.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":430,"string":"430"},"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 '../setup'\nrequire_relative './exercise_1'\nrequire_relative './exercise_2'\nrequire_relative './exercise_3'\nrequire_relative './exercise_4'\nrequire_relative './exercise_5'\nrequire_relative './exercise_6'\n\nputs \"Exercise 7\"\nputs \"----------\"\n\n# Ask the user for a store name (store it in a variable)\n\nputs \"What is your store's name?\"\na = gets.chomp\n\nstore = Store.create(name: a)\n\nputs store.errors.full_messages\n\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2972947,"cells":{"blob_id":{"kind":"string","value":"ce0c2d6b1bff6d2d664dfd0a64711a0346788692"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"gotar/internship_day_V"},"path":{"kind":"string","value":"/lib/model/product.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":239,"string":"239"},"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":"module Shop\n class Product\n attr_reader :id, :name, :price\n\n @@id = 0\n\n def initialize(name, price)\n @id = set_id\n @name = name\n @price = price\n end\n\n private\n def set_id\n @@id += 1\n end\n end\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2972948,"cells":{"blob_id":{"kind":"string","value":"b0a7fbb32fb5c86b85e032fe4ad5a5022e29ba9d"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"toshichanapp/projecteuler"},"path":{"kind":"string","value":"/1-10/problem5.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":195,"string":"195"},"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":"require 'prime'\n(1..20).map {|num| Prime.prime_division(num)}.flatten.each_slice(2).group_by{|arr| arr[0]}.map do |_, arr|\n arr.max_by{|nums| nums[1] }\nend.map do |a, b|\n a ** b\nend.reduce(:*)\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2972949,"cells":{"blob_id":{"kind":"string","value":"95b00a42ea438f4979db6b3d5da53f7d4a09b10a"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"masayuki038/chienowa"},"path":{"kind":"string","value":"/app/helpers/stars_helper.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":140,"string":"140"},"score":{"kind":"number","value":2.53125,"string":"2.53125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"module StarsHelper\n def starred?(stars)\n stars.each do |star|\n return true if current_user?(star.user)\n end\n false\n end\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2972950,"cells":{"blob_id":{"kind":"string","value":"194a25cbe0080c2db9109579d313ce0fb8f3f7d7"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"pamungkaski/Malkist-Ruby"},"path":{"kind":"string","value":"/spec/malkist_spec.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":3166,"string":"3,166"},"score":{"kind":"number","value":2.59375,"string":"2.59375"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"# frozen_string_literal: true\n\nRSpec.describe Malkist do\n it 'has a version number' do\n expect(Malkist::VERSION).not_to be nil\n end\n\n it 'return distance between two coordinate' do\n result = Malkist.calculate_distance(%w[40.6655101,-73.89188969999998], %w[40.6905615,-73.9976592])\n expect(result[0].distance).to eq(10423)\n end\n\n it 'return distance between one origin with many destinations' do\n result = Malkist.calculate_distance(%w[40.6655101,-73.89188969999998], %w[40.6905615,-73.9976592 40.8905615,-73.9976592 40.7905615,-73.9976592])\n expect(result[0].distance).to eq(10423)\n expect(result.length).to eq(3)\n end\n\n it 'return distance between many origin with one destinations' do\n result = Malkist.calculate_distance(%w[40.6655101,-73.89188969999998 40.6855101,-73.89188969999998 40.6255101,-73.89188969999998], %w[40.6905615,-73.9976592])\n expect(result[0].distance).to eq(10423)\n expect(result.length).to eq(3)\n end\n\n it 'return distance between many origin with one destinations' do\n result = Malkist.calculate_distance(%w[40.6655101,-73.89188969999998 40.6855101,-73.89188969999998 40.6255101,-73.89188969999998], %w[40.6905615,-73.9976592 40.8905615,-73.9976592 40.7905615,-73.9976592])\n expect(result[0].distance).to eq(10423)\n expect(result.length).to eq(9)\n end\nend\n\nRSpec.describe Malkist::Distances do\n it 'return distance between two coordinate' do\n distances = Malkist::Distances.new(%w[40.6655101,-73.89188969999998], %w[40.6905615,-73.9976592])\n result = distances.calculate_distance\n expect(result[0].distance).to eq(10423)\n end\n\n it 'return distance between one origin with many destinations' do\n distances = Malkist::Distances.new(%w[40.6655101,-73.89188969999998], %w[40.6905615,-73.9976592 40.8905615,-73.9976592 40.7905615,-73.9976592])\n result = distances.calculate_distance\n expect(result[0].distance).to eq(10423)\n expect(result.length).to eq(3)\n end\n\n it 'return distance between many origin with one destinations' do\n distances = Malkist::Distances.new(%w[40.6655101,-73.89188969999998 40.6855101,-73.89188969999998 40.6255101,-73.89188969999998], %w[40.6905615,-73.9976592])\n result = distances.calculate_distance\n expect(result[0].distance).to eq(10423)\n expect(result.length).to eq(3)\n end\n\n it 'return distance between many origin with one destinations' do\n distances = Malkist::Distances.new(%w[40.6655101,-73.89188969999998 40.6855101,-73.89188969999998 40.6255101,-73.89188969999998], %w[40.6905615,-73.9976592 40.8905615,-73.9976592 40.7905615,-73.9976592])\n result = distances.calculate_distance\n expect(result[0].distance).to eq(10423)\n expect(result.length).to eq(9)\n end\nend\n\nRSpec.describe Malkist::Distances::Distance do\n it 'return the assigned value upon initialization' do\n distance = Malkist::Distances::Distance.new('oRigiNaslz Addrewses', 'dWesttwinattizion Addrewses', 65123, 1235123)\n expect(distance.origin).to eq('oRigiNaslz Addrewses')\n expect(distance.destination).to eq('dWesttwinattizion Addrewses')\n expect(distance.distance).to eq(65123)\n expect(distance.duration).to eq(1235123)\n end\nend"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2972951,"cells":{"blob_id":{"kind":"string","value":"4ceee98fb56d597ffc2a8385e07adf7f32a2826d"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"kennyfrc/launch_school"},"path":{"kind":"string","value":"/130/anagram.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1197,"string":"1,197"},"score":{"kind":"number","value":4,"string":"4"},"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":"# 04/23/16 - Challenge: Anagrams\nclass Anagram\n attr_reader :detector\n\n def initialize(detector)\n @detector = detector\n end\n\n def match(array_of_words)\n filtered_words = array_of_words.map(&:downcase).select do |word|\n word.chars.all? do |chars|\n detector_letters.include?(chars)\n end && pass_anagram_checker?(word)\n end\n return filtered_words.map(&:capitalize) if capitalized?(detector)\n filtered_words\n end\n\n private\n\n def pass_anagram_checker?(arr)\n same_size_as_detector?(arr) && same_char_count_as_detector?(arr) && not_self?(arr)\n end\n\n def capitalized?(detector)\n capitalized_detector = detector.downcase.capitalize\n capitalized_detector == detector\n end\n\n def size(arr)\n arr.chars.size\n end\n\n def detector_letters\n detector.downcase.chars\n end\n\n def chars_of(str)\n hash_of_letters = Hash.new(0)\n str.chars.each do |letter|\n hash_of_letters[letter] += 1\n end\n hash_of_letters\n end\n\n def same_char_count_as_detector?(arr)\n chars_of(arr) == chars_of(detector.downcase)\n end\n\n def same_size_as_detector?(arr)\n size(arr) == detector.size\n end\n\n def not_self?(arr)\n arr != detector.downcase\n end\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2972952,"cells":{"blob_id":{"kind":"string","value":"21ef2d477d190f1f0989bcb0d5264d9c5793350e"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"sksamal/omnetpp-5.0"},"path":{"kind":"string","value":"/samples/FatTree/simulations/createIniBorderExp.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1226,"string":"1,226"},"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":"# Generating experiment inis\n\n#Execute with ruby createIniBorderExp.rb\n\ndata = File.readlines(\"inputBorders.ini\")\n\nupper = [10, 20, 40, 60, 80, 160]\nlower = [5,\t10,\t20,\t30,\t40,\t80]\nlower2 = [3, 5, 10, 15, 20, 40]\nrepeats = (1..5).to_a\n\nupper.zip(lower).each do |upper, lower|\n repeats.each do |i|\n data_temp = data.dup\n data_temp.map! {|line| line.gsub(/%SEED%/, \"#{i}\")}\n data_temp.map! {|line| line.gsub(/%LOW%/, \"#{lower}\")}\n data_temp.map! {|line| line.gsub(/%UP%/, \"#{upper}\")}\n name_temp = \"#{upper}-#{lower}-#{i}\"\n filename = \"border#{name_temp}.ini\"\n File.open(filename, \"a\") {|f| f.puts data_temp}\n puts \"Created #{filename} with borders up: #{upper}, low: #{lower}, seed: #{i}.\"\n end\nend\n\n=begin\nupper.zip(lower2).each do |upper, lower|\n repeats.each do |i|\n data_temp = data.dup\n data_temp.map! {|line| line.gsub(/%SEED%/, \"#{i}\")}\n data_temp.map! {|line| line.gsub(/%LOW%/, \"#{lower}\")}\n data_temp.map! {|line| line.gsub(/%UP%/, \"#{upper}\")}\n name_temp = \"#{upper}-#{lower}-#{i}\"\n filename = \"border#{name_temp}.ini\"\n File.open(filename, \"a\") {|f| f.puts data_temp}\n puts \"Created #{filename} with borders up: #{upper}, low: #{lower}, seed: #{i}.\"\n end\nend\n=end\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2972953,"cells":{"blob_id":{"kind":"string","value":"bdd6ee448b1dfae8533e0454f61b12702c51b7b9"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"kbehnfeldt/RB101"},"path":{"kind":"string","value":"/rb101-lesson4/Loops1/exercise6.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":76,"string":"76"},"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":"number = []\n\nwhile number.length < 5 \n number << rand(100)\nend\n\nputs number"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2972954,"cells":{"blob_id":{"kind":"string","value":"30b98fcc700dffac0c65bfc92cc84df8af8ad865"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"ric2b/learning_ruby"},"path":{"kind":"string","value":"/ruby/hamming/hamming.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":194,"string":"194"},"score":{"kind":"number","value":3.546875,"string":"3.546875"},"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 Hamming\n def self.compute(string_a, string_b)\n raise ArgumentError if string_a.length != string_b.length\n string_a.chars.zip(string_b.chars).map{|a, b| a != b ? 1 : 0}.sum\n end\nend"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2972955,"cells":{"blob_id":{"kind":"string","value":"091d14e988ba41047519cc89e48d9b15b979ea6c"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"btazi/rbnd-toycity-part4"},"path":{"kind":"string","value":"/lib/analyzable.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":891,"string":"891"},"score":{"kind":"number","value":3.09375,"string":"3.09375"},"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 Analyzable\n # Your code goes here!\n\tdef average_price(products)\n\t\taverage = products.map(&:price).map(&:to_f).reduce(:+)/products.length\n\t\taverage.round(2)\n\tend\n\n\tdef print_report(products)\n\t\treport = \"\"\n\t\tproducts.each do |product|\n\t\t\treport += \"#{product.name}, brand: #{product.brand}, price: #{product.price} \\n\"\n\t\tend\n\t\treport\n\tend\n\n\tdef create_count_by_methods(*attributes)\n\t\tattributes.each do |attr|\n\t\t\tself.class_eval %{def self.count_by_#{attr}(arg)\n\t\t\tcounts = {} \n\t\t\t\targ.map(&:#{attr}).each do |#{attr}_value|\n\t\t\t\t\tcounts[#{attr}_value] = Product.where(#{attr}: #{attr}_value).count \n\t\t\t\tend\n\t\t\t\tcounts\n\t\t\tend}\n\t\tend\n\tend\n\n\tdef self.method_missing(method_name, arguments)\n\t\tif method_name.to_s.start_with?(\"count_by\")\n\t\t\tattribute = method_name.to_s.gsub!(\"count_by_\", \"\")\n\t\t\tcreate_count_by_methods(attribute)\n\t\t\tself.public_send(method_name, arguments)\n\t\tend\n\tend\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2972956,"cells":{"blob_id":{"kind":"string","value":"542558846983f977142894603c5554457c5257e7"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"roodi/roodi"},"path":{"kind":"string","value":"/lib/roodi/checks/abc_metric_method_check.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2015,"string":"2,015"},"score":{"kind":"number","value":3.140625,"string":"3.140625"},"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 'roodi/checks/check'\n\nmodule Roodi\n module Checks\n # The ABC metric method check calculates the number of Assignments,\n # Branches and Conditionals in your code. It is similar to\n # cyclomatic complexity, so the lower the better.\n class AbcMetricMethodCheck < Check\n ASSIGNMENTS = [:lasgn]\n BRANCHES = [:vcall, :call]\n CONDITIONS = [:==, :\"!=\", :<=, :>=, :<, :>]\n OPERATORS = [:*, :/, :%, :+, :<<, :>>, :&, :|, :^]\n DEFAULT_SCORE = 10\n\n attr_accessor :score\n\n def initialize\n super()\n self.score = DEFAULT_SCORE\n end\n\n def interesting_nodes\n [:defn]\n end\n\n def evaluate_start(node)\n method_name = node[1]\n a = count_assignments(node)\n b = count_branches(node)\n c = count_conditionals(node)\n score = Math.sqrt(a*a + b*b + c*c)\n add_error \"Method name \\\"#{method_name}\\\" has an ABC metric score of <#{a},#{b},#{c}> = #{score}. It should be #{@score} or less.\" unless score <= @score\n end\n\n private\n\n def count_assignments(node)\n count = assignment?(node) ? 1 : 0\n node.children.each {|child_node| count += count_assignments(child_node)}\n count\n end\n\n def count_branches(node)\n count = branch?(node) ? 1 : 0\n node.children.each {|child_node| count += count_branches(child_node)}\n count\n end\n\n def count_conditionals(node)\n count = conditional?(node) ? 1 : 0\n node.children.each {|child_node| count += count_conditionals(child_node)}\n count\n end\n\n def assignment?(node)\n ASSIGNMENTS.include?(node.node_type)\n end\n\n def branch?(node)\n BRANCHES.include?(node.node_type) && !conditional?(node) && !operator?(node)\n end\n\n def conditional?(node)\n (:call == node.node_type) && CONDITIONS.include?(node[2])\n end\n\n def operator?(node)\n (:call == node.node_type) && OPERATORS.include?(node[2])\n end\n end\n end\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2972957,"cells":{"blob_id":{"kind":"string","value":"c303c31408aa672ed882d6950b428899282d7b93"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"jcquarto/everything-is-a-object-or-method"},"path":{"kind":"string","value":"/object_test2.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":110,"string":"110"},"score":{"kind":"number","value":3.171875,"string":"3.171875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"# works with classes too!\n\nclass Cat\nend\n\nputs Cat.class\n\nputs Cat.new.class\n\ncato = Cat.new\nputs cato.class\n\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2972958,"cells":{"blob_id":{"kind":"string","value":"104b1567e4d48ca27aa73a2f6510dd5769ca7fc1"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"magic8baller/the-bachelor-todo-prework"},"path":{"kind":"string","value":"/lib/bachelor.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1482,"string":"1,482"},"score":{"kind":"number","value":3.828125,"string":"3.828125"},"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":"#require 'pry'\n\ndef get_first_name_of_season_winner(data, season)\n data[season].each do |contestant_hash| # {'name'=>'Tessa H'..,}\n if contestant_hash['status'] == 'Winner'\n return contestant_hash['name'].split.first\n #split name into 2 strings, return first name\n end\n end\nend\n\n\ndef get_contestant_name(data, occupation)\n data.each do |season, contestant_array| # 'season ', [{..},{..},..]\n contestant_array.each do |contestant_hash| #{'name'=>'Ashley..',}\n if contestant_hash['occupation'] == occupation\n return contestant_hash['name']\n end\n end\n end\nend\n\n\ndef count_contestants_by_hometown(data, hometown)\n count = 0\n data.each do |season, contestant_array|\n contestant_array.each do |contestant_hash|\n if contestant_hash['hometown'] == hometown #if hometown matches parameter\n count += 1 #count it\n end\n end\n end\n count\nend\n\n\ndef get_occupation(data, hometown)\n data.each do |season, contestant_array|\n contestant_array.each do |contestant_hash|\n if contestant_hash['hometown'] == hometown\n return contestant_hash['occupation']\n end\n end\n end\nend\n\n\ndef get_average_age_for_season(data, season)\n contestant_count = 0\n total_ages = 0\n data[season].each do |contestant_hash|\n total_ages += contestant_hash['age'].to_f #float number => perform average w/ decimals\n contestant_count += 1\n\n end\n (total_ages/contestant_count).round #from decimal can accurately round average\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2972959,"cells":{"blob_id":{"kind":"string","value":"978e0b3723d87a83c9b7357b026b6b9f3e8e3461"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"itsolutionscorp/AutoStyle-Clustering"},"path":{"kind":"string","value":"/all_data/exercism_data/ruby/binary/309c0a008dd847918cd61c14010c5f45.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":357,"string":"357"},"score":{"kind":"number","value":3.8125,"string":"3.8125"},"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 Binary\n attr_reader :value\n\n def initialize(value)\n @value = value\n end\n\n def to_decimal\n return 0 unless is_decimal?\n\n chars.each_with_index\n .map { |digit, index| digit.to_i * (2 ** index) }\n .inject(&:+)\n end\n\n private\n\n def chars\n value.reverse.each_char\n end\n\n def is_decimal?\n value.match(/^(0|1)+$/)\n end\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2972960,"cells":{"blob_id":{"kind":"string","value":"dfa258b68b1e8e530a1b76762c9461b6a435406d"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"ajemobile/big"},"path":{"kind":"string","value":"/lib/bigmagic/database_object.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":634,"string":"634"},"score":{"kind":"number","value":2.859375,"string":"2.859375"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"module Bigmagic\n\n class DatabaseObject\n\n def eigen_class\n class << self\n self\n end\n end\n\n def add_instance_variables(argv)\n hash = {}\n if argv.kind_of?(Hash)\n hash = argv\n elsif argv.kind_of?(Array)\n argv.map! {|item| item.to_s.to_sym}\n hash = Hash[*argv.zip(Array.new(argv.size)).flatten]\n elsif argv.nil?\n return nil\n else\n raise \"invalid argument! Use a Hash or Array argument\"\n end\n hash.each_pair do |key,value|\n eigen_class.send :attr_accessor, key.to_sym\n send(\"#{key}=\".to_sym, value)\n end\n end\n\n end\n\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2972961,"cells":{"blob_id":{"kind":"string","value":"3a0ac8d9f7e32e0792c7b6f472ab3c5f24d64040"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"sans-pulp/ruby-exercises"},"path":{"kind":"string","value":"/ruby_basics/3_conditionals/string_caps.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":332,"string":"332"},"score":{"kind":"number","value":4.40625,"string":"4.40625"},"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":"# Write a method that takes a string as an argument and returns a new all caps version of the string only if the string is longer than 10 characters\n\ndef upcase_long_string(string)\n string.length > 10 ? string.upcase : string\n # if string.length > 10\n # string.upcase\n # end\nend\n\nputs upcase_long_string('This is interesting')"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2972962,"cells":{"blob_id":{"kind":"string","value":"d6a787429ce11e7b7ed18d6ba4a7041600de7109"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"mkaushish/quizsite"},"path":{"kind":"string","value":"/lib/QuestionGenerator/trig.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2422,"string":"2,422"},"score":{"kind":"number","value":3.21875,"string":"3.21875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"#!/usr/bin/env ruby\nrequire_relative 'questionbase'\nrequire_relative 'tohtml'\ninclude \"Math.rb\"\n\n\nPYTHTRIP=[[3,4,5],[5,12,13],[7,24,25],[8,15,17]]\nORD=[\"a\",\"o\",\"h\"]\nPYTH=[[1,1,Math.sqrt(2)], [1,Math.sqrt(3),2]]\nTRIGF=[\"sin\", \"cos\", \"tan\", \"cot\", \"cosec\", \"sec\"]\nTRIGDEF={\"sin\" => [\"o\",\"h\"], \"cos\" => [\"a\",\"h\"], \"tan\" => [\"o\",\"a\"], \"cot\" => [\"a\",\"o\"], \"cosec\" => [\"h\",\"o\"], \"sec\" => [\"h\",\"a\"]}\n\n\nmodule Trig\n class RatiosMissingSide\n def initialize\n trip=PYTHTRIP.sample\n mult=rand(3)+1\n for i in 0...trip.length\n trip[i]=trip[i]*mult\n end\n @fun=TRIGF.sample\n @trip={\"a\" => trip[0],\n \"o\" => trip[1],\n \"h\" => trip[2]}\n @whmis=TRIGDEF[@fun].sample\n end\n def solve\n rat=Rational(@trip[TRIGDEF[@fun][0]], @trip[TRIGDEF[@fun][1]])\n return {\"num\" => rat.numerator, \n \"den\" => rat.denominator}\n end\n def text\n txt=\"In a triangle ABC, right angled at B\"\n txt+=\", AB is of length #{@trip[\"a\"]} \" if @whmis != \"a\"\n if @whmis == \"h\"\n txt+=\"and \"\n else txt+=\", \"\n end\n txt+=\"BC is of length #{@trip[\"o\"]}\" if @whmis != \"o\"\n txt+=\" and CA is of length #{@trip[\"h\"]}\" if @whmis != \"h\"\n txt+=\". What is the value of #{@fun}(A) in its lowest form?\"\n [TextLabel.new(txt), Fraction.new(\"num\", \"den\")]\n end\n end\n class RatioGivenOther\n def initialize\n trip=PYTHTRIP.sample\n @orig=TRIGF.sample\n @fin=TRIGF.sample\n while @fin==@orig\n @fin=TRIGF.sample\n end\n mult=rand(3)+1\n for i in 0...trip.length\n trip[i]=trip[i]*mult\n end\n @trip={\"a\" => trip[0],\n \"o\" => trip[1],\n \"h\" => trip[2]}\n end\n def solve\n rat=Rational(@trip[TRIGDEF[@fin][0]], @trip[TRIGDEF[@fin][1]])\n return {\"num\" => rat.numerator, \n \"den\" => rat.denominator}\n end\n def text\n [TextLabel.new(\"In a triangle ABC, right angled at B, #{@orig}(A)=#{Fraction.new(@trip(TRIGDEF[@orig][0]), @trip(TRIGDEF[@orig][1]))}. What is the value of #{@fin}(A) in its lowest form?\"), Fraction.new(\"num\", \"den\")]\n end\n end\n class RatiosUsingId\n def initialize\n @fun=TRIGF.sample\n @ang=rand(85)+3\n end\n def solve\n \n end\n def text\n [TextLabel.new(\"Find the value of #{Fraction.new(\"sin(#{@ang})\", \"sin(#{90-@ang})\")} using identities\"), TextField.new(\"ans\")]\n end\n end\nend\n\n\n\n\n\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2972963,"cells":{"blob_id":{"kind":"string","value":"e2772763f491343e97a06dc05dbdb571757704a5"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"QPC-WORLDWIDE/rubinius"},"path":{"kind":"string","value":"/kernel/common/eval.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":3392,"string":"3,392"},"score":{"kind":"number","value":2.765625,"string":"2.765625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["BSD-3-Clause","LicenseRef-scancode-unknown-license-reference"],"string":"[\n \"BSD-3-Clause\",\n \"LicenseRef-scancode-unknown-license-reference\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"module Kernel\n\n # Names of local variables at point of call (including evaled)\n #\n def local_variables\n locals = []\n\n scope = Rubinius::VariableScope.of_sender\n\n # Ascend up through all applicable blocks to get all vars.\n while scope\n if scope.method.local_names\n scope.method.local_names.each do |name|\n name = name.to_s\n locals << name\n end\n end\n\n # the names of dynamic locals is now handled by the compiler\n # and thusly local_names has them.\n\n scope = scope.parent\n end\n\n locals\n end\n module_function :local_variables\n\n # Obtain binding here for future evaluation/execution context.\n #\n def binding\n return Binding.setup(\n Rubinius::VariableScope.of_sender,\n Rubinius::CompiledMethod.of_sender,\n Rubinius::StaticScope.of_sender,\n self)\n end\n module_function :binding\n\n # Evaluate and execute code given in the String.\n #\n def eval(string, binding=nil, filename=nil, lineno=1)\n filename = StringValue(filename) if filename\n lineno = Type.coerce_to lineno, Fixnum, :to_i\n\n if binding\n if binding.kind_of? Proc\n binding = binding.binding\n elsif binding.respond_to? :to_binding\n binding = binding.to_binding\n end\n\n unless binding.kind_of? Binding\n raise ArgumentError, \"unknown type of binding\"\n end\n\n filename ||= binding.static_scope.active_path\n else\n binding = Binding.setup(Rubinius::VariableScope.of_sender,\n Rubinius::CompiledMethod.of_sender,\n Rubinius::StaticScope.of_sender,\n self)\n\n filename ||= \"(eval)\"\n end\n\n binding.static_scope = binding.static_scope.dup\n\n be = Rubinius::Compiler.construct_block string, binding,\n filename, lineno\n\n be.set_eval_binding binding\n\n be.call_on_instance(binding.self)\n end\n module_function :eval\n private :eval\nend\n\nclass Module\n\n #--\n # These have to be aliases, not methods that call instance eval, because we\n # need to pull in the binding of the person that calls them, not the\n # intermediate binding.\n #++\n\n def module_eval(string=undefined, filename=\"(eval)\", line=1, &prc)\n # we have a custom version with the prc, rather than using instance_exec\n # so that we can setup the StaticScope properly.\n if prc\n unless string.equal?(undefined)\n raise ArgumentError, \"cannot pass both string and proc\"\n end\n\n # Return a copy of the BlockEnvironment with the receiver set to self\n env = prc.block\n static_scope = env.repoint_scope self\n return env.call_under(self, static_scope, self)\n elsif string.equal?(undefined)\n raise ArgumentError, 'block not supplied'\n end\n\n string = StringValue(string)\n filename = StringValue(filename)\n\n # The staticscope of a module_eval CM is the receiver of module_eval\n ss = Rubinius::StaticScope.new self, Rubinius::StaticScope.of_sender\n\n binding = Binding.setup(Rubinius::VariableScope.of_sender,\n Rubinius::CompiledMethod.of_sender,\n ss)\n\n be = Rubinius::Compiler.construct_block string, binding,\n filename, line\n\n be.call_under self, ss, self\n end\n\n alias_method :class_eval, :module_eval\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2972964,"cells":{"blob_id":{"kind":"string","value":"40f476049ab8f5f902a18876a02c28e6d5b8c9f7"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"guspowell/Battleships"},"path":{"kind":"string","value":"/spec/board_spec.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":812,"string":"812"},"score":{"kind":"number","value":2.984375,"string":"2.984375"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"require 'board'\nrequire 'player'\n\ndescribe Board do\n\n let(:board) { Board.new }\n let(:player) { Player.new }\n let(:ship) { Ship.new(2) }\n\n it 'should have no ships to start' do\n expect(board.ship_count).to eq 0\n end\n\n it \"should be able to receive ships from the player\" do\n player.place(board, ship, ['a1','a2'])\n player.place(board, ship, ['b1', 'b2'])\n expect(board.ship_count).to eq 2\n end\n\n it \"should be able to receive ships from the player in a position\" do\n board.receive(ship, 'j2')\n expect(board.ship_count).to eq 1\n end\n\n it \"should be able to fill places given the coordinates\" do\n player.place(board,player.patrol_boat,['a1','b1'])\n board.fill_cells\n expect(board.places[:a1]).to eq(:s) #check cell contents =\n expect(board.places[:b1]).to eq(:s)\n end\n\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2972965,"cells":{"blob_id":{"kind":"string","value":"e0f1b00bce3e385cb3e04afe1c861a43c92ffd39"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"filip373/ruby_algorithms"},"path":{"kind":"string","value":"/enumerable.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1389,"string":"1,389"},"score":{"kind":"number","value":3.296875,"string":"3.296875"},"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 Enumerable\n\n def my_each\n self.size.times do |time|\n yield self.to_a[time]\n end\n end\n\n def my_each_with_index\n self.size.times do |time|\n yield self.to_a[time], time\n end\n end\n\n def my_select\n arr = []\n self.my_each do |elem|\n arr.push elem if yield elem\n end\n return arr\n end\n\n def my_all?\n self.my_each do |elem|\n return false unless yield elem\n end\n return true\n end\n\n def my_none?\n self.my_each do |elem|\n return false if yield elem\n end\n return true\n end\n\n def my_count obj = (no_arg = true), &block\n unless no_arg\n return self.my_select do |elem|\n elem == obj\n end.size\n end\n if block_given?\n return self.my_select(&block).size\n else\n return self.size\n end\n end\n\n def my_map\n arr = []\n self.each do |elem|\n arr.push yield elem\n end\n return arr\n end\n\n def my_inject proc = (no_proc = true), initial = self[0]\n memo = initial\n return memo if no_proc\n self.each do |elem|\n memo = proc.call memo, elem\n end\n if block_given?\n memo2 = initial\n self.each do |elem|\n memo2 = yield memo2, elem\n end\n return memo, memo2\n else\n return memo\n end\n end\n\nend\n\ndef multiply_els arr\n proc = Proc.new do |memo, elem|\n memo *= elem\n end\n return arr.my_inject(proc, 1) { |m,e| m *= e }\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2972966,"cells":{"blob_id":{"kind":"string","value":"3c1e17fde955b1619f725c3753be36ad8552f3b8"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"pedro-ivo-molina/bank-slip-validator"},"path":{"kind":"string","value":"/validator.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":848,"string":"848"},"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":"class Validator\n attr_reader :body_annotations\n\n def initialize\n @header_errors = []\n @body_errors = []\n @body_annotations = []\n @footer_errors = []\n end\n\n def validate_header(bank_slip:, rules:)\n rules.each do |rule|\n rule.validate(bank_slip)\n\n @header_errors << rule.error unless rule.error.empty?\n end\n\n return @header_errors\n end\n\n def validate_body(bank_slip:, rules:)\n rules.each do |rule|\n rule.validate(bank_slip)\n\n @body_errors << rule.error unless rule.error.empty? \n @body_annotations << rule.annotation unless rule.annotation.empty?\n end\n\n return @body_errors\n end\n\n def validate_footer(bank_slip:, rules:)\n rules.each do |rule|\n rule.validate(bank_slip)\n\n @footer_errors << rule.error unless rule.error.empty?\n end\n\n return @footer_errors\n end\nend"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2972967,"cells":{"blob_id":{"kind":"string","value":"9a5af248af913ef1d60efd2b8a3ec901ba9cd4ab"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"huyu398/manmenmi"},"path":{"kind":"string","value":"/manmenmi.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2833,"string":"2,833"},"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 'capybara'\nrequire 'capybara-webkit'\nrequire 'logger'\nrequire 'yaml'\n\nrequire_relative 'tag_reader'\nrequire_relative 'errors'\n\nMANMENMI_ROOT = File.expand_path(File.dirname(__FILE__))\nAUDIO_PREFIX = \"#{MANMENMI_ROOT}/voice\"\nNFCPY_PREFIX = \"#{MANMENMI_ROOT}/nfcpy/0.9\"\nLOG_PREFIX = \"#{MANMENMI_ROOT}/log\"\n\nconfig = YAML.load(File.read(\"#{MANMENMI_ROOT}/config.yml\"))\nURL = config['url']\nUSERS = config['users']\n\nlogger = Logger.new(\"#{LOG_PREFIX}/test.log\")\nlogger.level = Logger::INFO\nlogger.info('Start MANMENMIIIIII!!!!!!!')\n\nnfc = TagReader.new\n\nloop do\n begin\n logger.info(\"Start polling\")\n tag = nfc.read rescue (raise Errors::NFCReadError.new(\"Can't read a nfc tag\", __LINE__))\n # manmenmi!!!\n `mplayer #{AUDIO_PREFIX}/comeonbaby.wav 2>/dev/null`\n logger.info(\"Read a tag of uid:#{tag}\")\n\n user = {}\n USERS.each do |_user|\n if _user['uid'] == tag\n user = _user\n end\n end\n raise Errors::UserRecognizeError.new(\"No user with uid:#{tag}\", __LINE__) if user.empty?\n logger.info(\"Recognize a user with id:#{user['id']} name:#{user['name']}\")\n\n session = Capybara::Session.new(:webkit)\n\n # login\n session.visit(URL)\n session.select(user['name'], from: '_ID')\n session.fill_in('Password', with: user['password'])\n session.click_button('ログイン')\n raise Errors::LoginError.new(\"Invalid password for user:#{user['name']}\", __LINE__) if session.title.match(/エラー/)\n logger.info('Success login')\n\n # arrived or left\n login_time = Time.now\n timecard_table = session.all(:xpath, 'html/body/div/div/div/table/tbody/tr/td/table/tbody/tr/td/div/div/div/form/table/tbody/tr/td')\n arrive_cell, leave_cell = [timecard_table.at(0), timecard_table.at(1)]\n arrive_time = Time.parse(arrive_cell.text.match(/\\d{2}:\\d{2}/)[0])\n\n if login_time < arrive_time + 15 * 60 # margin 15min\n `mplayer #{AUDIO_PREFIX}/goodmorn.wav 2>/dev/null`\n logger.info(\"#{user['name']} already logined cybozu\")\n else\n if arrive_cell.has_button?('出社')\n leave_cell.click_button('出社')\n raise Errors::UnexpectedError.new(\"!!! Unexpeced error !!!\", __LINE__) if session.title.match(/エラー/)\n `mplayer #{AUDIO_PREFIX}/goodmorn.wav 2>/dev/null`\n logger.info(\"#{user['name']} arrived office\")\n elsif leave_cell.has_button?('退社')\n leave_cell.click_button('退社')\n raise Errors::UnexpectedError.new(\"!!! Unexpeced error !!!\", __LINE__) if session.title.match(/エラー/)\n `mplayer #{AUDIO_PREFIX}/goodbay.wav 2>/dev/null`\n logger.info(\"#{user['name']} left office\")\n else\n raise Errors::UnexpectedError.new(\"!!! Unexpeced error !!!\", __LINE__)\n end\n end\n rescue => e\n `mplayer #{AUDIO_PREFIX}/error.wav 2>/dev/null`\n logger.error(e.message)\n end\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2972968,"cells":{"blob_id":{"kind":"string","value":"1b5b5026a1b64b07bdf61d825cfa84fb185f413d"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"CJStadler/state_machine_checker"},"path":{"kind":"string","value":"/lib/state_machine_checker/state_result.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1115,"string":"1,115"},"score":{"kind":"number","value":3.359375,"string":"3.359375"},"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 StateMachineChecker\n # The result of checking whether this state satisfies a formula.\n class StateResult\n # @param [Boolean] satisfied\n # @param [Array] path\n def initialize(satisfied, path)\n @satisfied = satisfied\n @path = path\n end\n\n # Whether the formula is satisfied from this state.\n #\n # @return [true, false]\n def satisfied?\n satisfied\n end\n\n # A witness that the formula is satisfied from this state.\n #\n # @return [Array] an array of the names of transitions.\n def witness\n if satisfied?\n path\n end\n end\n\n # A counterexample demonstrating that the formula is not satisfied from this\n # state.\n #\n # @return [Array] an array of the names of transitions.\n def counterexample\n unless satisfied?\n path\n end\n end\n\n def or(other)\n if satisfied?\n self\n else\n other\n end\n end\n\n def and(other)\n if !other.satisfied?\n other\n else\n self\n end\n end\n\n private\n\n attr_reader :satisfied, :path\n end\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2972969,"cells":{"blob_id":{"kind":"string","value":"ee0e187c1f0ab6b5b0b30312ecfcab794440e64b"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"msomji/bowling_kata"},"path":{"kind":"string","value":"/bowl.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":3918,"string":"3,918"},"score":{"kind":"number","value":3.484375,"string":"3.484375"},"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":"# as a bowler I want to be able to start a new game\n# as a bowler I want to be able to bowl\n# as a bowler I want to be able to be able to see how many pins I knocked out after each bowl\n# as a bowler I want to be able to see if I get a spare or a strike\n# as a bowler I want to be able to see my score after every frame\n# as a bowloer I would like to get some instructions\n#as a bowler I would want to be able to mannuall enter how many pins I knock out\n\n# features\n# as a bowler I want to have a name?\n\n\nclass Bowl\n attr_reader :score, :frame, :score_board\n\n def initialize\n @score = 0\n @frame = 0\n @score_board = [[0,0,0]]\n instructions\n end\n# sdfg\n def instructions\n \"Instructions: \n You have played bowling before! here are a couple methods to help you around this game!\n To bowl - bowl(first_try, second_try)\n To bowl bonus frames(10th frame) - bonus(first_try, second_try)\n To check Score - score\n To reset game - reset\n To get instructions again - instructions\n \"\n end\n\n def bowl(trial1, trial2)\n if trial2 + trial1 <= 10 && trial1 >= 0 && trial2 >= 0\n user_updates(trial1,trial2)\n else\n \"try again! you can knock out a max of only 10 pins per turn and positive numbers\"\n end\n end\n\n def bonus(bowl1, bowl2)\n if @frame == 10 && bowl2 + bowl1 <= 10 && bowl1 >= 0 && bowl2 >= 0 && @score_board[-2][0] == 10\n if bowl1 == 10\n update_score_board(bowl1,0)\n \"SRIKE | One more Bonus roll!\"\n elsif bowl1 + bowl2 == 10\n update_score_board(bowl1,bowl2)\n \"SPARE! #{bowl1} / #{bowl2} | Game Over\"\n else\n update_score_board(bowl1,bowl2)\n \"#{bowl1} / #{bowl2} | Game Over\"\n end\n elsif @frame == 10 && bowl2 + bowl1 <= 10 && bowl1 >= 0 && bowl2 >= 0 && @score_board[-2][0] != 10 && @score_board[-2][0] + @score_board[-2][1] == 10\n if bowl1 == 10\n update_score_board(bowl1,0)\n \"SRIKE | Game Over\"\n else\n update_score_board(bowl1,0)\n \"#{bowl1} / 0 | Game Over\"\n end\n\n elsif @frame == 11 && bowl1 >= 0 && @score_board[-2][0] == 10 && @score_board[-3][0] == 10\n update_score_board(bowl1,0)\n \"SRIKE | Awesome!! | Game Over!\"\n else\n \"No bonus rounds for you sir\"\n end\n end\n\n def score\n @score = 0\n next_frame = 0\n @score_board.each do |round|\n next_frame +=1\n if round[0] == 10\n @score += round[0] + @score_board[next_frame][0] + @score_board[next_frame][1]\n elsif round[0] + round[1] == 10\n @score += 10 + @score_board[next_frame][0]\n else\n @score += round[0] + round[1]\n end\n end\n @score\n end\n\n def reset\n @score = 0\n @frame = 0\n @score_board = [[0,0,0]]\n end\n\n private\n\n def update_score_board(trial1, trial2)\n @score_board.insert(-2, [trial1, trial2])\n @frame += 1\n end\n\n def user_updates(trial1,trial2)\n if @frame < 9\n pre_last_frame_user_updates(trial1,trial2)\n\n elsif @frame == 9\n last_frame_user_updates(trial1,trial2)\n else\n \"The Game is over buddy! Make a new Game\"\n end\n end\n\n def pre_last_frame_user_updates(trial1,trial2)\n if trial1 == 10\n update_score_board(trial1,0)\n \"STRIKE!\"\n elsif trial1 + trial2 == 10\n update_score_board(trial1,trial2)\n \"SPARE! #{trial1} / #{trial2}\"\n else\n update_score_board(trial1,trial2)\n \"#{trial1} / #{trial2}\"\n end\n end\n\n def last_frame_user_updates(trial1,trial2)\n if trial1 == 10\n update_score_board(trial1,0)\n \"STRIKE! | You have two more bonus bowl! Use the bonus method to enter your bonus pins\"\n elsif trial1 + trial2 == 10\n update_score_board(trial1,trial2)\n \"SPARE! #{trial1} / #{trial2} | You have one more bonus bowl! Use the bonus method to enter your bonus pins\"\n else\n update_score_board(trial1,trial2)\n \"#{trial1} / #{trial2} | Game Over\"\n end\n end\nend\n\nBowl.new\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2972970,"cells":{"blob_id":{"kind":"string","value":"502aeccf5aa28e42cc789c26ff40cb8a662e5a13"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"v9n/proc"},"path":{"kind":"string","value":"/study/interviewcake/matching-parens/spec.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":462,"string":"462"},"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_relative 'solution.rb'\nrequire 'minitest/spec'\nrequire 'minitest/autorun'\n\ndescribe InterviewCake::MatchingParens do\n it 'returns correct close posstion' do\n s = \"Sometimes (when I nest them (my parentheticals) too much (like this (and this))) they get confusing.\"\n solution = InterviewCake::MatchingParens.new\n solution.perform(s, 10).must_equal 79\n solution.perform(s, 57).must_equal 78\n solution.perform(s, 68).must_equal 77\n end\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2972971,"cells":{"blob_id":{"kind":"string","value":"2faaea69eca77e2681b2c2e070515301c5110172"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"StlMaris123/ruby_tutorials"},"path":{"kind":"string","value":"/learn ruby the hard way/ex3.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1544,"string":"1,544"},"score":{"kind":"number","value":4.40625,"string":"4.40625"},"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":"#mathematics\n#use of interpolation is how we insert Ruby computations\n#displays the following code\nputs \"i will now count my hens\"\n#executes the computations and interpolates it wit Hens and also Roosters\nputs \"Hens #{25 + 30 / 6}\"\nputs \"Roosters #{100-25*3%4}\"\n\n#displays the following code\nputs \"I will now count my eggs\"\n#Executes the following computation using PEMDA and displays the answer\nputs 3+2+1-5+4%2-1/4%6\n\n#displays the following code\nputs \"is it true that 3 + 2 < 5 - 7\"\n#compares the value of 3+2 and 5-7 and returns a boolean value\nputs 3 + 2 < 5 - 7\n\n#Executes the code inside the parenthesis and concatenates it with the string\nputs \"what is 3 + 2? #{3+2}\"\nputs \"what is 5 - 7? #{5-7}\"\n\n#Displays the following thhe code\nputs \"oh thats why its false\"\nputs \"How about some more?\"\n\n#executes the code inside the parenthesis and concatenates the boolean value value to the string\nputs \"is it greater? #{5 > -2}\"\nputs \"is it greater or equal? #{5 >= -2}\"\nputs \"is it less or equal? #{5 <= -2}\"\n\n#using floating point numbers\nputs \"i will now count my hens\"\nputs \"Hens #{25.00 + 30.00 / 6.00}\"\nputs \"Roosters #{100.00 - 25.00 * 3.00 % 4.00}\"\n\nputs \"I will now count my eggs\"\nputs 3.00 + 2.00 + 1.00 - 5.00 + 4.00 % 2.00 - 1.00 / 4.00 % 6.00\n\nputs \"is it true that 3 + 2 < 5 - 7\"\nputs 3 + 2 < 5 - 7\n\nputs \"what is 3 + 2? #{3+2}\"\nputs \"what is 5 - 7? #{5-7}\"\n\nputs \"oh thats why its false\"\nputs \"How about some more?\"\n\nputs \"is it greater? #{5 > -2}\"\nputs \"is it greater or equal? #{5 >= -2}\"\nputs \"is it less or equal? #{5 <= -2}\"\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2972972,"cells":{"blob_id":{"kind":"string","value":"4fb73857aa983f0cfc10960b91ccfadff7049233"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"alrawi90/day_name_displayer"},"path":{"kind":"string","value":"/day_name_display.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1185,"string":"1,185"},"score":{"kind":"number","value":3.65625,"string":"3.65625"},"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 Day_name_displayer\r\n \r\n def initialize\r\n welcome\r\n menu\r\n end\r\n def welcome\r\n puts \"\"\r\n puts \"\"\r\n puts \"welcome to ---Day Name Displayer----\"\r\n puts \"\"\r\n end\r\n def msg\r\n puts\t\"Please enter a number from 1-7 OR enter 'exit' to end application .\"\r\n end\r\n def menu\r\n \tmsg\r\n \tinput=nil\r\n \twhile(input !=\"exit\")\r\n \t\tputs \"\"\r\n \t\tinput=gets.strip\r\n if input ==\"1\"\r\n puts \"Sunday\"\r\n elsif input ==\"2\"\r\n puts \"Monday\"\r\n elsif input==\"3\"\r\n \t puts \"Tuesday\"\r\n elsif input==\"4\"\r\n \t puts \"Wednesday\"\r\n elsif input==\"5\"\r\n \t puts \"Thursday\"\r\n elsif input==\"6\"\r\n \t puts \"Friday\"\r\n elsif input==\"7\"\r\n \t puts \"Saturday\" \t \t \t \r\n elsif input==\"exit\"\r\n puts \"Thank you for using --Day Name Displayer--\" \r\n puts \"\"\r\n break\r\n else\r\n puts \"invalid input\"\r\n msg\r\n end\r\n\t \tend\r\n\t end\r\n \r\n\r\nend\r\nobj=Day_name_displayer.new\r\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2972973,"cells":{"blob_id":{"kind":"string","value":"77fc6c7b8fcc52837b08ba5995e88d34e3ec4746"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"squareben1/review_12_spellcheck"},"path":{"kind":"string","value":"/lib/spellchecker.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":818,"string":"818"},"score":{"kind":"number","value":3.75,"string":"3.75"},"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 SpellChecker \n def initialize(dictionary=[])\n @dictionary = homogenise_arr(dictionary)\n end\n\n def spellcheck(string)\n words = split_string(string)\n checked_words = []\n \n words.each do | word | \n checked_words.push(word_check(word))\n end\n checked_words.join(\" \")\n end\n\n def add_words(string)\n new_words = split_string(string)\n lower_case_words = homogenise_arr(new_words)\n\n @dictionary.push(*lower_case_words)\n end\n\n private\n\n def homogenise_arr(arr)\n arr.map!(&:downcase)\n end\n\n def split_string(string)\n # gives potential for extension when client needs punctuation, etc.\n string.split(\" \")\n end\n\n def word_check(word)\n down_case_word = word.downcase\n\n if !@dictionary.include?(down_case_word)\n \"~#{word}~\"\n else\n word\n end\n end\nend"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2972974,"cells":{"blob_id":{"kind":"string","value":"103902ed24dc2e9570dc384f42565e5dedda3a22"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"johndierks/ruby-intro"},"path":{"kind":"string","value":"/vehicles.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":306,"string":"306"},"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 Vehicle\n def go\n puts \"Pressed Gas Pedal\"\n end\n \n def stop\n puts \"Pressed Brake Pedal\"\n end\nend\n\nclass Convertible < Vehicle\n def lower_top\n puts \"It's a nice day, so I put the top down\"\n end\n \n def raise_top\n puts \"Looks like it's going to rain, so I raised the top.\"\n end\nend"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2972975,"cells":{"blob_id":{"kind":"string","value":"91f16e625d58019b95a8823cc5b085d82cd43387"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"Dwein9/ruby-object-initialize-lab-web-1116"},"path":{"kind":"string","value":"/lib/person.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":73,"string":"73"},"score":{"kind":"number","value":2.765625,"string":"2.765625"},"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 Person\n\n def initialize(the_name)\n @name = the_name\n end\n\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2972976,"cells":{"blob_id":{"kind":"string","value":"4733d1c6cfce81aa46248e89b7d5bb74a1f1c54e"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"jordanluce/AdvancedActiveRecord"},"path":{"kind":"string","value":"/has_many_activerecord.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":5095,"string":"5,095"},"score":{"kind":"number","value":3.359375,"string":"3.359375"},"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":"#has_many associations activerecord\n\nclass Person < ActiveRecord::Base\n belongs_to :location\n belongs_to :role\nend\n\nclass Role < ActiveRecord::Base\n has_many :people\nend\n\nclass Location < ActiveRecord::Base\n has_many :people\nend\n\n\n____________________________________________________________________________________________________________________\n\nRole.all\n\nid name billable\n1 Developer t\n2 Manager f\n3 Unassigned f\n\n____________________________________________________________________________________________________________________\n\nLocation.all\n\nid name billable\n1 Boston 1\n2 New York 1\n3 Denver 2\n\n____________________________________________________________________________________________________________________\n\nPeople.all\n\nid name role_id location_id\n1 Wendell 1 1\n2 Christie 1 1\n3 Sandy 1 3\n4 Eve 2 2\n\n____________________________________________________________________________________________________________________\n\n#First we want to fine all distinct locations with at least one person who belongs to a billable role.\n#We can also use joins with has_many just like on belongs_to\n\n\nLocation.joins(:people)\n\n locations | people\n id name region_id | id name role_id location_id\n 1 Boston 1 | 1 Wendell 1 1\n 1 Boston 1 | 2 Christie 1 1\n 3 Denver 2 | 3 Sandy 1 3\n 2 New York 1 | 4 Eve 2 2\n\n____________________________________________________________________________________________________________________\n\n#The use of has_many_through\n\n\nLocation.joins(people: :role)\n\n locations | people | roles\nid name region_id | id name role_id location_id | id name billable\n1 Boston 1 | 1 Wendell 1 1 | 1 Developer t\n1 Boston 1 | 2 Christie 1 1 | 1 Developer t\n3 Denver 2 | 3 Sandy 1 3 | 1 Developer t\n2 New York 1 | 4 Eve 2 2 | 2 Manager f\n\n\n#Then now we can filter through with .where\n\nLocation.joins(people: :role).where(roles: { billable: true })\n\n#Which then returns something like that:\n#\n\n locations | people | roles\nid name region_id | id name role_id location_id | id name billable\n1 Boston 1 | 1 Wendell 1 1 | 1 Developer t\n1 Boston 1 | 2 Christie 1 1 | 1 Developer t\n3 Denver 2 | 3 Sandy 1 3 | 1 Developer t\n\n#But now we can notice that we see BOSTON TWICE... We can remiediate to this with the (distinct)method.\n#\n\nLocation.joins(people: :role).where(roles: { billable: true}).distinct\n\n#Which now returns something like this:\n#\n locations\nid name region_id\n3 Denver 2\n1 Boston 1\n\n#We can now encapsulate our query in our object and do:\n#\n\nclass location < ActiveRecord::Base\n def self.billable\n joins(people: :role).where(roles: { billable: true }).distinct\n end\nend \n\nLocation.billable\n\n\n____________________________________________________________________________________________________________________\n\n\n#Now we want to order the billable locations by region name, then by location name.\n#\n\nclass Location < ActiveRecord::Base\n belongs_to :region\nend\n\nclass Region < ActiveRecord::Base\n has_many :locations\nend\n\n#So straigth away we can do the following query to get the billable locations to be ordered by region name then by location name:\n#\n\nLocation.joins(:region).merge(Region.order(:name)).order(:name)\n\n#Which gives us the following:\n#\n\n locations | regions\nid name region_id | id name\n1 Boston 1 | 1 East\n2 New York 1 | 1 East\n3 Denver 2 | 2 West\n\n\n#So now we can create our method on the model to scope things:\n#\n\nclass Location < ActiveRecord::Base\n def self.billable\n joins(people: :role).where(roles: { billable: true }).distinct\n end\n\n def self.by_region_and_location_name\n joins(:region).merge(Region.order(:name)).order(:name)\n end\nend\n\n#Now the problem that we are going to have is we won't be able to join our scopes and do:\n#\n\nXXXXXX Location.billable.by_region_and_location_name XXXXXX\n#This is because the (distinct) method.\n#We need to use a sub-query with the (from) method\n#Let's use it to first return distinct billable locations.\n#\nLocation.from(Location.billable, :locations)\n#Which returns this:\n#\n locations\nid name region_id\n3 Denver 2\n1 Boston 1\n\n#So now we can put it all together\n#\n\nLocation.from(Location.billable, :locations).by_region_and_location_name\n\n locations | regions\nid name region_id | id name\n1 Boston 1 | 1 East\n3 Denver 2 | 2 West\n\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2972977,"cells":{"blob_id":{"kind":"string","value":"3b7653ccbcc67d487eecff3adc342d73d8fcda77"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"danabo/zhat"},"path":{"kind":"string","value":"/_plugins/jumpto.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":384,"string":"384"},"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":"module Jekyll\n class JumpToBlock < Liquid::Block\n\n require \"shellwords\"\n\n def initialize(tag_name, text, tokens)\n super\n @text = text.shellsplit\n end\n\n def render(context)\n contents = super\n \"\"\\\n \"#{contents}\"\n end\n end\nend\n\nLiquid::Template.register_tag('jumpto', Jekyll::JumpToBlock)\n\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2972978,"cells":{"blob_id":{"kind":"string","value":"2063d534906cb9df672fdfa25f7da4e388116b43"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"stupergenius/Software-Engineering-for-SaaS"},"path":{"kind":"string","value":"/assignment1/part2_spec.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":3078,"string":"3,078"},"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":"load 'part2.rb'\n\ndescribe \"#rps_game_winner\" do\n context \"fail states\" do\n it \"should raise when number of players is not two\" do\n expect { rps_game_winner([]) }.to raise_error(WrongNumberOfPlayersError)\n expect { rps_game_winner([[\"Armando\", \"P\"]]) }.to raise_error(WrongNumberOfPlayersError)\n expect { rps_game_winner([[\"Armando\", \"P\"], [\"Dave\", \"S\"], [\"Ben\", \"P\"]]) }.to raise_error(WrongNumberOfPlayersError)\n end\n it \"should raise when an invalid strategy is given\" do\n expect { rps_game_winner([[\"Armando\", \"P\"], [\"Dave\", \"F\"]]) }.to raise_error(NoSuchStrategyError\n)\n end\n end\n context \"ties\" do\n it \"should return the first player in case of a tie\" do\n p1 = [\"Armando\", \"P\"]\n p2 = [\"Dave\", \"P\"]\n rps_game_winner([p1, p2]).should eq(p1)\n rps_game_winner([p2, p1]).should eq(p2)\n end\n end\n context \"winners\" do\n it \"should return rock beats scissors\" do\n p1 = [\"Armando\", \"R\"]\n p2 = [\"Dave\", \"S\"]\n rps_game_winner([p1, p2]).should eq(p1)\n rps_game_winner([p2, p1]).should eq(p1)\n end\n it \"should return paper beats rock\" do\n p1 = [\"Armando\", \"P\"]\n p2 = [\"Dave\", \"R\"]\n rps_game_winner([p1, p2]).should eq(p1)\n rps_game_winner([p2, p1]).should eq(p1)\n end\n it \"should return scissors beats paper\" do\n p1 = [\"Armando\", \"S\"]\n p2 = [\"Dave\", \"P\"]\n rps_game_winner([p1, p2]).should eq(p1)\n rps_game_winner([p2, p1]).should eq(p1)\n end\n end\nend\n\ndescribe \"#is_single_round\" do\n game = [ [\"Armando\", \"P\"], [\"Dave\", \"S\"] ]\n tournament = \n [ \n [ [\"Allen\", \"S\"], [\"Omer\", \"P\"] ],\n [ [\"David E.\", \"R\"], [\"Richard X.\", \"P\"] ],\n ]\n \n it \"should be able to detect a single round game\" do\n is_single_round?(game).should be_true\n is_single_round?(tournament).should be_false\n end\nend\n\ndescribe \"#rps_tournament_winner\" do\n winner = [\"Richard\", \"R\"]\n tournament1 = [ winner, [\"Michael\", \"S\"] ]\n tournament4 =\n [\n [ [\"Armando\", \"P\"], [\"Dave\", \"S\"] ],\n tournament1,\n ]\n tournament8 = \n [\n tournament4,\n [ \n [ [\"Allen\", \"S\"], [\"Omer\", \"P\"] ],\n [ [\"David E.\", \"R\"], [\"Richard X.\", \"P\"] ],\n ],\n ]\n tournament16 = \n [\n tournament8,\n [\n [\n [ [ \"P1\", \"P\" ], [ \"P2\", \"S\" ] ],\n [ [ \"P3\", \"R\" ] , [ \"P4\", \"P\" ] ],\n ],\n [\n [ [ \"P7\", \"P\" ], [ \"P5\", \"S\" ] ],\n [ [ \"P9\", \"R\" ] , [ \"P10\", \"P\" ] ],\n ],\n ],\n ]\n \n it \"should return the winner\" do\n rps_tournament_winner(tournament1)[0].should eq \"Richard\"\n rps_tournament_winner(tournament4)[0].should eq \"Richard\"\n rps_tournament_winner(tournament8)[0].should eq \"Richard\"\n rps_tournament_winner(tournament16)[0].should eq \"Richard\"\n end\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2972979,"cells":{"blob_id":{"kind":"string","value":"8cad1f79ccd8091f0b35197064bfd57ae7652eef"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"shoebham/Ruby_Projects_the_odin_project"},"path":{"kind":"string","value":"/Project_Tic_Tac_Toe/tic_tac_toe.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":3406,"string":"3,406"},"score":{"kind":"number","value":3.375,"string":"3.375"},"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":"LINES = [[1,2,3],[4,5,6],[7,8,9],[1,5,9],[3,5,7],[1,4,7],[2,5,8],[3,6,9]]\r\n\r\n\r\n class Game \r\n def initialize(player_1_class,player_2_class)\r\n @board = Array.new(10)\r\n @current_player_id=0\r\n @players = [player_1_class.new(self,\"X\",1),player_2_class.new(self,\"O\",2)]\r\n puts \"#{current_player} goes first\"\r\n end\r\n attr_reader :board, :current_player_id\r\n \r\n def play \r\n loop do\r\n place_marker(current_player)\r\n \r\n if player_won?(current_player)\r\n p \"#{current_player} is the winner\"\r\n print_board\r\n return\r\n elsif board_full?\r\n p \"It's a draw!\"\r\n print_board\r\n return\r\n end\r\n \r\n switch_player!\r\n \r\n end\r\n end\r\n \r\n def free_positions\r\n (1..9).select{|pos| @board[pos].nil?}\r\n end\r\n \r\n def place_marker(player)\r\n position = player.select_position!\r\n p \"#{player} selects #{player.marker} position #{position}\"\r\n @board[position] = player.marker\r\n end\r\n \r\n def player_won?(player)\r\n LINES.any? do |i|\r\n i.all? {|j| @board[j] == player.marker}\r\n end\r\n end\r\n \r\n \r\n def board_full?\r\n free_positions.empty?\r\n end\r\n \r\n def other_player_id\r\n 1-@current_player_id\r\n end\r\n \r\n def switch_player!\r\n @current_player_id = other_player_id\r\n end\r\n \r\n def current_player\r\n @players[current_player_id]\r\n end\r\n \r\n \r\n def print_board\r\n col_sep = \" | \"\r\n row_sep = \"--+---+--\"\r\n label_pos = ->(pos){ @board[pos] ? @board[pos] : pos}\r\n row_for_display= ->(row){row.map(&label_pos).join(col_sep)}\r\n row_pos = [[1,2,3],[4,5,6],[7,8,9]]\r\n rows_for_display=row_pos.map(&row_for_display)\r\n puts rows_for_display.join(\"\\n\"+ row_sep +\"\\n\")\r\n end\r\n end\r\n\r\n class Player\r\n attr_reader:marker,:num\r\n def initialize(game,marker,num)\r\n @game = game\r\n @marker =marker\r\n @num = num\r\n end\r\n end\r\n \r\n class HumanPlayer < Player\r\n attr_reader:i\r\n \r\n \r\n def select_position!\r\n @game.print_board\r\n loop do\r\n puts \"Select your #{marker} position\"\r\n selection = gets.to_i\r\n return selection if @game.free_positions.include?(selection) \r\n puts \"position #{selection} position is not available\"\r\n end\r\n end\r\n \r\n def to_s\r\n \"Human #{num}\"\r\n end\r\n end\r\n\r\nputs players_with_human = [HumanPlayer, HumanPlayer].shuffle\r\nGame.new(*players_with_human).play"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2972980,"cells":{"blob_id":{"kind":"string","value":"17a9860a23a7d87cfbb573810d55bf79bf09ccb6"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"idimitrov07/ruby_ood_book"},"path":{"kind":"string","value":"/chapter_five/duck_overlook.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":437,"string":"437"},"score":{"kind":"number","value":3.15625,"string":"3.15625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"# overlooking the duck\nclass Trip\n attr_reader :bicycles, :customers, :vehicle\n\n # this 'mechanic' could be of any class..\n def prepare(mechanic)\n mechanic.prepare_bicycles(bicycles)\n end\n\n # ...\nend\n\n# 'Mechanic' class in not referenced anywhere in the class above\nclass Mechanic\n def prepare_bicycles(bicycles)\n bicycles.each { |bicycle| prepare_bicycle(bicycle) }\n end\n\n def prepare_bicycle(bicycle)\n #...\n end\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2972981,"cells":{"blob_id":{"kind":"string","value":"fd588b4372f00639f2c3222c062f12d7199a4e30"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"smainar/backend_prework"},"path":{"kind":"string","value":"/day_1/exe3-1.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":296,"string":"296"},"score":{"kind":"number","value":3.578125,"string":"3.578125"},"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":"puts \"I will count my books.\"\nputs \"Old text books #{18 - 2 * 3}.\"\nputs \"Autobiographies #{3 + 3 % 1}.\"\nputs \"Non-fiction #{27 + 14 / 2 - 5}.\"\nputs \"Fiction #{56 - 17 % 3}.\"\n\n# Results:\n # I will count my books.\n # Old text books 12.\n # Autobiographies 3.\n # Non-fiction 29.\n # Fiction 54.\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2972982,"cells":{"blob_id":{"kind":"string","value":"9a2605235dfd8be5f55e327771ce6732dd30a5ed"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"goyox86/razer"},"path":{"kind":"string","value":"/lib/razer.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":984,"string":"984"},"score":{"kind":"number","value":3.640625,"string":"3.640625"},"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":"require \"razer/version\"\n\nmodule Razer\n #\n # A small utility class which for flattening nested arrays.\n #\n class Flattener\n # Flattens the input +array+ of arrays into a uni-dimensional one\n # preserving the relative order of eelements. If an empty array is\n # provided then the exact same empty array objevct will be returned.\n #\n # The algorithm is guaranteed to flatten the input array in O(n) time\n # and O(n) space with +n+ being the sum of the sizes of all involved\n # arrays including the top level one.\n #\n # input_array = [1, [2, 3, [4, 5, [6]]]]\n #\n # flattener = Flattener.new\n # flattener.flatten(input_array) # => [1, 2, 3, 4, 5, 6]\n #\n def flatten(array, accumulator = [])\n return array if array.empty?\n\n array.each do |element|\n if element.is_a?(Array)\n flatten(element, accumulator)\n else\n accumulator.push(element)\n end\n end\n\n accumulator\n end\n end\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2972983,"cells":{"blob_id":{"kind":"string","value":"3a371458f69091c787cb7e3bd844db7220ab7ff9"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"nickfryer21/screw-charlie"},"path":{"kind":"string","value":"/app/models/game_player.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":745,"string":"745"},"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":"# == Schema Information\n#\n# Table name: game_players\n#\n# id :integer not null, primary key\n# game_id :integer\n# player_id :integer\n# slot_id :integer\n#\n\nclass GamePlayer < ActiveRecord::Base\n belongs_to :game\n belongs_to :player\n has_one :hand, :dependent => :destroy\n has_many :turns, :dependent => :destroy\n belongs_to :slot\n\n after_create do\n self.hand = Hand.create!\n\n # Make sure newly added players are added to a slot\n next_slot = self.game.slots.where(available: true).first\n\n unless next_slot.nil?\n self.slot = next_slot\n self.save\n next_slot.available = false\n next_slot.save!\n end\n end\n\n def draw_card(draw_pile)\n self.hand.cards << draw_pile.draw_card\n end\nend\n\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2972984,"cells":{"blob_id":{"kind":"string","value":"9f55d4455b0328267d0dc466c14056b4f7f75add"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"fbenevides/conf-algorithm"},"path":{"kind":"string","value":"/lib/conferences/track.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":904,"string":"904"},"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":"module Conferences\n class Track\n attr_reader :name\n\n def initialize(name, sessions = [Session.new('Morning', 9, 12), Session.new('Afternoon', 13, 17)])\n @name = name\n @sessions = sessions\n end\n\n def duration\n @sessions.map(&:duration).reduce(&:+)\n end\n\n def distribute(talks)\n talks.sort_by(&:duration)\n removed = []\n\n @sessions.each do |session|\n sum = 0\n talks.each do |talk|\n if sum != session.duration\n if session.total + talk.duration <= session.duration\n session << talk\n sum += talk.duration\n removed << talk\n end\n end\n end\n\n talks -= removed\n end\n\n talks\n end\n\n def show\n puts \"#{name}\"\n @sessions.each do |session|\n puts \" #{session.name}\"\n session.show\n puts \" \"\n end\n end\n end\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2972985,"cells":{"blob_id":{"kind":"string","value":"babbe9f2186192f1da4a927285d6f42b52e3c223"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"junyuanxue/learn_to_program"},"path":{"kind":"string","value":"/ch14-blocks-and-procs/better_program_logger.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":448,"string":"448"},"score":{"kind":"number","value":3.4375,"string":"3.4375"},"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":"$indent = 0\n\ndef better_log desc, &block\n puts \" \" * $indent + \"Beginning \\\"#{desc}\\\"...\"\n $indent += 1\n result = block.call\n $indent -= 1\n puts \" \" * $indent + \"...\\\"#{desc}\\\" finished, returning: #{result.to_s}\"\nend\n\nbetter_log \"outer block\" do\n better_log \"some little block\" do\n better_log \"teeny-tiny block\" do\n \"lots of love\"\n end\n 42\n end\n\n better_log \"yet another block\" do\n \"I like Indian food!\"\n end\n\n true\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2972986,"cells":{"blob_id":{"kind":"string","value":"659316aa79719ba729942b2fc657afdaa0fe1e20"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"CoopTang/module_0_capstone"},"path":{"kind":"string","value":"/day_5/ex39.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2297,"string":"2,297"},"score":{"kind":"number","value":4.4375,"string":"4.4375"},"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":"# Hashes in 'Learn Ruby the Hard way'\r\n\r\n# Create a mapping of states to abbreviation\r\nstates = {\r\n 'Oregon' => 'OR',\r\n 'Florida' => 'FL',\r\n 'California' => 'CA',\r\n 'New York' => 'NY',\r\n 'Michigan' => 'MI'\r\n}\r\n\r\n# Creat a basic set of states and some cities in them\r\ncities = {\r\n 'CA' => 'San Francisco',\r\n 'MI' => 'Detroit',\r\n 'FL' => 'Jacksonville'\r\n}\r\n\r\n# Add some more cities\r\ncities['NY'] = 'New York'\r\ncities['OR'] = 'Portland'\r\n\r\n# puts out some cities\r\nputs '-' * 10\r\nputs \"NY State has: #{cities['NY']}\"\r\nputs \"OR State has: #{cities['OR']}\"\r\n\r\n# puts some states \r\nputs '-' * 10\r\nputs \"Michigan's abbreviation is: #{states['Michigan']}\"\r\nputs \"Florida's abbreviation is: #{states['Florida']}\"\r\n\r\n# do it using the state then cities dict\r\nputs '-' * 10\r\nputs \"Michigan has: #{cities[states['Michigan']]}\"\r\nputs \"Florida has: #{cities[states['Florida']]}\"\r\n\r\n# puts every state abbreviation\r\nputs '-' * 10\r\nstates.each do |state, abbrev|\r\n puts \"#{state} is abbreviated #{abbrev}\"\r\nend\r\n\r\n# puts every city in state\r\nputs '-' * 10\r\ncities.each do |abbrev, city|\r\n puts \"#{abbrev} has the city #{city}\"\r\nend\r\n\r\n# now do both at the same time\r\nputs '-' * 10\r\nstates.each do |state, abbrev|\r\n city = cities[abbrev]\r\n puts \"#{state} is abbreviated #{abbrev} and has city #{city}\"\r\nend\r\n\r\nputs '-' * 10\r\n# by default ruby says \"nill\" when something isn't in there\r\nstate = states['Texas']\r\n\r\nif !state\r\n puts \"Sorry, no Texas.\"\r\nend\r\n\r\n# default values using ||= with the nill result\r\ncity = cities['TX']\r\ncity ||= 'Does Not Exist'\r\nputs \"The city for the state 'TX' is: #{city}\"\r\n\r\n# doing some of my own stuff\r\ncities_of_co = [\"Boulder\", \"Denver\", \"Colorado Springs\"]\r\nstates['Colorado'] = 'CO'\r\ncities['CO'] = cities_of_co\r\n\r\n# let's print out the contents\r\nputs '-' * 10\r\nstates.each do |state, abbrev|\r\n city = cities[abbrev]\r\n print \"#{state} is abbreviated #{abbrev} and has \"\r\n # gotta handle an array differently than the original\r\n if (city.class == Array)\r\n print \"cities \"\r\n cities_str = \"\"\r\n city.each do |city|\r\n cities_str += \"#{city}, \"\r\n end\r\n # remove the final space and comma\r\n puts cities_str[0...-2]\r\n else\r\n puts \"city #{city}\"\r\n end\r\nend\r\n\r\n "},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2972987,"cells":{"blob_id":{"kind":"string","value":"8073b475c3f9cf87336820c2f7437add4a43cc37"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"arakla/binder-app"},"path":{"kind":"string","value":"/app/helpers/application_helper.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1325,"string":"1,325"},"score":{"kind":"number","value":2.625,"string":"2.625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"module ApplicationHelper\n\n def display_base_errors resource\n return '' if (resource.errors.empty?) or (resource.errors[:base].empty?)\n messages = resource.errors[:base].map { |msg| content_tag(:p, msg) }.join\n html = <<-HTML\n
\n \n #{messages}\n
\n HTML\n html.html_safe\n end\n\n def time(display_time)\n time_zone = ActiveSupport::TimeZone.new(\"Eastern Time (US & Canada)\")\n display_time.in_time_zone(time_zone).strftime(\"%I:%M%p\")\n end\n\n def date(display_date)\n time_zone = ActiveSupport::TimeZone.new(\"Eastern Time (US & Canada)\")\n display_date.in_time_zone(time_zone).strftime(\"%m/%d/%y\")\n end\n\n def date_and_time(display_date_and_time)\n [date(display_date_and_time), time(display_date_and_time)].compact.join(\" \")\n end\n\n def format_boolean(bool)\n bool ? \"Yes\" : \"No\"\n end\n\n def currency(display_currency)\n number_to_currency(display_currency)\n end\n\n def format_downtime(downtime)\n downtime = downtime.to_i\n if downtime < 0\n neg = '-'\n downtime *= -1\n else\n neg = ''\n end\n \n hours = downtime / 60 / 60\n minutes = downtime / 60 - hours * 60\n return neg + (\"%02d\" % hours) + \":\" + (\"%02d\" % minutes)\n end\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2972988,"cells":{"blob_id":{"kind":"string","value":"bc69eede1366cf4d862db29f1cbd0d2247f0380f"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"timbeiko/tealeaf-prework"},"path":{"kind":"string","value":"/greetings.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":177,"string":"177"},"score":{"kind":"number","value":3.90625,"string":"3.90625"},"int_score":{"kind":"number","value":4,"string":"4"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"# greetings.rb\n\ndef greetings(name)\n\tputs \"Hi there, \"+ name\nend\n\nname = gets.chomp\n\ngreetings(name)\n\nx = 2\n\nputs x = 2\n\np name=\"Joe\"\n\nfour = \"four\"\n\nprint something = \"nothing\""},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2972989,"cells":{"blob_id":{"kind":"string","value":"cb186eccb2a05d681feeb207b686282f486dd8a7"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"mdvincen/tts_projects"},"path":{"kind":"string","value":"/unless.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":77,"string":"77"},"score":{"kind":"number","value":3.015625,"string":"3.015625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"sum = 50\n\nunless sum ==50\n\tputs 'That is incorrect'\n\nelse\n\tputs 'Correct'\nend"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2972990,"cells":{"blob_id":{"kind":"string","value":"ab65df6218c1465eb922ba6ed8912f6957a0fbf7"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"mgdelin/operators-online-web-ft-081219"},"path":{"kind":"string","value":"/lib/operations.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":182,"string":"182"},"score":{"kind":"number","value":2.96875,"string":"2.96875"},"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 unsafe?(speed)\nif speed > 60 \n return true\n elsif speed < 40\n return true \nelse return false \nend\nend\n\n\n\ndef not_safe?(speed)\n\tspeed > 60 or speed < 40 ? true : false\nend\n\t\n\n\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2972991,"cells":{"blob_id":{"kind":"string","value":"37823c86fc5e1317850a71e1bd760e3b39919357"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"bemijonathan/tracker"},"path":{"kind":"string","value":"/app/models/transaction.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":435,"string":"435"},"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 \"securerandom\"\nclass Transaction < ApplicationRecord\n belongs_to :user\n before_save :getvalue\n def encode (uuid) \n return [uuid.tr('-', '').scan(/../).map(&:hex).pack('c*')].pack('m*').tr('+/', '-_').slice(0..21) \n end\n\n def getvalue()\n val = SecureRandom.uuid\n token = encode(val)\n self.tracking_id = token.toUpcase \n end\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2972992,"cells":{"blob_id":{"kind":"string","value":"03a5d9fdb45dbf687cc69a94a7e49a58dfbab955"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"learn-co-students/houston-web-062419"},"path":{"kind":"string","value":"/07-CLI-Application/lib/app.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":564,"string":"564"},"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":"$prompt = TTY::Prompt.new\n\ndef start\n puts 'Welcome to my APP!'\n name\nend\n\ndef name\n name = $prompt.ask('What is your name?')\n puts name\n p = password\n puts \"Your password is: #{p}\"\n choices = %w(milk coffee tea orageJuice)\n $prompt.multi_select(\"Select drinks?\", choices)\nend\n\n\n# name = prompt.ask('What is your name?')\n# puts name\n\n# choice = prompt.yes?('Do you like Ruby?')\n# puts choice\n\n# secret = prompt.mask(\"What is your secret?\")\n# puts secret\n\n# choice = prompt.select(\"Choose your destiny?\", %w(Scorpion Kano Jax))\n# puts choice"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2972993,"cells":{"blob_id":{"kind":"string","value":"d360de954a635d4546e2ffc30ece84f0a3b1c210"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"1powechri2/BikeShare"},"path":{"kind":"string","value":"/app/models/cart.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":764,"string":"764"},"score":{"kind":"number","value":3.25,"string":"3.25"},"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 Cart\n attr_reader :contents\n\n def initialize(initial_content)\n @contents = initial_content || Hash.new(0)\n end\n\n def total_count\n @contents.values.sum\n end\n\n def add_accessory(accessory_id)\n @contents[accessory_id.to_s] ||= 0\n @contents[accessory_id.to_s] += 1\n end\n\n def accessory_quantity(accessory_id)\n @contents[accessory_id.to_s]\n end\n\n def subtotal(accessory_id)\n accessory_quantity(accessory_id) * Accessory.find(accessory_id).price\n end\n\n def total\n sub_totals = []\n @contents.each do |id, quantity|\n sub_totals.push(Accessory.find(id).price * quantity)\n end\n sub_totals.sum\n end\n\n def accessory_ids\n ids = []\n @contents.each do |id, quantity|\n ids.push(id.to_i)\n end\n ids\n end\n\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2972994,"cells":{"blob_id":{"kind":"string","value":"c9ab308c2df9f5af1df9e8f4bf2d5985e8660b52"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"s6ruby/universum"},"path":{"kind":"string","value":"/universum-contracts/tokens/token_test.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1957,"string":"1,957"},"score":{"kind":"number","value":2.96875,"string":"2.96875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["CC0-1.0"],"string":"[\n \"CC0-1.0\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"# to test the contract script run:\r\n# $ ruby tokens/token_test.rb\r\n\r\n\r\nrequire 'minitest/autorun'\r\n\r\n\r\nrequire_relative 'token'\r\n\r\nclass TestToken < Minitest::Test\r\n\r\n def setup\r\n @token = Token.new(\r\n name: 'Your Crypto Token',\r\n symbol: 'YOU',\r\n decimals: 8,\r\n initial_supply: 1_000_000\r\n )\r\n end\r\n\r\n def test_transfer\r\n assert_equal 100_000_000_000_000, @token.balance_of( owner: '0x0000' )\r\n assert_equal 0, @token.balance_of( owner: '0x1111' )\r\n\r\n assert @token.transfer( to: '0x1111', value: 100 )\r\n assert_equal 100, @token.balance_of( owner: '0x1111' )\r\n\r\n assert @token.transfer( to: '0x2222', value: 200 )\r\n assert_equal 200, @token.balance_of( owner: '0x2222' )\r\n\r\n assert_equal 99_999_999_999_700, @token.balance_of( owner: '0x0000' )\r\n end\r\n\r\n\r\n def test_transfer_from\r\n\r\n ## note: NOT pre-approved (no allowance) - will FAIL\r\n assert !@token.transfer_from( from: '0x1111', to: '03333', value: 30 )\r\n assert_equal 0, @token.allowance( owner: '0x0000', spender: '0x1111' )\r\n\r\n assert @token.approve( spender: '0x1111', value: 50 )\r\n assert_equal 50, @token.allowance( owner: '0x0000', spender: '0x1111' )\r\n\r\n ### change sender to 0x0001\r\n Contract.msg = { sender: '0x1111' }\r\n pp Contract.msg\r\n\r\n assert @token.transfer_from( from: '0x0000', to: '0x3333', value: 30 )\r\n assert_equal 30, @token.balance_of( owner: '0x3333' )\r\n assert_equal 99_999_999_999_970, @token.balance_of( owner: '0x0000' )\r\n assert_equal 0, @token.balance_of( owner: '0x1111' )\r\n\r\n ### change sender back to 0x0000\r\n Contract.msg = { sender: '0x0000' }\r\n pp Contract.msg\r\n\r\n assert @token.transfer( to: '0x1111', value: 1 )\r\n assert_equal 99_999_999_999_969, @token.balance_of( owner: '0x0000' )\r\n assert_equal 1, @token.balance_of( owner: '0x1111' )\r\n end\r\n\r\nend # class TestToken\r\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2972995,"cells":{"blob_id":{"kind":"string","value":"4275ab528d5840b3c7bc3a859b31bb1482410d28"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"JDAVEHACKER/RubyLearning"},"path":{"kind":"string","value":"/comparacion_combinado.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":430,"string":"430"},"score":{"kind":"number","value":4.40625,"string":"4.40625"},"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":"puts \"Operador de comparación combinada\"\n\n#Devuelve 0 si el primero y el segundo son iguales\n#Devuelve 1 si el primero es mayor que el segundo\n#Devuelve -1 si el primero es menor que el segundo\n\nputs \"ingrese dos número\"\nnum1 = gets.chomp.to_i\nnum2 = gets.chomp.to_i\n\nres= num1 <=> num2 \nif res == 0\n\tputs \"son iguales\"\nelsif res == 1\n\tputs \"#{num1} es mayor que #{num2}\"\nelsif res == -1\n\tputs \"#{num1} es menor que #{num2}\"\nend"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2972996,"cells":{"blob_id":{"kind":"string","value":"f031dba05393c7aa815b60f135c0b7dea604ec81"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"paulalexrees/learn_to_program"},"path":{"kind":"string","value":"/ch14-blocks-and-procs/grandfather_clock.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":249,"string":"249"},"score":{"kind":"number","value":3.296875,"string":"3.296875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"def grandfather_clock &block\n hours = if Time.new.hour > 12\n Time.new.hour - 12\n else\n Time.new.hour\n end\n hours.times{\n yield\n }\nend\n\ndong = Proc.new {\n puts \"DONG!\"\n}\n\ngrandfather_clock &dong\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2972997,"cells":{"blob_id":{"kind":"string","value":"55fbbd4186f48f53254d844caa13709ebe04e92e"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"octosteve/hangman"},"path":{"kind":"string","value":"/lib/hangman/boundary/game_server.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1351,"string":"1,351"},"score":{"kind":"number","value":2.75,"string":"2.75"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"# frozen_string_literal: true\n\nmodule Boundary\n class GameServer\n attr_reader :name\n\n def initialize(name:)\n @name = name\n @ractor = create_ractor\n end\n\n def make_guess(guess)\n ractor.send([:make_guess, guess])\n end\n\n def won?\n ractor.send([:won?, Ractor.current])\n Ractor.receive\n end\n\n def lost?\n ractor.send([:lost?, Ractor.current])\n Ractor.receive\n end\n\n def word\n ractor.send([:get_word, Ractor.current])\n Ractor.receive\n end\n\n def masked_word\n ractor.send([:get_masked_word, Ractor.current])\n Ractor.receive\n end\n\n private\n\n attr_reader :ractor\n\n def create_ractor\n words_path = \"#{File.expand_path(__dir__)}/../../../assets/words.txt\"\n word_list = File.readlines(words_path).map(&:strip)\n Ractor.new(word_list, name: name) do |word_list|\n game = Core::Game.start_game(name, word_list)\n loop do\n case receive\n in [:make_guess, guess]\n game.make_guess(guess)\n in [:won?, from]\n from.send game.won?\n in [:lost?, from]\n from.send game.lost?\n in [:get_word, from]\n from.send game.selected_word\n in [:get_masked_word, from]\n from.send game.masked_word\n end\n end\n end\n end\n\n end\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2972998,"cells":{"blob_id":{"kind":"string","value":"6e1dfe76b3dca4517b9f9f5de59425ebc36d097f"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"klavinslab/ProtocolsForReview"},"path":{"kind":"string","value":"/illumina_ngs/protocol/dilute_total_rna/protocol.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":5823,"string":"5,823"},"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":"# By Eriberto Lopez\r\n# elopez3@uw.edu\r\n# Production 10/05/18\r\n# C µl\r\n\r\nneeds \"RNA/RNA_ExtractionPrep\"\r\nneeds \"Illumina NGS Libs/RNASeq_PrepHelper\"\r\nneeds \"Illumina NGS Libs/TruSeqStrandedTotalRNAKit\"\r\n\r\n\r\nclass Protocol\r\n include RNA_ExtractionPrep\r\n include RNASeq_PrepHelper\r\n include TruSeqStrandedTotalRNAKit\r\n \r\n \r\n INPUT = \"Total RNA\"\r\n OUTPUT = \"Diluted Total RNA Plate\"\r\n \r\n INPUT_RNA_CONC = 300#ng # TODO: Find right starting concentration for an input so that the enrich fragment step does not over amplify the cDNA library and make it too concentrated\r\n FINAL_VOL = 10\r\n \r\n def main\r\n operations.make\r\n \r\n # Retrieve RNA extracts and let thaw at room temp\r\n thaw_rna_etracts\r\n \r\n # Get ice for following reagents\r\n get_ice\r\n \r\n # Sanatize bench\r\n sanitize\r\n \r\n # Retrieve materials for rRNA depletion and Fragmentation \r\n gather_RiboZero_Deplete_Fragment_RNA_materials(operation_type())\r\n \r\n normalize_and_fill_rna_plates()\r\n \r\n show {note \"Put away the following.\"}\r\n operations.store\r\n return {}\r\n \r\n end # Main\r\n \r\n \r\n # Caluculates the volume needed from the RNA sample to meet the desired final concentration\r\n #\r\n # @params rna_conc [int] is the concentration of RNA in [ng/ul]\r\n # @returns rna_dil_vol [int] is the volume of RNA required to meet the desired final conc.\r\n def dilute_rna(rna_conc)\r\n r_num = Random.new\r\n (debug) ? rna_conc = r_num.rand(1000) : rna_conc = rna_conc # For testing & debugging\r\n rna_dil_vol = (INPUT_RNA_CONC.to_f/rna_conc.to_f)\r\n return rna_dil_vol\r\n end\r\n \r\n # Calculates the volume of MG H2O required to meet the desired final RNA conc\r\n #\r\n # @params rna_dil_vol [int] is the volume of RNA required to meet the desired final conc.\r\n # @returns h2o_dil_vol [int] is the volume of water required to meet the desired final conc.\r\n def dilute_h2o(rna_dil_vol)\r\n h2o_dil_vol = FINAL_VOL - rna_dil_vol\r\n if h2o_dil_vol < 0\r\n return 0\r\n else\r\n return h2o_dil_vol\r\n end\r\n # (h2o_dil_vol < 0) ? (return 0) : (return h2o_dil_vol)\r\n end\r\n \r\n # Finds all RNA extractions in the job and directs tech to grab them - TODO: Sort by box/location\r\n def thaw_rna_etracts()\r\n rna_etracts = operations.map {|op| op.input(INPUT).item}\r\n take(rna_etracts, interactive: true)\r\n show do\r\n title \"Thawing Samples\"\r\n separator\r\n note \"Let the RNA Extract(s) thaw at room temperature.\"\r\n end\r\n end\r\n \r\n # Directs tech to fill the output collection with the correct item, rna_vol, and water_vol into the appropriate well\r\n # \r\n # out_colleciions [Array of objs] is an array of collection objs that the RNAs will get diluted into\r\n def normalize_and_fill_rna_plates()\r\n r_num = Random.new\r\n \r\n groupby_out_collection = operations.group_by {|op| op.output(OUTPUT).collection}\r\n \r\n groupby_out_collection.each {|out_coll, ops|\r\n obj_type = ObjectType.find(out_coll.object_type_id)\r\n ops.each {|op|\r\n rna_item = op.input(INPUT).item\r\n rna_item.get(:concentration).nil? ? rna_conc = r_num.rand(1000) : rna_conc = rna_item.get(:concentration)\r\n op.temporary[:rna_dil_vol] = dilute_rna(rna_conc)\r\n op.temporary[:h2o_dil_vol] = dilute_h2o(op.temporary[:rna_dil_vol])\r\n }\r\n rc_list = ops.map {|op| [op.output(OUTPUT).row, op.output(OUTPUT).column]}\r\n item_matrix = ops.map {|op| op.input(INPUT).item.id}.each_slice(obj_type.columns).map {|slice| slice}\r\n rna_vol_matrix = ops.map {|op| op.temporary[:rna_dil_vol]}.each_slice(obj_type.columns).map {|slice| slice}\r\n h2o_vol_matrix = ops.map {|op| op.temporary[:h2o_dil_vol]}.each_slice(obj_type.columns).map {|slice| slice}\r\n log_info 'rna_vol_matrix',rna_vol_matrix,'h2o_vol_matrix',h2o_vol_matrix\r\n \r\n show do\r\n title \"Gather Material(s)\"\r\n separator\r\n check \"Gather a #{obj_type.name} and label #{out_coll.id}\"\r\n end\r\n \r\n tot_h2o_vol = 0\r\n h2o_vol_matrix.flatten.each {|vol| tot_h2o_vol += vol}\r\n show do\r\n title \"Fill #{obj_type.name} #{out_coll} with MG H2O\"\r\n separator\r\n check \"For the next steps you will need #{(tot_h2o_vol + 20.0).round(2)}#{MICROLITERS}\"\r\n end\r\n \r\n show do\r\n title \"Fill #{obj_type.name} #{out_coll} with MG H2O\"\r\n separator\r\n note \"Follow the table below to fill the plate:\"\r\n table highlight_alpha_rc(out_coll, rc_list) { |r, c| \"#{h2o_vol_matrix[r][c].round(1)}#{MICROLITERS}\" }\r\n end\r\n \r\n fill_by_row = rc_list.group_by {|r,c| r}.sort\r\n fill_by_row.each { |row, rc_list|\r\n show do\r\n title \"Fill #{obj_type.name} #{out_coll} with RNA [#{INPUT_RNA_CONC/FINAL_VOL}#{NANOGRAMS}/#{MICROLITERS}]\"\r\n separator\r\n table highlight_alpha_rc(out_coll, rc_list) { |r, c| \"#{item_matrix[r][c]}\\n#{rna_vol_matrix[r][c].round(1)}#{MICROLITERS}\" }\r\n end\r\n }\r\n }\r\n show do\r\n title \"Centrifuge Plate(s)\"\r\n separator\r\n note \"Use the large centrifuge with the the plate rotor\"\r\n check \"Spin plate(s) at 500 x g for 1 min to collect everything into the well.\"\r\n end\r\n end\r\nend #Class\r\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2972999,"cells":{"blob_id":{"kind":"string","value":"36c02a112f3c9408455458dbce25c4c33f317c90"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"Mew-Traveler/mew-api"},"path":{"kind":"string","value":"/lib/airbnb_api.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":659,"string":"659"},"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":"require 'http'\n\nmodule Airbnb\n # Service for all Airbnb API calls\n class AirbnbApi\n #Setting the URL and parameters\n Airbnb_URL = 'https://api.airbnb.com/'\n API_VER = 'v2'\n Airbnb_API_URL = URI.join(Airbnb_URL, \"#{API_VER}/\")\n Search_URL = URI.join(Airbnb_API_URL, \"search_results\")\n\n # attr_reader :airbnb_data\n def initialize(airbnb_id:)\n @airbnb_id = airbnb_id\n end\n\n def rooms_info(location)\n rooms_response = HTTP.get(Search_URL,\n params: { client_id: @airbnb_id,\n location: location\n })\n roomsinfo = JSON.load(rooms_response.to_s)['search_results']\n\n end\n\n end\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}}],"truncated":false,"partial":false},"paginationData":{"pageIndex":29729,"numItemsPerPage":100,"numTotalItems":2976874,"offset":2972900,"length":100}},"jwt":"eyJhbGciOiJFZERTQSJ9.eyJyZWFkIjp0cnVlLCJwZXJtaXNzaW9ucyI6eyJyZXBvLmNvbnRlbnQucmVhZCI6dHJ1ZX0sImlhdCI6MTc1ODM1MjU2MCwic3ViIjoiL2RhdGFzZXRzL2hvbmdsaXU5OTAzL3N0YWNrX2VkdV9ydWJ5IiwiZXhwIjoxNzU4MzU2MTYwLCJpc3MiOiJodHRwczovL2h1Z2dpbmdmYWNlLmNvIn0.oFtvb7o1UpIL72tH60ZWrnKKV6BLeVe-2MpibbLxtAipZtv9zTJYY_2P7QiAcj3k-W2xGtnfDv1efp0tR18XBQ","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
81e0f50f88fbd6b7e0ddf47fbb8ad335f073e18d
Ruby
namusyaka/mandrake
/lib/mandrake/dsl/stringify.rb
UTF-8
1,978
3.234375
3
[ "MIT" ]
permissive
module Mandrake module DSL # A class for building an expression by using the method_missing method # @example # Oh = Class.new(Mandrake::DSL::Stringify) # Oh.stringify.Mikey.hello('boy').to_s #=> "oh.Mikey.hello(\"boy\")" # Oh.stringify.James.goodbye('man').to_s #=> "oh.James.goodbye(\"man\")" # Oh.stringify.Mikey.hello('boy').and(Oh.stringify.James.goodbye('man')).to_s # #=> "oh.Mikey.hello(\"boy\") && oh.James.goodbye(\"man\")" # @!visibility private class Stringify # @!visibility private def stringify self.class.stringify end # @!visibility private def self.stringify Stringify::Relation.new(self) end # @!visibility private class Relation # Defines a method for the relation # @param [String, Symbol] name # @yield block on which to base the method # @!visibility private def self.chain(name, &block) define_method(name){|*args| instance_exec(*args, &block); self; } end # @param [Class] klass # @!visibility private def initialize(klass) @class = klass reset_string end # Returns a string built by this class # @!visibility private def to_s @string end chain(:[]) {|*args| @string << "[#{args.map(&:inspect) * ", "}]" } chain(:==) {|value| @string << " == #{value.inspect}" } chain(:and) {|relation| @string << " && " << relation.to_s } chain(:or) {|relation| @string << " || " << relation.to_s } chain(:method_missing) {|method_name, *args| @string << ".#{method_name}" @string << "(#{args.map(&:inspect) * ", "})" unless args.length.zero? } chain(:reset_string) { @string = "#{@class.name.downcase.split(/::/).last}" } alias equal == alias eq equal end end end end
true
22ece5b63a7a2e15c8df662ebd10c393f7068a10
Ruby
learn-co-students/atl-bonus-lectures
/testify-052819/spec/gilded_rose_spec.rb
UTF-8
4,153
2.921875
3
[]
no_license
require_relative 'spec_helper' describe "Gilded Rose" do it "should be able to tick a gilded rose" do # given a gilded rose rose = GildedRose.for("example", 20, 30) # when i tick rose.tick # then i expect quality and sell_in to go down by one expect(rose.sell_in).to eq(19) expect(rose.quality).to eq(29) end it "should decreate quality by two on the sell date" do rose = GildedRose.for("example", 0, 10) rose.tick expect(rose.quality).to eq(8) expect(rose.sell_in).to eq(-1) end it "should decrease quality by two after the sell date" do rose = GildedRose.for("example", -1, 10) rose.tick expect(rose.quality).to eq(8) expect(rose.sell_in).to eq(-2) end it "should never reach negative quality" do rose = GildedRose.for("example", 20, 0) rose.tick expect(rose.quality).to eq(0) expect(rose.sell_in).to eq(19) end it "should lose two quality after the sell by date if it isn't brie" do rose = GildedRose.for("example", 0, 12) rose.tick expect(rose.quality).to eq(10) expect(rose.sell_in).to eq(-1) end it "should increase quality of aged brie when we tick" do rose = GildedRose.for("Aged Brie", 20, 30) rose.tick expect(rose.quality).to eq(31) expect(rose.sell_in).to eq(19) end it "should increase the quality of aged brie after the sell date" do rose = GildedRose.for("Aged Brie", 0, 10) rose.tick expect(rose.quality).to eq(12) expect(rose.sell_in).to eq(-1) end it "should cap quality for brie at 50" do rose = GildedRose.for("Aged Brie", 20, 50) rose.tick expect(rose.quality).to eq(50) expect(rose.sell_in).to eq(19) end it "should cap quality for brie at 50 even after the sell date" do rose = GildedRose.for("Aged Brie", -1, 49) rose.tick expect(rose.quality).to eq(50) expect(rose.sell_in).to eq(-2) end it "should increase quality for backstage passes" do rose = GildedRose.for("Backstage passes to a TAFKAL80ETC concert", 20, 30) rose.tick expect(rose.quality).to eq(31) expect(rose.sell_in).to eq(19) end it "should bump quality by 2 when sell_in is 10 or less for backstage passes" do rose = GildedRose.for("Backstage passes to a TAFKAL80ETC concert", 10, 20) rose.tick expect(rose.quality).to eq(22) expect(rose.sell_in).to eq(9) end it "should bump quality by 3 for passes when sell_in is 5 or less" do rose = GildedRose.for("Backstage passes to a TAFKAL80ETC concert", 5, 20) rose.tick expect(rose.quality).to eq(23) expect(rose.sell_in).to eq(4) end it "should not modify sulfuras, hand of ragnaros for any reason" do rose = GildedRose.for("Sulfuras, Hand of Ragnaros", 20, 30) rose.tick expect(rose.quality).to eq(30) expect(rose.sell_in).to eq(20) end it "should cap quality for passes at 50" do rose = GildedRose.for("Backstage passes to a TAFKAL80ETC concert", 20, 50) rose.tick expect(rose.quality).to eq(50) expect(rose.sell_in).to eq(19) end it "should set quality to zero for passes after their sell date" do rose = GildedRose.for("Backstage passes to a TAFKAL80ETC concert", 0, 40) rose.tick expect(rose.quality).to eq(0) expect(rose.sell_in).to eq(-1) end it "should lower quality by 2 for conjured mana cake" do rose = GildedRose.for("Conjured Mana Cake", 5, 10) rose.tick expect(rose.quality).to eq(8) expect(rose.sell_in).to eq(4) end it "should limit mana cake to a minimum quality of zero" do rose = GildedRose.for("Conjured Mana Cake", 5, 0) rose.tick expect(rose.quality).to eq(0) expect(rose.sell_in).to eq(4) end it "should drop quality by 4 on the sell date for mana cake" do rose = GildedRose.for("Conjured Mana Cake", 0, 10) rose.tick expect(rose.quality).to eq(6) expect(rose.sell_in).to eq(-1) end it "should drop quality by 4 after the sell date for mana cake" do rose = GildedRose.for("Conjured Mana Cake", -1, 10) rose.tick expect(rose.quality).to eq(6) expect(rose.sell_in).to eq(-2) end end
true
9392672c36c6be328a331b73301b72162a3b1223
Ruby
tnishi/rdf-config
/bin/rdf-config
UTF-8
3,025
2.671875
3
[ "MIT" ]
permissive
#!/usr/bin/env ruby $LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib')) require 'getoptlong' require 'rdf-config' def help puts DATA.read exit end opts = { :config_dir => nil, :mode => nil, } args = GetoptLong.new( [ '--config', '-c', GetoptLong::REQUIRED_ARGUMENT ], [ '--help', '-h', GetoptLong::NO_ARGUMENT ], [ '--senbero', GetoptLong::NO_ARGUMENT ], [ '--schema', GetoptLong::OPTIONAL_ARGUMENT ], [ '--sparql', GetoptLong::OPTIONAL_ARGUMENT ], [ '--query', GetoptLong::OPTIONAL_ARGUMENT ], [ '--sparqlist', GetoptLong::OPTIONAL_ARGUMENT ], [ '--grasp', GetoptLong::OPTIONAL_ARGUMENT ], [ '--stanza', GetoptLong::OPTIONAL_ARGUMENT ], [ '--stanza_rb', GetoptLong::OPTIONAL_ARGUMENT ], [ '--shex', GetoptLong::OPTIONAL_ARGUMENT ] ) begin args.each_option do |name, value| case name when /--config/ opts[:config_dir] = value when /--senbero/ opts[:mode] = :senbero when /--schema/ opts[:mode] = :chart opts[:schema_opt] = value when /--sparqlist/ opts[:mode] = :sparqlist when /--sparql/ opts[:mode] = :sparql opts[:sparql_query_name] = value when /--query/ # pipe to https://gist.github.com/ktym/3385134 ? opts[:mode] = :query when /--grasp/ opts[:mode] = :grasp when /--stanza_rb/ opts[:mode] = :stanza_rb opts[:stanza_name] = value when /--stanza/ opts[:mode] = :stanza_js opts[:stanza_name] = value when /--shex/ opts[:mode] = :shex end end rescue puts help exit(1) end if opts[:config_dir] and opts[:mode] begin rdf_config = RDFConfig.new(opts) rdf_config.exec(opts) rescue => e STDERR.puts e.message exit(1) end else help end __END__ NAME rdf-config -- RDF model to SPARQL, Schema, Stanza converter SYNOPSIS rdf-config --help rdf-config --config path/to/config/name --sparql [queryname] rdf-config --config path/to/config/name --schema rdf-config --config path/to/config/name --senbero rdf-config --config path/to/config/name --grasp rdf-config --config path/to/config/name --stanza [stanzaname] rdf-config --config path/to/config/name --stanza_rb [stanzaname] rdf-config --config path/to/config/name --shex DESCRIPTION Read a RDF data model from config/name/ directory then generate SPARQL query, exec SPARQL query, generate Schema chart, and generate Stanza. Configuration files of a RDF model are written in the YAML format. * config/name/model.yaml: RDF deta model structure and variable names * config/name/endpoint.yaml: SPARQL endpoint * config/name/prefix.yaml: URI prefixes * config/name/sparql.yaml: SPARQL definition * config/name/stanza.yaml: TogoStanza definition * config/name/metadata.yaml: Metadata compatible with NBRC RDF portal * config/name/metadata_ja.yaml: Japanese version of Metadata
true
3f674d63b7e56e22080b9acdc71849957b420c49
Ruby
jgrazulis/1module
/Challenges/mid_mod/spec/term_spec.rb
UTF-8
1,298
3.171875
3
[]
no_license
require './lib/course' require './lib/student' require './lib/term' describe 'Term class' do it 'exists' do calculus = Course.new("Calculus", 2) term = Term.new("Winter 2018", [calculus]) expect(term).to be_an_instance_of(Term) end it 'has attributes' do calculus = Course.new("Calculus", 2) term = Term.new("Winter 2018", [calculus]) expect(term.name).to eq("Winter 2018") expect(term.courses).to eq([calculus]) end end describe 'courses in term' do it 'lists open courses' do calculus = Course.new("Calculus", 2) coding_101 = Course.new("coding_101", 3) term = Term.new("Winter 2018", [calculus, coding_101]) student1 = Student.new({name: "Morgan", age: 21}) student2 = Student.new({name: "Jordan", age: 29}) calculus.enroll(student1) calculus.enroll(student2) expect(term.open_courses).to eq([coding_101]) end it 'has a list of students' do student1 = Student.new({name: "Morgan", age: 21}) student2 = Student.new({name: "Jordan", age: 29}) calculus = Course.new("Calculus", 2) coding_101 = Course.new("coding_101", 3) term = Term.new("Winter 2018", [calculus, coding_101]) calculus.enroll(student1) calculus.enroll(student2) expect(term.students).to eq([student1, student2]) end end
true
f13ee1d4948e4e15bc9f229a3f9220f63dbb473b
Ruby
wuhuizuo/SCTM
/tech_demos/sf_parser.rb
UTF-8
764
2.546875
3
[ "MIT" ]
permissive
require_relative 'sf_baidu_parser' module Sctm class SfParser SF_SITES = { baidu: 'http://rj.baidu.com/' } SF_PARSERS = { baidu: SfBaiduParser } # @param [String] sf_center 软件中心类别 def initialize(sf_center = :baidu) @sf_main_url = SF_SITES[sf_center] @parser = SF_PARSERS[sf_center].new(@sf_main_url) end # 获取软件大类的分类 def get_groups @parser.get_groups end # 获取指定类别下的软件列表 def get_apps(group, limit = -1) @parser.get_apps(group, limit) end # 获取应用信息 # @param [String] app_name 查询应用名称 def get_app_detail(app_name) @parser.get_app_detail(app_name) end end end
true
ca1a0cd2550e51864aec8fdf493580b1c8c743a6
Ruby
baggio63446333/mrubyc
/examples/ledswitch/ledswitch.rb
UTF-8
258
2.640625
3
[ "BSD-3-Clause" ]
permissive
val = 0 portled = 64 portsw = 33 pin_mode(portsw, 0); while true if val == 1 val = 0 else val = 1 end if digital_read(portsw) == 0 portled += 1 if portled > 67 break end end digital_write(portled, val) sleep 1 end
true
13f868dc9a62b82335f818310bde77e227dc2270
Ruby
jtblow/oxford-comma-chicago-web-career-040119
/lib/oxford_comma.rb
UTF-8
237
3.4375
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def oxford_comma(array) if array.length === 1 array.join elsif array.length === 2 array.join(" and ") elsif array.length === 3 array[0..1].join(", ") + ", and " + array[2] else array[0..-2].join(", ") + ", and " + array[-1] end end
true
e9d1f4086f04670e6fc268a8a90938c7b845169e
Ruby
ttt242242/fx
/rubyOkn/EasyGraphMaker.rb
UTF-8
1,009
2.5625
3
[]
no_license
# -*- coding: utf-8 -*- $LOAD_PATH.push(File::dirname($0)) ; require "pry" require "gnuplot" Gnuplot.open do |gp| Gnuplot::Plot.new( gp ) do |plot| plot.output "test.eps" plot.set 'terminal postscript 16 eps enhanced color ' #必要epsで保存するには plot.size "1,0.8" plot.origin "0.0, 0.0" plot.grid x = (0..50).collect {|v| v.to_f} c = 10.0 ; array = Array.new array2 = Array.new x.each do |x1| # y = (1.0/(1.0+x1/35.0)) ; # y = (1.0/(1.0+x1/5.0)) ; y = x1 * Math.exp(-x1/c) ; array.push(y) ; if x1 <= c y = x1 else y = c * Math.exp(-x1/c) ; end array2.push(y) ; end plot.data << Gnuplot::DataSet.new( [x,array] ) do |ds| ds.with = "lp" #line+point ds.linewidth =1 ds.title = "test" ; end plot.data << Gnuplot::DataSet.new( [x,array2] ) do |ds| ds.with = "lp" #line+point ds.linewidth =1 ds.title end end end
true
88ee7b0e687ee11fe9db36bd611cad694ff29f2e
Ruby
jdun10/phase-0
/week-5/die-class/my_solution.rb
UTF-8
1,464
4.59375
5
[ "MIT" ]
permissive
# Die Class 1: Numeric # I worked on this challenge by myself. # I spent [] hours on this challenge. # 0. Pseudocode # Input: calling the method # Output: a number 1-6 # Steps: There will be a function that goes from 1-6 and selects a number. # A random number will be returned. # 1. Initial Solution # class Die # def initialize # die = Die.new(6) #This creates a new die object with 6 sides # end # def sides # die.sides == 6 # returns 6 # end # def roll # die.roll # returns a random number between 1 and 6 # puts rand(6) + 1 # end # end # def roll; # 3. Refactored Solution def roll puts rand(6) +1 end roll # 4. Reflection # What is an ArgumentError and why would you use one? # => I don't understand how to use Classes and how the other methods within a class relate to another method. # What new Ruby methods did you implement? What challenges and successes did you have in implementing them? # => The rand method was new to me but pretty simply used to generate a number from 1 to 6. # What is a Ruby class? # => Something that stores other methods in a group. # Why would you use a Ruby class? # => I don't know. # What is the difference between a local variable and an instance variable? # => A local variable is only applicable within its defined method. An instance variable is applicable within its Class. # Where can an instance variable be used? # => It can be used within its Class.
true
1f6c762f6bed9414e1115d70732b57dfead768de
Ruby
escobara/ro_design_patterns
/strategy_pattern/strategy_v1.rb
UTF-8
1,049
3.71875
4
[]
no_license
class Formatter def output_report(title, text) raise 'Abstract method called' end end class HTMLFormatter < Formatter def output_report(title, content) puts('<html>') puts(' <head>') puts(" <title> #{title} </title>") puts(' </head>') puts(' </body>') content.each do |line| puts(" <p>#{line}</p>") end puts(' </body>') puts('</html>') end end class PlainTextFormatter < Formatter def output_report(title, text) puts("***** #{title} *****") text.each do |line| puts(line) end end end class Report attr_reader :title, :content attr_accessor :formatter def initialize(formatter) @title = 'Monthly Report' @content = [ 'Things are going', 'really, really well.'] @formatter = formatter end def output_report @formatter.output_report(@title, @content) end end report = Report.new(HTMLFormatter.new) report.output_report # <html> # <head> # <title> Monthly Report </title> # </head> # </body> # <p>Things are going</p> # <p>really, really well.</p> # </body> # </html>
true
58f12cf64c1adc27327c2b99c035acda9ac9f1de
Ruby
jinhale/viper
/spec/make_bindings_spec.rb
UTF-8
3,201
2.640625
3
[ "MIT" ]
permissive
# make_bindings_spec.rb - specs for make_bindings require_relative 'spec_helper' describe 'make_bindings returns a key inserter proc for letters' do let(:buf) { Buffer.new '' } let(:bind) { make_bindings } let(:prc) { bind[:key_p] } subject { prc.call(buf); buf.to_s } specify { subject.must_equal 'p' } end describe 'inserter for caps' do let(:buf) { Buffer.new '' } let(:bind) { make_bindings } let(:prc) { bind[:key_A] } subject { prc.call(buf); buf.to_s } specify { subject.must_equal 'A' } end describe 'inserter 0' do let(:buf) { Buffer.new '' } let(:bind) { make_bindings } let(:prc) { bind[:key_0] } subject { prc.call(buf); buf.to_s } specify { subject.must_equal '0' } end describe 'special chars :space' do let(:buf) { Buffer.new '' } let(:bind) { make_bindings } let(:prc) { bind[:space] } subject { prc.call(buf); buf.to_s } specify { subject.must_equal ' ' } end describe 'ctrl_z cannot undo' do let(:buf) { ReadOnlyBuffer.new 'yyy' } let(:bind) { make_bindings } let(:prc) { bind[:ctrl_z] } subject { buf.ins 'xxx'; prc.call(buf); buf.to_s } specify { subject.must_equal 'yyy' } end describe 'Can undo insert' do let(:buf) { ScratchBuffer.new } let(:bind) { make_bindings } let(:prc) { bind[:ctrl_z] } subject { buf.ins 'xxx'; prc.call(buf); buf.to_s } specify { subject.must_equal '' } end class CannotRecordMe < Buffer include NonRecordable end describe 'ReadOnlyBuffer cannot redo from ctrl_u' do let(:buf) { CannotRecordMe.new '' } let(:bind) { make_bindings } let(:prc) { bind[:ctrl_u] } subject { buf.ins 'xxx'; buf.undo; prc.call(buf); buf.to_s } specify { subject.must_equal 'xxx' } end describe 'Can redo undon action from proc in bindings' do let(:buf) { ScratchBuffer.new } let(:bind) { make_bindings } let(:prc) { bind[:ctrl_u] } subject { buf.ins 'xxx'; buf.undo; prc.call(buf); buf.to_s } specify { subject.must_equal 'xxx' } end describe 'backspace if mark set' do let(:buf) { ScratchBuffer.new } let(:bind) { make_bindings } let(:prc) { bind[:backspace] } subject { buf.ins 'xxxxx'; buf.beg; buf.set_mark; buf.fwd 3; prc.call(buf); $clipboard } specify { subject.must_equal 'xxx' } end describe 'backspace when no mark set' do let(:buf) { ScratchBuffer.new } let(:bind) { make_bindings } let(:prc) { bind[:backspace] } subject { buf.ins 'xyz'; prc.call(buf); buf.to_s } specify { subject.must_equal 'xy' } end describe 'fn_4 sets mark when not set' do let(:buf) { ScratchBuffer.new } let(:bind) { make_bindings } let(:prc) { bind[:fn_4] } subject { buf.ins 'zzz'; buf.beg; prc.call(buf); buf.mark_set? } specify { subject.must_equal true } end describe 'fn_4 unsets mark when set' do let(:buf) { ScratchBuffer.new } let(:bind) { make_bindings } let(:prc) { bind[:fn_4] } subject { buf.ins 'zzz'; buf.beg; buf.set_mark; buf.fwd; prc.call(buf); buf.mark_set? } specify { subject.must_equal false } end describe 'ctrl_w move word fwd' do let(:buf) { Buffer.new '0123 4567' } let(:bind) { make_bindings } let(:prc) { bind[:ctrl_w] } subject { prc.call buf; buf.word_fwd } specify { subject.must_equal '4567' } end
true
bbf2df7fd953a34af26d3bd6dcf2081f9997dece
Ruby
GaronHock/Homework
/octopus problems/octopus.rb
UTF-8
2,094
4.3125
4
[]
no_license
# A Very Hungry Octopus wants to eat the longest fish in an array of fish. # ['fish', 'fiiish', 'fiiiiish', 'fiiiish', 'fffish', 'ffiiiiisshh', 'fsh', 'fiiiissshhhhhh'] # => "fiiiissshhhhhh" # Sluggish Octopus # Find the longest fish in O(n^2) time. Do this by comparing all fish lengths to all other fish lengths def sluggish_octopus(arr) longest = Hash.new(0) arr.each_with_index do |ele, i| longest[ele] = arr[i].length end sorted = longest.sort_by{|k,v| v} sorted[-1][0] end # fish = ['fish', 'fiiish', 'fiiiiish', 'fiiiish', 'fffish', 'ffiiiiisshh', 'fsh', 'fiiiissshhhhhh'] # p sluggish_octopus(fish) # Dominant Octopus # Find the longest fish in O(n log n) time. Hint: You saw a sorting algorithm that runs # in O(n log n) in the Sorting Complexity Demo. Remember that Big O is classified by the dominant term class Array # Write an Array#merge_sort method; it should not modify the original array. def dominant_octopus_merge_sort(&prc) prc ||= Proc.new{|a,b| a<=>b} return self if self.length < 2 mid = self.length / 2 left = self.take(mid) right = self.drop(mid) sorted_left = left.dominant_octopus_merge_sort(&prc) sorted_right = right.dominant_octopus_merge_sort(&prc) Array.merge(sorted_left,sorted_right, &prc) end private def self.merge(left, right, &prc) sorted = [] until left.empty? || right.empty? if prc.call(left.first.length, right.first.length) == -1 sorted << left.shift else sorted << right.shift end end sorted + left + right end end fish = ['fish', 'fiiish', 'fiiiiish', 'fiiiish', 'fffish', 'ffiiiiisshh', 'fsh', 'fiiiissshhhhhh'] p fish.dominant_octopus_merge_sort # Clever Octopus # Find the longest fish in O(n) time. # The octopus can hold on to the longest fish that you have found so far # while stepping through the array only once. def clever_octopus(arr) longest = "" arr.each do |ele| if ele.length > ele.length - 1 longest = ele end end longest end p clever_octopus(fish)
true
0db0691ddf25e2d2defd21cdc610a551066fa4ba
Ruby
nekokat/codewars
/8 kyu_1/grasshopper-make-change.rb
UTF-8
184
2.90625
3
[ "Unlicense" ]
permissive
#Kata: Grasshopper - Make change #URL: https://www.codewars.com/kata/560dab9f8b50f89fd6000070 money = 10 candy = 1.42 chips = 2.4 soda = 1 change = money - candy - chips - soda
true
c34128da13a2d380e31235d24fd7b329eda8608e
Ruby
denisson/BibliaSocial
/config/initializers/integer.rb
UTF-8
86
2.6875
3
[]
no_license
class Integer def quantos() return self.to_s if self > 0 return "" end end
true
2ddeb8f002933e7714a4b2c0a1679aadf627540e
Ruby
DiegoSalazar/template_parsing_challenge
/template_parser.rb
UTF-8
1,587
3.5
4
[]
no_license
# Given a template and an environment, fill the template with correct values. class TemplateParser IF_TAG = ?# # prefix for if tags UNLESS_TAG = ?^ # prefix for unless tags NIL_VAR = '' TAG_CAPTURE = / {(.+)} # capture an opening tag (.+) # capture content after opening tag {(\1)} # capture tag matching first capture | # or {(.+)} # capture just a tag /x # @param environment # a hash of values to interpolate into templates def initialize(environment) @environment = environment end # @param template # a string template # @return an interpolated string def parse(template) @template = template.dup interpolate_environment while contains_tags? @template end private def contains_tags? @template =~ TAG_CAPTURE end def interpolate_environment match, tag, content, _, variable = TAG_CAPTURE.match(@template).to_a return if match.nil? interpolate_variable match, variable if variable interpolate_tags match, tag, content if tag end def interpolate_variable(match, variable) @template.gsub! match, @environment.fetch(variable.downcase.to_sym, NIL_VAR) end def interpolate_tags(match, tag, content) symbol = tag.sub(/[#{IF_TAG}#{UNLESS_TAG}]/, NIL_VAR).downcase.to_sym @template.gsub! match, if tag =~ /#{IF_TAG}/ @environment[symbol] ? content : NIL_VAR elsif tag =~ /#{UNLESS_TAG}/ @environment[symbol] ? NIL_VAR : content end.strip end end
true
d2d00f06487a04f9ba0670fcdddac562085fae68
Ruby
juanlfr/tests-ruby
/lib/03_basics.rb
UTF-8
484
3.390625
3
[]
no_license
def who_is_bigger(a,b,c) if a==nil || b==nil || c==nil then return "nil detected" elsif a==[a,b,c].max then return("a is bigger") elsif b==[a,b,c].max then return("b is bigger") else return("c is bigger") end end def reverse_upcase_noLTA(string) return string.reverse.upcase.delete 'LTA' end def array_42(array) if array.count(42)>0 then return true else return false end end def magic_array(array) return array.flatten.sort.map{|x| x*=2}.reject{|x| x%3==0}.uniq end
true
8c307273ee2e549fec139bae0c9ab6e6bcdf8620
Ruby
narayana1208/git-review
/lib/git-review/local.rb
UTF-8
7,733
2.65625
3
[ "MIT" ]
permissive
module GitReview # The local repository is where the git-review command is being called # by default. It is (supposedly) able to handle systems other than Github. # TODO: remove Github-dependency class Local include ::GitReview::Internals attr_accessor :config # acts like a singleton class but it's actually not # use ::GitReview::Local.instance everywhere except in tests def self.instance @instance ||= new end def initialize # find root git directory if currently in subdirectory if git_call('rev-parse --show-toplevel').strip.empty? raise ::GitReview::InvalidGitRepositoryError else add_pull_refspec load_config end end # @return [Array<String>] all existing branches def all_branches git_call('branch -a').split("\n").collect { |s| s.strip } end # @return [Array<String>] all open requests' branches shouldn't be deleted def protected_branches github.current_requests.collect { |r| r.head.ref } end # @return [Array<String>] all review branches with 'review_' prefix def review_branches all_branches.collect { |branch| # only use uniq branch names (no matter if local or remote) branch.split('/').last if branch.include?('review_') }.compact.uniq end # clean a single request's obsolete branch def clean_single(number, force=false) request = github.pull_request(source_repo, number) if request && request.state == 'closed' # ensure there are no unmerged commits or '--force' flag has been set branch_name = request.head.ref if unmerged_commits?(branch_name) && !force puts "Won't delete branches that contain unmerged commits." puts "Use '--force' to override." else delete_branch(branch_name) end end rescue Octokit::NotFound false end # clean all obsolete branches def clean_all (review_branches - protected_branches).each do |branch_name| # only clean up obsolete branches. delete_branch(branch_name) unless unmerged_commits?(branch_name, false) end end # delete local and remote branches that match a given name # @param branch_name [String] name of the branch to delete def delete_branch(branch_name) delete_local_branch(branch_name) delete_remote_branch(branch_name) end # delete local branch if it exists. # @param (see #delete_branch) def delete_local_branch(branch_name) if branch_exists?(:local, branch_name) git_call("branch -D #{branch_name}", true) end end # delete remote branch if it exists. # @param (see #delete_branch) def delete_remote_branch(branch_name) if branch_exists?(:remote, branch_name) git_call("push origin :#{branch_name}", true) end end # @param location [Symbol] location of the branch, `:remote` or `:local` # @param branch_name [String] name of the branch # @return [Boolean] whether a branch exists in a specified location def branch_exists?(location, branch_name) return false unless [:remote, :local].include?(location) prefix = location == :remote ? 'remotes/origin/' : '' all_branches.include?(prefix + branch_name) end # @return [Boolean] whether there are local changes not committed def uncommitted_changes? !git_call('diff HEAD').empty? end # @param branch_name [String] name of the branch # @param verbose [Boolean] if verbose output # @return [Boolean] whether there are unmerged commits on the local or # remote branch. def unmerged_commits?(branch_name, verbose=true) locations = [] locations << '' if branch_exists?(:local, branch_name) locations << 'origin/' if branch_exists?(:remote, branch_name) locations = locations.repeated_permutation(2).to_a if locations.empty? puts 'Nothing to do. All cleaned up already.' if verbose return false end # compare remote and local branch with remote and local master responses = locations.collect { |loc| git_call "cherry #{loc.first}#{target_branch} #{loc.last}#{branch_name}" } # select commits (= non empty, not just an error message and not only # duplicate commits staring with '-'). unmerged_commits = responses.reject { |response| response.empty? or response.include?('fatal: Unknown commit') or response.split("\n").reject { |x| x.index('-') == 0 }.empty? } # if the array ain't empty, we got unmerged commits if unmerged_commits.empty? false else puts "Unmerged commits on branch '#{branch_name}'." true end end # @return [Boolean] whether there are commits not in target branch yet def new_commits?(upstream=false) target = upstream ? 'upstream/master' : target_branch not git_call("cherry #{target}").empty? end # @return [Boolean] whether a specified commit has already been merged. def merged?(sha) branches = git_call("branch --contains #{sha} 2>&1").split("\n"). collect { |b| b.delete('*').strip } branches.include?(target_branch) end # @return [String] the source repo def source_repo github.source_repo end # @return [String] the current source branch def source_branch git_call('branch').chomp.match(/\*(.*)/)[0][2..-1] end # @return [String] combine source repo and branch def source "#{source_repo}/#{source_branch}" end # @return [String] the name of the target branch def target_branch # TODO: Manually override this and set arbitrary branches ENV['TARGET_BRANCH'] || 'master' end # if to send a pull request to upstream repo, get the parent as target # @return [String] the name of the target repo def target_repo(upstream=false) # TODO: Manually override this and set arbitrary repositories if upstream github.repository(source_repo).parent.full_name else source_repo end end # @return [String] combine target repo and branch def target "#{target_repo}/#{target_branch}" end # @return [String] the head string used for pull requests def head # in the form of 'user:branch' "#{source_repo.split('/').first}:#{source_branch}" end # @return [Boolean] whether already on a feature branch def on_feature_branch? # If current and target are the same, we are not on a feature branch. # If they are different, but we are on master, we should still to switch # to a separate branch (since master makes for a poor feature branch). source_branch != target_branch && source_branch != 'master' end # add remote.origin.fetch to check out pull request locally # see {https://help.github.com/articles/checking-out-pull-requests-locally} def add_pull_refspec refspec = '+refs/pull/*/head:refs/remotes/origin/pr/*' fetch_config = "config --local --add remote.origin.fetch #{refspec}" git_call(fetch_config, false) unless config_list.include?(refspec) end def load_config @config = {} config_list.split("\n").each do |line| key, value = line.split(/=/, 2) if @config[key] && @config[key] != value @config[key] = [@config[key]].flatten << value else @config[key] = value end end @config end def config_list git_call('config --list', false) end def github @github ||= ::GitReview::Github.instance end end end
true
a7bfa377d2cfb9f91d417b9ca3f1e819cfe876ec
Ruby
awesome/coffeelint-ruby
/lib/coffeelint.rb
UTF-8
2,640
2.640625
3
[ "MIT" ]
permissive
require "coffeelint/version" require 'execjs' require 'coffee-script' require 'json' module Coffeelint require 'coffeelint/railtie' if defined?(Rails::Railtie) def self.path() @path ||= File.expand_path('../../coffeelint/lib/coffeelint.js', __FILE__) end def self.colorize(str, color_code) "\e[#{color_code}m#{str}\e[0m" end def self.red(str, pretty_output = true) pretty_output ? Coffeelint.colorize(str, 31) : str end def self.green(str, pretty_output = true) pretty_output ? Coffeelint.colorize(str, 32) : str end def self.context coffeescriptSource = File.read(CoffeeScript::Source.path) bootstrap = <<-EOF window = { CoffeeScript: CoffeeScript, coffeelint: {} }; EOF coffeelintSource = File.read(Coffeelint.path) ExecJS.compile(coffeescriptSource + bootstrap + coffeelintSource) end def self.lint(script, config = {}) if !config[:config_file].nil? fname = config.delete(:config_file) config.merge!(JSON.parse(File.read(fname))) end Coffeelint.context.call('window.coffeelint.lint', script, config) end def self.lint_file(filename, config = {}) Coffeelint.lint(File.read(filename), config) end def self.lint_dir(directory, config = {}) retval = {} Dir.glob("#{directory}/**/*.coffee") do |name| retval[name] = Coffeelint.lint_file(name, config) yield name, retval[name] if block_given? end retval end def self.display_test_results(name, errors, pretty_output = true) good = pretty_output ? "\u2713" : 'Passed' bad = pretty_output ? "\u2717" : 'Failed' if errors.length == 0 puts " #{good} " + Coffeelint.green(name, pretty_output) return true else puts " #{bad} " + Coffeelint.red(name, pretty_output) errors.each do |error| print " #{bad} " print Coffeelint.red(error["lineNumber"], pretty_output) puts ": #{error["message"]}, #{error["context"]}." end return false end end def self.run_test(file, config = {}) pretty_output = config.has_key?(:pretty_output) ? config.delete(:pretty_output) : true result = Coffeelint.lint_file(file, config) Coffeelint.display_test_results(file, result, pretty_output) end def self.run_test_suite(directory, config = {}) pretty_output = config.has_key?(:pretty_output) ? config.delete(:pretty_output) : true success = true Coffeelint.lint_dir(directory, config) do |name, errors| result = Coffeelint.display_test_results(name, errors, pretty_output) success = false if not result end success end end
true
effb7076c4fbcdc3d9008231e1b1515d0720ca05
Ruby
Maikon/learn_ruby_hard_zed
/ex9.rb
UTF-8
652
4
4
[]
no_license
# Here's some new strange stuff, remember type it exaxctly. days = "Mon Tue Wed Thu Fri Sat Sun" months = "Jan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug" puts "Here are the days: ", days # will print the list of days in a row puts "Here are the months: ", months # will print the list of months each one on its own line, # because of the \n (newline) character puts <<PARAGRAPH # beginning of the paragraph There's something going on here. With the PARAGRAPH thing We'll be able to type as much as we like. # everything between here gets converted Even 4 lines if we want, or 5, or 6. # into a string. Correct? PARAGRAPH # end of the paragraph
true
bc239ddffaa4c0b07f1b9fde83ce53a8e30e0c27
Ruby
yuta-pharmacy2359/ruby_tutorial
/第6章/Sample6_3_2.rb
UTF-8
1,118
3.515625
4
[]
no_license
text = <<-TEXT 島原の乱は1637年12月11日に発生し、1638年4月12日に終結しました。 TEXT p text.scan(/\d+年\d+月\d+日/) # ["1637年12月11日", "1638年4月12日"] p text.scan(/(\d+)年(\d+)月(\d+)日/) # [["1637", "12", "11"], ["1638", "4", "12"]] text = '本能寺の変は1582年6月21日に発生しました。' m = /(\d+)年(\d+)月(\d+)日/.match(text) puts m[0] # 1582年6月21日 puts m[1] # 1582 puts m[2] # 6 puts m[3] # 21 p m[2, 2] # ["6", "21"] puts m[-1] # 21 p m[1..3] # ["1582", "6", "21"] p m # #<MatchData "1582年6月21日" 1:"1582" 2:"6" 3:"21"> p /(\d+)年(\d+)月(\d+)日/.match('honnouji') # nil m = text.match(/(\d+)年(\d+)月(\d+)日/) p m # #<MatchData "1582年6月21日" 1:"1582" 2:"6" 3:"21"> text1 = 'ペリーは1853年7月8日に浦賀沖に来航しました。' text2 = '聖徳太子は574年に生まれました。' def ymd(text) if m = /(\d+)年(\d+)月(\d+)日/.match(text) 'マッチしました' else 'マッチしませんでした' end end puts ymd(text1) # マッチしました puts ymd(text2) # マッチしませんでした
true
1ff0aa7efb560a26e4bd3aeb701915f6f27f284d
Ruby
clone18476/ghibli_cli
/lib/api.rb
UTF-8
1,237
3.5
4
[]
no_license
class API # NOTE: all of your API methods should be class methods def self.fetch_films url = "https://ghibliapi.herokuapp.com/films/" uri = URI(url) response = Net::HTTP.get(uri) films_array = JSON.parse(response) # each hash represents a film, and we want to initialize a new drink for each hash # !!!! it's important that we're making objects (instances) with our api data # access one hash at a time to make an instance out of one hash at a time by ITERATING (as seen below) films_array.each do |film_hash| film = Film.new # THIS IS WHERE WE MAKE A NEW 'film' INSTANCE film.title = film_hash["title"] # assigning the title of the film as a part of our film object film.director = film_hash["director"] # and so on, and so forth film.producer = film_hash["producer"] film.release_date = film_hash["release_date"] film.run_time = film_hash["running_time"] film.characters = film_hash["people"] film.species = film_hash["species"] film.location = film_hash["location"] film.vehicles = film_hash["vehicles"] end end end
true
de2951aac31a02c0994cf3ae0c3c48b1e1669b8f
Ruby
HMJospeh/ruby-gets-input-v-000
/bin/greeting
UTF-8
266
3.515625
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
#!/usr/bin/env ruby require_relative '../lib/hello_ruby_programmer.rb' puts "What's happening! Welcome to the wonderful world of Ruby programming." puts "Let's get this game started!! Type in your name so we can get things going:" name = gets.strip greeting(name)
true
c6d5d74f9e4289dbaf42af53dbce87f80124107d
Ruby
MattStopa/Coding-Casts-Code
/modules/2_organizing/modules.rb
UTF-8
689
3.828125
4
[]
no_license
class Loan attr_accessor :balance_owed, :maturity_months, :interest_rate def owed_by_month balance_owed / maturity_months end def print_balance "Your balance is: #{balance_owed}" end def years_left_to_maturity maturity_months / 12 end def print_estimated_cost_per_day "The cost per day of your loan is roughly: $#{owed_by_month / 30}" end def cost_of_interest owed_by_month * interest_rate end end loan = Loan.new loan.balance_owed = 2000 loan.maturity_months = 10 loan.interest_rate = 0.01 puts loan.owed_by_month puts loan.years_left_to_maturity puts loan.cost_of_interest puts loan.print_balance puts loan.print_estimated_cost_per_day
true
becf18b0371e36657b66589b78d47bb33a8a557b
Ruby
thallam/odin_ruby
/advanced_building_blocks/lib/bubble_sort.rb
UTF-8
585
3.640625
4
[]
no_license
require 'pry' def bubble_sort(arr) binding.pry arr.length.times do arr.each_with_index do |item, index| next_item = arr[index+1] if next_item < item temp = item item = next_item next_item = temp # because a,b = b,a doesn't work end end end end =begin For each element in the list look at the next element. If it's a lower value, swap them around Continue until it is ordered Notes: Idiomatic switch below doesn't work. Next val gets nil.. Why? next_item, value = value, next_value if next_item < item =end
true
6157a36f3bbae3622f42217ae9a5909ce5bafb41
Ruby
justJosh1004/AcademyPGH
/Template Engine/Mad Libs.rb
UTF-8
518
2.828125
3
[]
no_license
require './lib/template_engine' #require './Star Wars.txt' mad_lib = Template_reader.new mad_lib.set_template(File.read('.\Star Wars.txt')) get_template = [] user_answers = [] get_template = mad_lib.get_template_fields i = 0 while i < get_template.length puts "Type in a #{get_template[i]}: " user_answers << gets.chomp i += 1 end p get_template p user_answers completed_hash = mad_lib.make_hash(get_template, user_answers) p completed_hash madlib_done = mad_lib.run_template(completed_hash) p madlib_done
true
1b404bb086eacad4bea7e6eb9915d54c469a4dcf
Ruby
Sancbella/jumpstart-app
/Basics/orangetree.rb
UTF-8
1,841
4.03125
4
[]
no_license
class OrangeTree def initialize @height = 120 @age = 0 @name = 'Mr.Orange' @orangeProduction = 0 puts 'Mr.Orange is born' end def oneYearPasses number if number <= 0 puts 'no time has passed' elsif @age = @age + (1*number) @height = @height + (30*number) puts 'Orangie is now ' + @age.to_s + ' years old' if @age >= 15 puts 'Mr. Orange is dead, RIP Mr.Orange, but say hello to Baby Orange' @age = 0 @height = 0 elsif @age == 2 puts 'Baby Orange is now Mr. Orange and produced 1 orange!' @orangeProduction = 1 elsif @age >= 3 and @age <= 15 @orangeProduction = @orangeProduction + 1 + rand(6) * number puts 'This year Mr. Orange produced ' + @orangeProduction.to_s + ' oranges!' end end end def countTheOranges if @orangeProduction == 0 puts 'There are no oranges, he\'s just a baby!' elsif @orangeProduction == 1 puts 'Mr.Orange produced 1 oranges' elsif @orangeProduction > 1 puts 'There are ' + @orangeProduction.to_s + 'Oranges' end end def pickAnOrange number puts 'There were ' + @orangeProduction.to_s + ' Oranges. It was super delicious!' puts 'You\'ve picked ' + number.to_s + ' oranges' puts 'Now there are ' + (@orangeProduction - number).to_s + ' left' @orangeProduction - number end end orangie = OrangeTree.new orangie.oneYearPasses(1) orangie.oneYearPasses(1) orangie.oneYearPasses(3) orangie.oneYearPasses(4) orangie.oneYearPasses(2) orangie.oneYearPasses(100) orangie.oneYearPasses(0) orangie.oneYearPasses(14) orangie.pickAnOrange(5)
true
2243b12cf8463297ae639c97f2d7ba15a780e2c3
Ruby
slague/night_writer
/lib/night_reader.rb
UTF-8
1,322
3.59375
4
[]
no_license
require_relative 'file_reader' require_relative 'letters' require 'pry' class NightReader attr_reader :file_reader def initialize @reader = FileReader.new end def decode_file_to_english braille = @reader.open_the_file char_count = braille.chomp.length braille_out = zip_input(scan_input(split_array_at_new_lines(braille))) message_text = characters_equal_english_letter(braille_out) File.write(ARGV[1], message_text) p "Created '#{ARGV[1]}' containing #{char_count} characters" end def split_array_at_new_lines(braille) braille.split("\n") end def scan_input(split_array_at_new_lines) scanned_braille = split_array_at_new_lines.map do |line| line.scan(/../) end scanned_braille end def zip_input(scanned_braille) zipped_input = [] until scanned_braille.empty? do zipped_input << scanned_braille[0].zip(scanned_braille[1], scanned_braille[2]) scanned_braille.shift(3) end zipped_input.flatten(1) end def characters_equal_english_letter(zipped_input) new_line = "" zipped_input.each do |character| # binding.pry english = LETTERS.key(character) new_line << english.to_s end new_line end end if __FILE__==$0 result_1 = NightReader.new result_1.decode_file_to_english end
true
e5e0ec2b01e23b428f6b1a809c65374d3d45905f
Ruby
grimesjm/clean_arch_rb
/core/lib/core/gateways/user/fake_user_repository.rb
UTF-8
257
2.8125
3
[]
no_license
class FakeUserRepository def initialize @users = [] end def save(user) require 'securerandom' user.id = SecureRandom.uuid @users << user end def find_by_username(username) @users.find { |u| u.username == username } end end
true
699519c3036ec4ba95f88a6dcc4517832a02e5ff
Ruby
access-watch/logstash-filter-accesswatch
/test.rb
UTF-8
2,917
2.578125
3
[ "Apache-2.0" ]
permissive
require "manticore" require "json" require "digest" require "lru_redux" require 'net/http' class AccessWatchClient def initialize(api_key, cache_size=10000) @client = Manticore::Client.new ssl: {ca_file: "cert.pem"} @api_key = api_key if cache_size > 0 @cache = LruRedux::ThreadSafeCache.new(cache_size) end end def handle_response(response) data = JSON.parse(response.body) if response.code == 200 {:status => :success, :data => data} else {:status => :error, :code => data["code"], :message => data["message"]} end end def url(path) "https://api.access.watch#{path}" end def submit(&block) begin block.call rescue => e {:status => :error, :error => e, :message => e.message} end end def get_json(path) self.submit { self.handle_response(@client.get(self.url(path), headers: {"Api-Key" => @api_key, "Accept" => "application/json", "User-Agent" => "Access Watch Logstash Plugin/0.2.0"})) } end def post_json(path, data) self.submit { self.handle_response(@client.post(self.url(path), headers: {"Api-Key" => @api_key, "Accept" => "application/json", "Content-Type" => "application/json", "User-Agent" => "Access Watch Logstash Plugin/0.2.0"}, body: JSON.generate(data))) } end def with_cache(id, &block) if @cache @cache.getset(id) { block.call } else block.call end end def fetch_address(ip) self.with_cache("ip-#{ip}") { self.get_json("/1.1/address/#{ip}") } end def fetch_user_agent(user_agent) self.with_cache("ua-#{Digest::MD5.hexdigest(user_agent)}") { self.post_json("/1.1/user-agent", {:value => user_agent}) } end def fetch_identity(ip, user_agent) ip = ip || '' user_agent = user_agent || '' self.with_cache("identity-#{Digest::MD5.hexdigest(ip)}-#{Digest::MD5.hexdigest(user_agent)}") { self.post_json("/1.1/identity", {:address => ip, :user_agent => user_agent}) } end def test p self.fetch_address("127.0.0.1") p "---" p self.fetch_user_agent("Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.125 Safari/537.36") p "---" p self.fetch_identity("77.123.68.232", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.125 Safari/537.36") end end client = AccessWatchClient.new("94bbc755f5b8aa96cfd40ce97faad568") p client.fetch_address("127.0.0.1")
true
a4eccd11808ed943efe5f6a2489d45704adacfde
Ruby
whastings/coding_practice
/problems/exponent_rec.rb
UTF-8
251
3.375
3
[]
no_license
def exponent_rec(base, power) return 1 if power == 0 return 1.0 / exponent_rec(base, power * -1) if power < 0 return base * exponent_rec(base, power - 1) if power.odd? # Power is even. half = exponent_rec(base, power / 2) half * half end
true
0bfd318d1bc5197dc4f0dfda4516b70712976cd5
Ruby
n-flint/brownfield-of-dreams-2
/app/services/github_api_service.rb
UTF-8
721
2.6875
3
[]
no_license
class GithubApiService def initialize(token) @token = token end def user_email(handle) parsed_response(conn.get("/users/#{handle}")) end def followers parsed_response(conn.get('/user/followers')) end def repos(limit = 5) response = conn.get('/user/repos') new_response = parsed_response(response) new_response.take(limit) end def following parsed_response(conn.get('/user/following')) end private def parsed_response(response) JSON.parse(response.body, symbolize_names: true) end def conn Faraday.new(url: 'https://api.github.com') do |f| f.headers['Authorization'] = "token #{@token}" f.adapter Faraday.default_adapter end end end
true
b91b3ee8e6378a51b1618a16a1464d02f62a76f9
Ruby
fertech/csv_decision
/lib/csv_decision/validate.rb
UTF-8
3,100
2.90625
3
[ "MIT" ]
permissive
# frozen_string_literal: true # CSV Decision: CSV based Ruby decision tables. # Created December 2017. # @author Brett Vickers <[email protected]> # See LICENSE and README.md for details. module CSVDecision # Parse and validate the column names in the header row. # These methods are only required at table load time. # @api private module Validate # These column types do not need a name. COLUMN_TYPE_ANONYMOUS = Set.new(%i[guard if path]).freeze private_constant :COLUMN_TYPE_ANONYMOUS # Validate a column header cell and return its type and name. # # @param cell [String] Header cell. # @param index [Integer] The header column's index. # @return [Array<(Symbol, Symbol)>] Column type and column name symbols. def self.column(cell:, index:) match = Header::COLUMN_TYPE.match(cell) raise CellValidationError, 'column name is not well formed' unless match column_type = match['type']&.downcase&.to_sym column_name = column_name(type: column_type, name: match['name'], index: index) [column_type, column_name] rescue CellValidationError => exp raise CellValidationError, "header column '#{cell}' is not valid as the #{exp.message}" end # Validate the column name against the dictionary of column names. # # @param columns [Symbol=>[false, Integer]] Column name dictionary. # @param name [Symbol] Column name. # @param out [false, Integer] False if an input column, otherwise the column index of # the output column. # @return [void] # @raise [CellValidationError] Column name invalid. def self.name(columns:, name:, out:) return unless (in_out = columns[name]) return validate_out_name(in_out: in_out, name: name) if out validate_in_name(in_out: in_out, name: name) end def self.column_name(type:, name:, index:) # if: columns are named after their index, which is an integer and so cannot # clash with other column name types, which are symbols. return index if type == :if return format_column_name(name) if name.present? return if COLUMN_TYPE_ANONYMOUS.member?(type) raise CellValidationError, 'column name is missing' end private_class_method :column_name def self.format_column_name(name) column_name = name.strip.tr("\s", '_') return column_name.to_sym if Header.column_name?(column_name) raise CellValidationError, "column name '#{name}' contains invalid characters" end private_class_method :format_column_name def self.validate_out_name(in_out:, name:) if in_out == :in raise CellValidationError, "output column name '#{name}' is also an input column" end raise CellValidationError, "output column name '#{name}' is duplicated" end private_class_method :validate_out_name def self.validate_in_name(in_out:, name:) # in: columns may be duped return if in_out == :in raise CellValidationError, "output column name '#{name}' is also an input column" end private_class_method :validate_in_name end end
true
ca5b3e486034511b4a1ef883f7f293755885341a
Ruby
Fabian-tapia7/ruby
/arreglos/sesion_online/aumento_precios.rb
UTF-8
177
3
3
[]
no_license
def promedio(notas) n= notas.count n.times do |i| if notas[i]=='N.A' notas[i] = 2 end end print notas.sum/notas.count end promedio([5, 5, 20]) print "\n"
true
a6f2ba7435c679956e4b574d20eccff8ab983fac
Ruby
p/lonely_coder
/lib/lonely_coder/profile.rb
UTF-8
7,573
2.53125
3
[ "MIT" ]
permissive
# encoding: UTF-8 class OKCupid def profile_for(username) Profile.by_username(username, @browser) end def visitors_for(username, previous_timestamp = 0) Profile.get_new_visitors(username, previous_timestamp, @browser) end def likes_for(username) Profile.get_new_likes(username, @browser) end def update_section(section, text) Profile.update_profile_section(section, text, @browser) end def upload_pic(file, caption) Profile.upload_picture(file, caption, @browser) end class Profile attr_accessor :username, :match, :friend, :enemy, :location, :age, :sex, :orientation, :relationship_status, :small_avatar_url, :relationship_type # extended profile details attr_accessor :last_online, :ethnicity, :height, :body_type, :diet, :smokes, :drinks, :drugs, :religion, :sign, :education, :job, :income, :offspring, :pets, :speaks, :profile_thumb_urls, :essays # Scraping is never pretty. def self.from_search_result(html) username = html.search('span.username').text age, sex, orientation, relationship_status = html.search('p.aso').text.split('/') percents = html.search('div.percentages') match = percents.search('p.match .percentage').text.to_i friend = percents.search('p.friend .percentage').text.to_i enemy = percents.search('p.enemy .percentage').text.to_i location = html.search('p.location').text small_avatar_url = html.search('a.user_image img').attribute('src').value OKCupid::Profile.new({ username: username, age: OKCupid.strip(age), sex: OKCupid.strip(sex), orientation: OKCupid.strip(orientation), relationship_status: OKCupid.strip(relationship_status), match: match, friend: friend, enemy: enemy, location: location, small_avatar_url: small_avatar_url, relationship_type: relationship_type, }) end def Profile.get_new_likes(username, browser) html = browser.get("http://www.okcupid.com/who-likes-you") text = html.search('#whosIntoYouUpgrade .title').text index = text.index(' people') likes = text[0, index].to_i return likes end def Profile.get_new_visitors(username, previous_timestamp = 1393545600, browser) html = browser.get("http://www.okcupid.com/visitors") visitors = html.search(".user_list .user_row_item") new_visitors = 0 # previous_timestamp = 1393545600 visitors.each { |visitor| begin timestamp_script = visitor.search(".timestamp script") timestamp_search = timestamp_script.text.match(/FancyDate\.add\([^,]+?,\s*(\d+)\s*,/) timestamp = timestamp_search[1] timestamp = timestamp.to_i rescue next end if (timestamp > previous_timestamp) new_visitors += 1 end } return new_visitors end def Profile.by_username(username, browser) html = browser.get("http://www.okcupid.com/profile/#{username}") percents = html.search('#percentages') match = percents.search('span.match').text.to_i friend = percents.search('span.friend').text.to_i enemy = percents.search('span.enemy').text.to_i basic = html.search('#aso_loc') age = basic.search('#ajax_age').text sex = basic.search('#ajax_gender').text orientation = basic.search('#ajax_orientation').text relationship_status = basic.search('#ajax_status').text location = basic.search('#ajax_location').text relationship_type = basic.search('#ajax_monogamous').text profile_thumb_urls = html.search('#profile_thumbs img').collect {|img| img.attribute('src').value} essays = [] 10.times do |i| essays[i] = html.search('#essay_text_' + i.to_s).text.strip! end attributes = { username: username, match: match, friend: friend, enemy: enemy, age: age, sex: sex, orientation: orientation, location: location, relationship_status: relationship_status, profile_thumb_urls: profile_thumb_urls, relationship_type: relationship_type, essays: essays, } details_div = html.search('#profile_details dl') details_div.each do |node| value = OKCupid.strip(node.search('dd').text) next if value == '—' attr_name = node.search('dt').text.downcase.gsub(' ','_') attributes[attr_name] = value end self.new(attributes) end def Profile.update_profile_section(section, text, browser) section_titles = [ "My self-summary", "What I’m doing with my life", "I’m really good at", "The first things people usually notice about me", "Favorite books, movies, shows, music, and food", "The six things I could never do without", "I spend a lot of time thinking about", "On a typical Friday night I am", "The most private thing I’m willing to admit", "You should message me if" ] section_titles_hash = { :self_summary => 0, :im_doing => 1, :good_at => 2, :first_thing => 3, :favorites => 4, :six_things => 5, :think_about => 6, :private => 7, :message_me => 8 } if section.class == Symbol section = section_titles_hash[section] end profile = browser.get('http://www.okcupid.com/profile') authcode = profile.body.match(/authcode['"]?\s*:\s*['"]([\w,;]+?)['"]/)[1] section_response = browser.post('http://www.okcupid.com/profileedit2', { :authcode => authcode, :essay_body => text, :essay_id => section, :change_summary => "[title:start]#{section_titles[section]}[title:end][add:start]#{text}[add:end]", :okc_api => 1 }) end def Profile.upload_picture(file, caption, browser) file_dimensions = Dimensions.dimensions(file) profile = browser.get('http://www.okcupid.com/profile') authcode = profile.body.match(/authcode['"]?\s*:\s*['"]([\w,;]+?)['"]/)[1] userid = profile.body.match(/userid['"]?\s*:\s*['"]?(\d+)['"]?/)[1] upload_response = browser.post('http://www.okcupid.com/ajaxuploader', { 'file' => File.new(file) }) picid = upload_response.body.match(/id'\s*:\s*'(\d+)/)[1] uri = Addressable::URI.parse('http://www.okcupid.com/photoupload') uri.query_values = { :authcode => authcode, :userid => userid, :picid => picid, :width => file_dimensions[0], :height => file_dimensions[1], :tn_upper_left_x => 0, :tn_upper_left_y => 0, :tn_lower_right_x => file_dimensions[0], :tn_lower_right_y => file_dimensions[1], :caption => caption, :albumid => 0, :use_new_upload => 1, :okc_api => 1, :'picture.add_ajax' => 1, } uri.to_s create_photo = browser.get(uri.to_s) end def initialize(attributes) attributes.each do |attr,val| self.send("#{attr}=", val) end end def ==(other) self.username == other.username end def eql?(other) self.username == other.username end def hash if self.username self.username.hash else super end end end end
true
ced90e8a6e3f67406ceab2ebfec2406ab0987fa7
Ruby
anotherminh/ruby_chess_game
/player.rb
UTF-8
2,114
3.71875
4
[]
no_license
require_relative 'display' class HumanPlayer # Reads keypresses from the user including 2 and 3 escape character sequences. def self.read_char STDIN.echo = false STDIN.raw! input = STDIN.getc.chr if input == "\e" then input << STDIN.read_nonblock(3) rescue nil input << STDIN.read_nonblock(2) rescue nil end ensure STDIN.echo = true STDIN.cooked! return input end def self.get_key(cursor_pos) c = read_char new_pos = cursor_pos.dup case c when "\e[A" # puts "UP ARROW" new_pos[0] -= 1 when "\e[B" # puts "DOWN ARROW" new_pos[0] += 1 when "\e[C" # puts "RIGHT ARROW" new_pos[1] += 1 when "\e[D" # puts "LEFT ARROW" new_pos[1] -= 1 when "\r" new_pos = false when "\e" Kernel.abort end new_pos end attr_reader :color def initialize(color) @color = color end def show_display(display) @display = display end def make_move(board) @board = board @selected = false @moved = false choose_piece move_piece end def choose_piece selected_pos = nil until @selected display.print_board new_input = HumanPlayer.get_key(display.cursor_pos) if new_input display.update_cursor(new_input) if board.on_board?(new_input) else @selected_pos = display.cursor_pos @selected = true if board.valid_selection?(color, @selected_pos) end end selected_pos end def move_piece until @moved display.print_board(selected_pos) new_input = HumanPlayer.get_key(display.cursor_pos) if new_input display.update_cursor(new_input) if board.on_board?(new_input) else new_pos = display.cursor_pos if new_pos == @selected_pos @selected = false choose_piece elsif board.valid_move?(@selected_pos, new_pos, color) @moved = true board.move_piece(@selected_pos, new_pos) end end end end private attr_accessor :display, :board, :selected_pos end
true
a52b6da4d4f5193ea16476b80e088d33588a6e9e
Ruby
tidorisan/ruby
/2-8/2-8.rb
UTF-8
1,660
4.03125
4
[]
no_license
# puts "aaa" # input_key = gets # puts "入力された内容は"+input_key # puts "hello" # input_key = gets # puts "入力された内容は"+input_key # a=gets.to_i # b=gets.to_i # puts "a+b=#{a+b}" # a=gets.to_i # b=gets.to_i # puts "a+b=#{a+b}" # puts "キーボードで数字「2」と数字「3」を入力してください" # a=gets.to_i # b=gets.to_i # puts "a+b=#{a+b}" # dice = 0 # diceに0を代入し、初期値を設定する # while dice != 6 do # dice = rand(1.6) # puts dic # end # dice = 0 # diceに0を代入し、初期値を設定する # while dice != 6 do #サイコロの目が6ではない間、diceの初期値は0なので条件を満たす。以降はdiceに代入される数によって結果が異なる # dice = rand(1..6) #1~6の数字がランダムに出力される # puts dice # end # for in do # for i in 1..10 do # puts i # end # for i in 1..10 do # 1..10は、1~10までの範囲を表す # puts i # end # (範囲、ハッシュ、配列などを指定).each do |変数| # 実行する処理 # end # {"apple"=>130,"strawberry"=>180, "orange"=>100} .each do |frute,price| # puts "#{fruit}は#{price}円です。" #変数展開 # end # {"apple"=>130, "strawberry"=>180, "orange"=>100}.each do |fruit, price| #ハッシュの内容を順にキーをfruit、値をpriceに代入して繰り返す # puts "#{fruit}は#{price}円です。" #変数展開 # end # # 1 = 0 # while i <= 10 do # if i >5 # break # end # puts i # i += 1 # end i = 0 while i <= 10 do if i >5 break #iが5より大きくなると繰り返しから抜ける end puts i i += 1 end
true
85cbd2d91e8e1e56a72765cebb1e897e6e891966
Ruby
SALIM-UsseF/DEPIC
/back-end/app/controllers/questionchoixes_controller.rb
UTF-8
1,972
2.90625
3
[]
no_license
################################ # Question choix Controller # ############################# # # Expose des services REST sous format Json: # - Afficher la liste des questions choix # - Afficher une question choix par ID # - Creer une nouvelle question choix # - Modifier une question choix # - Supprimer une question choix par ID require 'QuestionChoixService' class QuestionchoixesController < ApplicationController # Afficher la liste des questions choix def index questions = QuestionChoixService.instance.listeDesQuestions render json: questions, status: :ok end # Afficher une QuestionChoix par ID def show question = QuestionChoixService.instance.afficherQuestionParId(params[:id]) (question != nil) ? (render json: question, status: :ok) : (render json: nil, status: :not_found) end # Creer une nouvelle QuestionChoix def create params.permit(:intitule, :estObligatoire, :estUnique, :ordre, :sondage_id) ajout = QuestionChoixService.instance.creerQuestionChoix(params[:intitule], params[:estObligatoire], params[:estUnique], params[:ordre], params[:sondage_id]) (ajout != nil) ? (render json: ajout, status: :ok) : (render json: nil, status: :not_found) end # Modifier une QuestionChoix def update modifier = QuestionChoixService.instance.modifierQuestion(params[:id], params[:intitule], params[:estObligatoire], params[:estUnique], params[:ordre]) (modifier != nil) ? (render json: modifier, status: :ok) : (render json: nil, status: :not_found) end # Supprimer une QuestionChoix par ID def delete supprimer = QuestionChoixService.instance.supprimerQuestion(params[:id]) (supprimer) ? (render json: true, status: :ok) : (render json: false, status: :not_found) end # Liste des parametres à fournir private # parametres d'ajout def question_params params.permit(:intitule, :estObligatoire, :estUnique, :nombreChoix, :ordre, :sondage_id) end end
true
e7c9018c91fd455d3c8b3dcc676535ecd54ee0f0
Ruby
TwilioDevEd/api-snippets
/quickstart/ruby/autopilot/create-first-task/create_hello_world_task.6.x.rb
UTF-8
1,068
2.5625
3
[ "MIT" ]
permissive
# Download the helper library from https://www.twilio.com/docs/ruby/install require 'rubygems' require 'twilio-ruby' # Your Account Sid and Auth Token from twilio.com/console # To set up environmental variables, see http://twil.io/secure account_sid = ENV['TWILIO_ACCOUNT_SID'] auth_token = ENV['TWILIO_AUTH_TOKEN'] @client = Twilio::REST::Client.new(account_sid, auth_token) # Build task actions that say something and listens for a repsonse. hello_world_task_actions = { "actions" => [ { "say": "Hi there, I'm your virtual assistant! How can I help you?" }, { "listen": true } ] } # Create the hello_world task # Replace 'UAXXX...' with your Assistant's unique SID https://www.twilio.com/console/autopilot/list task = @client.autopilot.assistants('UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') .tasks .create( unique_name: "hello-world", actions: hello_world_task_actions ) puts "Hello-world task has been created!" puts task.sid
true
dc048a66e078f93adb0e21533d99cb691f8fd371
Ruby
jordansissel/experiments
/ruby/octokit/migrate-issue.rb
UTF-8
3,235
2.65625
3
[]
no_license
#!/usr/bin/env ruby # encoding: utf-8 require "clamp" require_relative "mixins/github" require_relative "mixins/logger" require_relative "mixins/cla" class GithubIssueMigrator < Clamp::Command include Mixin::GitHub include Mixin::Logger include Mixin::ElasticCLA parameter "SOURCE", "The github issue to migrate." parameter "DESTINATION", "The destination to migrate to" def execute issue = github.issue(source_project, source_issue) if issue[:pull_request] migrate_pull(issue) else migrate_issue(issue) end end def migrate_issue(issue) annotated_body = "(This issue was originally filed by @#{issue.user.login} at #{source})\n\n---\n\n" + issue.body if issue.state == "closed" puts "This issue is already closed. Nothing to migrate." return 1 end # Create the new issue new_issue = github.create_issue(destination_project, issue.title, annotated_body) # Comment on the old issue about the migration, and close it. github.add_comment(source_project, source_issue, "For Logstash 1.5.0, we've moved all plugins to individual repositories, so I have moved this issue to #{new_issue.html_url}. Let's continue the discussion there! :)") github.close_issue(source_project, source_issue) puts "Successfully migrated to: #{new_issue.html_url}" nil end # def execute def migrate_pull(issue) if cla_uri.nil? puts "Missing --cla-uri. Cannot migrate a PR without this." return 1 end comment = <<-COMMENT For Logstash 1.5.0, we've moved all plugins (and grok patterns) to individual repositories. Can you move this pull request to https://github.com/#{destination_project}? This sequence of steps _may_ help you do this migration: 1. Fork this repository 2. Clone your fork ```shell git clone #{issue.user.html_url}/#{source_project.split("/")[1]}.git ``` 3. Create a branch: ```shell git checkout -b my-branch-name ``` 4. Apply the patches from this PR into your branch: ```shell curl -s #{source}.patch | git am ``` This should take your commits from this PR and commit them to your new local branch. 5. Push! ```shell git push origin my-branch-name ``` 6. Open a new PR against https://github.com/#{destination_project} COMMENT cla_ok, cla_message = cla_status(source_project, source_issue, cla_uri) cla_message = cla_message[0,1].downcase + cla_message[1..-1] if !cla_ok comment << <<-COMMENT 7. Sign the CLA Our CLA check indicates that #{cla_message}. See our [contributor agreement](http://www.elasticsearch.org/contributor-agreement/) for more details. :) COMMENT end github.add_comment(source_project, source_issue, comment) github.close_issue(source_project, source_issue) puts "Added note to contributor for migration to #{destination_project}" end def source_project @source_project ||= source.gsub(%r{^https?://github.com/}, "").gsub(%r{(issues|pull)/\d+$}, "") end def source_issue @source_issue ||= source[/\d+$/].to_i end def destination_project @destination_project ||= destination.gsub(%r{^https?://github.com/}, "") end end # class GithubIssueMigrator GithubIssueMigrator.run
true
189706c51143988a519b4b309dd2095bc69fd0ab
Ruby
hirataya/fatechan
/lib/google_calc.rb
UTF-8
718
2.84375
3
[ "BSD-2-Clause" ]
permissive
require "uri" require "cgi" require "open-uri" require "nokogiri" module GoogleCalc def self.calc(expr, &block) uri = sprintf("http://www.google.com/search?hl=ja&q=%s", CGI.escape(expr)) #p uri result = nil open(uri, "r:utf-8", "User-Agent" => "Mozilla/5.0") do |fp| content = fp.read #p content doc = Nokogiri::HTML(content) result = doc.xpath("//h2[@class='r']").first end return nil if not result #result = result.text result = result.inner_html result.gsub!(%r{<sup>(.*?)</sup>}) { "^#{$1}" } result.gsub!(%r{<font size="-2"> </font>}, "") result.strip! result.gsub!(/\s{2,}/, " ") block.call(result) if block result end end
true
a20133fe9d6b00be177d6c28e91a9df4606b22ea
Ruby
tcrane20/AdvanceWarsEngine
/Advance Wars Edit/Scripts_Old/[191]Sea.rb
UTF-8
485
2.5625
3
[]
no_license
class Sea < Tile def initialize super @name = 'sea' @id = TILE_SEA end def move_cost_chart(move_type) return case move_type when MOVE_FOOT then return [0] when MOVE_MECH then return [0] when MOVE_TIRE then return [0] when MOVE_TREAD then return [0] when MOVE_AIR then return [1,2] when MOVE_TRANS then return [1,2] when MOVE_SEA then return [1,2] when MOVE_TIRE_B then return [0] end end end
true
44fa8a998fd2bedd52a5c0cd2c1433880fee6d78
Ruby
rubenpazch/ruby-algorithms
/strings/practice.rb
UTF-8
1,135
3.515625
4
[]
no_license
# p "abcdef" <=> "abcde" #=> 1 # p "abcdef" <=> "abcdef" #=> 0 # p "abcdef" <=> "abcdefg" #=> -1 # p "abcdef" <=> "ABCDEF" #=> 1 # p "abcdef" <=> 1 #=> nil # str1 = 'aa' # str2 = 'bb' # ar1 = str1.squeeze.each_char.to_a # ar2 = str2.squeeze.each_char.to_a # # p ar1 - ar2 # p ar2 - ar1 # ## str1.each_char{|x| x - } # # p str1 <=> str2 # # puts 3 / 2 # #cantidadACambiar = 1211 # cantidadACambiar = 1000 # cantidadACambiar = 100 # cantidadACambiar = 10 # cantidadACambiar = 1 # cantidadACambiar = 0 # cantidadACambiar = 1123 cantidadACambiar = 15 def totalBilletesMonedas(retirar) billete200 = 200.0 arr = [100.0, 50.0, 20.0, 10.0, 5.0, 2.0, 1.0, 0.5, 0.2, 0.1] minimo = 0.0 if retirar > billete200 division = retirar / billete200 residuo = retirar % billete200 minimo += division else residuo = retirar end return minimo if residuo == 0.0 i = 0 while residuo != 0.0 if residuo >= arr[i] division = residuo / arr[i] residuo = residuo % arr[i] minimo += division end i += 1 end minimo end p totalBilletesMonedas(cantidadACambiar) test
true
8ff2fc70915edfa5036c00ea783412436103f2c3
Ruby
Chrispolanco/debugging-with-pry-online-web-prework
/lib/pry_debugging.rb
UTF-8
53
2.546875
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def plus_two(num) num + 2 new_total = num + 2 end
true
c04a746ca13e22a7a5723f1b35cf6d9a68fc2136
Ruby
vuhailuyen1991/rails
/activesupport/lib/active_support/core_ext/date_and_time/compatibility.rb
UTF-8
601
2.640625
3
[ "MIT", "Ruby" ]
permissive
module DateAndTime module Compatibility # If true, +to_time+ preserves the the timezone offset. # # NOTE: With Ruby 2.4+ the default for +to_time+ changed from # converting to the local system time to preserving the offset # of the receiver. For backwards compatibility we're overriding # this behavior but new apps will have an initializer that sets # this to true because the new behavior is preferred. mattr_accessor(:preserve_timezone, instance_writer: false) { false } def to_time preserve_timezone ? getlocal(utc_offset) : getlocal end end end
true
6d99066e7787e4dc54923f4ed69a22b4e6192fc8
Ruby
sbasnyat/cosi166b
/PA2/MovieData.rb
UTF-8
6,995
3.359375
3
[]
no_license
class MovieData # constructor, if one parameter is passed, it takes path to the folder containing the movie data, # optionally if two arguments are passed, the first is taken as path to folder and second symbol to specify a particular training/test pair def initialize(*args) train_test_h = {:u1 => ["u1.base","u1.test"], :u2 => ["u2.base","u2.test"], :u3 => ["u3.base","u3.test"], :u4 => ["u4.base","u4.test"], :u5 => ["u5.base","u5.test"], :ua => ["ua.base","ua.test"], :ub => ["ub.base","ub.test"] } foldername = args[0] # @train_umr_h stands for training user movie rating hash and is a hash table that stores each line of data of training set in the form user_id as key and its # value is another hash table with key movie id and value rating # @train_mur_h stands for training movie user rating hash and is a hash table that stores each line of data in the training set in the form movie-id as key and its # value is another hash table with key user_id and value rating # @test_umr_arr stands for test user movie rating array and is 2D array i.e. an array of arrays in the form [user_id, movie_id, rating] for each line of test data if args.length == 1 train_filename = File.join(foldername,"u.data") @test_umr_arr = nil else train_test_pair = train_test_h[args[1]] train_filename = File.join(foldername,train_test_pair[0]) test_filename = File.join(foldername,train_test_pair[1]) @test_umr_arr = load_test(test_filename) end @train_umr_h, @train_mur_h = load_train(train_filename) end # this method reads the training dataset line by line, stores it in two hash table forms and returns the two hash tables def load_train(train_filename) train_data = open(train_filename).read umr_h = Hash.new mur_h = Hash.new train_data.each_line do |line| data = line.split(" ") user_id = data[0].to_i movie_id = data[1].to_i rate = data[2].to_i # for a particular key, it checks if it exists, if not creates a new hash table at that key if !umr_h.has_key?(user_id) umr_h[user_id] = Hash.new end umr_h [user_id] [movie_id] = rate # for a particular key, it checks if it exists, if not creates a new hash table at that key if !mur_h.has_key?(movie_id) mur_h[movie_id] = Hash.new end mur_h [movie_id][user_id] = rate end return umr_h, mur_h end # this method reads the test dataset and stores each line in a 2D array i.e an array of arrays in the form [user_id, movie_id, rating] and returns it def load_test(test_filename) test_data = open(test_filename).read umr_arr = Array.new test_data.each_line do |line| data=line.split(" ") user_id=data[0].to_i movie_id=data[1].to_i rate=data[2].to_i umr_arr.push([user_id, movie_id, rate]) end return umr_arr end # this method returns the rating that user u gave movie m in the training set, and 0 if user u did not rate movie m def rating(u,m) if @train_umr_h.has_key?(u) && @train_umr_h[u].has_key?(m) return @train_umr_h[u][m] else return 0 end end # this method returns the array of movies that user u has watched and 0 if the user id cannot be found in the dataset def movies(u) if @train_umr_h.has_key?(u) return @train_umr_h[u].keys else return 0 end end # this method returns the array of users that have seen movie m and 0 if the movie id cannot be found in the dataset def viewers(m) if @train_mur_h.has_key?(m) return @train_mur_h[m].keys else return 0 end end # this method returns a floating point number between 1.0 and 5.0 as an estimate of what user u would rate movie m # prediction algorithm sees 10 the users who have watched the movie and checks which of them have watched the most # common movies among the first 20 movies watched by the users with user u, and then returns the rating the user gave the movie m def predict(u,m) hash=Hash.new viewers_m = viewers(m) movies_u = movies(u) if (viewers_m == 0 || viewers_m.length < 20) && (movies_u == 0 || movies_u.length < 20) return 0 elsif viewers_m == 0 || viewers_m.length < 20 sum = 0 movies(u)[0..29].each do |mov| sum += rating(u,mov) end return sum/20 else ten_viewers=Array.new(viewers_m[0..9]) ten_viewers.each do |user| if user!=u && movies(user).length >= 50 num_common_movies=(movies_u & movies(user)[0..49]).length hash[num_common_movies]=user end end #finds the user out of the viewers who has the maximum number of movies watched in common with our user u and returns the rating that user gave to movie m return rating(hash[hash.keys.max],m) end end # runs the predict method on the first something number of ratings in the test set as specified in the parameter and returns a MovieTest object containing the results. # If the parameter is omitted, all of the tests will be run. def run_test(*args) if args.length == 1 k = args[0] ratinglist=Array.new(@test_umr_arr[0...k]) else ratinglist=Array.new(@test_umr_arr) end # now finds the prediction rating from the predict function and pushes it into the array ratinglist.each do |line| predicted= predict(line[0],line[1]) line.push(predicted) end # creates an instance of class MovieTest and passes the ratinglist as parameter return MovieTest.new(ratinglist) end end class MovieTest # takes ratinglist i.e. an array of arrays with each element in the form [user_id, movie_id, rating, predicted rating] # @error is an array whoese elements are the difference between predicted rating and actual rating for each element on the ratinglist def initialize(ratinglist) @ratinglist=ratinglist @error=find_error @length=ratinglist.length end # this method goes through each element of the rating list i.e. each array and finds the difference between the actual and # predicted rating for each and stores the value in an array and returns it def find_error error=[] @ratinglist.each do |result| error.push((result[2]-result[3]).abs) end return error end # this method returns the average predication error def mean summ = @error.inject(0) {|sum, i| sum + i } return (summ.to_f/@length) end # this method returns the standard deviation of the error def stddev mean_ = mean sum=0 @error.each do |error| sum += ((error - mean_ ) ** 2) end return Math.sqrt(sum.to_f/@length) end # this method returns the root mean square error of the prediction def rms sum=0 @error.each do |error| sum += (error) ** 2 end return Math.sqrt(sum.to_f/@length) end # this method returns an array of the predictions in the form [u,m,r,p]. def to_a print @ratinglist puts end end obj=MovieData.new("ml-100k", :u2) #puts obj.similarity(1,126) #puts obj.most_similar(1) #puts obj.viewers(100) #t=obj.run_test(2500) #puts t.mean #puts t.stddev #puts t.rms #t.to_a #puts t.rms
true
784cddaa14b24afa3245d7908e6aaad22e17de9e
Ruby
higepon/misc
/count-and-say.rb
UTF-8
507
3.609375
4
[]
no_license
# @param {Integer} n # @return {String} def count_and_say(n) if n == 1 return "1" end prev = count_and_say(n - 1) ret = '' currentVal = 0 num = 0 for i in 0...prev.size ch = prev[i] if num == 0 currentVal = ch num = 1 elsif ch == currentVal num = num + 1 else ret = "#{ret}#{num}#{currentVal}" num = 1 currentVal = ch end if i == prev.size - 1 ret = "#{ret}#{num}#{currentVal}" num = 0 end end return ret end
true
291f200ff99145d88b75bbab9dd6a581f73fed95
Ruby
sogbdn/ar-exercises
/exercises/exercise_7.rb
UTF-8
430
3.078125
3
[]
no_license
require_relative '../setup' require_relative './exercise_1' require_relative './exercise_2' require_relative './exercise_3' require_relative './exercise_4' require_relative './exercise_5' require_relative './exercise_6' puts "Exercise 7" puts "----------" # Ask the user for a store name (store it in a variable) puts "What is your store's name?" a = gets.chomp store = Store.create(name: a) puts store.errors.full_messages
true
ce0c2d6b1bff6d2d664dfd0a64711a0346788692
Ruby
gotar/internship_day_V
/lib/model/product.rb
UTF-8
239
3.046875
3
[]
no_license
module Shop class Product attr_reader :id, :name, :price @@id = 0 def initialize(name, price) @id = set_id @name = name @price = price end private def set_id @@id += 1 end end end
true
b0a7fbb32fb5c86b85e032fe4ad5a5022e29ba9d
Ruby
toshichanapp/projecteuler
/1-10/problem5.rb
UTF-8
195
2.875
3
[]
no_license
require 'prime' (1..20).map {|num| Prime.prime_division(num)}.flatten.each_slice(2).group_by{|arr| arr[0]}.map do |_, arr| arr.max_by{|nums| nums[1] } end.map do |a, b| a ** b end.reduce(:*)
true
95b00a42ea438f4979db6b3d5da53f7d4a09b10a
Ruby
masayuki038/chienowa
/app/helpers/stars_helper.rb
UTF-8
140
2.53125
3
[ "MIT" ]
permissive
module StarsHelper def starred?(stars) stars.each do |star| return true if current_user?(star.user) end false end end
true
194a25cbe0080c2db9109579d313ce0fb8f3f7d7
Ruby
pamungkaski/Malkist-Ruby
/spec/malkist_spec.rb
UTF-8
3,166
2.59375
3
[ "MIT" ]
permissive
# frozen_string_literal: true RSpec.describe Malkist do it 'has a version number' do expect(Malkist::VERSION).not_to be nil end it 'return distance between two coordinate' do result = Malkist.calculate_distance(%w[40.6655101,-73.89188969999998], %w[40.6905615,-73.9976592]) expect(result[0].distance).to eq(10423) end it 'return distance between one origin with many destinations' do result = Malkist.calculate_distance(%w[40.6655101,-73.89188969999998], %w[40.6905615,-73.9976592 40.8905615,-73.9976592 40.7905615,-73.9976592]) expect(result[0].distance).to eq(10423) expect(result.length).to eq(3) end it 'return distance between many origin with one destinations' do result = Malkist.calculate_distance(%w[40.6655101,-73.89188969999998 40.6855101,-73.89188969999998 40.6255101,-73.89188969999998], %w[40.6905615,-73.9976592]) expect(result[0].distance).to eq(10423) expect(result.length).to eq(3) end it 'return distance between many origin with one destinations' do result = Malkist.calculate_distance(%w[40.6655101,-73.89188969999998 40.6855101,-73.89188969999998 40.6255101,-73.89188969999998], %w[40.6905615,-73.9976592 40.8905615,-73.9976592 40.7905615,-73.9976592]) expect(result[0].distance).to eq(10423) expect(result.length).to eq(9) end end RSpec.describe Malkist::Distances do it 'return distance between two coordinate' do distances = Malkist::Distances.new(%w[40.6655101,-73.89188969999998], %w[40.6905615,-73.9976592]) result = distances.calculate_distance expect(result[0].distance).to eq(10423) end it 'return distance between one origin with many destinations' do distances = Malkist::Distances.new(%w[40.6655101,-73.89188969999998], %w[40.6905615,-73.9976592 40.8905615,-73.9976592 40.7905615,-73.9976592]) result = distances.calculate_distance expect(result[0].distance).to eq(10423) expect(result.length).to eq(3) end it 'return distance between many origin with one destinations' do distances = Malkist::Distances.new(%w[40.6655101,-73.89188969999998 40.6855101,-73.89188969999998 40.6255101,-73.89188969999998], %w[40.6905615,-73.9976592]) result = distances.calculate_distance expect(result[0].distance).to eq(10423) expect(result.length).to eq(3) end it 'return distance between many origin with one destinations' do distances = Malkist::Distances.new(%w[40.6655101,-73.89188969999998 40.6855101,-73.89188969999998 40.6255101,-73.89188969999998], %w[40.6905615,-73.9976592 40.8905615,-73.9976592 40.7905615,-73.9976592]) result = distances.calculate_distance expect(result[0].distance).to eq(10423) expect(result.length).to eq(9) end end RSpec.describe Malkist::Distances::Distance do it 'return the assigned value upon initialization' do distance = Malkist::Distances::Distance.new('oRigiNaslz Addrewses', 'dWesttwinattizion Addrewses', 65123, 1235123) expect(distance.origin).to eq('oRigiNaslz Addrewses') expect(distance.destination).to eq('dWesttwinattizion Addrewses') expect(distance.distance).to eq(65123) expect(distance.duration).to eq(1235123) end end
true
4ceee98fb56d597ffc2a8385e07adf7f32a2826d
Ruby
kennyfrc/launch_school
/130/anagram.rb
UTF-8
1,197
4
4
[]
no_license
# 04/23/16 - Challenge: Anagrams class Anagram attr_reader :detector def initialize(detector) @detector = detector end def match(array_of_words) filtered_words = array_of_words.map(&:downcase).select do |word| word.chars.all? do |chars| detector_letters.include?(chars) end && pass_anagram_checker?(word) end return filtered_words.map(&:capitalize) if capitalized?(detector) filtered_words end private def pass_anagram_checker?(arr) same_size_as_detector?(arr) && same_char_count_as_detector?(arr) && not_self?(arr) end def capitalized?(detector) capitalized_detector = detector.downcase.capitalize capitalized_detector == detector end def size(arr) arr.chars.size end def detector_letters detector.downcase.chars end def chars_of(str) hash_of_letters = Hash.new(0) str.chars.each do |letter| hash_of_letters[letter] += 1 end hash_of_letters end def same_char_count_as_detector?(arr) chars_of(arr) == chars_of(detector.downcase) end def same_size_as_detector?(arr) size(arr) == detector.size end def not_self?(arr) arr != detector.downcase end end
true
21ef2d477d190f1f0989bcb0d5264d9c5793350e
Ruby
sksamal/omnetpp-5.0
/samples/FatTree/simulations/createIniBorderExp.rb
UTF-8
1,226
2.78125
3
[]
no_license
# Generating experiment inis #Execute with ruby createIniBorderExp.rb data = File.readlines("inputBorders.ini") upper = [10, 20, 40, 60, 80, 160] lower = [5, 10, 20, 30, 40, 80] lower2 = [3, 5, 10, 15, 20, 40] repeats = (1..5).to_a upper.zip(lower).each do |upper, lower| repeats.each do |i| data_temp = data.dup data_temp.map! {|line| line.gsub(/%SEED%/, "#{i}")} data_temp.map! {|line| line.gsub(/%LOW%/, "#{lower}")} data_temp.map! {|line| line.gsub(/%UP%/, "#{upper}")} name_temp = "#{upper}-#{lower}-#{i}" filename = "border#{name_temp}.ini" File.open(filename, "a") {|f| f.puts data_temp} puts "Created #{filename} with borders up: #{upper}, low: #{lower}, seed: #{i}." end end =begin upper.zip(lower2).each do |upper, lower| repeats.each do |i| data_temp = data.dup data_temp.map! {|line| line.gsub(/%SEED%/, "#{i}")} data_temp.map! {|line| line.gsub(/%LOW%/, "#{lower}")} data_temp.map! {|line| line.gsub(/%UP%/, "#{upper}")} name_temp = "#{upper}-#{lower}-#{i}" filename = "border#{name_temp}.ini" File.open(filename, "a") {|f| f.puts data_temp} puts "Created #{filename} with borders up: #{upper}, low: #{lower}, seed: #{i}." end end =end
true
bdd6ee448b1dfae8533e0454f61b12702c51b7b9
Ruby
kbehnfeldt/RB101
/rb101-lesson4/Loops1/exercise6.rb
UTF-8
76
3.140625
3
[]
no_license
number = [] while number.length < 5 number << rand(100) end puts number
true
30b98fcc700dffac0c65bfc92cc84df8af8ad865
Ruby
ric2b/learning_ruby
/ruby/hamming/hamming.rb
UTF-8
194
3.546875
4
[]
no_license
class Hamming def self.compute(string_a, string_b) raise ArgumentError if string_a.length != string_b.length string_a.chars.zip(string_b.chars).map{|a, b| a != b ? 1 : 0}.sum end end
true
091d14e988ba41047519cc89e48d9b15b979ea6c
Ruby
btazi/rbnd-toycity-part4
/lib/analyzable.rb
UTF-8
891
3.09375
3
[]
no_license
module Analyzable # Your code goes here! def average_price(products) average = products.map(&:price).map(&:to_f).reduce(:+)/products.length average.round(2) end def print_report(products) report = "" products.each do |product| report += "#{product.name}, brand: #{product.brand}, price: #{product.price} \n" end report end def create_count_by_methods(*attributes) attributes.each do |attr| self.class_eval %{def self.count_by_#{attr}(arg) counts = {} arg.map(&:#{attr}).each do |#{attr}_value| counts[#{attr}_value] = Product.where(#{attr}: #{attr}_value).count end counts end} end end def self.method_missing(method_name, arguments) if method_name.to_s.start_with?("count_by") attribute = method_name.to_s.gsub!("count_by_", "") create_count_by_methods(attribute) self.public_send(method_name, arguments) end end end
true
542558846983f977142894603c5554457c5257e7
Ruby
roodi/roodi
/lib/roodi/checks/abc_metric_method_check.rb
UTF-8
2,015
3.140625
3
[ "MIT" ]
permissive
require 'roodi/checks/check' module Roodi module Checks # The ABC metric method check calculates the number of Assignments, # Branches and Conditionals in your code. It is similar to # cyclomatic complexity, so the lower the better. class AbcMetricMethodCheck < Check ASSIGNMENTS = [:lasgn] BRANCHES = [:vcall, :call] CONDITIONS = [:==, :"!=", :<=, :>=, :<, :>] OPERATORS = [:*, :/, :%, :+, :<<, :>>, :&, :|, :^] DEFAULT_SCORE = 10 attr_accessor :score def initialize super() self.score = DEFAULT_SCORE end def interesting_nodes [:defn] end def evaluate_start(node) method_name = node[1] a = count_assignments(node) b = count_branches(node) c = count_conditionals(node) score = Math.sqrt(a*a + b*b + c*c) add_error "Method name \"#{method_name}\" has an ABC metric score of <#{a},#{b},#{c}> = #{score}. It should be #{@score} or less." unless score <= @score end private def count_assignments(node) count = assignment?(node) ? 1 : 0 node.children.each {|child_node| count += count_assignments(child_node)} count end def count_branches(node) count = branch?(node) ? 1 : 0 node.children.each {|child_node| count += count_branches(child_node)} count end def count_conditionals(node) count = conditional?(node) ? 1 : 0 node.children.each {|child_node| count += count_conditionals(child_node)} count end def assignment?(node) ASSIGNMENTS.include?(node.node_type) end def branch?(node) BRANCHES.include?(node.node_type) && !conditional?(node) && !operator?(node) end def conditional?(node) (:call == node.node_type) && CONDITIONS.include?(node[2]) end def operator?(node) (:call == node.node_type) && OPERATORS.include?(node[2]) end end end end
true
c303c31408aa672ed882d6950b428899282d7b93
Ruby
jcquarto/everything-is-a-object-or-method
/object_test2.rb
UTF-8
110
3.171875
3
[]
no_license
# works with classes too! class Cat end puts Cat.class puts Cat.new.class cato = Cat.new puts cato.class
true
104b1567e4d48ca27aa73a2f6510dd5769ca7fc1
Ruby
magic8baller/the-bachelor-todo-prework
/lib/bachelor.rb
UTF-8
1,482
3.828125
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
#require 'pry' def get_first_name_of_season_winner(data, season) data[season].each do |contestant_hash| # {'name'=>'Tessa H'..,} if contestant_hash['status'] == 'Winner' return contestant_hash['name'].split.first #split name into 2 strings, return first name end end end def get_contestant_name(data, occupation) data.each do |season, contestant_array| # 'season ', [{..},{..},..] contestant_array.each do |contestant_hash| #{'name'=>'Ashley..',} if contestant_hash['occupation'] == occupation return contestant_hash['name'] end end end end def count_contestants_by_hometown(data, hometown) count = 0 data.each do |season, contestant_array| contestant_array.each do |contestant_hash| if contestant_hash['hometown'] == hometown #if hometown matches parameter count += 1 #count it end end end count end def get_occupation(data, hometown) data.each do |season, contestant_array| contestant_array.each do |contestant_hash| if contestant_hash['hometown'] == hometown return contestant_hash['occupation'] end end end end def get_average_age_for_season(data, season) contestant_count = 0 total_ages = 0 data[season].each do |contestant_hash| total_ages += contestant_hash['age'].to_f #float number => perform average w/ decimals contestant_count += 1 end (total_ages/contestant_count).round #from decimal can accurately round average end
true
978e0b3723d87a83c9b7357b026b6b9f3e8e3461
Ruby
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/ruby/binary/309c0a008dd847918cd61c14010c5f45.rb
UTF-8
357
3.8125
4
[]
no_license
class Binary attr_reader :value def initialize(value) @value = value end def to_decimal return 0 unless is_decimal? chars.each_with_index .map { |digit, index| digit.to_i * (2 ** index) } .inject(&:+) end private def chars value.reverse.each_char end def is_decimal? value.match(/^(0|1)+$/) end end
true
dfa258b68b1e8e530a1b76762c9461b6a435406d
Ruby
ajemobile/big
/lib/bigmagic/database_object.rb
UTF-8
634
2.859375
3
[]
no_license
module Bigmagic class DatabaseObject def eigen_class class << self self end end def add_instance_variables(argv) hash = {} if argv.kind_of?(Hash) hash = argv elsif argv.kind_of?(Array) argv.map! {|item| item.to_s.to_sym} hash = Hash[*argv.zip(Array.new(argv.size)).flatten] elsif argv.nil? return nil else raise "invalid argument! Use a Hash or Array argument" end hash.each_pair do |key,value| eigen_class.send :attr_accessor, key.to_sym send("#{key}=".to_sym, value) end end end end
true
3a0ac8d9f7e32e0792c7b6f472ab3c5f24d64040
Ruby
sans-pulp/ruby-exercises
/ruby_basics/3_conditionals/string_caps.rb
UTF-8
332
4.40625
4
[ "MIT" ]
permissive
# Write a method that takes a string as an argument and returns a new all caps version of the string only if the string is longer than 10 characters def upcase_long_string(string) string.length > 10 ? string.upcase : string # if string.length > 10 # string.upcase # end end puts upcase_long_string('This is interesting')
true
d6a787429ce11e7b7ed18d6ba4a7041600de7109
Ruby
mkaushish/quizsite
/lib/QuestionGenerator/trig.rb
UTF-8
2,422
3.21875
3
[]
no_license
#!/usr/bin/env ruby require_relative 'questionbase' require_relative 'tohtml' include "Math.rb" PYTHTRIP=[[3,4,5],[5,12,13],[7,24,25],[8,15,17]] ORD=["a","o","h"] PYTH=[[1,1,Math.sqrt(2)], [1,Math.sqrt(3),2]] TRIGF=["sin", "cos", "tan", "cot", "cosec", "sec"] TRIGDEF={"sin" => ["o","h"], "cos" => ["a","h"], "tan" => ["o","a"], "cot" => ["a","o"], "cosec" => ["h","o"], "sec" => ["h","a"]} module Trig class RatiosMissingSide def initialize trip=PYTHTRIP.sample mult=rand(3)+1 for i in 0...trip.length trip[i]=trip[i]*mult end @fun=TRIGF.sample @trip={"a" => trip[0], "o" => trip[1], "h" => trip[2]} @whmis=TRIGDEF[@fun].sample end def solve rat=Rational(@trip[TRIGDEF[@fun][0]], @trip[TRIGDEF[@fun][1]]) return {"num" => rat.numerator, "den" => rat.denominator} end def text txt="In a triangle ABC, right angled at B" txt+=", AB is of length #{@trip["a"]} " if @whmis != "a" if @whmis == "h" txt+="and " else txt+=", " end txt+="BC is of length #{@trip["o"]}" if @whmis != "o" txt+=" and CA is of length #{@trip["h"]}" if @whmis != "h" txt+=". What is the value of #{@fun}(A) in its lowest form?" [TextLabel.new(txt), Fraction.new("num", "den")] end end class RatioGivenOther def initialize trip=PYTHTRIP.sample @orig=TRIGF.sample @fin=TRIGF.sample while @fin==@orig @fin=TRIGF.sample end mult=rand(3)+1 for i in 0...trip.length trip[i]=trip[i]*mult end @trip={"a" => trip[0], "o" => trip[1], "h" => trip[2]} end def solve rat=Rational(@trip[TRIGDEF[@fin][0]], @trip[TRIGDEF[@fin][1]]) return {"num" => rat.numerator, "den" => rat.denominator} end def text [TextLabel.new("In a triangle ABC, right angled at B, #{@orig}(A)=#{Fraction.new(@trip(TRIGDEF[@orig][0]), @trip(TRIGDEF[@orig][1]))}. What is the value of #{@fin}(A) in its lowest form?"), Fraction.new("num", "den")] end end class RatiosUsingId def initialize @fun=TRIGF.sample @ang=rand(85)+3 end def solve end def text [TextLabel.new("Find the value of #{Fraction.new("sin(#{@ang})", "sin(#{90-@ang})")} using identities"), TextField.new("ans")] end end end
true
e2772763f491343e97a06dc05dbdb571757704a5
Ruby
QPC-WORLDWIDE/rubinius
/kernel/common/eval.rb
UTF-8
3,392
2.765625
3
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
module Kernel # Names of local variables at point of call (including evaled) # def local_variables locals = [] scope = Rubinius::VariableScope.of_sender # Ascend up through all applicable blocks to get all vars. while scope if scope.method.local_names scope.method.local_names.each do |name| name = name.to_s locals << name end end # the names of dynamic locals is now handled by the compiler # and thusly local_names has them. scope = scope.parent end locals end module_function :local_variables # Obtain binding here for future evaluation/execution context. # def binding return Binding.setup( Rubinius::VariableScope.of_sender, Rubinius::CompiledMethod.of_sender, Rubinius::StaticScope.of_sender, self) end module_function :binding # Evaluate and execute code given in the String. # def eval(string, binding=nil, filename=nil, lineno=1) filename = StringValue(filename) if filename lineno = Type.coerce_to lineno, Fixnum, :to_i if binding if binding.kind_of? Proc binding = binding.binding elsif binding.respond_to? :to_binding binding = binding.to_binding end unless binding.kind_of? Binding raise ArgumentError, "unknown type of binding" end filename ||= binding.static_scope.active_path else binding = Binding.setup(Rubinius::VariableScope.of_sender, Rubinius::CompiledMethod.of_sender, Rubinius::StaticScope.of_sender, self) filename ||= "(eval)" end binding.static_scope = binding.static_scope.dup be = Rubinius::Compiler.construct_block string, binding, filename, lineno be.set_eval_binding binding be.call_on_instance(binding.self) end module_function :eval private :eval end class Module #-- # These have to be aliases, not methods that call instance eval, because we # need to pull in the binding of the person that calls them, not the # intermediate binding. #++ def module_eval(string=undefined, filename="(eval)", line=1, &prc) # we have a custom version with the prc, rather than using instance_exec # so that we can setup the StaticScope properly. if prc unless string.equal?(undefined) raise ArgumentError, "cannot pass both string and proc" end # Return a copy of the BlockEnvironment with the receiver set to self env = prc.block static_scope = env.repoint_scope self return env.call_under(self, static_scope, self) elsif string.equal?(undefined) raise ArgumentError, 'block not supplied' end string = StringValue(string) filename = StringValue(filename) # The staticscope of a module_eval CM is the receiver of module_eval ss = Rubinius::StaticScope.new self, Rubinius::StaticScope.of_sender binding = Binding.setup(Rubinius::VariableScope.of_sender, Rubinius::CompiledMethod.of_sender, ss) be = Rubinius::Compiler.construct_block string, binding, filename, line be.call_under self, ss, self end alias_method :class_eval, :module_eval end
true
40f476049ab8f5f902a18876a02c28e6d5b8c9f7
Ruby
guspowell/Battleships
/spec/board_spec.rb
UTF-8
812
2.984375
3
[]
no_license
require 'board' require 'player' describe Board do let(:board) { Board.new } let(:player) { Player.new } let(:ship) { Ship.new(2) } it 'should have no ships to start' do expect(board.ship_count).to eq 0 end it "should be able to receive ships from the player" do player.place(board, ship, ['a1','a2']) player.place(board, ship, ['b1', 'b2']) expect(board.ship_count).to eq 2 end it "should be able to receive ships from the player in a position" do board.receive(ship, 'j2') expect(board.ship_count).to eq 1 end it "should be able to fill places given the coordinates" do player.place(board,player.patrol_boat,['a1','b1']) board.fill_cells expect(board.places[:a1]).to eq(:s) #check cell contents = expect(board.places[:b1]).to eq(:s) end end
true
e0f1b00bce3e385cb3e04afe1c861a43c92ffd39
Ruby
filip373/ruby_algorithms
/enumerable.rb
UTF-8
1,389
3.296875
3
[]
no_license
module Enumerable def my_each self.size.times do |time| yield self.to_a[time] end end def my_each_with_index self.size.times do |time| yield self.to_a[time], time end end def my_select arr = [] self.my_each do |elem| arr.push elem if yield elem end return arr end def my_all? self.my_each do |elem| return false unless yield elem end return true end def my_none? self.my_each do |elem| return false if yield elem end return true end def my_count obj = (no_arg = true), &block unless no_arg return self.my_select do |elem| elem == obj end.size end if block_given? return self.my_select(&block).size else return self.size end end def my_map arr = [] self.each do |elem| arr.push yield elem end return arr end def my_inject proc = (no_proc = true), initial = self[0] memo = initial return memo if no_proc self.each do |elem| memo = proc.call memo, elem end if block_given? memo2 = initial self.each do |elem| memo2 = yield memo2, elem end return memo, memo2 else return memo end end end def multiply_els arr proc = Proc.new do |memo, elem| memo *= elem end return arr.my_inject(proc, 1) { |m,e| m *= e } end
true
3c1e17fde955b1619f725c3753be36ad8552f3b8
Ruby
pedro-ivo-molina/bank-slip-validator
/validator.rb
UTF-8
848
2.53125
3
[]
no_license
class Validator attr_reader :body_annotations def initialize @header_errors = [] @body_errors = [] @body_annotations = [] @footer_errors = [] end def validate_header(bank_slip:, rules:) rules.each do |rule| rule.validate(bank_slip) @header_errors << rule.error unless rule.error.empty? end return @header_errors end def validate_body(bank_slip:, rules:) rules.each do |rule| rule.validate(bank_slip) @body_errors << rule.error unless rule.error.empty? @body_annotations << rule.annotation unless rule.annotation.empty? end return @body_errors end def validate_footer(bank_slip:, rules:) rules.each do |rule| rule.validate(bank_slip) @footer_errors << rule.error unless rule.error.empty? end return @footer_errors end end
true
9a5af248af913ef1d60efd2b8a3ec901ba9cd4ab
Ruby
huyu398/manmenmi
/manmenmi.rb
UTF-8
2,833
2.53125
3
[]
no_license
require 'capybara' require 'capybara-webkit' require 'logger' require 'yaml' require_relative 'tag_reader' require_relative 'errors' MANMENMI_ROOT = File.expand_path(File.dirname(__FILE__)) AUDIO_PREFIX = "#{MANMENMI_ROOT}/voice" NFCPY_PREFIX = "#{MANMENMI_ROOT}/nfcpy/0.9" LOG_PREFIX = "#{MANMENMI_ROOT}/log" config = YAML.load(File.read("#{MANMENMI_ROOT}/config.yml")) URL = config['url'] USERS = config['users'] logger = Logger.new("#{LOG_PREFIX}/test.log") logger.level = Logger::INFO logger.info('Start MANMENMIIIIII!!!!!!!') nfc = TagReader.new loop do begin logger.info("Start polling") tag = nfc.read rescue (raise Errors::NFCReadError.new("Can't read a nfc tag", __LINE__)) # manmenmi!!! `mplayer #{AUDIO_PREFIX}/comeonbaby.wav 2>/dev/null` logger.info("Read a tag of uid:#{tag}") user = {} USERS.each do |_user| if _user['uid'] == tag user = _user end end raise Errors::UserRecognizeError.new("No user with uid:#{tag}", __LINE__) if user.empty? logger.info("Recognize a user with id:#{user['id']} name:#{user['name']}") session = Capybara::Session.new(:webkit) # login session.visit(URL) session.select(user['name'], from: '_ID') session.fill_in('Password', with: user['password']) session.click_button('ログイン') raise Errors::LoginError.new("Invalid password for user:#{user['name']}", __LINE__) if session.title.match(/エラー/) logger.info('Success login') # arrived or left login_time = Time.now timecard_table = session.all(:xpath, 'html/body/div/div/div/table/tbody/tr/td/table/tbody/tr/td/div/div/div/form/table/tbody/tr/td') arrive_cell, leave_cell = [timecard_table.at(0), timecard_table.at(1)] arrive_time = Time.parse(arrive_cell.text.match(/\d{2}:\d{2}/)[0]) if login_time < arrive_time + 15 * 60 # margin 15min `mplayer #{AUDIO_PREFIX}/goodmorn.wav 2>/dev/null` logger.info("#{user['name']} already logined cybozu") else if arrive_cell.has_button?('出社') leave_cell.click_button('出社') raise Errors::UnexpectedError.new("!!! Unexpeced error !!!", __LINE__) if session.title.match(/エラー/) `mplayer #{AUDIO_PREFIX}/goodmorn.wav 2>/dev/null` logger.info("#{user['name']} arrived office") elsif leave_cell.has_button?('退社') leave_cell.click_button('退社') raise Errors::UnexpectedError.new("!!! Unexpeced error !!!", __LINE__) if session.title.match(/エラー/) `mplayer #{AUDIO_PREFIX}/goodbay.wav 2>/dev/null` logger.info("#{user['name']} left office") else raise Errors::UnexpectedError.new("!!! Unexpeced error !!!", __LINE__) end end rescue => e `mplayer #{AUDIO_PREFIX}/error.wav 2>/dev/null` logger.error(e.message) end end
true
1b5b5026a1b64b07bdf61d825cfa84fb185f413d
Ruby
CJStadler/state_machine_checker
/lib/state_machine_checker/state_result.rb
UTF-8
1,115
3.359375
3
[ "MIT" ]
permissive
module StateMachineChecker # The result of checking whether this state satisfies a formula. class StateResult # @param [Boolean] satisfied # @param [Array<Symbol>] path def initialize(satisfied, path) @satisfied = satisfied @path = path end # Whether the formula is satisfied from this state. # # @return [true, false] def satisfied? satisfied end # A witness that the formula is satisfied from this state. # # @return [Array<Symbol>] an array of the names of transitions. def witness if satisfied? path end end # A counterexample demonstrating that the formula is not satisfied from this # state. # # @return [Array<Symbol>] an array of the names of transitions. def counterexample unless satisfied? path end end def or(other) if satisfied? self else other end end def and(other) if !other.satisfied? other else self end end private attr_reader :satisfied, :path end end
true
ee0e187c1f0ab6b5b0b30312ecfcab794440e64b
Ruby
msomji/bowling_kata
/bowl.rb
UTF-8
3,918
3.484375
3
[ "MIT" ]
permissive
# as a bowler I want to be able to start a new game # as a bowler I want to be able to bowl # as a bowler I want to be able to be able to see how many pins I knocked out after each bowl # as a bowler I want to be able to see if I get a spare or a strike # as a bowler I want to be able to see my score after every frame # as a bowloer I would like to get some instructions #as a bowler I would want to be able to mannuall enter how many pins I knock out # features # as a bowler I want to have a name? class Bowl attr_reader :score, :frame, :score_board def initialize @score = 0 @frame = 0 @score_board = [[0,0,0]] instructions end # sdfg def instructions "Instructions: You have played bowling before! here are a couple methods to help you around this game! To bowl - bowl(first_try, second_try) To bowl bonus frames(10th frame) - bonus(first_try, second_try) To check Score - score To reset game - reset To get instructions again - instructions " end def bowl(trial1, trial2) if trial2 + trial1 <= 10 && trial1 >= 0 && trial2 >= 0 user_updates(trial1,trial2) else "try again! you can knock out a max of only 10 pins per turn and positive numbers" end end def bonus(bowl1, bowl2) if @frame == 10 && bowl2 + bowl1 <= 10 && bowl1 >= 0 && bowl2 >= 0 && @score_board[-2][0] == 10 if bowl1 == 10 update_score_board(bowl1,0) "SRIKE | One more Bonus roll!" elsif bowl1 + bowl2 == 10 update_score_board(bowl1,bowl2) "SPARE! #{bowl1} / #{bowl2} | Game Over" else update_score_board(bowl1,bowl2) "#{bowl1} / #{bowl2} | Game Over" end elsif @frame == 10 && bowl2 + bowl1 <= 10 && bowl1 >= 0 && bowl2 >= 0 && @score_board[-2][0] != 10 && @score_board[-2][0] + @score_board[-2][1] == 10 if bowl1 == 10 update_score_board(bowl1,0) "SRIKE | Game Over" else update_score_board(bowl1,0) "#{bowl1} / 0 | Game Over" end elsif @frame == 11 && bowl1 >= 0 && @score_board[-2][0] == 10 && @score_board[-3][0] == 10 update_score_board(bowl1,0) "SRIKE | Awesome!! | Game Over!" else "No bonus rounds for you sir" end end def score @score = 0 next_frame = 0 @score_board.each do |round| next_frame +=1 if round[0] == 10 @score += round[0] + @score_board[next_frame][0] + @score_board[next_frame][1] elsif round[0] + round[1] == 10 @score += 10 + @score_board[next_frame][0] else @score += round[0] + round[1] end end @score end def reset @score = 0 @frame = 0 @score_board = [[0,0,0]] end private def update_score_board(trial1, trial2) @score_board.insert(-2, [trial1, trial2]) @frame += 1 end def user_updates(trial1,trial2) if @frame < 9 pre_last_frame_user_updates(trial1,trial2) elsif @frame == 9 last_frame_user_updates(trial1,trial2) else "The Game is over buddy! Make a new Game" end end def pre_last_frame_user_updates(trial1,trial2) if trial1 == 10 update_score_board(trial1,0) "STRIKE!" elsif trial1 + trial2 == 10 update_score_board(trial1,trial2) "SPARE! #{trial1} / #{trial2}" else update_score_board(trial1,trial2) "#{trial1} / #{trial2}" end end def last_frame_user_updates(trial1,trial2) if trial1 == 10 update_score_board(trial1,0) "STRIKE! | You have two more bonus bowl! Use the bonus method to enter your bonus pins" elsif trial1 + trial2 == 10 update_score_board(trial1,trial2) "SPARE! #{trial1} / #{trial2} | You have one more bonus bowl! Use the bonus method to enter your bonus pins" else update_score_board(trial1,trial2) "#{trial1} / #{trial2} | Game Over" end end end Bowl.new
true
502aeccf5aa28e42cc789c26ff40cb8a662e5a13
Ruby
v9n/proc
/study/interviewcake/matching-parens/spec.rb
UTF-8
462
2.796875
3
[]
no_license
require_relative 'solution.rb' require 'minitest/spec' require 'minitest/autorun' describe InterviewCake::MatchingParens do it 'returns correct close posstion' do s = "Sometimes (when I nest them (my parentheticals) too much (like this (and this))) they get confusing." solution = InterviewCake::MatchingParens.new solution.perform(s, 10).must_equal 79 solution.perform(s, 57).must_equal 78 solution.perform(s, 68).must_equal 77 end end
true
2faaea69eca77e2681b2c2e070515301c5110172
Ruby
StlMaris123/ruby_tutorials
/learn ruby the hard way/ex3.rb
UTF-8
1,544
4.40625
4
[]
no_license
#mathematics #use of interpolation is how we insert Ruby computations #displays the following code puts "i will now count my hens" #executes the computations and interpolates it wit Hens and also Roosters puts "Hens #{25 + 30 / 6}" puts "Roosters #{100-25*3%4}" #displays the following code puts "I will now count my eggs" #Executes the following computation using PEMDA and displays the answer puts 3+2+1-5+4%2-1/4%6 #displays the following code puts "is it true that 3 + 2 < 5 - 7" #compares the value of 3+2 and 5-7 and returns a boolean value puts 3 + 2 < 5 - 7 #Executes the code inside the parenthesis and concatenates it with the string puts "what is 3 + 2? #{3+2}" puts "what is 5 - 7? #{5-7}" #Displays the following thhe code puts "oh thats why its false" puts "How about some more?" #executes the code inside the parenthesis and concatenates the boolean value value to the string puts "is it greater? #{5 > -2}" puts "is it greater or equal? #{5 >= -2}" puts "is it less or equal? #{5 <= -2}" #using floating point numbers puts "i will now count my hens" puts "Hens #{25.00 + 30.00 / 6.00}" puts "Roosters #{100.00 - 25.00 * 3.00 % 4.00}" puts "I will now count my eggs" puts 3.00 + 2.00 + 1.00 - 5.00 + 4.00 % 2.00 - 1.00 / 4.00 % 6.00 puts "is it true that 3 + 2 < 5 - 7" puts 3 + 2 < 5 - 7 puts "what is 3 + 2? #{3+2}" puts "what is 5 - 7? #{5-7}" puts "oh thats why its false" puts "How about some more?" puts "is it greater? #{5 > -2}" puts "is it greater or equal? #{5 >= -2}" puts "is it less or equal? #{5 <= -2}"
true
4fb73857aa983f0cfc10960b91ccfadff7049233
Ruby
alrawi90/day_name_displayer
/day_name_display.rb
UTF-8
1,185
3.65625
4
[]
no_license
class Day_name_displayer def initialize welcome menu end def welcome puts "" puts "" puts "welcome to ---Day Name Displayer----" puts "" end def msg puts "Please enter a number from 1-7 OR enter 'exit' to end application ." end def menu msg input=nil while(input !="exit") puts "" input=gets.strip if input =="1" puts "Sunday" elsif input =="2" puts "Monday" elsif input=="3" puts "Tuesday" elsif input=="4" puts "Wednesday" elsif input=="5" puts "Thursday" elsif input=="6" puts "Friday" elsif input=="7" puts "Saturday" elsif input=="exit" puts "Thank you for using --Day Name Displayer--" puts "" break else puts "invalid input" msg end end end end obj=Day_name_displayer.new
true
77fc6c7b8fcc52837b08ba5995e88d34e3ec4746
Ruby
squareben1/review_12_spellcheck
/lib/spellchecker.rb
UTF-8
818
3.75
4
[]
no_license
class SpellChecker def initialize(dictionary=[]) @dictionary = homogenise_arr(dictionary) end def spellcheck(string) words = split_string(string) checked_words = [] words.each do | word | checked_words.push(word_check(word)) end checked_words.join(" ") end def add_words(string) new_words = split_string(string) lower_case_words = homogenise_arr(new_words) @dictionary.push(*lower_case_words) end private def homogenise_arr(arr) arr.map!(&:downcase) end def split_string(string) # gives potential for extension when client needs punctuation, etc. string.split(" ") end def word_check(word) down_case_word = word.downcase if [email protected]?(down_case_word) "~#{word}~" else word end end end
true
103902ed24dc2e9570dc384f42565e5dedda3a22
Ruby
johndierks/ruby-intro
/vehicles.rb
UTF-8
306
3.609375
4
[]
no_license
class Vehicle def go puts "Pressed Gas Pedal" end def stop puts "Pressed Brake Pedal" end end class Convertible < Vehicle def lower_top puts "It's a nice day, so I put the top down" end def raise_top puts "Looks like it's going to rain, so I raised the top." end end
true
91f16e625d58019b95a8823cc5b085d82cd43387
Ruby
Dwein9/ruby-object-initialize-lab-web-1116
/lib/person.rb
UTF-8
73
2.765625
3
[]
no_license
class Person def initialize(the_name) @name = the_name end end
true
4733d1c6cfce81aa46248e89b7d5bb74a1f1c54e
Ruby
jordanluce/AdvancedActiveRecord
/has_many_activerecord.rb
UTF-8
5,095
3.359375
3
[]
no_license
#has_many associations activerecord class Person < ActiveRecord::Base belongs_to :location belongs_to :role end class Role < ActiveRecord::Base has_many :people end class Location < ActiveRecord::Base has_many :people end ____________________________________________________________________________________________________________________ Role.all id name billable 1 Developer t 2 Manager f 3 Unassigned f ____________________________________________________________________________________________________________________ Location.all id name billable 1 Boston 1 2 New York 1 3 Denver 2 ____________________________________________________________________________________________________________________ People.all id name role_id location_id 1 Wendell 1 1 2 Christie 1 1 3 Sandy 1 3 4 Eve 2 2 ____________________________________________________________________________________________________________________ #First we want to fine all distinct locations with at least one person who belongs to a billable role. #We can also use joins with has_many just like on belongs_to Location.joins(:people) locations | people id name region_id | id name role_id location_id 1 Boston 1 | 1 Wendell 1 1 1 Boston 1 | 2 Christie 1 1 3 Denver 2 | 3 Sandy 1 3 2 New York 1 | 4 Eve 2 2 ____________________________________________________________________________________________________________________ #The use of has_many_through Location.joins(people: :role) locations | people | roles id name region_id | id name role_id location_id | id name billable 1 Boston 1 | 1 Wendell 1 1 | 1 Developer t 1 Boston 1 | 2 Christie 1 1 | 1 Developer t 3 Denver 2 | 3 Sandy 1 3 | 1 Developer t 2 New York 1 | 4 Eve 2 2 | 2 Manager f #Then now we can filter through with .where Location.joins(people: :role).where(roles: { billable: true }) #Which then returns something like that: # locations | people | roles id name region_id | id name role_id location_id | id name billable 1 Boston 1 | 1 Wendell 1 1 | 1 Developer t 1 Boston 1 | 2 Christie 1 1 | 1 Developer t 3 Denver 2 | 3 Sandy 1 3 | 1 Developer t #But now we can notice that we see BOSTON TWICE... We can remiediate to this with the (distinct)method. # Location.joins(people: :role).where(roles: { billable: true}).distinct #Which now returns something like this: # locations id name region_id 3 Denver 2 1 Boston 1 #We can now encapsulate our query in our object and do: # class location < ActiveRecord::Base def self.billable joins(people: :role).where(roles: { billable: true }).distinct end end Location.billable ____________________________________________________________________________________________________________________ #Now we want to order the billable locations by region name, then by location name. # class Location < ActiveRecord::Base belongs_to :region end class Region < ActiveRecord::Base has_many :locations end #So straigth away we can do the following query to get the billable locations to be ordered by region name then by location name: # Location.joins(:region).merge(Region.order(:name)).order(:name) #Which gives us the following: # locations | regions id name region_id | id name 1 Boston 1 | 1 East 2 New York 1 | 1 East 3 Denver 2 | 2 West #So now we can create our method on the model to scope things: # class Location < ActiveRecord::Base def self.billable joins(people: :role).where(roles: { billable: true }).distinct end def self.by_region_and_location_name joins(:region).merge(Region.order(:name)).order(:name) end end #Now the problem that we are going to have is we won't be able to join our scopes and do: # XXXXXX Location.billable.by_region_and_location_name XXXXXX #This is because the (distinct) method. #We need to use a sub-query with the (from) method #Let's use it to first return distinct billable locations. # Location.from(Location.billable, :locations) #Which returns this: # locations id name region_id 3 Denver 2 1 Boston 1 #So now we can put it all together # Location.from(Location.billable, :locations).by_region_and_location_name locations | regions id name region_id | id name 1 Boston 1 | 1 East 3 Denver 2 | 2 West
true
3b7653ccbcc67d487eecff3adc342d73d8fcda77
Ruby
danabo/zhat
/_plugins/jumpto.rb
UTF-8
384
2.515625
3
[ "MIT" ]
permissive
module Jekyll class JumpToBlock < Liquid::Block require "shellwords" def initialize(tag_name, text, tokens) super @text = text.shellsplit end def render(context) contents = super "<a name='#{@text[0]}'></a>"\ "<span class='jump_to'>#{contents}</span>" end end end Liquid::Template.register_tag('jumpto', Jekyll::JumpToBlock)
true
2063d534906cb9df672fdfa25f7da4e388116b43
Ruby
stupergenius/Software-Engineering-for-SaaS
/assignment1/part2_spec.rb
UTF-8
3,078
3.265625
3
[]
no_license
load 'part2.rb' describe "#rps_game_winner" do context "fail states" do it "should raise when number of players is not two" do expect { rps_game_winner([]) }.to raise_error(WrongNumberOfPlayersError) expect { rps_game_winner([["Armando", "P"]]) }.to raise_error(WrongNumberOfPlayersError) expect { rps_game_winner([["Armando", "P"], ["Dave", "S"], ["Ben", "P"]]) }.to raise_error(WrongNumberOfPlayersError) end it "should raise when an invalid strategy is given" do expect { rps_game_winner([["Armando", "P"], ["Dave", "F"]]) }.to raise_error(NoSuchStrategyError ) end end context "ties" do it "should return the first player in case of a tie" do p1 = ["Armando", "P"] p2 = ["Dave", "P"] rps_game_winner([p1, p2]).should eq(p1) rps_game_winner([p2, p1]).should eq(p2) end end context "winners" do it "should return rock beats scissors" do p1 = ["Armando", "R"] p2 = ["Dave", "S"] rps_game_winner([p1, p2]).should eq(p1) rps_game_winner([p2, p1]).should eq(p1) end it "should return paper beats rock" do p1 = ["Armando", "P"] p2 = ["Dave", "R"] rps_game_winner([p1, p2]).should eq(p1) rps_game_winner([p2, p1]).should eq(p1) end it "should return scissors beats paper" do p1 = ["Armando", "S"] p2 = ["Dave", "P"] rps_game_winner([p1, p2]).should eq(p1) rps_game_winner([p2, p1]).should eq(p1) end end end describe "#is_single_round" do game = [ ["Armando", "P"], ["Dave", "S"] ] tournament = [ [ ["Allen", "S"], ["Omer", "P"] ], [ ["David E.", "R"], ["Richard X.", "P"] ], ] it "should be able to detect a single round game" do is_single_round?(game).should be_true is_single_round?(tournament).should be_false end end describe "#rps_tournament_winner" do winner = ["Richard", "R"] tournament1 = [ winner, ["Michael", "S"] ] tournament4 = [ [ ["Armando", "P"], ["Dave", "S"] ], tournament1, ] tournament8 = [ tournament4, [ [ ["Allen", "S"], ["Omer", "P"] ], [ ["David E.", "R"], ["Richard X.", "P"] ], ], ] tournament16 = [ tournament8, [ [ [ [ "P1", "P" ], [ "P2", "S" ] ], [ [ "P3", "R" ] , [ "P4", "P" ] ], ], [ [ [ "P7", "P" ], [ "P5", "S" ] ], [ [ "P9", "R" ] , [ "P10", "P" ] ], ], ], ] it "should return the winner" do rps_tournament_winner(tournament1)[0].should eq "Richard" rps_tournament_winner(tournament4)[0].should eq "Richard" rps_tournament_winner(tournament8)[0].should eq "Richard" rps_tournament_winner(tournament16)[0].should eq "Richard" end end
true
8cad1f79ccd8091f0b35197064bfd57ae7652eef
Ruby
shoebham/Ruby_Projects_the_odin_project
/Project_Tic_Tac_Toe/tic_tac_toe.rb
UTF-8
3,406
3.375
3
[]
no_license
LINES = [[1,2,3],[4,5,6],[7,8,9],[1,5,9],[3,5,7],[1,4,7],[2,5,8],[3,6,9]] class Game def initialize(player_1_class,player_2_class) @board = Array.new(10) @current_player_id=0 @players = [player_1_class.new(self,"X",1),player_2_class.new(self,"O",2)] puts "#{current_player} goes first" end attr_reader :board, :current_player_id def play loop do place_marker(current_player) if player_won?(current_player) p "#{current_player} is the winner" print_board return elsif board_full? p "It's a draw!" print_board return end switch_player! end end def free_positions (1..9).select{|pos| @board[pos].nil?} end def place_marker(player) position = player.select_position! p "#{player} selects #{player.marker} position #{position}" @board[position] = player.marker end def player_won?(player) LINES.any? do |i| i.all? {|j| @board[j] == player.marker} end end def board_full? free_positions.empty? end def other_player_id 1-@current_player_id end def switch_player! @current_player_id = other_player_id end def current_player @players[current_player_id] end def print_board col_sep = " | " row_sep = "--+---+--" label_pos = ->(pos){ @board[pos] ? @board[pos] : pos} row_for_display= ->(row){row.map(&label_pos).join(col_sep)} row_pos = [[1,2,3],[4,5,6],[7,8,9]] rows_for_display=row_pos.map(&row_for_display) puts rows_for_display.join("\n"+ row_sep +"\n") end end class Player attr_reader:marker,:num def initialize(game,marker,num) @game = game @marker =marker @num = num end end class HumanPlayer < Player attr_reader:i def select_position! @game.print_board loop do puts "Select your #{marker} position" selection = gets.to_i return selection if @game.free_positions.include?(selection) puts "position #{selection} position is not available" end end def to_s "Human #{num}" end end puts players_with_human = [HumanPlayer, HumanPlayer].shuffle Game.new(*players_with_human).play
true
17a9860a23a7d87cfbb573810d55bf79bf09ccb6
Ruby
idimitrov07/ruby_ood_book
/chapter_five/duck_overlook.rb
UTF-8
437
3.15625
3
[]
no_license
# overlooking the duck class Trip attr_reader :bicycles, :customers, :vehicle # this 'mechanic' could be of any class.. def prepare(mechanic) mechanic.prepare_bicycles(bicycles) end # ... end # 'Mechanic' class in not referenced anywhere in the class above class Mechanic def prepare_bicycles(bicycles) bicycles.each { |bicycle| prepare_bicycle(bicycle) } end def prepare_bicycle(bicycle) #... end end
true
fd588b4372f00639f2c3222c062f12d7199a4e30
Ruby
smainar/backend_prework
/day_1/exe3-1.rb
UTF-8
296
3.578125
4
[]
no_license
puts "I will count my books." puts "Old text books #{18 - 2 * 3}." puts "Autobiographies #{3 + 3 % 1}." puts "Non-fiction #{27 + 14 / 2 - 5}." puts "Fiction #{56 - 17 % 3}." # Results: # I will count my books. # Old text books 12. # Autobiographies 3. # Non-fiction 29. # Fiction 54.
true
9a2605235dfd8be5f55e327771ce6732dd30a5ed
Ruby
goyox86/razer
/lib/razer.rb
UTF-8
984
3.640625
4
[ "MIT" ]
permissive
require "razer/version" module Razer # # A small utility class which for flattening nested arrays. # class Flattener # Flattens the input +array+ of arrays into a uni-dimensional one # preserving the relative order of eelements. If an empty array is # provided then the exact same empty array objevct will be returned. # # The algorithm is guaranteed to flatten the input array in O(n) time # and O(n) space with +n+ being the sum of the sizes of all involved # arrays including the top level one. # # input_array = [1, [2, 3, [4, 5, [6]]]] # # flattener = Flattener.new # flattener.flatten(input_array) # => [1, 2, 3, 4, 5, 6] # def flatten(array, accumulator = []) return array if array.empty? array.each do |element| if element.is_a?(Array) flatten(element, accumulator) else accumulator.push(element) end end accumulator end end end
true
3a371458f69091c787cb7e3bd844db7220ab7ff9
Ruby
nickfryer21/screw-charlie
/app/models/game_player.rb
UTF-8
745
2.65625
3
[]
no_license
# == Schema Information # # Table name: game_players # # id :integer not null, primary key # game_id :integer # player_id :integer # slot_id :integer # class GamePlayer < ActiveRecord::Base belongs_to :game belongs_to :player has_one :hand, :dependent => :destroy has_many :turns, :dependent => :destroy belongs_to :slot after_create do self.hand = Hand.create! # Make sure newly added players are added to a slot next_slot = self.game.slots.where(available: true).first unless next_slot.nil? self.slot = next_slot self.save next_slot.available = false next_slot.save! end end def draw_card(draw_pile) self.hand.cards << draw_pile.draw_card end end
true
9f55d4455b0328267d0dc466c14056b4f7f75add
Ruby
fbenevides/conf-algorithm
/lib/conferences/track.rb
UTF-8
904
3.265625
3
[]
no_license
module Conferences class Track attr_reader :name def initialize(name, sessions = [Session.new('Morning', 9, 12), Session.new('Afternoon', 13, 17)]) @name = name @sessions = sessions end def duration @sessions.map(&:duration).reduce(&:+) end def distribute(talks) talks.sort_by(&:duration) removed = [] @sessions.each do |session| sum = 0 talks.each do |talk| if sum != session.duration if session.total + talk.duration <= session.duration session << talk sum += talk.duration removed << talk end end end talks -= removed end talks end def show puts "#{name}" @sessions.each do |session| puts " #{session.name}" session.show puts " " end end end end
true
babbe9f2186192f1da4a927285d6f42b52e3c223
Ruby
junyuanxue/learn_to_program
/ch14-blocks-and-procs/better_program_logger.rb
UTF-8
448
3.4375
3
[]
no_license
$indent = 0 def better_log desc, &block puts " " * $indent + "Beginning \"#{desc}\"..." $indent += 1 result = block.call $indent -= 1 puts " " * $indent + "...\"#{desc}\" finished, returning: #{result.to_s}" end better_log "outer block" do better_log "some little block" do better_log "teeny-tiny block" do "lots of love" end 42 end better_log "yet another block" do "I like Indian food!" end true end
true
659316aa79719ba729942b2fc657afdaa0fe1e20
Ruby
CoopTang/module_0_capstone
/day_5/ex39.rb
UTF-8
2,297
4.4375
4
[]
no_license
# Hashes in 'Learn Ruby the Hard way' # Create a mapping of states to abbreviation states = { 'Oregon' => 'OR', 'Florida' => 'FL', 'California' => 'CA', 'New York' => 'NY', 'Michigan' => 'MI' } # Creat a basic set of states and some cities in them cities = { 'CA' => 'San Francisco', 'MI' => 'Detroit', 'FL' => 'Jacksonville' } # Add some more cities cities['NY'] = 'New York' cities['OR'] = 'Portland' # puts out some cities puts '-' * 10 puts "NY State has: #{cities['NY']}" puts "OR State has: #{cities['OR']}" # puts some states puts '-' * 10 puts "Michigan's abbreviation is: #{states['Michigan']}" puts "Florida's abbreviation is: #{states['Florida']}" # do it using the state then cities dict puts '-' * 10 puts "Michigan has: #{cities[states['Michigan']]}" puts "Florida has: #{cities[states['Florida']]}" # puts every state abbreviation puts '-' * 10 states.each do |state, abbrev| puts "#{state} is abbreviated #{abbrev}" end # puts every city in state puts '-' * 10 cities.each do |abbrev, city| puts "#{abbrev} has the city #{city}" end # now do both at the same time puts '-' * 10 states.each do |state, abbrev| city = cities[abbrev] puts "#{state} is abbreviated #{abbrev} and has city #{city}" end puts '-' * 10 # by default ruby says "nill" when something isn't in there state = states['Texas'] if !state puts "Sorry, no Texas." end # default values using ||= with the nill result city = cities['TX'] city ||= 'Does Not Exist' puts "The city for the state 'TX' is: #{city}" # doing some of my own stuff cities_of_co = ["Boulder", "Denver", "Colorado Springs"] states['Colorado'] = 'CO' cities['CO'] = cities_of_co # let's print out the contents puts '-' * 10 states.each do |state, abbrev| city = cities[abbrev] print "#{state} is abbreviated #{abbrev} and has " # gotta handle an array differently than the original if (city.class == Array) print "cities " cities_str = "" city.each do |city| cities_str += "#{city}, " end # remove the final space and comma puts cities_str[0...-2] else puts "city #{city}" end end
true
8073b475c3f9cf87336820c2f7437add4a43cc37
Ruby
arakla/binder-app
/app/helpers/application_helper.rb
UTF-8
1,325
2.625
3
[]
no_license
module ApplicationHelper def display_base_errors resource return '' if (resource.errors.empty?) or (resource.errors[:base].empty?) messages = resource.errors[:base].map { |msg| content_tag(:p, msg) }.join html = <<-HTML <div class="alert alert-error alert-block"> <button type="button" class="close" data-dismiss="alert">&#215;</button> #{messages} </div> HTML html.html_safe end def time(display_time) time_zone = ActiveSupport::TimeZone.new("Eastern Time (US & Canada)") display_time.in_time_zone(time_zone).strftime("%I:%M%p") end def date(display_date) time_zone = ActiveSupport::TimeZone.new("Eastern Time (US & Canada)") display_date.in_time_zone(time_zone).strftime("%m/%d/%y") end def date_and_time(display_date_and_time) [date(display_date_and_time), time(display_date_and_time)].compact.join(" ") end def format_boolean(bool) bool ? "Yes" : "No" end def currency(display_currency) number_to_currency(display_currency) end def format_downtime(downtime) downtime = downtime.to_i if downtime < 0 neg = '-' downtime *= -1 else neg = '' end hours = downtime / 60 / 60 minutes = downtime / 60 - hours * 60 return neg + ("%02d" % hours) + ":" + ("%02d" % minutes) end end
true
bc69eede1366cf4d862db29f1cbd0d2247f0380f
Ruby
timbeiko/tealeaf-prework
/greetings.rb
UTF-8
177
3.90625
4
[]
no_license
# greetings.rb def greetings(name) puts "Hi there, "+ name end name = gets.chomp greetings(name) x = 2 puts x = 2 p name="Joe" four = "four" print something = "nothing"
true
cb186eccb2a05d681feeb207b686282f486dd8a7
Ruby
mdvincen/tts_projects
/unless.rb
UTF-8
77
3.015625
3
[]
no_license
sum = 50 unless sum ==50 puts 'That is incorrect' else puts 'Correct' end
true
ab65df6218c1465eb922ba6ed8912f6957a0fbf7
Ruby
mgdelin/operators-online-web-ft-081219
/lib/operations.rb
UTF-8
182
2.96875
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def unsafe?(speed) if speed > 60 return true elsif speed < 40 return true else return false end end def not_safe?(speed) speed > 60 or speed < 40 ? true : false end
true
37823c86fc5e1317850a71e1bd760e3b39919357
Ruby
bemijonathan/tracker
/app/models/transaction.rb
UTF-8
435
2.53125
3
[]
no_license
require "securerandom" class Transaction < ApplicationRecord belongs_to :user before_save :getvalue def encode (uuid) return [uuid.tr('-', '').scan(/../).map(&:hex).pack('c*')].pack('m*').tr('+/', '-_').slice(0..21) end def getvalue() val = SecureRandom.uuid token = encode(val) self.tracking_id = token.toUpcase end end
true
03a5d9fdb45dbf687cc69a94a7e49a58dfbab955
Ruby
learn-co-students/houston-web-062419
/07-CLI-Application/lib/app.rb
UTF-8
564
3.03125
3
[]
no_license
$prompt = TTY::Prompt.new def start puts 'Welcome to my APP!' name end def name name = $prompt.ask('What is your name?') puts name p = password puts "Your password is: #{p}" choices = %w(milk coffee tea orageJuice) $prompt.multi_select("Select drinks?", choices) end # name = prompt.ask('What is your name?') # puts name # choice = prompt.yes?('Do you like Ruby?') # puts choice # secret = prompt.mask("What is your secret?") # puts secret # choice = prompt.select("Choose your destiny?", %w(Scorpion Kano Jax)) # puts choice
true
d360de954a635d4546e2ffc30ece84f0a3b1c210
Ruby
1powechri2/BikeShare
/app/models/cart.rb
UTF-8
764
3.25
3
[]
no_license
class Cart attr_reader :contents def initialize(initial_content) @contents = initial_content || Hash.new(0) end def total_count @contents.values.sum end def add_accessory(accessory_id) @contents[accessory_id.to_s] ||= 0 @contents[accessory_id.to_s] += 1 end def accessory_quantity(accessory_id) @contents[accessory_id.to_s] end def subtotal(accessory_id) accessory_quantity(accessory_id) * Accessory.find(accessory_id).price end def total sub_totals = [] @contents.each do |id, quantity| sub_totals.push(Accessory.find(id).price * quantity) end sub_totals.sum end def accessory_ids ids = [] @contents.each do |id, quantity| ids.push(id.to_i) end ids end end
true
c9ab308c2df9f5af1df9e8f4bf2d5985e8660b52
Ruby
s6ruby/universum
/universum-contracts/tokens/token_test.rb
UTF-8
1,957
2.96875
3
[ "CC0-1.0" ]
permissive
# to test the contract script run: # $ ruby tokens/token_test.rb require 'minitest/autorun' require_relative 'token' class TestToken < Minitest::Test def setup @token = Token.new( name: 'Your Crypto Token', symbol: 'YOU', decimals: 8, initial_supply: 1_000_000 ) end def test_transfer assert_equal 100_000_000_000_000, @token.balance_of( owner: '0x0000' ) assert_equal 0, @token.balance_of( owner: '0x1111' ) assert @token.transfer( to: '0x1111', value: 100 ) assert_equal 100, @token.balance_of( owner: '0x1111' ) assert @token.transfer( to: '0x2222', value: 200 ) assert_equal 200, @token.balance_of( owner: '0x2222' ) assert_equal 99_999_999_999_700, @token.balance_of( owner: '0x0000' ) end def test_transfer_from ## note: NOT pre-approved (no allowance) - will FAIL assert [email protected]_from( from: '0x1111', to: '03333', value: 30 ) assert_equal 0, @token.allowance( owner: '0x0000', spender: '0x1111' ) assert @token.approve( spender: '0x1111', value: 50 ) assert_equal 50, @token.allowance( owner: '0x0000', spender: '0x1111' ) ### change sender to 0x0001 Contract.msg = { sender: '0x1111' } pp Contract.msg assert @token.transfer_from( from: '0x0000', to: '0x3333', value: 30 ) assert_equal 30, @token.balance_of( owner: '0x3333' ) assert_equal 99_999_999_999_970, @token.balance_of( owner: '0x0000' ) assert_equal 0, @token.balance_of( owner: '0x1111' ) ### change sender back to 0x0000 Contract.msg = { sender: '0x0000' } pp Contract.msg assert @token.transfer( to: '0x1111', value: 1 ) assert_equal 99_999_999_999_969, @token.balance_of( owner: '0x0000' ) assert_equal 1, @token.balance_of( owner: '0x1111' ) end end # class TestToken
true
4275ab528d5840b3c7bc3a859b31bb1482410d28
Ruby
JDAVEHACKER/RubyLearning
/comparacion_combinado.rb
UTF-8
430
4.40625
4
[]
no_license
puts "Operador de comparación combinada" #Devuelve 0 si el primero y el segundo son iguales #Devuelve 1 si el primero es mayor que el segundo #Devuelve -1 si el primero es menor que el segundo puts "ingrese dos número" num1 = gets.chomp.to_i num2 = gets.chomp.to_i res= num1 <=> num2 if res == 0 puts "son iguales" elsif res == 1 puts "#{num1} es mayor que #{num2}" elsif res == -1 puts "#{num1} es menor que #{num2}" end
true
f031dba05393c7aa815b60f135c0b7dea604ec81
Ruby
paulalexrees/learn_to_program
/ch14-blocks-and-procs/grandfather_clock.rb
UTF-8
249
3.296875
3
[]
no_license
def grandfather_clock &block hours = if Time.new.hour > 12 Time.new.hour - 12 else Time.new.hour end hours.times{ yield } end dong = Proc.new { puts "DONG!" } grandfather_clock &dong
true
55fbbd4186f48f53254d844caa13709ebe04e92e
Ruby
octosteve/hangman
/lib/hangman/boundary/game_server.rb
UTF-8
1,351
2.75
3
[ "MIT" ]
permissive
# frozen_string_literal: true module Boundary class GameServer attr_reader :name def initialize(name:) @name = name @ractor = create_ractor end def make_guess(guess) ractor.send([:make_guess, guess]) end def won? ractor.send([:won?, Ractor.current]) Ractor.receive end def lost? ractor.send([:lost?, Ractor.current]) Ractor.receive end def word ractor.send([:get_word, Ractor.current]) Ractor.receive end def masked_word ractor.send([:get_masked_word, Ractor.current]) Ractor.receive end private attr_reader :ractor def create_ractor words_path = "#{File.expand_path(__dir__)}/../../../assets/words.txt" word_list = File.readlines(words_path).map(&:strip) Ractor.new(word_list, name: name) do |word_list| game = Core::Game.start_game(name, word_list) loop do case receive in [:make_guess, guess] game.make_guess(guess) in [:won?, from] from.send game.won? in [:lost?, from] from.send game.lost? in [:get_word, from] from.send game.selected_word in [:get_masked_word, from] from.send game.masked_word end end end end end end
true
6e1dfe76b3dca4517b9f9f5de59425ebc36d097f
Ruby
klavinslab/ProtocolsForReview
/illumina_ngs/protocol/dilute_total_rna/protocol.rb
UTF-8
5,823
2.515625
3
[]
no_license
# By Eriberto Lopez # [email protected] # Production 10/05/18 # C µl needs "RNA/RNA_ExtractionPrep" needs "Illumina NGS Libs/RNASeq_PrepHelper" needs "Illumina NGS Libs/TruSeqStrandedTotalRNAKit" class Protocol include RNA_ExtractionPrep include RNASeq_PrepHelper include TruSeqStrandedTotalRNAKit INPUT = "Total RNA" OUTPUT = "Diluted Total RNA Plate" INPUT_RNA_CONC = 300#ng # TODO: Find right starting concentration for an input so that the enrich fragment step does not over amplify the cDNA library and make it too concentrated FINAL_VOL = 10 def main operations.make # Retrieve RNA extracts and let thaw at room temp thaw_rna_etracts # Get ice for following reagents get_ice # Sanatize bench sanitize # Retrieve materials for rRNA depletion and Fragmentation gather_RiboZero_Deplete_Fragment_RNA_materials(operation_type()) normalize_and_fill_rna_plates() show {note "<b>Put away the following.</b>"} operations.store return {} end # Main # Caluculates the volume needed from the RNA sample to meet the desired final concentration # # @params rna_conc [int] is the concentration of RNA in [ng/ul] # @returns rna_dil_vol [int] is the volume of RNA required to meet the desired final conc. def dilute_rna(rna_conc) r_num = Random.new (debug) ? rna_conc = r_num.rand(1000) : rna_conc = rna_conc # For testing & debugging rna_dil_vol = (INPUT_RNA_CONC.to_f/rna_conc.to_f) return rna_dil_vol end # Calculates the volume of MG H2O required to meet the desired final RNA conc # # @params rna_dil_vol [int] is the volume of RNA required to meet the desired final conc. # @returns h2o_dil_vol [int] is the volume of water required to meet the desired final conc. def dilute_h2o(rna_dil_vol) h2o_dil_vol = FINAL_VOL - rna_dil_vol if h2o_dil_vol < 0 return 0 else return h2o_dil_vol end # (h2o_dil_vol < 0) ? (return 0) : (return h2o_dil_vol) end # Finds all RNA extractions in the job and directs tech to grab them - TODO: Sort by box/location def thaw_rna_etracts() rna_etracts = operations.map {|op| op.input(INPUT).item} take(rna_etracts, interactive: true) show do title "Thawing Samples" separator note "Let the RNA Extract(s) thaw at room temperature." end end # Directs tech to fill the output collection with the correct item, rna_vol, and water_vol into the appropriate well # # out_colleciions [Array of objs] is an array of collection objs that the RNAs will get diluted into def normalize_and_fill_rna_plates() r_num = Random.new groupby_out_collection = operations.group_by {|op| op.output(OUTPUT).collection} groupby_out_collection.each {|out_coll, ops| obj_type = ObjectType.find(out_coll.object_type_id) ops.each {|op| rna_item = op.input(INPUT).item rna_item.get(:concentration).nil? ? rna_conc = r_num.rand(1000) : rna_conc = rna_item.get(:concentration) op.temporary[:rna_dil_vol] = dilute_rna(rna_conc) op.temporary[:h2o_dil_vol] = dilute_h2o(op.temporary[:rna_dil_vol]) } rc_list = ops.map {|op| [op.output(OUTPUT).row, op.output(OUTPUT).column]} item_matrix = ops.map {|op| op.input(INPUT).item.id}.each_slice(obj_type.columns).map {|slice| slice} rna_vol_matrix = ops.map {|op| op.temporary[:rna_dil_vol]}.each_slice(obj_type.columns).map {|slice| slice} h2o_vol_matrix = ops.map {|op| op.temporary[:h2o_dil_vol]}.each_slice(obj_type.columns).map {|slice| slice} log_info 'rna_vol_matrix',rna_vol_matrix,'h2o_vol_matrix',h2o_vol_matrix show do title "Gather Material(s)" separator check "Gather a #{obj_type.name} and label <b>#{out_coll.id}</b>" end tot_h2o_vol = 0 h2o_vol_matrix.flatten.each {|vol| tot_h2o_vol += vol} show do title "Fill #{obj_type.name} #{out_coll} with MG H2O" separator check "For the next steps you will need #{(tot_h2o_vol + 20.0).round(2)}#{MICROLITERS}" end show do title "Fill #{obj_type.name} #{out_coll} with MG H2O" separator note "Follow the table below to fill the plate:" table highlight_alpha_rc(out_coll, rc_list) { |r, c| "#{h2o_vol_matrix[r][c].round(1)}#{MICROLITERS}" } end fill_by_row = rc_list.group_by {|r,c| r}.sort fill_by_row.each { |row, rc_list| show do title "Fill #{obj_type.name} #{out_coll} with RNA [#{INPUT_RNA_CONC/FINAL_VOL}#{NANOGRAMS}/#{MICROLITERS}]" separator table highlight_alpha_rc(out_coll, rc_list) { |r, c| "#{item_matrix[r][c]}\n#{rna_vol_matrix[r][c].round(1)}#{MICROLITERS}" } end } } show do title "Centrifuge Plate(s)" separator note "Use the large centrifuge with the the plate rotor" check "Spin plate(s) at <b>500 x g</b> for <b>1 min</b> to collect everything into the well." end end end #Class
true
36c02a112f3c9408455458dbce25c4c33f317c90
Ruby
Mew-Traveler/mew-api
/lib/airbnb_api.rb
UTF-8
659
2.609375
3
[]
no_license
require 'http' module Airbnb # Service for all Airbnb API calls class AirbnbApi #Setting the URL and parameters Airbnb_URL = 'https://api.airbnb.com/' API_VER = 'v2' Airbnb_API_URL = URI.join(Airbnb_URL, "#{API_VER}/") Search_URL = URI.join(Airbnb_API_URL, "search_results") # attr_reader :airbnb_data def initialize(airbnb_id:) @airbnb_id = airbnb_id end def rooms_info(location) rooms_response = HTTP.get(Search_URL, params: { client_id: @airbnb_id, location: location }) roomsinfo = JSON.load(rooms_response.to_s)['search_results'] end end end
true