{ // 获取包含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 }); }); } })(); \"\nXML_PRETTY = \"\"\"\\\n\n \n

test1

\n

test2

\n \n\n\"\"\"\nXML_DICT = {'body': {'h2': 'test2', 'h1': 'test1'}}\n\n\n@unittest.skipUnless(etree, 'lxml not installed')\nclass XMLTestCase(TestCase):\n def test_pretty_xml(self):\n "},"suffix":{"kind":"string","value":"\n\n def test_element_to_dict(self):\n self.assertEqual(element_to_dict(etree.XML(XML_DATA)), XML_DICT)\n\n def test_xml_to_dict(self):\n self.assertEqual(xml_to_dict(XML_DATA), XML_DICT)\n"},"middle":{"kind":"string","value":"self.assertEqual(pretty_xml(XML_DATA), XML_PRETTY)"},"fim_type":{"kind":"string","value":"identifier_body"}}},{"rowIdx":236033,"cells":{"file_name":{"kind":"string","value":"test_xml.py"},"prefix":{"kind":"string","value":"from utile import pretty_xml, xml_to_dict, element_to_dict\nfrom testsuite.support import etree, TestCase"},"suffix":{"kind":"string","value":"import unittest\n\nXML_DATA = \"

test1

test2

\"\nXML_PRETTY = \"\"\"\\\n\n \n

test1

\n

test2

\n \n\n\"\"\"\nXML_DICT = {'body': {'h2': 'test2', 'h1': 'test1'}}\n\n\n@unittest.skipUnless(etree, 'lxml not installed')\nclass XMLTestCase(TestCase):\n def test_pretty_xml(self):\n self.assertEqual(pretty_xml(XML_DATA), XML_PRETTY)\n\n def test_element_to_dict(self):\n self.assertEqual(element_to_dict(etree.XML(XML_DATA)), XML_DICT)\n\n def test_xml_to_dict(self):\n self.assertEqual(xml_to_dict(XML_DATA), XML_DICT)"},"middle":{"kind":"string","value":""},"fim_type":{"kind":"string","value":"random_line_split"}}},{"rowIdx":236034,"cells":{"file_name":{"kind":"string","value":"test_xml.py"},"prefix":{"kind":"string","value":"\nfrom utile import pretty_xml, xml_to_dict, element_to_dict\nfrom testsuite.support import etree, TestCase\nimport unittest\n\nXML_DATA = \"

test1

test2

\"\nXML_PRETTY = \"\"\"\\\n\n \n

test1

\n

test2

\n \n\n\"\"\"\nXML_DICT = {'body': {'h2': 'test2', 'h1': 'test1'}}\n\n\n@unittest.skipUnless(etree, 'lxml not installed')\nclass XMLTestCase(TestCase):\n def test_pretty_xml(self):\n self.assertEqual(pretty_xml(XML_DATA), XML_PRETTY)\n\n def test_element_to_dict(self):\n self.assertEqual(element_to_dict(etree.XML(XML_DATA)), XML_DICT)\n\n def "},"suffix":{"kind":"string","value":"(self):\n self.assertEqual(xml_to_dict(XML_DATA), XML_DICT)\n"},"middle":{"kind":"string","value":"test_xml_to_dict"},"fim_type":{"kind":"string","value":"identifier_name"}}},{"rowIdx":236035,"cells":{"file_name":{"kind":"string","value":"aliased.rs"},"prefix":{"kind":"string","value":"use backend::Backend;\nuse expression::{Expression, NonAggregate, SelectableExpression};\nuse query_builder::*;\nuse query_builder::nodes::{Identifier, InfixNode};\nuse query_source::*;\n\n#[derive(Debug, Clone, Copy)]\npub struct "},"suffix":{"kind":"string","value":"<'a, Expr> {\n expr: Expr,\n alias: &'a str,\n}\n\nimpl<'a, Expr> Aliased<'a, Expr> {\n pub fn new(expr: Expr, alias: &'a str) -> Self {\n Aliased {\n expr: expr,\n alias: alias,\n }\n }\n}\n\npub struct FromEverywhere;\n\nimpl<'a, T> Expression for Aliased<'a, T> where\n T: Expression,\n{\n type SqlType = T::SqlType;\n}\n\nimpl<'a, T, DB> QueryFragment for Aliased<'a, T> where\n DB: Backend,\n T: QueryFragment,\n{\n fn to_sql(&self, out: &mut DB::QueryBuilder) -> BuildQueryResult {\n out.push_identifier(&self.alias)\n }\n}\n\n// FIXME This is incorrect, should only be selectable from WithQuerySource\nimpl<'a, T, QS> SelectableExpression for Aliased<'a, T> where\n Aliased<'a, T>: Expression,\n{\n}\n\nimpl<'a, T: Expression + Copy> QuerySource for Aliased<'a, T> {\n type FromClause = InfixNode<'static, T, Identifier<'a>>;\n\n fn from_clause(&self) -> Self::FromClause {\n InfixNode::new(self.expr, Identifier(self.alias), \" \")\n }\n}\n\nimpl<'a, T> NonAggregate for Aliased<'a, T> where Aliased<'a, T>: Expression {\n}\n"},"middle":{"kind":"string","value":"Aliased"},"fim_type":{"kind":"string","value":"identifier_name"}}},{"rowIdx":236036,"cells":{"file_name":{"kind":"string","value":"aliased.rs"},"prefix":{"kind":"string","value":"use backend::Backend;\nuse expression::{Expression, NonAggregate, SelectableExpression};\nuse query_builder::*;\nuse query_builder::nodes::{Identifier, InfixNode};\nuse query_source::*;\n\n#[derive(Debug, Clone, Copy)]\npub struct Aliased<'a, Expr> {\n expr: Expr,\n alias: &'a str,\n}\n\nimpl<'a, Expr> Aliased<'a, Expr> {\n pub fn new(expr: Expr, alias: &'a str) -> Self {\n Aliased {\n expr: expr,\n alias: alias,\n }\n }\n}\n\npub struct FromEverywhere;\n\nimpl<'a, T> Expression for Aliased<'a, T> where\n T: Expression,\n{\n type SqlType = T::SqlType;\n}"},"suffix":{"kind":"string","value":" fn to_sql(&self, out: &mut DB::QueryBuilder) -> BuildQueryResult {\n out.push_identifier(&self.alias)\n }\n}\n\n// FIXME This is incorrect, should only be selectable from WithQuerySource\nimpl<'a, T, QS> SelectableExpression for Aliased<'a, T> where\n Aliased<'a, T>: Expression,\n{\n}\n\nimpl<'a, T: Expression + Copy> QuerySource for Aliased<'a, T> {\n type FromClause = InfixNode<'static, T, Identifier<'a>>;\n\n fn from_clause(&self) -> Self::FromClause {\n InfixNode::new(self.expr, Identifier(self.alias), \" \")\n }\n}\n\nimpl<'a, T> NonAggregate for Aliased<'a, T> where Aliased<'a, T>: Expression {\n}"},"middle":{"kind":"string","value":"\nimpl<'a, T, DB> QueryFragment for Aliased<'a, T> where\n DB: Backend,\n T: QueryFragment,\n{"},"fim_type":{"kind":"string","value":"random_line_split"}}},{"rowIdx":236037,"cells":{"file_name":{"kind":"string","value":"aliased.rs"},"prefix":{"kind":"string","value":"use backend::Backend;\nuse expression::{Expression, NonAggregate, SelectableExpression};\nuse query_builder::*;\nuse query_builder::nodes::{Identifier, InfixNode};\nuse query_source::*;\n\n#[derive(Debug, Clone, Copy)]\npub struct Aliased<'a, Expr> {\n expr: Expr,\n alias: &'a str,\n}\n\nimpl<'a, Expr> Aliased<'a, Expr> {\n pub fn new(expr: Expr, alias: &'a str) -> Self "},"suffix":{"kind":"string","value":"\n}\n\npub struct FromEverywhere;\n\nimpl<'a, T> Expression for Aliased<'a, T> where\n T: Expression,\n{\n type SqlType = T::SqlType;\n}\n\nimpl<'a, T, DB> QueryFragment for Aliased<'a, T> where\n DB: Backend,\n T: QueryFragment,\n{\n fn to_sql(&self, out: &mut DB::QueryBuilder) -> BuildQueryResult {\n out.push_identifier(&self.alias)\n }\n}\n\n// FIXME This is incorrect, should only be selectable from WithQuerySource\nimpl<'a, T, QS> SelectableExpression for Aliased<'a, T> where\n Aliased<'a, T>: Expression,\n{\n}\n\nimpl<'a, T: Expression + Copy> QuerySource for Aliased<'a, T> {\n type FromClause = InfixNode<'static, T, Identifier<'a>>;\n\n fn from_clause(&self) -> Self::FromClause {\n InfixNode::new(self.expr, Identifier(self.alias), \" \")\n }\n}\n\nimpl<'a, T> NonAggregate for Aliased<'a, T> where Aliased<'a, T>: Expression {\n}\n"},"middle":{"kind":"string","value":"{\n Aliased {\n expr: expr,\n alias: alias,\n }\n }"},"fim_type":{"kind":"string","value":"identifier_body"}}},{"rowIdx":236038,"cells":{"file_name":{"kind":"string","value":"font.rs"},"prefix":{"kind":"string","value":"/* This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http://mozilla.org/MPL/2.0/. */\n\nuse euclid::{Point2D, Rect, Size2D};\nuse smallvec::SmallVec;\nuse std::borrow::ToOwned;\nuse std::cell::RefCell;\nuse std::mem;\nuse std::rc::Rc;\nuse std::slice;\nuse std::sync::Arc;\nuse style::computed_values::{font_stretch, font_variant, font_weight};\nuse style::properties::style_structs::Font as FontStyle;\nuse util::cache::HashCache;\n\nuse font_template::FontTemplateDescriptor;\nuse platform::font::{FontHandle, FontTable};\nuse platform::font_context::FontContextHandle;\nuse platform::font_template::FontTemplateData;\nuse text::Shaper;\nuse text::glyph::{GlyphStore, GlyphId};\nuse text::shaping::ShaperMethods;\nuse util::geometry::Au;\n\n// FontHandle encapsulates access to the platform's font API,\n// e.g. quartz, FreeType. It provides access to metrics and tables\n// needed by the text shaper as well as access to the underlying font\n// resources needed by the graphics layer to draw glyphs.\n\npub trait FontHandleMethods {\n fn new_from_template(fctx: &FontContextHandle, template: Arc, pt_size: Option)\n -> Result;\n fn template(&self) -> Arc;\n fn family_name(&self) -> String;\n fn face_name(&self) -> String;\n fn is_italic(&self) -> bool;\n fn boldness(&self) -> font_weight::T;\n fn stretchiness(&self) -> font_stretch::T;\n\n fn glyph_index(&self, codepoint: char) -> Option;\n fn glyph_h_advance(&self, GlyphId) -> Option;\n fn glyph_h_kerning(&self, GlyphId, GlyphId) -> FractionalPixel;\n fn metrics(&self) -> FontMetrics;\n fn get_table_for_tag(&self, FontTableTag) -> Option;\n}\n\n// Used to abstract over the shaper's choice of fixed int representation.\npub type FractionalPixel = f64;\n\npub type FontTableTag = u32;\n\npub trait FontTableTagConversions {\n fn tag_to_str(&self) -> String;\n}\n\nimpl FontTableTagConversions for FontTableTag {\n fn tag_to_str(&self) -> String {\n unsafe {\n let pointer = mem::transmute::<&u32, *const u8>(self);\n let mut bytes = slice::from_raw_parts(pointer, 4).to_vec();\n bytes.reverse();\n String::from_utf8_unchecked(bytes)\n }\n }\n}\n\npub trait FontTableMethods {\n fn with_buffer(&self, F) where F: FnOnce(*const u8, usize);\n}\n\n#[derive(Clone, Debug, Deserialize, Serialize)]\npub struct FontMetrics {\n pub underline_size: Au,\n pub underline_offset: Au,\n pub strikeout_size: Au,\n pub strikeout_offset: Au,\n pub leading: Au,\n pub x_height: Au,\n pub em_size: Au,\n pub ascent: Au,\n pub descent: Au,\n pub max_advance: Au,\n pub average_advance: Au,\n pub line_gap: Au,\n}\n\npub type SpecifiedFontStyle = FontStyle;\n\npub struct Font {\n pub handle: FontHandle,\n pub metrics: FontMetrics,\n pub variant: font_variant::T,\n pub descriptor: FontTemplateDescriptor,\n pub requested_pt_size: Au,\n pub actual_pt_size: Au,\n pub shaper: Option,\n pub shape_cache: HashCache>,\n pub glyph_advance_cache: HashCache,\n}\n\nbitflags! {\n flags ShapingFlags: u8 {\n #[doc = \"Set if the text is entirely whitespace.\"]\n const IS_WHITESPACE_SHAPING_FLAG = 0x01,\n #[doc = \"Set if we are to ignore ligatures.\"]\n const IGNORE_LIGATURES_SHAPING_FLAG = 0x02,\n #[doc = \"Set if we are to disable kerning.\"]\n const DISABLE_KERNING_SHAPING_FLAG = 0x04,\n #[doc = \"Text direction is right-to-left.\"]\n const RTL_FLAG = 0x08,\n }\n}\n\n/// Various options that control text shaping.\n#[derive(Clone, Eq, PartialEq, Hash, Copy)]\npub struct "},"suffix":{"kind":"string","value":" {\n /// Spacing to add between each letter. Corresponds to the CSS 2.1 `letter-spacing` property.\n /// NB: You will probably want to set the `IGNORE_LIGATURES_SHAPING_FLAG` if this is non-null.\n pub letter_spacing: Option,\n /// Spacing to add between each word. Corresponds to the CSS 2.1 `word-spacing` property.\n pub word_spacing: Au,\n /// Various flags.\n pub flags: ShapingFlags,\n}\n\n/// An entry in the shape cache.\n#[derive(Clone, Eq, PartialEq, Hash)]\npub struct ShapeCacheEntry {\n text: String,\n options: ShapingOptions,\n}\n\nimpl Font {\n pub fn shape_text(&mut self, text: &str, options: &ShapingOptions) -> Arc {\n self.make_shaper(options);\n\n //FIXME: find the equivalent of Equiv and the old ShapeCacheEntryRef\n let shaper = &self.shaper;\n let lookup_key = ShapeCacheEntry {\n text: text.to_owned(),\n options: options.clone(),\n };\n if let Some(glyphs) = self.shape_cache.find(&lookup_key) {\n return glyphs.clone();\n }\n\n let mut glyphs = GlyphStore::new(text.chars().count(),\n options.flags.contains(IS_WHITESPACE_SHAPING_FLAG),\n options.flags.contains(RTL_FLAG));\n shaper.as_ref().unwrap().shape_text(text, options, &mut glyphs);\n\n let glyphs = Arc::new(glyphs);\n self.shape_cache.insert(ShapeCacheEntry {\n text: text.to_owned(),\n options: *options,\n }, glyphs.clone());\n glyphs\n }\n\n fn make_shaper<'a>(&'a mut self, options: &ShapingOptions) -> &'a Shaper {\n // fast path: already created a shaper\n if let Some(ref mut shaper) = self.shaper {\n shaper.set_options(options);\n return shaper\n }\n\n let shaper = Shaper::new(self, options);\n self.shaper = Some(shaper);\n self.shaper.as_ref().unwrap()\n }\n\n pub fn get_table_for_tag(&self, tag: FontTableTag) -> Option {\n let result = self.handle.get_table_for_tag(tag);\n let status = if result.is_some() { \"Found\" } else { \"Didn't find\" };\n\n debug!(\"{} font table[{}] with family={}, face={}\",\n status, tag.tag_to_str(),\n self.handle.family_name(), self.handle.face_name());\n\n return result;\n }\n\n #[inline]\n pub fn glyph_index(&self, codepoint: char) -> Option {\n let codepoint = match self.variant {\n font_variant::T::small_caps => codepoint.to_uppercase().next().unwrap(), //FIXME: #5938\n font_variant::T::normal => codepoint,\n };\n self.handle.glyph_index(codepoint)\n }\n\n pub fn glyph_h_kerning(&mut self, first_glyph: GlyphId, second_glyph: GlyphId)\n -> FractionalPixel {\n self.handle.glyph_h_kerning(first_glyph, second_glyph)\n }\n\n pub fn glyph_h_advance(&mut self, glyph: GlyphId) -> FractionalPixel {\n let handle = &self.handle;\n self.glyph_advance_cache.find_or_create(&glyph, |glyph| {\n match handle.glyph_h_advance(*glyph) {\n Some(adv) => adv,\n None => 10f64 as FractionalPixel // FIXME: Need fallback strategy\n }\n })\n }\n}\n\npub struct FontGroup {\n pub fonts: SmallVec<[Rc>; 8]>,\n}\n\nimpl FontGroup {\n pub fn new(fonts: SmallVec<[Rc>; 8]>) -> FontGroup {\n FontGroup {\n fonts: fonts,\n }\n }\n}\n\npub struct RunMetrics {\n // may be negative due to negative width (i.e., kerning of '.' in 'P.T.')\n pub advance_width: Au,\n pub ascent: Au, // nonzero\n pub descent: Au, // nonzero\n // this bounding box is relative to the left origin baseline.\n // so, bounding_box.position.y = -ascent\n pub bounding_box: Rect\n}\n\nimpl RunMetrics {\n pub fn new(advance: Au, ascent: Au, descent: Au) -> RunMetrics {\n let bounds = Rect::new(Point2D::new(Au(0), -ascent),\n Size2D::new(advance, ascent + descent));\n\n // TODO(Issue #125): support loose and tight bounding boxes; using the\n // ascent+descent and advance is sometimes too generous and\n // looking at actual glyph extents can yield a tighter box.\n\n RunMetrics {\n advance_width: advance,\n bounding_box: bounds,\n ascent: ascent,\n descent: descent,\n }\n }\n}\n"},"middle":{"kind":"string","value":"ShapingOptions"},"fim_type":{"kind":"string","value":"identifier_name"}}},{"rowIdx":236039,"cells":{"file_name":{"kind":"string","value":"font.rs"},"prefix":{"kind":"string","value":"/* This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http://mozilla.org/MPL/2.0/. */\n\nuse euclid::{Point2D, Rect, Size2D};\nuse smallvec::SmallVec;\nuse std::borrow::ToOwned;\nuse std::cell::RefCell;\nuse std::mem;\nuse std::rc::Rc;\nuse std::slice;\nuse std::sync::Arc;\nuse style::computed_values::{font_stretch, font_variant, font_weight};\nuse style::properties::style_structs::Font as FontStyle;\nuse util::cache::HashCache;\n\nuse font_template::FontTemplateDescriptor;\nuse platform::font::{FontHandle, FontTable};\nuse platform::font_context::FontContextHandle;\nuse platform::font_template::FontTemplateData;\nuse text::Shaper;\nuse text::glyph::{GlyphStore, GlyphId};\nuse text::shaping::ShaperMethods;\nuse util::geometry::Au;\n\n// FontHandle encapsulates access to the platform's font API,\n// e.g. quartz, FreeType. It provides access to metrics and tables\n// needed by the text shaper as well as access to the underlying font\n// resources needed by the graphics layer to draw glyphs.\n\npub trait FontHandleMethods {\n fn new_from_template(fctx: &FontContextHandle, template: Arc, pt_size: Option)\n -> Result;\n fn template(&self) -> Arc;\n fn family_name(&self) -> String;\n fn face_name(&self) -> String;\n fn is_italic(&self) -> bool;\n fn boldness(&self) -> font_weight::T;\n fn stretchiness(&self) -> font_stretch::T;\n\n fn glyph_index(&self, codepoint: char) -> Option;\n fn glyph_h_advance(&self, GlyphId) -> Option;\n fn glyph_h_kerning(&self, GlyphId, GlyphId) -> FractionalPixel;\n fn metrics(&self) -> FontMetrics;\n fn get_table_for_tag(&self, FontTableTag) -> Option;\n}\n\n// Used to abstract over the shaper's choice of fixed int representation.\npub type FractionalPixel = f64;\n\npub type FontTableTag = u32;\n\npub trait FontTableTagConversions {\n fn tag_to_str(&self) -> String;\n}\n\nimpl FontTableTagConversions for FontTableTag {\n fn tag_to_str(&self) -> String {\n unsafe {\n let pointer = mem::transmute::<&u32, *const u8>(self);\n let mut bytes = slice::from_raw_parts(pointer, 4).to_vec();\n bytes.reverse();\n String::from_utf8_unchecked(bytes)\n }\n }\n}\n\npub trait FontTableMethods {\n fn with_buffer(&self, F) where F: FnOnce(*const u8, usize);\n}\n\n#[derive(Clone, Debug, Deserialize, Serialize)]\npub struct FontMetrics {\n pub underline_size: Au,\n pub underline_offset: Au,\n pub strikeout_size: Au,\n pub strikeout_offset: Au,\n pub leading: Au,\n pub x_height: Au,\n pub em_size: Au,\n pub ascent: Au,\n pub descent: Au,\n pub max_advance: Au,\n pub average_advance: Au,\n pub line_gap: Au,\n}\n\npub type SpecifiedFontStyle = FontStyle;\n\npub struct Font {\n pub handle: FontHandle,\n pub metrics: FontMetrics,\n pub variant: font_variant::T,\n pub descriptor: FontTemplateDescriptor,\n pub requested_pt_size: Au,\n pub actual_pt_size: Au,\n pub shaper: Option,\n pub shape_cache: HashCache>,\n pub glyph_advance_cache: HashCache,\n}\n\nbitflags! {\n flags ShapingFlags: u8 {\n #[doc = \"Set if the text is entirely whitespace.\"]\n const IS_WHITESPACE_SHAPING_FLAG = 0x01,\n #[doc = \"Set if we are to ignore ligatures.\"]\n const IGNORE_LIGATURES_SHAPING_FLAG = 0x02,\n #[doc = \"Set if we are to disable kerning.\"]\n const DISABLE_KERNING_SHAPING_FLAG = 0x04,\n #[doc = \"Text direction is right-to-left.\"]\n const RTL_FLAG = 0x08,\n }\n}\n\n/// Various options that control text shaping.\n#[derive(Clone, Eq, PartialEq, Hash, Copy)]\npub struct ShapingOptions {\n /// Spacing to add between each letter. Corresponds to the CSS 2.1 `letter-spacing` property.\n /// NB: You will probably want to set the `IGNORE_LIGATURES_SHAPING_FLAG` if this is non-null.\n pub letter_spacing: Option,\n /// Spacing to add between each word. Corresponds to the CSS 2.1 `word-spacing` property.\n pub word_spacing: Au,\n /// Various flags.\n pub flags: ShapingFlags,\n}\n\n/// An entry in the shape cache.\n#[derive(Clone, Eq, PartialEq, Hash)]\npub struct ShapeCacheEntry {\n text: String,\n options: ShapingOptions,\n}\n\nimpl Font {\n pub fn shape_text(&mut self, text: &str, options: &ShapingOptions) -> Arc {\n self.make_shaper(options);\n\n //FIXME: find the equivalent of Equiv and the old ShapeCacheEntryRef\n let shaper = &self.shaper;\n let lookup_key = ShapeCacheEntry {\n text: text.to_owned(),\n options: options.clone(),\n };\n if let Some(glyphs) = self.shape_cache.find(&lookup_key) {\n return glyphs.clone();\n }\n\n let mut glyphs = GlyphStore::new(text.chars().count(),\n options.flags.contains(IS_WHITESPACE_SHAPING_FLAG),\n options.flags.contains(RTL_FLAG));\n shaper.as_ref().unwrap().shape_text(text, options, &mut glyphs);\n\n let glyphs = Arc::new(glyphs);\n self.shape_cache.insert(ShapeCacheEntry {\n text: text.to_owned(),\n options: *options,\n }, glyphs.clone());\n glyphs\n }\n\n fn make_shaper<'a>(&'a mut self, options: &ShapingOptions) -> &'a Shaper {\n // fast path: already created a shaper\n if let Some(ref mut shaper) = self.shaper {\n shaper.set_options(options);\n return shaper\n }\n\n let shaper = Shaper::new(self, options);\n self.shaper = Some(shaper);\n self.shaper.as_ref().unwrap()\n }\n\n pub fn get_table_for_tag(&self, tag: FontTableTag) -> Option {\n let result = self.handle.get_table_for_tag(tag);\n let status = if result.is_some() { \"Found\" } else { \"Didn't find\" };\n\n debug!(\"{} font table[{}] with family={}, face={}\",\n status, tag.tag_to_str(),\n self.handle.family_name(), self.handle.face_name());\n\n return result;\n }\n\n #[inline]\n pub fn glyph_index(&self, codepoint: char) -> Option {\n let codepoint = match self.variant {\n font_variant::T::small_caps => codepoint.to_uppercase().next().unwrap(), //FIXME: #5938\n font_variant::T::normal => codepoint,\n };\n self.handle.glyph_index(codepoint)\n }\n\n pub fn glyph_h_kerning(&mut self, first_glyph: GlyphId, second_glyph: GlyphId)\n -> FractionalPixel {\n self.handle.glyph_h_kerning(first_glyph, second_glyph)\n }\n\n pub fn glyph_h_advance(&mut self, glyph: GlyphId) -> FractionalPixel {\n let handle = &self.handle;\n self.glyph_advance_cache.find_or_create(&glyph, |glyph| {\n match handle.glyph_h_advance(*glyph) {\n Some(adv) => adv,\n None => 10f64 as FractionalPixel // FIXME: Need fallback strategy\n }\n })\n }\n}\n\npub struct FontGroup {\n pub fonts: SmallVec<[Rc>; 8]>,\n}\n\nimpl FontGroup {\n pub fn new(fonts: SmallVec<[Rc>; 8]>) -> FontGroup {\n FontGroup {\n fonts: fonts,\n }\n }\n}\n\npub struct RunMetrics {\n // may be negative due to negative width (i.e., kerning of '.' in 'P.T.')\n pub advance_width: Au,\n pub ascent: Au, // nonzero\n pub descent: Au, // nonzero"},"suffix":{"kind":"string","value":"}\n\nimpl RunMetrics {\n pub fn new(advance: Au, ascent: Au, descent: Au) -> RunMetrics {\n let bounds = Rect::new(Point2D::new(Au(0), -ascent),\n Size2D::new(advance, ascent + descent));\n\n // TODO(Issue #125): support loose and tight bounding boxes; using the\n // ascent+descent and advance is sometimes too generous and\n // looking at actual glyph extents can yield a tighter box.\n\n RunMetrics {\n advance_width: advance,\n bounding_box: bounds,\n ascent: ascent,\n descent: descent,\n }\n }\n}"},"middle":{"kind":"string","value":" // this bounding box is relative to the left origin baseline.\n // so, bounding_box.position.y = -ascent\n pub bounding_box: Rect"},"fim_type":{"kind":"string","value":"random_line_split"}}},{"rowIdx":236040,"cells":{"file_name":{"kind":"string","value":"text_visual.py"},"prefix":{"kind":"string","value":"import numpy as np\r\nimport os\r\nfrom galry import log_debug, log_info, log_warn, get_color\r\nfrom fontmaps import load_font\r\nfrom visual import Visual\r\n\r\n__all__ = ['TextVisual']\r\n\r\nVS = \"\"\"\r\ngl_Position.x += (offset - text_width / 2) * spacing.x / window_size.x;\r\ngl_Position.y -= index * spacing.y / window_size.y;\r\n\r\ngl_Position.xy = gl_Position.xy + posoffset / window_size;\r\n\r\ngl_PointSize = point_size;\r\nflat_text_map = text_map;\r\n\"\"\"\r\n\r\ndef FS(background_transparent=True):\r\n if background_transparent:\r\n background_transparent_shader = \"letter_alpha\"\r\n else:\r\n background_transparent_shader = \"1.\"\r\n fs = \"\"\"\r\n// relative coordinates of the pixel within the sprite (in [0,1])\r\nfloat x = gl_PointCoord.x;\r\nfloat y = gl_PointCoord.y;\r\n\r\n// size of the corresponding character\r\nfloat w = flat_text_map.z;\r\nfloat h = flat_text_map.w;\r\n\r\n// display the character at the left of the sprite\r\nfloat delta = h / w;\r\nx = delta * x;\r\nif ((x >= 0) && (x <= 1))\r\n{\r\n // coordinates of the character in the font atlas\r\n vec2 coord = flat_text_map.xy + vec2(w * x, h * y);\r\n float letter_alpha = texture2D(tex_sampler, coord).a;\r\n out_color = color * letter_alpha;\r\n out_color.a = %s;\r\n}\r\nelse\r\n out_color = vec4(0, 0, 0, 0);\r\n\"\"\" % background_transparent_shader\r\n return fs\r\n\r\n\r\nclass TextVisual(Visual):\r\n \"\"\"Template for displaying short text on a single line.\r\n \r\n It uses the following technique: each character is rendered as a sprite,\r\n i.e. a pixel with a large point size, and a single texture for every point.\r\n The texture contains a font atlas, i.e. all characters in a given font.\r\n Every point comes with coordinates that indicate which small portion\r\n of the font atlas to display (that portion corresponds to the character).\r\n This is all done automatically, thanks to a font atlas stored in the\r\n `fontmaps` folder. There needs to be one font atlas per font and per font\r\n size. Also, there is a configuration text file with the coordinates and\r\n size of every character. The software used to generate font maps is\r\n AngelCode Bitmap Font Generator.\r\n \r\n For now, there is only the Segoe font.\r\n \r\n \"\"\"\r\n \r\n def position_compound(self, coordinates=None):\r\n \"\"\"Compound variable with the position of the text. All characters\r\n are at the exact same position, and are then shifted in the vertex\r\n shader.\"\"\"\r\n if coordinates is None:\r\n coordinates = (0., 0.)\r\n if type(coordinates) == tuple:\r\n coordinates = [coordinates]\r\n \r\n coordinates = np.array(coordinates)\r\n position = np.repeat(coordinates, self.textsizes, axis=0)\r\n return dict(position=position)\r\n \r\n def text_compound(self, text):\r\n \"\"\"Compound variable for the text string. It changes the text map,\r\n the character position, and the text width.\"\"\"\r\n \r\n coordinates = self.coordinates\r\n \r\n if \"\\n\" in text:\r\n text = text.split(\"\\n\")\r\n \r\n if type(text) == list:\r\n self.textsizes = [len(t) for t in text]\r\n text = \"\".join(text)\r\n if type(coordinates) != list:\r\n "},"suffix":{"kind":"string","value":"\r\n index = np.repeat(np.arange(len(self.textsizes)), self.textsizes)\r\n text_map = self.get_map(text)\r\n \r\n # offset for all characters in the merging of all texts\r\n offset = np.hstack((0., np.cumsum(text_map[:, 2])[:-1]))\r\n \r\n # for each text, the cumsum of the length of all texts strictly\r\n # before\r\n d = np.hstack(([0], np.cumsum(self.textsizes)[:-1]))\r\n \r\n # compensate the offsets for the length of each text\r\n offset -= np.repeat(offset[d], self.textsizes)\r\n \r\n text_width = 0.\r\n \r\n else:\r\n self.textsizes = len(text)\r\n text_map = self.get_map(text)\r\n offset = np.hstack((0., np.cumsum(text_map[:, 2])[:-1])) \r\n text_width = offset[-1]\r\n index = np.zeros(len(text))\r\n \r\n self.size = len(text)\r\n \r\n d = dict(text_map=text_map, offset=offset, text_width=text_width,\r\n index=index)\r\n d.update(self.position_compound(coordinates))\r\n \r\n return d\r\n \r\n def initialize_font(self, font, fontsize):\r\n \"\"\"Initialize the specified font at a given size.\"\"\"\r\n self.texture, self.matrix, self.get_map = load_font(font, fontsize)\r\n\r\n def initialize(self, text, coordinates=(0., 0.), font='segoe', fontsize=24,\r\n color=None, letter_spacing=None, interline=0., autocolor=None,\r\n background_transparent=True,\r\n prevent_constrain=False, depth=None, posoffset=None):\r\n \"\"\"Initialize the text template.\"\"\"\r\n \r\n if prevent_constrain:\r\n self.constrain_ratio = False\r\n \r\n if autocolor is not None:\r\n color = get_color(autocolor)\r\n \r\n if color is None:\r\n color = self.default_color\r\n \r\n self.size = len(text)\r\n self.primitive_type = 'POINTS'\r\n self.interline = interline\r\n \r\n text_length = self.size\r\n self.initialize_font(font, fontsize)\r\n self.coordinates = coordinates\r\n \r\n point_size = float(self.matrix[:,4].max() * self.texture.shape[1])\r\n\r\n # template attributes and varyings\r\n self.add_attribute(\"position\", vartype=\"float\", ndim=2, data=np.zeros((self.size, 2)))\r\n \r\n self.add_attribute(\"offset\", vartype=\"float\", ndim=1)\r\n self.add_attribute(\"index\", vartype=\"float\", ndim=1)\r\n self.add_attribute(\"text_map\", vartype=\"float\", ndim=4)\r\n self.add_varying(\"flat_text_map\", vartype=\"float\", flat=True, ndim=4)\r\n \r\n if posoffset is None:\r\n posoffset = (0., 0.)\r\n self.add_uniform('posoffset', vartype='float', ndim=2, data=posoffset)\r\n \r\n # texture\r\n self.add_texture(\"tex_sampler\", size=self.texture.shape[:2], ndim=2,\r\n ncomponents=self.texture.shape[2],\r\n data=self.texture)\r\n \r\n # pure heuristic (probably bogus)\r\n if letter_spacing is None:\r\n letter_spacing = (100 + 17. * fontsize)\r\n self.add_uniform(\"spacing\", vartype=\"float\", ndim=2,\r\n data=(letter_spacing, interline))\r\n self.add_uniform(\"point_size\", vartype=\"float\", ndim=1,\r\n data=point_size)\r\n # one color per\r\n if isinstance(color, np.ndarray) and color.ndim > 1:\r\n self.add_attribute('color0', vartype=\"float\", ndim=4, data=color)\r\n self.add_varying('color', vartype=\"float\", ndim=4)\r\n self.add_vertex_main('color = color0;')\r\n else:\r\n self.add_uniform(\"color\", vartype=\"float\", ndim=4, data=color)\r\n self.add_uniform(\"text_width\", vartype=\"float\", ndim=1)\r\n \r\n # compound variables\r\n self.add_compound(\"text\", fun=self.text_compound, data=text)\r\n self.add_compound(\"coordinates\", fun=self.position_compound, data=coordinates)\r\n\r\n # vertex shader\r\n self.add_vertex_main(VS, after='viewport')\r\n\r\n # fragment shader\r\n self.add_fragment_main(FS(background_transparent))\r\n \r\n self.depth = depth"},"middle":{"kind":"string","value":"coordinates = [coordinates] * len(self.textsizes)"},"fim_type":{"kind":"string","value":"conditional_block"}}},{"rowIdx":236041,"cells":{"file_name":{"kind":"string","value":"text_visual.py"},"prefix":{"kind":"string","value":"import numpy as np\r\nimport os\r\nfrom galry import log_debug, log_info, log_warn, get_color\r\nfrom fontmaps import load_font\r\nfrom visual import Visual\r\n\r\n__all__ = ['TextVisual']\r\n\r\nVS = \"\"\"\r\ngl_Position.x += (offset - text_width / 2) * spacing.x / window_size.x;\r\ngl_Position.y -= index * spacing.y / window_size.y;\r\n\r\ngl_Position.xy = gl_Position.xy + posoffset / window_size;\r\n\r\ngl_PointSize = point_size;\r\nflat_text_map = text_map;\r\n\"\"\"\r\n\r\ndef FS(background_transparent=True):\r\n if background_transparent:\r\n background_transparent_shader = \"letter_alpha\"\r\n else:\r\n background_transparent_shader = \"1.\"\r\n fs = \"\"\"\r\n// relative coordinates of the pixel within the sprite (in [0,1])\r\nfloat x = gl_PointCoord.x;\r\nfloat y = gl_PointCoord.y;\r\n\r\n// size of the corresponding character\r\nfloat w = flat_text_map.z;\r\nfloat h = flat_text_map.w;\r\n\r\n// display the character at the left of the sprite\r\nfloat delta = h / w;\r\nx = delta * x;\r\nif ((x >= 0) && (x <= 1))\r\n{\r\n // coordinates of the character in the font atlas\r\n vec2 coord = flat_text_map.xy + vec2(w * x, h * y);\r\n float letter_alpha = texture2D(tex_sampler, coord).a;\r\n out_color = color * letter_alpha;\r\n out_color.a = %s;\r\n}\r\nelse\r\n out_color = vec4(0, 0, 0, 0);\r\n\"\"\" % background_transparent_shader\r\n return fs\r\n\r\n\r\nclass TextVisual(Visual):\r\n "},"suffix":{"kind":"string","value":""},"middle":{"kind":"string","value":"\"\"\"Template for displaying short text on a single line.\r\n \r\n It uses the following technique: each character is rendered as a sprite,\r\n i.e. a pixel with a large point size, and a single texture for every point.\r\n The texture contains a font atlas, i.e. all characters in a given font.\r\n Every point comes with coordinates that indicate which small portion\r\n of the font atlas to display (that portion corresponds to the character).\r\n This is all done automatically, thanks to a font atlas stored in the\r\n `fontmaps` folder. There needs to be one font atlas per font and per font\r\n size. Also, there is a configuration text file with the coordinates and\r\n size of every character. The software used to generate font maps is\r\n AngelCode Bitmap Font Generator.\r\n \r\n For now, there is only the Segoe font.\r\n \r\n \"\"\"\r\n \r\n def position_compound(self, coordinates=None):\r\n \"\"\"Compound variable with the position of the text. All characters\r\n are at the exact same position, and are then shifted in the vertex\r\n shader.\"\"\"\r\n if coordinates is None:\r\n coordinates = (0., 0.)\r\n if type(coordinates) == tuple:\r\n coordinates = [coordinates]\r\n \r\n coordinates = np.array(coordinates)\r\n position = np.repeat(coordinates, self.textsizes, axis=0)\r\n return dict(position=position)\r\n \r\n def text_compound(self, text):\r\n \"\"\"Compound variable for the text string. It changes the text map,\r\n the character position, and the text width.\"\"\"\r\n \r\n coordinates = self.coordinates\r\n \r\n if \"\\n\" in text:\r\n text = text.split(\"\\n\")\r\n \r\n if type(text) == list:\r\n self.textsizes = [len(t) for t in text]\r\n text = \"\".join(text)\r\n if type(coordinates) != list:\r\n coordinates = [coordinates] * len(self.textsizes)\r\n index = np.repeat(np.arange(len(self.textsizes)), self.textsizes)\r\n text_map = self.get_map(text)\r\n \r\n # offset for all characters in the merging of all texts\r\n offset = np.hstack((0., np.cumsum(text_map[:, 2])[:-1]))\r\n \r\n # for each text, the cumsum of the length of all texts strictly\r\n # before\r\n d = np.hstack(([0], np.cumsum(self.textsizes)[:-1]))\r\n \r\n # compensate the offsets for the length of each text\r\n offset -= np.repeat(offset[d], self.textsizes)\r\n \r\n text_width = 0.\r\n \r\n else:\r\n self.textsizes = len(text)\r\n text_map = self.get_map(text)\r\n offset = np.hstack((0., np.cumsum(text_map[:, 2])[:-1])) \r\n text_width = offset[-1]\r\n index = np.zeros(len(text))\r\n \r\n self.size = len(text)\r\n \r\n d = dict(text_map=text_map, offset=offset, text_width=text_width,\r\n index=index)\r\n d.update(self.position_compound(coordinates))\r\n \r\n return d\r\n \r\n def initialize_font(self, font, fontsize):\r\n \"\"\"Initialize the specified font at a given size.\"\"\"\r\n self.texture, self.matrix, self.get_map = load_font(font, fontsize)\r\n\r\n def initialize(self, text, coordinates=(0., 0.), font='segoe', fontsize=24,\r\n color=None, letter_spacing=None, interline=0., autocolor=None,\r\n background_transparent=True,\r\n prevent_constrain=False, depth=None, posoffset=None):\r\n \"\"\"Initialize the text template.\"\"\"\r\n \r\n if prevent_constrain:\r\n self.constrain_ratio = False\r\n \r\n if autocolor is not None:\r\n color = get_color(autocolor)\r\n \r\n if color is None:\r\n color = self.default_color\r\n \r\n self.size = len(text)\r\n self.primitive_type = 'POINTS'\r\n self.interline = interline\r\n \r\n text_length = self.size\r\n self.initialize_font(font, fontsize)\r\n self.coordinates = coordinates\r\n \r\n point_size = float(self.matrix[:,4].max() * self.texture.shape[1])\r\n\r\n # template attributes and varyings\r\n self.add_attribute(\"position\", vartype=\"float\", ndim=2, data=np.zeros((self.size, 2)))\r\n \r\n self.add_attribute(\"offset\", vartype=\"float\", ndim=1)\r\n self.add_attribute(\"index\", vartype=\"float\", ndim=1)\r\n self.add_attribute(\"text_map\", vartype=\"float\", ndim=4)\r\n self.add_varying(\"flat_text_map\", vartype=\"float\", flat=True, ndim=4)\r\n \r\n if posoffset is None:\r\n posoffset = (0., 0.)\r\n self.add_uniform('posoffset', vartype='float', ndim=2, data=posoffset)\r\n \r\n # texture\r\n self.add_texture(\"tex_sampler\", size=self.texture.shape[:2], ndim=2,\r\n ncomponents=self.texture.shape[2],\r\n data=self.texture)\r\n \r\n # pure heuristic (probably bogus)\r\n if letter_spacing is None:\r\n letter_spacing = (100 + 17. * fontsize)\r\n self.add_uniform(\"spacing\", vartype=\"float\", ndim=2,\r\n data=(letter_spacing, interline))\r\n self.add_uniform(\"point_size\", vartype=\"float\", ndim=1,\r\n data=point_size)\r\n # one color per\r\n if isinstance(color, np.ndarray) and color.ndim > 1:\r\n self.add_attribute('color0', vartype=\"float\", ndim=4, data=color)\r\n self.add_varying('color', vartype=\"float\", ndim=4)\r\n self.add_vertex_main('color = color0;')\r\n else:\r\n self.add_uniform(\"color\", vartype=\"float\", ndim=4, data=color)\r\n self.add_uniform(\"text_width\", vartype=\"float\", ndim=1)\r\n \r\n # compound variables\r\n self.add_compound(\"text\", fun=self.text_compound, data=text)\r\n self.add_compound(\"coordinates\", fun=self.position_compound, data=coordinates)\r\n\r\n # vertex shader\r\n self.add_vertex_main(VS, after='viewport')\r\n\r\n # fragment shader\r\n self.add_fragment_main(FS(background_transparent))\r\n \r\n self.depth = depth"},"fim_type":{"kind":"string","value":"identifier_body"}}},{"rowIdx":236042,"cells":{"file_name":{"kind":"string","value":"text_visual.py"},"prefix":{"kind":"string","value":"import numpy as np\r\nimport os\r\nfrom galry import log_debug, log_info, log_warn, get_color\r\nfrom fontmaps import load_font\r\nfrom visual import Visual\r\n\r\n__all__ = ['TextVisual']\r\n\r\nVS = \"\"\"\r\ngl_Position.x += (offset - text_width / 2) * spacing.x / window_size.x;\r\ngl_Position.y -= index * spacing.y / window_size.y;\r\n\r\ngl_Position.xy = gl_Position.xy + posoffset / window_size;\r\n\r\ngl_PointSize = point_size;\r\nflat_text_map = text_map;\r\n\"\"\"\r\n\r\ndef FS(background_transparent=True):\r\n if background_transparent:\r\n background_transparent_shader = \"letter_alpha\"\r\n else:\r\n background_transparent_shader = \"1.\"\r\n fs = \"\"\"\r\n// relative coordinates of the pixel within the sprite (in [0,1])\r\nfloat x = gl_PointCoord.x;\r\nfloat y = gl_PointCoord.y;\r\n\r\n// size of the corresponding character\r\nfloat w = flat_text_map.z;\r\nfloat h = flat_text_map.w;\r\n\r\n// display the character at the left of the sprite\r\nfloat delta = h / w;\r\nx = delta * x;\r\nif ((x >= 0) && (x <= 1))\r\n{\r\n // coordinates of the character in the font atlas\r\n vec2 coord = flat_text_map.xy + vec2(w * x, h * y);\r\n float letter_alpha = texture2D(tex_sampler, coord).a;\r\n out_color = color * letter_alpha;\r\n out_color.a = %s;\r\n}\r\nelse\r\n out_color = vec4(0, 0, 0, 0);\r\n\"\"\" % background_transparent_shader\r\n return fs\r\n\r\n\r\nclass TextVisual(Visual):\r\n \"\"\"Template for displaying short text on a single line.\r\n \r\n It uses the following technique: each character is rendered as a sprite,\r\n i.e. a pixel with a large point size, and a single texture for every point.\r\n The texture contains a font atlas, i.e. all characters in a given font.\r\n Every point comes with coordinates that indicate which small portion\r\n of the font atlas to display (that portion corresponds to the character).\r\n This is all done automatically, thanks to a font atlas stored in the\r\n `fontmaps` folder. There needs to be one font atlas per font and per font\r\n size. Also, there is a configuration text file with the coordinates and\r\n size of every character. The software used to generate font maps is\r\n AngelCode Bitmap Font Generator.\r\n \r\n For now, there is only the Segoe font.\r\n \r\n \"\"\"\r\n \r\n def "},"suffix":{"kind":"string","value":"(self, coordinates=None):\r\n \"\"\"Compound variable with the position of the text. All characters\r\n are at the exact same position, and are then shifted in the vertex\r\n shader.\"\"\"\r\n if coordinates is None:\r\n coordinates = (0., 0.)\r\n if type(coordinates) == tuple:\r\n coordinates = [coordinates]\r\n \r\n coordinates = np.array(coordinates)\r\n position = np.repeat(coordinates, self.textsizes, axis=0)\r\n return dict(position=position)\r\n \r\n def text_compound(self, text):\r\n \"\"\"Compound variable for the text string. It changes the text map,\r\n the character position, and the text width.\"\"\"\r\n \r\n coordinates = self.coordinates\r\n \r\n if \"\\n\" in text:\r\n text = text.split(\"\\n\")\r\n \r\n if type(text) == list:\r\n self.textsizes = [len(t) for t in text]\r\n text = \"\".join(text)\r\n if type(coordinates) != list:\r\n coordinates = [coordinates] * len(self.textsizes)\r\n index = np.repeat(np.arange(len(self.textsizes)), self.textsizes)\r\n text_map = self.get_map(text)\r\n \r\n # offset for all characters in the merging of all texts\r\n offset = np.hstack((0., np.cumsum(text_map[:, 2])[:-1]))\r\n \r\n # for each text, the cumsum of the length of all texts strictly\r\n # before\r\n d = np.hstack(([0], np.cumsum(self.textsizes)[:-1]))\r\n \r\n # compensate the offsets for the length of each text\r\n offset -= np.repeat(offset[d], self.textsizes)\r\n \r\n text_width = 0.\r\n \r\n else:\r\n self.textsizes = len(text)\r\n text_map = self.get_map(text)\r\n offset = np.hstack((0., np.cumsum(text_map[:, 2])[:-1])) \r\n text_width = offset[-1]\r\n index = np.zeros(len(text))\r\n \r\n self.size = len(text)\r\n \r\n d = dict(text_map=text_map, offset=offset, text_width=text_width,\r\n index=index)\r\n d.update(self.position_compound(coordinates))\r\n \r\n return d\r\n \r\n def initialize_font(self, font, fontsize):\r\n \"\"\"Initialize the specified font at a given size.\"\"\"\r\n self.texture, self.matrix, self.get_map = load_font(font, fontsize)\r\n\r\n def initialize(self, text, coordinates=(0., 0.), font='segoe', fontsize=24,\r\n color=None, letter_spacing=None, interline=0., autocolor=None,\r\n background_transparent=True,\r\n prevent_constrain=False, depth=None, posoffset=None):\r\n \"\"\"Initialize the text template.\"\"\"\r\n \r\n if prevent_constrain:\r\n self.constrain_ratio = False\r\n \r\n if autocolor is not None:\r\n color = get_color(autocolor)\r\n \r\n if color is None:\r\n color = self.default_color\r\n \r\n self.size = len(text)\r\n self.primitive_type = 'POINTS'\r\n self.interline = interline\r\n \r\n text_length = self.size\r\n self.initialize_font(font, fontsize)\r\n self.coordinates = coordinates\r\n \r\n point_size = float(self.matrix[:,4].max() * self.texture.shape[1])\r\n\r\n # template attributes and varyings\r\n self.add_attribute(\"position\", vartype=\"float\", ndim=2, data=np.zeros((self.size, 2)))\r\n \r\n self.add_attribute(\"offset\", vartype=\"float\", ndim=1)\r\n self.add_attribute(\"index\", vartype=\"float\", ndim=1)\r\n self.add_attribute(\"text_map\", vartype=\"float\", ndim=4)\r\n self.add_varying(\"flat_text_map\", vartype=\"float\", flat=True, ndim=4)\r\n \r\n if posoffset is None:\r\n posoffset = (0., 0.)\r\n self.add_uniform('posoffset', vartype='float', ndim=2, data=posoffset)\r\n \r\n # texture\r\n self.add_texture(\"tex_sampler\", size=self.texture.shape[:2], ndim=2,\r\n ncomponents=self.texture.shape[2],\r\n data=self.texture)\r\n \r\n # pure heuristic (probably bogus)\r\n if letter_spacing is None:\r\n letter_spacing = (100 + 17. * fontsize)\r\n self.add_uniform(\"spacing\", vartype=\"float\", ndim=2,\r\n data=(letter_spacing, interline))\r\n self.add_uniform(\"point_size\", vartype=\"float\", ndim=1,\r\n data=point_size)\r\n # one color per\r\n if isinstance(color, np.ndarray) and color.ndim > 1:\r\n self.add_attribute('color0', vartype=\"float\", ndim=4, data=color)\r\n self.add_varying('color', vartype=\"float\", ndim=4)\r\n self.add_vertex_main('color = color0;')\r\n else:\r\n self.add_uniform(\"color\", vartype=\"float\", ndim=4, data=color)\r\n self.add_uniform(\"text_width\", vartype=\"float\", ndim=1)\r\n \r\n # compound variables\r\n self.add_compound(\"text\", fun=self.text_compound, data=text)\r\n self.add_compound(\"coordinates\", fun=self.position_compound, data=coordinates)\r\n\r\n # vertex shader\r\n self.add_vertex_main(VS, after='viewport')\r\n\r\n # fragment shader\r\n self.add_fragment_main(FS(background_transparent))\r\n \r\n self.depth = depth"},"middle":{"kind":"string","value":"position_compound"},"fim_type":{"kind":"string","value":"identifier_name"}}},{"rowIdx":236043,"cells":{"file_name":{"kind":"string","value":"text_visual.py"},"prefix":{"kind":"string","value":"import numpy as np\r\nimport os\r\nfrom galry import log_debug, log_info, log_warn, get_color\r\nfrom fontmaps import load_font\r\nfrom visual import Visual\r\n\r\n__all__ = ['TextVisual']\r\n\r\nVS = \"\"\"\r\ngl_Position.x += (offset - text_width / 2) * spacing.x / window_size.x;\r\ngl_Position.y -= index * spacing.y / window_size.y;\r\n\r\ngl_Position.xy = gl_Position.xy + posoffset / window_size;\r\n\r\ngl_PointSize = point_size;\r\nflat_text_map = text_map;\r\n\"\"\"\r\n\r\ndef FS(background_transparent=True):\r\n if background_transparent:\r\n background_transparent_shader = \"letter_alpha\"\r\n else:\r\n background_transparent_shader = \"1.\"\r\n fs = \"\"\"\r\n// relative coordinates of the pixel within the sprite (in [0,1])\r\nfloat x = gl_PointCoord.x;\r\nfloat y = gl_PointCoord.y;\r\n\r\n// size of the corresponding character\r\nfloat w = flat_text_map.z;\r\nfloat h = flat_text_map.w;\r\n\r\n// display the character at the left of the sprite\r\nfloat delta = h / w;\r"},"suffix":{"kind":"string","value":" vec2 coord = flat_text_map.xy + vec2(w * x, h * y);\r\n float letter_alpha = texture2D(tex_sampler, coord).a;\r\n out_color = color * letter_alpha;\r\n out_color.a = %s;\r\n}\r\nelse\r\n out_color = vec4(0, 0, 0, 0);\r\n\"\"\" % background_transparent_shader\r\n return fs\r\n\r\n\r\nclass TextVisual(Visual):\r\n \"\"\"Template for displaying short text on a single line.\r\n \r\n It uses the following technique: each character is rendered as a sprite,\r\n i.e. a pixel with a large point size, and a single texture for every point.\r\n The texture contains a font atlas, i.e. all characters in a given font.\r\n Every point comes with coordinates that indicate which small portion\r\n of the font atlas to display (that portion corresponds to the character).\r\n This is all done automatically, thanks to a font atlas stored in the\r\n `fontmaps` folder. There needs to be one font atlas per font and per font\r\n size. Also, there is a configuration text file with the coordinates and\r\n size of every character. The software used to generate font maps is\r\n AngelCode Bitmap Font Generator.\r\n \r\n For now, there is only the Segoe font.\r\n \r\n \"\"\"\r\n \r\n def position_compound(self, coordinates=None):\r\n \"\"\"Compound variable with the position of the text. All characters\r\n are at the exact same position, and are then shifted in the vertex\r\n shader.\"\"\"\r\n if coordinates is None:\r\n coordinates = (0., 0.)\r\n if type(coordinates) == tuple:\r\n coordinates = [coordinates]\r\n \r\n coordinates = np.array(coordinates)\r\n position = np.repeat(coordinates, self.textsizes, axis=0)\r\n return dict(position=position)\r\n \r\n def text_compound(self, text):\r\n \"\"\"Compound variable for the text string. It changes the text map,\r\n the character position, and the text width.\"\"\"\r\n \r\n coordinates = self.coordinates\r\n \r\n if \"\\n\" in text:\r\n text = text.split(\"\\n\")\r\n \r\n if type(text) == list:\r\n self.textsizes = [len(t) for t in text]\r\n text = \"\".join(text)\r\n if type(coordinates) != list:\r\n coordinates = [coordinates] * len(self.textsizes)\r\n index = np.repeat(np.arange(len(self.textsizes)), self.textsizes)\r\n text_map = self.get_map(text)\r\n \r\n # offset for all characters in the merging of all texts\r\n offset = np.hstack((0., np.cumsum(text_map[:, 2])[:-1]))\r\n \r\n # for each text, the cumsum of the length of all texts strictly\r\n # before\r\n d = np.hstack(([0], np.cumsum(self.textsizes)[:-1]))\r\n \r\n # compensate the offsets for the length of each text\r\n offset -= np.repeat(offset[d], self.textsizes)\r\n \r\n text_width = 0.\r\n \r\n else:\r\n self.textsizes = len(text)\r\n text_map = self.get_map(text)\r\n offset = np.hstack((0., np.cumsum(text_map[:, 2])[:-1])) \r\n text_width = offset[-1]\r\n index = np.zeros(len(text))\r\n \r\n self.size = len(text)\r\n \r\n d = dict(text_map=text_map, offset=offset, text_width=text_width,\r\n index=index)\r\n d.update(self.position_compound(coordinates))\r\n \r\n return d\r\n \r\n def initialize_font(self, font, fontsize):\r\n \"\"\"Initialize the specified font at a given size.\"\"\"\r\n self.texture, self.matrix, self.get_map = load_font(font, fontsize)\r\n\r\n def initialize(self, text, coordinates=(0., 0.), font='segoe', fontsize=24,\r\n color=None, letter_spacing=None, interline=0., autocolor=None,\r\n background_transparent=True,\r\n prevent_constrain=False, depth=None, posoffset=None):\r\n \"\"\"Initialize the text template.\"\"\"\r\n \r\n if prevent_constrain:\r\n self.constrain_ratio = False\r\n \r\n if autocolor is not None:\r\n color = get_color(autocolor)\r\n \r\n if color is None:\r\n color = self.default_color\r\n \r\n self.size = len(text)\r\n self.primitive_type = 'POINTS'\r\n self.interline = interline\r\n \r\n text_length = self.size\r\n self.initialize_font(font, fontsize)\r\n self.coordinates = coordinates\r\n \r\n point_size = float(self.matrix[:,4].max() * self.texture.shape[1])\r\n\r\n # template attributes and varyings\r\n self.add_attribute(\"position\", vartype=\"float\", ndim=2, data=np.zeros((self.size, 2)))\r\n \r\n self.add_attribute(\"offset\", vartype=\"float\", ndim=1)\r\n self.add_attribute(\"index\", vartype=\"float\", ndim=1)\r\n self.add_attribute(\"text_map\", vartype=\"float\", ndim=4)\r\n self.add_varying(\"flat_text_map\", vartype=\"float\", flat=True, ndim=4)\r\n \r\n if posoffset is None:\r\n posoffset = (0., 0.)\r\n self.add_uniform('posoffset', vartype='float', ndim=2, data=posoffset)\r\n \r\n # texture\r\n self.add_texture(\"tex_sampler\", size=self.texture.shape[:2], ndim=2,\r\n ncomponents=self.texture.shape[2],\r\n data=self.texture)\r\n \r\n # pure heuristic (probably bogus)\r\n if letter_spacing is None:\r\n letter_spacing = (100 + 17. * fontsize)\r\n self.add_uniform(\"spacing\", vartype=\"float\", ndim=2,\r\n data=(letter_spacing, interline))\r\n self.add_uniform(\"point_size\", vartype=\"float\", ndim=1,\r\n data=point_size)\r\n # one color per\r\n if isinstance(color, np.ndarray) and color.ndim > 1:\r\n self.add_attribute('color0', vartype=\"float\", ndim=4, data=color)\r\n self.add_varying('color', vartype=\"float\", ndim=4)\r\n self.add_vertex_main('color = color0;')\r\n else:\r\n self.add_uniform(\"color\", vartype=\"float\", ndim=4, data=color)\r\n self.add_uniform(\"text_width\", vartype=\"float\", ndim=1)\r\n \r\n # compound variables\r\n self.add_compound(\"text\", fun=self.text_compound, data=text)\r\n self.add_compound(\"coordinates\", fun=self.position_compound, data=coordinates)\r\n\r\n # vertex shader\r\n self.add_vertex_main(VS, after='viewport')\r\n\r\n # fragment shader\r\n self.add_fragment_main(FS(background_transparent))\r\n \r\n self.depth = depth"},"middle":{"kind":"string","value":"x = delta * x;\r\nif ((x >= 0) && (x <= 1))\r\n{\r\n // coordinates of the character in the font atlas\r"},"fim_type":{"kind":"string","value":"random_line_split"}}},{"rowIdx":236044,"cells":{"file_name":{"kind":"string","value":"three-effectcomposer.d.ts"},"prefix":{"kind":"string","value":"import { WebGLRenderTarget, WebGLRenderer } from \"./three-core\";\nimport { ShaderPass } from \"./three-shaderpass\";\n\nexport class EffectComposer {\n constructor(renderer: WebGLRenderer, renderTarget?: WebGLRenderTarget);\n\n renderTarget1: WebGLRenderTarget;\n renderTarget2: WebGLRenderTarget;\n writeBuffer: WebGLRenderTarget;\n readBuffer: WebGLRenderTarget;\n passes: Pass[];\n copyPass: ShaderPass;\n\n swapBuffers(): void;\n\n addPass(pass: any): void;\n\n insertPass(pass: any, index: number): void;\n\n render(delta?: number): void;\n\n reset(renderTarget?: WebGLRenderTarget): void;\n\n setSize(width: number, height: number): void;\n}\n\n\nexport class Pass{\n // if set to true, the pass is processed by the composer\n\tenabled: boolean;\n"},"suffix":{"kind":"string","value":"\n\t// if set to true, the result of the pass is rendered to screen\n renderToScreen: boolean;\n \n setSize(width: number, height:number ): void;\n\n render(renderer: WebGLRenderer, writeBuffer: WebGLRenderTarget, readBuffer: WebGLRenderTarget, delta: number, maskActive?: boolean): void;\n}"},"middle":{"kind":"string","value":"\t// if set to true, the pass indicates to swap read and write buffer after rendering\n\tneedsSwap: boolean;\n\n\t// if set to true, the pass clears its buffer before rendering\n\tclear: boolean;"},"fim_type":{"kind":"string","value":"random_line_split"}}},{"rowIdx":236045,"cells":{"file_name":{"kind":"string","value":"three-effectcomposer.d.ts"},"prefix":{"kind":"string","value":"import { WebGLRenderTarget, WebGLRenderer } from \"./three-core\";\nimport { ShaderPass } from \"./three-shaderpass\";\n\nexport class EffectComposer {\n constructor(renderer: WebGLRenderer, renderTarget?: WebGLRenderTarget);\n\n renderTarget1: WebGLRenderTarget;\n renderTarget2: WebGLRenderTarget;\n writeBuffer: WebGLRenderTarget;\n readBuffer: WebGLRenderTarget;\n passes: Pass[];\n copyPass: ShaderPass;\n\n swapBuffers(): void;\n\n addPass(pass: any): void;\n\n insertPass(pass: any, index: number): void;\n\n render(delta?: number): void;\n\n reset(renderTarget?: WebGLRenderTarget): void;\n\n setSize(width: number, height: number): void;\n}\n\n\nexport class "},"suffix":{"kind":"string","value":"{\n // if set to true, the pass is processed by the composer\n\tenabled: boolean;\n\n\t// if set to true, the pass indicates to swap read and write buffer after rendering\n\tneedsSwap: boolean;\n\n\t// if set to true, the pass clears its buffer before rendering\n\tclear: boolean;\n\n\t// if set to true, the result of the pass is rendered to screen\n renderToScreen: boolean;\n \n setSize(width: number, height:number ): void;\n\n render(renderer: WebGLRenderer, writeBuffer: WebGLRenderTarget, readBuffer: WebGLRenderTarget, delta: number, maskActive?: boolean): void;\n}"},"middle":{"kind":"string","value":"Pass"},"fim_type":{"kind":"string","value":"identifier_name"}}},{"rowIdx":236046,"cells":{"file_name":{"kind":"string","value":"toys.py"},"prefix":{"kind":"string","value":"from minieigen import *\nfrom woo.dem import *\nimport woo.core, woo.models\nfrom math import *\nimport numpy\n\n\nclass PourFeliciter(woo.core.Preprocessor,woo.pyderived.PyWooObject):\n '''Showcase for custom packing predicates, and importing surfaces from STL.'''\n _classTraits=None\n _PAT=woo.pyderived.PyAttrTrait # less typing\n _attrTraits=[\n ]\n def __init__(self,**kw):\n woo.core.Preprocessor.__init__(self)\n self.wooPyInit(self.__class__,woo.core.Preprocessor,**kw)\n def __call__(self):\n # preprocessor builds the simulation when called\n pass\n\nclass NewtonsCradle(woo.core.Preprocessor,woo.pyderived.PyWooObject):\n '''Showcase for custom packing predicates, and importing surfaces from STL.'''\n _classTraits=None\n _PAT=woo.pyderived.PyAttrTrait # less typing\n _attrTraits=[\n _PAT(int,'nSpheres',5,'Total number of spheres'),\n _PAT(int,'nFall',1,'The number of spheres which are out of the equilibrium position at the beginning.'),\n _PAT(float,'fallAngle',pi/4.,unit='deg',doc='Initial angle of falling spheres.'),\n _PAT(float,'rad',.005,unit='m',doc='Radius of spheres'),\n _PAT(Vector2,'cabHtWd',(.1,.1),unit='m',doc='Height and width of the suspension'),\n _PAT(float,'cabRad',.0005,unit='m',doc='Radius of the suspending cables'),\n _PAT(woo.models.ContactModelSelector,'model',woo.models.ContactModelSelector(name='Hertz',restitution=.99,numMat=(1,2),matDesc=['spheres','cables'],mats=[FrictMat(density=3e3,young=2e8),FrictMat(density=.001,young=2e8)]),doc='Select contact model. The first material is for spheres; the second, optional, material, is for the suspension cables.'),\n _PAT(Vector3,'gravity',(0,0,-9.81),'Gravity acceleration'),\n _PAT(int,'plotEvery',10,'How often to collect plot data'),\n _PAT(float,'dtSafety',.7,':obj:`woo.core.Scene.dtSafety`')\n ]\n def __init__(self,**kw):\n woo.core.Preprocessor.__init__(self)\n self.wooPyInit(self.__class__,woo.core.Preprocessor,**kw)\n def __call__(self):\n "},"suffix":{"kind":"string","value":"\n\n\n\n"},"middle":{"kind":"string","value":"pre=self\n S=woo.core.Scene(fields=[DemField(gravity=pre.gravity)],dtSafety=self.dtSafety)\n S.pre=pre.deepcopy()\n\n # preprocessor builds the simulation when called\n xx=numpy.linspace(0,(pre.nSpheres-1)*2*pre.rad,num=pre.nSpheres)\n mat=pre.model.mats[0]\n cabMat=(pre.model.mats[1] if len(pre.model.mats)>1 else mat)\n ht=pre.cabHtWd[0]\n for i,x in enumerate(xx):\n color=min(.999,(x/xx[-1]))\n s=Sphere.make((x,0,0) if i>=pre.nFall else (x-ht*sin(pre.fallAngle),0,ht-ht*cos(pre.fallAngle)),radius=pre.rad,mat=mat,color=color)\n n=s.shape.nodes[0]\n S.dem.par.add(s)\n # sphere's node is integrated\n S.dem.nodesAppend(n)\n for p in [Vector3(x,-pre.cabHtWd[1]/2,pre.cabHtWd[0]),Vector3(x,pre.cabHtWd[1]/2,pre.cabHtWd[0])]:\n t=Truss.make([n,p],radius=pre.cabRad,wire=False,color=color,mat=cabMat,fixed=None)\n t.shape.nodes[1].blocked='xyzXYZ'\n S.dem.par.add(t)\n S.engines=DemField.minimalEngines(model=pre.model,dynDtPeriod=20)+[\n IntraForce([In2_Truss_ElastMat()]),\n woo.core.PyRunner(self.plotEvery,'S.plot.addData(i=S.step,t=S.time,total=S.energy.total(),relErr=(S.energy.relErr() if S.step>1000 else 0),**S.energy)'),\n ]\n S.lab.dynDt.maxRelInc=1e-6\n S.trackEnergy=True\n S.plot.plots={'i':('total','**S.energy')}\n\n return S"},"fim_type":{"kind":"string","value":"identifier_body"}}},{"rowIdx":236047,"cells":{"file_name":{"kind":"string","value":"toys.py"},"prefix":{"kind":"string","value":"from minieigen import *\nfrom woo.dem import *\nimport woo.core, woo.models\nfrom math import *\nimport numpy\n\n\nclass PourFeliciter(woo.core.Preprocessor,woo.pyderived.PyWooObject):\n '''Showcase for custom packing predicates, and importing surfaces from STL.'''\n _classTraits=None\n _PAT=woo.pyderived.PyAttrTrait # less typing\n _attrTraits=[\n ]\n def __init__(self,**kw):\n woo.core.Preprocessor.__init__(self)\n self.wooPyInit(self.__class__,woo.core.Preprocessor,**kw)\n def "},"suffix":{"kind":"string","value":"(self):\n # preprocessor builds the simulation when called\n pass\n\nclass NewtonsCradle(woo.core.Preprocessor,woo.pyderived.PyWooObject):\n '''Showcase for custom packing predicates, and importing surfaces from STL.'''\n _classTraits=None\n _PAT=woo.pyderived.PyAttrTrait # less typing\n _attrTraits=[\n _PAT(int,'nSpheres',5,'Total number of spheres'),\n _PAT(int,'nFall',1,'The number of spheres which are out of the equilibrium position at the beginning.'),\n _PAT(float,'fallAngle',pi/4.,unit='deg',doc='Initial angle of falling spheres.'),\n _PAT(float,'rad',.005,unit='m',doc='Radius of spheres'),\n _PAT(Vector2,'cabHtWd',(.1,.1),unit='m',doc='Height and width of the suspension'),\n _PAT(float,'cabRad',.0005,unit='m',doc='Radius of the suspending cables'),\n _PAT(woo.models.ContactModelSelector,'model',woo.models.ContactModelSelector(name='Hertz',restitution=.99,numMat=(1,2),matDesc=['spheres','cables'],mats=[FrictMat(density=3e3,young=2e8),FrictMat(density=.001,young=2e8)]),doc='Select contact model. The first material is for spheres; the second, optional, material, is for the suspension cables.'),\n _PAT(Vector3,'gravity',(0,0,-9.81),'Gravity acceleration'),\n _PAT(int,'plotEvery',10,'How often to collect plot data'),\n _PAT(float,'dtSafety',.7,':obj:`woo.core.Scene.dtSafety`')\n ]\n def __init__(self,**kw):\n woo.core.Preprocessor.__init__(self)\n self.wooPyInit(self.__class__,woo.core.Preprocessor,**kw)\n def __call__(self):\n pre=self\n S=woo.core.Scene(fields=[DemField(gravity=pre.gravity)],dtSafety=self.dtSafety)\n S.pre=pre.deepcopy()\n\n # preprocessor builds the simulation when called\n xx=numpy.linspace(0,(pre.nSpheres-1)*2*pre.rad,num=pre.nSpheres)\n mat=pre.model.mats[0]\n cabMat=(pre.model.mats[1] if len(pre.model.mats)>1 else mat)\n ht=pre.cabHtWd[0]\n for i,x in enumerate(xx):\n color=min(.999,(x/xx[-1]))\n s=Sphere.make((x,0,0) if i>=pre.nFall else (x-ht*sin(pre.fallAngle),0,ht-ht*cos(pre.fallAngle)),radius=pre.rad,mat=mat,color=color)\n n=s.shape.nodes[0]\n S.dem.par.add(s)\n # sphere's node is integrated\n S.dem.nodesAppend(n)\n for p in [Vector3(x,-pre.cabHtWd[1]/2,pre.cabHtWd[0]),Vector3(x,pre.cabHtWd[1]/2,pre.cabHtWd[0])]:\n t=Truss.make([n,p],radius=pre.cabRad,wire=False,color=color,mat=cabMat,fixed=None)\n t.shape.nodes[1].blocked='xyzXYZ'\n S.dem.par.add(t)\n S.engines=DemField.minimalEngines(model=pre.model,dynDtPeriod=20)+[\n IntraForce([In2_Truss_ElastMat()]),\n woo.core.PyRunner(self.plotEvery,'S.plot.addData(i=S.step,t=S.time,total=S.energy.total(),relErr=(S.energy.relErr() if S.step>1000 else 0),**S.energy)'),\n ]\n S.lab.dynDt.maxRelInc=1e-6\n S.trackEnergy=True\n S.plot.plots={'i':('total','**S.energy')}\n\n return S\n\n\n\n"},"middle":{"kind":"string","value":"__call__"},"fim_type":{"kind":"string","value":"identifier_name"}}},{"rowIdx":236048,"cells":{"file_name":{"kind":"string","value":"toys.py"},"prefix":{"kind":"string","value":"from minieigen import *\nfrom woo.dem import *\nimport woo.core, woo.models\nfrom math import *\nimport numpy\n\n\nclass PourFeliciter(woo.core.Preprocessor,woo.pyderived.PyWooObject):\n '''Showcase for custom packing predicates, and importing surfaces from STL.'''\n _classTraits=None\n _PAT=woo.pyderived.PyAttrTrait # less typing\n _attrTraits=[\n ]\n def __init__(self,**kw):\n woo.core.Preprocessor.__init__(self)\n self.wooPyInit(self.__class__,woo.core.Preprocessor,**kw)\n def __call__(self):\n # preprocessor builds the simulation when called\n pass\n\nclass NewtonsCradle(woo.core.Preprocessor,woo.pyderived.PyWooObject):\n '''Showcase for custom packing predicates, and importing surfaces from STL.'''\n _classTraits=None\n _PAT=woo.pyderived.PyAttrTrait # less typing\n _attrTraits=[\n _PAT(int,'nSpheres',5,'Total number of spheres'),\n _PAT(int,'nFall',1,'The number of spheres which are out of the equilibrium position at the beginning.'),\n _PAT(float,'fallAngle',pi/4.,unit='deg',doc='Initial angle of falling spheres.'),\n _PAT(float,'rad',.005,unit='m',doc='Radius of spheres'),\n _PAT(Vector2,'cabHtWd',(.1,.1),unit='m',doc='Height and width of the suspension'),\n _PAT(float,'cabRad',.0005,unit='m',doc='Radius of the suspending cables'),\n _PAT(woo.models.ContactModelSelector,'model',woo.models.ContactModelSelector(name='Hertz',restitution=.99,numMat=(1,2),matDesc=['spheres','cables'],mats=[FrictMat(density=3e3,young=2e8),FrictMat(density=.001,young=2e8)]),doc='Select contact model. The first material is for spheres; the second, optional, material, is for the suspension cables.'),\n _PAT(Vector3,'gravity',(0,0,-9.81),'Gravity acceleration'),\n _PAT(int,'plotEvery',10,'How often to collect plot data'),\n _PAT(float,'dtSafety',.7,':obj:`woo.core.Scene.dtSafety`')\n ]\n def __init__(self,**kw):\n woo.core.Preprocessor.__init__(self)\n self.wooPyInit(self.__class__,woo.core.Preprocessor,**kw)\n def __call__(self):\n pre=self\n S=woo.core.Scene(fields=[DemField(gravity=pre.gravity)],dtSafety=self.dtSafety)\n S.pre=pre.deepcopy()\n\n # preprocessor builds the simulation when called\n xx=numpy.linspace(0,(pre.nSpheres-1)*2*pre.rad,num=pre.nSpheres)\n mat=pre.model.mats[0]\n cabMat=(pre.model.mats[1] if len(pre.model.mats)>1 else mat)\n ht=pre.cabHtWd[0]\n for i,x in enumerate(xx):\n "},"suffix":{"kind":"string","value":"\n S.engines=DemField.minimalEngines(model=pre.model,dynDtPeriod=20)+[\n IntraForce([In2_Truss_ElastMat()]),\n woo.core.PyRunner(self.plotEvery,'S.plot.addData(i=S.step,t=S.time,total=S.energy.total(),relErr=(S.energy.relErr() if S.step>1000 else 0),**S.energy)'),\n ]\n S.lab.dynDt.maxRelInc=1e-6\n S.trackEnergy=True\n S.plot.plots={'i':('total','**S.energy')}\n\n return S\n\n\n\n"},"middle":{"kind":"string","value":"color=min(.999,(x/xx[-1]))\n s=Sphere.make((x,0,0) if i>=pre.nFall else (x-ht*sin(pre.fallAngle),0,ht-ht*cos(pre.fallAngle)),radius=pre.rad,mat=mat,color=color)\n n=s.shape.nodes[0]\n S.dem.par.add(s)\n # sphere's node is integrated\n S.dem.nodesAppend(n)\n for p in [Vector3(x,-pre.cabHtWd[1]/2,pre.cabHtWd[0]),Vector3(x,pre.cabHtWd[1]/2,pre.cabHtWd[0])]:\n t=Truss.make([n,p],radius=pre.cabRad,wire=False,color=color,mat=cabMat,fixed=None)\n t.shape.nodes[1].blocked='xyzXYZ'\n S.dem.par.add(t)"},"fim_type":{"kind":"string","value":"conditional_block"}}},{"rowIdx":236049,"cells":{"file_name":{"kind":"string","value":"toys.py"},"prefix":{"kind":"string","value":"from minieigen import *\nfrom woo.dem import *\nimport woo.core, woo.models\nfrom math import *\nimport numpy\n\n\nclass PourFeliciter(woo.core.Preprocessor,woo.pyderived.PyWooObject):\n '''Showcase for custom packing predicates, and importing surfaces from STL.'''\n _classTraits=None\n _PAT=woo.pyderived.PyAttrTrait # less typing\n _attrTraits=[\n ]\n def __init__(self,**kw):\n woo.core.Preprocessor.__init__(self)\n self.wooPyInit(self.__class__,woo.core.Preprocessor,**kw)\n def __call__(self):\n # preprocessor builds the simulation when called\n pass\n\nclass NewtonsCradle(woo.core.Preprocessor,woo.pyderived.PyWooObject):\n '''Showcase for custom packing predicates, and importing surfaces from STL.'''\n _classTraits=None\n _PAT=woo.pyderived.PyAttrTrait # less typing\n _attrTraits=[\n _PAT(int,'nSpheres',5,'Total number of spheres'),\n _PAT(int,'nFall',1,'The number of spheres which are out of the equilibrium position at the beginning.'),\n _PAT(float,'fallAngle',pi/4.,unit='deg',doc='Initial angle of falling spheres.'),\n _PAT(float,'rad',.005,unit='m',doc='Radius of spheres'),\n _PAT(Vector2,'cabHtWd',(.1,.1),unit='m',doc='Height and width of the suspension'),\n _PAT(float,'cabRad',.0005,unit='m',doc='Radius of the suspending cables'),\n _PAT(woo.models.ContactModelSelector,'model',woo.models.ContactModelSelector(name='Hertz',restitution=.99,numMat=(1,2),matDesc=['spheres','cables'],mats=[FrictMat(density=3e3,young=2e8),FrictMat(density=.001,young=2e8)]),doc='Select contact model. The first material is for spheres; the second, optional, material, is for the suspension cables.'),\n _PAT(Vector3,'gravity',(0,0,-9.81),'Gravity acceleration'),"},"suffix":{"kind":"string","value":" woo.core.Preprocessor.__init__(self)\n self.wooPyInit(self.__class__,woo.core.Preprocessor,**kw)\n def __call__(self):\n pre=self\n S=woo.core.Scene(fields=[DemField(gravity=pre.gravity)],dtSafety=self.dtSafety)\n S.pre=pre.deepcopy()\n\n # preprocessor builds the simulation when called\n xx=numpy.linspace(0,(pre.nSpheres-1)*2*pre.rad,num=pre.nSpheres)\n mat=pre.model.mats[0]\n cabMat=(pre.model.mats[1] if len(pre.model.mats)>1 else mat)\n ht=pre.cabHtWd[0]\n for i,x in enumerate(xx):\n color=min(.999,(x/xx[-1]))\n s=Sphere.make((x,0,0) if i>=pre.nFall else (x-ht*sin(pre.fallAngle),0,ht-ht*cos(pre.fallAngle)),radius=pre.rad,mat=mat,color=color)\n n=s.shape.nodes[0]\n S.dem.par.add(s)\n # sphere's node is integrated\n S.dem.nodesAppend(n)\n for p in [Vector3(x,-pre.cabHtWd[1]/2,pre.cabHtWd[0]),Vector3(x,pre.cabHtWd[1]/2,pre.cabHtWd[0])]:\n t=Truss.make([n,p],radius=pre.cabRad,wire=False,color=color,mat=cabMat,fixed=None)\n t.shape.nodes[1].blocked='xyzXYZ'\n S.dem.par.add(t)\n S.engines=DemField.minimalEngines(model=pre.model,dynDtPeriod=20)+[\n IntraForce([In2_Truss_ElastMat()]),\n woo.core.PyRunner(self.plotEvery,'S.plot.addData(i=S.step,t=S.time,total=S.energy.total(),relErr=(S.energy.relErr() if S.step>1000 else 0),**S.energy)'),\n ]\n S.lab.dynDt.maxRelInc=1e-6\n S.trackEnergy=True\n S.plot.plots={'i':('total','**S.energy')}\n\n return S"},"middle":{"kind":"string","value":" _PAT(int,'plotEvery',10,'How often to collect plot data'),\n _PAT(float,'dtSafety',.7,':obj:`woo.core.Scene.dtSafety`')\n ]\n def __init__(self,**kw):"},"fim_type":{"kind":"string","value":"random_line_split"}}},{"rowIdx":236050,"cells":{"file_name":{"kind":"string","value":"periph_uart_if.py"},"prefix":{"kind":"string","value":"# Copyright (c) 2018 Kevin Weiss, for HAW Hamburg \n#\n# This file is subject to the terms and conditions of the GNU Lesser\n# General Public License v2.1. See the file LICENSE in the top level\n# directory for more details.\n\"\"\"@package PyToAPI\nThis module handles parsing of information from RIOT periph_uart test.\n\"\"\"\ntry:\n from riot_pal import DutShell"},"suffix":{"kind":"string","value":" raise ImportError('Cannot find riot_pal, try \"pip install riot_pal\"')\n\n\nclass PeriphUartIf(DutShell):\n \"\"\"Interface to the node with periph_uart firmware.\"\"\"\n\n def uart_init(self, dev, baud):\n \"\"\"Initialize DUT's UART.\"\"\"\n return self.send_cmd(\"init {} {}\".format(dev, baud))\n\n def uart_mode(self, dev, data_bits, parity, stop_bits):\n \"\"\"Setup databits, parity and stopbits.\"\"\"\n return self.send_cmd(\n \"mode {} {} {} {}\".format(dev, data_bits, parity, stop_bits))\n\n def uart_send_string(self, dev, test_string):\n \"\"\"Send data via DUT's UART.\"\"\"\n return self.send_cmd(\"send {} {}\".format(dev, test_string))"},"middle":{"kind":"string","value":"except ImportError:"},"fim_type":{"kind":"string","value":"random_line_split"}}},{"rowIdx":236051,"cells":{"file_name":{"kind":"string","value":"periph_uart_if.py"},"prefix":{"kind":"string","value":"# Copyright (c) 2018 Kevin Weiss, for HAW Hamburg \n#\n# This file is subject to the terms and conditions of the GNU Lesser\n# General Public License v2.1. See the file LICENSE in the top level\n# directory for more details.\n\"\"\"@package PyToAPI\nThis module handles parsing of information from RIOT periph_uart test.\n\"\"\"\ntry:\n from riot_pal import DutShell\nexcept ImportError:\n raise ImportError('Cannot find riot_pal, try \"pip install riot_pal\"')\n\n\nclass PeriphUartIf(DutShell):\n \"\"\"Interface to the node with periph_uart firmware.\"\"\"\n\n def uart_init(self, dev, baud):\n "},"suffix":{"kind":"string","value":"\n\n def uart_mode(self, dev, data_bits, parity, stop_bits):\n \"\"\"Setup databits, parity and stopbits.\"\"\"\n return self.send_cmd(\n \"mode {} {} {} {}\".format(dev, data_bits, parity, stop_bits))\n\n def uart_send_string(self, dev, test_string):\n \"\"\"Send data via DUT's UART.\"\"\"\n return self.send_cmd(\"send {} {}\".format(dev, test_string))\n"},"middle":{"kind":"string","value":"\"\"\"Initialize DUT's UART.\"\"\"\n return self.send_cmd(\"init {} {}\".format(dev, baud))"},"fim_type":{"kind":"string","value":"identifier_body"}}},{"rowIdx":236052,"cells":{"file_name":{"kind":"string","value":"periph_uart_if.py"},"prefix":{"kind":"string","value":"# Copyright (c) 2018 Kevin Weiss, for HAW Hamburg \n#\n# This file is subject to the terms and conditions of the GNU Lesser\n# General Public License v2.1. See the file LICENSE in the top level\n# directory for more details.\n\"\"\"@package PyToAPI\nThis module handles parsing of information from RIOT periph_uart test.\n\"\"\"\ntry:\n from riot_pal import DutShell\nexcept ImportError:\n raise ImportError('Cannot find riot_pal, try \"pip install riot_pal\"')\n\n\nclass PeriphUartIf(DutShell):\n \"\"\"Interface to the node with periph_uart firmware.\"\"\"\n\n def uart_init(self, dev, baud):\n \"\"\"Initialize DUT's UART.\"\"\"\n return self.send_cmd(\"init {} {}\".format(dev, baud))\n\n def uart_mode(self, dev, data_bits, parity, stop_bits):\n \"\"\"Setup databits, parity and stopbits.\"\"\"\n return self.send_cmd(\n \"mode {} {} {} {}\".format(dev, data_bits, parity, stop_bits))\n\n def "},"suffix":{"kind":"string","value":"(self, dev, test_string):\n \"\"\"Send data via DUT's UART.\"\"\"\n return self.send_cmd(\"send {} {}\".format(dev, test_string))\n"},"middle":{"kind":"string","value":"uart_send_string"},"fim_type":{"kind":"string","value":"identifier_name"}}},{"rowIdx":236053,"cells":{"file_name":{"kind":"string","value":"tag.component.ts"},"prefix":{"kind":"string","value":"// Copyright (c) 2017 VMware, Inc. All Rights Reserved.\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.\nimport {\n Component,\n OnInit,\n ViewChild,\n Input,\n Output,\n EventEmitter,\n ChangeDetectionStrategy,\n ChangeDetectorRef,\n ElementRef,\n OnDestroy\n} from '@angular/core';\n\nimport { TagService } from '../service/tag.service';\n\nimport { ErrorHandler } from '../error-handler/error-handler';\nimport { ConfirmationTargets, ConfirmationState, ConfirmationButtons } from '../shared/shared.const';\n\nimport { ConfirmationDialogComponent } from '../confirmation-dialog/confirmation-dialog.component';\nimport { ConfirmationMessage } from '../confirmation-dialog/confirmation-message';\nimport { ConfirmationAcknowledgement } from '../confirmation-dialog/confirmation-state-message';\n\nimport { Tag, TagClickEvent } from '../service/interface';\n\nimport { TAG_TEMPLATE } from './tag.component.html';\nimport { TAG_STYLE } from './tag.component.css';\n\nimport { toPromise, CustomComparator, VULNERABILITY_SCAN_STATUS } from '../utils';\n\nimport { TranslateService } from '@ngx-translate/core';\n\nimport { State, Comparator } from 'clarity-angular';\n\nimport { ScanningResultService } from '../service/index';\n\nimport { Observable, Subscription } from 'rxjs/Rx';\n\nconst STATE_CHECK_INTERVAL: number = 2000;//2s\n\n@Component({\n selector: 'hbr-tag',\n template: TAG_TEMPLATE,\n styles: [TAG_STYLE],\n changeDetection: ChangeDetectionStrategy.OnPush\n})\nexport class TagComponent implements OnInit, OnDestroy {\n\n @Input() projectId: number;\n @Input() repoName: string;\n @Input() isEmbedded: boolean;\n\n @Input() hasSignedIn: boolean;\n @Input() hasProjectAdminRole: boolean;\n @Input() registryUrl: string;\n @Input() withNotary: boolean;\n @Input() withClair: boolean;\n\n @Output() refreshRepo = new EventEmitter();\n @Output() tagClickEvent = new EventEmitter();\n\n tags: Tag[];\n\n\n showTagManifestOpened: boolean;\n manifestInfoTitle: string;\n digestId: string;\n staticBackdrop: boolean = true;\n closable: boolean = false;\n\n createdComparator: Comparator = new CustomComparator('created', 'date');\n\n loading: boolean = false;\n\n stateCheckTimer: Subscription;\n tagsInScanning: { [key: string]: any } = {};\n scanningTagCount: number = 0;\n\n copyFailed: boolean = false;\n\n @ViewChild('confirmationDialog')\n confirmationDialog: ConfirmationDialogComponent;\n\n @ViewChild('digestTarget') textInput: ElementRef;\n\n constructor(\n private errorHandler: ErrorHandler,\n private tagService: TagService,\n private translateService: TranslateService,\n private scanningService: ScanningResultService,\n private ref: ChangeDetectorRef) { }\n\n confirmDeletion(message: ConfirmationAcknowledgement) {\n if (message &&\n message.source === ConfirmationTargets.TAG\n && message.state === ConfirmationState.CONFIRMED) {\n let tag: Tag = message.data;\n if (tag) {\n if (tag.signature) {\n return;\n } else {\n toPromise(this.tagService\n .deleteTag(this.repoName, tag.name))\n .then(\n response => {\n this.retrieve();\n this.translateService.get('REPOSITORY.DELETED_TAG_SUCCESS')\n .subscribe(res => this.errorHandler.info(res));\n }).catch(error => this.errorHandler.error(error));\n }\n }\n }\n }\n\n ngOnInit() {\n if (!this.projectId) {\n this.errorHandler.error('Project ID cannot be unset.');\n return;\n }\n if (!this.repoName) {\n this.errorHandler.error('Repo name cannot be unset.');\n return;\n }\n\n this.retrieve();\n\n this.stateCheckTimer = Observable.timer(STATE_CHECK_INTERVAL, STATE_CHECK_INTERVAL).subscribe(() => {\n if (this.scanningTagCount > 0) {\n this.updateScanningStates();\n }\n });\n }\n\n ngOnDestroy(): void {\n if (this.stateCheckTimer) {\n this.stateCheckTimer.unsubscribe();\n }\n }\n\n retrieve() {\n this.tags = [];\n this.loading = true;"},"suffix":{"kind":"string","value":"\n toPromise(this.tagService\n .getTags(this.repoName))\n .then(items => {\n this.tags = items;\n this.loading = false;\n if (this.tags && this.tags.length === 0) {\n this.refreshRepo.emit(true);\n }\n })\n .catch(error => {\n this.errorHandler.error(error);\n this.loading = false;\n });\n let hnd = setInterval(() => this.ref.markForCheck(), 100);\n setTimeout(() => clearInterval(hnd), 1000);\n }\n\n deleteTag(tag: Tag) {\n if (tag) {\n let titleKey: string, summaryKey: string, content: string, buttons: ConfirmationButtons;\n if (tag.signature) {\n titleKey = 'REPOSITORY.DELETION_TITLE_TAG_DENIED';\n summaryKey = 'REPOSITORY.DELETION_SUMMARY_TAG_DENIED';\n buttons = ConfirmationButtons.CLOSE;\n content = 'notary -s https://' + this.registryUrl + ':4443 -d ~/.docker/trust remove -p ' + this.registryUrl + '/' + this.repoName + ' ' + tag.name;\n } else {\n titleKey = 'REPOSITORY.DELETION_TITLE_TAG';\n summaryKey = 'REPOSITORY.DELETION_SUMMARY_TAG';\n buttons = ConfirmationButtons.DELETE_CANCEL;\n content = tag.name;\n }\n let message = new ConfirmationMessage(\n titleKey,\n summaryKey,\n content,\n tag,\n ConfirmationTargets.TAG,\n buttons);\n this.confirmationDialog.open(message);\n }\n }\n\n showDigestId(tag: Tag) {\n if (tag) {\n this.manifestInfoTitle = 'REPOSITORY.COPY_DIGEST_ID';\n this.digestId = tag.digest;\n this.showTagManifestOpened = true;\n this.copyFailed = false;\n }\n }\n \n onTagClick(tag: Tag): void {\n if (tag) {\n let evt: TagClickEvent = {\n project_id: this.projectId,\n repository_name: this.repoName,\n tag_name: tag.name\n };\n this.tagClickEvent.emit(evt);\n }\n }\n\n scanTag(tagId: string): void {\n //Double check\n if (this.tagsInScanning[tagId]) {\n return;\n }\n toPromise(this.scanningService.startVulnerabilityScanning(this.repoName, tagId))\n .then(() => {\n //Add to scanning map\n this.tagsInScanning[tagId] = tagId;\n //Counting\n this.scanningTagCount += 1;\n })\n .catch(error => this.errorHandler.error(error));\n }\n\n updateScanningStates(): void {\n toPromise(this.tagService\n .getTags(this.repoName))\n .then(items => {\n console.debug(\"updateScanningStates called!\");\n //Reset the scanning states\n this.tagsInScanning = {};\n this.scanningTagCount = 0;\n\n items.forEach(item => {\n if (item.scan_overview) {\n if (item.scan_overview.scan_status === VULNERABILITY_SCAN_STATUS.pending ||\n item.scan_overview.scan_status === VULNERABILITY_SCAN_STATUS.running) {\n this.tagsInScanning[item.name] = item.name;\n this.scanningTagCount += 1;\n }\n }\n });\n\n this.tags = items;\n })\n .catch(error => {\n this.errorHandler.error(error);\n });\n let hnd = setInterval(() => this.ref.markForCheck(), 100);\n setTimeout(() => clearInterval(hnd), 1000);\n }\n\n onSuccess($event: any): void {\n this.copyFailed = false;\n //Directly close dialog\n this.showTagManifestOpened = false;\n }\n\n onError($event: any): void {\n //Show error\n this.copyFailed = true;\n //Select all text\n if(this.textInput){\n this.textInput.nativeElement.select();\n }\n }\n}"},"middle":{"kind":"string","value":""},"fim_type":{"kind":"string","value":"random_line_split"}}},{"rowIdx":236054,"cells":{"file_name":{"kind":"string","value":"tag.component.ts"},"prefix":{"kind":"string","value":"// Copyright (c) 2017 VMware, Inc. All Rights Reserved.\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.\nimport {\n Component,\n OnInit,\n ViewChild,\n Input,\n Output,\n EventEmitter,\n ChangeDetectionStrategy,\n ChangeDetectorRef,\n ElementRef,\n OnDestroy\n} from '@angular/core';\n\nimport { TagService } from '../service/tag.service';\n\nimport { ErrorHandler } from '../error-handler/error-handler';\nimport { ConfirmationTargets, ConfirmationState, ConfirmationButtons } from '../shared/shared.const';\n\nimport { ConfirmationDialogComponent } from '../confirmation-dialog/confirmation-dialog.component';\nimport { ConfirmationMessage } from '../confirmation-dialog/confirmation-message';\nimport { ConfirmationAcknowledgement } from '../confirmation-dialog/confirmation-state-message';\n\nimport { Tag, TagClickEvent } from '../service/interface';\n\nimport { TAG_TEMPLATE } from './tag.component.html';\nimport { TAG_STYLE } from './tag.component.css';\n\nimport { toPromise, CustomComparator, VULNERABILITY_SCAN_STATUS } from '../utils';\n\nimport { TranslateService } from '@ngx-translate/core';\n\nimport { State, Comparator } from 'clarity-angular';\n\nimport { ScanningResultService } from '../service/index';\n\nimport { Observable, Subscription } from 'rxjs/Rx';\n\nconst STATE_CHECK_INTERVAL: number = 2000;//2s\n\n@Component({\n selector: 'hbr-tag',\n template: TAG_TEMPLATE,\n styles: [TAG_STYLE],\n changeDetection: ChangeDetectionStrategy.OnPush\n})\nexport class "},"suffix":{"kind":"string","value":" implements OnInit, OnDestroy {\n\n @Input() projectId: number;\n @Input() repoName: string;\n @Input() isEmbedded: boolean;\n\n @Input() hasSignedIn: boolean;\n @Input() hasProjectAdminRole: boolean;\n @Input() registryUrl: string;\n @Input() withNotary: boolean;\n @Input() withClair: boolean;\n\n @Output() refreshRepo = new EventEmitter();\n @Output() tagClickEvent = new EventEmitter();\n\n tags: Tag[];\n\n\n showTagManifestOpened: boolean;\n manifestInfoTitle: string;\n digestId: string;\n staticBackdrop: boolean = true;\n closable: boolean = false;\n\n createdComparator: Comparator = new CustomComparator('created', 'date');\n\n loading: boolean = false;\n\n stateCheckTimer: Subscription;\n tagsInScanning: { [key: string]: any } = {};\n scanningTagCount: number = 0;\n\n copyFailed: boolean = false;\n\n @ViewChild('confirmationDialog')\n confirmationDialog: ConfirmationDialogComponent;\n\n @ViewChild('digestTarget') textInput: ElementRef;\n\n constructor(\n private errorHandler: ErrorHandler,\n private tagService: TagService,\n private translateService: TranslateService,\n private scanningService: ScanningResultService,\n private ref: ChangeDetectorRef) { }\n\n confirmDeletion(message: ConfirmationAcknowledgement) {\n if (message &&\n message.source === ConfirmationTargets.TAG\n && message.state === ConfirmationState.CONFIRMED) {\n let tag: Tag = message.data;\n if (tag) {\n if (tag.signature) {\n return;\n } else {\n toPromise(this.tagService\n .deleteTag(this.repoName, tag.name))\n .then(\n response => {\n this.retrieve();\n this.translateService.get('REPOSITORY.DELETED_TAG_SUCCESS')\n .subscribe(res => this.errorHandler.info(res));\n }).catch(error => this.errorHandler.error(error));\n }\n }\n }\n }\n\n ngOnInit() {\n if (!this.projectId) {\n this.errorHandler.error('Project ID cannot be unset.');\n return;\n }\n if (!this.repoName) {\n this.errorHandler.error('Repo name cannot be unset.');\n return;\n }\n\n this.retrieve();\n\n this.stateCheckTimer = Observable.timer(STATE_CHECK_INTERVAL, STATE_CHECK_INTERVAL).subscribe(() => {\n if (this.scanningTagCount > 0) {\n this.updateScanningStates();\n }\n });\n }\n\n ngOnDestroy(): void {\n if (this.stateCheckTimer) {\n this.stateCheckTimer.unsubscribe();\n }\n }\n\n retrieve() {\n this.tags = [];\n this.loading = true;\n\n toPromise(this.tagService\n .getTags(this.repoName))\n .then(items => {\n this.tags = items;\n this.loading = false;\n if (this.tags && this.tags.length === 0) {\n this.refreshRepo.emit(true);\n }\n })\n .catch(error => {\n this.errorHandler.error(error);\n this.loading = false;\n });\n let hnd = setInterval(() => this.ref.markForCheck(), 100);\n setTimeout(() => clearInterval(hnd), 1000);\n }\n\n deleteTag(tag: Tag) {\n if (tag) {\n let titleKey: string, summaryKey: string, content: string, buttons: ConfirmationButtons;\n if (tag.signature) {\n titleKey = 'REPOSITORY.DELETION_TITLE_TAG_DENIED';\n summaryKey = 'REPOSITORY.DELETION_SUMMARY_TAG_DENIED';\n buttons = ConfirmationButtons.CLOSE;\n content = 'notary -s https://' + this.registryUrl + ':4443 -d ~/.docker/trust remove -p ' + this.registryUrl + '/' + this.repoName + ' ' + tag.name;\n } else {\n titleKey = 'REPOSITORY.DELETION_TITLE_TAG';\n summaryKey = 'REPOSITORY.DELETION_SUMMARY_TAG';\n buttons = ConfirmationButtons.DELETE_CANCEL;\n content = tag.name;\n }\n let message = new ConfirmationMessage(\n titleKey,\n summaryKey,\n content,\n tag,\n ConfirmationTargets.TAG,\n buttons);\n this.confirmationDialog.open(message);\n }\n }\n\n showDigestId(tag: Tag) {\n if (tag) {\n this.manifestInfoTitle = 'REPOSITORY.COPY_DIGEST_ID';\n this.digestId = tag.digest;\n this.showTagManifestOpened = true;\n this.copyFailed = false;\n }\n }\n \n onTagClick(tag: Tag): void {\n if (tag) {\n let evt: TagClickEvent = {\n project_id: this.projectId,\n repository_name: this.repoName,\n tag_name: tag.name\n };\n this.tagClickEvent.emit(evt);\n }\n }\n\n scanTag(tagId: string): void {\n //Double check\n if (this.tagsInScanning[tagId]) {\n return;\n }\n toPromise(this.scanningService.startVulnerabilityScanning(this.repoName, tagId))\n .then(() => {\n //Add to scanning map\n this.tagsInScanning[tagId] = tagId;\n //Counting\n this.scanningTagCount += 1;\n })\n .catch(error => this.errorHandler.error(error));\n }\n\n updateScanningStates(): void {\n toPromise(this.tagService\n .getTags(this.repoName))\n .then(items => {\n console.debug(\"updateScanningStates called!\");\n //Reset the scanning states\n this.tagsInScanning = {};\n this.scanningTagCount = 0;\n\n items.forEach(item => {\n if (item.scan_overview) {\n if (item.scan_overview.scan_status === VULNERABILITY_SCAN_STATUS.pending ||\n item.scan_overview.scan_status === VULNERABILITY_SCAN_STATUS.running) {\n this.tagsInScanning[item.name] = item.name;\n this.scanningTagCount += 1;\n }\n }\n });\n\n this.tags = items;\n })\n .catch(error => {\n this.errorHandler.error(error);\n });\n let hnd = setInterval(() => this.ref.markForCheck(), 100);\n setTimeout(() => clearInterval(hnd), 1000);\n }\n\n onSuccess($event: any): void {\n this.copyFailed = false;\n //Directly close dialog\n this.showTagManifestOpened = false;\n }\n\n onError($event: any): void {\n //Show error\n this.copyFailed = true;\n //Select all text\n if(this.textInput){\n this.textInput.nativeElement.select();\n }\n }\n}"},"middle":{"kind":"string","value":"TagComponent"},"fim_type":{"kind":"string","value":"identifier_name"}}},{"rowIdx":236055,"cells":{"file_name":{"kind":"string","value":"tag.component.ts"},"prefix":{"kind":"string","value":"// Copyright (c) 2017 VMware, Inc. All Rights Reserved.\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.\nimport {\n Component,\n OnInit,\n ViewChild,\n Input,\n Output,\n EventEmitter,\n ChangeDetectionStrategy,\n ChangeDetectorRef,\n ElementRef,\n OnDestroy\n} from '@angular/core';\n\nimport { TagService } from '../service/tag.service';\n\nimport { ErrorHandler } from '../error-handler/error-handler';\nimport { ConfirmationTargets, ConfirmationState, ConfirmationButtons } from '../shared/shared.const';\n\nimport { ConfirmationDialogComponent } from '../confirmation-dialog/confirmation-dialog.component';\nimport { ConfirmationMessage } from '../confirmation-dialog/confirmation-message';\nimport { ConfirmationAcknowledgement } from '../confirmation-dialog/confirmation-state-message';\n\nimport { Tag, TagClickEvent } from '../service/interface';\n\nimport { TAG_TEMPLATE } from './tag.component.html';\nimport { TAG_STYLE } from './tag.component.css';\n\nimport { toPromise, CustomComparator, VULNERABILITY_SCAN_STATUS } from '../utils';\n\nimport { TranslateService } from '@ngx-translate/core';\n\nimport { State, Comparator } from 'clarity-angular';\n\nimport { ScanningResultService } from '../service/index';\n\nimport { Observable, Subscription } from 'rxjs/Rx';\n\nconst STATE_CHECK_INTERVAL: number = 2000;//2s\n\n@Component({\n selector: 'hbr-tag',\n template: TAG_TEMPLATE,\n styles: [TAG_STYLE],\n changeDetection: ChangeDetectionStrategy.OnPush\n})\nexport class TagComponent implements OnInit, OnDestroy {\n\n @Input() projectId: number;\n @Input() repoName: string;\n @Input() isEmbedded: boolean;\n\n @Input() hasSignedIn: boolean;\n @Input() hasProjectAdminRole: boolean;\n @Input() registryUrl: string;\n @Input() withNotary: boolean;\n @Input() withClair: boolean;\n\n @Output() refreshRepo = new EventEmitter();\n @Output() tagClickEvent = new EventEmitter();\n\n tags: Tag[];\n\n\n showTagManifestOpened: boolean;\n manifestInfoTitle: string;\n digestId: string;\n staticBackdrop: boolean = true;\n closable: boolean = false;\n\n createdComparator: Comparator = new CustomComparator('created', 'date');\n\n loading: boolean = false;\n\n stateCheckTimer: Subscription;\n tagsInScanning: { [key: string]: any } = {};\n scanningTagCount: number = 0;\n\n copyFailed: boolean = false;\n\n @ViewChild('confirmationDialog')\n confirmationDialog: ConfirmationDialogComponent;\n\n @ViewChild('digestTarget') textInput: ElementRef;\n\n constructor(\n private errorHandler: ErrorHandler,\n private tagService: TagService,\n private translateService: TranslateService,\n private scanningService: ScanningResultService,\n private ref: ChangeDetectorRef) { }\n\n confirmDeletion(message: ConfirmationAcknowledgement) {\n if (message &&\n message.source === ConfirmationTargets.TAG\n && message.state === ConfirmationState.CONFIRMED) {\n let tag: Tag = message.data;\n if (tag) {\n if (tag.signature) {\n return;\n } else {\n toPromise(this.tagService\n .deleteTag(this.repoName, tag.name))\n .then(\n response => {\n this.retrieve();\n this.translateService.get('REPOSITORY.DELETED_TAG_SUCCESS')\n .subscribe(res => this.errorHandler.info(res));\n }).catch(error => this.errorHandler.error(error));\n }\n }\n }\n }\n\n ngOnInit() {\n if (!this.projectId) {\n this.errorHandler.error('Project ID cannot be unset.');\n return;\n }\n if (!this.repoName) {\n this.errorHandler.error('Repo name cannot be unset.');\n return;\n }\n\n this.retrieve();\n\n this.stateCheckTimer = Observable.timer(STATE_CHECK_INTERVAL, STATE_CHECK_INTERVAL).subscribe(() => {\n if (this.scanningTagCount > 0) {\n this.updateScanningStates();\n }\n });\n }\n\n ngOnDestroy(): void {\n if (this.stateCheckTimer) {\n this.stateCheckTimer.unsubscribe();\n }\n }\n\n retrieve() {\n this.tags = [];\n this.loading = true;\n\n toPromise(this.tagService\n .getTags(this.repoName))\n .then(items => {\n this.tags = items;\n this.loading = false;\n if (this.tags && this.tags.length === 0) {\n this.refreshRepo.emit(true);\n }\n })\n .catch(error => {\n this.errorHandler.error(error);\n this.loading = false;\n });\n let hnd = setInterval(() => this.ref.markForCheck(), 100);\n setTimeout(() => clearInterval(hnd), 1000);\n }\n\n deleteTag(tag: Tag) {\n if (tag) {\n let titleKey: string, summaryKey: string, content: string, buttons: ConfirmationButtons;\n if (tag.signature) {\n titleKey = 'REPOSITORY.DELETION_TITLE_TAG_DENIED';\n summaryKey = 'REPOSITORY.DELETION_SUMMARY_TAG_DENIED';\n buttons = ConfirmationButtons.CLOSE;\n content = 'notary -s https://' + this.registryUrl + ':4443 -d ~/.docker/trust remove -p ' + this.registryUrl + '/' + this.repoName + ' ' + tag.name;\n } else {\n titleKey = 'REPOSITORY.DELETION_TITLE_TAG';\n summaryKey = 'REPOSITORY.DELETION_SUMMARY_TAG';\n buttons = ConfirmationButtons.DELETE_CANCEL;\n content = tag.name;\n }\n let message = new ConfirmationMessage(\n titleKey,\n summaryKey,\n content,\n tag,\n ConfirmationTargets.TAG,\n buttons);\n this.confirmationDialog.open(message);\n }\n }\n\n showDigestId(tag: Tag) {\n if (tag) {\n this.manifestInfoTitle = 'REPOSITORY.COPY_DIGEST_ID';\n this.digestId = tag.digest;\n this.showTagManifestOpened = true;\n this.copyFailed = false;\n }\n }\n \n onTagClick(tag: Tag): void {\n if (tag) {\n let evt: TagClickEvent = {\n project_id: this.projectId,\n repository_name: this.repoName,\n tag_name: tag.name\n };\n this.tagClickEvent.emit(evt);\n }\n }\n\n scanTag(tagId: string): void "},"suffix":{"kind":"string","value":"\n\n updateScanningStates(): void {\n toPromise(this.tagService\n .getTags(this.repoName))\n .then(items => {\n console.debug(\"updateScanningStates called!\");\n //Reset the scanning states\n this.tagsInScanning = {};\n this.scanningTagCount = 0;\n\n items.forEach(item => {\n if (item.scan_overview) {\n if (item.scan_overview.scan_status === VULNERABILITY_SCAN_STATUS.pending ||\n item.scan_overview.scan_status === VULNERABILITY_SCAN_STATUS.running) {\n this.tagsInScanning[item.name] = item.name;\n this.scanningTagCount += 1;\n }\n }\n });\n\n this.tags = items;\n })\n .catch(error => {\n this.errorHandler.error(error);\n });\n let hnd = setInterval(() => this.ref.markForCheck(), 100);\n setTimeout(() => clearInterval(hnd), 1000);\n }\n\n onSuccess($event: any): void {\n this.copyFailed = false;\n //Directly close dialog\n this.showTagManifestOpened = false;\n }\n\n onError($event: any): void {\n //Show error\n this.copyFailed = true;\n //Select all text\n if(this.textInput){\n this.textInput.nativeElement.select();\n }\n }\n}"},"middle":{"kind":"string","value":"{\n //Double check\n if (this.tagsInScanning[tagId]) {\n return;\n }\n toPromise(this.scanningService.startVulnerabilityScanning(this.repoName, tagId))\n .then(() => {\n //Add to scanning map\n this.tagsInScanning[tagId] = tagId;\n //Counting\n this.scanningTagCount += 1;\n })\n .catch(error => this.errorHandler.error(error));\n }"},"fim_type":{"kind":"string","value":"identifier_body"}}},{"rowIdx":236056,"cells":{"file_name":{"kind":"string","value":"tag.component.ts"},"prefix":{"kind":"string","value":"// Copyright (c) 2017 VMware, Inc. All Rights Reserved.\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.\nimport {\n Component,\n OnInit,\n ViewChild,\n Input,\n Output,\n EventEmitter,\n ChangeDetectionStrategy,\n ChangeDetectorRef,\n ElementRef,\n OnDestroy\n} from '@angular/core';\n\nimport { TagService } from '../service/tag.service';\n\nimport { ErrorHandler } from '../error-handler/error-handler';\nimport { ConfirmationTargets, ConfirmationState, ConfirmationButtons } from '../shared/shared.const';\n\nimport { ConfirmationDialogComponent } from '../confirmation-dialog/confirmation-dialog.component';\nimport { ConfirmationMessage } from '../confirmation-dialog/confirmation-message';\nimport { ConfirmationAcknowledgement } from '../confirmation-dialog/confirmation-state-message';\n\nimport { Tag, TagClickEvent } from '../service/interface';\n\nimport { TAG_TEMPLATE } from './tag.component.html';\nimport { TAG_STYLE } from './tag.component.css';\n\nimport { toPromise, CustomComparator, VULNERABILITY_SCAN_STATUS } from '../utils';\n\nimport { TranslateService } from '@ngx-translate/core';\n\nimport { State, Comparator } from 'clarity-angular';\n\nimport { ScanningResultService } from '../service/index';\n\nimport { Observable, Subscription } from 'rxjs/Rx';\n\nconst STATE_CHECK_INTERVAL: number = 2000;//2s\n\n@Component({\n selector: 'hbr-tag',\n template: TAG_TEMPLATE,\n styles: [TAG_STYLE],\n changeDetection: ChangeDetectionStrategy.OnPush\n})\nexport class TagComponent implements OnInit, OnDestroy {\n\n @Input() projectId: number;\n @Input() repoName: string;\n @Input() isEmbedded: boolean;\n\n @Input() hasSignedIn: boolean;\n @Input() hasProjectAdminRole: boolean;\n @Input() registryUrl: string;\n @Input() withNotary: boolean;\n @Input() withClair: boolean;\n\n @Output() refreshRepo = new EventEmitter();\n @Output() tagClickEvent = new EventEmitter();\n\n tags: Tag[];\n\n\n showTagManifestOpened: boolean;\n manifestInfoTitle: string;\n digestId: string;\n staticBackdrop: boolean = true;\n closable: boolean = false;\n\n createdComparator: Comparator = new CustomComparator('created', 'date');\n\n loading: boolean = false;\n\n stateCheckTimer: Subscription;\n tagsInScanning: { [key: string]: any } = {};\n scanningTagCount: number = 0;\n\n copyFailed: boolean = false;\n\n @ViewChild('confirmationDialog')\n confirmationDialog: ConfirmationDialogComponent;\n\n @ViewChild('digestTarget') textInput: ElementRef;\n\n constructor(\n private errorHandler: ErrorHandler,\n private tagService: TagService,\n private translateService: TranslateService,\n private scanningService: ScanningResultService,\n private ref: ChangeDetectorRef) { }\n\n confirmDeletion(message: ConfirmationAcknowledgement) {\n if (message &&\n message.source === ConfirmationTargets.TAG\n && message.state === ConfirmationState.CONFIRMED) {\n let tag: Tag = message.data;\n if (tag) {\n if (tag.signature) {\n return;\n } else {\n toPromise(this.tagService\n .deleteTag(this.repoName, tag.name))\n .then(\n response => {\n this.retrieve();\n this.translateService.get('REPOSITORY.DELETED_TAG_SUCCESS')\n .subscribe(res => this.errorHandler.info(res));\n }).catch(error => this.errorHandler.error(error));\n }\n }\n }\n }\n\n ngOnInit() {\n if (!this.projectId) {\n this.errorHandler.error('Project ID cannot be unset.');\n return;\n }\n if (!this.repoName) {\n this.errorHandler.error('Repo name cannot be unset.');\n return;\n }\n\n this.retrieve();\n\n this.stateCheckTimer = Observable.timer(STATE_CHECK_INTERVAL, STATE_CHECK_INTERVAL).subscribe(() => {\n if (this.scanningTagCount > 0) {\n this.updateScanningStates();\n }\n });\n }\n\n ngOnDestroy(): void {\n if (this.stateCheckTimer) "},"suffix":{"kind":"string","value":"\n }\n\n retrieve() {\n this.tags = [];\n this.loading = true;\n\n toPromise(this.tagService\n .getTags(this.repoName))\n .then(items => {\n this.tags = items;\n this.loading = false;\n if (this.tags && this.tags.length === 0) {\n this.refreshRepo.emit(true);\n }\n })\n .catch(error => {\n this.errorHandler.error(error);\n this.loading = false;\n });\n let hnd = setInterval(() => this.ref.markForCheck(), 100);\n setTimeout(() => clearInterval(hnd), 1000);\n }\n\n deleteTag(tag: Tag) {\n if (tag) {\n let titleKey: string, summaryKey: string, content: string, buttons: ConfirmationButtons;\n if (tag.signature) {\n titleKey = 'REPOSITORY.DELETION_TITLE_TAG_DENIED';\n summaryKey = 'REPOSITORY.DELETION_SUMMARY_TAG_DENIED';\n buttons = ConfirmationButtons.CLOSE;\n content = 'notary -s https://' + this.registryUrl + ':4443 -d ~/.docker/trust remove -p ' + this.registryUrl + '/' + this.repoName + ' ' + tag.name;\n } else {\n titleKey = 'REPOSITORY.DELETION_TITLE_TAG';\n summaryKey = 'REPOSITORY.DELETION_SUMMARY_TAG';\n buttons = ConfirmationButtons.DELETE_CANCEL;\n content = tag.name;\n }\n let message = new ConfirmationMessage(\n titleKey,\n summaryKey,\n content,\n tag,\n ConfirmationTargets.TAG,\n buttons);\n this.confirmationDialog.open(message);\n }\n }\n\n showDigestId(tag: Tag) {\n if (tag) {\n this.manifestInfoTitle = 'REPOSITORY.COPY_DIGEST_ID';\n this.digestId = tag.digest;\n this.showTagManifestOpened = true;\n this.copyFailed = false;\n }\n }\n \n onTagClick(tag: Tag): void {\n if (tag) {\n let evt: TagClickEvent = {\n project_id: this.projectId,\n repository_name: this.repoName,\n tag_name: tag.name\n };\n this.tagClickEvent.emit(evt);\n }\n }\n\n scanTag(tagId: string): void {\n //Double check\n if (this.tagsInScanning[tagId]) {\n return;\n }\n toPromise(this.scanningService.startVulnerabilityScanning(this.repoName, tagId))\n .then(() => {\n //Add to scanning map\n this.tagsInScanning[tagId] = tagId;\n //Counting\n this.scanningTagCount += 1;\n })\n .catch(error => this.errorHandler.error(error));\n }\n\n updateScanningStates(): void {\n toPromise(this.tagService\n .getTags(this.repoName))\n .then(items => {\n console.debug(\"updateScanningStates called!\");\n //Reset the scanning states\n this.tagsInScanning = {};\n this.scanningTagCount = 0;\n\n items.forEach(item => {\n if (item.scan_overview) {\n if (item.scan_overview.scan_status === VULNERABILITY_SCAN_STATUS.pending ||\n item.scan_overview.scan_status === VULNERABILITY_SCAN_STATUS.running) {\n this.tagsInScanning[item.name] = item.name;\n this.scanningTagCount += 1;\n }\n }\n });\n\n this.tags = items;\n })\n .catch(error => {\n this.errorHandler.error(error);\n });\n let hnd = setInterval(() => this.ref.markForCheck(), 100);\n setTimeout(() => clearInterval(hnd), 1000);\n }\n\n onSuccess($event: any): void {\n this.copyFailed = false;\n //Directly close dialog\n this.showTagManifestOpened = false;\n }\n\n onError($event: any): void {\n //Show error\n this.copyFailed = true;\n //Select all text\n if(this.textInput){\n this.textInput.nativeElement.select();\n }\n }\n}"},"middle":{"kind":"string","value":"{\n this.stateCheckTimer.unsubscribe();\n }"},"fim_type":{"kind":"string","value":"conditional_block"}}},{"rowIdx":236057,"cells":{"file_name":{"kind":"string","value":"__init__.py"},"prefix":{"kind":"string","value":"from sys import exit, version_info\nimport logging\n\nlogger = logging.getLogger(__name__)\n\ntry:\n from smbus import SMBus\nexcept ImportError:\n if version_info[0] < 3:\n "},"suffix":{"kind":"string","value":"\n elif version_info[0] == 3:\n logger.warning(\"Falling back to mock SMBus. This library requires python3-smbus. Install with: sudo apt-get install python3-smbus\")\n from picraftzero.thirdparty.mocks.raspiberrypi.rpidevmocks import Mock_smbusModule\n SMBus = Mock_smbusModule.SMBus\n\n\nfrom .pantilt import PanTilt, WS2812, PWM, RGB, GRB, RGBW, GRBW\n\n__version__ = '0.0.3'\n\npantilthat = PanTilt(i2c_bus=SMBus(1))\n\nbrightness = pantilthat.brightness\n\nidle_timeout = pantilthat.idle_timeout\n\nclear = pantilthat.clear\n\nlight_mode = pantilthat.light_mode\n\nlight_type = pantilthat.light_type\n\nservo_one = pantilthat.servo_one\n\nservo_pulse_max = pantilthat.servo_pulse_max\n\nservo_pulse_min = pantilthat.servo_pulse_min\n\nservo_two = pantilthat.servo_two\n\nservo_enable = pantilthat.servo_enable\n\nset_all = pantilthat.set_all\n\nset_pixel = pantilthat.set_pixel\n\nset_pixel_rgbw = pantilthat.set_pixel_rgbw\n\nshow = pantilthat.show\n\npan = pantilthat.servo_one\n\ntilt = pantilthat.servo_two\n"},"middle":{"kind":"string","value":"logger.warning(\"Falling back to mock SMBus. This library requires python-smbus. Install with: sudo apt-get install python-smbus\")"},"fim_type":{"kind":"string","value":"conditional_block"}}},{"rowIdx":236058,"cells":{"file_name":{"kind":"string","value":"__init__.py"},"prefix":{"kind":"string","value":"from sys import exit, version_info\nimport logging\n\nlogger = logging.getLogger(__name__)\n\ntry:\n from smbus import SMBus\nexcept ImportError:\n if version_info[0] < 3:\n logger.warning(\"Falling back to mock SMBus. This library requires python-smbus. Install with: sudo apt-get install python-smbus\")\n elif version_info[0] == 3:\n logger.warning(\"Falling back to mock SMBus. This library requires python3-smbus. Install with: sudo apt-get install python3-smbus\")\n from picraftzero.thirdparty.mocks.raspiberrypi.rpidevmocks import Mock_smbusModule\n SMBus = Mock_smbusModule.SMBus\n\n\nfrom .pantilt import PanTilt, WS2812, PWM, RGB, GRB, RGBW, GRBW\n\n__version__ = '0.0.3'\n\npantilthat = PanTilt(i2c_bus=SMBus(1))\n\nbrightness = pantilthat.brightness\n\nidle_timeout = pantilthat.idle_timeout\n\nclear = pantilthat.clear\n\nlight_mode = pantilthat.light_mode\n\nlight_type = pantilthat.light_type\n\nservo_one = pantilthat.servo_one\n\nservo_pulse_max = pantilthat.servo_pulse_max\n\nservo_pulse_min = pantilthat.servo_pulse_min\n\nservo_two = pantilthat.servo_two\n\nservo_enable = pantilthat.servo_enable\n\nset_all = pantilthat.set_all\n\nset_pixel = pantilthat.set_pixel"},"suffix":{"kind":"string","value":"pan = pantilthat.servo_one\n\ntilt = pantilthat.servo_two"},"middle":{"kind":"string","value":"\nset_pixel_rgbw = pantilthat.set_pixel_rgbw\n\nshow = pantilthat.show\n"},"fim_type":{"kind":"string","value":"random_line_split"}}},{"rowIdx":236059,"cells":{"file_name":{"kind":"string","value":"card-harness.e2e.spec.ts"},"prefix":{"kind":"string","value":"import {HarnessLoader} from '@angular/cdk/testing';\nimport {ProtractorHarnessEnvironment} from '@angular/cdk/testing/protractor';\nimport {MatCardHarness} from '@angular/material-experimental/mdc-card/testing/card-harness';\nimport {browser} from 'protractor';\n\ndescribe('card harness', () => {\n let loader: HarnessLoader;\n\n beforeEach(async () => await browser.get('/mdc-card'));\n\n beforeEach(() => {\n loader = ProtractorHarnessEnvironment.loader();\n });\n\n it('should get card text', async () => {\n const card = await loader.getHarness(MatCardHarness);"},"suffix":{"kind":"string","value":" ' Japan. A small, agile dog that copes very well with mountainous terrain, the Shiba Inu' +\n ' was originally bred for hunting.',\n 'LIKE',\n 'SHARE'\n ].join('\\n'));\n });\n\n it('should get title text', async () => {\n const card = await loader.getHarness(MatCardHarness);\n expect(await card.getTitleText()).toBe('Shiba Inu');\n });\n\n it('should get subtitle text', async () => {\n const card = await loader.getHarness(MatCardHarness);\n expect(await card.getSubtitleText()).toBe('Dog Breed');\n });\n});"},"middle":{"kind":"string","value":" expect(await card.getText()).toBe([\n 'Shiba Inu',\n 'Dog Breed',\n 'The Shiba Inu is the smallest of the six original and distinct spitz breeds of dog from' +"},"fim_type":{"kind":"string","value":"random_line_split"}}},{"rowIdx":236060,"cells":{"file_name":{"kind":"string","value":"hint.rs"},"prefix":{"kind":"string","value":"use std::slice;\nuse std::sync::Arc;\n\nuse super::*;\n\n#[derive(Debug)]\n#[allow(dead_code)]\npub enum StateOperation {\n Remove = 0, // _NET_WM_STATE_REMOVE\n Add = 1, // _NET_WM_STATE_ADD\n Toggle = 2, // _NET_WM_STATE_TOGGLE\n}\n\nimpl From for StateOperation {\n fn from(op: bool) -> Self {\n if op {\n StateOperation::Add\n } else {\n StateOperation::Remove\n }\n }\n}\n\n/// X window type. Maps directly to\n/// [`_NET_WM_WINDOW_TYPE`](https://specifications.freedesktop.org/wm-spec/wm-spec-1.5.html).\n#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]\n#[cfg_attr(feature = \"serde\", derive(Serialize, Deserialize))]\npub enum WindowType {\n /// A desktop feature. This can include a single window containing desktop icons with the same dimensions as the\n /// screen, allowing the desktop environment to have full control of the desktop, without the need for proxying\n /// root window clicks.\n Desktop,\n /// A dock or panel feature. Typically a Window Manager would keep such windows on top of all other windows.\n Dock,\n /// Toolbar windows. \"Torn off\" from the main application.\n Toolbar,\n /// Pinnable menu windows. \"Torn off\" from the main application.\n Menu,\n /// A small persistent utility window, such as a palette or toolbox.\n Utility,\n /// The window is a splash screen displayed as an application is starting up.\n Splash,\n /// This is a dialog window.\n Dialog,\n /// A dropdown menu that usually appears when the user clicks on an item in a menu bar.\n /// This property is typically used on override-redirect windows.\n DropdownMenu,\n /// A popup menu that usually appears when the user right clicks on an object.\n /// This property is typically used on override-redirect windows.\n PopupMenu,\n /// A tooltip window. Usually used to show additional information when hovering over an object with the cursor.\n /// This property is typically used on override-redirect windows.\n Tooltip,\n /// The window is a notification.\n /// This property is typically used on override-redirect windows.\n Notification,\n /// This should be used on the windows that are popped up by combo boxes.\n /// This property is typically used on override-redirect windows.\n Combo,\n /// This indicates the the window is being dragged.\n /// This property is typically used on override-redirect windows.\n Dnd,\n /// This is a normal, top-level window.\n Normal,\n}\n\nimpl Default for WindowType {\n fn default() -> Self {\n WindowType::Normal\n }\n}\n\nimpl WindowType {\n pub(crate) fn as_atom(&self, xconn: &Arc) -> ffi::Atom {\n use self::WindowType::*;\n let atom_name: &[u8] = match *self {\n Desktop => b\"_NET_WM_WINDOW_TYPE_DESKTOP\\0\",\n Dock => b\"_NET_WM_WINDOW_TYPE_DOCK\\0\",\n Toolbar => b\"_NET_WM_WINDOW_TYPE_TOOLBAR\\0\",\n Menu => b\"_NET_WM_WINDOW_TYPE_MENU\\0\",\n Utility => b\"_NET_WM_WINDOW_TYPE_UTILITY\\0\",\n Splash => b\"_NET_WM_WINDOW_TYPE_SPLASH\\0\",\n Dialog => b\"_NET_WM_WINDOW_TYPE_DIALOG\\0\",\n DropdownMenu => b\"_NET_WM_WINDOW_TYPE_DROPDOWN_MENU\\0\",\n PopupMenu => b\"_NET_WM_WINDOW_TYPE_POPUP_MENU\\0\",\n Tooltip => b\"_NET_WM_WINDOW_TYPE_TOOLTIP\\0\",\n Notification => b\"_NET_WM_WINDOW_TYPE_NOTIFICATION\\0\",\n Combo => b\"_NET_WM_WINDOW_TYPE_COMBO\\0\",\n Dnd => b\"_NET_WM_WINDOW_TYPE_DND\\0\",\n Normal => b\"_NET_WM_WINDOW_TYPE_NORMAL\\0\",\n };\n unsafe { xconn.get_atom_unchecked(atom_name) }\n }\n}\n\npub struct MotifHints {\n hints: MwmHints,\n}\n\n#[repr(C)]\nstruct MwmHints {\n flags: c_ulong,\n functions: c_ulong,\n decorations: c_ulong,\n input_mode: c_long,\n status: c_ulong,\n}\n\n#[allow(dead_code)]\nmod mwm {\n use libc::c_ulong;\n\n // Motif WM hints are obsolete, but still widely supported.\n // https://stackoverflow.com/a/1909708\n pub const MWM_HINTS_FUNCTIONS: c_ulong = 1 << 0;\n pub const MWM_HINTS_DECORATIONS: c_ulong = 1 << 1;\n\n pub const MWM_FUNC_ALL: c_ulong = 1 << 0;\n pub const MWM_FUNC_RESIZE: c_ulong = 1 << 1;\n pub const MWM_FUNC_MOVE: c_ulong = 1 << 2;\n pub const MWM_FUNC_MINIMIZE: c_ulong = 1 << 3;\n pub const MWM_FUNC_MAXIMIZE: c_ulong = 1 << 4;\n pub const MWM_FUNC_CLOSE: c_ulong = 1 << 5;\n}\n\nimpl MotifHints {\n pub fn new() -> MotifHints {\n MotifHints {\n hints: MwmHints {\n flags: 0,\n functions: 0,\n decorations: 0,\n input_mode: 0,\n status: 0,\n },\n }\n }\n\n pub fn set_decorations(&mut self, decorations: bool) {\n self.hints.flags |= mwm::MWM_HINTS_DECORATIONS;\n self.hints.decorations = decorations as c_ulong;\n }\n\n pub fn set_maximizable(&mut self, maximizable: bool) {\n if maximizable {\n self.add_func(mwm::MWM_FUNC_MAXIMIZE);\n } else {\n self.remove_func(mwm::MWM_FUNC_MAXIMIZE);\n }\n }\n\n fn add_func(&mut self, func: c_ulong) {\n if self.hints.flags & mwm::MWM_HINTS_FUNCTIONS != 0 {\n if self.hints.functions & mwm::MWM_FUNC_ALL != 0 {\n self.hints.functions &= !func;\n } else {\n self.hints.functions |= func;\n }\n }\n }\n\n fn remove_func(&mut self, func: c_ulong) {\n if self.hints.flags & mwm::MWM_HINTS_FUNCTIONS == 0 {\n self.hints.flags |= mwm::MWM_HINTS_FUNCTIONS;\n self.hints.functions = mwm::MWM_FUNC_ALL;\n }\n\n if self.hints.functions & mwm::MWM_FUNC_ALL != 0 {\n self.hints.functions |= func;\n } else {\n self.hints.functions &= !func;\n }\n }\n}\n\nimpl MwmHints {\n fn as_slice(&self) -> &[c_ulong] {\n unsafe { slice::from_raw_parts(self as *const _ as *const c_ulong, 5) }\n }\n}\n\npub struct NormalHints<'a> {\n size_hints: XSmartPointer<'a, ffi::XSizeHints>,\n}\n\nimpl<'a> NormalHints<'a> {\n pub fn new(xconn: &'a XConnection) -> Self {\n NormalHints {\n size_hints: xconn.alloc_size_hints(),\n }\n }\n\n pub fn get_position(&self) -> Option<(i32, i32)> {\n if has_flag(self.size_hints.flags, ffi::PPosition) {\n Some((self.size_hints.x as i32, self.size_hints.y as i32))\n } else {\n None\n }\n }\n\n pub fn set_position(&mut self, position: Option<(i32, i32)>) {\n if let Some((x, y)) = position {\n self.size_hints.flags |= ffi::PPosition;\n self.size_hints.x = x as c_int;\n self.size_hints.y = y as c_int;\n } else {\n self.size_hints.flags &= !ffi::PPosition;\n }\n }\n\n // WARNING: This hint is obsolete\n pub fn set_size(&mut self, size: Option<(u32, u32)>) {\n if let Some((width, height)) = size {\n self.size_hints.flags |= ffi::PSize;\n self.size_hints.width = width as c_int;\n self.size_hints.height = height as c_int;\n } else {\n self.size_hints.flags &= !ffi::PSize;\n }\n }\n\n pub fn set_max_size(&mut self, max_size: Option<(u32, u32)>) {\n if let Some((max_width, max_height)) = max_size {\n self.size_hints.flags |= ffi::PMaxSize;\n self.size_hints.max_width = max_width as c_int;\n self.size_hints.max_height = max_height as c_int;\n } else {\n self.size_hints.flags &= !ffi::PMaxSize;\n }\n }\n\n pub fn set_min_size(&mut self, min_size: Option<(u32, u32)>) {\n if let Some((min_width, min_height)) = min_size {\n self.size_hints.flags |= ffi::PMinSize;\n self.size_hints.min_width = min_width as c_int;\n self.size_hints.min_height = min_height as c_int;\n } else {\n self.size_hints.flags &= !ffi::PMinSize;\n }\n }\n\n pub fn set_resize_increments(&mut self, resize_increments: Option<(u32, u32)>) {\n if let Some((width_inc, height_inc)) = resize_increments {\n self.size_hints.flags |= ffi::PResizeInc;\n self.size_hints.width_inc = width_inc as c_int;\n self.size_hints.height_inc = height_inc as c_int;\n } else {\n self.size_hints.flags &= !ffi::PResizeInc;\n }\n }\n\n pub fn set_base_size(&mut self, base_size: Option<(u32, u32)>) {\n if let Some((base_width, base_height)) = base_size {\n self.size_hints.flags |= ffi::PBaseSize;\n self.size_hints.base_width = base_width as c_int;\n self.size_hints.base_height = base_height as c_int;\n } else {\n self.size_hints.flags &= !ffi::PBaseSize;\n }\n }\n}\n\nimpl XConnection {\n pub fn get_wm_hints(\n &self,\n window: ffi::Window,\n ) -> Result, XError> "},"suffix":{"kind":"string","value":"\n\n pub fn set_wm_hints(\n &self,\n window: ffi::Window,\n wm_hints: XSmartPointer<'_, ffi::XWMHints>,\n ) -> Flusher<'_> {\n unsafe {\n (self.xlib.XSetWMHints)(self.display, window, wm_hints.ptr);\n }\n Flusher::new(self)\n }\n\n pub fn get_normal_hints(&self, window: ffi::Window) -> Result, XError> {\n let size_hints = self.alloc_size_hints();\n let mut supplied_by_user = MaybeUninit::uninit();\n unsafe {\n (self.xlib.XGetWMNormalHints)(\n self.display,\n window,\n size_hints.ptr,\n supplied_by_user.as_mut_ptr(),\n );\n }\n self.check_errors().map(|_| NormalHints { size_hints })\n }\n\n pub fn set_normal_hints(\n &self,\n window: ffi::Window,\n normal_hints: NormalHints<'_>,\n ) -> Flusher<'_> {\n unsafe {\n (self.xlib.XSetWMNormalHints)(self.display, window, normal_hints.size_hints.ptr);\n }\n Flusher::new(self)\n }\n\n pub fn get_motif_hints(&self, window: ffi::Window) -> MotifHints {\n let motif_hints = unsafe { self.get_atom_unchecked(b\"_MOTIF_WM_HINTS\\0\") };\n\n let mut hints = MotifHints::new();\n\n if let Ok(props) = self.get_property::(window, motif_hints, motif_hints) {\n hints.hints.flags = props.get(0).cloned().unwrap_or(0);\n hints.hints.functions = props.get(1).cloned().unwrap_or(0);\n hints.hints.decorations = props.get(2).cloned().unwrap_or(0);\n hints.hints.input_mode = props.get(3).cloned().unwrap_or(0) as c_long;\n hints.hints.status = props.get(4).cloned().unwrap_or(0);\n }\n\n hints\n }\n\n pub fn set_motif_hints(&self, window: ffi::Window, hints: &MotifHints) -> Flusher<'_> {\n let motif_hints = unsafe { self.get_atom_unchecked(b\"_MOTIF_WM_HINTS\\0\") };\n\n self.change_property(\n window,\n motif_hints,\n motif_hints,\n PropMode::Replace,\n hints.hints.as_slice(),\n )\n }\n}\n"},"middle":{"kind":"string","value":"{\n let wm_hints = unsafe { (self.xlib.XGetWMHints)(self.display, window) };\n self.check_errors()?;\n let wm_hints = if wm_hints.is_null() {\n self.alloc_wm_hints()\n } else {\n XSmartPointer::new(self, wm_hints).unwrap()\n };\n Ok(wm_hints)\n }"},"fim_type":{"kind":"string","value":"identifier_body"}}},{"rowIdx":236061,"cells":{"file_name":{"kind":"string","value":"hint.rs"},"prefix":{"kind":"string","value":"use std::slice;\nuse std::sync::Arc;\n\nuse super::*;\n\n#[derive(Debug)]\n#[allow(dead_code)]\npub enum StateOperation {\n Remove = 0, // _NET_WM_STATE_REMOVE\n Add = 1, // _NET_WM_STATE_ADD\n Toggle = 2, // _NET_WM_STATE_TOGGLE\n}\n\nimpl From for StateOperation {\n fn from(op: bool) -> Self {\n if op {\n StateOperation::Add\n } else {\n StateOperation::Remove\n }\n }\n}\n\n/// X window type. Maps directly to\n/// [`_NET_WM_WINDOW_TYPE`](https://specifications.freedesktop.org/wm-spec/wm-spec-1.5.html).\n#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]\n#[cfg_attr(feature = \"serde\", derive(Serialize, Deserialize))]\npub enum WindowType {\n /// A desktop feature. This can include a single window containing desktop icons with the same dimensions as the\n /// screen, allowing the desktop environment to have full control of the desktop, without the need for proxying\n /// root window clicks.\n Desktop,\n /// A dock or panel feature. Typically a Window Manager would keep such windows on top of all other windows.\n Dock,\n /// Toolbar windows. \"Torn off\" from the main application.\n Toolbar,\n /// Pinnable menu windows. \"Torn off\" from the main application.\n Menu,\n /// A small persistent utility window, such as a palette or toolbox.\n Utility,\n /// The window is a splash screen displayed as an application is starting up.\n Splash,\n /// This is a dialog window.\n Dialog,\n /// A dropdown menu that usually appears when the user clicks on an item in a menu bar.\n /// This property is typically used on override-redirect windows.\n DropdownMenu,\n /// A popup menu that usually appears when the user right clicks on an object.\n /// This property is typically used on override-redirect windows.\n PopupMenu,\n /// A tooltip window. Usually used to show additional information when hovering over an object with the cursor.\n /// This property is typically used on override-redirect windows.\n Tooltip,\n /// The window is a notification.\n /// This property is typically used on override-redirect windows.\n Notification,\n /// This should be used on the windows that are popped up by combo boxes.\n /// This property is typically used on override-redirect windows.\n Combo,\n /// This indicates the the window is being dragged.\n /// This property is typically used on override-redirect windows.\n Dnd,\n /// This is a normal, top-level window.\n Normal,\n}\n\nimpl Default for WindowType {\n fn default() -> Self {\n WindowType::Normal\n }\n}\n\nimpl WindowType {\n pub(crate) fn as_atom(&self, xconn: &Arc) -> ffi::Atom {\n use self::WindowType::*;\n let atom_name: &[u8] = match *self {\n Desktop => b\"_NET_WM_WINDOW_TYPE_DESKTOP\\0\",\n Dock => b\"_NET_WM_WINDOW_TYPE_DOCK\\0\",\n Toolbar => b\"_NET_WM_WINDOW_TYPE_TOOLBAR\\0\",\n Menu => b\"_NET_WM_WINDOW_TYPE_MENU\\0\",\n Utility => b\"_NET_WM_WINDOW_TYPE_UTILITY\\0\",\n Splash => b\"_NET_WM_WINDOW_TYPE_SPLASH\\0\",\n Dialog => b\"_NET_WM_WINDOW_TYPE_DIALOG\\0\",\n DropdownMenu => b\"_NET_WM_WINDOW_TYPE_DROPDOWN_MENU\\0\",\n PopupMenu => b\"_NET_WM_WINDOW_TYPE_POPUP_MENU\\0\",\n Tooltip => b\"_NET_WM_WINDOW_TYPE_TOOLTIP\\0\",\n Notification => b\"_NET_WM_WINDOW_TYPE_NOTIFICATION\\0\",\n Combo => b\"_NET_WM_WINDOW_TYPE_COMBO\\0\","},"suffix":{"kind":"string","value":" };\n unsafe { xconn.get_atom_unchecked(atom_name) }\n }\n}\n\npub struct MotifHints {\n hints: MwmHints,\n}\n\n#[repr(C)]\nstruct MwmHints {\n flags: c_ulong,\n functions: c_ulong,\n decorations: c_ulong,\n input_mode: c_long,\n status: c_ulong,\n}\n\n#[allow(dead_code)]\nmod mwm {\n use libc::c_ulong;\n\n // Motif WM hints are obsolete, but still widely supported.\n // https://stackoverflow.com/a/1909708\n pub const MWM_HINTS_FUNCTIONS: c_ulong = 1 << 0;\n pub const MWM_HINTS_DECORATIONS: c_ulong = 1 << 1;\n\n pub const MWM_FUNC_ALL: c_ulong = 1 << 0;\n pub const MWM_FUNC_RESIZE: c_ulong = 1 << 1;\n pub const MWM_FUNC_MOVE: c_ulong = 1 << 2;\n pub const MWM_FUNC_MINIMIZE: c_ulong = 1 << 3;\n pub const MWM_FUNC_MAXIMIZE: c_ulong = 1 << 4;\n pub const MWM_FUNC_CLOSE: c_ulong = 1 << 5;\n}\n\nimpl MotifHints {\n pub fn new() -> MotifHints {\n MotifHints {\n hints: MwmHints {\n flags: 0,\n functions: 0,\n decorations: 0,\n input_mode: 0,\n status: 0,\n },\n }\n }\n\n pub fn set_decorations(&mut self, decorations: bool) {\n self.hints.flags |= mwm::MWM_HINTS_DECORATIONS;\n self.hints.decorations = decorations as c_ulong;\n }\n\n pub fn set_maximizable(&mut self, maximizable: bool) {\n if maximizable {\n self.add_func(mwm::MWM_FUNC_MAXIMIZE);\n } else {\n self.remove_func(mwm::MWM_FUNC_MAXIMIZE);\n }\n }\n\n fn add_func(&mut self, func: c_ulong) {\n if self.hints.flags & mwm::MWM_HINTS_FUNCTIONS != 0 {\n if self.hints.functions & mwm::MWM_FUNC_ALL != 0 {\n self.hints.functions &= !func;\n } else {\n self.hints.functions |= func;\n }\n }\n }\n\n fn remove_func(&mut self, func: c_ulong) {\n if self.hints.flags & mwm::MWM_HINTS_FUNCTIONS == 0 {\n self.hints.flags |= mwm::MWM_HINTS_FUNCTIONS;\n self.hints.functions = mwm::MWM_FUNC_ALL;\n }\n\n if self.hints.functions & mwm::MWM_FUNC_ALL != 0 {\n self.hints.functions |= func;\n } else {\n self.hints.functions &= !func;\n }\n }\n}\n\nimpl MwmHints {\n fn as_slice(&self) -> &[c_ulong] {\n unsafe { slice::from_raw_parts(self as *const _ as *const c_ulong, 5) }\n }\n}\n\npub struct NormalHints<'a> {\n size_hints: XSmartPointer<'a, ffi::XSizeHints>,\n}\n\nimpl<'a> NormalHints<'a> {\n pub fn new(xconn: &'a XConnection) -> Self {\n NormalHints {\n size_hints: xconn.alloc_size_hints(),\n }\n }\n\n pub fn get_position(&self) -> Option<(i32, i32)> {\n if has_flag(self.size_hints.flags, ffi::PPosition) {\n Some((self.size_hints.x as i32, self.size_hints.y as i32))\n } else {\n None\n }\n }\n\n pub fn set_position(&mut self, position: Option<(i32, i32)>) {\n if let Some((x, y)) = position {\n self.size_hints.flags |= ffi::PPosition;\n self.size_hints.x = x as c_int;\n self.size_hints.y = y as c_int;\n } else {\n self.size_hints.flags &= !ffi::PPosition;\n }\n }\n\n // WARNING: This hint is obsolete\n pub fn set_size(&mut self, size: Option<(u32, u32)>) {\n if let Some((width, height)) = size {\n self.size_hints.flags |= ffi::PSize;\n self.size_hints.width = width as c_int;\n self.size_hints.height = height as c_int;\n } else {\n self.size_hints.flags &= !ffi::PSize;\n }\n }\n\n pub fn set_max_size(&mut self, max_size: Option<(u32, u32)>) {\n if let Some((max_width, max_height)) = max_size {\n self.size_hints.flags |= ffi::PMaxSize;\n self.size_hints.max_width = max_width as c_int;\n self.size_hints.max_height = max_height as c_int;\n } else {\n self.size_hints.flags &= !ffi::PMaxSize;\n }\n }\n\n pub fn set_min_size(&mut self, min_size: Option<(u32, u32)>) {\n if let Some((min_width, min_height)) = min_size {\n self.size_hints.flags |= ffi::PMinSize;\n self.size_hints.min_width = min_width as c_int;\n self.size_hints.min_height = min_height as c_int;\n } else {\n self.size_hints.flags &= !ffi::PMinSize;\n }\n }\n\n pub fn set_resize_increments(&mut self, resize_increments: Option<(u32, u32)>) {\n if let Some((width_inc, height_inc)) = resize_increments {\n self.size_hints.flags |= ffi::PResizeInc;\n self.size_hints.width_inc = width_inc as c_int;\n self.size_hints.height_inc = height_inc as c_int;\n } else {\n self.size_hints.flags &= !ffi::PResizeInc;\n }\n }\n\n pub fn set_base_size(&mut self, base_size: Option<(u32, u32)>) {\n if let Some((base_width, base_height)) = base_size {\n self.size_hints.flags |= ffi::PBaseSize;\n self.size_hints.base_width = base_width as c_int;\n self.size_hints.base_height = base_height as c_int;\n } else {\n self.size_hints.flags &= !ffi::PBaseSize;\n }\n }\n}\n\nimpl XConnection {\n pub fn get_wm_hints(\n &self,\n window: ffi::Window,\n ) -> Result, XError> {\n let wm_hints = unsafe { (self.xlib.XGetWMHints)(self.display, window) };\n self.check_errors()?;\n let wm_hints = if wm_hints.is_null() {\n self.alloc_wm_hints()\n } else {\n XSmartPointer::new(self, wm_hints).unwrap()\n };\n Ok(wm_hints)\n }\n\n pub fn set_wm_hints(\n &self,\n window: ffi::Window,\n wm_hints: XSmartPointer<'_, ffi::XWMHints>,\n ) -> Flusher<'_> {\n unsafe {\n (self.xlib.XSetWMHints)(self.display, window, wm_hints.ptr);\n }\n Flusher::new(self)\n }\n\n pub fn get_normal_hints(&self, window: ffi::Window) -> Result, XError> {\n let size_hints = self.alloc_size_hints();\n let mut supplied_by_user = MaybeUninit::uninit();\n unsafe {\n (self.xlib.XGetWMNormalHints)(\n self.display,\n window,\n size_hints.ptr,\n supplied_by_user.as_mut_ptr(),\n );\n }\n self.check_errors().map(|_| NormalHints { size_hints })\n }\n\n pub fn set_normal_hints(\n &self,\n window: ffi::Window,\n normal_hints: NormalHints<'_>,\n ) -> Flusher<'_> {\n unsafe {\n (self.xlib.XSetWMNormalHints)(self.display, window, normal_hints.size_hints.ptr);\n }\n Flusher::new(self)\n }\n\n pub fn get_motif_hints(&self, window: ffi::Window) -> MotifHints {\n let motif_hints = unsafe { self.get_atom_unchecked(b\"_MOTIF_WM_HINTS\\0\") };\n\n let mut hints = MotifHints::new();\n\n if let Ok(props) = self.get_property::(window, motif_hints, motif_hints) {\n hints.hints.flags = props.get(0).cloned().unwrap_or(0);\n hints.hints.functions = props.get(1).cloned().unwrap_or(0);\n hints.hints.decorations = props.get(2).cloned().unwrap_or(0);\n hints.hints.input_mode = props.get(3).cloned().unwrap_or(0) as c_long;\n hints.hints.status = props.get(4).cloned().unwrap_or(0);\n }\n\n hints\n }\n\n pub fn set_motif_hints(&self, window: ffi::Window, hints: &MotifHints) -> Flusher<'_> {\n let motif_hints = unsafe { self.get_atom_unchecked(b\"_MOTIF_WM_HINTS\\0\") };\n\n self.change_property(\n window,\n motif_hints,\n motif_hints,\n PropMode::Replace,\n hints.hints.as_slice(),\n )\n }\n}"},"middle":{"kind":"string","value":" Dnd => b\"_NET_WM_WINDOW_TYPE_DND\\0\",\n Normal => b\"_NET_WM_WINDOW_TYPE_NORMAL\\0\","},"fim_type":{"kind":"string","value":"random_line_split"}}},{"rowIdx":236062,"cells":{"file_name":{"kind":"string","value":"hint.rs"},"prefix":{"kind":"string","value":"use std::slice;\nuse std::sync::Arc;\n\nuse super::*;\n\n#[derive(Debug)]\n#[allow(dead_code)]\npub enum StateOperation {\n Remove = 0, // _NET_WM_STATE_REMOVE\n Add = 1, // _NET_WM_STATE_ADD\n Toggle = 2, // _NET_WM_STATE_TOGGLE\n}\n\nimpl From for StateOperation {\n fn from(op: bool) -> Self {\n if op {\n StateOperation::Add\n } else {\n StateOperation::Remove\n }\n }\n}\n\n/// X window type. Maps directly to\n/// [`_NET_WM_WINDOW_TYPE`](https://specifications.freedesktop.org/wm-spec/wm-spec-1.5.html).\n#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]\n#[cfg_attr(feature = \"serde\", derive(Serialize, Deserialize))]\npub enum WindowType {\n /// A desktop feature. This can include a single window containing desktop icons with the same dimensions as the\n /// screen, allowing the desktop environment to have full control of the desktop, without the need for proxying\n /// root window clicks.\n Desktop,\n /// A dock or panel feature. Typically a Window Manager would keep such windows on top of all other windows.\n Dock,\n /// Toolbar windows. \"Torn off\" from the main application.\n Toolbar,\n /// Pinnable menu windows. \"Torn off\" from the main application.\n Menu,\n /// A small persistent utility window, such as a palette or toolbox.\n Utility,\n /// The window is a splash screen displayed as an application is starting up.\n Splash,\n /// This is a dialog window.\n Dialog,\n /// A dropdown menu that usually appears when the user clicks on an item in a menu bar.\n /// This property is typically used on override-redirect windows.\n DropdownMenu,\n /// A popup menu that usually appears when the user right clicks on an object.\n /// This property is typically used on override-redirect windows.\n PopupMenu,\n /// A tooltip window. Usually used to show additional information when hovering over an object with the cursor.\n /// This property is typically used on override-redirect windows.\n Tooltip,\n /// The window is a notification.\n /// This property is typically used on override-redirect windows.\n Notification,\n /// This should be used on the windows that are popped up by combo boxes.\n /// This property is typically used on override-redirect windows.\n Combo,\n /// This indicates the the window is being dragged.\n /// This property is typically used on override-redirect windows.\n Dnd,\n /// This is a normal, top-level window.\n Normal,\n}\n\nimpl Default for WindowType {\n fn default() -> Self {\n WindowType::Normal\n }\n}\n\nimpl WindowType {\n pub(crate) fn as_atom(&self, xconn: &Arc) -> ffi::Atom {\n use self::WindowType::*;\n let atom_name: &[u8] = match *self {\n Desktop => b\"_NET_WM_WINDOW_TYPE_DESKTOP\\0\",\n Dock => b\"_NET_WM_WINDOW_TYPE_DOCK\\0\",\n Toolbar => b\"_NET_WM_WINDOW_TYPE_TOOLBAR\\0\",\n Menu => b\"_NET_WM_WINDOW_TYPE_MENU\\0\",\n Utility => b\"_NET_WM_WINDOW_TYPE_UTILITY\\0\",\n Splash => b\"_NET_WM_WINDOW_TYPE_SPLASH\\0\",\n Dialog => b\"_NET_WM_WINDOW_TYPE_DIALOG\\0\",\n DropdownMenu => b\"_NET_WM_WINDOW_TYPE_DROPDOWN_MENU\\0\",\n PopupMenu => b\"_NET_WM_WINDOW_TYPE_POPUP_MENU\\0\",\n Tooltip => b\"_NET_WM_WINDOW_TYPE_TOOLTIP\\0\",\n Notification => b\"_NET_WM_WINDOW_TYPE_NOTIFICATION\\0\",\n Combo => b\"_NET_WM_WINDOW_TYPE_COMBO\\0\",\n Dnd => b\"_NET_WM_WINDOW_TYPE_DND\\0\",\n Normal => b\"_NET_WM_WINDOW_TYPE_NORMAL\\0\",\n };\n unsafe { xconn.get_atom_unchecked(atom_name) }\n }\n}\n\npub struct MotifHints {\n hints: MwmHints,\n}\n\n#[repr(C)]\nstruct MwmHints {\n flags: c_ulong,\n functions: c_ulong,\n decorations: c_ulong,\n input_mode: c_long,\n status: c_ulong,\n}\n\n#[allow(dead_code)]\nmod mwm {\n use libc::c_ulong;\n\n // Motif WM hints are obsolete, but still widely supported.\n // https://stackoverflow.com/a/1909708\n pub const MWM_HINTS_FUNCTIONS: c_ulong = 1 << 0;\n pub const MWM_HINTS_DECORATIONS: c_ulong = 1 << 1;\n\n pub const MWM_FUNC_ALL: c_ulong = 1 << 0;\n pub const MWM_FUNC_RESIZE: c_ulong = 1 << 1;\n pub const MWM_FUNC_MOVE: c_ulong = 1 << 2;\n pub const MWM_FUNC_MINIMIZE: c_ulong = 1 << 3;\n pub const MWM_FUNC_MAXIMIZE: c_ulong = 1 << 4;\n pub const MWM_FUNC_CLOSE: c_ulong = 1 << 5;\n}\n\nimpl MotifHints {\n pub fn new() -> MotifHints {\n MotifHints {\n hints: MwmHints {\n flags: 0,\n functions: 0,\n decorations: 0,\n input_mode: 0,\n status: 0,\n },\n }\n }\n\n pub fn set_decorations(&mut self, decorations: bool) {\n self.hints.flags |= mwm::MWM_HINTS_DECORATIONS;\n self.hints.decorations = decorations as c_ulong;\n }\n\n pub fn set_maximizable(&mut self, maximizable: bool) {\n if maximizable {\n self.add_func(mwm::MWM_FUNC_MAXIMIZE);\n } else {\n self.remove_func(mwm::MWM_FUNC_MAXIMIZE);\n }\n }\n\n fn add_func(&mut self, func: c_ulong) {\n if self.hints.flags & mwm::MWM_HINTS_FUNCTIONS != 0 {\n if self.hints.functions & mwm::MWM_FUNC_ALL != 0 {\n self.hints.functions &= !func;\n } else {\n self.hints.functions |= func;\n }\n }\n }\n\n fn remove_func(&mut self, func: c_ulong) {\n if self.hints.flags & mwm::MWM_HINTS_FUNCTIONS == 0 {\n self.hints.flags |= mwm::MWM_HINTS_FUNCTIONS;\n self.hints.functions = mwm::MWM_FUNC_ALL;\n }\n\n if self.hints.functions & mwm::MWM_FUNC_ALL != 0 {\n self.hints.functions |= func;\n } else {\n self.hints.functions &= !func;\n }\n }\n}\n\nimpl MwmHints {\n fn as_slice(&self) -> &[c_ulong] {\n unsafe { slice::from_raw_parts(self as *const _ as *const c_ulong, 5) }\n }\n}\n\npub struct NormalHints<'a> {\n size_hints: XSmartPointer<'a, ffi::XSizeHints>,\n}\n\nimpl<'a> NormalHints<'a> {\n pub fn new(xconn: &'a XConnection) -> Self {\n NormalHints {\n size_hints: xconn.alloc_size_hints(),\n }\n }\n\n pub fn get_position(&self) -> Option<(i32, i32)> {\n if has_flag(self.size_hints.flags, ffi::PPosition) {\n Some((self.size_hints.x as i32, self.size_hints.y as i32))\n } else {\n None\n }\n }\n\n pub fn set_position(&mut self, position: Option<(i32, i32)>) {\n if let Some((x, y)) = position {\n self.size_hints.flags |= ffi::PPosition;\n self.size_hints.x = x as c_int;\n self.size_hints.y = y as c_int;\n } else {\n self.size_hints.flags &= !ffi::PPosition;\n }\n }\n\n // WARNING: This hint is obsolete\n pub fn set_size(&mut self, size: Option<(u32, u32)>) {\n if let Some((width, height)) = size {\n self.size_hints.flags |= ffi::PSize;\n self.size_hints.width = width as c_int;\n self.size_hints.height = height as c_int;\n } else {\n self.size_hints.flags &= !ffi::PSize;\n }\n }\n\n pub fn set_max_size(&mut self, max_size: Option<(u32, u32)>) {\n if let Some((max_width, max_height)) = max_size {\n self.size_hints.flags |= ffi::PMaxSize;\n self.size_hints.max_width = max_width as c_int;\n self.size_hints.max_height = max_height as c_int;\n } else {\n self.size_hints.flags &= !ffi::PMaxSize;\n }\n }\n\n pub fn set_min_size(&mut self, min_size: Option<(u32, u32)>) {\n if let Some((min_width, min_height)) = min_size {\n self.size_hints.flags |= ffi::PMinSize;\n self.size_hints.min_width = min_width as c_int;\n self.size_hints.min_height = min_height as c_int;\n } else {\n self.size_hints.flags &= !ffi::PMinSize;\n }\n }\n\n pub fn set_resize_increments(&mut self, resize_increments: Option<(u32, u32)>) {\n if let Some((width_inc, height_inc)) = resize_increments {\n self.size_hints.flags |= ffi::PResizeInc;\n self.size_hints.width_inc = width_inc as c_int;\n self.size_hints.height_inc = height_inc as c_int;\n } else {\n self.size_hints.flags &= !ffi::PResizeInc;\n }\n }\n\n pub fn set_base_size(&mut self, base_size: Option<(u32, u32)>) {\n if let Some((base_width, base_height)) = base_size "},"suffix":{"kind":"string","value":" else {\n self.size_hints.flags &= !ffi::PBaseSize;\n }\n }\n}\n\nimpl XConnection {\n pub fn get_wm_hints(\n &self,\n window: ffi::Window,\n ) -> Result, XError> {\n let wm_hints = unsafe { (self.xlib.XGetWMHints)(self.display, window) };\n self.check_errors()?;\n let wm_hints = if wm_hints.is_null() {\n self.alloc_wm_hints()\n } else {\n XSmartPointer::new(self, wm_hints).unwrap()\n };\n Ok(wm_hints)\n }\n\n pub fn set_wm_hints(\n &self,\n window: ffi::Window,\n wm_hints: XSmartPointer<'_, ffi::XWMHints>,\n ) -> Flusher<'_> {\n unsafe {\n (self.xlib.XSetWMHints)(self.display, window, wm_hints.ptr);\n }\n Flusher::new(self)\n }\n\n pub fn get_normal_hints(&self, window: ffi::Window) -> Result, XError> {\n let size_hints = self.alloc_size_hints();\n let mut supplied_by_user = MaybeUninit::uninit();\n unsafe {\n (self.xlib.XGetWMNormalHints)(\n self.display,\n window,\n size_hints.ptr,\n supplied_by_user.as_mut_ptr(),\n );\n }\n self.check_errors().map(|_| NormalHints { size_hints })\n }\n\n pub fn set_normal_hints(\n &self,\n window: ffi::Window,\n normal_hints: NormalHints<'_>,\n ) -> Flusher<'_> {\n unsafe {\n (self.xlib.XSetWMNormalHints)(self.display, window, normal_hints.size_hints.ptr);\n }\n Flusher::new(self)\n }\n\n pub fn get_motif_hints(&self, window: ffi::Window) -> MotifHints {\n let motif_hints = unsafe { self.get_atom_unchecked(b\"_MOTIF_WM_HINTS\\0\") };\n\n let mut hints = MotifHints::new();\n\n if let Ok(props) = self.get_property::(window, motif_hints, motif_hints) {\n hints.hints.flags = props.get(0).cloned().unwrap_or(0);\n hints.hints.functions = props.get(1).cloned().unwrap_or(0);\n hints.hints.decorations = props.get(2).cloned().unwrap_or(0);\n hints.hints.input_mode = props.get(3).cloned().unwrap_or(0) as c_long;\n hints.hints.status = props.get(4).cloned().unwrap_or(0);\n }\n\n hints\n }\n\n pub fn set_motif_hints(&self, window: ffi::Window, hints: &MotifHints) -> Flusher<'_> {\n let motif_hints = unsafe { self.get_atom_unchecked(b\"_MOTIF_WM_HINTS\\0\") };\n\n self.change_property(\n window,\n motif_hints,\n motif_hints,\n PropMode::Replace,\n hints.hints.as_slice(),\n )\n }\n}\n"},"middle":{"kind":"string","value":"{\n self.size_hints.flags |= ffi::PBaseSize;\n self.size_hints.base_width = base_width as c_int;\n self.size_hints.base_height = base_height as c_int;\n }"},"fim_type":{"kind":"string","value":"conditional_block"}}},{"rowIdx":236063,"cells":{"file_name":{"kind":"string","value":"hint.rs"},"prefix":{"kind":"string","value":"use std::slice;\nuse std::sync::Arc;\n\nuse super::*;\n\n#[derive(Debug)]\n#[allow(dead_code)]\npub enum StateOperation {\n Remove = 0, // _NET_WM_STATE_REMOVE\n Add = 1, // _NET_WM_STATE_ADD\n Toggle = 2, // _NET_WM_STATE_TOGGLE\n}\n\nimpl From for StateOperation {\n fn from(op: bool) -> Self {\n if op {\n StateOperation::Add\n } else {\n StateOperation::Remove\n }\n }\n}\n\n/// X window type. Maps directly to\n/// [`_NET_WM_WINDOW_TYPE`](https://specifications.freedesktop.org/wm-spec/wm-spec-1.5.html).\n#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]\n#[cfg_attr(feature = \"serde\", derive(Serialize, Deserialize))]\npub enum WindowType {\n /// A desktop feature. This can include a single window containing desktop icons with the same dimensions as the\n /// screen, allowing the desktop environment to have full control of the desktop, without the need for proxying\n /// root window clicks.\n Desktop,\n /// A dock or panel feature. Typically a Window Manager would keep such windows on top of all other windows.\n Dock,\n /// Toolbar windows. \"Torn off\" from the main application.\n Toolbar,\n /// Pinnable menu windows. \"Torn off\" from the main application.\n Menu,\n /// A small persistent utility window, such as a palette or toolbox.\n Utility,\n /// The window is a splash screen displayed as an application is starting up.\n Splash,\n /// This is a dialog window.\n Dialog,\n /// A dropdown menu that usually appears when the user clicks on an item in a menu bar.\n /// This property is typically used on override-redirect windows.\n DropdownMenu,\n /// A popup menu that usually appears when the user right clicks on an object.\n /// This property is typically used on override-redirect windows.\n PopupMenu,\n /// A tooltip window. Usually used to show additional information when hovering over an object with the cursor.\n /// This property is typically used on override-redirect windows.\n Tooltip,\n /// The window is a notification.\n /// This property is typically used on override-redirect windows.\n Notification,\n /// This should be used on the windows that are popped up by combo boxes.\n /// This property is typically used on override-redirect windows.\n Combo,\n /// This indicates the the window is being dragged.\n /// This property is typically used on override-redirect windows.\n Dnd,\n /// This is a normal, top-level window.\n Normal,\n}\n\nimpl Default for WindowType {\n fn default() -> Self {\n WindowType::Normal\n }\n}\n\nimpl WindowType {\n pub(crate) fn as_atom(&self, xconn: &Arc) -> ffi::Atom {\n use self::WindowType::*;\n let atom_name: &[u8] = match *self {\n Desktop => b\"_NET_WM_WINDOW_TYPE_DESKTOP\\0\",\n Dock => b\"_NET_WM_WINDOW_TYPE_DOCK\\0\",\n Toolbar => b\"_NET_WM_WINDOW_TYPE_TOOLBAR\\0\",\n Menu => b\"_NET_WM_WINDOW_TYPE_MENU\\0\",\n Utility => b\"_NET_WM_WINDOW_TYPE_UTILITY\\0\",\n Splash => b\"_NET_WM_WINDOW_TYPE_SPLASH\\0\",\n Dialog => b\"_NET_WM_WINDOW_TYPE_DIALOG\\0\",\n DropdownMenu => b\"_NET_WM_WINDOW_TYPE_DROPDOWN_MENU\\0\",\n PopupMenu => b\"_NET_WM_WINDOW_TYPE_POPUP_MENU\\0\",\n Tooltip => b\"_NET_WM_WINDOW_TYPE_TOOLTIP\\0\",\n Notification => b\"_NET_WM_WINDOW_TYPE_NOTIFICATION\\0\",\n Combo => b\"_NET_WM_WINDOW_TYPE_COMBO\\0\",\n Dnd => b\"_NET_WM_WINDOW_TYPE_DND\\0\",\n Normal => b\"_NET_WM_WINDOW_TYPE_NORMAL\\0\",\n };\n unsafe { xconn.get_atom_unchecked(atom_name) }\n }\n}\n\npub struct MotifHints {\n hints: MwmHints,\n}\n\n#[repr(C)]\nstruct MwmHints {\n flags: c_ulong,\n functions: c_ulong,\n decorations: c_ulong,\n input_mode: c_long,\n status: c_ulong,\n}\n\n#[allow(dead_code)]\nmod mwm {\n use libc::c_ulong;\n\n // Motif WM hints are obsolete, but still widely supported.\n // https://stackoverflow.com/a/1909708\n pub const MWM_HINTS_FUNCTIONS: c_ulong = 1 << 0;\n pub const MWM_HINTS_DECORATIONS: c_ulong = 1 << 1;\n\n pub const MWM_FUNC_ALL: c_ulong = 1 << 0;\n pub const MWM_FUNC_RESIZE: c_ulong = 1 << 1;\n pub const MWM_FUNC_MOVE: c_ulong = 1 << 2;\n pub const MWM_FUNC_MINIMIZE: c_ulong = 1 << 3;\n pub const MWM_FUNC_MAXIMIZE: c_ulong = 1 << 4;\n pub const MWM_FUNC_CLOSE: c_ulong = 1 << 5;\n}\n\nimpl MotifHints {\n pub fn new() -> MotifHints {\n MotifHints {\n hints: MwmHints {\n flags: 0,\n functions: 0,\n decorations: 0,\n input_mode: 0,\n status: 0,\n },\n }\n }\n\n pub fn set_decorations(&mut self, decorations: bool) {\n self.hints.flags |= mwm::MWM_HINTS_DECORATIONS;\n self.hints.decorations = decorations as c_ulong;\n }\n\n pub fn "},"suffix":{"kind":"string","value":"(&mut self, maximizable: bool) {\n if maximizable {\n self.add_func(mwm::MWM_FUNC_MAXIMIZE);\n } else {\n self.remove_func(mwm::MWM_FUNC_MAXIMIZE);\n }\n }\n\n fn add_func(&mut self, func: c_ulong) {\n if self.hints.flags & mwm::MWM_HINTS_FUNCTIONS != 0 {\n if self.hints.functions & mwm::MWM_FUNC_ALL != 0 {\n self.hints.functions &= !func;\n } else {\n self.hints.functions |= func;\n }\n }\n }\n\n fn remove_func(&mut self, func: c_ulong) {\n if self.hints.flags & mwm::MWM_HINTS_FUNCTIONS == 0 {\n self.hints.flags |= mwm::MWM_HINTS_FUNCTIONS;\n self.hints.functions = mwm::MWM_FUNC_ALL;\n }\n\n if self.hints.functions & mwm::MWM_FUNC_ALL != 0 {\n self.hints.functions |= func;\n } else {\n self.hints.functions &= !func;\n }\n }\n}\n\nimpl MwmHints {\n fn as_slice(&self) -> &[c_ulong] {\n unsafe { slice::from_raw_parts(self as *const _ as *const c_ulong, 5) }\n }\n}\n\npub struct NormalHints<'a> {\n size_hints: XSmartPointer<'a, ffi::XSizeHints>,\n}\n\nimpl<'a> NormalHints<'a> {\n pub fn new(xconn: &'a XConnection) -> Self {\n NormalHints {\n size_hints: xconn.alloc_size_hints(),\n }\n }\n\n pub fn get_position(&self) -> Option<(i32, i32)> {\n if has_flag(self.size_hints.flags, ffi::PPosition) {\n Some((self.size_hints.x as i32, self.size_hints.y as i32))\n } else {\n None\n }\n }\n\n pub fn set_position(&mut self, position: Option<(i32, i32)>) {\n if let Some((x, y)) = position {\n self.size_hints.flags |= ffi::PPosition;\n self.size_hints.x = x as c_int;\n self.size_hints.y = y as c_int;\n } else {\n self.size_hints.flags &= !ffi::PPosition;\n }\n }\n\n // WARNING: This hint is obsolete\n pub fn set_size(&mut self, size: Option<(u32, u32)>) {\n if let Some((width, height)) = size {\n self.size_hints.flags |= ffi::PSize;\n self.size_hints.width = width as c_int;\n self.size_hints.height = height as c_int;\n } else {\n self.size_hints.flags &= !ffi::PSize;\n }\n }\n\n pub fn set_max_size(&mut self, max_size: Option<(u32, u32)>) {\n if let Some((max_width, max_height)) = max_size {\n self.size_hints.flags |= ffi::PMaxSize;\n self.size_hints.max_width = max_width as c_int;\n self.size_hints.max_height = max_height as c_int;\n } else {\n self.size_hints.flags &= !ffi::PMaxSize;\n }\n }\n\n pub fn set_min_size(&mut self, min_size: Option<(u32, u32)>) {\n if let Some((min_width, min_height)) = min_size {\n self.size_hints.flags |= ffi::PMinSize;\n self.size_hints.min_width = min_width as c_int;\n self.size_hints.min_height = min_height as c_int;\n } else {\n self.size_hints.flags &= !ffi::PMinSize;\n }\n }\n\n pub fn set_resize_increments(&mut self, resize_increments: Option<(u32, u32)>) {\n if let Some((width_inc, height_inc)) = resize_increments {\n self.size_hints.flags |= ffi::PResizeInc;\n self.size_hints.width_inc = width_inc as c_int;\n self.size_hints.height_inc = height_inc as c_int;\n } else {\n self.size_hints.flags &= !ffi::PResizeInc;\n }\n }\n\n pub fn set_base_size(&mut self, base_size: Option<(u32, u32)>) {\n if let Some((base_width, base_height)) = base_size {\n self.size_hints.flags |= ffi::PBaseSize;\n self.size_hints.base_width = base_width as c_int;\n self.size_hints.base_height = base_height as c_int;\n } else {\n self.size_hints.flags &= !ffi::PBaseSize;\n }\n }\n}\n\nimpl XConnection {\n pub fn get_wm_hints(\n &self,\n window: ffi::Window,\n ) -> Result, XError> {\n let wm_hints = unsafe { (self.xlib.XGetWMHints)(self.display, window) };\n self.check_errors()?;\n let wm_hints = if wm_hints.is_null() {\n self.alloc_wm_hints()\n } else {\n XSmartPointer::new(self, wm_hints).unwrap()\n };\n Ok(wm_hints)\n }\n\n pub fn set_wm_hints(\n &self,\n window: ffi::Window,\n wm_hints: XSmartPointer<'_, ffi::XWMHints>,\n ) -> Flusher<'_> {\n unsafe {\n (self.xlib.XSetWMHints)(self.display, window, wm_hints.ptr);\n }\n Flusher::new(self)\n }\n\n pub fn get_normal_hints(&self, window: ffi::Window) -> Result, XError> {\n let size_hints = self.alloc_size_hints();\n let mut supplied_by_user = MaybeUninit::uninit();\n unsafe {\n (self.xlib.XGetWMNormalHints)(\n self.display,\n window,\n size_hints.ptr,\n supplied_by_user.as_mut_ptr(),\n );\n }\n self.check_errors().map(|_| NormalHints { size_hints })\n }\n\n pub fn set_normal_hints(\n &self,\n window: ffi::Window,\n normal_hints: NormalHints<'_>,\n ) -> Flusher<'_> {\n unsafe {\n (self.xlib.XSetWMNormalHints)(self.display, window, normal_hints.size_hints.ptr);\n }\n Flusher::new(self)\n }\n\n pub fn get_motif_hints(&self, window: ffi::Window) -> MotifHints {\n let motif_hints = unsafe { self.get_atom_unchecked(b\"_MOTIF_WM_HINTS\\0\") };\n\n let mut hints = MotifHints::new();\n\n if let Ok(props) = self.get_property::(window, motif_hints, motif_hints) {\n hints.hints.flags = props.get(0).cloned().unwrap_or(0);\n hints.hints.functions = props.get(1).cloned().unwrap_or(0);\n hints.hints.decorations = props.get(2).cloned().unwrap_or(0);\n hints.hints.input_mode = props.get(3).cloned().unwrap_or(0) as c_long;\n hints.hints.status = props.get(4).cloned().unwrap_or(0);\n }\n\n hints\n }\n\n pub fn set_motif_hints(&self, window: ffi::Window, hints: &MotifHints) -> Flusher<'_> {\n let motif_hints = unsafe { self.get_atom_unchecked(b\"_MOTIF_WM_HINTS\\0\") };\n\n self.change_property(\n window,\n motif_hints,\n motif_hints,\n PropMode::Replace,\n hints.hints.as_slice(),\n )\n }\n}\n"},"middle":{"kind":"string","value":"set_maximizable"},"fim_type":{"kind":"string","value":"identifier_name"}}},{"rowIdx":236064,"cells":{"file_name":{"kind":"string","value":"reflection_capabilities.ts"},"prefix":{"kind":"string","value":"/**\n * @license\n * Copyright Google Inc. All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.io/license\n */\n\nimport {Type, isType} from '../interface/type';\nimport {ANNOTATIONS, PARAMETERS, PROP_METADATA} from '../util/decorators';\nimport {global} from '../util/global';\nimport {stringify} from '../util/stringify';\n\nimport {PlatformReflectionCapabilities} from './platform_reflection_capabilities';\nimport {GetterFn, MethodFn, SetterFn} from './types';\n\n\n\n/**\n * Attention: These regex has to hold even if the code is minified!\n */\nexport const DELEGATE_CTOR = /^function\\s+\\S+\\(\\)\\s*{[\\s\\S]+\\.apply\\(this,\\s*arguments\\)/;\nexport const INHERITED_CLASS = /^class\\s+[A-Za-z\\d$_]*\\s*extends\\s+[^{]+{/;\nexport const INHERITED_CLASS_WITH_CTOR =\n /^class\\s+[A-Za-z\\d$_]*\\s*extends\\s+[^{]+{[\\s\\S]*constructor\\s*\\(/;\n\nexport class ReflectionCapabilities implements PlatformReflectionCapabilities {\n private _reflect: any;\n\n constructor(reflect?: any) { this._reflect = reflect || global['Reflect']; }\n\n isReflectionEnabled(): boolean { return true; }\n\n factory(t: Type): (args: any[]) => T { return (...args: any[]) => new t(...args); }\n\n /** @internal */\n _zipTypesAndAnnotations(paramTypes: any[], paramAnnotations: any[]): any[][] {\n let result: any[][];\n\n if (typeof paramTypes === 'undefined') {\n result = new Array(paramAnnotations.length);\n } else {\n result = new Array(paramTypes.length);\n }\n\n for (let i = 0; i < result.length; i++) {\n // TS outputs Object for parameters without types, while Traceur omits\n // the annotations. For now we preserve the Traceur behavior to aid\n // migration, but this can be revisited.\n if (typeof paramTypes === 'undefined') {\n result[i] = [];\n } else if (paramTypes[i] != Object) {\n result[i] = [paramTypes[i]];\n } else {\n result[i] = [];\n }\n if (paramAnnotations && paramAnnotations[i] != null) {\n result[i] = result[i].concat(paramAnnotations[i]);\n }\n }\n return result;\n }\n\n private _ownParameters(type: Type, parentCtor: any): any[][]|null {\n const typeStr = type.toString();\n // If we have no decorators, we only have function.length as metadata.\n // In that case, to detect whether a child class declared an own constructor or not,\n // we need to look inside of that constructor to check whether it is\n // just calling the parent.\n // This also helps to work around for https://github.com/Microsoft/TypeScript/issues/12439\n // that sets 'design:paramtypes' to []\n // if a class inherits from another class but has no ctor declared itself.\n if (DELEGATE_CTOR.exec(typeStr) ||\n (INHERITED_CLASS.exec(typeStr) && !INHERITED_CLASS_WITH_CTOR.exec(typeStr))) {\n return null;\n }\n\n // Prefer the direct API.\n if ((type).parameters && (type).parameters !== parentCtor.parameters) {\n return (type).parameters;\n }\n\n // API of tsickle for lowering decorators to properties on the class.\n const tsickleCtorParams = (type).ctorParameters;\n if (tsickleCtorParams && tsickleCtorParams !== parentCtor.ctorParameters) {\n // Newer tsickle uses a function closure\n // Retain the non-function case for compatibility with older tsickle\n const ctorParameters =\n typeof tsickleCtorParams === 'function' ? tsickleCtorParams() : tsickleCtorParams;\n const paramTypes = ctorParameters.map((ctorParam: any) => ctorParam && ctorParam.type);\n const paramAnnotations = ctorParameters.map(\n (ctorParam: any) =>\n ctorParam && convertTsickleDecoratorIntoMetadata(ctorParam.decorators));\n return this._zipTypesAndAnnotations(paramTypes, paramAnnotations);\n }\n\n // API for metadata created by invoking the decorators.\n const paramAnnotations = type.hasOwnProperty(PARAMETERS) && (type as any)[PARAMETERS];\n const paramTypes = this._reflect && this._reflect.getOwnMetadata &&\n this._reflect.getOwnMetadata('design:paramtypes', type);\n if (paramTypes || paramAnnotations) {\n return this._zipTypesAndAnnotations(paramTypes, paramAnnotations);\n }\n\n // If a class has no decorators, at least create metadata\n // based on function.length.\n // Note: We know that this is a real constructor as we checked\n // the content of the constructor above.\n return new Array((type.length)).fill(undefined);\n }\n\n parameters(type: Type): any[][] {\n // Note: only report metadata if we have at least one class decorator\n // to stay in sync with the static reflector.\n if (!isType(type)) {\n return [];\n }\n const parentCtor = getParentCtor(type);\n let parameters = this._ownParameters(type, parentCtor);\n if (!parameters && parentCtor !== Object) {\n parameters = this.parameters(parentCtor);\n }\n return parameters || [];\n }\n\n private _ownAnnotations(typeOrFunc: Type, parentCtor: any): any[]|null {\n // Prefer the direct API.\n if ((typeOrFunc).annotations && (typeOrFunc).annotations !== parentCtor.annotations) {\n let annotations = (typeOrFunc).annotations;\n if (typeof annotations === 'function' && annotations.annotations) {\n annotations = annotations.annotations;\n }\n return annotations;\n }\n\n // API of tsickle for lowering decorators to properties on the class.\n if ((typeOrFunc).decorators && (typeOrFunc).decorators !== parentCtor.decorators) {\n return convertTsickleDecoratorIntoMetadata((typeOrFunc).decorators);\n }\n\n // API for metadata created by invoking the decorators.\n if (typeOrFunc.hasOwnProperty(ANNOTATIONS)) "},"suffix":{"kind":"string","value":"\n return null;\n }\n\n annotations(typeOrFunc: Type): any[] {\n if (!isType(typeOrFunc)) {\n return [];\n }\n const parentCtor = getParentCtor(typeOrFunc);\n const ownAnnotations = this._ownAnnotations(typeOrFunc, parentCtor) || [];\n const parentAnnotations = parentCtor !== Object ? this.annotations(parentCtor) : [];\n return parentAnnotations.concat(ownAnnotations);\n }\n\n private _ownPropMetadata(typeOrFunc: any, parentCtor: any): {[key: string]: any[]}|null {\n // Prefer the direct API.\n if ((typeOrFunc).propMetadata &&\n (typeOrFunc).propMetadata !== parentCtor.propMetadata) {\n let propMetadata = (typeOrFunc).propMetadata;\n if (typeof propMetadata === 'function' && propMetadata.propMetadata) {\n propMetadata = propMetadata.propMetadata;\n }\n return propMetadata;\n }\n\n // API of tsickle for lowering decorators to properties on the class.\n if ((typeOrFunc).propDecorators &&\n (typeOrFunc).propDecorators !== parentCtor.propDecorators) {\n const propDecorators = (typeOrFunc).propDecorators;\n const propMetadata = <{[key: string]: any[]}>{};\n Object.keys(propDecorators).forEach(prop => {\n propMetadata[prop] = convertTsickleDecoratorIntoMetadata(propDecorators[prop]);\n });\n return propMetadata;\n }\n\n // API for metadata created by invoking the decorators.\n if (typeOrFunc.hasOwnProperty(PROP_METADATA)) {\n return (typeOrFunc as any)[PROP_METADATA];\n }\n return null;\n }\n\n propMetadata(typeOrFunc: any): {[key: string]: any[]} {\n if (!isType(typeOrFunc)) {\n return {};\n }\n const parentCtor = getParentCtor(typeOrFunc);\n const propMetadata: {[key: string]: any[]} = {};\n if (parentCtor !== Object) {\n const parentPropMetadata = this.propMetadata(parentCtor);\n Object.keys(parentPropMetadata).forEach((propName) => {\n propMetadata[propName] = parentPropMetadata[propName];\n });\n }\n const ownPropMetadata = this._ownPropMetadata(typeOrFunc, parentCtor);\n if (ownPropMetadata) {\n Object.keys(ownPropMetadata).forEach((propName) => {\n const decorators: any[] = [];\n if (propMetadata.hasOwnProperty(propName)) {\n decorators.push(...propMetadata[propName]);\n }\n decorators.push(...ownPropMetadata[propName]);\n propMetadata[propName] = decorators;\n });\n }\n return propMetadata;\n }\n\n hasLifecycleHook(type: any, lcProperty: string): boolean {\n return type instanceof Type && lcProperty in type.prototype;\n }\n\n guards(type: any): {[key: string]: any} { return {}; }\n\n getter(name: string): GetterFn { return new Function('o', 'return o.' + name + ';'); }\n\n setter(name: string): SetterFn {\n return new Function('o', 'v', 'return o.' + name + ' = v;');\n }\n\n method(name: string): MethodFn {\n const functionBody = `if (!o.${name}) throw new Error('\"${name}\" is undefined');\n return o.${name}.apply(o, args);`;\n return new Function('o', 'args', functionBody);\n }\n\n // There is not a concept of import uri in Js, but this is useful in developing Dart applications.\n importUri(type: any): string {\n // StaticSymbol\n if (typeof type === 'object' && type['filePath']) {\n return type['filePath'];\n }\n // Runtime type\n return `./${stringify(type)}`;\n }\n\n resourceUri(type: any): string { return `./${stringify(type)}`; }\n\n resolveIdentifier(name: string, moduleUrl: string, members: string[], runtime: any): any {\n return runtime;\n }\n resolveEnum(enumIdentifier: any, name: string): any { return enumIdentifier[name]; }\n}\n\nfunction convertTsickleDecoratorIntoMetadata(decoratorInvocations: any[]): any[] {\n if (!decoratorInvocations) {\n return [];\n }\n return decoratorInvocations.map(decoratorInvocation => {\n const decoratorType = decoratorInvocation.type;\n const annotationCls = decoratorType.annotationCls;\n const annotationArgs = decoratorInvocation.args ? decoratorInvocation.args : [];\n return new annotationCls(...annotationArgs);\n });\n}\n\nfunction getParentCtor(ctor: Function): Type {\n const parentProto = ctor.prototype ? Object.getPrototypeOf(ctor.prototype) : null;\n const parentCtor = parentProto ? parentProto.constructor : null;\n // Note: We always use `Object` as the null value\n // to simplify checking later on.\n return parentCtor || Object;\n}\n"},"middle":{"kind":"string","value":"{\n return (typeOrFunc as any)[ANNOTATIONS];\n }"},"fim_type":{"kind":"string","value":"conditional_block"}}},{"rowIdx":236065,"cells":{"file_name":{"kind":"string","value":"reflection_capabilities.ts"},"prefix":{"kind":"string","value":"/**\n * @license\n * Copyright Google Inc. All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.io/license\n */\n\nimport {Type, isType} from '../interface/type';\nimport {ANNOTATIONS, PARAMETERS, PROP_METADATA} from '../util/decorators';\nimport {global} from '../util/global';\nimport {stringify} from '../util/stringify';\n\nimport {PlatformReflectionCapabilities} from './platform_reflection_capabilities';\nimport {GetterFn, MethodFn, SetterFn} from './types';\n\n\n\n/**\n * Attention: These regex has to hold even if the code is minified!\n */\nexport const DELEGATE_CTOR = /^function\\s+\\S+\\(\\)\\s*{[\\s\\S]+\\.apply\\(this,\\s*arguments\\)/;\nexport const INHERITED_CLASS = /^class\\s+[A-Za-z\\d$_]*\\s*extends\\s+[^{]+{/;\nexport const INHERITED_CLASS_WITH_CTOR =\n /^class\\s+[A-Za-z\\d$_]*\\s*extends\\s+[^{]+{[\\s\\S]*constructor\\s*\\(/;\n\nexport class ReflectionCapabilities implements PlatformReflectionCapabilities {\n private _reflect: any;\n\n constructor(reflect?: any) { this._reflect = reflect || global['Reflect']; }\n\n isReflectionEnabled(): boolean { return true; }\n\n "},"suffix":{"kind":"string","value":"(t: Type): (args: any[]) => T { return (...args: any[]) => new t(...args); }\n\n /** @internal */\n _zipTypesAndAnnotations(paramTypes: any[], paramAnnotations: any[]): any[][] {\n let result: any[][];\n\n if (typeof paramTypes === 'undefined') {\n result = new Array(paramAnnotations.length);\n } else {\n result = new Array(paramTypes.length);\n }\n\n for (let i = 0; i < result.length; i++) {\n // TS outputs Object for parameters without types, while Traceur omits\n // the annotations. For now we preserve the Traceur behavior to aid\n // migration, but this can be revisited.\n if (typeof paramTypes === 'undefined') {\n result[i] = [];\n } else if (paramTypes[i] != Object) {\n result[i] = [paramTypes[i]];\n } else {\n result[i] = [];\n }\n if (paramAnnotations && paramAnnotations[i] != null) {\n result[i] = result[i].concat(paramAnnotations[i]);\n }\n }\n return result;\n }\n\n private _ownParameters(type: Type, parentCtor: any): any[][]|null {\n const typeStr = type.toString();\n // If we have no decorators, we only have function.length as metadata.\n // In that case, to detect whether a child class declared an own constructor or not,\n // we need to look inside of that constructor to check whether it is\n // just calling the parent.\n // This also helps to work around for https://github.com/Microsoft/TypeScript/issues/12439\n // that sets 'design:paramtypes' to []\n // if a class inherits from another class but has no ctor declared itself.\n if (DELEGATE_CTOR.exec(typeStr) ||\n (INHERITED_CLASS.exec(typeStr) && !INHERITED_CLASS_WITH_CTOR.exec(typeStr))) {\n return null;\n }\n\n // Prefer the direct API.\n if ((type).parameters && (type).parameters !== parentCtor.parameters) {\n return (type).parameters;\n }\n\n // API of tsickle for lowering decorators to properties on the class.\n const tsickleCtorParams = (type).ctorParameters;\n if (tsickleCtorParams && tsickleCtorParams !== parentCtor.ctorParameters) {\n // Newer tsickle uses a function closure\n // Retain the non-function case for compatibility with older tsickle\n const ctorParameters =\n typeof tsickleCtorParams === 'function' ? tsickleCtorParams() : tsickleCtorParams;\n const paramTypes = ctorParameters.map((ctorParam: any) => ctorParam && ctorParam.type);\n const paramAnnotations = ctorParameters.map(\n (ctorParam: any) =>\n ctorParam && convertTsickleDecoratorIntoMetadata(ctorParam.decorators));\n return this._zipTypesAndAnnotations(paramTypes, paramAnnotations);\n }\n\n // API for metadata created by invoking the decorators.\n const paramAnnotations = type.hasOwnProperty(PARAMETERS) && (type as any)[PARAMETERS];\n const paramTypes = this._reflect && this._reflect.getOwnMetadata &&\n this._reflect.getOwnMetadata('design:paramtypes', type);\n if (paramTypes || paramAnnotations) {\n return this._zipTypesAndAnnotations(paramTypes, paramAnnotations);\n }\n\n // If a class has no decorators, at least create metadata\n // based on function.length.\n // Note: We know that this is a real constructor as we checked\n // the content of the constructor above.\n return new Array((type.length)).fill(undefined);\n }\n\n parameters(type: Type): any[][] {\n // Note: only report metadata if we have at least one class decorator\n // to stay in sync with the static reflector.\n if (!isType(type)) {\n return [];\n }\n const parentCtor = getParentCtor(type);\n let parameters = this._ownParameters(type, parentCtor);\n if (!parameters && parentCtor !== Object) {\n parameters = this.parameters(parentCtor);\n }\n return parameters || [];\n }\n\n private _ownAnnotations(typeOrFunc: Type, parentCtor: any): any[]|null {\n // Prefer the direct API.\n if ((typeOrFunc).annotations && (typeOrFunc).annotations !== parentCtor.annotations) {\n let annotations = (typeOrFunc).annotations;\n if (typeof annotations === 'function' && annotations.annotations) {\n annotations = annotations.annotations;\n }\n return annotations;\n }\n\n // API of tsickle for lowering decorators to properties on the class.\n if ((typeOrFunc).decorators && (typeOrFunc).decorators !== parentCtor.decorators) {\n return convertTsickleDecoratorIntoMetadata((typeOrFunc).decorators);\n }\n\n // API for metadata created by invoking the decorators.\n if (typeOrFunc.hasOwnProperty(ANNOTATIONS)) {\n return (typeOrFunc as any)[ANNOTATIONS];\n }\n return null;\n }\n\n annotations(typeOrFunc: Type): any[] {\n if (!isType(typeOrFunc)) {\n return [];\n }\n const parentCtor = getParentCtor(typeOrFunc);\n const ownAnnotations = this._ownAnnotations(typeOrFunc, parentCtor) || [];\n const parentAnnotations = parentCtor !== Object ? this.annotations(parentCtor) : [];\n return parentAnnotations.concat(ownAnnotations);\n }\n\n private _ownPropMetadata(typeOrFunc: any, parentCtor: any): {[key: string]: any[]}|null {\n // Prefer the direct API.\n if ((typeOrFunc).propMetadata &&\n (typeOrFunc).propMetadata !== parentCtor.propMetadata) {\n let propMetadata = (typeOrFunc).propMetadata;\n if (typeof propMetadata === 'function' && propMetadata.propMetadata) {\n propMetadata = propMetadata.propMetadata;\n }\n return propMetadata;\n }\n\n // API of tsickle for lowering decorators to properties on the class.\n if ((typeOrFunc).propDecorators &&\n (typeOrFunc).propDecorators !== parentCtor.propDecorators) {\n const propDecorators = (typeOrFunc).propDecorators;\n const propMetadata = <{[key: string]: any[]}>{};\n Object.keys(propDecorators).forEach(prop => {\n propMetadata[prop] = convertTsickleDecoratorIntoMetadata(propDecorators[prop]);\n });\n return propMetadata;\n }\n\n // API for metadata created by invoking the decorators.\n if (typeOrFunc.hasOwnProperty(PROP_METADATA)) {\n return (typeOrFunc as any)[PROP_METADATA];\n }\n return null;\n }\n\n propMetadata(typeOrFunc: any): {[key: string]: any[]} {\n if (!isType(typeOrFunc)) {\n return {};\n }\n const parentCtor = getParentCtor(typeOrFunc);\n const propMetadata: {[key: string]: any[]} = {};\n if (parentCtor !== Object) {\n const parentPropMetadata = this.propMetadata(parentCtor);\n Object.keys(parentPropMetadata).forEach((propName) => {\n propMetadata[propName] = parentPropMetadata[propName];\n });\n }\n const ownPropMetadata = this._ownPropMetadata(typeOrFunc, parentCtor);\n if (ownPropMetadata) {\n Object.keys(ownPropMetadata).forEach((propName) => {\n const decorators: any[] = [];\n if (propMetadata.hasOwnProperty(propName)) {\n decorators.push(...propMetadata[propName]);\n }\n decorators.push(...ownPropMetadata[propName]);\n propMetadata[propName] = decorators;\n });\n }\n return propMetadata;\n }\n\n hasLifecycleHook(type: any, lcProperty: string): boolean {\n return type instanceof Type && lcProperty in type.prototype;\n }\n\n guards(type: any): {[key: string]: any} { return {}; }\n\n getter(name: string): GetterFn { return new Function('o', 'return o.' + name + ';'); }\n\n setter(name: string): SetterFn {\n return new Function('o', 'v', 'return o.' + name + ' = v;');\n }\n\n method(name: string): MethodFn {\n const functionBody = `if (!o.${name}) throw new Error('\"${name}\" is undefined');\n return o.${name}.apply(o, args);`;\n return new Function('o', 'args', functionBody);\n }\n\n // There is not a concept of import uri in Js, but this is useful in developing Dart applications.\n importUri(type: any): string {\n // StaticSymbol\n if (typeof type === 'object' && type['filePath']) {\n return type['filePath'];\n }\n // Runtime type\n return `./${stringify(type)}`;\n }\n\n resourceUri(type: any): string { return `./${stringify(type)}`; }\n\n resolveIdentifier(name: string, moduleUrl: string, members: string[], runtime: any): any {\n return runtime;\n }\n resolveEnum(enumIdentifier: any, name: string): any { return enumIdentifier[name]; }\n}\n\nfunction convertTsickleDecoratorIntoMetadata(decoratorInvocations: any[]): any[] {\n if (!decoratorInvocations) {\n return [];\n }\n return decoratorInvocations.map(decoratorInvocation => {\n const decoratorType = decoratorInvocation.type;\n const annotationCls = decoratorType.annotationCls;\n const annotationArgs = decoratorInvocation.args ? decoratorInvocation.args : [];\n return new annotationCls(...annotationArgs);\n });\n}\n\nfunction getParentCtor(ctor: Function): Type {\n const parentProto = ctor.prototype ? Object.getPrototypeOf(ctor.prototype) : null;\n const parentCtor = parentProto ? parentProto.constructor : null;\n // Note: We always use `Object` as the null value\n // to simplify checking later on.\n return parentCtor || Object;\n}\n"},"middle":{"kind":"string","value":"factory"},"fim_type":{"kind":"string","value":"identifier_name"}}},{"rowIdx":236066,"cells":{"file_name":{"kind":"string","value":"reflection_capabilities.ts"},"prefix":{"kind":"string","value":"/**\n * @license\n * Copyright Google Inc. All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.io/license\n */\n\nimport {Type, isType} from '../interface/type';\nimport {ANNOTATIONS, PARAMETERS, PROP_METADATA} from '../util/decorators';\nimport {global} from '../util/global';\nimport {stringify} from '../util/stringify';\n\nimport {PlatformReflectionCapabilities} from './platform_reflection_capabilities';\nimport {GetterFn, MethodFn, SetterFn} from './types';\n\n\n\n/**\n * Attention: These regex has to hold even if the code is minified!\n */\nexport const DELEGATE_CTOR = /^function\\s+\\S+\\(\\)\\s*{[\\s\\S]+\\.apply\\(this,\\s*arguments\\)/;\nexport const INHERITED_CLASS = /^class\\s+[A-Za-z\\d$_]*\\s*extends\\s+[^{]+{/;\nexport const INHERITED_CLASS_WITH_CTOR =\n /^class\\s+[A-Za-z\\d$_]*\\s*extends\\s+[^{]+{[\\s\\S]*constructor\\s*\\(/;\n\nexport class ReflectionCapabilities implements PlatformReflectionCapabilities {\n private _reflect: any;\n\n constructor(reflect?: any) { this._reflect = reflect || global['Reflect']; }\n\n isReflectionEnabled(): boolean { return true; }\n\n factory(t: Type): (args: any[]) => T { return (...args: any[]) => new t(...args); }\n\n /** @internal */\n _zipTypesAndAnnotations(paramTypes: any[], paramAnnotations: any[]): any[][] {\n let result: any[][];\n\n if (typeof paramTypes === 'undefined') {\n result = new Array(paramAnnotations.length);\n } else {\n result = new Array(paramTypes.length);\n }\n\n for (let i = 0; i < result.length; i++) {\n // TS outputs Object for parameters without types, while Traceur omits\n // the annotations. For now we preserve the Traceur behavior to aid\n // migration, but this can be revisited.\n if (typeof paramTypes === 'undefined') {\n result[i] = [];\n } else if (paramTypes[i] != Object) {\n result[i] = [paramTypes[i]];\n } else {"},"suffix":{"kind":"string","value":" }\n return result;\n }\n\n private _ownParameters(type: Type, parentCtor: any): any[][]|null {\n const typeStr = type.toString();\n // If we have no decorators, we only have function.length as metadata.\n // In that case, to detect whether a child class declared an own constructor or not,\n // we need to look inside of that constructor to check whether it is\n // just calling the parent.\n // This also helps to work around for https://github.com/Microsoft/TypeScript/issues/12439\n // that sets 'design:paramtypes' to []\n // if a class inherits from another class but has no ctor declared itself.\n if (DELEGATE_CTOR.exec(typeStr) ||\n (INHERITED_CLASS.exec(typeStr) && !INHERITED_CLASS_WITH_CTOR.exec(typeStr))) {\n return null;\n }\n\n // Prefer the direct API.\n if ((type).parameters && (type).parameters !== parentCtor.parameters) {\n return (type).parameters;\n }\n\n // API of tsickle for lowering decorators to properties on the class.\n const tsickleCtorParams = (type).ctorParameters;\n if (tsickleCtorParams && tsickleCtorParams !== parentCtor.ctorParameters) {\n // Newer tsickle uses a function closure\n // Retain the non-function case for compatibility with older tsickle\n const ctorParameters =\n typeof tsickleCtorParams === 'function' ? tsickleCtorParams() : tsickleCtorParams;\n const paramTypes = ctorParameters.map((ctorParam: any) => ctorParam && ctorParam.type);\n const paramAnnotations = ctorParameters.map(\n (ctorParam: any) =>\n ctorParam && convertTsickleDecoratorIntoMetadata(ctorParam.decorators));\n return this._zipTypesAndAnnotations(paramTypes, paramAnnotations);\n }\n\n // API for metadata created by invoking the decorators.\n const paramAnnotations = type.hasOwnProperty(PARAMETERS) && (type as any)[PARAMETERS];\n const paramTypes = this._reflect && this._reflect.getOwnMetadata &&\n this._reflect.getOwnMetadata('design:paramtypes', type);\n if (paramTypes || paramAnnotations) {\n return this._zipTypesAndAnnotations(paramTypes, paramAnnotations);\n }\n\n // If a class has no decorators, at least create metadata\n // based on function.length.\n // Note: We know that this is a real constructor as we checked\n // the content of the constructor above.\n return new Array((type.length)).fill(undefined);\n }\n\n parameters(type: Type): any[][] {\n // Note: only report metadata if we have at least one class decorator\n // to stay in sync with the static reflector.\n if (!isType(type)) {\n return [];\n }\n const parentCtor = getParentCtor(type);\n let parameters = this._ownParameters(type, parentCtor);\n if (!parameters && parentCtor !== Object) {\n parameters = this.parameters(parentCtor);\n }\n return parameters || [];\n }\n\n private _ownAnnotations(typeOrFunc: Type, parentCtor: any): any[]|null {\n // Prefer the direct API.\n if ((typeOrFunc).annotations && (typeOrFunc).annotations !== parentCtor.annotations) {\n let annotations = (typeOrFunc).annotations;\n if (typeof annotations === 'function' && annotations.annotations) {\n annotations = annotations.annotations;\n }\n return annotations;\n }\n\n // API of tsickle for lowering decorators to properties on the class.\n if ((typeOrFunc).decorators && (typeOrFunc).decorators !== parentCtor.decorators) {\n return convertTsickleDecoratorIntoMetadata((typeOrFunc).decorators);\n }\n\n // API for metadata created by invoking the decorators.\n if (typeOrFunc.hasOwnProperty(ANNOTATIONS)) {\n return (typeOrFunc as any)[ANNOTATIONS];\n }\n return null;\n }\n\n annotations(typeOrFunc: Type): any[] {\n if (!isType(typeOrFunc)) {\n return [];\n }\n const parentCtor = getParentCtor(typeOrFunc);\n const ownAnnotations = this._ownAnnotations(typeOrFunc, parentCtor) || [];\n const parentAnnotations = parentCtor !== Object ? this.annotations(parentCtor) : [];\n return parentAnnotations.concat(ownAnnotations);\n }\n\n private _ownPropMetadata(typeOrFunc: any, parentCtor: any): {[key: string]: any[]}|null {\n // Prefer the direct API.\n if ((typeOrFunc).propMetadata &&\n (typeOrFunc).propMetadata !== parentCtor.propMetadata) {\n let propMetadata = (typeOrFunc).propMetadata;\n if (typeof propMetadata === 'function' && propMetadata.propMetadata) {\n propMetadata = propMetadata.propMetadata;\n }\n return propMetadata;\n }\n\n // API of tsickle for lowering decorators to properties on the class.\n if ((typeOrFunc).propDecorators &&\n (typeOrFunc).propDecorators !== parentCtor.propDecorators) {\n const propDecorators = (typeOrFunc).propDecorators;\n const propMetadata = <{[key: string]: any[]}>{};\n Object.keys(propDecorators).forEach(prop => {\n propMetadata[prop] = convertTsickleDecoratorIntoMetadata(propDecorators[prop]);\n });\n return propMetadata;\n }\n\n // API for metadata created by invoking the decorators.\n if (typeOrFunc.hasOwnProperty(PROP_METADATA)) {\n return (typeOrFunc as any)[PROP_METADATA];\n }\n return null;\n }\n\n propMetadata(typeOrFunc: any): {[key: string]: any[]} {\n if (!isType(typeOrFunc)) {\n return {};\n }\n const parentCtor = getParentCtor(typeOrFunc);\n const propMetadata: {[key: string]: any[]} = {};\n if (parentCtor !== Object) {\n const parentPropMetadata = this.propMetadata(parentCtor);\n Object.keys(parentPropMetadata).forEach((propName) => {\n propMetadata[propName] = parentPropMetadata[propName];\n });\n }\n const ownPropMetadata = this._ownPropMetadata(typeOrFunc, parentCtor);\n if (ownPropMetadata) {\n Object.keys(ownPropMetadata).forEach((propName) => {\n const decorators: any[] = [];\n if (propMetadata.hasOwnProperty(propName)) {\n decorators.push(...propMetadata[propName]);\n }\n decorators.push(...ownPropMetadata[propName]);\n propMetadata[propName] = decorators;\n });\n }\n return propMetadata;\n }\n\n hasLifecycleHook(type: any, lcProperty: string): boolean {\n return type instanceof Type && lcProperty in type.prototype;\n }\n\n guards(type: any): {[key: string]: any} { return {}; }\n\n getter(name: string): GetterFn { return new Function('o', 'return o.' + name + ';'); }\n\n setter(name: string): SetterFn {\n return new Function('o', 'v', 'return o.' + name + ' = v;');\n }\n\n method(name: string): MethodFn {\n const functionBody = `if (!o.${name}) throw new Error('\"${name}\" is undefined');\n return o.${name}.apply(o, args);`;\n return new Function('o', 'args', functionBody);\n }\n\n // There is not a concept of import uri in Js, but this is useful in developing Dart applications.\n importUri(type: any): string {\n // StaticSymbol\n if (typeof type === 'object' && type['filePath']) {\n return type['filePath'];\n }\n // Runtime type\n return `./${stringify(type)}`;\n }\n\n resourceUri(type: any): string { return `./${stringify(type)}`; }\n\n resolveIdentifier(name: string, moduleUrl: string, members: string[], runtime: any): any {\n return runtime;\n }\n resolveEnum(enumIdentifier: any, name: string): any { return enumIdentifier[name]; }\n}\n\nfunction convertTsickleDecoratorIntoMetadata(decoratorInvocations: any[]): any[] {\n if (!decoratorInvocations) {\n return [];\n }\n return decoratorInvocations.map(decoratorInvocation => {\n const decoratorType = decoratorInvocation.type;\n const annotationCls = decoratorType.annotationCls;\n const annotationArgs = decoratorInvocation.args ? decoratorInvocation.args : [];\n return new annotationCls(...annotationArgs);\n });\n}\n\nfunction getParentCtor(ctor: Function): Type {\n const parentProto = ctor.prototype ? Object.getPrototypeOf(ctor.prototype) : null;\n const parentCtor = parentProto ? parentProto.constructor : null;\n // Note: We always use `Object` as the null value\n // to simplify checking later on.\n return parentCtor || Object;\n}"},"middle":{"kind":"string","value":" result[i] = [];\n }\n if (paramAnnotations && paramAnnotations[i] != null) {\n result[i] = result[i].concat(paramAnnotations[i]);\n }"},"fim_type":{"kind":"string","value":"random_line_split"}}},{"rowIdx":236067,"cells":{"file_name":{"kind":"string","value":"reflection_capabilities.ts"},"prefix":{"kind":"string","value":"/**\n * @license\n * Copyright Google Inc. All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.io/license\n */\n\nimport {Type, isType} from '../interface/type';\nimport {ANNOTATIONS, PARAMETERS, PROP_METADATA} from '../util/decorators';\nimport {global} from '../util/global';\nimport {stringify} from '../util/stringify';\n\nimport {PlatformReflectionCapabilities} from './platform_reflection_capabilities';\nimport {GetterFn, MethodFn, SetterFn} from './types';\n\n\n\n/**\n * Attention: These regex has to hold even if the code is minified!\n */\nexport const DELEGATE_CTOR = /^function\\s+\\S+\\(\\)\\s*{[\\s\\S]+\\.apply\\(this,\\s*arguments\\)/;\nexport const INHERITED_CLASS = /^class\\s+[A-Za-z\\d$_]*\\s*extends\\s+[^{]+{/;\nexport const INHERITED_CLASS_WITH_CTOR =\n /^class\\s+[A-Za-z\\d$_]*\\s*extends\\s+[^{]+{[\\s\\S]*constructor\\s*\\(/;\n\nexport class ReflectionCapabilities implements PlatformReflectionCapabilities {\n private _reflect: any;\n\n constructor(reflect?: any) { this._reflect = reflect || global['Reflect']; }\n\n isReflectionEnabled(): boolean { return true; }\n\n factory(t: Type): (args: any[]) => T { return (...args: any[]) => new t(...args); }\n\n /** @internal */\n _zipTypesAndAnnotations(paramTypes: any[], paramAnnotations: any[]): any[][] {\n let result: any[][];\n\n if (typeof paramTypes === 'undefined') {\n result = new Array(paramAnnotations.length);\n } else {\n result = new Array(paramTypes.length);\n }\n\n for (let i = 0; i < result.length; i++) {\n // TS outputs Object for parameters without types, while Traceur omits\n // the annotations. For now we preserve the Traceur behavior to aid\n // migration, but this can be revisited.\n if (typeof paramTypes === 'undefined') {\n result[i] = [];\n } else if (paramTypes[i] != Object) {\n result[i] = [paramTypes[i]];\n } else {\n result[i] = [];\n }\n if (paramAnnotations && paramAnnotations[i] != null) {\n result[i] = result[i].concat(paramAnnotations[i]);\n }\n }\n return result;\n }\n\n private _ownParameters(type: Type, parentCtor: any): any[][]|null {\n const typeStr = type.toString();\n // If we have no decorators, we only have function.length as metadata.\n // In that case, to detect whether a child class declared an own constructor or not,\n // we need to look inside of that constructor to check whether it is\n // just calling the parent.\n // This also helps to work around for https://github.com/Microsoft/TypeScript/issues/12439\n // that sets 'design:paramtypes' to []\n // if a class inherits from another class but has no ctor declared itself.\n if (DELEGATE_CTOR.exec(typeStr) ||\n (INHERITED_CLASS.exec(typeStr) && !INHERITED_CLASS_WITH_CTOR.exec(typeStr))) {\n return null;\n }\n\n // Prefer the direct API.\n if ((type).parameters && (type).parameters !== parentCtor.parameters) {\n return (type).parameters;\n }\n\n // API of tsickle for lowering decorators to properties on the class.\n const tsickleCtorParams = (type).ctorParameters;\n if (tsickleCtorParams && tsickleCtorParams !== parentCtor.ctorParameters) {\n // Newer tsickle uses a function closure\n // Retain the non-function case for compatibility with older tsickle\n const ctorParameters =\n typeof tsickleCtorParams === 'function' ? tsickleCtorParams() : tsickleCtorParams;\n const paramTypes = ctorParameters.map((ctorParam: any) => ctorParam && ctorParam.type);\n const paramAnnotations = ctorParameters.map(\n (ctorParam: any) =>\n ctorParam && convertTsickleDecoratorIntoMetadata(ctorParam.decorators));\n return this._zipTypesAndAnnotations(paramTypes, paramAnnotations);\n }\n\n // API for metadata created by invoking the decorators.\n const paramAnnotations = type.hasOwnProperty(PARAMETERS) && (type as any)[PARAMETERS];\n const paramTypes = this._reflect && this._reflect.getOwnMetadata &&\n this._reflect.getOwnMetadata('design:paramtypes', type);\n if (paramTypes || paramAnnotations) {\n return this._zipTypesAndAnnotations(paramTypes, paramAnnotations);\n }\n\n // If a class has no decorators, at least create metadata\n // based on function.length.\n // Note: We know that this is a real constructor as we checked\n // the content of the constructor above.\n return new Array((type.length)).fill(undefined);\n }\n\n parameters(type: Type): any[][] {\n // Note: only report metadata if we have at least one class decorator\n // to stay in sync with the static reflector.\n if (!isType(type)) {\n return [];\n }\n const parentCtor = getParentCtor(type);\n let parameters = this._ownParameters(type, parentCtor);\n if (!parameters && parentCtor !== Object) {\n parameters = this.parameters(parentCtor);\n }\n return parameters || [];\n }\n\n private _ownAnnotations(typeOrFunc: Type, parentCtor: any): any[]|null {\n // Prefer the direct API.\n if ((typeOrFunc).annotations && (typeOrFunc).annotations !== parentCtor.annotations) {\n let annotations = (typeOrFunc).annotations;\n if (typeof annotations === 'function' && annotations.annotations) {\n annotations = annotations.annotations;\n }\n return annotations;\n }\n\n // API of tsickle for lowering decorators to properties on the class.\n if ((typeOrFunc).decorators && (typeOrFunc).decorators !== parentCtor.decorators) {\n return convertTsickleDecoratorIntoMetadata((typeOrFunc).decorators);\n }\n\n // API for metadata created by invoking the decorators.\n if (typeOrFunc.hasOwnProperty(ANNOTATIONS)) {\n return (typeOrFunc as any)[ANNOTATIONS];\n }\n return null;\n }\n\n annotations(typeOrFunc: Type): any[] {\n if (!isType(typeOrFunc)) {\n return [];\n }\n const parentCtor = getParentCtor(typeOrFunc);\n const ownAnnotations = this._ownAnnotations(typeOrFunc, parentCtor) || [];\n const parentAnnotations = parentCtor !== Object ? this.annotations(parentCtor) : [];\n return parentAnnotations.concat(ownAnnotations);\n }\n\n private _ownPropMetadata(typeOrFunc: any, parentCtor: any): {[key: string]: any[]}|null {\n // Prefer the direct API.\n if ((typeOrFunc).propMetadata &&\n (typeOrFunc).propMetadata !== parentCtor.propMetadata) {\n let propMetadata = (typeOrFunc).propMetadata;\n if (typeof propMetadata === 'function' && propMetadata.propMetadata) {\n propMetadata = propMetadata.propMetadata;\n }\n return propMetadata;\n }\n\n // API of tsickle for lowering decorators to properties on the class.\n if ((typeOrFunc).propDecorators &&\n (typeOrFunc).propDecorators !== parentCtor.propDecorators) {\n const propDecorators = (typeOrFunc).propDecorators;\n const propMetadata = <{[key: string]: any[]}>{};\n Object.keys(propDecorators).forEach(prop => {\n propMetadata[prop] = convertTsickleDecoratorIntoMetadata(propDecorators[prop]);\n });\n return propMetadata;\n }\n\n // API for metadata created by invoking the decorators.\n if (typeOrFunc.hasOwnProperty(PROP_METADATA)) {\n return (typeOrFunc as any)[PROP_METADATA];\n }\n return null;\n }\n\n propMetadata(typeOrFunc: any): {[key: string]: any[]} {\n if (!isType(typeOrFunc)) {\n return {};\n }\n const parentCtor = getParentCtor(typeOrFunc);\n const propMetadata: {[key: string]: any[]} = {};\n if (parentCtor !== Object) {\n const parentPropMetadata = this.propMetadata(parentCtor);\n Object.keys(parentPropMetadata).forEach((propName) => {\n propMetadata[propName] = parentPropMetadata[propName];\n });\n }\n const ownPropMetadata = this._ownPropMetadata(typeOrFunc, parentCtor);\n if (ownPropMetadata) {\n Object.keys(ownPropMetadata).forEach((propName) => {\n const decorators: any[] = [];\n if (propMetadata.hasOwnProperty(propName)) {\n decorators.push(...propMetadata[propName]);\n }\n decorators.push(...ownPropMetadata[propName]);\n propMetadata[propName] = decorators;\n });\n }\n return propMetadata;\n }\n\n hasLifecycleHook(type: any, lcProperty: string): boolean {\n return type instanceof Type && lcProperty in type.prototype;\n }\n\n guards(type: any): {[key: string]: any} { return {}; }\n\n getter(name: string): GetterFn { return new Function('o', 'return o.' + name + ';'); }\n\n setter(name: string): SetterFn {\n return new Function('o', 'v', 'return o.' + name + ' = v;');\n }\n\n method(name: string): MethodFn {\n const functionBody = `if (!o.${name}) throw new Error('\"${name}\" is undefined');\n return o.${name}.apply(o, args);`;\n return new Function('o', 'args', functionBody);\n }\n\n // There is not a concept of import uri in Js, but this is useful in developing Dart applications.\n importUri(type: any): string "},"suffix":{"kind":"string","value":"\n\n resourceUri(type: any): string { return `./${stringify(type)}`; }\n\n resolveIdentifier(name: string, moduleUrl: string, members: string[], runtime: any): any {\n return runtime;\n }\n resolveEnum(enumIdentifier: any, name: string): any { return enumIdentifier[name]; }\n}\n\nfunction convertTsickleDecoratorIntoMetadata(decoratorInvocations: any[]): any[] {\n if (!decoratorInvocations) {\n return [];\n }\n return decoratorInvocations.map(decoratorInvocation => {\n const decoratorType = decoratorInvocation.type;\n const annotationCls = decoratorType.annotationCls;\n const annotationArgs = decoratorInvocation.args ? decoratorInvocation.args : [];\n return new annotationCls(...annotationArgs);\n });\n}\n\nfunction getParentCtor(ctor: Function): Type {\n const parentProto = ctor.prototype ? Object.getPrototypeOf(ctor.prototype) : null;\n const parentCtor = parentProto ? parentProto.constructor : null;\n // Note: We always use `Object` as the null value\n // to simplify checking later on.\n return parentCtor || Object;\n}\n"},"middle":{"kind":"string","value":"{\n // StaticSymbol\n if (typeof type === 'object' && type['filePath']) {\n return type['filePath'];\n }\n // Runtime type\n return `./${stringify(type)}`;\n }"},"fim_type":{"kind":"string","value":"identifier_body"}}},{"rowIdx":236068,"cells":{"file_name":{"kind":"string","value":"github.py"},"prefix":{"kind":"string","value":"\"\"\"\nGithub Authentication\n\n\"\"\"\n\nimport httplib2\nfrom django.conf import settings\nfrom django.core.mail import send_mail\nfrom oauth2client.client import OAuth2WebServerFlow\n\nfrom helios_auth import utils\n\n# some parameters to indicate that status updating is not possible\nSTATUS_UPDATES = False\n\n# display tweaks\nLOGIN_MESSAGE = \"Log in with GitHub\"\n\ndef get_flow(redirect_url=None):\n "},"suffix":{"kind":"string","value":"\n\ndef get_auth_url(request, redirect_url):\n flow = get_flow(redirect_url)\n request.session['gh_redirect_uri'] = redirect_url\n return flow.step1_get_authorize_url()\n\ndef get_user_info_after_auth(request):\n redirect_uri = request.session['gh_redirect_uri']\n del request.session['gh_redirect_uri']\n flow = get_flow(redirect_uri)\n if 'code' not in request.GET:\n return None\n code = request.GET['code']\n credentials = flow.step2_exchange(code)\n\n http = httplib2.Http(\".cache\")\n http = credentials.authorize(http)\n (_, content) = http.request(\"https://api.github.com/user\", \"GET\")\n response = utils.from_json(content.decode('utf-8'))\n user_id = response['login']\n user_name = response['name']\n\n (_, content) = http.request(\"https://api.github.com/user/emails\", \"GET\")\n response = utils.from_json(content.decode('utf-8'))\n user_email = None\n for email in response:\n if email['verified'] and email['primary']:\n user_email = email['email']\n break\n if not user_email:\n raise Exception(\"email address with GitHub not verified\")\n\n return {\n 'type': 'github',\n 'user_id': user_id,\n 'name': '%s (%s)' % (user_id, user_name),\n 'info': {'email': user_email},\n 'token': {},\n }\n\ndef do_logout(user):\n return None\n\ndef update_status(token, message):\n pass\n\ndef send_message(user_id, name, user_info, subject, body):\n send_mail(\n subject,\n body,\n settings.SERVER_EMAIL,\n [\"%s <%s>\" % (user_id, user_info['email'])],\n fail_silently=False,\n )\n\ndef check_constraint(eligibility, user_info):\n pass\n\n#\n# Election Creation\n#\ndef can_create_election(user_id, user_info):\n return True\n"},"middle":{"kind":"string","value":"return OAuth2WebServerFlow(\n client_id=settings.GH_CLIENT_ID,\n client_secret=settings.GH_CLIENT_SECRET,\n scope='read:user user:email',\n auth_uri=\"https://github.com/login/oauth/authorize\",\n token_uri=\"https://github.com/login/oauth/access_token\",\n redirect_uri=redirect_url,\n )"},"fim_type":{"kind":"string","value":"identifier_body"}}},{"rowIdx":236069,"cells":{"file_name":{"kind":"string","value":"github.py"},"prefix":{"kind":"string","value":"\"\"\"\nGithub Authentication\n\n\"\"\"\n\nimport httplib2\nfrom django.conf import settings\nfrom django.core.mail import send_mail\nfrom oauth2client.client import OAuth2WebServerFlow\n\nfrom helios_auth import utils\n\n# some parameters to indicate that status updating is not possible\nSTATUS_UPDATES = False\n\n# display tweaks\nLOGIN_MESSAGE = \"Log in with GitHub\"\n\ndef get_flow(redirect_url=None):\n return OAuth2WebServerFlow(\n client_id=settings.GH_CLIENT_ID,\n client_secret=settings.GH_CLIENT_SECRET,\n scope='read:user user:email',\n auth_uri=\"https://github.com/login/oauth/authorize\",\n token_uri=\"https://github.com/login/oauth/access_token\",\n redirect_uri=redirect_url,\n )\n\ndef get_auth_url(request, redirect_url):\n flow = get_flow(redirect_url)\n request.session['gh_redirect_uri'] = redirect_url\n return flow.step1_get_authorize_url()\n\ndef get_user_info_after_auth(request):\n redirect_uri = request.session['gh_redirect_uri']\n del request.session['gh_redirect_uri']\n flow = get_flow(redirect_uri)\n if 'code' not in request.GET:\n return None\n code = request.GET['code']\n credentials = flow.step2_exchange(code)\n\n http = httplib2.Http(\".cache\")\n http = credentials.authorize(http)\n (_, content) = http.request(\"https://api.github.com/user\", \"GET\")\n response = utils.from_json(content.decode('utf-8'))\n user_id = response['login']\n user_name = response['name']\n\n (_, content) = http.request(\"https://api.github.com/user/emails\", \"GET\")\n response = utils.from_json(content.decode('utf-8'))\n user_email = None\n for email in response:\n if email['verified'] and email['primary']:\n user_email = email['email']\n break\n if not user_email:\n raise Exception(\"email address with GitHub not verified\")\n\n return {\n 'type': 'github',\n 'user_id': user_id,\n 'name': '%s (%s)' % (user_id, user_name),\n 'info': {'email': user_email},\n 'token': {},"},"suffix":{"kind":"string","value":"def do_logout(user):\n return None\n\ndef update_status(token, message):\n pass\n\ndef send_message(user_id, name, user_info, subject, body):\n send_mail(\n subject,\n body,\n settings.SERVER_EMAIL,\n [\"%s <%s>\" % (user_id, user_info['email'])],\n fail_silently=False,\n )\n\ndef check_constraint(eligibility, user_info):\n pass\n\n#\n# Election Creation\n#\ndef can_create_election(user_id, user_info):\n return True"},"middle":{"kind":"string","value":" }\n"},"fim_type":{"kind":"string","value":"random_line_split"}}},{"rowIdx":236070,"cells":{"file_name":{"kind":"string","value":"github.py"},"prefix":{"kind":"string","value":"\"\"\"\nGithub Authentication\n\n\"\"\"\n\nimport httplib2\nfrom django.conf import settings\nfrom django.core.mail import send_mail\nfrom oauth2client.client import OAuth2WebServerFlow\n\nfrom helios_auth import utils\n\n# some parameters to indicate that status updating is not possible\nSTATUS_UPDATES = False\n\n# display tweaks\nLOGIN_MESSAGE = \"Log in with GitHub\"\n\ndef get_flow(redirect_url=None):\n return OAuth2WebServerFlow(\n client_id=settings.GH_CLIENT_ID,\n client_secret=settings.GH_CLIENT_SECRET,\n scope='read:user user:email',\n auth_uri=\"https://github.com/login/oauth/authorize\",\n token_uri=\"https://github.com/login/oauth/access_token\",\n redirect_uri=redirect_url,\n )\n\ndef get_auth_url(request, redirect_url):\n flow = get_flow(redirect_url)\n request.session['gh_redirect_uri'] = redirect_url\n return flow.step1_get_authorize_url()\n\ndef get_user_info_after_auth(request):\n redirect_uri = request.session['gh_redirect_uri']\n del request.session['gh_redirect_uri']\n flow = get_flow(redirect_uri)\n if 'code' not in request.GET:\n return None\n code = request.GET['code']\n credentials = flow.step2_exchange(code)\n\n http = httplib2.Http(\".cache\")\n http = credentials.authorize(http)\n (_, content) = http.request(\"https://api.github.com/user\", \"GET\")\n response = utils.from_json(content.decode('utf-8'))\n user_id = response['login']\n user_name = response['name']\n\n (_, content) = http.request(\"https://api.github.com/user/emails\", \"GET\")\n response = utils.from_json(content.decode('utf-8'))\n user_email = None\n for email in response:\n if email['verified'] and email['primary']:\n user_email = email['email']\n break\n if not user_email:\n raise Exception(\"email address with GitHub not verified\")\n\n return {\n 'type': 'github',\n 'user_id': user_id,\n 'name': '%s (%s)' % (user_id, user_name),\n 'info': {'email': user_email},\n 'token': {},\n }\n\ndef do_logout(user):\n return None\n\ndef update_status(token, message):\n pass\n\ndef send_message(user_id, name, user_info, subject, body):\n send_mail(\n subject,\n body,\n settings.SERVER_EMAIL,\n [\"%s <%s>\" % (user_id, user_info['email'])],\n fail_silently=False,\n )\n\ndef check_constraint(eligibility, user_info):\n pass\n\n#\n# Election Creation\n#\ndef "},"suffix":{"kind":"string","value":"(user_id, user_info):\n return True\n"},"middle":{"kind":"string","value":"can_create_election"},"fim_type":{"kind":"string","value":"identifier_name"}}},{"rowIdx":236071,"cells":{"file_name":{"kind":"string","value":"github.py"},"prefix":{"kind":"string","value":"\"\"\"\nGithub Authentication\n\n\"\"\"\n\nimport httplib2\nfrom django.conf import settings\nfrom django.core.mail import send_mail\nfrom oauth2client.client import OAuth2WebServerFlow\n\nfrom helios_auth import utils\n\n# some parameters to indicate that status updating is not possible\nSTATUS_UPDATES = False\n\n# display tweaks\nLOGIN_MESSAGE = \"Log in with GitHub\"\n\ndef get_flow(redirect_url=None):\n return OAuth2WebServerFlow(\n client_id=settings.GH_CLIENT_ID,\n client_secret=settings.GH_CLIENT_SECRET,\n scope='read:user user:email',\n auth_uri=\"https://github.com/login/oauth/authorize\",\n token_uri=\"https://github.com/login/oauth/access_token\",\n redirect_uri=redirect_url,\n )\n\ndef get_auth_url(request, redirect_url):\n flow = get_flow(redirect_url)\n request.session['gh_redirect_uri'] = redirect_url\n return flow.step1_get_authorize_url()\n\ndef get_user_info_after_auth(request):\n redirect_uri = request.session['gh_redirect_uri']\n del request.session['gh_redirect_uri']\n flow = get_flow(redirect_uri)\n if 'code' not in request.GET:\n return None\n code = request.GET['code']\n credentials = flow.step2_exchange(code)\n\n http = httplib2.Http(\".cache\")\n http = credentials.authorize(http)\n (_, content) = http.request(\"https://api.github.com/user\", \"GET\")\n response = utils.from_json(content.decode('utf-8'))\n user_id = response['login']\n user_name = response['name']\n\n (_, content) = http.request(\"https://api.github.com/user/emails\", \"GET\")\n response = utils.from_json(content.decode('utf-8'))\n user_email = None\n for email in response:\n if email['verified'] and email['primary']:\n "},"suffix":{"kind":"string","value":"\n if not user_email:\n raise Exception(\"email address with GitHub not verified\")\n\n return {\n 'type': 'github',\n 'user_id': user_id,\n 'name': '%s (%s)' % (user_id, user_name),\n 'info': {'email': user_email},\n 'token': {},\n }\n\ndef do_logout(user):\n return None\n\ndef update_status(token, message):\n pass\n\ndef send_message(user_id, name, user_info, subject, body):\n send_mail(\n subject,\n body,\n settings.SERVER_EMAIL,\n [\"%s <%s>\" % (user_id, user_info['email'])],\n fail_silently=False,\n )\n\ndef check_constraint(eligibility, user_info):\n pass\n\n#\n# Election Creation\n#\ndef can_create_election(user_id, user_info):\n return True\n"},"middle":{"kind":"string","value":"user_email = email['email']\n break"},"fim_type":{"kind":"string","value":"conditional_block"}}},{"rowIdx":236072,"cells":{"file_name":{"kind":"string","value":"input.rs"},"prefix":{"kind":"string","value":"// Copyright 2015, 2016 Ethcore (UK) Ltd.\n// This file is part of Parity.\n\n// Parity is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n\n// Parity is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n\n// You should have received a copy of the GNU General Public License\n// along with Parity. If not, see .\n\n//! Trie test input deserialization.\n\nuse std::collections::BTreeMap;\nuse std::str::FromStr;\nuse bytes::Bytes;\nuse serde::{Deserialize, Deserializer, Error};\nuse serde::de::{Visitor, MapVisitor, SeqVisitor};\n\n/// Trie test input.\n#[derive(Debug, PartialEq)]\npub struct Input {\n\t/// Input params.\n\tpub data: BTreeMap>,\n}\n\nimpl Deserialize for Input {\n\tfn deserialize(deserializer: &mut D) -> Result\n\t\twhere D: Deserializer\n\t{\n\t\tdeserializer.deserialize(InputVisitor)\n\t}\n}\n\nstruct InputVisitor;\n\nimpl Visitor for InputVisitor {\n\ttype Value = Input;\n\n\tfn visit_map(&mut self, mut visitor: V) -> Result where V: MapVisitor {\n\t\tlet mut result = BTreeMap::new();\n\n\t\tloop {\n\t\t\tlet key_str: Option = try!(visitor.visit_key());\n\t\t\tlet key = match key_str {\n\t\t\t\tSome(ref k) if k.starts_with(\"0x\") => try!(Bytes::from_str(k).map_err(Error::custom)),\n\t\t\t\tSome(k) => Bytes::new(k.into_bytes()),\n\t\t\t\tNone => { break; }\n\t\t\t};\n\n\t\t\tlet val_str: Option = try!(visitor.visit_value());\n\t\t\tlet val = match val_str {\n\t\t\t\tSome(ref v) if v.starts_with(\"0x\") => Some(try!(Bytes::from_str(v).map_err(Error::custom))),\n\t\t\t\tSome(v) => Some(Bytes::new(v.into_bytes())),\n\t\t\t\tNone => None,\n\t\t\t};\n\n\t\t\tresult.insert(key, val);\n\t\t}\n\n\t\ttry!(visitor.end());\n\n\t\tlet input = Input {\n\t\t\tdata: result\n\t\t};\n\n\t\tOk(input)\n\t}\n\n\tfn visit_seq(&mut self, mut visitor: V) -> Result where V: SeqVisitor {\n\t\tlet mut result = BTreeMap::new();\n\n\t\tloop {\n\t\t\tlet keyval: Option>> = try!(visitor.visit());\n\t\t\tlet keyval = match keyval {\n\t\t\t\tSome(k) => k,\n\t\t\t\t_ => { break; },\n\t\t\t};\n\n\t\t\tif keyval.len() != 2 "},"suffix":{"kind":"string","value":"\n\n\t\t\tlet ref key_str: Option = keyval[0];\n\t\t\tlet ref val_str: Option = keyval[1];\n\n\t\t\tlet key = match *key_str {\n\t\t\t\tSome(ref k) if k.starts_with(\"0x\") => try!(Bytes::from_str(k).map_err(Error::custom)),\n\t\t\t\tSome(ref k) => Bytes::new(k.clone().into_bytes()),\n\t\t\t\tNone => { break; }\n\t\t\t};\n\n\t\t\tlet val = match *val_str {\n\t\t\t\tSome(ref v) if v.starts_with(\"0x\") => Some(try!(Bytes::from_str(v).map_err(Error::custom))),\n\t\t\t\tSome(ref v) => Some(Bytes::new(v.clone().into_bytes())),\n\t\t\t\tNone => None,\n\t\t\t};\n\n\t\t\tresult.insert(key, val);\n\t\t}\n\n\t\ttry!(visitor.end());\n\n\t\tlet input = Input {\n\t\t\tdata: result\n\t\t};\n\n\t\tOk(input)\n\t}\n}\n\n#[cfg(test)]\nmod tests {\n\tuse std::collections::BTreeMap;\n\tuse serde_json;\n\tuse bytes::Bytes;\n\tuse super::Input;\n\n\t#[test]\n\tfn input_deserialization_from_map() {\n\t\tlet s = r#\"{\n\t\t\t\"0x0045\" : \"0x0123456789\",\n\t\t\t\"be\" : \"e\",\n\t\t\t\"0x0a\" : null\n\t\t}\"#;\n\n\t\tlet input: Input = serde_json::from_str(s).unwrap();\n\t\tlet mut map = BTreeMap::new();\n\t\tmap.insert(Bytes::new(vec![0, 0x45]), Some(Bytes::new(vec![0x01, 0x23, 0x45, 0x67, 0x89])));\n\t\tmap.insert(Bytes::new(vec![0x62, 0x65]), Some(Bytes::new(vec![0x65])));\n\t\tmap.insert(Bytes::new(vec![0x0a]), None);\n\t\tassert_eq!(input.data, map);\n\t}\n\n\t#[test]\n\tfn input_deserialization_from_array() {\n\t\tlet s = r#\"[\n\t\t\t[\"0x0045\", \"0x0123456789\"],\n\t\t\t[\"be\", \"e\"],\n\t\t\t[\"0x0a\", null]\n\t\t]\"#;\n\n\t\tlet input: Input = serde_json::from_str(s).unwrap();\n\t\tlet mut map = BTreeMap::new();\n\t\tmap.insert(Bytes::new(vec![0, 0x45]), Some(Bytes::new(vec![0x01, 0x23, 0x45, 0x67, 0x89])));\n\t\tmap.insert(Bytes::new(vec![0x62, 0x65]), Some(Bytes::new(vec![0x65])));\n\t\tmap.insert(Bytes::new(vec![0x0a]), None);\n\t\tassert_eq!(input.data, map);\n\t}\n}\n"},"middle":{"kind":"string","value":"{\n\t\t\t\treturn Err(Error::custom(\"Invalid key value pair.\"));\n\t\t\t}"},"fim_type":{"kind":"string","value":"conditional_block"}}},{"rowIdx":236073,"cells":{"file_name":{"kind":"string","value":"input.rs"},"prefix":{"kind":"string","value":"// Copyright 2015, 2016 Ethcore (UK) Ltd.\n// This file is part of Parity.\n\n// Parity is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n\n// Parity is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n\n// You should have received a copy of the GNU General Public License\n// along with Parity. If not, see .\n\n//! Trie test input deserialization.\n\nuse std::collections::BTreeMap;\nuse std::str::FromStr;\nuse bytes::Bytes;\nuse serde::{Deserialize, Deserializer, Error};\nuse serde::de::{Visitor, MapVisitor, SeqVisitor};\n\n/// Trie test input.\n#[derive(Debug, PartialEq)]\npub struct Input {\n\t/// Input params.\n\tpub data: BTreeMap>,\n}\n\nimpl Deserialize for Input {\n\tfn "},"suffix":{"kind":"string","value":"(deserializer: &mut D) -> Result\n\t\twhere D: Deserializer\n\t{\n\t\tdeserializer.deserialize(InputVisitor)\n\t}\n}\n\nstruct InputVisitor;\n\nimpl Visitor for InputVisitor {\n\ttype Value = Input;\n\n\tfn visit_map(&mut self, mut visitor: V) -> Result where V: MapVisitor {\n\t\tlet mut result = BTreeMap::new();\n\n\t\tloop {\n\t\t\tlet key_str: Option = try!(visitor.visit_key());\n\t\t\tlet key = match key_str {\n\t\t\t\tSome(ref k) if k.starts_with(\"0x\") => try!(Bytes::from_str(k).map_err(Error::custom)),\n\t\t\t\tSome(k) => Bytes::new(k.into_bytes()),\n\t\t\t\tNone => { break; }\n\t\t\t};\n\n\t\t\tlet val_str: Option = try!(visitor.visit_value());\n\t\t\tlet val = match val_str {\n\t\t\t\tSome(ref v) if v.starts_with(\"0x\") => Some(try!(Bytes::from_str(v).map_err(Error::custom))),\n\t\t\t\tSome(v) => Some(Bytes::new(v.into_bytes())),\n\t\t\t\tNone => None,\n\t\t\t};\n\n\t\t\tresult.insert(key, val);\n\t\t}\n\n\t\ttry!(visitor.end());\n\n\t\tlet input = Input {\n\t\t\tdata: result\n\t\t};\n\n\t\tOk(input)\n\t}\n\n\tfn visit_seq(&mut self, mut visitor: V) -> Result where V: SeqVisitor {\n\t\tlet mut result = BTreeMap::new();\n\n\t\tloop {\n\t\t\tlet keyval: Option>> = try!(visitor.visit());\n\t\t\tlet keyval = match keyval {\n\t\t\t\tSome(k) => k,\n\t\t\t\t_ => { break; },\n\t\t\t};\n\n\t\t\tif keyval.len() != 2 {\n\t\t\t\treturn Err(Error::custom(\"Invalid key value pair.\"));\n\t\t\t}\n\n\t\t\tlet ref key_str: Option = keyval[0];\n\t\t\tlet ref val_str: Option = keyval[1];\n\n\t\t\tlet key = match *key_str {\n\t\t\t\tSome(ref k) if k.starts_with(\"0x\") => try!(Bytes::from_str(k).map_err(Error::custom)),\n\t\t\t\tSome(ref k) => Bytes::new(k.clone().into_bytes()),\n\t\t\t\tNone => { break; }\n\t\t\t};\n\n\t\t\tlet val = match *val_str {\n\t\t\t\tSome(ref v) if v.starts_with(\"0x\") => Some(try!(Bytes::from_str(v).map_err(Error::custom))),\n\t\t\t\tSome(ref v) => Some(Bytes::new(v.clone().into_bytes())),\n\t\t\t\tNone => None,\n\t\t\t};\n\n\t\t\tresult.insert(key, val);\n\t\t}\n\n\t\ttry!(visitor.end());\n\n\t\tlet input = Input {\n\t\t\tdata: result\n\t\t};\n\n\t\tOk(input)\n\t}\n}\n\n#[cfg(test)]\nmod tests {\n\tuse std::collections::BTreeMap;\n\tuse serde_json;\n\tuse bytes::Bytes;\n\tuse super::Input;\n\n\t#[test]\n\tfn input_deserialization_from_map() {\n\t\tlet s = r#\"{\n\t\t\t\"0x0045\" : \"0x0123456789\",\n\t\t\t\"be\" : \"e\",\n\t\t\t\"0x0a\" : null\n\t\t}\"#;\n\n\t\tlet input: Input = serde_json::from_str(s).unwrap();\n\t\tlet mut map = BTreeMap::new();\n\t\tmap.insert(Bytes::new(vec![0, 0x45]), Some(Bytes::new(vec![0x01, 0x23, 0x45, 0x67, 0x89])));\n\t\tmap.insert(Bytes::new(vec![0x62, 0x65]), Some(Bytes::new(vec![0x65])));\n\t\tmap.insert(Bytes::new(vec![0x0a]), None);\n\t\tassert_eq!(input.data, map);\n\t}\n\n\t#[test]\n\tfn input_deserialization_from_array() {\n\t\tlet s = r#\"[\n\t\t\t[\"0x0045\", \"0x0123456789\"],\n\t\t\t[\"be\", \"e\"],\n\t\t\t[\"0x0a\", null]\n\t\t]\"#;\n\n\t\tlet input: Input = serde_json::from_str(s).unwrap();\n\t\tlet mut map = BTreeMap::new();\n\t\tmap.insert(Bytes::new(vec![0, 0x45]), Some(Bytes::new(vec![0x01, 0x23, 0x45, 0x67, 0x89])));\n\t\tmap.insert(Bytes::new(vec![0x62, 0x65]), Some(Bytes::new(vec![0x65])));\n\t\tmap.insert(Bytes::new(vec![0x0a]), None);\n\t\tassert_eq!(input.data, map);\n\t}\n}\n"},"middle":{"kind":"string","value":"deserialize"},"fim_type":{"kind":"string","value":"identifier_name"}}},{"rowIdx":236074,"cells":{"file_name":{"kind":"string","value":"input.rs"},"prefix":{"kind":"string","value":"// Copyright 2015, 2016 Ethcore (UK) Ltd.\n// This file is part of Parity.\n\n// Parity is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n\n// Parity is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n\n// You should have received a copy of the GNU General Public License\n// along with Parity. If not, see .\n\n//! Trie test input deserialization.\n\nuse std::collections::BTreeMap;\nuse std::str::FromStr;\nuse bytes::Bytes;\nuse serde::{Deserialize, Deserializer, Error};\nuse serde::de::{Visitor, MapVisitor, SeqVisitor};\n\n/// Trie test input.\n#[derive(Debug, PartialEq)]\npub struct Input {\n\t/// Input params.\n\tpub data: BTreeMap>,\n}\n\nimpl Deserialize for Input {\n\tfn deserialize(deserializer: &mut D) -> Result\n\t\twhere D: Deserializer\n\t{\n\t\tdeserializer.deserialize(InputVisitor)\n\t}\n}\n\nstruct InputVisitor;\n\nimpl Visitor for InputVisitor {\n\ttype Value = Input;\n\n\tfn visit_map(&mut self, mut visitor: V) -> Result where V: MapVisitor {\n\t\tlet mut result = BTreeMap::new();\n\n\t\tloop {\n\t\t\tlet key_str: Option = try!(visitor.visit_key());\n\t\t\tlet key = match key_str {\n\t\t\t\tSome(ref k) if k.starts_with(\"0x\") => try!(Bytes::from_str(k).map_err(Error::custom)),\n\t\t\t\tSome(k) => Bytes::new(k.into_bytes()),\n\t\t\t\tNone => { break; }\n\t\t\t};\n\n\t\t\tlet val_str: Option = try!(visitor.visit_value());\n\t\t\tlet val = match val_str {\n\t\t\t\tSome(ref v) if v.starts_with(\"0x\") => Some(try!(Bytes::from_str(v).map_err(Error::custom))),\n\t\t\t\tSome(v) => Some(Bytes::new(v.into_bytes())),\n\t\t\t\tNone => None,\n\t\t\t};\n\n\t\t\tresult.insert(key, val);\n\t\t}\n\n\t\ttry!(visitor.end());\n\n\t\tlet input = Input {\n\t\t\tdata: result\n\t\t};\n\n\t\tOk(input)\n\t}\n\n\tfn visit_seq(&mut self, mut visitor: V) -> Result where V: SeqVisitor {\n\t\tlet mut result = BTreeMap::new();\n\n\t\tloop {\n\t\t\tlet keyval: Option>> = try!(visitor.visit());\n\t\t\tlet keyval = match keyval {\n\t\t\t\tSome(k) => k,\n\t\t\t\t_ => { break; },\n\t\t\t};\n\n\t\t\tif keyval.len() != 2 {\n\t\t\t\treturn Err(Error::custom(\"Invalid key value pair.\"));\n\t\t\t}\n\n\t\t\tlet ref key_str: Option = keyval[0];\n\t\t\tlet ref val_str: Option = keyval[1];\n\n\t\t\tlet key = match *key_str {\n\t\t\t\tSome(ref k) if k.starts_with(\"0x\") => try!(Bytes::from_str(k).map_err(Error::custom)),\n\t\t\t\tSome(ref k) => Bytes::new(k.clone().into_bytes()),\n\t\t\t\tNone => { break; }\n\t\t\t};\n\n\t\t\tlet val = match *val_str {\n\t\t\t\tSome(ref v) if v.starts_with(\"0x\") => Some(try!(Bytes::from_str(v).map_err(Error::custom))),\n\t\t\t\tSome(ref v) => Some(Bytes::new(v.clone().into_bytes())),\n\t\t\t\tNone => None,"},"suffix":{"kind":"string","value":"\n\t\ttry!(visitor.end());\n\n\t\tlet input = Input {\n\t\t\tdata: result\n\t\t};\n\n\t\tOk(input)\n\t}\n}\n\n#[cfg(test)]\nmod tests {\n\tuse std::collections::BTreeMap;\n\tuse serde_json;\n\tuse bytes::Bytes;\n\tuse super::Input;\n\n\t#[test]\n\tfn input_deserialization_from_map() {\n\t\tlet s = r#\"{\n\t\t\t\"0x0045\" : \"0x0123456789\",\n\t\t\t\"be\" : \"e\",\n\t\t\t\"0x0a\" : null\n\t\t}\"#;\n\n\t\tlet input: Input = serde_json::from_str(s).unwrap();\n\t\tlet mut map = BTreeMap::new();\n\t\tmap.insert(Bytes::new(vec![0, 0x45]), Some(Bytes::new(vec![0x01, 0x23, 0x45, 0x67, 0x89])));\n\t\tmap.insert(Bytes::new(vec![0x62, 0x65]), Some(Bytes::new(vec![0x65])));\n\t\tmap.insert(Bytes::new(vec![0x0a]), None);\n\t\tassert_eq!(input.data, map);\n\t}\n\n\t#[test]\n\tfn input_deserialization_from_array() {\n\t\tlet s = r#\"[\n\t\t\t[\"0x0045\", \"0x0123456789\"],\n\t\t\t[\"be\", \"e\"],\n\t\t\t[\"0x0a\", null]\n\t\t]\"#;\n\n\t\tlet input: Input = serde_json::from_str(s).unwrap();\n\t\tlet mut map = BTreeMap::new();\n\t\tmap.insert(Bytes::new(vec![0, 0x45]), Some(Bytes::new(vec![0x01, 0x23, 0x45, 0x67, 0x89])));\n\t\tmap.insert(Bytes::new(vec![0x62, 0x65]), Some(Bytes::new(vec![0x65])));\n\t\tmap.insert(Bytes::new(vec![0x0a]), None);\n\t\tassert_eq!(input.data, map);\n\t}\n}"},"middle":{"kind":"string","value":"\t\t\t};\n\n\t\t\tresult.insert(key, val);\n\t\t}"},"fim_type":{"kind":"string","value":"random_line_split"}}},{"rowIdx":236075,"cells":{"file_name":{"kind":"string","value":"conf.py"},"prefix":{"kind":"string","value":"import os\nimport string\nimport random\n\nfrom fabric.api import env\nfrom fabric.colors import green\n\nfrom literals import (DEFAULT_INSTALL_PATH, DEFAULT_VIRTUALENV_NAME, \n DEFAULT_REPOSITORY_NAME, DEFAULT_OS, OS_CHOICES, "},"suffix":{"kind":"string","value":"\ndef password_generator():\n # http://snipplr.com/view/63223/python-password-generator/\n chars = string.ascii_letters + string.digits\n return ''.join(random.choice(chars) for x in range(DEFAULT_PASSWORD_LENGTH))\n\n\n@reduce_env\ndef setup_environment():\n env['os'] = getattr(env, 'os', DEFAULT_OS)\n env['os_name'] = OS_CHOICES[env.os]\n \n env['install_path'] = getattr(env, 'install_path', DEFAULT_INSTALL_PATH[env.os])\n env['virtualenv_name'] = getattr(env, 'virtualenv_name', DEFAULT_VIRTUALENV_NAME[env.os])\n env['repository_name'] = getattr(env, 'repository_name', DEFAULT_REPOSITORY_NAME[env.os])\n env['virtualenv_path'] = os.path.join(env.install_path, env.virtualenv_name)\n env['repository_path'] = os.path.join(env.virtualenv_path, env.repository_name)\n \n env['database_manager'] = getattr(env, 'database_manager', DEFAULT_DATABASE_MANAGER)\n env['database_manager_name'] = DB_CHOICES[env.database_manager]\n env['database_username'] = getattr(env, 'database_username', DEFAULT_DATABASE_USERNAME)\n env['database_password'] = getattr(env, 'database_password', password_generator())\n env['database_host'] = getattr(env, 'database_host', DEFAULT_DATABASE_HOST)\n env['drop_database'] = getattr(env, 'drop_database', False)\n \n if not getattr(env, 'database_manager_admin_password', None):\n print('Must set the database_manager_admin_password entry in the fabric settings file (~/.fabricrc by default)')\n exit(1)\n \n env['database_name'] = getattr(env, 'database_name', DEFAULT_DATABASE_NAME)\n\n env['webserver'] = getattr(env, 'webserver', DEFAULT_WEBSERVER)\n env['webserver_name'] = WEB_CHOICES[env.webserver]\n\n env['django_database_driver'] = DJANGO_DB_DRIVERS[env.database_manager]\n\n\ndef print_supported_configs():\n print('Supported operating systems (os=): %s, default=\\'%s\\'' % (dict(OS_CHOICES).keys(), green(DEFAULT_OS)))\n print('Supported database managers (database_manager=): %s, default=\\'%s\\'' % (dict(DB_CHOICES).keys(), green(DEFAULT_DATABASE_MANAGER)))\n print('Supported webservers (webserver=): %s, default=\\'%s\\'' % (dict(WEB_CHOICES).keys(), green(DEFAULT_WEBSERVER)))\n print('\\n')"},"middle":{"kind":"string","value":" DEFAULT_DATABASE_MANAGER, DB_CHOICES, DEFAULT_DATABASE_NAME,\n DEFAULT_WEBSERVER, WEB_CHOICES, DEFAULT_DATABASE_USERNAME,\n DJANGO_DB_DRIVERS, DEFAULT_DATABASE_HOST, DEFAULT_PASSWORD_LENGTH)\nfrom server_config import reduce_env\n"},"fim_type":{"kind":"string","value":"random_line_split"}}},{"rowIdx":236076,"cells":{"file_name":{"kind":"string","value":"conf.py"},"prefix":{"kind":"string","value":"import os\nimport string\nimport random\n\nfrom fabric.api import env\nfrom fabric.colors import green\n\nfrom literals import (DEFAULT_INSTALL_PATH, DEFAULT_VIRTUALENV_NAME, \n DEFAULT_REPOSITORY_NAME, DEFAULT_OS, OS_CHOICES, \n DEFAULT_DATABASE_MANAGER, DB_CHOICES, DEFAULT_DATABASE_NAME,\n DEFAULT_WEBSERVER, WEB_CHOICES, DEFAULT_DATABASE_USERNAME,\n DJANGO_DB_DRIVERS, DEFAULT_DATABASE_HOST, DEFAULT_PASSWORD_LENGTH)\nfrom server_config import reduce_env\n\n\ndef "},"suffix":{"kind":"string","value":"():\n # http://snipplr.com/view/63223/python-password-generator/\n chars = string.ascii_letters + string.digits\n return ''.join(random.choice(chars) for x in range(DEFAULT_PASSWORD_LENGTH))\n\n\n@reduce_env\ndef setup_environment():\n env['os'] = getattr(env, 'os', DEFAULT_OS)\n env['os_name'] = OS_CHOICES[env.os]\n \n env['install_path'] = getattr(env, 'install_path', DEFAULT_INSTALL_PATH[env.os])\n env['virtualenv_name'] = getattr(env, 'virtualenv_name', DEFAULT_VIRTUALENV_NAME[env.os])\n env['repository_name'] = getattr(env, 'repository_name', DEFAULT_REPOSITORY_NAME[env.os])\n env['virtualenv_path'] = os.path.join(env.install_path, env.virtualenv_name)\n env['repository_path'] = os.path.join(env.virtualenv_path, env.repository_name)\n \n env['database_manager'] = getattr(env, 'database_manager', DEFAULT_DATABASE_MANAGER)\n env['database_manager_name'] = DB_CHOICES[env.database_manager]\n env['database_username'] = getattr(env, 'database_username', DEFAULT_DATABASE_USERNAME)\n env['database_password'] = getattr(env, 'database_password', password_generator())\n env['database_host'] = getattr(env, 'database_host', DEFAULT_DATABASE_HOST)\n env['drop_database'] = getattr(env, 'drop_database', False)\n \n if not getattr(env, 'database_manager_admin_password', None):\n print('Must set the database_manager_admin_password entry in the fabric settings file (~/.fabricrc by default)')\n exit(1)\n \n env['database_name'] = getattr(env, 'database_name', DEFAULT_DATABASE_NAME)\n\n env['webserver'] = getattr(env, 'webserver', DEFAULT_WEBSERVER)\n env['webserver_name'] = WEB_CHOICES[env.webserver]\n\n env['django_database_driver'] = DJANGO_DB_DRIVERS[env.database_manager]\n\n\ndef print_supported_configs():\n print('Supported operating systems (os=): %s, default=\\'%s\\'' % (dict(OS_CHOICES).keys(), green(DEFAULT_OS)))\n print('Supported database managers (database_manager=): %s, default=\\'%s\\'' % (dict(DB_CHOICES).keys(), green(DEFAULT_DATABASE_MANAGER)))\n print('Supported webservers (webserver=): %s, default=\\'%s\\'' % (dict(WEB_CHOICES).keys(), green(DEFAULT_WEBSERVER)))\n print('\\n')\n \n \n\n \n"},"middle":{"kind":"string","value":"password_generator"},"fim_type":{"kind":"string","value":"identifier_name"}}},{"rowIdx":236077,"cells":{"file_name":{"kind":"string","value":"conf.py"},"prefix":{"kind":"string","value":"import os\nimport string\nimport random\n\nfrom fabric.api import env\nfrom fabric.colors import green\n\nfrom literals import (DEFAULT_INSTALL_PATH, DEFAULT_VIRTUALENV_NAME, \n DEFAULT_REPOSITORY_NAME, DEFAULT_OS, OS_CHOICES, \n DEFAULT_DATABASE_MANAGER, DB_CHOICES, DEFAULT_DATABASE_NAME,\n DEFAULT_WEBSERVER, WEB_CHOICES, DEFAULT_DATABASE_USERNAME,\n DJANGO_DB_DRIVERS, DEFAULT_DATABASE_HOST, DEFAULT_PASSWORD_LENGTH)\nfrom server_config import reduce_env\n\n\ndef password_generator():\n # http://snipplr.com/view/63223/python-password-generator/\n chars = string.ascii_letters + string.digits\n return ''.join(random.choice(chars) for x in range(DEFAULT_PASSWORD_LENGTH))\n\n\n@reduce_env\ndef setup_environment():\n env['os'] = getattr(env, 'os', DEFAULT_OS)\n env['os_name'] = OS_CHOICES[env.os]\n \n env['install_path'] = getattr(env, 'install_path', DEFAULT_INSTALL_PATH[env.os])\n env['virtualenv_name'] = getattr(env, 'virtualenv_name', DEFAULT_VIRTUALENV_NAME[env.os])\n env['repository_name'] = getattr(env, 'repository_name', DEFAULT_REPOSITORY_NAME[env.os])\n env['virtualenv_path'] = os.path.join(env.install_path, env.virtualenv_name)\n env['repository_path'] = os.path.join(env.virtualenv_path, env.repository_name)\n \n env['database_manager'] = getattr(env, 'database_manager', DEFAULT_DATABASE_MANAGER)\n env['database_manager_name'] = DB_CHOICES[env.database_manager]\n env['database_username'] = getattr(env, 'database_username', DEFAULT_DATABASE_USERNAME)\n env['database_password'] = getattr(env, 'database_password', password_generator())\n env['database_host'] = getattr(env, 'database_host', DEFAULT_DATABASE_HOST)\n env['drop_database'] = getattr(env, 'drop_database', False)\n \n if not getattr(env, 'database_manager_admin_password', None):\n "},"suffix":{"kind":"string","value":"\n \n env['database_name'] = getattr(env, 'database_name', DEFAULT_DATABASE_NAME)\n\n env['webserver'] = getattr(env, 'webserver', DEFAULT_WEBSERVER)\n env['webserver_name'] = WEB_CHOICES[env.webserver]\n\n env['django_database_driver'] = DJANGO_DB_DRIVERS[env.database_manager]\n\n\ndef print_supported_configs():\n print('Supported operating systems (os=): %s, default=\\'%s\\'' % (dict(OS_CHOICES).keys(), green(DEFAULT_OS)))\n print('Supported database managers (database_manager=): %s, default=\\'%s\\'' % (dict(DB_CHOICES).keys(), green(DEFAULT_DATABASE_MANAGER)))\n print('Supported webservers (webserver=): %s, default=\\'%s\\'' % (dict(WEB_CHOICES).keys(), green(DEFAULT_WEBSERVER)))\n print('\\n')\n \n \n\n \n"},"middle":{"kind":"string","value":"print('Must set the database_manager_admin_password entry in the fabric settings file (~/.fabricrc by default)')\n exit(1)"},"fim_type":{"kind":"string","value":"conditional_block"}}},{"rowIdx":236078,"cells":{"file_name":{"kind":"string","value":"conf.py"},"prefix":{"kind":"string","value":"import os\nimport string\nimport random\n\nfrom fabric.api import env\nfrom fabric.colors import green\n\nfrom literals import (DEFAULT_INSTALL_PATH, DEFAULT_VIRTUALENV_NAME, \n DEFAULT_REPOSITORY_NAME, DEFAULT_OS, OS_CHOICES, \n DEFAULT_DATABASE_MANAGER, DB_CHOICES, DEFAULT_DATABASE_NAME,\n DEFAULT_WEBSERVER, WEB_CHOICES, DEFAULT_DATABASE_USERNAME,\n DJANGO_DB_DRIVERS, DEFAULT_DATABASE_HOST, DEFAULT_PASSWORD_LENGTH)\nfrom server_config import reduce_env\n\n\ndef password_generator():\n # http://snipplr.com/view/63223/python-password-generator/\n chars = string.ascii_letters + string.digits\n return ''.join(random.choice(chars) for x in range(DEFAULT_PASSWORD_LENGTH))\n\n\n@reduce_env\ndef setup_environment():\n env['os'] = getattr(env, 'os', DEFAULT_OS)\n env['os_name'] = OS_CHOICES[env.os]\n \n env['install_path'] = getattr(env, 'install_path', DEFAULT_INSTALL_PATH[env.os])\n env['virtualenv_name'] = getattr(env, 'virtualenv_name', DEFAULT_VIRTUALENV_NAME[env.os])\n env['repository_name'] = getattr(env, 'repository_name', DEFAULT_REPOSITORY_NAME[env.os])\n env['virtualenv_path'] = os.path.join(env.install_path, env.virtualenv_name)\n env['repository_path'] = os.path.join(env.virtualenv_path, env.repository_name)\n \n env['database_manager'] = getattr(env, 'database_manager', DEFAULT_DATABASE_MANAGER)\n env['database_manager_name'] = DB_CHOICES[env.database_manager]\n env['database_username'] = getattr(env, 'database_username', DEFAULT_DATABASE_USERNAME)\n env['database_password'] = getattr(env, 'database_password', password_generator())\n env['database_host'] = getattr(env, 'database_host', DEFAULT_DATABASE_HOST)\n env['drop_database'] = getattr(env, 'drop_database', False)\n \n if not getattr(env, 'database_manager_admin_password', None):\n print('Must set the database_manager_admin_password entry in the fabric settings file (~/.fabricrc by default)')\n exit(1)\n \n env['database_name'] = getattr(env, 'database_name', DEFAULT_DATABASE_NAME)\n\n env['webserver'] = getattr(env, 'webserver', DEFAULT_WEBSERVER)\n env['webserver_name'] = WEB_CHOICES[env.webserver]\n\n env['django_database_driver'] = DJANGO_DB_DRIVERS[env.database_manager]\n\n\ndef print_supported_configs():\n "},"suffix":{"kind":"string","value":"\n \n \n\n \n"},"middle":{"kind":"string","value":"print('Supported operating systems (os=): %s, default=\\'%s\\'' % (dict(OS_CHOICES).keys(), green(DEFAULT_OS)))\n print('Supported database managers (database_manager=): %s, default=\\'%s\\'' % (dict(DB_CHOICES).keys(), green(DEFAULT_DATABASE_MANAGER)))\n print('Supported webservers (webserver=): %s, default=\\'%s\\'' % (dict(WEB_CHOICES).keys(), green(DEFAULT_WEBSERVER)))\n print('\\n')"},"fim_type":{"kind":"string","value":"identifier_body"}}},{"rowIdx":236079,"cells":{"file_name":{"kind":"string","value":"htmlstyleelement.rs"},"prefix":{"kind":"string","value":"/* This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http://mozilla.org/MPL/2.0/. */\n\nuse cssparser::{Parser as CssParser, ParserInput};\nuse dom::bindings::cell::DomRefCell;\nuse dom::bindings::codegen::Bindings::HTMLStyleElementBinding;\nuse dom::bindings::codegen::Bindings::HTMLStyleElementBinding::HTMLStyleElementMethods;\nuse dom::bindings::codegen::Bindings::NodeBinding::NodeMethods;\nuse dom::bindings::inheritance::Castable;\nuse dom::bindings::root::{DomRoot, MutNullableDom};\nuse dom::cssstylesheet::CSSStyleSheet;\nuse dom::document::Document;\nuse dom::element::{Element, ElementCreator};\nuse dom::eventtarget::EventTarget;\nuse dom::htmlelement::HTMLElement;\nuse dom::node::{ChildrenMutation, Node, UnbindContext, document_from_node, window_from_node};\nuse dom::stylesheet::StyleSheet as DOMStyleSheet;\nuse dom::virtualmethods::VirtualMethods;\nuse dom_struct::dom_struct;\nuse html5ever::{LocalName, Prefix};\nuse net_traits::ReferrerPolicy;\nuse servo_arc::Arc;\nuse std::cell::Cell;\nuse style::media_queries::parse_media_query_list;\nuse style::parser::ParserContext as CssParserContext;\nuse style::stylesheets::{CssRuleType, Stylesheet, Origin};\nuse style_traits::PARSING_MODE_DEFAULT;\nuse stylesheet_loader::{StylesheetLoader, StylesheetOwner};\n\n#[dom_struct]\npub struct HTMLStyleElement {\n htmlelement: HTMLElement,\n #[ignore_heap_size_of = \"Arc\"]\n stylesheet: DomRefCell>>,\n cssom_stylesheet: MutNullableDom,\n /// https://html.spec.whatwg.org/multipage/#a-style-sheet-that-is-blocking-scripts\n parser_inserted: Cell,\n in_stack_of_open_elements: Cell,\n pending_loads: Cell,"},"suffix":{"kind":"string","value":"\nimpl HTMLStyleElement {\n fn new_inherited(local_name: LocalName,\n prefix: Option,\n document: &Document,\n creator: ElementCreator) -> HTMLStyleElement {\n HTMLStyleElement {\n htmlelement: HTMLElement::new_inherited(local_name, prefix, document),\n stylesheet: DomRefCell::new(None),\n cssom_stylesheet: MutNullableDom::new(None),\n parser_inserted: Cell::new(creator.is_parser_created()),\n in_stack_of_open_elements: Cell::new(creator.is_parser_created()),\n pending_loads: Cell::new(0),\n any_failed_load: Cell::new(false),\n line_number: creator.return_line_number(),\n }\n }\n\n #[allow(unrooted_must_root)]\n pub fn new(local_name: LocalName,\n prefix: Option,\n document: &Document,\n creator: ElementCreator) -> DomRoot {\n Node::reflect_node(box HTMLStyleElement::new_inherited(local_name, prefix, document, creator),\n document,\n HTMLStyleElementBinding::Wrap)\n }\n\n pub fn parse_own_css(&self) {\n let node = self.upcast::();\n let element = self.upcast::();\n assert!(node.is_in_doc());\n\n let window = window_from_node(node);\n let doc = document_from_node(self);\n\n let mq_attribute = element.get_attribute(&ns!(), &local_name!(\"media\"));\n let mq_str = match mq_attribute {\n Some(a) => String::from(&**a.value()),\n None => String::new(),\n };\n\n let data = node.GetTextContent().expect(\"Element.textContent must be a string\");\n let url = window.get_url();\n let context = CssParserContext::new_for_cssom(&url,\n Some(CssRuleType::Media),\n PARSING_MODE_DEFAULT,\n doc.quirks_mode());\n let shared_lock = node.owner_doc().style_shared_lock().clone();\n let mut input = ParserInput::new(&mq_str);\n let css_error_reporter = window.css_error_reporter();\n let mq = Arc::new(shared_lock.wrap(parse_media_query_list(&context,\n &mut CssParser::new(&mut input),\n css_error_reporter)));\n let loader = StylesheetLoader::for_element(self.upcast());\n let sheet = Stylesheet::from_str(&data, window.get_url(),\n Origin::Author, mq,\n shared_lock, Some(&loader),\n css_error_reporter,\n doc.quirks_mode(),\n self.line_number as u32);\n\n let sheet = Arc::new(sheet);\n\n // No subresource loads were triggered, just fire the load event now.\n if self.pending_loads.get() == 0 {\n self.upcast::().fire_event(atom!(\"load\"));\n }\n\n self.set_stylesheet(sheet);\n }\n\n // FIXME(emilio): This is duplicated with HTMLLinkElement::set_stylesheet.\n pub fn set_stylesheet(&self, s: Arc) {\n let doc = document_from_node(self);\n if let Some(ref s) = *self.stylesheet.borrow() {\n doc.remove_stylesheet(self.upcast(), s)\n }\n *self.stylesheet.borrow_mut() = Some(s.clone());\n self.cssom_stylesheet.set(None);\n doc.add_stylesheet(self.upcast(), s);\n }\n\n pub fn get_stylesheet(&self) -> Option> {\n self.stylesheet.borrow().clone()\n }\n\n pub fn get_cssom_stylesheet(&self) -> Option> {\n self.get_stylesheet().map(|sheet| {\n self.cssom_stylesheet.or_init(|| {\n CSSStyleSheet::new(&window_from_node(self),\n self.upcast::(),\n \"text/css\".into(),\n None, // todo handle location\n None, // todo handle title\n sheet)\n })\n })\n }\n}\n\nimpl VirtualMethods for HTMLStyleElement {\n fn super_type(&self) -> Option<&VirtualMethods> {\n Some(self.upcast::() as &VirtualMethods)\n }\n\n fn children_changed(&self, mutation: &ChildrenMutation) {\n self.super_type().unwrap().children_changed(mutation);\n\n // https://html.spec.whatwg.org/multipage/#update-a-style-block\n // Handles the case when:\n // \"The element is not on the stack of open elements of an HTML parser or XML parser,\n // and one of its child nodes is modified by a script.\"\n // TODO: Handle Text child contents being mutated.\n if self.upcast::().is_in_doc() && !self.in_stack_of_open_elements.get() {\n self.parse_own_css();\n }\n }\n\n fn bind_to_tree(&self, tree_in_doc: bool) {\n self.super_type().unwrap().bind_to_tree(tree_in_doc);\n\n // https://html.spec.whatwg.org/multipage/#update-a-style-block\n // Handles the case when:\n // \"The element is not on the stack of open elements of an HTML parser or XML parser,\n // and it becomes connected or disconnected.\"\n if tree_in_doc && !self.in_stack_of_open_elements.get() {\n self.parse_own_css();\n }\n }\n\n fn pop(&self) {\n self.super_type().unwrap().pop();\n\n // https://html.spec.whatwg.org/multipage/#update-a-style-block\n // Handles the case when:\n // \"The element is popped off the stack of open elements of an HTML parser or XML parser.\"\n self.in_stack_of_open_elements.set(false);\n if self.upcast::().is_in_doc() {\n self.parse_own_css();\n }\n }\n\n fn unbind_from_tree(&self, context: &UnbindContext) {\n if let Some(ref s) = self.super_type() {\n s.unbind_from_tree(context);\n }\n\n if context.tree_in_doc {\n if let Some(s) = self.stylesheet.borrow_mut().take() {\n document_from_node(self).remove_stylesheet(self.upcast(), &s)\n }\n }\n }\n}\n\nimpl StylesheetOwner for HTMLStyleElement {\n fn increment_pending_loads_count(&self) {\n self.pending_loads.set(self.pending_loads.get() + 1)\n }\n\n fn load_finished(&self, succeeded: bool) -> Option {\n assert!(self.pending_loads.get() > 0, \"What finished?\");\n if !succeeded {\n self.any_failed_load.set(true);\n }\n\n self.pending_loads.set(self.pending_loads.get() - 1);\n if self.pending_loads.get() != 0 {\n return None;\n }\n\n let any_failed = self.any_failed_load.get();\n self.any_failed_load.set(false);\n Some(any_failed)\n }\n\n fn parser_inserted(&self) -> bool {\n self.parser_inserted.get()\n }\n\n fn referrer_policy(&self) -> Option {\n None\n }\n\n fn set_origin_clean(&self, origin_clean: bool) {\n if let Some(stylesheet) = self.get_cssom_stylesheet() {\n stylesheet.set_origin_clean(origin_clean);\n }\n }\n}\n\n\nimpl HTMLStyleElementMethods for HTMLStyleElement {\n // https://drafts.csswg.org/cssom/#dom-linkstyle-sheet\n fn GetSheet(&self) -> Option> {\n self.get_cssom_stylesheet().map(DomRoot::upcast)\n }\n}"},"middle":{"kind":"string","value":" any_failed_load: Cell,\n line_number: u64,\n}"},"fim_type":{"kind":"string","value":"random_line_split"}}},{"rowIdx":236080,"cells":{"file_name":{"kind":"string","value":"htmlstyleelement.rs"},"prefix":{"kind":"string","value":"/* This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http://mozilla.org/MPL/2.0/. */\n\nuse cssparser::{Parser as CssParser, ParserInput};\nuse dom::bindings::cell::DomRefCell;\nuse dom::bindings::codegen::Bindings::HTMLStyleElementBinding;\nuse dom::bindings::codegen::Bindings::HTMLStyleElementBinding::HTMLStyleElementMethods;\nuse dom::bindings::codegen::Bindings::NodeBinding::NodeMethods;\nuse dom::bindings::inheritance::Castable;\nuse dom::bindings::root::{DomRoot, MutNullableDom};\nuse dom::cssstylesheet::CSSStyleSheet;\nuse dom::document::Document;\nuse dom::element::{Element, ElementCreator};\nuse dom::eventtarget::EventTarget;\nuse dom::htmlelement::HTMLElement;\nuse dom::node::{ChildrenMutation, Node, UnbindContext, document_from_node, window_from_node};\nuse dom::stylesheet::StyleSheet as DOMStyleSheet;\nuse dom::virtualmethods::VirtualMethods;\nuse dom_struct::dom_struct;\nuse html5ever::{LocalName, Prefix};\nuse net_traits::ReferrerPolicy;\nuse servo_arc::Arc;\nuse std::cell::Cell;\nuse style::media_queries::parse_media_query_list;\nuse style::parser::ParserContext as CssParserContext;\nuse style::stylesheets::{CssRuleType, Stylesheet, Origin};\nuse style_traits::PARSING_MODE_DEFAULT;\nuse stylesheet_loader::{StylesheetLoader, StylesheetOwner};\n\n#[dom_struct]\npub struct HTMLStyleElement {\n htmlelement: HTMLElement,\n #[ignore_heap_size_of = \"Arc\"]\n stylesheet: DomRefCell>>,\n cssom_stylesheet: MutNullableDom,\n /// https://html.spec.whatwg.org/multipage/#a-style-sheet-that-is-blocking-scripts\n parser_inserted: Cell,\n in_stack_of_open_elements: Cell,\n pending_loads: Cell,\n any_failed_load: Cell,\n line_number: u64,\n}\n\nimpl HTMLStyleElement {\n fn new_inherited(local_name: LocalName,\n prefix: Option,\n document: &Document,\n creator: ElementCreator) -> HTMLStyleElement {\n HTMLStyleElement {\n htmlelement: HTMLElement::new_inherited(local_name, prefix, document),\n stylesheet: DomRefCell::new(None),\n cssom_stylesheet: MutNullableDom::new(None),\n parser_inserted: Cell::new(creator.is_parser_created()),\n in_stack_of_open_elements: Cell::new(creator.is_parser_created()),\n pending_loads: Cell::new(0),\n any_failed_load: Cell::new(false),\n line_number: creator.return_line_number(),\n }\n }\n\n #[allow(unrooted_must_root)]\n pub fn new(local_name: LocalName,\n prefix: Option,\n document: &Document,\n creator: ElementCreator) -> DomRoot {\n Node::reflect_node(box HTMLStyleElement::new_inherited(local_name, prefix, document, creator),\n document,\n HTMLStyleElementBinding::Wrap)\n }\n\n pub fn parse_own_css(&self) {\n let node = self.upcast::();\n let element = self.upcast::();\n assert!(node.is_in_doc());\n\n let window = window_from_node(node);\n let doc = document_from_node(self);\n\n let mq_attribute = element.get_attribute(&ns!(), &local_name!(\"media\"));\n let mq_str = match mq_attribute {\n Some(a) => String::from(&**a.value()),\n None => String::new(),\n };\n\n let data = node.GetTextContent().expect(\"Element.textContent must be a string\");\n let url = window.get_url();\n let context = CssParserContext::new_for_cssom(&url,\n Some(CssRuleType::Media),\n PARSING_MODE_DEFAULT,\n doc.quirks_mode());\n let shared_lock = node.owner_doc().style_shared_lock().clone();\n let mut input = ParserInput::new(&mq_str);\n let css_error_reporter = window.css_error_reporter();\n let mq = Arc::new(shared_lock.wrap(parse_media_query_list(&context,\n &mut CssParser::new(&mut input),\n css_error_reporter)));\n let loader = StylesheetLoader::for_element(self.upcast());\n let sheet = Stylesheet::from_str(&data, window.get_url(),\n Origin::Author, mq,\n shared_lock, Some(&loader),\n css_error_reporter,\n doc.quirks_mode(),\n self.line_number as u32);\n\n let sheet = Arc::new(sheet);\n\n // No subresource loads were triggered, just fire the load event now.\n if self.pending_loads.get() == 0 {\n self.upcast::().fire_event(atom!(\"load\"));\n }\n\n self.set_stylesheet(sheet);\n }\n\n // FIXME(emilio): This is duplicated with HTMLLinkElement::set_stylesheet.\n pub fn set_stylesheet(&self, s: Arc) {\n let doc = document_from_node(self);\n if let Some(ref s) = *self.stylesheet.borrow() {\n doc.remove_stylesheet(self.upcast(), s)\n }\n *self.stylesheet.borrow_mut() = Some(s.clone());\n self.cssom_stylesheet.set(None);\n doc.add_stylesheet(self.upcast(), s);\n }\n\n pub fn get_stylesheet(&self) -> Option> {\n self.stylesheet.borrow().clone()\n }\n\n pub fn get_cssom_stylesheet(&self) -> Option> {\n self.get_stylesheet().map(|sheet| {\n self.cssom_stylesheet.or_init(|| {\n CSSStyleSheet::new(&window_from_node(self),\n self.upcast::(),\n \"text/css\".into(),\n None, // todo handle location\n None, // todo handle title\n sheet)\n })\n })\n }\n}\n\nimpl VirtualMethods for HTMLStyleElement {\n fn super_type(&self) -> Option<&VirtualMethods> {\n Some(self.upcast::() as &VirtualMethods)\n }\n\n fn children_changed(&self, mutation: &ChildrenMutation) {\n self.super_type().unwrap().children_changed(mutation);\n\n // https://html.spec.whatwg.org/multipage/#update-a-style-block\n // Handles the case when:\n // \"The element is not on the stack of open elements of an HTML parser or XML parser,\n // and one of its child nodes is modified by a script.\"\n // TODO: Handle Text child contents being mutated.\n if self.upcast::().is_in_doc() && !self.in_stack_of_open_elements.get() {\n self.parse_own_css();\n }\n }\n\n fn bind_to_tree(&self, tree_in_doc: bool) {\n self.super_type().unwrap().bind_to_tree(tree_in_doc);\n\n // https://html.spec.whatwg.org/multipage/#update-a-style-block\n // Handles the case when:\n // \"The element is not on the stack of open elements of an HTML parser or XML parser,\n // and it becomes connected or disconnected.\"\n if tree_in_doc && !self.in_stack_of_open_elements.get() {\n self.parse_own_css();\n }\n }\n\n fn pop(&self) {\n self.super_type().unwrap().pop();\n\n // https://html.spec.whatwg.org/multipage/#update-a-style-block\n // Handles the case when:\n // \"The element is popped off the stack of open elements of an HTML parser or XML parser.\"\n self.in_stack_of_open_elements.set(false);\n if self.upcast::().is_in_doc() {\n self.parse_own_css();\n }\n }\n\n fn unbind_from_tree(&self, context: &UnbindContext) {\n if let Some(ref s) = self.super_type() {\n s.unbind_from_tree(context);\n }\n\n if context.tree_in_doc {\n if let Some(s) = self.stylesheet.borrow_mut().take() {\n document_from_node(self).remove_stylesheet(self.upcast(), &s)\n }\n }\n }\n}\n\nimpl StylesheetOwner for HTMLStyleElement {\n fn increment_pending_loads_count(&self) {\n self.pending_loads.set(self.pending_loads.get() + 1)\n }\n\n fn "},"suffix":{"kind":"string","value":"(&self, succeeded: bool) -> Option {\n assert!(self.pending_loads.get() > 0, \"What finished?\");\n if !succeeded {\n self.any_failed_load.set(true);\n }\n\n self.pending_loads.set(self.pending_loads.get() - 1);\n if self.pending_loads.get() != 0 {\n return None;\n }\n\n let any_failed = self.any_failed_load.get();\n self.any_failed_load.set(false);\n Some(any_failed)\n }\n\n fn parser_inserted(&self) -> bool {\n self.parser_inserted.get()\n }\n\n fn referrer_policy(&self) -> Option {\n None\n }\n\n fn set_origin_clean(&self, origin_clean: bool) {\n if let Some(stylesheet) = self.get_cssom_stylesheet() {\n stylesheet.set_origin_clean(origin_clean);\n }\n }\n}\n\n\nimpl HTMLStyleElementMethods for HTMLStyleElement {\n // https://drafts.csswg.org/cssom/#dom-linkstyle-sheet\n fn GetSheet(&self) -> Option> {\n self.get_cssom_stylesheet().map(DomRoot::upcast)\n }\n}\n"},"middle":{"kind":"string","value":"load_finished"},"fim_type":{"kind":"string","value":"identifier_name"}}},{"rowIdx":236081,"cells":{"file_name":{"kind":"string","value":"htmlstyleelement.rs"},"prefix":{"kind":"string","value":"/* This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http://mozilla.org/MPL/2.0/. */\n\nuse cssparser::{Parser as CssParser, ParserInput};\nuse dom::bindings::cell::DomRefCell;\nuse dom::bindings::codegen::Bindings::HTMLStyleElementBinding;\nuse dom::bindings::codegen::Bindings::HTMLStyleElementBinding::HTMLStyleElementMethods;\nuse dom::bindings::codegen::Bindings::NodeBinding::NodeMethods;\nuse dom::bindings::inheritance::Castable;\nuse dom::bindings::root::{DomRoot, MutNullableDom};\nuse dom::cssstylesheet::CSSStyleSheet;\nuse dom::document::Document;\nuse dom::element::{Element, ElementCreator};\nuse dom::eventtarget::EventTarget;\nuse dom::htmlelement::HTMLElement;\nuse dom::node::{ChildrenMutation, Node, UnbindContext, document_from_node, window_from_node};\nuse dom::stylesheet::StyleSheet as DOMStyleSheet;\nuse dom::virtualmethods::VirtualMethods;\nuse dom_struct::dom_struct;\nuse html5ever::{LocalName, Prefix};\nuse net_traits::ReferrerPolicy;\nuse servo_arc::Arc;\nuse std::cell::Cell;\nuse style::media_queries::parse_media_query_list;\nuse style::parser::ParserContext as CssParserContext;\nuse style::stylesheets::{CssRuleType, Stylesheet, Origin};\nuse style_traits::PARSING_MODE_DEFAULT;\nuse stylesheet_loader::{StylesheetLoader, StylesheetOwner};\n\n#[dom_struct]\npub struct HTMLStyleElement {\n htmlelement: HTMLElement,\n #[ignore_heap_size_of = \"Arc\"]\n stylesheet: DomRefCell>>,\n cssom_stylesheet: MutNullableDom,\n /// https://html.spec.whatwg.org/multipage/#a-style-sheet-that-is-blocking-scripts\n parser_inserted: Cell,\n in_stack_of_open_elements: Cell,\n pending_loads: Cell,\n any_failed_load: Cell,\n line_number: u64,\n}\n\nimpl HTMLStyleElement {\n fn new_inherited(local_name: LocalName,\n prefix: Option,\n document: &Document,\n creator: ElementCreator) -> HTMLStyleElement {\n HTMLStyleElement {\n htmlelement: HTMLElement::new_inherited(local_name, prefix, document),\n stylesheet: DomRefCell::new(None),\n cssom_stylesheet: MutNullableDom::new(None),\n parser_inserted: Cell::new(creator.is_parser_created()),\n in_stack_of_open_elements: Cell::new(creator.is_parser_created()),\n pending_loads: Cell::new(0),\n any_failed_load: Cell::new(false),\n line_number: creator.return_line_number(),\n }\n }\n\n #[allow(unrooted_must_root)]\n pub fn new(local_name: LocalName,\n prefix: Option,\n document: &Document,\n creator: ElementCreator) -> DomRoot {\n Node::reflect_node(box HTMLStyleElement::new_inherited(local_name, prefix, document, creator),\n document,\n HTMLStyleElementBinding::Wrap)\n }\n\n pub fn parse_own_css(&self) {\n let node = self.upcast::();\n let element = self.upcast::();\n assert!(node.is_in_doc());\n\n let window = window_from_node(node);\n let doc = document_from_node(self);\n\n let mq_attribute = element.get_attribute(&ns!(), &local_name!(\"media\"));\n let mq_str = match mq_attribute {\n Some(a) => String::from(&**a.value()),\n None => String::new(),\n };\n\n let data = node.GetTextContent().expect(\"Element.textContent must be a string\");\n let url = window.get_url();\n let context = CssParserContext::new_for_cssom(&url,\n Some(CssRuleType::Media),\n PARSING_MODE_DEFAULT,\n doc.quirks_mode());\n let shared_lock = node.owner_doc().style_shared_lock().clone();\n let mut input = ParserInput::new(&mq_str);\n let css_error_reporter = window.css_error_reporter();\n let mq = Arc::new(shared_lock.wrap(parse_media_query_list(&context,\n &mut CssParser::new(&mut input),\n css_error_reporter)));\n let loader = StylesheetLoader::for_element(self.upcast());\n let sheet = Stylesheet::from_str(&data, window.get_url(),\n Origin::Author, mq,\n shared_lock, Some(&loader),\n css_error_reporter,\n doc.quirks_mode(),\n self.line_number as u32);\n\n let sheet = Arc::new(sheet);\n\n // No subresource loads were triggered, just fire the load event now.\n if self.pending_loads.get() == 0 {\n self.upcast::().fire_event(atom!(\"load\"));\n }\n\n self.set_stylesheet(sheet);\n }\n\n // FIXME(emilio): This is duplicated with HTMLLinkElement::set_stylesheet.\n pub fn set_stylesheet(&self, s: Arc) {\n let doc = document_from_node(self);\n if let Some(ref s) = *self.stylesheet.borrow() {\n doc.remove_stylesheet(self.upcast(), s)\n }\n *self.stylesheet.borrow_mut() = Some(s.clone());\n self.cssom_stylesheet.set(None);\n doc.add_stylesheet(self.upcast(), s);\n }\n\n pub fn get_stylesheet(&self) -> Option> {\n self.stylesheet.borrow().clone()\n }\n\n pub fn get_cssom_stylesheet(&self) -> Option> {\n self.get_stylesheet().map(|sheet| {\n self.cssom_stylesheet.or_init(|| {\n CSSStyleSheet::new(&window_from_node(self),\n self.upcast::(),\n \"text/css\".into(),\n None, // todo handle location\n None, // todo handle title\n sheet)\n })\n })\n }\n}\n\nimpl VirtualMethods for HTMLStyleElement {\n fn super_type(&self) -> Option<&VirtualMethods> {\n Some(self.upcast::() as &VirtualMethods)\n }\n\n fn children_changed(&self, mutation: &ChildrenMutation) {\n self.super_type().unwrap().children_changed(mutation);\n\n // https://html.spec.whatwg.org/multipage/#update-a-style-block\n // Handles the case when:\n // \"The element is not on the stack of open elements of an HTML parser or XML parser,\n // and one of its child nodes is modified by a script.\"\n // TODO: Handle Text child contents being mutated.\n if self.upcast::().is_in_doc() && !self.in_stack_of_open_elements.get() {\n self.parse_own_css();\n }\n }\n\n fn bind_to_tree(&self, tree_in_doc: bool) {\n self.super_type().unwrap().bind_to_tree(tree_in_doc);\n\n // https://html.spec.whatwg.org/multipage/#update-a-style-block\n // Handles the case when:\n // \"The element is not on the stack of open elements of an HTML parser or XML parser,\n // and it becomes connected or disconnected.\"\n if tree_in_doc && !self.in_stack_of_open_elements.get() {\n self.parse_own_css();\n }\n }\n\n fn pop(&self) {\n self.super_type().unwrap().pop();\n\n // https://html.spec.whatwg.org/multipage/#update-a-style-block\n // Handles the case when:\n // \"The element is popped off the stack of open elements of an HTML parser or XML parser.\"\n self.in_stack_of_open_elements.set(false);\n if self.upcast::().is_in_doc() {\n self.parse_own_css();\n }\n }\n\n fn unbind_from_tree(&self, context: &UnbindContext) {\n if let Some(ref s) = self.super_type() {\n s.unbind_from_tree(context);\n }\n\n if context.tree_in_doc {\n if let Some(s) = self.stylesheet.borrow_mut().take() {\n document_from_node(self).remove_stylesheet(self.upcast(), &s)\n }\n }\n }\n}\n\nimpl StylesheetOwner for HTMLStyleElement {\n fn increment_pending_loads_count(&self) {\n self.pending_loads.set(self.pending_loads.get() + 1)\n }\n\n fn load_finished(&self, succeeded: bool) -> Option {\n assert!(self.pending_loads.get() > 0, \"What finished?\");\n if !succeeded {\n self.any_failed_load.set(true);\n }\n\n self.pending_loads.set(self.pending_loads.get() - 1);\n if self.pending_loads.get() != 0 {\n return None;\n }\n\n let any_failed = self.any_failed_load.get();\n self.any_failed_load.set(false);\n Some(any_failed)\n }\n\n fn parser_inserted(&self) -> bool {\n self.parser_inserted.get()\n }\n\n fn referrer_policy(&self) -> Option {\n None\n }\n\n fn set_origin_clean(&self, origin_clean: bool) {\n if let Some(stylesheet) = self.get_cssom_stylesheet() {\n stylesheet.set_origin_clean(origin_clean);\n }\n }\n}\n\n\nimpl HTMLStyleElementMethods for HTMLStyleElement {\n // https://drafts.csswg.org/cssom/#dom-linkstyle-sheet\n fn GetSheet(&self) -> Option> "},"suffix":{"kind":"string","value":"\n}\n"},"middle":{"kind":"string","value":"{\n self.get_cssom_stylesheet().map(DomRoot::upcast)\n }"},"fim_type":{"kind":"string","value":"identifier_body"}}},{"rowIdx":236082,"cells":{"file_name":{"kind":"string","value":"htmlstyleelement.rs"},"prefix":{"kind":"string","value":"/* This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http://mozilla.org/MPL/2.0/. */\n\nuse cssparser::{Parser as CssParser, ParserInput};\nuse dom::bindings::cell::DomRefCell;\nuse dom::bindings::codegen::Bindings::HTMLStyleElementBinding;\nuse dom::bindings::codegen::Bindings::HTMLStyleElementBinding::HTMLStyleElementMethods;\nuse dom::bindings::codegen::Bindings::NodeBinding::NodeMethods;\nuse dom::bindings::inheritance::Castable;\nuse dom::bindings::root::{DomRoot, MutNullableDom};\nuse dom::cssstylesheet::CSSStyleSheet;\nuse dom::document::Document;\nuse dom::element::{Element, ElementCreator};\nuse dom::eventtarget::EventTarget;\nuse dom::htmlelement::HTMLElement;\nuse dom::node::{ChildrenMutation, Node, UnbindContext, document_from_node, window_from_node};\nuse dom::stylesheet::StyleSheet as DOMStyleSheet;\nuse dom::virtualmethods::VirtualMethods;\nuse dom_struct::dom_struct;\nuse html5ever::{LocalName, Prefix};\nuse net_traits::ReferrerPolicy;\nuse servo_arc::Arc;\nuse std::cell::Cell;\nuse style::media_queries::parse_media_query_list;\nuse style::parser::ParserContext as CssParserContext;\nuse style::stylesheets::{CssRuleType, Stylesheet, Origin};\nuse style_traits::PARSING_MODE_DEFAULT;\nuse stylesheet_loader::{StylesheetLoader, StylesheetOwner};\n\n#[dom_struct]\npub struct HTMLStyleElement {\n htmlelement: HTMLElement,\n #[ignore_heap_size_of = \"Arc\"]\n stylesheet: DomRefCell>>,\n cssom_stylesheet: MutNullableDom,\n /// https://html.spec.whatwg.org/multipage/#a-style-sheet-that-is-blocking-scripts\n parser_inserted: Cell,\n in_stack_of_open_elements: Cell,\n pending_loads: Cell,\n any_failed_load: Cell,\n line_number: u64,\n}\n\nimpl HTMLStyleElement {\n fn new_inherited(local_name: LocalName,\n prefix: Option,\n document: &Document,\n creator: ElementCreator) -> HTMLStyleElement {\n HTMLStyleElement {\n htmlelement: HTMLElement::new_inherited(local_name, prefix, document),\n stylesheet: DomRefCell::new(None),\n cssom_stylesheet: MutNullableDom::new(None),\n parser_inserted: Cell::new(creator.is_parser_created()),\n in_stack_of_open_elements: Cell::new(creator.is_parser_created()),\n pending_loads: Cell::new(0),\n any_failed_load: Cell::new(false),\n line_number: creator.return_line_number(),\n }\n }\n\n #[allow(unrooted_must_root)]\n pub fn new(local_name: LocalName,\n prefix: Option,\n document: &Document,\n creator: ElementCreator) -> DomRoot {\n Node::reflect_node(box HTMLStyleElement::new_inherited(local_name, prefix, document, creator),\n document,\n HTMLStyleElementBinding::Wrap)\n }\n\n pub fn parse_own_css(&self) {\n let node = self.upcast::();\n let element = self.upcast::();\n assert!(node.is_in_doc());\n\n let window = window_from_node(node);\n let doc = document_from_node(self);\n\n let mq_attribute = element.get_attribute(&ns!(), &local_name!(\"media\"));\n let mq_str = match mq_attribute {\n Some(a) => String::from(&**a.value()),\n None => String::new(),\n };\n\n let data = node.GetTextContent().expect(\"Element.textContent must be a string\");\n let url = window.get_url();\n let context = CssParserContext::new_for_cssom(&url,\n Some(CssRuleType::Media),\n PARSING_MODE_DEFAULT,\n doc.quirks_mode());\n let shared_lock = node.owner_doc().style_shared_lock().clone();\n let mut input = ParserInput::new(&mq_str);\n let css_error_reporter = window.css_error_reporter();\n let mq = Arc::new(shared_lock.wrap(parse_media_query_list(&context,\n &mut CssParser::new(&mut input),\n css_error_reporter)));\n let loader = StylesheetLoader::for_element(self.upcast());\n let sheet = Stylesheet::from_str(&data, window.get_url(),\n Origin::Author, mq,\n shared_lock, Some(&loader),\n css_error_reporter,\n doc.quirks_mode(),\n self.line_number as u32);\n\n let sheet = Arc::new(sheet);\n\n // No subresource loads were triggered, just fire the load event now.\n if self.pending_loads.get() == 0 {\n self.upcast::().fire_event(atom!(\"load\"));\n }\n\n self.set_stylesheet(sheet);\n }\n\n // FIXME(emilio): This is duplicated with HTMLLinkElement::set_stylesheet.\n pub fn set_stylesheet(&self, s: Arc) {\n let doc = document_from_node(self);\n if let Some(ref s) = *self.stylesheet.borrow() {\n doc.remove_stylesheet(self.upcast(), s)\n }\n *self.stylesheet.borrow_mut() = Some(s.clone());\n self.cssom_stylesheet.set(None);\n doc.add_stylesheet(self.upcast(), s);\n }\n\n pub fn get_stylesheet(&self) -> Option> {\n self.stylesheet.borrow().clone()\n }\n\n pub fn get_cssom_stylesheet(&self) -> Option> {\n self.get_stylesheet().map(|sheet| {\n self.cssom_stylesheet.or_init(|| {\n CSSStyleSheet::new(&window_from_node(self),\n self.upcast::(),\n \"text/css\".into(),\n None, // todo handle location\n None, // todo handle title\n sheet)\n })\n })\n }\n}\n\nimpl VirtualMethods for HTMLStyleElement {\n fn super_type(&self) -> Option<&VirtualMethods> {\n Some(self.upcast::() as &VirtualMethods)\n }\n\n fn children_changed(&self, mutation: &ChildrenMutation) {\n self.super_type().unwrap().children_changed(mutation);\n\n // https://html.spec.whatwg.org/multipage/#update-a-style-block\n // Handles the case when:\n // \"The element is not on the stack of open elements of an HTML parser or XML parser,\n // and one of its child nodes is modified by a script.\"\n // TODO: Handle Text child contents being mutated.\n if self.upcast::().is_in_doc() && !self.in_stack_of_open_elements.get() {\n self.parse_own_css();\n }\n }\n\n fn bind_to_tree(&self, tree_in_doc: bool) {\n self.super_type().unwrap().bind_to_tree(tree_in_doc);\n\n // https://html.spec.whatwg.org/multipage/#update-a-style-block\n // Handles the case when:\n // \"The element is not on the stack of open elements of an HTML parser or XML parser,\n // and it becomes connected or disconnected.\"\n if tree_in_doc && !self.in_stack_of_open_elements.get() {\n self.parse_own_css();\n }\n }\n\n fn pop(&self) {\n self.super_type().unwrap().pop();\n\n // https://html.spec.whatwg.org/multipage/#update-a-style-block\n // Handles the case when:\n // \"The element is popped off the stack of open elements of an HTML parser or XML parser.\"\n self.in_stack_of_open_elements.set(false);\n if self.upcast::().is_in_doc() {\n self.parse_own_css();\n }\n }\n\n fn unbind_from_tree(&self, context: &UnbindContext) {\n if let Some(ref s) = self.super_type() {\n s.unbind_from_tree(context);\n }\n\n if context.tree_in_doc {\n if let Some(s) = self.stylesheet.borrow_mut().take() {\n document_from_node(self).remove_stylesheet(self.upcast(), &s)\n }\n }\n }\n}\n\nimpl StylesheetOwner for HTMLStyleElement {\n fn increment_pending_loads_count(&self) {\n self.pending_loads.set(self.pending_loads.get() + 1)\n }\n\n fn load_finished(&self, succeeded: bool) -> Option {\n assert!(self.pending_loads.get() > 0, \"What finished?\");\n if !succeeded "},"suffix":{"kind":"string","value":"\n\n self.pending_loads.set(self.pending_loads.get() - 1);\n if self.pending_loads.get() != 0 {\n return None;\n }\n\n let any_failed = self.any_failed_load.get();\n self.any_failed_load.set(false);\n Some(any_failed)\n }\n\n fn parser_inserted(&self) -> bool {\n self.parser_inserted.get()\n }\n\n fn referrer_policy(&self) -> Option {\n None\n }\n\n fn set_origin_clean(&self, origin_clean: bool) {\n if let Some(stylesheet) = self.get_cssom_stylesheet() {\n stylesheet.set_origin_clean(origin_clean);\n }\n }\n}\n\n\nimpl HTMLStyleElementMethods for HTMLStyleElement {\n // https://drafts.csswg.org/cssom/#dom-linkstyle-sheet\n fn GetSheet(&self) -> Option> {\n self.get_cssom_stylesheet().map(DomRoot::upcast)\n }\n}\n"},"middle":{"kind":"string","value":"{\n self.any_failed_load.set(true);\n }"},"fim_type":{"kind":"string","value":"conditional_block"}}},{"rowIdx":236083,"cells":{"file_name":{"kind":"string","value":"entity-schema-target.ts"},"prefix":{"kind":"string","value":"import \"reflect-metadata\";\nimport {closeTestingConnections, createTestingConnections, reloadTestingDatabases} from \"../../../utils/test-utils\";\nimport {Connection} from \"../../../../src\";\nimport {PostEntity} from \"./entity/PostEntity\";\nimport {Post} from \"./model/Post\";\n\ndescribe(\"entity schemas > target option\", () => {\n\n let connections: Connection[];\n before(async () => connections = await createTestingConnections({\n entities: [PostEntity],\n }));\n beforeEach(() => reloadTestingDatabases(connections));\n after(() => closeTestingConnections(connections));\n\n it(\"should create instance of the target\", () => Promise.all(connections.map(async connection => {\n const postRepository = connection.getRepository(Post);\n const post = postRepository.create({\n title: \"First Post\",\n text: \"About first post\",\n });\n post.should.be.instanceof(Post);\n })));\n\n it(\"should find instances of the target\", () => Promise.all(connections.map(async connection => {\n const postRepository = connection.getRepository(Post);\n const post = new Post();\n post.title = \"First Post\";\n post.text = \"About first post\";\n await postRepository.save(post);\n\n const loadedPost = await postRepository.findOne({ title: \"First Post\" });\n loadedPost!.should.be.instanceof(Post);\n })));\n"},"suffix":{"kind":"string","value":"});"},"middle":{"kind":"string","value":""},"fim_type":{"kind":"string","value":"random_line_split"}}},{"rowIdx":236084,"cells":{"file_name":{"kind":"string","value":"geoWidgets.py"},"prefix":{"kind":"string","value":"# -*- coding: ISO-8859-1 -*-\n\"\"\"\nForm Widget classes specific to the geoSite admin site.\n\"\"\"\n\n# A class that corresponds to an HTML form widget, \n# e.g. or
Subsets and Splits

No community queries yet

The top public SQL queries from the community will appear here once available.