{ // 获取包含Hugging Face文本的span元素 const spans = link.querySelectorAll('span.whitespace-nowrap, span.hidden.whitespace-nowrap'); spans.forEach(span => { if (span.textContent && span.textContent.trim().match(/Hugging\s*Face/i)) { span.textContent = 'AI快站'; } }); }); // 替换logo图片的alt属性 document.querySelectorAll('img[alt*="Hugging"], img[alt*="Face"]').forEach(img => { if (img.alt.match(/Hugging\s*Face/i)) { img.alt = 'AI快站 logo'; } }); } // 替换导航栏中的链接 function replaceNavigationLinks() { // 已替换标记,防止重复运行 if (window._navLinksReplaced) { return; } // 已经替换过的链接集合,防止重复替换 const replacedLinks = new Set(); // 只在导航栏区域查找和替换链接 const headerArea = document.querySelector('header') || document.querySelector('nav'); if (!headerArea) { return; } // 在导航区域内查找链接 const navLinks = headerArea.querySelectorAll('a'); navLinks.forEach(link => { // 如果已经替换过,跳过 if (replacedLinks.has(link)) return; const linkText = link.textContent.trim(); const linkHref = link.getAttribute('href') || ''; // 替换Spaces链接 - 仅替换一次 if ( (linkHref.includes('/spaces') || linkHref === '/spaces' || linkText === 'Spaces' || linkText.match(/^s*Spacess*$/i)) && linkText !== 'OCR模型免费转Markdown' && linkText !== 'OCR模型免费转Markdown' ) { link.textContent = 'OCR模型免费转Markdown'; link.href = 'https://fast360.xyz'; link.setAttribute('target', '_blank'); link.setAttribute('rel', 'noopener noreferrer'); replacedLinks.add(link); } // 删除Posts链接 else if ( (linkHref.includes('/posts') || linkHref === '/posts' || linkText === 'Posts' || linkText.match(/^s*Postss*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } // 替换Docs链接 - 仅替换一次 else if ( (linkHref.includes('/docs') || linkHref === '/docs' || linkText === 'Docs' || linkText.match(/^s*Docss*$/i)) && linkText !== '模型下载攻略' ) { link.textContent = '模型下载攻略'; link.href = '/'; replacedLinks.add(link); } // 删除Enterprise链接 else if ( (linkHref.includes('/enterprise') || linkHref === '/enterprise' || linkText === 'Enterprise' || linkText.match(/^s*Enterprises*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } }); // 查找可能嵌套的Spaces和Posts文本 const textNodes = []; function findTextNodes(element) { if (element.nodeType === Node.TEXT_NODE) { const text = element.textContent.trim(); if (text === 'Spaces' || text === 'Posts' || text === 'Enterprise') { textNodes.push(element); } } else { for (const child of element.childNodes) { findTextNodes(child); } } } // 只在导航区域内查找文本节点 findTextNodes(headerArea); // 替换找到的文本节点 textNodes.forEach(node => { const text = node.textContent.trim(); if (text === 'Spaces') { node.textContent = node.textContent.replace(/Spaces/g, 'OCR模型免费转Markdown'); } else if (text === 'Posts') { // 删除Posts文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } else if (text === 'Enterprise') { // 删除Enterprise文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } }); // 标记已替换完成 window._navLinksReplaced = true; } // 替换代码区域中的域名 function replaceCodeDomains() { // 特别处理span.hljs-string和span.njs-string元素 document.querySelectorAll('span.hljs-string, span.njs-string, span[class*="hljs-string"], span[class*="njs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换hljs-string类的span中的域名(移除多余的转义符号) document.querySelectorAll('span.hljs-string, span[class*="hljs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换pre和code标签中包含git clone命令的域名 document.querySelectorAll('pre, code').forEach(element => { if (element.textContent && element.textContent.includes('git clone')) { const text = element.innerHTML; if (text.includes('huggingface.co')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 处理特定的命令行示例 document.querySelectorAll('pre, code').forEach(element => { const text = element.innerHTML; if (text.includes('huggingface.co')) { // 针对git clone命令的专门处理 if (text.includes('git clone') || text.includes('GIT_LFS_SKIP_SMUDGE=1')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 特别处理模型下载页面上的代码片段 document.querySelectorAll('.flex.border-t, .svelte_hydrator, .inline-block').forEach(container => { const content = container.innerHTML; if (content && content.includes('huggingface.co')) { container.innerHTML = content.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 特别处理模型仓库克隆对话框中的代码片段 try { // 查找包含"Clone this model repository"标题的对话框 const cloneDialog = document.querySelector('.svelte_hydration_boundary, [data-target="MainHeader"]'); if (cloneDialog) { // 查找对话框中所有的代码片段和命令示例 const codeElements = cloneDialog.querySelectorAll('pre, code, span'); codeElements.forEach(element => { if (element.textContent && element.textContent.includes('huggingface.co')) { if (element.innerHTML.includes('huggingface.co')) { element.innerHTML = element.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { element.textContent = element.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); } // 更精确地定位克隆命令中的域名 document.querySelectorAll('[data-target]').forEach(container => { const codeBlocks = container.querySelectorAll('pre, code, span.hljs-string'); codeBlocks.forEach(block => { if (block.textContent && block.textContent.includes('huggingface.co')) { if (block.innerHTML.includes('huggingface.co')) { block.innerHTML = block.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { block.textContent = block.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); }); } catch (e) { // 错误处理但不打印日志 } } // 当DOM加载完成后执行替换 if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', () => { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); }); } else { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); } // 增加一个MutationObserver来处理可能的动态元素加载 const observer = new MutationObserver(mutations => { // 检查是否导航区域有变化 const hasNavChanges = mutations.some(mutation => { // 检查是否存在header或nav元素变化 return Array.from(mutation.addedNodes).some(node => { if (node.nodeType === Node.ELEMENT_NODE) { // 检查是否是导航元素或其子元素 if (node.tagName === 'HEADER' || node.tagName === 'NAV' || node.querySelector('header, nav')) { return true; } // 检查是否在导航元素内部 let parent = node.parentElement; while (parent) { if (parent.tagName === 'HEADER' || parent.tagName === 'NAV') { return true; } parent = parent.parentElement; } } return false; }); }); // 只在导航区域有变化时执行替换 if (hasNavChanges) { // 重置替换状态,允许再次替换 window._navLinksReplaced = false; replaceHeaderBranding(); replaceNavigationLinks(); } }); // 开始观察document.body的变化,包括子节点 if (document.body) { observer.observe(document.body, { childList: true, subtree: true }); } else { document.addEventListener('DOMContentLoaded', () => { observer.observe(document.body, { childList: true, subtree: true }); }); } })(); \n\nEOF\n\nOPTIONS = []\nfonts = Hash.new\nmodename = \"All Installed\"\noptionname = []\noutfile = nil\n\nargv = []\nARGV.each do |i|\n if i =~ /^-/\n $'.scan(/(.)/) {|c| argv.push(\"-\" + $1) }\n else\n argv.push i\n end\nend\n\np argv\n\nwhile arg = argv.shift\n break if arg == \"--\"\n case arg.strip\n when \"-d\"\n OPTIONS.push :list_dual\n when \"-m\"\n OPTIONS.push :list_mono\n when \"-j\"\n OPTIONS.push :req_kana\n optionname |= [\"かな必須\"]\n when \"-H\"\n OPTIONS.push :req_hani\n optionname |= [\"漢字必須\"]\n when \"-o\"\n outfile = argv.shift\n when \"-h\"\n STDERR.puts \"Usage:\"\n STDERR.puts \" installed-font-list-html.rb [-m|-d] [-H] [-j] [-o outfile]\"\n end\nend\n\nif outfile\n STDOUT.reopen(File.open(outfile, \"w\"))\nend\n\nSTDERR.puts \"building list..........\"\n\nfontlist = nil\n\nif((OPTIONS & [:list_dual, :list_mono]).length > 1)\n STDERR.puts \"-d, -m options are able to turn on only one of them.\"\n exit 1\nend\n\nif OPTIONS.include?(:list_mono)\n modename = \"Monospace\"\n IO.popen([\"fc-list\", \":mono\", \":\", \"family\", \"fullname\", \"spacing\", \"capability\"], \"r\") do |io|\n fontlist = io.each.map {|i| i.split(\":\", 2)}\n end\nelsif OPTIONS.include?(:list_dual)\n modename = \"Monospace + Dualspace\"\n IO.popen([\"fc-list\", \":dual\", \":\", \"family\", \"fullname\", \"spacing\", \"capability\"], \"r\") do |io|\n fontlist = io.each.to_a\n end\n IO.popen([\"fc-list\", \":mono\", \":\", \"family\", \"fullname\", \"spacing\", \"capability\"], \"r\") do |io|\n fontlist |= io.each.to_a\n end\n fontlist = fontlist.map {|i| i.split(\":\", 2)}\nelse\n IO.popen([\"fc-list\", \":\", \"family\", \"fullname\", \"spacing\", \"capability\"], \"r\") do |io|\n fontlist = io.each.map {|i| i.split(\":\", 2)}\n end\nend\n\nfontlist.each do |fl|\n infoline = {fullname: nil, kana: false, hani: false, monospace: false}\n family = fl[0].split(\",\")\n capability = \"\"\n fullname = \"\"\n\n\n if fl[1] =~ /\\bfullname=(.*?)(?::|$)/\n infoline[:fullname] = $1.gsub('\\\\', '')\n end\n\n if fl[1] =~ /\\bspacing=(.*?)\\b/\n spacing = $1\n unless(spacing == \"0\" || spacing.casecmp?(\"proportional\"))\n infoline[:monospace] = true\n end\n infoline[:spacing] = spacing\n end\n\n if fl[1] =~ /\\bcapability=(.*)$/\n capability = $1.gsub('\\\\', '')\n end\n\n infoline[:kana] = true if capability.include?(\"otlayout:kana\")\n infoline[:hani] = true if capability.include?(\"otlayout:hani\")\n\n next if OPTIONS.include?(:req_kana) && ! infoline[:kana]\n next if OPTIONS.include?(:req_hani) && ! infoline[:hani]\n\n family.each do |i|\n fonts[i.gsub('\\\\', '')] = infoline\n end\n\n STDERR.puts(infoline[:fullname] || family.first)\nend\n\nSTDERR.puts \"Generating HTML...............\"\n\nERB.new(ERB_TEMPLATE).run(binding)\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975435,"cells":{"blob_id":{"kind":"string","value":"08533550ada040ba7229c175d6dab15e3f6e606e"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"tylergreason/pokemon_backend"},"path":{"kind":"string","value":"/db/seeds.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2538,"string":"2,538"},"score":{"kind":"number","value":3.015625,"string":"3.015625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"require 'faker'\n# Pokemon.delete_all\nUser.delete_all\nTeam.delete_all \n\n\n# reset all pokemon types \n\n\n# natures \n# only seed natures if Nature.all is empty \nif Nature.all.count == 0 \n natures = PokeApi.get(:nature).results\n natures.each do |nature| \n name = nature.name\n Nature.find_or_create_by(name:name) \n end\nend\n\n# types \n# only seed types if Type.all is empty \nif Type.all.count == 0 \n types = PokeApi.get(:type).results\n types.each do |type| \n name = type.name \n Type.find_or_create_by(name:name)\n end\nend\n\n700.times do |time|\n pokemon_number = time+1\n \n if Pokemon.find_by(number: pokemon_number) == nil\n\n fetch_pokemon = PokeApi.get(pokemon: pokemon_number)\n name = fetch_pokemon.name.capitalize\n number = fetch_pokemon.id\n image_url = fetch_pokemon.sprites.front_default\n new_pokemon = Pokemon.find_or_create_by(name:name,number:number,image_url:image_url)\n # nature \n new_pokemon.natures << Nature.all.sample\n # types\n fetch_pokemon.types.each do |type| \n new_pokemon.types << Type.find_or_create_by(name: type.type.name)\n end\n # abilities\n abilities = fetch_pokemon.abilities\n abilities.each do |result| \n new_ability = Ability.find_or_create_by(name:result.ability.name)\n new_pokemon.abilities << new_ability\n end\n # moves \n moves = fetch_pokemon.moves \n moves.each do |result| \n new_move = Move.find_or_create_by(name: result.move.name)\n new_pokemon.moves << new_move\n end\n end\nend\n\n# user \nnew_user = User.create(email:'test@mail.com', password:'test')\n\n# create a new team, then give that team to the test user \n4.times do \n new_team = Team.create(name: Faker::Team.name, description: \"Desc: \" + Faker::Lorem.sentence(word_count: 3), user_id: User.all.sample.id)\n 3.times do \n random_pokemon = Pokemon.all.sample \n if !new_team.pokemons.include?(random_pokemon)\n new_team.pokemons << Pokemon.all.sample\n end\n end\n new_user.teams << new_team\nend\n\n# make 4 of each pokemon's moves active \nPokemon.all.each do |pokemon| \n # make each move not active \n PokemonMove.where(pokemon_id: pokemon.id, active:true).each {|pokemonMove|\n pokemonMove.active = false \n pokemonMove.save \n }\n 4.times do |time| \n if pokemon.moves[time] != nil\n pokemon.set_move_active(pokemon.moves[time])\n end\n end\nend"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975436,"cells":{"blob_id":{"kind":"string","value":"16aced0ae01cf9e539877ead3d81dee6ea12bff2"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"kupolak/codewars"},"path":{"kind":"string","value":"/Ruby/7 KYU/Nickname Generator.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":159,"string":"159"},"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":"def nickname_generator(name)\n if name.length >= 4\n /\\A[auieoAUIEO]\\z/.match(name[2]) ? name[0..3] : name[0..2]\n else\n \"Error: Name too short\"\n end\nend"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975437,"cells":{"blob_id":{"kind":"string","value":"2b22f4f2eb68a8a6afef82f95624fca7970fa364"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"reneeknox/prime-ruby-online-web-pt-071519"},"path":{"kind":"string","value":"/prime.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":483,"string":"483"},"score":{"kind":"number","value":3.734375,"string":"3.734375"},"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":"def prime?(integer) # 11\n if integer < 2\n false\n else\n a = (2..integer - 1).to_a\n \n # [3,4,5,6,7,8,9]\n # a = [3,4,5,6,7,8,9,10]\n \n # integer % n == 0 is prime\n # [].none? # None of the numbers prior to integer are divisible by integer\n\n # Madeline told me this is a good idea to include; I read that it passes each element of the collection to the block. \n \n # This helps us iterate over the range.\n \n a.none?{|n| integer % n == 0 } #true\n \n \n end\nend"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975438,"cells":{"blob_id":{"kind":"string","value":"89826b68188ab75e503c6a7caabeaa8dd4d3a6c1"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"Artforge/has_many_translations"},"path":{"kind":"string","value":"/lib/has_many_translations/control.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1805,"string":"1,805"},"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":"module HasManyTranslations\n \n module Control\n \n def self.included(base) # :nodoc:\n base.class_eval do\n include InstanceMethods\n # alias_method_chain :create_translation?, :control\n # alias_method_chain :update_translation?, :control\n end\n end\n \n module InstanceMethods\n def force_update\n with_translation_flag(:force_update) do\n yield if block_given?\n save\n end\n end\n def force_update!\n with_translation_flag(:force_update) do\n yield if block_given?\n update_translations!\n end\n end\n \n def force_update?\n !!@force_update\n end\n \n def skip_translation\n with_translation_flag(:skip_translation) do\n yield if block_given?\n save\n end\n end\n \n def skip_translation!\n with_translation_flag(:skip_translation) do\n yield if block_given?\n save!\n end\n end\n \n def skip_translation?\n !!@skip_translation\n end\n \n private\n # Used for each control block, the +with_version_flag+ method sets a given variable to\n # true and then executes the given block, ensuring that the variable is returned to a nil\n # value before returning. This is useful to be certain that one of the control flag\n # instance variables isn't inadvertently left in the \"on\" position by execution within the\n # block raising an exception.\n def with_translation_flag(flag)\n begin\n instance_variable_set(\"@#{flag}\", !instance_variable_get(\"@#{flag}\"))\n yield\n # ensure\n # instance_variable_set(\"@#{flag}\", nil)\n end\n end\n \n end\n end\nend"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975439,"cells":{"blob_id":{"kind":"string","value":"5c6141454f1e0349a5bb009539c44248fa73c788"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"shoehead0125/crawler-study"},"path":{"kind":"string","value":"/chapter-1/sbcr-sample/sbcr1.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":491,"string":"491"},"score":{"kind":"number","value":2.9375,"string":"2.9375"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"#! /usr/bin/env ruby\n# -*- coding: utf-8 -*-\n\nrequire 'pry'\nrequire 'cgi'\n\ndef parse(page_source)\n dates = page_source.scan(\n %r!(\\d+)年 ?(\\d+)月 ?(\\d+)日
!)\n url_titles = page_source.scan(\n %r!^(.+?)
!)\n url_titles.zip(dates).map { |(aurl, atitle), ymd|\n [\n CGI.unescapeHTML(aurl),\n CGI.unescapeHTML(atitle),\n # splat 可変長引数\n Time.local(*ymd),\n ]\n }\nend\n\nx = parse(open('samplepage.html', &:read))\nputs x[0, 2]\n\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975440,"cells":{"blob_id":{"kind":"string","value":"ead40f498e599c58f6d5d9380e3b0c201f70a7e8"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"mvz/ripper_ruby_parser"},"path":{"kind":"string","value":"/test/samples/loops.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":378,"string":"378"},"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":"# Loop samples\n\ndef for_samples\n for foo in bar\n end\n\n for foo, bar in baz\n end\n\n for foo, in bar\n end\nend\n\n# begin..end in conditions\n#\ndef while_until_samples\n while begin foo end\n bar\n end\n\n until begin foo end\n bar\n end\n\n while begin foo end do\n bar\n end\n\n until begin foo end do\n bar\n end\n\n foo while begin bar end\n\n foo until begin bar end\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975441,"cells":{"blob_id":{"kind":"string","value":"acbb70446386aad295f8f93d882f70d221e3d874"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"dafoxia/mumble-ruby"},"path":{"kind":"string","value":"/lib/mumble-ruby/packet_data_stream.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":3408,"string":"3,408"},"score":{"kind":"number","value":3.171875,"string":"3.171875"},"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 Mumble\n class PacketDataStream\n def initialize(data=nil)\n @data = data || 0.chr * 8192\n @data = @data.split ''\n @pos = 0\n @ok = true\n @capacity = @data.size\n end\n\n def valid\n @ok\n end\n\n def size\n @pos\n end\n\n def left\n @capacity - @pos\n end\n\n def append(val)\n if @pos < @capacity\n @data[@pos] = val.chr\n skip\n else\n @ok = false\n end\n end\n\n def append_block(data)\n len = data.size\n if len < left\n @data[@pos, len] = data.split('')\n skip len\n else\n @ok = false\n end\n end\n\n def get_block(len)\n if len < left\n ret = @data[@pos, len]\n skip len\n else\n @ok = false\n ret = []\n end\n ret\n end\n\n def get_next\n if @pos < @capacity\n ret = @data[@pos].ord\n skip\n else\n ret = 0\n @ok = false\n end\n ret\n end\n\n def rewind\n @pos = 0\n end\n\n def skip(len=1)\n len < left ? @pos += len : @ok = false\n end\n\n def put_int(int)\n if !(int & 0x8000000000000000).zero? && (~int < 0x100000000)\n int = ~int\n puts int\n if int <= 0x3\n # Shortcase for -1 to -4\n append(0xFC | int)\n else\n append(0xF8)\n end\n end\n\n if int < 0x80\n # Need top bit clear\n append(int)\n elsif int < 0x4000\n # Need top two bits clear\n append((int >> 8) | 0x80)\n append(int & 0xFF)\n elsif int < 0x200000\n # Need top three bits clear\n append((int >> 16) | 0xC0)\n append((int >> 8) & 0xFF)\n append(int & 0xFF)\n elsif int < 0x10000000\n # Need top four bits clear\n append((int >> 24) | 0xE0)\n append((int >> 16) & 0xFF)\n append((int >> 8) & 0xFF)\n append(int & 0xFF)\n elsif int < 0x100000000\n # It's a full 32-bit integer.\n append(0xF0)\n append((int >> 24) & 0xFF)\n append((int >> 16) & 0xFF)\n append((int >> 8) & 0xFF)\n append(int & 0xFF)\n else\n # It's a 64-bit value.\n append(0xF4)\n append((int >> 56) & 0xFF)\n append((int >> 48) & 0xFF)\n append((int >> 40) & 0xFF)\n append((int >> 32) & 0xFF)\n append((int >> 24) & 0xFF)\n append((int >> 16) & 0xFF)\n append((int >> 8) & 0xFF)\n append(int & 0xFF)\n end\n end\n\n def get_int\n v = get_next\n int = 0\n\n if (v & 0x80) == 0x00\n int = v & 0x7F\n elsif (v & 0xC0) == 0x80\n int = (v & 0x3F) << 8 | get_next\n elsif (v & 0xF0) == 0xF0\n x = v & 0xFC\n if x == 0xF0\n int = get_next << 24 | get_next << 16 | get_next << 8 | get_next\n elsif x == 0xF4\n int = get_next << 56 | get_next << 48 | get_next << 40 | get_next << 32 |\n get_next << 24 | get_next << 16 | get_next << 8 | get_next\n elsif x == 0xF8\n int = get_int\n int = ~int\n elsif x == 0xFC\n int = v & 0x03\n int = ~int\n else\n @ok = false\n int = 0\n end\n elsif (v & 0xF0) == 0xE0\n int = (v & 0x0F) << 24 | get_next << 16 | get_next << 8 | get_next\n elsif (v & 0xE0) == 0xC0\n int = (v & 0x1F) << 16 | get_next << 8 | get_next\n end\n\n return int\n end\n end\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975442,"cells":{"blob_id":{"kind":"string","value":"b6c04964c0a96fdf8abc3f0bd92bdd09af4c35f9"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"kunks001/boris_bikes"},"path":{"kind":"string","value":"/boris_bikes.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":278,"string":"278"},"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":"# class Person\n\n# def initialize(name) \n# @name = name \n# @bike = 0 \n# end \n \n# def name \n# @name\n# end\n\n# def id\n# end\n\n# def bike\n# @bike\n# end\n\n# def gets_bike\n# @bike +=1\n# end\n\n# def returns_bike\n# @bike -=1\n# end\n# end"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975443,"cells":{"blob_id":{"kind":"string","value":"c0d3c4b9f2fe9690ecffa5651868569e774919a8"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"skunath/STAT"},"path":{"kind":"string","value":"/phoneme.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":6887,"string":"6,887"},"score":{"kind":"number","value":2.9375,"string":"2.9375"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"class Phoneme\n\n\n def initialize(args)\n @cskip = -10.0\n @csub = 35.0\n @cexp = 45.0\n @cvowel = 10.0\n @epsilon = 0.0\n\n @character = args[:character]\n @type = args[:type] # vowel, consonant, diacritic\n\n @manner = args[:manner]\n @place = args[:place]\n\n @high = args[:high]\n @back = args[:back]\n @round = args[:round]\n @long = args[:long]\n\n @syllabic = args[:syllabic]\n @nasal = args[:nasal]\n @retroflex = args[:retroflex]\n @voice = args[:voice]\n @lateral = args[:lateral]\n @aspirated = args[:aspirated]\n\n #\n #\n\n @features = {}\n @features[:manner] = args[:manner]\n @features[:place] = args[:place]\n\n @features[:high] = args[:high]\n @features[:back] = args[:back]\n @features[:round] = args[:round]\n @features[:long] = args[:long]\n\n @features[:syllabic] = args[:syllabic]\n @features[:nasal] = args[:nasal]\n @features[:retroflex] = args[:retroflex]\n @features[:voice] = args[:voice]\n @features[:lateral] = args[:lateral]\n @features[:aspirated] = args[:aspirated]\n\n\n end\n\n def character()\n return @character\n end\n\n def vowel()\n return @type == \"vowel\"\n end\n\n def vowel_cost()\n return @cvowel\n end\n\n def alter_feature(name, value)\n if !@features[name].nil?\n if @features[name].class == String\n @features[name] = value\n else\n @features[name] = @features[name] + value\n end\n else\n @features[name] = value\n end\n end\n\n def combine_features(phoneme_2)\n for feature in phoneme_2.features\n self.alter_feature(feature[0], feature[1])\n end\n end\n\n #@vowel a single vowel object\n #@pasofalkjf alksfja lskfja sf\n def self.vowel(vowel)\n # Runs a subprocess and applies handlers for stdout and stderr\n # Params:\n # +vowel+:: command line string to be executed by the system\n if vowel.vowel()\n return @cvowel\n end\n return 0.0\n end\n\n def to_s\n @character\n end\n\n def set_character(full_character)\n @character = full_character\n end\n\n def consonant()\n return @type == \"consonant\"\n end\n\n def sound_type()\n return @type\n end\n\n def round()\n return @round\n end\n\n def long()\n return @long\n end\n\n def manner()\n return Manner[@manner]\n end\n\n def high()\n return High[@high].to_f\n end\n\n def back()\n return Back[@back]\n end\n\n def place()\n return Place[@place]\n end\n\n def syllabic()\n return @syllabic\n end\n\n def nasal()\n return @nasal\n end\n\n def retroflex\n return @retroflex\n end\n\n def voice\n return @voice\n end\n\n def lateral\n return @lateral\n end\n\n def aspirated\n return @aspirated\n end\n\n def features\n features = []\n for pair in @features.to_a\n features << pair if !pair[1].nil?\n end\n\n return features\n end\n\n\n\n def vowel_compare(compare_vowel)\n diff = 0.0\n\n # roundness comparison\n roundness_diff = (self.round() - compare_vowel.round()).to_f.abs * Salience[\"round\"]\n # length comparison\n length_diff = (self.long() - compare_vowel.long()).to_f.abs * Salience[\"long\"]\n # backness comparison\n backness_diff = (self.back() - compare_vowel.back()).to_f.abs * Salience[\"back\"]\n # height comparison\n height_diff = (self.high() - compare_vowel.high()).to_f.abs * Salience[\"high\"]\n # manner comparison\n manner_diff = (self.manner() - compare_vowel.manner()).to_f.abs * Salience[\"manner\"]\n\n diff = diff + roundness_diff + length_diff + backness_diff + height_diff + manner_diff\n\n return diff.round(5);\n end\n\n def consonant_compare(compare_consonant)\n diff = 0.0\n\n # manner comparison\n manner_diff = (self.manner() - compare_consonant.manner()).to_f.abs * Salience[\"manner\"]\n\n # place comparison\n place_diff = (self.place() - compare_consonant.place()).to_f.abs * Salience[\"place\"]\n\n # syllabic comparison\n syllabic_diff = (self.syllabic() - compare_consonant.syllabic()).to_f.abs * Salience[\"syllabic\"]\n\n # nasal comparison\n nasal_diff = (self.nasal() - compare_consonant.nasal()).to_f.abs * Salience[\"nasal\"]\n\n # retroflex comparison\n retroflex_diff = (self.retroflex() - compare_consonant.retroflex()).to_f.abs * Salience[\"retroflex\"]\n\n # voice comparison\n voice_diff = (self.voice() - compare_consonant.voice()).to_f.abs * Salience[\"voice\"]\n\n # lateral comparison\n lateral_diff = (self.lateral() - compare_consonant.lateral()).to_f.abs * Salience[\"lateral\"]\n\n # aspirated comparison\n aspirated_diff = (self.aspirated() - compare_consonant.aspirated()).to_f.abs * Salience[\"aspirated\"]\n\n diff = manner_diff + place_diff + syllabic_diff + nasal_diff + retroflex_diff + voice_diff + lateral_diff + aspirated_diff\n\n return diff.round(5)\n end\n\n def mixed_compare(other_phoneme)\n vowel, consonant = nil\n\n if self.vowel()\n vowel = self\n consonant = other_phoneme\n else\n vowel = other_phoneme\n consonant = self\n end\n\n # begin computing diff\n diff = 0.0\n\n # syllabic comparison\n #syllabic_diff = (consonant.syllabic() - vowel.syllabic()).to_f.abs * Salience[\"syllabic\"]\n\n # nasal comparison\n #nasal_diff = (consonant.nasal() - vowel.nasal()).to_f.abs * Salience[\"nasal\"]\n\n # retroflex comparison\n #retroflex_diff = (consonant.retroflex() - vowel.retroflex()).to_f.abs * Salience[\"retroflex\"]\n\n # manner comparison\n manner_diff = (consonant.manner() - vowel.manner()).to_f.abs * Salience[\"manner\"]\n\n # place comparison\n place_diff = (consonant.place() - 0.0).to_f.abs * Salience[\"place\"]\n\n # voice comparison\n voice_diff = (consonant.voice() - 0.0).to_f.abs * Salience[\"voice\"]\n\n # lateral comparison\n lateral_diff = (consonant.lateral() - 0.0).to_f.abs * Salience[\"lateral\"]\n\n # aspirated comparison\n aspirated_diff = (consonant.aspirated() - 0.0).to_f.abs * Salience[\"aspirated\"]\n\n diff = manner_diff + place_diff + voice_diff + lateral_diff + aspirated_diff\n\n return diff.round(5)\n end\n\n def self.total_diff(phoneme_1, phoneme_2)\n # must be two phonemes coming in... alphabets will be different\n\n # This function determines the actual difference between two characters/phonemes\n # based on the features it knows of of the character/phoneme.\n\n # Notes:\n # This should probably create an on the fly hash when the class is instantiated to memoize\n # previous diff calculations...It should speed things up.\n\n first_string_vowel = phoneme_1.vowel()\n second_string_vowel = phoneme_2.vowel()\n\n\n if !first_string_vowel && !second_string_vowel\n # case where both characters/phonemes are consonants\n return phoneme_1.consonant_compare(phoneme_2)\n elsif first_string_vowel && second_string_vowel\n # case where only vowels are passed\n return phoneme_1.vowel_compare(phoneme_2)\n else\n # Mixed case with a vowel and a consonant\n return phoneme_1.mixed_compare(phoneme_2)\n end\n end\n\nend\n\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975444,"cells":{"blob_id":{"kind":"string","value":"b076f8978f2f51233968c40cafb911da7ea22421"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"sujankh/SimPlParser"},"path":{"kind":"string","value":"/simplparser.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":655,"string":"655"},"score":{"kind":"number","value":3.1875,"string":"3.1875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"#!/usr/bin/ruby\n\nrequire_relative './lexer'\nrequire_relative './parser'\n\ndef getTokenKind()\n $tokenizer.getTokenKind()\nend\n\ndef getTokenText()\n $tokenizer.getTokenText()\nend\n\n#consume token\ndef nextToken()\n $tokenizer.nextToken()\nend\n\ndef parseProgram()\n inputFile = ARGV[0]\n \n begin \n $tokenizer.readFile(inputFile)\n nextToken() #initialize the lexer to put the cursor to current token\n \n parseStatements()\n\n nextToken() #consume EOF\n puts \"End Of File\"\n puts \"Successful parse.\"\n rescue ParseError => e\n puts \"Syntax error:\"\n puts e.message\n end\nend\n\n#start parser program\n$tokenizer = Tokenizer.new\nparseProgram()\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975445,"cells":{"blob_id":{"kind":"string","value":"cfe0c4cb1d8f7b017e7b337507fa9a30f4e7a645"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"DavidPAdams/nlr"},"path":{"kind":"string","value":"/Lesson_1_hw/calculator.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":148,"string":"148"},"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":"\n\tdef add(a,b)\n\t\ta + b\n\tend\n\n\tdef subtract(c,d)\n\t\tc - d\n\tend\n\n\tdef multiply2(e,f)\n\t\te * f\n\tend\n\n\tdef divide2(g,h)\n\t\th != 0 ? g/h : \"undefined\"\n\tend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975446,"cells":{"blob_id":{"kind":"string","value":"435e0a014017addf59e0d5837188a3436b5a6bd5"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"dbirtwell/RubyLearning_32"},"path":{"kind":"string","value":"/Week_7/rubyprograms/lesson7exercise3.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1509,"string":"1,509"},"score":{"kind":"number","value":4.65625,"string":"4.65625"},"int_score":{"kind":"number","value":5,"string":"5"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"# lesson7exercise3.rb\n# David Birtwell\n=begin\n\n Week 7 Exercise 3. \n \n Write a method called month_days, that determines the number of days in a \n month. Usage:\n\n days = month_days(5) # 31 (May)\n\n days = month_days(2, 2000) # 29 (February 2000)\n\n Remember, you could use the Date class here. Read the online documentation \n for the Date class. You must account for leap years in this exercise. \n \n=end\n\nrequire 'date'\n\n# Default the year to current year if not passed in\ndef month_days(month_num, year=Time.now.year)\n\n # Steps:\n # 1) Set the date to the 1st day of the next month for which we want to\n # count the number of days.\n # 2) Roll back a day, which takes us to the end of the month\n # 3) Return that day of the mmonht (end of month day == number of days in\n # the month\n #\n # The code snipprt below shifts/increments the month of the date 1 month.\n # date >> 1\n # \n # The below snippet subtracts one day from the date. In our case, this rolls\n # back the date to the previous day (subtracts one day). \n # Note - This automativcally handes leap year.\n # date - 1\n #\n # returns the day of the date\n # date.day\n ((Date.new(year, month_num, 1) >> 1) - 1).day \nend\n \ndays = month_days(5) # 31 (May)\nputs \"Days: #{days}\"\n\ndays = month_days(2, 2000) # 29 (February 2000)\nputs \"Days: #{days}\"\n\ndays = month_days(6) # 30 (June)\nputs \"Days: #{days}\"\n\ndays = month_days(12) # 31 (December)\nputs \"Days: #{days}\"\n\ndays = month_days(1, 2008) # 1 (January 2008)\nputs \"Days: #{days}\"\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975447,"cells":{"blob_id":{"kind":"string","value":"b01cbb60fbaea909777bd1791b0921f794220ee2"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"ruben/smalltalk-best-practice-patterns"},"path":{"kind":"string","value":"/3-behaviour/2-messages/3-intention_revealing_message/1-paragraph_editor.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":372,"string":"372"},"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":"# How do you communicate your intent when the implementation is simple?\n#\n# Send a message to “self.” Name the message so it communicates what is to be done rather than how it is to be done.\n# Code a simple method for the message.\n\n# We highlight a rectangle (WHAT) by reversing it (HOW)\nclass ParagraphEditor\n def highlight rectangle\n reverse rectangle\n end\nend"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975448,"cells":{"blob_id":{"kind":"string","value":"2b9dfea91af9ec88509bd6b28c4b25310574dbfa"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"avescodes/botfly"},"path":{"kind":"string","value":"/lib/botfly/callback_context.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1629,"string":"1,629"},"score":{"kind":"number","value":2.765625,"string":"2.765625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT","LicenseRef-scancode-unknown-license-reference"],"string":"[\n \"MIT\",\n \"LicenseRef-scancode-unknown-license-reference\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"module Botfly\n class CallbackContext\n def initialize(caller, params)\n setup_params(params)\n @caller = caller\n end\n def method_missing(name, *args)\n @caller.send(name,*args) if name.to_s.scan(/^setup/).empty?\n end\n private\n # OK, so. Get the instance's eigenclass, then, call the private method define_method - thus created the method called #{name} that returns value. Basically attr_reader but for any generic variable.\n def expose(name, value)\n (class< 0\n# end\n# p flintstones_hash\n\n# puts \"the value of 40 + 2 is \" + \"#{(40 + 2)}\"\n\n# def titleize word\n# split_apart = word.split(//)\n# upper_cased = []\n# split_apart.each do |letter| \n# upper_cased << letter.upcase\n# end\n# final = upper_cased.join\n# puts final\n# end\n\n# titleize(\"Now is the time for all good men to come to the aid of their party!\")\n\nmunsters = {\n \"Herman\" => { \"age\" => 32, \"gender\" => \"male\" },\n \"Lily\" => { \"age\" => 30, \"gender\" => \"female\" },\n \"Grandpa\" => { \"age\" => 402, \"gender\" => \"male\" },\n \"Eddie\" => { \"age\" => 10, \"gender\" => \"male\" },\n \"Marilyn\" => { \"age\" => 23, \"gender\" => \"female\"}\n}\n\n# \"age_group\" => \"adult\"\n# munsters[key_counter].merge!({:\"age_group\" => \"adult\"})\n\n# key[counter] == [['new_key' => 'new_value']]\n\n# need to use map\n# loop\n# def sort_munsters(age)\n# case age\n# when age == 0..17 then \"kid\"\n# when age == 17..65 then \"adult\"\n# when age > 65 then \"senior\" \n# else \n# false\n# end\n# age\n# end\n# # now add to the munsters hash\n\n# munsters.each+ do |key, value|\n# sort_munsters(value:(\"age\", =>))\n# key[:key] << value.merge!([-1, \"age_group\" => \"age\"])\n# end\n\n# the REAL answer\n\nmunsters.each do |name, details|\n case details[\"age\"]\n when 0...18\n details[\"age_group\"] = \"kid\"\n when 18...65\n details[\"age_group\"] = \"adult\"\n else\n details[\"age_group\"] = \"senior\"\n end\nend\np munsters"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975454,"cells":{"blob_id":{"kind":"string","value":"fa59bf57da8f5a0febc23ea56fc64b089091c658"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"DanielVartanov/isp-logs-parser"},"path":{"kind":"string","value":"/lib/traffic_splitter.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":380,"string":"380"},"score":{"kind":"number","value":2.84375,"string":"2.84375"},"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":"class TrafficSplitter\n def self.split_traffic!(traffic)\n hosts = traffic.daily.internal.highest_twenty_hosts +\n traffic.nightly.internal.highest_twenty_hosts +\n traffic.daily.world.highest_twenty_hosts +\n traffic.nightly.world.highest_twenty_hosts\n\n hosts.sort! { |left, right| right.amount_of_traffic <=> left.amount_of_traffic }\n\n hosts[0..19]\n end\nend"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975455,"cells":{"blob_id":{"kind":"string","value":"ba8f9b57f2d9dc4e3e1d90ede3382b3029aadce0"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"slbug/test_img"},"path":{"kind":"string","value":"/app/models/image.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":439,"string":"439"},"score":{"kind":"number","value":2.546875,"string":"2.546875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"class Image < ActiveRecord::Base\n validates :title, :presence => true, :length => { :minimum => 3 }\n validates :url, :presence => true, :length => { :minimum => 10 }\n\n before_save :ensure_uid\n\n private\n\n def ensure_uid\n if uid.blank?\n allowed_symbols = ('a'..'z').to_a + ('A'..'Z').to_a + (0..9).to_a\n self.uid = (0...5).collect { allowed_symbols[Kernel.rand(allowed_symbols.length)] }.join\n end\n end\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975456,"cells":{"blob_id":{"kind":"string","value":"a154896e0969d98155f169a98c77c8c8131824ea"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"mizuhoiimori/rubybook"},"path":{"kind":"string","value":"/private.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":166,"string":"166"},"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":"class Cafe\n def staff\n makanai\n end\n\n private\n def makanai\n \"店員スペシャルメニュー\"\n end\nend\n\ncafe = Cafe.new\nputs cafe.staff\nputs cafe.makanai"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975457,"cells":{"blob_id":{"kind":"string","value":"b73ce11b5edde4c06e1f2c904e6608b3ef0a827d"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"RichardCharman/takeaway-challenge"},"path":{"kind":"string","value":"/spec/customer_spec.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":799,"string":"799"},"score":{"kind":"number","value":2.734375,"string":"2.734375"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"require 'customer'\ndescribe Customer do\n\n it { expect(subject).to respond_to(:show_menu) }\n\t \n describe '#ordering' do\n it 'should take an order for food with 2 arguments' do\n expect(subject).to respond_to(:order_item).with(2).argument\n end\n\n it { expect(subject).to respond_to(:view_order) }\n \n it 'should display correct order' do\n subject.order_item(\"burger\", 2)\n expect(subject.view_order).to eq [{\"burger\"=>4}, {\"burger\"=>4}]\n end\n \n it 'should give correct price' do\n subject.order_item(\"burger\", 2)\n expect(subject.order_price).to eq (\"The cost for your order is £8.0\")\n end\n \n it 'should raise an error if placing empty order' do\n\t expect{subject.place_order}.to raise_error \"You haven't ordered any food\"\n end\n end \nend "},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975458,"cells":{"blob_id":{"kind":"string","value":"2e09106b0fa5478524f95e5cd61da1987aba2e62"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"biancaguzenski/basic-algorithms-and-data-structures"},"path":{"kind":"string","value":"/Others/is_palindrome.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":617,"string":"617"},"score":{"kind":"number","value":3.53125,"string":"3.53125"},"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 \"test/unit/assertions\"\ninclude Test::Unit::Assertions\n\ndef to_char(string)\n string = string.downcase.chars\n string = string.keep_if {|c| c =~ /[abcdefghijklmnopqrstuvwxyz]/ }.join\n is_palindrome(string)\nend\ndef is_palindrome(string)\n i = string.size-1\n reversed = \"\"\n while i >= 0\n reversed << string[i]\n i -= 1\n end\n reversed == string ? true : false\nend\nassert_equal to_char(\"abba\"), true\nassert_equal to_char(\"abbas\"), false\nassert_equal to_char(\"tattarrattat\"), true\nassert_equal to_char(\"Was it a palindrome?\"), false\nassert_equal to_char(\"No lemon, no melon\"), true"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975459,"cells":{"blob_id":{"kind":"string","value":"7640ea18727d0ca0f1884b9755e7d45b92e9588a"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"sithobog/seo_tool"},"path":{"kind":"string","value":"/lib/seo/user.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1032,"string":"1,032"},"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 'sequel'\nrequire 'bcrypt'\nmodule Seo\n\n class User\n attr_accessor :id\n DB = Sequel.connect(:adapter => 'postgres', :host => 'localhost',\n :database => 'warden_test', :user => 'tester', :password => 'test_password')\n\n def initialize(id, username, password, ip)\n @id = id\n @username = username\n @password = password\n @ip = ip\n create_table\n end\n\n def authenticate(attempted_password)\n if @password == attempted_password\n true\n else\n false\n end\n end\n\n def self.get(id)\n DB.from(:users).where(:id => id).all\n end\n\n def self.get_by_name(name)\n DB.from(:users).where(:username => name).all\n end\n\n def add_user(name,password)\n users = DB.from(:users)\n users.insert.(:username => name, :password => password)\n end\n\n def create_table\n DB.create_table? :users do\n primary_key :id\n String :username\n String :password\n Inet :user_ip\n end\n end\n\n end\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975460,"cells":{"blob_id":{"kind":"string","value":"239a53c5500c6187dc4a0644b3d836edb2aafeb8"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"liyijie/span_report"},"path":{"kind":"string","value":"/app/span_report/logfile/csv_file_operate.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":4027,"string":"4,027"},"score":{"kind":"number","value":2.71875,"string":"2.71875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"# encoding: utf-8\n\nmodule SpanReport::Logfile\n\n class CsvReader\n ###################################################\n # 这里传入的files并不是普通的文件名,而是封装的结构\n ##################################################\n def initialize(files, is_temp=false)\n @files = files\n @is_temp = is_temp\n end\n\n def parse(processors)\n @files.each do |fileinfo|\n filename = fileinfo.filename\n puts \"process log #{filename}\"\n if @is_temp\n parse_temp_file filename, processors\n else\n parse_one_file filename,processors\n end\n end\n end\n\n private\n\n def parse_one_file filename, processors\n line_index = 0\n head_info = []\n File.foreach(filename) do |line|\n line = line.chop\n contents = line.split ','\n if line_index == 0\n contents.each do |item| \n head_info << item\n end\n else\n data_map = {}\n contents.each_with_index do |item, i|\n next if item.to_s.empty?\n data_map[head_info[i].to_s] = item\n end\n time = data_map[\"time\"]\n ue = data_map[\"ue\"]\n data_map.map do |key, value|\n key = key.encode('utf-8')\n value = value.encode('utf-8')\n end\n point_data = SpanReport::Simulate::PointData.new time, ue, data_map\n point_data.expand_data\n \n next if (point_data.rsrp.to_f <= -140) || !point_data.valid?\n \n # 调用每个处理器处理数据\n processors.each do |process|\n # begin\n process.process_pointdata point_data\n # rescue Exception => e\n # puts \"process data error:#{e.backtrace}\"\n # next\n # end\n end\n end\n line_index += 1\n end\n end\n\n def parse_temp_file filename, processors\n line_index = 0\n File.foreach(filename) do |line|\n if line_index == 0\n line_index += 1\n next\n end\n line = line.chop\n contents = line.split ','\n data_map = {}\n data_map[\"time\"] = contents[0]\n data_map[\"ue\"] = \"1\"\n data_map[\"lontitute\"] = contents[3]\n data_map[\"latitude\"] = contents[4]\n data_map[\"scell_pci\"] = contents[5]\n data_map[\"scell_freq\"] = \"1890\"\n data_map[\"scell_rsrp\"] = contents[6]\n data_map[\"scell_sinr\"] = 0\n\n (0..7).each do |i|\n data_map[\"ncell_pci_#{i}\"] = contents[7 + 2*i]\n data_map[\"ncell_freq_#{i}\"] = \"1890\"\n data_map[\"ncell_rsrp_#{i}\"] = contents[8 + 2*i]\n end\n time = data_map[\"time\"]\n ue = data_map[\"ue\"]\n point_data = SpanReport::Simulate::PointData.new time, ue, data_map\n point_data.expand_data\n\n # 调用每个处理器处理数据\n processors.each do |process|\n # begin\n process.process_pointdata point_data\n # rescue Exception => e\n # puts \"process data error:#{e.backtrace}\"\n # next\n # end\n end\n\n line_index += 1\n end\n end\n end\n\n class CsvWriter\n\n def initialize resultfile\n @export_datas = []\n open_file resultfile\n end\n\n def add_data pointdata\n @export_datas << pointdata\n write_result\n end\n\n def << pointdata\n add_data pointdata\n end\n\n def close_file\n flush\n @file.close if @file\n end\n\n private\n\n def open_file result_file\n # puts \"output csv file is:#{result_file}\"\n result_file = result_file.encode 'gbk'\n @file = File.new(result_file, \"w\")\n @file.puts head_string\n end\n\n def write_result\n if @export_datas.size > 100\n flush\n end\n end\n\n def flush\n @export_datas.each do |pointdata|\n @file.puts pointdata.to_s.encode 'gbk'\n end\n @export_datas.clear\n end\n\n def head_string\n SpanReport::Simulate::PointData.head_string\n end\n end\n\nend"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975461,"cells":{"blob_id":{"kind":"string","value":"710f5273f61dc58c0fb0b13300a706c306711ca9"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"tsunagun/cheats"},"path":{"kind":"string","value":"/webapi/yahoo/assistsearch.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1068,"string":"1,068"},"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":"# -*- coding: utf-8 -*-\n\n# Yahoo Web APIを使って関連検索ワードの取得を行うスクリプト\n\nclass Yahoo\n\n # ライブラリ読み込み\n require 'pp'\n require 'open-uri'\n require 'nokogiri'\n require 'cgi'\n\n # Yahoo Web APIのアプリケーションIDをyahoo_key.txtから読み込む\n load 'yahoo_key.txt'\n\n # APIへのリクエストURLを生成する\n def self.make_request_url(query)\n base_uri = \"http://search.yahooapis.jp/AssistSearchService/V1/webunitSearch?\"\n params = [\n \"appid=\" + YAHOO_KEY,\n \"query=\" + CGI.escape(query)\n ].join(\"&\")\n url = base_uri + params\n end\n\n # 入力文字列の形態素解析結果を取得\n def self.assistsearch(input)\n results_path = \"/xmlns:ResultSet/xmlns:Result\"\n\n request_url = self.make_request_url(input)\n parser = Nokogiri::XML(open(request_url))\n results = parser.xpath(results_path, parser.namespaces)\n results.map do |result| result.text end\n end\n\nend\n\n# queryの漢字変換候補を求める\nquery = ARGV[0] || \"大学\"\npp Yahoo.assistsearch(query)\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975462,"cells":{"blob_id":{"kind":"string","value":"8c03794f02fdea2f7956f361af6bbdd3e8173987"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"angelv8a8/SP1Ruby"},"path":{"kind":"string","value":"/Tarea1/Tarea1.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":5708,"string":"5,708"},"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":"module Tarea1 \n \n def atoi(str)\n \n valor = 0\n \n digitos = str.split(\"\")\n \n digitosC = digitos.count\n digitosC -= 1\n \n mul = 1\n \n digitosC.downto(0) do | i |\n case digitos[i]\n when \"0\"\n valor = valor\n when \"1\"\n valor += 1 * mul\n when \"2\"\n valor += 2*mul\n when \"3\"\n valor += 3*mul\n when \"4\"\n valor += 4*mul\n when \"5\"\n valor += 5*mul\n when \"6\"\n valor += 6*mul\n when \"7\"\n valor += 7*mul\n when \"8\"\n valor += 8*mul\n when \"9\"\n valor += 9*mul\n else\n puts \"Error, digito invalido \" + digitos[i]\n return\n \n end\n mul = mul*10\n end \n \n return valor\n end\n \n def char_count( s, c)\n \n letras = s.split(\"\");\n contador = 0\n \n if c.to_s.size > 1\n puts \"ERROR: El segundo parametro debe ser un caracter\"\n return nil\n end\n \n letrasC = letras.count\n 0.upto(letrasC - 1) do | i |\n if c == letras[i] \n contador += 1\n end\n end\n \n return contador\n end\n \n def sort(elArray, is_asc)\n \n resultado = Array.new\n #puts elArray\n 0.upto(elArray.count - 1) do |i|\n \n if is_asc \n indexMenor = getMayor(elArray)\n else\n indexMenor = getMenor(elArray)\n end\n #puts \"menor \" + indexMenor.to_s\n palabraMenor = elArray.delete_at(indexMenor)\n resultado.insert(0,palabraMenor)\n end\n \n return resultado\n \n end\n \n def getMayor(array)\n \n index = 0;\n mayor = array[0]\n \n 0.upto(array.count - 1 ) do | i | \n #puts \"It \" + i.to_s\n if array[i] >= mayor\n mayor = array[i]\n index = i\n end\n end\n return index\n \n end\n \n def getMenor(array)\n \n index = 0;\n menor = array[0]\n 0.upto(array.count - 1 ) do | i | \n if array[i] <= menor\n menor = array[i]\n index = i\n end\n end\n return index\n \n end\n \n \n def hanoi(height,fromPole, toPole, withPole)\n height_i = height.to_i\n if height_i >= 1\n hanoi(height_i-1,fromPole.to_i,withPole.to_i,toPole.to_i)\n moveDisk(fromPole.to_i,toPole.to_i)\n hanoi(height_i-1,withPole.to_i,toPole.to_i,fromPole.to_i)\n end\n end\n\n def moveDisk(fp,tp)\n puts \"Mover disco de \" + fp.to_i.to_s + \" a \" + tp.to_i.to_s\n end\n \n def cuenta_palabras (frase)\n \n hash = Hash.new(0)\n \n palabras = frase.to_s.split(\" \")\n puts \"Tamaño \" + palabras.count.to_s\n c_palabras = palabras.count\n 0.upto(c_palabras -1) do | i |\n\n #puts palabras[i].to_s + \" \" + hash[palabras[i].to_s].to_s\n hash[palabras[i].to_s] = hash[palabras[i].to_s] + 1\n \n end\n \n \n return hash\n end\n\n\tdef palindromo?(x)\n \n\t\ttam = x.to_s.size\n\n\t\tvalid = true;\n\t\t0.upto(x.size-1) do | i |\n\t\t\t\tstr = x[i].concat(\" \").concat(x[tam-i-1])\n\t\t\t\t\n\t\t\t\tif x[i] != x[tam-i-1]\n\t\t\t\t\t\tvalid = false;\n\t\t\t\t\t\tbreak;\n\t\t\t\tend\n\t\tend\n\n\t\treturn valid\n\n\tend\n\n\tclass Dessert\n \n @@desserts = 0\n \n def name=(value)\n @value = value\n end\n def name\n @name\n end\n \n def calories=(value)\n @calories = value\n end\n \n def calories\n @calories\n end\n \n \n\t def initialize(name, calories)\n @name = name\n @calories = calories\n @size = nil\n \n @@desserts += 1\n\n\t end\n\t \n\t def healthy?\n if @calories < 200\n return true\n end\n return false\n\t end\n\t \n\t def delicious?\n return true\n\t end\n\t \n def count\n return @@desserts\n end\n \n\t def to_s\n\t # YOUR CODE HERE\n\t end\n\tend\n\n\tclass JellyBean < Dessert\n def flavor=(value)\n @flavor = value\n end\n \n def flavor\n @flavor\n end\n\t def initialize(name, calories, flavor)\n super(name, calories)\n @flavor = flavor\n \n\t end\n \n def delicious? \n if @flavor == \"black licorice\"\n return false\n end\n \n return super\n end\n\tend\n\nend\n\n\nmodule Action\n \n @@distance = 0;\n def jump(vel)\n @@distance = rand(vel.to_i) + 2\n puts \"I jumped forward #{@@distance} feet!\"\n end\nend\n\nclass Rabbit\n include Action\n \n attr_reader :name, :velocidad\n \n def initialize(name)\n @name = name\n @velocidad = 8\n end\n \n def run()\n distInicial = 0\n start = Time.now\n while distInicial < 33 do\n jump(@velocidad)\n distInicial += @@distance\n end\n puts (Time.now - start).to_s + \" segundos\"\n end\nend\n\nclass Cricket\n include Action\n #include Date\n \n attr_reader :name, :velocidad\n\n def chirp()\n 0.upto(10 + rand(90)) do | i |\n puts i.to_s + \" Chirp... chirp!!!\"\n end\n end\n \n def initialize(name)\n @name = name\n @velocidad = 4\n end\n \n def run()\n distInicial = 0\n start = Time.now\n while distInicial < 33 do\n jump(@velocidad)\n distInicial += @@distance\n end\n puts (Time.now - start).to_s + \" segundos\"\n end\nend\n\n\nclass Computer\n include Tarea1\n \n @@users = {}\n \n @fileDir\n def initialize username, password\n @username = username\n @password = password\n \n @fileDir = Hash.new\n \n @files = {}\n end\n \n def insert (name)\n if @fileDir[name] == 0\n puts \"Error, el archivo ya existe\"\n else\n @fileDir[name] = Time.now.to_s\n end\n end\n \n def ls (sort)\n keys = @fileDir.keys\n if sort.to_s == \"asc\"\n keys = Tarea1.sort(keys,true)\n else\n keys = Tarea1.sort(keys,false)\n end\n \n 0.upto(keys.count-1) do | i |\n puts keys[i] + \"\\t\" + @fileDir[keys[i]]\n end\n puts \"End of List\"\n end\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975463,"cells":{"blob_id":{"kind":"string","value":"085048caa650229e2bfe0a807d3ab35698a28855"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"eriese/risqueFactr"},"path":{"kind":"string","value":"/app/models/partner.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1489,"string":"1,489"},"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":"# == Schema Information\n#\n# Table name: partners\n#\n# id :integer not null, primary key\n# user_id :integer\n# pref_id :integer\n# name :string(255)\n# frequency :string(255)\n# familiarity :integer\n# exclusivity :string(255)\n# created_at :datetime not null\n# updated_at :datetime not null\n#\n\nclass Partner < ActiveRecord::Base\n attr_accessible :user_id, :pref_id, :name, :frequency, :familiarity, :exclusivity, :pref_attributes\n belongs_to :user\n has_many :encounters\n belongs_to :pref\n accepts_nested_attributes_for :pref\n validates :user_id, :name, :presence => true\n def most_recent\n self.encounters_by_date.first\n end\n def encounters_by_date\n self.encounters.order(\"took_place DESC\")\n end\n def risk\n @risk = 0\n case self.exclusivity\n when \"exclusive\"\n @risk += 1\n when \"only having sex with known others\"\n @risk += 2\n when \"not exclusive with disclosure of other partners\"\n @risk += 3\n when \"not exclusive, no disclosure of other partners\"\n @risk += 4\n end\n @risk += 10 - self.familiarity\n return @risk\n end\n def pronoun\n if self.pref_id\n return self.pref.pronoun\n else\n return nil\n end\n end\n def at_risk(disease)\n if self.most_recent\n if disease.risk_window(self.user)\n return disease.risk_window(self.user) < self.most_recent.took_place\n else\n return true\n end\n else\n return false\n end\n end\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975464,"cells":{"blob_id":{"kind":"string","value":"621b7828249eceb670d5c8d180e2d654e0037a90"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"mattcrowe5/prime-ruby-prework"},"path":{"kind":"string","value":"/prime.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":239,"string":"239"},"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":"def prime?(number)\n if number == 0 || number == 1 || number == -1\n return false\n end\n \n x = 2\n stop = number/x\n while x <= stop\n if number % x == 0\n return false\n end\n x+=1\n stop = number/x\n end\n return true\nend"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975465,"cells":{"blob_id":{"kind":"string","value":"2c0d7194c26d2c4c281000aff8eda7b9ea5af79a"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"pongsanti/mcotv3"},"path":{"kind":"string","value":"/lib/util/record_op.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":214,"string":"214"},"score":{"kind":"number","value":3.046875,"string":"3.046875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"class RecordOp\n def initialize(array, skip)\n @array = array\n @skip = skip\n end\n\n def split\n return [], [] if @array.empty?\n return @array[0, @skip] || [], @array[@skip, @array.length] || []\n end\nend"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975466,"cells":{"blob_id":{"kind":"string","value":"37d71161e4e43ca08ad17d28f7e45a215b8f8a17"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"SVRourke/pantry_backend"},"path":{"kind":"string","value":"/test/models/user_test.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1588,"string":"1,588"},"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 \"test_helper\"\n\nclass UserTest < ActiveSupport::TestCase\n def setup\n @good_user = User.create(name: 'sam', email: 's@s.com', password: 'pass')\n @email_user = User.new(name: 'sam', password: 'pass')\n @password_user = User.new(name: 'sam', email: 's@s.com')\n\n @lists = [\n List.create(name: \"list one\"),\n List.create(name: \"list two\"),\n List.create(name: \"list three\")\n ]\n @lists.each { |l| l.contributors.push(@good_user) }\n\n @users = [\n User.new(name: \"a\", email: \"1A@b.c\", password: \"passsword\"),\n User.new(name: \"b\", email: \"2A@b.c\", password: \"passsword\"),\n User.new(name: \"c\", email: \"3A@b.c\", password: \"passsword\")\n ]\n\n @users.each {|u| @good_user.friends.push(u)}\n\n\n end\n \n test \"user can be created\" do\n assert @good_user.valid?, \"Valid User does not save\"\n end\n\n test \"user invalid without email\" do\n assert_not @email_user.valid?, \"Able to save User without email\"\n end\n\n test \"user invalid without password\" do\n assert_not @password_user.valid?, \"Able to save user without password\"\n end\n\n test \"user can have multiple lists\" do\n \n assert @good_user.lists.count > 1, \"list relationship needs to be two ways\"\n end\n\n test \"user can leave a list\" do\n @good_user.leave_list(@lists.first)\n assert @good_user.lists.count < 3, \"issue with #leave_list\"\n end\n\n test \"user can have many friends\" do\n assert @good_user.friends.count > 1\n end\n\n test \"user can remove a friend\" do\n @good_user.unfriend(@users.first)\n assert @good_user.friends.count < 3\n end\n\nend"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975467,"cells":{"blob_id":{"kind":"string","value":"caee6c35cc9c1eb3a1fc4dea0efd0ff4f028b20c"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"denalibalser/compost_cli"},"path":{"kind":"string","value":"/lib/cli.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2782,"string":"2,782"},"score":{"kind":"number","value":3.875,"string":"3.875"},"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":"#our CLI Controller, welcoming the user and dealing with user input\n\n\nclass CLI\n \n def start \n list_boroughs \n select_boroughs\n list_addresses\n select_address\n collection_day\n go_compost\n end\n \n def list_boroughs\n puts \"Welcome! Composting is an easy way to reduce waste. However, urban composting can be hard, we're here to help simplify it for New Yorkers!\" \n puts \"There are compost drop-off locations in all five boroughs:\"\n \n borough_arr = Borough.list_borough_names\n puts borough_arr.each_with_index(1) do |borough, index|\n \"#{index}. #{borough.name}\"\n end\n select_borough(borough_arr)\n end \n \n def select_borough(borough_arr)\n input = nil \n while input != \"exit\"\n puts \"Please select a borough 1 - 5 from which you would like to find a compost drop-off location or type 'exit' to exit:\"\n input = gets.strip.downcase\n \n input = input.to_i\n \n if input > 0 && input < 5 \n the_borough = borough_arr[input-1].name.strip\n puts \"Here is the list of compost drop-off locations for #{the_borough.upcase}:\"\n list_addresses(the_borough)\n elsif input.downcase == \"exit\"\n go_compost\n else \n puts \"Invalid Input. Please enter the number of the borough in which you would like to find a compost drop-off location or type 'exit' to exit:\"\n end \n end\n end \n \n def list_addresses(the_borough) \n puts \"Please select the number that corresponds with the compost drop-off address you would like more information on or type 'list' to return to the list of boroughs or type 'exit' to exit:\"\n addresses_arr = Address.list_addresses(the_borough)\n \n puts addresses_arr.each_with_index(1) do |address, index|\n \"#{index}. #{address.name}, #{address.location}\"\n end\n select_address(addresses_arr)\n end \n \n def select_address(addresses_arr)\n input = nil \n while input != \"exit\" \n input = gets.strip.downcase\n \n input = input.to_i\n \n if input > 0 \n chosen_address = addresses_arr[input-1].name.upcase\n \n puts \"Here are the days and hours of operation for #{chosen_address}:\"\n collection_day(chosen_address)\n elsif input == \"exit\"\n go_compost\n elsif input == \"list\"\n list_boroughs\n else \n puts \"Invalid Input. Please select the number that corresponds with the compost drop-off address you would like more information on or type 'list' to return to the list of boroughs or type 'exit' to exit:\"\n end \n end \n end \n \n def collection_day(chosen_address)\n collection_days = CollectionDay.new(chosen_address)\n puts collection_days.address_info\n end \n \n def go_compost\n puts \"Now get out there and start composting New York!\"\n exit\n end \nend\n\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975468,"cells":{"blob_id":{"kind":"string","value":"0db8d3c1f1065294feba0a034401ca400c4c537e"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"Nitemaeric/coding-lessons"},"path":{"kind":"string","value":"/ruby/1-programming-fundamentals/oop.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":341,"string":"341"},"score":{"kind":"number","value":3.796875,"string":"3.796875"},"int_score":{"kind":"number","value":4,"string":"4"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"class Me\n attr_accessor :age\n attr_writer :name\n attr_reader :story\n\n def initialize(name = nil, age, story: nil)\n @age = age\n @name = name\n @story = story\n end\n\n def name(addon = '')\n \"#{@name} is #{story} #{addon}\"\n end\n\n def do_something(&block)\n puts \"hi\"\n block.call(20) if block\n puts \"someting\"\n end\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975469,"cells":{"blob_id":{"kind":"string","value":"4a17d313d24e22f7c26ce0799eabdffe910b3f08"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"chrisrobertspdx/flatiron-store-project-v-000"},"path":{"kind":"string","value":"/app/models/cart.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":930,"string":"930"},"score":{"kind":"number","value":2.6875,"string":"2.6875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT","LicenseRef-scancode-unknown-license-reference","LicenseRef-scancode-public-domain"],"string":"[\n \"MIT\",\n \"LicenseRef-scancode-unknown-license-reference\",\n \"LicenseRef-scancode-public-domain\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"class Cart < ActiveRecord::Base\n belongs_to :user\n has_many :line_items\n has_many :items, through: :line_items\n \n def add_item(item_id)\n existing = self.line_items.detect{|l| l.item_id == item_id.to_i}\n\n if !existing\n #self.line_items << Line_Item.new({item_id: item_id, cart_id: self.cart_id, quantity: 1})\n self.line_items.new({item_id: item_id, quantity: 1})\n #self.save\n else\n existing.quantity += 1\n existing.save\n #this is awkward\n existing\n end\n end\n \n def total\n self.line_items.reduce(0) {|sum,i| \n sum + (i.item.price * i.quantity)\n }\n end\n \n def checkout\n self.line_items.each {|e|\n e.item.inventory -= e.quantity\n e.item.save\n }\n self.status = \"submitted\"\n self.save\n #binding.pry\n end\n \nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975470,"cells":{"blob_id":{"kind":"string","value":"6f36509fc3a963edb7333c26db43a0692c48a919"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"coderjonny/myrubyscripts"},"path":{"kind":"string","value":"/meta.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":3643,"string":"3,643"},"score":{"kind":"number","value":3.890625,"string":"3.890625"},"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 Test\r\n\tdef one\r\n\t\t@var = 99\r\n\t\ttwo\r\n\tend\r\n\tdef two \r\n\t\tputs @var\r\n\tend\r\nend\r\np t = Test.new\r\np t.one\r\n\r\nclass Test\r\n\tputs \"In the definition of class Test\"\r\n\tputs \"self = #{self}\"\r\n\tputs \"Class of self = #{self.class}\"\r\nend\r\n\r\nclass Test\r\n\t@var = 99\r\n\tdef self.value_of_var\r\n\t\t@var\r\n\tend\r\nend\r\nputs Test.value_of_var\r\n\r\nanimal = \"cat\"\r\nputs animal.upcase.reverse\r\n\r\ndef animal.speak\r\n\tputs \"Then #{self} says miaow\"\r\nend\r\nanimal.speak\r\nputs animal.upcase\r\n\r\nclass Dave\r\n\tdef self.class_method_one\r\n\t\tputs \"Class method one\"\r\n\tend\r\n\tdef Dave.class_method_one\r\n\t\tputs \"Class method one overwritten using self!?\"\r\n\tend\r\n\tdef Dave.class_method_two\r\n\t\tputs \"Class method two\"\r\n\tend\r\nend\r\n\r\nDave.class_method_one\r\nDave.class_method_two\r\n\r\nclass Test\r\n\t@var = 99\r\n\tdef self.var\r\n\t\t@var\r\n\tend\r\n\tdef self.var=(value)\r\n\t\t@var = value\r\n\tend\r\nend\r\nputs \"\\n\\n\\noriginal value = #{Test.var}\"\r\nTest.var = \"cat\"\r\nputs \"New value = #{Test.var}\"\r\n\r\n\r\n\r\nanimal = \"dog\"\r\nclass << animal\r\n\tdef speak\r\n\t\tputs \"The #{self} says woof!\"\r\n\tend\r\nend\r\nanimal.speak\r\n\r\nanimal = \"dog\"\r\ndef animal.speak\r\n\tputs \"the #{self} says woof!\"\r\nend\r\nsingleton = class << animal\r\n\tdef lie\r\n\t\tputs \"The #{self} lies down!\"\r\n\tend\r\n\tself #< anagrams(\"pears\")\n# # => [\"APERS\",\"APRES\",\"ASPER\",\"PARES\",\"PARSE\",\"PRASE\",\"PRESA\",\"RAPES\",\"REAPS\",\"SPARE\",\"SPEAR\"]\n\n# > anagrams(\"zygote\")\n# #=> []\n\nwords = %w[cars scar for four creams scream racs]\n\nanagrams = words.group_by { |word| word.chars.sort }.values\n# => [[\"cars\", \"scar\", \"racs\"], [\"for\"], [\"four\"], [\"creams\", \"scream\"]] "},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975473,"cells":{"blob_id":{"kind":"string","value":"96015b5ee01cea46a737835e3fc0585d0eb8b6f4"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"billgloff/data-engineering"},"path":{"kind":"string","value":"/data_normalizer/app/services/import_service.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":837,"string":"837"},"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":"require 'csv'\n\nclass ImportService\n\n\tattr_accessor :total_amount_gross\n\n\tdef initialize(file)\n\t\t@file = file\n\t\t@total_amount_gross = 0.0\n\tend\n\n\tdef parse\n\t\tCSV.parse(@file, headers: true, col_sep: \"\\t\").each do |row|\n customer_name, item_description, item_price = row[0], row[1], row[2].to_f\n purchase_count, merchant_address, merchant_name = row[3].to_i, row[4], row[5]\n \n merchant = Merchant.find_or_create_by(name: merchant_name, address: merchant_address)\n customer = Customer.find_or_create_by(name: customer_name)\n item = Item.find_or_create_by(description: item_description, price: item_price, count: purchase_count, merchant: merchant)\n Purchase.find_or_create_by(customer: customer, item: item)\n\n @total_amount_gross += item_price.to_f\n \tend\n\tend\n\nend"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975474,"cells":{"blob_id":{"kind":"string","value":"7ec192cf66f3d7abff5173a3bb9de72e78202f9f"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"rashmiagar/some_programs"},"path":{"kind":"string","value":"/are_anagrams.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":626,"string":"626"},"score":{"kind":"number","value":3.734375,"string":"3.734375"},"int_score":{"kind":"number","value":4,"string":"4"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"module AreAnagrams\n def self.are_anagrams?(string_a, string_b)\n if string_a.length != string_b.length\n false\n elsif \n hash_string_a = Hash.new\n string_a.downcase.each_char{|chr|\n if hash_string_a.has_key?(chr)\n hash_string_a[chr] += 1\n else\n hash_string_a[chr] = 1\n end\n }\n\n string_b.downcase.each_char{|chr|\n if hash_string_a[chr] != nil && hash_string_a[chr] > 0\n hash_string_a[chr] -= 1\n else\n return false\n end\n }\n return true\n end\n end\nend\n\nputs AreAnagrams.are_anagrams?('orchestra', 'carthorse')"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975475,"cells":{"blob_id":{"kind":"string","value":"5b02f0e0bb7ad0d9f1d630e589c7fb2a6025e6ce"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"LogaJ/CukeSalad"},"path":{"kind":"string","value":"/Examples/Calculator/features/lib/alternative/roles/calculating_web_user.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2002,"string":"2,002"},"score":{"kind":"number","value":2.96875,"string":"2.96875"},"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":"# To run with this version of the Calculating Individual:\n# cucumber --profile alternative \n\nrequire 'web_calculator'\nrequire 'capybara'\nrequire 'capybara/dsl'\n\nCapybara.app = WebCalculator\nCapybara.default_driver = :rack_test\n\nmodule CalculatingIndividual\n\n # Uses a Browser to perform its tasks\n include Capybara\n # This is not a page object. It is a WebUser, specialised to our application\n # See the comments in the 'enter' and 'press' method for an explanation of why\n\n def switch_on_the_calculator\n visit '/'\n end\n\n def enter value\n fill_in 'number', :with => value\n # Because the calculator is a simple web_app with only\n # one page we can put the id for the field here. In a more complex web-app\n # we would pass in the id of the thing to enter\n # The task would express the action as: enter( :the_number, \"10\")\n # Because we can change the id used in our application,\n # we would just change the id in the application to be 'the_number'.\n # If we were on a project where we could not change the id \n # in the application we would write an 'ApplicationExpert' \n # to map :the_number to the id for the field 'number'. Our CalculatingIndividual\n # would ask the ApplicationExpert for the id of the symbol :the_number\n # See 'press' below for am explanation of how an ApplicationExpert \n # would work \n end\n \n def press operator\n click_button operator.to_s\n # Here, our 'operator' happens to also match the id for the button.\n # If we were on a project where we could not choose what the id\n # was for buttons, we would write an ApplicationExpert to map \n # the symbol used in the task to the symbol for that button. \n # The ApplicationExpert would only need to know what page it \n # was on to find a mappings class (or yml file) for the fields on that page.\n end\n\n def look_at_the_display\n find_field('display').value.to_i\n end\n\n def is_the_calculator_ready?\n page.body.should =~ /Calculator is Ready!/\n end\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975476,"cells":{"blob_id":{"kind":"string","value":"ca7a91c4a3b8001d0981aa19dbd7eda13b3067ba"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"jsiny/101_programming_foundations"},"path":{"kind":"string","value":"/exercises/12_medium_2/ex_04.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2134,"string":"2,134"},"score":{"kind":"number","value":4.34375,"string":"4.34375"},"int_score":{"kind":"number","value":4,"string":"4"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"def balanced_1?(string)\n has_opening = 0\n has_closing = 0\n\n string.chars.each do |char|\n has_opening += 1 if char == '('\n has_closing += 1 if char == ')'\n break if has_closing > has_opening\n end\n\n has_opening == has_closing\nend\n\np balanced_1?('What (is) this?') == true\np balanced_1?('What is) this?') == false\np balanced_1?('What (is this?') == false\np balanced_1?('((What) (is this))?') == true\np balanced_1?('((What)) (is this))?') == false\np balanced_1?('Hey!') == true\np balanced_1?(')Hey!(') == false\np balanced_1?('What ((is))) up(') == false\n\nputs '--------'\n\n# Shorter method\n\ndef balanced_2?(string)\n parentheses = 0\n string.each_char do |char|\n parentheses += 1 if char == '('\n parentheses -= 1 if char == ')'\n break if parentheses < 0\n end\n parentheses.zero?\nend\n\np balanced_2?('What (is) this?') == true\np balanced_2?('What is) this?') == false\np balanced_2?('What (is this?') == false\np balanced_2?('((What) (is this))?') == true\np balanced_2?('((What)) (is this))?') == false\np balanced_2?('Hey!') == true\np balanced_2?(')Hey!(') == false\np balanced_2?('What ((is))) up(') == false\n\nputs '--------'\n\n# Further Exploration\n\nDIFFERENT_PAIRS = [%w(( )), %w([ ]), %w({ })].freeze\nQUOTES = ['\\'', '\\\"'].freeze\n\ndef extended_balance?(string)\n result = []\n\n DIFFERENT_PAIRS.each do |pair|\n result << balanced?(string, pair)\n end\n\n QUOTES.each do |quote|\n result << balanced_with_quote?(string, quote)\n end\n\n result.all? { |element| element == true }\nend\n\ndef balanced?(string, pair)\n duo = 0\n string.each_char do |char|\n duo += 1 if char == pair[0]\n duo -= 1 if char == pair[1]\n break if duo < 0\n end\n duo.zero?\nend\n\ndef balanced_with_quote?(string, quote)\n string.chars.count { |char| char == quote }.even?\nend\n\np extended_balance?('hey {') == false\np extended_balance?('hello (madam) I will be {your} guide') == true\np extended_balance?(\"hello (madam) I'll be {your} guide\") == false\np extended_balance?('hello (madam') == false\np extended_balance?('} next {') == false\np extended_balance?(\"I 'love' you\") == true\np extended_balance?('I \"would\" love to meet ya') == true\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975477,"cells":{"blob_id":{"kind":"string","value":"fee458ef5658aad7d2329dfd5f2ba43b77cfe3b6"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"heavenchou/cbwork-bin"},"path":{"kind":"string","value":"/xml2epub/unicode_service.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":453,"string":"453"},"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 'Unihan2'\nclass UnicodeService\n def initialize\n @u2 = Unihan2.new\n end\n\n def level1?(code)\n return false if code.nil?\n # Unicode 3.0 以內 在 mobile 可以正確顯示\n v = @u2.ver(code)\n raise CbetaError.new(500), \"Unihan2.ver 回傳 nil, code: #{code}\" if v.nil?\n v <= 3\n end\n\n def level2?(code)\n return false if code.nil?\n # Unicode 10 以內 在 desktop 有字型可以顯示\n @u2.ver(code) <= 10\n end\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975478,"cells":{"blob_id":{"kind":"string","value":"5d3d6bc419bc9554c23f0ffdd6e489b3a770b25b"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"mpeiros/mediocritter"},"path":{"kind":"string","value":"/app/models/user.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":947,"string":"947"},"score":{"kind":"number","value":2.625,"string":"2.625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT","LicenseRef-scancode-unknown-license-reference"],"string":"[\n \"MIT\",\n \"LicenseRef-scancode-unknown-license-reference\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"class User < ActiveRecord::Base\n has_many :comments\n has_many :searches\n has_many :favorites\n has_many :favorited_tweets, through: :favorites, source: :tweet\n\n validates_presence_of :email, :username, :password_hash\n validates_uniqueness_of :email, :username\n\n def password\n @password ||= BCrypt::Password.new(password_hash)\n end\n\n def password=(new_password)\n @password = BCrypt::Password.create(new_password)\n self.password_hash = @password\n end\n\n def self.authenticate(email, password)\n if @user = User.find_by(email: email)\n @user.password == password ? @user : nil\n end\n end\n\n def favorited?(tweet)\n self.favorited_tweets.each do |fav_tweet|\n if fav_tweet.tweet_time == tweet.tweet_time && fav_tweet.text == tweet.text\n return true \n end\n end\n false \n end\n\n def sort_favorited_tweets\n self.favorited_tweets.sort_by { |fav_tweet| fav_tweet.favorited_at(self.id) }.reverse\n end\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975479,"cells":{"blob_id":{"kind":"string","value":"86bb9490fcff1198db279cd6dc9a8681b761e3ba"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"evelynnkaplan/matrix_convert_to_zero"},"path":{"kind":"string","value":"/lib/matrix_convert_to_zero.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1550,"string":"1,550"},"score":{"kind":"number","value":4.09375,"string":"4.09375"},"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":"# Updates the input matrix based on the following rules:\n# Assumption/ Given: All numbers in the matrix are 0s or 1s\n# If any number is found to be 0, the method updates all the numbers in the\n# corresponding row as well as the corresponding column to be 0.\n\n# Time complexity: O(n*m) where n is the length of the matrix and m is the length of the longest array within the matrix.\n# For both loops, the outer will run n times and the inner will run m times.\n# Space complexity: O(n+m) where n is the length of the matrix and m is the length of the longest array within the matrix.\n# The maximum number of values in the outer_indexes array will be equal to n and the maximum number of values in the \n# inner_indexes array will be equal to m.\n\ndef matrix_convert_to_zero(matrix)\n outer_indexes = []\n inner_indexes = []\n\n matrix.each_with_index do |arr, outer_index|\n arr.each_with_index do |num, inner_index|\n if num == 0\n if !outer_indexes.include?(outer_index)\n outer_indexes << outer_index\n end\n if !inner_indexes.include?(inner_index)\n inner_indexes << inner_index\n end\n end\n end\n end\n\n matrix.each_with_index do |arr, outer_index|\n if outer_indexes.include?(outer_index)\n arr.each_with_index do |num, inner_index|\n if num == 1\n arr[inner_index] = 0\n end\n end\n end\n arr.each_with_index do |num, inner_index|\n if inner_indexes.include?(inner_index) && num == 1\n arr[inner_index] = 0\n end\n end\n end\n\n return matrix\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975480,"cells":{"blob_id":{"kind":"string","value":"d7a179bfa72eb98eb17c6415186dbabd9fac9bfa"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"smernick/square_array-001-prework-web"},"path":{"kind":"string","value":"/square_array.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":333,"string":"333"},"score":{"kind":"number","value":4.125,"string":"4.125"},"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":"def square_array(array)\n\n new_array = [] #defines a new array\n\n array.each do |number| #tells program to iterate throught the array\n new_array << (number**2) #tells program to square each number and add it to the back of the new_array\n end\n return new_array #returns the value of the new_array at the end of the iteration.\nend"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975481,"cells":{"blob_id":{"kind":"string","value":"082002b598742027165abc6e74d82ba343c9976f"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"jamensky/programming-univbasics-4-building-nested-hashes-online-web-prework"},"path":{"kind":"string","value":"/intro_to_ruby_hashes_lab.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1254,"string":"1,254"},"score":{"kind":"number","value":2.671875,"string":"2.671875"},"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 base_hash\n\thash = {:railroads => {} }\n\tend\n\ndef monopoly_with_second_tier \n hash = {:railroads => {} }\n hash[:railroads][:pieces] = 4\n return hash \nend \n\ndef monopoly_with_third_tier\n hash = {:railroads => {} }\n hash[:railroads][:pieces] = 4\n hash[:railroads][:rent_in_dollars] = {:one_piece_owned => 25, :two_pieces_owned => 50, :three_pieces_owned => 100, :four_pieces_owned => 200}\n hash[:railroads][:names] = {:reading_railroad => {}, :pennsylvania_railroad => {}, :b_and_o_railroad => {}, :shortline_railroad => {} }\n return hash\nend\n\ndef monopoly_with_fourth_tier \n hash = {:railroads => {} }\n hash[:railroads][:pieces] = 4\n hash[:railroads][:rent_in_dollars] = {:one_piece_owned => 25, :two_pieces_owned => 50, :three_pieces_owned => 100, :four_pieces_owned => 200}\n hash[:railroads][:names] = {:reading_railroad => {}, :pennsylvania_railroad => {}, :b_and_o_railroad => {}, :shortline_railroad => {} }\n hash[:railroads][:names][:reading_railroad][\"mortgage_value\"] = \"$100\"\n hash[:railroads][:names][:pennsylvania_railroad][\"mortgage_value\"] = \"$200\"\n hash[:railroads][:names][:b_and_o_railroad][\"mortgage_value\"] = \"$400\"\n hash[:railroads][:names][:shortline_railroad][\"mortgage_value\"] = \"$800\"\n \n return hash\nend\n\n\n\n\n\n\n\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975482,"cells":{"blob_id":{"kind":"string","value":"28b7e5e7e1cdd8cca1c0e1ca33523566024e324c"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"TwiceNo/Patterns"},"path":{"kind":"string","value":"/1/projecteuler40.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":523,"string":"523"},"score":{"kind":"number","value":3.5625,"string":"3.5625"},"int_score":{"kind":"number","value":4,"string":"4"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"def get_digit(n)\n\tcurr_block = 0\n\tcurr_upper = 0\n\tprev_upper = 0\n\twhile curr_upper < n\n\t\tprev_upper = curr_upper\n\t\tcurr_upper += 9 * 10 ** curr_block\n\t\tcurr_block += 1\n\tend\n\toffset = n - prev_upper - 1\n\tsequence = 1\n\twhile sequence * curr_block < offset\n\t\tsequence += 1\n\tend\n\tfraction = \"\"\n\tfor i in prev_upper + 1..prev_upper + 1 + sequence do\n\t\tfraction += i.to_s\n\tend\n\treturn fraction.split(//)[offset].to_i\nend\n\ndef product()\n\tres = 1\n\tfor i in 0..7 do\n\t\tres *= get_digit(10 ** i)\n\tend\n\treturn res\nend\n\n\nputs product()\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975483,"cells":{"blob_id":{"kind":"string","value":"8928f80734828e3a26073de7d7dc4b0409c1b73e"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"sgeorgi/pageflow"},"path":{"kind":"string","value":"/app/helpers/pageflow/files_helper.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":597,"string":"597"},"score":{"kind":"number","value":2.78125,"string":"2.78125"},"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 Pageflow\n module FilesHelper\n def file_format(file)\n file.format.presence || '-'\n end\n\n def file_dimensions(file)\n if file.width && file.height\n \"#{file.width} x #{file.height}px\"\n else\n \"-\"\n end\n end\n\n def file_duration(file)\n if file.duration_in_ms\n total_seconds = file.duration_in_ms / 1000\n seconds = total_seconds % 60\n minutes = (total_seconds / 60) % 60\n hours = total_seconds / (60 * 60)\n\n format(\"%02d:%02d:%02d\", hours, minutes, seconds)\n else\n \"-\"\n end\n end\n end\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975484,"cells":{"blob_id":{"kind":"string","value":"ac61ab9e1d574456ea1d95bec66e67724e509a85"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"mixophrygian/Text-Adventure"},"path":{"kind":"string","value":"/text_adventure.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":8294,"string":"8,294"},"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":"#How to play this file! Open the command line, type \"irb\" then type \"load 'text_adventure.rb'\" whenever you want to play! The game will quit itself if you win or lose. Load the file again to replay.\n\n\nclass Dungeon\n\tattr_accessor :player\n\n\tdef initialize(player_name)\n\t\t@player = Player.new(player_name)\n\t\t@rooms = []\n\tend\n\n\tdef add_room(reference, name, description, connections, eat_description, eatlethal, play_description, playlethal, win)\n\t\t@rooms << Room.new(reference, name, description, connections, eat_description, eatlethal, play_description, playlethal, win)\n\tend\n\n\tdef start(location)\n\t\t@player.location = location\n\t\tshow_current_description\n\t\tputs \"\\n\"\n\tend\n\n\tdef show_current_description\n\t\tputs find_room_in_dungeon(@player.location).full_description\n\t\tputs \"\\nWhat would you like to do next? Select \\\"Eat\\\", \\\"Play\\\", \\\"Explore\\\" or Exit\\n\"\n\tend\n\n\tdef show_eat_description\n\t\tputs \"\\n\" + find_room_in_dungeon(@player.location).eat_description\n\tend\n\n\tdef show_play_description\n\t\tputs \"\\n\" + find_room_in_dungeon(@player.location).play_description\n\tend\n\n\tdef find_room_in_dungeon(reference)\n\t\t@rooms.detect{ |room| room.reference == reference}\n\tend\n\n\tdef find_room_in_direction(direction)\n\t\tfind_room_in_dungeon(@player.location).connections[direction]\n\tend\n\n\tdef prompt(selection)\n\t\tunless selection == \"eat\" || selection ==\"play\" || selection ==\"explore\" || selection == \"exit\" || @player.dead === true\n\t\t\tputs \"\\nSelect Eat, Play, Explore or Exit\\n\"\n\t\t\tselection = gets.chomp.downcase\n\t\tend\n\n\t\tcase selection\n\t\twhen \"explore\" \n\t\t\tputs \"\\nWhich direction? North, South, East or West.\\n\"\n\t\t\tdirection = gets.chomp.downcase\n\t\t\tunless direction == \"north\" || direction == \"south\" || direction == \"east\" || direction == \"west\" || direction == \"exit\"\n\t\t\t\tputs \"\\nSelect a valid drection, north south east or west.\\n\"\n\t\t\t\tdirection = gets.chomp.downcase\n\t\t\tend\n\t\t\tgo(direction.to_sym)\n\t\twhen \"eat\"\n\t\t\tshow_eat_description\n\t\t\tif(find_room_in_dungeon(@player.location).eatlethal)\n\t\t\t\tputs \"GAME OVER #{@player.name}\"\n\t\t\t\t@player.dead = true\n\t\t\telse\n\t\t\t\tputs \"\\n What would you like to do next? Select \\\"Eat\\\", \\\"Play\\\", or \\\"Explore\\\" or Exit\\n\"\n\t\t\tend\n\t\twhen \"play\"\n\t\t\tshow_play_description\n\t\t\tif(find_room_in_dungeon(@player.location).playlethal)\n\t\t\t\tputs \"GAME OVER #{@player.name}\"\n\t\t\t\t@player.dead = true\n\t\t\telsif (find_room_in_dungeon(@player.location).win)\n\t\t\t\tputs \"YOU WON, #{@player.name}!\"\n\t\t\t\t@player.won = true\n\t\t\telse\n\t\t\t\tputs \"\\n What would you like to do next? Select \\\"Eat\\\", \\\"Play\\\", or \\\"Explore\\\" or Exit\\n\"\n\t\t\tend\n\t\twhen \"exit\"\n\t\t\tputs \"Goodbye breakfast-naut\"\n\t\t\t@player.dead = true\n\t\telse\n\t\t\tputs \"Invalid selection. Say again?\"\n\t\tend\n\tend\n\n\tdef go(direction)\n\t\tif find_room_in_direction(direction) != nil\n\t\t\tputs \"You go #{direction.to_s} and find yourself in... \\n\\n\"\n\t\t\t@player.location = find_room_in_direction(direction)\n\t\t\tshow_current_description\n\t\telse\n\t\t\tputs \"\\nYou try to go #{direction} but soon reach a magnetic forcefield and must turn around\"\n\t\tend\n\tend\n\n\tclass Player\n\t\tattr_accessor :name, :location, :dead, :won\n\n\t\tdef initialize(name)\n\t\t\t@name = name\n\t\t\t@dead = false\n\t\t\t@won = false\n\t\tend\n\tend\n\n\tclass Room\n\t\tattr_accessor :reference, :name, :description, :connections, :eat_description, :eatlethal, :play_description, :playlethal, :win\n\n\t\tdef initialize(reference, name, description, connections, eat_description, eatlethal, play_description, playlethal, win)\n\t\t\t@reference = reference\n\t\t\t@name = name\n\t\t\t@description = description\n\t\t\t@connections = connections\n\t\t\t@eat_description = eat_description\n\t\t\t@eatlethal = eatlethal\n\t\t\t@play_description = play_description\n\t\t\t@playlethal = playlethal\n\t\t\t@win = win\n\t\tend\n\n\n\t\tdef full_description\n\t\t\t@name + \"\\n\\nYou are in \" + @description\n\t\tend\n\tend\nend\n\n\n\tputs \"\\nWelcome to \n\t\\n==BREAKFAST GALAXY QUEST== \\n\\n\"\n\tputs \"Player, what is your name?\"\n\tplayer_name = gets.chomp\n\tnew_game = Dungeon.new(player_name)\n\t# initalizing locations\n\tnew_game.add_room(:pancakenebula, \"THE PANCAKE NEBULA\", \"a hazy region just north of Orion's griddle contain billions of pancake asteroids of all sizes. They are as fluffy as they are delicious.\", {:south => :orionsgriddle, :north => :baconbelt, :east => :celestialcrepes, :west => :browndwarfbagels}, \"These pancakes are delicious! The are perfectly browned with a hint of space-spice. Uh oh. You are now addicted to spice.\", false, \"You try playing with the pancakes a little too violently and a medium-sized cake spins out of control, thwaping you on the helmet causing you to lose consciousness briefly.\", false, false)\n\n\tnew_game.add_room(:orionsgriddle, \"ORION'S GRIDDLE\", \"an area in which mysterious magnetism between the angle of nearby stars combined with a fortunate shipwreck of egg cargo has resulted in a seemingly neverending supply of perfectly cooked, zero-gravity formed scrambled eggs.\", {:north => :pancakenebula}, \"You take a bite and the eggs are magnificent! You didn't know scrambled eggs could be so good!\", false, \"You attempt to play with the eggs but they form a face on your plate that looks distinctly disapproving. All the other space-diners stop and stare. The space-record-needle swerves off the tracks. You have committed an intergalactic space crime. The burliest chef comes out of the kitchen and the last thing you remember is a frying pan quickly approaching your face plate...\", true, false)\n\n\tnew_game.add_room(:baconbelt, \"THE BACON BELT\", \"a vast expanse of bacon strips in ring formation that spans the entire circumfrence of Breakfast-Saturn, the Bacon belt rings vary in crispyness according to their proximity to the celestial body. For well-done, try the outermost ring!.\", {:south => :pancakenebula}, \"You choose bacon on the crispier side and have fallen into a trance, a bacon-trance. You start imagining moving to the bacon belt, permanently.\", false, \"You try playing with bacon but run out of ideas, fast. Zero-gravity isn't very conducive to bacon art.\", false, false)\n\n\tnew_game.add_room(:celestialcrepes, \"CELESTIAL CREPES\", \"a mysterious location in which crepes are as delicious as they are dangerous. These massive, moon-sized crepes are edible and benign until they reach maturity, at which time they gain sentience and the ability to swallow breakfast-nauts whole, like a venus fly trap would swallow an unassuming gnat. Their jam, accordingly, is dangerous to harvest and commands a great price in the intergalactic cafeteria.\", {:west => :pancakenebula}, \"You carefully select a crepe with your space fork, but you selected wrong! This medium-size crape expands in size drastically as its delicious-looking jaws open wide to eat YOU for breakfast! Death by crepes.\", true, \"Instead of attempting to eat these beautiful creatures you tickle one with your fork. It smiles in friendship and the crepes form a space-sofa to carry you as their new space emperor.\", false, true)\n\n\tnew_game.add_room(:browndwarfbagels, \"BROWN DWARF BAGELS\", \"a zone formerly occuped by a star that went brown dwarf and thus did not achieve sufficient energy to explode. An enterprising breakfast-naut by the name of Hans saw the opportunity here to open a planet-sized delicatessen, harnessing the area's natural toasty-ness. They are famous for their bagels and brag a 'bagel event horizon' radius of 50 miles!\", {:east => :pancakenebula}, \"You attempt to eat a brown dwarf bagel...and succeed! Space lox and celestial cream cheese appear out of nowhere to make your space bagel more delicious.\", false, \"You try playing with your bagel but the bagel takes it too seriously and turns into a bready-black hole, engulfing you, the entire restaurant and the full galaxy, without even chewing. As a result the bagel is slightly bigger, but no one is around to notice.\", true, false)\n\t#end intializing locations\n\n\n\tputs \"\\n#{new_game.player.name}, you have just completed your one THOUSANDTH illustrious space mission and\nhave been awarded one round-trip hyper-space voyage to the ==BREAKFAST GALAXY==. The hyper-space arrival doc is located directly in...\\n\\n\"\n\n\tnew_game.start(:pancakenebula)\n\tselection = gets.chomp.downcase\n\twhile(selection != \"exit\")\n\t\tnew_game.prompt(selection)\n\t\tif new_game.player.dead || new_game.player.won\n\t\t\tbreak\n\t\telse\n\t\tselection = gets.chomp.downcase\n\t\tend\n\tend\n\n\n\n\n\n\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975485,"cells":{"blob_id":{"kind":"string","value":"de5cf0029aa89b1427a56ff9d7c136c7bf2c11d4"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"Elazp/Online_week1"},"path":{"kind":"string","value":"/Ejercicio2_Fruta_Solución.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1376,"string":"1,376"},"score":{"kind":"number","value":3.984375,"string":"3.984375"},"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\nclass ShoppingCart\n\t@@prices_list = {\n\t\t:apple\t \t=> 10,\n\t\t:orange \t=> 5,\n\t\t:grape\t\t=> 15,\n\t\t:banana\t\t=> 20,\n\t\t:watermelon\t=> 50\n\t}\n\n\tdef initialize\n\t\t@cart = Hash.new 0\t\n\tend\n\n\tdef get_item_price item\n\t\t@@prices_list[item]\n\tend\n\n\tdef add_item_to_cart item \n\t\t@cart[item] += 1\n\tend\t\n\n\tdef show\n\t\tshopping_cart_calculated = calculate_shopping_cart\n\t\t\n\t\tshopping_cart_calculated.each_with_index do |(key,value),index|\n\t\t\tputs \"#{index+1}: #{key} => #{@cart[key]} items #{value}€\"\n\t\tend\n\n\tend\n\n\tdef calculate_shopping_cart\n\t\tcalculated_cart = {}\n\t\t@cart.each do |key,value|\n\t\t\tcalculated_cart[key] = get_item_price(key) * value\n\t\tend\n\t\tcalculated_cart\t\t\t\n\tend\t\n\n\tdef get_cost\n\t\tshopping_cart_calculated = calculate_shopping_cart\n\t\tshopping_cart_calculated.reduce(0) {|sum, (key, val)| sum += val}\n\t\t#shopping_cart_calculated.values.reduce(:+)\n\tend\n\nend\n\nshopping_cart = ShoppingCart.new\n\nshopping_cart.add_item_to_cart :apple\nshopping_cart.add_item_to_cart :apple\nshopping_cart.add_item_to_cart :orange\nshopping_cart.add_item_to_cart :orange\nshopping_cart.add_item_to_cart :orange\nshopping_cart.add_item_to_cart :grape\nshopping_cart.add_item_to_cart :grape\nshopping_cart.add_item_to_cart :grape\nshopping_cart.add_item_to_cart :grape\nshopping_cart.add_item_to_cart :banana\n\nshopping_cart.show\nputs \"The cost of your shopping cart is #{shopping_cart.get_cost}€\"\n\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975486,"cells":{"blob_id":{"kind":"string","value":"8ca76452bae77847d1d42080a02ad539496bafe5"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"pravsingh/Algorithm-Implementations"},"path":{"kind":"string","value":"/Insertion_Sort/Ruby/mitogh/insertion_sort.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":206,"string":"206"},"score":{"kind":"number","value":3.515625,"string":"3.515625"},"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":"def insertion_sort(arr = []) \n arr.each_with_index do |element, i| \n j = i\n while(j > 0 and (prev = arr[j-1]) > element) do\n arr[j] = prev\n j -= 1\n end\n arr[j] = element\n end\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975487,"cells":{"blob_id":{"kind":"string","value":"86421313bbbda763dd01bf7efb319fc070c71490"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"romero-c-raul/ruby-basics"},"path":{"kind":"string","value":"/strings/pr2.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":80,"string":"80"},"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":"puts 'It\\'s now 12 o\\'clock.'\n\n# These are the same\n\nputs \"It's now 12 o'clock.\""},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975488,"cells":{"blob_id":{"kind":"string","value":"86fd793fb46cf29e2bf427d912f0104b45f7d46c"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"sp0gg/katas_and_exercises"},"path":{"kind":"string","value":"/ruby/lib/codility/tape_equilibrium.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":453,"string":"453"},"score":{"kind":"number","value":3.265625,"string":"3.265625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"class TapeEquilibrium\n\n def self.solution a\n\n #add all together.\n sum = a.reduce :+\n puts \"sum #{sum}\"\n left = a[0]\n right = sum - left\n puts \"l #{left} r #{right}\"\n min_diff = (right-left).abs\n puts \"mindiff #{min_diff}\"\n\n #run p through entire array.\n 1.upto(a.size-2) do |i|\n\n left += a[i]\n right -= a[i]\n diff = (right-left).abs\n min_diff = diff if min_diff > diff\n end\n p min_diff\n end\n\nend"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975489,"cells":{"blob_id":{"kind":"string","value":"7afb4ceac6dbcc6255d39137928781efb8ef40f4"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"duong110397/learn-ruby"},"path":{"kind":"string","value":"/300-children-exercises/array-exercises/ex6.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":172,"string":"172"},"score":{"kind":"number","value":2.75,"string":"2.75"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"=begin \nThay the cac gia tri am co trong mang bang 0\n=end\narr = 10.times.map{rand(-10..10)} \nnegativ = []\narr.each{|a| negativ.push(a < 0 ? 0 : a)} \nputs negativ.inspect\n\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975490,"cells":{"blob_id":{"kind":"string","value":"2378154ff94fdb670a5309a8d97b329053706307"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"emmabeynon/rps-challenge"},"path":{"kind":"string","value":"/spec/game_spec.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":3617,"string":"3,617"},"score":{"kind":"number","value":2.890625,"string":"2.890625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"require 'game'\n\ndescribe Game do\n subject(:game) { described_class.new(player_1, player_2)}\n let(:player_1) { double :player_1, weapon: :rock }\n let(:player_2) { double :player_2, weapon: :scissors }\n\n describe 'default' do\n it 'accepts two players' do\n expect(game.player_1).not_to be_nil\n expect(game.player_2).not_to be_nil\n end\n end\n\n describe '#outcome' do\n it 'returns the outcome of the two weapons' do\n expect(game.outcome).to eq :win\n end\n\n it 'returns Draw when Rock and Rock are played' do\n allow(player_1).to receive(:weapon) {:rock}\n allow(player_2).to receive(:weapon) {:rock}\n expect(game.outcome).to eq :draw\n end\n\n it 'returns Lose when Rock and Paper are played' do\n allow(player_1).to receive(:weapon) {:rock}\n allow(player_2).to receive(:weapon) {:paper}\n expect(game.outcome).to eq :lose\n end\n\n it 'returns Win when Rock and Scissors are played' do\n allow(player_1).to receive(:weapon) {:rock}\n allow(player_2).to receive(:weapon) {:scissors}\n expect(game.outcome).to eq :win\n end\n\n it 'returns Draw when Paper and Paper are played' do\n allow(player_1).to receive(:weapon) {:paper}\n allow(player_2).to receive(:weapon) {:paper}\n expect(game.outcome).to eq :draw\n end\n\n it 'returns Win when Paper and Scissors are played' do\n allow(player_1).to receive(:weapon) {:paper}\n allow(player_2).to receive(:weapon) {:scissors}\n expect(game.outcome).to eq :lose\n end\n\n it 'returns Draw when Scissors and Scissors are played' do\n allow(player_1).to receive(:weapon) {:paper}\n allow(player_2).to receive(:weapon) {:paper}\n expect(game.outcome).to eq :draw\n end\n\n it 'returns Draw when Spock and Spock are played' do\n allow(player_1).to receive(:weapon) {:spock}\n allow(player_2).to receive(:weapon) {:spock}\n expect(game.outcome).to eq :draw\n end\n\n it 'returns Win when Spock and Rock are played' do\n allow(player_1).to receive(:weapon) {:spock}\n allow(player_2).to receive(:weapon) {:rock}\n expect(game.outcome).to eq :win\n end\n\n it 'returns Lose when Spock and Paper are played' do\n allow(player_1).to receive(:weapon) {:spock}\n allow(player_2).to receive(:weapon) {:paper}\n expect(game.outcome).to eq :lose\n end\n\n it 'returns Win when Spock and Scissors are played' do\n allow(player_1).to receive(:weapon) {:spock}\n allow(player_2).to receive(:weapon) {:scissors}\n expect(game.outcome).to eq :win\n end\n\n it 'returns Lose when Spock and Lizard are played' do\n allow(player_1).to receive(:weapon) {:spock}\n allow(player_2).to receive(:weapon) {:lizard}\n expect(game.outcome).to eq :lose\n end\n\n it 'returns Lose when Lizard and Rock are played' do\n allow(player_1).to receive(:weapon) {:lizard}\n allow(player_2).to receive(:weapon) {:rock}\n expect(game.outcome).to eq :lose\n end\n\n it 'returns Win when Lizard and Paper are played' do\n allow(player_1).to receive(:weapon) {:lizard}\n allow(player_2).to receive(:weapon) {:paper}\n expect(game.outcome).to eq :win\n end\n\n it 'returns Lose when Lizard and Scissors are played' do\n allow(player_1).to receive(:weapon) {:lizard}\n allow(player_2).to receive(:weapon) {:scissors}\n expect(game.outcome).to eq :lose\n end\n\n it 'returns Draw when Lizard and Lizard are played' do\n allow(player_1).to receive(:weapon) {:lizard}\n allow(player_2).to receive(:weapon) {:lizard}\n expect(game.outcome).to eq :draw\n end\n end\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975491,"cells":{"blob_id":{"kind":"string","value":"8d720dd72fa3e5d80b152165b2b6cc963602d1a2"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"charlesduan/photobook"},"path":{"kind":"string","value":"/test/test_layout.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2066,"string":"2,066"},"score":{"kind":"number","value":2.671875,"string":"2.671875"},"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 'photobook'\nrequire 'minitest/autorun'\nrequire_relative 'helper'\n\nclass TestLayout < Minitest::Unit::TestCase\n\n include TestHelper\n\n def test_new\n try_cases(\n [ 1, 'h', 1, [ :h ] ],\n [ 2, 'hlvpa*', 6, [ :h, :h, :v, :v, :a, :a ] ],\n [ 1, 'hhhh', 4, [ :h, :h, :h, :h ] ]\n ) do |pages, pat, exp_used, exp_pat|\n pp = Photobook::Layout.new(\n 'test layout',\n 'pages' => pages,\n 'pattern' => pat,\n )\n assert_equal('test layout', pp.name)\n assert_equal(pages, pp.pages_used)\n assert_equal(exp_used, pp.photos_used)\n assert_equal(exp_pat, pp.pattern)\n end\n end\n\n def make_photos(orient)\n count = 0\n return orient.split('').map { |x|\n count += 1\n Photobook::Photo.new(\"Photo #{count}\", x.to_sym)\n }\n end\n\n def test_match_fail\n try_cases(\n [ 'v', '' ],\n [ 'v', 'h' ],\n [ 'v', 'vv' ],\n [ 'a', '' ],\n [ 'a', 'hv' ],\n ) do |pat, orient|\n photos = make_photos(orient)\n pp = Photobook::Layout.new('test layout', 'pattern' => pat)\n assert_nil(pp.match(photos), 'Match not expected')\n end\n end\n\n def test_match_success\n try_cases(\n [ 'h', 'h', '1' ],\n [ 'v', 'v', '1' ],\n [ 'a', 'h', '1' ],\n [ 'a', 'v', '1' ],\n [ 'aa', 'hv', '12' ],\n [ 'ah', 'hh', '12' ],\n [ 'ah', 'hv', '21' ],\n [ 'ah', 'vh', '12' ],\n [ 'aaav', 'vvhh', '1342' ],\n [ 'aaavh', 'vvvhh', '12435' ],\n [ 'aaavh', 'vvhhh', '13425' ],\n [ 'vhaaa', 'hhhvv', '41235' ],\n [ 'vvvhhh', 'hhhvvv', '456123' ]\n ) do |pat, orient, exp|\n photos = make_photos(orient)\n pp = Photobook::Layout.new('test layout', 'pattern' => pat)\n res = pp.match(photos)\n refute_nil(res, \"Match expected but not found\")\n assert_instance_of(Array, res)\n assert_equal(exp.length, res.count)\n res.zip(exp.split('')).each do |res_photo, exp_photo|\n assert_instance_of(Photobook::Photo, res_photo)\n assert_equal(\"Photo #{exp_photo}\", res_photo.name)\n end\n end\n end\n\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975492,"cells":{"blob_id":{"kind":"string","value":"64bcb50deadf3c0e8ced8898130504bc02e4657f"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"jaredonline/Ruby-Prolog-Solutions"},"path":{"kind":"string","value":"/spec/01.Lists/03.kth_element_spec.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":840,"string":"840"},"score":{"kind":"number","value":3.28125,"string":"3.28125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"require '01.Lists/03.kth_element'\n\ndescribe LinkedList do\n \n before do\n @list = LinkedList.new(1)\n @list.next = LinkedList.new(2)\n @list.next.next = LinkedList.new(3)\n @list.next.next.next = LinkedList.new(4)\n end\n \n context 'OO' do\n [1, 2, 3, 4].each_with_index do |element, index|\n index += 1 # Prolog wants the first element to be 1; Ruby wants it to be 0\n it \"should return #{element} for the index #{index}\" do\n @list[index].value.should == element \n end\n end\n end\n \n context 'functional' do\n [1, 2, 3, 4].each_with_index do |element, index|\n index += 1 # Prolog wants the first element to be 1; Ruby wants it to be 0\n it \"should return #{element} for the index #{index}\" do\n functional_kth_element(@list, index).value.should == element\n end\n end\n end\n \nend"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975493,"cells":{"blob_id":{"kind":"string","value":"edd9c752ca9790f83ac9e3ce2ca63760f8b340df"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"kalkrishnan/PhatStatsServer"},"path":{"kind":"string","value":"/lib/news/news_factory.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1399,"string":"1,399"},"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 'set'\nrequire 'mechanize'\nrequire 'json'\nrequire 'lib/util/word_count'\n\nrequire_relative 'news'\n\nclass NewsFactory\n\n\n def initialize()\n\n @news = Set.new\n @wordCount = WordCount.new\n end\n\n def get_top_news\n\n if(!@news.empty?)\n json_news\n elsif\n build_news_repo\n end\n end\n\n\n def build_news_repo url\n json_news = JSON.parse(get_rss_feed url)\n\n json_news[\"entry\"].each do |entry|\n @news.add(News.new(entry[\"title\"],entry[\"summary\"],entry[\"creator\"],entry[\"images\"]))\n end\n\n get_json_news\n end\n\n def build_player_news_repo url\n json_news = JSON.parse(get_rss_feed url)\n\n json_news[\"channel\"][\"item\"].first(9).each do |entry|\n\n url = entry[\"link\"].split(\"url=\")[1]\n\n if(url.include? \"com\")\n url = url[0...url.index(\"com/\")+3]\n elsif(url.include? \"ca\")\n url = url[0...url.index(\"ca/\")+3]\n end\n\n @news.add(News.new(entry[\"title\"],entry[\"description\"][\"content\"], url, nil))\n end\n\n get_json_news\n end\n\n def get_json_news\n String news = \"[{\\\"topic\\\":\\\"news\\\",\\\"items\\\":[\";\n i = 0;\n\n @news.each{|news_entry|\n\n news = news + news_entry.to_json+ \",\";\n }\n news = news[0..-2] +\"]}]\"\n end\n\n def get_rss_feed(url)\n\n rss = open(url).read\n js = XmlSimple.xml_in rss, { 'ForceArray' => false, 'KeyToSymbol' => true}\n\n JSON.pretty_generate(js)\n\n end\n\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975494,"cells":{"blob_id":{"kind":"string","value":"4f379f53b07533075fd868da1e459168b33d6f30"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"aijoskobi/class_two"},"path":{"kind":"string","value":"/hr/hr.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":949,"string":"949"},"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":"require 'employee'\nrequire 'salaried_employee'\nrequire 'hourly_employee'\n\nclass HumanResources\n \n def initialize()\n @employee_list = []\n @employee_list << HourlyEmployee.new(\"George\", \"Monkey\", 10)\n @employee_list << HourlyEmployee.new(\"Sally\", \"Summers\", 12)\n @employee_list << HourlyEmployee.new(\"Thomas\", \"Tank\", 18) \n @employee_list << SalariedEmployee.new(\"Dora\", \"el Exlorer\", 40000)\n end\n\n def run_payroll(week, hours)\n puts \"\\nFor week #{week} payroll\"\n @employee_list.each do |employee|\n print_employee_paycheck(employee, hours)\n end\n end\n\n def print_employee_list\n @employee_list.each { |employee| puts employee }\n end\n \n private\n def print_employee_paycheck(employee, hours)\n puts \"#{employee.fname} will be paid #{employee.pay(hours)}\"\n end\n\nend\n\n# hr = HumanResources.new\n# hr.employee_list\n# \n# hr.run_payroll(\"one\", 40)\n# hr.run_payroll(\"two\", 32)\n# hr.run_payroll(\"three with overtime\", 45)\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975495,"cells":{"blob_id":{"kind":"string","value":"fbd437980082b1a548971cb6d49e01418d7131b3"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"La-Pulga/Learn-Ruby-the-Hard-way"},"path":{"kind":"string","value":"/ex19bis.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":418,"string":"418"},"score":{"kind":"number","value":4.28125,"string":"4.28125"},"int_score":{"kind":"number","value":4,"string":"4"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"def kiss_away(kiss1, kiss2)\n\tputs \" I'd like to give you a kiss #{kiss1}\"\n\tputs \"Me too! #{kiss2}\"\n\tputs \"We can't do it both\"\n\tputs \"Yeah we can!\\n\"\nend\n\nputs \"-------How many ways are there to do this?-------\"\nkiss_away(':*', \"xxx\")\t\n\nputs \"--------------Using variables-------------\"\nkiss1 = \":*\"\nkiss2 = \"xxx\"\n\nkiss_away(kiss1, kiss2)\n\nputs \"--------Doing maths with love-------------\"\nkiss_away(kiss1 * 3, kiss2)\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975496,"cells":{"blob_id":{"kind":"string","value":"897cff2c8ae89145646f73de400c814f9ae6dead"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"helenndoo/collections_practice-v-000"},"path":{"kind":"string","value":"/collections_practice.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1173,"string":"1,173"},"score":{"kind":"number","value":4.40625,"string":"4.40625"},"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":"#1 array of integers and returns a copy of array in ascending order\ndef sort_array_asc(array)\n array.sort do |a, b|\n a <=> b\n end\nend\n#2 same, but in descending order\ndef sort_array_desc(array)\n array.sort do |b, a|\n a <=> b\n end\nend\n#3 ascending order by length\ndef sort_array_char_count(array)\n array.sort_by do |word|\n word.length\n end\nend\n#4 swap 2nd and 3rd elements\ndef swap_elements(array)\n element1 = array[1]\n element2 = array[2]\n array = [array[0], array[2], array[1]]\nend\n#5 reverse array\ndef reverse_array(array)\n array.reverse\nend\n#6 takes array of strings and replaces 3rd character in each\n# --- with dollar sign ke$ha style jesus\ndef kesha_maker(array)\n array.each do |string|\n string[2] = \"$\"\n end\nend\n#7 find A using start_with\ndef find_a(array)\n array.select do |word|\n word[0] == \"a\" #= changes, == finds\n end\nend\n#8 adds all intergers together and returns sum\ndef sum_array(array)\n array.inject do |a, b|\n a += b #a = a + b\n end\nend\n#9 add s to each word except for 2nd element\ndef add_s(array)\n array.each_with_index.collect do |word, index|\n if index == 1\n word\n else\n word << \"s\"\n end\n end\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975497,"cells":{"blob_id":{"kind":"string","value":"28b7eab9395d29129975907f8c9581c2b373771c"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"kimdcottrell/sombra"},"path":{"kind":"string","value":"/script/arg_guesses/numani_flights/test_flightboard.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":664,"string":"664"},"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":"#!/usr/bin/env ruby\nrequire_relative '../../../module/data_dump'\n\nDataDump::FLIGHT_LIST.each do |fl|\n abbr = fl[:flight_abbr]\n num = fl[:flight_num]\n\n time_raw = fl[:time]\n time = time_raw.split(\":\")\n time[0].rjust(2,'0')\n time[1].rjust(2,'0')\n\n##XOR num by zerofilled time\n print (num[0].to_i ^ time[0].to_i).chr\n print (num[1].to_i ^ time[1].to_i).chr\n print (num[2].to_i ^ time[2].to_i).chr\n print (num[3].to_i ^ time[3].to_i).chr\n\n##XOR abbr by num\n# print (abbr[0].hex ^ num[0..1].to_i).chr\n# print (abbr[1].hex ^ num[2..3].to_i).chr\n\n##XOR num by abbr\n# print (num[0..1].to_i ^ abbr[0].hex).chr\n# print (num[2..3].to_i ^ abbr[1].hex).chr\n\n\nend\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975498,"cells":{"blob_id":{"kind":"string","value":"2fc72f45a48108a34da39f702e7c593e0535c722"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"atjohnfeng/aa_homework"},"path":{"kind":"string","value":"/W3D5/map.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":750,"string":"750"},"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":"class Map\n\n def initialize\n @map = []\n end\n\n def set(key, value)\n map.each_with_index do |defin|\n if defin[0] == key\n defin[1] == value\n return true\n end\n end\n map << [key, value]\n self\n end\n\n def get(key)\n map.each_with_index do |defin,i|\n if defin[0] == key\n return map[i][1]\n end\n end\n end\n\n def delete(key)\n map.each_with_index do |defin,i|\n if defin[0] == key\n map.delete_at(i)\n end\n end\n end\n\n def show\n map.dup\n end\n\n def inspect\n \"#Map:#{self.object_id}\"\n end\n\n private\n \n attr_reader :map\n\nend"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975499,"cells":{"blob_id":{"kind":"string","value":"44778d4ff6e044f898189d54c93498362fa82e11"},"language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"jasondegraw/AFN2017"},"path":{"kind":"string","value":"/scripts/buildAFNtest.rb"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":68222,"string":"68,222"},"score":{"kind":"number","value":2.65625,"string":"2.65625"},"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 'openstudio'\n#\n#\n# +-------------------------------------------------------------+\n# | Surface_15 |\n# | |\n# | |\n# | north_space |\n# | north_zone |\n# | Surface_14 Surface_16 |\n# | Floor: Surface_19 |\n# | Roof: Surface_20 |\n# | |\n# | |\n# | Surface_17 Surface_18 |\n# +------------------------------+------------------------------+\n# | Surface_3 | Surface_11 |\n# | | |\n# | west_space | east_space |\n# | west_zone | east_zone |\n# | | |\n# | Surface_2 Surface_4 | Surface_10 Surface_9 |\n# | | |\n# | Floor: Surface_5 | Floor: Surface_12 |\n# | Roof: Surface_6 | Roof: Surface_13 |\n# | | |\n# | Surface_1 | Surface_8 |\n# +------------------------------+------------------------------+\n#\n#\n#\n#\n#\n#\n#\nclass SurfaceVisitor\n attr_reader :summary\n\n def initialize(model)\n setup(model)\n run(model)\n shutdown(model)\n end\n\n def setup(model)\n end\n\n def run(model)\n allsurfs = model.getSurfaces()\n @surfs = []\n for surf in allsurfs do\n if !@surfs.include?(surf) then\n other = surf.adjacentSurface()\n if !other.empty?() then\n if !@surfs.include?(other.get()) then\n # This is an interior surface\n stype = surf.surfaceType()\n @surfs << surf\n if stype == 'Floor' then\n interiorFloor(model, surf, other.get())\n elsif stype == 'RoofCeiling' then\n interiorRoofCeiling(model, surf, other.get())\n else\n interiorWall(model, surf, other.get())\n end\n end\n else\n # This is an exterior surface\n @surfs << surf\n exteriorSurface(model, surf)\n end\n end\n end\n end\n\n def interiorFloor(model, surface, adjacentSurface)\n end\n\n def interiorWall(model, surface, adjacentSurface)\n end\n\n def interiorRoofCeiling(model, surface, adjacentSurface)\n end\n\n def exteriorSurface(model, surface)\n end\n\n def shutdown(model)\n @summary = 'Visited ' + @surfs.size().to_s() + ' surfaces'\n end\n\nend\n\nclass SurfaceNetworkBuilder < SurfaceVisitor\n def initialize(model, interiorCrack, exteriorCrack, scaleByArea=false)\n @interiorCrack = interiorCrack\n if interiorCrack == nil then\n @interiorCrack = OpenStudio::Model::AirflowNetworkCrack.new(model, 1.0) # Need to fix multiplier!\n end\n @exteriorCrack = exteriorCrack\n if interiorCrack == nil then\n @exteriorCrack = OpenStudio::Model::AirflowNetworkCrack.new(model, 1.0) # Need to fix multiplier!\n end\n @scaleByArea = scaleByArea\n super(model)\n end\n\n def interiorFloor(model, surface, adjacentSurface)\n if !surface.outsideBoundaryCondition().start_with?('Ground') then\n # Create a surface linkage\n link = OpenStudio::Model::AirflowNetworkSurface.new(model,surface,@interiorCrack)\n end\n end\n\n def interiorRoofCeiling(model, surface, adjacentSurface)\n # Create a surface linkage\n link = OpenStudio::Model::AirflowNetworkSurface.new(model,surface,@interiorCrack)\n end\n\n def interiorWall(model, surface, adjacentSurface)\n # Create a surface linkage\n link = OpenStudio::Model::AirflowNetworkSurface.new(model,surface,@interiorCrack)\n end\n\n def exteriorSurface(model, surface)\n # Create an external node\n # Create a surface linkage\n link = OpenStudio::Model::AirflowNetworkSurface.new(model,surface,@exteriorCrack)\n end\nend\n\ndef addSurfaceCracks(model, intcrack, extcrack, scaledByArea=false)\n allsurfs = model.getSurfaces()\n surfs = []\n for surf in allsurfs do\n if !surfs.include?(surf) then\n other = surf.adjacentSurface()\n if !other.empty?() then\n if !surfs.include?(other.get()) then\n # This is an interior surface\n surfs << surf\n end\n else\n # This is an exterior surface\n surfs << surf\n end\n end\n end\n puts surfs.size()\n #puts extsurfs.size()\nend\n\nmodel = OpenStudio::Model::Model.new()\n\n# Material,A1 - 1 IN STUCCO,Smooth,2.5389841E-02,0.6918309,1858.142,836.8000,0.9000000,0.9200000,0.9200000\nstucco = OpenStudio::Model::StandardOpaqueMaterial.new(model, \"Smooth\", 2.5389841E-02, 0.6918309, 1858.142, 836.8)\nstucco.setThermalAbsorptance(0.9)\nstucco.setSolarAbsorptance(0.92)\nstucco.setVisibleAbsorptance(0.92)\n\n# Material,C4 - 4 IN COMMON BRICK,Rough,0.1014984,0.7264224,1922.216,836.8000,0.9000000,0.7600000,0.7600000\nbrick = OpenStudio::Model::StandardOpaqueMaterial.new(model, \"Rough\", 0.1014984, 0.7264224, 1922.216, 836.8)\nbrick.setThermalAbsorptance(0.9)\nbrick.setSolarAbsorptance(0.76)\nbrick.setVisibleAbsorptance(0.76)\n\n# Material,E1 - 3 / 4 IN PLASTER OR GYP BOARD,Smooth,1.905E-02,0.7264224,1601.846,836.8000,0.9000000,0.9200000,0.9200000\nwallboard = OpenStudio::Model::StandardOpaqueMaterial.new(model, \"Smooth\", 1.905E-02, 0.7264224, 1601.846, 836.8)\nwallboard.setThermalAbsorptance(0.92)\nwallboard.setSolarAbsorptance(0.92)\nwallboard.setVisibleAbsorptance(0.9)\n\n# Material,C6 - 8 IN CLAY TILE,Smooth,0.2033016,0.5707605,1121.292,836.8000,0.9000000,0.8200000,0.8200000\ntile = OpenStudio::Model::StandardOpaqueMaterial.new(model, \"Smooth\", 0.2033016, 0.5707605, 1121.292, 836.8)\ntile.setThermalAbsorptance(0.82)\ntile.setSolarAbsorptance(0.82)\ntile.setVisibleAbsorptance(0.9)\n\n# Material,C10 - 8 IN HW CONCRETE,MediumRough,0.2033016,1.729577,2242.585,836.8000,0.9000000,0.6500000,0.6500000\nconcrete8 = OpenStudio::Model::StandardOpaqueMaterial.new(model, \"MediumRough\", 0.2033016, 1.729577, 2242.585, 836.8)\nconcrete8.setThermalAbsorptance(0.65)\nconcrete8.setSolarAbsorptance(0.65)\nconcrete8.setVisibleAbsorptance(0.9)\n\n# Material,E2 - 1 / 2 IN SLAG OR STONE,Rough,1.2710161E-02,1.435549,881.0155,1673.600,0.9000000,0.5500000,0.5500000\nstone = OpenStudio::Model::StandardOpaqueMaterial.new(model, \"Rough\", 1.2710161E-02, 1.435549, 881.0155, 1673.6)\nstone.setThermalAbsorptance(0.55)\nstone.setSolarAbsorptance(0.55)\nstone.setVisibleAbsorptance(0.9)\n\n# Material,E3 - 3 / 8 IN FELT AND MEMBRANE,Rough,9.5402403E-03,0.1902535,1121.292,1673.600,0.9000000,0.7500000,0.7500000\nmembrane = OpenStudio::Model::StandardOpaqueMaterial.new(model, \"Rough\", 9.5402403E-03, 0.1902535, 1121.292, 1673.6)\nmembrane.setThermalAbsorptance(0.75)\nmembrane.setSolarAbsorptance(0.75)\nmembrane.setVisibleAbsorptance(0.9)\n\n# Material,B5 - 1 IN DENSE INSULATION,VeryRough,2.5389841E-02,4.3239430E-02,91.30524,836.8000,0.9000000,0.5000000,0.5000000\ninsulation = OpenStudio::Model::StandardOpaqueMaterial.new(model, \"VeryRough\", 2.5389841E-02, 4.3239430E-02, 91.30524, 836.8)\ninsulation.setThermalAbsorptance(0.5)\ninsulation.setSolarAbsorptance(0.5)\ninsulation.setVisibleAbsorptance(0.9)\n\n# Material,C12 - 2 IN HW CONCRETE,MediumRough,5.0901599E-02,1.729577,2242.585,836.8000,0.9000000,0.6500000,0.6500000\nconcrete2 = OpenStudio::Model::StandardOpaqueMaterial.new(model, \"MediumRough\", 5.0901599E-02, 1.729577, 2242.585, 836.8)\nconcrete2.setThermalAbsorptance(0.65)\nconcrete2.setSolarAbsorptance(0.65)\nconcrete2.setVisibleAbsorptance(0.9)\n\n# Material,1.375in-Solid-Core,Smooth,3.4925E-02,0.1525000,614.5000,1630.0000,0.9000000,0.9200000,0.9200000\nsolidcore = OpenStudio::Model::StandardOpaqueMaterial.new(model, \"Smooth\", 3.4925E-02, 0.1525, 614.50, 1630.0)\nsolidcore.setThermalAbsorptance(0.92)\nsolidcore.setSolarAbsorptance(0.92)\nsolidcore.setVisibleAbsorptance(0.9)\n\n# WindowMaterial:Glazing,WIN-LAY-GLASS-LIGHT,SpectralAverage,0.0025,0.850,0.075,0.075,0.901,0.081,0.081,0.0,0.84,0.84,0.9\nglazing = OpenStudio::Model::StandardGlazing.new(model, \"SpectralAverage\", 0.0025)\nglazing.setSolarTransmittanceatNormalIncidence(0.850)\nglazing.setFrontSideSolarReflectanceatNormalIncidence(0.075)\nglazing.setBackSideSolarReflectanceatNormalIncidence(0.075)\nglazing.setVisibleTransmittanceatNormalIncidence(0.901)\nglazing.setFrontSideVisibleReflectanceatNormalIncidence(0.081)\nglazing.setBackSideVisibleReflectanceatNormalIncidence(0.08)\nglazing.setInfraredTransmittanceatNormalIncidence(0.0)\nglazing.setFrontSideInfraredHemisphericalEmissivity(0.84)\nglazing.setBackSideInfraredHemisphericalEmissivity(0.84)\nglazing.setConductivity(0.9)\n\nmaterials = OpenStudio::Model::OpaqueMaterialVector.new()\n\n# Construction,DOOR-CON,1.375in-Solid-Core\nmaterials << solidcore\ndoor = OpenStudio::Model::Construction.new(materials)\n\n# Construction,EXTWALL80,A1 - 1 IN STUCCO,C4 - 4 IN COMMON BRICK,E1 - 3 / 4 IN PLASTER OR GYP BOARD\nmaterials.clear()\nmaterials << stucco\nmaterials << brick\nmaterials << wallboard\nextwall = OpenStudio::Model::Construction.new(materials)\n\n# Construction,PARTITION06,E1 - 3 / 4 IN PLASTER OR GYP BOARD,C6 - 8 IN CLAY TILE,E1 - 3 / 4 IN PLASTER OR GYP BOARD\nmaterials.clear()\nmaterials << wallboard\nmaterials << tile\nmaterials << wallboard\npartition = OpenStudio::Model::Construction.new(materials)\n\n# Construction,FLOOR SLAB 8 IN,C10 - 8 IN HW CONCRETE\nmaterials.clear()\nmaterials << concrete8\nfloorslab = OpenStudio::Model::Construction.new(materials)\n\n# Construction,ROOF34,E2 - 1 / 2 IN SLAG OR STONE,E3 - 3 / 8 IN FELT AND MEMBRANE,B5 - 1 IN DENSE INSULATION,C12 - 2 IN HW CONCRETE\nmaterials.clear()\nmaterials << stone\nmaterials << membrane\nmaterials << insulation\nmaterials << concrete2\nroof = OpenStudio::Model::Construction.new(materials)\n\n# Construction,WIN-CON-LIGHT,WIN-LAY-GLASS-LIGHT\n#materials = OpenStudio::Model::StandardGlazingVector.new()\nmaterials = OpenStudio::Model::FenestrationMaterialVector.new()\nmaterials.clear()\nmaterials << glazing\nlightwindow = OpenStudio::Model::Construction.new(materials)\n\npoints = OpenStudio::Point3dVector.new\n\n# BuildingSurface:Detailed,Surface_1,WALL,EXTWALL80,WEST_ZONE,Outdoors,,SunExposed,WindExposed,0.5000000,4,0,0,3.048000,0,0,0,6.096000,0,0,6.096000,0,3.048000\npoints << OpenStudio::Point3d.new(0, 0, 3.048000)\npoints << OpenStudio::Point3d.new(0, 0, 0)\npoints << OpenStudio::Point3d.new(6.096000, 0, 0)\npoints << OpenStudio::Point3d.new(6.096000, 0, 3.048000)\nsurface_1 = OpenStudio::Model::Surface.new(points, model)\nsurface_1.setSurfaceType(\"WALL\")\nsurface_1.setSunExposure(\"SunExposed\")\nsurface_1.setWindExposure(\"WindExposed\")\nsurface_1.setViewFactortoGround(0.5000000)\n# BuildingSurface:Detailed,Surface_2,WALL,EXTWALL80,WEST_ZONE,Outdoors,,SunExposed,WindExposed,0.5000000,4,0,6.096000,3.048000,0,6.096000,0,0,0,0,0,0,3.048000\npoints.clear\npoints << OpenStudio::Point3d.new(0, 6.096000, 3.048000)\npoints << OpenStudio::Point3d.new(0, 6.096000, 0)\npoints << OpenStudio::Point3d.new(0, 0, 0)\npoints << OpenStudio::Point3d.new(0, 0, 3.048000)\nsurface_2 = OpenStudio::Model::Surface.new(points, model)\nsurface_2.setSurfaceType(\"WALL\")\nsurface_2.setSunExposure(\"SunExposed\")\nsurface_2.setWindExposure(\"WindExposed\")\nsurface_2.setViewFactortoGround(0.5000000)\n# BuildingSurface:Detailed,Surface_3,WALL,PARTITION06,WEST_ZONE,Surface,Surface_17,NoSun,NoWind,0.5000000,4,6.096000,6.096000,3.048000,6.096000,6.096000,0,0,6.096000,0,0,6.096000,3.048000\npoints.clear\npoints << OpenStudio::Point3d.new(6.096000, 6.096000, 3.048000)\npoints << OpenStudio::Point3d.new(6.096000, 6.096000, 0)\npoints << OpenStudio::Point3d.new(0, 6.096000, 0)\npoints << OpenStudio::Point3d.new(0, 6.096000, 3.048000)\nsurface_3 = OpenStudio::Model::Surface.new(points, model)\nsurface_3.setSurfaceType(\"WALL\")\nsurface_3.setSunExposure(\"NoSun\")\nsurface_3.setWindExposure(\"NoWind\")\nsurface_3.setViewFactortoGround(0.5000000)\n# BuildingSurface:Detailed,Surface_4,WALL,PARTITION06,WEST_ZONE,Surface,Surface_10,NoSun,NoWind,0.5000000,4,6.096000,0,3.048000,6.096000,0,0,6.096000,6.096000,0,6.096000,6.096000,3.048000\npoints.clear\npoints << OpenStudio::Point3d.new(6.096000, 0, 3.048000)\npoints << OpenStudio::Point3d.new(6.096000, 0, 0)\npoints << OpenStudio::Point3d.new(6.096000, 6.096000, 0)\npoints << OpenStudio::Point3d.new(6.096000, 6.096000, 3.048000)\nsurface_4 = OpenStudio::Model::Surface.new(points, model)\nsurface_4.setSurfaceType(\"WALL\")\nsurface_4.setSunExposure(\"NoSun\")\nsurface_4.setWindExposure(\"NoWind\")\nsurface_4.setViewFactortoGround(0.5000000)\n# BuildingSurface:Detailed,Surface_5,FLOOR,FLOOR SLAB 8 IN,WEST_ZONE,Surface,Surface_5,NoSun,NoWind,1.000000,4,0,0,0,0,6.096000,0,6.096000,6.096000,0,6.096000,0,0\npoints.clear\npoints << OpenStudio::Point3d.new(0, 0, 0)\npoints << OpenStudio::Point3d.new(0, 6.096000, 0)\npoints << OpenStudio::Point3d.new(6.096000, 6.096000, 0)\npoints << OpenStudio::Point3d.new(6.096000, 0, 0)\nsurface_5 = OpenStudio::Model::Surface.new(points, model)\nsurface_5.setSurfaceType(\"FLOOR\")\nsurface_5.setSunExposure(\"NoSun\")\nsurface_5.setWindExposure(\"NoWind\")\nsurface_5.setViewFactortoGround(1.000000)\n# BuildingSurface:Detailed,Surface_6,ROOF,ROOF34,WEST_ZONE,Outdoors,,SunExposed,WindExposed,0,4,0,6.096000,3.048000,0,0,3.048000,6.096000,0,3.048000,6.096000,6.096000,3.048000\npoints.clear\npoints << OpenStudio::Point3d.new(0, 6.096000, 3.048000)\npoints << OpenStudio::Point3d.new(0, 0, 3.048000)\npoints << OpenStudio::Point3d.new(6.096000, 0, 3.048000)\npoints << OpenStudio::Point3d.new(6.096000, 6.096000, 3.048000)\nsurface_6 = OpenStudio::Model::Surface.new(points, model)\nsurface_6.setSurfaceType(\"ROOF\")\nsurface_6.setSunExposure(\"SunExposed\")\nsurface_6.setWindExposure(\"WindExposed\")\nsurface_6.setViewFactortoGround(0)\n# BuildingSurface:Detailed,Surface_8,WALL,EXTWALL80,EAST_ZONE,Outdoors,,SunExposed,WindExposed,0.5000000,4,6.096000,0,3.048000,6.096000,0,0,12.19200,0,0,12.19200,0,3.048000\npoints.clear\npoints << OpenStudio::Point3d.new(6.096000, 0, 3.048000)\npoints << OpenStudio::Point3d.new(6.096000, 0, 0)\npoints << OpenStudio::Point3d.new(12.19200, 0, 0)\npoints << OpenStudio::Point3d.new(12.19200, 0, 3.048000)\nsurface_8 = OpenStudio::Model::Surface.new(points, model)\nsurface_8.setSurfaceType(\"WALL\")\nsurface_8.setSunExposure(\"SunExposed\")\nsurface_8.setWindExposure(\"WindExposed\")\nsurface_8.setViewFactortoGround(0.5000000)\n# BuildingSurface:Detailed,Surface_9,WALL,EXTWALL80,EAST_ZONE,Outdoors,,SunExposed,WindExposed,0.5000000,4,12.19200,0,3.048000,12.19200,0,0,12.19200,6.096000,0,12.19200,6.096000,3.048000\npoints.clear\npoints << OpenStudio::Point3d.new(12.19200, 0, 3.048000)\npoints << OpenStudio::Point3d.new(12.19200, 0, 0)\npoints << OpenStudio::Point3d.new(12.19200, 6.096000, 0)\npoints << OpenStudio::Point3d.new(12.19200, 6.096000, 3.048000)\nsurface_9 = OpenStudio::Model::Surface.new(points, model)\nsurface_9.setSurfaceType(\"WALL\")\nsurface_9.setSunExposure(\"SunExposed\")\nsurface_9.setWindExposure(\"WindExposed\")\nsurface_9.setViewFactortoGround(0.5000000)\n# BuildingSurface:Detailed,Surface_10,WALL,PARTITION06,EAST_ZONE,Surface,Surface_4,NoSun,NoWind,0.5000000,4,6.096000,6.096000,3.048000,6.096000,6.096000,0,6.096000,0,0,6.096001,0,3.048000\npoints.clear\npoints << OpenStudio::Point3d.new(6.096000, 6.096000, 3.048000)\npoints << OpenStudio::Point3d.new(6.096000, 6.096000, 0)\npoints << OpenStudio::Point3d.new(6.096000, 0, 0)\npoints << OpenStudio::Point3d.new(6.096001, 0, 3.048000)\nsurface_10 = OpenStudio::Model::Surface.new(points, model)\nsurface_10.setSurfaceType(\"WALL\")\nsurface_10.setSunExposure(\"NoSun\")\nsurface_10.setWindExposure(\"NoWind\")\nsurface_10.setViewFactortoGround(0.5000000)\n# BuildingSurface:Detailed,Surface_11,WALL,PARTITION06,EAST_ZONE,Surface,Surface_18,NoSun,NoWind,0.5000000,4,12.19200,6.096000,3.048000,12.19200,6.096000,0,6.096000,6.096000,0,6.096000,6.096000,3.048000\npoints.clear\npoints << OpenStudio::Point3d.new(12.19200, 6.096000, 3.048000)\npoints << OpenStudio::Point3d.new(12.19200, 6.096000, 0)\npoints << OpenStudio::Point3d.new(6.096000, 6.096000, 0)\npoints << OpenStudio::Point3d.new(6.096000, 6.096000, 3.048000)\nsurface_11 = OpenStudio::Model::Surface.new(points, model)\nsurface_11.setSurfaceType(\"WALL\")\nsurface_11.setSunExposure(\"NoSun\")\nsurface_11.setWindExposure(\"NoWind\")\nsurface_11.setViewFactortoGround(0.5000000)\n# BuildingSurface:Detailed,Surface_12,FLOOR,FLOOR SLAB 8 IN,EAST_ZONE,Surface,Surface_12,NoSun,NoWind,1.000000,4,6.096000,0,0,6.096000,6.096000,0,12.19200,6.096000,0,12.19200,0,0\npoints.clear\npoints << OpenStudio::Point3d.new(6.096000, 0, 0)\npoints << OpenStudio::Point3d.new(6.096000, 6.096000, 0)\npoints << OpenStudio::Point3d.new(12.19200, 6.096000, 0)\npoints << OpenStudio::Point3d.new(12.19200, 0, 0)\nsurface_12 = OpenStudio::Model::Surface.new(points, model)\nsurface_12.setSurfaceType(\"FLOOR\")\nsurface_12.setSunExposure(\"NoSun\")\nsurface_12.setWindExposure(\"NoWind\")\nsurface_12.setViewFactortoGround(1.000000)\n# BuildingSurface:Detailed,Surface_13,ROOF,ROOF34,EAST_ZONE,Outdoors,,SunExposed,WindExposed,0,4,6.096000,6.096000,3.048000,6.096000,0,3.048000,12.19200,0,3.048000,12.19200,6.096000,3.048000\npoints.clear\npoints << OpenStudio::Point3d.new(6.096000, 6.096000, 3.048000)\npoints << OpenStudio::Point3d.new(6.096000, 0, 3.048000)\npoints << OpenStudio::Point3d.new(12.19200, 0, 3.048000)\npoints << OpenStudio::Point3d.new(12.19200, 6.096000, 3.048000)\nsurface_13 = OpenStudio::Model::Surface.new(points, model)\nsurface_13.setSurfaceType(\"ROOF\")\nsurface_13.setSunExposure(\"SunExposed\")\nsurface_13.setWindExposure(\"WindExposed\")\nsurface_13.setViewFactortoGround(0)\n# BuildingSurface:Detailed,Surface_14,WALL,EXTWALL80,NORTH_ZONE,Outdoors,,SunExposed,WindExposed,0.5000000,4,0,12.19200,3.048000,0,12.19200,0,0,6.096000,0,0,6.096000,3.048000\npoints.clear\npoints << OpenStudio::Point3d.new(0, 12.19200, 3.048000)\npoints << OpenStudio::Point3d.new(0, 12.19200, 0)\npoints << OpenStudio::Point3d.new(0, 6.096000, 0)\npoints << OpenStudio::Point3d.new(0, 6.096000, 3.048000)\nsurface_14 = OpenStudio::Model::Surface.new(points, model)\nsurface_14.setSurfaceType(\"WALL\")\nsurface_14.setSunExposure(\"SunExposed\")\nsurface_14.setWindExposure(\"WindExposed\")\nsurface_14.setViewFactortoGround(0.5000000)\n# BuildingSurface:Detailed,Surface_15,WALL,EXTWALL80,NORTH_ZONE,Outdoors,,SunExposed,WindExposed,0.5000000,4,12.19200,12.19200,3.048000,12.19200,12.19200,0,0,12.19200,0,0,12.19200,3.048000\npoints.clear\npoints << OpenStudio::Point3d.new(12.19200, 12.19200, 3.048000)\npoints << OpenStudio::Point3d.new(12.19200, 12.19200, 0)\npoints << OpenStudio::Point3d.new(0, 12.19200, 0)\npoints << OpenStudio::Point3d.new(0, 12.19200, 3.048000)\nsurface_15 = OpenStudio::Model::Surface.new(points, model)\nsurface_15.setSurfaceType(\"WALL\")\nsurface_15.setSunExposure(\"SunExposed\")\nsurface_15.setWindExposure(\"WindExposed\")\nsurface_15.setViewFactortoGround(0.5000000)\n# BuildingSurface:Detailed,Surface_16,WALL,EXTWALL80,NORTH_ZONE,Outdoors,,SunExposed,WindExposed,0.5000000,4,12.19200,6.096000,3.048000,12.19200,6.096000,0,12.19200,12.19200,0,12.19200,12.19200,3.048000\npoints.clear\npoints << OpenStudio::Point3d.new(12.19200, 6.096000, 3.048000)\npoints << OpenStudio::Point3d.new(12.19200, 6.096000, 0)\npoints << OpenStudio::Point3d.new(12.19200, 12.19200, 0)\npoints << OpenStudio::Point3d.new(12.19200, 12.19200, 3.048000)\nsurface_16 = OpenStudio::Model::Surface.new(points, model)\nsurface_16.setSurfaceType(\"WALL\")\nsurface_16.setSunExposure(\"SunExposed\")\nsurface_16.setWindExposure(\"WindExposed\")\nsurface_16.setViewFactortoGround(0.5000000)\n# BuildingSurface:Detailed,Surface_17,WALL,PARTITION06,NORTH_ZONE,Surface,Surface_3,NoSun,NoWind,0.5000000,4,0.000,6.096,3.048,0.000,6.096,0.000,6.096,6.096,0.000,6.096,6.096,3.048\npoints.clear\npoints << OpenStudio::Point3d.new(0.000, 6.096, 3.048)\npoints << OpenStudio::Point3d.new(0.000, 6.096, 0.000)\npoints << OpenStudio::Point3d.new(6.096, 6.096, 0.000)\npoints << OpenStudio::Point3d.new(6.096, 6.096, 3.048)\nsurface_17 = OpenStudio::Model::Surface.new(points, model)\nsurface_17.setSurfaceType(\"WALL\")\nsurface_17.setSunExposure(\"NoSun\")\nsurface_17.setWindExposure(\"NoWind\")\nsurface_17.setViewFactortoGround(0.5000000)\n# BuildingSurface:Detailed,Surface_18,WALL,PARTITION06,NORTH_ZONE,Surface,Surface_11,NoSun,NoWind,0.5000000,4,6.096000,6.096000,3.048000,6.096000,6.096000,0,12.19200,6.096000,0,12.19200,6.096000,3.048000\npoints.clear\npoints << OpenStudio::Point3d.new(6.096000, 6.096000, 3.048000)\npoints << OpenStudio::Point3d.new(6.096000, 6.096000, 0)\npoints << OpenStudio::Point3d.new(12.19200, 6.096000, 0)\npoints << OpenStudio::Point3d.new(12.19200, 6.096000, 3.048000)\nsurface_18 = OpenStudio::Model::Surface.new(points, model)\nsurface_18.setSurfaceType(\"WALL\")\nsurface_18.setSunExposure(\"NoSun\")\nsurface_18.setWindExposure(\"NoWind\")\nsurface_18.setViewFactortoGround(0.5000000)\n# BuildingSurface:Detailed,Surface_19,FLOOR,FLOOR SLAB 8 IN,NORTH_ZONE,Surface,Surface_19,NoSun,NoWind,1.000000,4,0,6.096000,0,0,12.19200,0,12.19200,12.19200,0,12.19200,6.096000,0\npoints.clear\npoints << OpenStudio::Point3d.new(0, 6.096000, 0)\npoints << OpenStudio::Point3d.new(0, 12.19200, 0)\npoints << OpenStudio::Point3d.new(12.19200, 12.19200, 0)\npoints << OpenStudio::Point3d.new(12.19200, 6.096000, 0)\nsurface_19 = OpenStudio::Model::Surface.new(points, model)\nsurface_19.setSurfaceType(\"FLOOR\")\nsurface_19.setSunExposure(\"NoSun\")\nsurface_19.setWindExposure(\"NoWind\")\nsurface_19.setViewFactortoGround(1.000000)\n# BuildingSurface:Detailed,Surface_20,ROOF,ROOF34,NORTH_ZONE,Outdoors,,SunExposed,WindExposed,0,4,0,12.19200,3.048000,0,6.096000,3.048000,12.19200,6.096000,3.048000,12.19200,12.19200,3.048000\npoints.clear\npoints << OpenStudio::Point3d.new(0, 12.19200, 3.048000)\npoints << OpenStudio::Point3d.new(0, 6.096000, 3.048000)\npoints << OpenStudio::Point3d.new(12.19200, 6.096000, 3.048000)\npoints << OpenStudio::Point3d.new(12.19200, 12.19200, 3.048000)\nsurface_20 = OpenStudio::Model::Surface.new(points, model)\nsurface_20.setSurfaceType(\"ROOF\")\nsurface_20.setSunExposure(\"SunExposed\")\nsurface_20.setWindExposure(\"WindExposed\")\nsurface_20.setViewFactortoGround(0)\n\n# Set the constructions\nsurface_1.setConstruction(extwall)\nsurface_2.setConstruction(extwall)\nsurface_3.setConstruction(partition)\nsurface_4.setConstruction(partition)\nsurface_5.setConstruction(floorslab)\nsurface_6.setConstruction(roof)\n#surface_7.setConstruction(extwall)\nsurface_8.setConstruction(extwall)\nsurface_9.setConstruction(extwall)\nsurface_10.setConstruction(partition)\nsurface_11.setConstruction(partition)\nsurface_12.setConstruction(floorslab)\nsurface_13.setConstruction(roof)\nsurface_14.setConstruction(extwall)\nsurface_15.setConstruction(extwall)\nsurface_16.setConstruction(extwall)\nsurface_17.setConstruction(partition)\nsurface_18.setConstruction(partition)\nsurface_19.setConstruction(floorslab)\nsurface_20.setConstruction(roof)\n\n# Connect the surfaces together\nsurface_3.setAdjacentSurface(surface_17)\nsurface_4.setAdjacentSurface(surface_10)\nsurface_11.setAdjacentSurface(surface_18)\n\n# Make spaces and thermal zones\nwest_space = OpenStudio::Model::Space.new(model)\nwest_zone = OpenStudio::Model::ThermalZone.new(model)\neast_space = OpenStudio::Model::Space.new(model)\neast_zone = OpenStudio::Model::ThermalZone.new(model)\nnorth_space = OpenStudio::Model::Space.new(model)\nnorth_zone = OpenStudio::Model::ThermalZone.new(model)\n\n# Connect spaces and surfaces\nsurface_1.setSpace(west_space)\nsurface_2.setSpace(west_space)\nsurface_3.setSpace(west_space)\nsurface_4.setSpace(west_space)\nsurface_5.setSpace(west_space)\nsurface_6.setSpace(west_space)\n\nsurface_8.setSpace(east_space)\nsurface_9.setSpace(east_space)\nsurface_10.setSpace(east_space)\nsurface_11.setSpace(east_space)\nsurface_12.setSpace(east_space)\nsurface_13.setSpace(east_space)\n\nsurface_14.setSpace(north_space)\nsurface_15.setSpace(north_space)\nsurface_16.setSpace(north_space)\nsurface_17.setSpace(north_space)\nsurface_18.setSpace(north_space)\nsurface_19.setSpace(north_space)\nsurface_20.setSpace(north_space)\n\n# Connect spaces and zones\nwest_space.setThermalZone(west_zone)\neast_space.setThermalZone(east_zone)\nnorth_space.setThermalZone(north_zone)\n\nputs surface_3.to_s\nputs surface_17.to_s\nputs surface_3.isNumberofVerticesAutocalculated\n\naddSurfaceCracks(model, nil, nil)\n\nvisitor = SurfaceNetworkBuilder.new(model, nil, nil)\nputs visitor.summary\n\nputs\nzones = model.getAirflowNetworkZones()\nputs 'Created ' + zones.size().to_s() + ' AFN zones'\nextnodes = model.getAirflowNetworkExternalNodes()\nputs 'Created ' + extnodes.size().to_s() + ' AFN external nodes'\nsurfs = model.getAirflowNetworkSurfaces()\nputs 'Created ' + surfs.size().to_s() + ' AFN surfaces'\ncracks = model.getAirflowNetworkCracks()\nputs 'Created ' + cracks.size().to_s() + ' AFN cracks'\n\njunk = <<-MLS\nGlobalGeometryRules,UpperLeftCorner,CounterClockWise,World\n\nFenestrationSurface:Detailed,WINDOW11,WINDOW,WIN-CON-LIGHT,Surface_1,0.5000000,1.0,3,1.00000,0,2.500000,1.00000,0,1.0000000,5.000000,0,1.0000000\nFenestrationSurface:Detailed,WINDOW12,WINDOW,WIN-CON-LIGHT,Surface_1,0.5000000,1.0,3,5.00000,0,1.0000000,5.000000,0,2.5000000,1.000000,0,2.500000\nFenestrationSurface:Detailed,DoorInSurface_3,DOOR,DOOR-CON,Surface_3,DoorInSurface_17,0.5000000,1.0,4,3.500,6.096000,2.0,3.500,6.096000,0.0,2.500,6.096000,0.0,2.500,6.096000,2.0\nFenestrationSurface:Detailed,WINDOW2,WINDOW,WIN-CON-LIGHT,Surface_15,0.5000000,1.0,4,6.000000,12.19200,2.333000,6.000000,12.19200,1.000000,3.000000,12.19200,1.000000,3.000000,12.19200,2.333000\nFenestrationSurface:Detailed,DoorInSurface_17,DOOR,DOOR-CON,Surface_17,DoorInSurface_3,0.5000000,1.0,4,2.500,6.096000,2.0,2.500,6.096000,0.0,3.500,6.096000,0.0,3.500,6.096000,2.0\n\nAirflowNetwork:SimulationControl,NaturalVentilation,MultizoneWithoutDistribution,INPUT,ExternalNode,LOWRISE,500,ZeroNodePressures,1.0E-05,1.0E-06,-0.5,0.0,1.0\n\nAirflowNetwork:MultiZone:Zone,WEST_ZONE,NoVent,Temperature,WindowVentSched,0.3,5.0,10.0,0.0,300000.0\nAirflowNetwork:MultiZone:Zone,EAST_ZONE,NoVent,1.0,0.0,100.0,0.0,300000.0\nAirflowNetwork:MultiZone:Zone,NORTH_ZONE,NoVent,Temperature,WindowVentSched,1.0,0.0,100.0,0.0,300000.0\nAirflowNetwork:MultiZone:Surface,Surface_1,CR-1,SFacade,1.0\nAirflowNetwork:MultiZone:Surface,Surface_4,CR-1,1.0\nAirflowNetwork:MultiZone:Surface,Surface_11,CR-1,1.0\nAirflowNetwork:MultiZone:Surface,Surface_15,CR-1,NFacade,1.0\nAirflowNetwork:MultiZone:ExternalNode,NFacade,1.524,NFacade_WPCValue\nAirflowNetwork:MultiZone:ExternalNode,SFacade,1.524,SFacade_WPCValue,No,Absolute\nAirflowNetwork:MultiZone:ReferenceCrackConditions,ReferenceCrackConditions,20.0,101320,0.005\nAirflowNetwork:MultiZone:Surface:Crack,CR-1,0.01,0.667,ReferenceCrackConditions\nAirflowNetwork:MultiZone:WindPressureCoefficientArray,Every 30 Degrees,0,30,60,90,120,150,180,210,240,270,300,330\nAirflowNetwork:MultiZone:WindPressureCoefficientValues,NFacade_WPCValue,Every 30 Degrees,0.60,0.48,0.04,-0.56,-0.56,-0.42,-0.37,-0.42,-0.56,-0.56,0.04,0.48\nAirflowNetwork:MultiZone:WindPressureCoefficientValues,SFacade_WPCValue,Every 30 Degrees,-0.37,-0.42,-0.56,-0.56,0.04,0.48,0.60,0.48,0.04,-0.56,-0.56,-0.42\n\nSurfaceConvectionAlgorithm:Inside,TARP\nSurfaceConvectionAlgorithm:Outside,DOE-2\nHeatBalanceAlgorithm,ConductionTransferFunction\nZoneAirHeatBalanceAlgorithm,AnalyticalSolution\n\n\nTEST_F(EnergyPlusFixture, TestExternalNodes) {\n\t\tstd::string const idf_objects = delimited_string({\n\t\t\t\"Version,8.6;\",\n\t\t\t\"Material,\",\n\t\t\t\" A1 - 1 IN STUCCO, !- Name\",\n\t\t\t\" Smooth, !- Roughness\",\n\t\t\t\" 2.5389841E-02, !- Thickness {m}\",\n\t\t\t\" 0.6918309, !- Conductivity {W/m-K}\",\n\t\t\t\" 1858.142, !- Density {kg/m3}\",\n\t\t\t\" 836.8000, !- Specific Heat {J/kg-K}\",\n\t\t\t\" 0.9000000, !- Thermal Absorptance\",\n\t\t\t\" 0.9200000, !- Solar Absorptance\",\n\t\t\t\" 0.9200000; !- Visible Absorptance\",\n\t\t\t\"Material,\",\n\t\t\t\" C4 - 4 IN COMMON BRICK, !- Name\",\n\t\t\t\" Rough, !- Roughness\",\n\t\t\t\" 0.1014984, !- Thickness {m}\",\n\t\t\t\" 0.7264224, !- Conductivity {W/m-K}\",\n\t\t\t\" 1922.216, !- Density {kg/m3}\",\n\t\t\t\" 836.8000, !- Specific Heat {J/kg-K}\",\n\t\t\t\" 0.9000000, !- Thermal Absorptance\",\n\t\t\t\" 0.7600000, !- Solar Absorptance\",\n\t\t\t\" 0.7600000; !- Visible Absorptance\",\n\t\t\t\"Material,\",\n\t\t\t\" E1 - 3 / 4 IN PLASTER OR GYP BOARD, !- Name\",\n\t\t\t\" Smooth, !- Roughness\",\n\t\t\t\" 1.905E-02, !- Thickness {m}\",\n\t\t\t\" 0.7264224, !- Conductivity {W/m-K}\",\n\t\t\t\" 1601.846, !- Density {kg/m3}\",\n\t\t\t\" 836.8000, !- Specific Heat {J/kg-K}\",\n\t\t\t\" 0.9000000, !- Thermal Absorptance\",\n\t\t\t\" 0.9200000, !- Solar Absorptance\",\n\t\t\t\" 0.9200000; !- Visible Absorptance\",\n\t\t\t\"Material,\",\n\t\t\t\" C6 - 8 IN CLAY TILE, !- Name\",\n\t\t\t\" Smooth, !- Roughness\",\n\t\t\t\" 0.2033016, !- Thickness {m}\",\n\t\t\t\" 0.5707605, !- Conductivity {W/m-K}\",\n\t\t\t\" 1121.292, !- Density {kg/m3}\",\n\t\t\t\" 836.8000, !- Specific Heat {J/kg-K}\",\n\t\t\t\" 0.9000000, !- Thermal Absorptance\",\n\t\t\t\" 0.8200000, !- Solar Absorptance\",\n\t\t\t\" 0.8200000; !- Visible Absorptance\",\n\t\t\t\"Material,\",\n\t\t\t\" C10 - 8 IN HW CONCRETE, !- Name\",\n\t\t\t\" MediumRough, !- Roughness\",\n\t\t\t\" 0.2033016, !- Thickness {m}\",\n\t\t\t\" 1.729577, !- Conductivity {W/m-K}\",\n\t\t\t\" 2242.585, !- Density {kg/m3}\",\n\t\t\t\" 836.8000, !- Specific Heat {J/kg-K}\",\n\t\t\t\" 0.9000000, !- Thermal Absorptance\",\n\t\t\t\" 0.6500000, !- Solar Absorptance\",\n\t\t\t\" 0.6500000; !- Visible Absorptance\",\n\t\t\t\"Material,\",\n\t\t\t\" E2 - 1 / 2 IN SLAG OR STONE, !- Name\",\n\t\t\t\" Rough, !- Roughness\",\n\t\t\t\" 1.2710161E-02, !- Thickness {m}\",\n\t\t\t\" 1.435549, !- Conductivity {W/m-K}\",\n\t\t\t\" 881.0155, !- Density {kg/m3}\",\n\t\t\t\" 1673.600, !- Specific Heat {J/kg-K}\",\n\t\t\t\" 0.9000000, !- Thermal Absorptance\",\n\t\t\t\" 0.5500000, !- Solar Absorptance\",\n\t\t\t\" 0.5500000; !- Visible Absorptance\",\n\t\t\t\"Material,\",\n\t\t\t\" E3 - 3 / 8 IN FELT AND MEMBRANE, !- Name\",\n\t\t\t\" Rough, !- Roughness\",\n\t\t\t\" 9.5402403E-03, !- Thickness {m}\",\n\t\t\t\" 0.1902535, !- Conductivity {W/m-K}\",\n\t\t\t\" 1121.292, !- Density {kg/m3}\",\n\t\t\t\" 1673.600, !- Specific Heat {J/kg-K}\",\n\t\t\t\" 0.9000000, !- Thermal Absorptance\",\n\t\t\t\" 0.7500000, !- Solar Absorptance\",\n\t\t\t\" 0.7500000; !- Visible Absorptance\",\n\t\t\t\"Material,\",\n\t\t\t\" B5 - 1 IN DENSE INSULATION, !- Name\",\n\t\t\t\" VeryRough, !- Roughness\",\n\t\t\t\" 2.5389841E-02, !- Thickness {m}\",\n\t\t\t\" 4.3239430E-02, !- Conductivity {W/m-K}\",\n\t\t\t\" 91.30524, !- Density {kg/m3}\",\n\t\t\t\" 836.8000, !- Specific Heat {J/kg-K}\",\n\t\t\t\" 0.9000000, !- Thermal Absorptance\",\n\t\t\t\" 0.5000000, !- Solar Absorptance\",\n\t\t\t\" 0.5000000; !- Visible Absorptance\",\n\t\t\t\"Material,\",\n\t\t\t\" C12 - 2 IN HW CONCRETE, !- Name\",\n\t\t\t\" MediumRough, !- Roughness\",\n\t\t\t\" 5.0901599E-02, !- Thickness {m}\",\n\t\t\t\" 1.729577, !- Conductivity {W/m-K}\",\n\t\t\t\" 2242.585, !- Density {kg/m3}\",\n\t\t\t\" 836.8000, !- Specific Heat {J/kg-K}\",\n\t\t\t\" 0.9000000, !- Thermal Absorptance\",\n\t\t\t\" 0.6500000, !- Solar Absorptance\",\n\t\t\t\" 0.6500000; !- Visible Absorptance\",\n\t\t\t\"Material,\",\n\t\t\t\" 1.375in-Solid-Core, !- Name\",\n\t\t\t\" Smooth, !- Roughness\",\n\t\t\t\" 3.4925E-02, !- Thickness {m}\",\n\t\t\t\" 0.1525000, !- Conductivity {W/m-K}\",\n\t\t\t\" 614.5000, !- Density {kg/m3}\",\n\t\t\t\" 1630.0000, !- Specific Heat {J/kg-K}\",\n\t\t\t\" 0.9000000, !- Thermal Absorptance\",\n\t\t\t\" 0.9200000, !- Solar Absorptance\",\n\t\t\t\" 0.9200000; !- Visible Absorptance\",\n\t\t\t\"WindowMaterial:Glazing,\",\n\t\t\t\" WIN-LAY-GLASS-LIGHT, !- Name\",\n\t\t\t\" SpectralAverage, !- Optical Data Type\",\n\t\t\t\" , !- Window Glass Spectral Data Set Name\",\n\t\t\t\" 0.0025, !- Thickness {m}\",\n\t\t\t\" 0.850, !- Solar Transmittance at Normal Incidence\",\n\t\t\t\" 0.075, !- Front Side Solar Reflectance at Normal Incidence\",\n\t\t\t\" 0.075, !- Back Side Solar Reflectance at Normal Incidence\",\n\t\t\t\" 0.901, !- Visible Transmittance at Normal Incidence\",\n\t\t\t\" 0.081, !- Front Side Visible Reflectance at Normal Incidence\",\n\t\t\t\" 0.081, !- Back Side Visible Reflectance at Normal Incidence\",\n\t\t\t\" 0.0, !- Infrared Transmittance at Normal Incidence\",\n\t\t\t\" 0.84, !- Front Side Infrared Hemispherical Emissivity\",\n\t\t\t\" 0.84, !- Back Side Infrared Hemispherical Emissivity\",\n\t\t\t\" 0.9; !- Conductivity {W/m-K}\",\n\t\t\t\"Construction,\",\n\t\t\t\" DOOR-CON, !- Name\",\n\t\t\t\" 1.375in-Solid-Core; !- Outside Layer\",\n\t\t\t\"Construction,\",\n\t\t\t\" EXTWALL80, !- Name\",\n\t\t\t\" A1 - 1 IN STUCCO, !- Outside Layer\",\n\t\t\t\" C4 - 4 IN COMMON BRICK, !- Layer 2\",\n\t\t\t\" E1 - 3 / 4 IN PLASTER OR GYP BOARD; !- Layer 3\",\n\t\t\t\"Construction,\",\n\t\t\t\" PARTITION06, !- Name\",\n\t\t\t\" E1 - 3 / 4 IN PLASTER OR GYP BOARD, !- Outside Layer\",\n\t\t\t\" C6 - 8 IN CLAY TILE, !- Layer 2\",\n\t\t\t\" E1 - 3 / 4 IN PLASTER OR GYP BOARD; !- Layer 3\",\n\t\t\t\" Construction,\",\n\t\t\t\" FLOOR SLAB 8 IN, !- Name\",\n\t\t\t\" C10 - 8 IN HW CONCRETE; !- Outside Layer\",\n\t\t\t\"Construction,\",\n\t\t\t\" ROOF34, !- Name\",\n\t\t\t\" E2 - 1 / 2 IN SLAG OR STONE, !- Outside Layer\",\n\t\t\t\" E3 - 3 / 8 IN FELT AND MEMBRANE, !- Layer 2\",\n\t\t\t\" B5 - 1 IN DENSE INSULATION, !- Layer 3\",\n\t\t\t\" C12 - 2 IN HW CONCRETE; !- Layer 4\",\n\t\t\t\"Construction,\",\n\t\t\t\" WIN-CON-LIGHT, !- Name\",\n\t\t\t\" WIN-LAY-GLASS-LIGHT; !- Outside Layer\",\n\t\t\t\"Zone,\",\n\t\t\t\" WEST_ZONE, !- Name\",\n\t\t\t\" 0, !- Direction of Relative North {deg}\",\n\t\t\t\" 0, !- X Origin {m}\",\n\t\t\t\" 0, !- Y Origin {m}\",\n\t\t\t\" 0, !- Z Origin {m}\",\n\t\t\t\" 1, !- Type\",\n\t\t\t\" 1, !- Multiplier\",\n\t\t\t\" autocalculate; !- Ceiling Height {m}\",\n\t\t\t\"Zone,\",\n\t\t\t\" EAST_ZONE, !- Name\",\n\t\t\t\" 0, !- Direction of Relative North {deg}\",\n\t\t\t\" 0, !- X Origin {m}\",\n\t\t\t\" 0, !- Y Origin {m}\",\n\t\t\t\" 0, !- Z Origin {m}\",\n\t\t\t\" 1, !- Type\",\n\t\t\t\" 1, !- Multiplier\",\n\t\t\t\" autocalculate; !- Ceiling Height {m}\",\n\t\t\t\"Zone,\",\n\t\t\t\" NORTH_ZONE, !- Name\",\n\t\t\t\" 0, !- Direction of Relative North {deg}\",\n\t\t\t\" 0, !- X Origin {m}\",\n\t\t\t\" 0, !- Y Origin {m}\",\n\t\t\t\" 0, !- Z Origin {m}\",\n\t\t\t\" 1, !- Type\",\n\t\t\t\" 1, !- Multiplier\",\n\t\t\t\" autocalculate; !- Ceiling Height {m}\",\n\t\t\t\"GlobalGeometryRules,\",\n\t\t\t\" UpperLeftCorner, !- Starting Vertex Position\",\n\t\t\t\" CounterClockWise, !- Vertex Entry Direction\",\n\t\t\t\" World; !- Coordinate System\",\n\t\t\t\"BuildingSurface:Detailed,\",\n\t\t\t\" Surface_1, !- Name\",\n\t\t\t\" WALL, !- Surface Type\",\n\t\t\t\" EXTWALL80, !- Construction Name\",\n\t\t\t\" WEST_ZONE, !- Zone Name\",\n\t\t\t\" Outdoors, !- Outside Boundary Condition\",\n\t\t\t\" , !- Outside Boundary Condition Object\",\n\t\t\t\" SunExposed, !- Sun Exposure\",\n\t\t\t\" WindExposed, !- Wind Exposure\",\n\t\t\t\" 0.5000000, !- View Factor to Ground\",\n\t\t\t\" 4, !- Number of Vertices\",\n\t\t\t\" 0,0,3.048000, !- X,Y,Z ==> Vertex 1 {m}\",\n\t\t\t\" 0,0,0, !- X,Y,Z ==> Vertex 2 {m}\",\n\t\t\t\" 6.096000,0,0, !- X,Y,Z ==> Vertex 3 {m}\",\n\t\t\t\" 6.096000,0,3.048000; !- X,Y,Z ==> Vertex 4 {m}\",\n\t\t\t\"BuildingSurface:Detailed,\",\n\t\t\t\" Surface_2, !- Name\",\n\t\t\t\" WALL, !- Surface Type\",\n\t\t\t\" EXTWALL80, !- Construction Name\",\n\t\t\t\" WEST_ZONE, !- Zone Name\",\n\t\t\t\" Outdoors, !- Outside Boundary Condition\",\n\t\t\t\" , !- Outside Boundary Condition Object\",\n\t\t\t\" SunExposed, !- Sun Exposure\",\n\t\t\t\" WindExposed, !- Wind Exposure\",\n\t\t\t\" 0.5000000, !- View Factor to Ground\",\n\t\t\t\" 4, !- Number of Vertices\",\n\t\t\t\" 0,6.096000,3.048000, !- X,Y,Z ==> Vertex 1 {m}\",\n\t\t\t\" 0,6.096000,0, !- X,Y,Z ==> Vertex 2 {m}\",\n\t\t\t\" 0,0,0, !- X,Y,Z ==> Vertex 3 {m}\",\n\t\t\t\" 0,0,3.048000; !- X,Y,Z ==> Vertex 4 {m}\",\n\t\t\t\"BuildingSurface:Detailed,\",\n\t\t\t\" Surface_3, !- Name\",\n\t\t\t\" WALL, !- Surface Type\",\n\t\t\t\" PARTITION06, !- Construction Name\",\n\t\t\t\" WEST_ZONE, !- Zone Name\",\n\t\t\t\" Surface, !- Outside Boundary Condition\",\n\t\t\t\" Surface_17, !- Outside Boundary Condition Object\",\n\t\t\t\" NoSun, !- Sun Exposure\",\n\t\t\t\" NoWind, !- Wind Exposure\",\n\t\t\t\" 0.5000000, !- View Factor to Ground\",\n\t\t\t\" 4, !- Number of Vertices\",\n\t\t\t\" 6.096000,6.096000,3.048000, !- X,Y,Z ==> Vertex 1 {m}\",\n\t\t\t\" 6.096000,6.096000,0, !- X,Y,Z ==> Vertex 2 {m}\",\n\t\t\t\" 0,6.096000,0, !- X,Y,Z ==> Vertex 3 {m}\",\n\t\t\t\" 0,6.096000,3.048000; !- X,Y,Z ==> Vertex 4 {m}\",\n\t\t\t\"BuildingSurface:Detailed,\",\n\t\t\t\" Surface_4, !- Name\",\n\t\t\t\" WALL, !- Surface Type\",\n\t\t\t\" PARTITION06, !- Construction Name\",\n\t\t\t\" WEST_ZONE, !- Zone Name\",\n\t\t\t\" Surface, !- Outside Boundary Condition\",\n\t\t\t\" Surface_10, !- Outside Boundary Condition Object\",\n\t\t\t\" NoSun, !- Sun Exposure\",\n\t\t\t\" NoWind, !- Wind Exposure\",\n\t\t\t\" 0.5000000, !- View Factor to Ground\",\n\t\t\t\" 4, !- Number of Vertices\",\n\t\t\t\" 6.096000,0,3.048000, !- X,Y,Z ==> Vertex 1 {m}\",\n\t\t\t\" 6.096000,0,0, !- X,Y,Z ==> Vertex 2 {m}\",\n\t\t\t\" 6.096000,6.096000,0, !- X,Y,Z ==> Vertex 3 {m}\",\n\t\t\t\" 6.096000,6.096000,3.048000; !- X,Y,Z ==> Vertex 4 {m}\",\n\t\t\t\"BuildingSurface:Detailed,\",\n\t\t\t\" Surface_5, !- Name\",\n\t\t\t\" FLOOR, !- Surface Type\",\n\t\t\t\" FLOOR SLAB 8 IN, !- Construction Name\",\n\t\t\t\" WEST_ZONE, !- Zone Name\",\n\t\t\t\" Surface, !- Outside Boundary Condition\",\n\t\t\t\" Surface_5, !- Outside Boundary Condition Object\",\n\t\t\t\" NoSun, !- Sun Exposure\",\n\t\t\t\" NoWind, !- Wind Exposure\",\n\t\t\t\" 1.000000, !- View Factor to Ground\",\n\t\t\t\" 4, !- Number of Vertices\",\n\t\t\t\" 0,0,0, !- X,Y,Z ==> Vertex 1 {m}\",\n\t\t\t\" 0,6.096000,0, !- X,Y,Z ==> Vertex 2 {m}\",\n\t\t\t\" 6.096000,6.096000,0, !- X,Y,Z ==> Vertex 3 {m}\",\n\t\t\t\" 6.096000,0,0; !- X,Y,Z ==> Vertex 4 {m}\",\n\t\t\t\"BuildingSurface:Detailed,\",\n\t\t\t\" Surface_6, !- Name\",\n\t\t\t\" ROOF, !- Surface Type\",\n\t\t\t\" ROOF34, !- Construction Name\",\n\t\t\t\" WEST_ZONE, !- Zone Name\",\n\t\t\t\" Outdoors, !- Outside Boundary Condition\",\n\t\t\t\" , !- Outside Boundary Condition Object\",\n\t\t\t\" SunExposed, !- Sun Exposure\",\n\t\t\t\" WindExposed, !- Wind Exposure\",\n\t\t\t\" 0, !- View Factor to Ground\",\n\t\t\t\" 4, !- Number of Vertices\",\n\t\t\t\" 0,6.096000,3.048000, !- X,Y,Z ==> Vertex 1 {m}\",\n\t\t\t\" 0,0,3.048000, !- X,Y,Z ==> Vertex 2 {m}\",\n\t\t\t\" 6.096000,0,3.048000, !- X,Y,Z ==> Vertex 3 {m}\",\n\t\t\t\" 6.096000,6.096000,3.048000; !- X,Y,Z ==> Vertex 4 {m}\",\n\t\t\t\"BuildingSurface:Detailed,\",\n\t\t\t\" Surface_8, !- Name\",\n\t\t\t\" WALL, !- Surface Type\",\n\t\t\t\" EXTWALL80, !- Construction Name\",\n\t\t\t\" EAST_ZONE, !- Zone Name\",\n\t\t\t\" Outdoors, !- Outside Boundary Condition\",\n\t\t\t\" , !- Outside Boundary Condition Object\",\n\t\t\t\" SunExposed, !- Sun Exposure\",\n\t\t\t\" WindExposed, !- Wind Exposure\",\n\t\t\t\" 0.5000000, !- View Factor to Ground\",\n\t\t\t\" 4, !- Number of Vertices\",\n\t\t\t\" 6.096000,0,3.048000, !- X,Y,Z ==> Vertex 1 {m}\",\n\t\t\t\" 6.096000,0,0, !- X,Y,Z ==> Vertex 2 {m}\",\n\t\t\t\" 12.19200,0,0, !- X,Y,Z ==> Vertex 3 {m}\",\n\t\t\t\" 12.19200,0,3.048000; !- X,Y,Z ==> Vertex 4 {m}\",\n\t\t\t\"BuildingSurface:Detailed,\",\n\t\t\t\" Surface_9, !- Name\",\n\t\t\t\" WALL, !- Surface Type\",\n\t\t\t\" EXTWALL80, !- Construction Name\",\n\t\t\t\" EAST_ZONE, !- Zone Name\",\n\t\t\t\" Outdoors, !- Outside Boundary Condition\",\n\t\t\t\" , !- Outside Boundary Condition Object\",\n\t\t\t\" SunExposed, !- Sun Exposure\",\n\t\t\t\" WindExposed, !- Wind Exposure\",\n\t\t\t\" 0.5000000, !- View Factor to Ground\",\n\t\t\t\" 4, !- Number of Vertices\",\n\t\t\t\" 12.19200,0,3.048000, !- X,Y,Z ==> Vertex 1 {m}\",\n\t\t\t\" 12.19200,0,0, !- X,Y,Z ==> Vertex 2 {m}\",\n\t\t\t\" 12.19200,6.096000,0, !- X,Y,Z ==> Vertex 3 {m}\",\n\t\t\t\" 12.19200,6.096000,3.048000; !- X,Y,Z ==> Vertex 4 {m}\",\n\t\t\t\"BuildingSurface:Detailed,\",\n\t\t\t\" Surface_10, !- Name\",\n\t\t\t\" WALL, !- Surface Type\",\n\t\t\t\" PARTITION06, !- Construction Name\",\n\t\t\t\" EAST_ZONE, !- Zone Name\",\n\t\t\t\" Surface, !- Outside Boundary Condition\",\n\t\t\t\" Surface_4, !- Outside Boundary Condition Object\",\n\t\t\t\" NoSun, !- Sun Exposure\",\n\t\t\t\" NoWind, !- Wind Exposure\",\n\t\t\t\" 0.5000000, !- View Factor to Ground\",\n\t\t\t\" 4, !- Number of Vertices\",\n\t\t\t\" 6.096000,6.096000,3.048000, !- X,Y,Z ==> Vertex 1 {m}\",\n\t\t\t\" 6.096000,6.096000,0, !- X,Y,Z ==> Vertex 2 {m}\",\n\t\t\t\" 6.096000,0,0, !- X,Y,Z ==> Vertex 3 {m}\",\n\t\t\t\" 6.096001,0,3.048000; !- X,Y,Z ==> Vertex 4 {m}\",\n\t\t\t\"BuildingSurface:Detailed,\",\n\t\t\t\" Surface_11, !- Name\",\n\t\t\t\" WALL, !- Surface Type\",\n\t\t\t\" PARTITION06, !- Construction Name\",\n\t\t\t\" EAST_ZONE, !- Zone Name\",\n\t\t\t\" Surface, !- Outside Boundary Condition\",\n\t\t\t\" Surface_18, !- Outside Boundary Condition Object\",\n\t\t\t\" NoSun, !- Sun Exposure\",\n\t\t\t\" NoWind, !- Wind Exposure\",\n\t\t\t\" 0.5000000, !- View Factor to Ground\",\n\t\t\t\" 4, !- Number of Vertices\",\n\t\t\t\" 12.19200,6.096000,3.048000, !- X,Y,Z ==> Vertex 1 {m}\",\n\t\t\t\" 12.19200,6.096000,0, !- X,Y,Z ==> Vertex 2 {m}\",\n\t\t\t\" 6.096000,6.096000,0, !- X,Y,Z ==> Vertex 3 {m}\",\n\t\t\t\" 6.096000,6.096000,3.048000; !- X,Y,Z ==> Vertex 4 {m}\",\n\t\t\t\"BuildingSurface:Detailed,\",\n\t\t\t\" Surface_12, !- Name\",\n\t\t\t\" FLOOR, !- Surface Type\",\n\t\t\t\" FLOOR SLAB 8 IN, !- Construction Name\",\n\t\t\t\" EAST_ZONE, !- Zone Name\",\n\t\t\t\" Surface, !- Outside Boundary Condition\",\n\t\t\t\" Surface_12, !- Outside Boundary Condition Object\",\n\t\t\t\" NoSun, !- Sun Exposure\",\n\t\t\t\" NoWind, !- Wind Exposure\",\n\t\t\t\" 1.000000, !- View Factor to Ground\",\n\t\t\t\" 4, !- Number of Vertices\",\n\t\t\t\" 6.096000,0,0, !- X,Y,Z ==> Vertex 1 {m}\",\n\t\t\t\" 6.096000,6.096000,0, !- X,Y,Z ==> Vertex 2 {m}\",\n\t\t\t\" 12.19200,6.096000,0, !- X,Y,Z ==> Vertex 3 {m}\",\n\t\t\t\" 12.19200,0,0; !- X,Y,Z ==> Vertex 4 {m}\",\n\t\t\t\"BuildingSurface:Detailed,\",\n\t\t\t\" Surface_13, !- Name\",\n\t\t\t\" ROOF, !- Surface Type\",\n\t\t\t\" ROOF34, !- Construction Name\",\n\t\t\t\" EAST_ZONE, !- Zone Name\",\n\t\t\t\" Outdoors, !- Outside Boundary Condition\",\n\t\t\t\" , !- Outside Boundary Condition Object\",\n\t\t\t\" SunExposed, !- Sun Exposure\",\n\t\t\t\" WindExposed, !- Wind Exposure\",\n\t\t\t\" 0, !- View Factor to Ground\",\n\t\t\t\" 4, !- Number of Vertices\",\n\t\t\t\" 6.096000,6.096000,3.048000, !- X,Y,Z ==> Vertex 1 {m}\",\n\t\t\t\" 6.096000,0,3.048000, !- X,Y,Z ==> Vertex 2 {m}\",\n\t\t\t\" 12.19200,0,3.048000, !- X,Y,Z ==> Vertex 3 {m}\",\n\t\t\t\" 12.19200,6.096000,3.048000; !- X,Y,Z ==> Vertex 4 {m}\",\n\t\t\t\"BuildingSurface:Detailed,\",\n\t\t\t\" Surface_14, !- Name\",\n\t\t\t\" WALL, !- Surface Type\",\n\t\t\t\" EXTWALL80, !- Construction Name\",\n\t\t\t\" NORTH_ZONE, !- Zone Name\",\n\t\t\t\" Outdoors, !- Outside Boundary Condition\",\n\t\t\t\" , !- Outside Boundary Condition Object\",\n\t\t\t\" SunExposed, !- Sun Exposure\",\n\t\t\t\" WindExposed, !- Wind Exposure\",\n\t\t\t\" 0.5000000, !- View Factor to Ground\",\n\t\t\t\" 4, !- Number of Vertices\",\n\t\t\t\" 0,12.19200,3.048000, !- X,Y,Z ==> Vertex 1 {m}\",\n\t\t\t\" 0,12.19200,0, !- X,Y,Z ==> Vertex 2 {m}\",\n\t\t\t\" 0,6.096000,0, !- X,Y,Z ==> Vertex 3 {m}\",\n\t\t\t\" 0,6.096000,3.048000; !- X,Y,Z ==> Vertex 4 {m}\",\n\t\t\t\"BuildingSurface:Detailed,\",\n\t\t\t\" Surface_15, !- Name\",\n\t\t\t\" WALL, !- Surface Type\",\n\t\t\t\" EXTWALL80, !- Construction Name\",\n\t\t\t\" NORTH_ZONE, !- Zone Name\",\n\t\t\t\" Outdoors, !- Outside Boundary Condition\",\n\t\t\t\" , !- Outside Boundary Condition Object\",\n\t\t\t\" SunExposed, !- Sun Exposure\",\n\t\t\t\" WindExposed, !- Wind Exposure\",\n\t\t\t\" 0.5000000, !- View Factor to Ground\",\n\t\t\t\" 4, !- Number of Vertices\",\n\t\t\t\" 12.19200,12.19200,3.048000, !- X,Y,Z ==> Vertex 1 {m}\",\n\t\t\t\" 12.19200,12.19200,0, !- X,Y,Z ==> Vertex 2 {m}\",\n\t\t\t\" 0,12.19200,0, !- X,Y,Z ==> Vertex 3 {m}\",\n\t\t\t\" 0,12.19200,3.048000; !- X,Y,Z ==> Vertex 4 {m}\",\n\t\t\t\"BuildingSurface:Detailed,\",\n\t\t\t\" Surface_16, !- Name\",\n\t\t\t\" WALL, !- Surface Type\",\n\t\t\t\" EXTWALL80, !- Construction Name\",\n\t\t\t\" NORTH_ZONE, !- Zone Name\",\n\t\t\t\" Outdoors, !- Outside Boundary Condition\",\n\t\t\t\" , !- Outside Boundary Condition Object\",\n\t\t\t\" SunExposed, !- Sun Exposure\",\n\t\t\t\" WindExposed, !- Wind Exposure\",\n\t\t\t\" 0.5000000, !- View Factor to Ground\",\n\t\t\t\" 4, !- Number of Vertices\",\n\t\t\t\" 12.19200,6.096000,3.048000, !- X,Y,Z ==> Vertex 1 {m}\",\n\t\t\t\" 12.19200,6.096000,0, !- X,Y,Z ==> Vertex 2 {m}\",\n\t\t\t\" 12.19200,12.19200,0, !- X,Y,Z ==> Vertex 3 {m}\",\n\t\t\t\" 12.19200,12.19200,3.048000; !- X,Y,Z ==> Vertex 4 {m}\",\n\t\t\t\"BuildingSurface:Detailed,\",\n\t\t\t\" Surface_17, !- Name\",\n\t\t\t\" WALL, !- Surface Type\",\n\t\t\t\" PARTITION06, !- Construction Name\",\n\t\t\t\" NORTH_ZONE, !- Zone Name\",\n\t\t\t\" Surface, !- Outside Boundary Condition\",\n\t\t\t\" Surface_3, !- Outside Boundary Condition Object\",\n\t\t\t\" NoSun, !- Sun Exposure\",\n\t\t\t\" NoWind, !- Wind Exposure\",\n\t\t\t\" 0.5000000, !- View Factor to Ground\",\n\t\t\t\" 4, !- Number of Vertices\",\n\t\t\t\" 0.000,6.096,3.048, !- X,Y,Z ==> Vertex 1 {m}\",\n\t\t\t\" 0.000,6.096,0.000, !- X,Y,Z ==> Vertex 2 {m}\",\n\t\t\t\" 6.096,6.096,0.000, !- X,Y,Z ==> Vertex 3 {m}\",\n\t\t\t\" 6.096,6.096,3.048; !- X,Y,Z ==> Vertex 4 {m}\",\n\t\t\t\"BuildingSurface:Detailed,\",\n\t\t\t\" Surface_18, !- Name\",\n\t\t\t\" WALL, !- Surface Type\",\n\t\t\t\" PARTITION06, !- Construction Name\",\n\t\t\t\" NORTH_ZONE, !- Zone Name\",\n\t\t\t\" Surface, !- Outside Boundary Condition\",\n\t\t\t\" Surface_11, !- Outside Boundary Condition Object\",\n\t\t\t\" NoSun, !- Sun Exposure\",\n\t\t\t\" NoWind, !- Wind Exposure\",\n\t\t\t\" 0.5000000, !- View Factor to Ground\",\n\t\t\t\" 4, !- Number of Vertices\",\n\t\t\t\" 6.096000,6.096000,3.048000, !- X,Y,Z ==> Vertex 1 {m}\",\n\t\t\t\" 6.096000,6.096000,0, !- X,Y,Z ==> Vertex 2 {m}\",\n\t\t\t\" 12.19200,6.096000,0, !- X,Y,Z ==> Vertex 3 {m}\",\n\t\t\t\" 12.19200,6.096000,3.048000; !- X,Y,Z ==> Vertex 4 {m}\",\n\t\t\t\"BuildingSurface:Detailed,\",\n\t\t\t\" Surface_19, !- Name\",\n\t\t\t\" FLOOR, !- Surface Type\",\n\t\t\t\" FLOOR SLAB 8 IN, !- Construction Name\",\n\t\t\t\" NORTH_ZONE, !- Zone Name\",\n\t\t\t\" Surface, !- Outside Boundary Condition\",\n\t\t\t\" Surface_19, !- Outside Boundary Condition Object\",\n\t\t\t\" NoSun, !- Sun Exposure\",\n\t\t\t\" NoWind, !- Wind Exposure\",\n\t\t\t\" 1.000000, !- View Factor to Ground\",\n\t\t\t\" 4, !- Number of Vertices\",\n\t\t\t\" 0,6.096000,0, !- X,Y,Z ==> Vertex 1 {m}\",\n\t\t\t\" 0,12.19200,0, !- X,Y,Z ==> Vertex 2 {m}\",\n\t\t\t\" 12.19200,12.19200,0, !- X,Y,Z ==> Vertex 3 {m}\",\n\t\t\t\" 12.19200,6.096000,0; !- X,Y,Z ==> Vertex 4 {m}\",\n\t\t\t\"BuildingSurface:Detailed,\",\n\t\t\t\" Surface_20, !- Name\",\n\t\t\t\" ROOF, !- Surface Type\",\n\t\t\t\" ROOF34, !- Construction Name\",\n\t\t\t\" NORTH_ZONE, !- Zone Name\",\n\t\t\t\" Outdoors, !- Outside Boundary Condition\",\n\t\t\t\" , !- Outside Boundary Condition Object\",\n\t\t\t\" SunExposed, !- Sun Exposure\",\n\t\t\t\" WindExposed, !- Wind Exposure\",\n\t\t\t\" 0, !- View Factor to Ground\",\n\t\t\t\" 4, !- Number of Vertices\",\n\t\t\t\" 0,12.19200,3.048000, !- X,Y,Z ==> Vertex 1 {m}\",\n\t\t\t\" 0,6.096000,3.048000, !- X,Y,Z ==> Vertex 2 {m}\",\n\t\t\t\" 12.19200,6.096000,3.048000, !- X,Y,Z ==> Vertex 3 {m}\",\n\t\t\t\" 12.19200,12.19200,3.048000; !- X,Y,Z ==> Vertex 4 {m}\",\n\t\t\t/*\"FenestrationSurface:Detailed,\",\n\t\t\t\" WINDOW11, !- Name\",\n\t\t\t\" WINDOW, !- Surface Type\",\n\t\t\t\" WIN-CON-LIGHT, !- Construction Name\",\n\t\t\t\" Surface_1, !- Building Surface Name\",\n\t\t\t\" , !- Outside Boundary Condition Object\",\n\t\t\t\" 0.5000000, !- View Factor to Ground\",\n\t\t\t\" , !- Shading Control Name\",\n\t\t\t\" , !- Frame and Divider Name\",\n\t\t\t\" 1.0, !- Multiplier\",\n\t\t\t\" 3, !- Number of Vertices\",\n\t\t\t\" 1.00000,0,2.500000, !- X,Y,Z ==> Vertex 1 {m}\",\n\t\t\t\" 1.00000,0,1.0000000, !- X,Y,Z ==> Vertex 2 {m}\",\n\t\t\t\" 5.000000,0,1.0000000; !- X,Y,Z ==> Vertex 3 {m}\",\n\t\t\t\"FenestrationSurface:Detailed,\",\n\t\t\t\" WINDOW12, !- Name\",\n\t\t\t\" WINDOW, !- Surface Type\",\n\t\t\t\" WIN-CON-LIGHT, !- Construction Name\",\n\t\t\t\" Surface_1, !- Building Surface Name\",\n\t\t\t\" , !- Outside Boundary Condition Object\",\n\t\t\t\" 0.5000000, !- View Factor to Ground\",\n\t\t\t\" , !- Shading Control Name\",\n\t\t\t\" , !- Frame and Divider Name\",\n\t\t\t\" 1.0, !- Multiplier\",\n\t\t\t\" 3, !- Number of Vertices\",\n\t\t\t\" 5.00000,0,1.0000000, !- X,Y,Z ==> Vertex 2 {m}\",\n\t\t\t\" 5.000000,0,2.5000000, !- X,Y,Z ==> Vertex 3 {m}\",\n\t\t\t\" 1.000000,0,2.500000; !- X,Y,Z ==> Vertex 4 {m}\",\n\t\t\t\"FenestrationSurface:Detailed,\",\n\t\t\t\" DoorInSurface_3, !- Name\",\n\t\t\t\" DOOR, !- Surface Type\",\n\t\t\t\" DOOR-CON, !- Construction Name\",\n\t\t\t\" Surface_3, !- Building Surface Name\",\n\t\t\t\" DoorInSurface_17, !- Outside Boundary Condition Object\",\n\t\t\t\" 0.5000000, !- View Factor to Ground\",\n\t\t\t\" , !- Shading Control Name\",\n\t\t\t\" , !- Frame and Divider Name\",\n\t\t\t\" 1.0, !- Multiplier\",\n\t\t\t\" 4, !- Number of Vertices\",\n\t\t\t\" 3.500,6.096000,2.0, !- X,Y,Z ==> Vertex 1 {m}\",\n\t\t\t\" 3.500,6.096000,0.0, !- X,Y,Z ==> Vertex 2 {m}\",\n\t\t\t\" 2.500,6.096000,0.0, !- X,Y,Z ==> Vertex 3 {m}\",\n\t\t\t\" 2.500,6.096000,2.0; !- X,Y,Z ==> Vertex 4 {m}\",\n\t\t\t\"FenestrationSurface:Detailed,\",\n\t\t\t\" WINDOW2, !- Name\",\n\t\t\t\" WINDOW, !- Surface Type\",\n\t\t\t\" WIN-CON-LIGHT, !- Construction Name\",\n\t\t\t\" Surface_15, !- Building Surface Name\",\n\t\t\t\" , !- Outside Boundary Condition Object\",\n\t\t\t\" 0.5000000, !- View Factor to Ground\",\n\t\t\t\" , !- Shading Control Name\",\n\t\t\t\" , !- Frame and Divider Name\",\n\t\t\t\" 1.0, !- Multiplier\",\n\t\t\t\" 4, !- Number of Vertices\",\n\t\t\t\" 6.000000,12.19200,2.333000, !- X,Y,Z ==> Vertex 1 {m}\",\n\t\t\t\" 6.000000,12.19200,1.000000, !- X,Y,Z ==> Vertex 2 {m}\",\n\t\t\t\" 3.000000,12.19200,1.000000, !- X,Y,Z ==> Vertex 3 {m}\",\n\t\t\t\" 3.000000,12.19200,2.333000; !- X,Y,Z ==> Vertex 4 {m}\",\n\t\t\t\"FenestrationSurface:Detailed,\",\n\t\t\t\" DoorInSurface_17, !- Name\",\n\t\t\t\" DOOR, !- Surface Type\",\n\t\t\t\" DOOR-CON, !- Construction Name\",\n\t\t\t\" Surface_17, !- Building Surface Name\",\n\t\t\t\" DoorInSurface_3, !- Outside Boundary Condition Object\",\n\t\t\t\" 0.5000000, !- View Factor to Ground\",\n\t\t\t\" , !- Shading Control Name\",\n\t\t\t\" , !- Frame and Divider Name\",\n\t\t\t\" 1.0, !- Multiplier\",\n\t\t\t\" 4, !- Number of Vertices\",\n\t\t\t\" 2.500,6.096000,2.0, !- X,Y,Z ==> Vertex 1 {m}\",\n\t\t\t\" 2.500,6.096000,0.0, !- X,Y,Z ==> Vertex 2 {m}\",\n\t\t\t\" 3.500,6.096000,0.0, !- X,Y,Z ==> Vertex 3 {m}\",\n\t\t\t\" 3.500,6.096000,2.0; !- X,Y,Z ==> Vertex 4 {m}\",*/\n\t\t\t\"AirflowNetwork:SimulationControl,\",\n\t\t\t\" NaturalVentilation, !- Name\",\n\t\t\t\" MultizoneWithoutDistribution, !- AirflowNetwork Control\",\n\t\t\t\" INPUT, !- Wind Pressure Coefficient Type\",\n\t\t\t\" ExternalNode, !- Height Selection for Local Wind Pressure Calculation\",\n\t\t\t\" LOWRISE, !- Building Type\",\n\t\t\t\" 500, !- Maximum Number of Iterations {dimensionless}\",\n\t\t\t\" ZeroNodePressures, !- Initialization Type\",\n\t\t\t\" 1.0E-05, !- Relative Airflow Convergence Tolerance {dimensionless}\",\n\t\t\t\" 1.0E-06, !- Absolute Airflow Convergence Tolerance {kg/s}\",\n\t\t\t\" -0.5, !- Convergence Acceleration Limit {dimensionless}\",\n\t\t\t\" 0.0, !- Azimuth Angle of Long Axis of Building {deg}\",\n\t\t\t\" 1.0; !- Ratio of Building Width Along Short Axis to Width Along Long Axis\",\n\t\t\t\"AirflowNetwork:MultiZone:Zone,\",\n\t\t\t\" WEST_ZONE, !- Zone Name\",\n\t\t\t\" NoVent, !- Ventilation Control Mode\",\n\t\t\t\" , !- Ventilation Control Zone Temperature Setpoint Schedule Name\",\n\t\t\t//\" Temperature, !- Ventilation Control Mode\",\n\t\t\t//\" WindowVentSched, !- Ventilation Control Zone Temperature Setpoint Schedule Name\",\n\t\t\t\" 0.3, !- Minimum Venting Open Factor {dimensionless}\",\n\t\t\t\" 5.0, !- Indoor and Outdoor Temperature Difference Lower Limit For Maximum Venting Open Factor {deltaC}\",\n\t\t\t\" 10.0, !- Indoor and Outdoor Temperature Difference Upper Limit for Minimum Venting Open Factor {deltaC}\",\n\t\t\t\" 0.0, !- Indoor and Outdoor Enthalpy Difference Lower Limit For Maximum Venting Open Factor {deltaJ/kg}\",\n\t\t\t\" 300000.0; !- Indoor and Outdoor Enthalpy Difference Upper Limit for Minimum Venting Open Factor {deltaJ/kg}\",\n\t\t\t\"AirflowNetwork:MultiZone:Zone,\",\n\t\t\t\" EAST_ZONE, !- Zone Name\",\n\t\t\t\" NoVent, !- Ventilation Control Mode\",\n\t\t\t\" , !- Ventilation Control Zone Temperature Setpoint Schedule Name\",\n\t\t\t\" 1.0, !- Minimum Venting Open Factor {dimensionless}\",\n\t\t\t\" 0.0, !- Indoor and Outdoor Temperature Difference Lower Limit For Maximum Venting Open Factor {deltaC}\",\n\t\t\t\" 100.0, !- Indoor and Outdoor Temperature Difference Upper Limit for Minimum Venting Open Factor {deltaC}\",\n\t\t\t\" 0.0, !- Indoor and Outdoor Enthalpy Difference Lower Limit For Maximum Venting Open Factor {deltaJ/kg}\",\n\t\t\t\" 300000.0; !- Indoor and Outdoor Enthalpy Difference Upper Limit for Minimum Venting Open Factor {deltaJ/kg}\",\n\t\t\t\"AirflowNetwork:MultiZone:Zone,\",\n\t\t\t\" NORTH_ZONE, !- Zone Name\",\n\t\t\t\" NoVent, !- Ventilation Control Mode\",\n\t\t\t\" , !- Ventilation Control Zone Temperature Setpoint Schedule Name\",\n\t\t\t//\" Temperature, !- Ventilation Control Mode\",\n\t\t\t//\" WindowVentSched, !- Ventilation Control Zone Temperature Setpoint Schedule Name\",\n\t\t\t\" 1.0, !- Minimum Venting Open Factor {dimensionless}\",\n\t\t\t\" 0.0, !- Indoor and Outdoor Temperature Difference Lower Limit For Maximum Venting Open Factor {deltaC}\",\n\t\t\t\" 100.0, !- Indoor and Outdoor Temperature Difference Upper Limit for Minimum Venting Open Factor {deltaC}\",\n\t\t\t\" 0.0, !- Indoor and Outdoor Enthalpy Difference Lower Limit For Maximum Venting Open Factor {deltaJ/kg}\",\n\t\t\t\" 300000.0; !- Indoor and Outdoor Enthalpy Difference Upper Limit for Minimum Venting Open Factor {deltaJ/kg}\",\n\t\t\t\"AirflowNetwork:MultiZone:Surface,\",\n\t\t\t\" Surface_1, !- Surface Name\",\n\t\t\t\" CR-1, !- Leakage Component Name\",\n\t\t\t\" SFacade, !- External Node Name\",\n\t\t\t\" 1.0; !- Window/Door Opening Factor, or Crack Factor {dimensionless}\",\n\t\t\t\"AirflowNetwork:MultiZone:Surface,\",\n\t\t\t\" Surface_4, !- Surface Name\",\n\t\t\t\" CR-1, !- Leakage Component Name\",\n\t\t\t\" , !- External Node Name\",\n\t\t\t\" 1.0; !- Window / Door Opening Factor, or Crack Factor{ dimensionless }\",\n\t\t\t\"AirflowNetwork:MultiZone:Surface,\",\n\t\t\t\" Surface_11, !- Surface Name\",\n\t\t\t\" CR-1, !- Leakage Component Name\",\n\t\t\t\" , !- External Node Name\",\n\t\t\t\" 1.0; !- Window / Door Opening Factor, or Crack Factor{ dimensionless }\",\n\t\t\t\"AirflowNetwork:MultiZone:Surface,\",\n\t\t\t\" Surface_15, !- Surface Name\",\n\t\t\t\" CR-1, !- Leakage Component Name\",\n\t\t\t\" NFacade, !- External Node Name\",\n\t\t\t\" 1.0; !- Window / Door Opening Factor, or Crack Factor{ dimensionless }\",\n\t\t\t\"AirflowNetwork:MultiZone:ExternalNode,\",\n\t\t\t\" NFacade, !- Name\",\n\t\t\t\" 1.524, !- External Node Height{ m }\",\n\t\t\t\" NFacade_WPCValue; !- Wind Pressure Coefficient Values Object Name\",\n\t\t\t\"AirflowNetwork:MultiZone:ExternalNode,\",\n\t\t\t\" SFacade, !- Name\",\n\t\t\t\" 1.524, !- External Node Height{ m }\",\n\t\t\t\" SFacade_WPCValue, !- Wind Pressure Coefficient Values Object Name\",\n\t\t\t\" No, !- Symmetric Wind Pressure Coefficient Curve\",\n\t\t\t\" Absolute; !- Wind Angle Type\",\n\t\t\t\"AirflowNetwork:MultiZone:ReferenceCrackConditions,\",\n\t\t\t\" ReferenceCrackConditions,!- Name\",\n\t\t\t\" 20.0, !- Reference Temperature{ C }\",\n\t\t\t\" 101320, !- Reference Barometric Pressure{ Pa }\",\n\t\t\t\" 0.005; !- Reference Humidity Ratio{ kgWater / kgDryAir }\",\n\t\t\t\"AirflowNetwork:MultiZone:Surface:Crack,\",\n\t\t\t\" CR-1, !- Name\",\n\t\t\t\" 0.01, !- Air Mass Flow Coefficient at Reference Conditions{ kg / s }\",\n\t\t\t\" 0.667, !- Air Mass Flow Exponent{ dimensionless }\",\n\t\t\t\" ReferenceCrackConditions;!- Reference Crack Conditions\",\n\t\t\t\"AirflowNetwork:MultiZone:WindPressureCoefficientArray,\",\n\t\t\t\" Every 30 Degrees, !- Name\",\n\t\t\t\" 0, !- Wind Direction 1 {deg}\",\n\t\t\t\" 30, !- Wind Direction 2 {deg}\",\n\t\t\t\" 60, !- Wind Direction 3 {deg}\",\n\t\t\t\" 90, !- Wind Direction 4 {deg}\",\n\t\t\t\" 120, !- Wind Direction 5 {deg}\",\n\t\t\t\" 150, !- Wind Direction 6 {deg}\",\n\t\t\t\" 180, !- Wind Direction 7 {deg}\",\n\t\t\t\" 210, !- Wind Direction 8 {deg}\",\n\t\t\t\" 240, !- Wind Direction 9 {deg}\",\n\t\t\t\" 270, !- Wind Direction 10 {deg}\",\n\t\t\t\" 300, !- Wind Direction 11 {deg}\",\n\t\t\t\" 330; !- Wind Direction 12 {deg}\",\n\t\t\t\"AirflowNetwork:MultiZone:WindPressureCoefficientValues,\",\n\t\t\t\" NFacade_WPCValue, !- Name\",\n\t\t\t\" Every 30 Degrees, !- AirflowNetwork:MultiZone:WindPressureCoefficientArray Name\",\n\t\t\t\" 0.60, !- Wind Pressure Coefficient Value 1 {dimensionless}\",\n\t\t\t\" 0.48, !- Wind Pressure Coefficient Value 2 {dimensionless}\",\n\t\t\t\" 0.04, !- Wind Pressure Coefficient Value 3 {dimensionless}\",\n\t\t\t\" -0.56, !- Wind Pressure Coefficient Value 4 {dimensionless}\",\n\t\t\t\" -0.56, !- Wind Pressure Coefficient Value 5 {dimensionless}\",\n\t\t\t\" -0.42, !- Wind Pressure Coefficient Value 6 {dimensionless}\",\n\t\t\t\" -0.37, !- Wind Pressure Coefficient Value 7 {dimensionless}\",\n\t\t\t\" -0.42, !- Wind Pressure Coefficient Value 8 {dimensionless}\",\n\t\t\t\" -0.56, !- Wind Pressure Coefficient Value 9 {dimensionless}\",\n\t\t\t\" -0.56, !- Wind Pressure Coefficient Value 10 {dimensionless}\",\n\t\t\t\" 0.04, !- Wind Pressure Coefficient Value 11 {dimensionless}\",\n\t\t\t\" 0.48; !- Wind Pressure Coefficient Value 12 {dimensionless}\",\n\t\t\t\"AirflowNetwork:MultiZone:WindPressureCoefficientValues,\",\n\t\t\t\" SFacade_WPCValue, !- Name\",\n\t\t\t\" Every 30 Degrees, !- AirflowNetwork:MultiZone:WindPressureCoefficientArray Name\",\n\t\t\t\" -0.37, !- Wind Pressure Coefficient Value 1 {dimensionless}\",\n\t\t\t\" -0.42, !- Wind Pressure Coefficient Value 2 {dimensionless}\",\n\t\t\t\" -0.56, !- Wind Pressure Coefficient Value 3 {dimensionless}\",\n\t\t\t\" -0.56, !- Wind Pressure Coefficient Value 4 {dimensionless}\",\n\t\t\t\" 0.04, !- Wind Pressure Coefficient Value 5 {dimensionless}\",\n\t\t\t\" 0.48, !- Wind Pressure Coefficient Value 6 {dimensionless}\",\n\t\t\t\" 0.60, !- Wind Pressure Coefficient Value 7 {dimensionless}\",\n\t\t\t\" 0.48, !- Wind Pressure Coefficient Value 8 {dimensionless}\",\n\t\t\t\" 0.04, !- Wind Pressure Coefficient Value 9 {dimensionless}\",\n\t\t\t\" -0.56, !- Wind Pressure Coefficient Value 10 {dimensionless}\",\n\t\t\t\" -0.56, !- Wind Pressure Coefficient Value 11 {dimensionless}\",\n\t\t\t\" -0.42; !- Wind Pressure Coefficient Value 12 {dimensionless}\",\n\t\t\t\"SurfaceConvectionAlgorithm:Inside,TARP;\",\n\t\t\t\"SurfaceConvectionAlgorithm:Outside,DOE-2;\",\n\t\t\t\"HeatBalanceAlgorithm,ConductionTransferFunction;\",\n\t\t\t\"ZoneAirHeatBalanceAlgorithm,\",\n\t\t\t\" AnalyticalSolution; !- Algorithm\" });\n\t\tASSERT_FALSE(process_idf(idf_objects));\n\n\t\tbool errors = false;\n\n\t\tHeatBalanceManager::GetMaterialData(errors); // read material data\n\t\tEXPECT_FALSE(errors); // expect no errors\n\n\t\tHeatBalanceManager::GetConstructData(errors); // read construction data\n\t\tEXPECT_FALSE(errors); // expect no errors\n\n\t\tHeatBalanceManager::GetZoneData(errors); // read zone data\n\t\tEXPECT_FALSE(errors); // expect no errors\n\n\t\t// Magic to get surfaces read in correctly\n\t\tDataHeatBalance::HeatTransferAlgosUsed.allocate(1);\n\t\tDataHeatBalance::HeatTransferAlgosUsed(1) = OverallHeatTransferSolutionAlgo;\n\t\tSurfaceGeometry::CosBldgRotAppGonly = 1.0;\n\t\tSurfaceGeometry::SinBldgRotAppGonly = 0.0;\n\n\t\tSurfaceGeometry::GetSurfaceData(errors); // setup zone geometry and get zone data\n\t\tEXPECT_FALSE(errors); // expect no errors\n\n\t\tCurveManager::GetCurveInput();\n\t\tEXPECT_EQ( CurveManager::NumCurves, 2 );\n\n\t\tAirflowNetworkBalanceManager::GetAirflowNetworkInput();\n\n\t\t// Check the airflow elements\n\t\tEXPECT_EQ( 2u, DataAirflowNetwork::MultizoneExternalNodeData.size() );\n\t\tEXPECT_EQ( 3u, DataAirflowNetwork::MultizoneZoneData.size() );\n\t\tEXPECT_EQ( 4u, DataAirflowNetwork::MultizoneSurfaceData.size() );\n\t\tEXPECT_EQ( 1u, DataAirflowNetwork::MultizoneSurfaceCrackData.size() );\n\t\tEXPECT_EQ( 2u, DataAirflowNetwork::MultizoneSurfaceStdConditionsCrackData.size() );\n\n\t\tEXPECT_EQ( 0.0, DataAirflowNetwork::MultizoneExternalNodeData( 1 ).azimuth );\n\t\tEXPECT_FALSE( DataAirflowNetwork::MultizoneExternalNodeData( 1 ).symmetricCurve );\n\t\tEXPECT_FALSE( DataAirflowNetwork::MultizoneExternalNodeData( 1 ).useRelativeAngle );\n\t\tEXPECT_EQ( 1, DataAirflowNetwork::MultizoneExternalNodeData( 1 ).curve );\n\n\t\tEXPECT_EQ( 180.0, DataAirflowNetwork::MultizoneExternalNodeData( 2 ).azimuth );\n\t\tEXPECT_FALSE( DataAirflowNetwork::MultizoneExternalNodeData( 2 ).symmetricCurve );\n\t\tEXPECT_FALSE( DataAirflowNetwork::MultizoneExternalNodeData( 2 ).useRelativeAngle );\n\t\tEXPECT_EQ( 2, DataAirflowNetwork::MultizoneExternalNodeData( 2 ).curve );\n\n\t\t// Set up some environmental parameters\n\t\tDataEnvironment::OutBaroPress = 101325.0;\n\t\tDataEnvironment::OutDryBulbTemp = 25.0;\n\t\tDataEnvironment::WindDir = 105.0;\n\t\tDataEnvironment::OutHumRat = 0.0; // Dry air only\n\t\tDataEnvironment::SiteTempGradient = 0.0; // Disconnect z from testing\n\t\tDataEnvironment::SiteWindExp = 0.0; // Disconnect variation by height\n\t\tDataEnvironment::WindSpeed = 10.0;\n\n\t\t// Make sure we can compute the right wind pressure\n\t\tReal64 rho = Psychrometrics::PsyRhoAirFnPbTdbW( DataEnvironment::OutBaroPress, DataEnvironment::OutDryBulbTemp,\n\t\t\tDataEnvironment::OutHumRat );\n\t\tEXPECT_DOUBLE_EQ( 1.1841123742118911, rho );\n\t\tReal64 p = AirflowNetworkBalanceManager::CalcWindPressure( DataAirflowNetwork::MultizoneExternalNodeData( 1 ).curve,\n\t\t\t1.0, 0.0, 0.0, false, false );\n\t\tEXPECT_DOUBLE_EQ( -0.56*0.5*1.1841123742118911, p );\n\n\t\t// Make sure the reference velocity comes out right\n\t\tEXPECT_DOUBLE_EQ( 10.0, DataEnvironment::WindSpeedAt( MultizoneExternalNodeData( 1 ).height) );\n\n\t\tEXPECT_EQ( 5u, DataAirflowNetwork::AirflowNetworkNodeSimu.size() );\n\n\t\t// Run the balance routine, for now only to get the pressure set at the external nodes\n\t\tAirflowNetworkBalanceManager::CalcAirflowNetworkAirBalance();\n\n\t\tEXPECT_DOUBLE_EQ( -0.56*0.5*118.41123742118911, DataAirflowNetwork::AirflowNetworkNodeSimu( 4 ).PZ );\n\t\tEXPECT_DOUBLE_EQ( -0.26*0.5*118.41123742118911, DataAirflowNetwork::AirflowNetworkNodeSimu( 5 ).PZ );\n\t}\nMLS\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}}],"truncated":false,"partial":false},"paginationData":{"pageIndex":29754,"numItemsPerPage":100,"numTotalItems":2976874,"offset":2975400,"length":100}},"jwt":"eyJhbGciOiJFZERTQSJ9.eyJyZWFkIjp0cnVlLCJwZXJtaXNzaW9ucyI6eyJyZXBvLmNvbnRlbnQucmVhZCI6dHJ1ZX0sImlhdCI6MTc1NjUyNjIwMSwic3ViIjoiL2RhdGFzZXRzL2hvbmdsaXU5OTAzL3N0YWNrX2VkdV9ydWJ5IiwiZXhwIjoxNzU2NTI5ODAxLCJpc3MiOiJodHRwczovL2h1Z2dpbmdmYWNlLmNvIn0.N2SK8e9xiaDzTc1QCpOX9W77cwgP51enjDh_jzDFMdh7WMQXE1Gr5bKy8jOFYhcAxoorQWU6E19g-nvt10PpAg","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
86ebc076621f02cd71d830fd098204a726ed847d
Ruby
troynt/AdventOfCode2018
/challenges/12/plant_pot.rb
UTF-8
755
3.171875
3
[]
no_license
class PlantPot attr_accessor( :state, :next, :prev, :next_state, :location ) def initialize(state, location: nil) @state = state @location = location end def state_with_neighbors self_with_neighbors.map(&:state).map {|x| !x.nil? && x == true ? '#' : '.'}.join '' end def self_with_neighbors ret = [] 5.times {ret << PlantPot.new(false)} if prev ret[1] = prev ret[0] = prev.prev unless prev.prev.nil? end ret[2] = self if self.next ret[3] = self.next ret[4] = self.next.next unless self.next.next.nil? end ret end def has_plant? state end def to_i has_plant? ? location : 0 end def to_s has_plant? ? '#' : '.' end end
true
815a6ed65f9a8fac912c12793c9b324f67c666e6
Ruby
smellman/chiba_5374_generator
/make_data.rb
UTF-8
1,907
2.78125
3
[]
no_license
# coding: utf-8 require 'csv' sites = %w(hanamigawa midori mihama tyuuou wakaba) # for target.csv use_target = %w(可燃ごみ びん・缶・ペットボトル 古紙・布類 不燃ごみ・有害ごみ(危険物)) target_header = %w(label name notice furigana) base_target_csv = 'chiba_target.csv' # for area_days.csv area_days_header = %w(地名 センター 可燃ごみ びん・缶・ペットボトル 古紙・布類 不燃ごみ・有害ごみ(危険物)) sites.each do |site| site_dir = "../chiba-#{site}.5374" # make target.csv target_output_csv = "#{site_dir}/data/target.csv" CSV.open(target_output_csv, 'w') do |csv| csv << target_header CSV.foreach(base_target_csv) do |row| if use_target.include? row[0] csv << row end end end # make area_days.csv area_days_input_csv = "./chiba_#{site}_area.csv" area_days_output_csv = "#{site_dir}/data/area_days.csv" found_notice = false CSV.open(area_days_output_csv, 'w') do |csv| csv << area_days_header count = 0 CSV.foreach(area_days_input_csv) do |row| count = count + 1 next if count == 1 add_row = Array.new row.each_with_index do |value, index| if value == "※" found_notice = true end if index == 0 add_row << value add_row << "" next end v = value.split('・') if v.count == 1 add_row << value next end if v[0] =~ /[0-5]/ base = v[1][1..-1] ret = base + v[0] ret = ret + " " ret = ret + base + v[1][0] add_row << ret else ret = "#{v[0]} #{v[1]}" add_row << ret end end csv << add_row end end if found_notice p "#{area_days_output_csv} で※が見つかりました。内容を確認してください" end end
true
cf0ae781b93a08e2fea3cfa1b3d074fc811dd4e6
Ruby
jake-webber-au/toy_robot
/Table.rb
UTF-8
245
3.140625
3
[]
no_license
require_relative './errors.rb' class Table def initialize(x = 5, y= 5) @x = x @y = y end def check_boundary(x,y) if !x.between?(0,@x) || !y.between?(0,@y) raise RobotOutOfBounds.new end return true end end
true
08bf772aee93afd99eca95f32ba24ca6cfded246
Ruby
exchai93-zz/student-directory
/directory_ex12.rb
UTF-8
2,779
4.53125
5
[]
no_license
# loading procedure is going to be the reverse of what we've done to save the data to the file # 1. open file for reading # 2. read contents of the file # 3. iterate over all lines # 4. split every line at the comma # 5. put a new hash into the array @students # 6. close the file @students = [] # an empty array accessible to all methods def input_students puts "Please enter the names of the students" puts "To finish, just hit return twice" # get the first name name = gets.chomp # while the name is not empty, repeat this code while !name.empty? do # add the student hash to the array @students << {name: name, cohort: :november} puts "Now we have #{@students.count} students" # get another name from the user name = gets.chomp end end def interactive_menu loop do print_menu process(gets.chomp) end end # extract the code that prints the menu into its own method def print_menu puts "1. Input the students" puts "2. Show the students" # add one more menu item to save the students puts "3. Save the list to students.csv" puts "4. Load the list from students.csv" puts "9. Exit" # 9 because we'll be adding more items end # extract the code that prints the students into a method def show_students print_header print_students_list print_footer end def save_students file = File.open("students.csv", "w") @students.each do |student| student_data = [student[:name], student[:cohort]] csv_line = student_data.join(",") file.puts csv_line end file.close end # loading data from the file def load_students # open file for reading file = File.open("students.csv", "r") # read all lines into an array and interate over it file.readlines.each do |line| # on every interation discard the trailing new line char from the line # split it at the comma (this gives us an array with two elements) # assign it to the name and cohort varibales name, cohort = line.chomp.split(',') # create a new hash and put it into the array of students # converting a string from the file to a symbol @students << {name: name, cohort: cohort.to_sym} end # close the file file.close end def process(selection) case selection when "1" input_students when "2" show_students when "3" save_students when "4" load_students when "9" exit else puts "I don't know what you mean, try again" end end def print_header puts "The students of my cohort at Makers Academy" puts "-------------" end def print_students_list @students.each do |student| puts "#{student[:name]} (#{student[:cohort]} cohort)" end end def print_footer puts "Overall, we have #{@students.count} great students." end interactive_menu
true
59c2e7016aeacc209399d8cf9bfaa7af117bfb7d
Ruby
justinnnnnnnn/aaclasswork
/w4d4/first tdd projects/lib/00_first_tdd.rb
UTF-8
941
3.6875
4
[]
no_license
def my_uniq(a) banana = [] a.map do |el| banana << el if !banana.include?(el) end banana end def two_sum(arr) pairs = [] arr.each_with_index do |el1, i1| arr.each_with_index do |el2, i2| if arr[i1] + arr[i2] == 0 && i2 > i1 pairs << [i1, i2] end end end pairs end def my_transpose(arr) rotated = Array.new(arr.length) {Array.new(arr.length)} arr.each_with_index do |row, i1| row.each_with_index do |el2, i2| rotated[i1][i2] = arr[i2][i1] end end rotated end def stock_picker(days) trade_possibilites = Hash.new() days.each_with_index do |el1, i1| days.each_with_index do |el2, i2| if i1 < i2 trade_possibilites[[i1,i2]] = el2 - el1 end end end trade_possibilites.sort_by{|k, v| v}[-1][0] end p stock_picker([8, 2, 4, 5, 6, 7, 3, 1])
true
bbcef4e0b5819c203d1b7d95753aa44b9c8e1d7e
Ruby
iamianami/ian_calculator
/ian_calculator.rb
UTF-8
1,271
3.90625
4
[]
no_license
# def say(msg) # puts "------#{msg}------" # end # say("Please type your first number") # number1 = gets.chomp.to_i # say("Please type your second number ") # number2 = gets.chomp.to_i # say("Choose 1)add 2)sub 3)multi 4) divided") # operation = gets.chomp.to_i # if operation == 1 # result = number1 + number2 # elsif operation == 2 # result = number1 - number2 # elsif operation == 3 # result = number1 * number2 # elsif operation == 4 # result = number1 / number2.to_f # else # puts "Please type the number,not thing else" # end # puts "The total is #{result}" begin puts "Enter your first number" number1 = gets.chomp.to_i puts "Enter your second number" number2 = gets.chomp.to_i puts "Choose 1)add,2)sub,3)multi,4)divided,please type the number" operation = gets.chomp.to_i if operation == 1 puts number1 + number2 elsif operation == 2 puts number1 - number2 elsif operation == 3 puts number1 * number2 elsif operation == 4 puts number1 / number2.to_f else puts "Please choose a number to active the operation" end puts "Do you want to count something again? (y/n)" end until gets.chomp.downcase == "n" #Finally ,I figured it out...
true
c0a36cf998b3f2bb27b7dc2ccd0f4bb9dee8993a
Ruby
fadhlinahamdan/webhook-shopify-ruby
/app.rb
UTF-8
4,108
2.53125
3
[]
no_license
require 'rubygems' require 'base64' require 'openssl' require 'sinatra' require 'active_support/security_utils' require 'shopify_api' require 'rails' require 'sendgrid-ruby' include SendGrid require 'twilio-ruby' # The Shopify app's shared secret, viewable from the Partner dashboard # webhook string SHARED_SECRET = '86b895992ac3377d945d29a232e84746ab59e58430b5ecca9ac3db34e73148ab' API_KEY = 'af5dbb553f3e90d76eb99f253d285a69' PASSWORD = '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' SHOP_NAME = 'kain-kain-store' # Shopify API gem setup shop_url = "https://#{API_KEY}:#{PASSWORD}@#{SHOP_NAME}.myshopify.com" ShopifyAPI::Base.site = shop_url ShopifyAPI::Base.api_version = '2021-07' helpers do # Compare the computed HMAC digest based on the shared secret and the request contents # to the reported HMAC in the headers def verify_webhook(data, hmac_header) calculated_hmac = Base64.strict_encode64(OpenSSL::HMAC.digest('sha256', SHARED_SECRET, data)) ActiveSupport::SecurityUtils.secure_compare(calculated_hmac, hmac_header) end end # Respond to HTTP POST requests sent to this web service # PRODUCT UPDATE post '/webhook/product_update' do request.body.rewind data = request.body.read verified = verify_webhook(data, env["HTTP_X_SHOPIFY_HMAC_SHA256"]) unless verified return [403, 'Authorization failed. Provided hmac was #{hmac_header}'] end # Output 'true' or 'false' puts "Webhook verified: #{verified}" json_data = JSON.parse data # Find product and add 'Updated' tag product = ShopifyAPI::Product.find(json_data['id'].to_i) product_title = json_data['title'] puts "Product: #{product_title}" product.tags += ', Updated' product.save # Always let Shopify know that we have received the webhook return [200, 'Webhook successfully received'] end # ORDER PAYMENT # A webhook will be sent every time an order has been paid # Send email / SMS when the order has been marked as paid post '/webhook/order_payment' do request.body.rewind data = request.body.read verified = verify_webhook(data, env["HTTP_X_SHOPIFY_HMAC_SHA256"]) unless verified return [403, 'Authorization failed. Provided hmac was #{hmac_header}'] end # Output 'true' or 'false' puts "Webhook verified: #{verified}" json_data = JSON.parse data # Find order and check financial status order_number = json_data['order_number'] financial_status = json_data['financial_status'] puts "Order: #{order_number}" puts "Payment status: #{financial_status}" # Check if customer registered using email or phone number for order updates contact_email = json_data['contact_email'] phone = json_data['phone'] if contact_email # puts "Customer email: #{email}" # Send email using Twilio Sendgrid from = Email.new(email: '[email protected]') to = Email.new(email: contact_email) subject = 'Your payment has been received' content = Content.new(type: 'text/html', value: 'Hi! This is from Kain Kain Store. Your payment has been received. Thank you for shopping with us!') # get value from email.liquid mail = Mail.new(from, subject, to, content) sg = SendGrid::API.new(api_key: ENV['SENDGRID_API_KEY']) response = sg.client.mail._('send').post(request_body: mail.to_json) puts response.status_code puts response.body puts response.headers else phone # puts "Customer phone number: #{phone}" # Send SMS using Twilio account_sid = 'AC3d1d141e02281cde6f86b7e9371ec70d' auth_token = 'a77ddec81338da65616b9b0c2c6becad' client = Twilio::REST::Client.new(account_sid, auth_token) from = '+12018176607' # Your Twilio number to = phone # Your mobile phone number client.messages.create( from: from, to: to, body: "Hi! This is Kain Kain Store. Your payment has been received. Thank you for shopping with us!" ) end # Always let Shopify know that we have received the webhook return [200, 'Webhook successfully received'] end # Respond to HTTP GET request get '/' do "Welcome to Shopify Webhook App! 🎉" end
true
9c002e4c1960164ec61c2a640edaae7e283470fb
Ruby
dhan0406/ride-share-rails
/test/models/passenger_test.rb
UTF-8
2,505
2.734375
3
[]
no_license
require "test_helper" # file replaced with one sent by Jared describe Passenger do let (:new_passenger) { Passenger.new(name: "Kari", phone_num: "111-111-1211") } it "can be instantiated" do # Assert expect(new_passenger.valid?).must_equal true end it "will have the required fields" do # Arrange new_passenger.save passenger = Passenger.first [:name, :phone_num].each do |field| # Assert expect(passenger).must_respond_to field end end describe "relationships" do it "can have many trips" do # Arrange new_passenger.save new_driver = Driver.create(name: "Waldo", vin: "ALWSS52P9NEYLVDE9") trip_1 = Trip.create(driver_id: new_driver.id, passenger_id: new_passenger.id, date: Date.today, rating: 5, cost: 1234) trip_2 = Trip.create(driver_id: new_driver.id, passenger_id: new_passenger.id, date: Date.today, rating: 3, cost: 6334) # Assert expect(new_passenger.trips.count).must_equal 2 new_passenger.trips.each do |trip| expect(trip).must_be_instance_of Trip end end end describe "validations" do it "must have a name" do # Arrange new_passenger.name = nil # Assert expect(new_passenger.valid?).must_equal false expect(new_passenger.errors.messages).must_include :name expect(new_passenger.errors.messages[:name]).must_equal ["can't be blank"] end it "must have a phone number" do # Arrange new_passenger.phone_num = nil # Assert expect(new_passenger.valid?).must_equal false expect(new_passenger.errors.messages).must_include :phone_num expect(new_passenger.errors.messages[:phone_num]).must_equal ["can't be blank"] end end # Tests for methods you create should go here describe "custom methods" do describe "request a ride" do # Your code here end describe "complete trip" do # Your code here end # You may have additional methods to test here describe 'total_charged' do it "should correctly return total amount charged for passenger" do new_passenger = Passenger.create(name: "Pass", phone_num: "1234567") new_driver = Driver.create(name: "Kari", vin: "123") new_trip_1 = Trip.create(date: Time.now, driver_id: new_driver.id, passenger_id: new_passenger.id, cost: 1000) new_trip_2 = Trip.create(date: Time.now, driver_id: new_driver.id, passenger_id: new_passenger.id, cost: 1000) expect(new_passenger.total_charged).must_equal 20.0 end end end end
true
71d058479a47abe743c999e046e5dfd5c047cffb
Ruby
Damnedlag/Ruby-exercises
/03_simon_says/simon_says.rb
UTF-8
896
4.15625
4
[]
no_license
#write your code here def echo(thing) thing end def shout(thing) thing.upcase end def repeat(*arr) array = *arr if !array[1] array << 2 end solution = (array[0] + ' ') * array[1] solution.chomp(' ') end def start_of_word(word, num) i = 1 solution = word[0] while i < num solution = solution + word[i] i = i + 1 end solution end def first_word(str) str.split[0] end def titleize(str) small_words = %w[on the and over] # %w(foo bar) is a shortcut for ["foo", "bar"]. Meaning it's a notation to write an array of strings separated by spaces instead of commas and without quotes around them. str.split(' ').map.with_index do |w, i| # http://www.zenspider.com/ruby/quickref.html#types unless (small_words.include? w) and (i > 0) w.capitalize else w end end.join(' ') end
true
246d8c1fed3c415cba17c6a40088b3dff8e0aff1
Ruby
bethsecor/tealeaf-intro-to-programming
/Workbook/Easy/Quiz3/exercise3.rb
UTF-8
210
2.609375
3
[]
no_license
# Tealeaf Academy Prep Course # Intro to Programming Workbook # Easy Questions - Quiz 3 # Exercise 3 flintstones = %w(Fred Barney Wilma Betty BamBam Pebbles) flintstones << "Dino" flintstones.push("Dino","Hoppy")
true
e4129e9642fd72d26e63b6305b5c4eedb2256c01
Ruby
codeauslander/actualize-class
/intro_to_apis/reddit_app.rb
UTF-8
914
3.171875
3
[]
no_license
require 'unirest' looking_up_words= true while looking_up_words url = "https://www.reddit.com/r/programming/.json" response = Unirest.get(url).body posts = response['data']['children'] print "Please enter the post number from 0 to #{posts.length}: " number = gets.chomp.to_i puts permalinks = [] posts.each do |post| permalinks << post['data']['permalink'] end url_comments = "https://www.reddit.com" + permalinks[number] + ".json" puts "Here are the comments for the post" puts url_comments comments = Unirest.get(url_comments).body comments = comments[1]['data']['children'] index = 1 comments.each do |comment| puts "-" * 50 puts "#{index}). #{comment['data']['body']}" index += 1 end puts puts "Press enter to keep going or enter q to Quit" command = gets.chomp system 'clear' if command == 'q' looking_up_words = false end end
true
f3967c8af1b514726020d3761a0455c51e50bc0b
Ruby
fastmode/badges-and-schedules-v-000
/conference_badges.rb
UTF-8
1,183
4.34375
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
attendees = ["Edsger", "Ada", "Charles", "Alan", "Grace", "Linus", "Matz"] def badge_maker(name) "Hello, my name is #{name}." end #This will create array of all the attendess with the welcome message. def batch_badge_creator(attendees) badges = [] attendees.each do |attendee| badges << badge_maker(attendee) end badges end #This will create array detailing the room assignment to each attendee def assign_rooms(attendees) room_assignment = [] attendees.each_with_index do |attendee, room| room_assignment << "Hello, #{attendee}! You'll be assigned to room #{room+1}!" end room_assignment end #This can be also used with the .map method which creates an array, so no need to specify a new array then enter it again to return it. #def assign_rooms(attendees) # attendees.each_with_index.map do |attendee, room| # "Hello, #{attendee}! You'll be assigned to room #{room+1}!" # end #end #This will call other methods to pull their arrays and puts them out. def printer(attendees) batch_badge_creator(attendees).each do |attendee| puts attendee end assign_rooms(attendees).each do |attendee| puts attendee end end printer(attendees)
true
3d93f1862ec5984ae14e51539100b91c4b7d2fc7
Ruby
inbabbini/ttps_ruby_2015
/Practicas/Practica3/exceptions/e4.rb
UTF-8
421
3.484375
3
[]
no_license
# retry # retry sirve para, justamente, volver a ejecutar el bloque en el cual # se encuentra, desde la sentencia begin (es decir, desde el principio) begin #dangerous code rescue Exception puts 'Something broke' #do something to fix problems retry end # Ejemplo boludo: num = 0 begin if num == 5 'ok' else raise RuntimeError end rescue RuntimeError puts 'catched!' num += 1 retry end
true
b54ab468bc40c9d517ddee9a50ecb44b1dab4e23
Ruby
TDA/Ruby-GithubAPI
/language_dictionary_generator.rb
UTF-8
1,542
3.1875
3
[]
no_license
require 'json' #language_dictionary_generator File.open('/Users/schandramouli/PycharmProjects/GithubAPI/languages_data_sorted.json') do |file| data = file.readlines data_string = "" data.each {|line| data_string += line.chomp} language_data = JSON.parse(data_string) # set the LoC for all the languages to 0 languages = Hash.new(0) # now cycle through the list, and add the lines to the respective langs # remember, LoC for JS is to be modded by 10 whenever it goes over 10k cuz jQuery language_data.each do |key, value| value = JSON.parse(value) # puts value value.each do |lang, loc| if lang.equal?("JavaScript") loc %= 10 end languages[lang] += loc end end # this sorts by value, yay! minus for descending languages = Hash[languages.sort_by { |key, value| -value}] puts languages File.write('./language_usage_data.json', JSON.pretty_unparse(languages)) # now to find frequency of usage of a language, ala how # many projects with that language. frequency = Hash.new(0) language_data.each do |key, value| value = JSON.parse(value) # puts value value.each do |lang, loc| frequency[lang] += 1 end end # this sorts by value, yay! minus for descending # frequency = Hash[frequency.sort_by { |key, value| key}.reverse] # does the same as -value, but more verbose frequency = Hash[frequency.sort_by { |key, value| value}.reverse] puts frequency File.write('./language_frequency_data.json', JSON.pretty_unparse(frequency)) end
true
a5856c467b598560b06adde93205f08e1c4835bf
Ruby
k2works/ruby-design-pattern
/factory/duck_pond.rb
UTF-8
284
2.96875
3
[]
no_license
require './pond' # # == アヒル@池クラス # # Author:: k2works # Version:: 1.0.0 # License:: Ruby License # class DuckPond < Pond def new_organism(type, name) if type == :animal Duck.new(name) else raise "Unknown organism type: #{type}" end end end
true
bd623103c7b1867ad301bfe909753b7b2fd9ace5
Ruby
NotReady/memo
/ruby/chapter2/2-2-2b.rb
UTF-8
405
4.09375
4
[]
no_license
# 引数と戻り値をもつメソッド # 戻り値は最終行の式結果 def triangle(base, height) return nil if base == 0 || height == 0 result = base * height / 2.0 result end area = triangle(11, 9) puts "面積は#{area}です。" area = triangle 11, 9 #=> 呼び出しの小かっこは省略可能 puts "面積は#{area}です。" area = triangle 0, 1 puts "面積は#{area}です。"
true
9812eae5483f4db37ee7ed48af71404ba9472aaf
Ruby
ElaErl/Challenges-1
/Easy1/perfect_number.rb
UTF-8
266
3.5
4
[]
no_license
class PerfectNumber def self.classify(num) raise RuntimeError if num < 0 sum = 0 1.upto(num-1) {|n| sum += n if num % n == 0} case when sum == num then 'perfect' when sum < num then 'deficient' else 'abundant' end end end
true
a3767cf60b376667025f127f3edabd99b65cd4b4
Ruby
ericak11/project_euler
/number_6_squares.rb
UTF-8
855
4.03125
4
[]
no_license
# ############################## sum of square difference - #6 ########################### # The sum of the squares of the first ten natural numbers is, # 12 + 22 + ... + 102 = 385 # The square of the sum of the first ten natural numbers is, # (1 + 2 + ... + 10)2 = 552 = 3025 # Hence the difference between the sum of the squares of # the first ten natural numbers and the square of the sum is 3025 − 385 = 2640. # Find the difference between the sum of the squares of the first one # hundred natural numbers and the square of the sum. to_ten_array = (1..10).to_a numbers_array = (1..100).to_a sum_of_squares = 0 sum_squared = 0 numbers_array.each do |num| sum_of_squares = sum_of_squares + (num * num) end numbers_array.each do |num| sum_squared = sum_squared + num end puts (sum_squared * sum_squared) - sum_of_squares # ANSWER - 25164150
true
68bf2db8f961b46c66a54cd74198449a9504ecb0
Ruby
KlotzAndrew/algorithms
/lib/graph/depth_first_search.rb
UTF-8
939
3.5
4
[]
no_license
class DepthFirstSearch def traverse(adjacency_list, node) @result = [] @stack = [] @traversed_graph = [] adjacency_list.length.times do @traversed_graph << [false, nil] end search_nodes adjacency_list, node @traversed_graph end private def search_nodes(adjacency_list, node) return if @result.include? node @traversed_graph[node][0] = true @traversed_graph[node][1] = @stack.last @result << node @stack << node adjacent_nodes = find_adjacent_nodes adjacency_list, node available_nodes = filter_unvisited_nodes adjacent_nodes available_nodes.each do |available_node| search_nodes(adjacency_list, available_node) end @stack.pop @result end def filter_unvisited_nodes(adjacent_nodes) adjacent_nodes.delete_if {|node| @result.include? node } end def find_adjacent_nodes(adjacency_list, node) adjacency_list[node] end end
true
f8b1aea68afaab25d669151f6eb071018206288f
Ruby
JasonP77/programming-univbasics-nds-nds-to-insight-with-methods-dc-web-012720
/lib/nds_extract.rb
UTF-8
718
3.171875
3
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
$LOAD_PATH.unshift(File.dirname(__FILE__)) require 'directors_database' # Find a way to accumulate the :worldwide_grosses and return that Integer # using director_data as input def gross_for_director(director_data) total = 0 i = 0 while i < director_data[:movies].length do total += director_data[:movies][i][:worldwide_gross] i += 1 end return total end # Write a method that, given an NDS creates a new Hash # The return value should be like: # # { directorOne => allTheMoneyTheyMade, ... } def directors_totals(nds) result = {} i = 0 while i < nds.length do arr = nds[i] result[arr[:name]] = gross_for_director(arr) i += 1 end return result end pp directors_database
true
9fcf5fcaaf417034f34ee7a040e3e551500ae35b
Ruby
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/ruby/word-count/eb71d15b94994b0bacbd53f47600f5db.rb
UTF-8
307
3.421875
3
[]
no_license
class Words attr_reader :words def initialize(string) @words = normalize_input(string) end def count words.each_with_object(Hash.new(0)) do |word, hash| hash[word] += 1 end end private def normalize_input(string) string.downcase.gsub(/\W+/, ' ').split(" ") end end
true
0569967dc9b0e3979c1ad1e47bc215442c0bc759
Ruby
alphagov-mirror/tv-radio-fillers-reporting-dashboard
/tests/helpers/csv_parser_radio_test.rb
UTF-8
1,811
2.6875
3
[]
no_license
require_relative '../../app/helpers/csv_parser_radio.rb' require_relative '../../app/models/transmission.rb' require 'test/unit' require 'csv' class CsvParserRadioTest < Test::Unit::TestCase DATE_FORMAT = '%d-%b-%y' SAMPLE_FILE_FULL_PATH = "tests/helpers/csv_samples/radio_fillers_sample.csv" def setup Mongoid.load!("mongoid.yml", :test) Transmission.delete_all @csv_parser = CsvParserRadio.new end def teardown Transmission.delete_all end def test_parse_row sample_row = ["CB00003030 Dance On 30s", "Absolute 70s", "2767", "17-Jan-13", "21:34"] filler = @csv_parser.parse_row(sample_row) assert !filler.nil? assert filler.type == "radio" assert filler.date.strftime('%d/%m/%Y') == DateTime.new(2013, 01, 17).strftime('%d/%m/%Y') assert filler.time_of_day == sample_row[4] assert filler.station_name == sample_row[1] assert filler.impact == sample_row[2] assert filler.filler_name == sample_row[0] end def test_parse_row_too_few_rows invalid_row = ["Absolute 70s", "2767", "17-Jan-13", "21:34"] exception = assert_raise(ArgumentError) { @csv_parser.parse_row(invalid_row) } assert_equal("Too few rows", exception.message) end def test_parse_row_invalid_date invalid_row = ["CB00003030 Dance On 30s", "Absolute 70s", "2767", "01/31/2013", "21:34"] exception = assert_raise(ArgumentError) { @csv_parser.parse_row(invalid_row) } assert_equal("Could not parse date: #{invalid_row[3]}", exception.message) end def test_parse_radio_sample_file CsvParserRadioTest.load_sample_file fillers = Transmission.where(type: "radio") assert fillers.count == 12 end def self.load_sample_file CsvParserRadio.new.parse_file(SAMPLE_FILE_FULL_PATH) end end
true
48839ae7f90eb263eaf8e20dfbcc87eec843e0c3
Ruby
MihirKale89/Ruby_code
/TimeProcessor/lib/time_processor.rb
UTF-8
1,995
3.921875
4
[]
no_license
=begin Without using any built-in date or time functions, write a function or method that accepts two mandatory arguments: the first argument is a 12-hour time string with the format "[H]H:MM {AM|PM}", and the second argument is a (signed) integer. The second argument is the number of minutes to add to the time of day represented by the first argument. The return value should be a string of the same format as the first argument. For example, AddMinutes("9:13 AM", 200) would return "12:33 PM". The exercise isn't meant to be too hard or take very long; we just want to see how you code. Please use Ruby to complete the assessment and include any test cases that you write. =end class TimeProcessor def self.add_minutes(time, minutes) return time if minutes == 0 time = time.split(' ') meridiem = time.last time = time.first.split(':') hour = time.first.to_i minute = time.last.to_i hour, minute, meridiem = process_minutes(hour, minute, minutes, meridiem) "#{hour}:#{minute} #{meridiem}" end def self.process_minutes(hour, minute, minutes, meridiem) # Handling adding over 24 hours and handling negative case. minutes = minutes < 0 ? minutes.abs%(24*60)*-1 : minutes%(24*60) hour = 0 if hour == 12 && meridiem == 'AM' hour +=12 if hour !=12 && meridiem == 'PM' sum = (hour*60+minute + minutes)%(24*60) # Handling going into the previous or next day sum = (24*60)-(sum.abs) if sum < 0 sum = sum-(24*60) if sum > (24*60) hour = (sum/60)%12 minute = sum%60<10 ? "0#{sum%60}":"#{sum%60}" [hour == 0 ? 12:hour, minute, (sum/60)<12 ? 'AM':'PM'] end end tp = TimeProcessor p tp.add_minutes("9:13 AM", 200) p tp.add_minutes("9:13 AM", -10) p tp.add_minutes("9:13 AM", 1441) p tp.add_minutes("9:13 AM", -1441) p tp.add_minutes("12:05 AM", -10) p tp.add_minutes("12:05 AM", -5) p tp.add_minutes("11:55 PM", 10) p tp.add_minutes("11:55 AM", 10) p tp.add_minutes("11:55 AM", 5) p tp.add_minutes("12:05 PM", -1450)
true
99786877d828de548c60d1f0e9a9e8d3413cb4fd
Ruby
hogeline/weather-analysis
/getaverage.rb
UTF-8
752
2.953125
3
[]
no_license
#!/usr/bin/env ruby # coding: utf-8 require 'fileutils' array = Array.new ARGV.each_with_index do |file, i| array[i] = Array.new(13, 0.0) count = Array.new(13, 0.0) array[i][0] = file.to_i open(file+'.csv', 'r:utf-8') do |f| f.each do |line| fields = line.chomp.split(',') date = fields[0].chomp.split('/') array[i][date[1].to_i] += fields[3].to_f count[date[1].to_i] += 1 end for j in 1..12 array[i][j] /= count[j] end end end print " :" ARGV.each do |file| printf(" %d\t", file) end print ': 平均' + "\n" for i in 1..12 printf("%2d月:", i) avg = 0 for j in 0...ARGV.size printf(" %0.2f\t", array[j][i]) avg += array[j][i] end printf(": %.2f\n", avg/ARGV.size) end
true
d5d0e23430420c3ba97a3e40cb83d906d516b567
Ruby
covaithe/project_euler
/lib/permutations.rb
UTF-8
907
3.8125
4
[]
no_license
class Permutations def self.of(list, n) raise "The list is nil" if list.nil? raise "There are not that many items in the list" if n > list.size raise "Cannot pick #{n} items from a list" if n < 0 return [] if n == 0 return [ list ] if n == list.size result = [] indexes = (0..n-1).to_a loop do result << choose_values(list, indexes) break unless increment_index(indexes, list.size - 1) end result end private def self.choose_values(list, indexes) indexes.map { |i| list[i] } end def self.increment_index(indexes, max) i = indexes.length - 1 while i >= 0 if indexes[i] >= max #can't increment this one i -= 1 max -= 1 else indexes[i] += 1 1.upto(indexes.length-i-1) do |j| indexes[i+j] = indexes[i] + j end return true end end false end end
true
08c142a841b6986e553939a03d35ca8f47c85822
Ruby
willcannings/impromptu
/lib/impromptu/resource.rb
UTF-8
9,370
2.765625
3
[ "CC0-1.0", "LicenseRef-scancode-public-domain" ]
permissive
module Impromptu # Resources represent the modules or classes that are tracked by # Impromptu and which can be lazy loaded. You should never create # resources yourself - use component definitions to define folders # of files which will implement resources. class Resource attr_reader :name, :base_symbol, :files, :children, :parent, :preload def initialize(name, parent) @name = name.to_sym @parent = parent @base_symbol = @name.base_symbol @files = OrderedSet.new @children = {} @reference = nil @namespace = false @dont_undef = self.loaded? # existing constants, such as 'String', should never be unloaded @preload = false # true if any folder defining this resource is marked to be preloaded @implicitly_defined = true end # Override eql? so two resources with the same name will be # considered equal by ordered set. Names are fully namespaced # so will always be unique. def eql?(other) other.name == @name end # Override hash so two resources with the same name will result # in the same hash value. Names are fully namespaced so will # always be unique. def hash @name.hash end # Indicate whether this resource needs to be preloaded def preload=(preload) @preload = preload end # True if this resource needs to be preloaded before other files # are automatically loaded on demand def preload? @preload end # Attempts to retrieve a reference to the object represented by # this resource. If the resource is unloaded, nil is returned. def reference return Object if root? return nil unless @parent && @parent.reference @reference ||= @parent.reference.const_get(@base_symbol) end # Reload the implementation of this resource from all files being # tracked for this resource. Call this method if you are manually # managing file tracking, and need to guarantee all files for this # resource have been loaded. It is normally unecessary to call this # if you rely on the autoloader and reloader. def reload @parent.reload unless @parent.loaded? if @implicitly_defined unload Object.module_eval "module #{@name}; end" else @files.first.reload end reload_preloaded_resources end # Unload the resource by undefining the constant representing it. # Any resources contained within this resource will also be # unloaded. This allows the resource to be garbage collected. If # the resource is a class, you can define a class method called # 'descendants' that returns an array of references to subclasses. # Any subclasses known to Impromptu will also be unloaded, just as # namespaced children are. This prevents subclasses holding a # reference to a stale version of a super class. def unload return unless loaded? # unload namespaced children @children.each_value(&:unload) # unload descendants if they can be reloaded by impromptu if reference.respond_to? :descendants reference.descendants.each do |descendant| resource = Impromptu.root_resource.child(descendant.name.to_sym) resource.unload unless resource.nil? end end # remove from the parent's descendants list if reference.respond_to?(:superclass) && reference.superclass.respond_to?(:descendants) reference.superclass.descendants.delete(reference) end unless @dont_undef @parent.reference.send(:remove_const, @base_symbol) @reference = nil end end # Start tracking a file which implements this resource. If the # file has already been added it won't be added a second time. # This method does not load the added file, so the definition # of the resource will be incomplete until reload is called. def add_file(file) @files << file @implicitly_defined = false end # Un-track a file implementing this resource. If the file was # never tracked, no error is raised. This does not reload the # resource, so the resource will be based on a stale definition # if it was previously loaded. def remove_file(file) @files.delete(file) @implicitly_defined = true if @files.size == 0 && namespace? end # True if no files have been associated with this resource. In # this case, loading the resource will be achieved by creating # a blank module with the name of the resource. If any files # have been associated, they will be loaded instead, and this # method will return false. def implicitly_defined? @implicitly_defined end # True if this resource represents a module acting as a # namespace. def namespace? @namespace end # Mark a resource as representing a module acting as a # namespace. def namespace! @namespace = true end # True if this resource is the parent of any resources. def children? [email protected]? end # Add a child resource to this resource. This does not load the # resource. This should only be called by get_or_create_child. def add_child(resource) @children[resource.base_symbol] = resource end # Remove a reference to a child resource. This does not unload # the object, but is called automatically by unload on its parent # resource. def remove_child(resource) @children.delete(resource.base_symbol) end # In most instances, this method should only be called on the # root resource to traverse the resource tree and retrieve or # create the specified resource. Name must be a symbol. def get_or_create_child(name) return nil unless name.is_a?(Symbol) current = self name.each_namespaced_symbol do |name| # attempt to get the current resource child_resource = current.child(name.base_symbol) # create the resource if needed if child_resource.nil? child_resource = Resource.new(name, current) current.add_child(child_resource) end # the next current resource is the one we just created or retrieved current = child_resource end # after iterating through the name, current will be the resulting resource current end # Walks the resource tree and returns the resource corresponding # to name (which must be a symbol and can be namespaced). If the # resource doesn't exist, nil is returned def child(name) return nil unless name.is_a?(Symbol) return @children[name.without_leading_colons.to_sym] if name.unnested? # if the name is nested, walk the resource tree to return the # resource under this branch. rerturn nil if we reach a # branch which doesn't exist nested_symbols = name.nested_symbols top_level_symbol = nested_symbols.first further_symbols = nested_symbols[1..-1].join('::').to_sym return nil unless @children.has_key?(top_level_symbol) @children[top_level_symbol].child(further_symbols) end # Walks the resource tree to determine if the resource referred # to by name (which must be a symbol, and may be namespaced) is # known by Impromptu. def child?(name) !self.child(name).nil? end # Unload and remove all references to this resource. def remove unload @parent.remove_child(self) if @parent end # True if this resource is the root resource referring to Object. def root? @parent.nil? end # True if this resource exists as a constant in its parent. # This does not guarantee that every file implementing this # resource has been loaded, however, so an incomplete instance # may exist. If you rely on the autoloader and reloader this # will not occur. def loaded? return true if root? return false unless @parent && @parent.loaded? && @parent.reference parent.reference.constants.include?(@base_symbol) end # Mark this resource as having been loaded before Impromptu if the # resource is already defined. def mark_dont_undef @dont_undef = self.loaded? @children.each_value(&:mark_dont_undef) end # Loads this resource if it is an extension of an existing class # or module (such as an object in the standard library). Should # only be called on app startup by Impromptu itself. Recurses to # this resource's children as well. def load_if_extending_stdlib reload if loaded? && !self.root? @children.each_value(&:load_if_extending_stdlib) end # Loads this resource, and any child resources, if the resource is # marked as requiring preloading, and the resource is not currently # loaded. This loading may happen multiple times during the application # life cycle depending on whether parent resources are reloaded and so on. def reload_preloaded_resources reload if !loaded? && preload? @children.each_value(&:reload_preloaded_resources) end end end
true
05d4deaee223fee00bc0ab08d843c77cf39809f0
Ruby
douglasf/base
/bin/web.watchr.rb
UTF-8
1,363
2.828125
3
[]
no_license
require "fileutils" # @key is pre compiled file type. # @value is # :compiler, what compiler to use, the compiler must print result to stdout # :ending, the file ending to use after compilation @settings = { "less" => { :compiler => "lessc", :ending => "css" }, "haml" => { :compiler => "haml", :ending => "html" }, "coffee" => { :compiler => "coffee -cs", :ending => "js" } } # Compiles "file" with appropriate compiler according to @settings. def compile_file file ending = file.split(".").last out = "publish/#{file.reverse.sub(ending.reverse, @settings[ending][:ending].reverse).reverse}" # lol unless File.exist?(out) new_file = true FileUtils.makedirs(File.dirname out) FileUtils.touch out end if File.mtime(file) > File.mtime(out) or new_file replace = File.read(file).gsub(/\<baseup (.*)\>/) { File.read("modules/#{$1}") } result = `echo \'#{replace}\' | #{@settings[ending][:compiler]} > #{out}` puts "WATCHR: Wrote to #{out}" if $?.success? end end # Starts a watchr method if no arguments are given, # if argument "-c file" is given it compiles the single file. arg = ARGV.shift unless arg == "-c" watch( ".*\.(#{@settings.keys.join("|")})" ) {|md| compile_file md[0] } puts "Starting to watch #{@settings.keys.join(", ")}" else compile_file ARGV.shift end
true
c6c1a0190ac8072ae119c19c672dcf820ac3dc78
Ruby
collinschaafsma/pedal
/lib/pedal/presenter.rb
UTF-8
296
2.578125
3
[ "MIT" ]
permissive
module Pedal class Presenter attr_reader :subject def initialize(subject) @subject = subject end # Proxy to the Builder, adds itself to the scope # so we can access the @subject def build(&block) Pedal::Builder.build(scope: self, &block) end end end
true
f21415f73d030e47972a537d83f4804e8bc3b97d
Ruby
Claire7514/exo_ruby
/exo_09.rb
UTF-8
88
2.8125
3
[]
no_license
user_name = gets.chomp name = gets.chomp puts "Bonjour " + user_name + " " + name + "!"
true
69b4423eab0cb21ed64ebd039e473b436131ec57
Ruby
bhserna/guests
/lib/invitations.rb
UTF-8
740
2.765625
3
[]
no_license
module Invitations def self.save_record(list_id, invitation, store) store.create( list_id: list_id, invitation_id: invitation["id"].to_i, raw_data: invitation) end def self.update_record(list_id, invitation, store) record = store.find_for_list_by_invitation_id(list_id, invitation["id"]) store.update(record[:id], list_id: list_id, invitation_id: invitation["id"].to_i, raw_data: invitation) end def self.delete_record(list_id, invitation_id, store) record = store.find_for_list_by_invitation_id(list_id, invitation_id) store.delete(record[:id]) end def self.fetch_records(list_id, store) store.find_for_list(list_id).map { |record| record[:raw_data] } end end
true
1ae8296f86427228acd3513c5fe601974e1237fd
Ruby
JonathanUriel/RailsWeb
/blog/app/controllers/articles_controller.rb
UTF-8
2,116
2.984375
3
[]
no_license
class ArticlesController < ApplicationController #Variables con "@" sirven para manipular esa variable ya sea #vistas o controladores, la variable sin @ solo se puede usar #en el controlador, en el cual fue declarada #GET /articles def index #Todos los registros @article = Article.all #Trae todos los datos de la BD end #GET /articles/:id def show #Encontrar registro por ID @article = Article.find(params[:id]) #where #Article.where("id = ? OR|AND title = ? ",params[:id],params[:title]) #sean diferente #Article.where.not("id = ?",params[:id]) end #GET /articles/new def new #Se manda un objeto(articulo) basio @article = Article.new end #POST /articles def create #Se inserta el objeto en la BD #sintaxis: new ("campo" params["formulario"]["Campo"]) #@article = Article.new(title: params[:article][:title], body: params[:article][:body]) #Manera corta de hacer un insert del Objeto a la BD @article = Article.new(article_params) #Create llama automaticamente al metodo save #@article = Article.create(title: params[:article][:title], body: params[:article][:body]) #@article.valid? es el articulo valido #@article.invalid? es el articulo invalido #Guardar en BD if @article.save #redireccionamiento redirect_to @article else render :new end end def edit #Se manda el objeto(articulo) al formulario @article = Article.find(params[:id]) end #PUT /articles/:id def update #Update #Actualiza el objeto en la BD @article = Article.find(params[:id]) if @article.update(article_params) redirect_to @article else render :edit end end #delete "/articles/:id" destroy def destroy #Delete #Busca el Articulo en la Bd @article = Article.find(params[:id]) #Destroy elimina el objeto de la BD @article.destroy #Se redirecciona a la pagina redirect_to articles_path end #------------------------------------------------------------------ #Metodos privados private def article_params #Campos que se permitiran para la creacion del objeto params.required(:article).permit(:title,:body) end end
true
2142bd3df573c0dded9f5ce903498dcbe5cc3a97
Ruby
bogdanovich/cadence-ruby
/examples/workflows/branching_workflow.rb
UTF-8
404
2.828125
3
[ "Apache-2.0" ]
permissive
require 'activities/random_number_activity' require 'activities/hello_world_activity' class BranchingWorkflow < Cadence::Workflow def execute random_number = RandomNumberActivity.execute!(max: 100) if random_number > 50 HelloWorldActivity.execute!('top half') else HelloWorldActivity.execute!('bottom half') end return "Number picked was: #{random_number}" end end
true
6a9a5a678f622c9d8ac46686ad386bab0f675964
Ruby
rohanphillips/activerecord-tvland-online-web-sp-000
/app/models/actor.rb
UTF-8
358
2.515625
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class Actor < ActiveRecord::Base has_many :shows, through: :characters has_many :characters def full_name self.first_name + " " + self.last_name end def list_roles collection = [] self.characters.joins(:show).each{|item| collection << (item.name + " - " + item.show.name) } collection end end
true
722a5a7d1158fd6fbcda30017ccc9bec38b15298
Ruby
jeik0210/prueba_capistrano
/app/models/user.rb
UTF-8
305
2.59375
3
[]
no_license
class User < ActiveRecord::Base belongs_to :editorial before_save :up_full_name def full_name paternal.to_s + " " + maternal.to_s + " " + name.to_s end def up_full_name self.name = self.name.upcase self.paternal = self.paternal.upcase self.maternal = self.maternal.upcase end end
true
e5e71c9bf9b4dedbbfaa01eb86cedcb58418d7aa
Ruby
reasonset/installed-font-list-html
/installed-font-list-html.rb
UTF-8
3,659
2.609375
3
[ "MIT" ]
permissive
#!/usr/bin/ruby require 'erb' ERB_TEMPLATE = <<EOF <html> <head> <title>Installed Fonts (<%= ([modename] + optionname).join(",") %>)</title> <style> p { margin-left: 40px; } section { margin-top: 15px; border-top: #339 solid 2px; } </style> </head> <body> <h1>Installed Fonts (<%= ([modename] + optionname).join(",") %>)</h1> <% fonts.keys.sort.each do |k| %> <section style="font-family: &quot;<%= k %>&quot;;"> <h2><%= k %> (<%= fonts[k][:fullname] %>)</h2> <p>The quick brown fox jumps over the lazy dog</p> <% if fonts[k][:monospace] %> <p>[monospace] 1lI|/\ 0O 6b 9g -=^~_ .,:; *+ ()[]{}&lt;&gt;</p> <% end %> <% if fonts[k][:kana] %> <p>[kana] いろはにほへと ちりぬるを </p> <% end %> <% if fonts[k][:hani] %> <p>[hani] 吾輩は猫である。名前は未だ無い。</p> <% end %> </section> <% end %> </body> </html> EOF OPTIONS = [] fonts = Hash.new modename = "All Installed" optionname = [] outfile = nil argv = [] ARGV.each do |i| if i =~ /^-/ $'.scan(/(.)/) {|c| argv.push("-" + $1) } else argv.push i end end p argv while arg = argv.shift break if arg == "--" case arg.strip when "-d" OPTIONS.push :list_dual when "-m" OPTIONS.push :list_mono when "-j" OPTIONS.push :req_kana optionname |= ["かな必須"] when "-H" OPTIONS.push :req_hani optionname |= ["漢字必須"] when "-o" outfile = argv.shift when "-h" STDERR.puts "Usage:" STDERR.puts " installed-font-list-html.rb [-m|-d] [-H] [-j] [-o outfile]" end end if outfile STDOUT.reopen(File.open(outfile, "w")) end STDERR.puts "building list.........." fontlist = nil if((OPTIONS & [:list_dual, :list_mono]).length > 1) STDERR.puts "-d, -m options are able to turn on only one of them." exit 1 end if OPTIONS.include?(:list_mono) modename = "Monospace" IO.popen(["fc-list", ":mono", ":", "family", "fullname", "spacing", "capability"], "r") do |io| fontlist = io.each.map {|i| i.split(":", 2)} end elsif OPTIONS.include?(:list_dual) modename = "Monospace + Dualspace" IO.popen(["fc-list", ":dual", ":", "family", "fullname", "spacing", "capability"], "r") do |io| fontlist = io.each.to_a end IO.popen(["fc-list", ":mono", ":", "family", "fullname", "spacing", "capability"], "r") do |io| fontlist |= io.each.to_a end fontlist = fontlist.map {|i| i.split(":", 2)} else IO.popen(["fc-list", ":", "family", "fullname", "spacing", "capability"], "r") do |io| fontlist = io.each.map {|i| i.split(":", 2)} end end fontlist.each do |fl| infoline = {fullname: nil, kana: false, hani: false, monospace: false} family = fl[0].split(",") capability = "" fullname = "" if fl[1] =~ /\bfullname=(.*?)(?::|$)/ infoline[:fullname] = $1.gsub('\\', '') end if fl[1] =~ /\bspacing=(.*?)\b/ spacing = $1 unless(spacing == "0" || spacing.casecmp?("proportional")) infoline[:monospace] = true end infoline[:spacing] = spacing end if fl[1] =~ /\bcapability=(.*)$/ capability = $1.gsub('\\', '') end infoline[:kana] = true if capability.include?("otlayout:kana") infoline[:hani] = true if capability.include?("otlayout:hani") next if OPTIONS.include?(:req_kana) && ! infoline[:kana] next if OPTIONS.include?(:req_hani) && ! infoline[:hani] family.each do |i| fonts[i.gsub('\\', '')] = infoline end STDERR.puts(infoline[:fullname] || family.first) end STDERR.puts "Generating HTML..............." ERB.new(ERB_TEMPLATE).run(binding)
true
08533550ada040ba7229c175d6dab15e3f6e606e
Ruby
tylergreason/pokemon_backend
/db/seeds.rb
UTF-8
2,538
3.015625
3
[]
no_license
require 'faker' # Pokemon.delete_all User.delete_all Team.delete_all # reset all pokemon types # natures # only seed natures if Nature.all is empty if Nature.all.count == 0 natures = PokeApi.get(:nature).results natures.each do |nature| name = nature.name Nature.find_or_create_by(name:name) end end # types # only seed types if Type.all is empty if Type.all.count == 0 types = PokeApi.get(:type).results types.each do |type| name = type.name Type.find_or_create_by(name:name) end end 700.times do |time| pokemon_number = time+1 if Pokemon.find_by(number: pokemon_number) == nil fetch_pokemon = PokeApi.get(pokemon: pokemon_number) name = fetch_pokemon.name.capitalize number = fetch_pokemon.id image_url = fetch_pokemon.sprites.front_default new_pokemon = Pokemon.find_or_create_by(name:name,number:number,image_url:image_url) # nature new_pokemon.natures << Nature.all.sample # types fetch_pokemon.types.each do |type| new_pokemon.types << Type.find_or_create_by(name: type.type.name) end # abilities abilities = fetch_pokemon.abilities abilities.each do |result| new_ability = Ability.find_or_create_by(name:result.ability.name) new_pokemon.abilities << new_ability end # moves moves = fetch_pokemon.moves moves.each do |result| new_move = Move.find_or_create_by(name: result.move.name) new_pokemon.moves << new_move end end end # user new_user = User.create(email:'[email protected]', password:'test') # create a new team, then give that team to the test user 4.times do new_team = Team.create(name: Faker::Team.name, description: "Desc: " + Faker::Lorem.sentence(word_count: 3), user_id: User.all.sample.id) 3.times do random_pokemon = Pokemon.all.sample if !new_team.pokemons.include?(random_pokemon) new_team.pokemons << Pokemon.all.sample end end new_user.teams << new_team end # make 4 of each pokemon's moves active Pokemon.all.each do |pokemon| # make each move not active PokemonMove.where(pokemon_id: pokemon.id, active:true).each {|pokemonMove| pokemonMove.active = false pokemonMove.save } 4.times do |time| if pokemon.moves[time] != nil pokemon.set_move_active(pokemon.moves[time]) end end end
true
16aced0ae01cf9e539877ead3d81dee6ea12bff2
Ruby
kupolak/codewars
/Ruby/7 KYU/Nickname Generator.rb
UTF-8
159
3.046875
3
[]
no_license
def nickname_generator(name) if name.length >= 4 /\A[auieoAUIEO]\z/.match(name[2]) ? name[0..3] : name[0..2] else "Error: Name too short" end end
true
2b22f4f2eb68a8a6afef82f95624fca7970fa364
Ruby
reneeknox/prime-ruby-online-web-pt-071519
/prime.rb
UTF-8
483
3.734375
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def prime?(integer) # 11 if integer < 2 false else a = (2..integer - 1).to_a # [3,4,5,6,7,8,9] # a = [3,4,5,6,7,8,9,10] # integer % n == 0 is prime # [].none? # None of the numbers prior to integer are divisible by integer # Madeline told me this is a good idea to include; I read that it passes each element of the collection to the block. # This helps us iterate over the range. a.none?{|n| integer % n == 0 } #true end end
true
89826b68188ab75e503c6a7caabeaa8dd4d3a6c1
Ruby
Artforge/has_many_translations
/lib/has_many_translations/control.rb
UTF-8
1,805
2.6875
3
[]
no_license
module HasManyTranslations module Control def self.included(base) # :nodoc: base.class_eval do include InstanceMethods # alias_method_chain :create_translation?, :control # alias_method_chain :update_translation?, :control end end module InstanceMethods def force_update with_translation_flag(:force_update) do yield if block_given? save end end def force_update! with_translation_flag(:force_update) do yield if block_given? update_translations! end end def force_update? !!@force_update end def skip_translation with_translation_flag(:skip_translation) do yield if block_given? save end end def skip_translation! with_translation_flag(:skip_translation) do yield if block_given? save! end end def skip_translation? !!@skip_translation end private # Used for each control block, the +with_version_flag+ method sets a given variable to # true and then executes the given block, ensuring that the variable is returned to a nil # value before returning. This is useful to be certain that one of the control flag # instance variables isn't inadvertently left in the "on" position by execution within the # block raising an exception. def with_translation_flag(flag) begin instance_variable_set("@#{flag}", !instance_variable_get("@#{flag}")) yield # ensure # instance_variable_set("@#{flag}", nil) end end end end end
true
5c6141454f1e0349a5bb009539c44248fa73c788
Ruby
shoehead0125/crawler-study
/chapter-1/sbcr-sample/sbcr1.rb
UTF-8
491
2.9375
3
[]
no_license
#! /usr/bin/env ruby # -*- coding: utf-8 -*- require 'pry' require 'cgi' def parse(page_source) dates = page_source.scan( %r!(\d+)年 ?(\d+)月 ?(\d+)日<br />!) url_titles = page_source.scan( %r!^<a href="(.+?)">(.+?)</a><br />!) url_titles.zip(dates).map { |(aurl, atitle), ymd| [ CGI.unescapeHTML(aurl), CGI.unescapeHTML(atitle), # splat 可変長引数 Time.local(*ymd), ] } end x = parse(open('samplepage.html', &:read)) puts x[0, 2]
true
ead40f498e599c58f6d5d9380e3b0c201f70a7e8
Ruby
mvz/ripper_ruby_parser
/test/samples/loops.rb
UTF-8
378
3.140625
3
[ "MIT" ]
permissive
# Loop samples def for_samples for foo in bar end for foo, bar in baz end for foo, in bar end end # begin..end in conditions # def while_until_samples while begin foo end bar end until begin foo end bar end while begin foo end do bar end until begin foo end do bar end foo while begin bar end foo until begin bar end end
true
acbb70446386aad295f8f93d882f70d221e3d874
Ruby
dafoxia/mumble-ruby
/lib/mumble-ruby/packet_data_stream.rb
UTF-8
3,408
3.171875
3
[ "MIT" ]
permissive
module Mumble class PacketDataStream def initialize(data=nil) @data = data || 0.chr * 8192 @data = @data.split '' @pos = 0 @ok = true @capacity = @data.size end def valid @ok end def size @pos end def left @capacity - @pos end def append(val) if @pos < @capacity @data[@pos] = val.chr skip else @ok = false end end def append_block(data) len = data.size if len < left @data[@pos, len] = data.split('') skip len else @ok = false end end def get_block(len) if len < left ret = @data[@pos, len] skip len else @ok = false ret = [] end ret end def get_next if @pos < @capacity ret = @data[@pos].ord skip else ret = 0 @ok = false end ret end def rewind @pos = 0 end def skip(len=1) len < left ? @pos += len : @ok = false end def put_int(int) if !(int & 0x8000000000000000).zero? && (~int < 0x100000000) int = ~int puts int if int <= 0x3 # Shortcase for -1 to -4 append(0xFC | int) else append(0xF8) end end if int < 0x80 # Need top bit clear append(int) elsif int < 0x4000 # Need top two bits clear append((int >> 8) | 0x80) append(int & 0xFF) elsif int < 0x200000 # Need top three bits clear append((int >> 16) | 0xC0) append((int >> 8) & 0xFF) append(int & 0xFF) elsif int < 0x10000000 # Need top four bits clear append((int >> 24) | 0xE0) append((int >> 16) & 0xFF) append((int >> 8) & 0xFF) append(int & 0xFF) elsif int < 0x100000000 # It's a full 32-bit integer. append(0xF0) append((int >> 24) & 0xFF) append((int >> 16) & 0xFF) append((int >> 8) & 0xFF) append(int & 0xFF) else # It's a 64-bit value. append(0xF4) append((int >> 56) & 0xFF) append((int >> 48) & 0xFF) append((int >> 40) & 0xFF) append((int >> 32) & 0xFF) append((int >> 24) & 0xFF) append((int >> 16) & 0xFF) append((int >> 8) & 0xFF) append(int & 0xFF) end end def get_int v = get_next int = 0 if (v & 0x80) == 0x00 int = v & 0x7F elsif (v & 0xC0) == 0x80 int = (v & 0x3F) << 8 | get_next elsif (v & 0xF0) == 0xF0 x = v & 0xFC if x == 0xF0 int = get_next << 24 | get_next << 16 | get_next << 8 | get_next elsif x == 0xF4 int = get_next << 56 | get_next << 48 | get_next << 40 | get_next << 32 | get_next << 24 | get_next << 16 | get_next << 8 | get_next elsif x == 0xF8 int = get_int int = ~int elsif x == 0xFC int = v & 0x03 int = ~int else @ok = false int = 0 end elsif (v & 0xF0) == 0xE0 int = (v & 0x0F) << 24 | get_next << 16 | get_next << 8 | get_next elsif (v & 0xE0) == 0xC0 int = (v & 0x1F) << 16 | get_next << 8 | get_next end return int end end end
true
b6c04964c0a96fdf8abc3f0bd92bdd09af4c35f9
Ruby
kunks001/boris_bikes
/boris_bikes.rb
UTF-8
278
3.640625
4
[]
no_license
# class Person # def initialize(name) # @name = name # @bike = 0 # end # def name # @name # end # def id # end # def bike # @bike # end # def gets_bike # @bike +=1 # end # def returns_bike # @bike -=1 # end # end
true
c0d3c4b9f2fe9690ecffa5651868569e774919a8
Ruby
skunath/STAT
/phoneme.rb
UTF-8
6,887
2.9375
3
[]
no_license
class Phoneme def initialize(args) @cskip = -10.0 @csub = 35.0 @cexp = 45.0 @cvowel = 10.0 @epsilon = 0.0 @character = args[:character] @type = args[:type] # vowel, consonant, diacritic @manner = args[:manner] @place = args[:place] @high = args[:high] @back = args[:back] @round = args[:round] @long = args[:long] @syllabic = args[:syllabic] @nasal = args[:nasal] @retroflex = args[:retroflex] @voice = args[:voice] @lateral = args[:lateral] @aspirated = args[:aspirated] # # @features = {} @features[:manner] = args[:manner] @features[:place] = args[:place] @features[:high] = args[:high] @features[:back] = args[:back] @features[:round] = args[:round] @features[:long] = args[:long] @features[:syllabic] = args[:syllabic] @features[:nasal] = args[:nasal] @features[:retroflex] = args[:retroflex] @features[:voice] = args[:voice] @features[:lateral] = args[:lateral] @features[:aspirated] = args[:aspirated] end def character() return @character end def vowel() return @type == "vowel" end def vowel_cost() return @cvowel end def alter_feature(name, value) if !@features[name].nil? if @features[name].class == String @features[name] = value else @features[name] = @features[name] + value end else @features[name] = value end end def combine_features(phoneme_2) for feature in phoneme_2.features self.alter_feature(feature[0], feature[1]) end end #@vowel a single vowel object #@pasofalkjf alksfja lskfja sf def self.vowel(vowel) # Runs a subprocess and applies handlers for stdout and stderr # Params: # +vowel+:: command line string to be executed by the system if vowel.vowel() return @cvowel end return 0.0 end def to_s @character end def set_character(full_character) @character = full_character end def consonant() return @type == "consonant" end def sound_type() return @type end def round() return @round end def long() return @long end def manner() return Manner[@manner] end def high() return High[@high].to_f end def back() return Back[@back] end def place() return Place[@place] end def syllabic() return @syllabic end def nasal() return @nasal end def retroflex return @retroflex end def voice return @voice end def lateral return @lateral end def aspirated return @aspirated end def features features = [] for pair in @features.to_a features << pair if !pair[1].nil? end return features end def vowel_compare(compare_vowel) diff = 0.0 # roundness comparison roundness_diff = (self.round() - compare_vowel.round()).to_f.abs * Salience["round"] # length comparison length_diff = (self.long() - compare_vowel.long()).to_f.abs * Salience["long"] # backness comparison backness_diff = (self.back() - compare_vowel.back()).to_f.abs * Salience["back"] # height comparison height_diff = (self.high() - compare_vowel.high()).to_f.abs * Salience["high"] # manner comparison manner_diff = (self.manner() - compare_vowel.manner()).to_f.abs * Salience["manner"] diff = diff + roundness_diff + length_diff + backness_diff + height_diff + manner_diff return diff.round(5); end def consonant_compare(compare_consonant) diff = 0.0 # manner comparison manner_diff = (self.manner() - compare_consonant.manner()).to_f.abs * Salience["manner"] # place comparison place_diff = (self.place() - compare_consonant.place()).to_f.abs * Salience["place"] # syllabic comparison syllabic_diff = (self.syllabic() - compare_consonant.syllabic()).to_f.abs * Salience["syllabic"] # nasal comparison nasal_diff = (self.nasal() - compare_consonant.nasal()).to_f.abs * Salience["nasal"] # retroflex comparison retroflex_diff = (self.retroflex() - compare_consonant.retroflex()).to_f.abs * Salience["retroflex"] # voice comparison voice_diff = (self.voice() - compare_consonant.voice()).to_f.abs * Salience["voice"] # lateral comparison lateral_diff = (self.lateral() - compare_consonant.lateral()).to_f.abs * Salience["lateral"] # aspirated comparison aspirated_diff = (self.aspirated() - compare_consonant.aspirated()).to_f.abs * Salience["aspirated"] diff = manner_diff + place_diff + syllabic_diff + nasal_diff + retroflex_diff + voice_diff + lateral_diff + aspirated_diff return diff.round(5) end def mixed_compare(other_phoneme) vowel, consonant = nil if self.vowel() vowel = self consonant = other_phoneme else vowel = other_phoneme consonant = self end # begin computing diff diff = 0.0 # syllabic comparison #syllabic_diff = (consonant.syllabic() - vowel.syllabic()).to_f.abs * Salience["syllabic"] # nasal comparison #nasal_diff = (consonant.nasal() - vowel.nasal()).to_f.abs * Salience["nasal"] # retroflex comparison #retroflex_diff = (consonant.retroflex() - vowel.retroflex()).to_f.abs * Salience["retroflex"] # manner comparison manner_diff = (consonant.manner() - vowel.manner()).to_f.abs * Salience["manner"] # place comparison place_diff = (consonant.place() - 0.0).to_f.abs * Salience["place"] # voice comparison voice_diff = (consonant.voice() - 0.0).to_f.abs * Salience["voice"] # lateral comparison lateral_diff = (consonant.lateral() - 0.0).to_f.abs * Salience["lateral"] # aspirated comparison aspirated_diff = (consonant.aspirated() - 0.0).to_f.abs * Salience["aspirated"] diff = manner_diff + place_diff + voice_diff + lateral_diff + aspirated_diff return diff.round(5) end def self.total_diff(phoneme_1, phoneme_2) # must be two phonemes coming in... alphabets will be different # This function determines the actual difference between two characters/phonemes # based on the features it knows of of the character/phoneme. # Notes: # This should probably create an on the fly hash when the class is instantiated to memoize # previous diff calculations...It should speed things up. first_string_vowel = phoneme_1.vowel() second_string_vowel = phoneme_2.vowel() if !first_string_vowel && !second_string_vowel # case where both characters/phonemes are consonants return phoneme_1.consonant_compare(phoneme_2) elsif first_string_vowel && second_string_vowel # case where only vowels are passed return phoneme_1.vowel_compare(phoneme_2) else # Mixed case with a vowel and a consonant return phoneme_1.mixed_compare(phoneme_2) end end end
true
b076f8978f2f51233968c40cafb911da7ea22421
Ruby
sujankh/SimPlParser
/simplparser.rb
UTF-8
655
3.1875
3
[]
no_license
#!/usr/bin/ruby require_relative './lexer' require_relative './parser' def getTokenKind() $tokenizer.getTokenKind() end def getTokenText() $tokenizer.getTokenText() end #consume token def nextToken() $tokenizer.nextToken() end def parseProgram() inputFile = ARGV[0] begin $tokenizer.readFile(inputFile) nextToken() #initialize the lexer to put the cursor to current token parseStatements() nextToken() #consume EOF puts "End Of File" puts "Successful parse." rescue ParseError => e puts "Syntax error:" puts e.message end end #start parser program $tokenizer = Tokenizer.new parseProgram()
true
cfe0c4cb1d8f7b017e7b337507fa9a30f4e7a645
Ruby
DavidPAdams/nlr
/Lesson_1_hw/calculator.rb
UTF-8
148
3.015625
3
[]
no_license
def add(a,b) a + b end def subtract(c,d) c - d end def multiply2(e,f) e * f end def divide2(g,h) h != 0 ? g/h : "undefined" end
true
435e0a014017addf59e0d5837188a3436b5a6bd5
Ruby
dbirtwell/RubyLearning_32
/Week_7/rubyprograms/lesson7exercise3.rb
UTF-8
1,509
4.65625
5
[]
no_license
# lesson7exercise3.rb # David Birtwell =begin Week 7 Exercise 3. Write a method called month_days, that determines the number of days in a month. Usage: days = month_days(5) # 31 (May) days = month_days(2, 2000) # 29 (February 2000) Remember, you could use the Date class here. Read the online documentation for the Date class. You must account for leap years in this exercise. =end require 'date' # Default the year to current year if not passed in def month_days(month_num, year=Time.now.year) # Steps: # 1) Set the date to the 1st day of the next month for which we want to # count the number of days. # 2) Roll back a day, which takes us to the end of the month # 3) Return that day of the mmonht (end of month day == number of days in # the month # # The code snipprt below shifts/increments the month of the date 1 month. # date >> 1 # # The below snippet subtracts one day from the date. In our case, this rolls # back the date to the previous day (subtracts one day). # Note - This automativcally handes leap year. # date - 1 # # returns the day of the date # date.day ((Date.new(year, month_num, 1) >> 1) - 1).day end days = month_days(5) # 31 (May) puts "Days: #{days}" days = month_days(2, 2000) # 29 (February 2000) puts "Days: #{days}" days = month_days(6) # 30 (June) puts "Days: #{days}" days = month_days(12) # 31 (December) puts "Days: #{days}" days = month_days(1, 2008) # 1 (January 2008) puts "Days: #{days}"
true
b01cbb60fbaea909777bd1791b0921f794220ee2
Ruby
ruben/smalltalk-best-practice-patterns
/3-behaviour/2-messages/3-intention_revealing_message/1-paragraph_editor.rb
UTF-8
372
3.515625
4
[]
no_license
# How do you communicate your intent when the implementation is simple? # # Send a message to “self.” Name the message so it communicates what is to be done rather than how it is to be done. # Code a simple method for the message. # We highlight a rectangle (WHAT) by reversing it (HOW) class ParagraphEditor def highlight rectangle reverse rectangle end end
true
2b9dfea91af9ec88509bd6b28c4b25310574dbfa
Ruby
avescodes/botfly
/lib/botfly/callback_context.rb
UTF-8
1,629
2.765625
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
module Botfly class CallbackContext def initialize(caller, params) setup_params(params) @caller = caller end def method_missing(name, *args) @caller.send(name,*args) if name.to_s.scan(/^setup/).empty? end private # OK, so. Get the instance's eigenclass, then, call the private method define_method - thus created the method called #{name} that returns value. Basically attr_reader but for any generic variable. def expose(name, value) (class<<self;self;end).send(:define_method,name,proc{value}) end def setup_params(params) params.each do |name,value| send(:"setup_#{name}", value) end end def setup_roster_item(roster_item) expose(:roster_item, roster_item) end def setup_message(message) expose(:message, message) expose(:body, message.body) expose(:chat_state, message.chat_state) expose(:subject, message.subject) expose(:type, message.type) expose(:from, message.from) expose(:to, message.to) end def setup_presence(presence, pre = '') expose(:"#{pre}presence", presence) expose(:"#{pre}from", presence.from) expose(:"#{pre}show", presence.show) expose(:"#{pre}priority", presence.priority) expose(:"#{pre}status", presence.status) expose(:"#{pre}type", presence.type) end def setup_old_presence(presence); setup_presence(presence, 'old_') end def setup_time(time); expose(:time, time) end def setup_nick(nick); expose(:from, nick); end def setup_text(text); expose(:text, text); expose(:body, text); end end end
true
70b038d2f1ea28c74e0ab5ee01e3adace44c24cc
Ruby
takahiro825/furima-28705
/spec/models/user_spec.rb
UTF-8
5,697
2.734375
3
[]
no_license
require 'rails_helper' describe User do before do @user = FactoryBot.build(:user) end describe 'ユーザー登録' do context 'ユーザー登録がうまくいくとき' do it "nicknameとemail、passwordとpassword_confirmation、family_name、first _name、family_name_kana、first _name_kana、birthdayが存在すれば登録できる" do expect(@user).to be_valid end it "emailは@が存在すれば登録できる" do @user.email = "[email protected]" expect(@user).to be_valid end it "passwordが6文字以上でであれば登録できる" do @user.password = "000000" @user.password_confirmation = "000000" expect(@user).to be_valid end it "passwordが半角英数字混同であれば登録できる" do @user.password = "abc123" @user.password_confirmation = "abc123" expect(@user).to be_valid end it "ユーザー名の苗字は全角で入力すれば登録できる" do @user.family_name = "後藤" expect(@user).to be_valid end it "ユーザー名の名前は全角で入力すれば登録できる" do @user.first_name = "貴裕" expect(@user).to be_valid end it "ユーザー名の苗字のフリガナは全角(カタカナ)で入力すれば登録できる" do @user.family_name_kana = "ゴトウ" expect(@user).to be_valid end it "ユーザー名の名前のフリガナは全角(カタカナ)で入力すれば登録できる" do @user.first_name_kana = "タカヒロ" expect(@user).to be_valid end end context 'ユーザー登録がうまくいかないとき' do it "nicknameが空だと登録できない" do @user.nickname = "" @user.valid? expect(@user.errors.full_messages).to include("Nickname can't be blank") end it "emailが空では登録できない" do @user.email = "" @user.valid? expect(@user.errors.full_messages).to include("Email can't be blank") end it "重複したemailが存在する場合登録できない" do @user.save another_user = FactoryBot.build(:user) another_user.email = @user.email another_user.valid? expect(another_user.errors.full_messages).to include("Email has already been taken") end it "emailには@が存在しない場合登録できない" do @user.email = "fgfdug42354ff" @user.valid? expect(@user.errors.full_messages).to include("Email is invalid") end it "passwordが空では登録できない" do @user.password = "" @user.valid? expect(@user.errors.full_messages).to include("Password can't be blank") end it "passwordが5文字以下であれば登録できない" do @user.password = "00000" @user.password_confirmation = "00000" @user.valid? expect(@user.errors.full_messages).to include("Password is too short (minimum is 6 characters)") end it "passwordが存在してもpassword_confirmationが空では登録できない" do @user.password_confirmation = "" @user.valid? expect(@user.errors.full_messages).to include("Password confirmation doesn't match Password") end it "password_confirmationが存在してもpasswordが空では登録できない" do @user.password = "" @user.valid? expect(@user.errors.full_messages).to include("Password can't be blank") end it "family_nameが空では登録できない" do @user.family_name = "" @user.valid? expect(@user.errors.full_messages).to include("Family name can't be blank") end it "first_nameが空では登録できない" do @user.first_name = "" @user.valid? expect(@user.errors.full_messages).to include("First name can't be blank") end it "family_name_kanaが空では登録できない" do @user.family_name_kana = "" @user.valid? expect(@user.errors.full_messages).to include("Family name kana can't be blank") end it "first_name_kanaが空では登録できない" do @user.first_name_kana = "" @user.valid? expect(@user.errors.full_messages).to include("First name kana can't be blank") end it "ユーザー名の苗字は全角で入力しなければ登録できない" do @user.family_name = "ssss" @user.valid? expect(@user.errors.full_messages).to include("Family name is invalid") end it "ユーザー名の名前は全角で入力しなければ登録できない" do @user.first_name = "aaaa" @user.valid? expect(@user.errors.full_messages).to include("First name is invalid") end it "ユーザー名の苗字のフリガナは全角(カタカナ)で入力しなければ登録できない" do @user.family_name = "たたたた" @user.valid? expect(@user.errors.full_messages).to include() end it "ユーザー名の名前のフリガナは全角(カタカナ)で入力しなければ登録できない" do @user.first_name_kana = "おおおお" @user.valid? expect(@user.errors.full_messages).to include("First name kana is invalid") end it "birthdayが空では登録できない" do @user.birthday = "" @user.valid? expect(@user.errors.full_messages).to include("Birthday can't be blank") end end end end
true
83b6236399857bfa000814239d608205f72daf6e
Ruby
Zoratoostar/Exercise_9
/cargo_train.rb
UTF-8
170
2.625
3
[]
no_license
class CargoTrain < Train def hitch_carriage(car) super(car) if car.is_a?(FreightWagon) end def to_s "#{unique_number}_cargo_#{carriages.count}" end end
true
4db89e62b28142104ae898e29ade0cd4b4eb8bc1
Ruby
yoshida-eth0/async_enum
/lib/enumerator/async.rb
UTF-8
2,086
2.96875
3
[]
no_license
class Enumerator class Async < Enumerator class Lockset def initialize @semaphores = Hash.new do |locks, key| locks[key] = Mutex.new end end def lock(key = :__default__, &thread_unsafe_block) @semaphores[key].synchronize(&thread_unsafe_block) end alias_method :evaluate, :instance_exec end def initialize(enum, pool_size = nil) @enum = enum @pool_size = pool_size @lockset = Lockset.new end def to_a @enum.to_a end def sync @enum end alias_method :to_enum, :sync def size @enum.size end def each(&work) raise_error('each') unless block_given? if @pool_size threads = @pool_size.times.map do Thread.new do loop do @enum.any? ? evaluate(*@enum.next, &work) : break end end end threads.each(&:join) @enum.rewind else unlimited_threads(&work).each(&:join) end self end def with_index(start = 0, &work) @enum = @enum.with_index(start) if block_given? each(&work) else self end end def with_object(obj, &work) @enum = @enum.with_object(obj) if block_given? each(&work); obj else self end end def map(&work) raise_error('map') unless block_given? if @pool_size outs = [] with_index do |item, index| outs[index] = evaluate(item, &work) end outs else unlimited_threads(&work).map(&:value) end end private def evaluate(*args, &work) @lockset.instance_exec(*args, &work) end def unlimited_threads(&work) @enum.map do |*args| Thread.new{ evaluate(*args, &work) } end end def raise_error(method) raise ArgumentError, "tried to call async #{method} without a block" end end end
true
5ab454070399ce5448d45bc7b1048b04361bfc4b
Ruby
loushark/battle
/spec/player_spec.rb
UTF-8
316
2.625
3
[]
no_license
require 'player' describe Player do let(:player) { Player.new("Crazy Teaspoon") } it 'initializes a name on a new player instance' do expect(player.name).to eq("Crazy Teaspoon") end it 'initializes a deafult hitpoint value on a new player instance' do expect(player.hitpoints).to eq(60) end end
true
1c98fa3bf47ba4e84d90afacef8c7f210ee2b28a
Ruby
pychap/Launch_school_101
/lesson_3/medium_1.rb
UTF-8
1,834
3.828125
4
[]
no_license
require 'pry' # stoneage_rock = "The Flintstones Rock!" # n = 23 # 10.times do # # n = n += 1 # puts stoneage_rock.center(n += 1) # end # 10.times {|num| puts (" " * num) + stoneage_rock} # statement = "The Flintstones Rock!" # flintstones_hash = {} # letters = ('A'..'Z').to_a + ('a'..'z').to_a # letters.each do | letter | # letter_frequency = statement.scan(letter).count # flintstones_hash[letter] = letter_frequency if letter_frequency > 0 # end # p flintstones_hash # puts "the value of 40 + 2 is " + "#{(40 + 2)}" # def titleize word # split_apart = word.split(//) # upper_cased = [] # split_apart.each do |letter| # upper_cased << letter.upcase # end # final = upper_cased.join # puts final # end # titleize("Now is the time for all good men to come to the aid of their party!") munsters = { "Herman" => { "age" => 32, "gender" => "male" }, "Lily" => { "age" => 30, "gender" => "female" }, "Grandpa" => { "age" => 402, "gender" => "male" }, "Eddie" => { "age" => 10, "gender" => "male" }, "Marilyn" => { "age" => 23, "gender" => "female"} } # "age_group" => "adult" # munsters[key_counter].merge!({:"age_group" => "adult"}) # key[counter] == [['new_key' => 'new_value']] # need to use map # loop # def sort_munsters(age) # case age # when age == 0..17 then "kid" # when age == 17..65 then "adult" # when age > 65 then "senior" # else # false # end # age # end # # now add to the munsters hash # munsters.each+ do |key, value| # sort_munsters(value:("age", =>)) # key[:key] << value.merge!([-1, "age_group" => "age"]) # end # the REAL answer munsters.each do |name, details| case details["age"] when 0...18 details["age_group"] = "kid" when 18...65 details["age_group"] = "adult" else details["age_group"] = "senior" end end p munsters
true
fa59bf57da8f5a0febc23ea56fc64b089091c658
Ruby
DanielVartanov/isp-logs-parser
/lib/traffic_splitter.rb
UTF-8
380
2.84375
3
[ "MIT" ]
permissive
class TrafficSplitter def self.split_traffic!(traffic) hosts = traffic.daily.internal.highest_twenty_hosts + traffic.nightly.internal.highest_twenty_hosts + traffic.daily.world.highest_twenty_hosts + traffic.nightly.world.highest_twenty_hosts hosts.sort! { |left, right| right.amount_of_traffic <=> left.amount_of_traffic } hosts[0..19] end end
true
ba8f9b57f2d9dc4e3e1d90ede3382b3029aadce0
Ruby
slbug/test_img
/app/models/image.rb
UTF-8
439
2.546875
3
[]
no_license
class Image < ActiveRecord::Base validates :title, :presence => true, :length => { :minimum => 3 } validates :url, :presence => true, :length => { :minimum => 10 } before_save :ensure_uid private def ensure_uid if uid.blank? allowed_symbols = ('a'..'z').to_a + ('A'..'Z').to_a + (0..9).to_a self.uid = (0...5).collect { allowed_symbols[Kernel.rand(allowed_symbols.length)] }.join end end end
true
a154896e0969d98155f169a98c77c8c8131824ea
Ruby
mizuhoiimori/rubybook
/private.rb
UTF-8
166
3.171875
3
[]
no_license
class Cafe def staff makanai end private def makanai "店員スペシャルメニュー" end end cafe = Cafe.new puts cafe.staff puts cafe.makanai
true
b73ce11b5edde4c06e1f2c904e6608b3ef0a827d
Ruby
RichardCharman/takeaway-challenge
/spec/customer_spec.rb
UTF-8
799
2.734375
3
[]
no_license
require 'customer' describe Customer do it { expect(subject).to respond_to(:show_menu) } describe '#ordering' do it 'should take an order for food with 2 arguments' do expect(subject).to respond_to(:order_item).with(2).argument end it { expect(subject).to respond_to(:view_order) } it 'should display correct order' do subject.order_item("burger", 2) expect(subject.view_order).to eq [{"burger"=>4}, {"burger"=>4}] end it 'should give correct price' do subject.order_item("burger", 2) expect(subject.order_price).to eq ("The cost for your order is £8.0") end it 'should raise an error if placing empty order' do expect{subject.place_order}.to raise_error "You haven't ordered any food" end end end
true
2e09106b0fa5478524f95e5cd61da1987aba2e62
Ruby
biancaguzenski/basic-algorithms-and-data-structures
/Others/is_palindrome.rb
UTF-8
617
3.53125
4
[]
no_license
require "test/unit/assertions" include Test::Unit::Assertions def to_char(string) string = string.downcase.chars string = string.keep_if {|c| c =~ /[abcdefghijklmnopqrstuvwxyz]/ }.join is_palindrome(string) end def is_palindrome(string) i = string.size-1 reversed = "" while i >= 0 reversed << string[i] i -= 1 end reversed == string ? true : false end assert_equal to_char("abba"), true assert_equal to_char("abbas"), false assert_equal to_char("tattarrattat"), true assert_equal to_char("Was it a palindrome?"), false assert_equal to_char("No lemon, no melon"), true
true
7640ea18727d0ca0f1884b9755e7d45b92e9588a
Ruby
sithobog/seo_tool
/lib/seo/user.rb
UTF-8
1,032
2.609375
3
[]
no_license
require 'sequel' require 'bcrypt' module Seo class User attr_accessor :id DB = Sequel.connect(:adapter => 'postgres', :host => 'localhost', :database => 'warden_test', :user => 'tester', :password => 'test_password') def initialize(id, username, password, ip) @id = id @username = username @password = password @ip = ip create_table end def authenticate(attempted_password) if @password == attempted_password true else false end end def self.get(id) DB.from(:users).where(:id => id).all end def self.get_by_name(name) DB.from(:users).where(:username => name).all end def add_user(name,password) users = DB.from(:users) users.insert.(:username => name, :password => password) end def create_table DB.create_table? :users do primary_key :id String :username String :password Inet :user_ip end end end end
true
239a53c5500c6187dc4a0644b3d836edb2aafeb8
Ruby
liyijie/span_report
/app/span_report/logfile/csv_file_operate.rb
UTF-8
4,027
2.71875
3
[]
no_license
# encoding: utf-8 module SpanReport::Logfile class CsvReader ################################################### # 这里传入的files并不是普通的文件名,而是封装的结构 ################################################## def initialize(files, is_temp=false) @files = files @is_temp = is_temp end def parse(processors) @files.each do |fileinfo| filename = fileinfo.filename puts "process log #{filename}" if @is_temp parse_temp_file filename, processors else parse_one_file filename,processors end end end private def parse_one_file filename, processors line_index = 0 head_info = [] File.foreach(filename) do |line| line = line.chop contents = line.split ',' if line_index == 0 contents.each do |item| head_info << item end else data_map = {} contents.each_with_index do |item, i| next if item.to_s.empty? data_map[head_info[i].to_s] = item end time = data_map["time"] ue = data_map["ue"] data_map.map do |key, value| key = key.encode('utf-8') value = value.encode('utf-8') end point_data = SpanReport::Simulate::PointData.new time, ue, data_map point_data.expand_data next if (point_data.rsrp.to_f <= -140) || !point_data.valid? # 调用每个处理器处理数据 processors.each do |process| # begin process.process_pointdata point_data # rescue Exception => e # puts "process data error:#{e.backtrace}" # next # end end end line_index += 1 end end def parse_temp_file filename, processors line_index = 0 File.foreach(filename) do |line| if line_index == 0 line_index += 1 next end line = line.chop contents = line.split ',' data_map = {} data_map["time"] = contents[0] data_map["ue"] = "1" data_map["lontitute"] = contents[3] data_map["latitude"] = contents[4] data_map["scell_pci"] = contents[5] data_map["scell_freq"] = "1890" data_map["scell_rsrp"] = contents[6] data_map["scell_sinr"] = 0 (0..7).each do |i| data_map["ncell_pci_#{i}"] = contents[7 + 2*i] data_map["ncell_freq_#{i}"] = "1890" data_map["ncell_rsrp_#{i}"] = contents[8 + 2*i] end time = data_map["time"] ue = data_map["ue"] point_data = SpanReport::Simulate::PointData.new time, ue, data_map point_data.expand_data # 调用每个处理器处理数据 processors.each do |process| # begin process.process_pointdata point_data # rescue Exception => e # puts "process data error:#{e.backtrace}" # next # end end line_index += 1 end end end class CsvWriter def initialize resultfile @export_datas = [] open_file resultfile end def add_data pointdata @export_datas << pointdata write_result end def << pointdata add_data pointdata end def close_file flush @file.close if @file end private def open_file result_file # puts "output csv file is:#{result_file}" result_file = result_file.encode 'gbk' @file = File.new(result_file, "w") @file.puts head_string end def write_result if @export_datas.size > 100 flush end end def flush @export_datas.each do |pointdata| @file.puts pointdata.to_s.encode 'gbk' end @export_datas.clear end def head_string SpanReport::Simulate::PointData.head_string end end end
true
710f5273f61dc58c0fb0b13300a706c306711ca9
Ruby
tsunagun/cheats
/webapi/yahoo/assistsearch.rb
UTF-8
1,068
2.90625
3
[]
no_license
# -*- coding: utf-8 -*- # Yahoo Web APIを使って関連検索ワードの取得を行うスクリプト class Yahoo # ライブラリ読み込み require 'pp' require 'open-uri' require 'nokogiri' require 'cgi' # Yahoo Web APIのアプリケーションIDをyahoo_key.txtから読み込む load 'yahoo_key.txt' # APIへのリクエストURLを生成する def self.make_request_url(query) base_uri = "http://search.yahooapis.jp/AssistSearchService/V1/webunitSearch?" params = [ "appid=" + YAHOO_KEY, "query=" + CGI.escape(query) ].join("&") url = base_uri + params end # 入力文字列の形態素解析結果を取得 def self.assistsearch(input) results_path = "/xmlns:ResultSet/xmlns:Result" request_url = self.make_request_url(input) parser = Nokogiri::XML(open(request_url)) results = parser.xpath(results_path, parser.namespaces) results.map do |result| result.text end end end # queryの漢字変換候補を求める query = ARGV[0] || "大学" pp Yahoo.assistsearch(query)
true
8c03794f02fdea2f7956f361af6bbdd3e8173987
Ruby
angelv8a8/SP1Ruby
/Tarea1/Tarea1.rb
UTF-8
5,708
3.546875
4
[]
no_license
module Tarea1 def atoi(str) valor = 0 digitos = str.split("") digitosC = digitos.count digitosC -= 1 mul = 1 digitosC.downto(0) do | i | case digitos[i] when "0" valor = valor when "1" valor += 1 * mul when "2" valor += 2*mul when "3" valor += 3*mul when "4" valor += 4*mul when "5" valor += 5*mul when "6" valor += 6*mul when "7" valor += 7*mul when "8" valor += 8*mul when "9" valor += 9*mul else puts "Error, digito invalido " + digitos[i] return end mul = mul*10 end return valor end def char_count( s, c) letras = s.split(""); contador = 0 if c.to_s.size > 1 puts "ERROR: El segundo parametro debe ser un caracter" return nil end letrasC = letras.count 0.upto(letrasC - 1) do | i | if c == letras[i] contador += 1 end end return contador end def sort(elArray, is_asc) resultado = Array.new #puts elArray 0.upto(elArray.count - 1) do |i| if is_asc indexMenor = getMayor(elArray) else indexMenor = getMenor(elArray) end #puts "menor " + indexMenor.to_s palabraMenor = elArray.delete_at(indexMenor) resultado.insert(0,palabraMenor) end return resultado end def getMayor(array) index = 0; mayor = array[0] 0.upto(array.count - 1 ) do | i | #puts "It " + i.to_s if array[i] >= mayor mayor = array[i] index = i end end return index end def getMenor(array) index = 0; menor = array[0] 0.upto(array.count - 1 ) do | i | if array[i] <= menor menor = array[i] index = i end end return index end def hanoi(height,fromPole, toPole, withPole) height_i = height.to_i if height_i >= 1 hanoi(height_i-1,fromPole.to_i,withPole.to_i,toPole.to_i) moveDisk(fromPole.to_i,toPole.to_i) hanoi(height_i-1,withPole.to_i,toPole.to_i,fromPole.to_i) end end def moveDisk(fp,tp) puts "Mover disco de " + fp.to_i.to_s + " a " + tp.to_i.to_s end def cuenta_palabras (frase) hash = Hash.new(0) palabras = frase.to_s.split(" ") puts "Tamaño " + palabras.count.to_s c_palabras = palabras.count 0.upto(c_palabras -1) do | i | #puts palabras[i].to_s + " " + hash[palabras[i].to_s].to_s hash[palabras[i].to_s] = hash[palabras[i].to_s] + 1 end return hash end def palindromo?(x) tam = x.to_s.size valid = true; 0.upto(x.size-1) do | i | str = x[i].concat(" ").concat(x[tam-i-1]) if x[i] != x[tam-i-1] valid = false; break; end end return valid end class Dessert @@desserts = 0 def name=(value) @value = value end def name @name end def calories=(value) @calories = value end def calories @calories end def initialize(name, calories) @name = name @calories = calories @size = nil @@desserts += 1 end def healthy? if @calories < 200 return true end return false end def delicious? return true end def count return @@desserts end def to_s # YOUR CODE HERE end end class JellyBean < Dessert def flavor=(value) @flavor = value end def flavor @flavor end def initialize(name, calories, flavor) super(name, calories) @flavor = flavor end def delicious? if @flavor == "black licorice" return false end return super end end end module Action @@distance = 0; def jump(vel) @@distance = rand(vel.to_i) + 2 puts "I jumped forward #{@@distance} feet!" end end class Rabbit include Action attr_reader :name, :velocidad def initialize(name) @name = name @velocidad = 8 end def run() distInicial = 0 start = Time.now while distInicial < 33 do jump(@velocidad) distInicial += @@distance end puts (Time.now - start).to_s + " segundos" end end class Cricket include Action #include Date attr_reader :name, :velocidad def chirp() 0.upto(10 + rand(90)) do | i | puts i.to_s + " Chirp... chirp!!!" end end def initialize(name) @name = name @velocidad = 4 end def run() distInicial = 0 start = Time.now while distInicial < 33 do jump(@velocidad) distInicial += @@distance end puts (Time.now - start).to_s + " segundos" end end class Computer include Tarea1 @@users = {} @fileDir def initialize username, password @username = username @password = password @fileDir = Hash.new @files = {} end def insert (name) if @fileDir[name] == 0 puts "Error, el archivo ya existe" else @fileDir[name] = Time.now.to_s end end def ls (sort) keys = @fileDir.keys if sort.to_s == "asc" keys = Tarea1.sort(keys,true) else keys = Tarea1.sort(keys,false) end 0.upto(keys.count-1) do | i | puts keys[i] + "\t" + @fileDir[keys[i]] end puts "End of List" end end
true
085048caa650229e2bfe0a807d3ab35698a28855
Ruby
eriese/risqueFactr
/app/models/partner.rb
UTF-8
1,489
2.5625
3
[]
no_license
# == Schema Information # # Table name: partners # # id :integer not null, primary key # user_id :integer # pref_id :integer # name :string(255) # frequency :string(255) # familiarity :integer # exclusivity :string(255) # created_at :datetime not null # updated_at :datetime not null # class Partner < ActiveRecord::Base attr_accessible :user_id, :pref_id, :name, :frequency, :familiarity, :exclusivity, :pref_attributes belongs_to :user has_many :encounters belongs_to :pref accepts_nested_attributes_for :pref validates :user_id, :name, :presence => true def most_recent self.encounters_by_date.first end def encounters_by_date self.encounters.order("took_place DESC") end def risk @risk = 0 case self.exclusivity when "exclusive" @risk += 1 when "only having sex with known others" @risk += 2 when "not exclusive with disclosure of other partners" @risk += 3 when "not exclusive, no disclosure of other partners" @risk += 4 end @risk += 10 - self.familiarity return @risk end def pronoun if self.pref_id return self.pref.pronoun else return nil end end def at_risk(disease) if self.most_recent if disease.risk_window(self.user) return disease.risk_window(self.user) < self.most_recent.took_place else return true end else return false end end end
true
621b7828249eceb670d5c8d180e2d654e0037a90
Ruby
mattcrowe5/prime-ruby-prework
/prime.rb
UTF-8
239
3.828125
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def prime?(number) if number == 0 || number == 1 || number == -1 return false end x = 2 stop = number/x while x <= stop if number % x == 0 return false end x+=1 stop = number/x end return true end
true
2c0d7194c26d2c4c281000aff8eda7b9ea5af79a
Ruby
pongsanti/mcotv3
/lib/util/record_op.rb
UTF-8
214
3.046875
3
[]
no_license
class RecordOp def initialize(array, skip) @array = array @skip = skip end def split return [], [] if @array.empty? return @array[0, @skip] || [], @array[@skip, @array.length] || [] end end
true
37d71161e4e43ca08ad17d28f7e45a215b8f8a17
Ruby
SVRourke/pantry_backend
/test/models/user_test.rb
UTF-8
1,588
2.828125
3
[]
no_license
require "test_helper" class UserTest < ActiveSupport::TestCase def setup @good_user = User.create(name: 'sam', email: '[email protected]', password: 'pass') @email_user = User.new(name: 'sam', password: 'pass') @password_user = User.new(name: 'sam', email: '[email protected]') @lists = [ List.create(name: "list one"), List.create(name: "list two"), List.create(name: "list three") ] @lists.each { |l| l.contributors.push(@good_user) } @users = [ User.new(name: "a", email: "[email protected]", password: "passsword"), User.new(name: "b", email: "[email protected]", password: "passsword"), User.new(name: "c", email: "[email protected]", password: "passsword") ] @users.each {|u| @good_user.friends.push(u)} end test "user can be created" do assert @good_user.valid?, "Valid User does not save" end test "user invalid without email" do assert_not @email_user.valid?, "Able to save User without email" end test "user invalid without password" do assert_not @password_user.valid?, "Able to save user without password" end test "user can have multiple lists" do assert @good_user.lists.count > 1, "list relationship needs to be two ways" end test "user can leave a list" do @good_user.leave_list(@lists.first) assert @good_user.lists.count < 3, "issue with #leave_list" end test "user can have many friends" do assert @good_user.friends.count > 1 end test "user can remove a friend" do @good_user.unfriend(@users.first) assert @good_user.friends.count < 3 end end
true
caee6c35cc9c1eb3a1fc4dea0efd0ff4f028b20c
Ruby
denalibalser/compost_cli
/lib/cli.rb
UTF-8
2,782
3.875
4
[ "MIT" ]
permissive
#our CLI Controller, welcoming the user and dealing with user input class CLI def start list_boroughs select_boroughs list_addresses select_address collection_day go_compost end def list_boroughs puts "Welcome! Composting is an easy way to reduce waste. However, urban composting can be hard, we're here to help simplify it for New Yorkers!" puts "There are compost drop-off locations in all five boroughs:" borough_arr = Borough.list_borough_names puts borough_arr.each_with_index(1) do |borough, index| "#{index}. #{borough.name}" end select_borough(borough_arr) end def select_borough(borough_arr) input = nil while input != "exit" puts "Please select a borough 1 - 5 from which you would like to find a compost drop-off location or type 'exit' to exit:" input = gets.strip.downcase input = input.to_i if input > 0 && input < 5 the_borough = borough_arr[input-1].name.strip puts "Here is the list of compost drop-off locations for #{the_borough.upcase}:" list_addresses(the_borough) elsif input.downcase == "exit" go_compost else puts "Invalid Input. Please enter the number of the borough in which you would like to find a compost drop-off location or type 'exit' to exit:" end end end def list_addresses(the_borough) puts "Please select the number that corresponds with the compost drop-off address you would like more information on or type 'list' to return to the list of boroughs or type 'exit' to exit:" addresses_arr = Address.list_addresses(the_borough) puts addresses_arr.each_with_index(1) do |address, index| "#{index}. #{address.name}, #{address.location}" end select_address(addresses_arr) end def select_address(addresses_arr) input = nil while input != "exit" input = gets.strip.downcase input = input.to_i if input > 0 chosen_address = addresses_arr[input-1].name.upcase puts "Here are the days and hours of operation for #{chosen_address}:" collection_day(chosen_address) elsif input == "exit" go_compost elsif input == "list" list_boroughs else puts "Invalid Input. Please select the number that corresponds with the compost drop-off address you would like more information on or type 'list' to return to the list of boroughs or type 'exit' to exit:" end end end def collection_day(chosen_address) collection_days = CollectionDay.new(chosen_address) puts collection_days.address_info end def go_compost puts "Now get out there and start composting New York!" exit end end
true
0db8d3c1f1065294feba0a034401ca400c4c537e
Ruby
Nitemaeric/coding-lessons
/ruby/1-programming-fundamentals/oop.rb
UTF-8
341
3.796875
4
[]
no_license
class Me attr_accessor :age attr_writer :name attr_reader :story def initialize(name = nil, age, story: nil) @age = age @name = name @story = story end def name(addon = '') "#{@name} is #{story} #{addon}" end def do_something(&block) puts "hi" block.call(20) if block puts "someting" end end
true
4a17d313d24e22f7c26ce0799eabdffe910b3f08
Ruby
chrisrobertspdx/flatiron-store-project-v-000
/app/models/cart.rb
UTF-8
930
2.6875
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class Cart < ActiveRecord::Base belongs_to :user has_many :line_items has_many :items, through: :line_items def add_item(item_id) existing = self.line_items.detect{|l| l.item_id == item_id.to_i} if !existing #self.line_items << Line_Item.new({item_id: item_id, cart_id: self.cart_id, quantity: 1}) self.line_items.new({item_id: item_id, quantity: 1}) #self.save else existing.quantity += 1 existing.save #this is awkward existing end end def total self.line_items.reduce(0) {|sum,i| sum + (i.item.price * i.quantity) } end def checkout self.line_items.each {|e| e.item.inventory -= e.quantity e.item.save } self.status = "submitted" self.save #binding.pry end end
true
6f36509fc3a963edb7333c26db43a0692c48a919
Ruby
coderjonny/myrubyscripts
/meta.rb
UTF-8
3,643
3.890625
4
[]
no_license
class Test def one @var = 99 two end def two puts @var end end p t = Test.new p t.one class Test puts "In the definition of class Test" puts "self = #{self}" puts "Class of self = #{self.class}" end class Test @var = 99 def self.value_of_var @var end end puts Test.value_of_var animal = "cat" puts animal.upcase.reverse def animal.speak puts "Then #{self} says miaow" end animal.speak puts animal.upcase class Dave def self.class_method_one puts "Class method one" end def Dave.class_method_one puts "Class method one overwritten using self!?" end def Dave.class_method_two puts "Class method two" end end Dave.class_method_one Dave.class_method_two class Test @var = 99 def self.var @var end def self.var=(value) @var = value end end puts "\n\n\noriginal value = #{Test.var}" Test.var = "cat" puts "New value = #{Test.var}" animal = "dog" class << animal def speak puts "The #{self} says woof!" end end animal.speak animal = "dog" def animal.speak puts "the #{self} says woof!" end singleton = class << animal def lie puts "The #{self} lies down!" end self #<<return singleton class object end animal.speak animal.lie puts "\n\n\nsingleton class object is #{singleton}" puts "it defines methods #{singleton.instance_methods - 'cat'.methods}" print <<-okay Ruby alreadu has attr_accessor, which defines getter and setter methods. normally, thought, these are defined as instance methods and hence will access values stored in instances of a class. To make them work with class-level instance variable, we have to invoke attr_accessor in the singleton class: okay class Test @var = 99 class << self attr_accessor :var end end puts "Original value = #{Test.var}" Test.var = "cat" puts "New value = #{Test.var}" #Inheritance and Visibility class Base def a_method puts "Got here" end private :a_method end class Derived1 < Base public :a_method end #^^^^^^^^^^^^^^^^^^^^^^^^^^^^ #same shit as this #class Derived1 < Base # def a_method(*) # super # end # public :a_method #end class Derived2 < Base end pub = Derived1.new pub.a_method pub.a_method module Logger def log(msg) STDERR.puts Time.now.strftime("%H:%M:%S: ") + "#{self} (#{msg})" end end class Song include Logger end class Album include Logger end s = Song.new s.log("created") module Mod def greeting "Hello" end end class Example include Mod end ex = Example.new puts "before, change, greeting is #{ex.greeting}" module Mod def greeting "hi" end end puts "after change, greeting is #{ex.greeting}" puts "\n\nextend method useful when adding the instance methods to a particular object. you do this using Object#extend." module Humor def tickle "#{self} says hee, hee!" end end obj = "Grouchy" obj.extend Humor puts obj.tickle H = "sleepy" H.extend Humor puts H.tickle #adding a module's methods at the class level: module Humor def tickle "#{self} says hee, hee!" end end class Grouchy extend Humor end puts Grouchy.tickle #Metaprogramming Class-level Macros class Example def self.add_logging def log(msg) STDERR.puts Time.now.strftime("%H:%M:%S: ") + "#{self}(#{msg})" end end add_logging end ex = Example.new ex.log("hello") class Logger def self.add_logging def log(msg) STDERR.puts Time.now.strftime("%H:%M:%S: ") + "#{self} (#{msg})" end end end class Example < Logger add_logging end ex = Example.new ex.log("hello")
true
6098e883352425e7ee7a6c395ed153f919d73f5f
Ruby
AlexanderCleasby/ruby-objects-has-many-lab-online-web-pt-102218
/lib/artist.rb
UTF-8
415
3.328125
3
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
class Artist attr_accessor :name, :songs @@library =[] def initialize(name) @name=name @songs=[] end def add_song(song) song.artist=self @songs.push(song) @@library.push(song) end def add_song_by_name(songname) newsong = Song.new(songname) self.add_song(newsong) end def self.song_count @@library.length end end
true
1206f4061c920671861c00f632e58775b2dfd8c3
Ruby
eljefesun/assignment_ruby_warmup
/anagram-testing.rb
UTF-8
384
3.28125
3
[]
no_license
# # Note: "pears" doesn't appear in the output # > anagrams("pears") # # => ["APERS","APRES","ASPER","PARES","PARSE","PRASE","PRESA","RAPES","REAPS","SPARE","SPEAR"] # > anagrams("zygote") # #=> [] words = %w[cars scar for four creams scream racs] anagrams = words.group_by { |word| word.chars.sort }.values # => [["cars", "scar", "racs"], ["for"], ["four"], ["creams", "scream"]]
true
96015b5ee01cea46a737835e3fc0585d0eb8b6f4
Ruby
billgloff/data-engineering
/data_normalizer/app/services/import_service.rb
UTF-8
837
3.046875
3
[]
no_license
require 'csv' class ImportService attr_accessor :total_amount_gross def initialize(file) @file = file @total_amount_gross = 0.0 end def parse CSV.parse(@file, headers: true, col_sep: "\t").each do |row| customer_name, item_description, item_price = row[0], row[1], row[2].to_f purchase_count, merchant_address, merchant_name = row[3].to_i, row[4], row[5] merchant = Merchant.find_or_create_by(name: merchant_name, address: merchant_address) customer = Customer.find_or_create_by(name: customer_name) item = Item.find_or_create_by(description: item_description, price: item_price, count: purchase_count, merchant: merchant) Purchase.find_or_create_by(customer: customer, item: item) @total_amount_gross += item_price.to_f end end end
true
7ec192cf66f3d7abff5173a3bb9de72e78202f9f
Ruby
rashmiagar/some_programs
/are_anagrams.rb
UTF-8
626
3.734375
4
[]
no_license
module AreAnagrams def self.are_anagrams?(string_a, string_b) if string_a.length != string_b.length false elsif hash_string_a = Hash.new string_a.downcase.each_char{|chr| if hash_string_a.has_key?(chr) hash_string_a[chr] += 1 else hash_string_a[chr] = 1 end } string_b.downcase.each_char{|chr| if hash_string_a[chr] != nil && hash_string_a[chr] > 0 hash_string_a[chr] -= 1 else return false end } return true end end end puts AreAnagrams.are_anagrams?('orchestra', 'carthorse')
true
5b02f0e0bb7ad0d9f1d630e589c7fb2a6025e6ce
Ruby
LogaJ/CukeSalad
/Examples/Calculator/features/lib/alternative/roles/calculating_web_user.rb
UTF-8
2,002
2.96875
3
[]
no_license
# To run with this version of the Calculating Individual: # cucumber --profile alternative require 'web_calculator' require 'capybara' require 'capybara/dsl' Capybara.app = WebCalculator Capybara.default_driver = :rack_test module CalculatingIndividual # Uses a Browser to perform its tasks include Capybara # This is not a page object. It is a WebUser, specialised to our application # See the comments in the 'enter' and 'press' method for an explanation of why def switch_on_the_calculator visit '/' end def enter value fill_in 'number', :with => value # Because the calculator is a simple web_app with only # one page we can put the id for the field here. In a more complex web-app # we would pass in the id of the thing to enter # The task would express the action as: enter( :the_number, "10") # Because we can change the id used in our application, # we would just change the id in the application to be 'the_number'. # If we were on a project where we could not change the id # in the application we would write an 'ApplicationExpert' # to map :the_number to the id for the field 'number'. Our CalculatingIndividual # would ask the ApplicationExpert for the id of the symbol :the_number # See 'press' below for am explanation of how an ApplicationExpert # would work end def press operator click_button operator.to_s # Here, our 'operator' happens to also match the id for the button. # If we were on a project where we could not choose what the id # was for buttons, we would write an ApplicationExpert to map # the symbol used in the task to the symbol for that button. # The ApplicationExpert would only need to know what page it # was on to find a mappings class (or yml file) for the fields on that page. end def look_at_the_display find_field('display').value.to_i end def is_the_calculator_ready? page.body.should =~ /Calculator is Ready!/ end end
true
ca7a91c4a3b8001d0981aa19dbd7eda13b3067ba
Ruby
jsiny/101_programming_foundations
/exercises/12_medium_2/ex_04.rb
UTF-8
2,134
4.34375
4
[]
no_license
def balanced_1?(string) has_opening = 0 has_closing = 0 string.chars.each do |char| has_opening += 1 if char == '(' has_closing += 1 if char == ')' break if has_closing > has_opening end has_opening == has_closing end p balanced_1?('What (is) this?') == true p balanced_1?('What is) this?') == false p balanced_1?('What (is this?') == false p balanced_1?('((What) (is this))?') == true p balanced_1?('((What)) (is this))?') == false p balanced_1?('Hey!') == true p balanced_1?(')Hey!(') == false p balanced_1?('What ((is))) up(') == false puts '--------' # Shorter method def balanced_2?(string) parentheses = 0 string.each_char do |char| parentheses += 1 if char == '(' parentheses -= 1 if char == ')' break if parentheses < 0 end parentheses.zero? end p balanced_2?('What (is) this?') == true p balanced_2?('What is) this?') == false p balanced_2?('What (is this?') == false p balanced_2?('((What) (is this))?') == true p balanced_2?('((What)) (is this))?') == false p balanced_2?('Hey!') == true p balanced_2?(')Hey!(') == false p balanced_2?('What ((is))) up(') == false puts '--------' # Further Exploration DIFFERENT_PAIRS = [%w(( )), %w([ ]), %w({ })].freeze QUOTES = ['\'', '\"'].freeze def extended_balance?(string) result = [] DIFFERENT_PAIRS.each do |pair| result << balanced?(string, pair) end QUOTES.each do |quote| result << balanced_with_quote?(string, quote) end result.all? { |element| element == true } end def balanced?(string, pair) duo = 0 string.each_char do |char| duo += 1 if char == pair[0] duo -= 1 if char == pair[1] break if duo < 0 end duo.zero? end def balanced_with_quote?(string, quote) string.chars.count { |char| char == quote }.even? end p extended_balance?('hey {') == false p extended_balance?('hello (madam) I will be {your} guide') == true p extended_balance?("hello (madam) I'll be {your} guide") == false p extended_balance?('hello (madam') == false p extended_balance?('} next {') == false p extended_balance?("I 'love' you") == true p extended_balance?('I "would" love to meet ya') == true
true
fee458ef5658aad7d2329dfd5f2ba43b77cfe3b6
Ruby
heavenchou/cbwork-bin
/xml2epub/unicode_service.rb
UTF-8
453
2.875
3
[]
no_license
require 'Unihan2' class UnicodeService def initialize @u2 = Unihan2.new end def level1?(code) return false if code.nil? # Unicode 3.0 以內 在 mobile 可以正確顯示 v = @u2.ver(code) raise CbetaError.new(500), "Unihan2.ver 回傳 nil, code: #{code}" if v.nil? v <= 3 end def level2?(code) return false if code.nil? # Unicode 10 以內 在 desktop 有字型可以顯示 @u2.ver(code) <= 10 end end
true
5d3d6bc419bc9554c23f0ffdd6e489b3a770b25b
Ruby
mpeiros/mediocritter
/app/models/user.rb
UTF-8
947
2.625
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
class User < ActiveRecord::Base has_many :comments has_many :searches has_many :favorites has_many :favorited_tweets, through: :favorites, source: :tweet validates_presence_of :email, :username, :password_hash validates_uniqueness_of :email, :username def password @password ||= BCrypt::Password.new(password_hash) end def password=(new_password) @password = BCrypt::Password.create(new_password) self.password_hash = @password end def self.authenticate(email, password) if @user = User.find_by(email: email) @user.password == password ? @user : nil end end def favorited?(tweet) self.favorited_tweets.each do |fav_tweet| if fav_tweet.tweet_time == tweet.tweet_time && fav_tweet.text == tweet.text return true end end false end def sort_favorited_tweets self.favorited_tweets.sort_by { |fav_tweet| fav_tweet.favorited_at(self.id) }.reverse end end
true
86bb9490fcff1198db279cd6dc9a8681b761e3ba
Ruby
evelynnkaplan/matrix_convert_to_zero
/lib/matrix_convert_to_zero.rb
UTF-8
1,550
4.09375
4
[]
no_license
# Updates the input matrix based on the following rules: # Assumption/ Given: All numbers in the matrix are 0s or 1s # If any number is found to be 0, the method updates all the numbers in the # corresponding row as well as the corresponding column to be 0. # Time complexity: O(n*m) where n is the length of the matrix and m is the length of the longest array within the matrix. # For both loops, the outer will run n times and the inner will run m times. # Space complexity: O(n+m) where n is the length of the matrix and m is the length of the longest array within the matrix. # The maximum number of values in the outer_indexes array will be equal to n and the maximum number of values in the # inner_indexes array will be equal to m. def matrix_convert_to_zero(matrix) outer_indexes = [] inner_indexes = [] matrix.each_with_index do |arr, outer_index| arr.each_with_index do |num, inner_index| if num == 0 if !outer_indexes.include?(outer_index) outer_indexes << outer_index end if !inner_indexes.include?(inner_index) inner_indexes << inner_index end end end end matrix.each_with_index do |arr, outer_index| if outer_indexes.include?(outer_index) arr.each_with_index do |num, inner_index| if num == 1 arr[inner_index] = 0 end end end arr.each_with_index do |num, inner_index| if inner_indexes.include?(inner_index) && num == 1 arr[inner_index] = 0 end end end return matrix end
true
d7a179bfa72eb98eb17c6415186dbabd9fac9bfa
Ruby
smernick/square_array-001-prework-web
/square_array.rb
UTF-8
333
4.125
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def square_array(array) new_array = [] #defines a new array array.each do |number| #tells program to iterate throught the array new_array << (number**2) #tells program to square each number and add it to the back of the new_array end return new_array #returns the value of the new_array at the end of the iteration. end
true
082002b598742027165abc6e74d82ba343c9976f
Ruby
jamensky/programming-univbasics-4-building-nested-hashes-online-web-prework
/intro_to_ruby_hashes_lab.rb
UTF-8
1,254
2.671875
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def base_hash hash = {:railroads => {} } end def monopoly_with_second_tier hash = {:railroads => {} } hash[:railroads][:pieces] = 4 return hash end def monopoly_with_third_tier hash = {:railroads => {} } hash[:railroads][:pieces] = 4 hash[:railroads][:rent_in_dollars] = {:one_piece_owned => 25, :two_pieces_owned => 50, :three_pieces_owned => 100, :four_pieces_owned => 200} hash[:railroads][:names] = {:reading_railroad => {}, :pennsylvania_railroad => {}, :b_and_o_railroad => {}, :shortline_railroad => {} } return hash end def monopoly_with_fourth_tier hash = {:railroads => {} } hash[:railroads][:pieces] = 4 hash[:railroads][:rent_in_dollars] = {:one_piece_owned => 25, :two_pieces_owned => 50, :three_pieces_owned => 100, :four_pieces_owned => 200} hash[:railroads][:names] = {:reading_railroad => {}, :pennsylvania_railroad => {}, :b_and_o_railroad => {}, :shortline_railroad => {} } hash[:railroads][:names][:reading_railroad]["mortgage_value"] = "$100" hash[:railroads][:names][:pennsylvania_railroad]["mortgage_value"] = "$200" hash[:railroads][:names][:b_and_o_railroad]["mortgage_value"] = "$400" hash[:railroads][:names][:shortline_railroad]["mortgage_value"] = "$800" return hash end
true
28b7e5e7e1cdd8cca1c0e1ca33523566024e324c
Ruby
TwiceNo/Patterns
/1/projecteuler40.rb
UTF-8
523
3.5625
4
[]
no_license
def get_digit(n) curr_block = 0 curr_upper = 0 prev_upper = 0 while curr_upper < n prev_upper = curr_upper curr_upper += 9 * 10 ** curr_block curr_block += 1 end offset = n - prev_upper - 1 sequence = 1 while sequence * curr_block < offset sequence += 1 end fraction = "" for i in prev_upper + 1..prev_upper + 1 + sequence do fraction += i.to_s end return fraction.split(//)[offset].to_i end def product() res = 1 for i in 0..7 do res *= get_digit(10 ** i) end return res end puts product()
true
8928f80734828e3a26073de7d7dc4b0409c1b73e
Ruby
sgeorgi/pageflow
/app/helpers/pageflow/files_helper.rb
UTF-8
597
2.78125
3
[ "MIT" ]
permissive
module Pageflow module FilesHelper def file_format(file) file.format.presence || '-' end def file_dimensions(file) if file.width && file.height "#{file.width} x #{file.height}px" else "-" end end def file_duration(file) if file.duration_in_ms total_seconds = file.duration_in_ms / 1000 seconds = total_seconds % 60 minutes = (total_seconds / 60) % 60 hours = total_seconds / (60 * 60) format("%02d:%02d:%02d", hours, minutes, seconds) else "-" end end end end
true
ac61ab9e1d574456ea1d95bec66e67724e509a85
Ruby
mixophrygian/Text-Adventure
/text_adventure.rb
UTF-8
8,294
4.03125
4
[]
no_license
#How to play this file! Open the command line, type "irb" then type "load 'text_adventure.rb'" whenever you want to play! The game will quit itself if you win or lose. Load the file again to replay. class Dungeon attr_accessor :player def initialize(player_name) @player = Player.new(player_name) @rooms = [] end def add_room(reference, name, description, connections, eat_description, eatlethal, play_description, playlethal, win) @rooms << Room.new(reference, name, description, connections, eat_description, eatlethal, play_description, playlethal, win) end def start(location) @player.location = location show_current_description puts "\n" end def show_current_description puts find_room_in_dungeon(@player.location).full_description puts "\nWhat would you like to do next? Select \"Eat\", \"Play\", \"Explore\" or Exit\n" end def show_eat_description puts "\n" + find_room_in_dungeon(@player.location).eat_description end def show_play_description puts "\n" + find_room_in_dungeon(@player.location).play_description end def find_room_in_dungeon(reference) @rooms.detect{ |room| room.reference == reference} end def find_room_in_direction(direction) find_room_in_dungeon(@player.location).connections[direction] end def prompt(selection) unless selection == "eat" || selection =="play" || selection =="explore" || selection == "exit" || @player.dead === true puts "\nSelect Eat, Play, Explore or Exit\n" selection = gets.chomp.downcase end case selection when "explore" puts "\nWhich direction? North, South, East or West.\n" direction = gets.chomp.downcase unless direction == "north" || direction == "south" || direction == "east" || direction == "west" || direction == "exit" puts "\nSelect a valid drection, north south east or west.\n" direction = gets.chomp.downcase end go(direction.to_sym) when "eat" show_eat_description if(find_room_in_dungeon(@player.location).eatlethal) puts "GAME OVER #{@player.name}" @player.dead = true else puts "\n What would you like to do next? Select \"Eat\", \"Play\", or \"Explore\" or Exit\n" end when "play" show_play_description if(find_room_in_dungeon(@player.location).playlethal) puts "GAME OVER #{@player.name}" @player.dead = true elsif (find_room_in_dungeon(@player.location).win) puts "YOU WON, #{@player.name}!" @player.won = true else puts "\n What would you like to do next? Select \"Eat\", \"Play\", or \"Explore\" or Exit\n" end when "exit" puts "Goodbye breakfast-naut" @player.dead = true else puts "Invalid selection. Say again?" end end def go(direction) if find_room_in_direction(direction) != nil puts "You go #{direction.to_s} and find yourself in... \n\n" @player.location = find_room_in_direction(direction) show_current_description else puts "\nYou try to go #{direction} but soon reach a magnetic forcefield and must turn around" end end class Player attr_accessor :name, :location, :dead, :won def initialize(name) @name = name @dead = false @won = false end end class Room attr_accessor :reference, :name, :description, :connections, :eat_description, :eatlethal, :play_description, :playlethal, :win def initialize(reference, name, description, connections, eat_description, eatlethal, play_description, playlethal, win) @reference = reference @name = name @description = description @connections = connections @eat_description = eat_description @eatlethal = eatlethal @play_description = play_description @playlethal = playlethal @win = win end def full_description @name + "\n\nYou are in " + @description end end end puts "\nWelcome to \n==BREAKFAST GALAXY QUEST== \n\n" puts "Player, what is your name?" player_name = gets.chomp new_game = Dungeon.new(player_name) # initalizing locations new_game.add_room(:pancakenebula, "THE PANCAKE NEBULA", "a hazy region just north of Orion's griddle contain billions of pancake asteroids of all sizes. They are as fluffy as they are delicious.", {:south => :orionsgriddle, :north => :baconbelt, :east => :celestialcrepes, :west => :browndwarfbagels}, "These pancakes are delicious! The are perfectly browned with a hint of space-spice. Uh oh. You are now addicted to spice.", false, "You try playing with the pancakes a little too violently and a medium-sized cake spins out of control, thwaping you on the helmet causing you to lose consciousness briefly.", false, false) new_game.add_room(:orionsgriddle, "ORION'S GRIDDLE", "an area in which mysterious magnetism between the angle of nearby stars combined with a fortunate shipwreck of egg cargo has resulted in a seemingly neverending supply of perfectly cooked, zero-gravity formed scrambled eggs.", {:north => :pancakenebula}, "You take a bite and the eggs are magnificent! You didn't know scrambled eggs could be so good!", false, "You attempt to play with the eggs but they form a face on your plate that looks distinctly disapproving. All the other space-diners stop and stare. The space-record-needle swerves off the tracks. You have committed an intergalactic space crime. The burliest chef comes out of the kitchen and the last thing you remember is a frying pan quickly approaching your face plate...", true, false) new_game.add_room(:baconbelt, "THE BACON BELT", "a vast expanse of bacon strips in ring formation that spans the entire circumfrence of Breakfast-Saturn, the Bacon belt rings vary in crispyness according to their proximity to the celestial body. For well-done, try the outermost ring!.", {:south => :pancakenebula}, "You choose bacon on the crispier side and have fallen into a trance, a bacon-trance. You start imagining moving to the bacon belt, permanently.", false, "You try playing with bacon but run out of ideas, fast. Zero-gravity isn't very conducive to bacon art.", false, false) new_game.add_room(:celestialcrepes, "CELESTIAL CREPES", "a mysterious location in which crepes are as delicious as they are dangerous. These massive, moon-sized crepes are edible and benign until they reach maturity, at which time they gain sentience and the ability to swallow breakfast-nauts whole, like a venus fly trap would swallow an unassuming gnat. Their jam, accordingly, is dangerous to harvest and commands a great price in the intergalactic cafeteria.", {:west => :pancakenebula}, "You carefully select a crepe with your space fork, but you selected wrong! This medium-size crape expands in size drastically as its delicious-looking jaws open wide to eat YOU for breakfast! Death by crepes.", true, "Instead of attempting to eat these beautiful creatures you tickle one with your fork. It smiles in friendship and the crepes form a space-sofa to carry you as their new space emperor.", false, true) new_game.add_room(:browndwarfbagels, "BROWN DWARF BAGELS", "a zone formerly occuped by a star that went brown dwarf and thus did not achieve sufficient energy to explode. An enterprising breakfast-naut by the name of Hans saw the opportunity here to open a planet-sized delicatessen, harnessing the area's natural toasty-ness. They are famous for their bagels and brag a 'bagel event horizon' radius of 50 miles!", {:east => :pancakenebula}, "You attempt to eat a brown dwarf bagel...and succeed! Space lox and celestial cream cheese appear out of nowhere to make your space bagel more delicious.", false, "You try playing with your bagel but the bagel takes it too seriously and turns into a bready-black hole, engulfing you, the entire restaurant and the full galaxy, without even chewing. As a result the bagel is slightly bigger, but no one is around to notice.", true, false) #end intializing locations puts "\n#{new_game.player.name}, you have just completed your one THOUSANDTH illustrious space mission and have been awarded one round-trip hyper-space voyage to the ==BREAKFAST GALAXY==. The hyper-space arrival doc is located directly in...\n\n" new_game.start(:pancakenebula) selection = gets.chomp.downcase while(selection != "exit") new_game.prompt(selection) if new_game.player.dead || new_game.player.won break else selection = gets.chomp.downcase end end
true
de5cf0029aa89b1427a56ff9d7c136c7bf2c11d4
Ruby
Elazp/Online_week1
/Ejercicio2_Fruta_Solución.rb
UTF-8
1,376
3.984375
4
[]
no_license
require 'pry' class ShoppingCart @@prices_list = { :apple => 10, :orange => 5, :grape => 15, :banana => 20, :watermelon => 50 } def initialize @cart = Hash.new 0 end def get_item_price item @@prices_list[item] end def add_item_to_cart item @cart[item] += 1 end def show shopping_cart_calculated = calculate_shopping_cart shopping_cart_calculated.each_with_index do |(key,value),index| puts "#{index+1}: #{key} => #{@cart[key]} items #{value}€" end end def calculate_shopping_cart calculated_cart = {} @cart.each do |key,value| calculated_cart[key] = get_item_price(key) * value end calculated_cart end def get_cost shopping_cart_calculated = calculate_shopping_cart shopping_cart_calculated.reduce(0) {|sum, (key, val)| sum += val} #shopping_cart_calculated.values.reduce(:+) end end shopping_cart = ShoppingCart.new shopping_cart.add_item_to_cart :apple shopping_cart.add_item_to_cart :apple shopping_cart.add_item_to_cart :orange shopping_cart.add_item_to_cart :orange shopping_cart.add_item_to_cart :orange shopping_cart.add_item_to_cart :grape shopping_cart.add_item_to_cart :grape shopping_cart.add_item_to_cart :grape shopping_cart.add_item_to_cart :grape shopping_cart.add_item_to_cart :banana shopping_cart.show puts "The cost of your shopping cart is #{shopping_cart.get_cost}€"
true
8ca76452bae77847d1d42080a02ad539496bafe5
Ruby
pravsingh/Algorithm-Implementations
/Insertion_Sort/Ruby/mitogh/insertion_sort.rb
UTF-8
206
3.515625
4
[ "MIT" ]
permissive
def insertion_sort(arr = []) arr.each_with_index do |element, i| j = i while(j > 0 and (prev = arr[j-1]) > element) do arr[j] = prev j -= 1 end arr[j] = element end end
true
86421313bbbda763dd01bf7efb319fc070c71490
Ruby
romero-c-raul/ruby-basics
/strings/pr2.rb
UTF-8
80
2.625
3
[]
no_license
puts 'It\'s now 12 o\'clock.' # These are the same puts "It's now 12 o'clock."
true
86fd793fb46cf29e2bf427d912f0104b45f7d46c
Ruby
sp0gg/katas_and_exercises
/ruby/lib/codility/tape_equilibrium.rb
UTF-8
453
3.265625
3
[]
no_license
class TapeEquilibrium def self.solution a #add all together. sum = a.reduce :+ puts "sum #{sum}" left = a[0] right = sum - left puts "l #{left} r #{right}" min_diff = (right-left).abs puts "mindiff #{min_diff}" #run p through entire array. 1.upto(a.size-2) do |i| left += a[i] right -= a[i] diff = (right-left).abs min_diff = diff if min_diff > diff end p min_diff end end
true
7afb4ceac6dbcc6255d39137928781efb8ef40f4
Ruby
duong110397/learn-ruby
/300-children-exercises/array-exercises/ex6.rb
UTF-8
172
2.75
3
[]
no_license
=begin Thay the cac gia tri am co trong mang bang 0 =end arr = 10.times.map{rand(-10..10)} negativ = [] arr.each{|a| negativ.push(a < 0 ? 0 : a)} puts negativ.inspect
true
2378154ff94fdb670a5309a8d97b329053706307
Ruby
emmabeynon/rps-challenge
/spec/game_spec.rb
UTF-8
3,617
2.890625
3
[]
no_license
require 'game' describe Game do subject(:game) { described_class.new(player_1, player_2)} let(:player_1) { double :player_1, weapon: :rock } let(:player_2) { double :player_2, weapon: :scissors } describe 'default' do it 'accepts two players' do expect(game.player_1).not_to be_nil expect(game.player_2).not_to be_nil end end describe '#outcome' do it 'returns the outcome of the two weapons' do expect(game.outcome).to eq :win end it 'returns Draw when Rock and Rock are played' do allow(player_1).to receive(:weapon) {:rock} allow(player_2).to receive(:weapon) {:rock} expect(game.outcome).to eq :draw end it 'returns Lose when Rock and Paper are played' do allow(player_1).to receive(:weapon) {:rock} allow(player_2).to receive(:weapon) {:paper} expect(game.outcome).to eq :lose end it 'returns Win when Rock and Scissors are played' do allow(player_1).to receive(:weapon) {:rock} allow(player_2).to receive(:weapon) {:scissors} expect(game.outcome).to eq :win end it 'returns Draw when Paper and Paper are played' do allow(player_1).to receive(:weapon) {:paper} allow(player_2).to receive(:weapon) {:paper} expect(game.outcome).to eq :draw end it 'returns Win when Paper and Scissors are played' do allow(player_1).to receive(:weapon) {:paper} allow(player_2).to receive(:weapon) {:scissors} expect(game.outcome).to eq :lose end it 'returns Draw when Scissors and Scissors are played' do allow(player_1).to receive(:weapon) {:paper} allow(player_2).to receive(:weapon) {:paper} expect(game.outcome).to eq :draw end it 'returns Draw when Spock and Spock are played' do allow(player_1).to receive(:weapon) {:spock} allow(player_2).to receive(:weapon) {:spock} expect(game.outcome).to eq :draw end it 'returns Win when Spock and Rock are played' do allow(player_1).to receive(:weapon) {:spock} allow(player_2).to receive(:weapon) {:rock} expect(game.outcome).to eq :win end it 'returns Lose when Spock and Paper are played' do allow(player_1).to receive(:weapon) {:spock} allow(player_2).to receive(:weapon) {:paper} expect(game.outcome).to eq :lose end it 'returns Win when Spock and Scissors are played' do allow(player_1).to receive(:weapon) {:spock} allow(player_2).to receive(:weapon) {:scissors} expect(game.outcome).to eq :win end it 'returns Lose when Spock and Lizard are played' do allow(player_1).to receive(:weapon) {:spock} allow(player_2).to receive(:weapon) {:lizard} expect(game.outcome).to eq :lose end it 'returns Lose when Lizard and Rock are played' do allow(player_1).to receive(:weapon) {:lizard} allow(player_2).to receive(:weapon) {:rock} expect(game.outcome).to eq :lose end it 'returns Win when Lizard and Paper are played' do allow(player_1).to receive(:weapon) {:lizard} allow(player_2).to receive(:weapon) {:paper} expect(game.outcome).to eq :win end it 'returns Lose when Lizard and Scissors are played' do allow(player_1).to receive(:weapon) {:lizard} allow(player_2).to receive(:weapon) {:scissors} expect(game.outcome).to eq :lose end it 'returns Draw when Lizard and Lizard are played' do allow(player_1).to receive(:weapon) {:lizard} allow(player_2).to receive(:weapon) {:lizard} expect(game.outcome).to eq :draw end end end
true
8d720dd72fa3e5d80b152165b2b6cc963602d1a2
Ruby
charlesduan/photobook
/test/test_layout.rb
UTF-8
2,066
2.671875
3
[ "MIT" ]
permissive
require 'photobook' require 'minitest/autorun' require_relative 'helper' class TestLayout < Minitest::Unit::TestCase include TestHelper def test_new try_cases( [ 1, 'h', 1, [ :h ] ], [ 2, 'hlvpa*', 6, [ :h, :h, :v, :v, :a, :a ] ], [ 1, 'hhhh', 4, [ :h, :h, :h, :h ] ] ) do |pages, pat, exp_used, exp_pat| pp = Photobook::Layout.new( 'test layout', 'pages' => pages, 'pattern' => pat, ) assert_equal('test layout', pp.name) assert_equal(pages, pp.pages_used) assert_equal(exp_used, pp.photos_used) assert_equal(exp_pat, pp.pattern) end end def make_photos(orient) count = 0 return orient.split('').map { |x| count += 1 Photobook::Photo.new("Photo #{count}", x.to_sym) } end def test_match_fail try_cases( [ 'v', '' ], [ 'v', 'h' ], [ 'v', 'vv' ], [ 'a', '' ], [ 'a', 'hv' ], ) do |pat, orient| photos = make_photos(orient) pp = Photobook::Layout.new('test layout', 'pattern' => pat) assert_nil(pp.match(photos), 'Match not expected') end end def test_match_success try_cases( [ 'h', 'h', '1' ], [ 'v', 'v', '1' ], [ 'a', 'h', '1' ], [ 'a', 'v', '1' ], [ 'aa', 'hv', '12' ], [ 'ah', 'hh', '12' ], [ 'ah', 'hv', '21' ], [ 'ah', 'vh', '12' ], [ 'aaav', 'vvhh', '1342' ], [ 'aaavh', 'vvvhh', '12435' ], [ 'aaavh', 'vvhhh', '13425' ], [ 'vhaaa', 'hhhvv', '41235' ], [ 'vvvhhh', 'hhhvvv', '456123' ] ) do |pat, orient, exp| photos = make_photos(orient) pp = Photobook::Layout.new('test layout', 'pattern' => pat) res = pp.match(photos) refute_nil(res, "Match expected but not found") assert_instance_of(Array, res) assert_equal(exp.length, res.count) res.zip(exp.split('')).each do |res_photo, exp_photo| assert_instance_of(Photobook::Photo, res_photo) assert_equal("Photo #{exp_photo}", res_photo.name) end end end end
true
64bcb50deadf3c0e8ced8898130504bc02e4657f
Ruby
jaredonline/Ruby-Prolog-Solutions
/spec/01.Lists/03.kth_element_spec.rb
UTF-8
840
3.28125
3
[]
no_license
require '01.Lists/03.kth_element' describe LinkedList do before do @list = LinkedList.new(1) @list.next = LinkedList.new(2) @list.next.next = LinkedList.new(3) @list.next.next.next = LinkedList.new(4) end context 'OO' do [1, 2, 3, 4].each_with_index do |element, index| index += 1 # Prolog wants the first element to be 1; Ruby wants it to be 0 it "should return #{element} for the index #{index}" do @list[index].value.should == element end end end context 'functional' do [1, 2, 3, 4].each_with_index do |element, index| index += 1 # Prolog wants the first element to be 1; Ruby wants it to be 0 it "should return #{element} for the index #{index}" do functional_kth_element(@list, index).value.should == element end end end end
true
edd9c752ca9790f83ac9e3ce2ca63760f8b340df
Ruby
kalkrishnan/PhatStatsServer
/lib/news/news_factory.rb
UTF-8
1,399
2.796875
3
[]
no_license
require 'set' require 'mechanize' require 'json' require 'lib/util/word_count' require_relative 'news' class NewsFactory def initialize() @news = Set.new @wordCount = WordCount.new end def get_top_news if([email protected]?) json_news elsif build_news_repo end end def build_news_repo url json_news = JSON.parse(get_rss_feed url) json_news["entry"].each do |entry| @news.add(News.new(entry["title"],entry["summary"],entry["creator"],entry["images"])) end get_json_news end def build_player_news_repo url json_news = JSON.parse(get_rss_feed url) json_news["channel"]["item"].first(9).each do |entry| url = entry["link"].split("url=")[1] if(url.include? "com") url = url[0...url.index("com/")+3] elsif(url.include? "ca") url = url[0...url.index("ca/")+3] end @news.add(News.new(entry["title"],entry["description"]["content"], url, nil)) end get_json_news end def get_json_news String news = "[{\"topic\":\"news\",\"items\":["; i = 0; @news.each{|news_entry| news = news + news_entry.to_json+ ","; } news = news[0..-2] +"]}]" end def get_rss_feed(url) rss = open(url).read js = XmlSimple.xml_in rss, { 'ForceArray' => false, 'KeyToSymbol' => true} JSON.pretty_generate(js) end end
true
4f379f53b07533075fd868da1e459168b33d6f30
Ruby
aijoskobi/class_two
/hr/hr.rb
UTF-8
949
3.828125
4
[]
no_license
require 'employee' require 'salaried_employee' require 'hourly_employee' class HumanResources def initialize() @employee_list = [] @employee_list << HourlyEmployee.new("George", "Monkey", 10) @employee_list << HourlyEmployee.new("Sally", "Summers", 12) @employee_list << HourlyEmployee.new("Thomas", "Tank", 18) @employee_list << SalariedEmployee.new("Dora", "el Exlorer", 40000) end def run_payroll(week, hours) puts "\nFor week #{week} payroll" @employee_list.each do |employee| print_employee_paycheck(employee, hours) end end def print_employee_list @employee_list.each { |employee| puts employee } end private def print_employee_paycheck(employee, hours) puts "#{employee.fname} will be paid #{employee.pay(hours)}" end end # hr = HumanResources.new # hr.employee_list # # hr.run_payroll("one", 40) # hr.run_payroll("two", 32) # hr.run_payroll("three with overtime", 45)
true
fbd437980082b1a548971cb6d49e01418d7131b3
Ruby
La-Pulga/Learn-Ruby-the-Hard-way
/ex19bis.rb
UTF-8
418
4.28125
4
[]
no_license
def kiss_away(kiss1, kiss2) puts " I'd like to give you a kiss #{kiss1}" puts "Me too! #{kiss2}" puts "We can't do it both" puts "Yeah we can!\n" end puts "-------How many ways are there to do this?-------" kiss_away(':*', "xxx") puts "--------------Using variables-------------" kiss1 = ":*" kiss2 = "xxx" kiss_away(kiss1, kiss2) puts "--------Doing maths with love-------------" kiss_away(kiss1 * 3, kiss2)
true
897cff2c8ae89145646f73de400c814f9ae6dead
Ruby
helenndoo/collections_practice-v-000
/collections_practice.rb
UTF-8
1,173
4.40625
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
#1 array of integers and returns a copy of array in ascending order def sort_array_asc(array) array.sort do |a, b| a <=> b end end #2 same, but in descending order def sort_array_desc(array) array.sort do |b, a| a <=> b end end #3 ascending order by length def sort_array_char_count(array) array.sort_by do |word| word.length end end #4 swap 2nd and 3rd elements def swap_elements(array) element1 = array[1] element2 = array[2] array = [array[0], array[2], array[1]] end #5 reverse array def reverse_array(array) array.reverse end #6 takes array of strings and replaces 3rd character in each # --- with dollar sign ke$ha style jesus def kesha_maker(array) array.each do |string| string[2] = "$" end end #7 find A using start_with def find_a(array) array.select do |word| word[0] == "a" #= changes, == finds end end #8 adds all intergers together and returns sum def sum_array(array) array.inject do |a, b| a += b #a = a + b end end #9 add s to each word except for 2nd element def add_s(array) array.each_with_index.collect do |word, index| if index == 1 word else word << "s" end end end
true
28b7eab9395d29129975907f8c9581c2b373771c
Ruby
kimdcottrell/sombra
/script/arg_guesses/numani_flights/test_flightboard.rb
UTF-8
664
2.984375
3
[]
no_license
#!/usr/bin/env ruby require_relative '../../../module/data_dump' DataDump::FLIGHT_LIST.each do |fl| abbr = fl[:flight_abbr] num = fl[:flight_num] time_raw = fl[:time] time = time_raw.split(":") time[0].rjust(2,'0') time[1].rjust(2,'0') ##XOR num by zerofilled time print (num[0].to_i ^ time[0].to_i).chr print (num[1].to_i ^ time[1].to_i).chr print (num[2].to_i ^ time[2].to_i).chr print (num[3].to_i ^ time[3].to_i).chr ##XOR abbr by num # print (abbr[0].hex ^ num[0..1].to_i).chr # print (abbr[1].hex ^ num[2..3].to_i).chr ##XOR num by abbr # print (num[0..1].to_i ^ abbr[0].hex).chr # print (num[2..3].to_i ^ abbr[1].hex).chr end
true
2fc72f45a48108a34da39f702e7c593e0535c722
Ruby
atjohnfeng/aa_homework
/W3D5/map.rb
UTF-8
750
2.984375
3
[]
no_license
class Map def initialize @map = [] end def set(key, value) map.each_with_index do |defin| if defin[0] == key defin[1] == value return true end end map << [key, value] self end def get(key) map.each_with_index do |defin,i| if defin[0] == key return map[i][1] end end end def delete(key) map.each_with_index do |defin,i| if defin[0] == key map.delete_at(i) end end end def show map.dup end def inspect "#Map:#{self.object_id}" end private attr_reader :map end
true
44778d4ff6e044f898189d54c93498362fa82e11
Ruby
jasondegraw/AFN2017
/scripts/buildAFNtest.rb
UTF-8
68,222
2.65625
3
[ "BSD-2-Clause" ]
permissive
require 'openstudio' # # # +-------------------------------------------------------------+ # | Surface_15 | # | | # | | # | north_space | # | north_zone | # | Surface_14 Surface_16 | # | Floor: Surface_19 | # | Roof: Surface_20 | # | | # | | # | Surface_17 Surface_18 | # +------------------------------+------------------------------+ # | Surface_3 | Surface_11 | # | | | # | west_space | east_space | # | west_zone | east_zone | # | | | # | Surface_2 Surface_4 | Surface_10 Surface_9 | # | | | # | Floor: Surface_5 | Floor: Surface_12 | # | Roof: Surface_6 | Roof: Surface_13 | # | | | # | Surface_1 | Surface_8 | # +------------------------------+------------------------------+ # # # # # # # class SurfaceVisitor attr_reader :summary def initialize(model) setup(model) run(model) shutdown(model) end def setup(model) end def run(model) allsurfs = model.getSurfaces() @surfs = [] for surf in allsurfs do if [email protected]?(surf) then other = surf.adjacentSurface() if !other.empty?() then if [email protected]?(other.get()) then # This is an interior surface stype = surf.surfaceType() @surfs << surf if stype == 'Floor' then interiorFloor(model, surf, other.get()) elsif stype == 'RoofCeiling' then interiorRoofCeiling(model, surf, other.get()) else interiorWall(model, surf, other.get()) end end else # This is an exterior surface @surfs << surf exteriorSurface(model, surf) end end end end def interiorFloor(model, surface, adjacentSurface) end def interiorWall(model, surface, adjacentSurface) end def interiorRoofCeiling(model, surface, adjacentSurface) end def exteriorSurface(model, surface) end def shutdown(model) @summary = 'Visited ' + @surfs.size().to_s() + ' surfaces' end end class SurfaceNetworkBuilder < SurfaceVisitor def initialize(model, interiorCrack, exteriorCrack, scaleByArea=false) @interiorCrack = interiorCrack if interiorCrack == nil then @interiorCrack = OpenStudio::Model::AirflowNetworkCrack.new(model, 1.0) # Need to fix multiplier! end @exteriorCrack = exteriorCrack if interiorCrack == nil then @exteriorCrack = OpenStudio::Model::AirflowNetworkCrack.new(model, 1.0) # Need to fix multiplier! end @scaleByArea = scaleByArea super(model) end def interiorFloor(model, surface, adjacentSurface) if !surface.outsideBoundaryCondition().start_with?('Ground') then # Create a surface linkage link = OpenStudio::Model::AirflowNetworkSurface.new(model,surface,@interiorCrack) end end def interiorRoofCeiling(model, surface, adjacentSurface) # Create a surface linkage link = OpenStudio::Model::AirflowNetworkSurface.new(model,surface,@interiorCrack) end def interiorWall(model, surface, adjacentSurface) # Create a surface linkage link = OpenStudio::Model::AirflowNetworkSurface.new(model,surface,@interiorCrack) end def exteriorSurface(model, surface) # Create an external node # Create a surface linkage link = OpenStudio::Model::AirflowNetworkSurface.new(model,surface,@exteriorCrack) end end def addSurfaceCracks(model, intcrack, extcrack, scaledByArea=false) allsurfs = model.getSurfaces() surfs = [] for surf in allsurfs do if !surfs.include?(surf) then other = surf.adjacentSurface() if !other.empty?() then if !surfs.include?(other.get()) then # This is an interior surface surfs << surf end else # This is an exterior surface surfs << surf end end end puts surfs.size() #puts extsurfs.size() end model = OpenStudio::Model::Model.new() # Material,A1 - 1 IN STUCCO,Smooth,2.5389841E-02,0.6918309,1858.142,836.8000,0.9000000,0.9200000,0.9200000 stucco = OpenStudio::Model::StandardOpaqueMaterial.new(model, "Smooth", 2.5389841E-02, 0.6918309, 1858.142, 836.8) stucco.setThermalAbsorptance(0.9) stucco.setSolarAbsorptance(0.92) stucco.setVisibleAbsorptance(0.92) # Material,C4 - 4 IN COMMON BRICK,Rough,0.1014984,0.7264224,1922.216,836.8000,0.9000000,0.7600000,0.7600000 brick = OpenStudio::Model::StandardOpaqueMaterial.new(model, "Rough", 0.1014984, 0.7264224, 1922.216, 836.8) brick.setThermalAbsorptance(0.9) brick.setSolarAbsorptance(0.76) brick.setVisibleAbsorptance(0.76) # Material,E1 - 3 / 4 IN PLASTER OR GYP BOARD,Smooth,1.905E-02,0.7264224,1601.846,836.8000,0.9000000,0.9200000,0.9200000 wallboard = OpenStudio::Model::StandardOpaqueMaterial.new(model, "Smooth", 1.905E-02, 0.7264224, 1601.846, 836.8) wallboard.setThermalAbsorptance(0.92) wallboard.setSolarAbsorptance(0.92) wallboard.setVisibleAbsorptance(0.9) # Material,C6 - 8 IN CLAY TILE,Smooth,0.2033016,0.5707605,1121.292,836.8000,0.9000000,0.8200000,0.8200000 tile = OpenStudio::Model::StandardOpaqueMaterial.new(model, "Smooth", 0.2033016, 0.5707605, 1121.292, 836.8) tile.setThermalAbsorptance(0.82) tile.setSolarAbsorptance(0.82) tile.setVisibleAbsorptance(0.9) # Material,C10 - 8 IN HW CONCRETE,MediumRough,0.2033016,1.729577,2242.585,836.8000,0.9000000,0.6500000,0.6500000 concrete8 = OpenStudio::Model::StandardOpaqueMaterial.new(model, "MediumRough", 0.2033016, 1.729577, 2242.585, 836.8) concrete8.setThermalAbsorptance(0.65) concrete8.setSolarAbsorptance(0.65) concrete8.setVisibleAbsorptance(0.9) # Material,E2 - 1 / 2 IN SLAG OR STONE,Rough,1.2710161E-02,1.435549,881.0155,1673.600,0.9000000,0.5500000,0.5500000 stone = OpenStudio::Model::StandardOpaqueMaterial.new(model, "Rough", 1.2710161E-02, 1.435549, 881.0155, 1673.6) stone.setThermalAbsorptance(0.55) stone.setSolarAbsorptance(0.55) stone.setVisibleAbsorptance(0.9) # Material,E3 - 3 / 8 IN FELT AND MEMBRANE,Rough,9.5402403E-03,0.1902535,1121.292,1673.600,0.9000000,0.7500000,0.7500000 membrane = OpenStudio::Model::StandardOpaqueMaterial.new(model, "Rough", 9.5402403E-03, 0.1902535, 1121.292, 1673.6) membrane.setThermalAbsorptance(0.75) membrane.setSolarAbsorptance(0.75) membrane.setVisibleAbsorptance(0.9) # Material,B5 - 1 IN DENSE INSULATION,VeryRough,2.5389841E-02,4.3239430E-02,91.30524,836.8000,0.9000000,0.5000000,0.5000000 insulation = OpenStudio::Model::StandardOpaqueMaterial.new(model, "VeryRough", 2.5389841E-02, 4.3239430E-02, 91.30524, 836.8) insulation.setThermalAbsorptance(0.5) insulation.setSolarAbsorptance(0.5) insulation.setVisibleAbsorptance(0.9) # Material,C12 - 2 IN HW CONCRETE,MediumRough,5.0901599E-02,1.729577,2242.585,836.8000,0.9000000,0.6500000,0.6500000 concrete2 = OpenStudio::Model::StandardOpaqueMaterial.new(model, "MediumRough", 5.0901599E-02, 1.729577, 2242.585, 836.8) concrete2.setThermalAbsorptance(0.65) concrete2.setSolarAbsorptance(0.65) concrete2.setVisibleAbsorptance(0.9) # Material,1.375in-Solid-Core,Smooth,3.4925E-02,0.1525000,614.5000,1630.0000,0.9000000,0.9200000,0.9200000 solidcore = OpenStudio::Model::StandardOpaqueMaterial.new(model, "Smooth", 3.4925E-02, 0.1525, 614.50, 1630.0) solidcore.setThermalAbsorptance(0.92) solidcore.setSolarAbsorptance(0.92) solidcore.setVisibleAbsorptance(0.9) # WindowMaterial:Glazing,WIN-LAY-GLASS-LIGHT,SpectralAverage,0.0025,0.850,0.075,0.075,0.901,0.081,0.081,0.0,0.84,0.84,0.9 glazing = OpenStudio::Model::StandardGlazing.new(model, "SpectralAverage", 0.0025) glazing.setSolarTransmittanceatNormalIncidence(0.850) glazing.setFrontSideSolarReflectanceatNormalIncidence(0.075) glazing.setBackSideSolarReflectanceatNormalIncidence(0.075) glazing.setVisibleTransmittanceatNormalIncidence(0.901) glazing.setFrontSideVisibleReflectanceatNormalIncidence(0.081) glazing.setBackSideVisibleReflectanceatNormalIncidence(0.08) glazing.setInfraredTransmittanceatNormalIncidence(0.0) glazing.setFrontSideInfraredHemisphericalEmissivity(0.84) glazing.setBackSideInfraredHemisphericalEmissivity(0.84) glazing.setConductivity(0.9) materials = OpenStudio::Model::OpaqueMaterialVector.new() # Construction,DOOR-CON,1.375in-Solid-Core materials << solidcore door = OpenStudio::Model::Construction.new(materials) # Construction,EXTWALL80,A1 - 1 IN STUCCO,C4 - 4 IN COMMON BRICK,E1 - 3 / 4 IN PLASTER OR GYP BOARD materials.clear() materials << stucco materials << brick materials << wallboard extwall = OpenStudio::Model::Construction.new(materials) # Construction,PARTITION06,E1 - 3 / 4 IN PLASTER OR GYP BOARD,C6 - 8 IN CLAY TILE,E1 - 3 / 4 IN PLASTER OR GYP BOARD materials.clear() materials << wallboard materials << tile materials << wallboard partition = OpenStudio::Model::Construction.new(materials) # Construction,FLOOR SLAB 8 IN,C10 - 8 IN HW CONCRETE materials.clear() materials << concrete8 floorslab = OpenStudio::Model::Construction.new(materials) # Construction,ROOF34,E2 - 1 / 2 IN SLAG OR STONE,E3 - 3 / 8 IN FELT AND MEMBRANE,B5 - 1 IN DENSE INSULATION,C12 - 2 IN HW CONCRETE materials.clear() materials << stone materials << membrane materials << insulation materials << concrete2 roof = OpenStudio::Model::Construction.new(materials) # Construction,WIN-CON-LIGHT,WIN-LAY-GLASS-LIGHT #materials = OpenStudio::Model::StandardGlazingVector.new() materials = OpenStudio::Model::FenestrationMaterialVector.new() materials.clear() materials << glazing lightwindow = OpenStudio::Model::Construction.new(materials) points = OpenStudio::Point3dVector.new # BuildingSurface:Detailed,Surface_1,WALL,EXTWALL80,WEST_ZONE,Outdoors,,SunExposed,WindExposed,0.5000000,4,0,0,3.048000,0,0,0,6.096000,0,0,6.096000,0,3.048000 points << OpenStudio::Point3d.new(0, 0, 3.048000) points << OpenStudio::Point3d.new(0, 0, 0) points << OpenStudio::Point3d.new(6.096000, 0, 0) points << OpenStudio::Point3d.new(6.096000, 0, 3.048000) surface_1 = OpenStudio::Model::Surface.new(points, model) surface_1.setSurfaceType("WALL") surface_1.setSunExposure("SunExposed") surface_1.setWindExposure("WindExposed") surface_1.setViewFactortoGround(0.5000000) # BuildingSurface:Detailed,Surface_2,WALL,EXTWALL80,WEST_ZONE,Outdoors,,SunExposed,WindExposed,0.5000000,4,0,6.096000,3.048000,0,6.096000,0,0,0,0,0,0,3.048000 points.clear points << OpenStudio::Point3d.new(0, 6.096000, 3.048000) points << OpenStudio::Point3d.new(0, 6.096000, 0) points << OpenStudio::Point3d.new(0, 0, 0) points << OpenStudio::Point3d.new(0, 0, 3.048000) surface_2 = OpenStudio::Model::Surface.new(points, model) surface_2.setSurfaceType("WALL") surface_2.setSunExposure("SunExposed") surface_2.setWindExposure("WindExposed") surface_2.setViewFactortoGround(0.5000000) # BuildingSurface:Detailed,Surface_3,WALL,PARTITION06,WEST_ZONE,Surface,Surface_17,NoSun,NoWind,0.5000000,4,6.096000,6.096000,3.048000,6.096000,6.096000,0,0,6.096000,0,0,6.096000,3.048000 points.clear points << OpenStudio::Point3d.new(6.096000, 6.096000, 3.048000) points << OpenStudio::Point3d.new(6.096000, 6.096000, 0) points << OpenStudio::Point3d.new(0, 6.096000, 0) points << OpenStudio::Point3d.new(0, 6.096000, 3.048000) surface_3 = OpenStudio::Model::Surface.new(points, model) surface_3.setSurfaceType("WALL") surface_3.setSunExposure("NoSun") surface_3.setWindExposure("NoWind") surface_3.setViewFactortoGround(0.5000000) # BuildingSurface:Detailed,Surface_4,WALL,PARTITION06,WEST_ZONE,Surface,Surface_10,NoSun,NoWind,0.5000000,4,6.096000,0,3.048000,6.096000,0,0,6.096000,6.096000,0,6.096000,6.096000,3.048000 points.clear points << OpenStudio::Point3d.new(6.096000, 0, 3.048000) points << OpenStudio::Point3d.new(6.096000, 0, 0) points << OpenStudio::Point3d.new(6.096000, 6.096000, 0) points << OpenStudio::Point3d.new(6.096000, 6.096000, 3.048000) surface_4 = OpenStudio::Model::Surface.new(points, model) surface_4.setSurfaceType("WALL") surface_4.setSunExposure("NoSun") surface_4.setWindExposure("NoWind") surface_4.setViewFactortoGround(0.5000000) # BuildingSurface:Detailed,Surface_5,FLOOR,FLOOR SLAB 8 IN,WEST_ZONE,Surface,Surface_5,NoSun,NoWind,1.000000,4,0,0,0,0,6.096000,0,6.096000,6.096000,0,6.096000,0,0 points.clear points << OpenStudio::Point3d.new(0, 0, 0) points << OpenStudio::Point3d.new(0, 6.096000, 0) points << OpenStudio::Point3d.new(6.096000, 6.096000, 0) points << OpenStudio::Point3d.new(6.096000, 0, 0) surface_5 = OpenStudio::Model::Surface.new(points, model) surface_5.setSurfaceType("FLOOR") surface_5.setSunExposure("NoSun") surface_5.setWindExposure("NoWind") surface_5.setViewFactortoGround(1.000000) # BuildingSurface:Detailed,Surface_6,ROOF,ROOF34,WEST_ZONE,Outdoors,,SunExposed,WindExposed,0,4,0,6.096000,3.048000,0,0,3.048000,6.096000,0,3.048000,6.096000,6.096000,3.048000 points.clear points << OpenStudio::Point3d.new(0, 6.096000, 3.048000) points << OpenStudio::Point3d.new(0, 0, 3.048000) points << OpenStudio::Point3d.new(6.096000, 0, 3.048000) points << OpenStudio::Point3d.new(6.096000, 6.096000, 3.048000) surface_6 = OpenStudio::Model::Surface.new(points, model) surface_6.setSurfaceType("ROOF") surface_6.setSunExposure("SunExposed") surface_6.setWindExposure("WindExposed") surface_6.setViewFactortoGround(0) # BuildingSurface:Detailed,Surface_8,WALL,EXTWALL80,EAST_ZONE,Outdoors,,SunExposed,WindExposed,0.5000000,4,6.096000,0,3.048000,6.096000,0,0,12.19200,0,0,12.19200,0,3.048000 points.clear points << OpenStudio::Point3d.new(6.096000, 0, 3.048000) points << OpenStudio::Point3d.new(6.096000, 0, 0) points << OpenStudio::Point3d.new(12.19200, 0, 0) points << OpenStudio::Point3d.new(12.19200, 0, 3.048000) surface_8 = OpenStudio::Model::Surface.new(points, model) surface_8.setSurfaceType("WALL") surface_8.setSunExposure("SunExposed") surface_8.setWindExposure("WindExposed") surface_8.setViewFactortoGround(0.5000000) # BuildingSurface:Detailed,Surface_9,WALL,EXTWALL80,EAST_ZONE,Outdoors,,SunExposed,WindExposed,0.5000000,4,12.19200,0,3.048000,12.19200,0,0,12.19200,6.096000,0,12.19200,6.096000,3.048000 points.clear points << OpenStudio::Point3d.new(12.19200, 0, 3.048000) points << OpenStudio::Point3d.new(12.19200, 0, 0) points << OpenStudio::Point3d.new(12.19200, 6.096000, 0) points << OpenStudio::Point3d.new(12.19200, 6.096000, 3.048000) surface_9 = OpenStudio::Model::Surface.new(points, model) surface_9.setSurfaceType("WALL") surface_9.setSunExposure("SunExposed") surface_9.setWindExposure("WindExposed") surface_9.setViewFactortoGround(0.5000000) # BuildingSurface:Detailed,Surface_10,WALL,PARTITION06,EAST_ZONE,Surface,Surface_4,NoSun,NoWind,0.5000000,4,6.096000,6.096000,3.048000,6.096000,6.096000,0,6.096000,0,0,6.096001,0,3.048000 points.clear points << OpenStudio::Point3d.new(6.096000, 6.096000, 3.048000) points << OpenStudio::Point3d.new(6.096000, 6.096000, 0) points << OpenStudio::Point3d.new(6.096000, 0, 0) points << OpenStudio::Point3d.new(6.096001, 0, 3.048000) surface_10 = OpenStudio::Model::Surface.new(points, model) surface_10.setSurfaceType("WALL") surface_10.setSunExposure("NoSun") surface_10.setWindExposure("NoWind") surface_10.setViewFactortoGround(0.5000000) # BuildingSurface:Detailed,Surface_11,WALL,PARTITION06,EAST_ZONE,Surface,Surface_18,NoSun,NoWind,0.5000000,4,12.19200,6.096000,3.048000,12.19200,6.096000,0,6.096000,6.096000,0,6.096000,6.096000,3.048000 points.clear points << OpenStudio::Point3d.new(12.19200, 6.096000, 3.048000) points << OpenStudio::Point3d.new(12.19200, 6.096000, 0) points << OpenStudio::Point3d.new(6.096000, 6.096000, 0) points << OpenStudio::Point3d.new(6.096000, 6.096000, 3.048000) surface_11 = OpenStudio::Model::Surface.new(points, model) surface_11.setSurfaceType("WALL") surface_11.setSunExposure("NoSun") surface_11.setWindExposure("NoWind") surface_11.setViewFactortoGround(0.5000000) # BuildingSurface:Detailed,Surface_12,FLOOR,FLOOR SLAB 8 IN,EAST_ZONE,Surface,Surface_12,NoSun,NoWind,1.000000,4,6.096000,0,0,6.096000,6.096000,0,12.19200,6.096000,0,12.19200,0,0 points.clear points << OpenStudio::Point3d.new(6.096000, 0, 0) points << OpenStudio::Point3d.new(6.096000, 6.096000, 0) points << OpenStudio::Point3d.new(12.19200, 6.096000, 0) points << OpenStudio::Point3d.new(12.19200, 0, 0) surface_12 = OpenStudio::Model::Surface.new(points, model) surface_12.setSurfaceType("FLOOR") surface_12.setSunExposure("NoSun") surface_12.setWindExposure("NoWind") surface_12.setViewFactortoGround(1.000000) # BuildingSurface:Detailed,Surface_13,ROOF,ROOF34,EAST_ZONE,Outdoors,,SunExposed,WindExposed,0,4,6.096000,6.096000,3.048000,6.096000,0,3.048000,12.19200,0,3.048000,12.19200,6.096000,3.048000 points.clear points << OpenStudio::Point3d.new(6.096000, 6.096000, 3.048000) points << OpenStudio::Point3d.new(6.096000, 0, 3.048000) points << OpenStudio::Point3d.new(12.19200, 0, 3.048000) points << OpenStudio::Point3d.new(12.19200, 6.096000, 3.048000) surface_13 = OpenStudio::Model::Surface.new(points, model) surface_13.setSurfaceType("ROOF") surface_13.setSunExposure("SunExposed") surface_13.setWindExposure("WindExposed") surface_13.setViewFactortoGround(0) # BuildingSurface:Detailed,Surface_14,WALL,EXTWALL80,NORTH_ZONE,Outdoors,,SunExposed,WindExposed,0.5000000,4,0,12.19200,3.048000,0,12.19200,0,0,6.096000,0,0,6.096000,3.048000 points.clear points << OpenStudio::Point3d.new(0, 12.19200, 3.048000) points << OpenStudio::Point3d.new(0, 12.19200, 0) points << OpenStudio::Point3d.new(0, 6.096000, 0) points << OpenStudio::Point3d.new(0, 6.096000, 3.048000) surface_14 = OpenStudio::Model::Surface.new(points, model) surface_14.setSurfaceType("WALL") surface_14.setSunExposure("SunExposed") surface_14.setWindExposure("WindExposed") surface_14.setViewFactortoGround(0.5000000) # BuildingSurface:Detailed,Surface_15,WALL,EXTWALL80,NORTH_ZONE,Outdoors,,SunExposed,WindExposed,0.5000000,4,12.19200,12.19200,3.048000,12.19200,12.19200,0,0,12.19200,0,0,12.19200,3.048000 points.clear points << OpenStudio::Point3d.new(12.19200, 12.19200, 3.048000) points << OpenStudio::Point3d.new(12.19200, 12.19200, 0) points << OpenStudio::Point3d.new(0, 12.19200, 0) points << OpenStudio::Point3d.new(0, 12.19200, 3.048000) surface_15 = OpenStudio::Model::Surface.new(points, model) surface_15.setSurfaceType("WALL") surface_15.setSunExposure("SunExposed") surface_15.setWindExposure("WindExposed") surface_15.setViewFactortoGround(0.5000000) # BuildingSurface:Detailed,Surface_16,WALL,EXTWALL80,NORTH_ZONE,Outdoors,,SunExposed,WindExposed,0.5000000,4,12.19200,6.096000,3.048000,12.19200,6.096000,0,12.19200,12.19200,0,12.19200,12.19200,3.048000 points.clear points << OpenStudio::Point3d.new(12.19200, 6.096000, 3.048000) points << OpenStudio::Point3d.new(12.19200, 6.096000, 0) points << OpenStudio::Point3d.new(12.19200, 12.19200, 0) points << OpenStudio::Point3d.new(12.19200, 12.19200, 3.048000) surface_16 = OpenStudio::Model::Surface.new(points, model) surface_16.setSurfaceType("WALL") surface_16.setSunExposure("SunExposed") surface_16.setWindExposure("WindExposed") surface_16.setViewFactortoGround(0.5000000) # BuildingSurface:Detailed,Surface_17,WALL,PARTITION06,NORTH_ZONE,Surface,Surface_3,NoSun,NoWind,0.5000000,4,0.000,6.096,3.048,0.000,6.096,0.000,6.096,6.096,0.000,6.096,6.096,3.048 points.clear points << OpenStudio::Point3d.new(0.000, 6.096, 3.048) points << OpenStudio::Point3d.new(0.000, 6.096, 0.000) points << OpenStudio::Point3d.new(6.096, 6.096, 0.000) points << OpenStudio::Point3d.new(6.096, 6.096, 3.048) surface_17 = OpenStudio::Model::Surface.new(points, model) surface_17.setSurfaceType("WALL") surface_17.setSunExposure("NoSun") surface_17.setWindExposure("NoWind") surface_17.setViewFactortoGround(0.5000000) # BuildingSurface:Detailed,Surface_18,WALL,PARTITION06,NORTH_ZONE,Surface,Surface_11,NoSun,NoWind,0.5000000,4,6.096000,6.096000,3.048000,6.096000,6.096000,0,12.19200,6.096000,0,12.19200,6.096000,3.048000 points.clear points << OpenStudio::Point3d.new(6.096000, 6.096000, 3.048000) points << OpenStudio::Point3d.new(6.096000, 6.096000, 0) points << OpenStudio::Point3d.new(12.19200, 6.096000, 0) points << OpenStudio::Point3d.new(12.19200, 6.096000, 3.048000) surface_18 = OpenStudio::Model::Surface.new(points, model) surface_18.setSurfaceType("WALL") surface_18.setSunExposure("NoSun") surface_18.setWindExposure("NoWind") surface_18.setViewFactortoGround(0.5000000) # BuildingSurface:Detailed,Surface_19,FLOOR,FLOOR SLAB 8 IN,NORTH_ZONE,Surface,Surface_19,NoSun,NoWind,1.000000,4,0,6.096000,0,0,12.19200,0,12.19200,12.19200,0,12.19200,6.096000,0 points.clear points << OpenStudio::Point3d.new(0, 6.096000, 0) points << OpenStudio::Point3d.new(0, 12.19200, 0) points << OpenStudio::Point3d.new(12.19200, 12.19200, 0) points << OpenStudio::Point3d.new(12.19200, 6.096000, 0) surface_19 = OpenStudio::Model::Surface.new(points, model) surface_19.setSurfaceType("FLOOR") surface_19.setSunExposure("NoSun") surface_19.setWindExposure("NoWind") surface_19.setViewFactortoGround(1.000000) # BuildingSurface:Detailed,Surface_20,ROOF,ROOF34,NORTH_ZONE,Outdoors,,SunExposed,WindExposed,0,4,0,12.19200,3.048000,0,6.096000,3.048000,12.19200,6.096000,3.048000,12.19200,12.19200,3.048000 points.clear points << OpenStudio::Point3d.new(0, 12.19200, 3.048000) points << OpenStudio::Point3d.new(0, 6.096000, 3.048000) points << OpenStudio::Point3d.new(12.19200, 6.096000, 3.048000) points << OpenStudio::Point3d.new(12.19200, 12.19200, 3.048000) surface_20 = OpenStudio::Model::Surface.new(points, model) surface_20.setSurfaceType("ROOF") surface_20.setSunExposure("SunExposed") surface_20.setWindExposure("WindExposed") surface_20.setViewFactortoGround(0) # Set the constructions surface_1.setConstruction(extwall) surface_2.setConstruction(extwall) surface_3.setConstruction(partition) surface_4.setConstruction(partition) surface_5.setConstruction(floorslab) surface_6.setConstruction(roof) #surface_7.setConstruction(extwall) surface_8.setConstruction(extwall) surface_9.setConstruction(extwall) surface_10.setConstruction(partition) surface_11.setConstruction(partition) surface_12.setConstruction(floorslab) surface_13.setConstruction(roof) surface_14.setConstruction(extwall) surface_15.setConstruction(extwall) surface_16.setConstruction(extwall) surface_17.setConstruction(partition) surface_18.setConstruction(partition) surface_19.setConstruction(floorslab) surface_20.setConstruction(roof) # Connect the surfaces together surface_3.setAdjacentSurface(surface_17) surface_4.setAdjacentSurface(surface_10) surface_11.setAdjacentSurface(surface_18) # Make spaces and thermal zones west_space = OpenStudio::Model::Space.new(model) west_zone = OpenStudio::Model::ThermalZone.new(model) east_space = OpenStudio::Model::Space.new(model) east_zone = OpenStudio::Model::ThermalZone.new(model) north_space = OpenStudio::Model::Space.new(model) north_zone = OpenStudio::Model::ThermalZone.new(model) # Connect spaces and surfaces surface_1.setSpace(west_space) surface_2.setSpace(west_space) surface_3.setSpace(west_space) surface_4.setSpace(west_space) surface_5.setSpace(west_space) surface_6.setSpace(west_space) surface_8.setSpace(east_space) surface_9.setSpace(east_space) surface_10.setSpace(east_space) surface_11.setSpace(east_space) surface_12.setSpace(east_space) surface_13.setSpace(east_space) surface_14.setSpace(north_space) surface_15.setSpace(north_space) surface_16.setSpace(north_space) surface_17.setSpace(north_space) surface_18.setSpace(north_space) surface_19.setSpace(north_space) surface_20.setSpace(north_space) # Connect spaces and zones west_space.setThermalZone(west_zone) east_space.setThermalZone(east_zone) north_space.setThermalZone(north_zone) puts surface_3.to_s puts surface_17.to_s puts surface_3.isNumberofVerticesAutocalculated addSurfaceCracks(model, nil, nil) visitor = SurfaceNetworkBuilder.new(model, nil, nil) puts visitor.summary puts zones = model.getAirflowNetworkZones() puts 'Created ' + zones.size().to_s() + ' AFN zones' extnodes = model.getAirflowNetworkExternalNodes() puts 'Created ' + extnodes.size().to_s() + ' AFN external nodes' surfs = model.getAirflowNetworkSurfaces() puts 'Created ' + surfs.size().to_s() + ' AFN surfaces' cracks = model.getAirflowNetworkCracks() puts 'Created ' + cracks.size().to_s() + ' AFN cracks' junk = <<-MLS GlobalGeometryRules,UpperLeftCorner,CounterClockWise,World FenestrationSurface:Detailed,WINDOW11,WINDOW,WIN-CON-LIGHT,Surface_1,0.5000000,1.0,3,1.00000,0,2.500000,1.00000,0,1.0000000,5.000000,0,1.0000000 FenestrationSurface:Detailed,WINDOW12,WINDOW,WIN-CON-LIGHT,Surface_1,0.5000000,1.0,3,5.00000,0,1.0000000,5.000000,0,2.5000000,1.000000,0,2.500000 FenestrationSurface:Detailed,DoorInSurface_3,DOOR,DOOR-CON,Surface_3,DoorInSurface_17,0.5000000,1.0,4,3.500,6.096000,2.0,3.500,6.096000,0.0,2.500,6.096000,0.0,2.500,6.096000,2.0 FenestrationSurface:Detailed,WINDOW2,WINDOW,WIN-CON-LIGHT,Surface_15,0.5000000,1.0,4,6.000000,12.19200,2.333000,6.000000,12.19200,1.000000,3.000000,12.19200,1.000000,3.000000,12.19200,2.333000 FenestrationSurface:Detailed,DoorInSurface_17,DOOR,DOOR-CON,Surface_17,DoorInSurface_3,0.5000000,1.0,4,2.500,6.096000,2.0,2.500,6.096000,0.0,3.500,6.096000,0.0,3.500,6.096000,2.0 AirflowNetwork:SimulationControl,NaturalVentilation,MultizoneWithoutDistribution,INPUT,ExternalNode,LOWRISE,500,ZeroNodePressures,1.0E-05,1.0E-06,-0.5,0.0,1.0 AirflowNetwork:MultiZone:Zone,WEST_ZONE,NoVent,Temperature,WindowVentSched,0.3,5.0,10.0,0.0,300000.0 AirflowNetwork:MultiZone:Zone,EAST_ZONE,NoVent,1.0,0.0,100.0,0.0,300000.0 AirflowNetwork:MultiZone:Zone,NORTH_ZONE,NoVent,Temperature,WindowVentSched,1.0,0.0,100.0,0.0,300000.0 AirflowNetwork:MultiZone:Surface,Surface_1,CR-1,SFacade,1.0 AirflowNetwork:MultiZone:Surface,Surface_4,CR-1,1.0 AirflowNetwork:MultiZone:Surface,Surface_11,CR-1,1.0 AirflowNetwork:MultiZone:Surface,Surface_15,CR-1,NFacade,1.0 AirflowNetwork:MultiZone:ExternalNode,NFacade,1.524,NFacade_WPCValue AirflowNetwork:MultiZone:ExternalNode,SFacade,1.524,SFacade_WPCValue,No,Absolute AirflowNetwork:MultiZone:ReferenceCrackConditions,ReferenceCrackConditions,20.0,101320,0.005 AirflowNetwork:MultiZone:Surface:Crack,CR-1,0.01,0.667,ReferenceCrackConditions AirflowNetwork:MultiZone:WindPressureCoefficientArray,Every 30 Degrees,0,30,60,90,120,150,180,210,240,270,300,330 AirflowNetwork:MultiZone:WindPressureCoefficientValues,NFacade_WPCValue,Every 30 Degrees,0.60,0.48,0.04,-0.56,-0.56,-0.42,-0.37,-0.42,-0.56,-0.56,0.04,0.48 AirflowNetwork:MultiZone:WindPressureCoefficientValues,SFacade_WPCValue,Every 30 Degrees,-0.37,-0.42,-0.56,-0.56,0.04,0.48,0.60,0.48,0.04,-0.56,-0.56,-0.42 SurfaceConvectionAlgorithm:Inside,TARP SurfaceConvectionAlgorithm:Outside,DOE-2 HeatBalanceAlgorithm,ConductionTransferFunction ZoneAirHeatBalanceAlgorithm,AnalyticalSolution TEST_F(EnergyPlusFixture, TestExternalNodes) { std::string const idf_objects = delimited_string({ "Version,8.6;", "Material,", " A1 - 1 IN STUCCO, !- Name", " Smooth, !- Roughness", " 2.5389841E-02, !- Thickness {m}", " 0.6918309, !- Conductivity {W/m-K}", " 1858.142, !- Density {kg/m3}", " 836.8000, !- Specific Heat {J/kg-K}", " 0.9000000, !- Thermal Absorptance", " 0.9200000, !- Solar Absorptance", " 0.9200000; !- Visible Absorptance", "Material,", " C4 - 4 IN COMMON BRICK, !- Name", " Rough, !- Roughness", " 0.1014984, !- Thickness {m}", " 0.7264224, !- Conductivity {W/m-K}", " 1922.216, !- Density {kg/m3}", " 836.8000, !- Specific Heat {J/kg-K}", " 0.9000000, !- Thermal Absorptance", " 0.7600000, !- Solar Absorptance", " 0.7600000; !- Visible Absorptance", "Material,", " E1 - 3 / 4 IN PLASTER OR GYP BOARD, !- Name", " Smooth, !- Roughness", " 1.905E-02, !- Thickness {m}", " 0.7264224, !- Conductivity {W/m-K}", " 1601.846, !- Density {kg/m3}", " 836.8000, !- Specific Heat {J/kg-K}", " 0.9000000, !- Thermal Absorptance", " 0.9200000, !- Solar Absorptance", " 0.9200000; !- Visible Absorptance", "Material,", " C6 - 8 IN CLAY TILE, !- Name", " Smooth, !- Roughness", " 0.2033016, !- Thickness {m}", " 0.5707605, !- Conductivity {W/m-K}", " 1121.292, !- Density {kg/m3}", " 836.8000, !- Specific Heat {J/kg-K}", " 0.9000000, !- Thermal Absorptance", " 0.8200000, !- Solar Absorptance", " 0.8200000; !- Visible Absorptance", "Material,", " C10 - 8 IN HW CONCRETE, !- Name", " MediumRough, !- Roughness", " 0.2033016, !- Thickness {m}", " 1.729577, !- Conductivity {W/m-K}", " 2242.585, !- Density {kg/m3}", " 836.8000, !- Specific Heat {J/kg-K}", " 0.9000000, !- Thermal Absorptance", " 0.6500000, !- Solar Absorptance", " 0.6500000; !- Visible Absorptance", "Material,", " E2 - 1 / 2 IN SLAG OR STONE, !- Name", " Rough, !- Roughness", " 1.2710161E-02, !- Thickness {m}", " 1.435549, !- Conductivity {W/m-K}", " 881.0155, !- Density {kg/m3}", " 1673.600, !- Specific Heat {J/kg-K}", " 0.9000000, !- Thermal Absorptance", " 0.5500000, !- Solar Absorptance", " 0.5500000; !- Visible Absorptance", "Material,", " E3 - 3 / 8 IN FELT AND MEMBRANE, !- Name", " Rough, !- Roughness", " 9.5402403E-03, !- Thickness {m}", " 0.1902535, !- Conductivity {W/m-K}", " 1121.292, !- Density {kg/m3}", " 1673.600, !- Specific Heat {J/kg-K}", " 0.9000000, !- Thermal Absorptance", " 0.7500000, !- Solar Absorptance", " 0.7500000; !- Visible Absorptance", "Material,", " B5 - 1 IN DENSE INSULATION, !- Name", " VeryRough, !- Roughness", " 2.5389841E-02, !- Thickness {m}", " 4.3239430E-02, !- Conductivity {W/m-K}", " 91.30524, !- Density {kg/m3}", " 836.8000, !- Specific Heat {J/kg-K}", " 0.9000000, !- Thermal Absorptance", " 0.5000000, !- Solar Absorptance", " 0.5000000; !- Visible Absorptance", "Material,", " C12 - 2 IN HW CONCRETE, !- Name", " MediumRough, !- Roughness", " 5.0901599E-02, !- Thickness {m}", " 1.729577, !- Conductivity {W/m-K}", " 2242.585, !- Density {kg/m3}", " 836.8000, !- Specific Heat {J/kg-K}", " 0.9000000, !- Thermal Absorptance", " 0.6500000, !- Solar Absorptance", " 0.6500000; !- Visible Absorptance", "Material,", " 1.375in-Solid-Core, !- Name", " Smooth, !- Roughness", " 3.4925E-02, !- Thickness {m}", " 0.1525000, !- Conductivity {W/m-K}", " 614.5000, !- Density {kg/m3}", " 1630.0000, !- Specific Heat {J/kg-K}", " 0.9000000, !- Thermal Absorptance", " 0.9200000, !- Solar Absorptance", " 0.9200000; !- Visible Absorptance", "WindowMaterial:Glazing,", " WIN-LAY-GLASS-LIGHT, !- Name", " SpectralAverage, !- Optical Data Type", " , !- Window Glass Spectral Data Set Name", " 0.0025, !- Thickness {m}", " 0.850, !- Solar Transmittance at Normal Incidence", " 0.075, !- Front Side Solar Reflectance at Normal Incidence", " 0.075, !- Back Side Solar Reflectance at Normal Incidence", " 0.901, !- Visible Transmittance at Normal Incidence", " 0.081, !- Front Side Visible Reflectance at Normal Incidence", " 0.081, !- Back Side Visible Reflectance at Normal Incidence", " 0.0, !- Infrared Transmittance at Normal Incidence", " 0.84, !- Front Side Infrared Hemispherical Emissivity", " 0.84, !- Back Side Infrared Hemispherical Emissivity", " 0.9; !- Conductivity {W/m-K}", "Construction,", " DOOR-CON, !- Name", " 1.375in-Solid-Core; !- Outside Layer", "Construction,", " EXTWALL80, !- Name", " A1 - 1 IN STUCCO, !- Outside Layer", " C4 - 4 IN COMMON BRICK, !- Layer 2", " E1 - 3 / 4 IN PLASTER OR GYP BOARD; !- Layer 3", "Construction,", " PARTITION06, !- Name", " E1 - 3 / 4 IN PLASTER OR GYP BOARD, !- Outside Layer", " C6 - 8 IN CLAY TILE, !- Layer 2", " E1 - 3 / 4 IN PLASTER OR GYP BOARD; !- Layer 3", " Construction,", " FLOOR SLAB 8 IN, !- Name", " C10 - 8 IN HW CONCRETE; !- Outside Layer", "Construction,", " ROOF34, !- Name", " E2 - 1 / 2 IN SLAG OR STONE, !- Outside Layer", " E3 - 3 / 8 IN FELT AND MEMBRANE, !- Layer 2", " B5 - 1 IN DENSE INSULATION, !- Layer 3", " C12 - 2 IN HW CONCRETE; !- Layer 4", "Construction,", " WIN-CON-LIGHT, !- Name", " WIN-LAY-GLASS-LIGHT; !- Outside Layer", "Zone,", " WEST_ZONE, !- Name", " 0, !- Direction of Relative North {deg}", " 0, !- X Origin {m}", " 0, !- Y Origin {m}", " 0, !- Z Origin {m}", " 1, !- Type", " 1, !- Multiplier", " autocalculate; !- Ceiling Height {m}", "Zone,", " EAST_ZONE, !- Name", " 0, !- Direction of Relative North {deg}", " 0, !- X Origin {m}", " 0, !- Y Origin {m}", " 0, !- Z Origin {m}", " 1, !- Type", " 1, !- Multiplier", " autocalculate; !- Ceiling Height {m}", "Zone,", " NORTH_ZONE, !- Name", " 0, !- Direction of Relative North {deg}", " 0, !- X Origin {m}", " 0, !- Y Origin {m}", " 0, !- Z Origin {m}", " 1, !- Type", " 1, !- Multiplier", " autocalculate; !- Ceiling Height {m}", "GlobalGeometryRules,", " UpperLeftCorner, !- Starting Vertex Position", " CounterClockWise, !- Vertex Entry Direction", " World; !- Coordinate System", "BuildingSurface:Detailed,", " Surface_1, !- Name", " WALL, !- Surface Type", " EXTWALL80, !- Construction Name", " WEST_ZONE, !- Zone Name", " Outdoors, !- Outside Boundary Condition", " , !- Outside Boundary Condition Object", " SunExposed, !- Sun Exposure", " WindExposed, !- Wind Exposure", " 0.5000000, !- View Factor to Ground", " 4, !- Number of Vertices", " 0,0,3.048000, !- X,Y,Z ==> Vertex 1 {m}", " 0,0,0, !- X,Y,Z ==> Vertex 2 {m}", " 6.096000,0,0, !- X,Y,Z ==> Vertex 3 {m}", " 6.096000,0,3.048000; !- X,Y,Z ==> Vertex 4 {m}", "BuildingSurface:Detailed,", " Surface_2, !- Name", " WALL, !- Surface Type", " EXTWALL80, !- Construction Name", " WEST_ZONE, !- Zone Name", " Outdoors, !- Outside Boundary Condition", " , !- Outside Boundary Condition Object", " SunExposed, !- Sun Exposure", " WindExposed, !- Wind Exposure", " 0.5000000, !- View Factor to Ground", " 4, !- Number of Vertices", " 0,6.096000,3.048000, !- X,Y,Z ==> Vertex 1 {m}", " 0,6.096000,0, !- X,Y,Z ==> Vertex 2 {m}", " 0,0,0, !- X,Y,Z ==> Vertex 3 {m}", " 0,0,3.048000; !- X,Y,Z ==> Vertex 4 {m}", "BuildingSurface:Detailed,", " Surface_3, !- Name", " WALL, !- Surface Type", " PARTITION06, !- Construction Name", " WEST_ZONE, !- Zone Name", " Surface, !- Outside Boundary Condition", " Surface_17, !- Outside Boundary Condition Object", " NoSun, !- Sun Exposure", " NoWind, !- Wind Exposure", " 0.5000000, !- View Factor to Ground", " 4, !- Number of Vertices", " 6.096000,6.096000,3.048000, !- X,Y,Z ==> Vertex 1 {m}", " 6.096000,6.096000,0, !- X,Y,Z ==> Vertex 2 {m}", " 0,6.096000,0, !- X,Y,Z ==> Vertex 3 {m}", " 0,6.096000,3.048000; !- X,Y,Z ==> Vertex 4 {m}", "BuildingSurface:Detailed,", " Surface_4, !- Name", " WALL, !- Surface Type", " PARTITION06, !- Construction Name", " WEST_ZONE, !- Zone Name", " Surface, !- Outside Boundary Condition", " Surface_10, !- Outside Boundary Condition Object", " NoSun, !- Sun Exposure", " NoWind, !- Wind Exposure", " 0.5000000, !- View Factor to Ground", " 4, !- Number of Vertices", " 6.096000,0,3.048000, !- X,Y,Z ==> Vertex 1 {m}", " 6.096000,0,0, !- X,Y,Z ==> Vertex 2 {m}", " 6.096000,6.096000,0, !- X,Y,Z ==> Vertex 3 {m}", " 6.096000,6.096000,3.048000; !- X,Y,Z ==> Vertex 4 {m}", "BuildingSurface:Detailed,", " Surface_5, !- Name", " FLOOR, !- Surface Type", " FLOOR SLAB 8 IN, !- Construction Name", " WEST_ZONE, !- Zone Name", " Surface, !- Outside Boundary Condition", " Surface_5, !- Outside Boundary Condition Object", " NoSun, !- Sun Exposure", " NoWind, !- Wind Exposure", " 1.000000, !- View Factor to Ground", " 4, !- Number of Vertices", " 0,0,0, !- X,Y,Z ==> Vertex 1 {m}", " 0,6.096000,0, !- X,Y,Z ==> Vertex 2 {m}", " 6.096000,6.096000,0, !- X,Y,Z ==> Vertex 3 {m}", " 6.096000,0,0; !- X,Y,Z ==> Vertex 4 {m}", "BuildingSurface:Detailed,", " Surface_6, !- Name", " ROOF, !- Surface Type", " ROOF34, !- Construction Name", " WEST_ZONE, !- Zone Name", " Outdoors, !- Outside Boundary Condition", " , !- Outside Boundary Condition Object", " SunExposed, !- Sun Exposure", " WindExposed, !- Wind Exposure", " 0, !- View Factor to Ground", " 4, !- Number of Vertices", " 0,6.096000,3.048000, !- X,Y,Z ==> Vertex 1 {m}", " 0,0,3.048000, !- X,Y,Z ==> Vertex 2 {m}", " 6.096000,0,3.048000, !- X,Y,Z ==> Vertex 3 {m}", " 6.096000,6.096000,3.048000; !- X,Y,Z ==> Vertex 4 {m}", "BuildingSurface:Detailed,", " Surface_8, !- Name", " WALL, !- Surface Type", " EXTWALL80, !- Construction Name", " EAST_ZONE, !- Zone Name", " Outdoors, !- Outside Boundary Condition", " , !- Outside Boundary Condition Object", " SunExposed, !- Sun Exposure", " WindExposed, !- Wind Exposure", " 0.5000000, !- View Factor to Ground", " 4, !- Number of Vertices", " 6.096000,0,3.048000, !- X,Y,Z ==> Vertex 1 {m}", " 6.096000,0,0, !- X,Y,Z ==> Vertex 2 {m}", " 12.19200,0,0, !- X,Y,Z ==> Vertex 3 {m}", " 12.19200,0,3.048000; !- X,Y,Z ==> Vertex 4 {m}", "BuildingSurface:Detailed,", " Surface_9, !- Name", " WALL, !- Surface Type", " EXTWALL80, !- Construction Name", " EAST_ZONE, !- Zone Name", " Outdoors, !- Outside Boundary Condition", " , !- Outside Boundary Condition Object", " SunExposed, !- Sun Exposure", " WindExposed, !- Wind Exposure", " 0.5000000, !- View Factor to Ground", " 4, !- Number of Vertices", " 12.19200,0,3.048000, !- X,Y,Z ==> Vertex 1 {m}", " 12.19200,0,0, !- X,Y,Z ==> Vertex 2 {m}", " 12.19200,6.096000,0, !- X,Y,Z ==> Vertex 3 {m}", " 12.19200,6.096000,3.048000; !- X,Y,Z ==> Vertex 4 {m}", "BuildingSurface:Detailed,", " Surface_10, !- Name", " WALL, !- Surface Type", " PARTITION06, !- Construction Name", " EAST_ZONE, !- Zone Name", " Surface, !- Outside Boundary Condition", " Surface_4, !- Outside Boundary Condition Object", " NoSun, !- Sun Exposure", " NoWind, !- Wind Exposure", " 0.5000000, !- View Factor to Ground", " 4, !- Number of Vertices", " 6.096000,6.096000,3.048000, !- X,Y,Z ==> Vertex 1 {m}", " 6.096000,6.096000,0, !- X,Y,Z ==> Vertex 2 {m}", " 6.096000,0,0, !- X,Y,Z ==> Vertex 3 {m}", " 6.096001,0,3.048000; !- X,Y,Z ==> Vertex 4 {m}", "BuildingSurface:Detailed,", " Surface_11, !- Name", " WALL, !- Surface Type", " PARTITION06, !- Construction Name", " EAST_ZONE, !- Zone Name", " Surface, !- Outside Boundary Condition", " Surface_18, !- Outside Boundary Condition Object", " NoSun, !- Sun Exposure", " NoWind, !- Wind Exposure", " 0.5000000, !- View Factor to Ground", " 4, !- Number of Vertices", " 12.19200,6.096000,3.048000, !- X,Y,Z ==> Vertex 1 {m}", " 12.19200,6.096000,0, !- X,Y,Z ==> Vertex 2 {m}", " 6.096000,6.096000,0, !- X,Y,Z ==> Vertex 3 {m}", " 6.096000,6.096000,3.048000; !- X,Y,Z ==> Vertex 4 {m}", "BuildingSurface:Detailed,", " Surface_12, !- Name", " FLOOR, !- Surface Type", " FLOOR SLAB 8 IN, !- Construction Name", " EAST_ZONE, !- Zone Name", " Surface, !- Outside Boundary Condition", " Surface_12, !- Outside Boundary Condition Object", " NoSun, !- Sun Exposure", " NoWind, !- Wind Exposure", " 1.000000, !- View Factor to Ground", " 4, !- Number of Vertices", " 6.096000,0,0, !- X,Y,Z ==> Vertex 1 {m}", " 6.096000,6.096000,0, !- X,Y,Z ==> Vertex 2 {m}", " 12.19200,6.096000,0, !- X,Y,Z ==> Vertex 3 {m}", " 12.19200,0,0; !- X,Y,Z ==> Vertex 4 {m}", "BuildingSurface:Detailed,", " Surface_13, !- Name", " ROOF, !- Surface Type", " ROOF34, !- Construction Name", " EAST_ZONE, !- Zone Name", " Outdoors, !- Outside Boundary Condition", " , !- Outside Boundary Condition Object", " SunExposed, !- Sun Exposure", " WindExposed, !- Wind Exposure", " 0, !- View Factor to Ground", " 4, !- Number of Vertices", " 6.096000,6.096000,3.048000, !- X,Y,Z ==> Vertex 1 {m}", " 6.096000,0,3.048000, !- X,Y,Z ==> Vertex 2 {m}", " 12.19200,0,3.048000, !- X,Y,Z ==> Vertex 3 {m}", " 12.19200,6.096000,3.048000; !- X,Y,Z ==> Vertex 4 {m}", "BuildingSurface:Detailed,", " Surface_14, !- Name", " WALL, !- Surface Type", " EXTWALL80, !- Construction Name", " NORTH_ZONE, !- Zone Name", " Outdoors, !- Outside Boundary Condition", " , !- Outside Boundary Condition Object", " SunExposed, !- Sun Exposure", " WindExposed, !- Wind Exposure", " 0.5000000, !- View Factor to Ground", " 4, !- Number of Vertices", " 0,12.19200,3.048000, !- X,Y,Z ==> Vertex 1 {m}", " 0,12.19200,0, !- X,Y,Z ==> Vertex 2 {m}", " 0,6.096000,0, !- X,Y,Z ==> Vertex 3 {m}", " 0,6.096000,3.048000; !- X,Y,Z ==> Vertex 4 {m}", "BuildingSurface:Detailed,", " Surface_15, !- Name", " WALL, !- Surface Type", " EXTWALL80, !- Construction Name", " NORTH_ZONE, !- Zone Name", " Outdoors, !- Outside Boundary Condition", " , !- Outside Boundary Condition Object", " SunExposed, !- Sun Exposure", " WindExposed, !- Wind Exposure", " 0.5000000, !- View Factor to Ground", " 4, !- Number of Vertices", " 12.19200,12.19200,3.048000, !- X,Y,Z ==> Vertex 1 {m}", " 12.19200,12.19200,0, !- X,Y,Z ==> Vertex 2 {m}", " 0,12.19200,0, !- X,Y,Z ==> Vertex 3 {m}", " 0,12.19200,3.048000; !- X,Y,Z ==> Vertex 4 {m}", "BuildingSurface:Detailed,", " Surface_16, !- Name", " WALL, !- Surface Type", " EXTWALL80, !- Construction Name", " NORTH_ZONE, !- Zone Name", " Outdoors, !- Outside Boundary Condition", " , !- Outside Boundary Condition Object", " SunExposed, !- Sun Exposure", " WindExposed, !- Wind Exposure", " 0.5000000, !- View Factor to Ground", " 4, !- Number of Vertices", " 12.19200,6.096000,3.048000, !- X,Y,Z ==> Vertex 1 {m}", " 12.19200,6.096000,0, !- X,Y,Z ==> Vertex 2 {m}", " 12.19200,12.19200,0, !- X,Y,Z ==> Vertex 3 {m}", " 12.19200,12.19200,3.048000; !- X,Y,Z ==> Vertex 4 {m}", "BuildingSurface:Detailed,", " Surface_17, !- Name", " WALL, !- Surface Type", " PARTITION06, !- Construction Name", " NORTH_ZONE, !- Zone Name", " Surface, !- Outside Boundary Condition", " Surface_3, !- Outside Boundary Condition Object", " NoSun, !- Sun Exposure", " NoWind, !- Wind Exposure", " 0.5000000, !- View Factor to Ground", " 4, !- Number of Vertices", " 0.000,6.096,3.048, !- X,Y,Z ==> Vertex 1 {m}", " 0.000,6.096,0.000, !- X,Y,Z ==> Vertex 2 {m}", " 6.096,6.096,0.000, !- X,Y,Z ==> Vertex 3 {m}", " 6.096,6.096,3.048; !- X,Y,Z ==> Vertex 4 {m}", "BuildingSurface:Detailed,", " Surface_18, !- Name", " WALL, !- Surface Type", " PARTITION06, !- Construction Name", " NORTH_ZONE, !- Zone Name", " Surface, !- Outside Boundary Condition", " Surface_11, !- Outside Boundary Condition Object", " NoSun, !- Sun Exposure", " NoWind, !- Wind Exposure", " 0.5000000, !- View Factor to Ground", " 4, !- Number of Vertices", " 6.096000,6.096000,3.048000, !- X,Y,Z ==> Vertex 1 {m}", " 6.096000,6.096000,0, !- X,Y,Z ==> Vertex 2 {m}", " 12.19200,6.096000,0, !- X,Y,Z ==> Vertex 3 {m}", " 12.19200,6.096000,3.048000; !- X,Y,Z ==> Vertex 4 {m}", "BuildingSurface:Detailed,", " Surface_19, !- Name", " FLOOR, !- Surface Type", " FLOOR SLAB 8 IN, !- Construction Name", " NORTH_ZONE, !- Zone Name", " Surface, !- Outside Boundary Condition", " Surface_19, !- Outside Boundary Condition Object", " NoSun, !- Sun Exposure", " NoWind, !- Wind Exposure", " 1.000000, !- View Factor to Ground", " 4, !- Number of Vertices", " 0,6.096000,0, !- X,Y,Z ==> Vertex 1 {m}", " 0,12.19200,0, !- X,Y,Z ==> Vertex 2 {m}", " 12.19200,12.19200,0, !- X,Y,Z ==> Vertex 3 {m}", " 12.19200,6.096000,0; !- X,Y,Z ==> Vertex 4 {m}", "BuildingSurface:Detailed,", " Surface_20, !- Name", " ROOF, !- Surface Type", " ROOF34, !- Construction Name", " NORTH_ZONE, !- Zone Name", " Outdoors, !- Outside Boundary Condition", " , !- Outside Boundary Condition Object", " SunExposed, !- Sun Exposure", " WindExposed, !- Wind Exposure", " 0, !- View Factor to Ground", " 4, !- Number of Vertices", " 0,12.19200,3.048000, !- X,Y,Z ==> Vertex 1 {m}", " 0,6.096000,3.048000, !- X,Y,Z ==> Vertex 2 {m}", " 12.19200,6.096000,3.048000, !- X,Y,Z ==> Vertex 3 {m}", " 12.19200,12.19200,3.048000; !- X,Y,Z ==> Vertex 4 {m}", /*"FenestrationSurface:Detailed,", " WINDOW11, !- Name", " WINDOW, !- Surface Type", " WIN-CON-LIGHT, !- Construction Name", " Surface_1, !- Building Surface Name", " , !- Outside Boundary Condition Object", " 0.5000000, !- View Factor to Ground", " , !- Shading Control Name", " , !- Frame and Divider Name", " 1.0, !- Multiplier", " 3, !- Number of Vertices", " 1.00000,0,2.500000, !- X,Y,Z ==> Vertex 1 {m}", " 1.00000,0,1.0000000, !- X,Y,Z ==> Vertex 2 {m}", " 5.000000,0,1.0000000; !- X,Y,Z ==> Vertex 3 {m}", "FenestrationSurface:Detailed,", " WINDOW12, !- Name", " WINDOW, !- Surface Type", " WIN-CON-LIGHT, !- Construction Name", " Surface_1, !- Building Surface Name", " , !- Outside Boundary Condition Object", " 0.5000000, !- View Factor to Ground", " , !- Shading Control Name", " , !- Frame and Divider Name", " 1.0, !- Multiplier", " 3, !- Number of Vertices", " 5.00000,0,1.0000000, !- X,Y,Z ==> Vertex 2 {m}", " 5.000000,0,2.5000000, !- X,Y,Z ==> Vertex 3 {m}", " 1.000000,0,2.500000; !- X,Y,Z ==> Vertex 4 {m}", "FenestrationSurface:Detailed,", " DoorInSurface_3, !- Name", " DOOR, !- Surface Type", " DOOR-CON, !- Construction Name", " Surface_3, !- Building Surface Name", " DoorInSurface_17, !- Outside Boundary Condition Object", " 0.5000000, !- View Factor to Ground", " , !- Shading Control Name", " , !- Frame and Divider Name", " 1.0, !- Multiplier", " 4, !- Number of Vertices", " 3.500,6.096000,2.0, !- X,Y,Z ==> Vertex 1 {m}", " 3.500,6.096000,0.0, !- X,Y,Z ==> Vertex 2 {m}", " 2.500,6.096000,0.0, !- X,Y,Z ==> Vertex 3 {m}", " 2.500,6.096000,2.0; !- X,Y,Z ==> Vertex 4 {m}", "FenestrationSurface:Detailed,", " WINDOW2, !- Name", " WINDOW, !- Surface Type", " WIN-CON-LIGHT, !- Construction Name", " Surface_15, !- Building Surface Name", " , !- Outside Boundary Condition Object", " 0.5000000, !- View Factor to Ground", " , !- Shading Control Name", " , !- Frame and Divider Name", " 1.0, !- Multiplier", " 4, !- Number of Vertices", " 6.000000,12.19200,2.333000, !- X,Y,Z ==> Vertex 1 {m}", " 6.000000,12.19200,1.000000, !- X,Y,Z ==> Vertex 2 {m}", " 3.000000,12.19200,1.000000, !- X,Y,Z ==> Vertex 3 {m}", " 3.000000,12.19200,2.333000; !- X,Y,Z ==> Vertex 4 {m}", "FenestrationSurface:Detailed,", " DoorInSurface_17, !- Name", " DOOR, !- Surface Type", " DOOR-CON, !- Construction Name", " Surface_17, !- Building Surface Name", " DoorInSurface_3, !- Outside Boundary Condition Object", " 0.5000000, !- View Factor to Ground", " , !- Shading Control Name", " , !- Frame and Divider Name", " 1.0, !- Multiplier", " 4, !- Number of Vertices", " 2.500,6.096000,2.0, !- X,Y,Z ==> Vertex 1 {m}", " 2.500,6.096000,0.0, !- X,Y,Z ==> Vertex 2 {m}", " 3.500,6.096000,0.0, !- X,Y,Z ==> Vertex 3 {m}", " 3.500,6.096000,2.0; !- X,Y,Z ==> Vertex 4 {m}",*/ "AirflowNetwork:SimulationControl,", " NaturalVentilation, !- Name", " MultizoneWithoutDistribution, !- AirflowNetwork Control", " INPUT, !- Wind Pressure Coefficient Type", " ExternalNode, !- Height Selection for Local Wind Pressure Calculation", " LOWRISE, !- Building Type", " 500, !- Maximum Number of Iterations {dimensionless}", " ZeroNodePressures, !- Initialization Type", " 1.0E-05, !- Relative Airflow Convergence Tolerance {dimensionless}", " 1.0E-06, !- Absolute Airflow Convergence Tolerance {kg/s}", " -0.5, !- Convergence Acceleration Limit {dimensionless}", " 0.0, !- Azimuth Angle of Long Axis of Building {deg}", " 1.0; !- Ratio of Building Width Along Short Axis to Width Along Long Axis", "AirflowNetwork:MultiZone:Zone,", " WEST_ZONE, !- Zone Name", " NoVent, !- Ventilation Control Mode", " , !- Ventilation Control Zone Temperature Setpoint Schedule Name", //" Temperature, !- Ventilation Control Mode", //" WindowVentSched, !- Ventilation Control Zone Temperature Setpoint Schedule Name", " 0.3, !- Minimum Venting Open Factor {dimensionless}", " 5.0, !- Indoor and Outdoor Temperature Difference Lower Limit For Maximum Venting Open Factor {deltaC}", " 10.0, !- Indoor and Outdoor Temperature Difference Upper Limit for Minimum Venting Open Factor {deltaC}", " 0.0, !- Indoor and Outdoor Enthalpy Difference Lower Limit For Maximum Venting Open Factor {deltaJ/kg}", " 300000.0; !- Indoor and Outdoor Enthalpy Difference Upper Limit for Minimum Venting Open Factor {deltaJ/kg}", "AirflowNetwork:MultiZone:Zone,", " EAST_ZONE, !- Zone Name", " NoVent, !- Ventilation Control Mode", " , !- Ventilation Control Zone Temperature Setpoint Schedule Name", " 1.0, !- Minimum Venting Open Factor {dimensionless}", " 0.0, !- Indoor and Outdoor Temperature Difference Lower Limit For Maximum Venting Open Factor {deltaC}", " 100.0, !- Indoor and Outdoor Temperature Difference Upper Limit for Minimum Venting Open Factor {deltaC}", " 0.0, !- Indoor and Outdoor Enthalpy Difference Lower Limit For Maximum Venting Open Factor {deltaJ/kg}", " 300000.0; !- Indoor and Outdoor Enthalpy Difference Upper Limit for Minimum Venting Open Factor {deltaJ/kg}", "AirflowNetwork:MultiZone:Zone,", " NORTH_ZONE, !- Zone Name", " NoVent, !- Ventilation Control Mode", " , !- Ventilation Control Zone Temperature Setpoint Schedule Name", //" Temperature, !- Ventilation Control Mode", //" WindowVentSched, !- Ventilation Control Zone Temperature Setpoint Schedule Name", " 1.0, !- Minimum Venting Open Factor {dimensionless}", " 0.0, !- Indoor and Outdoor Temperature Difference Lower Limit For Maximum Venting Open Factor {deltaC}", " 100.0, !- Indoor and Outdoor Temperature Difference Upper Limit for Minimum Venting Open Factor {deltaC}", " 0.0, !- Indoor and Outdoor Enthalpy Difference Lower Limit For Maximum Venting Open Factor {deltaJ/kg}", " 300000.0; !- Indoor and Outdoor Enthalpy Difference Upper Limit for Minimum Venting Open Factor {deltaJ/kg}", "AirflowNetwork:MultiZone:Surface,", " Surface_1, !- Surface Name", " CR-1, !- Leakage Component Name", " SFacade, !- External Node Name", " 1.0; !- Window/Door Opening Factor, or Crack Factor {dimensionless}", "AirflowNetwork:MultiZone:Surface,", " Surface_4, !- Surface Name", " CR-1, !- Leakage Component Name", " , !- External Node Name", " 1.0; !- Window / Door Opening Factor, or Crack Factor{ dimensionless }", "AirflowNetwork:MultiZone:Surface,", " Surface_11, !- Surface Name", " CR-1, !- Leakage Component Name", " , !- External Node Name", " 1.0; !- Window / Door Opening Factor, or Crack Factor{ dimensionless }", "AirflowNetwork:MultiZone:Surface,", " Surface_15, !- Surface Name", " CR-1, !- Leakage Component Name", " NFacade, !- External Node Name", " 1.0; !- Window / Door Opening Factor, or Crack Factor{ dimensionless }", "AirflowNetwork:MultiZone:ExternalNode,", " NFacade, !- Name", " 1.524, !- External Node Height{ m }", " NFacade_WPCValue; !- Wind Pressure Coefficient Values Object Name", "AirflowNetwork:MultiZone:ExternalNode,", " SFacade, !- Name", " 1.524, !- External Node Height{ m }", " SFacade_WPCValue, !- Wind Pressure Coefficient Values Object Name", " No, !- Symmetric Wind Pressure Coefficient Curve", " Absolute; !- Wind Angle Type", "AirflowNetwork:MultiZone:ReferenceCrackConditions,", " ReferenceCrackConditions,!- Name", " 20.0, !- Reference Temperature{ C }", " 101320, !- Reference Barometric Pressure{ Pa }", " 0.005; !- Reference Humidity Ratio{ kgWater / kgDryAir }", "AirflowNetwork:MultiZone:Surface:Crack,", " CR-1, !- Name", " 0.01, !- Air Mass Flow Coefficient at Reference Conditions{ kg / s }", " 0.667, !- Air Mass Flow Exponent{ dimensionless }", " ReferenceCrackConditions;!- Reference Crack Conditions", "AirflowNetwork:MultiZone:WindPressureCoefficientArray,", " Every 30 Degrees, !- Name", " 0, !- Wind Direction 1 {deg}", " 30, !- Wind Direction 2 {deg}", " 60, !- Wind Direction 3 {deg}", " 90, !- Wind Direction 4 {deg}", " 120, !- Wind Direction 5 {deg}", " 150, !- Wind Direction 6 {deg}", " 180, !- Wind Direction 7 {deg}", " 210, !- Wind Direction 8 {deg}", " 240, !- Wind Direction 9 {deg}", " 270, !- Wind Direction 10 {deg}", " 300, !- Wind Direction 11 {deg}", " 330; !- Wind Direction 12 {deg}", "AirflowNetwork:MultiZone:WindPressureCoefficientValues,", " NFacade_WPCValue, !- Name", " Every 30 Degrees, !- AirflowNetwork:MultiZone:WindPressureCoefficientArray Name", " 0.60, !- Wind Pressure Coefficient Value 1 {dimensionless}", " 0.48, !- Wind Pressure Coefficient Value 2 {dimensionless}", " 0.04, !- Wind Pressure Coefficient Value 3 {dimensionless}", " -0.56, !- Wind Pressure Coefficient Value 4 {dimensionless}", " -0.56, !- Wind Pressure Coefficient Value 5 {dimensionless}", " -0.42, !- Wind Pressure Coefficient Value 6 {dimensionless}", " -0.37, !- Wind Pressure Coefficient Value 7 {dimensionless}", " -0.42, !- Wind Pressure Coefficient Value 8 {dimensionless}", " -0.56, !- Wind Pressure Coefficient Value 9 {dimensionless}", " -0.56, !- Wind Pressure Coefficient Value 10 {dimensionless}", " 0.04, !- Wind Pressure Coefficient Value 11 {dimensionless}", " 0.48; !- Wind Pressure Coefficient Value 12 {dimensionless}", "AirflowNetwork:MultiZone:WindPressureCoefficientValues,", " SFacade_WPCValue, !- Name", " Every 30 Degrees, !- AirflowNetwork:MultiZone:WindPressureCoefficientArray Name", " -0.37, !- Wind Pressure Coefficient Value 1 {dimensionless}", " -0.42, !- Wind Pressure Coefficient Value 2 {dimensionless}", " -0.56, !- Wind Pressure Coefficient Value 3 {dimensionless}", " -0.56, !- Wind Pressure Coefficient Value 4 {dimensionless}", " 0.04, !- Wind Pressure Coefficient Value 5 {dimensionless}", " 0.48, !- Wind Pressure Coefficient Value 6 {dimensionless}", " 0.60, !- Wind Pressure Coefficient Value 7 {dimensionless}", " 0.48, !- Wind Pressure Coefficient Value 8 {dimensionless}", " 0.04, !- Wind Pressure Coefficient Value 9 {dimensionless}", " -0.56, !- Wind Pressure Coefficient Value 10 {dimensionless}", " -0.56, !- Wind Pressure Coefficient Value 11 {dimensionless}", " -0.42; !- Wind Pressure Coefficient Value 12 {dimensionless}", "SurfaceConvectionAlgorithm:Inside,TARP;", "SurfaceConvectionAlgorithm:Outside,DOE-2;", "HeatBalanceAlgorithm,ConductionTransferFunction;", "ZoneAirHeatBalanceAlgorithm,", " AnalyticalSolution; !- Algorithm" }); ASSERT_FALSE(process_idf(idf_objects)); bool errors = false; HeatBalanceManager::GetMaterialData(errors); // read material data EXPECT_FALSE(errors); // expect no errors HeatBalanceManager::GetConstructData(errors); // read construction data EXPECT_FALSE(errors); // expect no errors HeatBalanceManager::GetZoneData(errors); // read zone data EXPECT_FALSE(errors); // expect no errors // Magic to get surfaces read in correctly DataHeatBalance::HeatTransferAlgosUsed.allocate(1); DataHeatBalance::HeatTransferAlgosUsed(1) = OverallHeatTransferSolutionAlgo; SurfaceGeometry::CosBldgRotAppGonly = 1.0; SurfaceGeometry::SinBldgRotAppGonly = 0.0; SurfaceGeometry::GetSurfaceData(errors); // setup zone geometry and get zone data EXPECT_FALSE(errors); // expect no errors CurveManager::GetCurveInput(); EXPECT_EQ( CurveManager::NumCurves, 2 ); AirflowNetworkBalanceManager::GetAirflowNetworkInput(); // Check the airflow elements EXPECT_EQ( 2u, DataAirflowNetwork::MultizoneExternalNodeData.size() ); EXPECT_EQ( 3u, DataAirflowNetwork::MultizoneZoneData.size() ); EXPECT_EQ( 4u, DataAirflowNetwork::MultizoneSurfaceData.size() ); EXPECT_EQ( 1u, DataAirflowNetwork::MultizoneSurfaceCrackData.size() ); EXPECT_EQ( 2u, DataAirflowNetwork::MultizoneSurfaceStdConditionsCrackData.size() ); EXPECT_EQ( 0.0, DataAirflowNetwork::MultizoneExternalNodeData( 1 ).azimuth ); EXPECT_FALSE( DataAirflowNetwork::MultizoneExternalNodeData( 1 ).symmetricCurve ); EXPECT_FALSE( DataAirflowNetwork::MultizoneExternalNodeData( 1 ).useRelativeAngle ); EXPECT_EQ( 1, DataAirflowNetwork::MultizoneExternalNodeData( 1 ).curve ); EXPECT_EQ( 180.0, DataAirflowNetwork::MultizoneExternalNodeData( 2 ).azimuth ); EXPECT_FALSE( DataAirflowNetwork::MultizoneExternalNodeData( 2 ).symmetricCurve ); EXPECT_FALSE( DataAirflowNetwork::MultizoneExternalNodeData( 2 ).useRelativeAngle ); EXPECT_EQ( 2, DataAirflowNetwork::MultizoneExternalNodeData( 2 ).curve ); // Set up some environmental parameters DataEnvironment::OutBaroPress = 101325.0; DataEnvironment::OutDryBulbTemp = 25.0; DataEnvironment::WindDir = 105.0; DataEnvironment::OutHumRat = 0.0; // Dry air only DataEnvironment::SiteTempGradient = 0.0; // Disconnect z from testing DataEnvironment::SiteWindExp = 0.0; // Disconnect variation by height DataEnvironment::WindSpeed = 10.0; // Make sure we can compute the right wind pressure Real64 rho = Psychrometrics::PsyRhoAirFnPbTdbW( DataEnvironment::OutBaroPress, DataEnvironment::OutDryBulbTemp, DataEnvironment::OutHumRat ); EXPECT_DOUBLE_EQ( 1.1841123742118911, rho ); Real64 p = AirflowNetworkBalanceManager::CalcWindPressure( DataAirflowNetwork::MultizoneExternalNodeData( 1 ).curve, 1.0, 0.0, 0.0, false, false ); EXPECT_DOUBLE_EQ( -0.56*0.5*1.1841123742118911, p ); // Make sure the reference velocity comes out right EXPECT_DOUBLE_EQ( 10.0, DataEnvironment::WindSpeedAt( MultizoneExternalNodeData( 1 ).height) ); EXPECT_EQ( 5u, DataAirflowNetwork::AirflowNetworkNodeSimu.size() ); // Run the balance routine, for now only to get the pressure set at the external nodes AirflowNetworkBalanceManager::CalcAirflowNetworkAirBalance(); EXPECT_DOUBLE_EQ( -0.56*0.5*118.41123742118911, DataAirflowNetwork::AirflowNetworkNodeSimu( 4 ).PZ ); EXPECT_DOUBLE_EQ( -0.26*0.5*118.41123742118911, DataAirflowNetwork::AirflowNetworkNodeSimu( 5 ).PZ ); } MLS
true