{ // 获取包含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"},"label":{"kind":"class label","value":"57","name":"Visualize a tree"},"domain_label":{"kind":"class label","value":"10","name":"javascript"},"index":{"kind":"string","value":"qe3x8"}}},{"rowIdx":707,"cells":{"code":{"kind":"null"},"label":{"kind":"class label","value":"58","name":"Walk a directory/Recursively"},"domain_label":{"kind":"class label","value":"11","name":"kotlin"},"index":{"kind":"string","value":"osm8z"}}},{"rowIdx":708,"cells":{"code":{"kind":"null"},"label":{"kind":"class label","value":"56","name":"Water collected between towers"},"domain_label":{"kind":"class label","value":"11","name":"kotlin"},"index":{"kind":"string","value":"lmbcp"}}},{"rowIdx":709,"cells":{"code":{"kind":"null"},"label":{"kind":"class label","value":"63","name":"Video display modes"},"domain_label":{"kind":"class label","value":"11","name":"kotlin"},"index":{"kind":"string","value":"52jua"}}},{"rowIdx":710,"cells":{"code":{"kind":"string","value":"print(\"\\33[?3h\")"},"label":{"kind":"class label","value":"63","name":"Video display modes"},"domain_label":{"kind":"class label","value":"1","name":"lua"},"index":{"kind":"string","value":"4vh5c"}}},{"rowIdx":711,"cells":{"code":{"kind":"string","value":"void to_seq(uint64_t x, uint8_t *out)\n{\n\tint i, j;\n\tfor (i = 9; i > 0; i--) {\n\t\tif (x & 127ULL << i * 7) break;\n\t}\n\tfor (j = 0; j <= i; j++)\n\t\tout[j] = ((x >> ((i - j) * 7)) & 127) | 128;\n\n\tout[i] ^= 128;\n}\n\nuint64_t from_seq(uint8_t *in)\n{\n\tuint64_t r = 0;\n\n\tdo {\n\t\tr = (r << 7) | (uint64_t)(*in & 127);\n\t} while (*in++ & 128);\n\n\treturn r;\n}\n\nint main()\n{\n\tuint8_t s[10];\n\tuint64_t x[] = { 0x7f, 0x4000, 0, 0x3ffffe, 0x1fffff, 0x200000, 0x3311a1234df31413ULL};\n\n\tint i, j;\n\tfor (j = 0; j < sizeof(x)/8; j++) {\n\t\tto_seq(x[j], s);\n\t\tprintf(, x[j]);\n\n\t\ti = 0;\n\t\tdo { printf(, s[i]); } while ((s[i++] & 128));\n\t\tprintf(, from_seq(s));\n\t}\n\n\treturn 0;\n}"},"label":{"kind":"class label","value":"64","name":"Variable-length quantity"},"domain_label":{"kind":"class label","value":"5","name":"c"},"index":{"kind":"string","value":"3f9za"}}},{"rowIdx":712,"cells":{"code":{"kind":"string","value":"int_least32_t foo;"},"label":{"kind":"class label","value":"65","name":"Variable size/Set"},"domain_label":{"kind":"class label","value":"5","name":"c"},"index":{"kind":"string","value":"r5hg7"}}},{"rowIdx":713,"cells":{"code":{"kind":"null"},"label":{"kind":"class label","value":"62","name":"Verify distribution uniformity/Chi-squared test"},"domain_label":{"kind":"class label","value":"11","name":"kotlin"},"index":{"kind":"string","value":"n86ij"}}},{"rowIdx":714,"cells":{"code":{"kind":"string","value":"function waterCollected(i,tower)\n local length = 0\n for _ in pairs(tower) do\n length = length + 1\n end\n\n local wu = 0\n repeat\n local rht = length - 1\n while rht >= 0 do\n if tower[rht + 1] > 0 then\n break\n end\n rht = rht - 1\n end\n if rht < 0 then\n break\n end\n\n local bof = 0\n local col = 0\n while col <= rht do\n if tower[col + 1] > 0 then\n tower[col + 1] = tower[col + 1] - 1\n bof = bof + 1\n elseif bof > 0 then\n wu = wu + 1\n end\n col = col + 1\n end\n if bof < 2 then\n break\n end\n until false\n if wu == 0 then\n print(string.format(\"Block%d does not hold any water.\", i))\n else\n print(string.format(\"Block%d holds%d water units.\", i, wu))\n end\nend\n\nfunction main()\n local towers = {\n {1, 5, 3, 7, 2},\n {5, 3, 7, 2, 6, 4, 5, 9, 1, 2},\n {2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1},\n {5, 5, 5, 5},\n {5, 6, 7, 8},\n {8, 7, 7, 6},\n {6, 7, 10, 7, 6}\n }\n\n for i,tbl in pairs(towers) do\n waterCollected(i,tbl)\n end\nend\n\nmain()"},"label":{"kind":"class label","value":"56","name":"Water collected between towers"},"domain_label":{"kind":"class label","value":"1","name":"lua"},"index":{"kind":"string","value":"29pl3"}}},{"rowIdx":715,"cells":{"code":{"kind":"string","value":"$| = 1;\n\nmy @info = `xrandr -q`;\n$info[0] =~ /current (\\d+) x (\\d+)/;\nmy $current = \"$1x$2\";\n\nmy @resolutions;\nfor (@info) {\n push @resolutions, $1 if /^\\s+(\\d+x\\d+)/\n}\n\nsystem(\"xrandr -s $resolutions[-1]\");\nprint \"Current resolution $resolutions[-1].\\n\";\nfor (reverse 1 .. 9) {\n print \"\\rChanging back in $_ seconds...\";\n sleep 1;\n}\nsystem(\"xrandr -s $current\");\nprint \"\\rResolution returned to $current.\\n\";"},"label":{"kind":"class label","value":"63","name":"Video display modes"},"domain_label":{"kind":"class label","value":"2","name":"perl"},"index":{"kind":"string","value":"ost8x"}}},{"rowIdx":716,"cells":{"code":{"kind":"string","value":"import win32api\nimport win32con\nimport pywintypes\ndevmode=pywintypes.DEVMODEType()\ndevmode.PelsWidth=640\ndevmode.PelsHeight=480\ndevmode.Fields=win32con.DM_PELSWIDTH | win32con.DM_PELSHEIGHT\nwin32api.ChangeDisplaySettings(devmode,0)"},"label":{"kind":"class label","value":"63","name":"Video display modes"},"domain_label":{"kind":"class label","value":"3","name":"python"},"index":{"kind":"string","value":"i0zof"}}},{"rowIdx":717,"cells":{"code":{"kind":"string","value":"typedef struct{\n\tdouble x,y;\n}vector;\n\nvector initVector(double r,double theta){\n\tvector c;\n\n\tc.x = r*cos(theta);\n\tc.y = r*sin(theta);\n\n\treturn c;\n}\n\nvector addVector(vector a,vector b){\n\tvector c;\n\n\tc.x = a.x + b.x;\n\tc.y = a.y + b.y;\n\n\treturn c;\n}\n\nvector subtractVector(vector a,vector b){\n\tvector c;\n\n\tc.x = a.x - b.x;\n\tc.y = a.y - b.y;\n\n\treturn c;\n}\n\nvector multiplyVector(vector a,double b){\n\tvector c;\n\n\tc.x = b*a.x;\n\tc.y = b*a.y;\n\n\treturn c;\n}\n\nvector divideVector(vector a,double b){\n\tvector c;\n\n\tc.x = a.x/b;\n\tc.y = a.y/b;\n\n\treturn c;\n}\n\nvoid printVector(vector a){\n\tprintf(,a.x,140,(a.y>=0)?'+':'-',(a.y>=0)?a.y:fabs(a.y),150);\n}\n\nint main()\n{\n\tvector a = initVector(3,pi/6);\n\tvector b = initVector(5,2*pi/3);\n\n\tprintf();\n\tprintVector(a);\n\n\tprintf();\n\tprintVector(b);\n\n\tprintf();\n\tprintVector(addVector(a,b));\n\n\tprintf();\n\tprintVector(subtractVector(a,b));\n\n\tprintf();\n\tprintVector(multiplyVector(a,3));\n\n\tprintf();\n\tprintVector(divideVector(b,2.5));\n\n\treturn 0;\n}"},"label":{"kind":"class label","value":"66","name":"Vector"},"domain_label":{"kind":"class label","value":"5","name":"c"},"index":{"kind":"string","value":"8qi04"}}},{"rowIdx":718,"cells":{"code":{"kind":"null"},"label":{"kind":"class label","value":"57","name":"Visualize a tree"},"domain_label":{"kind":"class label","value":"11","name":"kotlin"},"index":{"kind":"string","value":"jgs7r"}}},{"rowIdx":719,"cells":{"code":{"kind":"string","value":"Dir.glob('*') { |file| puts file }\n\n\nDir.glob( File.join('/foo/bar', '*') ) { |file| puts file }\n\n\ndef file_match(pattern=/\\.txt/, path='.')\n Dir[File.join(path,'*')].each do |file|\n puts file if file =~ pattern\n end\nend"},"label":{"kind":"class label","value":"53","name":"Walk a directory/Non-recursively"},"domain_label":{"kind":"class label","value":"14","name":"ruby"},"index":{"kind":"string","value":"74ori"}}},{"rowIdx":720,"cells":{"code":{"kind":"string","value":"local lfs = require(\"lfs\")"},"label":{"kind":"class label","value":"58","name":"Walk a directory/Recursively"},"domain_label":{"kind":"class label","value":"1","name":"lua"},"index":{"kind":"string","value":"i09ot"}}},{"rowIdx":721,"cells":{"code":{"kind":"string","value":"package main\n\nimport \"fmt\"\n\ntype vkey string\n\nfunc newVigenre(key string) (vkey, bool) {\n v := vkey(upperOnly(key))\n return v, len(v) > 0"},"label":{"kind":"class label","value":"61","name":"Vigenère cipher"},"domain_label":{"kind":"class label","value":"0","name":"go"},"index":{"kind":"string","value":"os38q"}}},{"rowIdx":722,"cells":{"code":{"kind":"string","value":"function makeTree(v,ac)\n if type(ac) == \"table\" then\n return {value=v,children=ac}\n else\n return {value=v}\n end\nend\n\nfunction printTree(t,last,prefix)\n if last == nil then\n printTree(t, false, '')\n else\n local current = ''\n local next = ''\n\n if last then\n current = prefix .. '\\\\-' .. t.value\n next = prefix .. ' '\n else\n current = prefix .. '|-' .. t.value\n next = prefix .. '| '\n end\n\n print(current:sub(3))\n if t.children ~= nil then\n for k,v in pairs(t.children) do\n printTree(v, k == #t.children, next)\n end\n end\n end\nend\n\nprintTree(\n makeTree('A', {\n makeTree('B0', {\n makeTree('C1'),\n makeTree('C2', {\n makeTree('D', {\n makeTree('E1'),\n makeTree('E2'),\n makeTree('E3')\n })\n }),\n makeTree('C3', {\n makeTree('F1'),\n makeTree('F2'),\n makeTree('F3', {makeTree('G')}),\n makeTree('F4', {\n makeTree('H1'),\n makeTree('H2')\n })\n })\n }),\n makeTree('B1',{\n makeTree('K1'),\n makeTree('K2', {\n makeTree('L1', {makeTree('M')}),\n makeTree('L2'),\n makeTree('L3')\n }),\n makeTree('K3')\n })\n })\n)"},"label":{"kind":"class label","value":"57","name":"Visualize a tree"},"domain_label":{"kind":"class label","value":"1","name":"lua"},"index":{"kind":"string","value":"hr0j8"}}},{"rowIdx":723,"cells":{"code":{"kind":"string","value":"extern crate docopt;\nextern crate regex;\nextern crate rustc_serialize;\n\nuse docopt::Docopt;\nuse regex::Regex;\n\nconst USAGE: &'static str = \"\nUsage: rosetta \n\nWalks the directory tree starting with the current working directory and\nprint filenames matching .\n\";\n\n#[derive(Debug, RustcDecodable)]\nstruct Args {\n arg_pattern: String,\n}\n\nfn main() {\n let args: Args = Docopt::new(USAGE)\n .and_then(|d| d.decode())\n .unwrap_or_else(|e| e.exit());\n\n let re = Regex::new(&args.arg_pattern).unwrap();\n let paths = std::fs::read_dir(\".\").unwrap();\n\n for path in paths {\n let path = path.unwrap().path();\n let path = path.to_str().unwrap();\n\n if re.is_match(path) {\n println!(\"{}\", path);\n }\n }\n}"},"label":{"kind":"class label","value":"53","name":"Walk a directory/Non-recursively"},"domain_label":{"kind":"class label","value":"15","name":"rust"},"index":{"kind":"string","value":"jgi72"}}},{"rowIdx":724,"cells":{"code":{"kind":"string","value":"object VideoDisplayModes extends App {\n\n import java.util.Scanner\n\n def runSystemCommand(command: String) {\n val proc = Runtime.getRuntime.exec(command)\n\n val a: Unit = {\n val a = new Scanner(proc.getInputStream)\n while (a.hasNextLine) println(a.nextLine())\n }\n proc.waitFor()\n println()\n }"},"label":{"kind":"class label","value":"63","name":"Video display modes"},"domain_label":{"kind":"class label","value":"16","name":"scala"},"index":{"kind":"string","value":"3fczy"}}},{"rowIdx":725,"cells":{"code":{"kind":"string","value":"sub roll7 { 1+int rand(7) }\nsub roll5 { 1+int rand(5) }\nsub roll7_5 {\n while(1) {\n my $d7 = (5*&roll5 + &roll5 - 6) % 8;\n return $d7 if $d7;\n }\n}\n\nmy $threshold = 5;\n\nprint dist( $_, $threshold, \\&roll7 ) for <1001 1000006>;\nprint dist( $_, $threshold, \\&roll7_5 ) for <1001 1000006>;\n\nsub dist {\nmy($n, $threshold, $producer) = @_;\n my @dist;\n my $result;\n my $expect = $n / 7;\n $result .= sprintf \"%10d expected\\n\", $expect;\n\n for (1..$n) { @dist[&$producer]++; }\n\n for my $i (1..7) {\n my $v = @dist[$i];\n my $pct = ($v - $expect)/$expect*100;\n $result .= sprintf \"%d%8d%6.1f%%%s\\n\", $i, $v, $pct, (abs($pct) > $threshold ? ' - skewed' : '');\n }\n return $result . \"\\n\";\n}"},"label":{"kind":"class label","value":"59","name":"Verify distribution uniformity/Naive"},"domain_label":{"kind":"class label","value":"2","name":"perl"},"index":{"kind":"string","value":"vck20"}}},{"rowIdx":726,"cells":{"code":{"kind":"string","value":"package main\n\nimport (\n \"fmt\"\n \"unsafe\"\n)\n\nfunc main() {\n i := 5"},"label":{"kind":"class label","value":"65","name":"Variable size/Set"},"domain_label":{"kind":"class label","value":"0","name":"go"},"index":{"kind":"string","value":"n8ti1"}}},{"rowIdx":727,"cells":{"code":{"kind":"string","value":"import Data.Int\nimport Foreign.Storable\n\ntask name value = putStrLn $ name ++ \": \" ++ show (sizeOf value) ++ \" byte(s)\"\n\nmain = do\n let i8 = 0::Int8\n let i16 = 0::Int16\n let i32 = 0::Int32\n let i64 = 0::Int64\n let int = 0::Int\n task \"Int8\" i8\n task \"Int16\" i16\n task \"Int32\" i32\n task \"Int64\" i64\n task \"Int\" int"},"label":{"kind":"class label","value":"65","name":"Variable size/Set"},"domain_label":{"kind":"class label","value":"8","name":"haskell"},"index":{"kind":"string","value":"ulgv2"}}},{"rowIdx":728,"cells":{"code":{"kind":"string","value":"require_relative 'raster_graphics'\n\nclass ColourPixel < Pixel\n def initialize(x, y, colour)\n @colour = colour\n super x, y\n end\n attr_accessor :colour\n\n def distance_to(px, py)\n Math.hypot(px - x, py - y)\n end\nend\n\nwidth = 300\nheight = 200\nnpoints = 20\npixmap = Pixmap.new(width, height)\n\n@bases = npoints.times.collect do |_i|\n ColourPixel.new(\n 3 + rand(width - 6), 3 + rand(height - 6), \n RGBColour.new(rand(256), rand(256), rand(256))\n )\nend\n\npixmap.each_pixel do |x, y|\n nearest = @bases.min_by { |base| base.distance_to(x, y) }\n pixmap[x, y] = nearest.colour\nend\n\n@bases.each do |base|\n pixmap[base.x, base.y] = RGBColour::BLACK\n pixmap.draw_circle(base, 2, RGBColour::BLACK)\nend\n\npixmap.save_as_png('voronoi_rb.png')"},"label":{"kind":"class label","value":"54","name":"Voronoi diagram"},"domain_label":{"kind":"class label","value":"14","name":"ruby"},"index":{"kind":"string","value":"yzh6n"}}},{"rowIdx":729,"cells":{"code":{"kind":"string","value":"import Data.Char\nimport Text.Printf\n\n\ncrypt f key = map toLetter . zipWith f (cycle key)\n where toLetter = chr . (+) (ord 'A')\n\n\nenc k c = (ord k + ord c) `mod` 26\ndec k c = (ord c - ord k) `mod` 26\n\n\nencrypt = crypt enc\ndecrypt = crypt dec\n\n\nconvert = map toUpper . filter isLetter\n\nmain :: IO ()\nmain = do\n let key = \"VIGENERECIPHER\"\n text = \"Beware the Jabberwock, my son! The jaws that bite, \"\n ++ \"the claws that catch!\"\n encr = encrypt key $ convert text\n decr = decrypt key encr\n printf \" Input:%s\\n Key:%s\\nEncrypted:%s\\nDecrypted:%s\\n\"\n text key encr decr"},"label":{"kind":"class label","value":"61","name":"Vigenère cipher"},"domain_label":{"kind":"class label","value":"8","name":"haskell"},"index":{"kind":"string","value":"297ll"}}},{"rowIdx":730,"cells":{"code":{"kind":"string","value":"import java.io.File\n\nval dir = new File(\"/foo/bar\").list()\ndir.filter(file => file.endsWith(\".mp3\")).foreach(println)"},"label":{"kind":"class label","value":"53","name":"Walk a directory/Non-recursively"},"domain_label":{"kind":"class label","value":"16","name":"scala"},"index":{"kind":"string","value":"bjfk6"}}},{"rowIdx":731,"cells":{"code":{"kind":"null"},"label":{"kind":"class label","value":"65","name":"Variable size/Set"},"domain_label":{"kind":"class label","value":"11","name":"kotlin"},"index":{"kind":"string","value":"tn6f0"}}},{"rowIdx":732,"cells":{"code":{"kind":"string","value":"extern crate piston;\nextern crate opengl_graphics;\nextern crate graphics;\nextern crate touch_visualizer;\n\n#[cfg(feature = \"include_sdl2\")]\nextern crate sdl2_window;\n\nextern crate getopts;\nextern crate voronoi;\nextern crate rand;\n\nuse touch_visualizer::TouchVisualizer;\nuse opengl_graphics::{ GlGraphics, OpenGL };\nuse graphics::{ Context, Graphics };\nuse piston::window::{ Window, WindowSettings };\nuse piston::input::*;\nuse piston::event_loop::*;\n#[cfg(feature = \"include_sdl2\")]\nuse sdl2_window::Sdl2Window as AppWindow;\nuse voronoi::{voronoi, Point, make_polygons};\nuse rand::Rng;\n\nstatic DEFAULT_WINDOW_HEIGHT: u32 = 600;\nstatic DEFAULT_WINDOW_WIDTH: u32 = 600;\n\nstruct Settings {\n lines_only: bool,\n random_count: usize\n}\n\nfn main() {\n let args: Vec = std::env::args().collect();\n let mut opts = getopts::Options::new();\n opts.optflag(\"l\", \"lines_only\", \"Don't color polygons, just outline them\");\n opts.optopt(\"r\", \"random_count\", \"On keypress \\\"R\\\", put this many random points on-screen\", \"RANDOMCOUNT\");\n let matches = opts.parse(&args[1..]).expect(\"Failed to parse args\");\n\n let settings = Settings{\n lines_only: matches.opt_present(\"l\"),\n random_count: match matches.opt_str(\"r\") {\n None => { 50 },\n Some(s) => { s.parse().expect(\"Random count of bad format\") }\n }\n };\n\n event_loop(&settings);\n\n}\n\nfn random_point() -> [f64; 2] {\n [rand::thread_rng().gen_range(0., DEFAULT_WINDOW_HEIGHT as f64), rand::thread_rng().gen_range(0., DEFAULT_WINDOW_WIDTH as f64)]\n}\n\nfn random_color() -> [f32; 4] {\n [rand::random::(), rand::random::(), rand::random::(), 1.0]\n}\n\nfn random_voronoi(dots: &mut Vec<[f64;2]>, colors: &mut Vec<[f32;4]>, num: usize) {\n dots.clear();\n colors.clear();\n\n for _ in 0..num {\n dots.push(random_point());\n colors.push(random_color());\n }\n}\n\nfn event_loop(settings: &Settings) {\n let opengl = OpenGL::V3_2;\n let mut window: AppWindow = WindowSettings::new(\"Interactive Voronoi\", [DEFAULT_WINDOW_HEIGHT, DEFAULT_WINDOW_WIDTH])\n .exit_on_esc(true).opengl(opengl).build().unwrap();\n\n let ref mut gl = GlGraphics::new(opengl);\n let mut touch_visualizer = TouchVisualizer::new();\n let mut events = Events::new(EventSettings::new().lazy(true));\n let mut dots = Vec::new();\n let mut colors = Vec::new();\n\n let mut mx = 0.0;\n let mut my = 0.0;\n\n while let Some(e) = events.next(&mut window) {\n touch_visualizer.event(window.size(), &e);\n if let Some(button) = e.release_args() {\n match button {\n Button::Keyboard(key) => {\n if key == piston::input::keyboard::Key::N { dots.clear(); colors.clear(); }\n if key == piston::input::keyboard::Key::R { random_voronoi(&mut dots, &mut colors, settings.random_count); }\n }\n Button::Mouse(_) => {\n dots.push([mx, my]);\n colors.push(random_color());\n },\n _ => ()\n }\n };\n e.mouse_cursor(|x, y| {\n mx = x;\n my = y;\n });\n if let Some(args) = e.render_args() {\n gl.draw(args.viewport(), |c, g| {\n graphics::clear([1.0; 4], g);\n let mut vor_pts = Vec::new();\n for d in &dots {\n vor_pts.push(Point::new(d[0], d[1]));\n }\n if vor_pts.len() > 0 {\n let vor_diagram = voronoi(vor_pts, DEFAULT_WINDOW_WIDTH as f64);\n let vor_polys = make_polygons(&vor_diagram);\n for (i, poly) in vor_polys.iter().enumerate() {\n if settings.lines_only {\n draw_lines_in_polygon(poly, &c, g);\n } else {\n draw_polygon(poly, &c, g, colors[i]);\n }\n }\n }\n for d in &dots {\n draw_ellipse(&d, &c, g);\n }\n });\n }\n } \n\n}\n\nfn draw_lines_in_polygon(\n poly: &Vec,\n c: &Context,\n g: &mut G,\n)\n{\n let color = [0.0, 0.0, 1.0, 1.0];\n\n for i in 0..poly.len()-1 {\n graphics::line(\n color,\n 2.0,\n [poly[i].x.into(), poly[i].y.into(), poly[i+1].x.into(), poly[i+1].y.into()],\n c.transform,\n g\n )\n }\n}\n\nfn draw_polygon(\n poly: &Vec,\n c: &Context,\n g: &mut G,\n color: [f32; 4]\n) {\n let mut polygon_points: Vec<[f64; 2]> = Vec::new();\n\n for p in poly {\n polygon_points.push([p.x.into(), p.y.into()]);\n }\n\n graphics::polygon(\n color,\n polygon_points.as_slice(),\n c.transform,\n g\n )\n}\n\nfn draw_ellipse(\n cursor: &[f64; 2],\n c: &Context,\n g: &mut G,\n) {\n let color = [0.0, 0.0, 0.0, 1.0];\n graphics::ellipse(\n color,\n graphics::ellipse::circle(cursor[0], cursor[1], 4.0),\n c.transform,\n g\n );\n}"},"label":{"kind":"class label","value":"54","name":"Voronoi diagram"},"domain_label":{"kind":"class label","value":"15","name":"rust"},"index":{"kind":"string","value":"m3kya"}}},{"rowIdx":733,"cells":{"code":{"kind":"string","value":"use List::Util qw(sum reduce);\nuse constant pi => 3.14159265;\n\nsub incomplete_G_series {\n my($s, $z) = @_;\n my $n = 10;\n push @numers, $z**$_ for 1..$n;\n my @denoms = $s+1;\n push @denoms, $denoms[-1]*($s+$_) for 2..$n;\n my $M = 1;\n $M += $numers[$_-1]/$denoms[$_-1] for 1..$n;\n $z**$s / $s * exp(-$z) * $M;\n}\n\nsub G_of_half {\n my($n) = @_;\n if ($n % 2) { f(2*$_) / (4**$_ * f($_)) * sqrt(pi) for int ($n-1) / 2 }\n else { f(($n/2)-1) }\n}\n\nsub f { reduce { $a * $b } 1, 1 .. $_[0] } \n\nsub chi_squared_cdf {\n my($k, $x) = @_;\n my $f = $k < 20 ? 20 : 10;\n if ($x == 0) { 0.0 }\n elsif ($x < $k + $f*sqrt($k)) { incomplete_G_series($k/2, $x/2) / G_of_half($k) }\n else { 1.0 }\n}\nsub chi_squared_test {\n my(@bins) = @_;\n $significance = 0.05;\n my $n = @bins;\n my $N = sum @bins;\n my $expected = $N / $n;\n my $chi_squared = sum map { ($_ - $expected)**2 / $expected } @bins;\n my $p_value = 1 - chi_squared_cdf($n-1, $chi_squared);\n return $chi_squared, $p_value, $p_value > $significance ? 'True' : 'False';\n}\n\nfor $dataset ([199809, 200665, 199607, 200270, 199649], [522573, 244456, 139979, 71531, 21461]) {\n printf \"C2 =%10.3f, p-value =%.3f, uniform =%s\\n\", chi_squared_test(@$dataset);\n}"},"label":{"kind":"class label","value":"62","name":"Verify distribution uniformity/Chi-squared test"},"domain_label":{"kind":"class label","value":"2","name":"perl"},"index":{"kind":"string","value":"741rh"}}},{"rowIdx":734,"cells":{"code":{"kind":"string","value":"use Modern::Perl;\nuse List::Util qw{ min max sum };\n\nsub water_collected {\n my @t = map { { TOWER => $_, LEFT => 0, RIGHT => 0, LEVEL => 0 } } @_;\n\n my ( $l, $r ) = ( 0, 0 );\n $_->{LEFT} = ( $l = max( $l, $_->{TOWER} ) ) for @t;\n $_->{RIGHT} = ( $r = max( $r, $_->{TOWER} ) ) for reverse @t;\n $_->{LEVEL} = min( $_->{LEFT}, $_->{RIGHT} ) for @t;\n\n return sum map { $_->{LEVEL} > 0 ? $_->{LEVEL} - $_->{TOWER} : 0 } @t;\n}\n\nsay join ' ', map { water_collected( @{$_} ) } (\n [ 1, 5, 3, 7, 2 ],\n [ 5, 3, 7, 2, 6, 4, 5, 9, 1, 2 ],\n [ 2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1 ],\n [ 5, 5, 5, 5 ],\n [ 5, 6, 7, 8 ],\n [ 8, 7, 7, 6 ],\n [ 6, 7, 10, 7, 6 ],\n);"},"label":{"kind":"class label","value":"56","name":"Water collected between towers"},"domain_label":{"kind":"class label","value":"2","name":"perl"},"index":{"kind":"string","value":"qe6x6"}}},{"rowIdx":735,"cells":{"code":{"kind":"string","value":"package main\n\nimport (\n \"fmt\"\n \"encoding/binary\"\n)\n\nfunc main() {\n buf := make([]byte, binary.MaxVarintLen64)\n for _, x := range []int64{0x200000, 0x1fffff} {\n v := buf[:binary.PutVarint(buf, x)]\n fmt.Printf(\"%d encodes into%d bytes:%x\\n\", x, len(v), v)\n x, _ = binary.Varint(v)\n fmt.Println(x, \"decoded\")\n }\n}"},"label":{"kind":"class label","value":"64","name":"Variable-length quantity"},"domain_label":{"kind":"class label","value":"0","name":"go"},"index":{"kind":"string","value":"bjekh"}}},{"rowIdx":736,"cells":{"code":{"kind":"string","value":"import java.awt.geom.Ellipse2D\nimport java.awt.image.BufferedImage\nimport java.awt.{Color, Graphics, Graphics2D}\n\nimport scala.math.sqrt\n\nobject Voronoi extends App {\n private val (cells, dim) = (100, 1000)\n private val rand = new scala.util.Random\n private val color = Vector.fill(cells)(rand.nextInt(0x1000000))\n private val image = new BufferedImage(dim, dim, BufferedImage.TYPE_INT_RGB)\n private val g: Graphics2D = image.createGraphics()\n private val px = Vector.fill(cells)(rand.nextInt(dim))\n private val py = Vector.fill(cells)(rand.nextInt(dim))\n\n for (x <- 0 until dim;\n y <- 0 until dim) {\n var n = 0\n\n def distance(x1: Int, x2: Int, y1: Int, y2: Int) =\n sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2).toDouble)"},"label":{"kind":"class label","value":"54","name":"Voronoi diagram"},"domain_label":{"kind":"class label","value":"16","name":"scala"},"index":{"kind":"string","value":"lm1cq"}}},{"rowIdx":737,"cells":{"code":{"kind":"string","value":"from collections import Counter\nfrom pprint import pprint as pp\n\ndef distcheck(fn, repeats, delta):\n '''\\\n Bin the answers to fn() and check bin counts are within +/- delta%\n of repeats/bincount'''\n bin = Counter(fn() for i in range(repeats))\n target = repeats \n deltacount = int(delta / 100. * target)\n assert all( abs(target - count) < deltacount\n for count in bin.values() ), % (\n target, deltacount, [ (key, target - count)\n for key, count in sorted(bin.items()) ]\n )\n pp(dict(bin))"},"label":{"kind":"class label","value":"59","name":"Verify distribution uniformity/Naive"},"domain_label":{"kind":"class label","value":"3","name":"python"},"index":{"kind":"string","value":"ulbvd"}}},{"rowIdx":738,"cells":{"code":{"kind":"string","value":"final RADIX = 7\nfinal MASK = 2**RADIX - 1\n\ndef octetify = { n ->\n def octets = []\n for (def i = n; i != 0; i >>>= RADIX) {\n octets << ((byte)((i & MASK) + (octets.empty ? 0: MASK + 1)))\n }\n octets.reverse()\n}\n\ndef deoctetify = { octets ->\n octets.inject(0) { long n, octet ->\n (n << RADIX) + ((int)(octet) & MASK)\n }\n}"},"label":{"kind":"class label","value":"64","name":"Variable-length quantity"},"domain_label":{"kind":"class label","value":"7","name":"groovy"},"index":{"kind":"string","value":"r5kgh"}}},{"rowIdx":739,"cells":{"code":{"kind":"string","value":"import Numeric (readOct, showOct)\nimport Data.List (intercalate)\n\nto :: Int -> String\nto = flip showOct \"\"\n\nfrom :: String -> Int\nfrom = fst . head . readOct\n\nmain :: IO ()\nmain =\n mapM_\n (putStrLn .\n intercalate \" <-> \" . (pure (:) <*> to <*> (return . show . from . to)))\n [2097152, 2097151]"},"label":{"kind":"class label","value":"64","name":"Variable-length quantity"},"domain_label":{"kind":"class label","value":"8","name":"haskell"},"index":{"kind":"string","value":"do3n4"}}},{"rowIdx":740,"cells":{"code":{"kind":"string","value":"with javascript_semantics\nrequires(\"1.0.0\")\ninclude mpfr.e\nmpfr pi = mpfr_init(0,-121) -- 120 dp, +1 for the \"3.\"\nmpfr_const_pi(pi)\nprintf(1,\"PI with 120 decimals:%s\\n\\n\",mpfr_get_fixed(pi,120))"},"label":{"kind":"class label","value":"65","name":"Variable size/Set"},"domain_label":{"kind":"class label","value":"2","name":"perl"},"index":{"kind":"string","value":"k71hc"}}},{"rowIdx":741,"cells":{"code":{"kind":"string","value":"import math\nimport random\n\ndef GammaInc_Q( a, x):\n a1 = a-1\n a2 = a-2\n def f0( t ):\n return t**a1*math.exp(-t)\n\n def df0(t):\n return (a1-t)*t**a2*math.exp(-t)\n\n y = a1\n while f0(y)*(x-y) >2.0e-8 and y < x: y += .3\n if y > x: y = x\n\n h = 3.0e-4\n n = int(y/h)\n h = y/n\n hh = 0.5*h\n gamax = h * sum( f0(t)+hh*df0(t) for t in ( h*j for j in xrange(n-1, -1, -1)))\n\n return gamax/gamma_spounge(a)\n\nc = None\ndef gamma_spounge( z):\n global c\n a = 12\n\n if c is None:\n k1_factrl = 1.0\n c = []\n c.append(math.sqrt(2.0*math.pi))\n for k in range(1,a):\n c.append( math.exp(a-k) * (a-k)**(k-0.5) / k1_factrl )\n k1_factrl *= -k\n\n accm = c[0]\n for k in range(1,a):\n accm += c[k] / (z+k)\n accm *= math.exp( -(z+a)) * (z+a)**(z+0.5)\n return accm/z;\n\ndef chi2UniformDistance( dataSet ):\n expected = sum(dataSet)*1.0/len(dataSet)\n cntrd = (d-expected for d in dataSet)\n return sum(x*x for x in cntrd)/expected\n\ndef chi2Probability(dof, distance):\n return 1.0 - GammaInc_Q( 0.5*dof, 0.5*distance)\n\ndef chi2IsUniform(dataSet, significance):\n dof = len(dataSet)-1\n dist = chi2UniformDistance(dataSet)\n return chi2Probability( dof, dist ) > significance\n\ndset1 = [ 199809, 200665, 199607, 200270, 199649 ]\ndset2 = [ 522573, 244456, 139979, 71531, 21461 ]\n\nfor ds in (dset1, dset2):\n print , ds\n dof = len(ds)-1\n distance =chi2UniformDistance(ds)\n print % (dof, distance),\n prob = chi2Probability( dof, distance)\n print %prob,\n print , if chi2IsUniform(ds,0.05) else"},"label":{"kind":"class label","value":"62","name":"Verify distribution uniformity/Chi-squared test"},"domain_label":{"kind":"class label","value":"3","name":"python"},"index":{"kind":"string","value":"jga7p"}}},{"rowIdx":742,"cells":{"code":{"kind":"string","value":"public class VigenereCipher {\n public static void main(String[] args) {\n String key = \"VIGENERECIPHER\";\n String ori = \"Beware the Jabberwock, my son! The jaws that bite, the claws that catch!\";\n String enc = encrypt(ori, key);\n System.out.println(enc);\n System.out.println(decrypt(enc, key));\n }\n\n static String encrypt(String text, final String key) {\n String res = \"\";\n text = text.toUpperCase();\n for (int i = 0, j = 0; i < text.length(); i++) {\n char c = text.charAt(i);\n if (c < 'A' || c > 'Z') continue;\n res += (char)((c + key.charAt(j) - 2 * 'A') % 26 + 'A');\n j = ++j % key.length();\n }\n return res;\n }\n\n static String decrypt(String text, final String key) {\n String res = \"\";\n text = text.toUpperCase();\n for (int i = 0, j = 0; i < text.length(); i++) {\n char c = text.charAt(i);\n if (c < 'A' || c > 'Z') continue;\n res += (char)((c - key.charAt(j) + 26) % 26 + 'A');\n j = ++j % key.length();\n }\n return res;\n }\n}"},"label":{"kind":"class label","value":"61","name":"Vigenère cipher"},"domain_label":{"kind":"class label","value":"9","name":"java"},"index":{"kind":"string","value":"6tv3z"}}},{"rowIdx":743,"cells":{"code":{"kind":"string","value":"use warnings;\nuse strict;\nuse utf8;\nuse open OUT => ':utf8', ':std';\n\nsub parse {\n my ($tree) = shift;\n if (my ($root, $children) = $tree =~ /^(.+?)\\((.*)\\)$/) {\n\n my $depth = 0;\n for my $pos (0 .. length($children) - 1) {\n my $char = \\substr $children, $pos, 1;\n if (0 == $depth and ',' eq $$char) {\n $$char = \"\\x0\";\n } elsif ('(' eq $$char) {\n $depth++;\n } elsif (')' eq $$char) {\n $depth--;\n }\n }\n return($root, [map parse($_), split /\\x0/, $children]);\n\n } else { \n return $tree;\n }\n}\n\nsub output {\n my ($parsed, $prefix) = @_;\n my $is_root = not defined $prefix;\n $prefix //= ' ';\n while (my $member = shift @$parsed) {\n my $last = !@$parsed || (1 == @$parsed and ref $parsed->[0]);\n unless ($is_root) {\n substr $prefix, -3, 1, ' ';\n substr($prefix, -4, 1) =~ s///;\n substr $prefix, -2, 1, ref $member ? ' ' : '' if $last;\n }\n\n if (ref $member) {\n output($member, $prefix . '');\n } else {\n print $prefix, $member, \"\\n\";\n }\n }\n}\n\nmy $tree = 'a(b0(c1,c2(d(ef,gh)),c3(i1,i2,i3(jj),i4(kk,m))),b1(C1,C2(D1(E),D2,D3),C3))';\nmy $parsed = [parse($tree)];\noutput($parsed);"},"label":{"kind":"class label","value":"57","name":"Visualize a tree"},"domain_label":{"kind":"class label","value":"2","name":"perl"},"index":{"kind":"string","value":"tnufg"}}},{"rowIdx":744,"cells":{"code":{"kind":"string","value":"distcheck <- function(fn, repetitions=1e4, delta=3)\n{\n if(is.character(fn))\n {\n fn <- get(fn)\n }\n if(!is.function(fn))\n {\n stop(\"fn is not a function\")\n }\n samp <- fn(n=repetitions) \n counts <- table(samp)\n expected <- repetitions/length(counts)\n lbound <- expected * (1 - 0.01*delta)\n ubound <- expected * (1 + 0.01*delta)\n status <- ifelse(counts < lbound, \"under\", \n ifelse(counts > ubound, \"over\", \"okay\"))\n data.frame(value=names(counts), counts=as.vector(counts), status=status) \n}\ndistcheck(dice7.vec)"},"label":{"kind":"class label","value":"59","name":"Verify distribution uniformity/Naive"},"domain_label":{"kind":"class label","value":"13","name":"r"},"index":{"kind":"string","value":"cy795"}}},{"rowIdx":745,"cells":{"code":{"kind":"string","value":"dset1=c(199809,200665,199607,200270,199649)\ndset2=c(522573,244456,139979,71531,21461)\n\nchi2IsUniform<-function(dataset,significance=0.05){\n chi2IsUniform=(chisq.test(dataset)$p.value>significance)\n}\n\nfor (ds in list(dset1,dset2)){\n print(c(\"Data set:\",ds))\n print(chisq.test(ds))\n print(paste(\"uniform?\",chi2IsUniform(ds)))\n}"},"label":{"kind":"class label","value":"62","name":"Verify distribution uniformity/Chi-squared test"},"domain_label":{"kind":"class label","value":"13","name":"r"},"index":{"kind":"string","value":"4vk5y"}}},{"rowIdx":746,"cells":{"code":{"kind":"null"},"label":{"kind":"class label","value":"61","name":"Vigenère cipher"},"domain_label":{"kind":"class label","value":"10","name":"javascript"},"index":{"kind":"string","value":"lmrcf"}}},{"rowIdx":747,"cells":{"code":{"kind":"string","value":"public class VLQCode\n{\n public static byte[] encode(long n)\n {\n int numRelevantBits = 64 - Long.numberOfLeadingZeros(n);\n int numBytes = (numRelevantBits + 6) / 7;\n if (numBytes == 0)\n numBytes = 1;\n byte[] output = new byte[numBytes];\n for (int i = numBytes - 1; i >= 0; i--)\n {\n int curByte = (int)(n & 0x7F);\n if (i != (numBytes - 1))\n curByte |= 0x80;\n output[i] = (byte)curByte;\n n >>>= 7;\n }\n return output;\n }\n\n public static long decode(byte[] b)\n {\n long n = 0;\n for (int i = 0; i < b.length; i++)\n {\n int curByte = b[i] & 0xFF;\n n = (n << 7) | (curByte & 0x7F);\n if ((curByte & 0x80) == 0)\n break;\n }\n return n;\n }\n\n public static String byteArrayToString(byte[] b)\n {\n StringBuilder sb = new StringBuilder();\n for (int i = 0; i < b.length; i++)\n {\n if (i > 0)\n sb.append(\", \");\n String s = Integer.toHexString(b[i] & 0xFF);\n if (s.length() < 2)\n s = \"0\" + s;\n sb.append(s);\n }\n return sb.toString();\n }\n\n public static void main(String[] args)\n {\n long[] testNumbers = { 2097152, 2097151, 1, 127, 128, 589723405834L };\n for (long n : testNumbers)\n {\n byte[] encoded = encode(n);\n long decoded = decode(encoded);\n System.out.println(\"Original input=\" + n + \", encoded = [\" + byteArrayToString(encoded) + \"], decoded=\" + decoded + \", \" + ((n == decoded) ? \"OK\" : \"FAIL\"));\n }\n }\n}"},"label":{"kind":"class label","value":"64","name":"Variable-length quantity"},"domain_label":{"kind":"class label","value":"9","name":"java"},"index":{"kind":"string","value":"swiq0"}}},{"rowIdx":748,"cells":{"code":{"kind":"string","value":"numeric digits 100 \n\n\n\n\nz = 12345678901111111112222222222333333333344444444445555555555.66\nn =-12345678901111111112222222222333333333344444444445555555555.66"},"label":{"kind":"class label","value":"65","name":"Variable size/Set"},"domain_label":{"kind":"class label","value":"3","name":"python"},"index":{"kind":"string","value":"bjakr"}}},{"rowIdx":749,"cells":{"code":{"kind":"string","value":"println(s\"A Byte variable has a range of: ${Byte.MinValue} to ${Byte.MaxValue}\")\nprintln(s\"A Short variable has a range of: ${Short.MinValue} to ${Short.MaxValue}\")\nprintln(s\"An Int variable has a range of: ${Int.MinValue} to ${Int.MaxValue}\")\nprintln(s\"A Long variable has a range of: ${Long.MinValue} to ${Long.MaxValue}\")\nprintln(s\"A Float variable has a range of: ${Float.MinValue} to ${Float.MaxValue}\")\nprintln(s\"A Double variable has a range of: ${Double.MinValue} to ${Double.MaxValue}\")"},"label":{"kind":"class label","value":"65","name":"Variable size/Set"},"domain_label":{"kind":"class label","value":"16","name":"scala"},"index":{"kind":"string","value":"xa0wg"}}},{"rowIdx":750,"cells":{"code":{"kind":"string","value":"use File::Find qw(find);\nmy $dir = '.';\nmy $pattern = 'foo';\nmy $callback = sub { print $File::Find::name, \"\\n\" if /$pattern/ };\nfind $callback, $dir;"},"label":{"kind":"class label","value":"58","name":"Walk a directory/Recursively"},"domain_label":{"kind":"class label","value":"2","name":"perl"},"index":{"kind":"string","value":"gue4e"}}},{"rowIdx":751,"cells":{"code":{"kind":"string","value":"def water_collected(tower):\n N = len(tower)\n highest_left = [0] + [max(tower[:n]) for n in range(1,N)]\n highest_right = [max(tower[n:N]) for n in range(1,N)] + [0]\n water_level = [max(min(highest_left[n], highest_right[n]) - tower[n], 0)\n for n in range(N)]\n print(, highest_left)\n print(, highest_right)\n print(, water_level)\n print(, tower)\n print(, sum(water_level))\n print()\n return sum(water_level)\n\ntowers = [[1, 5, 3, 7, 2],\n [5, 3, 7, 2, 6, 4, 5, 9, 1, 2],\n [2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1],\n [5, 5, 5, 5],\n [5, 6, 7, 8],\n [8, 7, 7, 6],\n [6, 7, 10, 7, 6]]\n\n[water_collected(tower) for tower in towers]"},"label":{"kind":"class label","value":"56","name":"Water collected between towers"},"domain_label":{"kind":"class label","value":"3","name":"python"},"index":{"kind":"string","value":"swyq9"}}},{"rowIdx":752,"cells":{"code":{"kind":"string","value":"def distcheck(n, delta=1)\n unless block_given?\n raise ArgumentError, \n end\n\n h = Hash.new(0)\n n.times {h[ yield ] += 1}\n\n target = 1.0 * n / h.length\n h.each do |key, value| \n if (value - target).abs > 0.01 * delta * n\n raise StandardError,\n \n end\n end\n\n puts h.sort.map{|k, v| }\nend\n\nif __FILE__ == $0\n begin\n distcheck(100_000) {rand(10)}\n distcheck(100_000) {rand > 0.95} \n rescue StandardError => e\n p e\n end\nend"},"label":{"kind":"class label","value":"59","name":"Verify distribution uniformity/Naive"},"domain_label":{"kind":"class label","value":"14","name":"ruby"},"index":{"kind":"string","value":"4v15p"}}},{"rowIdx":753,"cells":{"code":{"kind":"string","value":"const RADIX = 7;\nconst MASK = 2**RADIX - 1;\n\nconst octetify = (n)=> {\n\tif (n >= 2147483648) {\n\t\tthrow new RangeError(\"Variable Length Quantity not supported for numbers >= 2147483648\");\n\t}\n\tconst octets = [];\n\tfor (let i = n; i != 0; i >>>= RADIX) {\n\t\toctets.push((((i & MASK) + (octets.empty ? 0 : (MASK + 1)))));\n\t}\n\toctets.reverse();\n\treturn octets;\n};\n\nconst deoctetify = (octets)=>\n\toctets.reduce((n, octet)=>\n\t\t(n << RADIX) + (octet & MASK)\n\t, 0);"},"label":{"kind":"class label","value":"64","name":"Variable-length quantity"},"domain_label":{"kind":"class label","value":"10","name":"javascript"},"index":{"kind":"string","value":"n8ziy"}}},{"rowIdx":754,"cells":{"code":{"kind":"string","value":"void varstrings(int count, ...) \n{\n va_list args;\n va_start(args, count);\n while (count--)\n puts(va_arg(args, const char *));\n va_end(args);\n}\n\nvarstrings(5, , , , , );"},"label":{"kind":"class label","value":"67","name":"Variadic function"},"domain_label":{"kind":"class label","value":"5","name":"c"},"index":{"kind":"string","value":"sw0q5"}}},{"rowIdx":755,"cells":{"code":{"kind":"string","value":"printf(, sizeof(int));"},"label":{"kind":"class label","value":"68","name":"Variable size/Get"},"domain_label":{"kind":"class label","value":"5","name":"c"},"index":{"kind":"string","value":"oso80"}}},{"rowIdx":756,"cells":{"code":{"kind":"string","value":"package main\n\nimport \"fmt\"\n\ntype vector []float64\n\nfunc (v vector) add(v2 vector) vector {\n r := make([]float64, len(v))\n for i, vi := range v {\n r[i] = vi + v2[i]\n }\n return r\n}\n\nfunc (v vector) sub(v2 vector) vector {\n r := make([]float64, len(v))\n for i, vi := range v {\n r[i] = vi - v2[i]\n }\n return r\n}\n\nfunc (v vector) scalarMul(s float64) vector {\n r := make([]float64, len(v))\n for i, vi := range v {\n r[i] = vi * s\n }\n return r\n}\n\nfunc (v vector) scalarDiv(s float64) vector {\n r := make([]float64, len(v))\n for i, vi := range v {\n r[i] = vi / s\n }\n return r\n}\n\nfunc main() {\n v1 := vector{5, 7}\n v2 := vector{2, 3}\n fmt.Println(v1.add(v2))\n fmt.Println(v1.sub(v2))\n fmt.Println(v1.scalarMul(11))\n fmt.Println(v1.scalarDiv(2))\n}"},"label":{"kind":"class label","value":"66","name":"Vector"},"domain_label":{"kind":"class label","value":"0","name":"go"},"index":{"kind":"string","value":"52gul"}}},{"rowIdx":757,"cells":{"code":{"kind":"string","value":"function findFiles($dir = '.', $pattern = '/./'){\n $prefix = $dir . '/';\n $dir = dir($dir);\n while (false !== ($file = $dir->read())){\n if ($file === '.' || $file === '..') continue;\n $file = $prefix . $file;\n if (is_dir($file)) findFiles($file, $pattern);\n if (preg_match($pattern, $file)){\n echo $file . ;\n }\n }\n}\nfindFiles('./foo', '/\\.bar$/');"},"label":{"kind":"class label","value":"58","name":"Walk a directory/Recursively"},"domain_label":{"kind":"class label","value":"12","name":"php"},"index":{"kind":"string","value":"n8cig"}}},{"rowIdx":758,"cells":{"code":{"kind":"string","value":"object DistrubCheck1 extends App {\n\n private def distCheck(f: () => Int, nRepeats: Int, delta: Double): Unit = {\n val counts = scala.collection.mutable.Map[Int, Int]()\n\n for (_ <- 0 until nRepeats)\n counts.updateWith(f()) {\n case Some(count) => Some(count + 1)\n case None => Some(1)\n }\n\n val target: Double = nRepeats.toDouble / counts.size\n val deltaCount: Int = (delta / 100.0 * target).toInt\n counts.foreach {\n case (k, v) =>\n if (math.abs(target - v) >= deltaCount)\n println(f\"distribution potentially skewed for $k%s: $v%d\")\n }\n counts.toIndexedSeq.foreach(entry => println(f\"${entry._1}%d ${entry._2}%d\"))\n }\n\n distCheck(() => 1 + util.Random.nextInt(5), 1_000_000, 1)\n\n}"},"label":{"kind":"class label","value":"59","name":"Verify distribution uniformity/Naive"},"domain_label":{"kind":"class label","value":"16","name":"scala"},"index":{"kind":"string","value":"jgx7i"}}},{"rowIdx":759,"cells":{"code":{"kind":"string","value":"int main() {\n int i, gprev = 0;\n int s[7] = {1, 2, 2, 3, 4, 4, 5};\n\n \n for (i = 0; i < 7; ++i) {\n\n int curr = s[i];\n int prev = 0;\n\n if (i > 0 && curr == prev) printf(, i);\n prev = curr;\n }\n\n \n for (i = 0; i < 7; ++i) {\n int curr = s[i];\n if (i > 0 && curr == gprev) printf(, i);\n gprev = curr;\n }\n\n return 0;\n}"},"label":{"kind":"class label","value":"69","name":"Variable declaration reset"},"domain_label":{"kind":"class label","value":"5","name":"c"},"index":{"kind":"string","value":"1hbpj"}}},{"rowIdx":760,"cells":{"code":{"kind":"null"},"label":{"kind":"class label","value":"64","name":"Variable-length quantity"},"domain_label":{"kind":"class label","value":"11","name":"kotlin"},"index":{"kind":"string","value":"abq13"}}},{"rowIdx":761,"cells":{"code":{"kind":"string","value":"import groovy.transform.EqualsAndHashCode\n\n@EqualsAndHashCode\nclass Vector {\n private List elements\n Vector(List e ) {\n if (!e) throw new IllegalArgumentException(\"A Vector must have at least one element.\")\n if (!e.every { it instanceof Number }) throw new IllegalArgumentException(\"Every element must be a number.\")\n elements = [] + e\n }\n Vector(Number... e) { this(e as List) }\n\n def order() { elements.size() }\n def norm2() { elements.sum { it ** 2 } ** 0.5 }\n\n def plus(Vector that) {\n if (this.order() != that.order()) throw new IllegalArgumentException(\"Vectors must be conformable for addition.\")\n [this.elements,that.elements].transpose()*.sum() as Vector\n }\n def minus(Vector that) { this + (-that) }\n def multiply(Number that) { this.elements.collect { it * that } as Vector }\n def div(Number that) { this * (1/that) }\n def negative() { this * -1 }\n\n String toString() { \"(${elements.join(',')})\" }\n}\n\nclass VectorCategory {\n static Vector plus (Number a, Vector b) { b + a }\n static Vector minus (Number a, Vector b) { -b + a }\n static Vector multiply (Number a, Vector b) { b * a }\n}"},"label":{"kind":"class label","value":"66","name":"Vector"},"domain_label":{"kind":"class label","value":"7","name":"groovy"},"index":{"kind":"string","value":"cy29i"}}},{"rowIdx":762,"cells":{"code":{"kind":"string","value":"def gammaInc_Q(a, x)\n a1, a2 = a-1, a-2\n f0 = lambda {|t| t**a1 * Math.exp(-t)}\n df0 = lambda {|t| (a1-t) * t**a2 * Math.exp(-t)}\n\n y = a1\n y += 0.3 while f0[y]*(x-y) > 2.0e-8 and y < x\n y = x if y > x\n\n h = 3.0e-4\n n = (y/h).to_i\n h = y/n\n hh = 0.5 * h\n sum = 0\n (n-1).step(0, -1) do |j|\n t = h * j\n sum += f0[t] + hh * df0[t]\n end\n h * sum / gamma_spounge(a)\nend\n\nA = 12\nk1_factrl = 1.0\ncoef = [Math.sqrt(2.0*Math::PI)]\nCOEF = (1...A).each_with_object(coef) do |k,c|\n c << Math.exp(A-k) * (A-k)**(k-0.5) / k1_factrl\n k1_factrl *= -k\nend\n\ndef gamma_spounge(z)\n accm = (1...A).inject(COEF[0]){|res,k| res += COEF[k] / (z+k)}\n accm * Math.exp(-(z+A)) * (z+A)**(z+0.5) / z\nend\n\ndef chi2UniformDistance(dataSet)\n expected = dataSet.inject(:+).to_f / dataSet.size\n dataSet.map{|d|(d-expected)**2}.inject(:+) / expected\nend\n\ndef chi2Probability(dof, distance)\n 1.0 - gammaInc_Q(0.5*dof, 0.5*distance)\nend\n\ndef chi2IsUniform(dataSet, significance=0.05)\n dof = dataSet.size - 1\n dist = chi2UniformDistance(dataSet)\n chi2Probability(dof, dist) > significance\nend\n\ndsets = [ [ 199809, 200665, 199607, 200270, 199649 ],\n [ 522573, 244456, 139979, 71531, 21461 ] ]\n\nfor ds in dsets\n puts \n dof = ds.size - 1\n puts % dof\n distance = chi2UniformDistance(ds)\n puts % distance\n puts % chi2Probability(dof, distance)\n puts % (chi2IsUniform(ds)? : )\nend"},"label":{"kind":"class label","value":"62","name":"Verify distribution uniformity/Chi-squared test"},"domain_label":{"kind":"class label","value":"14","name":"ruby"},"index":{"kind":"string","value":"k7whg"}}},{"rowIdx":763,"cells":{"code":{"kind":"null"},"label":{"kind":"class label","value":"61","name":"Vigenère cipher"},"domain_label":{"kind":"class label","value":"11","name":"kotlin"},"index":{"kind":"string","value":"domnz"}}},{"rowIdx":764,"cells":{"code":{"kind":"string","value":"Python 3.2.3 (default, May 3 2012, 15:54:42) \n[GCC 4.6.3] on linux2\nType , or for more information.\n>>> help('pprint.pprint')\nHelp on function pprint in pprint:\n\npprint.pprint = pprint(object, stream=None, indent=1, width=80, depth=None)\n Pretty-print a Python object to a stream [default is sys.stdout].\n\n>>> from pprint import pprint\n>>> for tree in [ (1, 2, 3, 4, 5, 6, 7, 8),\n\t (1, (( 2, 3 ), (4, (5, ((6, 7), 8))))),\n\t ((((1, 2), 3), 4), 5, 6, 7, 8) ]:\n\tprint(% (tree, ))\n\tpprint(tree, indent=1, width=1)\n\n\n\nTree (1, 2, 3, 4, 5, 6, 7, 8) can be pprint'd as:\n(1,\n 2,\n 3,\n 4,\n 5,\n 6,\n 7,\n 8)\n\nTree (1, ((2, 3), (4, (5, ((6, 7), 8))))) can be pprint'd as:\n(1,\n ((2,\n 3),\n (4,\n (5,\n ((6,\n 7),\n 8)))))\n\nTree ((((1, 2), 3), 4), 5, 6, 7, 8) can be pprint'd as:\n((((1,\n 2),\n 3),\n 4),\n 5,\n 6,\n 7,\n 8)\n>>>"},"label":{"kind":"class label","value":"57","name":"Visualize a tree"},"domain_label":{"kind":"class label","value":"3","name":"python"},"index":{"kind":"string","value":"zd5tt"}}},{"rowIdx":765,"cells":{"code":{"kind":"string","value":"(defn foo [& args]\n (doseq [a args]\n (println a)))\n\n(foo :bar :baz :quux)\n(apply foo [:bar :baz :quux])"},"label":{"kind":"class label","value":"67","name":"Variadic function"},"domain_label":{"kind":"class label","value":"6","name":"clojure"},"index":{"kind":"string","value":"n8dik"}}},{"rowIdx":766,"cells":{"code":{"kind":"string","value":"add (u,v) (x,y) = (u+x,v+y)\nminus (u,v) (x,y) = (u-x,v-y)\nmultByScalar k (x,y) = (k*x,k*y)\ndivByScalar (x,y) k = (x/k,y/k)\n\nmain = do\n let vecA = (3.0,8.0) \n let (r,theta) = (3,pi/12) :: (Double,Double)\n let vecB = (r*(cos theta),r*(sin theta)) \n putStrLn $ \"vecA = \" ++ (show vecA)\n putStrLn $ \"vecB = \" ++ (show vecB)\n putStrLn $ \"vecA + vecB = \" ++ (show.add vecA $ vecB)\n putStrLn $ \"vecA - vecB = \" ++ (show.minus vecA $ vecB)\n putStrLn $ \"2 * vecB = \" ++ (show.multByScalar 2 $ vecB)\n putStrLn $ \"vecA / 3 = \" ++ (show.divByScalar vecA $ 3)"},"label":{"kind":"class label","value":"66","name":"Vector"},"domain_label":{"kind":"class label","value":"8","name":"haskell"},"index":{"kind":"string","value":"xasw4"}}},{"rowIdx":767,"cells":{"code":{"kind":"string","value":"use statrs::function::gamma::gamma_li;\n\nfn chi_distance(dataset: &[u32]) -> f64 {\n let expected = f64::from(dataset.iter().sum::()) / dataset.len() as f64;\n dataset\n .iter()\n .fold(0., |acc, &elt| acc + (elt as f64 - expected).powf(2.))\n / expected\n}\n\nfn chi2_probability(dof: f64, distance: f64) -> f64 {\n 1. - gamma_li(dof * 0.5, distance * 0.5)\n}\n\nfn chi2_uniform(dataset: &[u32], significance: f64) -> bool {\n let d = chi_distance(&dataset);\n chi2_probability(dataset.len() as f64 - 1., d) > significance\n}\n\nfn main() {\n let dsets = vec![\n vec![199809, 200665, 199607, 200270, 199649],\n vec![522573, 244456, 139979, 71531, 21461],\n ];\n\n for ds in dsets {\n println!(\"Data set: {:?}\", ds);\n let d = chi_distance(&ds);\n print!(\"Distance: {:.6} \", d);\n print!(\n \"Chi2 probability: {:.6} \",\n chi2_probability(ds.len() as f64 - 1., d)\n );\n print!(\"Uniform? {}\\n\", chi2_uniform(&ds, 0.05));\n }\n}"},"label":{"kind":"class label","value":"62","name":"Verify distribution uniformity/Chi-squared test"},"domain_label":{"kind":"class label","value":"15","name":"rust"},"index":{"kind":"string","value":"bjxkx"}}},{"rowIdx":768,"cells":{"code":{"kind":"string","value":"import org.apache.commons.math3.special.Gamma.regularizedGammaQ\n\nobject ChiSquare extends App {\n private val dataSets: Seq[Seq[Double]] =\n Seq(\n Seq(199809, 200665, 199607, 200270, 199649),\n Seq(522573, 244456, 139979, 71531, 21461)\n )\n\n private def 2IsUniform(data: Seq[Double], significance: Double) =\n 2Prob(data.size - 1.0, 2Dist(data)) > significance\n\n private def 2Dist(data: Seq[Double]) = {\n val avg = data.sum / data.size\n\n data.reduce((a, b) => a + math.pow(b - avg, 2)) / avg\n }\n\n private def 2Prob(dof: Double, distance: Double) =\n regularizedGammaQ(dof / 2, distance / 2)\n\n printf(\"%4s%10s %12s%8s %s%n\",\n \"d.f.\", \"distance\", \"probability\", \"Uniform?\", \"dataset\")\n dataSets.foreach { ds =>\n val (dist, dof) = (2Dist(ds), ds.size - 1)\n\n printf(\"%4d%11.3f %13.8f %5s %6s%n\",\n dof, dist, 2Prob(dof.toDouble, dist), if (2IsUniform(ds, 0.05)) \"YES\" else \"NO\", ds.mkString(\", \"))\n }\n}"},"label":{"kind":"class label","value":"62","name":"Verify distribution uniformity/Chi-squared test"},"domain_label":{"kind":"class label","value":"16","name":"scala"},"index":{"kind":"string","value":"ab01n"}}},{"rowIdx":769,"cells":{"code":{"kind":"string","value":"package main\n\nimport \"fmt\"\n\nfunc main() {\n s := []int{1, 2, 2, 3, 4, 4, 5}"},"label":{"kind":"class label","value":"69","name":"Variable declaration reset"},"domain_label":{"kind":"class label","value":"0","name":"go"},"index":{"kind":"string","value":"yt364"}}},{"rowIdx":770,"cells":{"code":{"kind":"string","value":"import java.util.Locale;\n\npublic class Test {\n\n public static void main(String[] args) {\n System.out.println(new Vec2(5, 7).add(new Vec2(2, 3)));\n System.out.println(new Vec2(5, 7).sub(new Vec2(2, 3)));\n System.out.println(new Vec2(5, 7).mult(11));\n System.out.println(new Vec2(5, 7).div(2));\n }\n}\n\nclass Vec2 {\n final double x, y;\n\n Vec2(double x, double y) {\n this.x = x;\n this.y = y;\n }\n\n Vec2 add(Vec2 v) {\n return new Vec2(x + v.x, y + v.y);\n }\n\n Vec2 sub(Vec2 v) {\n return new Vec2(x - v.x, y - v.y);\n }\n\n Vec2 div(double val) {\n return new Vec2(x / val, y / val);\n }\n\n Vec2 mult(double val) {\n return new Vec2(x * val, y * val);\n }\n\n @Override\n public String toString() {\n return String.format(Locale.US, \"[%s,%s]\", x, y);\n }\n}"},"label":{"kind":"class label","value":"66","name":"Vector"},"domain_label":{"kind":"class label","value":"9","name":"java"},"index":{"kind":"string","value":"bj1k3"}}},{"rowIdx":771,"cells":{"code":{"kind":"string","value":"def a(array)\nn=array.length\nleft={}\nright={}\nleft[0]=array[0]\ni=1\nloop do\n break if i >=n\nleft[i]=[left[i-1],array[i]].max\n i += 1 \nend\nright[n-1]=array[n-1]\ni=n-2\nloop do \nbreak if i<0\n right[i]=[right[i+1],array[i]].max\ni-=1\nend\ni=0\nwater=0\nloop do\nbreak if i>=n\nwater+=[left[i],right[i]].min-array[i]\ni+=1\nend\nputs water\nend\n\na([ 5, 3, 7, 2, 6, 4, 5, 9, 1, 2 ])\na([ 2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1 ])\na([ 5, 5, 5, 5 ])\na([ 5, 6, 7, 8 ])\na([ 8, 7, 7, 6 ])\na([ 6, 7, 10, 7, 6 ])\nreturn"},"label":{"kind":"class label","value":"56","name":"Water collected between towers"},"domain_label":{"kind":"class label","value":"14","name":"ruby"},"index":{"kind":"string","value":"8q901"}}},{"rowIdx":772,"cells":{"code":{"kind":"string","value":"public class VariableDeclarationReset {\n public static void main(String[] args) {\n int[] s = {1, 2, 2, 3, 4, 4, 5};"},"label":{"kind":"class label","value":"69","name":"Variable declaration reset"},"domain_label":{"kind":"class label","value":"9","name":"java"},"index":{"kind":"string","value":"5lvuf"}}},{"rowIdx":773,"cells":{"code":{"kind":"string","value":"\n\n \n \n \n variable declaration reset\n \n \n \n \n"},"label":{"kind":"class label","value":"69","name":"Variable declaration reset"},"domain_label":{"kind":"class label","value":"10","name":"javascript"},"index":{"kind":"string","value":"j4r7n"}}},{"rowIdx":774,"cells":{"code":{"kind":"string","value":"typedef uint64_t xint;\ntypedef unsigned long long ull;\n\nxint tens[20];\n\ninline xint max(xint a, xint b) { return a > b ? a : b; }\ninline xint min(xint a, xint b) { return a < b ? a : b; }\ninline int ndigits(xint x)\n{\n\tint n = 0;\n\twhile (x) n++, x /= 10;\n\treturn n;\n}\n\ninline xint dtally(xint x)\n{\n\txint t = 0;\n\twhile (x) t += 1<<((x%10) * 6), x /= 10;\n\n\treturn t;\n}\n\nint fangs(xint x, xint *f)\n{\n\tint n = 0;\n\tint nd = ndigits(x);\n\tif (nd & 1) return 0;\n\tnd /= 2;\n\n\txint lo, hi;\n\tlo = max(tens[nd-1], (x + tens[nd] - 2)/ (tens[nd] - 1));\n\thi = min(x / lo, sqrt(x));\n\n\txint a, b, t = dtally(x);\n\tfor (a = lo; a <= hi; a++) {\n\t\tb = x / a;\n\t\tif (a * b == x && ((a%10) || (b%10)) && t == dtally(a) + dtally(b))\n\t\t\tf[n++] = a;\n\t}\n\n\treturn n;\n}\n\nvoid show_fangs(xint x, xint *f, xint cnt)\n{\n\tprintf(, (ull)x);\n\tint i;\n\tfor (i = 0; i < cnt; i++)\n\t\tprintf(, (ull)f[i], (ull)(x / f[i]));\n\tputchar('\\n');\n}\n\nint main(void)\n{\n\tint i, j, n;\n\txint x, f[16], bigs[] = {16758243290880ULL, 24959017348650ULL, 14593825548650ULL, 0};\n\n\ttens[0] = 1;\n\tfor (i = 1; i < 20; i++)\n\t\ttens[i] = tens[i-1] * 10;\n\n\tfor (x = 1, n = 0; n < 25; x++) {\n\t\tif (!(j = fangs(x, f))) continue;\n\t\tprintf(, ++n);\n\t\tshow_fangs(x, f, j);\n\t}\n\n\tputchar('\\n');\n\tfor (i = 0; bigs[i]; i++) {\n\t\tif ((j = fangs(bigs[i], f)))\n\t\t\tshow_fangs(bigs[i], f, j);\n\t\telse\n\t\t\tprintf(, (ull)bigs[i]);\n\t}\n\n\treturn 0;\n}"},"label":{"kind":"class label","value":"70","name":"Vampire number"},"domain_label":{"kind":"class label","value":"5","name":"c"},"index":{"kind":"string","value":"tinf4"}}},{"rowIdx":775,"cells":{"code":{"kind":"string","value":"use warnings;\nuse strict;\n\nfor my $testcase (\n 0, 0xa, 123, 254, 255, 256,\n 257, 65534, 65535, 65536, 65537, 0x1fffff,\n 0x200000\n )\n{\n my @vlq = vlq_encode($testcase);\n printf \"%8s%12s%8s\\n\", $testcase, ( join ':', @vlq ), vlq_decode(@vlq);\n}\n\nsub vlq_encode {\n my @vlq;\n my $binary = sprintf \"%s%b\", 0 x 7, shift;\n $binary =~ s/(.{7})$//;\n @vlq = ( unpack 'H2', ( pack 'B8', '0' . $1 ) );\n while ( 0 + $binary ) {\n $binary =~ s/(.{7})$//;\n unshift @vlq, ( unpack 'H2', pack 'B8', '1' . $1 );\n }\n return @vlq;\n}\n\nsub vlq_decode {\n my $num;\n $num .= sprintf \"%07b\", hex(shift @_) & 0x7f while @_;\n return oct '0b' . $num;\n}"},"label":{"kind":"class label","value":"64","name":"Variable-length quantity"},"domain_label":{"kind":"class label","value":"2","name":"perl"},"index":{"kind":"string","value":"96vmn"}}},{"rowIdx":776,"cells":{"code":{"kind":"string","value":"function Encrypt( _msg, _key ) \n local msg = { _msg:upper():byte( 1, -1 ) }\n local key = { _key:upper():byte( 1, -1 ) } \n local enc = {}\n\n local j, k = 1, 1\n for i = 1, #msg do \n if msg[i] >= string.byte('A') and msg[i] <= string.byte('Z') then\n enc[k] = ( msg[i] + key[j] - 2*string.byte('A') ) % 26 + string.byte('A')\n\n k = k + 1\n if j == #key then j = 1 else j = j + 1 end\n end\n end\n\n return string.char( unpack(enc) )\nend\n\nfunction Decrypt( _msg, _key )\n local msg = { _msg:byte( 1, -1 ) }\n local key = { _key:upper():byte( 1, -1 ) } \n local dec = {}\n\n local j = 1\n for i = 1, #msg do \n dec[i] = ( msg[i] - key[j] + 26 ) % 26 + string.byte('A')\n\n if j == #key then j = 1 else j = j + 1 end\n end \n\n return string.char( unpack(dec) )\nend\n\n\noriginal = \"Beware the Jabberwock, my son! The jaws that bite, the claws that catch!\"\nkey = \"VIGENERECIPHER\";\n\nencrypted = Encrypt( original, key )\ndecrypted = Decrypt( encrypted, key )\n\nprint( encrypted )\nprint( decrypted )"},"label":{"kind":"class label","value":"61","name":"Vigenère cipher"},"domain_label":{"kind":"class label","value":"1","name":"lua"},"index":{"kind":"string","value":"fi9dp"}}},{"rowIdx":777,"cells":{"code":{"kind":"string","value":"root = BinaryTreeNode.from_array [1, [2, [4, 7], [5]], [3, [6, [8], [9]]]]"},"label":{"kind":"class label","value":"57","name":"Visualize a tree"},"domain_label":{"kind":"class label","value":"14","name":"ruby"},"index":{"kind":"string","value":"6tg3t"}}},{"rowIdx":778,"cells":{"code":{"kind":"string","value":"extern crate rustc_serialize;\nextern crate term_painter;\n\nuse rustc_serialize::json;\nuse std::fmt::{Debug, Display, Formatter, Result};\nuse term_painter::ToStyle;\nuse term_painter::Color::*;\n\ntype NodePtr = Option;\n\n#[derive(Debug, PartialEq, Clone, Copy)]\nenum Side {\n Left,\n Right,\n Up,\n}\n\n#[derive(Debug, PartialEq, Clone, Copy)]\nenum DisplayElement {\n TrunkSpace,\n SpaceLeft,\n SpaceRight,\n SpaceSpace,\n Root,\n}\n\nimpl DisplayElement {\n fn string(&self) -> String {\n match *self {\n DisplayElement::TrunkSpace => \" \".to_string(),\n DisplayElement::SpaceRight => \" \".to_string(),\n DisplayElement::SpaceLeft => \" \".to_string(),\n DisplayElement::SpaceSpace => \" \".to_string(),\n DisplayElement::Root => \"\".to_string(),\n }\n }\n}\n\n#[derive(Debug, Clone, Copy, RustcDecodable, RustcEncodable)]\nstruct Node {\n key: K,\n value: V,\n left: NodePtr,\n right: NodePtr,\n up: NodePtr,\n}\n\nimpl Node {\n pub fn get_ptr(&self, side: Side) -> NodePtr {\n match side {\n Side::Up => self.up,\n Side::Left => self.left,\n _ => self.right,\n }\n }\n}\n\n#[derive(Debug, RustcDecodable, RustcEncodable)]\nstruct Tree {\n root: NodePtr,\n store: Vec>,\n}\n\nimpl Tree {\n pub fn get_node(&self, np: NodePtr) -> Node {\n assert!(np.is_some());\n self.store[np.unwrap()]\n }\n\n pub fn get_pointer(&self, np: NodePtr, side: Side) -> NodePtr {\n assert!(np.is_some());\n self.store[np.unwrap()].get_ptr(side)\n }"},"label":{"kind":"class label","value":"57","name":"Visualize a tree"},"domain_label":{"kind":"class label","value":"15","name":"rust"},"index":{"kind":"string","value":"yzr68"}}},{"rowIdx":779,"cells":{"code":{"kind":"string","value":"use std::cmp::min;\n\nfn getfill(pattern: &[usize]) -> usize {\n let mut total = 0;\n for (idx, val) in pattern.iter().enumerate() {\n let l_peak = pattern[..idx].iter().max();\n let r_peak = pattern[idx + 1..].iter().max();\n if l_peak.is_some() && r_peak.is_some() {\n let peak = min(l_peak.unwrap(), r_peak.unwrap());\n if peak > val {\n total += peak - val;\n }\n }\n }\n total\n}\n\nfn main() {\n let patterns = vec![\n vec![1, 5, 3, 7, 2],\n vec![5, 3, 7, 2, 6, 4, 5, 9, 1, 2],\n vec![2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1],\n vec![5, 5, 5, 5],\n vec![5, 6, 7, 8],\n vec![8, 7, 7, 6],\n vec![6, 7, 10, 7, 6],\n ];\n\n for pattern in patterns {\n println!(\"pattern: {:?}, fill: {}\", &pattern, getfill(&pattern));\n }\n}"},"label":{"kind":"class label","value":"56","name":"Water collected between towers"},"domain_label":{"kind":"class label","value":"15","name":"rust"},"index":{"kind":"string","value":"osc83"}}},{"rowIdx":780,"cells":{"code":{"kind":"string","value":"@s = <1 2 2 3 4 4 5>;\nfor ($i = 0; $i < 7; $i++) {\n $curr = $s[$i];\n if ($i > 1 and $curr == $prev) { print \"$i\\n\" }\n $prev = $curr;\n}"},"label":{"kind":"class label","value":"69","name":"Variable declaration reset"},"domain_label":{"kind":"class label","value":"2","name":"perl"},"index":{"kind":"string","value":"x1ew8"}}},{"rowIdx":781,"cells":{"code":{"kind":"null"},"label":{"kind":"class label","value":"66","name":"Vector"},"domain_label":{"kind":"class label","value":"11","name":"kotlin"},"index":{"kind":"string","value":"r5jgo"}}},{"rowIdx":782,"cells":{"code":{"kind":"string","value":"from pathlib import Path\n\nfor path in Path('.').rglob('*.*'):\n print(path)"},"label":{"kind":"class label","value":"58","name":"Walk a directory/Recursively"},"domain_label":{"kind":"class label","value":"3","name":"python"},"index":{"kind":"string","value":"r5wgq"}}},{"rowIdx":783,"cells":{"code":{"kind":"string","value":"dir(\"/bar/foo\", \"mp3\",recursive=T)"},"label":{"kind":"class label","value":"58","name":"Walk a directory/Recursively"},"domain_label":{"kind":"class label","value":"13","name":"r"},"index":{"kind":"string","value":"ulpvx"}}},{"rowIdx":784,"cells":{"code":{"kind":"string","value":"import scala.collection.parallel.CollectionConverters.VectorIsParallelizable"},"label":{"kind":"class label","value":"56","name":"Water collected between towers"},"domain_label":{"kind":"class label","value":"16","name":"scala"},"index":{"kind":"string","value":"dovng"}}},{"rowIdx":785,"cells":{"code":{"kind":"string","value":"def tobits(n, _group=8, _sep='_', _pad=False):\n 'Express n as binary bits with separator'\n bits = '{0:b}'.format(n)[::-1]\n if _pad:\n bits = '{0:0{1}b}'.format(n,\n ((_group+len(bits)-1)\n answer = _sep.join(bits[i:i+_group]\n for i in range(0, len(bits), _group))[::-1]\n answer = '0'*(len(_sep)-1) + answer\n else:\n answer = _sep.join(bits[i:i+_group]\n for i in range(0, len(bits), _group))[::-1]\n return answer\n\ndef tovlq(n):\n return tobits(n, _group=7, _sep='1_', _pad=True)\n\ndef toint(vlq):\n return int(''.join(vlq.split('_1')), 2) \n\ndef vlqsend(vlq):\n for i, byte in enumerate(vlq.split('_')[::-1]):\n print('Sent byte {0:3}: {1:"},"label":{"kind":"class label","value":"64","name":"Variable-length quantity"},"domain_label":{"kind":"class label","value":"3","name":"python"},"index":{"kind":"string","value":"cyu9q"}}},{"rowIdx":786,"cells":{"code":{"kind":"string","value":"import \"unsafe\"\n\nunsafe.Sizeof(x)"},"label":{"kind":"class label","value":"68","name":"Variable size/Get"},"domain_label":{"kind":"class label","value":"0","name":"go"},"index":{"kind":"string","value":"4v452"}}},{"rowIdx":787,"cells":{"code":{"kind":"string","value":"vector = {mt = {}}\n\nfunction vector.new (x, y)\n local new = {x = x or 0, y = y or 0}\n setmetatable(new, vector.mt)\n return new\nend\n\nfunction vector.mt.__add (v1, v2)\n return vector.new(v1.x + v2.x, v1.y + v2.y)\nend\n\nfunction vector.mt.__sub (v1, v2)\n return vector.new(v1.x - v2.x, v1.y - v2.y) \nend\n\nfunction vector.mt.__mul (v, s)\n return vector.new(v.x * s, v.y * s)\nend\n\nfunction vector.mt.__div (v, s)\n return vector.new(v.x / s, v.y / s)\nend\n\nfunction vector.print (vec) \n print(\"(\" .. vec.x .. \", \" .. vec.y .. \")\")\nend\n\nlocal a, b = vector.new(5, 7), vector.new(2, 3)\nvector.print(a + b)\nvector.print(a - b)\nvector.print(a * 11)\nvector.print(a / 2)"},"label":{"kind":"class label","value":"66","name":"Vector"},"domain_label":{"kind":"class label","value":"1","name":"lua"},"index":{"kind":"string","value":"74hru"}}},{"rowIdx":788,"cells":{"code":{"kind":"string","value":"s = [1, 2, 2, 3, 4, 4, 5]\n\nfor i in range(len(s)):\n curr = s[i]\n if i > 0 and curr == prev:\n print(i)\n prev = curr"},"label":{"kind":"class label","value":"69","name":"Variable declaration reset"},"domain_label":{"kind":"class label","value":"3","name":"python"},"index":{"kind":"string","value":"qawxi"}}},{"rowIdx":789,"cells":{"code":{"kind":"string","value":"(defn factor-pairs [n]\n (for [x (range 2 (Math/sqrt n))\n :when (zero? (mod n x))]\n [x (quot n x)]))\n\n(defn fangs [n]\n (let [dlen (comp count str)\n half (/ (dlen n) 2)\n halves? #(apply = (cons half (map dlen %)))\n digits #(sort (apply str %))]\n (filter #(and (halves? %)\n (= (sort (str n)) (digits %)))\n (factor-pairs n))))\n\n(defn vampiric? [n]\n (let [fangs (fangs n)]\n (if (empty? fangs) nil [n fangs])))\n\n(doseq [n (take 25 (keep vampiric? (range)))]\n (prn n))\n\n(doseq [n [16758243290880, 24959017348650, 14593825548650]]\n (println (or (vampiric? n) (str n \" is not vampiric.\"))))"},"label":{"kind":"class label","value":"70","name":"Vampire number"},"domain_label":{"kind":"class label","value":"6","name":"clojure"},"index":{"kind":"string","value":"mz3yq"}}},{"rowIdx":790,"cells":{"code":{"kind":"string","value":"import Foreign\n\nsizeOf (undefined :: Int) \nsizeOf (undefined :: Double) \nsizeOf (undefined :: Bool) \nsizeOf (undefined :: Ptr a)"},"label":{"kind":"class label","value":"68","name":"Variable size/Get"},"domain_label":{"kind":"class label","value":"8","name":"haskell"},"index":{"kind":"string","value":"qeqx9"}}},{"rowIdx":791,"cells":{"code":{"kind":"string","value":"int check_isin(char *a) {\n int i, j, k, v, s[24];\n\n j = 0;\n for(i = 0; i < 12; i++) {\n k = a[i];\n if(k >= '0' && k <= '9') {\n if(i < 2) return 0;\n s[j++] = k - '0';\n } else if(k >= 'A' && k <= 'Z') {\n if(i == 11) return 0;\n k -= 'A' - 10;\n s[j++] = k / 10;\n s[j++] = k % 10;\n } else {\n return 0;\n }\n }\n\n if(a[i]) return 0;\n\n v = 0;\n for(i = j - 2; i >= 0; i -= 2) {\n k = 2 * s[i];\n v += k > 9 ? k - 9 : k;\n }\n\n for(i = j - 1; i >= 0; i -= 2) {\n v += s[i];\n }\n\n return v % 10 == 0;\n}\n\nint main() {\n char *test[7] = {, , ,\n , , ,\n };\n int i;\n for(i = 0; i < 7; i++) printf(, check_isin(test[i]) ? 'T' : 'F', i == 6 ? '\\n' : ' ');\n return 0;\n}"},"label":{"kind":"class label","value":"71","name":"Validate International Securities Identification Number"},"domain_label":{"kind":"class label","value":"5","name":"c"},"index":{"kind":"string","value":"2mmlo"}}},{"rowIdx":792,"cells":{"code":{"kind":"null"},"label":{"kind":"class label","value":"68","name":"Variable size/Get"},"domain_label":{"kind":"class label","value":"11","name":"kotlin"},"index":{"kind":"string","value":"747r4"}}},{"rowIdx":793,"cells":{"code":{"kind":"null"},"label":{"kind":"class label","value":"56","name":"Water collected between towers"},"domain_label":{"kind":"class label","value":"17","name":"swift"},"index":{"kind":"string","value":"0xms6"}}},{"rowIdx":794,"cells":{"code":{"kind":"string","value":"typedef struct{\n\tfloat i,j,k;\n\t}Vector;\n\nVector a = {3, 4, 5},b = {4, 3, 5},c = {-5, -12, -13};\n\nfloat dotProduct(Vector a, Vector b)\n{\n\treturn a.i*b.i+a.j*b.j+a.k*b.k;\n}\n\nVector crossProduct(Vector a,Vector b)\n{\n\tVector c = {a.j*b.k - a.k*b.j, a.k*b.i - a.i*b.k, a.i*b.j - a.j*b.i};\n\n\treturn c;\n}\n\nfloat scalarTripleProduct(Vector a,Vector b,Vector c)\n{\n\treturn dotProduct(a,crossProduct(b,c));\n}\n\nVector vectorTripleProduct(Vector a,Vector b,Vector c)\n{\n\treturn crossProduct(a,crossProduct(b,c));\n}\n\nvoid printVector(Vector a)\n{\n\tprintf(,a.i,a.j,a.k);\n}\n\nint main()\n{\n\tprintf(); printVector(a);\n\tprintf(); printVector(b);\n\tprintf(); printVector(c);\n\tprintf(,dotProduct(a,b));\n\tprintf(); printVector(crossProduct(a,b));\n\tprintf(,scalarTripleProduct(a,b,c));\n\tprintf(); printVector(vectorTripleProduct(a,b,c));\n\n\treturn 0;\n}"},"label":{"kind":"class label","value":"72","name":"Vector products"},"domain_label":{"kind":"class label","value":"5","name":"c"},"index":{"kind":"string","value":"pj7by"}}},{"rowIdx":795,"cells":{"code":{"kind":"string","value":"void vc(int n, int base, int *num, int *denom)\n{\n int p = 0, q = 1;\n\n while (n) {\n p = p * base + (n % base);\n q *= base;\n n /= base;\n }\n\n *num = p; \n *denom = q;\n\n while (p) { n = p; p = q % p; q = n; }\n *num /= q;\n *denom /= q;\n}\n\nint main()\n{\n int d, n, i, b;\n for (b = 2; b < 6; b++) {\n printf(, b);\n for (i = 0; i < 10; i++) {\n vc(i, b, &n, &d);\n if (n) printf(, n, d);\n else printf();\n }\n printf();\n }\n\n return 0;\n}"},"label":{"kind":"class label","value":"73","name":"Van der Corput sequence"},"domain_label":{"kind":"class label","value":"5","name":"c"},"index":{"kind":"string","value":"wpkec"}}},{"rowIdx":796,"cells":{"code":{"kind":"string","value":"[0x200000, 0x1fffff].each do |i|\n \n ber = [i].pack()\n hex = ber.unpack().collect {|c| % c}.join()\n printf , i, hex\n\n \n j = ber.unpack().first\n i == j or fail \nend"},"label":{"kind":"class label","value":"64","name":"Variable-length quantity"},"domain_label":{"kind":"class label","value":"14","name":"ruby"},"index":{"kind":"string","value":"294lw"}}},{"rowIdx":797,"cells":{"code":{"kind":"string","value":"object VlqCode {\n def encode(x:Long)={\n val result=scala.collection.mutable.Stack[Byte]()\n result push (x&0x7f).toByte\n var l = x >>> 7\n while(l>0){\n result push ((l&0x7f)|0x80).toByte\n l >>>= 7\n }\n result.toArray\n }\n\n def decode(a:Array[Byte])=a.foldLeft(0L)((r, b) => r<<7|b&0x7f)\n\n def toString(a:Array[Byte])=a map(\"%02x\".format(_)) mkString(\"[\", \", \", \"]\") \n\n def test(x:Long)={\n val enc=encode(x)\n println(\"0x%x =>%s => 0x%x\".format(x, toString(enc), decode(enc)))\n }\n\n def main(args: Array[String]): Unit = {\n val xs=Seq(0, 0x7f, 0x80, 0x2000, 0x3fff, 0x4000, 0x1FFFFF, 0x200000, 0x8000000,\n 0xFFFFFFF, 0xFFFFFFFFL, 0x842FFFFFFFFL, 0x0FFFFFFFFFFFFFFFL)\n xs foreach test\n }\n}"},"label":{"kind":"class label","value":"64","name":"Variable-length quantity"},"domain_label":{"kind":"class label","value":"16","name":"scala"},"index":{"kind":"string","value":"4vj50"}}},{"rowIdx":798,"cells":{"code":{"kind":"string","value":"> s = \"hello\"\n> print(#s)\n5\n> t = { 1,2,3,4,5 }\n> print(#t)\n5"},"label":{"kind":"class label","value":"68","name":"Variable size/Get"},"domain_label":{"kind":"class label","value":"1","name":"lua"},"index":{"kind":"string","value":"jgj71"}}},{"rowIdx":799,"cells":{"code":{"kind":"string","value":"1 )? : ;\n echo $key . PHP_EOL ;\n foreach ($tree as $key => $value) {\n if ($key === array_key_last($tree)){\n echo (($first)? : $firstPadding ) . $stack . ;\n $padding = ;\n if($first) $firstPadding = ;\n }\n else {\n echo (($first)? : $firstPadding ) . $stack . ;\n $padding = ;\n }\n if( is_array($value) )printTree( $value , $key , $stack . (($first)? : $padding ) , FALSE , $firstPadding );\n else echo $key . . $value . PHP_EOL;\n }\n }\n else echo $tree . PHP_EOL;\n}\n\n\n\n\n\n\n$sample_array_1 = \n[\n 0 => [\n 'item_id' => 6,\n 'price' => ,\n 'qty' => 12,\n 'discount' => 0\n ],\n 1 => [\n 'item_id' => 7,\n 'price' => ,\n 'qty' => 1,\n 'discount' => 12\n ],\n 2 => [\n 'item_id' => 8,\n 'price' => ,\n 'qty' => 0,\n 'discount' => 24\n ]\n];\n$sample_array_2 = array(\n array(\n =>,\n =>,\n =>,\n =>,\n =>,\n =>array(\n =>,\n =>array(\n =>\n )\n )\n\n )\n);\n$sample_array_3 = [\n => [\n =>[\n ,\n => [\n ,\n ,\n => [\n ,\n ,\n ]\n ],\n ,\n ] ,\n => [\n => [ => [1]]\n ]\n ]\n];\n$sample_array_4 = [];\n$sample_array_5 = [];\n$sample_array_5 = [];\n$sample_array_6 = [\n ,\n ,\n ,\n ,\n ,\n ,\n ,\n ,\n ,\n ,\n ,\n];\n\n\nprintTree($sample_array_1);\necho PHP_EOL . . PHP_EOL;\nprintTree($sample_array_2);\necho PHP_EOL . . PHP_EOL;\nprintTree($sample_array_3);\necho PHP_EOL . . PHP_EOL;\nprintTree($sample_array_4);\necho PHP_EOL . . PHP_EOL;\nprintTree($sample_array_5);\necho PHP_EOL . . PHP_EOL;\nprintTree($sample_array_6);\n\n\n?>"},"label":{"kind":"class label","value":"57","name":"Visualize a tree"},"domain_label":{"kind":"class label","value":"12","name":"php"},"index":{"kind":"string","value":"k78hv"}}}],"truncated":false,"partial":false},"paginationData":{"pageIndex":7,"numItemsPerPage":100,"numTotalItems":14581,"offset":700,"length":100}},"jwt":"eyJhbGciOiJFZERTQSJ9.eyJyZWFkIjp0cnVlLCJwZXJtaXNzaW9ucyI6eyJyZXBvLmNvbnRlbnQucmVhZCI6dHJ1ZX0sImlhdCI6MTc1NjIyMTQzOSwic3ViIjoiL2RhdGFzZXRzL2d1eWNodWsvY29kZS1kdXBsaWNhdGVzLWFjcm9zcy1sYW5ndWFnZXMiLCJleHAiOjE3NTYyMjUwMzksImlzcyI6Imh0dHBzOi8vaHVnZ2luZ2ZhY2UuY28ifQ.Tf8-TuMxkvympuD-1xlWIFHUKXGAIxgmBvBSIFqkVd9BxsTwY1CxOjlc6aWGSAKsKJBdk8OL68DvXia1hTmMBw","displayUrls":true},"discussionsStats":{"closed":0,"open":1,"total":1},"fullWidth":true,"hasGatedAccess":true,"hasFullAccess":true,"isEmbedded":false,"savedQueries":{"community":[],"user":[]}}">
code
stringlengths
1
46.1k
label
class label
1.18k classes
domain_label
class label
21 classes
index
stringlengths
4
5
public class VisualizeTree { public static void main(String[] args) { BinarySearchTree tree = new BinarySearchTree(); tree.insert(100); for (int i = 0; i < 20; i++) tree.insert((int) (Math.random() * 200)); tree.display(); } } class BinarySearchTree { private Node root; private class Node { private int key; private Node left, right; Node(int k) { key = k; } } public boolean insert(int key) { if (root == null) root = new Node(key); else { Node n = root; Node parent; while (true) { if (n.key == key) return false; parent = n; boolean goLeft = key < n.key; n = goLeft ? n.left : n.right; if (n == null) { if (goLeft) { parent.left = new Node(key); } else { parent.right = new Node(key); } break; } } } return true; } public void display() { final int height = 5, width = 64; int len = width * height * 2 + 2; StringBuilder sb = new StringBuilder(len); for (int i = 1; i <= len; i++) sb.append(i < len - 2 && i % width == 0 ? "\n" : ' '); displayR(sb, width / 2, 1, width / 4, width, root, " "); System.out.println(sb); } private void displayR(StringBuilder sb, int c, int r, int d, int w, Node n, String edge) { if (n != null) { displayR(sb, c - d, r + 2, d / 2, w, n.left, " /"); String s = String.valueOf(n.key); int idx1 = r * w + c - (s.length() + 1) / 2; int idx2 = idx1 + s.length(); int idx3 = idx1 - w; if (idx2 < sb.length()) sb.replace(idx1, idx2, s).replace(idx3, idx3 + 2, edge); displayR(sb, c + d, r + 2, d / 2, w, n.right, "\\ "); } } }
57Visualize a tree
9java
1knp2
dir("/foo/bar", "mp3")
53Walk a directory/Non-recursively
13r
vcw27
var fso = new ActiveXObject("Scripting.FileSystemObject"); function walkDirectoryTree(folder, folder_name, re_pattern) { WScript.Echo("Files in " + folder_name + " matching '" + re_pattern + "':"); walkDirectoryFilter(folder.files, re_pattern); var subfolders = folder.SubFolders; WScript.Echo("Folders in " + folder_name + " matching '" + re_pattern + "':"); walkDirectoryFilter(subfolders, re_pattern); WScript.Echo(); var en = new Enumerator(subfolders); while (! en.atEnd()) { var subfolder = en.item(); walkDirectoryTree(subfolder, folder_name + "/" + subfolder.name, re_pattern); en.moveNext(); } } function walkDirectoryFilter(items, re_pattern) { var e = new Enumerator(items); while (! e.atEnd()) { var item = e.item(); if (item.name.match(re_pattern)) WScript.Echo(item.name); e.moveNext(); } } walkDirectoryTree(dir, dir.name, '\\.txt$');
58Walk a directory/Recursively
10javascript
m3ryv
def invoke(String cmd) { println(cmd.execute().text) } invoke("xrandr -q") Thread.sleep(3000) invoke("xrandr -s 1024x768") Thread.sleep(3000) invoke("xrandr -s 1366x768")
63Video display modes
7groovy
yz26o
null
59Verify distribution uniformity/Naive
11kotlin
qetx1
import static java.lang.Math.pow; import java.util.Arrays; import static java.util.Arrays.stream; import org.apache.commons.math3.special.Gamma; public class Test { static double x2Dist(double[] data) { double avg = stream(data).sum() / data.length; double sqs = stream(data).reduce(0, (a, b) -> a + pow((b - avg), 2)); return sqs / avg; } static double x2Prob(double dof, double distance) { return Gamma.regularizedGammaQ(dof / 2, distance / 2); } static boolean x2IsUniform(double[] data, double significance) { return x2Prob(data.length - 1.0, x2Dist(data)) > significance; } public static void main(String[] a) { double[][] dataSets = {{199809, 200665, 199607, 200270, 199649}, {522573, 244456, 139979, 71531, 21461}}; System.out.printf("%4s%12s %12s%8s %s%n", "dof", "distance", "probability", "Uniform?", "dataset"); for (double[] ds : dataSets) { int dof = ds.length - 1; double dist = x2Dist(ds); double prob = x2Prob(dof, dist); System.out.printf("%4d%12.3f %12.8f %5s %6s%n", dof, dist, prob, x2IsUniform(ds, 0.05) ? "YES" : "NO", Arrays.toString(ds)); } } }
62Verify distribution uniformity/Chi-squared test
9java
3flzg
<!doctype html> <html id="doc"> <head><meta charset="utf-8"/> <title>Stuff</title> <script type="application/javascript"> function gid(id) { return document.getElementById(id); } function ce(tag, cls, parent_node) { var e = document.createElement(tag); e.className = cls; if (parent_node) parent_node.appendChild(e); return e; } function dom_tree(id) { gid('tree').textContent = ""; gid('tree').appendChild(mktree(gid(id), null)); } function mktree(e, p) { var t = ce("div", "tree", p); var tog = ce("span", "toggle", t); var h = ce("span", "tag", t); if (e.tagName === undefined) { h.textContent = "#Text"; var txt = e.textContent; if (txt.length > 0 && txt.match(/\S/)) { h = ce("div", "txt", t); h.textContent = txt; } return t; } tog.textContent = ""; tog.onclick = function () { clicked(tog); } h.textContent = e.nodeName; var l = e.childNodes; for (var i = 0; i!= l.length; i++) mktree(l[i], t); return t; } function clicked(e) { var is_on = e.textContent == ""; e.textContent = is_on? "+": ""; e.parentNode.className = is_on? "tree-hide": "tree"; } </script> <style> #tree { white-space: pre; font-family: monospace; border: 1px solid } .tree > .tree-hide, .tree > .tree { margin-left: 2em; border-left: 1px dotted rgba(0,0,0,.2)} .tree-hide > .tree, .tree-hide > .tree-hide { display: none } .tag { color: navy } .tree-hide > .tag { color: maroon } .txt { color: gray; padding: 0 .5em; margin: 0 .5em 0 2em; border: 1px dotted rgba(0,0,0,.1) } .toggle { display: inline-block; width: 2em; text-align: center } </style> </head> <body> <article> <section> <h1>Headline</h1> Blah blah </section> <section> <h1>More headline</h1> <blockquote>Something something</blockquote> <section><h2>Nested section</h2> Somethin somethin list: <ul> <li>Apples</li> <li>Oranges</li> <li>Cetera Fruits</li> </ul> </section> </section> </article> <div id="tree"><a href="javascript:dom_tree('doc')">click me</a></div> </body> </html>
57Visualize a tree
10javascript
qe3x8
null
58Walk a directory/Recursively
11kotlin
osm8z
null
56Water collected between towers
11kotlin
lmbcp
null
63Video display modes
11kotlin
52jua
print("\33[?3h")
63Video display modes
1lua
4vh5c
void to_seq(uint64_t x, uint8_t *out) { int i, j; for (i = 9; i > 0; i--) { if (x & 127ULL << i * 7) break; } for (j = 0; j <= i; j++) out[j] = ((x >> ((i - j) * 7)) & 127) | 128; out[i] ^= 128; } uint64_t from_seq(uint8_t *in) { uint64_t r = 0; do { r = (r << 7) | (uint64_t)(*in & 127); } while (*in++ & 128); return r; } int main() { uint8_t s[10]; uint64_t x[] = { 0x7f, 0x4000, 0, 0x3ffffe, 0x1fffff, 0x200000, 0x3311a1234df31413ULL}; int i, j; for (j = 0; j < sizeof(x)/8; j++) { to_seq(x[j], s); printf(, x[j]); i = 0; do { printf(, s[i]); } while ((s[i++] & 128)); printf(, from_seq(s)); } return 0; }
64Variable-length quantity
5c
3f9za
int_least32_t foo;
65Variable size/Set
5c
r5hg7
null
62Verify distribution uniformity/Chi-squared test
11kotlin
n86ij
function waterCollected(i,tower) local length = 0 for _ in pairs(tower) do length = length + 1 end local wu = 0 repeat local rht = length - 1 while rht >= 0 do if tower[rht + 1] > 0 then break end rht = rht - 1 end if rht < 0 then break end local bof = 0 local col = 0 while col <= rht do if tower[col + 1] > 0 then tower[col + 1] = tower[col + 1] - 1 bof = bof + 1 elseif bof > 0 then wu = wu + 1 end col = col + 1 end if bof < 2 then break end until false if wu == 0 then print(string.format("Block%d does not hold any water.", i)) else print(string.format("Block%d holds%d water units.", i, wu)) end end function main() local towers = { {1, 5, 3, 7, 2}, {5, 3, 7, 2, 6, 4, 5, 9, 1, 2}, {2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1}, {5, 5, 5, 5}, {5, 6, 7, 8}, {8, 7, 7, 6}, {6, 7, 10, 7, 6} } for i,tbl in pairs(towers) do waterCollected(i,tbl) end end main()
56Water collected between towers
1lua
29pl3
$| = 1; my @info = `xrandr -q`; $info[0] =~ /current (\d+) x (\d+)/; my $current = "$1x$2"; my @resolutions; for (@info) { push @resolutions, $1 if /^\s+(\d+x\d+)/ } system("xrandr -s $resolutions[-1]"); print "Current resolution $resolutions[-1].\n"; for (reverse 1 .. 9) { print "\rChanging back in $_ seconds..."; sleep 1; } system("xrandr -s $current"); print "\rResolution returned to $current.\n";
63Video display modes
2perl
ost8x
import win32api import win32con import pywintypes devmode=pywintypes.DEVMODEType() devmode.PelsWidth=640 devmode.PelsHeight=480 devmode.Fields=win32con.DM_PELSWIDTH | win32con.DM_PELSHEIGHT win32api.ChangeDisplaySettings(devmode,0)
63Video display modes
3python
i0zof
typedef struct{ double x,y; }vector; vector initVector(double r,double theta){ vector c; c.x = r*cos(theta); c.y = r*sin(theta); return c; } vector addVector(vector a,vector b){ vector c; c.x = a.x + b.x; c.y = a.y + b.y; return c; } vector subtractVector(vector a,vector b){ vector c; c.x = a.x - b.x; c.y = a.y - b.y; return c; } vector multiplyVector(vector a,double b){ vector c; c.x = b*a.x; c.y = b*a.y; return c; } vector divideVector(vector a,double b){ vector c; c.x = a.x/b; c.y = a.y/b; return c; } void printVector(vector a){ printf(,a.x,140,(a.y>=0)?'+':'-',(a.y>=0)?a.y:fabs(a.y),150); } int main() { vector a = initVector(3,pi/6); vector b = initVector(5,2*pi/3); printf(); printVector(a); printf(); printVector(b); printf(); printVector(addVector(a,b)); printf(); printVector(subtractVector(a,b)); printf(); printVector(multiplyVector(a,3)); printf(); printVector(divideVector(b,2.5)); return 0; }
66Vector
5c
8qi04
null
57Visualize a tree
11kotlin
jgs7r
Dir.glob('*') { |file| puts file } Dir.glob( File.join('/foo/bar', '*') ) { |file| puts file } def file_match(pattern=/\.txt/, path='.') Dir[File.join(path,'*')].each do |file| puts file if file =~ pattern end end
53Walk a directory/Non-recursively
14ruby
74ori
local lfs = require("lfs")
58Walk a directory/Recursively
1lua
i09ot
package main import "fmt" type vkey string func newVigenre(key string) (vkey, bool) { v := vkey(upperOnly(key)) return v, len(v) > 0
61Vigenère cipher
0go
os38q
function makeTree(v,ac) if type(ac) == "table" then return {value=v,children=ac} else return {value=v} end end function printTree(t,last,prefix) if last == nil then printTree(t, false, '') else local current = '' local next = '' if last then current = prefix .. '\\-' .. t.value next = prefix .. ' ' else current = prefix .. '|-' .. t.value next = prefix .. '| ' end print(current:sub(3)) if t.children ~= nil then for k,v in pairs(t.children) do printTree(v, k == #t.children, next) end end end end printTree( makeTree('A', { makeTree('B0', { makeTree('C1'), makeTree('C2', { makeTree('D', { makeTree('E1'), makeTree('E2'), makeTree('E3') }) }), makeTree('C3', { makeTree('F1'), makeTree('F2'), makeTree('F3', {makeTree('G')}), makeTree('F4', { makeTree('H1'), makeTree('H2') }) }) }), makeTree('B1',{ makeTree('K1'), makeTree('K2', { makeTree('L1', {makeTree('M')}), makeTree('L2'), makeTree('L3') }), makeTree('K3') }) }) )
57Visualize a tree
1lua
hr0j8
extern crate docopt; extern crate regex; extern crate rustc_serialize; use docopt::Docopt; use regex::Regex; const USAGE: &'static str = " Usage: rosetta <pattern> Walks the directory tree starting with the current working directory and print filenames matching <pattern>. "; #[derive(Debug, RustcDecodable)] struct Args { arg_pattern: String, } fn main() { let args: Args = Docopt::new(USAGE) .and_then(|d| d.decode()) .unwrap_or_else(|e| e.exit()); let re = Regex::new(&args.arg_pattern).unwrap(); let paths = std::fs::read_dir(".").unwrap(); for path in paths { let path = path.unwrap().path(); let path = path.to_str().unwrap(); if re.is_match(path) { println!("{}", path); } } }
53Walk a directory/Non-recursively
15rust
jgi72
object VideoDisplayModes extends App { import java.util.Scanner def runSystemCommand(command: String) { val proc = Runtime.getRuntime.exec(command) val a: Unit = { val a = new Scanner(proc.getInputStream) while (a.hasNextLine) println(a.nextLine()) } proc.waitFor() println() }
63Video display modes
16scala
3fczy
sub roll7 { 1+int rand(7) } sub roll5 { 1+int rand(5) } sub roll7_5 { while(1) { my $d7 = (5*&roll5 + &roll5 - 6) % 8; return $d7 if $d7; } } my $threshold = 5; print dist( $_, $threshold, \&roll7 ) for <1001 1000006>; print dist( $_, $threshold, \&roll7_5 ) for <1001 1000006>; sub dist { my($n, $threshold, $producer) = @_; my @dist; my $result; my $expect = $n / 7; $result .= sprintf "%10d expected\n", $expect; for (1..$n) { @dist[&$producer]++; } for my $i (1..7) { my $v = @dist[$i]; my $pct = ($v - $expect)/$expect*100; $result .= sprintf "%d%8d%6.1f%%%s\n", $i, $v, $pct, (abs($pct) > $threshold ? ' - skewed' : ''); } return $result . "\n"; }
59Verify distribution uniformity/Naive
2perl
vck20
package main import ( "fmt" "unsafe" ) func main() { i := 5
65Variable size/Set
0go
n8ti1
import Data.Int import Foreign.Storable task name value = putStrLn $ name ++ ": " ++ show (sizeOf value) ++ " byte(s)" main = do let i8 = 0::Int8 let i16 = 0::Int16 let i32 = 0::Int32 let i64 = 0::Int64 let int = 0::Int task "Int8" i8 task "Int16" i16 task "Int32" i32 task "Int64" i64 task "Int" int
65Variable size/Set
8haskell
ulgv2
require_relative 'raster_graphics' class ColourPixel < Pixel def initialize(x, y, colour) @colour = colour super x, y end attr_accessor :colour def distance_to(px, py) Math.hypot(px - x, py - y) end end width = 300 height = 200 npoints = 20 pixmap = Pixmap.new(width, height) @bases = npoints.times.collect do |_i| ColourPixel.new( 3 + rand(width - 6), 3 + rand(height - 6), RGBColour.new(rand(256), rand(256), rand(256)) ) end pixmap.each_pixel do |x, y| nearest = @bases.min_by { |base| base.distance_to(x, y) } pixmap[x, y] = nearest.colour end @bases.each do |base| pixmap[base.x, base.y] = RGBColour::BLACK pixmap.draw_circle(base, 2, RGBColour::BLACK) end pixmap.save_as_png('voronoi_rb.png')
54Voronoi diagram
14ruby
yzh6n
import Data.Char import Text.Printf crypt f key = map toLetter . zipWith f (cycle key) where toLetter = chr . (+) (ord 'A') enc k c = (ord k + ord c) `mod` 26 dec k c = (ord c - ord k) `mod` 26 encrypt = crypt enc decrypt = crypt dec convert = map toUpper . filter isLetter main :: IO () main = do let key = "VIGENERECIPHER" text = "Beware the Jabberwock, my son! The jaws that bite, " ++ "the claws that catch!" encr = encrypt key $ convert text decr = decrypt key encr printf " Input:%s\n Key:%s\nEncrypted:%s\nDecrypted:%s\n" text key encr decr
61Vigenère cipher
8haskell
297ll
import java.io.File val dir = new File("/foo/bar").list() dir.filter(file => file.endsWith(".mp3")).foreach(println)
53Walk a directory/Non-recursively
16scala
bjfk6
null
65Variable size/Set
11kotlin
tn6f0
extern crate piston; extern crate opengl_graphics; extern crate graphics; extern crate touch_visualizer; #[cfg(feature = "include_sdl2")] extern crate sdl2_window; extern crate getopts; extern crate voronoi; extern crate rand; use touch_visualizer::TouchVisualizer; use opengl_graphics::{ GlGraphics, OpenGL }; use graphics::{ Context, Graphics }; use piston::window::{ Window, WindowSettings }; use piston::input::*; use piston::event_loop::*; #[cfg(feature = "include_sdl2")] use sdl2_window::Sdl2Window as AppWindow; use voronoi::{voronoi, Point, make_polygons}; use rand::Rng; static DEFAULT_WINDOW_HEIGHT: u32 = 600; static DEFAULT_WINDOW_WIDTH: u32 = 600; struct Settings { lines_only: bool, random_count: usize } fn main() { let args: Vec<String> = std::env::args().collect(); let mut opts = getopts::Options::new(); opts.optflag("l", "lines_only", "Don't color polygons, just outline them"); opts.optopt("r", "random_count", "On keypress \"R\", put this many random points on-screen", "RANDOMCOUNT"); let matches = opts.parse(&args[1..]).expect("Failed to parse args"); let settings = Settings{ lines_only: matches.opt_present("l"), random_count: match matches.opt_str("r") { None => { 50 }, Some(s) => { s.parse().expect("Random count of bad format") } } }; event_loop(&settings); } fn random_point() -> [f64; 2] { [rand::thread_rng().gen_range(0., DEFAULT_WINDOW_HEIGHT as f64), rand::thread_rng().gen_range(0., DEFAULT_WINDOW_WIDTH as f64)] } fn random_color() -> [f32; 4] { [rand::random::<f32>(), rand::random::<f32>(), rand::random::<f32>(), 1.0] } fn random_voronoi(dots: &mut Vec<[f64;2]>, colors: &mut Vec<[f32;4]>, num: usize) { dots.clear(); colors.clear(); for _ in 0..num { dots.push(random_point()); colors.push(random_color()); } } fn event_loop(settings: &Settings) { let opengl = OpenGL::V3_2; let mut window: AppWindow = WindowSettings::new("Interactive Voronoi", [DEFAULT_WINDOW_HEIGHT, DEFAULT_WINDOW_WIDTH]) .exit_on_esc(true).opengl(opengl).build().unwrap(); let ref mut gl = GlGraphics::new(opengl); let mut touch_visualizer = TouchVisualizer::new(); let mut events = Events::new(EventSettings::new().lazy(true)); let mut dots = Vec::new(); let mut colors = Vec::new(); let mut mx = 0.0; let mut my = 0.0; while let Some(e) = events.next(&mut window) { touch_visualizer.event(window.size(), &e); if let Some(button) = e.release_args() { match button { Button::Keyboard(key) => { if key == piston::input::keyboard::Key::N { dots.clear(); colors.clear(); } if key == piston::input::keyboard::Key::R { random_voronoi(&mut dots, &mut colors, settings.random_count); } } Button::Mouse(_) => { dots.push([mx, my]); colors.push(random_color()); }, _ => () } }; e.mouse_cursor(|x, y| { mx = x; my = y; }); if let Some(args) = e.render_args() { gl.draw(args.viewport(), |c, g| { graphics::clear([1.0; 4], g); let mut vor_pts = Vec::new(); for d in &dots { vor_pts.push(Point::new(d[0], d[1])); } if vor_pts.len() > 0 { let vor_diagram = voronoi(vor_pts, DEFAULT_WINDOW_WIDTH as f64); let vor_polys = make_polygons(&vor_diagram); for (i, poly) in vor_polys.iter().enumerate() { if settings.lines_only { draw_lines_in_polygon(poly, &c, g); } else { draw_polygon(poly, &c, g, colors[i]); } } } for d in &dots { draw_ellipse(&d, &c, g); } }); } } } fn draw_lines_in_polygon<G: Graphics>( poly: &Vec<Point>, c: &Context, g: &mut G, ) { let color = [0.0, 0.0, 1.0, 1.0]; for i in 0..poly.len()-1 { graphics::line( color, 2.0, [poly[i].x.into(), poly[i].y.into(), poly[i+1].x.into(), poly[i+1].y.into()], c.transform, g ) } } fn draw_polygon<G: Graphics>( poly: &Vec<Point>, c: &Context, g: &mut G, color: [f32; 4] ) { let mut polygon_points: Vec<[f64; 2]> = Vec::new(); for p in poly { polygon_points.push([p.x.into(), p.y.into()]); } graphics::polygon( color, polygon_points.as_slice(), c.transform, g ) } fn draw_ellipse<G: Graphics>( cursor: &[f64; 2], c: &Context, g: &mut G, ) { let color = [0.0, 0.0, 0.0, 1.0]; graphics::ellipse( color, graphics::ellipse::circle(cursor[0], cursor[1], 4.0), c.transform, g ); }
54Voronoi diagram
15rust
m3kya
use List::Util qw(sum reduce); use constant pi => 3.14159265; sub incomplete_G_series { my($s, $z) = @_; my $n = 10; push @numers, $z**$_ for 1..$n; my @denoms = $s+1; push @denoms, $denoms[-1]*($s+$_) for 2..$n; my $M = 1; $M += $numers[$_-1]/$denoms[$_-1] for 1..$n; $z**$s / $s * exp(-$z) * $M; } sub G_of_half { my($n) = @_; if ($n % 2) { f(2*$_) / (4**$_ * f($_)) * sqrt(pi) for int ($n-1) / 2 } else { f(($n/2)-1) } } sub f { reduce { $a * $b } 1, 1 .. $_[0] } sub chi_squared_cdf { my($k, $x) = @_; my $f = $k < 20 ? 20 : 10; if ($x == 0) { 0.0 } elsif ($x < $k + $f*sqrt($k)) { incomplete_G_series($k/2, $x/2) / G_of_half($k) } else { 1.0 } } sub chi_squared_test { my(@bins) = @_; $significance = 0.05; my $n = @bins; my $N = sum @bins; my $expected = $N / $n; my $chi_squared = sum map { ($_ - $expected)**2 / $expected } @bins; my $p_value = 1 - chi_squared_cdf($n-1, $chi_squared); return $chi_squared, $p_value, $p_value > $significance ? 'True' : 'False'; } for $dataset ([199809, 200665, 199607, 200270, 199649], [522573, 244456, 139979, 71531, 21461]) { printf "C2 =%10.3f, p-value =%.3f, uniform =%s\n", chi_squared_test(@$dataset); }
62Verify distribution uniformity/Chi-squared test
2perl
741rh
use Modern::Perl; use List::Util qw{ min max sum }; sub water_collected { my @t = map { { TOWER => $_, LEFT => 0, RIGHT => 0, LEVEL => 0 } } @_; my ( $l, $r ) = ( 0, 0 ); $_->{LEFT} = ( $l = max( $l, $_->{TOWER} ) ) for @t; $_->{RIGHT} = ( $r = max( $r, $_->{TOWER} ) ) for reverse @t; $_->{LEVEL} = min( $_->{LEFT}, $_->{RIGHT} ) for @t; return sum map { $_->{LEVEL} > 0 ? $_->{LEVEL} - $_->{TOWER} : 0 } @t; } say join ' ', map { water_collected( @{$_} ) } ( [ 1, 5, 3, 7, 2 ], [ 5, 3, 7, 2, 6, 4, 5, 9, 1, 2 ], [ 2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1 ], [ 5, 5, 5, 5 ], [ 5, 6, 7, 8 ], [ 8, 7, 7, 6 ], [ 6, 7, 10, 7, 6 ], );
56Water collected between towers
2perl
qe6x6
package main import ( "fmt" "encoding/binary" ) func main() { buf := make([]byte, binary.MaxVarintLen64) for _, x := range []int64{0x200000, 0x1fffff} { v := buf[:binary.PutVarint(buf, x)] fmt.Printf("%d encodes into%d bytes:%x\n", x, len(v), v) x, _ = binary.Varint(v) fmt.Println(x, "decoded") } }
64Variable-length quantity
0go
bjekh
import java.awt.geom.Ellipse2D import java.awt.image.BufferedImage import java.awt.{Color, Graphics, Graphics2D} import scala.math.sqrt object Voronoi extends App { private val (cells, dim) = (100, 1000) private val rand = new scala.util.Random private val color = Vector.fill(cells)(rand.nextInt(0x1000000)) private val image = new BufferedImage(dim, dim, BufferedImage.TYPE_INT_RGB) private val g: Graphics2D = image.createGraphics() private val px = Vector.fill(cells)(rand.nextInt(dim)) private val py = Vector.fill(cells)(rand.nextInt(dim)) for (x <- 0 until dim; y <- 0 until dim) { var n = 0 def distance(x1: Int, x2: Int, y1: Int, y2: Int) = sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2).toDouble)
54Voronoi diagram
16scala
lm1cq
from collections import Counter from pprint import pprint as pp def distcheck(fn, repeats, delta): '''\ Bin the answers to fn() and check bin counts are within +/- delta% of repeats/bincount''' bin = Counter(fn() for i in range(repeats)) target = repeats deltacount = int(delta / 100. * target) assert all( abs(target - count) < deltacount for count in bin.values() ), % ( target, deltacount, [ (key, target - count) for key, count in sorted(bin.items()) ] ) pp(dict(bin))
59Verify distribution uniformity/Naive
3python
ulbvd
final RADIX = 7 final MASK = 2**RADIX - 1 def octetify = { n -> def octets = [] for (def i = n; i != 0; i >>>= RADIX) { octets << ((byte)((i & MASK) + (octets.empty ? 0: MASK + 1))) } octets.reverse() } def deoctetify = { octets -> octets.inject(0) { long n, octet -> (n << RADIX) + ((int)(octet) & MASK) } }
64Variable-length quantity
7groovy
r5kgh
import Numeric (readOct, showOct) import Data.List (intercalate) to :: Int -> String to = flip showOct "" from :: String -> Int from = fst . head . readOct main :: IO () main = mapM_ (putStrLn . intercalate " <-> " . (pure (:) <*> to <*> (return . show . from . to))) [2097152, 2097151]
64Variable-length quantity
8haskell
do3n4
with javascript_semantics requires("1.0.0") include mpfr.e mpfr pi = mpfr_init(0,-121) -- 120 dp, +1 for the "3." mpfr_const_pi(pi) printf(1,"PI with 120 decimals:%s\n\n",mpfr_get_fixed(pi,120))
65Variable size/Set
2perl
k71hc
import math import random def GammaInc_Q( a, x): a1 = a-1 a2 = a-2 def f0( t ): return t**a1*math.exp(-t) def df0(t): return (a1-t)*t**a2*math.exp(-t) y = a1 while f0(y)*(x-y) >2.0e-8 and y < x: y += .3 if y > x: y = x h = 3.0e-4 n = int(y/h) h = y/n hh = 0.5*h gamax = h * sum( f0(t)+hh*df0(t) for t in ( h*j for j in xrange(n-1, -1, -1))) return gamax/gamma_spounge(a) c = None def gamma_spounge( z): global c a = 12 if c is None: k1_factrl = 1.0 c = [] c.append(math.sqrt(2.0*math.pi)) for k in range(1,a): c.append( math.exp(a-k) * (a-k)**(k-0.5) / k1_factrl ) k1_factrl *= -k accm = c[0] for k in range(1,a): accm += c[k] / (z+k) accm *= math.exp( -(z+a)) * (z+a)**(z+0.5) return accm/z; def chi2UniformDistance( dataSet ): expected = sum(dataSet)*1.0/len(dataSet) cntrd = (d-expected for d in dataSet) return sum(x*x for x in cntrd)/expected def chi2Probability(dof, distance): return 1.0 - GammaInc_Q( 0.5*dof, 0.5*distance) def chi2IsUniform(dataSet, significance): dof = len(dataSet)-1 dist = chi2UniformDistance(dataSet) return chi2Probability( dof, dist ) > significance dset1 = [ 199809, 200665, 199607, 200270, 199649 ] dset2 = [ 522573, 244456, 139979, 71531, 21461 ] for ds in (dset1, dset2): print , ds dof = len(ds)-1 distance =chi2UniformDistance(ds) print % (dof, distance), prob = chi2Probability( dof, distance) print %prob, print , if chi2IsUniform(ds,0.05) else
62Verify distribution uniformity/Chi-squared test
3python
jga7p
public class VigenereCipher { public static void main(String[] args) { String key = "VIGENERECIPHER"; String ori = "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!"; String enc = encrypt(ori, key); System.out.println(enc); System.out.println(decrypt(enc, key)); } static String encrypt(String text, final String key) { String res = ""; text = text.toUpperCase(); for (int i = 0, j = 0; i < text.length(); i++) { char c = text.charAt(i); if (c < 'A' || c > 'Z') continue; res += (char)((c + key.charAt(j) - 2 * 'A') % 26 + 'A'); j = ++j % key.length(); } return res; } static String decrypt(String text, final String key) { String res = ""; text = text.toUpperCase(); for (int i = 0, j = 0; i < text.length(); i++) { char c = text.charAt(i); if (c < 'A' || c > 'Z') continue; res += (char)((c - key.charAt(j) + 26) % 26 + 'A'); j = ++j % key.length(); } return res; } }
61Vigenère cipher
9java
6tv3z
use warnings; use strict; use utf8; use open OUT => ':utf8', ':std'; sub parse { my ($tree) = shift; if (my ($root, $children) = $tree =~ /^(.+?)\((.*)\)$/) { my $depth = 0; for my $pos (0 .. length($children) - 1) { my $char = \substr $children, $pos, 1; if (0 == $depth and ',' eq $$char) { $$char = "\x0"; } elsif ('(' eq $$char) { $depth++; } elsif (')' eq $$char) { $depth--; } } return($root, [map parse($_), split /\x0/, $children]); } else { return $tree; } } sub output { my ($parsed, $prefix) = @_; my $is_root = not defined $prefix; $prefix //= ' '; while (my $member = shift @$parsed) { my $last = !@$parsed || (1 == @$parsed and ref $parsed->[0]); unless ($is_root) { substr $prefix, -3, 1, ' '; substr($prefix, -4, 1) =~ s///; substr $prefix, -2, 1, ref $member ? ' ' : '' if $last; } if (ref $member) { output($member, $prefix . ''); } else { print $prefix, $member, "\n"; } } } my $tree = 'a(b0(c1,c2(d(ef,gh)),c3(i1,i2,i3(jj),i4(kk,m))),b1(C1,C2(D1(E),D2,D3),C3))'; my $parsed = [parse($tree)]; output($parsed);
57Visualize a tree
2perl
tnufg
distcheck <- function(fn, repetitions=1e4, delta=3) { if(is.character(fn)) { fn <- get(fn) } if(!is.function(fn)) { stop("fn is not a function") } samp <- fn(n=repetitions) counts <- table(samp) expected <- repetitions/length(counts) lbound <- expected * (1 - 0.01*delta) ubound <- expected * (1 + 0.01*delta) status <- ifelse(counts < lbound, "under", ifelse(counts > ubound, "over", "okay")) data.frame(value=names(counts), counts=as.vector(counts), status=status) } distcheck(dice7.vec)
59Verify distribution uniformity/Naive
13r
cy795
dset1=c(199809,200665,199607,200270,199649) dset2=c(522573,244456,139979,71531,21461) chi2IsUniform<-function(dataset,significance=0.05){ chi2IsUniform=(chisq.test(dataset)$p.value>significance) } for (ds in list(dset1,dset2)){ print(c("Data set:",ds)) print(chisq.test(ds)) print(paste("uniform?",chi2IsUniform(ds))) }
62Verify distribution uniformity/Chi-squared test
13r
4vk5y
null
61Vigenère cipher
10javascript
lmrcf
public class VLQCode { public static byte[] encode(long n) { int numRelevantBits = 64 - Long.numberOfLeadingZeros(n); int numBytes = (numRelevantBits + 6) / 7; if (numBytes == 0) numBytes = 1; byte[] output = new byte[numBytes]; for (int i = numBytes - 1; i >= 0; i--) { int curByte = (int)(n & 0x7F); if (i != (numBytes - 1)) curByte |= 0x80; output[i] = (byte)curByte; n >>>= 7; } return output; } public static long decode(byte[] b) { long n = 0; for (int i = 0; i < b.length; i++) { int curByte = b[i] & 0xFF; n = (n << 7) | (curByte & 0x7F); if ((curByte & 0x80) == 0) break; } return n; } public static String byteArrayToString(byte[] b) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < b.length; i++) { if (i > 0) sb.append(", "); String s = Integer.toHexString(b[i] & 0xFF); if (s.length() < 2) s = "0" + s; sb.append(s); } return sb.toString(); } public static void main(String[] args) { long[] testNumbers = { 2097152, 2097151, 1, 127, 128, 589723405834L }; for (long n : testNumbers) { byte[] encoded = encode(n); long decoded = decode(encoded); System.out.println("Original input=" + n + ", encoded = [" + byteArrayToString(encoded) + "], decoded=" + decoded + ", " + ((n == decoded) ? "OK" : "FAIL")); } } }
64Variable-length quantity
9java
swiq0
numeric digits 100 z = 12345678901111111112222222222333333333344444444445555555555.66 n =-12345678901111111112222222222333333333344444444445555555555.66
65Variable size/Set
3python
bjakr
println(s"A Byte variable has a range of: ${Byte.MinValue} to ${Byte.MaxValue}") println(s"A Short variable has a range of: ${Short.MinValue} to ${Short.MaxValue}") println(s"An Int variable has a range of: ${Int.MinValue} to ${Int.MaxValue}") println(s"A Long variable has a range of: ${Long.MinValue} to ${Long.MaxValue}") println(s"A Float variable has a range of: ${Float.MinValue} to ${Float.MaxValue}") println(s"A Double variable has a range of: ${Double.MinValue} to ${Double.MaxValue}")
65Variable size/Set
16scala
xa0wg
use File::Find qw(find); my $dir = '.'; my $pattern = 'foo'; my $callback = sub { print $File::Find::name, "\n" if /$pattern/ }; find $callback, $dir;
58Walk a directory/Recursively
2perl
gue4e
def water_collected(tower): N = len(tower) highest_left = [0] + [max(tower[:n]) for n in range(1,N)] highest_right = [max(tower[n:N]) for n in range(1,N)] + [0] water_level = [max(min(highest_left[n], highest_right[n]) - tower[n], 0) for n in range(N)] print(, highest_left) print(, highest_right) print(, water_level) print(, tower) print(, sum(water_level)) print() return sum(water_level) towers = [[1, 5, 3, 7, 2], [5, 3, 7, 2, 6, 4, 5, 9, 1, 2], [2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1], [5, 5, 5, 5], [5, 6, 7, 8], [8, 7, 7, 6], [6, 7, 10, 7, 6]] [water_collected(tower) for tower in towers]
56Water collected between towers
3python
swyq9
def distcheck(n, delta=1) unless block_given? raise ArgumentError, end h = Hash.new(0) n.times {h[ yield ] += 1} target = 1.0 * n / h.length h.each do |key, value| if (value - target).abs > 0.01 * delta * n raise StandardError, end end puts h.sort.map{|k, v| } end if __FILE__ == $0 begin distcheck(100_000) {rand(10)} distcheck(100_000) {rand > 0.95} rescue StandardError => e p e end end
59Verify distribution uniformity/Naive
14ruby
4v15p
const RADIX = 7; const MASK = 2**RADIX - 1; const octetify = (n)=> { if (n >= 2147483648) { throw new RangeError("Variable Length Quantity not supported for numbers >= 2147483648"); } const octets = []; for (let i = n; i != 0; i >>>= RADIX) { octets.push((((i & MASK) + (octets.empty ? 0 : (MASK + 1))))); } octets.reverse(); return octets; }; const deoctetify = (octets)=> octets.reduce((n, octet)=> (n << RADIX) + (octet & MASK) , 0);
64Variable-length quantity
10javascript
n8ziy
void varstrings(int count, ...) { va_list args; va_start(args, count); while (count--) puts(va_arg(args, const char *)); va_end(args); } varstrings(5, , , , , );
67Variadic function
5c
sw0q5
printf(, sizeof(int));
68Variable size/Get
5c
oso80
package main import "fmt" type vector []float64 func (v vector) add(v2 vector) vector { r := make([]float64, len(v)) for i, vi := range v { r[i] = vi + v2[i] } return r } func (v vector) sub(v2 vector) vector { r := make([]float64, len(v)) for i, vi := range v { r[i] = vi - v2[i] } return r } func (v vector) scalarMul(s float64) vector { r := make([]float64, len(v)) for i, vi := range v { r[i] = vi * s } return r } func (v vector) scalarDiv(s float64) vector { r := make([]float64, len(v)) for i, vi := range v { r[i] = vi / s } return r } func main() { v1 := vector{5, 7} v2 := vector{2, 3} fmt.Println(v1.add(v2)) fmt.Println(v1.sub(v2)) fmt.Println(v1.scalarMul(11)) fmt.Println(v1.scalarDiv(2)) }
66Vector
0go
52gul
function findFiles($dir = '.', $pattern = '/./'){ $prefix = $dir . '/'; $dir = dir($dir); while (false !== ($file = $dir->read())){ if ($file === '.' || $file === '..') continue; $file = $prefix . $file; if (is_dir($file)) findFiles($file, $pattern); if (preg_match($pattern, $file)){ echo $file . ; } } } findFiles('./foo', '/\.bar$/');
58Walk a directory/Recursively
12php
n8cig
object DistrubCheck1 extends App { private def distCheck(f: () => Int, nRepeats: Int, delta: Double): Unit = { val counts = scala.collection.mutable.Map[Int, Int]() for (_ <- 0 until nRepeats) counts.updateWith(f()) { case Some(count) => Some(count + 1) case None => Some(1) } val target: Double = nRepeats.toDouble / counts.size val deltaCount: Int = (delta / 100.0 * target).toInt counts.foreach { case (k, v) => if (math.abs(target - v) >= deltaCount) println(f"distribution potentially skewed for $k%s: $v%d") } counts.toIndexedSeq.foreach(entry => println(f"${entry._1}%d ${entry._2}%d")) } distCheck(() => 1 + util.Random.nextInt(5), 1_000_000, 1) }
59Verify distribution uniformity/Naive
16scala
jgx7i
int main() { int i, gprev = 0; int s[7] = {1, 2, 2, 3, 4, 4, 5}; for (i = 0; i < 7; ++i) { int curr = s[i]; int prev = 0; if (i > 0 && curr == prev) printf(, i); prev = curr; } for (i = 0; i < 7; ++i) { int curr = s[i]; if (i > 0 && curr == gprev) printf(, i); gprev = curr; } return 0; }
69Variable declaration reset
5c
1hbpj
null
64Variable-length quantity
11kotlin
abq13
import groovy.transform.EqualsAndHashCode @EqualsAndHashCode class Vector { private List<Number> elements Vector(List<Number> e ) { if (!e) throw new IllegalArgumentException("A Vector must have at least one element.") if (!e.every { it instanceof Number }) throw new IllegalArgumentException("Every element must be a number.") elements = [] + e } Vector(Number... e) { this(e as List) } def order() { elements.size() } def norm2() { elements.sum { it ** 2 } ** 0.5 } def plus(Vector that) { if (this.order() != that.order()) throw new IllegalArgumentException("Vectors must be conformable for addition.") [this.elements,that.elements].transpose()*.sum() as Vector } def minus(Vector that) { this + (-that) } def multiply(Number that) { this.elements.collect { it * that } as Vector } def div(Number that) { this * (1/that) } def negative() { this * -1 } String toString() { "(${elements.join(',')})" } } class VectorCategory { static Vector plus (Number a, Vector b) { b + a } static Vector minus (Number a, Vector b) { -b + a } static Vector multiply (Number a, Vector b) { b * a } }
66Vector
7groovy
cy29i
def gammaInc_Q(a, x) a1, a2 = a-1, a-2 f0 = lambda {|t| t**a1 * Math.exp(-t)} df0 = lambda {|t| (a1-t) * t**a2 * Math.exp(-t)} y = a1 y += 0.3 while f0[y]*(x-y) > 2.0e-8 and y < x y = x if y > x h = 3.0e-4 n = (y/h).to_i h = y/n hh = 0.5 * h sum = 0 (n-1).step(0, -1) do |j| t = h * j sum += f0[t] + hh * df0[t] end h * sum / gamma_spounge(a) end A = 12 k1_factrl = 1.0 coef = [Math.sqrt(2.0*Math::PI)] COEF = (1...A).each_with_object(coef) do |k,c| c << Math.exp(A-k) * (A-k)**(k-0.5) / k1_factrl k1_factrl *= -k end def gamma_spounge(z) accm = (1...A).inject(COEF[0]){|res,k| res += COEF[k] / (z+k)} accm * Math.exp(-(z+A)) * (z+A)**(z+0.5) / z end def chi2UniformDistance(dataSet) expected = dataSet.inject(:+).to_f / dataSet.size dataSet.map{|d|(d-expected)**2}.inject(:+) / expected end def chi2Probability(dof, distance) 1.0 - gammaInc_Q(0.5*dof, 0.5*distance) end def chi2IsUniform(dataSet, significance=0.05) dof = dataSet.size - 1 dist = chi2UniformDistance(dataSet) chi2Probability(dof, dist) > significance end dsets = [ [ 199809, 200665, 199607, 200270, 199649 ], [ 522573, 244456, 139979, 71531, 21461 ] ] for ds in dsets puts dof = ds.size - 1 puts % dof distance = chi2UniformDistance(ds) puts % distance puts % chi2Probability(dof, distance) puts % (chi2IsUniform(ds)? : ) end
62Verify distribution uniformity/Chi-squared test
14ruby
k7whg
null
61Vigenère cipher
11kotlin
domnz
Python 3.2.3 (default, May 3 2012, 15:54:42) [GCC 4.6.3] on linux2 Type , or for more information. >>> help('pprint.pprint') Help on function pprint in pprint: pprint.pprint = pprint(object, stream=None, indent=1, width=80, depth=None) Pretty-print a Python object to a stream [default is sys.stdout]. >>> from pprint import pprint >>> for tree in [ (1, 2, 3, 4, 5, 6, 7, 8), (1, (( 2, 3 ), (4, (5, ((6, 7), 8))))), ((((1, 2), 3), 4), 5, 6, 7, 8) ]: print(% (tree, )) pprint(tree, indent=1, width=1) Tree (1, 2, 3, 4, 5, 6, 7, 8) can be pprint'd as: (1, 2, 3, 4, 5, 6, 7, 8) Tree (1, ((2, 3), (4, (5, ((6, 7), 8))))) can be pprint'd as: (1, ((2, 3), (4, (5, ((6, 7), 8))))) Tree ((((1, 2), 3), 4), 5, 6, 7, 8) can be pprint'd as: ((((1, 2), 3), 4), 5, 6, 7, 8) >>>
57Visualize a tree
3python
zd5tt
(defn foo [& args] (doseq [a args] (println a))) (foo :bar :baz :quux) (apply foo [:bar :baz :quux])
67Variadic function
6clojure
n8dik
add (u,v) (x,y) = (u+x,v+y) minus (u,v) (x,y) = (u-x,v-y) multByScalar k (x,y) = (k*x,k*y) divByScalar (x,y) k = (x/k,y/k) main = do let vecA = (3.0,8.0) let (r,theta) = (3,pi/12) :: (Double,Double) let vecB = (r*(cos theta),r*(sin theta)) putStrLn $ "vecA = " ++ (show vecA) putStrLn $ "vecB = " ++ (show vecB) putStrLn $ "vecA + vecB = " ++ (show.add vecA $ vecB) putStrLn $ "vecA - vecB = " ++ (show.minus vecA $ vecB) putStrLn $ "2 * vecB = " ++ (show.multByScalar 2 $ vecB) putStrLn $ "vecA / 3 = " ++ (show.divByScalar vecA $ 3)
66Vector
8haskell
xasw4
use statrs::function::gamma::gamma_li; fn chi_distance(dataset: &[u32]) -> f64 { let expected = f64::from(dataset.iter().sum::<u32>()) / dataset.len() as f64; dataset .iter() .fold(0., |acc, &elt| acc + (elt as f64 - expected).powf(2.)) / expected } fn chi2_probability(dof: f64, distance: f64) -> f64 { 1. - gamma_li(dof * 0.5, distance * 0.5) } fn chi2_uniform(dataset: &[u32], significance: f64) -> bool { let d = chi_distance(&dataset); chi2_probability(dataset.len() as f64 - 1., d) > significance } fn main() { let dsets = vec![ vec![199809, 200665, 199607, 200270, 199649], vec![522573, 244456, 139979, 71531, 21461], ]; for ds in dsets { println!("Data set: {:?}", ds); let d = chi_distance(&ds); print!("Distance: {:.6} ", d); print!( "Chi2 probability: {:.6} ", chi2_probability(ds.len() as f64 - 1., d) ); print!("Uniform? {}\n", chi2_uniform(&ds, 0.05)); } }
62Verify distribution uniformity/Chi-squared test
15rust
bjxkx
import org.apache.commons.math3.special.Gamma.regularizedGammaQ object ChiSquare extends App { private val dataSets: Seq[Seq[Double]] = Seq( Seq(199809, 200665, 199607, 200270, 199649), Seq(522573, 244456, 139979, 71531, 21461) ) private def 2IsUniform(data: Seq[Double], significance: Double) = 2Prob(data.size - 1.0, 2Dist(data)) > significance private def 2Dist(data: Seq[Double]) = { val avg = data.sum / data.size data.reduce((a, b) => a + math.pow(b - avg, 2)) / avg } private def 2Prob(dof: Double, distance: Double) = regularizedGammaQ(dof / 2, distance / 2) printf("%4s%10s %12s%8s %s%n", "d.f.", "distance", "probability", "Uniform?", "dataset") dataSets.foreach { ds => val (dist, dof) = (2Dist(ds), ds.size - 1) printf("%4d%11.3f %13.8f %5s %6s%n", dof, dist, 2Prob(dof.toDouble, dist), if (2IsUniform(ds, 0.05)) "YES" else "NO", ds.mkString(", ")) } }
62Verify distribution uniformity/Chi-squared test
16scala
ab01n
package main import "fmt" func main() { s := []int{1, 2, 2, 3, 4, 4, 5}
69Variable declaration reset
0go
yt364
import java.util.Locale; public class Test { public static void main(String[] args) { System.out.println(new Vec2(5, 7).add(new Vec2(2, 3))); System.out.println(new Vec2(5, 7).sub(new Vec2(2, 3))); System.out.println(new Vec2(5, 7).mult(11)); System.out.println(new Vec2(5, 7).div(2)); } } class Vec2 { final double x, y; Vec2(double x, double y) { this.x = x; this.y = y; } Vec2 add(Vec2 v) { return new Vec2(x + v.x, y + v.y); } Vec2 sub(Vec2 v) { return new Vec2(x - v.x, y - v.y); } Vec2 div(double val) { return new Vec2(x / val, y / val); } Vec2 mult(double val) { return new Vec2(x * val, y * val); } @Override public String toString() { return String.format(Locale.US, "[%s,%s]", x, y); } }
66Vector
9java
bj1k3
def a(array) n=array.length left={} right={} left[0]=array[0] i=1 loop do break if i >=n left[i]=[left[i-1],array[i]].max i += 1 end right[n-1]=array[n-1] i=n-2 loop do break if i<0 right[i]=[right[i+1],array[i]].max i-=1 end i=0 water=0 loop do break if i>=n water+=[left[i],right[i]].min-array[i] i+=1 end puts water end a([ 5, 3, 7, 2, 6, 4, 5, 9, 1, 2 ]) a([ 2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1 ]) a([ 5, 5, 5, 5 ]) a([ 5, 6, 7, 8 ]) a([ 8, 7, 7, 6 ]) a([ 6, 7, 10, 7, 6 ]) return
56Water collected between towers
14ruby
8q901
public class VariableDeclarationReset { public static void main(String[] args) { int[] s = {1, 2, 2, 3, 4, 4, 5};
69Variable declaration reset
9java
5lvuf
<!DOCTYPE html> <html lang="en" > <head> <meta charset="utf-8"/> <meta name="viewport" content="width=device-width, initial-scale=1"/> <title>variable declaration reset</title> </head> <body> <script> "use strict"; let s = [1, 2, 2, 3, 4, 4, 5]; for (let i=0; i<7; i+=1) { let curr = s[i], prev; if (i>0 && (curr===prev)) { console.log(i); } prev = curr; } </script> </body> </html>
69Variable declaration reset
10javascript
j4r7n
typedef uint64_t xint; typedef unsigned long long ull; xint tens[20]; inline xint max(xint a, xint b) { return a > b ? a : b; } inline xint min(xint a, xint b) { return a < b ? a : b; } inline int ndigits(xint x) { int n = 0; while (x) n++, x /= 10; return n; } inline xint dtally(xint x) { xint t = 0; while (x) t += 1<<((x%10) * 6), x /= 10; return t; } int fangs(xint x, xint *f) { int n = 0; int nd = ndigits(x); if (nd & 1) return 0; nd /= 2; xint lo, hi; lo = max(tens[nd-1], (x + tens[nd] - 2)/ (tens[nd] - 1)); hi = min(x / lo, sqrt(x)); xint a, b, t = dtally(x); for (a = lo; a <= hi; a++) { b = x / a; if (a * b == x && ((a%10) || (b%10)) && t == dtally(a) + dtally(b)) f[n++] = a; } return n; } void show_fangs(xint x, xint *f, xint cnt) { printf(, (ull)x); int i; for (i = 0; i < cnt; i++) printf(, (ull)f[i], (ull)(x / f[i])); putchar('\n'); } int main(void) { int i, j, n; xint x, f[16], bigs[] = {16758243290880ULL, 24959017348650ULL, 14593825548650ULL, 0}; tens[0] = 1; for (i = 1; i < 20; i++) tens[i] = tens[i-1] * 10; for (x = 1, n = 0; n < 25; x++) { if (!(j = fangs(x, f))) continue; printf(, ++n); show_fangs(x, f, j); } putchar('\n'); for (i = 0; bigs[i]; i++) { if ((j = fangs(bigs[i], f))) show_fangs(bigs[i], f, j); else printf(, (ull)bigs[i]); } return 0; }
70Vampire number
5c
tinf4
use warnings; use strict; for my $testcase ( 0, 0xa, 123, 254, 255, 256, 257, 65534, 65535, 65536, 65537, 0x1fffff, 0x200000 ) { my @vlq = vlq_encode($testcase); printf "%8s%12s%8s\n", $testcase, ( join ':', @vlq ), vlq_decode(@vlq); } sub vlq_encode { my @vlq; my $binary = sprintf "%s%b", 0 x 7, shift; $binary =~ s/(.{7})$//; @vlq = ( unpack 'H2', ( pack 'B8', '0' . $1 ) ); while ( 0 + $binary ) { $binary =~ s/(.{7})$//; unshift @vlq, ( unpack 'H2', pack 'B8', '1' . $1 ); } return @vlq; } sub vlq_decode { my $num; $num .= sprintf "%07b", hex(shift @_) & 0x7f while @_; return oct '0b' . $num; }
64Variable-length quantity
2perl
96vmn
function Encrypt( _msg, _key ) local msg = { _msg:upper():byte( 1, -1 ) } local key = { _key:upper():byte( 1, -1 ) } local enc = {} local j, k = 1, 1 for i = 1, #msg do if msg[i] >= string.byte('A') and msg[i] <= string.byte('Z') then enc[k] = ( msg[i] + key[j] - 2*string.byte('A') ) % 26 + string.byte('A') k = k + 1 if j == #key then j = 1 else j = j + 1 end end end return string.char( unpack(enc) ) end function Decrypt( _msg, _key ) local msg = { _msg:byte( 1, -1 ) } local key = { _key:upper():byte( 1, -1 ) } local dec = {} local j = 1 for i = 1, #msg do dec[i] = ( msg[i] - key[j] + 26 ) % 26 + string.byte('A') if j == #key then j = 1 else j = j + 1 end end return string.char( unpack(dec) ) end original = "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!" key = "VIGENERECIPHER"; encrypted = Encrypt( original, key ) decrypted = Decrypt( encrypted, key ) print( encrypted ) print( decrypted )
61Vigenère cipher
1lua
fi9dp
root = BinaryTreeNode.from_array [1, [2, [4, 7], [5]], [3, [6, [8], [9]]]]
57Visualize a tree
14ruby
6tg3t
extern crate rustc_serialize; extern crate term_painter; use rustc_serialize::json; use std::fmt::{Debug, Display, Formatter, Result}; use term_painter::ToStyle; use term_painter::Color::*; type NodePtr = Option<usize>; #[derive(Debug, PartialEq, Clone, Copy)] enum Side { Left, Right, Up, } #[derive(Debug, PartialEq, Clone, Copy)] enum DisplayElement { TrunkSpace, SpaceLeft, SpaceRight, SpaceSpace, Root, } impl DisplayElement { fn string(&self) -> String { match *self { DisplayElement::TrunkSpace => " ".to_string(), DisplayElement::SpaceRight => " ".to_string(), DisplayElement::SpaceLeft => " ".to_string(), DisplayElement::SpaceSpace => " ".to_string(), DisplayElement::Root => "".to_string(), } } } #[derive(Debug, Clone, Copy, RustcDecodable, RustcEncodable)] struct Node<K, V> { key: K, value: V, left: NodePtr, right: NodePtr, up: NodePtr, } impl<K: Ord + Copy, V: Copy> Node<K, V> { pub fn get_ptr(&self, side: Side) -> NodePtr { match side { Side::Up => self.up, Side::Left => self.left, _ => self.right, } } } #[derive(Debug, RustcDecodable, RustcEncodable)] struct Tree<K, V> { root: NodePtr, store: Vec<Node<K, V>>, } impl<K: Ord + Copy + Debug + Display, V: Debug + Copy + Display> Tree<K, V> { pub fn get_node(&self, np: NodePtr) -> Node<K, V> { assert!(np.is_some()); self.store[np.unwrap()] } pub fn get_pointer(&self, np: NodePtr, side: Side) -> NodePtr { assert!(np.is_some()); self.store[np.unwrap()].get_ptr(side) }
57Visualize a tree
15rust
yzr68
use std::cmp::min; fn getfill(pattern: &[usize]) -> usize { let mut total = 0; for (idx, val) in pattern.iter().enumerate() { let l_peak = pattern[..idx].iter().max(); let r_peak = pattern[idx + 1..].iter().max(); if l_peak.is_some() && r_peak.is_some() { let peak = min(l_peak.unwrap(), r_peak.unwrap()); if peak > val { total += peak - val; } } } total } fn main() { let patterns = vec![ vec![1, 5, 3, 7, 2], vec![5, 3, 7, 2, 6, 4, 5, 9, 1, 2], vec![2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1], vec![5, 5, 5, 5], vec![5, 6, 7, 8], vec![8, 7, 7, 6], vec![6, 7, 10, 7, 6], ]; for pattern in patterns { println!("pattern: {:?}, fill: {}", &pattern, getfill(&pattern)); } }
56Water collected between towers
15rust
osc83
@s = <1 2 2 3 4 4 5>; for ($i = 0; $i < 7; $i++) { $curr = $s[$i]; if ($i > 1 and $curr == $prev) { print "$i\n" } $prev = $curr; }
69Variable declaration reset
2perl
x1ew8
null
66Vector
11kotlin
r5jgo
from pathlib import Path for path in Path('.').rglob('*.*'): print(path)
58Walk a directory/Recursively
3python
r5wgq
dir("/bar/foo", "mp3",recursive=T)
58Walk a directory/Recursively
13r
ulpvx
import scala.collection.parallel.CollectionConverters.VectorIsParallelizable
56Water collected between towers
16scala
dovng
def tobits(n, _group=8, _sep='_', _pad=False): 'Express n as binary bits with separator' bits = '{0:b}'.format(n)[::-1] if _pad: bits = '{0:0{1}b}'.format(n, ((_group+len(bits)-1) answer = _sep.join(bits[i:i+_group] for i in range(0, len(bits), _group))[::-1] answer = '0'*(len(_sep)-1) + answer else: answer = _sep.join(bits[i:i+_group] for i in range(0, len(bits), _group))[::-1] return answer def tovlq(n): return tobits(n, _group=7, _sep='1_', _pad=True) def toint(vlq): return int(''.join(vlq.split('_1')), 2) def vlqsend(vlq): for i, byte in enumerate(vlq.split('_')[::-1]): print('Sent byte {0:3}: {1:
64Variable-length quantity
3python
cyu9q
import "unsafe" unsafe.Sizeof(x)
68Variable size/Get
0go
4v452
vector = {mt = {}} function vector.new (x, y) local new = {x = x or 0, y = y or 0} setmetatable(new, vector.mt) return new end function vector.mt.__add (v1, v2) return vector.new(v1.x + v2.x, v1.y + v2.y) end function vector.mt.__sub (v1, v2) return vector.new(v1.x - v2.x, v1.y - v2.y) end function vector.mt.__mul (v, s) return vector.new(v.x * s, v.y * s) end function vector.mt.__div (v, s) return vector.new(v.x / s, v.y / s) end function vector.print (vec) print("(" .. vec.x .. ", " .. vec.y .. ")") end local a, b = vector.new(5, 7), vector.new(2, 3) vector.print(a + b) vector.print(a - b) vector.print(a * 11) vector.print(a / 2)
66Vector
1lua
74hru
s = [1, 2, 2, 3, 4, 4, 5] for i in range(len(s)): curr = s[i] if i > 0 and curr == prev: print(i) prev = curr
69Variable declaration reset
3python
qawxi
(defn factor-pairs [n] (for [x (range 2 (Math/sqrt n)) :when (zero? (mod n x))] [x (quot n x)])) (defn fangs [n] (let [dlen (comp count str) half (/ (dlen n) 2) halves? #(apply = (cons half (map dlen %))) digits #(sort (apply str %))] (filter #(and (halves? %) (= (sort (str n)) (digits %))) (factor-pairs n)))) (defn vampiric? [n] (let [fangs (fangs n)] (if (empty? fangs) nil [n fangs]))) (doseq [n (take 25 (keep vampiric? (range)))] (prn n)) (doseq [n [16758243290880, 24959017348650, 14593825548650]] (println (or (vampiric? n) (str n " is not vampiric."))))
70Vampire number
6clojure
mz3yq
import Foreign sizeOf (undefined :: Int) sizeOf (undefined :: Double) sizeOf (undefined :: Bool) sizeOf (undefined :: Ptr a)
68Variable size/Get
8haskell
qeqx9
int check_isin(char *a) { int i, j, k, v, s[24]; j = 0; for(i = 0; i < 12; i++) { k = a[i]; if(k >= '0' && k <= '9') { if(i < 2) return 0; s[j++] = k - '0'; } else if(k >= 'A' && k <= 'Z') { if(i == 11) return 0; k -= 'A' - 10; s[j++] = k / 10; s[j++] = k % 10; } else { return 0; } } if(a[i]) return 0; v = 0; for(i = j - 2; i >= 0; i -= 2) { k = 2 * s[i]; v += k > 9 ? k - 9 : k; } for(i = j - 1; i >= 0; i -= 2) { v += s[i]; } return v % 10 == 0; } int main() { char *test[7] = {, , , , , , }; int i; for(i = 0; i < 7; i++) printf(, check_isin(test[i]) ? 'T' : 'F', i == 6 ? '\n' : ' '); return 0; }
71Validate International Securities Identification Number
5c
2mmlo
null
68Variable size/Get
11kotlin
747r4
null
56Water collected between towers
17swift
0xms6
typedef struct{ float i,j,k; }Vector; Vector a = {3, 4, 5},b = {4, 3, 5},c = {-5, -12, -13}; float dotProduct(Vector a, Vector b) { return a.i*b.i+a.j*b.j+a.k*b.k; } Vector crossProduct(Vector a,Vector b) { Vector c = {a.j*b.k - a.k*b.j, a.k*b.i - a.i*b.k, a.i*b.j - a.j*b.i}; return c; } float scalarTripleProduct(Vector a,Vector b,Vector c) { return dotProduct(a,crossProduct(b,c)); } Vector vectorTripleProduct(Vector a,Vector b,Vector c) { return crossProduct(a,crossProduct(b,c)); } void printVector(Vector a) { printf(,a.i,a.j,a.k); } int main() { printf(); printVector(a); printf(); printVector(b); printf(); printVector(c); printf(,dotProduct(a,b)); printf(); printVector(crossProduct(a,b)); printf(,scalarTripleProduct(a,b,c)); printf(); printVector(vectorTripleProduct(a,b,c)); return 0; }
72Vector products
5c
pj7by
void vc(int n, int base, int *num, int *denom) { int p = 0, q = 1; while (n) { p = p * base + (n % base); q *= base; n /= base; } *num = p; *denom = q; while (p) { n = p; p = q % p; q = n; } *num /= q; *denom /= q; } int main() { int d, n, i, b; for (b = 2; b < 6; b++) { printf(, b); for (i = 0; i < 10; i++) { vc(i, b, &n, &d); if (n) printf(, n, d); else printf(); } printf(); } return 0; }
73Van der Corput sequence
5c
wpkec
[0x200000, 0x1fffff].each do |i| ber = [i].pack() hex = ber.unpack().collect {|c| % c}.join() printf , i, hex j = ber.unpack().first i == j or fail end
64Variable-length quantity
14ruby
294lw
object VlqCode { def encode(x:Long)={ val result=scala.collection.mutable.Stack[Byte]() result push (x&0x7f).toByte var l = x >>> 7 while(l>0){ result push ((l&0x7f)|0x80).toByte l >>>= 7 } result.toArray } def decode(a:Array[Byte])=a.foldLeft(0L)((r, b) => r<<7|b&0x7f) def toString(a:Array[Byte])=a map("%02x".format(_)) mkString("[", ", ", "]") def test(x:Long)={ val enc=encode(x) println("0x%x =>%s => 0x%x".format(x, toString(enc), decode(enc))) } def main(args: Array[String]): Unit = { val xs=Seq(0, 0x7f, 0x80, 0x2000, 0x3fff, 0x4000, 0x1FFFFF, 0x200000, 0x8000000, 0xFFFFFFF, 0xFFFFFFFFL, 0x842FFFFFFFFL, 0x0FFFFFFFFFFFFFFFL) xs foreach test } }
64Variable-length quantity
16scala
4vj50
> s = "hello" > print(#s) 5 > t = { 1,2,3,4,5 } > print(#t) 5
68Variable size/Get
1lua
jgj71
<?php function printTree( array $tree , string $key = , string $stack = , $first = TRUE , $firstPadding = NULL ) { if ( gettype($tree) == ) { if($firstPadding === NULL) $firstPadding = ( count($tree)>1 )? : ; echo $key . PHP_EOL ; foreach ($tree as $key => $value) { if ($key === array_key_last($tree)){ echo (($first)? : $firstPadding ) . $stack . ; $padding = ; if($first) $firstPadding = ; } else { echo (($first)? : $firstPadding ) . $stack . ; $padding = ; } if( is_array($value) )printTree( $value , $key , $stack . (($first)? : $padding ) , FALSE , $firstPadding ); else echo $key . . $value . PHP_EOL; } } else echo $tree . PHP_EOL; } $sample_array_1 = [ 0 => [ 'item_id' => 6, 'price' => , 'qty' => 12, 'discount' => 0 ], 1 => [ 'item_id' => 7, 'price' => , 'qty' => 1, 'discount' => 12 ], 2 => [ 'item_id' => 8, 'price' => , 'qty' => 0, 'discount' => 24 ] ]; $sample_array_2 = array( array( =>, =>, =>, =>, =>, =>array( =>, =>array( => ) ) ) ); $sample_array_3 = [ => [ =>[ , => [ , , => [ , , ] ], , ] , => [ => [ => [1]] ] ] ]; $sample_array_4 = []; $sample_array_5 = []; $sample_array_5 = []; $sample_array_6 = [ , , , , , , , , , , , ]; printTree($sample_array_1); echo PHP_EOL . . PHP_EOL; printTree($sample_array_2); echo PHP_EOL . . PHP_EOL; printTree($sample_array_3); echo PHP_EOL . . PHP_EOL; printTree($sample_array_4); echo PHP_EOL . . PHP_EOL; printTree($sample_array_5); echo PHP_EOL . . PHP_EOL; printTree($sample_array_6); ?>
57Visualize a tree
12php
k78hv