{ // 获取包含Hugging Face文本的span元素 const spans = link.querySelectorAll('span.whitespace-nowrap, span.hidden.whitespace-nowrap'); spans.forEach(span => { if (span.textContent && span.textContent.trim().match(/Hugging\s*Face/i)) { span.textContent = 'AI快站'; } }); }); // 替换logo图片的alt属性 document.querySelectorAll('img[alt*="Hugging"], img[alt*="Face"]').forEach(img => { if (img.alt.match(/Hugging\s*Face/i)) { img.alt = 'AI快站 logo'; } }); } // 替换导航栏中的链接 function replaceNavigationLinks() { // 已替换标记,防止重复运行 if (window._navLinksReplaced) { return; } // 已经替换过的链接集合,防止重复替换 const replacedLinks = new Set(); // 只在导航栏区域查找和替换链接 const headerArea = document.querySelector('header') || document.querySelector('nav'); if (!headerArea) { return; } // 在导航区域内查找链接 const navLinks = headerArea.querySelectorAll('a'); navLinks.forEach(link => { // 如果已经替换过,跳过 if (replacedLinks.has(link)) return; const linkText = link.textContent.trim(); const linkHref = link.getAttribute('href') || ''; // 替换Spaces链接 - 仅替换一次 if ( (linkHref.includes('/spaces') || linkHref === '/spaces' || linkText === 'Spaces' || linkText.match(/^s*Spacess*$/i)) && linkText !== 'OCR模型免费转Markdown' && linkText !== 'OCR模型免费转Markdown' ) { link.textContent = 'OCR模型免费转Markdown'; link.href = 'https://fast360.xyz'; link.setAttribute('target', '_blank'); link.setAttribute('rel', 'noopener noreferrer'); replacedLinks.add(link); } // 删除Posts链接 else if ( (linkHref.includes('/posts') || linkHref === '/posts' || linkText === 'Posts' || linkText.match(/^s*Postss*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } // 替换Docs链接 - 仅替换一次 else if ( (linkHref.includes('/docs') || linkHref === '/docs' || linkText === 'Docs' || linkText.match(/^s*Docss*$/i)) && linkText !== '模型下载攻略' ) { link.textContent = '模型下载攻略'; link.href = '/'; replacedLinks.add(link); } // 删除Enterprise链接 else if ( (linkHref.includes('/enterprise') || linkHref === '/enterprise' || linkText === 'Enterprise' || linkText.match(/^s*Enterprises*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } }); // 查找可能嵌套的Spaces和Posts文本 const textNodes = []; function findTextNodes(element) { if (element.nodeType === Node.TEXT_NODE) { const text = element.textContent.trim(); if (text === 'Spaces' || text === 'Posts' || text === 'Enterprise') { textNodes.push(element); } } else { for (const child of element.childNodes) { findTextNodes(child); } } } // 只在导航区域内查找文本节点 findTextNodes(headerArea); // 替换找到的文本节点 textNodes.forEach(node => { const text = node.textContent.trim(); if (text === 'Spaces') { node.textContent = node.textContent.replace(/Spaces/g, 'OCR模型免费转Markdown'); } else if (text === 'Posts') { // 删除Posts文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } else if (text === 'Enterprise') { // 删除Enterprise文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } }); // 标记已替换完成 window._navLinksReplaced = true; } // 替换代码区域中的域名 function replaceCodeDomains() { // 特别处理span.hljs-string和span.njs-string元素 document.querySelectorAll('span.hljs-string, span.njs-string, span[class*="hljs-string"], span[class*="njs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换hljs-string类的span中的域名(移除多余的转义符号) document.querySelectorAll('span.hljs-string, span[class*="hljs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换pre和code标签中包含git clone命令的域名 document.querySelectorAll('pre, code').forEach(element => { if (element.textContent && element.textContent.includes('git clone')) { const text = element.innerHTML; if (text.includes('huggingface.co')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 处理特定的命令行示例 document.querySelectorAll('pre, code').forEach(element => { const text = element.innerHTML; if (text.includes('huggingface.co')) { // 针对git clone命令的专门处理 if (text.includes('git clone') || text.includes('GIT_LFS_SKIP_SMUDGE=1')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 特别处理模型下载页面上的代码片段 document.querySelectorAll('.flex.border-t, .svelte_hydrator, .inline-block').forEach(container => { const content = container.innerHTML; if (content && content.includes('huggingface.co')) { container.innerHTML = content.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 特别处理模型仓库克隆对话框中的代码片段 try { // 查找包含"Clone this model repository"标题的对话框 const cloneDialog = document.querySelector('.svelte_hydration_boundary, [data-target="MainHeader"]'); if (cloneDialog) { // 查找对话框中所有的代码片段和命令示例 const codeElements = cloneDialog.querySelectorAll('pre, code, span'); codeElements.forEach(element => { if (element.textContent && element.textContent.includes('huggingface.co')) { if (element.innerHTML.includes('huggingface.co')) { element.innerHTML = element.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { element.textContent = element.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); } // 更精确地定位克隆命令中的域名 document.querySelectorAll('[data-target]').forEach(container => { const codeBlocks = container.querySelectorAll('pre, code, span.hljs-string'); codeBlocks.forEach(block => { if (block.textContent && block.textContent.includes('huggingface.co')) { if (block.innerHTML.includes('huggingface.co')) { block.innerHTML = block.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { block.textContent = block.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); }); } catch (e) { // 错误处理但不打印日志 } } // 当DOM加载完成后执行替换 if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', () => { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); }); } else { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); } // 增加一个MutationObserver来处理可能的动态元素加载 const observer = new MutationObserver(mutations => { // 检查是否导航区域有变化 const hasNavChanges = mutations.some(mutation => { // 检查是否存在header或nav元素变化 return Array.from(mutation.addedNodes).some(node => { if (node.nodeType === Node.ELEMENT_NODE) { // 检查是否是导航元素或其子元素 if (node.tagName === 'HEADER' || node.tagName === 'NAV' || node.querySelector('header, nav')) { return true; } // 检查是否在导航元素内部 let parent = node.parentElement; while (parent) { if (parent.tagName === 'HEADER' || parent.tagName === 'NAV') { return true; } parent = parent.parentElement; } } return false; }); }); // 只在导航区域有变化时执行替换 if (hasNavChanges) { // 重置替换状态,允许再次替换 window._navLinksReplaced = false; replaceHeaderBranding(); replaceNavigationLinks(); } }); // 开始观察document.body的变化,包括子节点 if (document.body) { observer.observe(document.body, { childList: true, subtree: true }); } else { document.addEventListener('DOMContentLoaded', () => { observer.observe(document.body, { childList: true, subtree: true }); }); } })(); \n \"\"\")\n results = list(extract(buf, ['_', 'ngettext'], [], {}))\n self.assertEqual([\n (3, None, 'Example', []),\n (6, None, 'Example', []),\n (7, '_', 'Hello, %(name)s', []),\n (8, 'ngettext', ('You have %d item', 'You have %d items', None),\n []),\n ], results)\n\n def test_extraction_without_text(self):\n buf = StringIO(\"\"\"\n

Foo

\n ${ngettext(\"Singular\", \"Plural\", num)}\n \"\"\")\n results = list(extract(buf, ['_', 'ngettext'], [], {\n 'extract_text': 'no'\n }))\n self.assertEqual([\n (3, 'ngettext', ('Singular', 'Plural', None), []),\n ], results)\n\n def test_text_template_extraction(self):\n buf = StringIO(\"\"\"${_(\"Dear %(name)s\") % {'name': name}},\n\n ${ngettext(\"Your item:\", \"Your items\", len(items))}\n #for item in items\n * $item\n #end\n\n All the best,\n Foobar\"\"\")\n results = list(extract(buf, ['_', 'ngettext'], [], {\n 'template_class': 'genshi.template:TextTemplate'\n }))\n self.assertEqual([\n (1, '_', 'Dear %(name)s', []),\n (3, 'ngettext', ('Your item:', 'Your items', None), []),\n (7, None, 'All the best,\\n Foobar', [])\n ], results)\n\n def test_extraction_with_keyword_arg(self):\n buf = StringIO(\"\"\"\n ${gettext('Foobar', foo='bar')}\n \"\"\")\n results = list(extract(buf, ['gettext'], [], {}))\n self.assertEqual([\n (2, 'gettext', ('Foobar'), []),\n ], results)\n\n def test_extraction_with_nonstring_arg(self):\n buf = StringIO(\"\"\"\n ${dgettext(curdomain, 'Foobar')}\n \"\"\")\n results = list(extract(buf, ['dgettext'], [], {}))\n self.assertEqual([\n (2, 'dgettext', (None, 'Foobar'), []),\n ], results)\n\n def test_extraction_inside_ignored_tags(self):\n buf = StringIO(\"\"\"\n \n \"\"\")\n results = list(extract(buf, ['_'], [], {}))\n self.assertEqual([\n (5, '_', 'Please wait...', []),\n ], results)\n\n def test_extraction_inside_ignored_tags_with_directives(self):\n buf = StringIO(\"\"\"\n \n \"\"\")\n self.assertEqual([], list(extract(buf, ['_'], [], {})))\n\n def test_extract_py_def_directive_with_py_strip(self):\n # Failed extraction from Trac\n tmpl = MarkupTemplate(\"\"\"\n \n \n \n
\n Show \n \n
\n
\n Ignore:\n
\n \n \n
\n
\n \n \n
\n
\n \n \n
\n
\n
\n \n
\n
\"\"\")\n translator = Translator()\n tmpl.add_directives(Translator.NAMESPACE, translator)\n messages = list(translator.extract(tmpl.stream))\n self.assertEqual(10, len(messages))\n self.assertEqual([\n (3, None, 'View differences', []),\n (6, None, 'inline', []),\n (8, None, 'side by side', []),\n (10, None, 'Show', []),\n (13, None, 'lines around each change', []),\n (16, None, 'Ignore:', []),\n (20, None, 'Blank lines', []),\n (25, None, 'Case changes',[]),\n (30, None, 'White space changes', []),\n (34, '_', 'Update', [])], messages)\n\n\ndef suite():\n suite = unittest.TestSuite()\n suite.addTest(doctest.DocTestSuite(Translator.__module__))\n suite.addTest(unittest.makeSuite(TranslatorTestCase, 'test'))\n suite.addTest(unittest.makeSuite(MsgDirectiveTestCase, 'test'))\n suite.addTest(unittest.makeSuite(ChooseDirectiveTestCase, 'test'))\n suite.addTest(unittest.makeSuite(DomainDirectiveTestCase, 'test'))\n suite.addTest(unittest.makeSuite(ExtractTestCase, 'test'))\n return suite\n\nif __name__ == '__main__':\n unittest.main(defaultTest='suite')\n"},"repo_name":{"kind":"string","value":"mitchellrj/genshi"},"path":{"kind":"string","value":"genshi/filters/tests/i18n.py"},"language":{"kind":"string","value":"Python"},"license":{"kind":"string","value":"bsd-3-clause"},"size":{"kind":"number","value":89114,"string":"89,114"}}},{"rowIdx":61538282,"cells":{"code":{"kind":"string","value":"// Copyright (c) 2012 The Chromium Authors. All rights reserved.\n// Use of this source code is governed by a BSD-style license that can be\n// found in the LICENSE file.\n\n#include \"chrome/browser/chromeos/login/version_info_updater.h\"\n\n#include \n\n#include \"base/bind.h\"\n#include \"base/bind_helpers.h\"\n#include \"base/strings/string_util.h\"\n#include \"base/strings/stringprintf.h\"\n#include \"base/strings/utf_string_conversions.h\"\n#include \"base/sys_info.h\"\n#include \"base/task_runner_util.h\"\n#include \"chrome/browser/browser_process.h\"\n#include \"chrome/browser/chromeos/policy/browser_policy_connector_chromeos.h\"\n#include \"chrome/browser/chromeos/policy/device_cloud_policy_manager_chromeos.h\"\n#include \"chrome/browser/chromeos/settings/cros_settings.h\"\n#include \"chrome/common/chrome_version_info.h\"\n#include \"chrome/grit/chromium_strings.h\"\n#include \"chrome/grit/generated_resources.h\"\n#include \"chromeos/settings/cros_settings_names.h\"\n#include \"content/public/browser/browser_thread.h\"\n#include \"ui/base/l10n/l10n_util.h\"\n\nnamespace chromeos {\n\nnamespace {\n\nconst char* const kReportingFlags[] = {\n chromeos::kReportDeviceVersionInfo,\n chromeos::kReportDeviceActivityTimes,\n chromeos::kReportDeviceBootMode,\n chromeos::kReportDeviceLocation,\n};\n\n// Strings used to generate the serial number part of the version string.\nconst char kSerialNumberPrefix[] = \"SN:\";\n\n} // namespace\n\n///////////////////////////////////////////////////////////////////////////////\n// VersionInfoUpdater public:\n\nVersionInfoUpdater::VersionInfoUpdater(Delegate* delegate)\n : cros_settings_(chromeos::CrosSettings::Get()),\n delegate_(delegate),\n weak_pointer_factory_(this) {\n}\n\nVersionInfoUpdater::~VersionInfoUpdater() {\n policy::BrowserPolicyConnectorChromeOS* connector =\n g_browser_process->platform_part()->browser_policy_connector_chromeos();\n policy::DeviceCloudPolicyManagerChromeOS* policy_manager =\n connector->GetDeviceCloudPolicyManager();\n if (policy_manager)\n policy_manager->core()->store()->RemoveObserver(this);\n}\n\nvoid VersionInfoUpdater::StartUpdate(bool is_official_build) {\n if (base::SysInfo::IsRunningOnChromeOS()) {\n base::PostTaskAndReplyWithResult(\n content::BrowserThread::GetBlockingPool(),\n FROM_HERE,\n base::Bind(&version_loader::GetVersion,\n is_official_build ? version_loader::VERSION_SHORT_WITH_DATE\n : version_loader::VERSION_FULL),\n base::Bind(&VersionInfoUpdater::OnVersion,\n weak_pointer_factory_.GetWeakPtr()));\n } else {\n UpdateVersionLabel();\n }\n\n policy::BrowserPolicyConnectorChromeOS* connector =\n g_browser_process->platform_part()->browser_policy_connector_chromeos();\n policy::DeviceCloudPolicyManagerChromeOS* policy_manager =\n connector->GetDeviceCloudPolicyManager();\n if (policy_manager) {\n policy_manager->core()->store()->AddObserver(this);\n\n // Ensure that we have up-to-date enterprise info in case enterprise policy\n // is already fetched and has finished initialization.\n UpdateEnterpriseInfo();\n }\n\n // Watch for changes to the reporting flags.\n base::Closure callback =\n base::Bind(&VersionInfoUpdater::UpdateEnterpriseInfo,\n base::Unretained(this));\n for (unsigned int i = 0; i < arraysize(kReportingFlags); ++i) {\n subscriptions_.push_back(\n cros_settings_->AddSettingsObserver(kReportingFlags[i],\n callback).release());\n }\n}\n\nvoid VersionInfoUpdater::UpdateVersionLabel() {\n if (version_text_.empty())\n return;\n\n UpdateSerialNumberInfo();\n\n chrome::VersionInfo version_info;\n std::string label_text = l10n_util::GetStringFUTF8(\n IDS_LOGIN_VERSION_LABEL_FORMAT,\n l10n_util::GetStringUTF16(IDS_PRODUCT_NAME),\n base::UTF8ToUTF16(version_info.Version()),\n base::UTF8ToUTF16(version_text_),\n base::UTF8ToUTF16(serial_number_text_));\n\n // Workaround over incorrect width calculation in old fonts.\n // TODO(glotov): remove the following line when new fonts are used.\n label_text += ' ';\n\n if (delegate_)\n delegate_->OnOSVersionLabelTextUpdated(label_text);\n}\n\nvoid VersionInfoUpdater::UpdateEnterpriseInfo() {\n policy::BrowserPolicyConnectorChromeOS* connector =\n g_browser_process->platform_part()->browser_policy_connector_chromeos();\n SetEnterpriseInfo(connector->GetEnterpriseDomain());\n}\n\nvoid VersionInfoUpdater::SetEnterpriseInfo(const std::string& domain_name) {\n // Update the notification about device status reporting.\n if (delegate_ && !domain_name.empty()) {\n std::string enterprise_info;\n enterprise_info = l10n_util::GetStringFUTF8(\n IDS_DEVICE_OWNED_BY_NOTICE,\n base::UTF8ToUTF16(domain_name));\n delegate_->OnEnterpriseInfoUpdated(enterprise_info);\n }\n}\n\nvoid VersionInfoUpdater::UpdateSerialNumberInfo() {\n std::string sn = policy::DeviceCloudPolicyManagerChromeOS::GetMachineID();\n if (!sn.empty()) {\n serial_number_text_ = kSerialNumberPrefix;\n serial_number_text_.append(sn);\n }\n}\n\nvoid VersionInfoUpdater::OnVersion(const std::string& version) {\n version_text_ = version;\n UpdateVersionLabel();\n}\n\nvoid VersionInfoUpdater::OnStoreLoaded(policy::CloudPolicyStore* store) {\n UpdateEnterpriseInfo();\n}\n\nvoid VersionInfoUpdater::OnStoreError(policy::CloudPolicyStore* store) {\n UpdateEnterpriseInfo();\n}\n\n} // namespace chromeos\n"},"repo_name":{"kind":"string","value":"mohamed--abdel-maksoud/chromium.src"},"path":{"kind":"string","value":"chrome/browser/chromeos/login/version_info_updater.cc"},"language":{"kind":"string","value":"C++"},"license":{"kind":"string","value":"bsd-3-clause"},"size":{"kind":"number","value":5419,"string":"5,419"}}},{"rowIdx":61538283,"cells":{"code":{"kind":"string","value":"using System.Reflection;\nusing System.Runtime.CompilerServices;\nusing System.Runtime.InteropServices;\n\n// General Information about an assembly is controlled through the following \n// set of attributes. Change these attribute values to modify the information\n// associated with an assembly.\n[assembly: AssemblyTitle(\"SimpleNavigation\")]\n[assembly: AssemblyDescription(\"\")]\n[assembly: AssemblyConfiguration(\"\")]\n[assembly: AssemblyCompany(\"\")]\n[assembly: AssemblyProduct(\"SimpleNavigation\")]\n[assembly: AssemblyCopyright(\"Copyright © 2015\")]\n[assembly: AssemblyTrademark(\"\")]\n[assembly: AssemblyCulture(\"\")]\n\n// Version information for an assembly consists of the following four values:\n//\n// Major Version\n// Minor Version \n// Build Number\n// Revision\n//\n// You can specify all the values or you can default the Build and Revision Numbers \n// by using the '*' as shown below:\n// [assembly: AssemblyVersion(\"1.0.*\")]\n[assembly: AssemblyVersion(\"1.0.0.0\")]\n[assembly: AssemblyFileVersion(\"1.0.0.0\")]\n[assembly: ComVisible(false)]"},"repo_name":{"kind":"string","value":"Windows-Readiness/WinDevWorkshop"},"path":{"kind":"string","value":"RU/!RU 01. Introduction/01. Lab B. Solution/Exercise 2/SimpleNavigation/Properties/AssemblyInfo.cs"},"language":{"kind":"string","value":"C#"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":1052,"string":"1,052"}}},{"rowIdx":61538284,"cells":{"code":{"kind":"string","value":"//\n// Copyright 2012 Christian Henning\n//\n// Distributed under the Boost Software License, Version 1.0\n// See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt\n//\n#ifndef BOOST_GIL_EXTENSION_IO_PNG_DETAIL_WRITER_BACKEND_HPP\n#define BOOST_GIL_EXTENSION_IO_PNG_DETAIL_WRITER_BACKEND_HPP\n\n#include \n#include \n#include \n\n#include \n#include \n\nnamespace boost { namespace gil {\n\n#if BOOST_WORKAROUND(BOOST_MSVC, >= 1400)\n#pragma warning(push)\n#pragma warning(disable:4512) //assignment operator could not be generated\n#pragma warning(disable:4611) //interaction between '_setjmp' and C++ object destruction is non-portable\n#endif\n\n///\n/// PNG Writer Backend\n///\ntemplate< typename Device >\nstruct writer_backend< Device\n , png_tag\n >\n : public detail::png_struct_info_wrapper\n{\n\nprivate:\n\n using this_t = writer_backend;\n\npublic:\n\n using format_tag_t = png_tag;\n\n ///\n /// Constructor\n ///\n writer_backend( const Device& io_dev\n , const image_write_info< png_tag >& info\n )\n : png_struct_info_wrapper( false )\n , _io_dev( io_dev )\n , _info( info )\n {\n // Create and initialize the png_struct with the desired error handler\n // functions. If you want to use the default stderr and longjump method,\n // you can supply NULL for the last three parameters. We also check that\n // the library version is compatible with the one used at compile time,\n // in case we are using dynamically linked libraries. REQUIRED.\n get()->_struct = png_create_write_struct( PNG_LIBPNG_VER_STRING\n , nullptr // user_error_ptr\n , nullptr // user_error_fn\n , nullptr // user_warning_fn\n );\n\n io_error_if( get_struct() == nullptr\n , \"png_writer: fail to call png_create_write_struct()\"\n );\n\n // Allocate/initialize the image information data. REQUIRED\n get()->_info = png_create_info_struct( get_struct() );\n\n if( get_info() == nullptr )\n {\n png_destroy_write_struct( &get()->_struct\n , nullptr\n );\n\n io_error( \"png_writer: fail to call png_create_info_struct()\" );\n }\n\n // Set error handling. REQUIRED if you aren't supplying your own\n // error handling functions in the png_create_write_struct() call.\n if( setjmp( png_jmpbuf( get_struct() )))\n {\n //free all of the memory associated with the png_ptr and info_ptr\n png_destroy_write_struct( &get()->_struct\n , &get()->_info\n );\n\n io_error( \"png_writer: fail to call setjmp()\" );\n }\n\n init_io( get_struct() );\n }\n\nprotected:\n\n template< typename View >\n void write_header( const View& view )\n {\n using png_rw_info_t = detail::png_write_support\n <\n typename channel_type::type>::type,\n typename color_space_type::type\n >;\n\n // Set the image information here. Width and height are up to 2^31,\n // bit_depth is one of 1, 2, 4, 8, or 16, but valid values also depend on\n // the color_type selected. color_type is one of PNG_COLOR_TYPE_GRAY,\n // PNG_COLOR_TYPE_GRAY_ALPHA, PNG_COLOR_TYPE_PALETTE, PNG_COLOR_TYPE_RGB,\n // or PNG_COLOR_TYPE_RGB_ALPHA. interlace is either PNG_INTERLACE_NONE or\n // PNG_INTERLACE_ADAM7, and the compression_type and filter_type MUST\n // currently be PNG_COMPRESSION_TYPE_BASE and PNG_FILTER_TYPE_BASE. REQUIRED\n png_set_IHDR( get_struct()\n , get_info()\n , static_cast< png_image_width::type >( view.width() )\n , static_cast< png_image_height::type >( view.height() )\n , static_cast< png_bitdepth::type >( png_rw_info_t::_bit_depth )\n , static_cast< png_color_type::type >( png_rw_info_t::_color_type )\n , _info._interlace_method\n , _info._compression_type\n , _info._filter_method\n );\n\n#ifdef BOOST_GIL_IO_PNG_FLOATING_POINT_SUPPORTED\n if( _info._valid_cie_colors )\n {\n png_set_cHRM( get_struct()\n , get_info()\n , _info._white_x\n , _info._white_y\n , _info._red_x\n , _info._red_y\n , _info._green_x\n , _info._green_y\n , _info._blue_x\n , _info._blue_y\n );\n }\n\n if( _info._valid_file_gamma )\n {\n png_set_gAMA( get_struct()\n , get_info()\n , _info._file_gamma\n );\n }\n#else\n if( _info._valid_cie_colors )\n {\n png_set_cHRM_fixed( get_struct()\n , get_info()\n , _info._white_x\n , _info._white_y\n , _info._red_x\n , _info._red_y\n , _info._green_x\n , _info._green_y\n , _info._blue_x\n , _info._blue_y\n );\n }\n\n if( _info._valid_file_gamma )\n {\n png_set_gAMA_fixed( get_struct()\n , get_info()\n , _info._file_gamma\n );\n }\n#endif // BOOST_GIL_IO_PNG_FLOATING_POINT_SUPPORTED\n\n if( _info._valid_icc_profile )\n {\n#if PNG_LIBPNG_VER_MINOR >= 5\n png_set_iCCP( get_struct()\n , get_info()\n , const_cast< png_charp >( _info._icc_name.c_str() )\n , _info._iccp_compression_type\n , reinterpret_cast< png_const_bytep >( & (_info._profile.front ()) )\n , _info._profile_length\n );\n#else\n png_set_iCCP( get_struct()\n , get_info()\n , const_cast< png_charp >( _info._icc_name.c_str() )\n , _info._iccp_compression_type\n , const_cast< png_charp >( & (_info._profile.front()) )\n , _info._profile_length\n );\n#endif\n }\n\n if( _info._valid_intent )\n {\n png_set_sRGB( get_struct()\n , get_info()\n , _info._intent\n );\n }\n\n if( _info._valid_palette )\n {\n png_set_PLTE( get_struct()\n , get_info()\n , const_cast< png_colorp >( &_info._palette.front() )\n , _info._num_palette\n );\n }\n\n if( _info._valid_background )\n {\n png_set_bKGD( get_struct()\n , get_info()\n , const_cast< png_color_16p >( &_info._background )\n );\n }\n\n if( _info._valid_histogram )\n {\n png_set_hIST( get_struct()\n , get_info()\n , const_cast< png_uint_16p >( &_info._histogram.front() )\n );\n }\n\n if( _info._valid_offset )\n {\n png_set_oFFs( get_struct()\n , get_info()\n , _info._offset_x\n , _info._offset_y\n , _info._off_unit_type\n );\n }\n\n if( _info._valid_pixel_calibration )\n {\n std::vector< const char* > params( _info._num_params );\n for( std::size_t i = 0; i < params.size(); ++i )\n {\n params[i] = _info._params[ i ].c_str();\n }\n\n png_set_pCAL( get_struct()\n , get_info()\n , const_cast< png_charp >( _info._purpose.c_str() )\n , _info._X0\n , _info._X1\n , _info._cal_type\n , _info._num_params\n , const_cast< png_charp >( _info._units.c_str() )\n , const_cast< png_charpp >( &params.front() )\n );\n }\n\n if( _info._valid_resolution )\n {\n png_set_pHYs( get_struct()\n , get_info()\n , _info._res_x\n , _info._res_y\n , _info._phy_unit_type\n );\n }\n\n if( _info._valid_significant_bits )\n {\n png_set_sBIT( get_struct()\n , get_info()\n , const_cast< png_color_8p >( &_info._sig_bits )\n );\n }\n\n#ifndef BOOST_GIL_IO_PNG_1_4_OR_LOWER\n\n#ifdef BOOST_GIL_IO_PNG_FLOATING_POINT_SUPPORTED\n if( _info._valid_scale_factors )\n {\n png_set_sCAL( get_struct()\n , get_info()\n , this->_info._scale_unit\n , this->_info._scale_width\n , this->_info._scale_height\n );\n }\n#else\n#ifdef BOOST_GIL_IO_PNG_FIXED_POINT_SUPPORTED\n if( _info._valid_scale_factors )\n {\n png_set_sCAL_fixed( get_struct()\n , get_info()\n , this->_info._scale_unit\n , this->_info._scale_width\n , this->_info._scale_height\n );\n }\n#else\n if( _info._valid_scale_factors )\n {\n png_set_sCAL_s( get_struct()\n , get_info()\n , this->_info._scale_unit\n , const_cast< png_charp >( this->_info._scale_width.c_str() )\n , const_cast< png_charp >( this->_info._scale_height.c_str() )\n );\n }\n\n#endif // BOOST_GIL_IO_PNG_FIXED_POINT_SUPPORTED\n#endif // BOOST_GIL_IO_PNG_FLOATING_POINT_SUPPORTED\n#endif // BOOST_GIL_IO_PNG_1_4_OR_LOWER\n\n if( _info._valid_text )\n {\n std::vector< png_text > texts( _info._num_text );\n for( std::size_t i = 0; i < texts.size(); ++i )\n {\n png_text pt;\n pt.compression = _info._text[i]._compression;\n pt.key = const_cast< png_charp >( this->_info._text[i]._key.c_str() );\n pt.text = const_cast< png_charp >( this->_info._text[i]._text.c_str() );\n pt.text_length = _info._text[i]._text.length();\n\n texts[i] = pt;\n }\n\n png_set_text( get_struct()\n , get_info()\n , &texts.front()\n , _info._num_text\n );\n }\n\n if( _info._valid_modification_time )\n {\n png_set_tIME( get_struct()\n , get_info()\n , const_cast< png_timep >( &_info._mod_time )\n );\n }\n\n if( _info._valid_transparency_factors )\n {\n int sample_max = ( 1u << _info._bit_depth );\n\n /* libpng doesn't reject a tRNS chunk with out-of-range samples */\n if( !( ( _info._color_type == PNG_COLOR_TYPE_GRAY\n && (int) _info._trans_values[0].gray > sample_max\n )\n || ( _info._color_type == PNG_COLOR_TYPE_RGB\n &&( (int) _info._trans_values[0].red > sample_max\n || (int) _info._trans_values[0].green > sample_max\n || (int) _info._trans_values[0].blue > sample_max\n )\n )\n )\n )\n {\n //@todo Fix that once reading transparency values works\n/*\n png_set_tRNS( get_struct()\n , get_info()\n , trans\n , num_trans\n , trans_values\n );\n*/\n }\n }\n\n // Compression Levels - valid values are [0,9]\n png_set_compression_level( get_struct()\n , _info._compression_level\n );\n\n png_set_compression_mem_level( get_struct()\n , _info._compression_mem_level\n );\n\n png_set_compression_strategy( get_struct()\n , _info._compression_strategy\n );\n\n png_set_compression_window_bits( get_struct()\n , _info._compression_window_bits\n );\n\n png_set_compression_method( get_struct()\n , _info._compression_method\n );\n\n png_set_compression_buffer_size( get_struct()\n , _info._compression_buffer_size\n );\n\n#ifdef BOOST_GIL_IO_PNG_DITHERING_SUPPORTED\n // Dithering\n if( _info._set_dithering )\n {\n png_set_dither( get_struct()\n , &_info._dithering_palette.front()\n , _info._dithering_num_palette\n , _info._dithering_maximum_colors\n , &_info._dithering_histogram.front()\n , _info._full_dither\n );\n }\n#endif // BOOST_GIL_IO_PNG_DITHERING_SUPPORTED\n\n // Filter\n if( _info._set_filter )\n {\n png_set_filter( get_struct()\n , 0\n , _info._filter\n );\n }\n\n // Invert Mono\n if( _info._invert_mono )\n {\n png_set_invert_mono( get_struct() );\n }\n\n // True Bits\n if( _info._set_true_bits )\n {\n png_set_sBIT( get_struct()\n , get_info()\n , &_info._true_bits.front()\n );\n }\n\n // sRGB Intent\n if( _info._set_srgb_intent )\n {\n png_set_sRGB( get_struct()\n , get_info()\n , _info._srgb_intent\n );\n }\n\n // Strip Alpha\n if( _info._strip_alpha )\n {\n png_set_strip_alpha( get_struct() );\n }\n\n // Swap Alpha\n if( _info._swap_alpha )\n {\n png_set_swap_alpha( get_struct() );\n }\n\n\n png_write_info( get_struct()\n , get_info()\n );\n }\n\nprotected:\n\n static void write_data( png_structp png_ptr\n , png_bytep data\n , png_size_t length\n )\n {\n static_cast< Device* >( png_get_io_ptr( png_ptr ))->write( data\n , length );\n }\n\n static void flush( png_structp png_ptr )\n {\n static_cast< Device* >(png_get_io_ptr(png_ptr) )->flush();\n }\n\nprivate:\n\n void init_io( png_structp png_ptr )\n {\n png_set_write_fn( png_ptr\n , static_cast< void* > ( &this->_io_dev )\n , static_cast< png_rw_ptr > ( &this_t::write_data )\n , static_cast< png_flush_ptr >( &this_t::flush )\n );\n }\n\npublic:\n\n Device _io_dev;\n\n image_write_info< png_tag > _info;\n};\n\n#if BOOST_WORKAROUND(BOOST_MSVC, >= 1400)\n#pragma warning(pop)\n#endif\n\n} // namespace gil\n} // namespace boost\n\n#endif\n"},"repo_name":{"kind":"string","value":"kumakoko/KumaGL"},"path":{"kind":"string","value":"third_lib/boost/1.75.0/boost/gil/extension/io/png/detail/writer_backend.hpp"},"language":{"kind":"string","value":"C++"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":16790,"string":"16,790"}}},{"rowIdx":61538285,"cells":{"code":{"kind":"string","value":"# encoding: utf-8\nrequire 'spec_helper'\n\ndef encode_base64(str)\n Mail::Encodings::Base64.encode(str)\nend\n\ndef check_decoded(actual, expected)\n if RUBY_VERSION >= '1.9'\n expect(actual.encoding).to eq Encoding::BINARY\n expect(actual).to eq expected.force_encoding(Encoding::BINARY)\n else\n expect(actual).to eq expected\n end\nend\n\ndescribe \"Attachments\" do\n\n before(:each) do\n @mail = Mail.new\n @test_png = File.open(fixture('attachments', 'test.png'), 'rb', &:read)\n end\n\n describe \"from direct content\" do\n it \"should work\" do\n @mail.attachments['test.png'] = @test_png\n expect(@mail.attachments['test.png'].filename).to eq 'test.png'\n check_decoded(@mail.attachments[0].decoded, @test_png)\n end\n\n it \"should work out magically the mime_type\" do\n @mail.attachments['test.png'] = @test_png\n expect(@mail.attachments[0].mime_type).to eq 'image/png'\n end\n\n it \"should assign the filename\" do\n @mail.attachments['test.png'] = @test_png\n expect(@mail.attachments[0].filename).to eq 'test.png'\n end\n\n it \"should assign mime-encoded multibyte filename\" do\n @mail.attachments['てすと.txt'] = File.open(fixture('attachments', 'てすと.txt'), 'rb', &:read)\n expect(@mail.attachments).not_to be_blank\n expect(Mail::Encodings.decode_encode(@mail.attachments[0].filename, :decode)).to eq 'てすと.txt'\n end\n end\n\n describe \"from a supplied Hash\" do\n it \"should work\" do\n @mail.attachments['test.png'] = { :content => @test_png }\n expect(@mail.attachments[0].filename).to eq 'test.png'\n check_decoded(@mail.attachments[0].decoded, @test_png)\n end\n\n it \"should allow you to override the content_type\" do\n @mail.attachments['test.png'] = { :content => @test_png,\n :content_type => \"application/x-gzip\" }\n expect(@mail.attachments[0].content_type).to eq 'application/x-gzip'\n end\n\n it \"should allow you to override the mime_type\" do\n @mail.attachments['test.png'] = { :content => @test_png,\n :mime_type => \"application/x-gzip\" }\n expect(@mail.attachments[0].mime_type).to eq 'application/x-gzip'\n end\n\n it \"should allow you to override the mime_type\" do\n @mail.attachments['invoice.jpg'] = { :data => \"you smiling\",\n :mime_type => \"image/x-jpg\",\n :transfer_encoding => \"base64\" }\n expect(@mail.attachments[0].mime_type).to eq 'image/x-jpg'\n end\n\n end\n\n describe \"decoding and encoding\" do\n\n it \"should set its content_transfer_encoding\" do\n @mail.attachments['test.png'] = { :content => @test_png }\n @mail.ready_to_send!\n expect(@mail.attachments[0].content_transfer_encoding).to eq 'base64'\n end\n\n it \"should encode its body to base64\" do\n @mail.attachments['test.png'] = { :content => @test_png }\n @mail.ready_to_send!\n expect(@mail.attachments[0].encoded).to include(encode_base64(@test_png))\n end\n\n it \"should allow you to pass in an encoded attachment with an encoding\" do\n encoded_data = encode_base64(@test_png)\n @mail.attachments['test.png'] = { :content => encoded_data,\n :encoding => 'base64' }\n check_decoded(@mail.attachments[0].decoded, @test_png)\n end\n\n it \"should allow you set a mime type and encoding without overriding the encoding\" do\n encoded = encode_base64('')\n @mail.attachments['test.png'] = { :mime_type => 'text/xml', :content => encoded, :encoding => 'base64' }\n expect(@mail.attachments[0].content_transfer_encoding).to eq 'base64'\n check_decoded(@mail.attachments[0].decoded, '')\n end\n\n it \"should not allow you to pass in an encoded attachment with an unknown encoding\" do\n base64_encoded_data = encode_base64(@test_png)\n expect {@mail.attachments['test.png'] = { :content => base64_encoded_data,\n :encoding => 'weird_encoding' }}.to raise_error\n end\n\n it \"should be able to call read on the attachment to return the decoded data\" do\n @mail.attachments['test.png'] = { :content => @test_png }\n if RUBY_VERSION >= '1.9'\n expected = @mail.attachments[0].read.force_encoding(@test_png.encoding)\n else\n expected = @mail.attachments[0].read\n end\n expect(expected).to eq @test_png\n end\n\n it \"should only add one newline between attachment body and boundary\" do\n contents = \"I have\\ntwo lines with trailing newlines\\n\\n\"\n @mail.attachments['text.txt'] = { :content => contents}\n encoded = @mail.encoded\n regex = /\\r\\n#{Regexp.escape(contents.gsub(/\\n/, \"\\r\\n\"))}\\r\\n--#{@mail.boundary}--\\r\\n\\Z/\n expect(encoded).to match regex\n end\n\n end\n\n describe \"multiple attachments\" do\n\n it \"should allow you to pass in more than one attachment\" do\n mail = Mail.new\n mail.attachments['test.pdf'] = File.open(fixture('attachments', 'test.pdf'), 'rb', &:read)\n mail.attachments['test.gif'] = File.open(fixture('attachments', 'test.gif'), 'rb', &:read)\n mail.attachments['test.jpg'] = File.open(fixture('attachments', 'test.jpg'), 'rb', &:read)\n mail.attachments['test.zip'] = File.open(fixture('attachments', 'test.zip'), 'rb', &:read)\n expect(mail.attachments[0].filename).to eq 'test.pdf'\n expect(mail.attachments[1].filename).to eq 'test.gif'\n expect(mail.attachments[2].filename).to eq 'test.jpg'\n expect(mail.attachments[3].filename).to eq 'test.zip'\n end\n\n end\n\n describe \"inline attachments\" do\n\n it \"should set the content_disposition to inline or attachment as appropriate\" do\n mail = Mail.new\n mail.attachments['test.pdf'] = File.open(fixture('attachments', 'test.pdf'), 'rb', &:read)\n expect(mail.attachments['test.pdf'].content_disposition).to eq 'attachment; filename=test.pdf'\n mail.attachments.inline['test.png'] = File.open(fixture('attachments', 'test.png'), 'rb', &:read)\n expect(mail.attachments.inline['test.png'].content_disposition).to eq 'inline; filename=test.png'\n end\n\n it \"should return a cid\" do\n mail = Mail.new\n mail.attachments.inline['test.png'] = @test_png\n expect(mail.attachments['test.png'].url).to eq \"cid:#{mail.attachments['test.png'].cid}\"\n end\n\n it \"should respond true to inline?\" do\n mail = Mail.new\n mail.attachments.inline['test.png'] = @test_png\n expect(mail.attachments['test.png']).to be_inline\n end\n end\n\n describe \"getting the content ID from an attachment\" do\n before(:each) do\n @mail = Mail.new\n @mail.attachments['test.gif'] = File.open(fixture('attachments', 'test.gif'), 'rb', &:read)\n @cid = @mail.attachments['test.gif'].content_id\n end\n\n it \"should return a content-id for the attachment on creation if passed inline => true\" do\n expect(@cid).not_to be_nil\n end\n\n it \"should return a valid content-id on inline attachments\" do\n expect(Mail::ContentIdField.new(@cid).errors).to be_empty\n end\n\n it \"should provide a URL escaped content_id (without brackets) for use inside an email\" do\n @inline = @mail.attachments['test.gif'].cid\n uri_parser = URI.const_defined?(:Parser) ? URI::Parser.new : URI\n expect(@inline).to eq uri_parser.escape(@cid.gsub(/^$/, ''))\n end\n end\n\n describe \"setting the content type correctly\" do\n it \"should set the content type to multipart/mixed if none given and you add an attachment\" do\n mail = Mail.new\n mail.attachments['test.pdf'] = File.open(fixture('attachments', 'test.pdf'), 'rb', &:read)\n mail.encoded\n expect(mail.mime_type).to eq 'multipart/mixed'\n end\n\n it \"allows you to set the attachment before the content type\" do\n mail = Mail.new\n mail.attachments[\"test.png\"] = File.open(fixture('attachments', 'test.png'), 'rb', &:read)\n mail.body = \"Lots of HTML\"\n mail.mime_version = '1.0'\n mail.content_type = 'text/html; charset=UTF-8'\n end\n\n end\n\n describe \"should handle filenames with non-7bit characters correctly\" do\n it \"should not raise an exception with a filename that contains a non-7bit-character\" do\n filename = \"f\\u00f6\\u00f6.b\\u00e4r\"\n if RUBY_VERSION >= '1.9'\n expect(filename.encoding).to eq Encoding::UTF_8\n end\n mail = Mail.new\n expect {\n mail.attachments[filename] = File.open(fixture('attachments', 'test.pdf'), 'rb', &:read)\n }.not_to raise_error\n end\n end\n\nend\n\ndescribe \"reading emails with attachments\" do\n describe \"test emails\" do\n\n it \"should find the attachment using content location\" do\n mail = Mail.read(fixture(File.join('emails', 'attachment_emails', 'attachment_content_location.eml')))\n expect(mail.attachments.length).to eq 1\n end\n\n it \"should find an attachment defined with 'name' and Content-Disposition: attachment\" do\n mail = Mail.read(fixture(File.join('emails', 'attachment_emails', 'attachment_content_disposition.eml')))\n expect(mail.attachments.length).to eq 1\n end\n\n it \"should use the content-type filename or name over the content-disposition filename\" do\n mail = Mail.read(fixture(File.join('emails', 'attachment_emails', 'attachment_content_disposition.eml')))\n expect(mail.attachments[0].filename).to eq 'hello.rb'\n end\n\n it \"should decode an attachment\" do\n mail = Mail.read(fixture(File.join('emails', 'attachment_emails', 'attachment_pdf.eml')))\n expect(mail.attachments[0].decoded.length).to eq 1026\n end\n\n it \"should find an attachment that has an encoded name value\" do\n mail = Mail.read(fixture(File.join('emails', 'attachment_emails', 'attachment_with_encoded_name.eml')))\n expect(mail.attachments.length).to eq 1\n result = mail.attachments[0].filename\n if RUBY_VERSION >= '1.9'\n expected = \"01 Quien Te Dij\\212at. Pitbull.mp3\".force_encoding(result.encoding)\n else\n expected = \"01 Quien Te Dij\\212at. Pitbull.mp3\"\n end\n expect(result).to eq expected\n end\n\n it \"should find an attachment that has a name not surrounded by quotes\" do\n mail = Mail.read(fixture(File.join('emails', 'attachment_emails', \"attachment_with_unquoted_name.eml\")))\n expect(mail.attachments.length).to eq 1\n expect(mail.attachments.first.filename).to eq \"This is a test.txt\"\n end\n\n it \"should find attachments inside parts with content-type message/rfc822\" do\n mail = Mail.read(fixture(File.join(\"emails\",\n \"attachment_emails\",\n \"attachment_message_rfc822.eml\")))\n expect(mail.attachments.length).to eq 1\n expect(mail.attachments[0].decoded.length).to eq 1026\n end\n\n it \"attach filename decoding (issue 83)\" do\n data = <<-limitMAIL\nSubject: aaa\nFrom: aaa@aaa.com\nTo: bbb@aaa.com\nContent-Type: multipart/mixed; boundary=0016e64c0af257c3a7048b69e1ac\n\n--0016e64c0af257c3a7048b69e1ac\nContent-Type: multipart/alternative; boundary=0016e64c0af257c3a1048b69e1aa\n\n--0016e64c0af257c3a1048b69e1aa\nContent-Type: text/plain; charset=ISO-8859-1\n\naaa\n\n--0016e64c0af257c3a1048b69e1aa\nContent-Type: text/html; charset=ISO-8859-1\n\naaa
\n\n--0016e64c0af257c3a1048b69e1aa--\n--0016e64c0af257c3a7048b69e1ac\nContent-Type: text/plain; charset=US-ASCII; name=\"=?utf-8?b?Rm90bzAwMDkuanBn?=\"\nContent-Disposition: attachment; filename=\"=?utf-8?b?Rm90bzAwMDkuanBn?=\"\nContent-Transfer-Encoding: base64\nX-Attachment-Id: f_gbneqxxy0\n\nYWFhCg==\n--0016e64c0af257c3a7048b69e1ac--\nlimitMAIL\n mail = Mail.new(data)\n #~ puts Mail::Encodings.decode_encode(mail.attachments[0].filename, :decode)\n expect(mail.attachments[0].filename).to eq \"Foto0009.jpg\"\n end\n\n end\nend\n\ndescribe \"attachment order\" do\n it \"should be preserved instead when content type exists\" do\n mail = Mail.new do\n to \"aaaa@aaaa.aaa\"\n from \"aaaa2@aaaa.aaa\"\n subject \"a subject\"\n date Time.now\n text_part do\n content_type 'text/plain; charset=UTF-8'\n body \"a \\nsimplebody\\n\"\n end\n end\n\n mail.attachments['test.zip'] = File.open(fixture('attachments', 'test.zip'), 'rb', &:read)\n mail.attachments['test.pdf'] = File.open(fixture('attachments', 'test.pdf'), 'rb', &:read)\n mail.attachments['test.gif'] = File.open(fixture('attachments', 'test.gif'), 'rb', &:read)\n mail.attachments['test.jpg'] = File.open(fixture('attachments', 'test.jpg'), 'rb', &:read)\n expect(mail.attachments[0].filename).to eq 'test.zip'\n expect(mail.attachments[1].filename).to eq 'test.pdf'\n expect(mail.attachments[2].filename).to eq 'test.gif'\n expect(mail.attachments[3].filename).to eq 'test.jpg'\n\n\n mail2 = Mail.new(mail.encoded)\n expect(mail2.attachments[0].filename).to eq 'test.zip'\n expect(mail2.attachments[1].filename).to eq 'test.pdf'\n expect(mail2.attachments[2].filename).to eq 'test.gif'\n expect(mail2.attachments[3].filename).to eq 'test.jpg'\n end\nend\n"},"repo_name":{"kind":"string","value":"kjg/mail"},"path":{"kind":"string","value":"spec/mail/attachments_list_spec.rb"},"language":{"kind":"string","value":"Ruby"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":13083,"string":"13,083"}}},{"rowIdx":61538286,"cells":{"code":{"kind":"string","value":"/*\n * Copyright 2016 Rethink Robotics\n *\n * Copyright 2016 Chris Smith\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 * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n'use strict';\n\nlet fs = require('fs');\nlet path = require('path');\n\nlet cmakePath = process.env.CMAKE_PREFIX_PATH;\nlet cmakePaths = cmakePath.split(':');\nlet jsMsgPath = 'share/gennodejs/ros';\n\nlet packagePaths = {};\n\nmodule.exports = function (messagePackage) {\n if (packagePaths.hasOwnProperty(messagePackage)) {\n return packagePaths[messagePackage];\n }\n // else\n const found = cmakePaths.some((cmakePath) => {\n let path_ = path.join(cmakePath, jsMsgPath, messagePackage, '_index.js');\n if (fs.existsSync(path_)) {\n packagePaths[messagePackage] = require(path_);\n return true;\n }\n return false;\n });\n if (found) {\n return packagePaths[messagePackage];\n }\n // else\n throw new Error('Unable to find message package ' + messagePackage + ' from CMAKE_PREFIX_PATH');\n};\n"},"repo_name":{"kind":"string","value":"tarquasso/softroboticfish6"},"path":{"kind":"string","value":"fish/pi/ros/catkin_ws/src/rosserial/devel/share/gennodejs/ros/rosserial_msgs/find.js"},"language":{"kind":"string","value":"JavaScript"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":1464,"string":"1,464"}}},{"rowIdx":61538287,"cells":{"code":{"kind":"string","value":"/**\n * @fileoverview Rule to flag wrapping non-iife in parens\n * @author Gyandeep Singh\n */\n\n\"use strict\";\n\n//------------------------------------------------------------------------------\n// Helpers\n//------------------------------------------------------------------------------\n\n/**\n * Checks whether or not a given node is an `Identifier` node which was named a given name.\n * @param {ASTNode} node - A node to check.\n * @param {string} name - An expected name of the node.\n * @returns {boolean} `true` if the node is an `Identifier` node which was named as expected.\n */\nfunction isIdentifier(node, name) {\n return node.type === \"Identifier\" && node.name === name;\n}\n\n/**\n * Checks whether or not a given node is an argument of a specified method call.\n * @param {ASTNode} node - A node to check.\n * @param {number} index - An expected index of the node in arguments.\n * @param {string} object - An expected name of the object of the method.\n * @param {string} property - An expected name of the method.\n * @returns {boolean} `true` if the node is an argument of the specified method call.\n */\nfunction isArgumentOfMethodCall(node, index, object, property) {\n const parent = node.parent;\n\n return (\n parent.type === \"CallExpression\" &&\n parent.callee.type === \"MemberExpression\" &&\n parent.callee.computed === false &&\n isIdentifier(parent.callee.object, object) &&\n isIdentifier(parent.callee.property, property) &&\n parent.arguments[index] === node\n );\n}\n\n/**\n * Checks whether or not a given node is a property descriptor.\n * @param {ASTNode} node - A node to check.\n * @returns {boolean} `true` if the node is a property descriptor.\n */\nfunction isPropertyDescriptor(node) {\n\n // Object.defineProperty(obj, \"foo\", {set: ...})\n if (isArgumentOfMethodCall(node, 2, \"Object\", \"defineProperty\") ||\n isArgumentOfMethodCall(node, 2, \"Reflect\", \"defineProperty\")\n ) {\n return true;\n }\n\n /*\n * Object.defineProperties(obj, {foo: {set: ...}})\n * Object.create(proto, {foo: {set: ...}})\n */\n const grandparent = node.parent.parent;\n\n return grandparent.type === \"ObjectExpression\" && (\n isArgumentOfMethodCall(grandparent, 1, \"Object\", \"create\") ||\n isArgumentOfMethodCall(grandparent, 1, \"Object\", \"defineProperties\")\n );\n}\n\n//------------------------------------------------------------------------------\n// Rule Definition\n//------------------------------------------------------------------------------\n\nmodule.exports = {\n meta: {\n docs: {\n description: \"enforce getter and setter pairs in objects\",\n category: \"Best Practices\",\n recommended: false,\n url: \"https://eslint.org/docs/rules/accessor-pairs\"\n },\n schema: [{\n type: \"object\",\n properties: {\n getWithoutSet: {\n type: \"boolean\"\n },\n setWithoutGet: {\n type: \"boolean\"\n }\n },\n additionalProperties: false\n }],\n messages: {\n getter: \"Getter is not present.\",\n setter: \"Setter is not present.\"\n }\n },\n create(context) {\n const config = context.options[0] || {};\n const checkGetWithoutSet = config.getWithoutSet === true;\n const checkSetWithoutGet = config.setWithoutGet !== false;\n\n /**\n * Checks a object expression to see if it has setter and getter both present or none.\n * @param {ASTNode} node The node to check.\n * @returns {void}\n * @private\n */\n function checkLonelySetGet(node) {\n let isSetPresent = false;\n let isGetPresent = false;\n const isDescriptor = isPropertyDescriptor(node);\n\n for (let i = 0, end = node.properties.length; i < end; i++) {\n const property = node.properties[i];\n\n let propToCheck = \"\";\n\n if (property.kind === \"init\") {\n if (isDescriptor && !property.computed) {\n propToCheck = property.key.name;\n }\n } else {\n propToCheck = property.kind;\n }\n\n switch (propToCheck) {\n case \"set\":\n isSetPresent = true;\n break;\n\n case \"get\":\n isGetPresent = true;\n break;\n\n default:\n\n // Do nothing\n }\n\n if (isSetPresent && isGetPresent) {\n break;\n }\n }\n\n if (checkSetWithoutGet && isSetPresent && !isGetPresent) {\n context.report({ node, messageId: \"getter\" });\n } else if (checkGetWithoutSet && isGetPresent && !isSetPresent) {\n context.report({ node, messageId: \"setter\" });\n }\n }\n\n return {\n ObjectExpression(node) {\n if (checkSetWithoutGet || checkGetWithoutSet) {\n checkLonelySetGet(node);\n }\n }\n };\n }\n};\n"},"repo_name":{"kind":"string","value":"EdwardStudy/myghostblog"},"path":{"kind":"string","value":"versions/1.25.7/node_modules/eslint/lib/rules/accessor-pairs.js"},"language":{"kind":"string","value":"JavaScript"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":5257,"string":"5,257"}}},{"rowIdx":61538288,"cells":{"code":{"kind":"string","value":"// Copyright 2014 The Chromium Authors. All rights reserved.\n// Use of this source code is governed by a BSD-style license that can be\n// found in the LICENSE file.\n\n// This is the version of the Android-specific Chromium linker that uses\n// the crazy linker to load libraries.\n\n// This source code *cannot* depend on anything from base/ or the C++\n// STL, to keep the final library small, and avoid ugly dependency issues.\n\n#include \"legacy_linker_jni.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"linker_jni.h\"\n\nnamespace chromium_android_linker {\nnamespace {\n\n// Retrieve the SDK build version and pass it into the crazy linker. This\n// needs to be done early in initialization, before any other crazy linker\n// code is run.\n// |env| is the current JNI environment handle.\n// On success, return true.\nbool InitSDKVersionInfo(JNIEnv* env) {\n jint value = 0;\n if (!InitStaticInt(env, \"android/os/Build$VERSION\", \"SDK_INT\", &value))\n return false;\n\n crazy_set_sdk_build_version(static_cast(value));\n LOG_INFO(\"Set SDK build version to %d\", static_cast(value));\n\n return true;\n}\n\n// The linker uses a single crazy_context_t object created on demand.\n// There is no need to protect this against concurrent access, locking\n// is already handled on the Java side.\ncrazy_context_t* GetCrazyContext() {\n static crazy_context_t* s_crazy_context = nullptr;\n\n if (!s_crazy_context) {\n // Create new context.\n s_crazy_context = crazy_context_create();\n\n // Ensure libraries located in the same directory as the linker\n // can be loaded before system ones.\n crazy_context_add_search_path_for_address(\n s_crazy_context, reinterpret_cast(&s_crazy_context));\n }\n\n return s_crazy_context;\n}\n\n// A scoped crazy_library_t that automatically closes the handle\n// on scope exit, unless Release() has been called.\nclass ScopedLibrary {\n public:\n ScopedLibrary() : lib_(nullptr) {}\n\n ~ScopedLibrary() {\n if (lib_)\n crazy_library_close_with_context(lib_, GetCrazyContext());\n }\n\n crazy_library_t* Get() { return lib_; }\n\n crazy_library_t** GetPtr() { return &lib_; }\n\n crazy_library_t* Release() {\n crazy_library_t* ret = lib_;\n lib_ = nullptr;\n return ret;\n }\n\n private:\n crazy_library_t* lib_;\n};\n\ntemplate \nbool GenericLoadLibrary(JNIEnv* env,\n const char* library_name,\n jlong load_address,\n jobject lib_info_obj,\n const LibraryOpener& opener) {\n LOG_INFO(\"Called for %s, at address 0x%llx\", library_name, load_address);\n crazy_context_t* context = GetCrazyContext();\n\n if (!IsValidAddress(load_address)) {\n LOG_ERROR(\"Invalid address 0x%llx\", load_address);\n return false;\n }\n\n // Set the desired load address (0 means randomize it).\n crazy_context_set_load_address(context, static_cast(load_address));\n\n ScopedLibrary library;\n if (!opener.Open(library.GetPtr(), library_name, context)) {\n return false;\n }\n\n crazy_library_info_t info;\n if (!crazy_library_get_info(library.Get(), context, &info)) {\n LOG_ERROR(\"Could not get library information for %s: %s\",\n library_name, crazy_context_get_error(context));\n return false;\n }\n\n // Release library object to keep it alive after the function returns.\n library.Release();\n\n s_lib_info_fields.SetLoadInfo(env,\n lib_info_obj,\n info.load_address, info.load_size);\n LOG_INFO(\"Success loading library %s\", library_name);\n return true;\n}\n\n// Used for opening the library in a regular file.\nclass FileLibraryOpener {\n public:\n bool Open(crazy_library_t** library,\n const char* library_name,\n crazy_context_t* context) const;\n};\n\nbool FileLibraryOpener::Open(crazy_library_t** library,\n const char* library_name,\n crazy_context_t* context) const {\n if (!crazy_library_open(library, library_name, context)) {\n LOG_ERROR(\"Could not open %s: %s\",\n library_name, crazy_context_get_error(context));\n return false;\n }\n return true;\n}\n\n// Used for opening the library in a zip file.\nclass ZipLibraryOpener {\n public:\n explicit ZipLibraryOpener(const char* zip_file) : zip_file_(zip_file) { }\n bool Open(crazy_library_t** library,\n const char* library_name,\n crazy_context_t* context) const;\n private:\n const char* zip_file_;\n};\n\nbool ZipLibraryOpener::Open(crazy_library_t** library,\n const char* library_name,\n crazy_context_t* context) const {\n if (!crazy_library_open_in_zip_file(library,\n zip_file_,\n library_name,\n context)) {\n LOG_ERROR(\"Could not open %s in zip file %s: %s\",\n library_name, zip_file_, crazy_context_get_error(context));\n return false;\n }\n return true;\n}\n\n// Load a library with the chromium linker. This will also call its\n// JNI_OnLoad() method, which shall register its methods. Note that\n// lazy native method resolution will _not_ work after this, because\n// Dalvik uses the system's dlsym() which won't see the new library,\n// so explicit registration is mandatory.\n//\n// |env| is the current JNI environment handle.\n// |clazz| is the static class handle for org.chromium.base.Linker,\n// and is ignored here.\n// |library_name| is the library name (e.g. libfoo.so).\n// |load_address| is an explicit load address.\n// |library_info| is a LibInfo handle used to communicate information\n// with the Java side.\n// Return true on success.\njboolean LoadLibrary(JNIEnv* env,\n jclass clazz,\n jstring library_name,\n jlong load_address,\n jobject lib_info_obj) {\n String lib_name(env, library_name);\n FileLibraryOpener opener;\n\n return GenericLoadLibrary(env,\n lib_name.c_str(),\n static_cast(load_address),\n lib_info_obj,\n opener);\n}\n\n// Load a library from a zipfile with the chromium linker. The\n// library in the zipfile must be uncompressed and page aligned.\n// The basename of the library is given. The library is expected\n// to be lib//crazy.. The used will be the\n// same as the abi for this linker. The \"crazy.\" prefix is included\n// so that the Android Package Manager doesn't extract the library into\n// /data/app-lib.\n//\n// Loading the library will also call its JNI_OnLoad() method, which\n// shall register its methods. Note that lazy native method resolution\n// will _not_ work after this, because Dalvik uses the system's dlsym()\n// which won't see the new library, so explicit registration is mandatory.\n//\n// |env| is the current JNI environment handle.\n// |clazz| is the static class handle for org.chromium.base.Linker,\n// and is ignored here.\n// |zipfile_name| is the filename of the zipfile containing the library.\n// |library_name| is the library base name (e.g. libfoo.so).\n// |load_address| is an explicit load address.\n// |library_info| is a LibInfo handle used to communicate information\n// with the Java side.\n// Returns true on success.\njboolean LoadLibraryInZipFile(JNIEnv* env,\n jclass clazz,\n jstring zipfile_name,\n jstring library_name,\n jlong load_address,\n jobject lib_info_obj) {\n String zipfile_name_str(env, zipfile_name);\n String lib_name(env, library_name);\n ZipLibraryOpener opener(zipfile_name_str.c_str());\n\n return GenericLoadLibrary(env,\n lib_name.c_str(),\n static_cast(load_address),\n lib_info_obj,\n opener);\n}\n\n// Class holding the Java class and method ID for the Java side Linker\n// postCallbackOnMainThread method.\nstruct JavaCallbackBindings_class {\n jclass clazz;\n jmethodID method_id;\n\n // Initialize an instance.\n bool Init(JNIEnv* env, jclass linker_class) {\n clazz = reinterpret_cast(env->NewGlobalRef(linker_class));\n return InitStaticMethodId(env,\n linker_class,\n \"postCallbackOnMainThread\",\n \"(J)V\",\n &method_id);\n }\n};\n\nstatic JavaCallbackBindings_class s_java_callback_bindings;\n\n// Designated receiver function for callbacks from Java. Its name is known\n// to the Java side.\n// |env| is the current JNI environment handle and is ignored here.\n// |clazz| is the static class handle for org.chromium.base.Linker,\n// and is ignored here.\n// |arg| is a pointer to an allocated crazy_callback_t, deleted after use.\nvoid RunCallbackOnUiThread(JNIEnv* env, jclass clazz, jlong arg) {\n crazy_callback_t* callback = reinterpret_cast(arg);\n\n LOG_INFO(\"Called back from java with handler %p, opaque %p\",\n callback->handler, callback->opaque);\n\n crazy_callback_run(callback);\n delete callback;\n}\n\n// Request a callback from Java. The supplied crazy_callback_t is valid only\n// for the duration of this call, so we copy it to a newly allocated\n// crazy_callback_t and then call the Java side's postCallbackOnMainThread.\n// This will call back to to our RunCallbackOnUiThread some time\n// later on the UI thread.\n// |callback_request| is a crazy_callback_t.\n// |poster_opaque| is unused.\n// Returns true if the callback request succeeds.\nstatic bool PostForLaterExecution(crazy_callback_t* callback_request,\n void* poster_opaque UNUSED) {\n crazy_context_t* context = GetCrazyContext();\n\n JavaVM* vm;\n int minimum_jni_version;\n crazy_context_get_java_vm(context,\n reinterpret_cast(&vm),\n &minimum_jni_version);\n\n // Do not reuse JNIEnv from JNI_OnLoad, but retrieve our own.\n JNIEnv* env;\n if (JNI_OK != vm->GetEnv(\n reinterpret_cast(&env), minimum_jni_version)) {\n LOG_ERROR(\"Could not create JNIEnv\");\n return false;\n }\n\n // Copy the callback; the one passed as an argument may be temporary.\n crazy_callback_t* callback = new crazy_callback_t();\n *callback = *callback_request;\n\n LOG_INFO(\"Calling back to java with handler %p, opaque %p\",\n callback->handler, callback->opaque);\n\n jlong arg = static_cast(reinterpret_cast(callback));\n\n env->CallStaticVoidMethod(\n s_java_callback_bindings.clazz, s_java_callback_bindings.method_id, arg);\n\n // Back out and return false if we encounter a JNI exception.\n if (env->ExceptionCheck() == JNI_TRUE) {\n env->ExceptionDescribe();\n env->ExceptionClear();\n delete callback;\n return false;\n }\n\n return true;\n}\n\njboolean CreateSharedRelro(JNIEnv* env,\n jclass clazz,\n jstring library_name,\n jlong load_address,\n jobject lib_info_obj) {\n String lib_name(env, library_name);\n\n LOG_INFO(\"Called for %s\", lib_name.c_str());\n\n if (!IsValidAddress(load_address)) {\n LOG_ERROR(\"Invalid address 0x%llx\", load_address);\n return false;\n }\n\n ScopedLibrary library;\n if (!crazy_library_find_by_name(lib_name.c_str(), library.GetPtr())) {\n LOG_ERROR(\"Could not find %s\", lib_name.c_str());\n return false;\n }\n\n crazy_context_t* context = GetCrazyContext();\n size_t relro_start = 0;\n size_t relro_size = 0;\n int relro_fd = -1;\n\n if (!crazy_library_create_shared_relro(library.Get(),\n context,\n static_cast(load_address),\n &relro_start,\n &relro_size,\n &relro_fd)) {\n LOG_ERROR(\"Could not create shared RELRO sharing for %s: %s\\n\",\n lib_name.c_str(), crazy_context_get_error(context));\n return false;\n }\n\n s_lib_info_fields.SetRelroInfo(env,\n lib_info_obj,\n relro_start, relro_size, relro_fd);\n return true;\n}\n\njboolean UseSharedRelro(JNIEnv* env,\n jclass clazz,\n jstring library_name,\n jobject lib_info_obj) {\n String lib_name(env, library_name);\n\n LOG_INFO(\"Called for %s, lib_info_ref=%p\", lib_name.c_str(), lib_info_obj);\n\n ScopedLibrary library;\n if (!crazy_library_find_by_name(lib_name.c_str(), library.GetPtr())) {\n LOG_ERROR(\"Could not find %s\", lib_name.c_str());\n return false;\n }\n\n crazy_context_t* context = GetCrazyContext();\n size_t relro_start = 0;\n size_t relro_size = 0;\n int relro_fd = -1;\n s_lib_info_fields.GetRelroInfo(env,\n lib_info_obj,\n &relro_start, &relro_size, &relro_fd);\n\n LOG_INFO(\"library=%s relro start=%p size=%p fd=%d\",\n lib_name.c_str(), (void*)relro_start, (void*)relro_size, relro_fd);\n\n if (!crazy_library_use_shared_relro(library.Get(),\n context,\n relro_start, relro_size, relro_fd)) {\n LOG_ERROR(\"Could not use shared RELRO for %s: %s\",\n lib_name.c_str(), crazy_context_get_error(context));\n return false;\n }\n\n LOG_INFO(\"Library %s using shared RELRO section!\", lib_name.c_str());\n\n return true;\n}\n\nconst JNINativeMethod kNativeMethods[] = {\n {\"nativeLoadLibrary\",\n \"(\"\n \"Ljava/lang/String;\"\n \"J\"\n \"Lorg/chromium/base/library_loader/Linker$LibInfo;\"\n \")\"\n \"Z\",\n reinterpret_cast(&LoadLibrary)},\n {\"nativeLoadLibraryInZipFile\",\n \"(\"\n \"Ljava/lang/String;\"\n \"Ljava/lang/String;\"\n \"J\"\n \"Lorg/chromium/base/library_loader/Linker$LibInfo;\"\n \")\"\n \"Z\",\n reinterpret_cast(&LoadLibraryInZipFile)},\n {\"nativeRunCallbackOnUiThread\",\n \"(\"\n \"J\"\n \")\"\n \"V\",\n reinterpret_cast(&RunCallbackOnUiThread)},\n {\"nativeCreateSharedRelro\",\n \"(\"\n \"Ljava/lang/String;\"\n \"J\"\n \"Lorg/chromium/base/library_loader/Linker$LibInfo;\"\n \")\"\n \"Z\",\n reinterpret_cast(&CreateSharedRelro)},\n {\"nativeUseSharedRelro\",\n \"(\"\n \"Ljava/lang/String;\"\n \"Lorg/chromium/base/library_loader/Linker$LibInfo;\"\n \")\"\n \"Z\",\n reinterpret_cast(&UseSharedRelro)},\n};\n\nconst size_t kNumNativeMethods =\n sizeof(kNativeMethods) / sizeof(kNativeMethods[0]);\n\n} // namespace\n\nbool LegacyLinkerJNIInit(JavaVM* vm, JNIEnv* env) {\n LOG_INFO(\"Entering\");\n\n // Initialize SDK version info.\n LOG_INFO(\"Retrieving SDK version info\");\n if (!InitSDKVersionInfo(env))\n return false;\n\n // Register native methods.\n jclass linker_class;\n if (!InitClassReference(env,\n \"org/chromium/base/library_loader/LegacyLinker\",\n &linker_class))\n return false;\n\n LOG_INFO(\"Registering native methods\");\n if (env->RegisterNatives(linker_class, kNativeMethods, kNumNativeMethods) < 0)\n return false;\n\n // Resolve and save the Java side Linker callback class and method.\n LOG_INFO(\"Resolving callback bindings\");\n if (!s_java_callback_bindings.Init(env, linker_class)) {\n return false;\n }\n\n // Save JavaVM* handle into context.\n crazy_context_t* context = GetCrazyContext();\n crazy_context_set_java_vm(context, vm, JNI_VERSION_1_4);\n\n // Register the function that the crazy linker can call to post code\n // for later execution.\n crazy_context_set_callback_poster(context, &PostForLaterExecution, nullptr);\n\n return true;\n}\n\n} // namespace chromium_android_linker\n"},"repo_name":{"kind":"string","value":"junhuac/MQUIC"},"path":{"kind":"string","value":"src/base/android/linker/legacy_linker_jni.cc"},"language":{"kind":"string","value":"C++"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":16030,"string":"16,030"}}},{"rowIdx":61538289,"cells":{"code":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\nusing Microsoft.Win32.SafeHandles;\n\nusing System.Diagnostics;\nusing System.Threading;\n\nnamespace System.Net.Sockets\n{\n // This class implements a safe socket handle.\n // It uses an inner and outer SafeHandle to do so. The inner\n // SafeHandle holds the actual socket, but only ever has one\n // reference to it. The outer SafeHandle guards the inner\n // SafeHandle with real ref counting. When the outer SafeHandle\n // is cleaned up, it releases the inner SafeHandle - since\n // its ref is the only ref to the inner SafeHandle, it deterministically\n // gets closed at that point - no races with concurrent IO calls.\n // This allows Close() on the outer SafeHandle to deterministically\n // close the inner SafeHandle, in turn allowing the inner SafeHandle\n // to block the user thread in case a graceful close has been\n // requested. (It's not legal to block any other thread - such closes\n // are always abortive.)\n internal partial class SafeCloseSocket :\n#if DEBUG\n DebugSafeHandleMinusOneIsInvalid\n#else\n SafeHandleMinusOneIsInvalid\n#endif\n {\n protected SafeCloseSocket() : base(true) { }\n\n private InnerSafeCloseSocket _innerSocket;\n private volatile bool _released;\n#if DEBUG\n private InnerSafeCloseSocket _innerSocketCopy;\n#endif\n\n public override bool IsInvalid\n {\n get\n {\n return IsClosed || base.IsInvalid;\n }\n }\n\n#if DEBUG\n public void AddRef()\n {\n try\n {\n // The inner socket can be closed by CloseAsIs and when SafeHandle runs ReleaseHandle.\n InnerSafeCloseSocket innerSocket = Volatile.Read(ref _innerSocket);\n if (innerSocket != null)\n {\n innerSocket.AddRef();\n }\n }\n catch (Exception e)\n {\n Debug.Fail(\"SafeCloseSocket.AddRef after inner socket disposed.\" + e);\n }\n }\n\n public void Release()\n {\n try\n {\n // The inner socket can be closed by CloseAsIs and when SafeHandle runs ReleaseHandle.\n InnerSafeCloseSocket innerSocket = Volatile.Read(ref _innerSocket);\n if (innerSocket != null)\n {\n innerSocket.Release();\n }\n }\n catch (Exception e)\n {\n Debug.Fail(\"SafeCloseSocket.Release after inner socket disposed.\" + e);\n }\n }\n#endif\n\n private void SetInnerSocket(InnerSafeCloseSocket socket)\n {\n _innerSocket = socket;\n SetHandle(socket.DangerousGetHandle());\n#if DEBUG\n _innerSocketCopy = socket;\n#endif\n }\n\n private static SafeCloseSocket CreateSocket(InnerSafeCloseSocket socket)\n {\n SafeCloseSocket ret = new SafeCloseSocket();\n CreateSocket(socket, ret);\n\n if (NetEventSource.IsEnabled) NetEventSource.Info(null, ret);\n\n return ret;\n }\n\n protected static void CreateSocket(InnerSafeCloseSocket socket, SafeCloseSocket target)\n {\n if (socket != null && socket.IsInvalid)\n {\n target.SetHandleAsInvalid();\n return;\n }\n\n bool b = false;\n try\n {\n socket.DangerousAddRef(ref b);\n }\n catch\n {\n if (b)\n {\n socket.DangerousRelease();\n b = false;\n }\n }\n finally\n {\n if (b)\n {\n target.SetInnerSocket(socket);\n socket.Dispose();\n }\n else\n {\n target.SetHandleAsInvalid();\n }\n }\n }\n\n protected override bool ReleaseHandle()\n {\n if (NetEventSource.IsEnabled) NetEventSource.Info(this, $\"_innerSocket={_innerSocket}\");\n\n _released = true;\n InnerSafeCloseSocket innerSocket = _innerSocket == null ? null : Interlocked.Exchange(ref _innerSocket, null);\n\n#if DEBUG\n // On AppDomain unload we may still have pending Overlapped operations.\n // ThreadPoolBoundHandle should handle this scenario by canceling them.\n innerSocket?.LogRemainingOperations();\n#endif\n\n InnerReleaseHandle();\n innerSocket?.DangerousRelease();\n\n return true;\n }\n\n internal void CloseAsIs()\n {\n if (NetEventSource.IsEnabled) NetEventSource.Info(this, $\"_innerSocket={_innerSocket}\");\n\n#if DEBUG\n // If this throws it could be very bad.\n try\n {\n#endif\n InnerSafeCloseSocket innerSocket = _innerSocket == null ? null : Interlocked.Exchange(ref _innerSocket, null);\n\n Dispose();\n if (innerSocket != null)\n {\n // Wait until it's safe.\n SpinWait sw = new SpinWait();\n while (!_released)\n {\n sw.SpinOnce();\n }\n\n // Now free it with blocking.\n innerSocket.BlockingRelease();\n }\n\n InnerReleaseHandle();\n#if DEBUG\n }\n catch (Exception exception) when (!ExceptionCheck.IsFatal(exception))\n {\n NetEventSource.Fail(this, $\"handle:{handle}, error:{exception}\");\n throw;\n }\n#endif\n }\n\n internal sealed partial class InnerSafeCloseSocket : SafeHandleMinusOneIsInvalid\n {\n private InnerSafeCloseSocket() : base(true) { }\n\n private bool _blockable;\n\n public override bool IsInvalid\n {\n get\n {\n return IsClosed || base.IsInvalid;\n }\n }\n\n // This method is implicitly reliable and called from a CER.\n protected override bool ReleaseHandle()\n {\n bool ret = false;\n\n#if DEBUG\n try\n {\n#endif\n if (NetEventSource.IsEnabled) NetEventSource.Info(this, $\"handle:{handle}\");\n\n SocketError errorCode = InnerReleaseHandle();\n return ret = errorCode == SocketError.Success;\n#if DEBUG\n }\n catch (Exception exception)\n {\n if (!ExceptionCheck.IsFatal(exception))\n {\n NetEventSource.Fail(this, $\"handle:{handle}, error:{exception}\");\n }\n\n ret = true; // Avoid a second assert.\n throw;\n }\n finally\n {\n _closeSocketThread = Environment.CurrentManagedThreadId;\n _closeSocketTick = Environment.TickCount;\n if (!ret)\n {\n NetEventSource.Fail(this, $\"ReleaseHandle failed. handle:{handle}\");\n }\n }\n#endif\n }\n\n#if DEBUG\n private IntPtr _closeSocketHandle;\n private SocketError _closeSocketResult = unchecked((SocketError)0xdeadbeef);\n private SocketError _closeSocketLinger = unchecked((SocketError)0xdeadbeef);\n private int _closeSocketThread;\n private int _closeSocketTick;\n\n private int _refCount = 0;\n\n public void AddRef()\n {\n Interlocked.Increment(ref _refCount);\n }\n\n public void Release()\n {\n Interlocked.MemoryBarrier();\n Debug.Assert(_refCount > 0, \"InnerSafeCloseSocket: Release() called more times than AddRef\");\n Interlocked.Decrement(ref _refCount);\n }\n\n public void LogRemainingOperations()\n {\n Interlocked.MemoryBarrier();\n if (NetEventSource.IsEnabled) NetEventSource.Info(this, $\"Releasing with pending operations: {_refCount}\");\n }\n#endif\n\n // Use this method to close the socket handle using the linger options specified on the socket.\n // Guaranteed to only be called once, under a CER, and not if regular DangerousRelease is called.\n internal void BlockingRelease()\n {\n#if DEBUG\n // Expected to have outstanding operations such as Accept.\n LogRemainingOperations();\n#endif\n\n _blockable = true;\n DangerousRelease();\n }\n }\n }\n}\n"},"repo_name":{"kind":"string","value":"nbarbettini/corefx"},"path":{"kind":"string","value":"src/Common/src/System/Net/SafeCloseSocket.cs"},"language":{"kind":"string","value":"C#"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":9141,"string":"9,141"}}},{"rowIdx":61538290,"cells":{"code":{"kind":"string","value":"// Package api provides a generic, low-level WebDriver API client for Go.\n// All methods map directly to endpoints of the WebDriver Wire Protocol:\n// https://code.google.com/p/selenium/wiki/JsonWireProtocol\n//\n// This package was previously internal to the agouti package. It currently\n// does not have a fixed API, but this will change in the near future\n// (with the addition of adequate documentation).\npackage api\n"},"repo_name":{"kind":"string","value":"johanbrandhorst/protobuf"},"path":{"kind":"string","value":"vendor/github.com/sclevine/agouti/api/api.go"},"language":{"kind":"string","value":"GO"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":418,"string":"418"}}},{"rowIdx":61538291,"cells":{"code":{"kind":"string","value":"module ActiveRecord\n module AttributeMethods\n module Serialization\n extend ActiveSupport::Concern\n\n module ClassMethods\n # If you have an attribute that needs to be saved to the database as an\n # object, and retrieved as the same object, then specify the name of that\n # attribute using this method and it will be handled automatically. The\n # serialization is done through YAML. If +class_name+ is specified, the\n # serialized object must be of that class on assignment and retrieval.\n # Otherwise SerializationTypeMismatch will be raised.\n #\n # Empty objects as {}, in the case of +Hash+, or [], in the case of\n # +Array+, will always be persisted as null.\n #\n # Keep in mind that database adapters handle certain serialization tasks\n # for you. For instance: +json+ and +jsonb+ types in PostgreSQL will be\n # converted between JSON object/array syntax and Ruby +Hash+ or +Array+\n # objects transparently. There is no need to use #serialize in this\n # case.\n #\n # For more complex cases, such as conversion to or from your application\n # domain objects, consider using the ActiveRecord::Attributes API.\n #\n # ==== Parameters\n #\n # * +attr_name+ - The field name that should be serialized.\n # * +class_name_or_coder+ - Optional, a coder object, which responds to `.load` / `.dump`\n # or a class name that the object type should be equal to.\n #\n # ==== Example\n #\n # # Serialize a preferences attribute.\n # class User < ActiveRecord::Base\n # serialize :preferences\n # end\n #\n # # Serialize preferences using JSON as coder.\n # class User < ActiveRecord::Base\n # serialize :preferences, JSON\n # end\n #\n # # Serialize preferences as Hash using YAML coder.\n # class User < ActiveRecord::Base\n # serialize :preferences, Hash\n # end\n def serialize(attr_name, class_name_or_coder = Object)\n # When ::JSON is used, force it to go through the Active Support JSON encoder\n # to ensure special objects (e.g. Active Record models) are dumped correctly\n # using the #as_json hook.\n coder = if class_name_or_coder == ::JSON\n Coders::JSON\n elsif [:load, :dump].all? { |x| class_name_or_coder.respond_to?(x) }\n class_name_or_coder\n else\n Coders::YAMLColumn.new(class_name_or_coder)\n end\n\n decorate_attribute_type(attr_name, :serialize) do |type|\n Type::Serialized.new(type, coder)\n end\n end\n end\n end\n end\nend\n"},"repo_name":{"kind":"string","value":"afuerstenau/daily-notes"},"path":{"kind":"string","value":"vendor/cache/ruby/2.5.0/gems/activerecord-5.0.6/lib/active_record/attribute_methods/serialization.rb"},"language":{"kind":"string","value":"Ruby"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":2841,"string":"2,841"}}},{"rowIdx":61538292,"cells":{"code":{"kind":"string","value":"//------------------------------------------------------------------------------\n// \n// Copyright (c) Microsoft Corporation. All rights reserved.\n// \n//------------------------------------------------------------------------------\n\nnamespace System.Net.Configuration\n{\n using System;\n using System.Configuration;\n using System.Reflection;\n using System.Security.Permissions;\n\n public sealed class PerformanceCountersElement : ConfigurationElement\n {\n public PerformanceCountersElement()\n {\n this.properties.Add(this.enabled);\n }\n \n [ConfigurationProperty(ConfigurationStrings.Enabled, DefaultValue=false)]\n public bool Enabled\n {\n get { return (bool) this[this.enabled]; }\n set { this[this.enabled] = value; }\n }\n\n protected override ConfigurationPropertyCollection Properties\n {\n get \n {\n return this.properties;\n }\n }\n\n ConfigurationPropertyCollection properties = new ConfigurationPropertyCollection();\n\n readonly ConfigurationProperty enabled =\n new ConfigurationProperty(ConfigurationStrings.Enabled, typeof(bool), false,\n ConfigurationPropertyOptions.None);\n }\n}\n"},"repo_name":{"kind":"string","value":"sekcheong/referencesource"},"path":{"kind":"string","value":"System/net/System/Net/Configuration/PerformanceCountersElement.cs"},"language":{"kind":"string","value":"C#"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":1389,"string":"1,389"}}},{"rowIdx":61538293,"cells":{"code":{"kind":"string","value":"//used for the media picker dialog\r\nangular.module(\"umbraco\")\r\n .controller(\"Umbraco.Dialogs.MediaPickerController\",\r\n function ($scope, mediaResource, umbRequestHelper, entityResource, $log, mediaHelper, eventsService, treeService, $cookies, $element, $timeout, notificationsService) {\r\n\r\n var dialogOptions = $scope.dialogOptions;\r\n\r\n $scope.onlyImages = dialogOptions.onlyImages;\r\n $scope.showDetails = dialogOptions.showDetails;\r\n $scope.multiPicker = (dialogOptions.multiPicker && dialogOptions.multiPicker !== \"0\") ? true : false;\r\n $scope.startNodeId = dialogOptions.startNodeId ? dialogOptions.startNodeId : -1;\r\n $scope.cropSize = dialogOptions.cropSize;\r\n \r\n $scope.filesUploading = 0;\r\n $scope.dropping = false;\r\n $scope.progress = 0;\r\n\r\n $scope.options = {\r\n url: umbRequestHelper.getApiUrl(\"mediaApiBaseUrl\", \"PostAddFile\") + \"?origin=blueimp\",\r\n autoUpload: true,\r\n dropZone: $element.find(\".umb-dialogs-mediapicker.browser\"),\r\n fileInput: $element.find(\"input.uploader\"),\r\n formData: {\r\n currentFolder: -1\r\n }\r\n };\r\n\r\n //preload selected item\r\n $scope.target = undefined;\r\n if(dialogOptions.currentTarget){\r\n $scope.target = dialogOptions.currentTarget;\r\n }\r\n\r\n $scope.submitFolder = function(e) {\r\n if (e.keyCode === 13) {\r\n e.preventDefault();\r\n $scope.showFolderInput = false;\r\n\r\n mediaResource\r\n .addFolder($scope.newFolderName, $scope.options.formData.currentFolder)\r\n .then(function(data) {\r\n\r\n //we've added a new folder so lets clear the tree cache for that specific item\r\n treeService.clearCache({\r\n cacheKey: \"__media\", //this is the main media tree cache key\r\n childrenOf: data.parentId //clear the children of the parent\r\n });\r\n\r\n $scope.gotoFolder(data);\r\n });\r\n }\r\n };\r\n\r\n $scope.gotoFolder = function(folder) {\r\n\r\n if(!folder){\r\n folder = {id: -1, name: \"Media\", icon: \"icon-folder\"};\r\n }\r\n\r\n if (folder.id > 0) {\r\n entityResource.getAncestors(folder.id, \"media\")\r\n .then(function(anc) {\r\n // anc.splice(0,1); \r\n $scope.path = _.filter(anc, function (f) {\r\n return f.path.indexOf($scope.startNodeId) !== -1;\r\n });\r\n });\r\n }\r\n else {\r\n $scope.path = [];\r\n }\r\n\r\n //mediaResource.rootMedia()\r\n mediaResource.getChildren(folder.id)\r\n .then(function(data) {\r\n $scope.searchTerm = \"\";\r\n $scope.images = data.items ? data.items : [];\r\n });\r\n\r\n $scope.options.formData.currentFolder = folder.id;\r\n $scope.currentFolder = folder; \r\n };\r\n\r\n //This executes prior to the whole processing which we can use to get the UI going faster,\r\n //this also gives us the start callback to invoke to kick of the whole thing\r\n $scope.$on('fileuploadadd', function (e, data) {\r\n $scope.$apply(function () {\r\n $scope.filesUploading++;\r\n });\r\n });\r\n\r\n //when one is finished\r\n $scope.$on('fileuploaddone', function (e, data) {\r\n $scope.filesUploading--;\r\n if ($scope.filesUploading == 0) {\r\n $scope.$apply(function () {\r\n $scope.progress = 0;\r\n $scope.gotoFolder($scope.currentFolder);\r\n });\r\n }\r\n //Show notifications!!!!\r\n if (data.result && data.result.notifications && angular.isArray(data.result.notifications)) {\r\n for (var n = 0; n < data.result.notifications.length; n++) {\r\n notificationsService.showNotification(data.result.notifications[n]);\r\n }\r\n }\r\n });\r\n\r\n // All these sit-ups are to add dropzone area and make sure it gets removed if dragging is aborted! \r\n $scope.$on('fileuploaddragover', function (e, data) {\r\n if (!$scope.dragClearTimeout) {\r\n $scope.$apply(function () {\r\n $scope.dropping = true;\r\n });\r\n }\r\n else {\r\n $timeout.cancel($scope.dragClearTimeout);\r\n }\r\n $scope.dragClearTimeout = $timeout(function () {\r\n $scope.dropping = null;\r\n $scope.dragClearTimeout = null;\r\n }, 300);\r\n });\r\n\r\n $scope.clickHandler = function(image, ev, select) {\r\n ev.preventDefault();\r\n \r\n if (image.isFolder && !select) {\r\n $scope.gotoFolder(image);\r\n }else{\r\n eventsService.emit(\"dialogs.mediaPicker.select\", image);\r\n \r\n //we have 3 options add to collection (if multi) show details, or submit it right back to the callback\r\n if ($scope.multiPicker) {\r\n $scope.select(image);\r\n image.cssclass = ($scope.dialogData.selection.indexOf(image) > -1) ? \"selected\" : \"\";\r\n }else if($scope.showDetails) {\r\n $scope.target= image;\r\n $scope.target.url = mediaHelper.resolveFile(image);\r\n }else{\r\n $scope.submit(image);\r\n }\r\n }\r\n };\r\n\r\n $scope.exitDetails = function(){\r\n if(!$scope.currentFolder){\r\n $scope.gotoFolder();\r\n }\r\n\r\n $scope.target = undefined;\r\n };\r\n\r\n \r\n\r\n //default root item\r\n if(!$scope.target){\r\n $scope.gotoFolder({ id: $scope.startNodeId, name: \"Media\", icon: \"icon-folder\" }); \r\n }\r\n });"},"repo_name":{"kind":"string","value":"gregoriusxu/Umbraco-CMS"},"path":{"kind":"string","value":"src/Umbraco.Web.UI.Client/src/views/common/dialogs/mediapicker.controller.js"},"language":{"kind":"string","value":"JavaScript"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":6762,"string":"6,762"}}},{"rowIdx":61538294,"cells":{"code":{"kind":"string","value":"package volume\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"testing\"\n\n\t\"github.com/docker/docker/api/types\"\n\t\"github.com/docker/docker/cli/internal/test\"\n\t\"github.com/pkg/errors\"\n\t// Import builders to get the builder function as package function\n\t. \"github.com/docker/docker/cli/internal/test/builders\"\n\t\"github.com/docker/docker/pkg/testutil/assert\"\n\t\"github.com/docker/docker/pkg/testutil/golden\"\n)\n\nfunc TestVolumeInspectErrors(t *testing.T) {\n\ttestCases := []struct {\n\t\targs []string\n\t\tflags map[string]string\n\t\tvolumeInspectFunc func(volumeID string) (types.Volume, error)\n\t\texpectedError string\n\t}{\n\t\t{\n\t\t\texpectedError: \"requires at least 1 argument\",\n\t\t},\n\t\t{\n\t\t\targs: []string{\"foo\"},\n\t\t\tvolumeInspectFunc: func(volumeID string) (types.Volume, error) {\n\t\t\t\treturn types.Volume{}, errors.Errorf(\"error while inspecting the volume\")\n\t\t\t},\n\t\t\texpectedError: \"error while inspecting the volume\",\n\t\t},\n\t\t{\n\t\t\targs: []string{\"foo\"},\n\t\t\tflags: map[string]string{\n\t\t\t\t\"format\": \"{{invalid format}}\",\n\t\t\t},\n\t\t\texpectedError: \"Template parsing error\",\n\t\t},\n\t\t{\n\t\t\targs: []string{\"foo\", \"bar\"},\n\t\t\tvolumeInspectFunc: func(volumeID string) (types.Volume, error) {\n\t\t\t\tif volumeID == \"foo\" {\n\t\t\t\t\treturn types.Volume{\n\t\t\t\t\t\tName: \"foo\",\n\t\t\t\t\t}, nil\n\t\t\t\t}\n\t\t\t\treturn types.Volume{}, errors.Errorf(\"error while inspecting the volume\")\n\t\t\t},\n\t\t\texpectedError: \"error while inspecting the volume\",\n\t\t},\n\t}\n\tfor _, tc := range testCases {\n\t\tbuf := new(bytes.Buffer)\n\t\tcmd := newInspectCommand(\n\t\t\ttest.NewFakeCli(&fakeClient{\n\t\t\t\tvolumeInspectFunc: tc.volumeInspectFunc,\n\t\t\t}, buf),\n\t\t)\n\t\tcmd.SetArgs(tc.args)\n\t\tfor key, value := range tc.flags {\n\t\t\tcmd.Flags().Set(key, value)\n\t\t}\n\t\tcmd.SetOutput(ioutil.Discard)\n\t\tassert.Error(t, cmd.Execute(), tc.expectedError)\n\t}\n}\n\nfunc TestVolumeInspectWithoutFormat(t *testing.T) {\n\ttestCases := []struct {\n\t\tname string\n\t\targs []string\n\t\tvolumeInspectFunc func(volumeID string) (types.Volume, error)\n\t}{\n\t\t{\n\t\t\tname: \"single-volume\",\n\t\t\targs: []string{\"foo\"},\n\t\t\tvolumeInspectFunc: func(volumeID string) (types.Volume, error) {\n\t\t\t\tif volumeID != \"foo\" {\n\t\t\t\t\treturn types.Volume{}, errors.Errorf(\"Invalid volumeID, expected %s, got %s\", \"foo\", volumeID)\n\t\t\t\t}\n\t\t\t\treturn *Volume(), nil\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"multiple-volume-with-labels\",\n\t\t\targs: []string{\"foo\", \"bar\"},\n\t\t\tvolumeInspectFunc: func(volumeID string) (types.Volume, error) {\n\t\t\t\treturn *Volume(VolumeName(volumeID), VolumeLabels(map[string]string{\n\t\t\t\t\t\"foo\": \"bar\",\n\t\t\t\t})), nil\n\t\t\t},\n\t\t},\n\t}\n\tfor _, tc := range testCases {\n\t\tbuf := new(bytes.Buffer)\n\t\tcmd := newInspectCommand(\n\t\t\ttest.NewFakeCli(&fakeClient{\n\t\t\t\tvolumeInspectFunc: tc.volumeInspectFunc,\n\t\t\t}, buf),\n\t\t)\n\t\tcmd.SetArgs(tc.args)\n\t\tassert.NilError(t, cmd.Execute())\n\t\tactual := buf.String()\n\t\texpected := golden.Get(t, []byte(actual), fmt.Sprintf(\"volume-inspect-without-format.%s.golden\", tc.name))\n\t\tassert.EqualNormalizedString(t, assert.RemoveSpace, actual, string(expected))\n\t}\n}\n\nfunc TestVolumeInspectWithFormat(t *testing.T) {\n\tvolumeInspectFunc := func(volumeID string) (types.Volume, error) {\n\t\treturn *Volume(VolumeLabels(map[string]string{\n\t\t\t\"foo\": \"bar\",\n\t\t})), nil\n\t}\n\ttestCases := []struct {\n\t\tname string\n\t\tformat string\n\t\targs []string\n\t\tvolumeInspectFunc func(volumeID string) (types.Volume, error)\n\t}{\n\t\t{\n\t\t\tname: \"simple-template\",\n\t\t\tformat: \"{{.Name}}\",\n\t\t\targs: []string{\"foo\"},\n\t\t\tvolumeInspectFunc: volumeInspectFunc,\n\t\t},\n\t\t{\n\t\t\tname: \"json-template\",\n\t\t\tformat: \"{{json .Labels}}\",\n\t\t\targs: []string{\"foo\"},\n\t\t\tvolumeInspectFunc: volumeInspectFunc,\n\t\t},\n\t}\n\tfor _, tc := range testCases {\n\t\tbuf := new(bytes.Buffer)\n\t\tcmd := newInspectCommand(\n\t\t\ttest.NewFakeCli(&fakeClient{\n\t\t\t\tvolumeInspectFunc: tc.volumeInspectFunc,\n\t\t\t}, buf),\n\t\t)\n\t\tcmd.SetArgs(tc.args)\n\t\tcmd.Flags().Set(\"format\", tc.format)\n\t\tassert.NilError(t, cmd.Execute())\n\t\tactual := buf.String()\n\t\texpected := golden.Get(t, []byte(actual), fmt.Sprintf(\"volume-inspect-with-format.%s.golden\", tc.name))\n\t\tassert.EqualNormalizedString(t, assert.RemoveSpace, actual, string(expected))\n\t}\n}\n"},"repo_name":{"kind":"string","value":"Originate/exosphere"},"path":{"kind":"string","value":"vendor/github.com/moby/moby/cli/command/volume/inspect_test.go"},"language":{"kind":"string","value":"GO"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":4211,"string":"4,211"}}},{"rowIdx":61538295,"cells":{"code":{"kind":"string","value":"/*\n*********************************************************************************************\n\n System Loader Implementation\n\n - Implemented to https://github.com/jorendorff/js-loaders/blob/master/browser-loader.js\n\n -