code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
<TS language="fa" version="2.0"> <context> <name>AboutDialog</name> <message> <source>About Argentum Core</source> <translation type="unfinished"/> </message> <message> <source>&lt;b&gt;Argentum Core&lt;/b&gt; version</source> <translation type="unfinished"/> </message> <message> <source> This is experimental software. Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php. This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young (eay@cryptsoft.com) and UPnP software written by Thomas Bernard.</source> <translation>⏎ ⏎ این یک نرم‌افزار آزمایشی است⏎ ⏎ نرم افزار تحت مجوز MIT/X11 منتشر شده است. پروندهٔ COPYING یا نشانی http://www.opensource.org/licenses/mit-license.php. را ببینید⏎ ⏎ این محصول شامل نرم‌افزار توسعه داده‌شده در پروژهٔ OpenSSL است. در این نرم‌افزار از OpenSSL Toolkit (http://www.openssl.org/) و نرم‌افزار رمزنگاری نوشته شده توسط اریک یانگ (eay@cryptsoft.com) و UPnP توسط توماس برنارد استفاده شده است.</translation> </message> <message> <source>Copyright</source> <translation>حق تألیف</translation> </message> <message> <source>The Argentum Core developers</source> <translation type="unfinished"/> </message> <message> <source>(%1-bit)</source> <translation type="unfinished"/> </message> </context> <context> <name>AddressBookPage</name> <message> <source>Double-click to edit address or label</source> <translation>برای ویرایش نشانی یا برچسب دوبار کلیک کنید</translation> </message> <message> <source>Create a new address</source> <translation>ایجاد نشانی جدید</translation> </message> <message> <source>&amp;New</source> <translation type="unfinished"/> </message> <message> <source>Copy the currently selected address to the system clipboard</source> <translation>کپی نشانی انتخاب شده به حافظهٔ سیستم</translation> </message> <message> <source>&amp;Copy</source> <translation>&amp;رونوشت</translation> </message> <message> <source>C&amp;lose</source> <translation>&amp;بستن</translation> </message> <message> <source>&amp;Copy Address</source> <translation>&amp;کپی نشانی</translation> </message> <message> <source>Delete the currently selected address from the list</source> <translation>حذف نشانی انتخاب‌شده از لیست</translation> </message> <message> <source>Export the data in the current tab to a file</source> <translation>خروجی گرفتن داده‌های برگهٔ فعلی به یک پرونده</translation> </message> <message> <source>&amp;Export</source> <translation>&amp;صدور</translation> </message> <message> <source>&amp;Delete</source> <translation>&amp;حذف</translation> </message> <message> <source>Choose the address to send coins to</source> <translation type="unfinished"/> </message> <message> <source>Choose the address to receive coins with</source> <translation type="unfinished"/> </message> <message> <source>C&amp;hoose</source> <translation type="unfinished"/> </message> <message> <source>Sending addresses</source> <translation type="unfinished"/> </message> <message> <source>Receiving addresses</source> <translation type="unfinished"/> </message> <message> <source>These are your Argentum addresses for sending payments. Always check the amount and the receiving address before sending coins.</source> <translation>این‌ها نشانی‌های بیت‌کوین شما برای ارسال وجود هستند. همیشه قبل از ارسال سکه‌ها، نشانی دریافت‌کننده و مقدار ارسالی را بررسی کنید.</translation> </message> <message> <source>These are your Argentum addresses for receiving payments. It is recommended to use a new receiving address for each transaction.</source> <translation type="unfinished"/> </message> <message> <source>Copy &amp;Label</source> <translation>کپی و برچسب‌&amp;گذاری</translation> </message> <message> <source>&amp;Edit</source> <translation>&amp;ویرایش</translation> </message> <message> <source>Export Address List</source> <translation>استخراج لیست آدرس</translation> </message> <message> <source>Comma separated file (*.csv)</source> <translation>پروندهٔ نوع CSV جداشونده با کاما (*.csv)</translation> </message> <message> <source>Exporting Failed</source> <translation type="unfinished"/> </message> <message> <source>There was an error trying to save the address list to %1.</source> <translation type="unfinished"/> </message> </context> <context> <name>AddressTableModel</name> <message> <source>Label</source> <translation>برچسب</translation> </message> <message> <source>Address</source> <translation>آدرس</translation> </message> <message> <source>(no label)</source> <translation>(بدون برچسب)</translation> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <source>Passphrase Dialog</source> <translation>پنجرهٔ گذرواژه</translation> </message> <message> <source>Enter passphrase</source> <translation>گذرواژه را وارد کنید</translation> </message> <message> <source>New passphrase</source> <translation>گذرواژهٔ جدید</translation> </message> <message> <source>Repeat new passphrase</source> <translation>تکرار گذرواژهٔ جدید</translation> </message> <message> <source>Enter the new passphrase to the wallet.&lt;br/&gt;Please use a passphrase of &lt;b&gt;10 or more random characters&lt;/b&gt;, or &lt;b&gt;eight or more words&lt;/b&gt;.</source> <translation>گذرواژهٔ جدید کیف پول خود را وارد کنید.&lt;br/&gt;لطفاً از گذرواژه‌ای با &lt;b&gt;حداقل ۱۰ حرف تصادفی&lt;/b&gt;، یا &lt;b&gt;حداقل هشت کلمه&lt;/b&gt; انتخاب کنید.</translation> </message> <message> <source>Encrypt wallet</source> <translation>رمزنگاری کیف پول</translation> </message> <message> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation>انجام این عملیات نیازمند گذرواژهٔ کیف پول شما برای باز کردن قفل آن است.</translation> </message> <message> <source>Unlock wallet</source> <translation>باز کردن قفل کیف پول</translation> </message> <message> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation>انجام این عملیات نیازمند گذرواژهٔ کیف پول شما برای رمزگشایی کردن آن است.</translation> </message> <message> <source>Decrypt wallet</source> <translation>رمزگشایی کیف پول</translation> </message> <message> <source>Change passphrase</source> <translation>تغییر گذرواژه</translation> </message> <message> <source>Enter the old and new passphrase to the wallet.</source> <translation>گذرواژهٔ قدیمی و جدید کیف پول را وارد کنید.</translation> </message> <message> <source>Confirm wallet encryption</source> <translation>تأیید رمزنگاری کیف پول</translation> </message> <message> <source>Warning: If you encrypt your wallet and lose your passphrase, you will &lt;b&gt;LOSE ALL OF YOUR ARGENTUMS&lt;/b&gt;!</source> <translation>هشدار: اگر کیف پول خود را رمزنگاری کنید و گذرواژه را فراموش کنید، &lt;b&gt;تمام دارایی بیت‌کوین خود را از دست خواهید داد&lt;/b&gt;!</translation> </message> <message> <source>Are you sure you wish to encrypt your wallet?</source> <translation>آیا مطمئن هستید که می‌خواهید کیف پول خود را رمزنگاری کنید؟</translation> </message> <message> <source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source> <translation>مهم: هر نسخهٔ پشتیبانی که تا کنون از کیف پول خود تهیه کرده‌اید، باید با کیف پول رمزنگاری شدهٔ جدید جایگزین شود. به دلایل امنیتی، پروندهٔ قدیمی کیف پول بدون رمزنگاری، تا زمانی که از کیف پول رمزنگاری‌شدهٔ جدید استفاده نکنید، غیرقابل استفاده خواهد بود.</translation> </message> <message> <source>Warning: The Caps Lock key is on!</source> <translation>هشدار: کلید Caps Lock روشن است!</translation> </message> <message> <source>Wallet encrypted</source> <translation>کیف پول رمزنگاری شد</translation> </message> <message> <source>Argentum will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your argentums from being stolen by malware infecting your computer.</source> <translation>بیت‌کوین هم اکنون بسته می‌شود تا فرایند رمزگذاری را تمام کند. به خاطر داشته باشید که رمزگذاری کردن کیف پول‌تان نمی‌تواند به طور کامل بیت‌کوین‌های شما را در برابر دزدیده شدن توسط بدافزارهایی که احتمالاً رایانهٔ شما را آلوده می‌کنند، محافظت نماید.</translation> </message> <message> <source>Wallet encryption failed</source> <translation>رمزنگاری کیف پول با شکست مواجه شد</translation> </message> <message> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation>رمزنگاری کیف پول بنا به یک خطای داخلی با شکست مواجه شد. کیف پول شما رمزنگاری نشد.</translation> </message> <message> <source>The supplied passphrases do not match.</source> <translation>گذرواژه‌های داده شده با هم تطابق ندارند.</translation> </message> <message> <source>Wallet unlock failed</source> <translation>بازگشایی قفل کیف‌پول با شکست مواجه شد</translation> </message> <message> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation>گذرواژهٔ وارد شده برای رمزگشایی کیف پول نادرست بود.</translation> </message> <message> <source>Wallet decryption failed</source> <translation>رمزگشایی ناموفق کیف پول</translation> </message> <message> <source>Wallet passphrase was successfully changed.</source> <translation>گذرواژهٔ کیف پول با موفقیت عوض شد.</translation> </message> </context> <context> <name>BitcoinGUI</name> <message> <source>Sign &amp;message...</source> <translation>&amp;امضای پیام...</translation> </message> <message> <source>Synchronizing with network...</source> <translation>همگام‌سازی با شبکه...</translation> </message> <message> <source>&amp;Overview</source> <translation>&amp;بررسی اجمالی</translation> </message> <message> <source>Node</source> <translation type="unfinished"/> </message> <message> <source>Show general overview of wallet</source> <translation>نمایش بررسی اجمالی کیف پول</translation> </message> <message> <source>&amp;Transactions</source> <translation>&amp;تراکنش‌ها</translation> </message> <message> <source>Browse transaction history</source> <translation>مرور تاریخچهٔ تراکنش‌ها</translation> </message> <message> <source>E&amp;xit</source> <translation>&amp;خروج</translation> </message> <message> <source>Quit application</source> <translation>خروج از برنامه</translation> </message> <message> <source>Show information about Argentum</source> <translation>نمایش اطلاعات در مورد بیت‌کوین</translation> </message> <message> <source>About &amp;Qt</source> <translation>دربارهٔ &amp;کیوت</translation> </message> <message> <source>Show information about Qt</source> <translation>نمایش اطلاعات دربارهٔ کیوت</translation> </message> <message> <source>&amp;Options...</source> <translation>&amp;تنظیمات...</translation> </message> <message> <source>&amp;Encrypt Wallet...</source> <translation>&amp;رمزنگاری کیف پول...</translation> </message> <message> <source>&amp;Backup Wallet...</source> <translation>&amp;پیشتیبان‌گیری از کیف پول...</translation> </message> <message> <source>&amp;Change Passphrase...</source> <translation>&amp;تغییر گذرواژه...</translation> </message> <message> <source>Very &amp;sending addresses...</source> <translation type="unfinished"/> </message> <message> <source>Receiving addresses...</source> <translation type="unfinished"/> </message> <message> <source>Open &amp;URI...</source> <translation type="unfinished"/> </message> <message> <source>Importing blocks from disk...</source> <translation>دریافت بلوک‌ها از دیسک...</translation> </message> <message> <source>Reindexing blocks on disk...</source> <translation>بازنشانی بلوک‌ها روی دیسک...</translation> </message> <message> <source>Send coins to a Argentum address</source> <translation>ارسال وجه به نشانی بیت‌کوین</translation> </message> <message> <source>Modify configuration options for Argentum Core</source> <translation>تغییر و اصلاح تنظیمات پیکربندی بیت‌کوین</translation> </message> <message> <source>Backup wallet to another location</source> <translation>تهیهٔ پشتیبان از کیف پول در یک مکان دیگر</translation> </message> <message> <source>Change the passphrase used for wallet encryption</source> <translation>تغییر گذرواژهٔ مورد استفاده در رمزنگاری کیف پول</translation> </message> <message> <source>&amp;Debug window</source> <translation>پنجرهٔ ا&amp;شکال‌زدایی</translation> </message> <message> <source>Open debugging and diagnostic console</source> <translation>باز کردن کنسول خطایابی و اشکال‌زدایی</translation> </message> <message> <source>&amp;Verify message...</source> <translation>با&amp;زبینی پیام...</translation> </message> <message> <source>Argentum</source> <translation>بیت‌کوین</translation> </message> <message> <source>Wallet</source> <translation>کیف پول</translation> </message> <message> <source>&amp;Send</source> <translation>&amp;ارسال</translation> </message> <message> <source>&amp;Receive</source> <translation>&amp;دریافت</translation> </message> <message> <source>&amp;Show / Hide</source> <translation>&amp;نمایش/ عدم نمایش</translation> </message> <message> <source>Show or hide the main Window</source> <translation>نمایش یا مخفی‌کردن پنجرهٔ اصلی</translation> </message> <message> <source>Encrypt the private keys that belong to your wallet</source> <translation>رمزنگاری کلیدهای خصوصی متعلق به کیف پول شما</translation> </message> <message> <source>Sign messages with your Argentum addresses to prove you own them</source> <translation>برای اثبات اینکه پیام‌ها به شما تعلق دارند، آن‌ها را با نشانی بیت‌کوین خود امضا کنید</translation> </message> <message> <source>Verify messages to ensure they were signed with specified Argentum addresses</source> <translation>برای حصول اطمینان از اینکه پیام با نشانی بیت‌کوین مشخص شده امضا است یا خیر، پیام را شناسایی کنید</translation> </message> <message> <source>&amp;File</source> <translation>&amp;فایل</translation> </message> <message> <source>&amp;Settings</source> <translation>&amp;تنظیمات</translation> </message> <message> <source>&amp;Help</source> <translation>&amp;کمک‌رسانی</translation> </message> <message> <source>Tabs toolbar</source> <translation>نوارابزار برگه‌ها</translation> </message> <message> <source>[testnet]</source> <translation>[شبکهٔ آزمایش]</translation> </message> <message> <source>Argentum Core</source> <translation> هسته Argentum </translation> </message> <message> <source>Request payments (generates QR codes and argentum: URIs)</source> <translation type="unfinished"/> </message> <message> <source>&amp;About Argentum Core</source> <translation type="unfinished"/> </message> <message> <source>Show the list of used sending addresses and labels</source> <translation type="unfinished"/> </message> <message> <source>Show the list of used receiving addresses and labels</source> <translation type="unfinished"/> </message> <message> <source>Open a argentum: URI or payment request</source> <translation type="unfinished"/> </message> <message> <source>&amp;Command-line options</source> <translation type="unfinished"/> </message> <message> <source>Show the Argentum Core help message to get a list with possible command-line options</source> <translation type="unfinished"/> </message> <message> <source>Argentum client</source> <translation>کلاینت بیت‌کوین</translation> </message> <message numerus="yes"> <source>%n active connection(s) to Argentum network</source> <translation><numerusform>%n ارتباط فعال با شبکهٔ بیت‌کوین</numerusform></translation> </message> <message> <source>No block source available...</source> <translation>منبعی برای دریافت بلاک در دسترس نیست...</translation> </message> <message> <source>Processed %1 of %2 (estimated) blocks of transaction history.</source> <translation>%1 بلاک از مجموع %2 بلاک (تخمینی) تاریخچهٔ تراکنش‌ها پردازش شده است.</translation> </message> <message> <source>Processed %1 blocks of transaction history.</source> <translation>%1 بلاک از تاریخچهٔ تراکنش‌ها پردازش شده است.</translation> </message> <message numerus="yes"> <source>%n hour(s)</source> <translation><numerusform>%n ساعت</numerusform></translation> </message> <message numerus="yes"> <source>%n day(s)</source> <translation><numerusform>%n روز</numerusform></translation> </message> <message numerus="yes"> <source>%n week(s)</source> <translation><numerusform>%n هفته</numerusform></translation> </message> <message> <source>%1 and %2</source> <translation type="unfinished"/> </message> <message numerus="yes"> <source>%n year(s)</source> <translation type="unfinished"><numerusform/></translation> </message> <message> <source>%1 behind</source> <translation>%1 عقب‌تر</translation> </message> <message> <source>Last received block was generated %1 ago.</source> <translation>آخرین بلاک دریافتی %1 پیش ایجاد شده است.</translation> </message> <message> <source>Transactions after this will not yet be visible.</source> <translation>تراکنش‌های بعد از این هنوز قابل مشاهده نیستند.</translation> </message> <message> <source>Error</source> <translation>خطا</translation> </message> <message> <source>Warning</source> <translation>هشدار</translation> </message> <message> <source>Information</source> <translation>اطلاعات</translation> </message> <message> <source>Up to date</source> <translation>وضعیت به‌روز</translation> </message> <message> <source>Catching up...</source> <translation>به‌روز رسانی...</translation> </message> <message> <source>Sent transaction</source> <translation>تراکنش ارسال شد</translation> </message> <message> <source>Incoming transaction</source> <translation>تراکنش دریافت شد</translation> </message> <message> <source>Date: %1 Amount: %2 Type: %3 Address: %4 </source> <translation>تاریخ: %1 مبلغ: %2 نوع: %3 نشانی: %4 </translation> </message> <message> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation>کیف پول &lt;b&gt;رمزنگاری شده&lt;/b&gt; است و هم‌اکنون &lt;b&gt;باز&lt;/b&gt; است</translation> </message> <message> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation>کیف پول &lt;b&gt;رمزنگاری شده&lt;/b&gt; است و هم‌اکنون &lt;b&gt;قفل&lt;/b&gt; است</translation> </message> <message> <source>A fatal error occurred. Argentum can no longer continue safely and will quit.</source> <translation>یک خطای مهلک اتفاق افتاده است. بیت‌کوین نمی‌تواند بدون مشکل به کار خود ادامه دهد و بسته خواهد شد.</translation> </message> </context> <context> <name>ClientModel</name> <message> <source>Network Alert</source> <translation>پیام شبکه</translation> </message> </context> <context> <name>CoinControlDialog</name> <message> <source>Coin Control Address Selection</source> <translation type="unfinished"/> </message> <message> <source>Quantity:</source> <translation type="unfinished"/> </message> <message> <source>Bytes:</source> <translation type="unfinished"/> </message> <message> <source>Amount:</source> <translation>مبلغ:</translation> </message> <message> <source>Priority:</source> <translation type="unfinished"/> </message> <message> <source>Fee:</source> <translation type="unfinished"/> </message> <message> <source>Low Output:</source> <translation type="unfinished"/> </message> <message> <source>After Fee:</source> <translation type="unfinished"/> </message> <message> <source>Change:</source> <translation type="unfinished"/> </message> <message> <source>(un)select all</source> <translation type="unfinished"/> </message> <message> <source>Tree mode</source> <translation type="unfinished"/> </message> <message> <source>List mode</source> <translation type="unfinished"/> </message> <message> <source>Amount</source> <translation>مبلغ</translation> </message> <message> <source>Label</source> <translation type="unfinished"/> </message> <message> <source>Address</source> <translation>نشانی</translation> </message> <message> <source>Date</source> <translation>تاریخ</translation> </message> <message> <source>Confirmations</source> <translation type="unfinished"/> </message> <message> <source>Confirmed</source> <translation>تأیید شده</translation> </message> <message> <source>Priority</source> <translation type="unfinished"/> </message> <message> <source>Copy address</source> <translation>کپی نشانی</translation> </message> <message> <source>Copy label</source> <translation>کپی برچسب</translation> </message> <message> <source>Copy amount</source> <translation>کپی مقدار</translation> </message> <message> <source>Copy transaction ID</source> <translation>کپی شناسهٔ تراکنش</translation> </message> <message> <source>Lock unspent</source> <translation type="unfinished"/> </message> <message> <source>Unlock unspent</source> <translation type="unfinished"/> </message> <message> <source>Copy quantity</source> <translation type="unfinished"/> </message> <message> <source>Copy fee</source> <translation type="unfinished"/> </message> <message> <source>Copy after fee</source> <translation type="unfinished"/> </message> <message> <source>Copy bytes</source> <translation type="unfinished"/> </message> <message> <source>Copy priority</source> <translation type="unfinished"/> </message> <message> <source>Copy low output</source> <translation type="unfinished"/> </message> <message> <source>Copy change</source> <translation type="unfinished"/> </message> <message> <source>highest</source> <translation type="unfinished"/> </message> <message> <source>higher</source> <translation type="unfinished"/> </message> <message> <source>high</source> <translation type="unfinished"/> </message> <message> <source>medium-high</source> <translation type="unfinished"/> </message> <message> <source>medium</source> <translation type="unfinished"/> </message> <message> <source>low-medium</source> <translation type="unfinished"/> </message> <message> <source>low</source> <translation type="unfinished"/> </message> <message> <source>lower</source> <translation type="unfinished"/> </message> <message> <source>lowest</source> <translation type="unfinished"/> </message> <message> <source>(%1 locked)</source> <translation type="unfinished"/> </message> <message> <source>none</source> <translation type="unfinished"/> </message> <message> <source>Dust</source> <translation type="unfinished"/> </message> <message> <source>yes</source> <translation>بله</translation> </message> <message> <source>no</source> <translation>خیر</translation> </message> <message> <source>This label turns red, if the transaction size is greater than 1000 bytes.</source> <translation type="unfinished"/> </message> <message> <source>This means a fee of at least %1 per kB is required.</source> <translation type="unfinished"/> </message> <message> <source>Can vary +/- 1 byte per input.</source> <translation type="unfinished"/> </message> <message> <source>Transactions with higher priority are more likely to get included into a block.</source> <translation type="unfinished"/> </message> <message> <source>This label turns red, if the priority is smaller than &quot;medium&quot;.</source> <translation type="unfinished"/> </message> <message> <source>This label turns red, if any recipient receives an amount smaller than %1.</source> <translation type="unfinished"/> </message> <message> <source>This means a fee of at least %1 is required.</source> <translation type="unfinished"/> </message> <message> <source>Amounts below 0.546 times the minimum relay fee are shown as dust.</source> <translation type="unfinished"/> </message> <message> <source>This label turns red, if the change is smaller than %1.</source> <translation type="unfinished"/> </message> <message> <source>(no label)</source> <translation>(بدون برچسب)</translation> </message> <message> <source>change from %1 (%2)</source> <translation type="unfinished"/> </message> <message> <source>(change)</source> <translation type="unfinished"/> </message> </context> <context> <name>EditAddressDialog</name> <message> <source>Edit Address</source> <translation>ویرایش نشانی</translation> </message> <message> <source>&amp;Label</source> <translation>&amp;برچسب</translation> </message> <message> <source>The label associated with this address list entry</source> <translation type="unfinished"/> </message> <message> <source>The address associated with this address list entry. This can only be modified for sending addresses.</source> <translation type="unfinished"/> </message> <message> <source>&amp;Address</source> <translation>&amp;نشانی</translation> </message> <message> <source>New receiving address</source> <translation>نشانی دریافتی جدید</translation> </message> <message> <source>New sending address</source> <translation>نشانی ارسالی جدید</translation> </message> <message> <source>Edit receiving address</source> <translation>ویرایش نشانی دریافتی</translation> </message> <message> <source>Edit sending address</source> <translation>ویرایش نشانی ارسالی</translation> </message> <message> <source>The entered address &quot;%1&quot; is already in the address book.</source> <translation>نشانی وارد شده «%1» در حال حاضر در دفترچه وجود دارد.</translation> </message> <message> <source>The entered address &quot;%1&quot; is not a valid Argentum address.</source> <translation>نشانی وارد شده «%1» یک نشانی معتبر بیت‌کوین نیست.</translation> </message> <message> <source>Could not unlock wallet.</source> <translation>نمی‌توان کیف پول را رمزگشایی کرد.</translation> </message> <message> <source>New key generation failed.</source> <translation>ایجاد کلید جدید با شکست مواجه شد.</translation> </message> </context> <context> <name>FreespaceChecker</name> <message> <source>A new data directory will be created.</source> <translation>یک مسیر دادهٔ جدید ایجاد خواهد شد.</translation> </message> <message> <source>name</source> <translation>نام</translation> </message> <message> <source>Directory already exists. Add %1 if you intend to create a new directory here.</source> <translation>این پوشه در حال حاضر وجود دارد. اگر می‌خواهید یک دایرکتوری جدید در این‌جا ایجاد کنید، %1 را اضافه کنید.</translation> </message> <message> <source>Path already exists, and is not a directory.</source> <translation>مسیر داده شده موجود است و به یک پوشه اشاره نمی‌کند.</translation> </message> <message> <source>Cannot create data directory here.</source> <translation>نمی‌توان پوشهٔ داده در این‌جا ایجاد کرد.</translation> </message> </context> <context> <name>HelpMessageDialog</name> <message> <source>Argentum Core - Command-line options</source> <translation type="unfinished"/> </message> <message> <source>Argentum Core</source> <translation> هسته Argentum </translation> </message> <message> <source>version</source> <translation>نسخه</translation> </message> <message> <source>Usage:</source> <translation>استفاده:</translation> </message> <message> <source>command-line options</source> <translation>گزینه‌های خط فرمان</translation> </message> <message> <source>UI options</source> <translation>گزینه‌های رابط کاربری</translation> </message> <message> <source>Set language, for example &quot;de_DE&quot; (default: system locale)</source> <translation>زبان را تنظیم کنید؛ برای مثال «de_DE» (زبان پیش‌فرض محلی)</translation> </message> <message> <source>Start minimized</source> <translation>اجرای برنامه به صورت کوچک‌شده</translation> </message> <message> <source>Set SSL root certificates for payment request (default: -system-)</source> <translation type="unfinished"/> </message> <message> <source>Show splash screen on startup (default: 1)</source> <translation>نمایش پنجرهٔ خوشامدگویی در ابتدای اجرای برنامه (پیش‌فرض: 1)</translation> </message> <message> <source>Choose data directory on startup (default: 0)</source> <translation>انتخاب مسیر داده‌ها در ابتدای اجرای برنامه (پیش‌فرض: 0)</translation> </message> </context> <context> <name>Intro</name> <message> <source>Welcome</source> <translation>خوش‌آمدید</translation> </message> <message> <source>Welcome to Argentum Core.</source> <translation type="unfinished"/> </message> <message> <source>As this is the first time the program is launched, you can choose where Argentum Core will store its data.</source> <translation type="unfinished"/> </message> <message> <source>Argentum Core will download and store a copy of the Argentum block chain. At least %1GB of data will be stored in this directory, and it will grow over time. The wallet will also be stored in this directory.</source> <translation type="unfinished"/> </message> <message> <source>Use the default data directory</source> <translation>استفاده از مسیر پیش‌فرض</translation> </message> <message> <source>Use a custom data directory:</source> <translation>استفاده از یک مسیر سفارشی:</translation> </message> <message> <source>Argentum</source> <translation>بیت‌کوین</translation> </message> <message> <source>Error: Specified data directory &quot;%1&quot; can not be created.</source> <translation>خطا: نمی‌توان پوشه‌ای برای داده‌ها در «%1» ایجاد کرد.</translation> </message> <message> <source>Error</source> <translation>خطا</translation> </message> <message> <source>GB of free space available</source> <translation>گیگابات فضا موجود است</translation> </message> <message> <source>(of %1GB needed)</source> <translation>(از %1 گیگابایت فضای مورد نیاز)</translation> </message> </context> <context> <name>OpenURIDialog</name> <message> <source>Open URI</source> <translation type="unfinished"/> </message> <message> <source>Open payment request from URI or file</source> <translation type="unfinished"/> </message> <message> <source>URI:</source> <translation type="unfinished"/> </message> <message> <source>Select payment request file</source> <translation type="unfinished"/> </message> <message> <source>Select payment request file to open</source> <translation type="unfinished"/> </message> </context> <context> <name>OptionsDialog</name> <message> <source>Options</source> <translation>گزینه‌ها</translation> </message> <message> <source>&amp;Main</source> <translation>&amp;عمومی</translation> </message> <message> <source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB.</source> <translation>کارمزد اختیاریِ هر کیلوبایت برای انتقال سریع‌تر تراکنش. اکثر تراکنش‌ها ۱ کیلوبایتی هستند.</translation> </message> <message> <source>Pay transaction &amp;fee</source> <translation>پرداخت &amp;کارمزد تراکنش</translation> </message> <message> <source>Automatically start Argentum Core after logging in to the system.</source> <translation>اجرای خودکار بیت‌کوین در زمان ورود به سیستم.</translation> </message> <message> <source>&amp;Start Argentum Core on system login</source> <translation>&amp;اجرای بیت‌کوین با ورود به سیستم</translation> </message> <message> <source>Size of &amp;database cache</source> <translation type="unfinished"/> </message> <message> <source>MB</source> <translation type="unfinished"/> </message> <message> <source>Number of script &amp;verification threads</source> <translation type="unfinished"/> </message> <message> <source>Connect to the Argentum network through a SOCKS proxy.</source> <translation type="unfinished"/> </message> <message> <source>&amp;Connect through SOCKS proxy (default proxy):</source> <translation type="unfinished"/> </message> <message> <source>IP address of the proxy (e.g. IPv4: 127.0.0.1 / IPv6: ::1)</source> <translation type="unfinished"/> </message> <message> <source>Active command-line options that override above options:</source> <translation type="unfinished"/> </message> <message> <source>Reset all client options to default.</source> <translation>بازنشانی تمام تنظیمات به پیش‌فرض.</translation> </message> <message> <source>&amp;Reset Options</source> <translation>&amp;بازنشانی تنظیمات</translation> </message> <message> <source>&amp;Network</source> <translation>&amp;شبکه</translation> </message> <message> <source>(0 = auto, &lt;0 = leave that many cores free)</source> <translation type="unfinished"/> </message> <message> <source>W&amp;allet</source> <translation type="unfinished"/> </message> <message> <source>Expert</source> <translation>استخراج</translation> </message> <message> <source>Enable coin &amp;control features</source> <translation type="unfinished"/> </message> <message> <source>If you disable the spending of unconfirmed change, the change from a transaction cannot be used until that transaction has at least one confirmation. This also affects how your balance is computed.</source> <translation type="unfinished"/> </message> <message> <source>&amp;Spend unconfirmed change</source> <translation type="unfinished"/> </message> <message> <source>Automatically open the Argentum client port on the router. This only works when your router supports UPnP and it is enabled.</source> <translation>باز کردن خودکار درگاه شبکهٔ بیت‌کوین روی روترها. تنها زمانی کار می‌کند که روتر از پروتکل UPnP پشتیبانی کند و این پروتکل فعال باشد.</translation> </message> <message> <source>Map port using &amp;UPnP</source> <translation>نگاشت درگاه شبکه با استفاده از پروتکل &amp;UPnP</translation> </message> <message> <source>Proxy &amp;IP:</source> <translation>آ&amp;ی‌پی پراکسی:</translation> </message> <message> <source>&amp;Port:</source> <translation>&amp;درگاه:</translation> </message> <message> <source>Port of the proxy (e.g. 9050)</source> <translation>درگاه پراکسی (مثال 9050)</translation> </message> <message> <source>SOCKS &amp;Version:</source> <translation>&amp;نسخهٔ SOCKS:</translation> </message> <message> <source>SOCKS version of the proxy (e.g. 5)</source> <translation>نسخهٔ پراکسی SOCKS (مثلاً 5)</translation> </message> <message> <source>&amp;Window</source> <translation>&amp;پنجره</translation> </message> <message> <source>Show only a tray icon after minimizing the window.</source> <translation>تنها بعد از کوچک کردن پنجره، tray icon را نشان بده.</translation> </message> <message> <source>&amp;Minimize to the tray instead of the taskbar</source> <translation>&amp;کوچک کردن به سینی به‌جای نوار وظیفه</translation> </message> <message> <source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source> <translation>مخفی کردن در نوار کناری به‌جای خروج هنگام بستن پنجره. زمانی که این گزینه فعال است، برنامه فقط با استفاده از گزینهٔ خروج در منو قابل بسته شدن است.</translation> </message> <message> <source>M&amp;inimize on close</source> <translation>کوچک کردن &amp;در زمان بسته شدن</translation> </message> <message> <source>&amp;Display</source> <translation>&amp;نمایش</translation> </message> <message> <source>User Interface &amp;language:</source> <translation>زبان &amp;رابط کاربری:</translation> </message> <message> <source>The user interface language can be set here. This setting will take effect after restarting Argentum Core.</source> <translation>زبان رابط کاربر می‌تواند در این‌جا تنظیم شود. تنظیمات بعد از ظروع مجدد بیت‌کوین اعمال خواهد شد.</translation> </message> <message> <source>&amp;Unit to show amounts in:</source> <translation>&amp;واحد نمایش مبالغ:</translation> </message> <message> <source>Choose the default subdivision unit to show in the interface and when sending coins.</source> <translation>انتخاب واحد پول مورد استفاده برای نمایش در پنجره‌ها و برای ارسال سکه.</translation> </message> <message> <source>Whether to show Argentum addresses in the transaction list or not.</source> <translation>نمایش یا عدم نمایش نشانی‌های بیت‌کوین در لیست تراکنش‌ها.</translation> </message> <message> <source>&amp;Display addresses in transaction list</source> <translation>نمایش ن&amp;شانی‌ها در فهرست تراکنش‌ها</translation> </message> <message> <source>Whether to show coin control features or not.</source> <translation type="unfinished"/> </message> <message> <source>&amp;OK</source> <translation>&amp;تأیید</translation> </message> <message> <source>&amp;Cancel</source> <translation>&amp;لغو</translation> </message> <message> <source>default</source> <translation>پیش‌فرض</translation> </message> <message> <source>none</source> <translation type="unfinished"/> </message> <message> <source>Confirm options reset</source> <translation>تأییدِ بازنشانی گزینه‌ها</translation> </message> <message> <source>Client restart required to activate changes.</source> <translation type="unfinished"/> </message> <message> <source>Client will be shutdown, do you want to proceed?</source> <translation type="unfinished"/> </message> <message> <source>This change would require a client restart.</source> <translation>برای این تغییرات بازنشانی مشتری ضروری است</translation> </message> <message> <source>The supplied proxy address is invalid.</source> <translation>آدرس پراکسی داده شده صحیح نیست.</translation> </message> </context> <context> <name>OverviewPage</name> <message> <source>Form</source> <translation>فرم</translation> </message> <message> <source>The displayed information may be out of date. Your wallet automatically synchronizes with the Argentum network after a connection is established, but this process has not completed yet.</source> <translation>اطلاعات نمایش‌داده شده ممکن است قدیمی باشند. بعد از این که یک اتصال با شبکه برقرار شد، کیف پول شما به‌صورت خودکار با شبکهٔ بیت‌کوین همگام‌سازی می‌شود. اما این روند هنوز کامل نشده است.</translation> </message> <message> <source>Wallet</source> <translation>کیف پول</translation> </message> <message> <source>Available:</source> <translation>در دسترس:</translation> </message> <message> <source>Your current spendable balance</source> <translation>تراز علی‌الحساب شما</translation> </message> <message> <source>Pending:</source> <translation type="unfinished"/> </message> <message> <source>Total of transactions that have yet to be confirmed, and do not yet count toward the spendable balance</source> <translation>مجموع تراکنش‌هایی که هنوز تأیید نشده‌اند؛ و هنوز روی تراز علی‌الحساب اعمال نشده‌اند</translation> </message> <message> <source>Immature:</source> <translation>نارسیده:</translation> </message> <message> <source>Mined balance that has not yet matured</source> <translation>تراز استخراج شده از معدن که هنوز بالغ نشده است</translation> </message> <message> <source>Total:</source> <translation>جمع کل:</translation> </message> <message> <source>Your current total balance</source> <translation>تراز کل فعلی شما</translation> </message> <message> <source>&lt;b&gt;Recent transactions&lt;/b&gt;</source> <translation>&lt;b&gt;تراکنش‌های اخیر&lt;/b&gt;</translation> </message> <message> <source>out of sync</source> <translation>ناهمگام</translation> </message> </context> <context> <name>PaymentServer</name> <message> <source>URI handling</source> <translation>مدیریت URI</translation> </message> <message> <source>URI can not be parsed! This can be caused by an invalid Argentum address or malformed URI parameters.</source> <translation>نشانی اینترنتی قابل تجزیه و تحلیل نیست! دلیل این وضعیت ممکن است یک نشانی نامعتبر بیت‌کوین و یا پارامترهای ناهنجار در URI بوده باشد.</translation> </message> <message> <source>Requested payment amount of %1 is too small (considered dust).</source> <translation type="unfinished"/> </message> <message> <source>Payment request error</source> <translation type="unfinished"/> </message> <message> <source>Cannot start argentum: click-to-pay handler</source> <translation>نمی‌توان بیت‌کوین را اجرا کرد: کنترل‌کنندهٔ کلیک-و-پرداخت</translation> </message> <message> <source>Net manager warning</source> <translation type="unfinished"/> </message> <message> <source>Your active proxy doesn&apos;t support SOCKS5, which is required for payment requests via proxy.</source> <translation type="unfinished"/> </message> <message> <source>Payment request fetch URL is invalid: %1</source> <translation type="unfinished"/> </message> <message> <source>Payment request file handling</source> <translation type="unfinished"/> </message> <message> <source>Payment request file can not be read or processed! This can be caused by an invalid payment request file.</source> <translation type="unfinished"/> </message> <message> <source>Unverified payment requests to custom payment scripts are unsupported.</source> <translation type="unfinished"/> </message> <message> <source>Refund from %1</source> <translation type="unfinished"/> </message> <message> <source>Error communicating with %1: %2</source> <translation type="unfinished"/> </message> <message> <source>Payment request can not be parsed or processed!</source> <translation type="unfinished"/> </message> <message> <source>Bad response from server %1</source> <translation type="unfinished"/> </message> <message> <source>Payment acknowledged</source> <translation type="unfinished"/> </message> <message> <source>Network request error</source> <translation type="unfinished"/> </message> </context> <context> <name>QObject</name> <message> <source>Argentum</source> <translation>بیت‌کوین</translation> </message> <message> <source>Error: Specified data directory &quot;%1&quot; does not exist.</source> <translation>خطا: پوشهٔ مشخص شده برای داده‌ها در «%1» وجود ندارد.</translation> </message> <message> <source>Error: Cannot parse configuration file: %1. Only use key=value syntax.</source> <translation type="unfinished"/> </message> <message> <source>Error: Invalid combination of -regtest and -testnet.</source> <translation type="unfinished"/> </message> <message> <source>Argentum Core did&apos;t yet exit safely...</source> <translation type="unfinished"/> </message> <message> <source>Enter a Argentum address (e.g. AWRLWS0d6eEuu0qwsNBxkGxB4RV6FMo90X)</source> <translation>یک آدرس بیت‌کوین وارد کنید (مثلاً AWRLWS0d6eEuu0qwsNBxkGxB4RV6FMo90X)</translation> </message> </context> <context> <name>QRImageWidget</name> <message> <source>&amp;Save Image...</source> <translation type="unfinished"/> </message> <message> <source>&amp;Copy Image</source> <translation type="unfinished"/> </message> <message> <source>Save QR Code</source> <translation>ذخیرهٔ کد QR</translation> </message> <message> <source>PNG Image (*.png)</source> <translation type="unfinished"/> </message> </context> <context> <name>RPCConsole</name> <message> <source>Client name</source> <translation>نام کلاینت</translation> </message> <message> <source>N/A</source> <translation>ناموجود</translation> </message> <message> <source>Client version</source> <translation>نسخهٔ کلاینت</translation> </message> <message> <source>&amp;Information</source> <translation>&amp;اطلاعات</translation> </message> <message> <source>Debug window</source> <translation type="unfinished"/> </message> <message> <source>General</source> <translation type="unfinished"/> </message> <message> <source>Using OpenSSL version</source> <translation>نسخهٔ OpenSSL استفاده شده</translation> </message> <message> <source>Startup time</source> <translation>زمان آغاز به کار</translation> </message> <message> <source>Network</source> <translation>شبکه</translation> </message> <message> <source>Name</source> <translation>اسم</translation> </message> <message> <source>Number of connections</source> <translation>تعداد ارتباطات</translation> </message> <message> <source>Block chain</source> <translation>زنجیرهٔ بلوک‌ها</translation> </message> <message> <source>Current number of blocks</source> <translation>تعداد فعلی بلوک‌ها</translation> </message> <message> <source>Estimated total blocks</source> <translation>تعداد تخمینی بلوک‌ها</translation> </message> <message> <source>Last block time</source> <translation>زمان آخرین بلوک</translation> </message> <message> <source>&amp;Open</source> <translation>با&amp;ز کردن</translation> </message> <message> <source>&amp;Console</source> <translation>&amp;کنسول</translation> </message> <message> <source>&amp;Network Traffic</source> <translation type="unfinished"/> </message> <message> <source>&amp;Clear</source> <translation type="unfinished"/> </message> <message> <source>Totals</source> <translation>جمع کل:</translation> </message> <message> <source>In:</source> <translation type="unfinished"/> </message> <message> <source>Out:</source> <translation type="unfinished"/> </message> <message> <source>Build date</source> <translation>ساخت تاریخ</translation> </message> <message> <source>Debug log file</source> <translation>فایلِ لاگِ اشکال زدایی</translation> </message> <message> <source>Open the Argentum debug log file from the current data directory. This can take a few seconds for large log files.</source> <translation>فایلِ لاگِ اشکال زدایی Argentum را از دایرکتوری جاری داده ها باز کنید. این عملیات ممکن است برای فایلهای لاگِ حجیم طولانی شود.</translation> </message> <message> <source>Clear console</source> <translation>پاکسازی کنسول</translation> </message> <message> <source>Welcome to the Argentum RPC console.</source> <translation>به کنسور RPC بیت‌کوین خوش آمدید.</translation> </message> <message> <source>Use up and down arrows to navigate history, and &lt;b&gt;Ctrl-L&lt;/b&gt; to clear screen.</source> <translation>دکمه‌های بالا و پایین برای پیمایش تاریخچه و &lt;b&gt;Ctrl-L&lt;/b&gt; برای پاک کردن صفحه.</translation> </message> <message> <source>Type &lt;b&gt;help&lt;/b&gt; for an overview of available commands.</source> <translation>برای نمایش یک مرور کلی از دستورات ممکن، عبارت &lt;b&gt;help&lt;/b&gt; را بنویسید.</translation> </message> <message> <source>%1 B</source> <translation type="unfinished"/> </message> <message> <source>%1 KB</source> <translation type="unfinished"/> </message> <message> <source>%1 MB</source> <translation type="unfinished"/> </message> <message> <source>%1 GB</source> <translation type="unfinished"/> </message> <message> <source>%1 m</source> <translation type="unfinished"/> </message> <message> <source>%1 h</source> <translation type="unfinished"/> </message> <message> <source>%1 h %2 m</source> <translation type="unfinished"/> </message> </context> <context> <name>ReceiveCoinsDialog</name> <message> <source>&amp;Amount:</source> <translation type="unfinished"/> </message> <message> <source>&amp;Label:</source> <translation>&amp;برچسب:</translation> </message> <message> <source>&amp;Message:</source> <translation type="unfinished"/> </message> <message> <source>Reuse one of the previously used receiving addresses. Reusing addresses has security and privacy issues. Do not use this unless re-generating a payment request made before.</source> <translation type="unfinished"/> </message> <message> <source>R&amp;euse an existing receiving address (not recommended)</source> <translation type="unfinished"/> </message> <message> <source>An optional message to attach to the payment request, which will be displayed when the request is opened. Note: The message will not be sent with the payment over the Argentum network.</source> <translation type="unfinished"/> </message> <message> <source>An optional label to associate with the new receiving address.</source> <translation type="unfinished"/> </message> <message> <source>Use this form to request payments. All fields are &lt;b&gt;optional&lt;/b&gt;.</source> <translation type="unfinished"/> </message> <message> <source>An optional amount to request. Leave this empty or zero to not request a specific amount.</source> <translation type="unfinished"/> </message> <message> <source>Clear all fields of the form.</source> <translation type="unfinished"/> </message> <message> <source>Clear</source> <translation type="unfinished"/> </message> <message> <source>Requested payments history</source> <translation type="unfinished"/> </message> <message> <source>&amp;Request payment</source> <translation type="unfinished"/> </message> <message> <source>Show the selected request (does the same as double clicking an entry)</source> <translation type="unfinished"/> </message> <message> <source>Show</source> <translation type="unfinished"/> </message> <message> <source>Remove the selected entries from the list</source> <translation type="unfinished"/> </message> <message> <source>Remove</source> <translation type="unfinished"/> </message> <message> <source>Copy label</source> <translation>کپی برچسب</translation> </message> <message> <source>Copy message</source> <translation type="unfinished"/> </message> <message> <source>Copy amount</source> <translation>کپی مقدار</translation> </message> </context> <context> <name>ReceiveRequestDialog</name> <message> <source>QR Code</source> <translation>کد QR</translation> </message> <message> <source>Copy &amp;URI</source> <translation type="unfinished"/> </message> <message> <source>Copy &amp;Address</source> <translation type="unfinished"/> </message> <message> <source>&amp;Save Image...</source> <translation type="unfinished"/> </message> <message> <source>Request payment to %1</source> <translation type="unfinished"/> </message> <message> <source>Payment information</source> <translation type="unfinished"/> </message> <message> <source>URI</source> <translation type="unfinished"/> </message> <message> <source>Address</source> <translation>نشانی</translation> </message> <message> <source>Amount</source> <translation>مبلغ</translation> </message> <message> <source>Label</source> <translation>برچسب</translation> </message> <message> <source>Message</source> <translation>پیام</translation> </message> <message> <source>Resulting URI too long, try to reduce the text for label / message.</source> <translation>URL ایجاد شده خیلی طولانی است. سعی کنید طول برچسب و یا پیام را کمتر کنید.</translation> </message> <message> <source>Error encoding URI into QR Code.</source> <translation>خطا در تبدیل نشانی اینترنتی به صورت کد QR.</translation> </message> </context> <context> <name>RecentRequestsTableModel</name> <message> <source>Date</source> <translation>تاریخ</translation> </message> <message> <source>Label</source> <translation>برچسب</translation> </message> <message> <source>Message</source> <translation>پیام</translation> </message> <message> <source>Amount</source> <translation>مبلغ</translation> </message> <message> <source>(no label)</source> <translation>(بدون برچسب)</translation> </message> <message> <source>(no message)</source> <translation type="unfinished"/> </message> <message> <source>(no amount)</source> <translation type="unfinished"/> </message> </context> <context> <name>SendCoinsDialog</name> <message> <source>Send Coins</source> <translation>ارسال سکه</translation> </message> <message> <source>Coin Control Features</source> <translation type="unfinished"/> </message> <message> <source>Inputs...</source> <translation type="unfinished"/> </message> <message> <source>automatically selected</source> <translation type="unfinished"/> </message> <message> <source>Insufficient funds!</source> <translation type="unfinished"/> </message> <message> <source>Quantity:</source> <translation type="unfinished"/> </message> <message> <source>Bytes:</source> <translation type="unfinished"/> </message> <message> <source>Amount:</source> <translation>مبلغ:</translation> </message> <message> <source>Priority:</source> <translation type="unfinished"/> </message> <message> <source>Fee:</source> <translation type="unfinished"/> </message> <message> <source>Low Output:</source> <translation type="unfinished"/> </message> <message> <source>After Fee:</source> <translation type="unfinished"/> </message> <message> <source>Change:</source> <translation type="unfinished"/> </message> <message> <source>If this is activated, but the change address is empty or invalid, change will be sent to a newly generated address.</source> <translation type="unfinished"/> </message> <message> <source>Custom change address</source> <translation type="unfinished"/> </message> <message> <source>Send to multiple recipients at once</source> <translation>ارسال به چند دریافت‌کنندهٔ به‌طور همزمان</translation> </message> <message> <source>Add &amp;Recipient</source> <translation>&amp;دریافت‌کنندهٔ جدید</translation> </message> <message> <source>Clear all fields of the form.</source> <translation type="unfinished"/> </message> <message> <source>Clear &amp;All</source> <translation>پاکسازی &amp;همه</translation> </message> <message> <source>Balance:</source> <translation>تزار:</translation> </message> <message> <source>Confirm the send action</source> <translation>عملیات ارسال را تأیید کنید</translation> </message> <message> <source>S&amp;end</source> <translation>&amp;ارسال</translation> </message> <message> <source>Confirm send coins</source> <translation>ارسال سکه را تأیید کنید</translation> </message> <message> <source>%1 to %2</source> <translation type="unfinished"/> </message> <message> <source>Copy quantity</source> <translation type="unfinished"/> </message> <message> <source>Copy amount</source> <translation>کپی مقدار</translation> </message> <message> <source>Copy fee</source> <translation type="unfinished"/> </message> <message> <source>Copy after fee</source> <translation type="unfinished"/> </message> <message> <source>Copy bytes</source> <translation type="unfinished"/> </message> <message> <source>Copy priority</source> <translation type="unfinished"/> </message> <message> <source>Copy low output</source> <translation type="unfinished"/> </message> <message> <source>Copy change</source> <translation type="unfinished"/> </message> <message> <source>Total Amount %1 (= %2)</source> <translation type="unfinished"/> </message> <message> <source>or</source> <translation>یا</translation> </message> <message> <source>The recipient address is not valid, please recheck.</source> <translation>نشانی گیرنده معتبر نیست؛ لطفا دوباره بررسی کنید.</translation> </message> <message> <source>The amount to pay must be larger than 0.</source> <translation>مبلغ پرداخت باید بیشتر از ۰ باشد.</translation> </message> <message> <source>The amount exceeds your balance.</source> <translation>میزان پرداخت از تراز شما بیشتر است.</translation> </message> <message> <source>The total exceeds your balance when the %1 transaction fee is included.</source> <translation>با احتساب هزینهٔ %1 برای هر تراکنش، مجموع میزان پرداختی از مبلغ تراز شما بیشتر می‌شود.</translation> </message> <message> <source>Duplicate address found, can only send to each address once per send operation.</source> <translation>یک نشانی تکراری پیدا شد. در هر عملیات ارسال، به هر نشانی فقط مبلغ می‌توان ارسال کرد.</translation> </message> <message> <source>Transaction creation failed!</source> <translation type="unfinished"/> </message> <message> <source>The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation type="unfinished"/> </message> <message> <source>Warning: Invalid Argentum address</source> <translation type="unfinished"/> </message> <message> <source>(no label)</source> <translation>(بدون برچسب)</translation> </message> <message> <source>Warning: Unknown change address</source> <translation type="unfinished"/> </message> <message> <source>Are you sure you want to send?</source> <translation type="unfinished"/> </message> <message> <source>added as transaction fee</source> <translation type="unfinished"/> </message> <message> <source>Payment request expired</source> <translation type="unfinished"/> </message> <message> <source>Invalid payment address %1</source> <translation type="unfinished"/> </message> </context> <context> <name>SendCoinsEntry</name> <message> <source>A&amp;mount:</source> <translation>A&amp;مبلغ :</translation> </message> <message> <source>Pay &amp;To:</source> <translation>پرداخ&amp;ت به:</translation> </message> <message> <source>The address to send the payment to (e.g. AWRLWS0d6eEuu0qwsNBxkGxB4RV6FMo90X)</source> <translation>نشانی مقصد برای پرداخت (مثلاً AWRLWS0d6eEuu0qwsNBxkGxB4RV6FMo90X)</translation> </message> <message> <source>Enter a label for this address to add it to your address book</source> <translation>برای این نشانی یک برچسب وارد کنید تا در دفترچهٔ آدرس ذخیره شود</translation> </message> <message> <source>&amp;Label:</source> <translation>&amp;برچسب:</translation> </message> <message> <source>Choose previously used address</source> <translation type="unfinished"/> </message> <message> <source>This is a normal payment.</source> <translation type="unfinished"/> </message> <message> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <source>Paste address from clipboard</source> <translation>چسباندن نشانی از حافظهٔ سیستم</translation> </message> <message> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <source>Remove this entry</source> <translation type="unfinished"/> </message> <message> <source>Message:</source> <translation>پیام:</translation> </message> <message> <source>This is a verified payment request.</source> <translation type="unfinished"/> </message> <message> <source>Enter a label for this address to add it to the list of used addresses</source> <translation type="unfinished"/> </message> <message> <source>A message that was attached to the argentum: URI which will be stored with the transaction for your reference. Note: This message will not be sent over the Argentum network.</source> <translation type="unfinished"/> </message> <message> <source>This is an unverified payment request.</source> <translation type="unfinished"/> </message> <message> <source>Pay To:</source> <translation type="unfinished"/> </message> <message> <source>Memo:</source> <translation type="unfinished"/> </message> </context> <context> <name>ShutdownWindow</name> <message> <source>Argentum Core is shutting down...</source> <translation type="unfinished"/> </message> <message> <source>Do not shut down the computer until this window disappears.</source> <translation type="unfinished"/> </message> </context> <context> <name>SignVerifyMessageDialog</name> <message> <source>Signatures - Sign / Verify a Message</source> <translation>امضاها - امضا / تأیید یک پیام</translation> </message> <message> <source>&amp;Sign Message</source> <translation>ا&amp;مضای پیام</translation> </message> <message> <source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source> <translation>برای احراز اینکه پیام‌ها از جانب شما هستند، می‌توانید آن‌ها را با نشانی خودتان امضا کنید. مراقب باشید چیزی که بدان اطمینان ندارید را امضا نکنید زیرا حملات فیشینگ ممکن است بخواهند از.پیامی با امضای شما سوءاستفاده کنند. تنها مواردی را که حاوی اطلاعات دقیق و قابل قبول برای شما هستند امضا کنید.</translation> </message> <message> <source>The address to sign the message with (e.g. AWRLWS0d6eEuu0qwsNBxkGxB4RV6FMo90X)</source> <translation>نشانی مورد استفاده برای امضا کردن پیام (برای مثال AWRLWS0d6eEuu0qwsNBxkGxB4RV6FMo90X)</translation> </message> <message> <source>Choose previously used address</source> <translation type="unfinished"/> </message> <message> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <source>Paste address from clipboard</source> <translation>چسباندن نشانی از حافظهٔ سیستم</translation> </message> <message> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <source>Enter the message you want to sign here</source> <translation>پیامی را که می‌خواهید امضا کنید در اینجا وارد کنید</translation> </message> <message> <source>Signature</source> <translation>امضا</translation> </message> <message> <source>Copy the current signature to the system clipboard</source> <translation>امضای فعلی را به حافظهٔ سیستم کپی کن</translation> </message> <message> <source>Sign the message to prove you own this Argentum address</source> <translation>برای اثبات تعلق این نشانی به شما، پیام را امضا کنید</translation> </message> <message> <source>Sign &amp;Message</source> <translation>ا&amp;مضای پیام</translation> </message> <message> <source>Reset all sign message fields</source> <translation>بازنشانی تمام فیلدهای پیام</translation> </message> <message> <source>Clear &amp;All</source> <translation>پاک &amp;کردن همه</translation> </message> <message> <source>&amp;Verify Message</source> <translation>&amp;شناسایی پیام</translation> </message> <message> <source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source> <translation>برای شناسایی پیام، نشانیِ امضا کننده و متن پیام را وارد کنید. (مطمئن شوید که فاصله‌ها، تب‌ها و خطوط را عیناً کپی می‌کنید.) مراقب باشید در امضا چیزی بیشتر از آنچه در پیام می‌بینید وجود نداشته باشد تا فریب دزدان اینترنتی و حملات از نوع MITM را نخورید.</translation> </message> <message> <source>The address the message was signed with (e.g. AWRLWS0d6eEuu0qwsNBxkGxB4RV6FMo90X)</source> <translation>نشانی مورد استفاده برای امضا کردن پیام (برای مثال AWRLWS0d6eEuu0qwsNBxkGxB4RV6FMo90X)</translation> </message> <message> <source>Verify the message to ensure it was signed with the specified Argentum address</source> <translation>برای حصول اطمینان از اینکه پیام با نشانی بیت‌کوین مشخص شده امضا است یا خیر، پیام را شناسایی کنید</translation> </message> <message> <source>Verify &amp;Message</source> <translation>&amp;شناسایی پیام</translation> </message> <message> <source>Reset all verify message fields</source> <translation>بازنشانی تمام فیلدهای پیام</translation> </message> <message> <source>Enter a Argentum address (e.g. AWRLWS0d6eEuu0qwsNBxkGxB4RV6FMo90X)</source> <translation>یک نشانی بیت‌کوین وارد کنید (مثلاً AWRLWS0d6eEuu0qwsNBxkGxB4RV6FMo90X)</translation> </message> <message> <source>Click &quot;Sign Message&quot; to generate signature</source> <translation>برای ایجاد یک امضای جدید روی «امضای پیام» کلیک کنید</translation> </message> <message> <source>The entered address is invalid.</source> <translation>نشانی وارد شده نامعتبر است.</translation> </message> <message> <source>Please check the address and try again.</source> <translation>لطفاً نشانی را بررسی کنید و دوباره تلاش کنید.</translation> </message> <message> <source>The entered address does not refer to a key.</source> <translation>نشانی وارد شده به هیچ کلیدی اشاره نمی‌کند.</translation> </message> <message> <source>Wallet unlock was cancelled.</source> <translation>عملیات باز کرن قفل کیف پول لغو شد.</translation> </message> <message> <source>Private key for the entered address is not available.</source> <translation>کلید خصوصی برای نشانی وارد شده در دسترس نیست.</translation> </message> <message> <source>Message signing failed.</source> <translation>امضای پیام با شکست مواجه شد.</translation> </message> <message> <source>Message signed.</source> <translation>پیام امضا شد.</translation> </message> <message> <source>The signature could not be decoded.</source> <translation>امضا نمی‌تواند کدگشایی شود.</translation> </message> <message> <source>Please check the signature and try again.</source> <translation>لطفاً امضا را بررسی نموده و دوباره تلاش کنید.</translation> </message> <message> <source>The signature did not match the message digest.</source> <translation>امضا با خلاصهٔ پیام مطابقت ندارد.</translation> </message> <message> <source>Message verification failed.</source> <translation>شناسایی پیام با شکست مواجه شد.</translation> </message> <message> <source>Message verified.</source> <translation>پیام شناسایی شد.</translation> </message> </context> <context> <name>SplashScreen</name> <message> <source>Argentum Core</source> <translation> هسته Argentum </translation> </message> <message> <source>The Argentum Core developers</source> <translation type="unfinished"/> </message> <message> <source>[testnet]</source> <translation>آزمایش شبکه</translation> </message> </context> <context> <name>TrafficGraphWidget</name> <message> <source>KB/s</source> <translation type="unfinished"/> </message> </context> <context> <name>TransactionDesc</name> <message> <source>Open until %1</source> <translation>باز تا %1</translation> </message> <message> <source>conflicted</source> <translation type="unfinished"/> </message> <message> <source>%1/offline</source> <translation>%1/آفلاین</translation> </message> <message> <source>%1/unconfirmed</source> <translation>%1/تأیید نشده</translation> </message> <message> <source>%1 confirmations</source> <translation>%1 تأییدیه</translation> </message> <message> <source>Status</source> <translation>وضعیت</translation> </message> <message numerus="yes"> <source>, broadcast through %n node(s)</source> <translation><numerusform>، پخش از طریق %n گره</numerusform></translation> </message> <message> <source>Date</source> <translation>تاریخ</translation> </message> <message> <source>Source</source> <translation>منبع</translation> </message> <message> <source>Generated</source> <translation>تولید شده</translation> </message> <message> <source>From</source> <translation>فرستنده</translation> </message> <message> <source>To</source> <translation>گیرنده</translation> </message> <message> <source>own address</source> <translation>آدرس شما</translation> </message> <message> <source>label</source> <translation>برچسب</translation> </message> <message> <source>Credit</source> <translation>بدهی</translation> </message> <message numerus="yes"> <source>matures in %n more block(s)</source> <translation><numerusform>بلوغ در %n بلوک دیگر</numerusform></translation> </message> <message> <source>not accepted</source> <translation>پذیرفته نشد</translation> </message> <message> <source>Debit</source> <translation>اعتبار</translation> </message> <message> <source>Transaction fee</source> <translation>هزینهٔ تراکنش</translation> </message> <message> <source>Net amount</source> <translation>مبلغ خالص</translation> </message> <message> <source>Message</source> <translation>پیام</translation> </message> <message> <source>Comment</source> <translation>نظر</translation> </message> <message> <source>Transaction ID</source> <translation>شناسهٔ تراکنش</translation> </message> <message> <source>Merchant</source> <translation type="unfinished"/> </message> <message> <source>Generated coins must mature %1 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to &quot;not accepted&quot; and it won&apos;t be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source> <translation type="unfinished"/> </message> <message> <source>Debug information</source> <translation>اطلاعات اشکال‌زدایی</translation> </message> <message> <source>Transaction</source> <translation>تراکنش</translation> </message> <message> <source>Inputs</source> <translation>ورودی‌ها</translation> </message> <message> <source>Amount</source> <translation>مبلغ</translation> </message> <message> <source>true</source> <translation>درست</translation> </message> <message> <source>false</source> <translation>نادرست</translation> </message> <message> <source>, has not been successfully broadcast yet</source> <translation>، هنوز با موفقیت ارسال نشده</translation> </message> <message numerus="yes"> <source>Open for %n more block(s)</source> <translation><numerusform>باز برای %n بلوک دیگر</numerusform></translation> </message> <message> <source>unknown</source> <translation>ناشناس</translation> </message> </context> <context> <name>TransactionDescDialog</name> <message> <source>Transaction details</source> <translation>جزئیات تراکنش</translation> </message> <message> <source>This pane shows a detailed description of the transaction</source> <translation>این پانل شامل توصیف کاملی از جزئیات تراکنش است</translation> </message> </context> <context> <name>TransactionTableModel</name> <message> <source>Date</source> <translation>تاریخ</translation> </message> <message> <source>Type</source> <translation>نوع</translation> </message> <message> <source>Address</source> <translation>نشانی</translation> </message> <message> <source>Amount</source> <translation>مبلغ</translation> </message> <message> <source>Immature (%1 confirmations, will be available after %2)</source> <translation type="unfinished"/> </message> <message numerus="yes"> <source>Open for %n more block(s)</source> <translation><numerusform>باز برای %n بلوک دیگر</numerusform></translation> </message> <message> <source>Open until %1</source> <translation>باز شده تا %1</translation> </message> <message> <source>Confirmed (%1 confirmations)</source> <translation>تأیید شده (%1 تأییدیه)</translation> </message> <message> <source>This block was not received by any other nodes and will probably not be accepted!</source> <translation>این بلوک از هیچ همتای دیگری دریافت نشده است و احتمال می‌رود پذیرفته نشود!</translation> </message> <message> <source>Generated but not accepted</source> <translation>تولید شده ولی قبول نشده</translation> </message> <message> <source>Offline</source> <translation type="unfinished"/> </message> <message> <source>Unconfirmed</source> <translation type="unfinished"/> </message> <message> <source>Confirming (%1 of %2 recommended confirmations)</source> <translation type="unfinished"/> </message> <message> <source>Conflicted</source> <translation type="unfinished"/> </message> <message> <source>Received with</source> <translation>دریافت‌شده با</translation> </message> <message> <source>Received from</source> <translation>دریافت‌شده از</translation> </message> <message> <source>Sent to</source> <translation>ارسال‌شده به</translation> </message> <message> <source>Payment to yourself</source> <translation>پر داخت به خودتان</translation> </message> <message> <source>Mined</source> <translation>استخراج‌شده</translation> </message> <message> <source>(n/a)</source> <translation>(ناموجود)</translation> </message> <message> <source>Transaction status. Hover over this field to show number of confirmations.</source> <translation>وضعیت تراکنش. نشانگر را روی این فیلد نگه دارید تا تعداد تأییدیه‌ها نشان داده شود.</translation> </message> <message> <source>Date and time that the transaction was received.</source> <translation>تاریخ و ساعت دریافت تراکنش.</translation> </message> <message> <source>Type of transaction.</source> <translation>نوع تراکنش.</translation> </message> <message> <source>Destination address of transaction.</source> <translation>نشانی مقصد تراکنش.</translation> </message> <message> <source>Amount removed from or added to balance.</source> <translation>مبلغ کسر شده و یا اضافه شده به تراز.</translation> </message> </context> <context> <name>TransactionView</name> <message> <source>All</source> <translation>همه</translation> </message> <message> <source>Today</source> <translation>امروز</translation> </message> <message> <source>This week</source> <translation>این هفته</translation> </message> <message> <source>This month</source> <translation>این ماه</translation> </message> <message> <source>Last month</source> <translation>ماه گذشته</translation> </message> <message> <source>This year</source> <translation>امسال</translation> </message> <message> <source>Range...</source> <translation>محدوده...</translation> </message> <message> <source>Received with</source> <translation>دریافت‌شده با </translation> </message> <message> <source>Sent to</source> <translation>ارسال به</translation> </message> <message> <source>To yourself</source> <translation>به خودتان</translation> </message> <message> <source>Mined</source> <translation>استخراج‌شده</translation> </message> <message> <source>Other</source> <translation>دیگر</translation> </message> <message> <source>Enter address or label to search</source> <translation>برای جست‌‌وجو نشانی یا برچسب را وارد کنید</translation> </message> <message> <source>Min amount</source> <translation>مبلغ حداقل</translation> </message> <message> <source>Copy address</source> <translation>کپی نشانی</translation> </message> <message> <source>Copy label</source> <translation>کپی برچسب</translation> </message> <message> <source>Copy amount</source> <translation>کپی مقدار</translation> </message> <message> <source>Copy transaction ID</source> <translation>کپی شناسهٔ تراکنش</translation> </message> <message> <source>Edit label</source> <translation>ویرایش برچسب</translation> </message> <message> <source>Show transaction details</source> <translation>نمایش جزئیات تراکنش</translation> </message> <message> <source>Export Transaction History</source> <translation type="unfinished"/> </message> <message> <source>Exporting Failed</source> <translation type="unfinished"/> </message> <message> <source>There was an error trying to save the transaction history to %1.</source> <translation type="unfinished"/> </message> <message> <source>Exporting Successful</source> <translation type="unfinished"/> </message> <message> <source>The transaction history was successfully saved to %1.</source> <translation type="unfinished"/> </message> <message> <source>Comma separated file (*.csv)</source> <translation>پروندهٔ نوع CSV جداشونده با کاما (*.csv)</translation> </message> <message> <source>Confirmed</source> <translation>تأیید شده</translation> </message> <message> <source>Date</source> <translation>تاریخ</translation> </message> <message> <source>Type</source> <translation>نوع</translation> </message> <message> <source>Label</source> <translation>برچسب</translation> </message> <message> <source>Address</source> <translation>نشانی</translation> </message> <message> <source>Amount</source> <translation>مبلغ</translation> </message> <message> <source>ID</source> <translation>شناسه</translation> </message> <message> <source>Range:</source> <translation>محدوده:</translation> </message> <message> <source>to</source> <translation>به</translation> </message> </context> <context> <name>WalletFrame</name> <message> <source>No wallet has been loaded.</source> <translation type="unfinished"/> </message> </context> <context> <name>WalletModel</name> <message> <source>Send Coins</source> <translation>ارسال وجه</translation> </message> </context> <context> <name>WalletView</name> <message> <source>&amp;Export</source> <translation>&amp;صدور</translation> </message> <message> <source>Export the data in the current tab to a file</source> <translation>داده ها نوارِ جاری را به فایل انتقال دهید</translation> </message> <message> <source>Backup Wallet</source> <translation>نسخهٔ پشتیبان کیف پول</translation> </message> <message> <source>Wallet Data (*.dat)</source> <translation>دادهٔ کیف پول (*.dat)</translation> </message> <message> <source>Backup Failed</source> <translation>خطا در پشتیبان‌گیری</translation> </message> <message> <source>There was an error trying to save the wallet data to %1.</source> <translation type="unfinished"/> </message> <message> <source>The wallet data was successfully saved to %1.</source> <translation type="unfinished"/> </message> <message> <source>Backup Successful</source> <translation>پشتیبان‌گیری موفق</translation> </message> </context> <context> <name>bitcoin-core</name> <message> <source>Usage:</source> <translation>استفاده:</translation> </message> <message> <source>List commands</source> <translation>نمایش لیست فرمان‌ها</translation> </message> <message> <source>Get help for a command</source> <translation>راهنمایی در مورد یک دستور</translation> </message> <message> <source>Options:</source> <translation>گزینه‌ها:</translation> </message> <message> <source>Specify configuration file (default: argentum.conf)</source> <translation>مشخص کردن فایل پیکربندی (پیش‌فرض: argentum.conf)</translation> </message> <message> <source>Specify pid file (default: bitcoind.pid)</source> <translation>مشخص کردن فایل شناسهٔ پردازش - pid - (پیش‌فرض: argentumd.pid)</translation> </message> <message> <source>Specify data directory</source> <translation>مشخص کردن دایرکتوری داده‌ها</translation> </message> <message> <source>Listen for connections on &lt;port&gt; (default: 8333 or testnet: 18333)</source> <translation>پذیرش اتصالات روی پورت &lt;port&gt; (پیش‌فرض: 8833 یا شبکهٔ آزمایشی: 18333)</translation> </message> <message> <source>Maintain at most &lt;n&gt; connections to peers (default: 125)</source> <translation>حداکثر &lt;n&gt; اتصال با همتایان برقرار شود (پیش‌فرض: ۱۲۵)</translation> </message> <message> <source>Connect to a node to retrieve peer addresses, and disconnect</source> <translation>اتصال به یک گره برای دریافت آدرس‌های همتا و قطع اتصال پس از اتمام عملیات</translation> </message> <message> <source>Specify your own public address</source> <translation>آدرس عمومی خود را مشخص کنید</translation> </message> <message> <source>Threshold for disconnecting misbehaving peers (default: 100)</source> <translation>حد آستانه برای قطع ارتباط با همتایان بدرفتار (پیش‌فرض: ۱۰۰)</translation> </message> <message> <source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source> <translation>مدت زمان جلوگیری از اتصال مجدد همتایان بدرفتار، به ثانیه (پیش‌فرض: ۸۴۶۰۰)</translation> </message> <message> <source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source> <translation>هنگام تنظیم پورت RPC %u برای گوش دادن روی IPv4 خطایی رخ داده است: %s</translation> </message> <message> <source>Listen for JSON-RPC connections on &lt;port&gt; (default: 8332 or testnet: 18332)</source> <translation>پورت مورد شنود برای اتصالات JSON-RPC (پیش‌فرض: 8332 برای شبکهٔ تست 18332)</translation> </message> <message> <source>Accept command line and JSON-RPC commands</source> <translation>پذیرش دستورات خط فرمان و دستورات JSON-RPC</translation> </message> <message> <source>Argentum Core RPC client version</source> <translation type="unfinished"/> </message> <message> <source>Run in the background as a daemon and accept commands</source> <translation>اجرا در پشت زمینه به‌صورت یک سرویس و پذیرش دستورات</translation> </message> <message> <source>Use the test network</source> <translation>استفاده از شبکهٔ آزمایش</translation> </message> <message> <source>Accept connections from outside (default: 1 if no -proxy or -connect)</source> <translation>پذیرش اتصالات از بیرون (پیش فرض:1 بدون پراکسی یا اتصال)</translation> </message> <message> <source>%s, you must set a rpcpassword in the configuration file: %s It is recommended you use the following random password: rpcuser=bitcoinrpc rpcpassword=%s (you do not need to remember this password) The username and password MUST NOT be the same. If the file does not exist, create it with owner-readable-only file permissions. It is also recommended to set alertnotify so you are notified of problems; for example: alertnotify=echo %%s | mail -s &quot;Argentum Alert&quot; admin@foo.com </source> <translation type="unfinished"/> </message> <message> <source>Acceptable ciphers (default: TLSv1.2+HIGH:TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!3DES:@STRENGTH)</source> <translation type="unfinished"/> </message> <message> <source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source> <translation type="unfinished"/> </message> <message> <source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source> <translation>مقید به نشانی داده شده باشید و همیشه از آن پیروی کنید. از نشانه گذاری استاندار IPv6 به صورت Host]:Port] استفاده کنید.</translation> </message> <message> <source>Continuously rate-limit free transactions to &lt;n&gt;*1000 bytes per minute (default:15)</source> <translation type="unfinished"/> </message> <message> <source>Enter regression test mode, which uses a special chain in which blocks can be solved instantly. This is intended for regression testing tools and app development.</source> <translation type="unfinished"/> </message> <message> <source>Enter regression test mode, which uses a special chain in which blocks can be solved instantly.</source> <translation type="unfinished"/> </message> <message> <source>Error: Listening for incoming connections failed (listen returned error %d)</source> <translation type="unfinished"/> </message> <message> <source>Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation>تراکنش پذیرفته نیست! این خطا ممکن است در حالتی رخ داده باشد که مقداری از سکه های شما در کیف پولتان از جایی دیگر، همانند یک کپی از کیف پول اصلی اتان، خرج شده باشد اما در کیف پول اصلی اتان به عنوان مبلغ خرج شده، نشانه گذاری نشده باشد.</translation> </message> <message> <source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!</source> <translation>خطا: این تراکنش به علت میزان وجه، دشواری، و یا استفاده از وجوه دریافتی اخیر نیازمند کارمزد به مبلغ حداقل %s است.</translation> </message> <message> <source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source> <translation>هنگامی که یک تراکنش در کیف پولی رخ می دهد، دستور را اجرا کن(%s در دستورات بوسیله ی TxID جایگزین می شود)</translation> </message> <message> <source>Fees smaller than this are considered zero fee (for transaction creation) (default:</source> <translation type="unfinished"/> </message> <message> <source>Flush database activity from memory pool to disk log every &lt;n&gt; megabytes (default: 100)</source> <translation type="unfinished"/> </message> <message> <source>How thorough the block verification of -checkblocks is (0-4, default: 3)</source> <translation type="unfinished"/> </message> <message> <source>In this mode -genproclimit controls how many blocks are generated immediately.</source> <translation type="unfinished"/> </message> <message> <source>Set the number of script verification threads (%u to %d, 0 = auto, &lt;0 = leave that many cores free, default: %d)</source> <translation type="unfinished"/> </message> <message> <source>Set the processor limit for when generation is on (-1 = unlimited, default: -1)</source> <translation type="unfinished"/> </message> <message> <source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source> <translation>این یک نسخه ی آزمایشی است - با مسئولیت خودتان از آن استفاده کنید - آن را در معدن و بازرگانی بکار نگیرید.</translation> </message> <message> <source>Unable to bind to %s on this computer. Argentum Core is probably already running.</source> <translation type="unfinished"/> </message> <message> <source>Use separate SOCKS5 proxy to reach peers via Tor hidden services (default: -proxy)</source> <translation type="unfinished"/> </message> <message> <source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source> <translation>هشدار: مبلغ paytxfee بسیار بالایی تنظیم شده است! این مبلغ هزینه‌ای است که شما برای تراکنش‌ها پرداخت می‌کنید.</translation> </message> <message> <source>Warning: Please check that your computer&apos;s date and time are correct! If your clock is wrong Argentum will not work properly.</source> <translation>هشدار: لطفا زمان و تاریخ رایانه خود را تصحیح نمایید! اگر ساعت رایانه شما اشتباه باشد bitcoin ممکن است صحیح کار نکند</translation> </message> <message> <source>Warning: The network does not appear to fully agree! Some miners appear to be experiencing issues.</source> <translation type="unfinished"/> </message> <message> <source>Warning: We do not appear to fully agree with our peers! You may need to upgrade, or other nodes may need to upgrade.</source> <translation type="unfinished"/> </message> <message> <source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source> <translation type="unfinished"/> </message> <message> <source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source> <translation type="unfinished"/> </message> <message> <source>(default: 1)</source> <translation type="unfinished"/> </message> <message> <source>(default: wallet.dat)</source> <translation type="unfinished"/> </message> <message> <source>&lt;category&gt; can be:</source> <translation type="unfinished"/> </message> <message> <source>Attempt to recover private keys from a corrupt wallet.dat</source> <translation type="unfinished"/> </message> <message> <source>Argentum Core Daemon</source> <translation type="unfinished"/> </message> <message> <source>Block creation options:</source> <translation>بستن گزینه ایجاد</translation> </message> <message> <source>Clear list of wallet transactions (diagnostic tool; implies -rescan)</source> <translation type="unfinished"/> </message> <message> <source>Connect only to the specified node(s)</source> <translation>تنها در گره (های) مشخص شده متصل شوید</translation> </message> <message> <source>Connect through SOCKS proxy</source> <translation type="unfinished"/> </message> <message> <source>Connect to JSON-RPC on &lt;port&gt; (default: 8332 or testnet: 18332)</source> <translation type="unfinished"/> </message> <message> <source>Connection options:</source> <translation type="unfinished"/> </message> <message> <source>Corrupted block database detected</source> <translation>یک پایگاه داده ی بلوک خراب یافت شد</translation> </message> <message> <source>Debugging/Testing options:</source> <translation type="unfinished"/> </message> <message> <source>Disable safemode, override a real safe mode event (default: 0)</source> <translation type="unfinished"/> </message> <message> <source>Discover own IP address (default: 1 when listening and no -externalip)</source> <translation>آدرس آی.پی. خود را شناسایی کنید (پیش فرض:1 در زمان when listening وno -externalip)</translation> </message> <message> <source>Do not load the wallet and disable wallet RPC calls</source> <translation type="unfinished"/> </message> <message> <source>Do you want to rebuild the block database now?</source> <translation>آیا مایلید که اکنون پایگاه داده ی بلوک را بازسازی کنید؟</translation> </message> <message> <source>Error initializing block database</source> <translation>خطا در آماده سازی پایگاه داده ی بلوک</translation> </message> <message> <source>Error initializing wallet database environment %s!</source> <translation type="unfinished"/> </message> <message> <source>Error loading block database</source> <translation>خطا در بارگذاری پایگاه داده ها</translation> </message> <message> <source>Error opening block database</source> <translation>خطا در بازگشایی پایگاه داده ی بلوک</translation> </message> <message> <source>Error: Disk space is low!</source> <translation type="unfinished"/> </message> <message> <source>Error: Wallet locked, unable to create transaction!</source> <translation type="unfinished"/> </message> <message> <source>Error: system error: </source> <translation>خطا: خطای سامانه:</translation> </message> <message> <source>Failed to listen on any port. Use -listen=0 if you want this.</source> <translation>شنیدن هر گونه درگاه انجام پذیر نیست. ازlisten=0 برای اینکار استفاده کیند.</translation> </message> <message> <source>Failed to read block info</source> <translation>خواندن اطلاعات بلوک با شکست مواجه شد</translation> </message> <message> <source>Failed to read block</source> <translation>خواندن بلوک با شکست مواجه شد</translation> </message> <message> <source>Failed to sync block index</source> <translation>همگام سازی فهرست بلوک با شکست مواجه شد</translation> </message> <message> <source>Failed to write block index</source> <translation>نوشتن فهرست بلوک با شکست مواجه شد</translation> </message> <message> <source>Failed to write block info</source> <translation>نوشتن اطلاعات بلوک با شکست مواجه شد</translation> </message> <message> <source>Failed to write block</source> <translation>نوشتن بلوک با شکست مواجه شد</translation> </message> <message> <source>Failed to write file info</source> <translation>نوشتن اطلاعات پرونده با شکست مواجه شد</translation> </message> <message> <source>Failed to write to coin database</source> <translation>نوشتن اطلاعات در پایگاه داده ی سکه ها با شکست مواجه شد</translation> </message> <message> <source>Failed to write transaction index</source> <translation>نوشتن فهرست تراکنش ها با شکست مواجه شد</translation> </message> <message> <source>Failed to write undo data</source> <translation>عملیات بازگشت دادن اطلاعات با شکست مواجه شدن</translation> </message> <message> <source>Fee per kB to add to transactions you send</source> <translation>نرخ هر کیلوبایت برای اضافه کردن به تراکنش‌هایی که می‌فرستید</translation> </message> <message> <source>Fees smaller than this are considered zero fee (for relaying) (default:</source> <translation type="unfinished"/> </message> <message> <source>Find peers using DNS lookup (default: 1 unless -connect)</source> <translation>قرینه ها را برای جستجوی DNS بیاب (پیش فرض: 1 مگر در زمان اتصال)</translation> </message> <message> <source>Force safe mode (default: 0)</source> <translation type="unfinished"/> </message> <message> <source>Generate coins (default: 0)</source> <translation type="unfinished"/> </message> <message> <source>How many blocks to check at startup (default: 288, 0 = all)</source> <translation>چند بلوک نیاز است که در ابتدای راه اندازی بررسی شوند(پیش فرض:288 ،0=همه)</translation> </message> <message> <source>If &lt;category&gt; is not supplied, output all debugging information.</source> <translation type="unfinished"/> </message> <message> <source>Importing...</source> <translation type="unfinished"/> </message> <message> <source>Incorrect or no genesis block found. Wrong datadir for network?</source> <translation type="unfinished"/> </message> <message> <source>Invalid -onion address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <source>Not enough file descriptors available.</source> <translation type="unfinished"/> </message> <message> <source>Prepend debug output with timestamp (default: 1)</source> <translation type="unfinished"/> </message> <message> <source>RPC client options:</source> <translation type="unfinished"/> </message> <message> <source>Rebuild block chain index from current blk000??.dat files</source> <translation type="unfinished"/> </message> <message> <source>Select SOCKS version for -proxy (4 or 5, default: 5)</source> <translation type="unfinished"/> </message> <message> <source>Set database cache size in megabytes (%d to %d, default: %d)</source> <translation type="unfinished"/> </message> <message> <source>Set maximum block size in bytes (default: %d)</source> <translation type="unfinished"/> </message> <message> <source>Set the number of threads to service RPC calls (default: 4)</source> <translation type="unfinished"/> </message> <message> <source>Specify wallet file (within data directory)</source> <translation type="unfinished"/> </message> <message> <source>Spend unconfirmed change when sending transactions (default: 1)</source> <translation type="unfinished"/> </message> <message> <source>This is intended for regression testing tools and app development.</source> <translation type="unfinished"/> </message> <message> <source>Usage (deprecated, use argentum-cli):</source> <translation type="unfinished"/> </message> <message> <source>Verifying blocks...</source> <translation>در حال بازبینی بلوک ها...</translation> </message> <message> <source>Verifying wallet...</source> <translation>در حال بازبینی کیف پول...</translation> </message> <message> <source>Wait for RPC server to start</source> <translation type="unfinished"/> </message> <message> <source>Wallet %s resides outside data directory %s</source> <translation type="unfinished"/> </message> <message> <source>Wallet options:</source> <translation type="unfinished"/> </message> <message> <source>Warning: Deprecated argument -debugnet ignored, use -debug=net</source> <translation type="unfinished"/> </message> <message> <source>You need to rebuild the database using -reindex to change -txindex</source> <translation type="unfinished"/> </message> <message> <source>Imports blocks from external blk000??.dat file</source> <translation type="unfinished"/> </message> <message> <source>Cannot obtain a lock on data directory %s. Argentum Core is probably already running.</source> <translation type="unfinished"/> </message> <message> <source>Execute command when a relevant alert is received or we see a really long fork (%s in cmd is replaced by message)</source> <translation type="unfinished"/> </message> <message> <source>Output debugging information (default: 0, supplying &lt;category&gt; is optional)</source> <translation type="unfinished"/> </message> <message> <source>Set maximum size of high-priority/low-fee transactions in bytes (default: %d)</source> <translation type="unfinished"/> </message> <message> <source>Information</source> <translation>اطلاعات</translation> </message> <message> <source>Invalid amount for -minrelaytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <source>Invalid amount for -mintxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <source>Limit size of signature cache to &lt;n&gt; entries (default: 50000)</source> <translation type="unfinished"/> </message> <message> <source>Log transaction priority and fee per kB when mining blocks (default: 0)</source> <translation type="unfinished"/> </message> <message> <source>Maintain a full transaction index (default: 0)</source> <translation type="unfinished"/> </message> <message> <source>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: 5000)</source> <translation>حداکثر بافر دریافت شده بر اساس اتصال &lt;n&gt;* 1000 بایت (پیش فرض:5000)</translation> </message> <message> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: 1000)</source> <translation>حداکثر بافر دریافت شده بر اساس اتصال &lt;n&gt;* 1000 بایت (پیش فرض:1000)</translation> </message> <message> <source>Only accept block chain matching built-in checkpoints (default: 1)</source> <translation type="unfinished"/> </message> <message> <source>Only connect to nodes in network &lt;net&gt; (IPv4, IPv6 or Tor)</source> <translation>تنها =به گره ها در شبکه متصا شوید &lt;net&gt; (IPv4, IPv6 or Tor)</translation> </message> <message> <source>Print block on startup, if found in block index</source> <translation type="unfinished"/> </message> <message> <source>Print block tree on startup (default: 0)</source> <translation type="unfinished"/> </message> <message> <source>RPC SSL options: (see the Bitcoin Wiki for SSL setup instructions)</source> <translation type="unfinished"/> </message> <message> <source>RPC server options:</source> <translation type="unfinished"/> </message> <message> <source>Randomly drop 1 of every &lt;n&gt; network messages</source> <translation type="unfinished"/> </message> <message> <source>Randomly fuzz 1 of every &lt;n&gt; network messages</source> <translation type="unfinished"/> </message> <message> <source>Run a thread to flush wallet periodically (default: 1)</source> <translation type="unfinished"/> </message> <message> <source>SSL options: (see the Bitcoin Wiki for SSL setup instructions)</source> <translation>گزینه ssl (به ویکیbitcoin برای راهنمای راه اندازی ssl مراجعه شود)</translation> </message> <message> <source>Send command to Argentum Core</source> <translation type="unfinished"/> </message> <message> <source>Send trace/debug info to console instead of debug.log file</source> <translation>اطلاعات ردگیری/اشکال‌زدایی را به جای فایل لاگ اشکال‌زدایی به کنسول بفرستید</translation> </message> <message> <source>Set minimum block size in bytes (default: 0)</source> <translation>حداقل سایز بلاک بر اساس بایت تنظیم شود (پیش فرض: 0)</translation> </message> <message> <source>Sets the DB_PRIVATE flag in the wallet db environment (default: 1)</source> <translation type="unfinished"/> </message> <message> <source>Show all debugging options (usage: --help -help-debug)</source> <translation type="unfinished"/> </message> <message> <source>Show benchmark information (default: 0)</source> <translation type="unfinished"/> </message> <message> <source>Shrink debug.log file on client startup (default: 1 when no -debug)</source> <translation>فایل debug.log را در startup مشتری کوچک کن (پیش فرض:1 اگر اشکال زدایی روی نداد)</translation> </message> <message> <source>Signing transaction failed</source> <translation type="unfinished"/> </message> <message> <source>Specify connection timeout in milliseconds (default: 5000)</source> <translation>(میلی ثانیه )فاصله ارتباط خاص</translation> </message> <message> <source>Start Argentum Core Daemon</source> <translation type="unfinished"/> </message> <message> <source>System error: </source> <translation>خطای سامانه</translation> </message> <message> <source>Transaction amount too small</source> <translation type="unfinished"/> </message> <message> <source>Transaction amounts must be positive</source> <translation type="unfinished"/> </message> <message> <source>Transaction too large</source> <translation type="unfinished"/> </message> <message> <source>Use UPnP to map the listening port (default: 0)</source> <translation>از UPnP برای شناسایی درگاه شنیداری استفاده کنید (پیش فرض:0)</translation> </message> <message> <source>Use UPnP to map the listening port (default: 1 when listening)</source> <translation>از UPnP برای شناسایی درگاه شنیداری استفاده کنید (پیش فرض:1 در زمان شنیدن)</translation> </message> <message> <source>Username for JSON-RPC connections</source> <translation>JSON-RPC شناسه برای ارتباطات</translation> </message> <message> <source>Warning</source> <translation>هشدار</translation> </message> <message> <source>Warning: This version is obsolete, upgrade required!</source> <translation>هشدار: این نسخه قدیمی است، روزآمدسازی مورد نیاز است</translation> </message> <message> <source>Zapping all transactions from wallet...</source> <translation type="unfinished"/> </message> <message> <source>on startup</source> <translation type="unfinished"/> </message> <message> <source>version</source> <translation>نسخه</translation> </message> <message> <source>wallet.dat corrupt, salvage failed</source> <translation type="unfinished"/> </message> <message> <source>Password for JSON-RPC connections</source> <translation>JSON-RPC عبارت عبور برای ارتباطات</translation> </message> <message> <source>Allow JSON-RPC connections from specified IP address</source> <translation>از آدرس آی پی خاص JSON-RPC قبول ارتباطات</translation> </message> <message> <source>Send commands to node running on &lt;ip&gt; (default: 127.0.0.1)</source> <translation>(127.0.0.1پیش فرض: ) &amp;lt;ip&amp;gt; دادن فرمانها برای استفاده گره ها روی</translation> </message> <message> <source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source> <translation>زمانی که بهترین بلاک تغییر کرد، دستور را اجرا کن (%s در cmd با block hash جایگزین شده است)</translation> </message> <message> <source>Upgrade wallet to latest format</source> <translation>wallet را به جدیدترین فرمت روزآمد کنید</translation> </message> <message> <source>Set key pool size to &lt;n&gt; (default: 100)</source> <translation> (100پیش فرض:)&amp;lt;n&amp;gt; گذاشتن اندازه کلید روی </translation> </message> <message> <source>Rescan the block chain for missing wallet transactions</source> <translation>اسکان مجدد زنجیر بلوکها برای گم والت معامله</translation> </message> <message> <source>Use OpenSSL (https) for JSON-RPC connections</source> <translation>JSON-RPCبرای ارتباطات استفاده کنید OpenSSL (https)</translation> </message> <message> <source>Server certificate file (default: server.cert)</source> <translation> (server.certپیش فرض: )گواهی نامه سرور</translation> </message> <message> <source>Server private key (default: server.pem)</source> <translation>(server.pemپیش فرض: ) کلید خصوصی سرور</translation> </message> <message> <source>This help message</source> <translation>پیام کمکی</translation> </message> <message> <source>Unable to bind to %s on this computer (bind returned error %d, %s)</source> <translation>امکان اتصال به %s از این رایانه وجود ندارد ( bind returned error %d, %s)</translation> </message> <message> <source>Allow DNS lookups for -addnode, -seednode and -connect</source> <translation>به DNS اجازه بده تا برای addnode ، seednode و اتصال جستجو کند</translation> </message> <message> <source>Loading addresses...</source> <translation>بار گیری آدرس ها</translation> </message> <message> <source>Error loading wallet.dat: Wallet corrupted</source> <translation>خطا در بارگیری wallet.dat: کیف پول خراب شده است</translation> </message> <message> <source>Error loading wallet.dat: Wallet requires newer version of Argentum</source> <translation>خطا در بارگیری wallet.dat: کیف پول به ویرایش جدیدتری از Biticon نیاز دارد</translation> </message> <message> <source>Wallet needed to be rewritten: restart Argentum to complete</source> <translation>سلام</translation> </message> <message> <source>Error loading wallet.dat</source> <translation>خطا در بارگیری wallet.dat</translation> </message> <message> <source>Invalid -proxy address: &apos;%s&apos;</source> <translation>آدرس پراکسی اشتباه %s</translation> </message> <message> <source>Unknown network specified in -onlynet: &apos;%s&apos;</source> <translation>شبکه مشخص شده غیرقابل شناسایی در onlynet: &apos;%s&apos;</translation> </message> <message> <source>Unknown -socks proxy version requested: %i</source> <translation>نسخه پراکسی ساکس غیرقابل شناسایی درخواست شده است: %i</translation> </message> <message> <source>Cannot resolve -bind address: &apos;%s&apos;</source> <translation>آدرس قابل اتصال- شناسایی نیست %s</translation> </message> <message> <source>Cannot resolve -externalip address: &apos;%s&apos;</source> <translation>آدرس خارجی قابل اتصال- شناسایی نیست %s</translation> </message> <message> <source>Invalid amount for -paytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation>میزان وجه اشتباه برای paytxfee=&lt;میزان وجه&gt;: %s</translation> </message> <message> <source>Invalid amount</source> <translation>میزان وجه اشتباه</translation> </message> <message> <source>Insufficient funds</source> <translation>بود جه نا کافی </translation> </message> <message> <source>Loading block index...</source> <translation>بار گیری شاخص بلوک</translation> </message> <message> <source>Add a node to connect to and attempt to keep the connection open</source> <translation>به اتصال یک گره اضافه کنید و اتصال را باز نگاه دارید</translation> </message> <message> <source>Loading wallet...</source> <translation>بار گیری والت</translation> </message> <message> <source>Cannot downgrade wallet</source> <translation>امکان تنزل نسخه در wallet وجود ندارد</translation> </message> <message> <source>Cannot write default address</source> <translation>آدرس پیش فرض قابل ذخیره نیست</translation> </message> <message> <source>Rescanning...</source> <translation>اسکان مجدد</translation> </message> <message> <source>Done loading</source> <translation>بار گیری انجام شده است</translation> </message> <message> <source>To use the %s option</source> <translation>برای استفاده از %s از انتخابات</translation> </message> <message> <source>Error</source> <translation>خطا</translation> </message> <message> <source>You must set rpcpassword=&lt;password&gt; in the configuration file: %s If the file does not exist, create it with owner-readable-only file permissions.</source> <translation>، شما باید یک rpcpassword را در فایل پیکربندی تنظیم کنید :⏎%s⏎ اگر فایل ایجاد نشد، یک فایل فقط متنی ایجاد کنید. </translation> </message> </context> </TS>
Cryptcollector/ARG2.0
src/qt/locale/bitcoin_fa.ts
TypeScript
mit
135,299
import { readFileSync } from 'fs'; import { createServer } from 'http'; import { parse } from 'url'; import { join } from 'path'; var server = createServer(function(req, res) { let path = parse(req.url, true).query.path; // BAD: This could read any file on the file system res.write(readFileSync(join("public", path))); });
github/codeql
javascript/ql/test/query-tests/Security/CWE-022/TaintedPath/TaintedPath-es6.js
JavaScript
mit
332
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. #nullable enable #pragma warning disable CS0618 // Type or member is obsolete using DocumentFormat.OpenXml; using DocumentFormat.OpenXml.Drawing; using DocumentFormat.OpenXml.Drawing.Charts; using DocumentFormat.OpenXml.Framework; using DocumentFormat.OpenXml.Framework.Metadata; using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Validation.Schema; using System; using System.Collections.Generic; using System.IO.Packaging; namespace DocumentFormat.OpenXml.Office2013.Drawing.Chart { /// <summary> /// <para>Defines the PivotSource Class.</para> /// <para>This class is available in Office 2013 and above.</para> /// <para>When the object is serialized out as xml, it's qualified name is c15:pivotSource.</para> /// </summary> /// <remark> /// <para>The following table lists the possible child types:</para> /// <list type="bullet"> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.ExtensionList" /> <c>&lt;c:extLst></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.FormatId" /> <c>&lt;c:fmtId></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.PivotTableName" /> <c>&lt;c:name></c></description></item> /// </list> /// </remark> [SchemaAttr("c15:pivotSource")] public partial class PivotSource : OpenXmlCompositeElement { /// <summary> /// Initializes a new instance of the PivotSource class. /// </summary> public PivotSource() : base() { } /// <summary> /// Initializes a new instance of the PivotSource class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public PivotSource(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the PivotSource class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public PivotSource(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the PivotSource class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public PivotSource(string outerXml) : base(outerXml) { } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.SetSchema("c15:pivotSource"); builder.Availability = FileFormatVersions.Office2013; builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.ExtensionList>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.FormatId>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.PivotTableName>(); builder.Particle = new CompositeParticle.Builder(ParticleType.Sequence, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.PivotTableName), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.FormatId), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.ExtensionList), 0, 1) }; } /// <summary> /// <para>Pivot Name.</para> /// <para>Represents the following element tag in the schema: c:name.</para> /// </summary> /// <remark> /// xmlns:c = http://schemas.openxmlformats.org/drawingml/2006/chart /// </remark> public DocumentFormat.OpenXml.Drawing.Charts.PivotTableName? PivotTableName { get => GetElement<DocumentFormat.OpenXml.Drawing.Charts.PivotTableName>(); set => SetElement(value); } /// <summary> /// <para>Format ID.</para> /// <para>Represents the following element tag in the schema: c:fmtId.</para> /// </summary> /// <remark> /// xmlns:c = http://schemas.openxmlformats.org/drawingml/2006/chart /// </remark> public DocumentFormat.OpenXml.Drawing.Charts.FormatId? FormatId { get => GetElement<DocumentFormat.OpenXml.Drawing.Charts.FormatId>(); set => SetElement(value); } /// <summary> /// <para>Chart Extensibility.</para> /// <para>Represents the following element tag in the schema: c:extLst.</para> /// </summary> /// <remark> /// xmlns:c = http://schemas.openxmlformats.org/drawingml/2006/chart /// </remark> public DocumentFormat.OpenXml.Drawing.Charts.ExtensionList? ExtensionList { get => GetElement<DocumentFormat.OpenXml.Drawing.Charts.ExtensionList>(); set => SetElement(value); } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<PivotSource>(deep); } /// <summary> /// <para>Defines the NumberingFormat Class.</para> /// <para>This class is available in Office 2013 and above.</para> /// <para>When the object is serialized out as xml, it's qualified name is c15:numFmt.</para> /// </summary> [SchemaAttr("c15:numFmt")] public partial class NumberingFormat : OpenXmlLeafElement { /// <summary> /// Initializes a new instance of the NumberingFormat class. /// </summary> public NumberingFormat() : base() { } /// <summary> /// <para>Number Format Code</para> /// <para>Represents the following attribute in the schema: formatCode</para> /// </summary> [SchemaAttr("formatCode")] public StringValue? FormatCode { get => GetAttribute<StringValue>(); set => SetAttribute(value); } /// <summary> /// <para>Linked to Source</para> /// <para>Represents the following attribute in the schema: sourceLinked</para> /// </summary> [SchemaAttr("sourceLinked")] public BooleanValue? SourceLinked { get => GetAttribute<BooleanValue>(); set => SetAttribute(value); } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.SetSchema("c15:numFmt"); builder.Availability = FileFormatVersions.Office2013; builder.AddElement<NumberingFormat>() .AddAttribute("formatCode", a => a.FormatCode, aBuilder => { aBuilder.AddValidator(RequiredValidator.Instance); }) .AddAttribute("sourceLinked", a => a.SourceLinked); } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<NumberingFormat>(deep); } /// <summary> /// <para>Defines the ShapeProperties Class.</para> /// <para>This class is available in Office 2013 and above.</para> /// <para>When the object is serialized out as xml, it's qualified name is c15:spPr.</para> /// </summary> /// <remark> /// <para>The following table lists the possible child types:</para> /// <list type="bullet"> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.BlipFill" /> <c>&lt;a:blipFill></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.CustomGeometry" /> <c>&lt;a:custGeom></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.EffectDag" /> <c>&lt;a:effectDag></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.EffectList" /> <c>&lt;a:effectLst></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.GradientFill" /> <c>&lt;a:gradFill></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.GroupFill" /> <c>&lt;a:grpFill></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Outline" /> <c>&lt;a:ln></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.NoFill" /> <c>&lt;a:noFill></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.PatternFill" /> <c>&lt;a:pattFill></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.PresetGeometry" /> <c>&lt;a:prstGeom></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Scene3DType" /> <c>&lt;a:scene3d></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Shape3DType" /> <c>&lt;a:sp3d></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.ShapePropertiesExtensionList" /> <c>&lt;a:extLst></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.SolidFill" /> <c>&lt;a:solidFill></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Transform2D" /> <c>&lt;a:xfrm></c></description></item> /// </list> /// </remark> [SchemaAttr("c15:spPr")] public partial class ShapeProperties : OpenXmlCompositeElement { /// <summary> /// Initializes a new instance of the ShapeProperties class. /// </summary> public ShapeProperties() : base() { } /// <summary> /// Initializes a new instance of the ShapeProperties class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public ShapeProperties(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the ShapeProperties class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public ShapeProperties(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the ShapeProperties class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public ShapeProperties(string outerXml) : base(outerXml) { } /// <summary> /// <para>Black and White Mode</para> /// <para>Represents the following attribute in the schema: bwMode</para> /// </summary> [SchemaAttr("bwMode")] public EnumValue<DocumentFormat.OpenXml.Drawing.BlackWhiteModeValues>? BlackWhiteMode { get => GetAttribute<EnumValue<DocumentFormat.OpenXml.Drawing.BlackWhiteModeValues>>(); set => SetAttribute(value); } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.SetSchema("c15:spPr"); builder.Availability = FileFormatVersions.Office2013; builder.AddChild<DocumentFormat.OpenXml.Drawing.BlipFill>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.CustomGeometry>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.EffectDag>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.EffectList>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.GradientFill>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.GroupFill>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Outline>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.NoFill>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.PatternFill>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.PresetGeometry>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Scene3DType>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Shape3DType>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.ShapePropertiesExtensionList>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.SolidFill>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Transform2D>(); builder.AddElement<ShapeProperties>() .AddAttribute("bwMode", a => a.BlackWhiteMode, aBuilder => { aBuilder.AddValidator(new StringValidator() { IsToken = (true) }); }); builder.Particle = new CompositeParticle.Builder(ParticleType.Sequence, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Transform2D), 0, 1), new CompositeParticle.Builder(ParticleType.Group, 0, 1) { new CompositeParticle.Builder(ParticleType.Choice, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.CustomGeometry), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.PresetGeometry), 1, 1) } }, new CompositeParticle.Builder(ParticleType.Group, 0, 1) { new CompositeParticle.Builder(ParticleType.Choice, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.NoFill), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.SolidFill), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.GradientFill), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.BlipFill), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.PatternFill), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.GroupFill), 1, 1) } }, new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Outline), 0, 1), new CompositeParticle.Builder(ParticleType.Group, 0, 1) { new CompositeParticle.Builder(ParticleType.Choice, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.EffectList), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.EffectDag), 1, 1) } }, new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Scene3DType), 0, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Shape3DType), 0, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.ShapePropertiesExtensionList), 0, 1) }; } /// <summary> /// <para>2D Transform for Individual Objects.</para> /// <para>Represents the following element tag in the schema: a:xfrm.</para> /// </summary> /// <remark> /// xmlns:a = http://schemas.openxmlformats.org/drawingml/2006/main /// </remark> public DocumentFormat.OpenXml.Drawing.Transform2D? Transform2D { get => GetElement<DocumentFormat.OpenXml.Drawing.Transform2D>(); set => SetElement(value); } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<ShapeProperties>(deep); } /// <summary> /// <para>Defines the Layout Class.</para> /// <para>This class is available in Office 2013 and above.</para> /// <para>When the object is serialized out as xml, it's qualified name is c15:layout.</para> /// </summary> /// <remark> /// <para>The following table lists the possible child types:</para> /// <list type="bullet"> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.ExtensionList" /> <c>&lt;c:extLst></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.ManualLayout" /> <c>&lt;c:manualLayout></c></description></item> /// </list> /// </remark> [SchemaAttr("c15:layout")] public partial class Layout : OpenXmlCompositeElement { /// <summary> /// Initializes a new instance of the Layout class. /// </summary> public Layout() : base() { } /// <summary> /// Initializes a new instance of the Layout class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public Layout(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the Layout class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public Layout(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the Layout class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public Layout(string outerXml) : base(outerXml) { } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.SetSchema("c15:layout"); builder.Availability = FileFormatVersions.Office2013; builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.ExtensionList>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.ManualLayout>(); builder.Particle = new CompositeParticle.Builder(ParticleType.Sequence, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.ManualLayout), 0, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.ExtensionList), 0, 1) }; } /// <summary> /// <para>Manual Layout.</para> /// <para>Represents the following element tag in the schema: c:manualLayout.</para> /// </summary> /// <remark> /// xmlns:c = http://schemas.openxmlformats.org/drawingml/2006/chart /// </remark> public DocumentFormat.OpenXml.Drawing.Charts.ManualLayout? ManualLayout { get => GetElement<DocumentFormat.OpenXml.Drawing.Charts.ManualLayout>(); set => SetElement(value); } /// <summary> /// <para>Chart Extensibility.</para> /// <para>Represents the following element tag in the schema: c:extLst.</para> /// </summary> /// <remark> /// xmlns:c = http://schemas.openxmlformats.org/drawingml/2006/chart /// </remark> public DocumentFormat.OpenXml.Drawing.Charts.ExtensionList? ExtensionList { get => GetElement<DocumentFormat.OpenXml.Drawing.Charts.ExtensionList>(); set => SetElement(value); } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<Layout>(deep); } /// <summary> /// <para>Defines the FullReference Class.</para> /// <para>This class is available in Office 2013 and above.</para> /// <para>When the object is serialized out as xml, it's qualified name is c15:fullRef.</para> /// </summary> /// <remark> /// <para>The following table lists the possible child types:</para> /// <list type="bullet"> /// <item><description><see cref="DocumentFormat.OpenXml.Office2013.Drawing.Chart.SequenceOfReferences" /> <c>&lt;c15:sqref></c></description></item> /// </list> /// </remark> [SchemaAttr("c15:fullRef")] public partial class FullReference : OpenXmlCompositeElement { /// <summary> /// Initializes a new instance of the FullReference class. /// </summary> public FullReference() : base() { } /// <summary> /// Initializes a new instance of the FullReference class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public FullReference(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the FullReference class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public FullReference(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the FullReference class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public FullReference(string outerXml) : base(outerXml) { } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.SetSchema("c15:fullRef"); builder.Availability = FileFormatVersions.Office2013; builder.AddChild<DocumentFormat.OpenXml.Office2013.Drawing.Chart.SequenceOfReferences>(); builder.Particle = new CompositeParticle.Builder(ParticleType.Sequence, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Office2013.Drawing.Chart.SequenceOfReferences), 1, 1, version: FileFormatVersions.Office2013) }; } /// <summary> /// <para>SequenceOfReferences.</para> /// <para>Represents the following element tag in the schema: c15:sqref.</para> /// </summary> /// <remark> /// xmlns:c15 = http://schemas.microsoft.com/office/drawing/2012/chart /// </remark> public DocumentFormat.OpenXml.Office2013.Drawing.Chart.SequenceOfReferences? SequenceOfReferences { get => GetElement<DocumentFormat.OpenXml.Office2013.Drawing.Chart.SequenceOfReferences>(); set => SetElement(value); } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<FullReference>(deep); } /// <summary> /// <para>Defines the LevelReference Class.</para> /// <para>This class is available in Office 2013 and above.</para> /// <para>When the object is serialized out as xml, it's qualified name is c15:levelRef.</para> /// </summary> /// <remark> /// <para>The following table lists the possible child types:</para> /// <list type="bullet"> /// <item><description><see cref="DocumentFormat.OpenXml.Office2013.Drawing.Chart.SequenceOfReferences" /> <c>&lt;c15:sqref></c></description></item> /// </list> /// </remark> [SchemaAttr("c15:levelRef")] public partial class LevelReference : OpenXmlCompositeElement { /// <summary> /// Initializes a new instance of the LevelReference class. /// </summary> public LevelReference() : base() { } /// <summary> /// Initializes a new instance of the LevelReference class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public LevelReference(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the LevelReference class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public LevelReference(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the LevelReference class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public LevelReference(string outerXml) : base(outerXml) { } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.SetSchema("c15:levelRef"); builder.Availability = FileFormatVersions.Office2013; builder.AddChild<DocumentFormat.OpenXml.Office2013.Drawing.Chart.SequenceOfReferences>(); builder.Particle = new CompositeParticle.Builder(ParticleType.Sequence, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Office2013.Drawing.Chart.SequenceOfReferences), 1, 1, version: FileFormatVersions.Office2013) }; } /// <summary> /// <para>SequenceOfReferences.</para> /// <para>Represents the following element tag in the schema: c15:sqref.</para> /// </summary> /// <remark> /// xmlns:c15 = http://schemas.microsoft.com/office/drawing/2012/chart /// </remark> public DocumentFormat.OpenXml.Office2013.Drawing.Chart.SequenceOfReferences? SequenceOfReferences { get => GetElement<DocumentFormat.OpenXml.Office2013.Drawing.Chart.SequenceOfReferences>(); set => SetElement(value); } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<LevelReference>(deep); } /// <summary> /// <para>Defines the FormulaReference Class.</para> /// <para>This class is available in Office 2013 and above.</para> /// <para>When the object is serialized out as xml, it's qualified name is c15:formulaRef.</para> /// </summary> /// <remark> /// <para>The following table lists the possible child types:</para> /// <list type="bullet"> /// <item><description><see cref="DocumentFormat.OpenXml.Office2013.Drawing.Chart.SequenceOfReferences" /> <c>&lt;c15:sqref></c></description></item> /// </list> /// </remark> [SchemaAttr("c15:formulaRef")] public partial class FormulaReference : OpenXmlCompositeElement { /// <summary> /// Initializes a new instance of the FormulaReference class. /// </summary> public FormulaReference() : base() { } /// <summary> /// Initializes a new instance of the FormulaReference class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public FormulaReference(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the FormulaReference class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public FormulaReference(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the FormulaReference class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public FormulaReference(string outerXml) : base(outerXml) { } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.SetSchema("c15:formulaRef"); builder.Availability = FileFormatVersions.Office2013; builder.AddChild<DocumentFormat.OpenXml.Office2013.Drawing.Chart.SequenceOfReferences>(); builder.Particle = new CompositeParticle.Builder(ParticleType.Sequence, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Office2013.Drawing.Chart.SequenceOfReferences), 1, 1, version: FileFormatVersions.Office2013) }; } /// <summary> /// <para>SequenceOfReferences.</para> /// <para>Represents the following element tag in the schema: c15:sqref.</para> /// </summary> /// <remark> /// xmlns:c15 = http://schemas.microsoft.com/office/drawing/2012/chart /// </remark> public DocumentFormat.OpenXml.Office2013.Drawing.Chart.SequenceOfReferences? SequenceOfReferences { get => GetElement<DocumentFormat.OpenXml.Office2013.Drawing.Chart.SequenceOfReferences>(); set => SetElement(value); } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<FormulaReference>(deep); } /// <summary> /// <para>Defines the FilteredSeriesTitle Class.</para> /// <para>This class is available in Office 2013 and above.</para> /// <para>When the object is serialized out as xml, it's qualified name is c15:filteredSeriesTitle.</para> /// </summary> /// <remark> /// <para>The following table lists the possible child types:</para> /// <list type="bullet"> /// <item><description><see cref="DocumentFormat.OpenXml.Office2013.Drawing.Chart.ChartText" /> <c>&lt;c15:tx></c></description></item> /// </list> /// </remark> [SchemaAttr("c15:filteredSeriesTitle")] public partial class FilteredSeriesTitle : OpenXmlCompositeElement { /// <summary> /// Initializes a new instance of the FilteredSeriesTitle class. /// </summary> public FilteredSeriesTitle() : base() { } /// <summary> /// Initializes a new instance of the FilteredSeriesTitle class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public FilteredSeriesTitle(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the FilteredSeriesTitle class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public FilteredSeriesTitle(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the FilteredSeriesTitle class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public FilteredSeriesTitle(string outerXml) : base(outerXml) { } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.SetSchema("c15:filteredSeriesTitle"); builder.Availability = FileFormatVersions.Office2013; builder.AddChild<DocumentFormat.OpenXml.Office2013.Drawing.Chart.ChartText>(); builder.Particle = new CompositeParticle.Builder(ParticleType.Sequence, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Office2013.Drawing.Chart.ChartText), 1, 1, version: FileFormatVersions.Office2013) }; } /// <summary> /// <para>ChartText.</para> /// <para>Represents the following element tag in the schema: c15:tx.</para> /// </summary> /// <remark> /// xmlns:c15 = http://schemas.microsoft.com/office/drawing/2012/chart /// </remark> public DocumentFormat.OpenXml.Office2013.Drawing.Chart.ChartText? ChartText { get => GetElement<DocumentFormat.OpenXml.Office2013.Drawing.Chart.ChartText>(); set => SetElement(value); } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<FilteredSeriesTitle>(deep); } /// <summary> /// <para>Defines the FilteredCategoryTitle Class.</para> /// <para>This class is available in Office 2013 and above.</para> /// <para>When the object is serialized out as xml, it's qualified name is c15:filteredCategoryTitle.</para> /// </summary> /// <remark> /// <para>The following table lists the possible child types:</para> /// <list type="bullet"> /// <item><description><see cref="DocumentFormat.OpenXml.Office2013.Drawing.Chart.AxisDataSourceType" /> <c>&lt;c15:cat></c></description></item> /// </list> /// </remark> [SchemaAttr("c15:filteredCategoryTitle")] public partial class FilteredCategoryTitle : OpenXmlCompositeElement { /// <summary> /// Initializes a new instance of the FilteredCategoryTitle class. /// </summary> public FilteredCategoryTitle() : base() { } /// <summary> /// Initializes a new instance of the FilteredCategoryTitle class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public FilteredCategoryTitle(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the FilteredCategoryTitle class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public FilteredCategoryTitle(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the FilteredCategoryTitle class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public FilteredCategoryTitle(string outerXml) : base(outerXml) { } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.SetSchema("c15:filteredCategoryTitle"); builder.Availability = FileFormatVersions.Office2013; builder.AddChild<DocumentFormat.OpenXml.Office2013.Drawing.Chart.AxisDataSourceType>(); builder.Particle = new CompositeParticle.Builder(ParticleType.Sequence, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Office2013.Drawing.Chart.AxisDataSourceType), 1, 1, version: FileFormatVersions.Office2013) }; } /// <summary> /// <para>AxisDataSourceType.</para> /// <para>Represents the following element tag in the schema: c15:cat.</para> /// </summary> /// <remark> /// xmlns:c15 = http://schemas.microsoft.com/office/drawing/2012/chart /// </remark> public DocumentFormat.OpenXml.Office2013.Drawing.Chart.AxisDataSourceType? AxisDataSourceType { get => GetElement<DocumentFormat.OpenXml.Office2013.Drawing.Chart.AxisDataSourceType>(); set => SetElement(value); } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<FilteredCategoryTitle>(deep); } /// <summary> /// <para>Defines the FilteredAreaSeries Class.</para> /// <para>This class is available in Office 2013 and above.</para> /// <para>When the object is serialized out as xml, it's qualified name is c15:filteredAreaSeries.</para> /// </summary> /// <remark> /// <para>The following table lists the possible child types:</para> /// <list type="bullet"> /// <item><description><see cref="DocumentFormat.OpenXml.Office2013.Drawing.Chart.AreaChartSeries" /> <c>&lt;c15:ser></c></description></item> /// </list> /// </remark> [SchemaAttr("c15:filteredAreaSeries")] public partial class FilteredAreaSeries : OpenXmlCompositeElement { /// <summary> /// Initializes a new instance of the FilteredAreaSeries class. /// </summary> public FilteredAreaSeries() : base() { } /// <summary> /// Initializes a new instance of the FilteredAreaSeries class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public FilteredAreaSeries(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the FilteredAreaSeries class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public FilteredAreaSeries(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the FilteredAreaSeries class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public FilteredAreaSeries(string outerXml) : base(outerXml) { } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.SetSchema("c15:filteredAreaSeries"); builder.Availability = FileFormatVersions.Office2013; builder.AddChild<DocumentFormat.OpenXml.Office2013.Drawing.Chart.AreaChartSeries>(); builder.Particle = new CompositeParticle.Builder(ParticleType.Sequence, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Office2013.Drawing.Chart.AreaChartSeries), 1, 1, version: FileFormatVersions.Office2013) }; } /// <summary> /// <para>AreaChartSeries.</para> /// <para>Represents the following element tag in the schema: c15:ser.</para> /// </summary> /// <remark> /// xmlns:c15 = http://schemas.microsoft.com/office/drawing/2012/chart /// </remark> public DocumentFormat.OpenXml.Office2013.Drawing.Chart.AreaChartSeries? AreaChartSeries { get => GetElement<DocumentFormat.OpenXml.Office2013.Drawing.Chart.AreaChartSeries>(); set => SetElement(value); } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<FilteredAreaSeries>(deep); } /// <summary> /// <para>Defines the FilteredBarSeries Class.</para> /// <para>This class is available in Office 2013 and above.</para> /// <para>When the object is serialized out as xml, it's qualified name is c15:filteredBarSeries.</para> /// </summary> /// <remark> /// <para>The following table lists the possible child types:</para> /// <list type="bullet"> /// <item><description><see cref="DocumentFormat.OpenXml.Office2013.Drawing.Chart.BarChartSeries" /> <c>&lt;c15:ser></c></description></item> /// </list> /// </remark> [SchemaAttr("c15:filteredBarSeries")] public partial class FilteredBarSeries : OpenXmlCompositeElement { /// <summary> /// Initializes a new instance of the FilteredBarSeries class. /// </summary> public FilteredBarSeries() : base() { } /// <summary> /// Initializes a new instance of the FilteredBarSeries class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public FilteredBarSeries(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the FilteredBarSeries class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public FilteredBarSeries(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the FilteredBarSeries class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public FilteredBarSeries(string outerXml) : base(outerXml) { } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.SetSchema("c15:filteredBarSeries"); builder.Availability = FileFormatVersions.Office2013; builder.AddChild<DocumentFormat.OpenXml.Office2013.Drawing.Chart.BarChartSeries>(); builder.Particle = new CompositeParticle.Builder(ParticleType.Sequence, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Office2013.Drawing.Chart.BarChartSeries), 1, 1, version: FileFormatVersions.Office2013) }; } /// <summary> /// <para>BarChartSeries.</para> /// <para>Represents the following element tag in the schema: c15:ser.</para> /// </summary> /// <remark> /// xmlns:c15 = http://schemas.microsoft.com/office/drawing/2012/chart /// </remark> public DocumentFormat.OpenXml.Office2013.Drawing.Chart.BarChartSeries? BarChartSeries { get => GetElement<DocumentFormat.OpenXml.Office2013.Drawing.Chart.BarChartSeries>(); set => SetElement(value); } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<FilteredBarSeries>(deep); } /// <summary> /// <para>Defines the FilteredBubbleSeries Class.</para> /// <para>This class is available in Office 2013 and above.</para> /// <para>When the object is serialized out as xml, it's qualified name is c15:filteredBubbleSeries.</para> /// </summary> /// <remark> /// <para>The following table lists the possible child types:</para> /// <list type="bullet"> /// <item><description><see cref="DocumentFormat.OpenXml.Office2013.Drawing.Chart.BubbleChartSeries" /> <c>&lt;c15:ser></c></description></item> /// </list> /// </remark> [SchemaAttr("c15:filteredBubbleSeries")] public partial class FilteredBubbleSeries : OpenXmlCompositeElement { /// <summary> /// Initializes a new instance of the FilteredBubbleSeries class. /// </summary> public FilteredBubbleSeries() : base() { } /// <summary> /// Initializes a new instance of the FilteredBubbleSeries class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public FilteredBubbleSeries(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the FilteredBubbleSeries class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public FilteredBubbleSeries(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the FilteredBubbleSeries class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public FilteredBubbleSeries(string outerXml) : base(outerXml) { } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.SetSchema("c15:filteredBubbleSeries"); builder.Availability = FileFormatVersions.Office2013; builder.AddChild<DocumentFormat.OpenXml.Office2013.Drawing.Chart.BubbleChartSeries>(); builder.Particle = new CompositeParticle.Builder(ParticleType.Sequence, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Office2013.Drawing.Chart.BubbleChartSeries), 1, 1, version: FileFormatVersions.Office2013) }; } /// <summary> /// <para>BubbleChartSeries.</para> /// <para>Represents the following element tag in the schema: c15:ser.</para> /// </summary> /// <remark> /// xmlns:c15 = http://schemas.microsoft.com/office/drawing/2012/chart /// </remark> public DocumentFormat.OpenXml.Office2013.Drawing.Chart.BubbleChartSeries? BubbleChartSeries { get => GetElement<DocumentFormat.OpenXml.Office2013.Drawing.Chart.BubbleChartSeries>(); set => SetElement(value); } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<FilteredBubbleSeries>(deep); } /// <summary> /// <para>Defines the FilteredLineSeriesExtension Class.</para> /// <para>This class is available in Office 2013 and above.</para> /// <para>When the object is serialized out as xml, it's qualified name is c15:filteredLineSeries.</para> /// </summary> /// <remark> /// <para>The following table lists the possible child types:</para> /// <list type="bullet"> /// <item><description><see cref="DocumentFormat.OpenXml.Office2013.Drawing.Chart.LineChartSeries" /> <c>&lt;c15:ser></c></description></item> /// </list> /// </remark> [SchemaAttr("c15:filteredLineSeries")] public partial class FilteredLineSeriesExtension : OpenXmlCompositeElement { /// <summary> /// Initializes a new instance of the FilteredLineSeriesExtension class. /// </summary> public FilteredLineSeriesExtension() : base() { } /// <summary> /// Initializes a new instance of the FilteredLineSeriesExtension class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public FilteredLineSeriesExtension(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the FilteredLineSeriesExtension class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public FilteredLineSeriesExtension(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the FilteredLineSeriesExtension class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public FilteredLineSeriesExtension(string outerXml) : base(outerXml) { } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.SetSchema("c15:filteredLineSeries"); builder.Availability = FileFormatVersions.Office2013; builder.AddChild<DocumentFormat.OpenXml.Office2013.Drawing.Chart.LineChartSeries>(); builder.Particle = new CompositeParticle.Builder(ParticleType.Sequence, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Office2013.Drawing.Chart.LineChartSeries), 1, 1, version: FileFormatVersions.Office2013) }; } /// <summary> /// <para>LineChartSeries.</para> /// <para>Represents the following element tag in the schema: c15:ser.</para> /// </summary> /// <remark> /// xmlns:c15 = http://schemas.microsoft.com/office/drawing/2012/chart /// </remark> public DocumentFormat.OpenXml.Office2013.Drawing.Chart.LineChartSeries? LineChartSeries { get => GetElement<DocumentFormat.OpenXml.Office2013.Drawing.Chart.LineChartSeries>(); set => SetElement(value); } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<FilteredLineSeriesExtension>(deep); } /// <summary> /// <para>Defines the FilteredPieSeries Class.</para> /// <para>This class is available in Office 2013 and above.</para> /// <para>When the object is serialized out as xml, it's qualified name is c15:filteredPieSeries.</para> /// </summary> /// <remark> /// <para>The following table lists the possible child types:</para> /// <list type="bullet"> /// <item><description><see cref="DocumentFormat.OpenXml.Office2013.Drawing.Chart.PieChartSeries" /> <c>&lt;c15:ser></c></description></item> /// </list> /// </remark> [SchemaAttr("c15:filteredPieSeries")] public partial class FilteredPieSeries : OpenXmlCompositeElement { /// <summary> /// Initializes a new instance of the FilteredPieSeries class. /// </summary> public FilteredPieSeries() : base() { } /// <summary> /// Initializes a new instance of the FilteredPieSeries class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public FilteredPieSeries(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the FilteredPieSeries class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public FilteredPieSeries(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the FilteredPieSeries class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public FilteredPieSeries(string outerXml) : base(outerXml) { } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.SetSchema("c15:filteredPieSeries"); builder.Availability = FileFormatVersions.Office2013; builder.AddChild<DocumentFormat.OpenXml.Office2013.Drawing.Chart.PieChartSeries>(); builder.Particle = new CompositeParticle.Builder(ParticleType.Sequence, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Office2013.Drawing.Chart.PieChartSeries), 1, 1, version: FileFormatVersions.Office2013) }; } /// <summary> /// <para>PieChartSeries.</para> /// <para>Represents the following element tag in the schema: c15:ser.</para> /// </summary> /// <remark> /// xmlns:c15 = http://schemas.microsoft.com/office/drawing/2012/chart /// </remark> public DocumentFormat.OpenXml.Office2013.Drawing.Chart.PieChartSeries? PieChartSeries { get => GetElement<DocumentFormat.OpenXml.Office2013.Drawing.Chart.PieChartSeries>(); set => SetElement(value); } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<FilteredPieSeries>(deep); } /// <summary> /// <para>Defines the FilteredRadarSeries Class.</para> /// <para>This class is available in Office 2013 and above.</para> /// <para>When the object is serialized out as xml, it's qualified name is c15:filteredRadarSeries.</para> /// </summary> /// <remark> /// <para>The following table lists the possible child types:</para> /// <list type="bullet"> /// <item><description><see cref="DocumentFormat.OpenXml.Office2013.Drawing.Chart.RadarChartSeries" /> <c>&lt;c15:ser></c></description></item> /// </list> /// </remark> [SchemaAttr("c15:filteredRadarSeries")] public partial class FilteredRadarSeries : OpenXmlCompositeElement { /// <summary> /// Initializes a new instance of the FilteredRadarSeries class. /// </summary> public FilteredRadarSeries() : base() { } /// <summary> /// Initializes a new instance of the FilteredRadarSeries class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public FilteredRadarSeries(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the FilteredRadarSeries class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public FilteredRadarSeries(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the FilteredRadarSeries class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public FilteredRadarSeries(string outerXml) : base(outerXml) { } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.SetSchema("c15:filteredRadarSeries"); builder.Availability = FileFormatVersions.Office2013; builder.AddChild<DocumentFormat.OpenXml.Office2013.Drawing.Chart.RadarChartSeries>(); builder.Particle = new CompositeParticle.Builder(ParticleType.Sequence, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Office2013.Drawing.Chart.RadarChartSeries), 1, 1, version: FileFormatVersions.Office2013) }; } /// <summary> /// <para>RadarChartSeries.</para> /// <para>Represents the following element tag in the schema: c15:ser.</para> /// </summary> /// <remark> /// xmlns:c15 = http://schemas.microsoft.com/office/drawing/2012/chart /// </remark> public DocumentFormat.OpenXml.Office2013.Drawing.Chart.RadarChartSeries? RadarChartSeries { get => GetElement<DocumentFormat.OpenXml.Office2013.Drawing.Chart.RadarChartSeries>(); set => SetElement(value); } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<FilteredRadarSeries>(deep); } /// <summary> /// <para>Defines the FilteredScatterSeries Class.</para> /// <para>This class is available in Office 2013 and above.</para> /// <para>When the object is serialized out as xml, it's qualified name is c15:filteredScatterSeries.</para> /// </summary> /// <remark> /// <para>The following table lists the possible child types:</para> /// <list type="bullet"> /// <item><description><see cref="DocumentFormat.OpenXml.Office2013.Drawing.Chart.ScatterChartSeries" /> <c>&lt;c15:ser></c></description></item> /// </list> /// </remark> [SchemaAttr("c15:filteredScatterSeries")] public partial class FilteredScatterSeries : OpenXmlCompositeElement { /// <summary> /// Initializes a new instance of the FilteredScatterSeries class. /// </summary> public FilteredScatterSeries() : base() { } /// <summary> /// Initializes a new instance of the FilteredScatterSeries class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public FilteredScatterSeries(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the FilteredScatterSeries class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public FilteredScatterSeries(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the FilteredScatterSeries class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public FilteredScatterSeries(string outerXml) : base(outerXml) { } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.SetSchema("c15:filteredScatterSeries"); builder.Availability = FileFormatVersions.Office2013; builder.AddChild<DocumentFormat.OpenXml.Office2013.Drawing.Chart.ScatterChartSeries>(); builder.Particle = new CompositeParticle.Builder(ParticleType.Sequence, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Office2013.Drawing.Chart.ScatterChartSeries), 1, 1, version: FileFormatVersions.Office2013) }; } /// <summary> /// <para>ScatterChartSeries.</para> /// <para>Represents the following element tag in the schema: c15:ser.</para> /// </summary> /// <remark> /// xmlns:c15 = http://schemas.microsoft.com/office/drawing/2012/chart /// </remark> public DocumentFormat.OpenXml.Office2013.Drawing.Chart.ScatterChartSeries? ScatterChartSeries { get => GetElement<DocumentFormat.OpenXml.Office2013.Drawing.Chart.ScatterChartSeries>(); set => SetElement(value); } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<FilteredScatterSeries>(deep); } /// <summary> /// <para>Defines the FilteredSurfaceSeries Class.</para> /// <para>This class is available in Office 2013 and above.</para> /// <para>When the object is serialized out as xml, it's qualified name is c15:filteredSurfaceSeries.</para> /// </summary> /// <remark> /// <para>The following table lists the possible child types:</para> /// <list type="bullet"> /// <item><description><see cref="DocumentFormat.OpenXml.Office2013.Drawing.Chart.SurfaceChartSeries" /> <c>&lt;c15:ser></c></description></item> /// </list> /// </remark> [SchemaAttr("c15:filteredSurfaceSeries")] public partial class FilteredSurfaceSeries : OpenXmlCompositeElement { /// <summary> /// Initializes a new instance of the FilteredSurfaceSeries class. /// </summary> public FilteredSurfaceSeries() : base() { } /// <summary> /// Initializes a new instance of the FilteredSurfaceSeries class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public FilteredSurfaceSeries(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the FilteredSurfaceSeries class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public FilteredSurfaceSeries(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the FilteredSurfaceSeries class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public FilteredSurfaceSeries(string outerXml) : base(outerXml) { } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.SetSchema("c15:filteredSurfaceSeries"); builder.Availability = FileFormatVersions.Office2013; builder.AddChild<DocumentFormat.OpenXml.Office2013.Drawing.Chart.SurfaceChartSeries>(); builder.Particle = new CompositeParticle.Builder(ParticleType.Sequence, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Office2013.Drawing.Chart.SurfaceChartSeries), 1, 1, version: FileFormatVersions.Office2013) }; } /// <summary> /// <para>SurfaceChartSeries.</para> /// <para>Represents the following element tag in the schema: c15:ser.</para> /// </summary> /// <remark> /// xmlns:c15 = http://schemas.microsoft.com/office/drawing/2012/chart /// </remark> public DocumentFormat.OpenXml.Office2013.Drawing.Chart.SurfaceChartSeries? SurfaceChartSeries { get => GetElement<DocumentFormat.OpenXml.Office2013.Drawing.Chart.SurfaceChartSeries>(); set => SetElement(value); } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<FilteredSurfaceSeries>(deep); } /// <summary> /// <para>Defines the DataLabelsRange Class.</para> /// <para>This class is available in Office 2013 and above.</para> /// <para>When the object is serialized out as xml, it's qualified name is c15:datalabelsRange.</para> /// </summary> /// <remark> /// <para>The following table lists the possible child types:</para> /// <list type="bullet"> /// <item><description><see cref="DocumentFormat.OpenXml.Office2013.Drawing.Chart.DataLabelsRangeChache" /> <c>&lt;c15:dlblRangeCache></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Office2013.Drawing.Chart.Formula" /> <c>&lt;c15:f></c></description></item> /// </list> /// </remark> [SchemaAttr("c15:datalabelsRange")] public partial class DataLabelsRange : OpenXmlCompositeElement { /// <summary> /// Initializes a new instance of the DataLabelsRange class. /// </summary> public DataLabelsRange() : base() { } /// <summary> /// Initializes a new instance of the DataLabelsRange class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public DataLabelsRange(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the DataLabelsRange class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public DataLabelsRange(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the DataLabelsRange class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public DataLabelsRange(string outerXml) : base(outerXml) { } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.SetSchema("c15:datalabelsRange"); builder.Availability = FileFormatVersions.Office2013; builder.AddChild<DocumentFormat.OpenXml.Office2013.Drawing.Chart.DataLabelsRangeChache>(); builder.AddChild<DocumentFormat.OpenXml.Office2013.Drawing.Chart.Formula>(); builder.Particle = new CompositeParticle.Builder(ParticleType.Sequence, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Office2013.Drawing.Chart.Formula), 1, 1, version: FileFormatVersions.Office2013), new ElementParticle(typeof(DocumentFormat.OpenXml.Office2013.Drawing.Chart.DataLabelsRangeChache), 0, 1, version: FileFormatVersions.Office2013) }; } /// <summary> /// <para>Formula.</para> /// <para>Represents the following element tag in the schema: c15:f.</para> /// </summary> /// <remark> /// xmlns:c15 = http://schemas.microsoft.com/office/drawing/2012/chart /// </remark> public DocumentFormat.OpenXml.Office2013.Drawing.Chart.Formula? Formula { get => GetElement<DocumentFormat.OpenXml.Office2013.Drawing.Chart.Formula>(); set => SetElement(value); } /// <summary> /// <para>DataLabelsRangeChache.</para> /// <para>Represents the following element tag in the schema: c15:dlblRangeCache.</para> /// </summary> /// <remark> /// xmlns:c15 = http://schemas.microsoft.com/office/drawing/2012/chart /// </remark> public DocumentFormat.OpenXml.Office2013.Drawing.Chart.DataLabelsRangeChache? DataLabelsRangeChache { get => GetElement<DocumentFormat.OpenXml.Office2013.Drawing.Chart.DataLabelsRangeChache>(); set => SetElement(value); } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<DataLabelsRange>(deep); } /// <summary> /// <para>Defines the CategoryFilterExceptions Class.</para> /// <para>This class is available in Office 2013 and above.</para> /// <para>When the object is serialized out as xml, it's qualified name is c15:categoryFilterExceptions.</para> /// </summary> /// <remark> /// <para>The following table lists the possible child types:</para> /// <list type="bullet"> /// <item><description><see cref="DocumentFormat.OpenXml.Office2013.Drawing.Chart.CategoryFilterException" /> <c>&lt;c15:categoryFilterException></c></description></item> /// </list> /// </remark> [SchemaAttr("c15:categoryFilterExceptions")] public partial class CategoryFilterExceptions : OpenXmlCompositeElement { /// <summary> /// Initializes a new instance of the CategoryFilterExceptions class. /// </summary> public CategoryFilterExceptions() : base() { } /// <summary> /// Initializes a new instance of the CategoryFilterExceptions class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public CategoryFilterExceptions(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the CategoryFilterExceptions class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public CategoryFilterExceptions(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the CategoryFilterExceptions class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public CategoryFilterExceptions(string outerXml) : base(outerXml) { } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.SetSchema("c15:categoryFilterExceptions"); builder.Availability = FileFormatVersions.Office2013; builder.AddChild<DocumentFormat.OpenXml.Office2013.Drawing.Chart.CategoryFilterException>(); builder.Particle = new CompositeParticle.Builder(ParticleType.Sequence, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Office2013.Drawing.Chart.CategoryFilterException), 1, 0, version: FileFormatVersions.Office2013) }; } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<CategoryFilterExceptions>(deep); } /// <summary> /// <para>Defines the DataLabelFieldTable Class.</para> /// <para>This class is available in Office 2013 and above.</para> /// <para>When the object is serialized out as xml, it's qualified name is c15:dlblFieldTable.</para> /// </summary> /// <remark> /// <para>The following table lists the possible child types:</para> /// <list type="bullet"> /// <item><description><see cref="DocumentFormat.OpenXml.Office2013.Drawing.Chart.DataLabelFieldTableEntry" /> <c>&lt;c15:dlblFTEntry></c></description></item> /// </list> /// </remark> [SchemaAttr("c15:dlblFieldTable")] public partial class DataLabelFieldTable : OpenXmlCompositeElement { /// <summary> /// Initializes a new instance of the DataLabelFieldTable class. /// </summary> public DataLabelFieldTable() : base() { } /// <summary> /// Initializes a new instance of the DataLabelFieldTable class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public DataLabelFieldTable(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the DataLabelFieldTable class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public DataLabelFieldTable(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the DataLabelFieldTable class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public DataLabelFieldTable(string outerXml) : base(outerXml) { } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.SetSchema("c15:dlblFieldTable"); builder.Availability = FileFormatVersions.Office2013; builder.AddChild<DocumentFormat.OpenXml.Office2013.Drawing.Chart.DataLabelFieldTableEntry>(); builder.Particle = new CompositeParticle.Builder(ParticleType.Sequence, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Office2013.Drawing.Chart.DataLabelFieldTableEntry), 0, 0, version: FileFormatVersions.Office2013) }; } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<DataLabelFieldTable>(deep); } /// <summary> /// <para>Defines the ExceptionForSave Class.</para> /// <para>This class is available in Office 2013 and above.</para> /// <para>When the object is serialized out as xml, it's qualified name is c15:xForSave.</para> /// </summary> [SchemaAttr("c15:xForSave")] public partial class ExceptionForSave : BooleanType { /// <summary> /// Initializes a new instance of the ExceptionForSave class. /// </summary> public ExceptionForSave() : base() { } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.SetSchema("c15:xForSave"); builder.Availability = FileFormatVersions.Office2013; } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<ExceptionForSave>(deep); } /// <summary> /// <para>Defines the ShowDataLabelsRange Class.</para> /// <para>This class is available in Office 2013 and above.</para> /// <para>When the object is serialized out as xml, it's qualified name is c15:showDataLabelsRange.</para> /// </summary> [SchemaAttr("c15:showDataLabelsRange")] public partial class ShowDataLabelsRange : BooleanType { /// <summary> /// Initializes a new instance of the ShowDataLabelsRange class. /// </summary> public ShowDataLabelsRange() : base() { } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.SetSchema("c15:showDataLabelsRange"); builder.Availability = FileFormatVersions.Office2013; } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<ShowDataLabelsRange>(deep); } /// <summary> /// <para>Defines the ShowLeaderLines Class.</para> /// <para>This class is available in Office 2013 and above.</para> /// <para>When the object is serialized out as xml, it's qualified name is c15:showLeaderLines.</para> /// </summary> [SchemaAttr("c15:showLeaderLines")] public partial class ShowLeaderLines : BooleanType { /// <summary> /// Initializes a new instance of the ShowLeaderLines class. /// </summary> public ShowLeaderLines() : base() { } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.SetSchema("c15:showLeaderLines"); builder.Availability = FileFormatVersions.Office2013; } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<ShowLeaderLines>(deep); } /// <summary> /// <para>Defines the AutoGeneneratedCategories Class.</para> /// <para>This class is available in Office 2013 and above.</para> /// <para>When the object is serialized out as xml, it's qualified name is c15:autoCat.</para> /// </summary> [SchemaAttr("c15:autoCat")] public partial class AutoGeneneratedCategories : BooleanType { /// <summary> /// Initializes a new instance of the AutoGeneneratedCategories class. /// </summary> public AutoGeneneratedCategories() : base() { } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.SetSchema("c15:autoCat"); builder.Availability = FileFormatVersions.Office2013; } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<AutoGeneneratedCategories>(deep); } /// <summary> /// <para>Defines the InvertIfNegativeBoolean Class.</para> /// <para>This class is available in Office 2013 and above.</para> /// <para>When the object is serialized out as xml, it's qualified name is c15:invertIfNegative.</para> /// </summary> [SchemaAttr("c15:invertIfNegative")] public partial class InvertIfNegativeBoolean : BooleanType { /// <summary> /// Initializes a new instance of the InvertIfNegativeBoolean class. /// </summary> public InvertIfNegativeBoolean() : base() { } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.SetSchema("c15:invertIfNegative"); builder.Availability = FileFormatVersions.Office2013; } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<InvertIfNegativeBoolean>(deep); } /// <summary> /// <para>Defines the Bubble3D Class.</para> /// <para>This class is available in Office 2013 and above.</para> /// <para>When the object is serialized out as xml, it's qualified name is c15:bubble3D.</para> /// </summary> [SchemaAttr("c15:bubble3D")] public partial class Bubble3D : BooleanType { /// <summary> /// Initializes a new instance of the Bubble3D class. /// </summary> public Bubble3D() : base() { } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.SetSchema("c15:bubble3D"); builder.Availability = FileFormatVersions.Office2013; } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<Bubble3D>(deep); } /// <summary> /// <para>Defines the BooleanType Class.</para> /// <para>This class is available in Office 2007 and above.</para> /// <para>When the object is serialized out as xml, it's qualified name is :.</para> /// </summary> public abstract partial class BooleanType : OpenXmlLeafElement { /// <summary> /// Initializes a new instance of the BooleanType class. /// </summary> protected BooleanType() : base() { } /// <summary> /// <para>Boolean Value</para> /// <para>Represents the following attribute in the schema: val</para> /// </summary> [SchemaAttr("val")] public BooleanValue? Val { get => GetAttribute<BooleanValue>(); set => SetAttribute(value); } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.AddElement<BooleanType>() .AddAttribute("val", a => a.Val); } } /// <summary> /// <para>Defines the ChartText Class.</para> /// <para>This class is available in Office 2013 and above.</para> /// <para>When the object is serialized out as xml, it's qualified name is c15:tx.</para> /// </summary> /// <remark> /// <para>The following table lists the possible child types:</para> /// <list type="bullet"> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.RichText" /> <c>&lt;c:rich></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.StringLiteral" /> <c>&lt;c:strLit></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.StringReference" /> <c>&lt;c:strRef></c></description></item> /// </list> /// </remark> [SchemaAttr("c15:tx")] public partial class ChartText : OpenXmlCompositeElement { /// <summary> /// Initializes a new instance of the ChartText class. /// </summary> public ChartText() : base() { } /// <summary> /// Initializes a new instance of the ChartText class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public ChartText(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the ChartText class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public ChartText(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the ChartText class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public ChartText(string outerXml) : base(outerXml) { } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.SetSchema("c15:tx"); builder.Availability = FileFormatVersions.Office2013; builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.RichText>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.StringLiteral>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.StringReference>(); builder.Particle = new CompositeParticle.Builder(ParticleType.Sequence, 1, 1) { new CompositeParticle.Builder(ParticleType.Choice, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.StringReference), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.RichText), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.StringLiteral), 1, 1) } }; } /// <summary> /// <para>String Reference.</para> /// <para>Represents the following element tag in the schema: c:strRef.</para> /// </summary> /// <remark> /// xmlns:c = http://schemas.openxmlformats.org/drawingml/2006/chart /// </remark> public DocumentFormat.OpenXml.Drawing.Charts.StringReference? StringReference { get => GetElement<DocumentFormat.OpenXml.Drawing.Charts.StringReference>(); set => SetElement(value); } /// <summary> /// <para>Rich Text.</para> /// <para>Represents the following element tag in the schema: c:rich.</para> /// </summary> /// <remark> /// xmlns:c = http://schemas.openxmlformats.org/drawingml/2006/chart /// </remark> public DocumentFormat.OpenXml.Drawing.Charts.RichText? RichText { get => GetElement<DocumentFormat.OpenXml.Drawing.Charts.RichText>(); set => SetElement(value); } /// <summary> /// <para>String Literal.</para> /// <para>Represents the following element tag in the schema: c:strLit.</para> /// </summary> /// <remark> /// xmlns:c = http://schemas.openxmlformats.org/drawingml/2006/chart /// </remark> public DocumentFormat.OpenXml.Drawing.Charts.StringLiteral? StringLiteral { get => GetElement<DocumentFormat.OpenXml.Drawing.Charts.StringLiteral>(); set => SetElement(value); } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<ChartText>(deep); } /// <summary> /// <para>Defines the LeaderLines Class.</para> /// <para>This class is available in Office 2013 and above.</para> /// <para>When the object is serialized out as xml, it's qualified name is c15:leaderLines.</para> /// </summary> /// <remark> /// <para>The following table lists the possible child types:</para> /// <list type="bullet"> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.ChartShapeProperties" /> <c>&lt;c:spPr></c></description></item> /// </list> /// </remark> [SchemaAttr("c15:leaderLines")] public partial class LeaderLines : OpenXmlCompositeElement { /// <summary> /// Initializes a new instance of the LeaderLines class. /// </summary> public LeaderLines() : base() { } /// <summary> /// Initializes a new instance of the LeaderLines class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public LeaderLines(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the LeaderLines class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public LeaderLines(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the LeaderLines class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public LeaderLines(string outerXml) : base(outerXml) { } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.SetSchema("c15:leaderLines"); builder.Availability = FileFormatVersions.Office2013; builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.ChartShapeProperties>(); builder.Particle = new CompositeParticle.Builder(ParticleType.Sequence, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.ChartShapeProperties), 0, 1) }; } /// <summary> /// <para>ChartShapeProperties.</para> /// <para>Represents the following element tag in the schema: c:spPr.</para> /// </summary> /// <remark> /// xmlns:c = http://schemas.openxmlformats.org/drawingml/2006/chart /// </remark> public DocumentFormat.OpenXml.Drawing.Charts.ChartShapeProperties? ChartShapeProperties { get => GetElement<DocumentFormat.OpenXml.Drawing.Charts.ChartShapeProperties>(); set => SetElement(value); } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<LeaderLines>(deep); } /// <summary> /// <para>Defines the SequenceOfReferences Class.</para> /// <para>This class is available in Office 2013 and above.</para> /// <para>When the object is serialized out as xml, it's qualified name is c15:sqref.</para> /// </summary> [SchemaAttr("c15:sqref")] public partial class SequenceOfReferences : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the SequenceOfReferences class. /// </summary> public SequenceOfReferences() : base() { } /// <summary> /// Initializes a new instance of the SequenceOfReferences class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public SequenceOfReferences(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new StringValue { InnerText = text }; } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.SetSchema("c15:sqref"); builder.Availability = FileFormatVersions.Office2013; } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<SequenceOfReferences>(deep); } /// <summary> /// <para>Defines the Formula Class.</para> /// <para>This class is available in Office 2013 and above.</para> /// <para>When the object is serialized out as xml, it's qualified name is c15:f.</para> /// </summary> [SchemaAttr("c15:f")] public partial class Formula : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the Formula class. /// </summary> public Formula() : base() { } /// <summary> /// Initializes a new instance of the Formula class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public Formula(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new StringValue { InnerText = text }; } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.SetSchema("c15:f"); builder.Availability = FileFormatVersions.Office2013; } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<Formula>(deep); } /// <summary> /// <para>Defines the TextFieldGuid Class.</para> /// <para>This class is available in Office 2013 and above.</para> /// <para>When the object is serialized out as xml, it's qualified name is c15:txfldGUID.</para> /// </summary> [SchemaAttr("c15:txfldGUID")] public partial class TextFieldGuid : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the TextFieldGuid class. /// </summary> public TextFieldGuid() : base() { } /// <summary> /// Initializes a new instance of the TextFieldGuid class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public TextFieldGuid(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new StringValue { InnerText = text }; } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.SetSchema("c15:txfldGUID"); builder.Availability = FileFormatVersions.Office2013; } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<TextFieldGuid>(deep); } /// <summary> /// <para>Defines the AxisDataSourceType Class.</para> /// <para>This class is available in Office 2013 and above.</para> /// <para>When the object is serialized out as xml, it's qualified name is c15:cat.</para> /// </summary> /// <remark> /// <para>The following table lists the possible child types:</para> /// <list type="bullet"> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.MultiLevelStringReference" /> <c>&lt;c:multiLvlStrRef></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.NumberLiteral" /> <c>&lt;c:numLit></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.NumberReference" /> <c>&lt;c:numRef></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.StringLiteral" /> <c>&lt;c:strLit></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.StringReference" /> <c>&lt;c:strRef></c></description></item> /// </list> /// </remark> [SchemaAttr("c15:cat")] public partial class AxisDataSourceType : OpenXmlCompositeElement { /// <summary> /// Initializes a new instance of the AxisDataSourceType class. /// </summary> public AxisDataSourceType() : base() { } /// <summary> /// Initializes a new instance of the AxisDataSourceType class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public AxisDataSourceType(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the AxisDataSourceType class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public AxisDataSourceType(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the AxisDataSourceType class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public AxisDataSourceType(string outerXml) : base(outerXml) { } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.SetSchema("c15:cat"); builder.Availability = FileFormatVersions.Office2013; builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.MultiLevelStringReference>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.NumberLiteral>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.NumberReference>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.StringLiteral>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.StringReference>(); builder.Particle = new CompositeParticle.Builder(ParticleType.Sequence, 1, 1) { new CompositeParticle.Builder(ParticleType.Choice, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.MultiLevelStringReference), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.NumberReference), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.NumberLiteral), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.StringReference), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.StringLiteral), 1, 1) } }; } /// <summary> /// <para>Multi Level String Reference.</para> /// <para>Represents the following element tag in the schema: c:multiLvlStrRef.</para> /// </summary> /// <remark> /// xmlns:c = http://schemas.openxmlformats.org/drawingml/2006/chart /// </remark> public DocumentFormat.OpenXml.Drawing.Charts.MultiLevelStringReference? MultiLevelStringReference { get => GetElement<DocumentFormat.OpenXml.Drawing.Charts.MultiLevelStringReference>(); set => SetElement(value); } /// <summary> /// <para>Number Reference.</para> /// <para>Represents the following element tag in the schema: c:numRef.</para> /// </summary> /// <remark> /// xmlns:c = http://schemas.openxmlformats.org/drawingml/2006/chart /// </remark> public DocumentFormat.OpenXml.Drawing.Charts.NumberReference? NumberReference { get => GetElement<DocumentFormat.OpenXml.Drawing.Charts.NumberReference>(); set => SetElement(value); } /// <summary> /// <para>Number Literal.</para> /// <para>Represents the following element tag in the schema: c:numLit.</para> /// </summary> /// <remark> /// xmlns:c = http://schemas.openxmlformats.org/drawingml/2006/chart /// </remark> public DocumentFormat.OpenXml.Drawing.Charts.NumberLiteral? NumberLiteral { get => GetElement<DocumentFormat.OpenXml.Drawing.Charts.NumberLiteral>(); set => SetElement(value); } /// <summary> /// <para>StringReference.</para> /// <para>Represents the following element tag in the schema: c:strRef.</para> /// </summary> /// <remark> /// xmlns:c = http://schemas.openxmlformats.org/drawingml/2006/chart /// </remark> public DocumentFormat.OpenXml.Drawing.Charts.StringReference? StringReference { get => GetElement<DocumentFormat.OpenXml.Drawing.Charts.StringReference>(); set => SetElement(value); } /// <summary> /// <para>String Literal.</para> /// <para>Represents the following element tag in the schema: c:strLit.</para> /// </summary> /// <remark> /// xmlns:c = http://schemas.openxmlformats.org/drawingml/2006/chart /// </remark> public DocumentFormat.OpenXml.Drawing.Charts.StringLiteral? StringLiteral { get => GetElement<DocumentFormat.OpenXml.Drawing.Charts.StringLiteral>(); set => SetElement(value); } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<AxisDataSourceType>(deep); } /// <summary> /// <para>Defines the BarChartSeries Class.</para> /// <para>This class is available in Office 2013 and above.</para> /// <para>When the object is serialized out as xml, it's qualified name is c15:ser.</para> /// </summary> /// <remark> /// <para>The following table lists the possible child types:</para> /// <list type="bullet"> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.ChartShapeProperties" /> <c>&lt;c:spPr></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.CategoryAxisData" /> <c>&lt;c:cat></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.BarSerExtensionList" /> <c>&lt;c:extLst></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.InvertIfNegative" /> <c>&lt;c:invertIfNegative></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.DataLabels" /> <c>&lt;c:dLbls></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.DataPoint" /> <c>&lt;c:dPt></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.ErrorBars" /> <c>&lt;c:errBars></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.Values" /> <c>&lt;c:val></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.PictureOptions" /> <c>&lt;c:pictureOptions></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.SeriesText" /> <c>&lt;c:tx></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.Shape" /> <c>&lt;c:shape></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.Trendline" /> <c>&lt;c:trendline></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.Index" /> <c>&lt;c:idx></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.Order" /> <c>&lt;c:order></c></description></item> /// </list> /// </remark> [SchemaAttr("c15:ser")] public partial class BarChartSeries : OpenXmlCompositeElement { /// <summary> /// Initializes a new instance of the BarChartSeries class. /// </summary> public BarChartSeries() : base() { } /// <summary> /// Initializes a new instance of the BarChartSeries class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public BarChartSeries(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the BarChartSeries class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public BarChartSeries(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the BarChartSeries class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public BarChartSeries(string outerXml) : base(outerXml) { } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.SetSchema("c15:ser"); builder.Availability = FileFormatVersions.Office2013; builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.ChartShapeProperties>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.CategoryAxisData>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.BarSerExtensionList>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.InvertIfNegative>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.DataLabels>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.DataPoint>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.ErrorBars>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.Values>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.PictureOptions>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.SeriesText>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.Shape>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.Trendline>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.Index>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.Order>(); builder.Particle = new CompositeParticle.Builder(ParticleType.Sequence, 1, 1) { new CompositeParticle.Builder(ParticleType.Group, 1, 1) { new CompositeParticle.Builder(ParticleType.Sequence, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.Index), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.Order), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.SeriesText), 0, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.ChartShapeProperties), 0, 1) } }, new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.InvertIfNegative), 0, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.PictureOptions), 0, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.DataPoint), 0, 0), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.DataLabels), 0, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.Trendline), 0, 0), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.ErrorBars), 0, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.CategoryAxisData), 0, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.Values), 0, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.Shape), 0, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.BarSerExtensionList), 0, 1) }; } /// <summary> /// <para>Index.</para> /// <para>Represents the following element tag in the schema: c:idx.</para> /// </summary> /// <remark> /// xmlns:c = http://schemas.openxmlformats.org/drawingml/2006/chart /// </remark> public DocumentFormat.OpenXml.Drawing.Charts.Index? Index { get => GetElement<DocumentFormat.OpenXml.Drawing.Charts.Index>(); set => SetElement(value); } /// <summary> /// <para>Order.</para> /// <para>Represents the following element tag in the schema: c:order.</para> /// </summary> /// <remark> /// xmlns:c = http://schemas.openxmlformats.org/drawingml/2006/chart /// </remark> public DocumentFormat.OpenXml.Drawing.Charts.Order? Order { get => GetElement<DocumentFormat.OpenXml.Drawing.Charts.Order>(); set => SetElement(value); } /// <summary> /// <para>Series Text.</para> /// <para>Represents the following element tag in the schema: c:tx.</para> /// </summary> /// <remark> /// xmlns:c = http://schemas.openxmlformats.org/drawingml/2006/chart /// </remark> public DocumentFormat.OpenXml.Drawing.Charts.SeriesText? SeriesText { get => GetElement<DocumentFormat.OpenXml.Drawing.Charts.SeriesText>(); set => SetElement(value); } /// <summary> /// <para>ChartShapeProperties.</para> /// <para>Represents the following element tag in the schema: c:spPr.</para> /// </summary> /// <remark> /// xmlns:c = http://schemas.openxmlformats.org/drawingml/2006/chart /// </remark> public DocumentFormat.OpenXml.Drawing.Charts.ChartShapeProperties? ChartShapeProperties { get => GetElement<DocumentFormat.OpenXml.Drawing.Charts.ChartShapeProperties>(); set => SetElement(value); } /// <summary> /// <para>InvertIfNegative.</para> /// <para>Represents the following element tag in the schema: c:invertIfNegative.</para> /// </summary> /// <remark> /// xmlns:c = http://schemas.openxmlformats.org/drawingml/2006/chart /// </remark> public DocumentFormat.OpenXml.Drawing.Charts.InvertIfNegative? InvertIfNegative { get => GetElement<DocumentFormat.OpenXml.Drawing.Charts.InvertIfNegative>(); set => SetElement(value); } /// <summary> /// <para>PictureOptions.</para> /// <para>Represents the following element tag in the schema: c:pictureOptions.</para> /// </summary> /// <remark> /// xmlns:c = http://schemas.openxmlformats.org/drawingml/2006/chart /// </remark> public DocumentFormat.OpenXml.Drawing.Charts.PictureOptions? PictureOptions { get => GetElement<DocumentFormat.OpenXml.Drawing.Charts.PictureOptions>(); set => SetElement(value); } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<BarChartSeries>(deep); } /// <summary> /// <para>Defines the LineChartSeries Class.</para> /// <para>This class is available in Office 2013 and above.</para> /// <para>When the object is serialized out as xml, it's qualified name is c15:ser.</para> /// </summary> /// <remark> /// <para>The following table lists the possible child types:</para> /// <list type="bullet"> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.ChartShapeProperties" /> <c>&lt;c:spPr></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.CategoryAxisData" /> <c>&lt;c:cat></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.Smooth" /> <c>&lt;c:smooth></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.DataLabels" /> <c>&lt;c:dLbls></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.DataPoint" /> <c>&lt;c:dPt></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.ErrorBars" /> <c>&lt;c:errBars></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.LineSerExtensionList" /> <c>&lt;c:extLst></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.Marker" /> <c>&lt;c:marker></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.Values" /> <c>&lt;c:val></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.PictureOptions" /> <c>&lt;c:pictureOptions></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.SeriesText" /> <c>&lt;c:tx></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.Trendline" /> <c>&lt;c:trendline></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.Index" /> <c>&lt;c:idx></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.Order" /> <c>&lt;c:order></c></description></item> /// </list> /// </remark> [SchemaAttr("c15:ser")] public partial class LineChartSeries : OpenXmlCompositeElement { /// <summary> /// Initializes a new instance of the LineChartSeries class. /// </summary> public LineChartSeries() : base() { } /// <summary> /// Initializes a new instance of the LineChartSeries class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public LineChartSeries(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the LineChartSeries class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public LineChartSeries(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the LineChartSeries class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public LineChartSeries(string outerXml) : base(outerXml) { } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.SetSchema("c15:ser"); builder.Availability = FileFormatVersions.Office2013; builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.ChartShapeProperties>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.CategoryAxisData>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.Smooth>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.DataLabels>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.DataPoint>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.ErrorBars>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.LineSerExtensionList>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.Marker>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.Values>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.PictureOptions>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.SeriesText>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.Trendline>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.Index>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.Order>(); builder.Particle = new CompositeParticle.Builder(ParticleType.Sequence, 1, 1) { new CompositeParticle.Builder(ParticleType.Group, 1, 1) { new CompositeParticle.Builder(ParticleType.Sequence, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.Index), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.Order), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.SeriesText), 0, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.ChartShapeProperties), 0, 1) } }, new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.Marker), 0, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.PictureOptions), 0, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.DataPoint), 0, 0), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.DataLabels), 0, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.Trendline), 0, 0), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.ErrorBars), 0, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.CategoryAxisData), 0, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.Values), 0, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.Smooth), 0, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.LineSerExtensionList), 0, 1) }; } /// <summary> /// <para>Index.</para> /// <para>Represents the following element tag in the schema: c:idx.</para> /// </summary> /// <remark> /// xmlns:c = http://schemas.openxmlformats.org/drawingml/2006/chart /// </remark> public DocumentFormat.OpenXml.Drawing.Charts.Index? Index { get => GetElement<DocumentFormat.OpenXml.Drawing.Charts.Index>(); set => SetElement(value); } /// <summary> /// <para>Order.</para> /// <para>Represents the following element tag in the schema: c:order.</para> /// </summary> /// <remark> /// xmlns:c = http://schemas.openxmlformats.org/drawingml/2006/chart /// </remark> public DocumentFormat.OpenXml.Drawing.Charts.Order? Order { get => GetElement<DocumentFormat.OpenXml.Drawing.Charts.Order>(); set => SetElement(value); } /// <summary> /// <para>Series Text.</para> /// <para>Represents the following element tag in the schema: c:tx.</para> /// </summary> /// <remark> /// xmlns:c = http://schemas.openxmlformats.org/drawingml/2006/chart /// </remark> public DocumentFormat.OpenXml.Drawing.Charts.SeriesText? SeriesText { get => GetElement<DocumentFormat.OpenXml.Drawing.Charts.SeriesText>(); set => SetElement(value); } /// <summary> /// <para>ChartShapeProperties.</para> /// <para>Represents the following element tag in the schema: c:spPr.</para> /// </summary> /// <remark> /// xmlns:c = http://schemas.openxmlformats.org/drawingml/2006/chart /// </remark> public DocumentFormat.OpenXml.Drawing.Charts.ChartShapeProperties? ChartShapeProperties { get => GetElement<DocumentFormat.OpenXml.Drawing.Charts.ChartShapeProperties>(); set => SetElement(value); } /// <summary> /// <para>Marker.</para> /// <para>Represents the following element tag in the schema: c:marker.</para> /// </summary> /// <remark> /// xmlns:c = http://schemas.openxmlformats.org/drawingml/2006/chart /// </remark> public DocumentFormat.OpenXml.Drawing.Charts.Marker? Marker { get => GetElement<DocumentFormat.OpenXml.Drawing.Charts.Marker>(); set => SetElement(value); } /// <summary> /// <para>PictureOptions.</para> /// <para>Represents the following element tag in the schema: c:pictureOptions.</para> /// </summary> /// <remark> /// xmlns:c = http://schemas.openxmlformats.org/drawingml/2006/chart /// </remark> public DocumentFormat.OpenXml.Drawing.Charts.PictureOptions? PictureOptions { get => GetElement<DocumentFormat.OpenXml.Drawing.Charts.PictureOptions>(); set => SetElement(value); } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<LineChartSeries>(deep); } /// <summary> /// <para>Defines the ScatterChartSeries Class.</para> /// <para>This class is available in Office 2013 and above.</para> /// <para>When the object is serialized out as xml, it's qualified name is c15:ser.</para> /// </summary> /// <remark> /// <para>The following table lists the possible child types:</para> /// <list type="bullet"> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.ChartShapeProperties" /> <c>&lt;c:spPr></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.XValues" /> <c>&lt;c:xVal></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.Smooth" /> <c>&lt;c:smooth></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.DataLabels" /> <c>&lt;c:dLbls></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.DataPoint" /> <c>&lt;c:dPt></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.ErrorBars" /> <c>&lt;c:errBars></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.Marker" /> <c>&lt;c:marker></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.YValues" /> <c>&lt;c:yVal></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.ScatterSerExtensionList" /> <c>&lt;c:extLst></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.SeriesText" /> <c>&lt;c:tx></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.Trendline" /> <c>&lt;c:trendline></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.Index" /> <c>&lt;c:idx></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.Order" /> <c>&lt;c:order></c></description></item> /// </list> /// </remark> [SchemaAttr("c15:ser")] public partial class ScatterChartSeries : OpenXmlCompositeElement { /// <summary> /// Initializes a new instance of the ScatterChartSeries class. /// </summary> public ScatterChartSeries() : base() { } /// <summary> /// Initializes a new instance of the ScatterChartSeries class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public ScatterChartSeries(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the ScatterChartSeries class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public ScatterChartSeries(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the ScatterChartSeries class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public ScatterChartSeries(string outerXml) : base(outerXml) { } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.SetSchema("c15:ser"); builder.Availability = FileFormatVersions.Office2013; builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.ChartShapeProperties>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.XValues>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.Smooth>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.DataLabels>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.DataPoint>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.ErrorBars>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.Marker>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.YValues>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.ScatterSerExtensionList>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.SeriesText>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.Trendline>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.Index>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.Order>(); builder.Particle = new CompositeParticle.Builder(ParticleType.Sequence, 1, 1) { new CompositeParticle.Builder(ParticleType.Group, 1, 1) { new CompositeParticle.Builder(ParticleType.Sequence, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.Index), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.Order), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.SeriesText), 0, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.ChartShapeProperties), 0, 1) } }, new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.Marker), 0, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.DataPoint), 0, 0), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.DataLabels), 0, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.Trendline), 0, 0), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.ErrorBars), 0, 2), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.XValues), 0, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.YValues), 0, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.Smooth), 0, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.ScatterSerExtensionList), 0, 1) }; } /// <summary> /// <para>Index.</para> /// <para>Represents the following element tag in the schema: c:idx.</para> /// </summary> /// <remark> /// xmlns:c = http://schemas.openxmlformats.org/drawingml/2006/chart /// </remark> public DocumentFormat.OpenXml.Drawing.Charts.Index? Index { get => GetElement<DocumentFormat.OpenXml.Drawing.Charts.Index>(); set => SetElement(value); } /// <summary> /// <para>Order.</para> /// <para>Represents the following element tag in the schema: c:order.</para> /// </summary> /// <remark> /// xmlns:c = http://schemas.openxmlformats.org/drawingml/2006/chart /// </remark> public DocumentFormat.OpenXml.Drawing.Charts.Order? Order { get => GetElement<DocumentFormat.OpenXml.Drawing.Charts.Order>(); set => SetElement(value); } /// <summary> /// <para>Series Text.</para> /// <para>Represents the following element tag in the schema: c:tx.</para> /// </summary> /// <remark> /// xmlns:c = http://schemas.openxmlformats.org/drawingml/2006/chart /// </remark> public DocumentFormat.OpenXml.Drawing.Charts.SeriesText? SeriesText { get => GetElement<DocumentFormat.OpenXml.Drawing.Charts.SeriesText>(); set => SetElement(value); } /// <summary> /// <para>ChartShapeProperties.</para> /// <para>Represents the following element tag in the schema: c:spPr.</para> /// </summary> /// <remark> /// xmlns:c = http://schemas.openxmlformats.org/drawingml/2006/chart /// </remark> public DocumentFormat.OpenXml.Drawing.Charts.ChartShapeProperties? ChartShapeProperties { get => GetElement<DocumentFormat.OpenXml.Drawing.Charts.ChartShapeProperties>(); set => SetElement(value); } /// <summary> /// <para>Marker.</para> /// <para>Represents the following element tag in the schema: c:marker.</para> /// </summary> /// <remark> /// xmlns:c = http://schemas.openxmlformats.org/drawingml/2006/chart /// </remark> public DocumentFormat.OpenXml.Drawing.Charts.Marker? Marker { get => GetElement<DocumentFormat.OpenXml.Drawing.Charts.Marker>(); set => SetElement(value); } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<ScatterChartSeries>(deep); } /// <summary> /// <para>Defines the AreaChartSeries Class.</para> /// <para>This class is available in Office 2013 and above.</para> /// <para>When the object is serialized out as xml, it's qualified name is c15:ser.</para> /// </summary> /// <remark> /// <para>The following table lists the possible child types:</para> /// <list type="bullet"> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.ChartShapeProperties" /> <c>&lt;c:spPr></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.AreaSerExtensionList" /> <c>&lt;c:extLst></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.CategoryAxisData" /> <c>&lt;c:cat></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.DataLabels" /> <c>&lt;c:dLbls></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.DataPoint" /> <c>&lt;c:dPt></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.ErrorBars" /> <c>&lt;c:errBars></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.Values" /> <c>&lt;c:val></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.PictureOptions" /> <c>&lt;c:pictureOptions></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.SeriesText" /> <c>&lt;c:tx></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.Trendline" /> <c>&lt;c:trendline></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.Index" /> <c>&lt;c:idx></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.Order" /> <c>&lt;c:order></c></description></item> /// </list> /// </remark> [SchemaAttr("c15:ser")] public partial class AreaChartSeries : OpenXmlCompositeElement { /// <summary> /// Initializes a new instance of the AreaChartSeries class. /// </summary> public AreaChartSeries() : base() { } /// <summary> /// Initializes a new instance of the AreaChartSeries class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public AreaChartSeries(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the AreaChartSeries class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public AreaChartSeries(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the AreaChartSeries class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public AreaChartSeries(string outerXml) : base(outerXml) { } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.SetSchema("c15:ser"); builder.Availability = FileFormatVersions.Office2013; builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.ChartShapeProperties>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.AreaSerExtensionList>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.CategoryAxisData>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.DataLabels>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.DataPoint>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.ErrorBars>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.Values>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.PictureOptions>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.SeriesText>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.Trendline>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.Index>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.Order>(); builder.Particle = new CompositeParticle.Builder(ParticleType.Sequence, 1, 1) { new CompositeParticle.Builder(ParticleType.Group, 1, 1) { new CompositeParticle.Builder(ParticleType.Sequence, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.Index), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.Order), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.SeriesText), 0, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.ChartShapeProperties), 0, 1) } }, new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.PictureOptions), 0, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.DataPoint), 0, 0), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.DataLabels), 0, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.Trendline), 0, 0), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.ErrorBars), 0, 2), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.CategoryAxisData), 0, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.Values), 0, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.AreaSerExtensionList), 0, 1) }; } /// <summary> /// <para>Index.</para> /// <para>Represents the following element tag in the schema: c:idx.</para> /// </summary> /// <remark> /// xmlns:c = http://schemas.openxmlformats.org/drawingml/2006/chart /// </remark> public DocumentFormat.OpenXml.Drawing.Charts.Index? Index { get => GetElement<DocumentFormat.OpenXml.Drawing.Charts.Index>(); set => SetElement(value); } /// <summary> /// <para>Order.</para> /// <para>Represents the following element tag in the schema: c:order.</para> /// </summary> /// <remark> /// xmlns:c = http://schemas.openxmlformats.org/drawingml/2006/chart /// </remark> public DocumentFormat.OpenXml.Drawing.Charts.Order? Order { get => GetElement<DocumentFormat.OpenXml.Drawing.Charts.Order>(); set => SetElement(value); } /// <summary> /// <para>Series Text.</para> /// <para>Represents the following element tag in the schema: c:tx.</para> /// </summary> /// <remark> /// xmlns:c = http://schemas.openxmlformats.org/drawingml/2006/chart /// </remark> public DocumentFormat.OpenXml.Drawing.Charts.SeriesText? SeriesText { get => GetElement<DocumentFormat.OpenXml.Drawing.Charts.SeriesText>(); set => SetElement(value); } /// <summary> /// <para>ChartShapeProperties.</para> /// <para>Represents the following element tag in the schema: c:spPr.</para> /// </summary> /// <remark> /// xmlns:c = http://schemas.openxmlformats.org/drawingml/2006/chart /// </remark> public DocumentFormat.OpenXml.Drawing.Charts.ChartShapeProperties? ChartShapeProperties { get => GetElement<DocumentFormat.OpenXml.Drawing.Charts.ChartShapeProperties>(); set => SetElement(value); } /// <summary> /// <para>PictureOptions.</para> /// <para>Represents the following element tag in the schema: c:pictureOptions.</para> /// </summary> /// <remark> /// xmlns:c = http://schemas.openxmlformats.org/drawingml/2006/chart /// </remark> public DocumentFormat.OpenXml.Drawing.Charts.PictureOptions? PictureOptions { get => GetElement<DocumentFormat.OpenXml.Drawing.Charts.PictureOptions>(); set => SetElement(value); } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<AreaChartSeries>(deep); } /// <summary> /// <para>Defines the PieChartSeries Class.</para> /// <para>This class is available in Office 2013 and above.</para> /// <para>When the object is serialized out as xml, it's qualified name is c15:ser.</para> /// </summary> /// <remark> /// <para>The following table lists the possible child types:</para> /// <list type="bullet"> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.ChartShapeProperties" /> <c>&lt;c:spPr></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.CategoryAxisData" /> <c>&lt;c:cat></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.DataLabels" /> <c>&lt;c:dLbls></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.DataPoint" /> <c>&lt;c:dPt></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.Values" /> <c>&lt;c:val></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.PictureOptions" /> <c>&lt;c:pictureOptions></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.PieSerExtensionList" /> <c>&lt;c:extLst></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.SeriesText" /> <c>&lt;c:tx></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.Index" /> <c>&lt;c:idx></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.Order" /> <c>&lt;c:order></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.Explosion" /> <c>&lt;c:explosion></c></description></item> /// </list> /// </remark> [SchemaAttr("c15:ser")] public partial class PieChartSeries : OpenXmlCompositeElement { /// <summary> /// Initializes a new instance of the PieChartSeries class. /// </summary> public PieChartSeries() : base() { } /// <summary> /// Initializes a new instance of the PieChartSeries class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public PieChartSeries(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the PieChartSeries class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public PieChartSeries(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the PieChartSeries class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public PieChartSeries(string outerXml) : base(outerXml) { } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.SetSchema("c15:ser"); builder.Availability = FileFormatVersions.Office2013; builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.ChartShapeProperties>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.CategoryAxisData>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.DataLabels>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.DataPoint>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.Values>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.PictureOptions>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.PieSerExtensionList>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.SeriesText>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.Index>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.Order>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.Explosion>(); builder.Particle = new CompositeParticle.Builder(ParticleType.Sequence, 1, 1) { new CompositeParticle.Builder(ParticleType.Group, 1, 1) { new CompositeParticle.Builder(ParticleType.Sequence, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.Index), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.Order), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.SeriesText), 0, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.ChartShapeProperties), 0, 1) } }, new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.PictureOptions), 0, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.Explosion), 0, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.DataPoint), 0, 0), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.DataLabels), 0, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.CategoryAxisData), 0, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.Values), 0, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.PieSerExtensionList), 0, 1) }; } /// <summary> /// <para>Index.</para> /// <para>Represents the following element tag in the schema: c:idx.</para> /// </summary> /// <remark> /// xmlns:c = http://schemas.openxmlformats.org/drawingml/2006/chart /// </remark> public DocumentFormat.OpenXml.Drawing.Charts.Index? Index { get => GetElement<DocumentFormat.OpenXml.Drawing.Charts.Index>(); set => SetElement(value); } /// <summary> /// <para>Order.</para> /// <para>Represents the following element tag in the schema: c:order.</para> /// </summary> /// <remark> /// xmlns:c = http://schemas.openxmlformats.org/drawingml/2006/chart /// </remark> public DocumentFormat.OpenXml.Drawing.Charts.Order? Order { get => GetElement<DocumentFormat.OpenXml.Drawing.Charts.Order>(); set => SetElement(value); } /// <summary> /// <para>Series Text.</para> /// <para>Represents the following element tag in the schema: c:tx.</para> /// </summary> /// <remark> /// xmlns:c = http://schemas.openxmlformats.org/drawingml/2006/chart /// </remark> public DocumentFormat.OpenXml.Drawing.Charts.SeriesText? SeriesText { get => GetElement<DocumentFormat.OpenXml.Drawing.Charts.SeriesText>(); set => SetElement(value); } /// <summary> /// <para>ChartShapeProperties.</para> /// <para>Represents the following element tag in the schema: c:spPr.</para> /// </summary> /// <remark> /// xmlns:c = http://schemas.openxmlformats.org/drawingml/2006/chart /// </remark> public DocumentFormat.OpenXml.Drawing.Charts.ChartShapeProperties? ChartShapeProperties { get => GetElement<DocumentFormat.OpenXml.Drawing.Charts.ChartShapeProperties>(); set => SetElement(value); } /// <summary> /// <para>PictureOptions.</para> /// <para>Represents the following element tag in the schema: c:pictureOptions.</para> /// </summary> /// <remark> /// xmlns:c = http://schemas.openxmlformats.org/drawingml/2006/chart /// </remark> public DocumentFormat.OpenXml.Drawing.Charts.PictureOptions? PictureOptions { get => GetElement<DocumentFormat.OpenXml.Drawing.Charts.PictureOptions>(); set => SetElement(value); } /// <summary> /// <para>Explosion.</para> /// <para>Represents the following element tag in the schema: c:explosion.</para> /// </summary> /// <remark> /// xmlns:c = http://schemas.openxmlformats.org/drawingml/2006/chart /// </remark> public DocumentFormat.OpenXml.Drawing.Charts.Explosion? Explosion { get => GetElement<DocumentFormat.OpenXml.Drawing.Charts.Explosion>(); set => SetElement(value); } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<PieChartSeries>(deep); } /// <summary> /// <para>Defines the BubbleChartSeries Class.</para> /// <para>This class is available in Office 2013 and above.</para> /// <para>When the object is serialized out as xml, it's qualified name is c15:ser.</para> /// </summary> /// <remark> /// <para>The following table lists the possible child types:</para> /// <list type="bullet"> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.ChartShapeProperties" /> <c>&lt;c:spPr></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.XValues" /> <c>&lt;c:xVal></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.InvertIfNegative" /> <c>&lt;c:invertIfNegative></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.Bubble3D" /> <c>&lt;c:bubble3D></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.BubbleSerExtensionList" /> <c>&lt;c:extLst></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.DataLabels" /> <c>&lt;c:dLbls></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.DataPoint" /> <c>&lt;c:dPt></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.ErrorBars" /> <c>&lt;c:errBars></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.YValues" /> <c>&lt;c:yVal></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.BubbleSize" /> <c>&lt;c:bubbleSize></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.PictureOptions" /> <c>&lt;c:pictureOptions></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.SeriesText" /> <c>&lt;c:tx></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.Trendline" /> <c>&lt;c:trendline></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.Index" /> <c>&lt;c:idx></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.Order" /> <c>&lt;c:order></c></description></item> /// </list> /// </remark> [SchemaAttr("c15:ser")] public partial class BubbleChartSeries : OpenXmlCompositeElement { /// <summary> /// Initializes a new instance of the BubbleChartSeries class. /// </summary> public BubbleChartSeries() : base() { } /// <summary> /// Initializes a new instance of the BubbleChartSeries class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public BubbleChartSeries(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the BubbleChartSeries class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public BubbleChartSeries(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the BubbleChartSeries class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public BubbleChartSeries(string outerXml) : base(outerXml) { } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.SetSchema("c15:ser"); builder.Availability = FileFormatVersions.Office2013; builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.ChartShapeProperties>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.XValues>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.InvertIfNegative>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.Bubble3D>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.BubbleSerExtensionList>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.DataLabels>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.DataPoint>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.ErrorBars>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.YValues>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.BubbleSize>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.PictureOptions>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.SeriesText>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.Trendline>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.Index>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.Order>(); builder.Particle = new CompositeParticle.Builder(ParticleType.Sequence, 1, 1) { new CompositeParticle.Builder(ParticleType.Group, 1, 1) { new CompositeParticle.Builder(ParticleType.Sequence, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.Index), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.Order), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.SeriesText), 0, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.ChartShapeProperties), 0, 1) } }, new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.PictureOptions), 0, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.InvertIfNegative), 0, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.DataPoint), 0, 0), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.DataLabels), 0, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.Trendline), 0, 0), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.ErrorBars), 0, 2), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.XValues), 0, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.YValues), 0, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.BubbleSize), 0, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.Bubble3D), 0, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.BubbleSerExtensionList), 0, 1) }; } /// <summary> /// <para>Index.</para> /// <para>Represents the following element tag in the schema: c:idx.</para> /// </summary> /// <remark> /// xmlns:c = http://schemas.openxmlformats.org/drawingml/2006/chart /// </remark> public DocumentFormat.OpenXml.Drawing.Charts.Index? Index { get => GetElement<DocumentFormat.OpenXml.Drawing.Charts.Index>(); set => SetElement(value); } /// <summary> /// <para>Order.</para> /// <para>Represents the following element tag in the schema: c:order.</para> /// </summary> /// <remark> /// xmlns:c = http://schemas.openxmlformats.org/drawingml/2006/chart /// </remark> public DocumentFormat.OpenXml.Drawing.Charts.Order? Order { get => GetElement<DocumentFormat.OpenXml.Drawing.Charts.Order>(); set => SetElement(value); } /// <summary> /// <para>Series Text.</para> /// <para>Represents the following element tag in the schema: c:tx.</para> /// </summary> /// <remark> /// xmlns:c = http://schemas.openxmlformats.org/drawingml/2006/chart /// </remark> public DocumentFormat.OpenXml.Drawing.Charts.SeriesText? SeriesText { get => GetElement<DocumentFormat.OpenXml.Drawing.Charts.SeriesText>(); set => SetElement(value); } /// <summary> /// <para>ChartShapeProperties.</para> /// <para>Represents the following element tag in the schema: c:spPr.</para> /// </summary> /// <remark> /// xmlns:c = http://schemas.openxmlformats.org/drawingml/2006/chart /// </remark> public DocumentFormat.OpenXml.Drawing.Charts.ChartShapeProperties? ChartShapeProperties { get => GetElement<DocumentFormat.OpenXml.Drawing.Charts.ChartShapeProperties>(); set => SetElement(value); } /// <summary> /// <para>PictureOptions.</para> /// <para>Represents the following element tag in the schema: c:pictureOptions.</para> /// </summary> /// <remark> /// xmlns:c = http://schemas.openxmlformats.org/drawingml/2006/chart /// </remark> public DocumentFormat.OpenXml.Drawing.Charts.PictureOptions? PictureOptions { get => GetElement<DocumentFormat.OpenXml.Drawing.Charts.PictureOptions>(); set => SetElement(value); } /// <summary> /// <para>InvertIfNegative.</para> /// <para>Represents the following element tag in the schema: c:invertIfNegative.</para> /// </summary> /// <remark> /// xmlns:c = http://schemas.openxmlformats.org/drawingml/2006/chart /// </remark> public DocumentFormat.OpenXml.Drawing.Charts.InvertIfNegative? InvertIfNegative { get => GetElement<DocumentFormat.OpenXml.Drawing.Charts.InvertIfNegative>(); set => SetElement(value); } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<BubbleChartSeries>(deep); } /// <summary> /// <para>Defines the RadarChartSeries Class.</para> /// <para>This class is available in Office 2013 and above.</para> /// <para>When the object is serialized out as xml, it's qualified name is c15:ser.</para> /// </summary> /// <remark> /// <para>The following table lists the possible child types:</para> /// <list type="bullet"> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.ChartShapeProperties" /> <c>&lt;c:spPr></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.CategoryAxisData" /> <c>&lt;c:cat></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.DataLabels" /> <c>&lt;c:dLbls></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.DataPoint" /> <c>&lt;c:dPt></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.Marker" /> <c>&lt;c:marker></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.Values" /> <c>&lt;c:val></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.PictureOptions" /> <c>&lt;c:pictureOptions></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.RadarSerExtensionList" /> <c>&lt;c:extLst></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.SeriesText" /> <c>&lt;c:tx></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.Index" /> <c>&lt;c:idx></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.Order" /> <c>&lt;c:order></c></description></item> /// </list> /// </remark> [SchemaAttr("c15:ser")] public partial class RadarChartSeries : OpenXmlCompositeElement { /// <summary> /// Initializes a new instance of the RadarChartSeries class. /// </summary> public RadarChartSeries() : base() { } /// <summary> /// Initializes a new instance of the RadarChartSeries class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public RadarChartSeries(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the RadarChartSeries class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public RadarChartSeries(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the RadarChartSeries class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public RadarChartSeries(string outerXml) : base(outerXml) { } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.SetSchema("c15:ser"); builder.Availability = FileFormatVersions.Office2013; builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.ChartShapeProperties>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.CategoryAxisData>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.DataLabels>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.DataPoint>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.Marker>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.Values>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.PictureOptions>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.RadarSerExtensionList>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.SeriesText>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.Index>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.Order>(); builder.Particle = new CompositeParticle.Builder(ParticleType.Sequence, 1, 1) { new CompositeParticle.Builder(ParticleType.Group, 1, 1) { new CompositeParticle.Builder(ParticleType.Sequence, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.Index), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.Order), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.SeriesText), 0, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.ChartShapeProperties), 0, 1) } }, new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.PictureOptions), 0, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.Marker), 0, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.DataPoint), 0, 0), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.DataLabels), 0, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.CategoryAxisData), 0, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.Values), 0, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.RadarSerExtensionList), 0, 1) }; } /// <summary> /// <para>Index.</para> /// <para>Represents the following element tag in the schema: c:idx.</para> /// </summary> /// <remark> /// xmlns:c = http://schemas.openxmlformats.org/drawingml/2006/chart /// </remark> public DocumentFormat.OpenXml.Drawing.Charts.Index? Index { get => GetElement<DocumentFormat.OpenXml.Drawing.Charts.Index>(); set => SetElement(value); } /// <summary> /// <para>Order.</para> /// <para>Represents the following element tag in the schema: c:order.</para> /// </summary> /// <remark> /// xmlns:c = http://schemas.openxmlformats.org/drawingml/2006/chart /// </remark> public DocumentFormat.OpenXml.Drawing.Charts.Order? Order { get => GetElement<DocumentFormat.OpenXml.Drawing.Charts.Order>(); set => SetElement(value); } /// <summary> /// <para>Series Text.</para> /// <para>Represents the following element tag in the schema: c:tx.</para> /// </summary> /// <remark> /// xmlns:c = http://schemas.openxmlformats.org/drawingml/2006/chart /// </remark> public DocumentFormat.OpenXml.Drawing.Charts.SeriesText? SeriesText { get => GetElement<DocumentFormat.OpenXml.Drawing.Charts.SeriesText>(); set => SetElement(value); } /// <summary> /// <para>ChartShapeProperties.</para> /// <para>Represents the following element tag in the schema: c:spPr.</para> /// </summary> /// <remark> /// xmlns:c = http://schemas.openxmlformats.org/drawingml/2006/chart /// </remark> public DocumentFormat.OpenXml.Drawing.Charts.ChartShapeProperties? ChartShapeProperties { get => GetElement<DocumentFormat.OpenXml.Drawing.Charts.ChartShapeProperties>(); set => SetElement(value); } /// <summary> /// <para>PictureOptions.</para> /// <para>Represents the following element tag in the schema: c:pictureOptions.</para> /// </summary> /// <remark> /// xmlns:c = http://schemas.openxmlformats.org/drawingml/2006/chart /// </remark> public DocumentFormat.OpenXml.Drawing.Charts.PictureOptions? PictureOptions { get => GetElement<DocumentFormat.OpenXml.Drawing.Charts.PictureOptions>(); set => SetElement(value); } /// <summary> /// <para>Marker.</para> /// <para>Represents the following element tag in the schema: c:marker.</para> /// </summary> /// <remark> /// xmlns:c = http://schemas.openxmlformats.org/drawingml/2006/chart /// </remark> public DocumentFormat.OpenXml.Drawing.Charts.Marker? Marker { get => GetElement<DocumentFormat.OpenXml.Drawing.Charts.Marker>(); set => SetElement(value); } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<RadarChartSeries>(deep); } /// <summary> /// <para>Defines the SurfaceChartSeries Class.</para> /// <para>This class is available in Office 2013 and above.</para> /// <para>When the object is serialized out as xml, it's qualified name is c15:ser.</para> /// </summary> /// <remark> /// <para>The following table lists the possible child types:</para> /// <list type="bullet"> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.ChartShapeProperties" /> <c>&lt;c:spPr></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.CategoryAxisData" /> <c>&lt;c:cat></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.Bubble3D" /> <c>&lt;c:bubble3D></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.Values" /> <c>&lt;c:val></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.PictureOptions" /> <c>&lt;c:pictureOptions></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.SeriesText" /> <c>&lt;c:tx></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.SurfaceSerExtensionList" /> <c>&lt;c:extLst></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.Index" /> <c>&lt;c:idx></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.Order" /> <c>&lt;c:order></c></description></item> /// </list> /// </remark> [SchemaAttr("c15:ser")] public partial class SurfaceChartSeries : OpenXmlCompositeElement { /// <summary> /// Initializes a new instance of the SurfaceChartSeries class. /// </summary> public SurfaceChartSeries() : base() { } /// <summary> /// Initializes a new instance of the SurfaceChartSeries class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public SurfaceChartSeries(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the SurfaceChartSeries class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public SurfaceChartSeries(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the SurfaceChartSeries class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public SurfaceChartSeries(string outerXml) : base(outerXml) { } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.SetSchema("c15:ser"); builder.Availability = FileFormatVersions.Office2013; builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.ChartShapeProperties>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.CategoryAxisData>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.Bubble3D>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.Values>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.PictureOptions>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.SeriesText>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.SurfaceSerExtensionList>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.Index>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.Order>(); builder.Particle = new CompositeParticle.Builder(ParticleType.Sequence, 1, 1) { new CompositeParticle.Builder(ParticleType.Group, 1, 1) { new CompositeParticle.Builder(ParticleType.Sequence, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.Index), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.Order), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.SeriesText), 0, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.ChartShapeProperties), 0, 1) } }, new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.PictureOptions), 0, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.CategoryAxisData), 0, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.Values), 0, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.Bubble3D), 0, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.SurfaceSerExtensionList), 0, 1) }; } /// <summary> /// <para>Index.</para> /// <para>Represents the following element tag in the schema: c:idx.</para> /// </summary> /// <remark> /// xmlns:c = http://schemas.openxmlformats.org/drawingml/2006/chart /// </remark> public DocumentFormat.OpenXml.Drawing.Charts.Index? Index { get => GetElement<DocumentFormat.OpenXml.Drawing.Charts.Index>(); set => SetElement(value); } /// <summary> /// <para>Order.</para> /// <para>Represents the following element tag in the schema: c:order.</para> /// </summary> /// <remark> /// xmlns:c = http://schemas.openxmlformats.org/drawingml/2006/chart /// </remark> public DocumentFormat.OpenXml.Drawing.Charts.Order? Order { get => GetElement<DocumentFormat.OpenXml.Drawing.Charts.Order>(); set => SetElement(value); } /// <summary> /// <para>Series Text.</para> /// <para>Represents the following element tag in the schema: c:tx.</para> /// </summary> /// <remark> /// xmlns:c = http://schemas.openxmlformats.org/drawingml/2006/chart /// </remark> public DocumentFormat.OpenXml.Drawing.Charts.SeriesText? SeriesText { get => GetElement<DocumentFormat.OpenXml.Drawing.Charts.SeriesText>(); set => SetElement(value); } /// <summary> /// <para>ChartShapeProperties.</para> /// <para>Represents the following element tag in the schema: c:spPr.</para> /// </summary> /// <remark> /// xmlns:c = http://schemas.openxmlformats.org/drawingml/2006/chart /// </remark> public DocumentFormat.OpenXml.Drawing.Charts.ChartShapeProperties? ChartShapeProperties { get => GetElement<DocumentFormat.OpenXml.Drawing.Charts.ChartShapeProperties>(); set => SetElement(value); } /// <summary> /// <para>PictureOptions.</para> /// <para>Represents the following element tag in the schema: c:pictureOptions.</para> /// </summary> /// <remark> /// xmlns:c = http://schemas.openxmlformats.org/drawingml/2006/chart /// </remark> public DocumentFormat.OpenXml.Drawing.Charts.PictureOptions? PictureOptions { get => GetElement<DocumentFormat.OpenXml.Drawing.Charts.PictureOptions>(); set => SetElement(value); } /// <summary> /// <para>CategoryAxisData.</para> /// <para>Represents the following element tag in the schema: c:cat.</para> /// </summary> /// <remark> /// xmlns:c = http://schemas.openxmlformats.org/drawingml/2006/chart /// </remark> public DocumentFormat.OpenXml.Drawing.Charts.CategoryAxisData? CategoryAxisData { get => GetElement<DocumentFormat.OpenXml.Drawing.Charts.CategoryAxisData>(); set => SetElement(value); } /// <summary> /// <para>Values.</para> /// <para>Represents the following element tag in the schema: c:val.</para> /// </summary> /// <remark> /// xmlns:c = http://schemas.openxmlformats.org/drawingml/2006/chart /// </remark> public DocumentFormat.OpenXml.Drawing.Charts.Values? Values { get => GetElement<DocumentFormat.OpenXml.Drawing.Charts.Values>(); set => SetElement(value); } /// <summary> /// <para>Bubble3D.</para> /// <para>Represents the following element tag in the schema: c:bubble3D.</para> /// </summary> /// <remark> /// xmlns:c = http://schemas.openxmlformats.org/drawingml/2006/chart /// </remark> public DocumentFormat.OpenXml.Drawing.Charts.Bubble3D? Bubble3D { get => GetElement<DocumentFormat.OpenXml.Drawing.Charts.Bubble3D>(); set => SetElement(value); } /// <summary> /// <para>SurfaceSerExtensionList.</para> /// <para>Represents the following element tag in the schema: c:extLst.</para> /// </summary> /// <remark> /// xmlns:c = http://schemas.openxmlformats.org/drawingml/2006/chart /// </remark> public DocumentFormat.OpenXml.Drawing.Charts.SurfaceSerExtensionList? SurfaceSerExtensionList { get => GetElement<DocumentFormat.OpenXml.Drawing.Charts.SurfaceSerExtensionList>(); set => SetElement(value); } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<SurfaceChartSeries>(deep); } /// <summary> /// <para>Defines the DataLabelsRangeChache Class.</para> /// <para>This class is available in Office 2013 and above.</para> /// <para>When the object is serialized out as xml, it's qualified name is c15:dlblRangeCache.</para> /// </summary> /// <remark> /// <para>The following table lists the possible child types:</para> /// <list type="bullet"> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.StrDataExtensionList" /> <c>&lt;c:extLst></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.StringPoint" /> <c>&lt;c:pt></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.PointCount" /> <c>&lt;c:ptCount></c></description></item> /// </list> /// </remark> [SchemaAttr("c15:dlblRangeCache")] public partial class DataLabelsRangeChache : StringDataType { /// <summary> /// Initializes a new instance of the DataLabelsRangeChache class. /// </summary> public DataLabelsRangeChache() : base() { } /// <summary> /// Initializes a new instance of the DataLabelsRangeChache class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public DataLabelsRangeChache(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the DataLabelsRangeChache class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public DataLabelsRangeChache(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the DataLabelsRangeChache class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public DataLabelsRangeChache(string outerXml) : base(outerXml) { } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.SetSchema("c15:dlblRangeCache"); builder.Availability = FileFormatVersions.Office2013; builder.Particle = new CompositeParticle.Builder(ParticleType.Sequence, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.PointCount), 0, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.StringPoint), 0, 0), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.StrDataExtensionList), 0, 1) }; } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<DataLabelsRangeChache>(deep); } /// <summary> /// <para>Defines the DataLabelFieldTableCache Class.</para> /// <para>This class is available in Office 2013 and above.</para> /// <para>When the object is serialized out as xml, it's qualified name is c15:dlblFieldTableCache.</para> /// </summary> /// <remark> /// <para>The following table lists the possible child types:</para> /// <list type="bullet"> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.StrDataExtensionList" /> <c>&lt;c:extLst></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.StringPoint" /> <c>&lt;c:pt></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.PointCount" /> <c>&lt;c:ptCount></c></description></item> /// </list> /// </remark> [SchemaAttr("c15:dlblFieldTableCache")] public partial class DataLabelFieldTableCache : StringDataType { /// <summary> /// Initializes a new instance of the DataLabelFieldTableCache class. /// </summary> public DataLabelFieldTableCache() : base() { } /// <summary> /// Initializes a new instance of the DataLabelFieldTableCache class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public DataLabelFieldTableCache(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the DataLabelFieldTableCache class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public DataLabelFieldTableCache(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the DataLabelFieldTableCache class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public DataLabelFieldTableCache(string outerXml) : base(outerXml) { } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.SetSchema("c15:dlblFieldTableCache"); builder.Availability = FileFormatVersions.Office2013; builder.Particle = new CompositeParticle.Builder(ParticleType.Sequence, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.PointCount), 0, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.StringPoint), 0, 0), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.StrDataExtensionList), 0, 1) }; } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<DataLabelFieldTableCache>(deep); } /// <summary> /// <para>Defines the StringDataType Class.</para> /// <para>This class is available in Office 2007 and above.</para> /// <para>When the object is serialized out as xml, it's qualified name is :.</para> /// </summary> /// <remark> /// <para>The following table lists the possible child types:</para> /// <list type="bullet"> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.StrDataExtensionList" /> <c>&lt;c:extLst></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.StringPoint" /> <c>&lt;c:pt></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.PointCount" /> <c>&lt;c:ptCount></c></description></item> /// </list> /// </remark> public abstract partial class StringDataType : OpenXmlCompositeElement { /// <summary> /// Initializes a new instance of the StringDataType class. /// </summary> protected StringDataType() : base() { } /// <summary> /// Initializes a new instance of the StringDataType class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> protected StringDataType(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the StringDataType class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> protected StringDataType(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the StringDataType class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> protected StringDataType(string outerXml) : base(outerXml) { } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.StrDataExtensionList>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.StringPoint>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.PointCount>(); } /// <summary> /// <para>PointCount.</para> /// <para>Represents the following element tag in the schema: c:ptCount.</para> /// </summary> /// <remark> /// xmlns:c = http://schemas.openxmlformats.org/drawingml/2006/chart /// </remark> public DocumentFormat.OpenXml.Drawing.Charts.PointCount? PointCount { get => GetElement<DocumentFormat.OpenXml.Drawing.Charts.PointCount>(); set => SetElement(value); } } /// <summary> /// <para>Defines the Explosion Class.</para> /// <para>This class is available in Office 2013 and above.</para> /// <para>When the object is serialized out as xml, it's qualified name is c15:explosion.</para> /// </summary> [SchemaAttr("c15:explosion")] public partial class Explosion : OpenXmlLeafElement { /// <summary> /// Initializes a new instance of the Explosion class. /// </summary> public Explosion() : base() { } /// <summary> /// <para>Integer Value</para> /// <para>Represents the following attribute in the schema: val</para> /// </summary> [SchemaAttr("val")] public UInt32Value? Val { get => GetAttribute<UInt32Value>(); set => SetAttribute(value); } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.SetSchema("c15:explosion"); builder.Availability = FileFormatVersions.Office2013; builder.AddElement<Explosion>() .AddAttribute("val", a => a.Val, aBuilder => { aBuilder.AddValidator(RequiredValidator.Instance); }); } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<Explosion>(deep); } /// <summary> /// <para>Defines the Marker Class.</para> /// <para>This class is available in Office 2013 and above.</para> /// <para>When the object is serialized out as xml, it's qualified name is c15:marker.</para> /// </summary> /// <remark> /// <para>The following table lists the possible child types:</para> /// <list type="bullet"> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.ChartShapeProperties" /> <c>&lt;c:spPr></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.ExtensionList" /> <c>&lt;c:extLst></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.Size" /> <c>&lt;c:size></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.Symbol" /> <c>&lt;c:symbol></c></description></item> /// </list> /// </remark> [SchemaAttr("c15:marker")] public partial class Marker : OpenXmlCompositeElement { /// <summary> /// Initializes a new instance of the Marker class. /// </summary> public Marker() : base() { } /// <summary> /// Initializes a new instance of the Marker class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public Marker(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the Marker class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public Marker(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the Marker class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public Marker(string outerXml) : base(outerXml) { } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.SetSchema("c15:marker"); builder.Availability = FileFormatVersions.Office2013; builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.ChartShapeProperties>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.ExtensionList>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.Size>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.Symbol>(); builder.Particle = new CompositeParticle.Builder(ParticleType.Sequence, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.Symbol), 0, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.Size), 0, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.ChartShapeProperties), 0, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.ExtensionList), 0, 1) }; } /// <summary> /// <para>Symbol.</para> /// <para>Represents the following element tag in the schema: c:symbol.</para> /// </summary> /// <remark> /// xmlns:c = http://schemas.openxmlformats.org/drawingml/2006/chart /// </remark> public DocumentFormat.OpenXml.Drawing.Charts.Symbol? Symbol { get => GetElement<DocumentFormat.OpenXml.Drawing.Charts.Symbol>(); set => SetElement(value); } /// <summary> /// <para>Size.</para> /// <para>Represents the following element tag in the schema: c:size.</para> /// </summary> /// <remark> /// xmlns:c = http://schemas.openxmlformats.org/drawingml/2006/chart /// </remark> public DocumentFormat.OpenXml.Drawing.Charts.Size? Size { get => GetElement<DocumentFormat.OpenXml.Drawing.Charts.Size>(); set => SetElement(value); } /// <summary> /// <para>ChartShapeProperties.</para> /// <para>Represents the following element tag in the schema: c:spPr.</para> /// </summary> /// <remark> /// xmlns:c = http://schemas.openxmlformats.org/drawingml/2006/chart /// </remark> public DocumentFormat.OpenXml.Drawing.Charts.ChartShapeProperties? ChartShapeProperties { get => GetElement<DocumentFormat.OpenXml.Drawing.Charts.ChartShapeProperties>(); set => SetElement(value); } /// <summary> /// <para>Chart Extensibility.</para> /// <para>Represents the following element tag in the schema: c:extLst.</para> /// </summary> /// <remark> /// xmlns:c = http://schemas.openxmlformats.org/drawingml/2006/chart /// </remark> public DocumentFormat.OpenXml.Drawing.Charts.ExtensionList? ExtensionList { get => GetElement<DocumentFormat.OpenXml.Drawing.Charts.ExtensionList>(); set => SetElement(value); } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<Marker>(deep); } /// <summary> /// <para>Defines the DataLabel Class.</para> /// <para>This class is available in Office 2013 and above.</para> /// <para>When the object is serialized out as xml, it's qualified name is c15:dLbl.</para> /// </summary> /// <remark> /// <para>The following table lists the possible child types:</para> /// <list type="bullet"> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.ChartShapeProperties" /> <c>&lt;c:spPr></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.TextProperties" /> <c>&lt;c:txPr></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.Delete" /> <c>&lt;c:delete></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.ShowLegendKey" /> <c>&lt;c:showLegendKey></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.ShowValue" /> <c>&lt;c:showVal></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.ShowCategoryName" /> <c>&lt;c:showCatName></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.ShowSeriesName" /> <c>&lt;c:showSerName></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.ShowPercent" /> <c>&lt;c:showPercent></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.ShowBubbleSize" /> <c>&lt;c:showBubbleSize></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.DLblExtensionList" /> <c>&lt;c:extLst></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.DataLabelPosition" /> <c>&lt;c:dLblPos></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.Layout" /> <c>&lt;c:layout></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.NumberingFormat" /> <c>&lt;c:numFmt></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.ChartText" /> <c>&lt;c:tx></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.Index" /> <c>&lt;c:idx></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Drawing.Charts.Separator" /> <c>&lt;c:separator></c></description></item> /// </list> /// </remark> [SchemaAttr("c15:dLbl")] public partial class DataLabel : OpenXmlCompositeElement { /// <summary> /// Initializes a new instance of the DataLabel class. /// </summary> public DataLabel() : base() { } /// <summary> /// Initializes a new instance of the DataLabel class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public DataLabel(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the DataLabel class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public DataLabel(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the DataLabel class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public DataLabel(string outerXml) : base(outerXml) { } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.SetSchema("c15:dLbl"); builder.Availability = FileFormatVersions.Office2013; builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.ChartShapeProperties>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.TextProperties>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.Delete>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.ShowLegendKey>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.ShowValue>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.ShowCategoryName>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.ShowSeriesName>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.ShowPercent>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.ShowBubbleSize>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.DLblExtensionList>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.DataLabelPosition>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.Layout>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.NumberingFormat>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.ChartText>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.Index>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Charts.Separator>(); builder.Particle = new CompositeParticle.Builder(ParticleType.Sequence, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.Index), 1, 1), new CompositeParticle.Builder(ParticleType.Choice, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.Delete), 1, 1), new CompositeParticle.Builder(ParticleType.Group, 1, 1) { new CompositeParticle.Builder(ParticleType.Sequence, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.Layout), 0, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.ChartText), 0, 1), new CompositeParticle.Builder(ParticleType.Group, 1, 1) { new CompositeParticle.Builder(ParticleType.Sequence, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.NumberingFormat), 0, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.ChartShapeProperties), 0, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.TextProperties), 0, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.DataLabelPosition), 0, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.ShowLegendKey), 0, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.ShowValue), 0, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.ShowCategoryName), 0, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.ShowSeriesName), 0, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.ShowPercent), 0, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.ShowBubbleSize), 0, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.Separator), 0, 1) } } } } }, new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Charts.DLblExtensionList), 0, 1) }; } /// <summary> /// <para>Index.</para> /// <para>Represents the following element tag in the schema: c:idx.</para> /// </summary> /// <remark> /// xmlns:c = http://schemas.openxmlformats.org/drawingml/2006/chart /// </remark> public DocumentFormat.OpenXml.Drawing.Charts.Index? Index { get => GetElement<DocumentFormat.OpenXml.Drawing.Charts.Index>(); set => SetElement(value); } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<DataLabel>(deep); } /// <summary> /// <para>Defines the CategoryFilterException Class.</para> /// <para>This class is available in Office 2013 and above.</para> /// <para>When the object is serialized out as xml, it's qualified name is c15:categoryFilterException.</para> /// </summary> /// <remark> /// <para>The following table lists the possible child types:</para> /// <list type="bullet"> /// <item><description><see cref="DocumentFormat.OpenXml.Office2013.Drawing.Chart.ShapeProperties" /> <c>&lt;c15:spPr></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Office2013.Drawing.Chart.InvertIfNegativeBoolean" /> <c>&lt;c15:invertIfNegative></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Office2013.Drawing.Chart.Bubble3D" /> <c>&lt;c15:bubble3D></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Office2013.Drawing.Chart.DataLabel" /> <c>&lt;c15:dLbl></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Office2013.Drawing.Chart.Marker" /> <c>&lt;c15:marker></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Office2013.Drawing.Chart.Explosion" /> <c>&lt;c15:explosion></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Office2013.Drawing.Chart.SequenceOfReferences" /> <c>&lt;c15:sqref></c></description></item> /// </list> /// </remark> [SchemaAttr("c15:categoryFilterException")] public partial class CategoryFilterException : OpenXmlCompositeElement { /// <summary> /// Initializes a new instance of the CategoryFilterException class. /// </summary> public CategoryFilterException() : base() { } /// <summary> /// Initializes a new instance of the CategoryFilterException class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public CategoryFilterException(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the CategoryFilterException class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public CategoryFilterException(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the CategoryFilterException class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public CategoryFilterException(string outerXml) : base(outerXml) { } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.SetSchema("c15:categoryFilterException"); builder.Availability = FileFormatVersions.Office2013; builder.AddChild<DocumentFormat.OpenXml.Office2013.Drawing.Chart.ShapeProperties>(); builder.AddChild<DocumentFormat.OpenXml.Office2013.Drawing.Chart.InvertIfNegativeBoolean>(); builder.AddChild<DocumentFormat.OpenXml.Office2013.Drawing.Chart.Bubble3D>(); builder.AddChild<DocumentFormat.OpenXml.Office2013.Drawing.Chart.DataLabel>(); builder.AddChild<DocumentFormat.OpenXml.Office2013.Drawing.Chart.Marker>(); builder.AddChild<DocumentFormat.OpenXml.Office2013.Drawing.Chart.Explosion>(); builder.AddChild<DocumentFormat.OpenXml.Office2013.Drawing.Chart.SequenceOfReferences>(); builder.Particle = new CompositeParticle.Builder(ParticleType.Sequence, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Office2013.Drawing.Chart.SequenceOfReferences), 1, 1, version: FileFormatVersions.Office2013), new ElementParticle(typeof(DocumentFormat.OpenXml.Office2013.Drawing.Chart.ShapeProperties), 0, 1, version: FileFormatVersions.Office2013), new ElementParticle(typeof(DocumentFormat.OpenXml.Office2013.Drawing.Chart.Explosion), 0, 1, version: FileFormatVersions.Office2013), new ElementParticle(typeof(DocumentFormat.OpenXml.Office2013.Drawing.Chart.InvertIfNegativeBoolean), 0, 1, version: FileFormatVersions.Office2013), new ElementParticle(typeof(DocumentFormat.OpenXml.Office2013.Drawing.Chart.Bubble3D), 0, 1, version: FileFormatVersions.Office2013), new ElementParticle(typeof(DocumentFormat.OpenXml.Office2013.Drawing.Chart.Marker), 0, 1, version: FileFormatVersions.Office2013), new ElementParticle(typeof(DocumentFormat.OpenXml.Office2013.Drawing.Chart.DataLabel), 0, 1, version: FileFormatVersions.Office2013) }; } /// <summary> /// <para>SequenceOfReferences.</para> /// <para>Represents the following element tag in the schema: c15:sqref.</para> /// </summary> /// <remark> /// xmlns:c15 = http://schemas.microsoft.com/office/drawing/2012/chart /// </remark> public DocumentFormat.OpenXml.Office2013.Drawing.Chart.SequenceOfReferences? SequenceOfReferences { get => GetElement<DocumentFormat.OpenXml.Office2013.Drawing.Chart.SequenceOfReferences>(); set => SetElement(value); } /// <summary> /// <para>ShapeProperties.</para> /// <para>Represents the following element tag in the schema: c15:spPr.</para> /// </summary> /// <remark> /// xmlns:c15 = http://schemas.microsoft.com/office/drawing/2012/chart /// </remark> public DocumentFormat.OpenXml.Office2013.Drawing.Chart.ShapeProperties? ShapeProperties { get => GetElement<DocumentFormat.OpenXml.Office2013.Drawing.Chart.ShapeProperties>(); set => SetElement(value); } /// <summary> /// <para>Explosion.</para> /// <para>Represents the following element tag in the schema: c15:explosion.</para> /// </summary> /// <remark> /// xmlns:c15 = http://schemas.microsoft.com/office/drawing/2012/chart /// </remark> public DocumentFormat.OpenXml.Office2013.Drawing.Chart.Explosion? Explosion { get => GetElement<DocumentFormat.OpenXml.Office2013.Drawing.Chart.Explosion>(); set => SetElement(value); } /// <summary> /// <para>InvertIfNegativeBoolean.</para> /// <para>Represents the following element tag in the schema: c15:invertIfNegative.</para> /// </summary> /// <remark> /// xmlns:c15 = http://schemas.microsoft.com/office/drawing/2012/chart /// </remark> public DocumentFormat.OpenXml.Office2013.Drawing.Chart.InvertIfNegativeBoolean? InvertIfNegativeBoolean { get => GetElement<DocumentFormat.OpenXml.Office2013.Drawing.Chart.InvertIfNegativeBoolean>(); set => SetElement(value); } /// <summary> /// <para>Bubble3D.</para> /// <para>Represents the following element tag in the schema: c15:bubble3D.</para> /// </summary> /// <remark> /// xmlns:c15 = http://schemas.microsoft.com/office/drawing/2012/chart /// </remark> public DocumentFormat.OpenXml.Office2013.Drawing.Chart.Bubble3D? Bubble3D { get => GetElement<DocumentFormat.OpenXml.Office2013.Drawing.Chart.Bubble3D>(); set => SetElement(value); } /// <summary> /// <para>Marker.</para> /// <para>Represents the following element tag in the schema: c15:marker.</para> /// </summary> /// <remark> /// xmlns:c15 = http://schemas.microsoft.com/office/drawing/2012/chart /// </remark> public DocumentFormat.OpenXml.Office2013.Drawing.Chart.Marker? Marker { get => GetElement<DocumentFormat.OpenXml.Office2013.Drawing.Chart.Marker>(); set => SetElement(value); } /// <summary> /// <para>DataLabel.</para> /// <para>Represents the following element tag in the schema: c15:dLbl.</para> /// </summary> /// <remark> /// xmlns:c15 = http://schemas.microsoft.com/office/drawing/2012/chart /// </remark> public DocumentFormat.OpenXml.Office2013.Drawing.Chart.DataLabel? DataLabel { get => GetElement<DocumentFormat.OpenXml.Office2013.Drawing.Chart.DataLabel>(); set => SetElement(value); } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<CategoryFilterException>(deep); } /// <summary> /// <para>Defines the DataLabelFieldTableEntry Class.</para> /// <para>This class is available in Office 2013 and above.</para> /// <para>When the object is serialized out as xml, it's qualified name is c15:dlblFTEntry.</para> /// </summary> /// <remark> /// <para>The following table lists the possible child types:</para> /// <list type="bullet"> /// <item><description><see cref="DocumentFormat.OpenXml.Office2013.Drawing.Chart.DataLabelFieldTableCache" /> <c>&lt;c15:dlblFieldTableCache></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Office2013.Drawing.Chart.TextFieldGuid" /> <c>&lt;c15:txfldGUID></c></description></item> /// <item><description><see cref="DocumentFormat.OpenXml.Office2013.Drawing.Chart.Formula" /> <c>&lt;c15:f></c></description></item> /// </list> /// </remark> [SchemaAttr("c15:dlblFTEntry")] public partial class DataLabelFieldTableEntry : OpenXmlCompositeElement { /// <summary> /// Initializes a new instance of the DataLabelFieldTableEntry class. /// </summary> public DataLabelFieldTableEntry() : base() { } /// <summary> /// Initializes a new instance of the DataLabelFieldTableEntry class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public DataLabelFieldTableEntry(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the DataLabelFieldTableEntry class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public DataLabelFieldTableEntry(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the DataLabelFieldTableEntry class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public DataLabelFieldTableEntry(string outerXml) : base(outerXml) { } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.SetSchema("c15:dlblFTEntry"); builder.Availability = FileFormatVersions.Office2013; builder.AddChild<DocumentFormat.OpenXml.Office2013.Drawing.Chart.DataLabelFieldTableCache>(); builder.AddChild<DocumentFormat.OpenXml.Office2013.Drawing.Chart.TextFieldGuid>(); builder.AddChild<DocumentFormat.OpenXml.Office2013.Drawing.Chart.Formula>(); builder.Particle = new CompositeParticle.Builder(ParticleType.Sequence, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Office2013.Drawing.Chart.TextFieldGuid), 1, 1, version: FileFormatVersions.Office2013), new ElementParticle(typeof(DocumentFormat.OpenXml.Office2013.Drawing.Chart.Formula), 1, 1, version: FileFormatVersions.Office2013), new ElementParticle(typeof(DocumentFormat.OpenXml.Office2013.Drawing.Chart.DataLabelFieldTableCache), 0, 1, version: FileFormatVersions.Office2013) }; } /// <summary> /// <para>TextFieldGuid.</para> /// <para>Represents the following element tag in the schema: c15:txfldGUID.</para> /// </summary> /// <remark> /// xmlns:c15 = http://schemas.microsoft.com/office/drawing/2012/chart /// </remark> public DocumentFormat.OpenXml.Office2013.Drawing.Chart.TextFieldGuid? TextFieldGuid { get => GetElement<DocumentFormat.OpenXml.Office2013.Drawing.Chart.TextFieldGuid>(); set => SetElement(value); } /// <summary> /// <para>Formula.</para> /// <para>Represents the following element tag in the schema: c15:f.</para> /// </summary> /// <remark> /// xmlns:c15 = http://schemas.microsoft.com/office/drawing/2012/chart /// </remark> public DocumentFormat.OpenXml.Office2013.Drawing.Chart.Formula? Formula { get => GetElement<DocumentFormat.OpenXml.Office2013.Drawing.Chart.Formula>(); set => SetElement(value); } /// <summary> /// <para>DataLabelFieldTableCache.</para> /// <para>Represents the following element tag in the schema: c15:dlblFieldTableCache.</para> /// </summary> /// <remark> /// xmlns:c15 = http://schemas.microsoft.com/office/drawing/2012/chart /// </remark> public DocumentFormat.OpenXml.Office2013.Drawing.Chart.DataLabelFieldTableCache? DataLabelFieldTableCache { get => GetElement<DocumentFormat.OpenXml.Office2013.Drawing.Chart.DataLabelFieldTableCache>(); set => SetElement(value); } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<DataLabelFieldTableEntry>(deep); } }
ThomasBarnekow/Open-XML-SDK
src/DocumentFormat.OpenXml/GeneratedCode/schemas_microsoft_com_office_drawing_2012_chart.g.cs
C#
mit
211,463
<?php /** * (c) Vincent Patry * This file is part of the Rebond package * For the full copyright and license information, please view the LICENSE.txt * file that was distributed with this source code. */ namespace Rebond\Enums\Core; use Rebond\Enums\AbstractEnum; class ResponseFormat extends AbstractEnum { const HTML = 0; const JSON = 1; }
vincium/rebond-framework
src/Rebond/Enums/Core/ResponseFormat.php
PHP
mit
357
#include <cctype> #include <iostream> #include <map> #include <string> using namespace std; constexpr char found_symbol {'#'}; inline void use_io_optimizations() { ios_base::sync_with_stdio(false); cin.tie(nullptr); } inline char opposite(char symbol) { return islower(symbol) ? toupper(symbol) : tolower(symbol); } int main() { use_io_optimizations(); string message; string newspaper; cin >> message >> newspaper; map<char, unsigned int> frequencies; for (auto symbol : newspaper) { ++frequencies[symbol]; } unsigned int yay_count {0}; unsigned int woops_count {0}; for (auto& symbol : message) { if (frequencies[symbol]) { ++yay_count; --frequencies[symbol]; symbol = found_symbol; } } for (auto symbol : message) { if (symbol != found_symbol && frequencies[opposite(symbol)]) { ++woops_count; --frequencies[opposite(symbol)]; } } cout << yay_count << ' ' << woops_count << '\n'; return 0; }
gshopov/competitive-programming-archive
codeforces/round-293/div-2/tanya_and_postcard.cpp
C++
mit
1,111
from django.core.exceptions import ObjectDoesNotExist from django.http import HttpResponseRedirect from django.contrib import messages from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User from django.template.loader import render_to_string from django.core.mail import send_mail from django.shortcuts import render, reverse from interlecture.local_settings import HOSTNAME,EMAIL_FROM import datetime import hashlib import random import dateutil.tz from interauth.forms import UserForm from interauth.models import UserActivation def login_view(request): context = {'app_name': 'login'} if request.user.is_authenticated(): return HttpResponseRedirect(reverse('select-course')) elif request.method == 'POST': user = authenticate(username=request.POST['uname'], password=request.POST['passwd']) if user is not None: login(request, user) if request.user.is_authenticated(): messages.info(request, "True") return HttpResponseRedirect(reverse('select-course')) else: context['args'] = '{failedLogin:true,}' return render(request, 'base.html', context=context) else: context['args'] = '{failedLogin:false,}' return render(request, 'base.html', context=context) @login_required def logout_view(request): logout(request) return HttpResponseRedirect(reverse('login')) def register(request): if request.user.is_authenticated(): return HttpResponseRedirect(reverse('select-course')) context = {} if request.method == 'POST': form = UserForm(request.POST) if form.is_valid(): new_user = User.objects.create_user( username=request.POST['username'], email=request.POST['email'], password=request.POST['password'], first_name=request.POST['first_name'], last_name=request.POST['last_name'], is_active=False ) # TODO: Email activation of user init_activation(new_user) context['args'] = '{}' context['app_name'] = 'login' return render(request, 'base.html', context=context) else: context['args'] = '{' + form.d2r_friendly_errors() + form.safe_data() + '}' context['app_name'] = 'register' return render(request, 'base.html', context=context) else: context['app_name'] = 'register' context['args'] = '{}' return render(request, 'base.html', context=context) def activate(request, key): try: activation = UserActivation.objects.get(activation_key=key) except ObjectDoesNotExist: return HttpResponseRedirect(reverse('register')) if not activation.user.is_active: if datetime.datetime.now(tz=dateutil.tz.tzlocal()) > activation.key_expires: return HttpResponseRedirect(reverse('resend-activation')) else: activation.user.is_active = True activation.user.save() return HttpResponseRedirect(reverse('select-course')) def resend_activation_link(request): if request.user.is_authenticated: return HttpResponseRedirect(reverse('select-course')) if request.method == 'POST': try: user = User.objects.get(email=request.POST['email']) if user.is_active: return HttpResponseRedirect(reverse('login')) activation = UserActivation.objects.get(user=user) activation.key_expires = datetime.datetime.now(dateutil.tz.tzlocal()) + datetime.timedelta(days=2) send_activation_mail(activation) return HttpResponseRedirect('login') except ObjectDoesNotExist: return HttpResponseRedirect(reverse('resend-activation')) context = { 'app_name': 'resend_activation', 'args': '{}' } return render(request, 'base.html', context=context) def init_activation(user): salt = hashlib.sha1(str(random.random()).encode('utf8')).hexdigest()[:8] usernamesalt = user.username activation = UserActivation() activation.user = user activation.activation_key = hashlib.sha3_512(str(salt + usernamesalt).encode('utf8')).hexdigest() activation.key_expires = datetime.datetime.now(dateutil.tz.tzlocal()) + datetime.timedelta(days=2) activation.save() send_activation_mail(activation) def send_activation_mail(activation): mail_body = render_to_string('activation_mail.html', context={'activation': activation,'HOSTNAME':HOSTNAME}) _ = send_mail( subject='Interlecture Account Activation', message='', from_email=EMAIL_FROM, recipient_list=[activation.user.email], html_message=mail_body )
afriestad/interlecture
interlecture/interauth/views.py
Python
mit
4,933
// This file is licensed to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Linq; using System.Xml.Linq; using Spines.Utility; namespace Spines.Tenhou.Client { /// <summary> /// Data provided by the server when a player discards a tile. /// </summary> public class DiscardInformation { /// <summary> /// 0, 1, 2, 3 for T, U, V, W. /// </summary> public int PlayerIndex { get; private set; } /// <summary> /// Id of the discarded tile. /// </summary> public Tile Tile { get; private set; } /// <summary> /// True if the discarded tile is the last tile drawn. /// </summary> public bool Tsumokiri { get; } /// <summary> /// True if the discarded tile can be called. /// </summary> public bool Callable { get; private set; } internal DiscardInformation(XElement message) { Callable = message.Attributes("t").Any(); var name = message.Name.LocalName; Tsumokiri = "defg".Contains(name[0]); PlayerIndex = name[0] - (Tsumokiri ? 'd' : 'D'); Tile = new Tile(InvariantConvert.ToInt32(name.Substring(1))); } } }
spinesheath/HanaMahjong
Spines.Mahjong/Spines.Tenhou.Client/DiscardInformation.cs
C#
mit
1,186
package besa_adaptado.adaptador; import adaptation.common.query.AdaptationQueryAES; public class Consulta extends AdaptationQueryAES { public Consulta(String query) { setQuery(query); } }
Coregraph/Ayllu
JigSaw - AYPUY - CS/AES_MATEO/src/besa_adaptado/adaptador/Consulta.java
Java
mit
217
var clients = require('./../../data.js').clients; module.exports.getId = function(client) { return client.id; }; module.exports.getRedirectUri = function(client) { return client.redirectUri; }; module.exports.fetchById = function(clientId, cb) { for (var i in clients) { if (clientId == clients[i].id) return cb(null, clients[i]); } cb(); }; module.exports.checkSecret = function(client, secret) { return (client.secret == secret); };
ojengwa/node-oauth20-provider
test/server/model/memory/oauth2/client.js
JavaScript
mit
470
#!/usr/bin/env node /* Logfella Copyright (c) 2015 - 2019 Cédric Ronvel The MIT License (MIT) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ "use strict" ; var Logfella = require( '../lib/Logfella.js' ) ; /* Tests */ describe( "NetServer Transport" , function() { it( "simple test" , function( done ) { this.timeout( 10000 ) ; var logger = Logfella.create() ; var count = 0 ; logger.setGlobalConfig( { minLevel: 'trace' , defaultDomain: 'default-domain' } ) ; logger.addTransport( 'console' , { minLevel: 'trace' , output: process.stderr } ) ; logger.addTransport( 'netServer' , { minLevel: 'trace' , listen: 1234 } ) ; logger.logTransports[ 1 ].server.on( 'connection' , function() { count ++ ; if ( count >= 2 ) { logger.warning( 'storage' , 'gloups' , 'We are running out of storage! Only %iMB left' , 139 ) ; logger.info( 'idle' , { some: 'meta' , few: 'data' , somethingElse: 4 } , 'Youpla boum!' ) ; setTimeout( done , 30 ) ; } } ) ; } ) ; } ) ;
cronvel/logger-kit
sample/net-server-test.js
JavaScript
mit
2,053
/* * Copyright (C) 2009 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * @constructor */ WebInspector.Settings = function() { this._eventSupport = new WebInspector.Object(); this._registry = /** @type {!Object.<string, !WebInspector.Setting>} */ ({}); this.colorFormat = this.createSetting("colorFormat", "original"); this.consoleHistory = this.createSetting("consoleHistory", []); this.domWordWrap = this.createSetting("domWordWrap", true); this.eventListenersFilter = this.createSetting("eventListenersFilter", "all"); this.lastViewedScriptFile = this.createSetting("lastViewedScriptFile", "application"); this.monitoringXHREnabled = this.createSetting("monitoringXHREnabled", false); this.preserveConsoleLog = this.createSetting("preserveConsoleLog", false); this.consoleTimestampsEnabled = this.createSetting("consoleTimestampsEnabled", false); this.resourcesLargeRows = this.createSetting("resourcesLargeRows", true); this.resourcesSortOptions = this.createSetting("resourcesSortOptions", {timeOption: "responseTime", sizeOption: "transferSize"}); this.resourceViewTab = this.createSetting("resourceViewTab", "preview"); this.showInheritedComputedStyleProperties = this.createSetting("showInheritedComputedStyleProperties", false); this.showUserAgentStyles = this.createSetting("showUserAgentStyles", true); this.watchExpressions = this.createSetting("watchExpressions", []); this.breakpoints = this.createSetting("breakpoints", []); this.eventListenerBreakpoints = this.createSetting("eventListenerBreakpoints", []); this.domBreakpoints = this.createSetting("domBreakpoints", []); this.xhrBreakpoints = this.createSetting("xhrBreakpoints", []); this.jsSourceMapsEnabled = this.createSetting("sourceMapsEnabled", true); this.cssSourceMapsEnabled = this.createSetting("cssSourceMapsEnabled", true); this.cacheDisabled = this.createSetting("cacheDisabled", false); this.showUAShadowDOM = this.createSetting("showUAShadowDOM", false); this.savedURLs = this.createSetting("savedURLs", {}); this.javaScriptDisabled = this.createSetting("javaScriptDisabled", false); this.showAdvancedHeapSnapshotProperties = this.createSetting("showAdvancedHeapSnapshotProperties", false); this.recordAllocationStacks = this.createSetting("recordAllocationStacks", false); this.highResolutionCpuProfiling = this.createSetting("highResolutionCpuProfiling", false); this.searchInContentScripts = this.createSetting("searchInContentScripts", false); this.textEditorIndent = this.createSetting("textEditorIndent", " "); this.textEditorAutoDetectIndent = this.createSetting("textEditorAutoIndentIndent", true); this.textEditorAutocompletion = this.createSetting("textEditorAutocompletion", true); this.textEditorBracketMatching = this.createSetting("textEditorBracketMatching", true); this.cssReloadEnabled = this.createSetting("cssReloadEnabled", false); this.timelineLiveUpdate = this.createSetting("timelineLiveUpdate", true); this.showMetricsRulers = this.createSetting("showMetricsRulers", false); this.workerInspectorWidth = this.createSetting("workerInspectorWidth", 600); this.workerInspectorHeight = this.createSetting("workerInspectorHeight", 600); this.messageURLFilters = this.createSetting("messageURLFilters", {}); this.networkHideDataURL = this.createSetting("networkHideDataURL", false); this.networkResourceTypeFilters = this.createSetting("networkResourceTypeFilters", {}); this.messageLevelFilters = this.createSetting("messageLevelFilters", {}); this.splitVerticallyWhenDockedToRight = this.createSetting("splitVerticallyWhenDockedToRight", true); this.visiblePanels = this.createSetting("visiblePanels", {}); this.shortcutPanelSwitch = this.createSetting("shortcutPanelSwitch", false); this.showWhitespacesInEditor = this.createSetting("showWhitespacesInEditor", false); this.skipStackFramesPattern = this.createRegExpSetting("skipStackFramesPattern", ""); this.pauseOnExceptionEnabled = this.createSetting("pauseOnExceptionEnabled", false); this.pauseOnCaughtException = this.createSetting("pauseOnCaughtException", false); this.enableAsyncStackTraces = this.createSetting("enableAsyncStackTraces", false); this.showMediaQueryInspector = this.createSetting("showMediaQueryInspector", false); this.disableOverridesWarning = this.createSetting("disableOverridesWarning", false); // Rendering options this.showPaintRects = this.createSetting("showPaintRects", false); this.showDebugBorders = this.createSetting("showDebugBorders", false); this.showFPSCounter = this.createSetting("showFPSCounter", false); this.continuousPainting = this.createSetting("continuousPainting", false); this.showScrollBottleneckRects = this.createSetting("showScrollBottleneckRects", false); } WebInspector.Settings.prototype = { /** * @param {string} key * @param {*} defaultValue * @return {!WebInspector.Setting} */ createSetting: function(key, defaultValue) { if (!this._registry[key]) this._registry[key] = new WebInspector.Setting(key, defaultValue, this._eventSupport, window.localStorage); return this._registry[key]; }, /** * @param {string} key * @param {string} defaultValue * @param {string=} regexFlags * @return {!WebInspector.Setting} */ createRegExpSetting: function(key, defaultValue, regexFlags) { if (!this._registry[key]) this._registry[key] = new WebInspector.RegExpSetting(key, defaultValue, this._eventSupport, window.localStorage, regexFlags); return this._registry[key]; } } /** * @constructor * @param {string} name * @param {V} defaultValue * @param {!WebInspector.Object} eventSupport * @param {?Storage} storage * @template V */ WebInspector.Setting = function(name, defaultValue, eventSupport, storage) { this._name = name; this._defaultValue = defaultValue; this._eventSupport = eventSupport; this._storage = storage; } WebInspector.Setting.prototype = { /** * @param {function(!WebInspector.Event)} listener * @param {!Object=} thisObject */ addChangeListener: function(listener, thisObject) { this._eventSupport.addEventListener(this._name, listener, thisObject); }, /** * @param {function(!WebInspector.Event)} listener * @param {!Object=} thisObject */ removeChangeListener: function(listener, thisObject) { this._eventSupport.removeEventListener(this._name, listener, thisObject); }, get name() { return this._name; }, /** * @return {V} */ get: function() { if (typeof this._value !== "undefined") return this._value; this._value = this._defaultValue; if (this._storage && this._name in this._storage) { try { this._value = JSON.parse(this._storage[this._name]); } catch(e) { delete this._storage[this._name]; } } return this._value; }, /** * @param {V} value */ set: function(value) { this._value = value; if (this._storage) { try { this._storage[this._name] = JSON.stringify(value); } catch(e) { console.error("Error saving setting with name:" + this._name); } } this._eventSupport.dispatchEventToListeners(this._name, value); } } /** * @constructor * @extends {WebInspector.Setting} * @param {string} name * @param {string} defaultValue * @param {!WebInspector.Object} eventSupport * @param {?Storage} storage * @param {string=} regexFlags */ WebInspector.RegExpSetting = function(name, defaultValue, eventSupport, storage, regexFlags) { WebInspector.Setting.call(this, name, defaultValue ? [{ pattern: defaultValue }] : [], eventSupport, storage); this._regexFlags = regexFlags; } WebInspector.RegExpSetting.prototype = { /** * @override * @return {string} */ get: function() { var result = []; var items = this.getAsArray(); for (var i = 0; i < items.length; ++i) { var item = items[i]; if (item.pattern && !item.disabled) result.push(item.pattern); } return result.join("|"); }, /** * @return {!Array.<{pattern: string, disabled: (boolean|undefined)}>} */ getAsArray: function() { return WebInspector.Setting.prototype.get.call(this); }, /** * @override * @param {string} value */ set: function(value) { this.setAsArray([{ pattern: value }]); }, /** * @param {!Array.<{pattern: string, disabled: (boolean|undefined)}>} value */ setAsArray: function(value) { delete this._regex; WebInspector.Setting.prototype.set.call(this, value); }, /** * @return {?RegExp} */ asRegExp: function() { if (typeof this._regex !== "undefined") return this._regex; this._regex = null; try { var pattern = this.get(); if (pattern) this._regex = new RegExp(pattern, this._regexFlags || ""); } catch (e) { } return this._regex; }, __proto__: WebInspector.Setting.prototype } /** * @constructor * @param {boolean} experimentsEnabled */ WebInspector.ExperimentsSettings = function(experimentsEnabled) { this._experimentsEnabled = experimentsEnabled; this._setting = WebInspector.settings.createSetting("experiments", {}); this._experiments = []; this._enabledForTest = {}; // Add currently running experiments here. this.applyCustomStylesheet = this._createExperiment("applyCustomStylesheet", "Allow custom UI themes"); this.canvasInspection = this._createExperiment("canvasInspection ", "Canvas inspection"); this.devicesPanel = this._createExperiment("devicesPanel", "Devices panel"); this.disableAgentsWhenProfile = this._createExperiment("disableAgentsWhenProfile", "Disable other agents and UI when profiler is active", true); this.dockToLeft = this._createExperiment("dockToLeft", "Dock to left", true); this.documentation = this._createExperiment("documentation", "Documentation for JS and CSS", true); this.fileSystemInspection = this._createExperiment("fileSystemInspection", "FileSystem inspection"); this.gpuTimeline = this._createExperiment("gpuTimeline", "GPU data on timeline", true); this.layersPanel = this._createExperiment("layersPanel", "Layers panel"); this.paintProfiler = this._createExperiment("paintProfiler", "Paint profiler"); this.timelineOnTraceEvents = this._createExperiment("timelineOnTraceEvents", "Timeline on trace events"); this.timelinePowerProfiler = this._createExperiment("timelinePowerProfiler", "Timeline power profiler"); this.timelineJSCPUProfile = this._createExperiment("timelineJSCPUProfile", "Timeline with JS sampling"); this._cleanUpSetting(); } WebInspector.ExperimentsSettings.prototype = { /** * @return {!Array.<!WebInspector.Experiment>} */ get experiments() { return this._experiments.slice(); }, /** * @return {boolean} */ get experimentsEnabled() { return this._experimentsEnabled; }, /** * @param {string} experimentName * @param {string} experimentTitle * @param {boolean=} hidden * @return {!WebInspector.Experiment} */ _createExperiment: function(experimentName, experimentTitle, hidden) { var experiment = new WebInspector.Experiment(this, experimentName, experimentTitle, !!hidden); this._experiments.push(experiment); return experiment; }, /** * @param {string} experimentName * @return {boolean} */ isEnabled: function(experimentName) { if (this._enabledForTest[experimentName]) return true; if (!this.experimentsEnabled) return false; var experimentsSetting = this._setting.get(); return experimentsSetting[experimentName]; }, /** * @param {string} experimentName * @param {boolean} enabled */ setEnabled: function(experimentName, enabled) { var experimentsSetting = this._setting.get(); experimentsSetting[experimentName] = enabled; this._setting.set(experimentsSetting); }, /** * @param {string} experimentName */ _enableForTest: function(experimentName) { this._enabledForTest[experimentName] = true; }, _cleanUpSetting: function() { var experimentsSetting = this._setting.get(); var cleanedUpExperimentSetting = {}; for (var i = 0; i < this._experiments.length; ++i) { var experimentName = this._experiments[i].name; if (experimentsSetting[experimentName]) cleanedUpExperimentSetting[experimentName] = true; } this._setting.set(cleanedUpExperimentSetting); } } /** * @constructor * @param {!WebInspector.ExperimentsSettings} experimentsSettings * @param {string} name * @param {string} title * @param {boolean} hidden */ WebInspector.Experiment = function(experimentsSettings, name, title, hidden) { this._name = name; this._title = title; this._hidden = hidden; this._experimentsSettings = experimentsSettings; } WebInspector.Experiment.prototype = { /** * @return {string} */ get name() { return this._name; }, /** * @return {string} */ get title() { return this._title; }, /** * @return {boolean} */ get hidden() { return this._hidden; }, /** * @return {boolean} */ isEnabled: function() { return this._experimentsSettings.isEnabled(this._name); }, /** * @param {boolean} enabled */ setEnabled: function(enabled) { this._experimentsSettings.setEnabled(this._name, enabled); }, enableForTest: function() { this._experimentsSettings._enableForTest(this._name); } } /** * @constructor */ WebInspector.VersionController = function() { } WebInspector.VersionController.currentVersion = 9; WebInspector.VersionController.prototype = { updateVersion: function() { var versionSetting = WebInspector.settings.createSetting("inspectorVersion", 0); var currentVersion = WebInspector.VersionController.currentVersion; var oldVersion = versionSetting.get(); var methodsToRun = this._methodsToRunToUpdateVersion(oldVersion, currentVersion); for (var i = 0; i < methodsToRun.length; ++i) this[methodsToRun[i]].call(this); versionSetting.set(currentVersion); }, /** * @param {number} oldVersion * @param {number} currentVersion */ _methodsToRunToUpdateVersion: function(oldVersion, currentVersion) { var result = []; for (var i = oldVersion; i < currentVersion; ++i) result.push("_updateVersionFrom" + i + "To" + (i + 1)); return result; }, _updateVersionFrom0To1: function() { this._clearBreakpointsWhenTooMany(WebInspector.settings.breakpoints, 500000); }, _updateVersionFrom1To2: function() { var versionSetting = WebInspector.settings.createSetting("previouslyViewedFiles", []); versionSetting.set([]); }, _updateVersionFrom2To3: function() { var fileSystemMappingSetting = WebInspector.settings.createSetting("fileSystemMapping", {}); fileSystemMappingSetting.set({}); if (window.localStorage) delete window.localStorage["fileMappingEntries"]; }, _updateVersionFrom3To4: function() { var advancedMode = WebInspector.settings.createSetting("showHeaSnapshotObjectsHiddenProperties", false).get(); WebInspector.settings.showAdvancedHeapSnapshotProperties.set(advancedMode); }, _updateVersionFrom4To5: function() { if (!window.localStorage) return; var settingNames = { "FileSystemViewSidebarWidth": "fileSystemViewSplitViewState", "canvasProfileViewReplaySplitLocation": "canvasProfileViewReplaySplitViewState", "canvasProfileViewSplitLocation": "canvasProfileViewSplitViewState", "elementsSidebarWidth": "elementsPanelSplitViewState", "StylesPaneSplitRatio": "stylesPaneSplitViewState", "heapSnapshotRetainersViewSize": "heapSnapshotSplitViewState", "InspectorView.splitView": "InspectorView.splitViewState", "InspectorView.screencastSplitView": "InspectorView.screencastSplitViewState", "Inspector.drawerSplitView": "Inspector.drawerSplitViewState", "layerDetailsSplitView": "layerDetailsSplitViewState", "networkSidebarWidth": "networkPanelSplitViewState", "sourcesSidebarWidth": "sourcesPanelSplitViewState", "scriptsPanelNavigatorSidebarWidth": "sourcesPanelNavigatorSplitViewState", "sourcesPanelSplitSidebarRatio": "sourcesPanelDebuggerSidebarSplitViewState", "timeline-details": "timelinePanelDetailsSplitViewState", "timeline-split": "timelinePanelRecorsSplitViewState", "timeline-view": "timelinePanelTimelineStackSplitViewState", "auditsSidebarWidth": "auditsPanelSplitViewState", "layersSidebarWidth": "layersPanelSplitViewState", "profilesSidebarWidth": "profilesPanelSplitViewState", "resourcesSidebarWidth": "resourcesPanelSplitViewState" }; for (var oldName in settingNames) { var newName = settingNames[oldName]; var oldNameH = oldName + "H"; var newValue = null; var oldSetting = WebInspector.settings.createSetting(oldName, undefined).get(); if (oldSetting) { newValue = newValue || {}; newValue.vertical = {}; newValue.vertical.size = oldSetting; delete window.localStorage[oldName]; } var oldSettingH = WebInspector.settings.createSetting(oldNameH, undefined).get(); if (oldSettingH) { newValue = newValue || {}; newValue.horizontal = {}; newValue.horizontal.size = oldSettingH; delete window.localStorage[oldNameH]; } var newSetting = WebInspector.settings.createSetting(newName, {}); if (newValue) newSetting.set(newValue); } }, _updateVersionFrom5To6: function() { if (!window.localStorage) return; var settingNames = { "debuggerSidebarHidden": "sourcesPanelSplitViewState", "navigatorHidden": "sourcesPanelNavigatorSplitViewState", "WebInspector.Drawer.showOnLoad": "Inspector.drawerSplitViewState" }; for (var oldName in settingNames) { var newName = settingNames[oldName]; var oldSetting = WebInspector.settings.createSetting(oldName, undefined).get(); var invert = "WebInspector.Drawer.showOnLoad" === oldName; var hidden = !!oldSetting !== invert; delete window.localStorage[oldName]; var showMode = hidden ? "OnlyMain" : "Both"; var newSetting = WebInspector.settings.createSetting(newName, null); var newValue = newSetting.get() || {}; newValue.vertical = newValue.vertical || {}; newValue.vertical.showMode = showMode; newValue.horizontal = newValue.horizontal || {}; newValue.horizontal.showMode = showMode; newSetting.set(newValue); } }, _updateVersionFrom6To7: function() { if (!window.localStorage) return; var settingNames = { "sourcesPanelNavigatorSplitViewState": "sourcesPanelNavigatorSplitViewState", "elementsPanelSplitViewState": "elementsPanelSplitViewState", "canvasProfileViewReplaySplitViewState": "canvasProfileViewReplaySplitViewState", "stylesPaneSplitViewState": "stylesPaneSplitViewState", "sourcesPanelDebuggerSidebarSplitViewState": "sourcesPanelDebuggerSidebarSplitViewState" }; for (var name in settingNames) { if (!(name in window.localStorage)) continue; var setting = WebInspector.settings.createSetting(name, undefined); var value = setting.get(); if (!value) continue; // Zero out saved percentage sizes, and they will be restored to defaults. if (value.vertical && value.vertical.size && value.vertical.size < 1) value.vertical.size = 0; if (value.horizontal && value.horizontal.size && value.horizontal.size < 1) value.horizontal.size = 0; setting.set(value); } }, _updateVersionFrom7To8: function() { var settingName = "deviceMetrics"; if (!window.localStorage || !(settingName in window.localStorage)) return; var setting = WebInspector.settings.createSetting(settingName, undefined); var value = setting.get(); if (!value) return; var components = value.split("x"); if (components.length >= 3) { var width = parseInt(components[0], 10); var height = parseInt(components[1], 10); var deviceScaleFactor = parseFloat(components[2]); if (deviceScaleFactor) { components[0] = "" + Math.round(width / deviceScaleFactor); components[1] = "" + Math.round(height / deviceScaleFactor); } } value = components.join("x"); setting.set(value); }, _updateVersionFrom8To9: function() { if (!window.localStorage) return; var settingNames = [ "skipStackFramesPattern", "workspaceFolderExcludePattern" ]; for (var i = 0; i < settingNames.length; ++i) { var settingName = settingNames[i]; if (!(settingName in window.localStorage)) continue; try { var value = JSON.parse(window.localStorage[settingName]); if (!value) continue; if (typeof value === "string") value = [value]; for (var j = 0; j < value.length; ++j) { if (typeof value[j] === "string") value[j] = { pattern: value[j] }; } window.localStorage[settingName] = JSON.stringify(value); } catch(e) { } } }, /** * @param {!WebInspector.Setting} breakpointsSetting * @param {number} maxBreakpointsCount */ _clearBreakpointsWhenTooMany: function(breakpointsSetting, maxBreakpointsCount) { // If there are too many breakpoints in a storage, it is likely due to a recent bug that caused // periodical breakpoints duplication leading to inspector slowness. if (breakpointsSetting.get().length > maxBreakpointsCount) breakpointsSetting.set([]); } } /** * @type {!WebInspector.Settings} */ WebInspector.settings; /** * @type {!WebInspector.ExperimentsSettings} */ WebInspector.experimentsSettings; // These methods are added for backwards compatibility with Devtools CodeSchool extension. // DO NOT REMOVE /** * @constructor */ WebInspector.PauseOnExceptionStateSetting = function() { WebInspector.settings.pauseOnExceptionEnabled.addChangeListener(this._enabledChanged, this); WebInspector.settings.pauseOnCaughtException.addChangeListener(this._pauseOnCaughtChanged, this); this._name = "pauseOnExceptionStateString"; this._eventSupport = new WebInspector.Object(); this._value = this._calculateValue(); } WebInspector.PauseOnExceptionStateSetting.prototype = { /** * @param {function(!WebInspector.Event)} listener * @param {!Object=} thisObject */ addChangeListener: function(listener, thisObject) { this._eventSupport.addEventListener(this._name, listener, thisObject); }, /** * @param {function(!WebInspector.Event)} listener * @param {!Object=} thisObject */ removeChangeListener: function(listener, thisObject) { this._eventSupport.removeEventListener(this._name, listener, thisObject); }, /** * @return {string} */ get: function() { return this._value; }, /** * @return {string} */ _calculateValue: function() { if (!WebInspector.settings.pauseOnExceptionEnabled.get()) return "none"; // The correct code here would be // return WebInspector.settings.pauseOnCaughtException.get() ? "all" : "uncaught"; // But the CodeSchool DevTools relies on the fact that we used to enable pausing on ALL extensions by default, so we trick it here. return "all"; }, _enabledChanged: function(event) { this._fireChangedIfNeeded(); }, _pauseOnCaughtChanged: function(event) { this._fireChangedIfNeeded(); }, _fireChangedIfNeeded: function() { var newValue = this._calculateValue(); if (newValue === this._value) return; this._value = newValue; this._eventSupport.dispatchEventToListeners(this._name, this._value); } }
tsiry95/openshift-strongloop-cartridge
strongloop/node_modules/strong-arc/devtools/frontend/common/Settings.js
JavaScript
mit
27,489
var assert = require('assert') var mongoose = require('mongoose') var request = require('request') var sinon = require('sinon') var util = require('util') module.exports = function (createFn, setup, dismantle) { var erm = require('../../lib/express-restify-mongoose') var db = require('./setup')() var testPort = 30023 var testUrl = 'http://localhost:' + testPort var invalidId = 'invalid-id' var randomId = mongoose.Types.ObjectId().toHexString() describe('preMiddleware/Create/Read/Update/Delete - null', function () { var app = createFn() var server var customer beforeEach(function (done) { setup(function (err) { if (err) { return done(err) } erm.serve(app, db.models.Customer, { preMiddleware: null, preCreate: null, preRead: null, preUpdate: null, preDelete: null, restify: app.isRestify }) db.models.Customer.create({ name: 'Bob' }).then(function (createdCustomer) { customer = createdCustomer server = app.listen(testPort, done) }, function (err) { done(err) }) }) }) afterEach(function (done) { dismantle(app, server, done) }) it('POST /Customers 201', function (done) { request.post({ url: util.format('%s/api/v1/Customers', testUrl), json: { name: 'John' } }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 201) done() }) }) it('GET /Customers 200', function (done) { request.get({ url: util.format('%s/api/v1/Customers', testUrl), json: true }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 200) done() }) }) it('POST /Customers/:id 200', function (done) { request.post({ url: util.format('%s/api/v1/Customers/%s', testUrl, customer._id), json: { name: 'Bobby' } }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 200) done() }) }) it('PUT /Customers/:id 200', function (done) { request.put({ url: util.format('%s/api/v1/Customers/%s', testUrl, customer._id), json: { name: 'Bobby' } }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 200) done() }) }) it('DELETE /Customers/:id 204', function (done) { request.del({ url: util.format('%s/api/v1/Customers/%s', testUrl, customer._id), json: true }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 204) done() }) }) }) describe('preMiddleware', function () { var app = createFn() var server var customer var options = { preMiddleware: sinon.spy(function (req, res, next) { next() }), restify: app.isRestify } beforeEach(function (done) { setup(function (err) { if (err) { return done(err) } erm.serve(app, db.models.Customer, options) db.models.Customer.create({ name: 'Bob' }).then(function (createdCustomer) { customer = createdCustomer server = app.listen(testPort, done) }, function (err) { done(err) }) }) }) afterEach(function (done) { options.preMiddleware.reset() dismantle(app, server, done) }) it('GET /Customers 200', function (done) { request.get({ url: util.format('%s/api/v1/Customers', testUrl), json: true }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 200) sinon.assert.calledOnce(options.preMiddleware) var args = options.preMiddleware.args[0] assert.equal(args.length, 3) assert.equal(typeof args[2], 'function') done() }) }) it('GET /Customers/:id 200', function (done) { request.get({ url: util.format('%s/api/v1/Customers', testUrl), json: true }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 200) sinon.assert.calledOnce(options.preMiddleware) var args = options.preMiddleware.args[0] assert.equal(args.length, 3) assert.equal(typeof args[2], 'function') done() }) }) it('POST /Customers 201', function (done) { request.post({ url: util.format('%s/api/v1/Customers', testUrl), json: { name: 'Pre' } }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 201) sinon.assert.calledOnce(options.preMiddleware) var args = options.preMiddleware.args[0] assert.equal(args.length, 3) assert.equal(typeof args[2], 'function') done() }) }) it('POST /Customers 400 - not called (missing content type)', function (done) { request.post({ url: util.format('%s/api/v1/Customers', testUrl) }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 400) sinon.assert.notCalled(options.preMiddleware) done() }) }) it('POST /Customers 400 - not called (invalid content type)', function (done) { request.post({ url: util.format('%s/api/v1/Customers', testUrl), formData: {} }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 400) sinon.assert.notCalled(options.preMiddleware) done() }) }) it('POST /Customers/:id 200', function (done) { request.post({ url: util.format('%s/api/v1/Customers/%s', testUrl, customer._id), json: {} }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 200) sinon.assert.calledOnce(options.preMiddleware) var args = options.preMiddleware.args[0] assert.equal(args.length, 3) assert.equal(typeof args[2], 'function') done() }) }) it('POST /Customers/:id 400 - not called (missing content type)', function (done) { request.post({ url: util.format('%s/api/v1/Customers/%s', testUrl, customer._id) }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 400) sinon.assert.notCalled(options.preMiddleware) done() }) }) it('POST /Customers/:id 400 - not called (invalid content type)', function (done) { request.post({ url: util.format('%s/api/v1/Customers/%s', testUrl, customer._id), formData: {} }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 400) sinon.assert.notCalled(options.preMiddleware) done() }) }) it('PUT /Customers/:id 200', function (done) { request.put({ url: util.format('%s/api/v1/Customers/%s', testUrl, customer._id), json: {} }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 200) sinon.assert.calledOnce(options.preMiddleware) var args = options.preMiddleware.args[0] assert.equal(args.length, 3) assert.equal(typeof args[2], 'function') done() }) }) it('PUT /Customers/:id 400 - not called (missing content type)', function (done) { request.put({ url: util.format('%s/api/v1/Customers/%s', testUrl, customer._id) }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 400) sinon.assert.notCalled(options.preMiddleware) done() }) }) it('PUT /Customers/:id 400 - not called (invalid content type)', function (done) { request.put({ url: util.format('%s/api/v1/Customers/%s', testUrl, customer._id), formData: {} }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 400) sinon.assert.notCalled(options.preMiddleware) done() }) }) it('DELETE /Customers 204', function (done) { request.del({ url: util.format('%s/api/v1/Customers', testUrl), json: true }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 204) sinon.assert.calledOnce(options.preMiddleware) var args = options.preMiddleware.args[0] assert.equal(args.length, 3) assert.equal(typeof args[2], 'function') done() }) }) it('DELETE /Customers/:id 204', function (done) { request.del({ url: util.format('%s/api/v1/Customers/%s', testUrl, customer._id), json: true }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 204) sinon.assert.calledOnce(options.preMiddleware) var args = options.preMiddleware.args[0] assert.equal(args.length, 3) assert.equal(typeof args[2], 'function') done() }) }) }) describe('preCreate', function () { var app = createFn() var server var options = { preCreate: sinon.spy(function (req, res, next) { next() }), restify: app.isRestify } beforeEach(function (done) { setup(function (err) { if (err) { return done(err) } erm.serve(app, db.models.Customer, options) server = app.listen(testPort, done) }) }) afterEach(function (done) { options.preCreate.reset() dismantle(app, server, done) }) it('POST /Customers 201', function (done) { request.post({ url: util.format('%s/api/v1/Customers', testUrl), json: { name: 'Bob' } }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 201) sinon.assert.calledOnce(options.preCreate) var args = options.preCreate.args[0] assert.equal(args.length, 3) assert.equal(args[0].erm.result.name, 'Bob') assert.equal(args[0].erm.statusCode, 201) assert.equal(typeof args[2], 'function') done() }) }) }) describe('preRead', function () { var app = createFn() var server var customer var options = { preRead: sinon.spy(function (req, res, next) { next() }), restify: app.isRestify } beforeEach(function (done) { setup(function (err) { if (err) { return done(err) } erm.serve(app, db.models.Customer, options) db.models.Customer.create({ name: 'Bob' }).then(function (createdCustomer) { customer = createdCustomer server = app.listen(testPort, done) }, function (err) { done(err) }) }) }) afterEach(function (done) { options.preRead.reset() dismantle(app, server, done) }) it('GET /Customers 200', function (done) { request.get({ url: util.format('%s/api/v1/Customers', testUrl), json: true }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 200) sinon.assert.calledOnce(options.preRead) var args = options.preRead.args[0] assert.equal(args.length, 3) assert.equal(args[0].erm.result[0].name, 'Bob') assert.equal(args[0].erm.statusCode, 200) assert.equal(typeof args[2], 'function') done() }) }) it('GET /Customers/count 200', function (done) { request.get({ url: util.format('%s/api/v1/Customers/count', testUrl), json: true }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 200) sinon.assert.calledOnce(options.preRead) var args = options.preRead.args[0] assert.equal(args.length, 3) assert.equal(args[0].erm.result.count, 1) assert.equal(args[0].erm.statusCode, 200) assert.equal(typeof args[2], 'function') done() }) }) it('GET /Customers/:id 200', function (done) { request.get({ url: util.format('%s/api/v1/Customers/%s', testUrl, customer._id), json: true }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 200) sinon.assert.calledOnce(options.preRead) var args = options.preRead.args[0] assert.equal(args.length, 3) assert.equal(args[0].erm.result.name, 'Bob') assert.equal(args[0].erm.statusCode, 200) assert.equal(typeof args[2], 'function') done() }) }) it('GET /Customers/:id/shallow 200', function (done) { request.get({ url: util.format('%s/api/v1/Customers/%s/shallow', testUrl, customer._id), json: true }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 200) sinon.assert.calledOnce(options.preRead) var args = options.preRead.args[0] assert.equal(args.length, 3) assert.equal(args[0].erm.result.name, 'Bob') assert.equal(args[0].erm.statusCode, 200) assert.equal(typeof args[2], 'function') done() }) }) }) describe('preUpdate', function () { var app = createFn() var server var customer var options = { preUpdate: sinon.spy(function (req, res, next) { next() }), restify: app.isRestify } beforeEach(function (done) { setup(function (err) { if (err) { return done(err) } erm.serve(app, db.models.Customer, options) db.models.Customer.create({ name: 'Bob' }).then(function (createdCustomer) { customer = createdCustomer server = app.listen(testPort, done) }, function (err) { done(err) }) }) }) afterEach(function (done) { options.preUpdate.reset() dismantle(app, server, done) }) it('POST /Customers/:id 200', function (done) { request.post({ url: util.format('%s/api/v1/Customers/%s', testUrl, customer._id), json: { name: 'Bobby' } }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 200) sinon.assert.calledOnce(options.preUpdate) var args = options.preUpdate.args[0] assert.equal(args.length, 3) assert.equal(args[0].erm.result.name, 'Bobby') assert.equal(args[0].erm.statusCode, 200) assert.equal(typeof args[2], 'function') done() }) }) it('POST /Customers/:id 400 - not called (missing content type)', function (done) { request.post({ url: util.format('%s/api/v1/Customers/%s', testUrl, customer._id) }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 400) sinon.assert.notCalled(options.preUpdate) done() }) }) it('POST /Customers/:id 400 - not called (invalid content type)', function (done) { request.post({ url: util.format('%s/api/v1/Customers/%s', testUrl, customer._id), formData: {} }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 400) sinon.assert.notCalled(options.preUpdate) done() }) }) it('PUT /Customers/:id 200', function (done) { request.put({ url: util.format('%s/api/v1/Customers/%s', testUrl, customer._id), json: { name: 'Bobby' } }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 200) sinon.assert.calledOnce(options.preUpdate) var args = options.preUpdate.args[0] assert.equal(args.length, 3) assert.equal(args[0].erm.result.name, 'Bobby') assert.equal(args[0].erm.statusCode, 200) assert.equal(typeof args[2], 'function') done() }) }) it('PUT /Customers/:id 400 - not called (missing content type)', function (done) { request.put({ url: util.format('%s/api/v1/Customers/%s', testUrl, customer._id) }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 400) sinon.assert.notCalled(options.preUpdate) done() }) }) it('PUT /Customers/:id 400 - not called (invalid content type)', function (done) { request.put({ url: util.format('%s/api/v1/Customers/%s', testUrl, customer._id), formData: {} }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 400) sinon.assert.notCalled(options.preUpdate) done() }) }) }) describe('preDelete', function () { var app = createFn() var server var customer var options = { preDelete: sinon.spy(function (req, res, next) { next() }), restify: app.isRestify } beforeEach(function (done) { setup(function (err) { if (err) { return done(err) } erm.serve(app, db.models.Customer, options) db.models.Customer.create({ name: 'Bob' }).then(function (createdCustomer) { customer = createdCustomer server = app.listen(testPort, done) }, function (err) { done(err) }) }) }) afterEach(function (done) { options.preDelete.reset() dismantle(app, server, done) }) it('DELETE /Customers 204', function (done) { request.del({ url: util.format('%s/api/v1/Customers', testUrl), json: true }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 204) sinon.assert.calledOnce(options.preDelete) var args = options.preDelete.args[0] assert.equal(args.length, 3) assert.equal(args[0].erm.result, undefined) assert.equal(args[0].erm.statusCode, 204) assert.equal(typeof args[2], 'function') done() }) }) it('DELETE /Customers/:id 204', function (done) { request.del({ url: util.format('%s/api/v1/Customers/%s', testUrl, customer._id), json: true }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 204) sinon.assert.calledOnce(options.preDelete) var args = options.preDelete.args[0] assert.equal(args.length, 3) assert.equal(args[0].erm.result, undefined) assert.equal(args[0].erm.statusCode, 204) assert.equal(typeof args[2], 'function') done() }) }) }) describe('postCreate/Read/Update/Delete - null', function () { var app = createFn() var server var customer beforeEach(function (done) { setup(function (err) { if (err) { return done(err) } erm.serve(app, db.models.Customer, { postCreate: null, postRead: null, postUpdate: null, postDelete: null, restify: app.isRestify }) db.models.Customer.create({ name: 'Bob' }).then(function (createdCustomer) { customer = createdCustomer server = app.listen(testPort, done) }, function (err) { done(err) }) }) }) afterEach(function (done) { dismantle(app, server, done) }) it('POST /Customers 201', function (done) { request.post({ url: util.format('%s/api/v1/Customers', testUrl), json: { name: 'John' } }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 201) done() }) }) it('GET /Customers 200', function (done) { request.get({ url: util.format('%s/api/v1/Customers', testUrl), json: true }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 200) done() }) }) it('POST /Customers/:id 200', function (done) { request.post({ url: util.format('%s/api/v1/Customers/%s', testUrl, customer._id), json: { name: 'Bobby' } }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 200) done() }) }) it('PUT /Customers/:id 200', function (done) { request.put({ url: util.format('%s/api/v1/Customers/%s', testUrl, customer._id), json: { name: 'Bobby' } }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 200) done() }) }) it('DELETE /Customers/:id 204', function (done) { request.del({ url: util.format('%s/api/v1/Customers/%s', testUrl, customer._id), json: true }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 204) done() }) }) }) describe('postCreate', function () { var app = createFn() var server var options = { postCreate: sinon.spy(function (req, res, next) { next() }), restify: app.isRestify } beforeEach(function (done) { setup(function (err) { if (err) { return done(err) } erm.serve(app, db.models.Customer, options) server = app.listen(testPort, done) }) }) afterEach(function (done) { options.postCreate.reset() dismantle(app, server, done) }) it('POST /Customers 201', function (done) { request.post({ url: util.format('%s/api/v1/Customers', testUrl), json: { name: 'Bob' } }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 201) sinon.assert.calledOnce(options.postCreate) var args = options.postCreate.args[0] assert.equal(args.length, 3) assert.equal(args[0].erm.result.name, 'Bob') assert.equal(args[0].erm.statusCode, 201) assert.equal(typeof args[2], 'function') done() }) }) it('POST /Customers 400 - missing required field', function (done) { request.post({ url: util.format('%s/api/v1/Customers', testUrl), json: { comment: 'Bar' } }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 400) sinon.assert.notCalled(options.postCreate) done() }) }) }) describe('postRead', function () { var app = createFn() var server var customer var options = { postRead: sinon.spy(function (req, res, next) { next() }), restify: app.isRestify } beforeEach(function (done) { setup(function (err) { if (err) { return done(err) } erm.serve(app, db.models.Customer, options) db.models.Customer.create({ name: 'Bob' }).then(function (createdCustomer) { customer = createdCustomer server = app.listen(testPort, done) }, function (err) { done(err) }) }) }) afterEach(function (done) { options.postRead.reset() dismantle(app, server, done) }) it('GET /Customers 200', function (done) { request.get({ url: util.format('%s/api/v1/Customers', testUrl), json: true }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 200) sinon.assert.calledOnce(options.postRead) var args = options.postRead.args[0] assert.equal(args.length, 3) assert.equal(args[0].erm.result[0].name, 'Bob') assert.equal(args[0].erm.statusCode, 200) assert.equal(typeof args[2], 'function') done() }) }) it('GET /Customers/count 200', function (done) { request.get({ url: util.format('%s/api/v1/Customers/count', testUrl), json: true }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 200) sinon.assert.calledOnce(options.postRead) var args = options.postRead.args[0] assert.equal(args.length, 3) assert.equal(args[0].erm.result.count, 1) assert.equal(args[0].erm.statusCode, 200) assert.equal(typeof args[2], 'function') done() }) }) it('GET /Customers/:id 200', function (done) { request.get({ url: util.format('%s/api/v1/Customers/%s', testUrl, customer._id), json: true }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 200) sinon.assert.calledOnce(options.postRead) var args = options.postRead.args[0] assert.equal(args.length, 3) assert.equal(args[0].erm.result.name, 'Bob') assert.equal(args[0].erm.statusCode, 200) assert.equal(typeof args[2], 'function') done() }) }) it('GET /Customers/:id 404', function (done) { request.get({ url: util.format('%s/api/v1/Customers/%s', testUrl, randomId), json: true }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 404) sinon.assert.notCalled(options.postRead) done() }) }) it('GET /Customers/:id 400', function (done) { request.get({ url: util.format('%s/api/v1/Customers/%s', testUrl, invalidId), json: true }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 400) sinon.assert.notCalled(options.postRead) done() }) }) it('GET /Customers/:id/shallow 200', function (done) { request.get({ url: util.format('%s/api/v1/Customers/%s/shallow', testUrl, customer._id), json: true }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 200) sinon.assert.calledOnce(options.postRead) var args = options.postRead.args[0] assert.equal(args.length, 3) assert.equal(args[0].erm.result.name, 'Bob') assert.equal(args[0].erm.statusCode, 200) assert.equal(typeof args[2], 'function') done() }) }) }) describe('postUpdate', function () { var app = createFn() var server var customer var options = { postUpdate: sinon.spy(function (req, res, next) { next() }), restify: app.isRestify } beforeEach(function (done) { setup(function (err) { if (err) { return done(err) } erm.serve(app, db.models.Customer, options) db.models.Customer.create({ name: 'Bob' }).then(function (createdCustomer) { customer = createdCustomer server = app.listen(testPort, done) }, function (err) { done(err) }) }) }) afterEach(function (done) { options.postUpdate.reset() dismantle(app, server, done) }) it('POST /Customers/:id 200', function (done) { request.post({ url: util.format('%s/api/v1/Customers/%s', testUrl, customer._id), json: { name: 'Bobby' } }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 200) sinon.assert.calledOnce(options.postUpdate) var args = options.postUpdate.args[0] assert.equal(args.length, 3) assert.equal(args[0].erm.result.name, 'Bobby') assert.equal(args[0].erm.statusCode, 200) assert.equal(typeof args[2], 'function') done() }) }) it('POST /Customers/:id 404 - random id', function (done) { request.post({ url: util.format('%s/api/v1/Customers/%s', testUrl, randomId), json: { name: 'Bobby' } }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 404) sinon.assert.notCalled(options.postUpdate) done() }) }) it('POST /Customers/:id 400 - invalid id', function (done) { request.post({ url: util.format('%s/api/v1/Customers/%s', testUrl, invalidId), json: { name: 'Bobby' } }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 400) sinon.assert.notCalled(options.postUpdate) done() }) }) it('POST /Customers/:id 400 - not called (missing content type)', function (done) { request.post({ url: util.format('%s/api/v1/Customers/%s', testUrl, customer._id) }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 400) sinon.assert.notCalled(options.postUpdate) done() }) }) it('POST /Customers/:id 400 - not called (invalid content type)', function (done) { request.post({ url: util.format('%s/api/v1/Customers/%s', testUrl, customer._id), formData: {} }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 400) sinon.assert.notCalled(options.postUpdate) done() }) }) it('PUT /Customers/:id 200', function (done) { request.put({ url: util.format('%s/api/v1/Customers/%s', testUrl, customer._id), json: { name: 'Bobby' } }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 200) sinon.assert.calledOnce(options.postUpdate) var args = options.postUpdate.args[0] assert.equal(args.length, 3) assert.equal(args[0].erm.result.name, 'Bobby') assert.equal(args[0].erm.statusCode, 200) assert.equal(typeof args[2], 'function') done() }) }) it('PUT /Customers/:id 404 - random id', function (done) { request.put({ url: util.format('%s/api/v1/Customers/%s', testUrl, randomId), json: { name: 'Bobby' } }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 404) sinon.assert.notCalled(options.postUpdate) done() }) }) it('PUT /Customers/:id 400 - invalid id', function (done) { request.put({ url: util.format('%s/api/v1/Customers/%s', testUrl, invalidId), json: { name: 'Bobby' } }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 400) sinon.assert.notCalled(options.postUpdate) done() }) }) it('PUT /Customers/:id 400 - not called (missing content type)', function (done) { request.put({ url: util.format('%s/api/v1/Customers/%s', testUrl, customer._id) }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 400) sinon.assert.notCalled(options.postUpdate) done() }) }) it('PUT /Customers/:id 400 - not called (invalid content type)', function (done) { request.put({ url: util.format('%s/api/v1/Customers/%s', testUrl, customer._id), formData: {} }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 400) sinon.assert.notCalled(options.postUpdate) done() }) }) }) describe('postDelete', function () { var app = createFn() var server var customer var options = { postDelete: sinon.spy(function (req, res, next) { next() }), restify: app.isRestify } beforeEach(function (done) { setup(function (err) { if (err) { return done(err) } erm.serve(app, db.models.Customer, options) db.models.Customer.create({ name: 'Bob' }).then(function (createdCustomer) { customer = createdCustomer server = app.listen(testPort, done) }, function (err) { done(err) }) }) }) afterEach(function (done) { options.postDelete.reset() dismantle(app, server, done) }) it('DELETE /Customers 204', function (done) { request.del({ url: util.format('%s/api/v1/Customers', testUrl), json: true }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 204) sinon.assert.calledOnce(options.postDelete) var args = options.postDelete.args[0] assert.equal(args.length, 3) assert.equal(args[0].erm.result, undefined) assert.equal(args[0].erm.statusCode, 204) assert.equal(typeof args[2], 'function') done() }) }) it('DELETE /Customers/:id 204', function (done) { request.del({ url: util.format('%s/api/v1/Customers/%s', testUrl, customer._id), json: true }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 204) sinon.assert.calledOnce(options.postDelete) var args = options.postDelete.args[0] assert.equal(args.length, 3) assert.equal(args[0].erm.result, undefined) assert.equal(args[0].erm.statusCode, 204) assert.equal(typeof args[2], 'function') done() }) }) it('DELETE /Customers/:id 404', function (done) { request.del({ url: util.format('%s/api/v1/Customers/%s', testUrl, randomId), json: true }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 404) sinon.assert.notCalled(options.postDelete) done() }) }) it('DELETE /Customers/:id 400', function (done) { request.del({ url: util.format('%s/api/v1/Customers/%s', testUrl, invalidId), json: true }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 400) sinon.assert.notCalled(options.postDelete) done() }) }) }) describe('postCreate yields an error', function () { var app = createFn() var server var options = { postCreate: sinon.spy(function (req, res, next) { var err = new Error('Something went wrong') err.statusCode = 400 next(err) }), postProcess: sinon.spy(), restify: app.isRestify } beforeEach(function (done) { setup(function (err) { if (err) { return done(err) } erm.serve(app, db.models.Customer, options) server = app.listen(testPort, done) }) }) afterEach(function (done) { options.postCreate.reset() dismantle(app, server, done) }) it('POST /Customers 201', function (done) { request.post({ url: util.format('%s/api/v1/Customers', testUrl), json: { name: 'Bob' } }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 400) sinon.assert.calledOnce(options.postCreate) var args = options.postCreate.args[0] assert.equal(args.length, 3) assert.equal(args[0].erm.result.name, 'Bob') assert.equal(args[0].erm.statusCode, 201) assert.equal(typeof args[2], 'function') sinon.assert.notCalled(options.postProcess) done() }) }) }) describe('postProcess', function () { var app = createFn() var server var options = { postProcess: sinon.spy(function (req, res, next) { next() }), restify: app.isRestify } beforeEach(function (done) { setup(function (err) { if (err) { return done(err) } erm.serve(app, db.models.Customer, options) server = app.listen(testPort, done) }) }) afterEach(function (done) { options.postProcess.reset() dismantle(app, server, done) }) it('GET /Customers 200', function (done) { request.get({ url: util.format('%s/api/v1/Customers', testUrl), json: true }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 200) sinon.assert.calledOnce(options.postProcess) var args = options.postProcess.args[0] assert.equal(args.length, 3) assert.deepEqual(args[0].erm.result, []) assert.equal(args[0].erm.statusCode, 200) assert.equal(typeof args[2], 'function') done() }) }) }) }
Ensequence/express-restify-mongoose
test/integration/middleware.js
JavaScript
mit
36,848
<?php return array( 'AD' => 'Andorra', 'AE' => 'Sameindu Emirríkini', 'AF' => 'Afganistan', 'AG' => 'Antigua og Barbuda', 'AI' => 'Anguilla', 'AL' => 'Albania', 'AM' => 'Armenia', 'AN' => 'Niðurlendsku Antilloyggjar', 'AO' => 'Angola', 'AQ' => 'Antarktis', 'AR' => 'Argentina', 'AS' => 'Amerikanska Sámoa', 'AT' => 'Eysturríki', 'AU' => 'Avstralia', 'AW' => 'Aruba', 'AX' => 'Áland', 'AZ' => 'Aserbajdsjan', 'BA' => 'Bosnia-Hersegovina', 'BB' => 'Barbados', 'BD' => 'Bangladesj', 'BE' => 'Belgia', 'BF' => 'Burkina Faso', 'BG' => 'Bulgaria', 'BH' => 'Bahrain', 'BI' => 'Burundi', 'BJ' => 'Benin', 'BL' => 'Saint Barthélemy', 'BM' => 'Bermuda', 'BN' => 'Brunei', 'BO' => 'Bolivia', 'BR' => 'Brasilia', 'BS' => 'Bahamas', 'BT' => 'Butan', 'BV' => 'Bouvetoy', 'BW' => 'Botsvana', 'BY' => 'Hvítarussland', 'BZ' => 'Belis', 'CA' => 'Kanada', 'CC' => 'Kokosoyggjar', 'CD' => 'Kongo-Kinshasa', 'CF' => 'Miðafrikalýðveldið', 'CG' => 'Kongo', 'CH' => 'Sveis', 'CI' => 'Fílabeinsstrondin', 'CK' => 'Cooksoyggjar', 'CL' => 'Kili', 'CM' => 'Kamerun', 'CN' => 'Kina', 'CO' => 'Kolombia', 'CR' => 'Kosta Rika', 'CU' => 'Kuba', 'CV' => 'Grønhøvdaoyggjarnar', 'CX' => 'Jólaoyggjin', 'CY' => 'Kýpros', 'CZ' => 'Kekkia', 'DE' => 'Týskland', 'DJ' => 'Djibouti', 'DK' => 'Danmørk', 'DM' => 'Dominika', 'DO' => 'Domingo lýðveldið', 'DZ' => 'Algeria', 'EC' => 'Ekvador', 'EE' => 'Estland', 'EG' => 'Egyptaland', 'EH' => 'Vestursahara', 'ER' => 'Eritrea', 'ES' => 'Spania', 'ET' => 'Etiopia', 'FI' => 'Finnland', 'FJ' => 'Fiji', 'FK' => 'Falklandsoyggjar', 'FM' => 'Mikronesia', 'FO' => 'Føroyar', 'FR' => 'Frakland', 'GA' => 'Gabon', 'GB' => 'Stóra Bretland', 'GD' => 'Grenada', 'GE' => 'Georgia', 'GF' => 'Fransk Gujana', 'GG' => 'Guernsey', 'GH' => 'Ghana', 'GI' => 'Gibraltar', 'GL' => 'Grønland', 'GM' => 'Gambia', 'GN' => 'Guinea', 'GP' => 'Guadeloupe', 'GQ' => 'Ekvator Guinea', 'GR' => 'Grikkaland', 'GS' => 'Suðurgeorgia', 'GT' => 'Guatemala', 'GU' => 'Guam', 'GW' => 'Guinea Bissau', 'GY' => 'Gujana', 'HK' => 'Hongkong', 'HM' => 'Heard- og McDonald-oyggjar', 'HN' => 'Honduras', 'HR' => 'Kroatia', 'HT' => 'Haiti', 'HU' => 'Ungarn', 'ID' => 'Indonesia', 'IE' => 'Írland', 'IL' => 'Ísrael', 'IM' => 'Mann', 'IN' => 'India', 'IO' => 'Bretsku Indiahavsoyggjar', 'IQ' => 'Irak', 'IR' => 'Iran', 'IS' => 'Ísland', 'IT' => 'Italia', 'JE' => 'Jersey', 'JM' => 'Jameika', 'JO' => 'Jordan', 'JP' => 'Japan', 'KE' => 'Kenja', 'KG' => 'Kirgisia', 'KH' => 'Kambodja', 'KI' => 'Kiribati', 'KM' => 'Komorooyggjarnar', 'KN' => 'Saint Kitts og Nevis', 'KP' => 'Norður-Korea', 'KR' => 'Suður-Korea', 'KW' => 'Kuvait', 'KY' => 'Caymanoyggjar', 'KZ' => 'Kasakstan', 'LA' => 'Laos', 'LB' => 'Libanon', 'LC' => 'Saint Lusia', 'LI' => 'Liktenstein', 'LK' => 'Sri Lanka', 'LR' => 'Liberia', 'LS' => 'Lesoto', 'LT' => 'Litava', 'LU' => 'Luksemborg', 'LV' => 'Lettland', 'LY' => 'Libya', 'MA' => 'Marokko', 'MC' => 'Monako', 'MD' => 'Moldova', 'ME' => 'Montenegro', 'MF' => 'Saint Martin', 'MG' => 'Madagaskar', 'MH' => 'Marshalloyggjarnar', 'MK' => 'Makedónia', 'ML' => 'Mali', 'MM' => 'Burma', 'MN' => 'Mongolia', 'MO' => 'Makao', 'MP' => 'Norðurmarianoyggjar', 'MQ' => 'Martinique', 'MR' => 'Móritania', 'MS' => 'Montserrat', 'MT' => 'Malta', 'MU' => 'Móritius', 'MV' => 'Maldivuoyggjarnar', 'MW' => 'Malavi', 'MX' => 'Meksiko', 'MY' => 'Maleisia', 'MZ' => 'Mosambik', 'NA' => 'Namibia', 'NC' => 'Ný-Kaledonia', 'NE' => 'Niger', 'NF' => 'Norfolkoy', 'NG' => 'Nigeria', 'NI' => 'Nikaragua', 'NL' => 'Niðurlond', 'NO' => 'Noreg', 'NP' => 'Nepal', 'NR' => 'Nauru', 'NU' => 'Niue', 'NZ' => 'Ný Sæland', 'OM' => 'Oman', 'PA' => 'Panama', 'PE' => 'Perú', 'PF' => 'Franska Polynesia', 'PG' => 'Papua Nýguinea', 'PH' => 'Filipsoyggjar', 'PK' => 'Pakistan', 'PL' => 'Pólland', 'PM' => 'Saint-Pierre og Miquelon', 'PN' => 'Pitcairn', 'PR' => 'Puerto Rico', 'PS' => 'Palestinskt territorium', 'PT' => 'Portugal', 'PW' => 'Palau', 'PY' => 'Paraguei', 'QA' => 'Katar', 'RE' => 'Réunion', 'RO' => 'Rumenia', 'RS' => 'Serbia', 'RU' => 'Russland', 'RW' => 'Ruanda', 'SA' => 'Saudi-Arábia', 'SB' => 'Sálomonoyggjarnar', 'SC' => 'Seyskelloyggjarnar', 'SD' => 'Sudan', 'SE' => 'Svøríki', 'SG' => 'Singapor', 'SH' => 'Saint Helena', 'SI' => 'Slovenia', 'SJ' => 'Svalbard og Jan Mayen', 'SK' => 'Slovakia', 'SL' => 'Sierra Leone', 'SM' => 'San Marino', 'SN' => 'Senegal', 'SO' => 'Somalia', 'SR' => 'Surinam', 'ST' => 'Sao Tome og Prinsipi', 'SV' => 'El Salvador', 'SY' => 'Syria', 'SZ' => 'Svasiland', 'TC' => 'Turks- og Caicosoyggjar', 'TD' => 'Kjad', 'TG' => 'Togo', 'TH' => 'Teiland', 'TJ' => 'Tadsjikistan', 'TK' => 'Tokelau', 'TL' => 'Eystur Timor', 'TM' => 'Turkmenistan', 'TN' => 'Tunesia', 'TO' => 'Tonga', 'TR' => 'Turkaland', 'TT' => 'Trinidad og Tobago', 'TV' => 'Tuvalu', 'TW' => 'Teivan', 'TZ' => 'Tansania', 'UA' => 'Ukreina', 'UG' => 'Uganda', 'US' => 'Sambandsríki Amerika', 'UY' => 'Uruguei', 'UZ' => 'Usbekistan', 'VA' => 'Vatikan', 'VC' => 'Saint Vinsent og Grenadinoyggjar', 'VE' => 'Venesuela', 'VG' => 'Stóra Bretlands Jómfrúoyggjar', 'VI' => 'Sambandsríki Amerikas Jómfrúoyggjar', 'VN' => 'Vietnam', 'VU' => 'Vanuatu', 'WF' => 'Wallis og Futuna', 'WS' => 'Sámoa', 'YE' => 'Jemen', 'YT' => 'Mayotte', 'ZA' => 'Suðurafrika', 'ZM' => 'Sambia', 'ZW' => 'Simbabvi' );
forxer/okatea
Okatea/Tao/L10n/country-list/fo_FO/country.php
PHP
mit
5,531
import {Component, View, FORM_DIRECTIVES, EventEmitter, NgFor} from 'angular2/angular2'; @Component({ selector: 'font-family-component', inputs: ['fontFamily'], outputs: ['fontFamilyChange'] }) @View({ template: ` <select class="form-control" [ng-model]="fontFamily" (input)="fontFamilyChange.next($event.target.value)"> <option *ng-for="#font of fonts">{{font}}</option> </select> `, directives: [FORM_DIRECTIVES, NgFor] }) export class FontFamilyComponent { fontFamily: string; fontFamilyChange = new EventEmitter(); fonts: string[]; constructor() { this.fonts = ['Helvetica', 'Ariel', 'fantasy', 'cursive']; } }
yanivefraim/theme-creator-demo-angular-2
app/components/font-family-component/font-family-component.ts
TypeScript
mit
656
'use strict'; var _ = require('lodash'); var util = require('util'); var property = require('corazon/property'); var inflection = require('../util/inflection'); var Mixin = require('corazon/mixin'); /** * A helper function for creating config properties that either reads from a * cached value or calls a function to get a value to cache. * * @function BelongsTo~config * @param {String} name The name of the option/property. * @param {Function} calculate A function to calculate the default value. * @return {Property} A config property */ var config = function(name, calculate) { var attr = '$' + name; return property(function() { if (this[attr] === undefined) { this[attr] = calculate.call(this); } return this[attr]; }); }; /** * BelongsTo mixin for options/configuration. * * This mixin separates some of the logic of {@link BelongsTo} and is only * intended to be mixed into that one class. */ module.exports = Mixin.create(/** @lends BelongsTo# */ { /** * Override of {@link BaseRelation#configure}. * * @protected * @method * @see {@link BaseRelation#configure} */ configure: function() { /* jshint expr: true */ // configure each of the properties that are calculated on a delay by // simply invoking the property once. configure the inverse first as some // other calculations may rely on it. this.inverse; this.primaryKey; this.primaryKeyAttr; this.foreignKey; this.foreignKeyAttr; this.inverseRelation(); // ensure the inverse is configured this._super(); }, /** * Get the inverse of this relation. Access the option that was given or * calculate the value based on the current model class name. * * The resulting value will be locked in after the first call to avoid any * possible changes due to changing state outside of the relation. * * @private * @type {String} */ inverse: config('inverse', function() { var inverse = this._options.inverse || this._inverse(); // add the inverse if it's missing if (inverse && !this._relatedModel[inverse + 'Relation']) { var db = this._modelClass.db; var attr = db.hasMany(this._modelClass, { inverse: this._name, primaryKey: this._options.primaryKey, foreignKey: this._options.foreignKey, implicit: true, }); this._relatedModel.reopen(_.object([[inverse, attr]])); } return inverse; }), /** * Calculate the default value of the inverse for when an option was not * provided for this relation. * * Mixins installed after this one can override {@link HasMany#_inverse} if * they need to change the default. * * @method * @private * @return {String} The default value. */ _inverse: function() { var name = _.camelCase(this._modelClass.__name__); var singularized = inflection.singularize(name); var pluralized = inflection.pluralize(name); var related = this._relatedModel; var inverse; if (related[pluralized + 'Relation']) { inverse = pluralized; } else if (related[singularized + 'Relation']) { inverse = singularized; } else { // find a relation w/ an inverse that points back to this one var match = _.find(related.relations, function(relation) { return relation._options.inverse === this._name; }.bind(this)); inverse = _.get(match, '_name'); } if (!inverse) { inverse = pluralized; } return inverse; }, /** * Get the primary key for this relation. This will access the primary key * value specified on the inverse relation, if an inverse relation exists. If * the inverse exists and the user also provided the `primaryKey` option when * creating this relation, it will ensure that the given value matches the * value from the inverse. * * If an inverse does not exist, this will return the value given for the * `primaryKey` option or `pk` as a default. * * The resulting value will be locked in after the first call to avoid any * possible changes due to changing state outside of the relation. * * @private * @type {String} */ primaryKey: config('primaryKey', function() { var primaryKey = this._options.primaryKey; var inverseRelation = this.inverseRelation(); var inversePrimaryKey = inverseRelation && inverseRelation.primaryKey; if (inverseRelation && primaryKey && primaryKey !== inversePrimaryKey) { throw new Error(util.format('%s.%s primary key must equal %j ' + 'specified by %s.%s relation', this._modelClass.__identity__.__name__, this._name, inverseRelation.primaryKey, inverseRelation._modelClass.__identity__.__name__, inverseRelation._name)); } if (inverseRelation) { primaryKey = inverseRelation.primaryKey; } if (!primaryKey) { // default in case the inverse does not exist primaryKey = 'pk'; } return primaryKey; }), /** * Get the primary key attribute value for this relation. This looks up the * attribute value on the related class. If that value was not defied, it * falls back to the underscored version of {@link BelongsTo#primaryKey}. * * @private * @type {String} */ primaryKeyAttr: config('primaryKeyAttr', function() { // since the related model may not have defined the attribute being used as // the primary key attribute, we need a fallback here, so we snake case the // property name. var relatedClass = this._relatedModel.__class__; var prototype = relatedClass.prototype; var primaryKeyAttr = prototype[this.primaryKey + 'Attr']; return primaryKeyAttr || _.snakeCase(this.primaryKey); }), /** * Get the foreign key for this relation. Access the option that was given or * calculate the value based on the relation name. * * @private * @type {String} */ foreignKey: config('foreignKey', function() { return this._options.foreignKey || _.camelCase(this._name + 'Id'); }), /** * Get the foreign key attribute value for this relation. This looks up the * attribute value on the model class. * * @private * @type {String} */ foreignKeyAttr: config('foreignKeyAttr', function() { // we always try to find the foreign key attribute by looking at the model // class. it's possible that it won't be there, though. belongs-to // relationships that were created implicitly from a has-many won't add the // attribute, so we need to fall back to snake casing the foreign key. var modelClass = this._modelClass; var prototype = modelClass.__class__.prototype; var foreignKeyAttr = prototype[this.foreignKey + 'Attr']; if (!foreignKeyAttr) { foreignKeyAttr = _.snakeCase(this.foreignKey); } return foreignKeyAttr; }), });
tgriesser/azul
lib/relations/belongs_to_config.js
JavaScript
mit
6,858
class Myaccount::BaseController < ApplicationController before_filter :require_user protected def ssl_required? ssl_supported? end end
drhenner/elzzad
app/controllers/myaccount/base_controller.rb
Ruby
mit
149
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class AddIndexesToPosts extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('posts', function (Blueprint $table) { $table->index('created_at'); $table->index(['status', 'deleted_at']); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('posts', function (Blueprint $table) { $table->dropIndex('posts_status_deleted_at_index'); $table->dropIndex('posts_created_at_index'); }); } }
DoSomething/rogue
database/migrations/2017_12_08_203149_add_indexes_to_posts.php
PHP
mit
763
package types import ( "reflect" "testing" "time" ) type structTest struct { Int int IntArray []int Float float32 FloatArray []float64 String string StringArray []string Blob []byte BlobArray [][]byte Time time.Time } var marshallTests = []struct { item structTest value AttributeValue }{ { structTest{ Int: 8, IntArray: []int{8, 12}, }, AttributeValue{ "Int": { "N": "8", }, "IntArray": { "NS": []string{"8", "12"}, }, }, }, { structTest{ Float: 8.12, FloatArray: []float64{8.12, 12.8}, }, AttributeValue{ "Float": { "N": "8.12", }, "FloatArray": { "NS": []string{"8.12", "12.8"}, }, }, }, { structTest{ String: "abc", StringArray: []string{"a", "b"}, }, AttributeValue{ "String": { "S": "abc", }, "StringArray": { "SS": []string{"a", "b"}, }, }, }, { structTest{ Blob: []byte{'a', 'b', 'c'}, BlobArray: [][]byte{ {'a', 'b', 'c'}, {'d', 'e', 'f'}, }, }, AttributeValue{ "Blob": { "B": "abc", }, "BlobArray": { "BS": []string{"abc", "def"}, }, }, }, { structTest{ Time: time.Date(2013, 12, 12, 17, 55, 30, 0, time.UTC), }, AttributeValue{ "Time": { "S": "2013-12-12T17:55:30Z", }, }, }, } func TestMarshall(t *testing.T) { for _, e := range marshallTests { v, err := Marshal(e.item, false) if err != nil { t.Fatal(err) } if !reflect.DeepEqual(v, e.value) { t.Errorf("got %v wants %v", v, e.value) } } } func TestUnmarshall(t *testing.T) { for _, e := range marshallTests { var item structTest err := Unmarshal(e.value, &item) if err != nil { t.Fatal(err) } if !reflect.DeepEqual(item, e.item) { t.Errorf("got %v wants %v", item, e.item) } } }
cyberdelia/dynamodb
types/attributes_test.go
GO
mit
1,829
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.datamigration.v2017_11_15_preview.implementation; import java.util.Arrays; import java.util.Iterator; class IdParsingUtils { public static String getValueFromIdByName(String id, String name) { if (id == null) { return null; } Iterable<String> iterable = Arrays.asList(id.split("/")); Iterator<String> itr = iterable.iterator(); while (itr.hasNext()) { String part = itr.next(); if (part != null && part.trim() != "") { if (part.equalsIgnoreCase(name)) { if (itr.hasNext()) { return itr.next(); } else { return null; } } } } return null; } public static String getValueFromIdByPosition(String id, int pos) { if (id == null) { return null; } Iterable<String> iterable = Arrays.asList(id.split("/")); Iterator <String> itr = iterable.iterator(); int index = 0; while (itr.hasNext()) { String part = itr.next(); if (part != null && part.trim() != "") { if (index == pos) { if (itr.hasNext()) { return itr.next(); } else { return null; } } } index++; } return null; } }
selvasingh/azure-sdk-for-java
sdk/datamigration/mgmt-v2017_11_15_preview/src/main/java/com/microsoft/azure/management/datamigration/v2017_11_15_preview/implementation/IdParsingUtils.java
Java
mit
1,762
using System.Collections.Generic; using System.IO; using GitVersion; using GitVersion.BuildAgents; using GitVersionCore.Tests.Helpers; using Microsoft.Extensions.DependencyInjection; using NUnit.Framework; using Shouldly; using Environment = System.Environment; namespace GitVersionCore.Tests.BuildAgents { [TestFixture] public class GitHubActionsTests : TestBase { private IEnvironment environment; private GitHubActions buildServer; private string githubSetEnvironmentTempFilePath; [SetUp] public void SetUp() { var sp = ConfigureServices(services => { services.AddSingleton<GitHubActions>(); }); environment = sp.GetService<IEnvironment>(); buildServer = sp.GetService<GitHubActions>(); environment.SetEnvironmentVariable(GitHubActions.EnvironmentVariableName, "true"); githubSetEnvironmentTempFilePath = Path.GetTempFileName(); environment.SetEnvironmentVariable(GitHubActions.GitHubSetEnvTempFileEnvironmentVariableName, githubSetEnvironmentTempFilePath); } [TearDown] public void TearDown() { environment.SetEnvironmentVariable(GitHubActions.EnvironmentVariableName, null); environment.SetEnvironmentVariable(GitHubActions.GitHubSetEnvTempFileEnvironmentVariableName, null); if (githubSetEnvironmentTempFilePath != null && File.Exists(githubSetEnvironmentTempFilePath)) { File.Delete(githubSetEnvironmentTempFilePath); githubSetEnvironmentTempFilePath = null; } } [Test] public void CanApplyToCurrentContextShouldBeTrueWhenEnvironmentVariableIsSet() { // Act var result = buildServer.CanApplyToCurrentContext(); // Assert result.ShouldBeTrue(); } [Test] public void CanApplyToCurrentContextShouldBeFalseWhenEnvironmentVariableIsNotSet() { // Arrange environment.SetEnvironmentVariable(GitHubActions.EnvironmentVariableName, ""); // Act var result = buildServer.CanApplyToCurrentContext(); // Assert result.ShouldBeFalse(); } [Test] public void GetCurrentBranchShouldHandleBranches() { // Arrange environment.SetEnvironmentVariable("GITHUB_REF", "refs/heads/master"); // Act var result = buildServer.GetCurrentBranch(false); // Assert result.ShouldBe("refs/heads/master"); } [Test] public void GetCurrentBranchShouldHandleTags() { // Arrange environment.SetEnvironmentVariable("GITHUB_REF", "refs/tags/1.0.0"); // Act var result = buildServer.GetCurrentBranch(false); // Assert result.ShouldBe("refs/tags/1.0.0"); } [Test] public void GetCurrentBranchShouldHandlePullRequests() { // Arrange environment.SetEnvironmentVariable("GITHUB_REF", "refs/pull/1/merge"); // Act var result = buildServer.GetCurrentBranch(false); // Assert result.ShouldBe("refs/pull/1/merge"); } [Test] public void GetSetParameterMessage() { // Assert environment.GetEnvironmentVariable("GitVersion_Something").ShouldBeNullOrWhiteSpace(); // Act var result = buildServer.GenerateSetParameterMessage("GitVersion_Something", "1.0.0"); // Assert result.ShouldContain(s => true, 0); } [Test] public void SkipEmptySetParameterMessage() { // Act var result = buildServer.GenerateSetParameterMessage("Hello", string.Empty); // Assert result.ShouldBeEquivalentTo(new string[0]); } [Test] public void ShouldWriteIntegration() { // Arrange var vars = new TestableVersionVariables("1.0.0"); var list = new List<string>(); // Assert environment.GetEnvironmentVariable("GitVersion_Major").ShouldBeNullOrWhiteSpace(); // Act buildServer.WriteIntegration(s => { list.Add(s); }, vars); // Assert var expected = new List<string> { "Executing GenerateSetVersionMessage for 'GitHubActions'.", "", "Executing GenerateBuildLogOutput for 'GitHubActions'.", "Writing version variables to $GITHUB_ENV file for 'GitHubActions'." }; string.Join(Environment.NewLine, list) .ShouldBe(string.Join(Environment.NewLine, expected)); var expectedFileContents = new List<string> { "GitVersion_Major=1.0.0" }; var actualFileContents = File.ReadAllLines(githubSetEnvironmentTempFilePath); actualFileContents.ShouldBe(expectedFileContents); } [Test] public void ShouldNotWriteIntegration() { // Arrange var vars = new TestableVersionVariables("1.0.0"); var list = new List<string>(); // Assert environment.GetEnvironmentVariable("GitVersion_Major").ShouldBeNullOrWhiteSpace(); // Act buildServer.WriteIntegration(s => { list.Add(s); }, vars, false); list.ShouldNotContain(x => x.StartsWith("Executing GenerateSetVersionMessage for ")); } [Test] public void GetEmptyGenerateSetVersionMessage() { // Arrange var vars = new TestableVersionVariables("1.0.0"); // Act var message = buildServer.GenerateSetVersionMessage(vars); // Assert message.ShouldBeEmpty(); } } }
ParticularLabs/GitVersion
src/GitVersionCore.Tests/BuildAgents/GitHubActionsTests.cs
C#
mit
6,097
/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-present Torus Knot Software Ltd Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------------- */ #include "OgreVulkanQueue.h" #include "OgreVulkanDevice.h" #include "OgreVulkanMappings.h" #include "OgreVulkanRenderSystem.h" #include "OgreVulkanTextureGpu.h" #include "OgreVulkanWindow.h" #include "OgreException.h" #include "OgrePixelFormat.h" #include "OgreStringConverter.h" #include "OgreVulkanUtils.h" #include "OgreVulkanDescriptorPool.h" #define TODO_findRealPresentQueue #define TODO_we_assume_has_stencil namespace Ogre { // Mask away read flags from srcAccessMask static const uint32 c_srcValidAccessFlags = 0xFFFFFFFF ^ ( VK_ACCESS_INDIRECT_COMMAND_READ_BIT | VK_ACCESS_INDEX_READ_BIT | VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT | VK_ACCESS_UNIFORM_READ_BIT | VK_ACCESS_INPUT_ATTACHMENT_READ_BIT | VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_HOST_READ_BIT | VK_ACCESS_MEMORY_READ_BIT ); VulkanQueue::VulkanQueue() : mDevice( 0 ), mFamily( NumQueueFamilies ), mFamilyIdx( 0u ), mQueueIdx( 0u ), mQueue( 0 ), mCurrentCmdBuffer( 0 ), mOwnerDevice( 0 ), mNumFramesInFlight( 3 ), mCurrentFrameIdx( 0 ), mRenderSystem( 0 ), mCurrentFence( 0 ), mEncoderState( EncoderClosed ), mCopyEndReadSrcBufferFlags( 0 ), mCopyEndReadDstBufferFlags( 0 ), mCopyEndReadDstTextureFlags( 0 ), mCopyStartWriteSrcBufferFlags( 0 ) { } //------------------------------------------------------------------------- VulkanQueue::~VulkanQueue() { destroy(); } //------------------------------------------------------------------------- void VulkanQueue::setQueueData( VulkanDevice *owner, QueueFamily family, uint32 familyIdx, uint32 queueIdx ) { mOwnerDevice = owner; mFamily = family; mFamilyIdx = familyIdx; mQueueIdx = queueIdx; } //------------------------------------------------------------------------- void VulkanQueue::init( VkDevice device, VkQueue queue, VulkanRenderSystem *renderSystem ) { mDevice = device; mQueue = queue; mRenderSystem = renderSystem; mPerFrameData.resize( mNumFramesInFlight ); VkCommandPoolCreateInfo cmdPoolCreateInfo = {VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO}; cmdPoolCreateInfo.flags = VK_COMMAND_POOL_CREATE_TRANSIENT_BIT; cmdPoolCreateInfo.queueFamilyIndex = mFamilyIdx; VkCommandBufferAllocateInfo allocateInfo = {VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO}; allocateInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; allocateInfo.commandBufferCount = 1u; VkFenceCreateInfo fenceCi = {VK_STRUCTURE_TYPE_FENCE_CREATE_INFO}; fenceCi.flags = VK_FENCE_CREATE_SIGNALED_BIT; for (auto& fd : mPerFrameData) { OGRE_VK_CHECK(vkCreateCommandPool(mDevice, &cmdPoolCreateInfo, 0, &fd.mCommandPool)); allocateInfo.commandPool = fd.mCommandPool; OGRE_VK_CHECK(vkAllocateCommandBuffers( mDevice, &allocateInfo, &fd.mCommandBuffer )); OGRE_VK_CHECK(vkCreateFence(mDevice, &fenceCi, 0, &fd.mProtectingFence)); } newCommandBuffer(); } void VulkanQueue::destroy() { if( mDevice ) { vkDeviceWaitIdle( mDevice ); for(size_t i = 0; i < mPerFrameData.size(); ++i) { _waitOnFrame(i); } for(auto& fd : mPerFrameData) { vkDestroyFence( mDevice, fd.mProtectingFence, 0 ); vkDestroyCommandPool( mDevice, fd.mCommandPool, 0 ); } mDevice = 0; } } //------------------------------------------------------------------------- void VulkanQueue::newCommandBuffer( void ) { _waitOnFrame(mCurrentFrameIdx); vkResetCommandPool(mDevice, mPerFrameData[mCurrentFrameIdx].mCommandPool, 0); mCurrentCmdBuffer = mPerFrameData[mCurrentFrameIdx].mCommandBuffer; mCurrentFence = mPerFrameData[mCurrentFrameIdx].mProtectingFence; VkCommandBufferBeginInfo beginInfo = {VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; beginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; vkBeginCommandBuffer( mCurrentCmdBuffer, &beginInfo ); } //------------------------------------------------------------------------- void VulkanQueue::endCommandBuffer( void ) { if( mCurrentCmdBuffer ) { endAllEncoders(); OGRE_VK_CHECK(vkEndCommandBuffer( mCurrentCmdBuffer )); } } //------------------------------------------------------------------------- void VulkanQueue::getGraphicsEncoder( void ) { if( mEncoderState != EncoderGraphicsOpen ) { endCopyEncoder(); endComputeEncoder(); mEncoderState = EncoderGraphicsOpen; } } //------------------------------------------------------------------------- void VulkanQueue::getComputeEncoder( void ) { if( mEncoderState != EncoderComputeOpen ) { endRenderEncoder(); endCopyEncoder(); mEncoderState = EncoderComputeOpen; } } //------------------------------------------------------------------------- VkPipelineStageFlags VulkanQueue::deriveStageFromBufferAccessFlags( VkAccessFlags accessFlags ) { VkPipelineStageFlags stage = 0; if( accessFlags & VK_ACCESS_INDIRECT_COMMAND_READ_BIT ) stage |= VK_PIPELINE_STAGE_DRAW_INDIRECT_BIT; if( accessFlags & ( VK_ACCESS_INDEX_READ_BIT | VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT ) ) { stage |= VK_PIPELINE_STAGE_VERTEX_INPUT_BIT; } if( accessFlags & ( VK_ACCESS_UNIFORM_READ_BIT | VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT ) ) { stage |= VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_TESSELLATION_CONTROL_SHADER_BIT | VK_PIPELINE_STAGE_TESSELLATION_EVALUATION_SHADER_BIT | VK_PIPELINE_STAGE_GEOMETRY_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT; } if( accessFlags & ( VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT ) ) { stage |= VK_PIPELINE_STAGE_TRANSFER_BIT; } return stage; } //------------------------------------------------------------------------- VkPipelineStageFlags VulkanQueue::deriveStageFromTextureAccessFlags( VkAccessFlags accessFlags ) { VkPipelineStageFlags stage = 0; if( accessFlags & ( VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT ) ) { stage |= VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT; } if( accessFlags & ( VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT ) ) { stage |= VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; } if( accessFlags & ( VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT ) ) { stage |= VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_TESSELLATION_CONTROL_SHADER_BIT | VK_PIPELINE_STAGE_TESSELLATION_EVALUATION_SHADER_BIT | VK_PIPELINE_STAGE_GEOMETRY_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT; } if( accessFlags & ( VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT ) ) { stage |= VK_PIPELINE_STAGE_TRANSFER_BIT; } if( accessFlags & VK_ACCESS_INPUT_ATTACHMENT_READ_BIT ) stage |= VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT; return stage; } //------------------------------------------------------------------------- void VulkanQueue::insertRestoreBarrier( VulkanTextureGpu *vkTexture, const VkImageLayout newTransferLayout ) { const VkImageLayout oldLayout = vkTexture->mCurrLayout; const VkImageLayout otherTransferLayout = newTransferLayout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL ? VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL : VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; const VkAccessFlags accessFlags = newTransferLayout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL ? VK_ACCESS_TRANSFER_READ_BIT : VK_ACCESS_TRANSFER_WRITE_BIT; if( oldLayout == newTransferLayout ) { // Nothing to do. A restore barrier has already been inserted // If the assert fails, then the texture transitioned // to this layout without us knowing OGRE_ASSERT_HIGH( std::find( mImageMemBarrierPtrs.begin(), mImageMemBarrierPtrs.end(), vkTexture ) != mImageMemBarrierPtrs.end() && "Only this class should set VK_IMAGE_LAYOUT_TRANSFER_*_OPTIMAL" ); } else if( oldLayout == otherTransferLayout ) { // A restore barrier has already been inserted, but it needs modification FastArray<TextureGpu *>::iterator itor = std::find( mImageMemBarrierPtrs.begin(), mImageMemBarrierPtrs.end(), vkTexture ); // If the assert fails, then the texture transitioned // to this layout without us knowing OGRE_ASSERT_LOW( itor != mImageMemBarrierPtrs.end() && "Only this class should set VK_IMAGE_LAYOUT_TRANSFER_*_OPTIMAL" ); const size_t idx = ( size_t )( itor - mImageMemBarrierPtrs.begin() ); VkImageMemoryBarrier &imageMemBarrier = *( mImageMemBarriers.begin() + idx ); imageMemBarrier.srcAccessMask = accessFlags & c_srcValidAccessFlags; imageMemBarrier.oldLayout = newTransferLayout; } else { // First time we see this texture VkImageMemoryBarrier imageMemBarrier = vkTexture->getImageMemoryBarrier(); imageMemBarrier.srcAccessMask = accessFlags & c_srcValidAccessFlags; imageMemBarrier.dstAccessMask = VulkanMappings::get( vkTexture ); if( newTransferLayout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL ) { // We need to block subsequent stages from writing to this texture // until we're done copying from it (but they can read) imageMemBarrier.dstAccessMask &= (VkAccessFlags)~VK_ACCESS_SHADER_READ_BIT; mCopyEndReadDstTextureFlags |= imageMemBarrier.dstAccessMask; } imageMemBarrier.oldLayout = newTransferLayout; imageMemBarrier.newLayout = vkTexture->mNextLayout; mImageMemBarriers.push_back( imageMemBarrier ); mImageMemBarrierPtrs.push_back( vkTexture ); } } //------------------------------------------------------------------------- void VulkanQueue::prepareForUpload( const BufferPacked *buffer, TextureGpu *texture ) { VkAccessFlags bufferAccessFlags = 0; if( buffer ) { BufferPackedDownloadMap::iterator it = mCopyDownloadBuffers.find( buffer ); if( it == mCopyDownloadBuffers.end() ) ;//bufferAccessFlags = VulkanMappings::get( buffer->getBufferPackedType() ); else { if( !it->second ) { // bufferAccessFlags = VK_ACCESS_TRANSFER_WRITE_BIT; // We assume consecutive writes means we're writing to non-overlapping areas // Do not wait for previous transfers. bufferAccessFlags = 0; } else bufferAccessFlags = VK_ACCESS_TRANSFER_READ_BIT; } mCopyDownloadBuffers[buffer] = false; mCopyEndReadSrcBufferFlags |= VK_ACCESS_TRANSFER_WRITE_BIT; } OGRE_ASSERT_HIGH( !texture || dynamic_cast<VulkanTextureGpu *>( texture ) ); VulkanTextureGpu *vkTexture = static_cast<VulkanTextureGpu *>( texture ); VkAccessFlags texAccessFlags = 0; if( texture ) { TextureGpuDownloadMap::iterator it = mCopyDownloadTextures.find( vkTexture ); if( vkTexture->mCurrLayout == VK_IMAGE_LAYOUT_UNDEFINED ) { // This texture must just have been created texAccessFlags = 0; } else if( it == mCopyDownloadTextures.end() ) { if( vkTexture->mCurrLayout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL || vkTexture->mCurrLayout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL ) { OGRE_EXCEPT( Exception::ERR_INVALID_STATE, "Texture " + vkTexture->getName() + " is already in CopySrc or CopyDst layout, externally set. Perhaps " "you need to call RenderSystem::flushTextureCopyOperations", "VulkanQueue::prepareForUpload" ); } texAccessFlags = VulkanMappings::get( texture ); } else { if( !it->second ) { OGRE_ASSERT_MEDIUM( vkTexture->mCurrLayout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL ); // texAccessFlags = VK_ACCESS_TRANSFER_WRITE_BIT; // We assume consecutive writes means we're writing to non-overlapping areas // Do not wait for previous transfers. texAccessFlags = 0; } else { OGRE_ASSERT_MEDIUM( vkTexture->mCurrLayout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL ); texAccessFlags = VK_ACCESS_TRANSFER_READ_BIT; } } // We need to block subsequent stages from accessing this texture at all // until we're done copying into it mCopyEndReadDstTextureFlags |= VulkanMappings::get( texture ); mCopyDownloadTextures[vkTexture] = false; } // One buffer barrier is enough for all buffers. // Unless we already issued a transfer to this same buffer const bool bNeedsBufferBarrier = ( bufferAccessFlags && ( mCopyEndReadDstBufferFlags & bufferAccessFlags ) != bufferAccessFlags ) || ( bufferAccessFlags & ( VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT ) ); const bool bNeedsTexTransition = vkTexture && vkTexture->mCurrLayout != VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; mCopyEndReadDstBufferFlags |= bufferAccessFlags; // Trigger the barrier if we actually have to wait. // And only if we haven't issued this barrier already if( bNeedsBufferBarrier || bNeedsTexTransition ) { VkPipelineStageFlags srcStage = 0; uint32 numMemBarriers = 0u; VkMemoryBarrier memBarrier = {VK_STRUCTURE_TYPE_MEMORY_BARRIER}; if( bNeedsBufferBarrier ) { // GPU must stop using this buffer before we can write into it memBarrier.srcAccessMask = bufferAccessFlags & c_srcValidAccessFlags; memBarrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; srcStage |= deriveStageFromBufferAccessFlags( bufferAccessFlags ); numMemBarriers = 1u; } uint32 numImageMemBarriers = 0u; VkImageMemoryBarrier imageMemBarrier; if( bNeedsTexTransition ) { // GPU must stop using this texture before we can write into it // Also we need to do a transition imageMemBarrier = vkTexture->getImageMemoryBarrier(); imageMemBarrier.srcAccessMask = texAccessFlags & c_srcValidAccessFlags; imageMemBarrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; imageMemBarrier.oldLayout = vkTexture->mCurrLayout; imageMemBarrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; if( texAccessFlags == 0u ) { if( bufferAccessFlags == 0u ) { // Wait for nothing. We're only issuing a barrier // because of the texture transition srcStage = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT; } } else { srcStage |= deriveStageFromTextureAccessFlags( texAccessFlags ); } insertRestoreBarrier( vkTexture, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL ); vkTexture->mCurrLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; numImageMemBarriers = 1u; } // Wait until earlier render, compute and transfers are done so we can copy what // they wrote (unless we're only here for a texture transition) vkCmdPipelineBarrier( mCurrentCmdBuffer, srcStage & mOwnerDevice->mSupportedStages, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, numMemBarriers, &memBarrier, 0u, 0, numImageMemBarriers, &imageMemBarrier ); } } //------------------------------------------------------------------------- void VulkanQueue::prepareForDownload( const BufferPacked *buffer, VulkanTextureGpu *texture ) { VkAccessFlags bufferAccessFlags = 0; VkPipelineStageFlags srcStage = 0; // Evaluate the stages which blocks us before we can begin our transfer if( buffer ) { BufferPackedDownloadMap::iterator it = mCopyDownloadBuffers.find( buffer ); if( it == mCopyDownloadBuffers.end() ) { if( /*buffer->getBufferPackedType() == BP_TYPE_UAV*/ 0 ) { bufferAccessFlags = VK_ACCESS_SHADER_WRITE_BIT; srcStage |= VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_TESSELLATION_CONTROL_SHADER_BIT | VK_PIPELINE_STAGE_TESSELLATION_EVALUATION_SHADER_BIT | VK_PIPELINE_STAGE_GEOMETRY_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT; } // else //{ // If the buffer is not BT_TYPE_UAV, the GPU won't modify these buffers, // we can start downloading right away without waiting //} } else { if( !it->second ) { bufferAccessFlags = VK_ACCESS_TRANSFER_WRITE_BIT; srcStage |= VK_PIPELINE_STAGE_TRANSFER_BIT; } else bufferAccessFlags = 0; // Consecutive reads don't require waiting } mCopyDownloadBuffers[buffer] = true; mCopyEndReadSrcBufferFlags |= VK_ACCESS_TRANSFER_READ_BIT; } OGRE_ASSERT_HIGH( !texture || dynamic_cast<VulkanTextureGpu *>( texture ) ); VulkanTextureGpu *vkTexture = static_cast<VulkanTextureGpu *>( texture ); VkAccessFlags texAccessFlags = 0; if( texture ) { TextureGpuDownloadMap::iterator it = mCopyDownloadTextures.find( vkTexture ); if( it == mCopyDownloadTextures.end() ) { if( vkTexture->mCurrLayout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL || vkTexture->mCurrLayout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL ) { OGRE_EXCEPT( Exception::ERR_INVALID_STATE, "Texture " + vkTexture->getName() + " is already in CopySrc or CopyDst layout, externally set. Perhaps " "you need to call RenderSystem::flushTextureCopyOperations", "VulkanQueue::prepareForDownload" ); } if( texture->isUav() ) { texAccessFlags |= VK_ACCESS_SHADER_WRITE_BIT; srcStage |= VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_TESSELLATION_CONTROL_SHADER_BIT | VK_PIPELINE_STAGE_TESSELLATION_EVALUATION_SHADER_BIT | VK_PIPELINE_STAGE_GEOMETRY_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT; } if( texture->getUsage() & TU_RENDERTARGET ) { texAccessFlags |= VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; if( !PixelUtil::isDepth( texture->getFormat() ) ) { texAccessFlags |= VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; srcStage |= VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; } else { texAccessFlags |= VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT; srcStage |= VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT; } } } else { if( !it->second ) { OGRE_ASSERT_MEDIUM( vkTexture->mCurrLayout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL ); texAccessFlags = VK_ACCESS_TRANSFER_WRITE_BIT; srcStage |= VK_PIPELINE_STAGE_TRANSFER_BIT; } else { OGRE_ASSERT_MEDIUM( vkTexture->mCurrLayout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL ); texAccessFlags = 0; // Consecutive reads don't require waiting } } mCopyDownloadTextures[vkTexture] = true; } // One buffer barrier is enough for all buffers. // Unless we already issued a transfer to this same buffer const bool bNeedsBufferBarrier = ( bufferAccessFlags && ( mCopyStartWriteSrcBufferFlags & bufferAccessFlags ) != bufferAccessFlags ) || ( bufferAccessFlags & ( VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT ) ); mCopyStartWriteSrcBufferFlags |= bufferAccessFlags; const bool bNeedsTexTransition = vkTexture && vkTexture->mCurrLayout != VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; // Trigger the barrier if we actually have to wait. // And only if we haven't issued this barrier already if( bNeedsBufferBarrier || bNeedsTexTransition ) { uint32 numMemBarriers = 0u; VkMemoryBarrier memBarrier = {VK_STRUCTURE_TYPE_MEMORY_BARRIER}; if( bNeedsBufferBarrier ) { memBarrier.srcAccessMask = bufferAccessFlags & c_srcValidAccessFlags; memBarrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT; numMemBarriers = 1u; } uint32 numImageMemBarriers = 0u; VkImageMemoryBarrier imageMemBarrier; if( bNeedsTexTransition ) { imageMemBarrier = vkTexture->getImageMemoryBarrier(); imageMemBarrier.srcAccessMask = texAccessFlags & c_srcValidAccessFlags; imageMemBarrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT; imageMemBarrier.oldLayout = vkTexture->mCurrLayout; imageMemBarrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; insertRestoreBarrier( vkTexture, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL ); vkTexture->mCurrLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; numImageMemBarriers = 1u; if( !srcStage ) { // If we're here the texture is read-only and we only // need the barrier to perform a layout transition srcStage = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT; } } // Wait until earlier render, compute and transfers are done so we can copy what // they wrote (unless we're only here for a texture transition) vkCmdPipelineBarrier( mCurrentCmdBuffer, srcStage & mOwnerDevice->mSupportedStages, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, numMemBarriers, &memBarrier, 0u, 0, numImageMemBarriers, &imageMemBarrier ); } } //------------------------------------------------------------------------- void VulkanQueue::getCopyEncoder( const BufferPacked *buffer, VulkanTextureGpu *texture, const bool bDownload ) { OgreAssert(mEncoderState != EncoderGraphicsOpen, "interrupting RenderPass not supported"); if( mEncoderState != EncoderCopyOpen ) { endRenderEncoder(); endComputeEncoder(); mEncoderState = EncoderCopyOpen; // Submission guarantees the host write being complete, as per // khronos.org/registry/vulkan/specs/1.0/html/vkspec.html#synchronization-submission-host-writes // So no need for a barrier before the transfer // // The only exception is when writing from CPU to GPU when a command that uses that region // has already been submitted via vkQueueSubmit (and you're using vkCmdWaitEvents to wait // for the CPU to write the data and give ok to the GPU). // Which Ogre does not do (too complex to get right). } if( bDownload ) prepareForDownload( buffer, texture ); else prepareForUpload( buffer, texture ); } //------------------------------------------------------------------------- void VulkanQueue::getCopyEncoderV1Buffer( const bool bDownload ) { OgreAssert(mEncoderState != EncoderGraphicsOpen, "interrupting RenderPass not supported"); if( mEncoderState != EncoderCopyOpen ) { endRenderEncoder(); endComputeEncoder(); mEncoderState = EncoderCopyOpen; } if( !bDownload ) { // V1 buffers are only used for vertex and index buffers // We assume v1 buffers don't try to write then read (or read then write) in a row const VkAccessFlags bufferAccessFlags = VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT | VK_ACCESS_INDEX_READ_BIT; if( ( mCopyEndReadDstBufferFlags & bufferAccessFlags ) != bufferAccessFlags ) { uint32 numMemBarriers = 0u; VkMemoryBarrier memBarrier = {VK_STRUCTURE_TYPE_MEMORY_BARRIER}; memBarrier.srcAccessMask = bufferAccessFlags & c_srcValidAccessFlags; memBarrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; numMemBarriers = 1u; // GPU must stop using this buffer before we can write into it vkCmdPipelineBarrier( mCurrentCmdBuffer, VK_PIPELINE_STAGE_VERTEX_INPUT_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, numMemBarriers, &memBarrier, 0u, 0, 0u, 0 ); } mCopyEndReadDstBufferFlags |= bufferAccessFlags; mCopyEndReadSrcBufferFlags |= VK_ACCESS_TRANSFER_WRITE_BIT; } else { mCopyEndReadSrcBufferFlags |= VK_ACCESS_TRANSFER_READ_BIT; } } //------------------------------------------------------------------------- void VulkanQueue::endCopyEncoder( void ) { if( mEncoderState != EncoderCopyOpen ) return; if( mCopyEndReadDstBufferFlags || !mImageMemBarrierPtrs.empty() ) { VkPipelineStageFlags dstStage = 0; uint32 numMemBarriers = 0u; VkMemoryBarrier memBarrier = {VK_STRUCTURE_TYPE_MEMORY_BARRIER}; if( mCopyEndReadDstBufferFlags ) { memBarrier.srcAccessMask = mCopyEndReadSrcBufferFlags & c_srcValidAccessFlags; memBarrier.dstAccessMask = mCopyEndReadDstBufferFlags; // Evaluate the stages we can unblock when our transfers are done dstStage |= deriveStageFromBufferAccessFlags( memBarrier.dstAccessMask ); numMemBarriers = 1u; } dstStage |= deriveStageFromTextureAccessFlags( mCopyEndReadDstTextureFlags ); if( dstStage == 0u ) { // Nothing needs to wait for us. Can happen if all we're // doing is copying from read-only textures (rare) dstStage = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT; #if OGRE_DEBUG_MODE FastArray<TextureGpu *>::const_iterator itor = mImageMemBarrierPtrs.begin(); FastArray<TextureGpu *>::const_iterator endt = mImageMemBarrierPtrs.end(); while( itor != endt ) { OgreAssert( (( *itor )->getUsage() & TU_RENDERTARGET) == 0/*&& !( *itor )->isUav()*/, "endCopyEncoder says nothing will wait on this texture(s) but " "we don't know if a subsequent stage will write to it" ); ++itor; } #endif } // Wait until earlier render, compute and transfers are done // Block render, compute and transfers until we're done vkCmdPipelineBarrier( mCurrentCmdBuffer, VK_PIPELINE_STAGE_TRANSFER_BIT, dstStage & mOwnerDevice->mSupportedStages, 0, numMemBarriers, &memBarrier, 0u, 0, static_cast<uint32_t>( mImageMemBarriers.size() ), mImageMemBarriers.data() ); mImageMemBarriers.clear(); mImageMemBarrierPtrs.clear(); TextureGpuDownloadMap::const_iterator itor = mCopyDownloadTextures.begin(); TextureGpuDownloadMap::const_iterator endt = mCopyDownloadTextures.end(); while( itor != endt ) { itor->first->mCurrLayout = itor->first->mNextLayout; ++itor; } } mCopyEndReadSrcBufferFlags = 0; mCopyEndReadDstBufferFlags = 0; mCopyEndReadDstTextureFlags = 0; mCopyStartWriteSrcBufferFlags = 0; mCopyDownloadTextures.clear(); mCopyDownloadBuffers.clear(); mEncoderState = EncoderClosed; } //------------------------------------------------------------------------- void VulkanQueue::endRenderEncoder( const bool endRenderPassDesc ) { if( mEncoderState != EncoderGraphicsOpen ) return; mRenderSystem->_notifyActiveEncoderEnded(); if( endRenderPassDesc ) mRenderSystem->endRenderPassDescriptor(); mEncoderState = EncoderClosed; } //------------------------------------------------------------------------- void VulkanQueue::endComputeEncoder( void ) { if( mEncoderState != EncoderComputeOpen ) return; mEncoderState = EncoderClosed; mRenderSystem->_notifyActiveComputeEnded(); } //------------------------------------------------------------------------- void VulkanQueue::endAllEncoders( const bool endRenderPassDesc ) { endCopyEncoder(); endRenderEncoder( endRenderPassDesc ); endComputeEncoder(); } //------------------------------------------------------------------------- void VulkanQueue::notifyTextureDestroyed( VulkanTextureGpu *texture ) { if( mEncoderState == EncoderCopyOpen ) { bool needsToFlush = false; TextureGpuDownloadMap::const_iterator itor = mCopyDownloadTextures.find( texture ); if( itor != mCopyDownloadTextures.end() ) needsToFlush = true; else { FastArray<TextureGpu *>::const_iterator it2 = std::find( mImageMemBarrierPtrs.begin(), mImageMemBarrierPtrs.end(), texture ); if( it2 != mImageMemBarrierPtrs.end() ) needsToFlush = true; } if( needsToFlush ) { // If this asserts triggers, then the texture is probably being referenced // by something else doing anything on the texture and was interrupted // midway (since Ogre must ensure the texture ends in TRANSFER_SRC/DST_OPTIMAL // if the copy encoder is holding a reference. OGRE_ASSERT_LOW( texture->mCurrLayout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL || texture->mCurrLayout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL ); endCopyEncoder(); } } } //------------------------------------------------------------------------- void VulkanQueue::addWindowToWaitFor( VkSemaphore imageAcquisitionSemaph ) { OGRE_ASSERT_MEDIUM( mFamily == Graphics ); mGpuWaitFlags.push_back( VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT ); mGpuWaitSemaphForCurrCmdBuff.push_back( imageAcquisitionSemaph ); } //------------------------------------------------------------------------- void VulkanQueue::queueForDeletion(VkBuffer buffer, VkDeviceMemory memory) { mPerFrameData[mCurrentFrameIdx].mBufferGraveyard.push_back({buffer, memory}); } void VulkanQueue::queueForDeletion(const std::shared_ptr<VulkanDescriptorPool>& descriptorPool) { mPerFrameData[mCurrentFrameIdx].mDescriptorPoolGraveyard.push_back(descriptorPool); } void VulkanQueue::_waitOnFrame( uint8 frameIdx ) { VkFence fence = mPerFrameData[frameIdx].mProtectingFence; vkWaitForFences( mDevice, 1, &fence, VK_TRUE, UINT64_MAX ); // it is safe to free staging buffers now for(auto bm : mPerFrameData[frameIdx].mBufferGraveyard) { vkDestroyBuffer(mDevice, bm.first, nullptr); vkFreeMemory(mDevice, bm.second, nullptr); } mPerFrameData[frameIdx].mBufferGraveyard.clear(); mPerFrameData[frameIdx].mDescriptorPoolGraveyard.clear(); } //------------------------------------------------------------------------- bool VulkanQueue::_isFrameFinished( uint8 frameIdx ) { VkFence fence = mPerFrameData[frameIdx].mProtectingFence; VkResult ret = vkWaitForFences( mDevice, 1, &fence, VK_TRUE, 0u ); if( ret != VK_TIMEOUT ) { OGRE_VK_CHECK(ret); //recycleFences( fences ); return true; } return false; } //------------------------------------------------------------------------- void VulkanQueue::commitAndNextCommandBuffer( SubmissionType::SubmissionType submissionType ) { endCommandBuffer(); VkSubmitInfo submitInfo = {VK_STRUCTURE_TYPE_SUBMIT_INFO}; submitInfo.commandBufferCount = 1; submitInfo.pCommandBuffers = &mCurrentCmdBuffer; if( !mGpuWaitSemaphForCurrCmdBuff.empty() ) { // We need to wait on these semaphores so that rendering can // only happen start the swapchain is done presenting submitInfo.waitSemaphoreCount = mGpuWaitSemaphForCurrCmdBuff.size(); submitInfo.pWaitSemaphores = mGpuWaitSemaphForCurrCmdBuff.data(); submitInfo.pWaitDstStageMask = mGpuWaitFlags.data(); } if( submissionType >= SubmissionType::NewFrameIdx ) { if( submissionType >= SubmissionType::EndFrameAndSwap ) { // Get semaphores so that presentation can wait for this job to finish rendering // (one for each window that will be swapped) for (auto w : mWindowsPendingSwap) { mGpuSignalSemaphForCurrCmdBuff.push_back(w->getRenderFinishedSemaphore()); w->setImageFence(mCurrentFence); } } if( !mGpuSignalSemaphForCurrCmdBuff.empty() ) { // We need to signal these semaphores so that presentation // can only happen after we're done rendering (presentation may not be the // only thing waiting for us though; thus we must set this with NewFrameIdx // and not just with EndFrameAndSwap) submitInfo.signalSemaphoreCount = mGpuSignalSemaphForCurrCmdBuff.size(); submitInfo.pSignalSemaphores = mGpuSignalSemaphForCurrCmdBuff.data(); } } OGRE_VK_CHECK(vkResetFences(mDevice, 1, &mCurrentFence) ); vkQueueSubmit( mQueue, 1u, &submitInfo, mCurrentFence ); mGpuWaitSemaphForCurrCmdBuff.clear(); mCurrentCmdBuffer = VK_NULL_HANDLE; if( submissionType >= SubmissionType::EndFrameAndSwap ) { for (auto w : mWindowsPendingSwap) w->_swapBuffers(); } if( submissionType >= SubmissionType::NewFrameIdx ) { mCurrentFrameIdx = (mCurrentFrameIdx + 1) % mPerFrameData.size(); } newCommandBuffer(); if( submissionType >= SubmissionType::EndFrameAndSwap ) { // acquireNextImage must be called after newCommandBuffer() for (auto w : mWindowsPendingSwap) w->acquireNextImage(); mWindowsPendingSwap.clear(); mGpuSignalSemaphForCurrCmdBuff.clear(); } } } // namespace Ogre
OGRECave/ogre
RenderSystems/Vulkan/src/OgreVulkanQueue.cpp
C++
mit
40,249
function foo() { var bar = ''; };
michaelghinrichs/hello-world
scope-chains-closures/scopes.js
JavaScript
mit
37
/*-- 简单测试node.js端使用的air-js -note 所有的模块以模块简称为属性名挂载在air上 */ var air = require('air-js'); var byteLength = air.byteLength; console.log(byteLength('中国人')); // => 6 console.log(byteLength('air')); // => 3 console.log(air.byteLength('air')); // => 3 console.log(air.clip('我是中国人', 8)); // => 我是中国… console.log(air.thousandFloat(78934.25)); // => 78,934.25
erniu/air
test-air.js
JavaScript
mit
442
import forIn from '../core/forIn' import forElements from '../core/forElements' export default function _parseAndApply (parse, apply, elements, options) { forIn(options, parse.bind(null, options)) return forElements(elements, apply.bind(null, options)) }
chirashijs/chirashi
lib/_internals/_parseAndApply.js
JavaScript
mit
261
<?php /* * This file is part of the PHPExifTool package. * * (c) Alchemy <support@alchemy.fr> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPExiftool\Driver\Tag\DICOM; use JMS\Serializer\Annotation\ExclusionPolicy; use PHPExiftool\Driver\AbstractTag; /** * @ExclusionPolicy("all") */ class SelectorSequencePointer extends AbstractTag { protected $Id = '0072,0052'; protected $Name = 'SelectorSequencePointer'; protected $FullName = 'DICOM::Main'; protected $GroupName = 'DICOM'; protected $g0 = 'DICOM'; protected $g1 = 'DICOM'; protected $g2 = 'Image'; protected $Type = '?'; protected $Writable = false; protected $Description = 'Selector Sequence Pointer'; }
bburnichon/PHPExiftool
lib/PHPExiftool/Driver/Tag/DICOM/SelectorSequencePointer.php
PHP
mit
822
<?php namespace kiwi\Http\Middleware; use kiwi\Http\Request; trait AuthorizesRequests { /** * Dont access without authorizing. * * @return void */ public function middleware() { if (!auth()->check()) { Request::redirect('/login'); } } }
jakobjohansson/Verbalizer
framework/Http/Middleware/AuthorizesRequests.php
PHP
mit
304
<?php namespace NilPortugues\ForbiddenFunctions\Console; use NilPortugues\ForbiddenFunctions\Command\CheckCommand; class Application extends \Symfony\Component\Console\Application { /** * Construct method */ public function __construct() { $name = <<<NAME ------------------------------------------------- PHP Forbidden Functions Checker ------------------------------------------------- NAME; parent::__construct($name); } /** * Initializes all the composer commands * * @return \Symfony\Component\Console\Command\Command[] */ protected function getDefaultCommands() { $commands = parent::getDefaultCommands(); $commands[] = new CheckCommand(); return $commands; } }
nilportugues/php_forbidden_functions
src/ForbiddenFunctions/Console/Application.php
PHP
mit
778
/** * This class is generated by jOOQ */ package de.piratenpartei.berlin.ldadmin.dbaccess.generated.routines; /** * This class is generated by jOOQ. */ @javax.annotation.Generated(value = { "http://www.jooq.org", "3.4.4" }, comments = "This class is generated by jOOQ") @java.lang.SuppressWarnings({ "all", "unchecked", "rawtypes" }) public class DelegationChainForClosedIssue extends org.jooq.impl.AbstractRoutine<de.piratenpartei.berlin.ldadmin.dbaccess.generated.udt.records.DelegationChainRowRecord> { private static final long serialVersionUID = -1265014680; /** * The parameter <code>delegation_chain_for_closed_issue.RETURN_VALUE</code>. */ public static final org.jooq.Parameter<de.piratenpartei.berlin.ldadmin.dbaccess.generated.udt.records.DelegationChainRowRecord> RETURN_VALUE = createParameter("RETURN_VALUE", de.piratenpartei.berlin.ldadmin.dbaccess.generated.udt.DelegationChainRow.DELEGATION_CHAIN_ROW.getDataType()); /** * The parameter <code>delegation_chain_for_closed_issue.member_id_p</code>. */ public static final org.jooq.Parameter<java.lang.Integer> MEMBER_ID_P = createParameter("member_id_p", org.jooq.impl.SQLDataType.INTEGER); /** * The parameter <code>delegation_chain_for_closed_issue.issue_id_p</code>. */ public static final org.jooq.Parameter<java.lang.Integer> ISSUE_ID_P = createParameter("issue_id_p", org.jooq.impl.SQLDataType.INTEGER); /** * Create a new routine call instance */ public DelegationChainForClosedIssue() { super("delegation_chain_for_closed_issue", de.piratenpartei.berlin.ldadmin.dbaccess.generated.DefaultSchema.DEFAULT_SCHEMA, de.piratenpartei.berlin.ldadmin.dbaccess.generated.udt.DelegationChainRow.DELEGATION_CHAIN_ROW.getDataType()); setReturnParameter(RETURN_VALUE); addInParameter(MEMBER_ID_P); addInParameter(ISSUE_ID_P); } /** * Set the <code>member_id_p</code> parameter IN value to the routine */ public void setMemberIdP(java.lang.Integer value) { setValue(de.piratenpartei.berlin.ldadmin.dbaccess.generated.routines.DelegationChainForClosedIssue.MEMBER_ID_P, value); } /** * Set the <code>member_id_p</code> parameter to the function to be used with a {@link org.jooq.Select} statement */ public void setMemberIdP(org.jooq.Field<java.lang.Integer> field) { setField(MEMBER_ID_P, field); } /** * Set the <code>issue_id_p</code> parameter IN value to the routine */ public void setIssueIdP(java.lang.Integer value) { setValue(de.piratenpartei.berlin.ldadmin.dbaccess.generated.routines.DelegationChainForClosedIssue.ISSUE_ID_P, value); } /** * Set the <code>issue_id_p</code> parameter to the function to be used with a {@link org.jooq.Select} statement */ public void setIssueIdP(org.jooq.Field<java.lang.Integer> field) { setField(ISSUE_ID_P, field); } }
plattformbrandenburg/ldadmin
src/main/java/de/piratenpartei/berlin/ldadmin/dbaccess/generated/routines/DelegationChainForClosedIssue.java
Java
mit
2,840
using Microsoft.Azure.ServiceBus; using Microsoft.Extensions.Logging; using System; using System.IO; namespace Microsoft.eShopOnContainers.BuildingBlocks.EventBusServiceBus { public class DefaultServiceBusPersisterConnection :IServiceBusPersisterConnection { private readonly ILogger<DefaultServiceBusPersisterConnection> _logger; private readonly ServiceBusConnectionStringBuilder _serviceBusConnectionStringBuilder; private ITopicClient _topicClient; bool _disposed; public DefaultServiceBusPersisterConnection(ServiceBusConnectionStringBuilder serviceBusConnectionStringBuilder, ILogger<DefaultServiceBusPersisterConnection> logger) { _logger = logger ?? throw new ArgumentNullException(nameof(logger)); _serviceBusConnectionStringBuilder = serviceBusConnectionStringBuilder ?? throw new ArgumentNullException(nameof(serviceBusConnectionStringBuilder)); _topicClient = new TopicClient(_serviceBusConnectionStringBuilder, RetryPolicy.Default); } public ServiceBusConnectionStringBuilder ServiceBusConnectionStringBuilder => _serviceBusConnectionStringBuilder; public ITopicClient CreateModel() { if(_topicClient.IsClosedOrClosing) { _topicClient = new TopicClient(_serviceBusConnectionStringBuilder, RetryPolicy.Default); } return _topicClient; } public void Dispose() { if (_disposed) return; _disposed = true; } } }
TypeW/eShopOnContainers
src/BuildingBlocks/EventBus/EventBusServiceBus/DefaultServiceBusPersisterConnection.cs
C#
mit
1,621
/// <reference path="./event.ts" /> module Fusion { /** * Represents a component of discrete functionality in a Fusion application */ export interface Widget extends EventEmittable { } /** * Represents a component of discrete functionality in a Fusion application */ export class WidgetBase extends EventEmitter implements Widget { constructor() { super(); } } }
jumpinjackie/mapguide-ajax-viewer
shared/src/fusion/widget.ts
TypeScript
mit
448
'use strict'; app.controller('DeleteTripModalCtrl', function($scope, $uibModalInstance, TripFactory, $routeParams, $window, ActivityFactory, MemberFactory){ let tripId = $routeParams.tripId; $scope.close = () => { $uibModalInstance.close(); }; //Not only do we want to delete the trip object connected to that user from Firebase but we also want to delete anything associated with the trip - notes, packing list, and trails that have been added. $scope.deleteTrip = ()=>{ TripFactory.deleteTrip(tripId) .then(()=>{ console.log("trip was deleted"); $scope.close(); $window.location.href='#/parks/explore'; return ActivityFactory.getActivities(tripId) }) .then((activityData)=>{ console.log("activities in trip", activityData); Object.keys(activityData).forEach((activityId)=>{ ActivityFactory.deleteActivityFromTrip(activityId); }); return TripFactory.getUserPackingList(tripId) }) .then((packingData)=>{ console.log("user packing list", packingData); Object.keys(packingData).forEach((listId)=>{ TripFactory.deleteItemFromList(listId); }); return MemberFactory.getMembersOfTrip(tripId) }) .then((members)=>{ console.log("members", members); Object.keys(members).forEach((memberId)=>{ MemberFactory.deleteMember(memberId); }); return TripFactory.getInvitationsInTrip(tripId) }) .then((invitations)=>{ console.log("invitations", invitations); Object.keys(invitations).forEach((invitationId)=>{ TripFactory.deleteInvitation(invitationId); }); }) }; });
delainewendling/NP_trip_planner
deploy/app/controllers/DeleteTripModalCtrl.js
JavaScript
mit
1,660
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace XmlGuy { public class XmlElement : AbstractXmlElement { public XmlElement(XmlElement parent = null) : base(parent) { Children = new List<IXmlElement>(); Attributes = new Dictionary<string, string>(); } public IList<IXmlElement> Children { get; set; } public IDictionary<string, string> Attributes { get; set; } public XmlElement Up() { return Parent; } public XmlElement Add(string name, params object[] args) { string value = null; Dictionary<string, string> attributes = new Dictionary<string, string>(); if (args != null) { foreach (var arg in args) { if (arg is string) value = arg as string; else foreach (var prop in arg.GetType().GetProperties()) attributes.Add(prop.Name, prop.GetValue(arg, null) as string); } } return Add(name, value, attributes); } private XmlElement Add(string name, string value, IDictionary<string, string> attributes) { if (Value != null) throw new InvalidOperationException("XML Element " + Name + " has a text value: it cannot contain child elements"); var child = new XmlElement(this) { Name = name, Value = value, Attributes = attributes }; Children.Add(child); return child; } public XmlElement CData(string data) { Children.Add(new CDataElement(this) { Value = data }); return this; } } public class CDataElement : AbstractXmlElement { public CDataElement(XmlElement parent = null) : base(parent) { } } }
windracer/xmlguy
src/XmlElement.cs
C#
mit
1,589
import isArray from '../../util/isArray' import forEach from '../../util/forEach' import TreeIndex from '../../util/TreeIndex' import NodeIndex from './NodeIndex' class PropertyIndex extends NodeIndex { constructor(property) { super() this._property = property || 'id' this.index = new TreeIndex() } /** Get all indexed nodes for a given path. @param {Array<String>} path @returns A node or an object with ids and nodes as values. */ get(path) { return this.index.get(path) || {} } /** Collects nodes recursively. @returns An object with ids as keys and nodes as values. */ getAll(path) { return this.index.getAll(path) } /** Check if a node should be indexed. Used internally only. Override this in subclasses to achieve a custom behavior. @private @param {Node} @returns {Boolean} true if the given node should be added to the index. */ select(node) { // eslint-disable-line return true } /** Called when a node has been created. Override this in subclasses for customization. @private @param {Node} node */ create(node) { var values = node[this._property] if (!isArray(values)) { values = [values] } forEach(values, function(value) { this.index.set([value, node.id], node) }.bind(this)) } /** * Called when a node has been deleted. * * Override this in subclasses for customization. * * @private * @param {model/data/Node} node */ delete(node) { var values = node[this._property] if (!isArray(values)) { values = [values] } forEach(values, function(value) { this.index.delete([value, node.id]) }.bind(this)) } /** Called when a property has been updated. Override this in subclasses for customization. @private @param {Node} node */ update(node, path, newValue, oldValue) { if (!this.select(node) || path[1] !== this._property) return var values = oldValue if (!isArray(values)) { values = [values] } forEach(values, function(value) { this.index.delete([value, node.id]) }.bind(this)) values = newValue if (!isArray(values)) { values = [values] } forEach(values, function(value) { this.index.set([value, node.id], node) }.bind(this)) } set(node, path, newValue, oldValue) { this.update(node, path, newValue, oldValue) } _clear() { this.index.clear() } _initialize(data) { forEach(data.getNodes(), function(node) { if (this.select(node)) { this.create(node) } }.bind(this)) } } export default PropertyIndex
andene/substance
model/data/PropertyIndex.js
JavaScript
mit
2,682
(function(){ function buildForm(attrs) { attrs = $.extend({ action: '/echo', 'data-remote': 'true' }, attrs); $('#qunit-fixture').append($('<form />', attrs)) .find('form').append($('<input type="text" name="user_name" value="john">')); }; module('call-remote'); function submit(fn) { $('form') .on('ajax:success', fn) .on('ajax:complete', function() { start() }) .trigger('submit'); } asyncTest('form method is read from "method" and not from "data-method"', 1, function() { buildForm({ method: 'post', 'data-method': 'get' }); submit(function(e, data, status, xhr) { App.assertPostRequest(data); }); }); asyncTest('form method is not read from "data-method" attribute in case of missing "method"', 1, function() { buildForm({ 'data-method': 'put' }); submit(function(e, data, status, xhr) { App.assertGetRequest(data); }); }); asyncTest('form method is read from submit button "formmethod" if submit is triggered by that button', 1, function() { var submitButton = $('<input type="submit" formmethod="get">') buildForm({ method: 'post' }); $('#qunit-fixture').find('form').append(submitButton) .on('ajax:success', function(e, data, status, xhr) { App.assertGetRequest(data); }) .on('ajax:complete', function() { start() }); submitButton.trigger('click'); }); asyncTest('form default method is GET', 1, function() { buildForm(); submit(function(e, data, status, xhr) { App.assertGetRequest(data); }); }); asyncTest('form url is picked up from "action"', 1, function() { buildForm({ method: 'post' }); submit(function(e, data, status, xhr) { App.assertRequestPath(data, '/echo'); }); }); asyncTest('form url is read from "action" not "href"', 1, function() { buildForm({ method: 'post', href: '/echo2' }); submit(function(e, data, status, xhr) { App.assertRequestPath(data, '/echo'); }); }); asyncTest('form url is read from submit button "formaction" if submit is triggered by that button', 1, function() { var submitButton = $('<input type="submit" formaction="/echo">') buildForm({ method: 'post', href: '/echo2' }); $('#qunit-fixture').find('form').append(submitButton) .on('ajax:success', function(e, data, status, xhr) { App.assertRequestPath(data, '/echo'); }) .on('ajax:complete', function() { start() }); submitButton.trigger('click'); }); asyncTest('prefer JS, but accept any format', 1, function() { buildForm({ method: 'post' }); submit(function(e, data, status, xhr) { var accept = data.HTTP_ACCEPT; ok(accept.indexOf('*/*;q=0.5, text/javascript, application/javascript') === 0, 'Accept: ' + accept); }); }); asyncTest('accept application/json if "data-type" is json', 1, function() { buildForm({ method: 'post', 'data-type': 'json' }); submit(function(e, data, status, xhr) { equal(data.HTTP_ACCEPT, 'application/json, text/javascript, */*; q=0.01'); }); }); asyncTest('allow empty "data-remote" attribute', 1, function() { var form = $('#qunit-fixture').append($('<form action="/echo" data-remote />')).find('form'); submit(function() { ok(true, 'form with empty "data-remote" attribute is also allowed'); }); }); asyncTest('allow empty form "action"', 1, function() { var currentLocation, ajaxLocation; buildForm({ action: '' }); $('#qunit-fixture').find('form') .on('ajax:beforeSend', function(e, xhr, settings) { // Get current location (the same way jQuery does) try { currentLocation = location.href; } catch(e) { currentLocation = document.createElement( "a" ); currentLocation.href = ""; currentLocation = currentLocation.href; } currentLocation = currentLocation.replace(/\?$/, ''); // Actual location (strip out settings.data that jQuery serializes and appends) // HACK: can no longer use settings.data below to see what was appended to URL, as of // jQuery 1.6.3 (see http://bugs.jquery.com/ticket/10202 and https://github.com/jquery/jquery/pull/544) ajaxLocation = settings.url.replace("user_name=john","").replace(/&$/, "").replace(/\?$/, ""); equal(ajaxLocation.match(/^(.*)/)[1], currentLocation, 'URL should be current page by default'); // Prevent the request from actually getting sent to the current page and // causing an error. return false; }) .trigger('submit'); setTimeout(function() { start(); }, 13); }); asyncTest('sends CSRF token in custom header', 1, function() { buildForm({ method: 'post' }); $('#qunit-fixture').append('<meta name="csrf-token" content="cf50faa3fe97702ca1ae" />'); submit(function(e, data, status, xhr) { equal(data.HTTP_X_CSRF_TOKEN, 'cf50faa3fe97702ca1ae', 'X-CSRF-Token header should be sent'); }); }); asyncTest('intelligently guesses crossDomain behavior when target URL has a different protocol and/or hostname', 1, function(e, xhr) { // Don't set data-cross-domain here, just set action to be a different domain than localhost buildForm({ action: 'http://www.alfajango.com' }); $('#qunit-fixture').append('<meta name="csrf-token" content="cf50faa3fe97702ca1ae" />'); $('#qunit-fixture').find('form') .on('ajax:beforeSend', function(e, xhr, settings) { equal(settings.crossDomain, true, 'crossDomain should be set to true'); // prevent request from actually getting sent off-domain return false; }) .trigger('submit'); setTimeout(function() { start(); }, 13); }); asyncTest('intelligently guesses crossDomain behavior when target URL consists of only a path', 1, function(e, xhr) { // Don't set data-cross-domain here, just set action to be a different domain than localhost buildForm({ action: '/just/a/path' }); $('#qunit-fixture').append('<meta name="csrf-token" content="cf50faa3fe97702ca1ae" />'); $('#qunit-fixture').find('form') .on('ajax:beforeSend', function(e, xhr, settings) { equal(settings.crossDomain, false, 'crossDomain should be set to false'); // prevent request from actually getting sent off-domain return false; }) .trigger('submit'); setTimeout(function() { start(); }, 13); }); })();
rails/jquery-ujs
test/public/test/call-remote.js
JavaScript
mit
6,202
/* * Smush In - jQuery plugin * * Copyright (c) 2013 Shane Donnelly * * Licensed under the MIT license: * http://www.opensource.org/licenses/mit-license.php * * Project home: * http://shanejdonnelly.github.io/smush-in * Version: 1.0 * */ ;(function ($) { "use strict"; /* CLASS DEFINITION * ====================== */ var SmushIn = function ($element, options) { this.settings = options; this.$el = $element; this.setup(); } SmushIn.prototype = { constructor: SmushIn, setup: function(){ this.height = this.$el.height(); this.width = this.$el.width(); this.left = parseInt(this.$el.css('left')); this.top = parseInt(this.$el.css('top')); this.font_size = parseInt(this.$el.css('font-size')); this.window_width = $(window).width(); this.window_height = $(window).height(); this.max_anim_speed = (this.settings.speed === 'slow') ? 130 : 75; if(this.settings.overshot === 0){ this.settings.overshot = this.rand(10,70) } //decide direction if(this.settings.from_direction === 'random') { var random_direction = (this.rand(0,20) < 10) ? 'left' : 'right'; this.horzAnim(random_direction); } else{ this.horzAnim(this.settings.from_direction); } }, horzAnim: function(from_direction){ var base = this, start_position = (from_direction === 'right') ? ( base.rand((base.window_width * 1.1), (base.window_width * 2)) ) : ( start_position = -1 * base.rand((base.window_width * 1.1), (base.window_width * 2)) ), fly_to = (from_direction === 'right') ? (base.left - base.settings.overshot) : (base.left + base.settings.overshot); //set start position base.$el.css('left', start_position ); setTimeout(function(){ //fly in base.$el.show().animate({'left': fly_to}, base.rand(200,500 ), function(){ //hit the 'wall' base.$el.animate( { 'height': (base.height * base.rand(1,2)), 'width': base.width * base.rand(.3, .7), 'margin-top': -(base.height * base.rand(.2,.4)) }, base.max_anim_speed, function(){ //bounce back base.$el.animate( { 'height': base.height, 'width': base.width, 'margin-top':0, 'left':base.left }, ( base.max_anim_speed * 1.75)); }); }); }, base.rand(500,1500)); }, //returns float rand: function(min, max){ return Math.random() * (max - min) + min; } } /* PLUGIN DEFINITION * ======================= */ $.fn.smushIn = function (custom_options) { return this.each(function () { var $el = $(this), options = $.extend({}, $.fn.smushIn.defaults, custom_options); new SmushIn($el, options) }) } $.fn.smushIn.defaults = { 'overshot' : 0, 'speed' : 'slow', 'from_direction' : 'left' } $.fn.smushIn.Constructor = SmushIn })(window.jQuery);
shanejdonnelly/smush-in
smushIn.js
JavaScript
mit
3,613
<?php // SonataMediaBundle:Form:media_widgets.html.twig return array ( );
DevKhater/YallaWebSite
app/cache/prod/assetic/config/4/423e5d4324992a3bd20ae71d066b011d.php
PHP
mit
75
<?php defined('_JEXEC') or die('Restricted access'); /** * Mercado Pago plugin * * @author Developers Mercado Pago <modulos@mercadopago.com> * @version 2.0.5 * @package VirtueMart * @subpackage payment * @link https://www.mercadopago.com * @copyright Copyright © 2016 MercadoPago.com * @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.php */ ?> <br/> <img src="<?php echo MercadoPagoHelper::getBanner($viewData['site_id']);?>" id="mercadopago-banner-basic">
yaelduckwen/lo_imaginario
web2/plugins/vmpayment/mercadopago/mercadopago/tmpl/mercadopago_checkout_standard.php
PHP
mit
491
#!/usr/bin/env node "use strict"; // XXX currently this project is written to support node 0.10.* // when Meteor 1.4 is ready, we can rewrite in es6 var Vorpal = require("vorpal")(), Path = require("path"), Fs = require("fs"), Exec = require("child_process").exec, Spawn = require("child_process").spawn, Rimraf = require("rimraf").sync, Promise = require("es6-promise").Promise, GitHub = require("github-download"), Mkdirp = require("mkdirp") ; var root = Path.resolve(__dirname, "../"); var built = [ ".remote", "node_modules", "packages", ".meteor/local" ]; function installDep(src, dep){ return new Promise(function(resolve, reject){ Mkdirp(src, function(err) { if (err) return reject(err); GitHub(dep, src) .on("error", function(err){}) // XXX handle error .on("end", resolve); }); }); } Vorpal .command("setup") .description("Bootstrap an application. This may take some time...") .option("-c, --clean", "Force rebuild of application(s)") .option("-l, --log [level]", "Sets verbosity level.") .action(function(args, cb) { var app = root; var options = args.options; if (options.clean) { console.log("Cleaning all dependencies..."); for (var i = 0; i < built.length; i++) { var localPath = built[i]; Rimraf(Path.join(app, localPath)); } } var packageFile = require(Path.join(app, "package.json")); var depPromises = []; if (packageFile.apollos && packageFile.apollos.resource) { for (var subDir in packageFile.apollos.resource) { if (!packageFile.apollos.resource.hasOwnProperty(subDir)) continue; var localPath = Path.join(app, subDir); var deps = packageFile.apollos.resource[subDir]; for (var dep in deps) { if (!deps.hasOwnProperty(dep)) continue; console.log("installing resource: " + dep) depPromises.push(installDep(Path.join(localPath, dep), deps[dep])); } } } // var npmPromises = []; // npmPromises.push( // new Promise(function(p, f){ // console.log("installing npm deps"); // var child = Spawn("npm", ["install"], { // cwd: app, stdio: "inherit" // }); // child.on("error", f); // }) // ); return Promise.all(depPromises) .then(function(){ console.log("Holtzmann should be ready to go!"); // console.log("you will need to clone it down manually"); // console.log("\n"); // console.log(" cd " + app + "/.remote/ && git clone https://github.com/NewSpring/ops-settings.git settings"); // console.log("\n"); cb(); }) .catch(function(err) { console.error(err); cb(); }) }); Vorpal .command("run") .description("Start a local server to serve the site and print its address in your console") .option("-p, --port", "Choose a port to run the application") .option("-v, --verbosity [level]", "Sets verbosity level.") .option("-q, --quick", "Only runs the app, not apollos watcher as well") .option("-n, --native", "Runs the native version of the application") .option("--ios", "Run the native app of a given site in the iOS simulator") .option("--android", "Run the native app of a given site in the Android simulator") .option("--device", "Run the native app of a given site on the device of the platform") .option("--production", "Run the application in production mode") .option("--debug", "Run the application in debug mode") .action(function(args, cb) { var app = root; var options = args.options; var packageFile = require(Path.join(app, "package.json")); var env = process.env; env.METEOR_DISABLE_FS_FIBERS = 1; // https://github.com/meteor/meteor/pull/7668#issuecomment-256230102 if (options.debug) env.METEOR_PROFILE = 200; if (options.production) env.NODE_ENV = "production"; if (!options.ios && !options.android && !options.native) env.WEB = true; if (options.native || options.ios || options.android) env.NATIVE = true; var configFile = Path.join(__dirname, "apollos-runtime.json"); if (!Fs.existsSync(configFile)) { Fs.writeFileSync(configFile, JSON.stringify({ WEB: !!env.WEB }, null, 2), "utf8"); } var apolloRuntime = require(configFile); // removes the built files for a rebuild if (!options.quick && !!apolloRuntime.WEB != !!env.WEB) { Rimraf(Path.join(app, ".meteor/local")); } var meteorArgs = [ "--settings" ]; if (options.ios && !options.device) meteorArgs.unshift("run", "ios"); if (options.android && !options.device) meteorArgs.unshift("run", "android"); if (options.ios && options.device) meteorArgs.unshift("run", "ios-device"); if (options.android && options.device) meteorArgs.unshift("run", "android-device"); if ( packageFile.apollos && packageFile.apollos.settings && Fs.existsSync(Path.join(app, packageFile.apollos.settings)) ) { meteorArgs.push(packageFile.apollos.settings) } else { meteorArgs.push(Path.join(app, ".meteor/sample.settings.json")); } function run() { var meteor = Spawn("meteor", meteorArgs, { stdio: "inherit", cwd: app, env: env }); } Fs.writeFileSync(configFile, JSON.stringify({ WEB: !!env.WEB }, null, 2), "utf8"); if (options.production) { console.log("Building apollos in production mode"); meteorArgs.push("--production"); } run(); }); Vorpal .parse(process.argv);
NewSpring/apollos-core
.bin/index.js
JavaScript
mit
5,565
function calculaIMC(altura, peso) { return peso / (altura * altura); } console.log("O seu imc é: " + calculaIMC(prompt("Sua altura? "), prompt("Seu peso? "))); //https://pt.stackoverflow.com/q/327751/101
maniero/SOpt
JavaScript/Algorithm/Bmi2.js
JavaScript
mit
207
/* * Sample Adjuster * */ #include "LimitAdjuster.h" // Sample Simple Adjuster class Sample1 : public SimpleAdjuster { public: const char* GetLimitName() { return GetGVM().IsSA()? "FoodLimit" : nullptr; } void ChangeLimit(int, const std::string& value) { injector::WriteMemory(0xF00D, std::stof(value)); } // Instantiate the adjuster on the global scope } simple_adjuster_sample; // Sample "Complex" Adjuster class Sample2 : public Adjuster { public: // ID enum, those ids are local between each Adjuster, you shouldn't worry about conflicts with other adjusters enum { CoffeeLimit, FoodLimit, IceLimit }; // Get the limit table that we're going to handle const Limit* GetLimits() { static Limit limits[] = { // You could use DEFINE_LIMIT(CoffeeLimit) instead of {...} { "CoffeeLimit", CoffeeLimit }, { "FoodLimit", FoodLimit }, { "IceLimit", IceLimit }, // You could also use FINISH_LIMITS() { nullptr, 0 } }; // This Sample Adjuster can handle only San Andreas game if(GetGVM().IsSA()) return limits; return nullptr; } // Change an specific limit void ChangeLimit(int id, const std::string& value) { switch(id) { case CoffeeLimit: // Changes the cofee limit injector::WriteMemory(0xC0FFEE, std::stoi(value, 0, 0)); break; case FoodLimit: // Changes the food limit injector::WriteMemory(0xF00D, std::stof(value)); break; case IceLimit: // Changes the ice limit injector::WriteMemory<short>(0x1CED, std::stoi(value) % 1337); break; } } // Instantiate the adjuster on the global scope } complex_adjuster_sample;
ThirteenAG/limit_adjuster_gta3vcsa
src/sample/sample.cpp
C++
mit
2,162
<?php if ( ! defined( 'ABSPATH' ) ) { die( '-1' ); } /** * Class Vc_Vendor_Woocommerce * * @since 4.4 * @todo move to separate file and dir. */ class Vc_Vendor_Woocommerce { protected static $product_fields_list = false; protected static $order_fields_list = false; /** * @since 4.4 */ public function load() { if ( class_exists( 'WooCommerce' ) ) { add_action( 'vc_after_mapping', array( $this, 'mapShortcodes', ) ); add_action( 'vc_backend_editor_render', array( $this, 'enqueueJsBackend', ) ); add_action( 'vc_frontend_editor_render', array( $this, 'enqueueJsFrontend', ) ); add_filter( 'vc_grid_item_shortcodes', array( $this, 'mapGridItemShortcodes', ) ); add_action( 'vc_vendor_yoastseo_filter_results', array( $this, 'yoastSeoCompatibility', ) ); add_filter( 'woocommerce_product_tabs', array( $this, 'addContentTabPageEditable', ) ); add_filter( 'woocommerce_shop_manager_editable_roles', array( $this, 'addShopManagerRoleToEditable', ) ); } } /** * @param $rules * @return array */ public function addShopManagerRoleToEditable( $rules ) { $rules[] = 'shop_manager'; return array_unique( $rules ); } /** * @param $tabs * @return mixed */ public function addContentTabPageEditable( $tabs ) { if ( vc_is_page_editable() ) { // Description tab - shows product content $tabs['description'] = array( 'title' => esc_html__( 'Description', 'woocommerce' ), 'priority' => 10, 'callback' => 'woocommerce_product_description_tab', ); } return $tabs; } /** * @since 4.4 */ public function enqueueJsBackend() { wp_enqueue_script( 'vc_vendor_woocommerce_backend', vc_asset_url( 'js/vendors/woocommerce.js' ), array( 'vc-backend-min-js' ), '1.0', true ); } /** * @since 4.4 */ public function enqueueJsFrontend() { wp_enqueue_script( 'vc_vendor_woocommerce_frontend', vc_asset_url( 'js/vendors/woocommerce.js' ), array( 'vc-frontend-editor-min-js' ), '1.0', true ); } /** * Add settings for shortcodes * * @param $tag * * @return array * @since 4.9 * */ public function addShortcodeSettings( $tag ) { $args = array( 'type' => 'post', 'child_of' => 0, 'parent' => '', 'orderby' => 'name', 'order' => 'ASC', 'hide_empty' => false, 'hierarchical' => 1, 'exclude' => '', 'include' => '', 'number' => '', 'taxonomy' => 'product_cat', 'pad_counts' => false, ); $order_by_values = array( '', esc_html__( 'Date', 'js_composer' ) => 'date', esc_html__( 'ID', 'js_composer' ) => 'ID', esc_html__( 'Author', 'js_composer' ) => 'author', esc_html__( 'Title', 'js_composer' ) => 'title', esc_html__( 'Modified', 'js_composer' ) => 'modified', esc_html__( 'Random', 'js_composer' ) => 'rand', esc_html__( 'Comment count', 'js_composer' ) => 'comment_count', esc_html__( 'Menu order', 'js_composer' ) => 'menu_order', esc_html__( 'Menu order & title', 'js_composer' ) => 'menu_order title', esc_html__( 'Include', 'js_composer' ) => 'include', ); $order_way_values = array( '', esc_html__( 'Descending', 'js_composer' ) => 'DESC', esc_html__( 'Ascending', 'js_composer' ) => 'ASC', ); $settings = array(); switch ( $tag ) { case 'woocommerce_cart': $settings = array( 'name' => esc_html__( 'Cart', 'js_composer' ), 'base' => 'woocommerce_cart', 'icon' => 'icon-wpb-woocommerce', 'category' => esc_html__( 'WooCommerce', 'js_composer' ), 'description' => esc_html__( 'Displays the cart contents', 'js_composer' ), 'show_settings_on_create' => false, 'php_class_name' => 'Vc_WooCommerce_NotEditable', ); break; case 'woocommerce_checkout': /** * @shortcode woocommerce_checkout * @description Used on the checkout page, the checkout shortcode displays the checkout process. * @no_params * @not_editable */ $settings = array( 'name' => esc_html__( 'Checkout', 'js_composer' ), 'base' => 'woocommerce_checkout', 'icon' => 'icon-wpb-woocommerce', 'category' => esc_html__( 'WooCommerce', 'js_composer' ), 'description' => esc_html__( 'Displays the checkout', 'js_composer' ), 'show_settings_on_create' => false, 'php_class_name' => 'Vc_WooCommerce_NotEditable', ); break; case 'woocommerce_order_tracking': /** * @shortcode woocommerce_order_tracking * @description Lets a user see the status of an order by entering their order details. * @no_params * @not_editable */ $settings = array( 'name' => esc_html__( 'Order Tracking Form', 'js_composer' ), 'base' => 'woocommerce_order_tracking', 'icon' => 'icon-wpb-woocommerce', 'category' => esc_html__( 'WooCommerce', 'js_composer' ), 'description' => esc_html__( 'Lets a user see the status of an order', 'js_composer' ), 'show_settings_on_create' => false, 'php_class_name' => 'Vc_WooCommerce_NotEditable', ); break; case 'woocommerce_my_account': /** * @shortcode woocommerce_my_account * @description Shows the ‘my account’ section where the customer can view past orders and update their information. * You can specify the number or order to show, it’s set by default to 15 (use -1 to display all orders.) * * @param order_count integer * Current user argument is automatically set using get_user_by( ‘id’, get_current_user_id() ). */ $settings = array( 'name' => esc_html__( 'My Account', 'js_composer' ), 'base' => 'woocommerce_my_account', 'icon' => 'icon-wpb-woocommerce', 'category' => esc_html__( 'WooCommerce', 'js_composer' ), 'description' => esc_html__( 'Shows the "my account" section', 'js_composer' ), 'params' => array( array( 'type' => 'textfield', 'heading' => esc_html__( 'Order count', 'js_composer' ), 'value' => 15, 'save_always' => true, 'param_name' => 'order_count', 'description' => esc_html__( 'You can specify the number or order to show, it\'s set by default to 15 (use -1 to display all orders.)', 'js_composer' ), ), ), ); break; case 'recent_products': /** * @shortcode recent_products * @description Lists recent products – useful on the homepage. The ‘per_page’ shortcode determines how many products * to show on the page and the columns attribute controls how many columns wide the products should be before wrapping. * To learn more about the default ‘orderby’ parameters please reference the WordPress Codex: http://codex.wordpress.org/Class_Reference/WP_Query * * @param per_page integer * @param columns integer * @param orderby array * @param order array */ $settings = array( 'name' => esc_html__( 'Recent products', 'js_composer' ), 'base' => 'recent_products', 'icon' => 'icon-wpb-woocommerce', 'category' => esc_html__( 'WooCommerce', 'js_composer' ), 'description' => esc_html__( 'Lists recent products', 'js_composer' ), 'params' => array( array( 'type' => 'textfield', 'heading' => esc_html__( 'Per page', 'js_composer' ), 'value' => 12, 'save_always' => true, 'param_name' => 'per_page', 'description' => esc_html__( 'The "per_page" shortcode determines how many products to show on the page', 'js_composer' ), ), array( 'type' => 'textfield', 'heading' => esc_html__( 'Columns', 'js_composer' ), 'value' => 4, 'param_name' => 'columns', 'save_always' => true, 'description' => esc_html__( 'The columns attribute controls how many columns wide the products should be before wrapping.', 'js_composer' ), ), array( 'type' => 'dropdown', 'heading' => esc_html__( 'Order by', 'js_composer' ), 'param_name' => 'orderby', 'value' => $order_by_values, 'std' => 'date', // default WC value for recent_products 'save_always' => true, 'description' => sprintf( esc_html__( 'Select how to sort retrieved products. More at %s.', 'js_composer' ), '<a href="https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters" target="_blank">WordPress codex page</a>' ), ), array( 'type' => 'dropdown', 'heading' => esc_html__( 'Sort order', 'js_composer' ), 'param_name' => 'order', 'value' => $order_way_values, 'std' => 'DESC', // default WC value 'save_always' => true, 'description' => sprintf( esc_html__( 'Designates the ascending or descending order. More at %s.', 'js_composer' ), '<a href="https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters" target="_blank">WordPress codex page</a>' ), ), ), ); break; case 'featured_products': /** * @shortcode featured_products * @description Works exactly the same as recent products but displays products which have been set as “featured”. * * @param per_page integer * @param columns integer * @param orderby array * @param order array */ $settings = array( 'name' => esc_html__( 'Featured products', 'js_composer' ), 'base' => 'featured_products', 'icon' => 'icon-wpb-woocommerce', 'category' => esc_html__( 'WooCommerce', 'js_composer' ), 'description' => esc_html__( 'Display products set as "featured"', 'js_composer' ), 'params' => array( array( 'type' => 'textfield', 'heading' => esc_html__( 'Per page', 'js_composer' ), 'value' => 12, 'param_name' => 'per_page', 'save_always' => true, 'description' => esc_html__( 'The "per_page" shortcode determines how many products to show on the page', 'js_composer' ), ), array( 'type' => 'textfield', 'heading' => esc_html__( 'Columns', 'js_composer' ), 'value' => 4, 'param_name' => 'columns', 'save_always' => true, 'description' => esc_html__( 'The columns attribute controls how many columns wide the products should be before wrapping.', 'js_composer' ), ), array( 'type' => 'dropdown', 'heading' => esc_html__( 'Order by', 'js_composer' ), 'param_name' => 'orderby', 'value' => $order_by_values, 'std' => 'date', // default WC value 'save_always' => true, 'description' => sprintf( esc_html__( 'Select how to sort retrieved products. More at %s.', 'js_composer' ), '<a href="https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters" target="_blank">WordPress codex page</a>' ), ), array( 'type' => 'dropdown', 'heading' => esc_html__( 'Sort order', 'js_composer' ), 'param_name' => 'order', 'value' => $order_way_values, 'std' => 'DESC', // default WC value 'save_always' => true, 'description' => sprintf( esc_html__( 'Designates the ascending or descending order. More at %s.', 'js_composer' ), '<a href="s://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters" target="_blank">WordPress codex page</a>' ), ), ), ); break; case 'product': /** * @shortcode product * @description Show a single product by ID or SKU. * * @param id integer * @param sku string * If the product isn’t showing, make sure it isn’t set to Hidden in the Catalog Visibility. * To find the Product ID, go to the Product > Edit screen and look in the URL for the postid= . */ $settings = array( 'name' => esc_html__( 'Product', 'js_composer' ), 'base' => 'product', 'icon' => 'icon-wpb-woocommerce', 'category' => esc_html__( 'WooCommerce', 'js_composer' ), 'description' => esc_html__( 'Show a single product by ID or SKU', 'js_composer' ), 'params' => array( array( 'type' => 'autocomplete', 'heading' => esc_html__( 'Select identificator', 'js_composer' ), 'param_name' => 'id', 'description' => esc_html__( 'Input product ID or product SKU or product title to see suggestions', 'js_composer' ), ), array( 'type' => 'hidden', // This will not show on render, but will be used when defining value for autocomplete 'param_name' => 'sku', ), ), ); break; case 'products': $settings = array( 'name' => esc_html__( 'Products', 'js_composer' ), 'base' => 'products', 'icon' => 'icon-wpb-woocommerce', 'category' => esc_html__( 'WooCommerce', 'js_composer' ), 'description' => esc_html__( 'Show multiple products by ID or SKU.', 'js_composer' ), 'params' => array( array( 'type' => 'textfield', 'heading' => esc_html__( 'Columns', 'js_composer' ), 'value' => 4, 'param_name' => 'columns', 'save_always' => true, ), array( 'type' => 'dropdown', 'heading' => esc_html__( 'Order by', 'js_composer' ), 'param_name' => 'orderby', 'value' => $order_by_values, 'std' => 'title', // Default WC value 'save_always' => true, 'description' => sprintf( esc_html__( 'Select how to sort retrieved products. More at %s. Default by Title', 'js_composer' ), '<a href="https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters" target="_blank">WordPress codex page</a>' ), ), array( 'type' => 'dropdown', 'heading' => esc_html__( 'Sort order', 'js_composer' ), 'param_name' => 'order', 'value' => $order_way_values, 'std' => 'ASC', // default WC value 'save_always' => true, 'description' => sprintf( esc_html__( 'Designates the ascending or descending order. More at %s. Default by ASC', 'js_composer' ), '<a href="https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters" target="_blank">WordPress codex page</a>' ), ), array( 'type' => 'autocomplete', 'heading' => esc_html__( 'Products', 'js_composer' ), 'param_name' => 'ids', 'settings' => array( 'multiple' => true, 'sortable' => true, 'unique_values' => true, // In UI show results except selected. NB! You should manually check values in backend ), 'save_always' => true, 'description' => esc_html__( 'Enter List of Products', 'js_composer' ), ), array( 'type' => 'hidden', 'param_name' => 'skus', ), ), ); break; case 'add_to_cart': /** * @shortcode add_to_cart * @description Show the price and add to cart button of a single product by ID (or SKU). * * @param id integer * @param sku string * @param style string * If the product isn’t showing, make sure it isn’t set to Hidden in the Catalog Visibility. */ $settings = array( 'name' => esc_html__( 'Add to cart', 'js_composer' ), 'base' => 'add_to_cart', 'icon' => 'icon-wpb-woocommerce', 'category' => esc_html__( 'WooCommerce', 'js_composer' ), 'description' => esc_html__( 'Show multiple products by ID or SKU', 'js_composer' ), 'params' => array( array( 'type' => 'autocomplete', 'heading' => esc_html__( 'Select identificator', 'js_composer' ), 'param_name' => 'id', 'description' => esc_html__( 'Input product ID or product SKU or product title to see suggestions', 'js_composer' ), ), array( 'type' => 'hidden', 'param_name' => 'sku', ), array( 'type' => 'textfield', 'heading' => esc_html__( 'Wrapper inline style', 'js_composer' ), 'param_name' => 'style', ), ), ); break; case 'add_to_cart_url': /** * @shortcode add_to_cart_url * @description Print the URL on the add to cart button of a single product by ID. * * @param id integer * @param sku string */ $settings = array( 'name' => esc_html__( 'Add to cart URL', 'js_composer' ), 'base' => 'add_to_cart_url', 'icon' => 'icon-wpb-woocommerce', 'category' => esc_html__( 'WooCommerce', 'js_composer' ), 'description' => esc_html__( 'Show URL on the add to cart button', 'js_composer' ), 'params' => array( array( 'type' => 'autocomplete', 'heading' => esc_html__( 'Select identificator', 'js_composer' ), 'param_name' => 'id', 'description' => esc_html__( 'Input product ID or product SKU or product title to see suggestions', 'js_composer' ), ), array( 'type' => 'hidden', 'param_name' => 'sku', ), ), ); break; case 'product_page': /** * @shortcode product_page * @description Show a full single product page by ID or SKU. * * @param id integer * @param sku string */ $settings = array( 'name' => esc_html__( 'Product page', 'js_composer' ), 'base' => 'product_page', 'icon' => 'icon-wpb-woocommerce', 'category' => esc_html__( 'WooCommerce', 'js_composer' ), 'description' => esc_html__( 'Show single product by ID or SKU', 'js_composer' ), 'params' => array( array( 'type' => 'autocomplete', 'heading' => esc_html__( 'Select identificator', 'js_composer' ), 'param_name' => 'id', 'description' => esc_html__( 'Input product ID or product SKU or product title to see suggestions', 'js_composer' ), ), array( 'type' => 'hidden', 'param_name' => 'sku', ), ), ); break; case 'product_category': /** * @shortcode product_category * @description Show multiple products in a category by slug. * * @param per_page integer * @param columns integer * @param orderby array * @param order array * @param category string * Go to: WooCommerce > Products > Categories to find the slug column. */ // All this move to product $categories = get_categories( $args ); $product_categories_dropdown = array(); $this->getCategoryChildsFull( 0, $categories, 0, $product_categories_dropdown ); $settings = array( 'name' => esc_html__( 'Product category', 'js_composer' ), 'base' => 'product_category', 'icon' => 'icon-wpb-woocommerce', 'category' => esc_html__( 'WooCommerce', 'js_composer' ), 'description' => esc_html__( 'Show multiple products in a category', 'js_composer' ), 'params' => array( array( 'type' => 'textfield', 'heading' => esc_html__( 'Per page', 'js_composer' ), 'value' => 12, 'save_always' => true, 'param_name' => 'per_page', 'description' => esc_html__( 'How much items per page to show', 'js_composer' ), ), array( 'type' => 'textfield', 'heading' => esc_html__( 'Columns', 'js_composer' ), 'value' => 4, 'save_always' => true, 'param_name' => 'columns', 'description' => esc_html__( 'How much columns grid', 'js_composer' ), ), array( 'type' => 'dropdown', 'heading' => esc_html__( 'Order by', 'js_composer' ), 'param_name' => 'orderby', 'value' => $order_by_values, 'std' => 'menu_order title', // Default WC value 'save_always' => true, 'description' => sprintf( esc_html__( 'Select how to sort retrieved products. More at %s.', 'js_composer' ), '<a href="s://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters" target="_blank">WordPress codex page</a>' ), ), array( 'type' => 'dropdown', 'heading' => esc_html__( 'Sort order', 'js_composer' ), 'param_name' => 'order', 'value' => $order_way_values, 'std' => 'ASC', // default WC value 'save_always' => true, 'description' => sprintf( esc_html__( 'Designates the ascending or descending order. More at %s.', 'js_composer' ), '<a href="https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters" target="_blank">WordPress codex page</a>' ), ), array( 'type' => 'dropdown', 'heading' => esc_html__( 'Category', 'js_composer' ), 'value' => $product_categories_dropdown, 'param_name' => 'category', 'save_always' => true, 'description' => esc_html__( 'Product category list', 'js_composer' ), ), ), ); break; case 'product_categories': $settings = array( 'name' => esc_html__( 'Product categories', 'js_composer' ), 'base' => 'product_categories', 'icon' => 'icon-wpb-woocommerce', 'category' => esc_html__( 'WooCommerce', 'js_composer' ), 'description' => esc_html__( 'Display product categories loop', 'js_composer' ), 'params' => array( array( 'type' => 'textfield', 'heading' => esc_html__( 'Number', 'js_composer' ), 'param_name' => 'number', 'description' => esc_html__( 'The `number` field is used to display the number of products.', 'js_composer' ), ), array( 'type' => 'dropdown', 'heading' => esc_html__( 'Order by', 'js_composer' ), 'param_name' => 'orderby', 'value' => $order_by_values, 'std' => 'name', // default WC value 'save_always' => true, 'description' => sprintf( esc_html__( 'Select how to sort retrieved products. More at %s.', 'js_composer' ), '<a href="https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters" target="_blank">WordPress codex page</a>' ), ), array( 'type' => 'dropdown', 'heading' => esc_html__( 'Sort order', 'js_composer' ), 'param_name' => 'order', 'value' => $order_way_values, 'std' => 'ASC', // default WC value 'save_always' => true, 'description' => sprintf( esc_html__( 'Designates the ascending or descending order. More at %s.', 'js_composer' ), '<a href="https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters" target="_blank">WordPress codex page</a>' ), ), array( 'type' => 'textfield', 'heading' => esc_html__( 'Columns', 'js_composer' ), 'value' => 4, 'param_name' => 'columns', 'save_always' => true, 'description' => esc_html__( 'How much columns grid', 'js_composer' ), ), array( 'type' => 'textfield', 'heading' => esc_html__( 'Number', 'js_composer' ), 'param_name' => 'hide_empty', 'description' => esc_html__( 'Hide empty', 'js_composer' ), ), array( 'type' => 'autocomplete', 'heading' => esc_html__( 'Categories', 'js_composer' ), 'param_name' => 'ids', 'settings' => array( 'multiple' => true, 'sortable' => true, ), 'save_always' => true, 'description' => esc_html__( 'List of product categories', 'js_composer' ), ), ), ); break; case 'sale_products': /** * @shortcode sale_products * @description List all products on sale. * * @param per_page integer * @param columns integer * @param orderby array * @param order array */ $settings = array( 'name' => esc_html__( 'Sale products', 'js_composer' ), 'base' => 'sale_products', 'icon' => 'icon-wpb-woocommerce', 'category' => esc_html__( 'WooCommerce', 'js_composer' ), 'description' => esc_html__( 'List all products on sale', 'js_composer' ), 'params' => array( array( 'type' => 'textfield', 'heading' => esc_html__( 'Per page', 'js_composer' ), 'value' => 12, 'save_always' => true, 'param_name' => 'per_page', 'description' => esc_html__( 'How much items per page to show', 'js_composer' ), ), array( 'type' => 'textfield', 'heading' => esc_html__( 'Columns', 'js_composer' ), 'value' => 4, 'save_always' => true, 'param_name' => 'columns', 'description' => esc_html__( 'How much columns grid', 'js_composer' ), ), array( 'type' => 'dropdown', 'heading' => esc_html__( 'Order by', 'js_composer' ), 'param_name' => 'orderby', 'value' => $order_by_values, 'std' => 'title', // default WC value 'save_always' => true, 'description' => sprintf( esc_html__( 'Select how to sort retrieved products. More at %s.', 'js_composer' ), '<a href="https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters" target="_blank">WordPress codex page</a>' ), ), array( 'type' => 'dropdown', 'heading' => esc_html__( 'Sort order', 'js_composer' ), 'param_name' => 'order', 'value' => $order_way_values, 'std' => 'ASC', // default WC value 'save_always' => true, 'description' => sprintf( esc_html__( 'Designates the ascending or descending order. More at %s.', 'js_composer' ), '<a href="https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters" target="_blank">WordPress codex page</a>' ), ), ), ); break; case 'best_selling_products': /** * @shortcode best_selling_products * @description List best selling products on sale. * * @param per_page integer * @param columns integer */ $settings = array( 'name' => esc_html__( 'Best Selling Products', 'js_composer' ), 'base' => 'best_selling_products', 'icon' => 'icon-wpb-woocommerce', 'category' => esc_html__( 'WooCommerce', 'js_composer' ), 'description' => esc_html__( 'List best selling products on sale', 'js_composer' ), 'params' => array( array( 'type' => 'textfield', 'heading' => esc_html__( 'Per page', 'js_composer' ), 'value' => 12, 'param_name' => 'per_page', 'save_always' => true, 'description' => esc_html__( 'How much items per page to show', 'js_composer' ), ), array( 'type' => 'textfield', 'heading' => esc_html__( 'Columns', 'js_composer' ), 'value' => 4, 'param_name' => 'columns', 'save_always' => true, 'description' => esc_html__( 'How much columns grid', 'js_composer' ), ), ), ); break; case 'top_rated_products': /** * @shortcode top_rated_products * @description List top rated products on sale. * * @param per_page integer * @param columns integer * @param orderby array * @param order array */ $settings = array( 'name' => esc_html__( 'Top Rated Products', 'js_composer' ), 'base' => 'top_rated_products', 'icon' => 'icon-wpb-woocommerce', 'category' => esc_html__( 'WooCommerce', 'js_composer' ), 'description' => esc_html__( 'List all products on sale', 'js_composer' ), 'params' => array( array( 'type' => 'textfield', 'heading' => esc_html__( 'Per page', 'js_composer' ), 'value' => 12, 'param_name' => 'per_page', 'save_always' => true, 'description' => esc_html__( 'How much items per page to show', 'js_composer' ), ), array( 'type' => 'textfield', 'heading' => esc_html__( 'Columns', 'js_composer' ), 'value' => 4, 'param_name' => 'columns', 'save_always' => true, 'description' => esc_html__( 'How much columns grid', 'js_composer' ), ), array( 'type' => 'dropdown', 'heading' => esc_html__( 'Order by', 'js_composer' ), 'param_name' => 'orderby', 'value' => $order_by_values, 'std' => 'title', // default WC value 'save_always' => true, 'description' => sprintf( esc_html__( 'Select how to sort retrieved products. More at %s.', 'js_composer' ), '<a href="https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters" target="_blank">WordPress codex page</a>' ), ), array( 'type' => 'dropdown', 'heading' => esc_html__( 'Sort order', 'js_composer' ), 'param_name' => 'order', 'value' => $order_way_values, 'std' => 'ASC', // Default WP Value 'save_always' => true, 'description' => sprintf( esc_html__( 'Designates the ascending or descending order. More at %s.', 'js_composer' ), '<a href="https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters" target="_blank">WordPress codex page</a>' ), ), ), ); break; case 'product_attribute': /** * @shortcode product_attribute * @description List products with an attribute shortcode. * * @param per_page integer * @param columns integer * @param orderby array * @param order array * @param attribute string * @param filter string */ $attributes_tax = wc_get_attribute_taxonomies(); $attributes = array(); foreach ( $attributes_tax as $attribute ) { $attributes[ $attribute->attribute_label ] = $attribute->attribute_name; } $settings = array( 'name' => esc_html__( 'Product Attribute', 'js_composer' ), 'base' => 'product_attribute', 'icon' => 'icon-wpb-woocommerce', 'category' => esc_html__( 'WooCommerce', 'js_composer' ), 'description' => esc_html__( 'List products with an attribute shortcode', 'js_composer' ), 'params' => array( array( 'type' => 'textfield', 'heading' => esc_html__( 'Per page', 'js_composer' ), 'value' => 12, 'param_name' => 'per_page', 'save_always' => true, 'description' => esc_html__( 'How much items per page to show', 'js_composer' ), ), array( 'type' => 'textfield', 'heading' => esc_html__( 'Columns', 'js_composer' ), 'value' => 4, 'param_name' => 'columns', 'save_always' => true, 'description' => esc_html__( 'How much columns grid', 'js_composer' ), ), array( 'type' => 'dropdown', 'heading' => esc_html__( 'Order by', 'js_composer' ), 'param_name' => 'orderby', 'value' => $order_by_values, 'std' => 'title', // default WC value 'save_always' => true, 'description' => sprintf( esc_html__( 'Select how to sort retrieved products. More at %s.', 'js_composer' ), '<a href="https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters" target="_blank">WordPress codex page</a>' ), ), array( 'type' => 'dropdown', 'heading' => esc_html__( 'Sort order', 'js_composer' ), 'param_name' => 'order', 'value' => $order_way_values, 'std' => 'ASC', // Default WC value 'save_always' => true, 'description' => sprintf( esc_html__( 'Designates the ascending or descending order. More at %s.', 'js_composer' ), '<a href="https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters" target="_blank">WordPress codex page</a>' ), ), array( 'type' => 'dropdown', 'heading' => esc_html__( 'Attribute', 'js_composer' ), 'param_name' => 'attribute', 'value' => $attributes, 'save_always' => true, 'description' => esc_html__( 'List of product taxonomy attribute', 'js_composer' ), ), array( 'type' => 'checkbox', 'heading' => esc_html__( 'Filter', 'js_composer' ), 'param_name' => 'filter', 'value' => array( 'empty' => 'empty' ), 'save_always' => true, 'description' => esc_html__( 'Taxonomy values', 'js_composer' ), 'dependency' => array( 'callback' => 'vcWoocommerceProductAttributeFilterDependencyCallback', ), ), ), ); break; case 'related_products': /** * @shortcode related_products * @description List related products. * * @param per_page integer * @param columns integer * @param orderby array * @param order array */ /* we need to detect post type to show this shortcode */ global $post, $typenow, $current_screen; $post_type = ''; if ( $post && $post->post_type ) { //we have a post so we can just get the post type from that $post_type = $post->post_type; } elseif ( $typenow ) { //check the global $typenow - set in admin.php $post_type = $typenow; } elseif ( $current_screen && $current_screen->post_type ) { //check the global $current_screen object - set in sceen.php $post_type = $current_screen->post_type; } elseif ( isset( $_REQUEST['post_type'] ) ) { //lastly check the post_type querystring $post_type = sanitize_key( $_REQUEST['post_type'] ); //we do not know the post type! } $settings = array( 'name' => esc_html__( 'Related Products', 'js_composer' ), 'base' => 'related_products', 'icon' => 'icon-wpb-woocommerce', 'content_element' => 'product' === $post_type, // disable showing if not product type 'category' => esc_html__( 'WooCommerce', 'js_composer' ), 'description' => esc_html__( 'List related products', 'js_composer' ), 'params' => array( array( 'type' => 'textfield', 'heading' => esc_html__( 'Per page', 'js_composer' ), 'value' => 12, 'save_always' => true, 'param_name' => 'per_page', 'description' => esc_html__( 'Please note: the "per_page" shortcode argument will determine how many products are shown on a page. This will not add pagination to the shortcode. ', 'js_composer' ), ), array( 'type' => 'textfield', 'heading' => esc_html__( 'Columns', 'js_composer' ), 'value' => 4, 'save_always' => true, 'param_name' => 'columns', 'description' => esc_html__( 'How much columns grid', 'js_composer' ), ), array( 'type' => 'dropdown', 'heading' => esc_html__( 'Order by', 'js_composer' ), 'param_name' => 'orderby', 'value' => $order_by_values, 'std' => 'rand', // default WC value 'save_always' => true, 'description' => sprintf( esc_html__( 'Select how to sort retrieved products. More at %s.', 'js_composer' ), '<a href="https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters" target="_blank">WordPress codex page</a>' ), ), array( 'type' => 'dropdown', 'heading' => esc_html__( 'Sort order', 'js_composer' ), 'param_name' => 'order', 'value' => $order_way_values, 'std' => 'DESC', // Default WC value 'save_always' => true, 'description' => sprintf( esc_html__( 'Designates the ascending or descending order. More at %s.', 'js_composer' ), '<a href="https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters" target="_blank">WordPress codex page</a>' ), ), ), ); break; } return $settings; } /** * Add woocommerce shortcodes and hooks/filters for it. * @since 4.4 */ public function mapShortcodes() { add_action( 'wp_ajax_vc_woocommerce_get_attribute_terms', array( $this, 'getAttributeTermsAjax', ) ); $tags = array( 'woocommerce_cart', 'woocommerce_checkout', 'woocommerce_order_tracking', 'woocommerce_my_account', 'recent_products', 'featured_products', 'product', 'products', 'add_to_cart', 'add_to_cart_url', 'product_page', 'product_category', 'product_categories', 'sale_products', 'best_selling_products', 'top_rated_products', 'product_attribute', 'related_products', ); while ( $tag = current( $tags ) ) { vc_lean_map( $tag, array( $this, 'addShortcodeSettings', ) ); next( $tags ); } //Filters For autocomplete param: //For suggestion: vc_autocomplete_[shortcode_name]_[param_name]_callback add_filter( 'vc_autocomplete_product_id_callback', array( $this, 'productIdAutocompleteSuggester', ), 10, 1 ); // Get suggestion(find). Must return an array add_filter( 'vc_autocomplete_product_id_render', array( $this, 'productIdAutocompleteRender', ), 10, 1 ); // Render exact product. Must return an array (label,value) //For param: ID default value filter add_filter( 'vc_form_fields_render_field_product_id_param_value', array( $this, 'productIdDefaultValue', ), 10, 4 ); // Defines default value for param if not provided. Takes from other param value. //Filters For autocomplete param: //For suggestion: vc_autocomplete_[shortcode_name]_[param_name]_callback add_filter( 'vc_autocomplete_products_ids_callback', array( $this, 'productIdAutocompleteSuggester', ), 10, 1 ); // Get suggestion(find). Must return an array add_filter( 'vc_autocomplete_products_ids_render', array( $this, 'productIdAutocompleteRender', ), 10, 1 ); // Render exact product. Must return an array (label,value) //For param: ID default value filter add_filter( 'vc_form_fields_render_field_products_ids_param_value', array( $this, 'productsIdsDefaultValue', ), 10, 4 ); // Defines default value for param if not provided. Takes from other param value. //Filters For autocomplete param: Exactly Same as "product" shortcode //For suggestion: vc_autocomplete_[shortcode_name]_[param_name]_callback add_filter( 'vc_autocomplete_add_to_cart_id_callback', array( $this, 'productIdAutocompleteSuggester', ), 10, 1 ); // Get suggestion(find). Must return an array add_filter( 'vc_autocomplete_add_to_cart_id_render', array( $this, 'productIdAutocompleteRender', ), 10, 1 ); // Render exact product. Must return an array (label,value) //For param: ID default value filter add_filter( 'vc_form_fields_render_field_add_to_cart_id_param_value', array( $this, 'productIdDefaultValue', ), 10, 4 ); // Defines default value for param if not provided. Takes from other param value. //Filters For autocomplete param: Exactly Same as "product" shortcode //For suggestion: vc_autocomplete_[shortcode_name]_[param_name]_callback add_filter( 'vc_autocomplete_add_to_cart_url_id_callback', array( $this, 'productIdAutocompleteSuggester', ), 10, 1 ); // Get suggestion(find). Must return an array add_filter( 'vc_autocomplete_add_to_cart_url_id_render', array( $this, 'productIdAutocompleteRender', ), 10, 1 ); // Render exact product. Must return an array (label,value) //For param: ID default value filter add_filter( 'vc_form_fields_render_field_add_to_cart_url_id_param_value', array( $this, 'productIdDefaultValue', ), 10, 4 ); // Defines default value for param if not provided. Takes from other param value. //Filters For autocomplete param: Exactly Same as "product" shortcode //For suggestion: vc_autocomplete_[shortcode_name]_[param_name]_callback add_filter( 'vc_autocomplete_product_page_id_callback', array( $this, 'productIdAutocompleteSuggester', ), 10, 1 ); // Get suggestion(find). Must return an array add_filter( 'vc_autocomplete_product_page_id_render', array( $this, 'productIdAutocompleteRender', ), 10, 1 ); // Render exact product. Must return an array (label,value) //For param: ID default value filter add_filter( 'vc_form_fields_render_field_product_page_id_param_value', array( $this, 'productIdDefaultValue', ), 10, 4 ); // Defines default value for param if not provided. Takes from other param value. //Filters For autocomplete param: //For suggestion: vc_autocomplete_[shortcode_name]_[param_name]_callback add_filter( 'vc_autocomplete_product_category_category_callback', array( $this, 'productCategoryCategoryAutocompleteSuggesterBySlug', ), 10, 1 ); // Get suggestion(find). Must return an array add_filter( 'vc_autocomplete_product_category_category_render', array( $this, 'productCategoryCategoryRenderBySlugExact', ), 10, 1 ); // Render exact category by Slug. Must return an array (label,value) //Filters For autocomplete param: //For suggestion: vc_autocomplete_[shortcode_name]_[param_name]_callback add_filter( 'vc_autocomplete_product_categories_ids_callback', array( $this, 'productCategoryCategoryAutocompleteSuggester', ), 10, 1 ); // Get suggestion(find). Must return an array add_filter( 'vc_autocomplete_product_categories_ids_render', array( $this, 'productCategoryCategoryRenderByIdExact', ), 10, 1 ); // Render exact category by id. Must return an array (label,value) //For param: "filter" param value //vc_form_fields_render_field_{shortcode_name}_{param_name}_param add_filter( 'vc_form_fields_render_field_product_attribute_filter_param', array( $this, 'productAttributeFilterParamValue', ), 10, 4 ); // Defines default value for param if not provided. Takes from other param value. } /** * @param array $shortcodes * @return array|mixed */ /** * @param array $shortcodes * @return array|mixed */ public function mapGridItemShortcodes( array $shortcodes ) { require_once vc_path_dir( 'VENDORS_DIR', 'plugins/woocommerce/class-vc-gitem-woocommerce-shortcode.php' ); require_once vc_path_dir( 'VENDORS_DIR', 'plugins/woocommerce/grid-item-attributes.php' ); $wc_shortcodes = include vc_path_dir( 'VENDORS_DIR', 'plugins/woocommerce/grid-item-shortcodes.php' ); return $shortcodes + $wc_shortcodes; } /** * Defines default value for param if not provided. Takes from other param value. * @param array $param_settings * @param $current_value * @param $map_settings * @param $atts * * @return array * @since 4.4 * */ public function productAttributeFilterParamValue( $param_settings, $current_value, $map_settings, $atts ) { if ( isset( $atts['attribute'] ) ) { $value = $this->getAttributeTerms( $atts['attribute'] ); if ( is_array( $value ) && ! empty( $value ) ) { $param_settings['value'] = $value; } } return $param_settings; } /** * Get attribute terms hooks from ajax request * @since 4.4 */ public function getAttributeTermsAjax() { vc_user_access()->checkAdminNonce()->validateDie()->wpAny( 'edit_posts', 'edit_pages' )->validateDie(); $attribute = vc_post_param( 'attribute' ); $values = $this->getAttributeTerms( $attribute ); $param = array( 'param_name' => 'filter', 'type' => 'checkbox', ); $param_line = ''; foreach ( $values as $label => $v ) { $param_line .= ' <label class="vc_checkbox-label"><input id="' . $param['param_name'] . '-' . $v . '" value="' . $v . '" class="wpb_vc_param_value ' . $param['param_name'] . ' ' . $param['type'] . '" type="checkbox" name="' . $param['param_name'] . '"' . '> ' . $label . '</label>'; } die( wp_json_encode( $param_line ) ); } /** * Get attribute terms suggester * @param $attribute * * @return array * @since 4.4 * */ public function getAttributeTerms( $attribute ) { $terms = get_terms( 'pa_' . $attribute ); // return array. take slug $data = array(); if ( ! empty( $terms ) && empty( $terms->errors ) ) { foreach ( $terms as $term ) { $data[ $term->name ] = $term->slug; } } return $data; } /** * Get lists of categories. * @param $parent_id * @param array $array * @param $level * @param array $dropdown - passed by reference * @return array * @since 4.5.3 * */ protected function getCategoryChildsFull( $parent_id, $array, $level, &$dropdown ) { $keys = array_keys( $array ); $i = 0; while ( $i < count( $array ) ) { $key = $keys[ $i ]; $item = $array[ $key ]; $i ++; if ( $item->category_parent == $parent_id ) { $name = str_repeat( '- ', $level ) . $item->name; $value = $item->slug; $dropdown[] = array( 'label' => $name . '(' . $item->term_id . ')', 'value' => $value, ); unset( $array[ $key ] ); $array = $this->getCategoryChildsFull( $item->term_id, $array, $level + 1, $dropdown ); $keys = array_keys( $array ); $i = 0; } } return $array; } /** * Replace single product sku to id. * @param $current_value * @param $param_settings * @param $map_settings * @param $atts * * @return bool|string * @since 4.4 * */ public function productIdDefaultValue( $current_value, $param_settings, $map_settings, $atts ) { $value = trim( $current_value ); if ( strlen( trim( $current_value ) ) === 0 && isset( $atts['sku'] ) && strlen( $atts['sku'] ) > 0 ) { $value = $this->productIdDefaultValueFromSkuToId( $atts['sku'] ); } return $value; } /** * Replaces product skus to id's. * @param $current_value * @param $param_settings * @param $map_settings * @param $atts * * @return string * @since 4.4 * */ public function productsIdsDefaultValue( $current_value, $param_settings, $map_settings, $atts ) { $value = trim( $current_value ); if ( strlen( trim( $value ) ) === 0 && isset( $atts['skus'] ) && strlen( $atts['skus'] ) > 0 ) { $data = array(); $skus = $atts['skus']; $skus_array = explode( ',', $skus ); foreach ( $skus_array as $sku ) { $id = $this->productIdDefaultValueFromSkuToId( trim( $sku ) ); if ( is_numeric( $id ) ) { $data[] = $id; } } if ( ! empty( $data ) ) { $values = explode( ',', $value ); $values = array_merge( $values, $data ); $value = implode( ',', $values ); } } return $value; } /** * Suggester for autocomplete by id/name/title/sku * @param $query * * @return array - id's from products with title/sku. * @since 4.4 * */ public function productIdAutocompleteSuggester( $query ) { global $wpdb; $product_id = (int) $query; $post_meta_infos = $wpdb->get_results( $wpdb->prepare( "SELECT a.ID AS id, a.post_title AS title, b.meta_value AS sku FROM {$wpdb->posts} AS a LEFT JOIN ( SELECT meta_value, post_id FROM {$wpdb->postmeta} WHERE `meta_key` = '_sku' ) AS b ON b.post_id = a.ID WHERE a.post_type = 'product' AND ( a.ID = '%d' OR b.meta_value LIKE '%%%s%%' OR a.post_title LIKE '%%%s%%' )", $product_id > 0 ? $product_id : - 1, stripslashes( $query ), stripslashes( $query ) ), ARRAY_A ); $results = array(); if ( is_array( $post_meta_infos ) && ! empty( $post_meta_infos ) ) { foreach ( $post_meta_infos as $value ) { $data = array(); $data['value'] = $value['id']; $data['label'] = esc_html__( 'Id', 'js_composer' ) . ': ' . $value['id'] . ( ( strlen( $value['title'] ) > 0 ) ? ' - ' . esc_html__( 'Title', 'js_composer' ) . ': ' . $value['title'] : '' ) . ( ( strlen( $value['sku'] ) > 0 ) ? ' - ' . esc_html__( 'Sku', 'js_composer' ) . ': ' . $value['sku'] : '' ); $results[] = $data; } } return $results; } /** * Find product by id * @param $query * * @return bool|array * @since 4.4 * */ public function productIdAutocompleteRender( $query ) { $query = trim( $query['value'] ); // get value from requested if ( ! empty( $query ) ) { // get product $product_object = wc_get_product( (int) $query ); if ( is_object( $product_object ) ) { $product_sku = $product_object->get_sku(); $product_title = $product_object->get_title(); $product_id = $product_object->get_id(); $product_sku_display = ''; if ( ! empty( $product_sku ) ) { $product_sku_display = ' - ' . esc_html__( 'Sku', 'js_composer' ) . ': ' . $product_sku; } $product_title_display = ''; if ( ! empty( $product_title ) ) { $product_title_display = ' - ' . esc_html__( 'Title', 'js_composer' ) . ': ' . $product_title; } $product_id_display = esc_html__( 'Id', 'js_composer' ) . ': ' . $product_id; $data = array(); $data['value'] = $product_id; $data['label'] = $product_id_display . $product_title_display . $product_sku_display; return ! empty( $data ) ? $data : false; } return false; } return false; } /** * Return ID of product by provided SKU of product. * @param $query * * @return bool * @since 4.4 * */ public function productIdDefaultValueFromSkuToId( $query ) { $result = $this->productIdAutocompleteSuggesterExactSku( $query ); return isset( $result['value'] ) ? $result['value'] : false; } /** * Find product by SKU * @param $query * * @return bool|array * @since 4.4 * */ public function productIdAutocompleteSuggesterExactSku( $query ) { global $wpdb; $query = trim( $query ); $product_id = $wpdb->get_var( $wpdb->prepare( "SELECT post_id FROM {$wpdb->postmeta} WHERE meta_key='_sku' AND meta_value='%s' LIMIT 1", stripslashes( $query ) ) ); $product_data = get_post( $product_id ); if ( 'product' !== $product_data->post_type ) { return ''; } $product_object = wc_get_product( $product_data ); if ( is_object( $product_object ) ) { $product_sku = $product_object->get_sku(); $product_title = $product_object->get_title(); $product_id = $product_object->get_id(); $product_sku_display = ''; if ( ! empty( $product_sku ) ) { $product_sku_display = ' - ' . esc_html__( 'Sku', 'js_composer' ) . ': ' . $product_sku; } $product_title_display = ''; if ( ! empty( $product_title ) ) { $product_title_display = ' - ' . esc_html__( 'Title', 'js_composer' ) . ': ' . $product_title; } $product_id_display = esc_html__( 'Id', 'js_composer' ) . ': ' . $product_id; $data = array(); $data['value'] = $product_id; $data['label'] = $product_id_display . $product_title_display . $product_sku_display; return ! empty( $data ) ? $data : false; } return false; } /** * Autocomplete suggester to search product category by name/slug or id. * @param $query * @param bool $slug - determines what output is needed * default false - return id of product category * true - return slug of product category * * @return array * @since 4.4 * */ public function productCategoryCategoryAutocompleteSuggester( $query, $slug = false ) { global $wpdb; $cat_id = (int) $query; $query = trim( $query ); $post_meta_infos = $wpdb->get_results( $wpdb->prepare( "SELECT a.term_id AS id, b.name as name, b.slug AS slug FROM {$wpdb->term_taxonomy} AS a INNER JOIN {$wpdb->terms} AS b ON b.term_id = a.term_id WHERE a.taxonomy = 'product_cat' AND (a.term_id = '%d' OR b.slug LIKE '%%%s%%' OR b.name LIKE '%%%s%%' )", $cat_id > 0 ? $cat_id : - 1, stripslashes( $query ), stripslashes( $query ) ), ARRAY_A ); $result = array(); if ( is_array( $post_meta_infos ) && ! empty( $post_meta_infos ) ) { foreach ( $post_meta_infos as $value ) { $data = array(); $data['value'] = $slug ? $value['slug'] : $value['id']; $data['label'] = esc_html__( 'Id', 'js_composer' ) . ': ' . $value['id'] . ( ( strlen( $value['name'] ) > 0 ) ? ' - ' . esc_html__( 'Name', 'js_composer' ) . ': ' . $value['name'] : '' ) . ( ( strlen( $value['slug'] ) > 0 ) ? ' - ' . esc_html__( 'Slug', 'js_composer' ) . ': ' . $value['slug'] : '' ); $result[] = $data; } } return $result; } /** * Search product category by id * @param $query * * @return bool|array * @since 4.4 * */ public function productCategoryCategoryRenderByIdExact( $query ) { $query = $query['value']; $cat_id = (int) $query; $term = get_term( $cat_id, 'product_cat' ); return $this->productCategoryTermOutput( $term ); } /** * Suggester for autocomplete to find product category by id/name/slug but return found product category SLUG * @param $query * * @return array - slug of products categories. * @since 4.4 * */ public function productCategoryCategoryAutocompleteSuggesterBySlug( $query ) { $result = $this->productCategoryCategoryAutocompleteSuggester( $query, true ); return $result; } /** * Search product category by slug. * @param $query * * @return bool|array * @since 4.4 * */ public function productCategoryCategoryRenderBySlugExact( $query ) { $query = $query['value']; $query = trim( $query ); $term = get_term_by( 'slug', $query, 'product_cat' ); return $this->productCategoryTermOutput( $term ); } /** * Return product category value|label array * * @param $term * * @return array|bool * @since 4.4 */ protected function productCategoryTermOutput( $term ) { $term_slug = $term->slug; $term_title = $term->name; $term_id = $term->term_id; $term_slug_display = ''; if ( ! empty( $term_slug ) ) { $term_slug_display = ' - ' . esc_html__( 'Sku', 'js_composer' ) . ': ' . $term_slug; } $term_title_display = ''; if ( ! empty( $term_title ) ) { $term_title_display = ' - ' . esc_html__( 'Title', 'js_composer' ) . ': ' . $term_title; } $term_id_display = esc_html__( 'Id', 'js_composer' ) . ': ' . $term_id; $data = array(); $data['value'] = $term_id; $data['label'] = $term_id_display . $term_title_display . $term_slug_display; return ! empty( $data ) ? $data : false; } /** * @return array */ /** * @return array */ public static function getProductsFieldsList() { return array( esc_html__( 'SKU', 'js_composer' ) => 'sku', esc_html__( 'ID', 'js_composer' ) => 'id', esc_html__( 'Price', 'js_composer' ) => 'price', esc_html__( 'Regular Price', 'js_composer' ) => 'regular_price', esc_html__( 'Sale Price', 'js_composer' ) => 'sale_price', esc_html__( 'Price html', 'js_composer' ) => 'price_html', esc_html__( 'Reviews count', 'js_composer' ) => 'reviews_count', esc_html__( 'Short description', 'js_composer' ) => 'short_description', esc_html__( 'Dimensions', 'js_composer' ) => 'dimensions', esc_html__( 'Rating count', 'js_composer' ) => 'rating_count', esc_html__( 'Weight', 'js_composer' ) => 'weight', esc_html__( 'Is on sale', 'js_composer' ) => 'on_sale', esc_html__( 'Custom field', 'js_composer' ) => '_custom_', ); } /** * @param $key * @return string */ /** * @param $key * @return string */ public static function getProductFieldLabel( $key ) { if ( false === self::$product_fields_list ) { self::$product_fields_list = array_flip( self::getProductsFieldsList() ); } return isset( self::$product_fields_list[ $key ] ) ? self::$product_fields_list[ $key ] : ''; } /** * @return array */ /** * @return array */ public static function getOrderFieldsList() { return array( esc_html__( 'ID', 'js_composer' ) => 'id', esc_html__( 'Order number', 'js_composer' ) => 'order_number', esc_html__( 'Currency', 'js_composer' ) => 'order_currency', esc_html__( 'Total', 'js_composer' ) => 'total', esc_html__( 'Status', 'js_composer' ) => 'status', esc_html__( 'Payment method', 'js_composer' ) => 'payment_method', esc_html__( 'Billing address city', 'js_composer' ) => 'billing_address_city', esc_html__( 'Billing address country', 'js_composer' ) => 'billing_address_country', esc_html__( 'Shipping address city', 'js_composer' ) => 'shipping_address_city', esc_html__( 'Shipping address country', 'js_composer' ) => 'shipping_address_country', esc_html__( 'Customer Note', 'js_composer' ) => 'customer_note', esc_html__( 'Customer API', 'js_composer' ) => 'customer_api', esc_html__( 'Custom field', 'js_composer' ) => '_custom_', ); } /** * @param $key * @return string */ /** * @param $key * @return string */ public static function getOrderFieldLabel( $key ) { if ( false === self::$order_fields_list ) { self::$order_fields_list = array_flip( self::getOrderFieldsList() ); } return isset( self::$order_fields_list[ $key ] ) ? self::$order_fields_list[ $key ] : ''; } public function yoastSeoCompatibility() { if ( function_exists( 'WC' ) ) { // WC()->frontend_includes(); include_once( WC()->plugin_path() . '/includes/wc-template-functions.php' ); // include_once WC()->plugin_path() . ''; } } } /** * Removes EDIT button in backend and frontend editor * Class Vc_WooCommerce_NotEditable * @since 4.4 */ class Vc_WooCommerce_NotEditable extends WPBakeryShortCode { /** * @since 4.4 * @var array */ protected $controls_list = array( 'clone', 'delete', ); }
jujudellago/yc2016
web/app/plugins/js_composer/include/classes/vendors/plugins/class-vc-vendor-woocommerce.php
PHP
mit
55,910
using System; using System.Threading; namespace Remotus.Base.Observables { public sealed class DelegateObserver<T> : IObserver<T>, IDisposable { private readonly Action _onCompleted; private readonly Action<Exception> _onError; private readonly Action<T> _onNext; private int _isStopped; public DelegateObserver(Action<T> onNext, Action<Exception> onError = null, Action onCompleted = null) { _onNext = onNext; _onError = onError; _onCompleted = onCompleted; } public void OnNext(T value) { if (_isStopped == 0) _onNext?.Invoke(value); } public void OnError(Exception error) { if (Interlocked.Exchange(ref _isStopped, 1) == 0) _onError?.Invoke(error); } public void OnCompleted() { if (Interlocked.Exchange(ref _isStopped, 1) == 0) _onCompleted?.Invoke(); } public void Dispose() { Interlocked.Exchange(ref _isStopped, 1); } } }
LazyTarget/ProcHelper
src/Remotus.Base/Observables/DelegateObserver.cs
C#
mit
1,134
from django.conf.urls.defaults import * urlpatterns = patterns('', url(r'^$', 'topics.views.topics', name="topic_list"), url(r'^(?P<topic_id>\d+)/edit/$', 'topics.views.topic', kwargs={"edit": True}, name="topic_edit"), url(r'^(?P<topic_id>\d+)/delete/$', 'topics.views.topic_delete', name="topic_delete"), url(r'^(?P<topic_id>\d+)/$', 'topics.views.topic', name="topic_detail"), )
ericholscher/pinax
pinax/apps/topics/urls.py
Python
mit
399
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.ComponentModel.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Notification; using Microsoft.CodeAnalysis.Shared.Options; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.SolutionCrawler; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.TaskList { internal sealed class ExternalErrorDiagnosticUpdateSource : IDiagnosticUpdateSource { private readonly Workspace _workspace; private readonly IDiagnosticAnalyzerService _diagnosticService; private readonly IGlobalOperationNotificationService _notificationService; private readonly SimpleTaskQueue _taskQueue; private readonly IAsynchronousOperationListener _listener; private readonly object _gate = new object(); private InProgressState _stateDoNotAccessDirectly = null; private ImmutableArray<DiagnosticData> _lastBuiltResult = ImmutableArray<DiagnosticData>.Empty; public ExternalErrorDiagnosticUpdateSource( VisualStudioWorkspace workspace, IDiagnosticAnalyzerService diagnosticService, IDiagnosticUpdateSourceRegistrationService registrationService, IAsynchronousOperationListenerProvider listenerProvider) : this(workspace, diagnosticService, listenerProvider.GetListener(FeatureAttribute.ErrorList)) { registrationService.Register(this); } /// <summary> /// internal for testing /// </summary> internal ExternalErrorDiagnosticUpdateSource( Workspace workspace, IDiagnosticAnalyzerService diagnosticService, IAsynchronousOperationListener listener) { // use queue to serialize work. no lock needed _taskQueue = new SimpleTaskQueue(TaskScheduler.Default); _listener = listener; _workspace = workspace; _workspace.WorkspaceChanged += OnWorkspaceChanged; _diagnosticService = diagnosticService; _notificationService = _workspace.Services.GetService<IGlobalOperationNotificationService>(); } public event EventHandler<BuildProgress> BuildProgressChanged; public event EventHandler<DiagnosticsUpdatedArgs> DiagnosticsUpdated; public event EventHandler DiagnosticsCleared { add { } remove { } } public bool IsInProgress => BuildInprogressState != null; public ImmutableArray<DiagnosticData> GetBuildErrors() { return _lastBuiltResult; } public bool IsSupportedDiagnosticId(ProjectId projectId, string id) { return BuildInprogressState?.IsSupportedDiagnosticId(projectId, id) ?? false; } public void ClearErrors(ProjectId projectId) { // capture state if it exists var state = BuildInprogressState; var asyncToken = _listener.BeginAsyncOperation("ClearErrors"); _taskQueue.ScheduleTask(() => { // this will get called if the project is actually built by "build" command. // we track what project has been built, so that later we can clear any stale live errors // if build give us no errors for this project state?.Built(projectId); ClearProjectErrors(state?.Solution ?? _workspace.CurrentSolution, projectId); }).CompletesAsyncOperation(asyncToken); } private void OnWorkspaceChanged(object sender, WorkspaceChangeEventArgs e) { switch (e.Kind) { case WorkspaceChangeKind.SolutionAdded: case WorkspaceChangeKind.SolutionRemoved: case WorkspaceChangeKind.SolutionCleared: case WorkspaceChangeKind.SolutionReloaded: { var asyncToken = _listener.BeginAsyncOperation("OnSolutionChanged"); _taskQueue.ScheduleTask(() => e.OldSolution.ProjectIds.Do(p => ClearProjectErrors(e.OldSolution, p))).CompletesAsyncOperation(asyncToken); break; } case WorkspaceChangeKind.ProjectRemoved: case WorkspaceChangeKind.ProjectReloaded: { var asyncToken = _listener.BeginAsyncOperation("OnProjectChanged"); _taskQueue.ScheduleTask(() => ClearProjectErrors(e.OldSolution, e.ProjectId)).CompletesAsyncOperation(asyncToken); break; } case WorkspaceChangeKind.DocumentRemoved: case WorkspaceChangeKind.DocumentReloaded: { var asyncToken = _listener.BeginAsyncOperation("OnDocumentRemoved"); _taskQueue.ScheduleTask(() => ClearDocumentErrors(e.OldSolution, e.ProjectId, e.DocumentId)).CompletesAsyncOperation(asyncToken); break; } case WorkspaceChangeKind.ProjectAdded: case WorkspaceChangeKind.DocumentAdded: case WorkspaceChangeKind.DocumentChanged: case WorkspaceChangeKind.ProjectChanged: case WorkspaceChangeKind.SolutionChanged: case WorkspaceChangeKind.AdditionalDocumentAdded: case WorkspaceChangeKind.AdditionalDocumentRemoved: case WorkspaceChangeKind.AdditionalDocumentReloaded: case WorkspaceChangeKind.AdditionalDocumentChanged: case WorkspaceChangeKind.AnalyzerConfigDocumentAdded: case WorkspaceChangeKind.AnalyzerConfigDocumentRemoved: case WorkspaceChangeKind.AnalyzerConfigDocumentChanged: case WorkspaceChangeKind.AnalyzerConfigDocumentReloaded: break; default: Contract.Fail("Unknown workspace events"); break; } } internal void OnSolutionBuildStarted() { // build just started, create the state and fire build in progress event. // build just started, create the state and fire build in progress event. _ = GetOrCreateInProgressState(); } internal void OnSolutionBuildCompleted() { // building is done. reset the state // and get local copy of in-progress state var inProgressState = ClearInProgressState(); // enqueue build/live sync in the queue. var asyncToken = _listener.BeginAsyncOperation("OnSolutionBuild"); _taskQueue.ScheduleTask(async () => { // nothing to do if (inProgressState == null) { return; } // explicitly start solution crawler if it didn't start yet. since solution crawler is lazy, // user might have built solution before workspace fires its first event yet (which is when solution crawler is initialized) // here we give initializeLazily: false so that solution crawler is fully initialized when we do de-dup live and build errors, // otherwise, we will think none of error we have here belong to live errors since diagnostic service is not initialized yet. var registrationService = (SolutionCrawlerRegistrationService)_workspace.Services.GetService<ISolutionCrawlerRegistrationService>(); registrationService.EnsureRegistration(_workspace, initializeLazily: false); _lastBuiltResult = inProgressState.GetBuildDiagnostics(); // we are about to update live analyzer data using one from build. // pause live analyzer using var operation = _notificationService.Start("BuildDone"); if (_diagnosticService is DiagnosticAnalyzerService diagnosticService) { await CleanupAllLiveErrorsAsync(diagnosticService, inProgressState.GetProjectsWithoutErrors()).ConfigureAwait(false); await SyncBuildErrorsAndReportAsync(diagnosticService, inProgressState).ConfigureAwait(false); } inProgressState.Done(); }).CompletesAsyncOperation(asyncToken); } private Task CleanupAllLiveErrorsAsync(DiagnosticAnalyzerService diagnosticService, IEnumerable<ProjectId> projects) { var map = projects.ToImmutableDictionary(p => p, _ => ImmutableArray<DiagnosticData>.Empty); return diagnosticService.SynchronizeWithBuildAsync(_workspace, map); } private async Task SyncBuildErrorsAndReportAsync(DiagnosticAnalyzerService diagnosticService, InProgressState inProgressState) { var solution = inProgressState.Solution; var map = await inProgressState.GetLiveDiagnosticsPerProjectAsync().ConfigureAwait(false); // make those errors live errors await diagnosticService.SynchronizeWithBuildAsync(_workspace, map).ConfigureAwait(false); // raise events for ones left-out var buildErrors = GetBuildErrors().Except(map.Values.SelectMany(v => v)).GroupBy(k => k.DocumentId); foreach (var group in buildErrors) { if (group.Key == null) { foreach (var projectGroup in group.GroupBy(g => g.ProjectId)) { Contract.ThrowIfNull(projectGroup.Key); ReportBuildErrors(projectGroup.Key, solution, projectGroup.ToImmutableArray()); } continue; } ReportBuildErrors(group.Key, solution, group.ToImmutableArray()); } } private void ReportBuildErrors<T>(T item, Solution solution, ImmutableArray<DiagnosticData> buildErrors) { if (item is ProjectId projectId) { RaiseDiagnosticsCreated(projectId, solution, projectId, null, buildErrors); return; } // must be not null var documentId = item as DocumentId; RaiseDiagnosticsCreated(documentId, solution, documentId.ProjectId, documentId, buildErrors); } private void ClearProjectErrors(Solution solution, ProjectId projectId) { // remove all project errors RaiseDiagnosticsRemoved(projectId, solution, projectId, documentId: null); var project = solution.GetProject(projectId); if (project == null) { return; } // remove all document errors foreach (var documentId in project.DocumentIds) { ClearDocumentErrors(solution, projectId, documentId); } } private void ClearDocumentErrors(Solution solution, ProjectId projectId, DocumentId documentId) { RaiseDiagnosticsRemoved(documentId, solution, projectId, documentId); } public void AddNewErrors(ProjectId projectId, DiagnosticData diagnostic) { // capture state that will be processed in background thread. var state = GetOrCreateInProgressState(); var asyncToken = _listener.BeginAsyncOperation("Project New Errors"); _taskQueue.ScheduleTask(() => { state.AddError(projectId, diagnostic); }).CompletesAsyncOperation(asyncToken); } public void AddNewErrors(DocumentId documentId, DiagnosticData diagnostic) { // capture state that will be processed in background thread. var state = GetOrCreateInProgressState(); var asyncToken = _listener.BeginAsyncOperation("Document New Errors"); _taskQueue.ScheduleTask(() => { state.AddError(documentId, diagnostic); }).CompletesAsyncOperation(asyncToken); } public void AddNewErrors( ProjectId projectId, HashSet<DiagnosticData> projectErrors, Dictionary<DocumentId, HashSet<DiagnosticData>> documentErrorMap) { // capture state that will be processed in background thread var state = GetOrCreateInProgressState(); var asyncToken = _listener.BeginAsyncOperation("Project New Errors"); _taskQueue.ScheduleTask(() => { foreach (var kv in documentErrorMap) { state.AddErrors(kv.Key, kv.Value); } state.AddErrors(projectId, projectErrors); }).CompletesAsyncOperation(asyncToken); } private InProgressState BuildInprogressState { get { lock (_gate) { return _stateDoNotAccessDirectly; } } } private InProgressState ClearInProgressState() { lock (_gate) { var state = _stateDoNotAccessDirectly; _stateDoNotAccessDirectly = null; return state; } } private InProgressState GetOrCreateInProgressState() { lock (_gate) { if (_stateDoNotAccessDirectly == null) { // here, we take current snapshot of solution when the state is first created. and through out this code, we use this snapshot. // since we have no idea what actual snapshot of solution the out of proc build has picked up, it doesn't remove the race we can have // between build and diagnostic service, but this at least make us to consistent inside of our code. _stateDoNotAccessDirectly = new InProgressState(this, _workspace.CurrentSolution); } return _stateDoNotAccessDirectly; } } private void RaiseDiagnosticsCreated(object id, Solution solution, ProjectId projectId, DocumentId documentId, ImmutableArray<DiagnosticData> items) { DiagnosticsUpdated?.Invoke(this, DiagnosticsUpdatedArgs.DiagnosticsCreated( CreateArgumentKey(id), _workspace, solution, projectId, documentId, items)); } private void RaiseDiagnosticsRemoved(object id, Solution solution, ProjectId projectId, DocumentId documentId) { DiagnosticsUpdated?.Invoke(this, DiagnosticsUpdatedArgs.DiagnosticsRemoved( CreateArgumentKey(id), _workspace, solution, projectId, documentId)); } private static ArgumentKey CreateArgumentKey(object id) => new ArgumentKey(id); private void RaiseBuildProgressChanged(BuildProgress progress) { BuildProgressChanged?.Invoke(this, progress); } #region not supported public bool SupportGetDiagnostics { get { return false; } } public ImmutableArray<DiagnosticData> GetDiagnostics( Workspace workspace, ProjectId projectId, DocumentId documentId, object id, bool includeSuppressedDiagnostics = false, CancellationToken cancellationToken = default) { return ImmutableArray<DiagnosticData>.Empty; } #endregion internal enum BuildProgress { Started, Updated, Done } private sealed class InProgressState { private int _incrementDoNotAccessDirectly = 0; private readonly ExternalErrorDiagnosticUpdateSource _owner; private readonly HashSet<ProjectId> _projectsBuilt = new HashSet<ProjectId>(); private readonly HashSet<ProjectId> _projectsWithErrors = new HashSet<ProjectId>(); private readonly Dictionary<ProjectId, ImmutableHashSet<string>> _allDiagnosticIdMap = new Dictionary<ProjectId, ImmutableHashSet<string>>(); private readonly Dictionary<ProjectId, ImmutableHashSet<string>> _liveDiagnosticIdMap = new Dictionary<ProjectId, ImmutableHashSet<string>>(); private readonly Dictionary<ProjectId, Dictionary<DiagnosticData, int>> _projectMap = new Dictionary<ProjectId, Dictionary<DiagnosticData, int>>(); private readonly Dictionary<DocumentId, Dictionary<DiagnosticData, int>> _documentMap = new Dictionary<DocumentId, Dictionary<DiagnosticData, int>>(); public InProgressState(ExternalErrorDiagnosticUpdateSource owner, Solution solution) { _owner = owner; Solution = solution; // let people know build has started _owner.RaiseBuildProgressChanged(BuildProgress.Started); } public Solution Solution { get; } public void Done() { _owner.RaiseBuildProgressChanged(BuildProgress.Done); } public bool IsSupportedDiagnosticId(ProjectId projectId, string id) { lock (_allDiagnosticIdMap) { if (_allDiagnosticIdMap.TryGetValue(projectId, out var ids)) { return ids.Contains(id); } var project = Solution.GetProject(projectId); if (project == null) { // projectId no longer exist, return false; _allDiagnosticIdMap.Add(projectId, ImmutableHashSet<string>.Empty); return false; } // set ids set var builder = ImmutableHashSet.CreateBuilder<string>(); var descriptorMap = _owner._diagnosticService.AnalyzerInfoCache.GetDiagnosticDescriptorsPerReference(project); builder.UnionWith(descriptorMap.Values.SelectMany(v => v.Select(d => d.Id))); var set = builder.ToImmutable(); _allDiagnosticIdMap.Add(projectId, set); return set.Contains(id); } } public ImmutableArray<DiagnosticData> GetBuildDiagnostics() { // return errors in the order that is reported return ImmutableArray.CreateRange( _projectMap.Values.SelectMany(d => d).Concat(_documentMap.Values.SelectMany(d => d)).OrderBy(kv => kv.Value).Select(kv => kv.Key)); } public void Built(ProjectId projectId) { _projectsBuilt.Add(projectId); } public IEnumerable<ProjectId> GetProjectsWithErrors() { // filter out project that is no longer exist in IDE // this can happen if user started a "build" and then remove a project from IDE // before build finishes return _projectsWithErrors.Where(p => Solution.GetProject(p) != null); } public IEnumerable<ProjectId> GetProjectsWithoutErrors() { return GetProjectsBuilt().Except(GetProjectsWithErrors()); IEnumerable<ProjectId> GetProjectsBuilt() { // filter out project that is no longer exist in IDE // this can happen if user started a "build" and then remove a project from IDE // before build finishes return Solution.ProjectIds.Where(p => _projectsBuilt.Contains(p)); } } public async Task<ImmutableDictionary<ProjectId, ImmutableArray<DiagnosticData>>> GetLiveDiagnosticsPerProjectAsync() { var builder = ImmutableDictionary.CreateBuilder<ProjectId, ImmutableArray<DiagnosticData>>(); foreach (var projectId in GetProjectsWithErrors()) { var project = Solution.GetProject(projectId); var compilation = project.SupportsCompilation ? await project.GetCompilationAsync(CancellationToken.None).ConfigureAwait(false) : null; var diagnostics = ImmutableArray.CreateRange( _projectMap.Where(kv => kv.Key == projectId).SelectMany(kv => kv.Value).Concat( _documentMap.Where(kv => kv.Key.ProjectId == projectId).SelectMany(kv => kv.Value)) .Select(kv => kv.Key).Where(d => IsLive(project, compilation, d))); builder.Add(projectId, diagnostics); } return builder.ToImmutable(); } public void AddErrors(DocumentId key, HashSet<DiagnosticData> diagnostics) { AddErrors(_documentMap, key, diagnostics); } public void AddErrors(ProjectId key, HashSet<DiagnosticData> diagnostics) { AddErrors(_projectMap, key, diagnostics); } public void AddError(DocumentId key, DiagnosticData diagnostic) { AddError(_documentMap, key, diagnostic); } public void AddError(ProjectId key, DiagnosticData diagnostic) { AddError(_projectMap, key, diagnostic); } private bool IsLive(Project project, Compilation compilation, DiagnosticData diagnosticData) { // REVIEW: current design is that we special case compiler analyzer case and we accept only document level // diagnostic as live. otherwise, we let them be build errors. we changed compiler analyzer accordingly as well // so that it doesn't report project level diagnostic as live errors. if (_owner._diagnosticService.AnalyzerInfoCache.IsCompilerDiagnostic(project.Language, diagnosticData) && !IsDocumentLevelDiagnostic(diagnosticData)) { // compiler error but project level error return false; } if (SupportedLiveDiagnosticId(project, compilation, diagnosticData.Id)) { return true; } return false; static bool IsDocumentLevelDiagnostic(DiagnosticData diagnoaticData) { if (diagnoaticData.DocumentId != null) { return true; } // due to mapped file such as // // A.cs having // #line 2 RandomeFile.txt // ErrorHere // #line default // // we can't simply say it is not document level diagnostic since // file path is not part of solution. build output will just tell us // mapped span not original span, so any code like above will not // part of solution. // // but also we can't simply say it is a document level error because it has file path // since project level error can have a file path pointing to a file such as dll // , pdb, embedded files and etc. // // unfortunately, there is no 100% correct way to do this. // so we will use a heuristic that will most likely work for most of common cases. return !string.IsNullOrEmpty(diagnoaticData.DataLocation.OriginalFilePath) && (diagnoaticData.DataLocation.OriginalStartLine > 0 || diagnoaticData.DataLocation.OriginalStartColumn > 0); } } private bool SupportedLiveDiagnosticId(Project project, Compilation compilation, string id) { var projectId = project.Id; lock (_liveDiagnosticIdMap) { if (_liveDiagnosticIdMap.TryGetValue(projectId, out var ids)) { return ids.Contains(id); } var fullSolutionAnalysis = SolutionCrawlerOptions.GetBackgroundAnalysisScope(project) == BackgroundAnalysisScope.FullSolution; if (!project.SupportsCompilation || fullSolutionAnalysis) { return IsSupportedDiagnosticId(project.Id, id); } // set ids set var builder = ImmutableHashSet.CreateBuilder<string>(); var diagnosticService = _owner._diagnosticService; var infoCache = diagnosticService.AnalyzerInfoCache; foreach (var analyzersPerReference in infoCache.CreateDiagnosticAnalyzersPerReference(project)) { foreach (var analyzer in analyzersPerReference.Value) { if (diagnosticService.IsCompilationEndAnalyzer(analyzer, project, compilation)) { continue; } var diagnosticIds = infoCache.GetDiagnosticDescriptors(analyzer).Select(d => d.Id); builder.UnionWith(diagnosticIds); } } var set = builder.ToImmutable(); _liveDiagnosticIdMap.Add(projectId, set); return set.Contains(id); } } private void AddErrors<T>(Dictionary<T, Dictionary<DiagnosticData, int>> map, T key, HashSet<DiagnosticData> diagnostics) { var errors = GetErrorSet(map, key); foreach (var diagnostic in diagnostics) { AddError(errors, diagnostic, key); } } private void AddError<T>(Dictionary<T, Dictionary<DiagnosticData, int>> map, T key, DiagnosticData diagnostic) { var errors = GetErrorSet(map, key); AddError(errors, diagnostic, key); } private void AddError<T>(Dictionary<DiagnosticData, int> errors, DiagnosticData diagnostic, T key) { RecordProjectContainsErrors(); // add only new errors if (!errors.TryGetValue(diagnostic, out _)) { Logger.Log(FunctionId.ExternalErrorDiagnosticUpdateSource_AddError, d => d.ToString(), diagnostic); errors.Add(diagnostic, GetNextIncrement()); } int GetNextIncrement() { return _incrementDoNotAccessDirectly++; } void RecordProjectContainsErrors() { var projectId = (key is DocumentId documentId) ? documentId.ProjectId : (ProjectId)(object)key; if (!_projectsWithErrors.Add(projectId)) { return; } // this will make build only error list to be updated per project rather than per solution. // basically this will make errors up to last project to show up in error list _owner._lastBuiltResult = GetBuildDiagnostics(); _owner.RaiseBuildProgressChanged(BuildProgress.Updated); } } private Dictionary<DiagnosticData, int> GetErrorSet<T>(Dictionary<T, Dictionary<DiagnosticData, int>> map, T key) { return map.GetOrAdd(key, _ => new Dictionary<DiagnosticData, int>(DiagnosticDataComparer.Instance)); } } private sealed class ArgumentKey : BuildToolId.Base<object> { public ArgumentKey(object key) : base(key) { } public override string BuildTool { get { return PredefinedBuildTools.Build; } } public override bool Equals(object obj) => obj is ArgumentKey && base.Equals(obj); public override int GetHashCode() { return base.GetHashCode(); } } private sealed class DiagnosticDataComparer : IEqualityComparer<DiagnosticData> { public static readonly DiagnosticDataComparer Instance = new DiagnosticDataComparer(); public bool Equals(DiagnosticData item1, DiagnosticData item2) { if ((item1.DocumentId == null) != (item2.DocumentId == null) || item1.Id != item2.Id || item1.ProjectId != item2.ProjectId || item1.Severity != item2.Severity || item1.Message != item2.Message || (item1.DataLocation?.MappedStartLine ?? 0) != (item2.DataLocation?.MappedStartLine ?? 0) || (item1.DataLocation?.MappedStartColumn ?? 0) != (item2.DataLocation?.MappedStartColumn ?? 0) || (item1.DataLocation?.OriginalStartLine ?? 0) != (item2.DataLocation?.OriginalStartLine ?? 0) || (item1.DataLocation?.OriginalStartColumn ?? 0) != (item2.DataLocation?.OriginalStartColumn ?? 0)) { return false; } return (item1.DocumentId != null) ? item1.DocumentId == item2.DocumentId : item1.DataLocation?.OriginalFilePath == item2.DataLocation?.OriginalFilePath; } public int GetHashCode(DiagnosticData obj) { var result = Hash.Combine(obj.Id, Hash.Combine(obj.Message, Hash.Combine(obj.ProjectId, Hash.Combine(obj.DataLocation?.MappedStartLine ?? 0, Hash.Combine(obj.DataLocation?.MappedStartColumn ?? 0, Hash.Combine(obj.DataLocation?.OriginalStartLine ?? 0, Hash.Combine(obj.DataLocation?.OriginalStartColumn ?? 0, (int)obj.Severity))))))); return obj.DocumentId != null ? Hash.Combine(obj.DocumentId, result) : Hash.Combine(obj.DataLocation?.OriginalFilePath?.GetHashCode() ?? 0, result); } } } }
abock/roslyn
src/VisualStudio/Core/Def/Implementation/TaskList/ExternalErrorDiagnosticUpdateSource.cs
C#
mit
31,502
package main import ( "github.com/gorilla/handlers" "github.com/gorilla/mux" "html/template" "log" "net/http" "os" ) const ( addr = "127.0.0.1:8090" ) var ( indexTemplate = template.Must(template.ParseFiles("index.html")) tasks = []Task{ Task{1, "Learn golang", true}, Task{2, "Write webapp", true}, Task{3, "???", false}, Task{4, "Profit! $$$", false}, } ) type Index struct { Tasks []Task Addr string } type Task struct { Id uint64 Name string Done bool } func index(w http.ResponseWriter, r *http.Request) { indexTemplate.Execute(w, Index{tasks, addr}) } func main() { r := mux.NewRouter() r.HandleFunc("/", index) r.HandleFunc("/ws", serveWs) static := http.StripPrefix("/static/", http.FileServer(http.Dir("./static/"))) r.PathPrefix("/static/").Handler(static) go h.run() logger := handlers.LoggingHandler(os.Stdout, r) log.Println("Starting server on", addr) log.Fatal(http.ListenAndServe(addr, logger)) }
vinzBad/checklost
main.go
GO
mit
965
module Pwb class OmniauthController < ApplicationController # https://github.com/plataformatec/devise/wiki/How-To:-OmniAuth-inside-localized-scope def localized # Just save the current locale in the session and redirect to the unscoped path as before session[:omniauth_login_locale] = I18n.locale # user_facebook_omniauth_authorize_path # redirect_to user_omniauth_authorize_path(params[:provider]) redirect_to omniauth_authorize_path("user", params[:provider]) end end end
etewiah/property-web-builder
app/controllers/pwb/omniauth_controller.rb
Ruby
mit
520
<?php namespace Alterway\Component\Workflow\Exception; class MoreThanOneOpenTransitionException extends \LogicException { public function __construct() { return parent::__construct('More than one open transition with current context'); } }
alterway/component-workflow
src/Exception/MoreThanOneOpenTransitionException.php
PHP
mit
264
/** * JS initialization and core functions for API test servlet * * @depends {3rdparty/jquery.js} * @depends {3rdparty/bootstrap.js} * @depends {3rdparty/highlight.pack.js} */ var ATS = (function(ATS, $, undefined) { ATS.apiCalls = []; ATS.selectedApiCalls = []; ATS.init = function() { hljs.initHighlightingOnLoad(); ATS.selectedApiCalls = ATS.setSelectedApiCalls(); ATS.selectedApiCallsChange(); $('#search').keyup(function(e) { if (e.keyCode == 13) { ATS.performSearch($(this).val()); } }); $(".collapse-link").click(function(event) { event.preventDefault(); }); $('#navi-show-open').click(function(e) { $('.api-call-All').each(function() { if($(this).find('.panel-collapse.in').length != 0) { $(this).show(); } else { $(this).hide(); } }); $('#navi-show-all').css('font-weight', 'normal'); $(this).css('font-weight', 'bold'); e.preventDefault(); }); $('#navi-show-all').click(function(e) { $('.api-call-All').show(); $('#navi-show-open').css('font-weight', 'normal'); $(this).css('font-weight', 'bold'); e.preventDefault(); }); $('.api-call-sel-ALL').change(function() { if($(this).is(":checked")) { ATS.addToSelected($(this)); } else { ATS.removeFromSelected($(this)); } }); $('#navi-select-all-d-add-btn').click(function(e) { $.each($('.api-call-sel-ALL:visible:not(:checked)'), function(key, value) { ATS.addToSelected($(value)); }); e.preventDefault(); }); $('#navi-select-all-d-replace-btn').click(function(e) { ATS.selectedApiCalls = []; $.each($('.api-call-sel-ALL:visible'), function(key, value) { ATS.addToSelected($(value)); }); e.preventDefault(); }); $('#navi-deselect-all-d-btn').click(function(e) { $.each($('.api-call-sel-ALL:visible'), function(key, value) { ATS.removeFromSelected($(value)); }); e.preventDefault(); }); $('#navi-deselect-all-btn').click(function(e) { ATS.selectedApiCalls = []; $('.api-call-sel-ALL').prop('checked', false); ATS.selectedApiCallsChange(); e.preventDefault(); }); } ATS.performSearch = function(searchStr) { if (searchStr == '') { $('.api-call-All').show(); } else { $('.api-call-All').hide(); $('.topic-link').css('font-weight', 'normal'); for(var i=0; i<ATS.apiCalls.length; i++) { var apiCall = ATS.apiCalls[i]; if (new RegExp(searchStr.toLowerCase()).test(apiCall.toLowerCase())) { $('#api-call-' + apiCall).show(); } } } } ATS.submitForm = function(form) { var url = '/life'; var params = {}; for (i = 0; i < form.elements.length; i++) { if (form.elements[i].type != 'button' && form.elements[i].value && form.elements[i].value != 'submit') { var key = form.elements[i].name; var value = form.elements[i].value; if(key in params) { var index = params[key].length; params[key][index] = value; } else { params[key] = [value]; } } } $.ajax({ url: url, type: 'POST', data: params, traditional: true // "true" needed for duplicate params }) .done(function(result) { var resultStr = JSON.stringify(JSON.parse(result), null, 4); var code_elem = form.getElementsByClassName("result")[0]; code_elem.textContent = resultStr; hljs.highlightBlock(code_elem); }) .error(function() { alert('API not available, check if Life Server is running!'); }); if ($(form).has('.uri-link').length > 0) { var uri = '/life?' + jQuery.param(params, true); var html = '<a href="' + uri + '" target="_blank" style="font-size:12px;font-weight:normal;">Open GET URL</a>'; form.getElementsByClassName("uri-link")[0].innerHTML = html; } return false; } ATS.selectedApiCallsChange = function() { var newUrl = '/test?requestTypes=' + encodeURIComponent(ATS.selectedApiCalls.join('_')); $('#navi-selected').attr('href', newUrl); $('#navi-selected').text('SELECTED (' + ATS.selectedApiCalls.length + ')'); ATS.setCookie('selected_api_calls', ATS.selectedApiCalls.join('_'), 30); } ATS.setSelectedApiCalls = function() { var calls = []; var getParam = ATS.getUrlParameter('requestTypes'); var cookieParam = ATS.getCookie('selected_api_calls'); if (getParam != undefined && getParam != '') { calls=getParam.split('_'); } else if (cookieParam != undefined && cookieParam != ''){ calls=cookieParam.split('_'); } for (var i=0; i<calls.length; i++) { $('#api-call-sel-' + calls[i]).prop('checked', true); } return calls; } ATS.addToSelected = function(elem) { var type=elem.attr('id').substr(13); elem.prop('checked', true); if($.inArray(type, ATS.selectedApiCalls) == -1) { ATS.selectedApiCalls.push(type); ATS.selectedApiCallsChange(); } } ATS.removeFromSelected = function(elem) { var type=elem.attr('id').substr(13); elem.prop('checked', false); var index = ATS.selectedApiCalls.indexOf(type); if (index > -1) { ATS.selectedApiCalls.splice(index, 1); ATS.selectedApiCallsChange(); } } return ATS; }(ATS || {}, jQuery)); $(document).ready(function() { ATS.init(); });
YawLife/LIFE
html/ui/js/ats.js
JavaScript
mit
6,337
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices.ComTypes; using System.Threading.Tasks; using Autofac; using Nancy.Bootstrapper; using Nancy.Bootstrappers.Autofac; using Nancy.Swagger.Annotations; using Nancy.Swagger.Autofac.Demo.Modules; using Nancy.Swagger.Services; using Swagger.ObjectModel; namespace Nancy.Swagger.Autofac.Demo { public class AutofacBootstrapper : AutofacNancyBootstrapper { public AutofacBootstrapper() : base() { } protected override void ConfigureApplicationContainer(ILifetimeScope container) { SwaggerMetadataProvider.SetInfo("Nancy Swagger w/ AutoFac Example", "v0", "Our awesome service", new Contact() { EmailAddress = "exampleEmail@example.com" }); SwaggerAnnotationsConfig.ShowOnlyAnnotatedRoutes = true; this.ApplicationPipelines.AfterRequest.AddItemToEndOfPipeline(x => x.Response.Headers.Add("Access-Control-Allow-Origin", "*")); this.ApplicationPipelines.AfterRequest.AddItemToEndOfPipeline(x => x.Response.Headers.Add("Access-Control-Allow-Headers", "*")); this.ApplicationPipelines.AfterRequest.AddItemToEndOfPipeline(x => x.Response.Headers.Add("Access-Control-Allow-Methods", "*")); } } }
yahehe/Nancy.Swagger
samples/Nancy.Swagger.Autofac.Demo/AutofacBootstrapper.cs
C#
mit
1,351
<?php /** * ====================================================================== * LICENSE: This file is subject to the terms and conditions defined in * * file 'license.txt', which is part of this source code package. * * ====================================================================== */ /** * Abstract subject * * @package AAM * @author Vasyl Martyniuk <vasyl@vasyltech.com> */ abstract class AAM_Core_Subject { /** * Subject ID * * Whether it is User ID or Role ID * * @var string|int * * @access private */ private $_id; /** * WordPres Subject * * It can be WP_User or WP_Role, based on what class has been used * * @var WP_Role|WP_User * * @access private */ private $_subject; /** * List of Objects to be access controlled for current subject * * All access control objects like Admin Menu, Metaboxes, Posts etc * * @var array * * @access private */ private $_objects = array(); /** * Constructor * * @param string|int $id * * @return void * * @access public */ public function __construct($id = '') { //set subject $this->setId($id); //retrieve and set subject itself $this->setSubject($this->retrieveSubject()); } /** * Trigger Subject native methods * * @param string $name * @param array $args * * @return mixed * * @access public */ public function __call($name, $args) { $subject = $this->getSubject(); //make sure that method is callable if (method_exists($subject, $name)) { $response = call_user_func_array(array($subject, $name), $args); } else { $response = null; } return $response; } /** * Get Subject's native properties * * @param string $name * * @return mixed * * @access public */ public function __get($name) { $subject = $this->getSubject(); return (!empty($subject->$name) ? $subject->$name : null); } /** * Set Subject's native properties * * @param string $name * * @return mixed * * @access public */ public function __set($name, $value) { $subject = $this->getSubject(); if ($subject) { $subject->$name = $value; } } /** * Set Subject ID * * @param string|int * * @return void * * @access public */ public function setId($id) { $this->_id = $id; } /** * Get Subject ID * * @return string|int * * @access public */ public function getId() { return $this->_id; } /** * Get subject name * * @return string * * @access public */ public function getName() { return ''; } /** * * @return int */ public function getMaxLevel() { return 0; } /** * Get Subject * * @return WP_Role|WP_User * * @access public */ public function getSubject() { return $this->_subject; } /** * Set Subject * * @param WP_Role|WP_User $subject * * @return void * * @access public */ public function setSubject($subject) { $this->_subject = $subject; } /** * Get Individual Object * * @param string $type * @param mixed $id * * @return AAM_Core_Object * * @access public */ public function getObject($type, $id = 'none', $param = null) { $object = null; //performance optimization $id = (is_scalar($id) ? $id : 'none'); //prevent from any surprises //check if there is an object with specified ID if (!isset($this->_objects[$type][$id])) { $classname = 'AAM_Core_Object_' . ucfirst($type); if (class_exists($classname)) { $object = new $classname($this, (is_null($param) ? $id : $param)); } $object = apply_filters('aam-object-filter', $object, $type, $id, $this); if (is_a($object, 'AAM_Core_Object')) { $this->_objects[$type][$id] = $object; } } else { $object = $this->_objects[$type][$id]; } return $object; } /** * Check if subject has capability * * @param string $capability * * @return boolean * * @access public */ public function hasCapability($capability) { $subject = $this->getSubject(); return ($subject ? $subject->has_cap($capability) : false); } /** * Save option * * @param string $param * @param mixed $value * @param string $object * @param mixed $objectId * * @return boolean * * @access public */ public function save($param, $value, $object, $objectId = 0) { return $this->getObject($object, $objectId)->save($param, $value); } /** * Reset object * * @param string $object * * @return boolean * * @access public */ public function resetObject($object) { return $this->deleteOption($object); } /** * Delete option * * @param string $object * @param mixed $id * * @return boolean * * @access public */ public function deleteOption($object, $id = 0) { return AAM_Core_API::deleteOption($this->getOptionName($object, $id)); } /** * Retrieve list of subject's capabilities * * @return array * * @access public */ public function getCapabilities() { return array(); } /** * Retrieve subject based on used class * * @return void * * @access protected */ protected function retrieveSubject() { return null; } /** * */ abstract public function getOptionName($object, $id); /** * Read object from parent subject * * @param string $object * @param mixed $id * * @return mixed * * @access public */ public function inheritFromParent($object, $id = '', $param = null){ if ($subject = $this->getParent()){ $option = $subject->getObject($object, $id, $param)->getOption(); } else { $option = null; } return $option; } /** * Retrieve parent subject * * If there is no parent subject, return null * * @return AAM_Core_Subject|null * * @access public */ public function getParent() { return null; } }
mandino/nu
wp-content/plugins/advanced-access-manager/Application/Core/Subject.php
PHP
mit
7,033
package org.diorite.impl.connection.packets.play.server; import java.io.IOException; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; import org.diorite.impl.connection.EnumProtocol; import org.diorite.impl.connection.EnumProtocolDirection; import org.diorite.impl.connection.packets.PacketClass; import org.diorite.impl.connection.packets.PacketDataSerializer; import org.diorite.impl.connection.packets.play.PacketPlayServerListener; import org.diorite.impl.connection.packets.play.client.PacketPlayClientResourcePackStatus; @PacketClass(id = 0x48, protocol = EnumProtocol.PLAY, direction = EnumProtocolDirection.CLIENTBOUND, size = 180) public class PacketPlayServerResourcePackSend extends PacketPlayServer { private String url; // ~130 bytes private String hash; // ~41 bytes public PacketPlayServerResourcePackSend() { } public PacketPlayServerResourcePackSend(final String url, final String hash) { if (hash.length() > PacketPlayClientResourcePackStatus.MAX_HASH_SIZE) { throw new IllegalArgumentException("Hash is too long (max 40, was " + hash.length() + ")"); } this.url = url; this.hash = hash; } public String getUrl() { return this.url; } public void setUrl(final String url) { this.url = url; } public String getHash() { return this.hash; } public void setHash(final String hash) { this.hash = hash; } @Override public void readPacket(final PacketDataSerializer data) throws IOException { this.url = data.readText(Short.MAX_VALUE); this.hash = data.readText(PacketPlayClientResourcePackStatus.MAX_HASH_SIZE); } @Override public void writeFields(final PacketDataSerializer data) throws IOException { data.writeText(this.url); data.writeText(this.hash); } @Override public void handle(final PacketPlayServerListener listener) { listener.handle(this); } @Override public String toString() { return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE).appendSuper(super.toString()).append("url", this.url).append("hash", this.hash).toString(); } }
marszczybrew/Diorite
DioriteCore/src/main/java/org/diorite/impl/connection/packets/play/server/PacketPlayServerResourcePackSend.java
Java
mit
2,319
using UnityEngine; using System.Collections; public class ShapeInfo { public int Column { get; set; } public int Row { get; set; } }
michael-munoz/MooMooPlanet
Project455/Assets/Scripts/ShapeInfo.cs
C#
mit
145
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.azure.resourcemanager.trafficmanager.implementation; import com.azure.core.management.Region; import com.azure.resourcemanager.resources.fluentcore.utils.ResourceManagerUtils; import com.azure.resourcemanager.trafficmanager.fluent.EndpointsClient; import com.azure.resourcemanager.trafficmanager.fluent.models.EndpointInner; import com.azure.resourcemanager.trafficmanager.models.TrafficManagerNestedProfileEndpoint; /** Implementation for {@link TrafficManagerNestedProfileEndpoint}. */ class TrafficManagerNestedProfileEndpointImpl extends TrafficManagerEndpointImpl implements TrafficManagerNestedProfileEndpoint { TrafficManagerNestedProfileEndpointImpl( String name, TrafficManagerProfileImpl parent, EndpointInner inner, EndpointsClient client) { super(name, parent, inner, client); } @Override public String nestedProfileId() { return innerModel().targetResourceId(); } @Override public long minimumChildEndpointCount() { return ResourceManagerUtils.toPrimitiveLong(innerModel().minChildEndpoints()); } @Override public Region sourceTrafficLocation() { return Region.fromName((innerModel().endpointLocation())); } }
selvasingh/azure-sdk-for-java
sdk/resourcemanager/azure-resourcemanager-trafficmanager/src/main/java/com/azure/resourcemanager/trafficmanager/implementation/TrafficManagerNestedProfileEndpointImpl.java
Java
mit
1,325
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _assign = require('lodash/assign'); var _assign2 = _interopRequireDefault(_assign); exports.default = termsAggregation; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } /** * Construct a Terms aggregation. * * @param {String} field Field name to aggregate over. * @param {String} name Aggregation name. Defaults to agg_terms_<field>. * @param {Object} opts Additional options to include in the aggregation. * @return {Object} Terms aggregation. */ function termsAggregation(field, name, opts) { name = name || 'agg_terms_' + field; return _defineProperty({}, name, { terms: function () { return (0, _assign2.default)({ field: field }, opts); }() }); }
evgenypoyarkov/bodybuilder
lib/aggregations/terms-aggregation.js
JavaScript
mit
1,036
YUI.add('selector', function (Y, NAME) { }, '3.10.3', {"requires": ["selector-native"]});
braz/mojito-helloworld
node_modules/mojito/node_modules/yui/selector/selector.js
JavaScript
mit
93
using System.Linq; using Xunit; using Signum.Engine; using Signum.Entities; using Signum.Utilities; using Signum.Test.Environment; namespace Signum.Test.LinqProvider { /// <summary> /// Summary description for LinqProvider /// </summary> public class JoinGroupTest { public JoinGroupTest() { MusicStarter.StartAndLoad(); Connector.CurrentLogger = new DebugTextWriter(); } [Fact] public void Join() { var songsAlbum = (from a in Database.Query<AlbumEntity>() join b in Database.Query<AlbumEntity>().SelectMany(a => a.Songs) on a.Name equals b.Name select new { a.Name, Label = a.Label.Name }).ToList(); } [Fact] public void JoinEntity() { var songsAlbum = (from a in Database.Query<ArtistEntity>() join b in Database.Query<AlbumEntity>() on a equals b.Author select new { Artist = a.Name, Album = b.Name }).ToList(); } [Fact] public void JoinEntityTwice() { var algums = (from a1 in Database.Query<AlbumEntity>() join a2 in Database.Query<AlbumEntity>() on a1.Label equals a2.Label join a3 in Database.Query<AlbumEntity>() on a2.Label equals a3.Label select new { Name1 = a1.Name, Name2 = a2.Name, Name3 = a3.Name }).ToList(); } [Fact] public void JoinerExpansions() { var labels = Database.Query<AlbumEntity>().Join( Database.Query<AlbumEntity>(), a => a.Year, a => a.Year, (a1, a2) => a1.Label.Name + " " + a2.Label.Name).ToList(); } [Fact] public void LeftOuterJoinEntity() { var songsAlbum = (from a in Database.Query<ArtistEntity>().DefaultIfEmpty() join b in Database.Query<AlbumEntity>() on a equals b.Author select new { Artist = a.Name, Album = b.Name }).ToList(); } [Fact] public void LeftOuterJoinEntityNotNull() { var songsAlbum = (from a in Database.Query<ArtistEntity>().DefaultIfEmpty() join b in Database.Query<AlbumEntity>() on a equals b.Author select new { Artist = a.Name, Album = b.Name, HasArtist = a != null }).ToList(); } [Fact] public void RightOuterJoinEntity() { var songsAlbum = (from a in Database.Query<ArtistEntity>() join b in Database.Query<AlbumEntity>().DefaultIfEmpty() on a equals b.Author select new { Artist = a.Name, Album = b.Name }).ToList(); } [Fact] public void RightOuterJoinEntityNotNull() { var songsAlbum = (from a in Database.Query<ArtistEntity>() join b in Database.Query<AlbumEntity>().DefaultIfEmpty() on a equals b.Author select new { Artist = a.Name, Album = b.Name, HasArtist = b != null }).ToList(); } [Fact] public void FullOuterJoinEntity() { var songsAlbum = (from a in Database.Query<ArtistEntity>().DefaultIfEmpty() join b in Database.Query<AlbumEntity>().DefaultIfEmpty() on a equals b.Author select new { Artist = a.Name, Album = b.Name }).ToList(); } [Fact] public void FullOuterJoinEntityNotNull() { var songsAlbum = (from a in Database.Query<ArtistEntity>().DefaultIfEmpty() join b in Database.Query<AlbumEntity>().DefaultIfEmpty() on a equals b.Author select new { Artist = a.Name, Album = b.Name, HasArtist = a != null, HasAlbum = b != null }).ToList(); } [Fact] public void JoinGroup() { var songsAlbum = (from a in Database.Query<ArtistEntity>() join b in Database.Query<AlbumEntity>() on a equals b.Author into g select new { a.Name, Albums = (int?)g.Count() }).ToList(); } [Fact] public void LeftOuterJoinGroup() { var songsAlbum = (from a in Database.Query<ArtistEntity>() join b in Database.Query<AlbumEntity>().DefaultIfEmpty() on a equals b.Author into g select new { a.Name, Albums = (int?)g.Count() }).ToList(); } [TableName("#MyView")] class MyTempView : IView { [ViewPrimaryKey] public Lite<ArtistEntity> Artist { get; set; } } [Fact] public void LeftOuterMyView() { using (Transaction tr = new Transaction()) { Administrator.CreateTemporaryTable<MyTempView>(); Database.Query<ArtistEntity>().Where(a => a.Name.StartsWith("M")).UnsafeInsertView(a => new MyTempView { Artist = a.ToLite() }); var artists = (from a in Database.Query<ArtistEntity>() join b in Database.View<MyTempView>() on a.ToLite() equals b.Artist into g select a.ToLite()).ToList(); Assert.True(artists.All(a => a.ToString()!.StartsWith("M"))); var list1 = Database.View<MyTempView>().ToList(); var list2 = Database.Query<ArtistEntity>().Where(a => a.Name.StartsWith("M")).ToList(); Assert.Equal(list1.Count, list2.Count); tr.Commit(); } } } }
AlejandroCano/framework
Signum.Test/LinqProvider/JoinGroupTest.cs
C#
mit
6,007
<?php session_start(); require('php/userProfile.class.php'); //load userProfileclass ?> <!DOCTYPE html> <html> <head> <?php require("head_userpage.php"); //load special header only for this page ?> </head> <body> <?php if(isset($_SESSION['ID'])){ //load the appropriate menu require("menu_co.php"); }else{ require("menu_pasco_general.php"); } ?> <div class="site-pusher"> <div class="content"> <?php if(!isset($errorProfile)){ require("disp_user_profile.php"); //load banner, pseudo and avatar of the current user require("disp_info_user.php"); //load info box for the user ?> <div class="fade"></div> <div class=blockallz> <?php $userPage->printPosts('profile'); //show all posts of the user (userProfile.class.php) }else{ include('disp_userNotExist.php'); //if we can't find user } ?> </div> <?php require("js/animation_user.php") ?> <script src="js/explore.js"></script> </body> </html>
KamevoTeam/Kamevo
kamevo_src/user.php
PHP
mit
962
<?php /* * This file is part of the PHPExifTool package. * * (c) Alchemy <support@alchemy.fr> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPExiftool\Driver\Tag\Pentax; use JMS\Serializer\Annotation\ExclusionPolicy; use PHPExiftool\Driver\AbstractTag; /** * @ExclusionPolicy("all") */ class InternalSerialNumber extends AbstractTag { protected $Id = 4; protected $Name = 'InternalSerialNumber'; protected $FullName = 'Pentax::CameraInfo'; protected $GroupName = 'Pentax'; protected $g0 = 'MakerNotes'; protected $g1 = 'Pentax'; protected $g2 = 'Camera'; protected $Type = 'int32u'; protected $Writable = true; protected $Description = 'Internal Serial Number'; protected $flag_Permanent = true; }
bburnichon/PHPExiftool
lib/PHPExiftool/Driver/Tag/Pentax/InternalSerialNumber.php
PHP
mit
862
using StyletIoC.Creation; using System; using System.Collections.Generic; using System.Linq.Expressions; namespace StyletIoC.Internal.Creators { /// <summary> /// Base class for all ICreators (which want to use it). Provides convenience /// </summary> internal abstract class CreatorBase : ICreator { public virtual RuntimeTypeHandle TypeHandle { get; protected set; } protected IRegistrationContext ParentContext { get; set; } protected CreatorBase(IRegistrationContext parentContext) { this.ParentContext = parentContext; } // Common utility method protected Expression CompleteExpressionFromCreator(Expression creator, ParameterExpression registrationContext) { var type = Type.GetTypeFromHandle(this.TypeHandle); var instanceVar = Expression.Variable(type, "instance"); var assignment = Expression.Assign(instanceVar, creator); var buildUpExpression = this.ParentContext.GetBuilderUpper(type).GetExpression(instanceVar, registrationContext); // We always start with: // var instance = new Class(.....) // instance.Property1 = new .... // instance.Property2 = new .... var blockItems = new List<Expression>() { assignment, buildUpExpression }; // If it implements IInjectionAware, follow that up with: // instance.ParametersInjected() if (typeof(IInjectionAware).IsAssignableFrom(type)) blockItems.Add(Expression.Call(instanceVar, typeof(IInjectionAware).GetMethod("ParametersInjected"))); // Final appearance of instanceVar, as this sets the return value of the block blockItems.Add(instanceVar); var completeExpression = Expression.Block(new[] { instanceVar }, blockItems); return completeExpression; } public abstract Expression GetInstanceExpression(ParameterExpression registrationContext); } }
canton7/Stylet
Stylet/StyletIoC/Internal/Creators/CreatorBase.cs
C#
mit
2,037
import { Directive, ElementRef, EventEmitter, Output, Input, OnInit } from '@angular/core'; import { TcCollectionService } from '../tc-collection/tc-collection.service'; import { TcCollection } from '../tc-collection/tc-collection.class'; declare var $: any; @Directive({ selector: '[tc-sortable]' }) export class TcSortableDirective { @Input('ignoreItem') ignoreItem = 0; @Input('list') list: any[]; @Input('ghostClass') ghostClass: string; @Output() itemMoved = new EventEmitter(); private element: HTMLElement; constructor(public el: ElementRef, private collectionService: TcCollectionService) { } ngOnInit() { this.element = this.el.nativeElement; var elCopy = this.element; let newIndex; let oldIndex; $(this.element).sortable({ placeholder: this.ghostClass, helper: function(x, y){ y.addClass('card-moving'); return y }, handle: '.card-collection--drag-handle', cancel: '.cancel-sort', tolerance: "pointer", items: "> :not(.not-sortable-item)", scroll: false, start: (event, ui) => { $(this).attr('data-previndex', ui.item.index()); }, update: (event, ui) => { newIndex = ui.item.index()-this.ignoreItem; oldIndex = $(this).attr('data-previndex')-this.ignoreItem; $(this).removeAttr('data-previndex'); }, stop: (event, ui) => { ui.item.removeClass('card-moving'); let tmpItem = this.list[oldIndex]; if(!tmpItem) return; tmpItem.position = newIndex; tmpItem.updatePosition = true; this.itemMoved.emit({ value: {modifiedItem: tmpItem} }) tmpItem.updatePosition = false; this.list.splice(oldIndex,1); this.list.splice(newIndex, 0, tmpItem); for(let i in this.list){ this.list[i].position = i; } } }) } }
OlivierCoue/invow
src/app/tc-shared/tc-sortable.directive.ts
TypeScript
mit
2,177
#include "stdafx.h" #include "WindowClient.h" #include <SDL2/SDL.h> int main(int, char *[]) { try { CWindow window(ContextProfile::RobustOpenGL_3_2, ContextMode::Normal); // window.ShowFullscreen("Demo #19 (Particle Systems)"); window.Show("Demo #19 (Particle Systems)", {800, 600}); CWindowClient client(window); window.DoMainLoop(); } catch (const std::exception &ex) { const char *title = "Fatal Error"; const char *message = ex.what(); SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, title, message, nullptr); } return 0; }
PS-Group/cg_course_examples
chapter_4/lesson_19/main.cpp
C++
mit
620
/** */ package gluemodel.COSEM.COSEMObjects.impl; import gluemodel.COSEM.COSEMObjects.COSEMObjectsPackage; import gluemodel.COSEM.COSEMObjects.PushSchedule; import gluemodel.COSEM.InterfaceClasses.impl.SingleactionscheduleImpl; import org.eclipse.emf.ecore.EClass; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Push Schedule</b></em>'. * <!-- end-user-doc --> * * @generated */ public class PushScheduleImpl extends SingleactionscheduleImpl implements PushSchedule { /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected PushScheduleImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return COSEMObjectsPackage.eINSTANCE.getPushSchedule(); } } //PushScheduleImpl
georghinkel/ttc2017smartGrids
solutions/eMoflon/rgse.ttc17.metamodels.src/src/gluemodel/COSEM/COSEMObjects/impl/PushScheduleImpl.java
Java
mit
844
//------------------------------------------------------------------------------ // dummyFSWrapper.cc //------------------------------------------------------------------------------ #include "Pre.h" #include "dummyFSWrapper.h" namespace Oryol { namespace _priv { //------------------------------------------------------------------------------ dummyFSWrapper::handle dummyFSWrapper::openRead(const char* path) { return invalidHandle; } //------------------------------------------------------------------------------ dummyFSWrapper::handle dummyFSWrapper::openWrite(const char* path) { return invalidHandle; } //------------------------------------------------------------------------------ int dummyFSWrapper::write(handle f, const void* ptr, int numBytes) { return 0; } //------------------------------------------------------------------------------ int dummyFSWrapper::read(handle f, void* ptr, int numBytes) { return 0; } //------------------------------------------------------------------------------ bool dummyFSWrapper::seek(handle f, int offset) { return true; } //------------------------------------------------------------------------------ int dummyFSWrapper::size(handle f) { return 0; } //------------------------------------------------------------------------------ void dummyFSWrapper::close(handle f) { // empty } //------------------------------------------------------------------------------ String dummyFSWrapper::getExecutableDir() { return String(); } //------------------------------------------------------------------------------ String dummyFSWrapper::getCwd() { return String(); } } // namespace _priv } // namespace Oryol
floooh/oryol
code/Modules/LocalFS/private/dummy/dummyFSWrapper.cc
C++
mit
1,707
module Jekyll VERSION = '3.0.0.pre.beta6' end
mixxmac/jekyll
lib/jekyll/version.rb
Ruby
mit
48
import logging from django.conf import settings from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from django.db import models from django.utils.translation import ugettext_lazy as _ from wagtail.admin.edit_handlers import FieldPanel, MultiFieldPanel from wagtail.core.fields import RichTextField from wagtail.core.models import Page from wagtail.images.models import Image from wagtail.images.edit_handlers import ImageChooserPanel class PhotoGalleryIndexPage(Page): intro = RichTextField(blank=True) feed_image = models.ForeignKey( Image, help_text="An optional image to represent the page", null=True, blank=True, on_delete=models.SET_NULL, related_name='+' ) indexed_fields = ('intro') @property def galleries(self): galleries = GalleryIndex.objects.live().descendant_of(self) galleries = galleries.order_by('-first_published_at') return galleries def get_context(self, request): galleries = self.galleries page = request.GET.get('page') paginator = Paginator(galleries, 16) try: galleries = paginator.page(page) except PageNotAnInteger: galleries = paginator.page(1) except EmptyPage: galleries = paginator.page(paginator.num_pages) context = super(PhotoGalleryIndexPage, self).get_context(request) context['galleries'] = galleries return context class Meta: verbose_name = _('Photo Gallery Index') PhotoGalleryIndexPage.content_panels = [ FieldPanel('title', classname="full title"), FieldPanel('intro', classname="full"), ] PhotoGalleryIndexPage.promote_panels = [ MultiFieldPanel(Page.promote_panels, "Common page configuration"), ImageChooserPanel('feed_image'), ] IMAGE_ORDER_TYPES = ( (1, 'Image title'), (2, 'Newest image first'), ) class GalleryIndex(Page): intro = RichTextField( blank=True, verbose_name=_('Intro text'), help_text=_('Optional text to go with the intro text.') ) collection = models.ForeignKey( 'wagtailcore.Collection', verbose_name=_('Collection'), null=True, blank=False, on_delete=models.SET_NULL, related_name='+', help_text=_('Show images in this collection in the gallery view.') ) images_per_page = models.IntegerField( default=20, verbose_name=_('Images per page'), help_text=_('How many images there should be on one page.') ) order_images_by = models.IntegerField(choices=IMAGE_ORDER_TYPES, default=1) feed_image = models.ForeignKey( Image, help_text="An optional image to represent the page", null=True, blank=True, on_delete=models.SET_NULL, related_name='+' ) content_panels = Page.content_panels + [ FieldPanel('intro', classname='full title'), FieldPanel('collection'), FieldPanel('images_per_page', classname='full title'), FieldPanel('order_images_by'), ] promote_panels = [ MultiFieldPanel(Page.promote_panels, "Common page configuration"), ImageChooserPanel('feed_image'), ] @property def images(self): return get_gallery_images(self.collection.name, self) def get_context(self, request): images = self.images page = request.GET.get('page') paginator = Paginator(images, self.images_per_page) try: images = paginator.page(page) except PageNotAnInteger: images = paginator.page(1) except EmptyPage: images = paginator.page(paginator.num_pages) context = super(GalleryIndex, self).get_context(request) context['gallery_images'] = images return context class Meta: verbose_name = _('Photo Gallery') verbose_name_plural = _('Photo Galleries') template = getattr(settings, 'GALLERY_TEMPLATE', 'gallery/gallery_index.html') def get_gallery_images(collection, page=None, tags=None): images = None try: images = Image.objects.filter(collection__name=collection) if page: if page.order_images_by == 0: images = images.order_by('title') elif page.order_images_by == 1: images = images.order_by('-created_at') except Exception as e: logging.exception(e) if images and tags: images = images.filter(tags__name__in=tags).distinct() return images
ilendl2/wagtail-cookiecutter-foundation
{{cookiecutter.project_slug}}/gallery/models.py
Python
mit
4,587
// // client.cpp // ~~~~~~~~~~ // // Copyright (c) 2003-2015 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <asio.hpp> #include <boost/lambda/lambda.hpp> #include <boost/lambda/bind.hpp> #include <boost/lambda/if.hpp> #include <boost/shared_ptr.hpp> #include <algorithm> #include <cstdlib> #include <exception> #include <iostream> #include <string> #include "protocol.hpp" using namespace boost; using asio::ip::tcp; using asio::ip::udp; int main(int argc, char* argv[]) { try { if (argc != 3) { std::cerr << "Usage: client <host> <port>\n"; return 1; } using namespace std; // For atoi. std::string host_name = argv[1]; std::string port = argv[2]; asio::io_context io_context; // Determine the location of the server. tcp::resolver resolver(io_context); tcp::endpoint remote_endpoint = *resolver.resolve(host_name, port).begin(); // Establish the control connection to the server. tcp::socket control_socket(io_context); control_socket.connect(remote_endpoint); // Create a datagram socket to receive data from the server. boost::shared_ptr<udp::socket> data_socket( new udp::socket(io_context, udp::endpoint(udp::v4(), 0))); // Determine what port we will receive data on. udp::endpoint data_endpoint = data_socket->local_endpoint(); // Ask the server to start sending us data. control_request start = control_request::start(data_endpoint.port()); asio::write(control_socket, start.to_buffers()); unsigned long last_frame_number = 0; for (;;) { // Receive 50 messages on the current data socket. for (int i = 0; i < 50; ++i) { // Receive a frame from the server. frame f; data_socket->receive(f.to_buffers(), 0); if (f.number() > last_frame_number) { last_frame_number = f.number(); std::cout << "\n" << f.payload(); } } // Time to switch to a new socket. To ensure seamless handover we will // continue to receive packets using the old socket until data arrives on // the new one. std::cout << " Starting renegotiation"; // Create the new data socket. boost::shared_ptr<udp::socket> new_data_socket( new udp::socket(io_context, udp::endpoint(udp::v4(), 0))); // Determine the new port we will use to receive data. udp::endpoint new_data_endpoint = new_data_socket->local_endpoint(); // Ask the server to switch over to the new port. control_request change = control_request::change( data_endpoint.port(), new_data_endpoint.port()); asio::error_code control_result; asio::async_write(control_socket, change.to_buffers(), ( lambda::var(control_result) = lambda::_1 )); // Try to receive a frame from the server on the new data socket. If we // successfully receive a frame on this new data socket we can consider // the renegotation complete. In that case we will close the old data // socket, which will cause any outstanding receive operation on it to be // cancelled. frame f1; asio::error_code new_data_socket_result; new_data_socket->async_receive(f1.to_buffers(), ( // Note: lambda::_1 is the first argument to the callback handler, // which in this case is the error code for the operation. lambda::var(new_data_socket_result) = lambda::_1, lambda::if_(!lambda::_1) [ // We have successfully received a frame on the new data socket, // so we can close the old data socket. This will cancel any // outstanding receive operation on the old data socket. lambda::var(data_socket) = boost::shared_ptr<udp::socket>() ] )); // This loop will continue until we have successfully completed the // renegotiation (i.e. received a frame on the new data socket), or some // unrecoverable error occurs. bool done = false; while (!done) { // Even though we're performing a renegotation, we want to continue // receiving data as smoothly as possible. Therefore we will continue to // try to receive a frame from the server on the old data socket. If we // receive a frame on this socket we will interrupt the io_context, // print the frame, and resume waiting for the other operations to // complete. frame f2; done = true; // Let's be optimistic. if (data_socket) // Might have been closed by new_data_socket's handler. { data_socket->async_receive(f2.to_buffers(), 0, ( lambda::if_(!lambda::_1) [ // We have successfully received a frame on the old data // socket. Stop the io_context so that we can print it. lambda::bind(&asio::io_context::stop, &io_context), lambda::var(done) = false ] )); } // Run the operations in parallel. This will block until all operations // have finished, or until the io_context is interrupted. (No threads!) io_context.restart(); io_context.run(); // If the io_context.run() was interrupted then we have received a frame // on the old data socket. We need to keep waiting for the renegotation // operations to complete. if (!done) { if (f2.number() > last_frame_number) { last_frame_number = f2.number(); std::cout << "\n" << f2.payload(); } } } // Since the loop has finished, we have either successfully completed // the renegotation, or an error has occurred. First we'll check for // errors. if (control_result) throw asio::system_error(control_result); if (new_data_socket_result) throw asio::system_error(new_data_socket_result); // If we get here it means we have successfully started receiving data on // the new data socket. This new data socket will be used from now on // (until the next time we renegotiate). std::cout << " Renegotiation complete"; data_socket = new_data_socket; data_endpoint = new_data_endpoint; if (f1.number() > last_frame_number) { last_frame_number = f1.number(); std::cout << "\n" << f1.payload(); } } } catch (std::exception& e) { std::cerr << "Exception: " << e.what() << std::endl; } return 0; }
mojmir-svoboda/BlackBoxTT
3rd_party/asio/src/examples/cpp03/porthopper/client.cpp
C++
mit
6,839
'use strict'; //Setting up route angular.module('mean.articles').config(['$stateProvider', 'markedProvider', function($stateProvider, markedProvider) { markedProvider.setOptions({ gfm: true, tables: true, breaks: true, highlight: function (code) { /* jshint ignore:start */ return hljs.highlightAuto(code).value; /* jshint ignore:end */ } }); // Check if the user is connected var checkLoggedin = function($q, $timeout, $http, $location) { // Initialize a new promise var deferred = $q.defer(); // Make an AJAX call to check if the user is logged in $http.get('/loggedin').success(function(user) { // Authenticated if (user !== '0') $timeout(deferred.resolve); // Not Authenticated else { $timeout(deferred.reject); $location.url('/login'); } }); return deferred.promise; }; // states for my app $stateProvider .state('all articles', { url: '/articles', templateUrl: 'articles/views/list.html', //resolve: { // loggedin: checkLoggedin //} }) .state('create article', { url: '/articles/create', templateUrl: 'articles/views/create.html', resolve: { loggedin: checkLoggedin } }) .state('edit article', { url: '/articles/:articleId/edit', templateUrl: 'articles/views/edit.html', resolve: { loggedin: checkLoggedin } }) .state('article by id', { url: '/articles/:articleId', templateUrl: 'articles/views/view.html', //resolve: { // loggedin: checkLoggedin //} }); } ]);
darul75/nsjoy.github.io2
packages/articles/public/routes/articles.js
JavaScript
mit
1,768
/**************************************************************************** Copyright (c) 2011-2013,WebJet Business Division,CYOU http://www.genesis-3d.com.cn Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ using System; using System.Runtime.CompilerServices; using ScriptRuntime; namespace ScriptRuntime { /// <summary> /// 网格渲染组件类 /// </summary> public partial class MeshRenderComponent : RenderComponent { // - internal call declare [MethodImplAttribute(MethodImplOptions.InternalCall)] extern private static void ICall_MeshRenderComponent_SetMeshID(MeshRenderComponent self, String sMeshId, int priority); [MethodImplAttribute(MethodImplOptions.InternalCall)] extern private static void ICall_MeshRenderComponent_SetDrawDepth(MeshRenderComponent self, bool bDraw); [MethodImplAttribute(MethodImplOptions.InternalCall)] extern private static int ICall_MeshRenderComponent_GetTriangleCount(MeshRenderComponent self); [MethodImplAttribute(MethodImplOptions.InternalCall)] extern private static int ICall_MeshRenderComponent_GetVertexCount(MeshRenderComponent self); [MethodImplAttribute(MethodImplOptions.InternalCall)] extern private static string ICall_MeshRenderComponent_GetMeshID(MeshRenderComponent self); } }
EngineDreamer/DreamEngine
Engine/script/runtimelibrary/MeshRenderComponent_register.cs
C#
mit
2,409
using System; using System.Text; using System.Threading.Tasks; using System.Collections.Generic; using AuthorizeNet.Api.Controllers; using AuthorizeNet.Api.Contracts.V1; using AuthorizeNet.Api.Controllers.Bases; namespace net.authorize.sample { class PayPalPriorAuthorizationCapture { public static void Run(String ApiLoginID, String ApiTransactionKey, string TransactionID) { Console.WriteLine("PayPal Prior Authorization Transaction"); ApiOperationBase<ANetApiRequest, ANetApiResponse>.RunEnvironment = AuthorizeNet.Environment.SANDBOX; // define the merchant information (authentication / transaction id) ApiOperationBase<ANetApiRequest, ANetApiResponse>.MerchantAuthentication = new merchantAuthenticationType() { name = ApiLoginID, ItemElementName = ItemChoiceType.transactionKey, Item = ApiTransactionKey }; var payPalType = new payPalType { cancelUrl = "http://www.merchanteCommerceSite.com/Success/TC25262", successUrl = "http://www.merchanteCommerceSite.com/Success/TC25262", // the url where the user will be returned to }; //standard api call to retrieve response var paymentType = new paymentType { Item = payPalType }; var transactionRequest = new transactionRequestType { transactionType = transactionTypeEnum.priorAuthCaptureTransaction.ToString(), // capture a prior authorization payment = paymentType, amount = 19.45m, refTransId = TransactionID // the TransID value that was returned from the first AuthOnlyTransaction call }; var request = new createTransactionRequest { transactionRequest = transactionRequest }; // instantiate the contoller that will call the service var controller = new createTransactionController(request); controller.Execute(); // get the response from the service (errors contained if any) var response = controller.GetApiResponse(); //validate if (response.messages.resultCode == messageTypeEnum.Ok) { if (response.transactionResponse != null) { Console.WriteLine("Success, Auth Code : " + response.transactionResponse.authCode); } } else { Console.WriteLine("Error: " + response.messages.message[0].code + " " + response.messages.message[0].text); if (response.transactionResponse != null) { Console.WriteLine("Transaction Error : " + response.transactionResponse.errors[0].errorCode + " " + response.transactionResponse.errors[0].errorText); } } } } }
rmorrin/sample-code-csharp
PaypalExpressCheckout/PriorAuthorizationCapture.cs
C#
mit
3,051
BASE.require(["Object"], function () { BASE.namespace("LG.core.dataModel.core"); LG.core.dataModel.core.PeopleGroupToPermission = (function (Super) { var PeopleGroupToPermission = function () { var self = this; if (!(self instanceof arguments.callee)) { return new PeopleGroupToPermission(); } Super.call(self); return self; }; BASE.extend(PeopleGroupToPermission, Super); return PeopleGroupToPermission; }(Object)); });
jaredjbarnes/WoodlandCreatures
packages/WebLib.2.0.0.724/content/lib/weblib/lib/BASE/LG/core/dataModel/core/PeopleGroupToPermission.js
JavaScript
mit
545
<?php /* * This File is part of the Lucid\Mux package * * (c) iwyg <mail@thomas-appel.com> * * For full copyright and license information, please refer to the LICENSE file * that was distributed with this package. */ namespace Lucid\Mux\Tests; use Lucid\Mux\Route; /** * @class RouteTest * * @package Lucid\Mux * @version $Id$ * @author iwyg <mail@thomas-appel.com> */ class RouteTest extends \PHPUnit_Framework_TestCase { /** @test */ public function itShouldBeInstantiable() { $this->assertInstanceOf('Lucid\Mux\RouteInterface', $this->newRoute()); } /** @test */ public function itShouldGetPattern() { $route = new Route($pattern = '/user/{id}', 'action'); $this->assertSame($pattern, $route->getPattern()); } /** @test */ public function itShouldBeSerializable() { $route = new Route( $pattern = '/user/{id}', $handler = 'action', $methods = ['DELETE'], $host = 'example.com', $defaults = ['id' => 12], $constraints = ['id' => '\d+'], $schemes = ['https'] ); $newRoute = unserialize(serialize($route)); $this->assertSame($pattern, $newRoute->getPattern()); $this->assertSame($handler, $newRoute->getHandler()); $this->assertSame($methods, $newRoute->getMethods()); $this->assertSame($host, $newRoute->getHost()); $this->assertSame($defaults, $newRoute->getDefaults()); $this->assertSame($constraints, $newRoute->getConstraints()); $this->assertSame($schemes, $newRoute->getSchemes()); } /** @test */ public function itShouldThrowIfSerializedAndAnderIsClosure() { $route = new Route('/', function () { }); try { serialize($route); } catch (\LogicException $e) { $this->assertEquals('Cannot serialize handler.', $e->getMessage()); } } /** @test */ public function itShouldGetMethods() { $route = new Route('/', 'action', ['POST']); $this->assertTrue($route->hasMethod('post')); $route = new Route('/', 'action', $methods = ['get', 'head']); $this->assertTrue($route->hasMethod('get')); $this->assertTrue($route->hasMethod('head')); $this->assertSame(['GET', 'HEAD'], $route->getMethods()); } /** @test */ public function itShouldGetSchemes() { $route = new Route('/', 'action'); $this->assertTrue($route->hasScheme('http')); $this->assertTrue($route->hasScheme('https')); $route = new Route('/', 'action', null, null, null, null, ['https']); $this->assertFalse($route->hasScheme('http')); $this->assertTrue($route->hasScheme('HTTPS')); $route = new Route('/', 'action', null, null, null, null, null, ['HTTP', 'https']); $this->assertSame(['http', 'https'], $route->getSchemes()); } /** @test */ public function itShouldGetHost() { $route = new Route('/', 'action'); $this->assertNull($route->getHost()); $route = new Route('/', 'action', null, $host = 'example.com'); $this->assertSame($host, $route->getHost()); } /** @test */ public function itShouldGetDefaults() { $route = new Route('/', 'action', null, null, $def = ['foo' => 'bar']); $this->assertSame($def, $route->getDefaults()); $this->assertSame('bar', $route->getDefault('foo')); } /** @test */ public function itShouldGetConstraints() { $route = new Route('/', 'action', null, null, null, $const = ['foo' => 'bar']); $this->assertSame($const, $route->getConstraints()); $this->assertSame('bar', $route->getConstraint('foo')); } /** @test */ public function itShouldCallParser() { $route = $this->getMock(Route::class, ['getParserFunc'], ['/', 'action']); $route->method('getParserFunc')->willReturnCallback(function () { return function () { return 'RouteContext'; }; }); $this->assertSame('RouteContext', $route->getContext()); } private function newRoute($path = '/', $handler = 'action') { return new Route($path, $handler); } }
lucidphp/mux
tests/RouteTest.php
PHP
mit
4,374
"""Splits the time dimension into an reftime and a leadtime so that multiple files can be concatenated more easily""" import sys from netCDF4 import Dataset, num2date, date2num for f in sys.argv[1:]: dataset = Dataset(f, 'a') # rename record dimension to reftime dataset.renameDimension('record', 'reftime') # rename time dimension to leadtime dataset.renameDimension('time', 'leadtime') dataset.renameVariable('time', 'leadtime') time = dataset.variables['leadtime'] reftime = dataset.createVariable('reftime', 'f8', ('reftime',)) reftime.units = time.units reftime.calendar = time.calendar reftime[0] = time[0] reftime.standard_name = "forecast_reference_time" reftime.long_name = "Time of model initialization" dt = num2date(time[:], units=time.units, calendar=time.calendar) lt = date2num(dt, units="hours since %s" % dt[0], calendar=time.calendar) # use the existing time variable to hold lead time information time.units = "hours" time.standard_name = "forecast_period" time.long_name = "hours since forecast_reference_time" time[:] = lt del(time.calendar) dataset.renameVariable('location', 'old_location') dataset.renameVariable('lat', 'old_lat') dataset.renameVariable('lon', 'old_lon') dataset.renameVariable('height', 'old_height') loc = dataset.createVariable('location', 'S1', ('location','loc_str_length')) lat = dataset.createVariable('lat', 'f8', ('location',)) lon = dataset.createVariable('lon', 'f8', ('location',)) hgt = dataset.createVariable('height','i4',('height',)) loc[:] = dataset.variables['old_location'][0] lat[:] = dataset.variables['old_lat'][0] lon[:] = dataset.variables['old_lon'][0] hgt[:] = dataset.variables['old_height'][0] dataset.close()
samwisehawkins/wrftools
util/split_time_dimension.py
Python
mit
1,878
/* global chrome */ const VERSION = 1; const handlers = { 'vclub:screenShare:requestSourceId': () => { chrome.runtime.sendMessage({ type: 'vclub:requestSourceId' }, (response) => { window.postMessage({ type: 'vclub:screenShare:response', response, }, '*'); }); }, 'vclub:ping': () => { window.postMessage({ type: 'vclub:extension:loaded', version: VERSION, }, '*'); }, }; window.addEventListener('message', (event) => { if (event.source !== window) return; const handler = handlers[event.data.type]; if (handler) { handler(event.data, event); } }); handlers['vclub:ping']();
VirtualClub/vclub
browserExtensions/chromeExtension/content-script.js
JavaScript
mit
658
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- from msrest.serialization import Model class TargetCostProperties(Model): """Properties of a cost target. :param status: Target cost status. Possible values include: 'Enabled', 'Disabled' :type status: str or :class:`TargetCostStatus <azure.mgmt.devtestlabs.models.TargetCostStatus>` :param target: Lab target cost :type target: int :param cost_thresholds: Cost thresholds. :type cost_thresholds: list of :class:`CostThresholdProperties <azure.mgmt.devtestlabs.models.CostThresholdProperties>` :param cycle_start_date_time: Reporting cycle start date. :type cycle_start_date_time: datetime :param cycle_end_date_time: Reporting cycle end date. :type cycle_end_date_time: datetime :param cycle_type: Reporting cycle type. Possible values include: 'CalendarMonth', 'Custom' :type cycle_type: str or :class:`ReportingCycleType <azure.mgmt.devtestlabs.models.ReportingCycleType>` """ _attribute_map = { 'status': {'key': 'status', 'type': 'str'}, 'target': {'key': 'target', 'type': 'int'}, 'cost_thresholds': {'key': 'costThresholds', 'type': '[CostThresholdProperties]'}, 'cycle_start_date_time': {'key': 'cycleStartDateTime', 'type': 'iso-8601'}, 'cycle_end_date_time': {'key': 'cycleEndDateTime', 'type': 'iso-8601'}, 'cycle_type': {'key': 'cycleType', 'type': 'str'}, } def __init__(self, status=None, target=None, cost_thresholds=None, cycle_start_date_time=None, cycle_end_date_time=None, cycle_type=None): self.status = status self.target = target self.cost_thresholds = cost_thresholds self.cycle_start_date_time = cycle_start_date_time self.cycle_end_date_time = cycle_end_date_time self.cycle_type = cycle_type
v-iam/azure-sdk-for-python
azure-mgmt-devtestlabs/azure/mgmt/devtestlabs/models/target_cost_properties.py
Python
mit
2,286
import unittest import base64 from hashlib import md5 as basic_md5 from flask import Flask from flask_httpauth import HTTPBasicAuth def md5(s): if isinstance(s, str): s = s.encode('utf-8') return basic_md5(s) class HTTPAuthTestCase(unittest.TestCase): def setUp(self): app = Flask(__name__) app.config['SECRET_KEY'] = 'my secret' basic_custom_auth = HTTPBasicAuth() @basic_custom_auth.get_password def get_basic_custom_auth_get_password(username): if username == 'john': return md5('hello').hexdigest() elif username == 'susan': return md5('bye').hexdigest() else: return None @basic_custom_auth.hash_password def basic_custom_auth_hash_password(password): return md5(password).hexdigest() @app.route('/') def index(): return 'index' @app.route('/basic-custom') @basic_custom_auth.login_required def basic_custom_auth_route(): return 'basic_custom_auth:' + basic_custom_auth.username() self.app = app self.basic_custom_auth = basic_custom_auth self.client = app.test_client() def test_basic_auth_login_valid_with_hash1(self): creds = base64.b64encode(b'john:hello').decode('utf-8') response = self.client.get( '/basic-custom', headers={'Authorization': 'Basic ' + creds}) self.assertEqual(response.data.decode('utf-8'), 'basic_custom_auth:john') def test_basic_custom_auth_login_valid(self): creds = base64.b64encode(b'john:hello').decode('utf-8') response = self.client.get( '/basic-custom', headers={'Authorization': 'Basic ' + creds}) self.assertEqual(response.data, b'basic_custom_auth:john') def test_basic_custom_auth_login_invalid(self): creds = base64.b64encode(b'john:bye').decode('utf-8') response = self.client.get( '/basic-custom', headers={"Authorization": "Basic " + creds}) self.assertEqual(response.status_code, 401) self.assertTrue("WWW-Authenticate" in response.headers)
miguelgrinberg/Flask-HTTPAuth
tests/test_basic_hashed_password.py
Python
mit
2,215
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using System.Collections.ObjectModel; using System.Windows.Markup; using System.Windows.Controls.Primitives; namespace GAPPSF.UIControls { /// <summary> /// Interaction logic for TimeCtrl.xaml /// </summary> [ContentProperty("Children")] public partial class TimeCtrl : UserControl, IFrameTxtBoxCtrl { private static readonly DependencyProperty ValueProperty = DependencyProperty.Register("Value", typeof(DateTime), typeof(TimeCtrl), new PropertyMetadata(DateTime.Now, ValueChangedCallback)); private static readonly DependencyProperty TimePatternProperty = DependencyProperty.Register("TimePattern", typeof(string), typeof(TimeCtrl), new PropertyMetadata(SystemDateInfo.LongTimePattern)); private static readonly DependencyProperty TextAlignmentProperty = DependencyProperty.Register("TextAlignment", typeof(TextAlignment), typeof(TimeCtrl), new PropertyMetadata(TextAlignment.Left, TextAlignmentChangedCallback)); public static readonly DependencyProperty UseValidTimesProperty = DependencyProperty.Register("UseValidTimes", typeof(bool), typeof(TimeCtrl), new PropertyMetadata(false, UseValidTimesChangedCallback)); public static readonly DependencyProperty ValidTimesNameProperty = DependencyProperty.Register("ValidTimesName", typeof(string), typeof(TimeCtrl), new PropertyMetadata(LanguageStrings.ValidTimes)); public static readonly DependencyProperty NoValidTimesStringProperty = DependencyProperty.Register("NoValidTimesString", typeof(string), typeof(TimeCtrl), new PropertyMetadata(LanguageStrings.None)); private static readonly DependencyProperty InvalidTimeTextBrushProperty = DependencyProperty.Register("InvalidTimeTextBrush", typeof(Brush), typeof(TimeCtrl), new PropertyMetadata(Brushes.Red)); public static readonly DependencyProperty IsValidTimeProperty = DependencyProperty.Register("IsValidTime", typeof(bool), typeof(TimeCtrl), new PropertyMetadata(true, IsValidTimeChangedCallback)); private static void ValueChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e) { TimeCtrl tc = d as TimeCtrl; if (tc != null && e.NewValue is DateTime) { foreach (UIElement ele in tc.TimeCtrls.Children) { var ctrl = ele as FrameworkElement; HMSType hmsType = ctrl.get_HMSType(); if (hmsType != HMSType.unknown) { var tb = ctrl as TextBox; if (tb != null) tb.set_HMSText((DateTime)e.NewValue); } } tc.SetIsValidTime(); } } private static void TextAlignmentChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e) { TimeCtrl tc = d as TimeCtrl; if (tc != null && e.NewValue is TextAlignment) { tc.TextBoxCtrl.TextAlignment = (TextAlignment)e.NewValue; tc.ReloadTimeCtrlsGrid(); } } private static void IsValidTimeChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e) { TimeCtrl tc = d as TimeCtrl; if (tc != null && e.NewValue is bool) { foreach (FrameworkElement fe in tc.TimeCtrls.Children) { if (fe is TextBox) ((TextBox)fe).Foreground = tc.TextBrush; else if (fe is TextBlock) ((TextBlock)fe).Foreground = tc.TextBrush; } } } private static void UseValidTimesChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e) { TimeCtrl tc = d as TimeCtrl; if (tc != null && e.NewValue is bool) tc.SetIsValidTime(); } static TimeCtrl() { Coercer.Initialize<TimeCtrl>(); } public TimeCtrl() { Children = new ObservableCollection<ValidTimeItem>(); InitializeComponent(); this.Children.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(Children_CollectionChanged); } public DateTime Value { get { return (DateTime)GetValue(ValueProperty); } set { SetValue(ValueProperty, value); } } public string TimePattern { get { return (string)GetValue(TimePatternProperty); } set { SetValue(TimePatternProperty, value); } } public TextAlignment TextAlignment { get { return (TextAlignment)GetValue(TextAlignmentProperty); } set { SetValue(TextAlignmentProperty, value); } } public bool UseValidTimes { get { return (bool)GetValue(UseValidTimesProperty); } set { SetValue(UseValidTimesProperty, value); } } public string ValidTimesName { get { return (string)GetValue(ValidTimesNameProperty); } set { SetValue(ValidTimesNameProperty, value); } } public string NoValidTimesString { get { return (string)GetValue(NoValidTimesStringProperty); } set { SetValue(NoValidTimesStringProperty, value); } } public Brush InvalidTimeTextBrush { get { return (Brush)GetValue(InvalidTimeTextBrushProperty); } set { SetValue(InvalidTimeTextBrushProperty, value); } } public bool IsValidTime { get { return (bool)GetValue(IsValidTimeProperty); } private set { SetValue(IsValidTimeProperty, value); } } public ObservableCollection<ValidTimeItem> Children { get; private set; } private Brush TextBrush { get { return IsEnabled ? (IsValidTime ? Foreground : InvalidTimeTextBrush) : SystemColors.GrayTextBrush; } } private void SetIsValidTime() { if (!UseValidTimes) IsValidTime = true; else { IsValidTime = false; foreach (ValidTimeItem vti in Children) { if (Value >= vti.BeginTime && Value <= vti.EndTime) { IsValidTime = true; break; } } } } private void Children_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e) { SetIsValidTime(); } TextBox IFrameTxtBoxCtrl.TextBox { get { return TextBoxCtrl; } } private bool MouseClicked = false; private void AddGridCtrl(FrameworkElement ctrl) { var cd = new ColumnDefinition(); cd.Width = new GridLength(1, GridUnitType.Auto); TimeCtrls.ColumnDefinitions.Add(cd); TimeCtrls.Children.Add(ctrl); Grid.SetColumn(ctrl, TimeCtrls.ColumnDefinitions.Count - 1); } private void AddHMSCtrlContextMenuItems(TextBox tb, params ICommand[] Commands) { foreach (ICommand Command in Commands) { MenuItem mi = new MenuItem(); mi.Command = Command; tb.ContextMenu.Items.Add(mi); } } private bool CmdBindCutPasteExecuteHandler(object sender, bool Execute, bool Cut) { var tb = sender as TextBox; bool CanExecute = false; string ClipTxt = ""; if (tb != null) { int CurPos = tb.SelectionStart, CurrentValue = 0, SelLength = tb.SelectionLength; if (Cut) ClipTxt = tb.Text.Substring(CurPos, tb.SelectionLength); string Txt = tb.Text.Remove(CurPos, tb.SelectionLength); if (!Cut) // If paste ClipTxt = (string)System.Windows.Clipboard.GetData("Text"); CanExecute = (!Cut && string.IsNullOrEmpty(ClipTxt)) ? false : (tb.IsAM_PM() ? (ClipTxt == SystemDateInfo.AMDesignator || ClipTxt == SystemDateInfo.PMDesignator) : ValidateInput(tb, (Cut)? Txt : Txt.Insert(CurPos, ClipTxt), out CurrentValue)); if (Execute) { Value = tb.IsAM_PM() ? Value.Reset_AM_PM_Time(ClipTxt == SystemDateInfo.AMDesignator) : Value.ResetTime(CurrentValue, tb.get_HMSType()); tb.SelectionStart = CurPos + SelLength; if (Cut) System.Windows.Clipboard.SetData("Text", ClipTxt); } } return CanExecute; } private void CmdBindCutExecuted(object sender, ExecutedRoutedEventArgs e) { CmdBindCutPasteExecuteHandler(sender, true, true); e.Handled = true; } void CmdBindCutCanExecute(object sender, CanExecuteRoutedEventArgs e) { var tb = sender as TextBox; e.CanExecute = (tb != null) && tb.SelectionLength > 0 && !tb.IsAM_PM(); } private void CmdBindPasteExecuted(object sender, ExecutedRoutedEventArgs e) { CmdBindCutPasteExecuteHandler(sender, true, false); e.Handled = true; } void CmdBindPasteCanExecute(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = CmdBindCutPasteExecuteHandler(sender, false, false); e.Handled = true; } private void CmdBindCopyTimeExecuted(object sender, ExecutedRoutedEventArgs e) { string strClipTime = ""; foreach (FrameworkElement fe in TimeCtrls.Children) { if (fe is TextBox) strClipTime += ((TextBox)fe).Text; else if (fe is TextBlock) strClipTime += ((TextBlock)fe).Text; } System.Windows.Clipboard.SetData("Text", strClipTime); e.Handled = true; } private void CmdBindPasteTimeExecuted(object sender, ExecutedRoutedEventArgs e) { int Hour, Minute, Second; if (TimeCtrlExtensions.IsValidTime((string)System.Windows.Clipboard.GetData("Text"), TimePattern, out Hour, out Minute, out Second)) Value = new DateTime(Value.Year, Value.Month, Value.Day, Hour, Minute, Second, Value.Millisecond, Value.Kind); } void CmdBindPasteTimeCanExecute(object sender, CanExecuteRoutedEventArgs e) { int Hour, Minute, Second; e.CanExecute = TimeCtrlExtensions.IsValidTime((string)System.Windows.Clipboard.GetData("Text"), TimePattern, out Hour, out Minute, out Second); } private void AddValidTimeString(string str, bool Highlighted = false) { var rd = new RowDefinition(); ValidTimesGrid.RowDefinitions.Add(rd); TextBlock tb = new TextBlock(); tb.Text = str; if (Highlighted) tb.FontWeight = FontWeights.Bold; tb.HorizontalAlignment = HorizontalAlignment.Center; tb.Background = Background; tb.Foreground = Foreground; tb.Margin = new Thickness(0.0); ValidTimesGrid.Children.Add(tb); Grid.SetRow(tb, ValidTimesGrid.RowDefinitions.Count - 1); ; ValidTimesGrid.Height += tb.Height; } private string GetFormatedStr(TimeEntry te) { string strFormat = ""; string strAMPM = (te.Hour >= 12) ? SystemDateInfo.PMDesignator : SystemDateInfo.AMDesignator; char AMPMShort = (te.Hour >= 12) ? SystemDateInfo.PMDesignator[TimeCtrlExtensions.Get_t_Idx()] : SystemDateInfo.AMDesignator[TimeCtrlExtensions.Get_t_Idx()]; foreach (FrameworkElement fe in TimeCtrls.Children) strFormat += fe.get_TextFormat(); return string.Format(strFormat, te.Hour, te.Hour.Get12Hour(), te.Minute, te.Second, strAMPM, AMPMShort); } private void CmdBindShowValidTimesExecuted(object sender, ExecutedRoutedEventArgs e) { if (ValidTimesGrid.Background == null) ValidTimesGrid.Background = Brushes.White; ValidTimesGrid.Children.Clear(); ValidTimesGrid.ColumnDefinitions.Clear(); ValidTimesGrid.RowDefinitions.Clear(); var cd = new ColumnDefinition(); ValidTimesGrid.ColumnDefinitions.Add(cd); ValidTimesGrid.Height = 0; AddValidTimeString(" " + ValidTimesName + " ", true); string str; foreach (ValidTimeItem vti in Children) { str = " " + LanguageStrings.From + " " + GetFormatedStr(vti.BeginTime) + " " + LanguageStrings.To + " " + GetFormatedStr(vti.EndTime) + " "; AddValidTimeString(str); } if (Children.Count == 0) AddValidTimeString(" " + NoValidTimesString + " "); ValidTimesPopup.IsOpen = true; } private void AddHMSCtrlContextMenu(TextBox tb) { ContextMenu cmSource = new ContextMenu(); tb.ContextMenu = cmSource; cmSource.PlacementTarget = tb; // Very important line: without this, context menu won't work if cursor not over a TextBox (but will otherwise!) AddHMSCtrlContextMenuItems(tb, ApplicationCommands.Cut, ApplicationCommands.Copy, ApplicationCommands.Paste, TimeCtrlCustomCommands.CopyTime, TimeCtrlCustomCommands.PasteTime); if (UseValidTimes) { TimeCtrlCustomCommands.ShowValidTimes.Text = ValidTimesName; AddHMSCtrlContextMenuItems(tb, TimeCtrlCustomCommands.ShowValidTimes); } CommandBinding CmdBindCut = new CommandBinding(ApplicationCommands.Cut, CmdBindCutExecuted, CmdBindCutCanExecute); tb.CommandBindings.Add(CmdBindCut); CommandBinding CmdBindPaste = new CommandBinding(ApplicationCommands.Paste, CmdBindPasteExecuted, CmdBindPasteCanExecute); tb.CommandBindings.Add(CmdBindPaste); CommandBinding CmdBindCopyTime = new CommandBinding(TimeCtrlCustomCommands.CopyTime, CmdBindCopyTimeExecuted); tb.CommandBindings.Add(CmdBindCopyTime); CommandBinding CmdBindPasteTime = new CommandBinding(TimeCtrlCustomCommands.PasteTime, CmdBindPasteTimeExecuted, CmdBindPasteTimeCanExecute); tb.CommandBindings.Add(CmdBindPasteTime); CommandBinding CmdBindShowValidTimes = new CommandBinding(TimeCtrlCustomCommands.ShowValidTimes, CmdBindShowValidTimesExecuted); tb.CommandBindings.Add(CmdBindShowValidTimes); } private void AddHMSCtrl(HMSType hmsType) { TextBox tb = new TextBox(); tb.set_HMSType(hmsType); tb.set_HMSText(Value); tb.Height = ActualHeight; tb.Margin = new Thickness(0.0); tb.BorderThickness = new Thickness(); tb.Background = Background; tb.Foreground = TextBrush; tb.IsEnabled = IsEnabled; if (hmsType == HMSType.t || hmsType == HMSType.tt) { tb.Focusable = true; tb.AllowDrop = false; tb.IsReadOnly = true; tb.IsUndoEnabled = false; tb.GotKeyboardFocus += new KeyboardFocusChangedEventHandler(tb_tt_GotKeyboardFocus); tb.PreviewMouseLeftButtonDown += new MouseButtonEventHandler(tb_tt_PreviewMouseLeftButtonDown); tb.PreviewKeyDown += new KeyEventHandler(tb_tt_PreviewKeyDown); tb.PreviewTextInput += new TextCompositionEventHandler(tb_tt_PreviewTextInput); } else { tb.PreviewTextInput += new TextCompositionEventHandler(tb_PreviewTextInput); tb.PreviewLostKeyboardFocus += new KeyboardFocusChangedEventHandler(tb_PreviewLostKeyboardFocus); tb.GotKeyboardFocus += new KeyboardFocusChangedEventHandler(tb_GotKeyboardFocus); tb.LostKeyboardFocus += new KeyboardFocusChangedEventHandler(tb_LostKeyboardFocus); tb.PreviewKeyDown += new KeyEventHandler(tb_PreviewKeyDown); tb.PreviewMouseLeftButtonDown += new MouseButtonEventHandler(tb_PreviewMouseLeftButtonDown); tb.PreviewMouseRightButtonDown += new MouseButtonEventHandler(tb_PreviewMouseRightButtonDown); tb.PreviewQueryContinueDrag += new QueryContinueDragEventHandler(tb_PreviewQueryContinueDrag); tb.PreviewDragEnter += new DragEventHandler(tb_PreviewDrag); tb.PreviewDragOver += new DragEventHandler(tb_PreviewDrag); } AddHMSCtrlContextMenu(tb); tb.PreviewMouseWheel += new MouseWheelEventHandler(tb_PreviewMouseWheel); AddGridCtrl(tb); } private void AddString(string str) { TextBlock tb = new TextBlock(); tb.Text = str; tb.Background = Brushes.Transparent; tb.Foreground = TextBrush; tb.Margin = new Thickness(0.0); tb.Height = Height; AddGridCtrl(tb); } void tb_PreviewMouseWheel(object sender, MouseWheelEventArgs e) { // MouseWheel does not work very well. The mouse cursor has to be over the item for it to work. // CodePlex sample does same, which is why I am leaving implementation as such. var tb = sender as TextBox; if (tb != null) { if (e.Delta > 0) ManipulateValue(tb, IncrementValue); else ManipulateValue(tb, DecrementValue); // Following is illegal: !!!!! (would replace 4 lines above) // ManipulateValue(tb, (e.Delta > 0) ? IncrementValue : DecrementValue); tb.Focus(); e.Handled = true; } } void tb_tt_GotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e) { var tb = sender as TextBox; if (tb != null) tb.SelectAll(); } void tb_tt_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e) { var tb = sender as TextBox; if (tb != null) { tb.Focus(); e.Handled = true; } } void AM_PM_Handle(TextBox tb) { bool IsAm; if (tb.get_HMSType() == HMSType.tt) IsAm = (tb.Text == SystemDateInfo.AMDesignator); else // tb.get_HMSType() == HMSType.t IsAm = (tb.Text == SystemDateInfo.AMDesignator[TimeCtrlExtensions.Get_t_Idx()].ToString()); Value = Value.Reset_AM_PM_Time(IsAm); tb.SelectAll(); } void AM_PM_Change(TextBox tb) { if (tb.get_HMSType() == HMSType.tt) tb.Text = (tb.Text == SystemDateInfo.AMDesignator) ? SystemDateInfo.PMDesignator : SystemDateInfo.AMDesignator; else // tb.get_HMSType() == HMSType.t { int Idx = TimeCtrlExtensions.Get_t_Idx(); tb.Text = (tb.Text == SystemDateInfo.AMDesignator[Idx].ToString()) ? SystemDateInfo.PMDesignator[Idx].ToString() : SystemDateInfo.AMDesignator[Idx].ToString(); } AM_PM_Handle(tb); } void tb_tt_PreviewKeyDown(object sender, KeyEventArgs e) { var tb = sender as TextBox; if (tb == null) return; if (e.Key == Key.Up || e.Key == Key.Down) { AM_PM_Change(tb); e.Handled = true; } } bool AM_PM_HandleInput(TextBox tb, string InputTxt, string AM_PM_Designator, int Idx) { if (string.Compare(InputTxt, AM_PM_Designator[Idx].ToString(), true) == 0) { if (tb.get_HMSType() == HMSType.tt) tb.Text = AM_PM_Designator; else // tb.get_HMSType() == HMSType.t tb.Text = AM_PM_Designator[Idx].ToString(); AM_PM_Handle(tb); return true; } return false; } void tb_tt_PreviewTextInput(object sender, TextCompositionEventArgs e) { TextBox tb = sender as TextBox; if (tb != null) { int Idx = TimeCtrlExtensions.Get_t_Idx(); if (!AM_PM_HandleInput(tb, e.Text, SystemDateInfo.AMDesignator, Idx)) e.Handled = AM_PM_HandleInput(tb, e.Text, SystemDateInfo.PMDesignator, Idx); else e.Handled = true; } } void tb_LostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e) { var tb = sender as TextBox; if (tb != null && tb.Text == "") tb.set_HMSText(Value); } void tb_PreviewDrag(object sender, DragEventArgs e) { e.Effects = DragDropEffects.None; e.Handled = true; } void tb_PreviewQueryContinueDrag(object sender, QueryContinueDragEventArgs e) { e.Action = DragAction.Cancel; e.Handled = true; } void tb_PreviewMouseRightButtonDown(object sender, MouseButtonEventArgs e) { MouseClicked = true; } void tb_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e) { MouseClicked = true; } private delegate void ValueManipulator(TextBox tb, int NewValue); private int AdjustHalfDayHour(TextBox tb, int CurrentValue) { if (tb.IsHalfDayHour()) { if (CurrentValue == 12) { if (Value.Hour < 12) CurrentValue = 0; } else if (Value.Hour >= 12) CurrentValue += 12; } return CurrentValue; } private void IncrementValue(TextBox tb, int NewValue) { NewValue = (NewValue < tb.get_Max() - 1) ? NewValue + 1 : tb.get_Min(); NewValue = AdjustHalfDayHour(tb, NewValue); Value = Value.ResetTime(NewValue, tb.get_HMSType()); } private void DecrementValue(TextBox tb, int NewValue) { NewValue = (NewValue > tb.get_Min()) ? NewValue - 1 : tb.get_Max() - 1; NewValue = AdjustHalfDayHour(tb, NewValue); Value = Value.ResetTime(NewValue, tb.get_HMSType()); } private void ManipulateValue(TextBox tb, ValueManipulator ValMan) { if (tb.get_HMSType() == HMSType.t || tb.get_HMSType() == HMSType.tt) { AM_PM_Change(tb); return; } int NewValue; if (int.TryParse(tb.Text, out NewValue)) ValMan(tb, NewValue); tb.Focus(); tb.SelectAll(); } void tb_PreviewKeyDown(object sender, KeyEventArgs e) { var tb = sender as TextBox; if (tb == null) return; if (e.Key == Key.Up) { ManipulateValue(tb, IncrementValue); e.Handled = true; } else if (e.Key == Key.Down) { ManipulateValue(tb, DecrementValue); e.Handled = true; } else if (e.Key == Key.Delete || e.Key == Key.Back) { int CurPos = tb.SelectionStart; string Txt = tb.Text; e.Handled = true; if (tb.SelectionLength > 0) Txt = Txt.Remove(CurPos, tb.SelectionLength); else if (e.Key == Key.Delete && CurPos < Txt.Length) { Txt = Txt.Remove(CurPos, 1); if (tb.IsAlways2CharInt()) CurPos++; } else if (e.Key == Key.Back && CurPos > 0) { Txt = Txt.Remove(CurPos - 1, 1); if (!tb.IsAlways2CharInt()) --CurPos; } else e.Handled = false; if (e.Handled) { int CurrentValue; if (ValidateInput(tb, Txt, out CurrentValue)) { Value = Value.ResetTime(CurrentValue, tb.get_HMSType()); tb.SelectionStart = CurPos; } else if (Txt == "" || (Txt == "0" && tb.get_HMSType() == HMSType.hhour)) { tb.SelectionStart = 0; tb.Text = ""; } else e.Handled = false; } } else if (e.Key == Key.Space) // Want to prevent entering spaces. Amazingly, tb_PreviewTextInput not called, even though // tb_PreviewTextInput IS called when enter return key (and e.Text = '\r') ??!!! e.Handled = true; } void tb_GotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e) { var tb = sender as TextBox; if (tb != null && MouseClicked == false) // We do not want to select all when user has clicked on TextBox. // Without the MouseClicked parameter, everything is selected/deselected immediately, which looks ugly. // I agree having this parameter is not the most pretty programming style, but know no better way. tb.SelectAll(); MouseClicked = false; } void tb_PreviewLostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e) { var tb = sender as TextBox; if (tb != null && e.NewFocus == tb.ContextMenu) { tb.Focus(); tb.ContextMenu.DataContext = tb; e.Handled = true; } } /// <param name="shortHMS">An HMS tag corresponding to 'H', 'h', 'm', 's', 't' </param> /// <param name="longHMS">An HMS tag corresponding to 'HH', 'hh', 'mm', 'ss', 'tt'</param> private int LoadTimeTag(string TimePattern, int Idx, HMSType shortHMS, HMSType longHMS) { if (Idx < TimePattern.Length - 1 && TimePattern[Idx + 1] == TimePattern[Idx]) { AddHMSCtrl(longHMS); Idx++; } else AddHMSCtrl(shortHMS); return Idx; } private int LoadTimeSeparator(string TimePattern, int Idx) { // Assume the separator is something like ':' or '.'. Not considering case when want to use a character normally used // to indicate a time tag. int StartIdx = Idx; while (Idx < TimePattern.Length - 1 && TimePattern[Idx + 1] != 'H' && TimePattern[Idx + 1] != 'h' && TimePattern[Idx + 1] != 'm' && TimePattern[Idx + 1] != 's' && TimePattern[Idx + 1] != 't') Idx++; AddString(TimePattern.Substring(StartIdx, Idx - StartIdx + 1)); return Idx; } private void LoadTimePattern(string TimePattern) { for (int Idx = 0; Idx < TimePattern.Length; Idx++) { switch (TimePattern[Idx]) { case 'H': Idx = LoadTimeTag(TimePattern, Idx, HMSType.Hour, HMSType.HHour); break; case 'h': Idx = LoadTimeTag(TimePattern, Idx, HMSType.hour, HMSType.hhour); break; case 'm': Idx = LoadTimeTag(TimePattern, Idx, HMSType.minute, HMSType.mminute); break; case 's': Idx = LoadTimeTag(TimePattern, Idx, HMSType.second, HMSType.ssecond); break; case 't': Idx = LoadTimeTag(TimePattern, Idx, HMSType.t, HMSType.tt); break; default: Idx = LoadTimeSeparator(TimePattern, Idx); break; } } } private void ReloadTimeCtrlsGrid() { TimeCtrls.Children.Clear(); TimeCtrls.ColumnDefinitions.Clear(); TimeCtrls.RowDefinitions.Clear(); TimeCtrls.RowDefinitions.Add(new RowDefinition()); if (TextAlignment == TextAlignment.Right || TextAlignment == TextAlignment.Center) TimeCtrls.ColumnDefinitions.Add(new ColumnDefinition()); LoadTimePattern(TimePattern); if (TextAlignment == TextAlignment.Left || TextAlignment == TextAlignment.Center) TimeCtrls.ColumnDefinitions.Add(new ColumnDefinition()); } private void Root_Loaded(object sender, RoutedEventArgs e) { ReloadTimeCtrlsGrid(); } private TextBox GetNextTextBox(int Idx) { while (++Idx < TimeCtrls.Children.Count && !(TimeCtrls.Children[Idx] is TextBox)) ; return (Idx < TimeCtrls.Children.Count) ? (TextBox)TimeCtrls.Children[Idx] : null; } void tb_PreviewTextInput(object sender, TextCompositionEventArgs e) { TextBox tb = sender as TextBox; if (tb != null) { int CurrentValue; int CurPos = tb.SelectionStart, SelLen = tb.SelectionLength; string Txt = tb.Text.Remove(CurPos, SelLen); if (Keyboard.GetKeyStates(Key.Insert) == KeyStates.Toggled && CurPos < Txt.Length) Txt = Txt.Remove(CurPos, 1); Txt = Txt.Insert(CurPos, e.Text); // Don't do anything for entries like "003" "012" or "05" (not '0' prefixed) when entry is a '0' only if (!(e.Text == "0" && ((Txt.Length == 3 && Txt[0] == '0' && CurPos == 0) || (!tb.IsAlways2CharInt() && Txt.Length == 2 && Txt[0] == '0'))) && ValidateInput(tb, Txt, out CurrentValue)) { CurrentValue = AdjustHalfDayHour(tb, CurrentValue); Value = Value.ResetTime(CurrentValue, tb.get_HMSType()); tb.SelectionStart = (tb.Text.Length == 1 || (CurPos == 0 && SelLen < 2 && Txt.Length >= 2) || (Txt.Length == 3 && Txt[0] == '0' && CurPos == 1 && SelLen == 0)) ? 1 : 2; } else if (tb.IsHalfDayHour() && (Txt == "0" || Txt == "00")) tb.Text = ""; } e.Handled = true; } private bool ValidateInput(TextBox tb, string Txt, out int CurrentValue) { if (int.TryParse(Txt, out CurrentValue)) return (CurrentValue < tb.get_Max() && CurrentValue >= tb.get_Min()); return false; } private TextBox SetFocusToClosestTextBox() { Point pt; TextBox tbClosest = null; double MinDist = 0; foreach (UIElement ele in TimeCtrls.Children) { var tb = ele as TextBox; if (tb != null) { pt = Mouse.GetPosition(tb); if (tbClosest == null || Math.Abs(pt.X) < MinDist) { tbClosest = tb; MinDist = Math.Abs(pt.X); } } } if (tbClosest != null) { tbClosest.Focus(); tbClosest.CaptureMouse(); } return tbClosest; } private void Root_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { MouseClicked = true; SetFocusToClosestTextBox(); } private void Root_MouseRightButtonDown(object sender, MouseButtonEventArgs e) { MouseClicked = true; TextBox tb = SetFocusToClosestTextBox(); if (tb != null) { tb.ContextMenu.IsOpen = true; e.Handled = true; } } private void CommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = false; e.Handled = true; } private TextBox GetTextBoxToFocusOn() { var tb = FocusManager.GetFocusedElement(this) as TextBox; if (tb == null) tb = GetNextTextBox(-1); return tb; } private void UpDown_UpClick(object sender, RoutedEventArgs e) { var tb = GetTextBoxToFocusOn(); if (tb != null) ManipulateValue(tb, IncrementValue); } private void UpDown_DownClick(object sender, RoutedEventArgs e) { var tb = GetTextBoxToFocusOn(); if (tb != null) ManipulateValue(tb, DecrementValue); } private void Root_IsEnabledChanged(object sender, DependencyPropertyChangedEventArgs e) { foreach (FrameworkElement fe in TimeCtrls.Children) { if (fe is TextBox) { ((TextBox)fe).IsEnabled = (bool)e.NewValue; ((TextBox)fe).Foreground = TextBrush; } else if (fe is TextBlock) ((TextBlock)fe).Foreground = TextBrush; } } } }
GlobalcachingEU/GAPP
GAPPSF/UIControls/UpDownCtrls/TimeCtrl.xaml.cs
C#
mit
35,541
/* * The MIT License * * Copyright (c) 2015, Mahmoud Ben Hassine (mahmoud@benhassine.fr) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.easybatch.integration.apache.common.csv; import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVParser; import org.apache.commons.csv.CSVRecord; import org.easybatch.core.api.Record; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import java.io.StringReader; import static org.assertj.core.api.Assertions.assertThat; /** * Test class for {@link ApacheCommonCsvRecordReader}. * * @author Mahmoud Ben Hassine (mahmoud@benhassine.fr) */ public class ApacheCommonCsvRecordReaderTest { private ApacheCommonCsvRecordReader recordReader; @Before public void setUp() throws Exception { StringReader stringReader = new StringReader("foo,bar,15,true"); CSVFormat csvFormat = CSVFormat.DEFAULT.withHeader("firstName", "lastName", "age", "married"); CSVParser parser = new CSVParser(stringReader, csvFormat); recordReader = new ApacheCommonCsvRecordReader(parser); recordReader.open(); } @Test public void testHasNextRecord() throws Exception { Assert.assertTrue(recordReader.hasNextRecord()); } @Test public void testReadNextRecord() throws Exception { recordReader.hasNextRecord(); Record record = recordReader.readNextRecord(); assertThat(record).isNotNull().isInstanceOf(ApacheCommonCsvRecord.class); ApacheCommonCsvRecord apacheCommonCsvRecord = (ApacheCommonCsvRecord) record; assertThat(apacheCommonCsvRecord.getHeader()).isNotNull(); assertThat(apacheCommonCsvRecord.getHeader().getNumber()).isEqualTo(1); CSVRecord csvRecord = apacheCommonCsvRecord.getPayload(); assertThat(csvRecord.get("firstName")).isEqualTo("foo"); assertThat(csvRecord.get("lastName")).isEqualTo("bar"); assertThat(csvRecord.get("age")).isEqualTo("15"); assertThat(csvRecord.get("married")).isEqualTo("true"); } @After public void tearDown() throws Exception { recordReader.close(); } }
dmullins78/easybatch-framework
easybatch-integration/easybatch-apache-commons-csv/src/test/java/org/easybatch/integration/apache/common/csv/ApacheCommonCsvRecordReaderTest.java
Java
mit
3,254
""" Module. Includes classes for all time dependent lattice. """ import sys import os import math from orbit.teapot import TEAPOT_Lattice from orbit.parsers.mad_parser import MAD_Parser, MAD_LattLine from orbit.lattice import AccNode, AccActionsContainer from orbit.time_dep import waveform class TIME_DEP_Lattice(TEAPOT_Lattice): """ The subclass of the TEAPOT_Lattice. TIME_DEP_Lattice has the ability to set time dependent parameters to the Lattice. Multi-turn track also available. """ def __init__(self, name = "no name"): TEAPOT_Lattice.__init__(self,name) self.__latticeDict = {} self.__TDNodeDict = {} self.__turns = 1 def setLatticeOrder(self): """ Sets the time dependent lattice names to the lattice. """ accNodes = self.getNodes() elemInLine = {} for i in range(len(accNodes)): elem = accNodes[i] elemname = elem.getName() if(elemInLine.has_key(elemname)): elemInLine[elemname] += 1 else: elemInLine[elemname] = 1 node = self.getNodes()[i] node.setParam("TPName",node.getName()+"_"+str(elemInLine[elemname])) #node.setParam("sequence",i+1) #print "debug node",node.getName(),node.getParamsDict() def setTimeDepNode(self, TPName, waveform): """ Sets the waveform function to the TP node before track. """ flag = 0 for node in self.getNodes(): if (TPName == node.getParam("TPName")): flag = 1 node.setParam("waveform",waveform) self.__TDNodeDict[TPName] = node if not flag: print "The",TPName,"is not found." sys.exit(1) def setTimeDepStrength(self, time): """ Set strength to the TP node while running. """ NodeDict = self.__TDNodeDict for i in NodeDict.keys(): node = NodeDict[i] waveform = node.getParam("waveform") waveform.calc(time) waveformType = waveform.getType() if waveformType == "kicker waveform": if node.getType() == "kick teapot": self.setParam(node,"kx",waveform.getKx()) self.setParam(node,"ky",waveform.getKy()) else: print "No kicker waveform added. Please check node type." elif waveformType == "magnet waveform": strength = waveform.getStrength() if node.getType() == "multipole teapot": self.setParam(node,"kls",strength) elif node.getType() == "quad teapot": self.setParam(node,"kls",strength) self.setParam(node,"kq",strength) elif node.getType() == "solenoid teapot": self.setParam(node,"B",strength) else: print "No magnet waveform added. Please check node type." def setParam(self, node, Kparam, strength): if node.hasParam(Kparam): paramval = node.getParam(Kparam) if Kparam == "kls": newparamval = [] for i in range(len(paramval)): newparamval.append(paramval[i]*strength) paramval = newparamval else:paramval = paramval*strength node.setParam(Kparam,paramval) def trackBunchTurns(self, bunch): """ It tracks the bunch through the lattice with multi-turn. """ turns = self.__turns #start for i in range(turns-1): self.trackBunch(bunch) syncPart = bunch.getSyncParticle() time = syncPart.time() self.setTimeDepStrength(time) print "debug trackBunchTurns time",time,"in",i,"turn" #getsublattice #sublattice.trackBunch(bunch) def setTurns(self, turns, startPosition = 0, endPosition = -1): """ Sets the turns and start end position before track. """ startNode = StartNode("start node") endNode = EndNode("end node") self.addNode(startNode, startPosition) self.addNode(endNode, endPosition) self.__turns = turns #print self.getNodes() class StartNode(AccNode): def __init__(self, name = "no name"): AccNode.__init__(self,name) self.setType("start node") def track(self, paramsDict): bunch = paramsDict["bunch"] #bunch.getSyncParticle().time(0.) class EndNode(AccNode): def __init__(self, name = "no name"): AccNode.__init__(self,name) self.setType("end node") def track(self, paramsDict): pass
PyORBIT-Collaboration/py-orbit
py/orbit/time_dep/time_dep.py
Python
mit
4,174
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // // This is used internally to create best fit behavior as per the original windows best fit behavior. // using System; using System.Globalization; using System.Text; using System.Threading; using System.Diagnostics; using System.Diagnostics.Contracts; namespace System.Text { [Serializable] internal class InternalEncoderBestFitFallback : EncoderFallback { // Our variables internal Encoding encoding = null; internal char[] arrayBestFit = null; internal InternalEncoderBestFitFallback(Encoding encoding) { // Need to load our replacement characters table. this.encoding = encoding; this.bIsMicrosoftBestFitFallback = true; } public override EncoderFallbackBuffer CreateFallbackBuffer() { return new InternalEncoderBestFitFallbackBuffer(this); } // Maximum number of characters that this instance of this fallback could return public override int MaxCharCount { get { return 1; } } public override bool Equals(Object value) { InternalEncoderBestFitFallback that = value as InternalEncoderBestFitFallback; if (that != null) { return (this.encoding.CodePage == that.encoding.CodePage); } return (false); } public override int GetHashCode() { return this.encoding.CodePage; } } internal sealed class InternalEncoderBestFitFallbackBuffer : EncoderFallbackBuffer { // Our variables private char cBestFit = '\0'; private InternalEncoderBestFitFallback oFallback; private int iCount = -1; private int iSize; // Private object for locking instead of locking on a public type for SQL reliability work. private static Object s_InternalSyncObject; private static Object InternalSyncObject { get { if (s_InternalSyncObject == null) { Object o = new Object(); Interlocked.CompareExchange<Object>(ref s_InternalSyncObject, o, null); } return s_InternalSyncObject; } } // Constructor public InternalEncoderBestFitFallbackBuffer(InternalEncoderBestFitFallback fallback) { oFallback = fallback; if (oFallback.arrayBestFit == null) { // Lock so we don't confuse ourselves. lock (InternalSyncObject) { // Double check before we do it again. if (oFallback.arrayBestFit == null) oFallback.arrayBestFit = fallback.encoding.GetBestFitUnicodeToBytesData(); } } } // Fallback methods public override bool Fallback(char charUnknown, int index) { // If we had a buffer already we're being recursive, throw, it's probably at the suspect // character in our array. // Shouldn't be able to get here for all of our code pages, table would have to be messed up. Debug.Assert(iCount < 1, "[InternalEncoderBestFitFallbackBuffer.Fallback(non surrogate)] Fallback char " + ((int)cBestFit).ToString("X4", CultureInfo.InvariantCulture) + " caused recursive fallback"); iCount = iSize = 1; cBestFit = TryBestFit(charUnknown); if (cBestFit == '\0') cBestFit = '?'; return true; } public override bool Fallback(char charUnknownHigh, char charUnknownLow, int index) { // Double check input surrogate pair if (!Char.IsHighSurrogate(charUnknownHigh)) throw new ArgumentOutOfRangeException(nameof(charUnknownHigh), Environment.GetResourceString("ArgumentOutOfRange_Range", 0xD800, 0xDBFF)); if (!Char.IsLowSurrogate(charUnknownLow)) throw new ArgumentOutOfRangeException(nameof(charUnknownLow), Environment.GetResourceString("ArgumentOutOfRange_Range", 0xDC00, 0xDFFF)); Contract.EndContractBlock(); // If we had a buffer already we're being recursive, throw, it's probably at the suspect // character in our array. 0 is processing last character, < 0 is not falling back // Shouldn't be able to get here, table would have to be messed up. Debug.Assert(iCount < 1, "[InternalEncoderBestFitFallbackBuffer.Fallback(surrogate)] Fallback char " + ((int)cBestFit).ToString("X4", CultureInfo.InvariantCulture) + " caused recursive fallback"); // Go ahead and get our fallback, surrogates don't have best fit cBestFit = '?'; iCount = iSize = 2; return true; } // Default version is overridden in EncoderReplacementFallback.cs public override char GetNextChar() { // We want it to get < 0 because == 0 means that the current/last character is a fallback // and we need to detect recursion. We could have a flag but we already have this counter. iCount--; // Do we have anything left? 0 is now last fallback char, negative is nothing left if (iCount < 0) return '\0'; // Need to get it out of the buffer. // Make sure it didn't wrap from the fast count-- path if (iCount == int.MaxValue) { iCount = -1; return '\0'; } // Return the best fit character return cBestFit; } public override bool MovePrevious() { // Exception fallback doesn't have anywhere to back up to. if (iCount >= 0) iCount++; // Return true if we could do it. return (iCount >= 0 && iCount <= iSize); } // How many characters left to output? public override int Remaining { get { return (iCount > 0) ? iCount : 0; } } // Clear the buffer public override unsafe void Reset() { iCount = -1; charStart = null; bFallingBack = false; } // private helper methods private char TryBestFit(char cUnknown) { // Need to figure out our best fit character, low is beginning of array, high is 1 AFTER end of array int lowBound = 0; int highBound = oFallback.arrayBestFit.Length; int index; // Binary search the array int iDiff; while ((iDiff = (highBound - lowBound)) > 6) { // Look in the middle, which is complicated by the fact that we have 2 #s for each pair, // so we don't want index to be odd because we want to be on word boundaries. // Also note that index can never == highBound (because diff is rounded down) index = ((iDiff / 2) + lowBound) & 0xFFFE; char cTest = oFallback.arrayBestFit[index]; if (cTest == cUnknown) { // We found it Debug.Assert(index + 1 < oFallback.arrayBestFit.Length, "[InternalEncoderBestFitFallbackBuffer.TryBestFit]Expected replacement character at end of array"); return oFallback.arrayBestFit[index + 1]; } else if (cTest < cUnknown) { // We weren't high enough lowBound = index; } else { // We weren't low enough highBound = index; } } for (index = lowBound; index < highBound; index += 2) { if (oFallback.arrayBestFit[index] == cUnknown) { // We found it Debug.Assert(index + 1 < oFallback.arrayBestFit.Length, "[InternalEncoderBestFitFallbackBuffer.TryBestFit]Expected replacement character at end of array"); return oFallback.arrayBestFit[index + 1]; } } // Char wasn't in our table return '\0'; } } }
sjsinju/coreclr
src/mscorlib/src/System/Text/EncoderBestFitFallback.cs
C#
mit
8,893
'use strict'; var Pagelet = require('pagelet') , async = require('async') , path = require('path'); Pagelet.extend({ view: 'view.ejs', css: 'css.styl', js: 'client.js', // // Allow FORM submits to be streaming. // streaming: true, // // Force a name. // name: 'service-select', // // What data needs to be synced with the front-end. // query: ['services'], pagelets: { target: Pagelet.extend({ view: 'target.ejs', streaming: true }).on(module) }, // // External dependencies that should be included on the page using a regular // script tag. This dependency is needed for the `package.js` client file. // dependencies: [ path.join(__dirname, '/selectize.default.css'), '//code.jquery.com/jquery-2.1.0.min.js', path.join(__dirname, '/selectize.js') ], /** * Respond to POST requests. * * @param {Object} fields The input fields. * @param {Object} files Optional uploaded files. * @param {Function} next Completion callback. * @api public */ post: function post(fields, files, next) { if ('delete' in fields) { this.remove(fields, next); } else if ('add' in fields) { this.add(fields, next); } else { next(new Error('Invalid form data')); } }, /** * Called when a new service has to be added. * * @param {Object} data The data to add. * @param {FUnction} next Continuation function. * @api public */ add: function add(data, next) { throw new Error([ 'You, as a developer need to implement the `.add` method of the service', 'select pagelet. If you dont know how to do this, see the documenation', 'about Pagelet.extend({});' ].join(' ')); }, /** * A service has been removed from the UI. * * @param {Object} data The data containing the info about the service */ remove: function remove(data, next) { throw new Error([ 'You, as a developer need to implement the `.remove` method of the service', 'select pagelet. If you dont know how to do this, see the documenation', 'about Pagelet.extend({});' ].join(' ')); }, /** * The available services that should be listed in the UI. * * @param {Function} next Continuation callback * @api public */ services: function services(next) { throw new Error([ 'You, as a developer need to implement the `.services` method of the service', 'select pagelet. If you dont know how to do this, see the documenation', 'about Pagelet.extend({});' ].join(' ')); }, /** * List of added services that should be displayed in the UI. * * @param {Fucntion} next Continuation callback. * @api public */ added: function added(next) { throw new Error([ 'You, as a developer need to implement the `.added` method of the service', 'select pagelet. If you dont know how to do this, see the documenation', 'about Pagelet.extend({});' ].join(' ')); }, /** * Render the HTML things. * * @param {Function} done Continuation callback. * @api public */ get: function get(done) { var pagelet = this; async.parallel({ services: this.services.bind(this), added: this.added.bind(this) }, function completed(err, data) { if (err) return done(err); data.services = data.services || []; data.added = data.added || []; ['services', 'added'].forEach(function transform(key) { if (Array.isArray(data[key])) return; data[key] = Object.keys(data[key]).map(function map(name) { var thing = data[key][name]; thing.name = thing.name || name; return thing; }); }); data.description = pagelet.description; data.name = pagelet.name.replace('-', ' '); data.name = data.name.slice(0, 1).toUpperCase() + data.name.slice(1); done(err, data); }); } }).on(module);
nodejitsu/service-select
index.js
JavaScript
mit
3,961
#region Licence /* The MIT License (MIT) Copyright © 2015 Ian Cooper <ian_hammond_cooper@yahoo.co.uk> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #endregion using System; namespace Paramore.Brighter.Core.Tests.CommandProcessors.TestDoubles { class MyPostLoggingHandlerAsyncAttribute : RequestHandlerAttribute { public MyPostLoggingHandlerAsyncAttribute(int step, HandlerTiming timing) : base(step, timing) { } public override Type GetHandlerType() { return typeof(MyLoggingHandlerAsync<>); } } }
BrighterCommand/Brighter
tests/Paramore.Brighter.Core.Tests/CommandProcessors/TestDoubles/MyPostLoggingHandlerAsyncAttribute.cs
C#
mit
1,576
using System; using System.Collections.Generic; using System.Windows.Forms; namespace DotMaysWind.Data.Test { static class Program { /// <summary> /// 应用程序的主入口点。 /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new MainForm()); } } }
GuanLee1990/DotMaysWind.Data
DotMaysWind.Data.Test/Program.cs
C#
mit
465
using System; using Fluky.Extensions; using Fluky.Types; namespace Fluky { public partial class Randomizer { public float DistributionNormal(float mean, float standardDeviation) { // Get random normal from Standard Normal Distribution var randomNormalNumber = DistributionStandardNormal(); // Stretch distribution to the requested sigma variance randomNormalNumber *= standardDeviation; // Shift mean to requested mean: randomNormalNumber += mean; // now you have a number selected from a normal distribution with requested mean and sigma! return randomNormalNumber; } public float DistributionStandardNormal() { // This code follows the polar form of the muller transform: // https://en.wikipedia.org/wiki/Box%E2%80%93Muller_transform#Polar_form // also known as Marsaglia polar method // https://en.wikipedia.org/wiki/Marsaglia_polar_method // calculate points on a circle float u, v; float s; // this is the hypotenuse squared. do { u = Float(-1, 1); v = Float(-1, 1); s = (u * u) + (v * v); } while (!(Math.Abs(s) > 0.001f && s < 1)); // keep going until s is nonzero and less than one // TODO: allow a user to specify how many random numbers they want! // choose between u and v for seed (z0 vs z1) var seed = Integer(0, 2) == 0 ? u : v; // create normally distributed number. var z = (seed * Math.Sqrt(-2.0f * Math.Log(s) / s)); var result = z.ToFloat(); return result; } //-------------------------------------------------------------------------------------------- // Sloped Distribution //-------------------------------------------------------------------------------------------- public float DistributionRangeSlope(float min, float max, float skew, DistributionDirection direction) { return min + DistributionSloped(skew, direction) * (max - min); } public float DistributionSloped(float skew, DistributionDirection direction) { // the difference in scale is just the same as the max y-value.. var maxY = skew; // our curve will go from 0 to max_x. var maxX = Inverse_Sec_Sqrd(maxY); var maxCdf = Sec_Sqrd_CumulativeDistributionFunction(maxX); var u = Float(0, maxCdf); var xVal = Sec_Sqrd_InverseCumulativeDistributionFunction(u); // scale to [0,1] var value = xVal / maxX; if (direction == DistributionDirection.Left) value = 1.0f - value; return value; } //-------------------------------------------------------------------------------------------- // Linear Distribution //-------------------------------------------------------------------------------------------- // Returns random in range [min, max] with linear distribution of given slope. public float DistributionRangeLinear(float min, float max, float slope) { var val = DistributionRandomLinear(slope); return min + (max - min) * val; } // Returns random in range [0,1] with linear distribution of given slope. public float DistributionRandomLinear(float slope) { var absValue = DistributionLinearWithPositiveSlope(Math.Abs(slope)); if (slope < 0) return 1 - absValue; return absValue; } private float DistributionLinearWithPositiveSlope(float slope) { if (Math.Abs(slope) < 0.001f) return Float(0.0f, 1.0f); float x, y; do { x = Float(0.0f, 1.0f); y = Float(0.0f, 1.0f); if (slope < 1) { y -= (1 - slope) / 2.0f; } } while (y > x * slope); return x; } //-------------------------------------------------------------------------------------------- // Exponential Distribution //-------------------------------------------------------------------------------------------- public float DistributionExponentialRange(float min, float max, float exponent, DistributionDirection direction) { return min + DistributionExponential(exponent, direction) * (max - min); } public float DistributionExponential(float exponent, DistributionDirection direction) { // our curve will go from 0 to 1. var maxCdf = ExponentialRightCdf(1.0f, exponent); var u = Float(0.0f, maxCdf); var xVal = EponentialRightInverseCDF(u, exponent); if (direction == DistributionDirection.Left) xVal = 1.0f - xVal; return xVal; } // The inverse of the curve. private float DistributionExponentialRightInverse(float y, float exponent) { return Math.Pow(y, 1.0f / exponent).ToFloat(); } // The integral of the exponent curve. private static float ExponentialRightCdf(float x, float exponent) { var integralExp = exponent + 1.0f; var exponentialRightCdf = (Math.Pow(x, integralExp)) / integralExp; return exponentialRightCdf.ToFloat(); } // The inverse of the integral of the exponent curve. private static float EponentialRightInverseCDF(float x, float exponent) { var integralExp = exponent + 1.0f; return Math.Pow(integralExp * x, 1.0f / integralExp).ToFloat(); } /// <summary> /// The inverse of the sec^2 function. /// </summary> /// <param name="y">The y coordinate. if y < 1, returns NaN. </param> private float Inverse_Sec_Sqrd(float y) { // Note: arcsec(x) = arccos(1/x) // return arcsec(sqrt(y)) var inverseSecSqrd = Math.Acos(1.0f / Math.Sqrt(y)); return inverseSecSqrd.ToFloat(); } /// <summary> /// The integral of sec^2 /// </summary> /// <param name="x"></param> /// <returns></returns> private static float Sec_Sqrd_CumulativeDistributionFunction(float x) { // The cumulative distribution function for sec^2 is just the definite integral of sec^2(x) = tan(x) - tan(0) = tan(x) return Math.Tan(x).ToFloat(); } /// <summary> /// The inverse of the integral of sec^2 /// </summary> /// <param name="x"></param> /// <returns></returns> private static float Sec_Sqrd_InverseCumulativeDistributionFunction(float x) { // The cumulative distribution function for sec^2 is just the definite integral of sec^2(x) = tan(x) - tan(0) = tan(x) // Then the Inverse cumulative distribution function is just atan(x) return Math.Atan(x).ToFloat(); } } }
michaeljbaird/Fluky
src/Fluky/Randomizer.Distribution.cs
C#
mit
6,560
/* * The MIT License * * Copyright (c) 2019 CloudBees, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.cloudbees.plugins.credentials.builds; import com.cloudbees.plugins.credentials.CredentialsParameterDefinition; import com.cloudbees.plugins.credentials.CredentialsParameterValue; import com.cloudbees.plugins.credentials.CredentialsProvider; import com.cloudbees.plugins.credentials.CredentialsScope; import com.cloudbees.plugins.credentials.common.IdCredentials; import com.cloudbees.plugins.credentials.domains.Domain; import com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl; import hudson.model.Cause; import hudson.model.CauseAction; import hudson.model.ParametersAction; import hudson.model.ParametersDefinitionProperty; import hudson.model.User; import hudson.model.queue.QueueTaskFuture; import hudson.security.ACL; import hudson.security.ACLContext; import org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition; import org.jenkinsci.plugins.workflow.cps.replay.ReplayAction; import org.jenkinsci.plugins.workflow.job.WorkflowJob; import org.jenkinsci.plugins.workflow.job.WorkflowRun; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.jvnet.hudson.test.JenkinsRule; import java.util.UUID; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; public class CredentialsParameterBinderReplayActionIntegrationTest { private static final String PARAMETER_NAME = "parameterName"; @Rule public JenkinsRule j = new JenkinsRule(); private String credentialsId; @Before public void setUp() throws Exception { j.jenkins.setSecurityRealm(j.createDummySecurityRealm()); final User alpha = User.getById("alpha", true); try (ACLContext ignored = ACL.as(alpha)) { credentialsId = UUID.randomUUID().toString(); CredentialsProvider.lookupStores(alpha).iterator().next() .addCredentials(Domain.global(), new UsernamePasswordCredentialsImpl( CredentialsScope.USER, credentialsId, null, "user", "pass")); } } @Test public void replayActionShouldNotCopyCredentialsParameterBindingUserIds() throws Exception { final WorkflowJob job = j.createProject(WorkflowJob.class); job.addProperty(new ParametersDefinitionProperty(new CredentialsParameterDefinition( PARAMETER_NAME, null, null, IdCredentials.class.getName(), true))); job.setDefinition(new CpsFlowDefinition("echo 'hello, world'", true)); final WorkflowRun run = j.assertBuildStatusSuccess(job.scheduleBuild2(0, new CauseAction(new Cause.UserIdCause("alpha")), new ParametersAction(new CredentialsParameterValue(PARAMETER_NAME, credentialsId, null)) )); final CredentialsParameterBinding original = CredentialsParameterBinder.getOrCreate(run).forParameterName(PARAMETER_NAME); assertNotNull(original); assertEquals("alpha", original.getUserId()); assertNotNull(CredentialsProvider.findCredentialById(PARAMETER_NAME, IdCredentials.class, run)); final User beta = User.getById("beta", true); final WorkflowRun replayedRun = replayRunAs(run, beta); final CredentialsParameterBinding replayed = CredentialsParameterBinder.getOrCreate(replayedRun).forParameterName(PARAMETER_NAME); assertNotNull(replayed); assertEquals("beta", replayed.getUserId()); assertNull(CredentialsProvider.findCredentialById(PARAMETER_NAME, IdCredentials.class, replayedRun)); } @SuppressWarnings("unchecked") private WorkflowRun replayRunAs(WorkflowRun run, User user) throws Exception { final ReplayAction replay = run.getAction(ReplayAction.class); assertNotNull(replay); final QueueTaskFuture<WorkflowRun> futureRun; try (ACLContext ignored = ACL.as(user)) { futureRun = replay.run(replay.getOriginalScript(), replay.getOriginalLoadedScripts()); } return j.assertBuildStatusSuccess(futureRun); } }
jenkinsci/credentials-plugin
src/test/java/com/cloudbees/plugins/credentials/builds/CredentialsParameterBinderReplayActionIntegrationTest.java
Java
mit
5,191
export * from './card-demo.component';
blackbaud/skyux2
src/demos/card/index.ts
TypeScript
mit
39
function listEvent(login, userCity, done, fail, always) { done = typeof done !== 'undefined' ? done : function() { }; fail = typeof fail !== 'undefined' ? fail : function() { }; always = typeof always !== 'undefined' ? always : function() { }; $.ajax({ url : 'rest/event/' + login + '/' + userCity, type : 'GET' }).done(done).fail(fail).always(always); } function joinEvent(login, eventId, done, fail, always) { done = typeof done !== 'undefined' ? done : function() { }; fail = typeof fail !== 'undefined' ? fail : function() { }; always = typeof always !== 'undefined' ? always : function() { }; $.ajax({ url : 'rest/event/' + eventId + '/' + login, type : 'POST' }).done(done).fail(fail).always(always); }
michada/HYS2
DAAExample-master/src/main/webapp/js/dao/event.js
JavaScript
mit
737
require 'fileutils' require 'simplecov' SimpleCov.start def fixture *args File.join File.dirname(__FILE__), "fixtures", *args end def directory path full = fixture(path) FileUtils::mkdir_p full return full end def file *args file = File.join(*args[0..-2]) directory File.dirname(file) File.open(file, 'w') {|f| f.write args[-1] } return file end def rm path FileUtils::rm_rf path end RSpec::Matchers.define :match_stdout do |check| @capture = nil match do |block| begin stdout_saved = $stdout $stdout = StringIO.new block.call ensure @capture = $stdout $stdout = stdout_saved end @capture.string.match check end failure_message do "expected to #{description}" end failure_message_when_negated do "expected not to #{description}" end description do "match [#{check}] on stdout [#{@capture.string}]" end end
clarete/s3sync
spec/spec_helper.rb
Ruby
mit
912
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using NUnit.Framework; using SIL.TestUtilities; using SIL.WritingSystems; using SIL.WritingSystems.Tests; namespace SIL.Windows.Forms.WritingSystems.Tests { [TestFixture] [OfflineSldr] public class WritingSystemFromWindowsLocaleProviderTests { private class WritingSystemFromWindowsLocaleProviderAccessor: WritingSystemFromWindowsLocaleProvider { public WritingSystemFromWindowsLocaleProviderAccessor( IWritingSystemFactory writingSystemFactory) : base(writingSystemFactory) { } public static string CallGetRegion(string cultureName) { return GetRegion(cultureName); } } [Test] [Category("DesktopRequired")] // Fails on Jenkins because InputLanguage.InstalledInputLanguages returns an empty list. [Platform(Exclude = "Linux", Reason = "Linux only usually returns the Invariant, reimplement using IBus")] public void ActiveIncludesAtLeastOneLanguage() { IEnumerable<Tuple<string, string>> provider = new WritingSystemFromWindowsLocaleProvider(new TestWritingSystemFactory()); Assert.IsNotNull(provider.First()); } /// <summary> /// This is only really testing something if your computer happens to have multiple /// keyboards set up for a language. /// </summary> [Test] [Category("DesktopRequired")] // Fails on Jenkins because InputLanguage.InstalledInputLanguages returns an empty list. [Platform(Exclude = "Linux", Reason = "Linux only usually returns the Invariant, reimplement using IBus")] public void GetEnumerator_IfHaveMultipleSystemKeyboardsForSameLanguage_OnlyReturnsOneForEachLanguage() { IEnumerable<Tuple<string, string>> provider = new WritingSystemFromWindowsLocaleProvider(new TestWritingSystemFactory()); Assert.IsNotNull(provider.First()); foreach (var group in provider.GroupBy(d => d.Item1)) Assert.AreEqual(1, group.Count()); } // [Test] // public void GetGoodPropertiesOutOfCulture() // { // IEnumerable<WritingSystemDefinition> provider = // new SIL.Windows.Forms.WritingSystems.WritingSystemFromWindowsLocaleProvider(); // foreach (WritingSystemDefinition language in provider.WritingSystems) // { //// if (language.Language == "eng") //// { //// Assert.AreEqual("Latn",language.Script); //// Assert.AreEqual("en-Latn", language.RFC5646); //// } // } // } [TestCase("aa", ExpectedResult = "ET")] // returns default region [TestCase("chr", ExpectedResult = "US")] // previously ArgumentException [TestCase("chr-Cher", ExpectedResult = "US")] // previously ArgumentException [TestCase("chr-Cher-US", ExpectedResult = "US")] [TestCase("en", ExpectedResult = "US")] // previously ArgumentException [TestCase("en-US", ExpectedResult = "US")] [TestCase("en-001", ExpectedResult = "001")] [TestCase("jv-Latn", ExpectedResult = "ID")] [TestCase("jv-Latn-ID", ExpectedResult = "ID")] [TestCase("kok", ExpectedResult = "IN")] // previously ArgumentException [TestCase("kok-IN", ExpectedResult = "IN")] [TestCase("und", ExpectedResult = "")] [TestCase("und-001", ExpectedResult = "001")] public string GetRegion(string cultureName) { return WritingSystemFromWindowsLocaleProviderAccessor.CallGetRegion(cultureName); } } }
sillsdev/libpalaso
SIL.Windows.Forms.WritingSystems.Tests/WritingSystemFromWindowsLocaleProviderTests.cs
C#
mit
3,430
// Copyright (c) 2007-2010 Satoshi Nakamoto // Copyright (c) 2009-2016 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "amount.h" #include "chain.h" #include "chainparams.h" #include "checkpoints.h" #include "checkpointsync.h" #include "coins.h" #include "consensus/validation.h" #include "validation.h" #include "policy/policy.h" #include "primitives/transaction.h" #include "rpc/server.h" #include "streams.h" #include "sync.h" #include "txmempool.h" #include "util.h" #include "utilstrencodings.h" #include "hash.h" #include <stdint.h> #include <univalue.h> #include <boost/thread/thread.hpp> // boost::thread::interrupt #include <mutex> #include <condition_variable> using namespace std; struct CUpdatedBlock { uint256 hash; int height; }; static std::mutex cs_blockchange; static std::condition_variable cond_blockchange; static CUpdatedBlock latestblock; extern void TxToJSON(const CTransaction& tx, const uint256 hashBlock, UniValue& entry); void ScriptPubKeyToJSON(const CScript& scriptPubKey, UniValue& out, bool fIncludeHex); double GetDifficulty(const CBlockIndex* blockindex) { // Floating point number that is a multiple of the minimum difficulty, // minimum difficulty = 1.0. if (blockindex == NULL) { if (chainActive.Tip() == NULL) return 1.0; else blockindex = chainActive.Tip(); } int nShift = (blockindex->nBits >> 24) & 0xff; double dDiff = (double)0x0000ffff / (double)(blockindex->nBits & 0x00ffffff); while (nShift < 29) { dDiff *= 256.0; nShift++; } while (nShift > 29) { dDiff /= 256.0; nShift--; } return dDiff; } UniValue blockheaderToJSON(const CBlockIndex* blockindex) { UniValue result(UniValue::VOBJ); result.push_back(Pair("hash", blockindex->GetBlockHash().GetHex())); int confirmations = -1; // Only report confirmations if the block is on the main chain if (chainActive.Contains(blockindex)) confirmations = chainActive.Height() - blockindex->nHeight + 1; result.push_back(Pair("confirmations", confirmations)); result.push_back(Pair("height", blockindex->nHeight)); result.push_back(Pair("version", blockindex->nVersion)); result.push_back(Pair("versionHex", strprintf("%08x", blockindex->nVersion))); result.push_back(Pair("merkleroot", blockindex->hashMerkleRoot.GetHex())); result.push_back(Pair("time", (int64_t)blockindex->nTime)); result.push_back(Pair("mediantime", (int64_t)blockindex->GetMedianTimePast())); result.push_back(Pair("nonce", (uint64_t)blockindex->nNonce)); result.push_back(Pair("bits", strprintf("%08x", blockindex->nBits))); result.push_back(Pair("difficulty", GetDifficulty(blockindex))); result.push_back(Pair("chainwork", blockindex->nChainWork.GetHex())); if (blockindex->pprev) result.push_back(Pair("previousblockhash", blockindex->pprev->GetBlockHash().GetHex())); CBlockIndex *pnext = chainActive.Next(blockindex); if (pnext) result.push_back(Pair("nextblockhash", pnext->GetBlockHash().GetHex())); return result; } UniValue blockToJSON(const CBlock& block, const CBlockIndex* blockindex, bool txDetails = false, bool fQueuedBlock = false) { UniValue result(UniValue::VOBJ); result.push_back(Pair("hash", !fQueuedBlock ? blockindex->GetBlockHash().GetHex() : block.GetHash().GetHex())); int confirmations = -1; // Only report confirmations if the block is on the main chain if (chainActive.Contains(blockindex)) confirmations = chainActive.Height() - blockindex->nHeight + 1; result.push_back(Pair("confirmations", confirmations)); result.push_back(Pair("strippedsize", (int)::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION | SERIALIZE_TRANSACTION_NO_WITNESS))); result.push_back(Pair("size", (int)::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION | SERIALIZE_TRANSACTION_NO_WITNESS))); result.push_back(Pair("height", fQueuedBlock ? blockindex->nHeight+1 : blockindex->nHeight)); result.push_back(Pair("version", block.nVersion)); result.push_back(Pair("versionHex", strprintf("%08x", block.nVersion))); result.push_back(Pair("merkleroot", block.hashMerkleRoot.GetHex())); UniValue txs(UniValue::VARR); for(const auto& tx : block.vtx) { if(txDetails) { UniValue objTx(UniValue::VOBJ); TxToJSON(*tx, uint256(), objTx); txs.push_back(objTx); } else txs.push_back(tx->GetHash().GetHex()); } result.push_back(Pair("tx", txs)); result.push_back(Pair("time", block.GetBlockTime())); result.push_back(Pair("mediantime", blockindex->GetMedianTimePast())); result.push_back(Pair("nonce", (uint64_t)block.nNonce)); result.push_back(Pair("bits", strprintf("%08x", block.nBits))); result.push_back(Pair("difficulty", GetDifficulty(blockindex))); result.push_back(Pair("chainwork", blockindex ? blockindex->nChainWork.GetHex() : 0)); if (!fQueuedBlock && blockindex->pprev) result.push_back(Pair("previousblockhash", blockindex->pprev->GetBlockHash().GetHex())); else result.push_back(Pair("previousblockhash", blockindex->GetBlockHash().GetHex())); if (!fQueuedBlock) { CBlockIndex *pnext = chainActive.Next(blockindex); if (pnext) result.push_back(Pair("nextblockhash", pnext->GetBlockHash().GetHex())); } return result; } UniValue getblockcount(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 0) throw runtime_error( "getblockcount\n" "\nReturns the number of blocks in the longest blockchain.\n" "\nResult:\n" "n (numeric) The current block count\n" "\nExamples:\n" + HelpExampleCli("getblockcount", "") + HelpExampleRpc("getblockcount", "") ); LOCK(cs_main); return chainActive.Height(); } UniValue getbestblockhash(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 0) throw runtime_error( "getbestblockhash\n" "\nReturns the hash of the best (tip) block in the longest blockchain.\n" "\nResult:\n" "\"hex\" (string) the block hash hex encoded\n" "\nExamples:\n" + HelpExampleCli("getbestblockhash", "") + HelpExampleRpc("getbestblockhash", "") ); LOCK(cs_main); return chainActive.Tip()->GetBlockHash().GetHex(); } void RPCNotifyBlockChange(bool ibd, const CBlockIndex * pindex) { if(pindex) { std::lock_guard<std::mutex> lock(cs_blockchange); latestblock.hash = pindex->GetBlockHash(); latestblock.height = pindex->nHeight; } cond_blockchange.notify_all(); } UniValue waitfornewblock(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() > 1) throw runtime_error( "waitfornewblock (timeout)\n" "\nWaits for a specific new block and returns useful info about it.\n" "\nReturns the current block on timeout or exit.\n" "\nArguments:\n" "1. timeout (int, optional, default=0) Time in milliseconds to wait for a response. 0 indicates no timeout.\n" "\nResult:\n" "{ (json object)\n" " \"hash\" : { (string) The blockhash\n" " \"height\" : { (int) Block height\n" "}\n" "\nExamples:\n" + HelpExampleCli("waitfornewblock", "1000") + HelpExampleRpc("waitfornewblock", "1000") ); int timeout = 0; if (request.params.size() > 0) timeout = request.params[0].get_int(); CUpdatedBlock block; { std::unique_lock<std::mutex> lock(cs_blockchange); block = latestblock; if(timeout) cond_blockchange.wait_for(lock, std::chrono::milliseconds(timeout), [&block]{return latestblock.height != block.height || latestblock.hash != block.hash || !IsRPCRunning(); }); else cond_blockchange.wait(lock, [&block]{return latestblock.height != block.height || latestblock.hash != block.hash || !IsRPCRunning(); }); block = latestblock; } UniValue ret(UniValue::VOBJ); ret.push_back(Pair("hash", block.hash.GetHex())); ret.push_back(Pair("height", block.height)); return ret; } UniValue waitforblock(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() < 1 || request.params.size() > 2) throw runtime_error( "waitforblock <blockhash> (timeout)\n" "\nWaits for a specific new block and returns useful info about it.\n" "\nReturns the current block on timeout or exit.\n" "\nArguments:\n" "1. \"blockhash\" (required, string) Block hash to wait for.\n" "2. timeout (int, optional, default=0) Time in milliseconds to wait for a response. 0 indicates no timeout.\n" "\nResult:\n" "{ (json object)\n" " \"hash\" : { (string) The blockhash\n" " \"height\" : { (int) Block height\n" "}\n" "\nExamples:\n" + HelpExampleCli("waitforblock", "\"0000000000079f8ef3d2c688c244eb7a4570b24c9ed7b4a8c619eb02596f8862\", 1000") + HelpExampleRpc("waitforblock", "\"0000000000079f8ef3d2c688c244eb7a4570b24c9ed7b4a8c619eb02596f8862\", 1000") ); int timeout = 0; uint256 hash = uint256S(request.params[0].get_str()); if (request.params.size() > 1) timeout = request.params[1].get_int(); CUpdatedBlock block; { std::unique_lock<std::mutex> lock(cs_blockchange); if(timeout) cond_blockchange.wait_for(lock, std::chrono::milliseconds(timeout), [&hash]{return latestblock.hash == hash || !IsRPCRunning();}); else cond_blockchange.wait(lock, [&hash]{return latestblock.hash == hash || !IsRPCRunning(); }); block = latestblock; } UniValue ret(UniValue::VOBJ); ret.push_back(Pair("hash", block.hash.GetHex())); ret.push_back(Pair("height", block.height)); return ret; } UniValue waitforblockheight(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() < 1 || request.params.size() > 2) throw runtime_error( "waitforblockheight <height> (timeout)\n" "\nWaits for (at least) block height and returns the height and hash\n" "of the current tip.\n" "\nReturns the current block on timeout or exit.\n" "\nArguments:\n" "1. height (required, int) Block height to wait for (int)\n" "2. timeout (int, optional, default=0) Time in milliseconds to wait for a response. 0 indicates no timeout.\n" "\nResult:\n" "{ (json object)\n" " \"hash\" : { (string) The blockhash\n" " \"height\" : { (int) Block height\n" "}\n" "\nExamples:\n" + HelpExampleCli("waitforblockheight", "\"100\", 1000") + HelpExampleRpc("waitforblockheight", "\"100\", 1000") ); int timeout = 0; int height = request.params[0].get_int(); if (request.params.size() > 1) timeout = request.params[1].get_int(); CUpdatedBlock block; { std::unique_lock<std::mutex> lock(cs_blockchange); if(timeout) cond_blockchange.wait_for(lock, std::chrono::milliseconds(timeout), [&height]{return latestblock.height >= height || !IsRPCRunning();}); else cond_blockchange.wait(lock, [&height]{return latestblock.height >= height || !IsRPCRunning(); }); block = latestblock; } UniValue ret(UniValue::VOBJ); ret.push_back(Pair("hash", block.hash.GetHex())); ret.push_back(Pair("height", block.height)); return ret; } UniValue getdifficulty(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 0) throw runtime_error( "getdifficulty\n" "\nReturns the proof-of-work difficulty as a multiple of the minimum difficulty.\n" "\nResult:\n" "n.nnn (numeric) the proof-of-work difficulty as a multiple of the minimum difficulty.\n" "\nExamples:\n" + HelpExampleCli("getdifficulty", "") + HelpExampleRpc("getdifficulty", "") ); LOCK(cs_main); return GetDifficulty(); } std::string EntryDescriptionString() { return " \"size\" : n, (numeric) actual transaction size\n" " \"fee\" : n, (numeric) transaction fee in " + CURRENCY_UNIT + "\n" " \"modifiedfee\" : n, (numeric) transaction fee with fee deltas used for mining priority\n" " \"time\" : n, (numeric) local time transaction entered pool in seconds since 1 Jan 1970 GMT\n" " \"height\" : n, (numeric) block height when transaction entered pool\n" " \"startingpriority\" : n, (numeric) DEPRECATED. Priority when transaction entered pool\n" " \"currentpriority\" : n, (numeric) DEPRECATED. Transaction priority now\n" " \"descendantcount\" : n, (numeric) number of in-mempool descendant transactions (including this one)\n" " \"descendantsize\" : n, (numeric) virtual transaction size of in-mempool descendants (including this one)\n" " \"descendantfees\" : n, (numeric) modified fees (see above) of in-mempool descendants (including this one)\n" " \"ancestorcount\" : n, (numeric) number of in-mempool ancestor transactions (including this one)\n" " \"ancestorsize\" : n, (numeric) transaction size of in-mempool ancestors (including this one)\n" " \"ancestorfees\" : n, (numeric) modified fees (see above) of in-mempool ancestors (including this one)\n" " \"depends\" : [ (array) unconfirmed transactions used as inputs for this transaction\n" " \"transactionid\", (string) parent transaction id\n" " ... ]\n"; } void entryToJSON(UniValue &info, const CTxMemPoolEntry &e) { AssertLockHeld(mempool.cs); info.push_back(Pair("size", (int)e.GetTxSize())); info.push_back(Pair("fee", ValueFromAmount(e.GetFee()))); info.push_back(Pair("modifiedfee", ValueFromAmount(e.GetModifiedFee()))); info.push_back(Pair("time", e.GetTime())); info.push_back(Pair("height", (int)e.GetHeight())); info.push_back(Pair("startingpriority", e.GetPriority(e.GetHeight()))); info.push_back(Pair("currentpriority", e.GetPriority(chainActive.Height()))); info.push_back(Pair("descendantcount", e.GetCountWithDescendants())); info.push_back(Pair("descendantsize", e.GetSizeWithDescendants())); info.push_back(Pair("descendantfees", e.GetModFeesWithDescendants())); info.push_back(Pair("ancestorcount", e.GetCountWithAncestors())); info.push_back(Pair("ancestorsize", e.GetSizeWithAncestors())); info.push_back(Pair("ancestorfees", e.GetModFeesWithAncestors())); const CTransaction& tx = e.GetTx(); set<string> setDepends; BOOST_FOREACH(const CTxIn& txin, tx.vin) { if (mempool.exists(txin.prevout.hash)) setDepends.insert(txin.prevout.hash.ToString()); } UniValue depends(UniValue::VARR); BOOST_FOREACH(const string& dep, setDepends) { depends.push_back(dep); } info.push_back(Pair("depends", depends)); } UniValue mempoolToJSON(bool fVerbose = false) { if (fVerbose) { LOCK(mempool.cs); UniValue o(UniValue::VOBJ); BOOST_FOREACH(const CTxMemPoolEntry& e, mempool.mapTx) { const uint256& hash = e.GetTx().GetHash(); UniValue info(UniValue::VOBJ); entryToJSON(info, e); o.push_back(Pair(hash.ToString(), info)); } return o; } else { vector<uint256> vtxid; mempool.queryHashes(vtxid); UniValue a(UniValue::VARR); BOOST_FOREACH(const uint256& hash, vtxid) a.push_back(hash.ToString()); return a; } } UniValue getrawmempool(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() > 1) throw runtime_error( "getrawmempool ( verbose )\n" "\nReturns all transaction ids in memory pool as a json array of string transaction ids.\n" "\nArguments:\n" "1. verbose (boolean, optional, default=false) True for a json object, false for array of transaction ids\n" "\nResult: (for verbose = false):\n" "[ (json array of string)\n" " \"transactionid\" (string) The transaction id\n" " ,...\n" "]\n" "\nResult: (for verbose = true):\n" "{ (json object)\n" " \"transactionid\" : { (json object)\n" + EntryDescriptionString() + " }, ...\n" "}\n" "\nExamples:\n" + HelpExampleCli("getrawmempool", "true") + HelpExampleRpc("getrawmempool", "true") ); bool fVerbose = false; if (request.params.size() > 0) fVerbose = request.params[0].get_bool(); return mempoolToJSON(fVerbose); } UniValue getmempoolancestors(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() < 1 || request.params.size() > 2) { throw runtime_error( "getmempoolancestors txid (verbose)\n" "\nIf txid is in the mempool, returns all in-mempool ancestors.\n" "\nArguments:\n" "1. \"txid\" (string, required) The transaction id (must be in mempool)\n" "2. verbose (boolean, optional, default=false) True for a json object, false for array of transaction ids\n" "\nResult (for verbose=false):\n" "[ (json array of strings)\n" " \"transactionid\" (string) The transaction id of an in-mempool ancestor transaction\n" " ,...\n" "]\n" "\nResult (for verbose=true):\n" "{ (json object)\n" " \"transactionid\" : { (json object)\n" + EntryDescriptionString() + " }, ...\n" "}\n" "\nExamples:\n" + HelpExampleCli("getmempoolancestors", "\"mytxid\"") + HelpExampleRpc("getmempoolancestors", "\"mytxid\"") ); } bool fVerbose = false; if (request.params.size() > 1) fVerbose = request.params[1].get_bool(); uint256 hash = ParseHashV(request.params[0], "parameter 1"); LOCK(mempool.cs); CTxMemPool::txiter it = mempool.mapTx.find(hash); if (it == mempool.mapTx.end()) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction not in mempool"); } CTxMemPool::setEntries setAncestors; uint64_t noLimit = std::numeric_limits<uint64_t>::max(); std::string dummy; mempool.CalculateMemPoolAncestors(*it, setAncestors, noLimit, noLimit, noLimit, noLimit, dummy, false); if (!fVerbose) { UniValue o(UniValue::VARR); BOOST_FOREACH(CTxMemPool::txiter ancestorIt, setAncestors) { o.push_back(ancestorIt->GetTx().GetHash().ToString()); } return o; } else { UniValue o(UniValue::VOBJ); BOOST_FOREACH(CTxMemPool::txiter ancestorIt, setAncestors) { const CTxMemPoolEntry &e = *ancestorIt; const uint256& _hash = e.GetTx().GetHash(); UniValue info(UniValue::VOBJ); entryToJSON(info, e); o.push_back(Pair(_hash.ToString(), info)); } return o; } } UniValue getmempooldescendants(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() < 1 || request.params.size() > 2) { throw runtime_error( "getmempooldescendants txid (verbose)\n" "\nIf txid is in the mempool, returns all in-mempool descendants.\n" "\nArguments:\n" "1. \"txid\" (string, required) The transaction id (must be in mempool)\n" "2. verbose (boolean, optional, default=false) True for a json object, false for array of transaction ids\n" "\nResult (for verbose=false):\n" "[ (json array of strings)\n" " \"transactionid\" (string) The transaction id of an in-mempool descendant transaction\n" " ,...\n" "]\n" "\nResult (for verbose=true):\n" "{ (json object)\n" " \"transactionid\" : { (json object)\n" + EntryDescriptionString() + " }, ...\n" "}\n" "\nExamples:\n" + HelpExampleCli("getmempooldescendants", "\"mytxid\"") + HelpExampleRpc("getmempooldescendants", "\"mytxid\"") ); } bool fVerbose = false; if (request.params.size() > 1) fVerbose = request.params[1].get_bool(); uint256 hash = ParseHashV(request.params[0], "parameter 1"); LOCK(mempool.cs); CTxMemPool::txiter it = mempool.mapTx.find(hash); if (it == mempool.mapTx.end()) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction not in mempool"); } CTxMemPool::setEntries setDescendants; mempool.CalculateDescendants(it, setDescendants); // CTxMemPool::CalculateDescendants will include the given tx setDescendants.erase(it); if (!fVerbose) { UniValue o(UniValue::VARR); BOOST_FOREACH(CTxMemPool::txiter descendantIt, setDescendants) { o.push_back(descendantIt->GetTx().GetHash().ToString()); } return o; } else { UniValue o(UniValue::VOBJ); BOOST_FOREACH(CTxMemPool::txiter descendantIt, setDescendants) { const CTxMemPoolEntry &e = *descendantIt; const uint256& _hash = e.GetTx().GetHash(); UniValue info(UniValue::VOBJ); entryToJSON(info, e); o.push_back(Pair(_hash.ToString(), info)); } return o; } } UniValue getmempoolentry(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 1) { throw runtime_error( "getmempoolentry txid\n" "\nReturns mempool data for given transaction\n" "\nArguments:\n" "1. \"txid\" (string, required) The transaction id (must be in mempool)\n" "\nResult:\n" "{ (json object)\n" + EntryDescriptionString() + "}\n" "\nExamples:\n" + HelpExampleCli("getmempoolentry", "\"mytxid\"") + HelpExampleRpc("getmempoolentry", "\"mytxid\"") ); } uint256 hash = ParseHashV(request.params[0], "parameter 1"); LOCK(mempool.cs); CTxMemPool::txiter it = mempool.mapTx.find(hash); if (it == mempool.mapTx.end()) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction not in mempool"); } const CTxMemPoolEntry &e = *it; UniValue info(UniValue::VOBJ); entryToJSON(info, e); return info; } UniValue getblockhash(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 1) throw runtime_error( "getblockhash height\n" "\nReturns hash of block in best-block-chain at height provided.\n" "\nArguments:\n" "1. height (numeric, required) The height index\n" "\nResult:\n" "\"hash\" (string) The block hash\n" "\nExamples:\n" + HelpExampleCli("getblockhash", "1000") + HelpExampleRpc("getblockhash", "1000") ); LOCK(cs_main); int nHeight = request.params[0].get_int(); if (nHeight < 0 || nHeight > chainActive.Height()) throw JSONRPCError(RPC_INVALID_PARAMETER, "Block height out of range"); CBlockIndex* pblockindex = chainActive[nHeight]; return pblockindex->GetBlockHash().GetHex(); } UniValue getblockheader(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() < 1 || request.params.size() > 2) throw runtime_error( "getblockheader \"hash\" ( verbose )\n" "\nIf verbose is false, returns a string that is serialized, hex-encoded data for blockheader 'hash'.\n" "If verbose is true, returns an Object with information about blockheader <hash>.\n" "\nArguments:\n" "1. \"hash\" (string, required) The block hash\n" "2. verbose (boolean, optional, default=true) true for a json object, false for the hex encoded data\n" "\nResult (for verbose = true):\n" "{\n" " \"hash\" : \"hash\", (string) the block hash (same as provided)\n" " \"confirmations\" : n, (numeric) The number of confirmations, or -1 if the block is not on the main chain\n" " \"height\" : n, (numeric) The block height or index\n" " \"version\" : n, (numeric) The block version\n" " \"versionHex\" : \"00000000\", (string) The block version formatted in hexadecimal\n" " \"merkleroot\" : \"xxxx\", (string) The merkle root\n" " \"time\" : ttt, (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\n" " \"mediantime\" : ttt, (numeric) The median block time in seconds since epoch (Jan 1 1970 GMT)\n" " \"nonce\" : n, (numeric) The nonce\n" " \"bits\" : \"1d00ffff\", (string) The bits\n" " \"difficulty\" : x.xxx, (numeric) The difficulty\n" " \"chainwork\" : \"0000...1f3\" (string) Expected number of hashes required to produce the current chain (in hex)\n" " \"previousblockhash\" : \"hash\", (string) The hash of the previous block\n" " \"nextblockhash\" : \"hash\", (string) The hash of the next block\n" "}\n" "\nResult (for verbose=false):\n" "\"data\" (string) A string that is serialized, hex-encoded data for block 'hash'.\n" "\nExamples:\n" + HelpExampleCli("getblockheader", "\"e2acdf2dd19a702e5d12a925f1e984b01e47a933562ca893656d4afb38b44ee3\"") + HelpExampleRpc("getblockheader", "\"e2acdf2dd19a702e5d12a925f1e984b01e47a933562ca893656d4afb38b44ee3\"") ); LOCK(cs_main); std::string strHash = request.params[0].get_str(); uint256 hash(uint256S(strHash)); bool fVerbose = true; if (request.params.size() > 1) fVerbose = request.params[1].get_bool(); if (mapBlockIndex.count(hash) == 0) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found"); CBlockIndex* pblockindex = mapBlockIndex[hash]; if (!fVerbose) { CDataStream ssBlock(SER_NETWORK, PROTOCOL_VERSION); ssBlock << pblockindex->GetBlockHeader(); std::string strHex = HexStr(ssBlock.begin(), ssBlock.end()); return strHex; } return blockheaderToJSON(pblockindex); } UniValue getblock(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() < 1 || request.params.size() > 2) throw runtime_error( "getblock \"blockhash\" ( verbose )\n" "\nIf verbose is false, returns a string that is serialized, hex-encoded data for block 'hash'.\n" "If verbose is true, returns an Object with information about block <hash>.\n" "\nArguments:\n" "1. \"blockhash\" (string, required) The block hash\n" "2. verbose (boolean, optional, default=true) true for a json object, false for the hex encoded data\n" "\nResult (for verbose = true):\n" "{\n" " \"hash\" : \"hash\", (string) the block hash (same as provided)\n" " \"confirmations\" : n, (numeric) The number of confirmations, or -1 if the block is not on the main chain\n" " \"size\" : n, (numeric) The block size\n" " \"weight\" : n (numeric) The block weight as defined in BIP 141\n" " \"height\" : n, (numeric) The block height or index\n" " \"version\" : n, (numeric) The block version\n" " \"versionHex\" : \"00000000\", (string) The block version formatted in hexadecimal\n" " \"merkleroot\" : \"xxxx\", (string) The merkle root\n" " \"tx\" : [ (array of string) The transaction ids\n" " \"transactionid\" (string) The transaction id\n" " ,...\n" " ],\n" " \"time\" : ttt, (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\n" " \"mediantime\" : ttt, (numeric) The median block time in seconds since epoch (Jan 1 1970 GMT)\n" " \"nonce\" : n, (numeric) The nonce\n" " \"bits\" : \"1d00ffff\", (string) The bits\n" " \"difficulty\" : x.xxx, (numeric) The difficulty\n" " \"chainwork\" : \"xxxx\", (string) Expected number of hashes required to produce the chain up to this block (in hex)\n" " \"previousblockhash\" : \"hash\", (string) The hash of the previous block\n" " \"nextblockhash\" : \"hash\" (string) The hash of the next block\n" "}\n" "\nResult (for verbose=false):\n" "\"data\" (string) A string that is serialized, hex-encoded data for block 'hash'.\n" "\nExamples:\n" + HelpExampleCli("getblock", "\"e2acdf2dd19a702e5d12a925f1e984b01e47a933562ca893656d4afb38b44ee3\"") + HelpExampleRpc("getblock", "\"e2acdf2dd19a702e5d12a925f1e984b01e47a933562ca893656d4afb38b44ee3\"") ); LOCK(cs_main); std::string strHash = request.params[0].get_str(); uint256 hash(uint256S(strHash)); shared_ptr<const CBlock> queuedBlock; bool fVerbose = true; if (request.params.size() > 1) fVerbose = request.params[1].get_bool(); if (mapBlockIndex.count(hash) == 0) { queuedBlock = GetQueuedBlock(); if(queuedBlock == nullptr || queuedBlock->GetHash().Compare(hash) != 0 || nReportQueuedBlocks != REPORT_QUEUED_BLOCK_TRANSACTION) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found"); } CBlock block; CBlockIndex* pblockindex = queuedBlock == nullptr ? mapBlockIndex[hash] : 0; if(queuedBlock == nullptr) { if (fHavePruned && !(pblockindex->nStatus & BLOCK_HAVE_DATA) && pblockindex->nTx > 0) throw JSONRPCError(RPC_INTERNAL_ERROR, "Block not available (pruned data)"); if(!ReadBlockFromDisk(block, pblockindex, Params().GetConsensus())) throw JSONRPCError(RPC_INTERNAL_ERROR, "Can't read block from disk"); } else { //Copy the block so it is available in the waiting thread. CDataStream stream(SER_NETWORK, PROTOCOL_VERSION); queuedBlock->Serialize(stream); stream.Rewind(stream.size()); block.Unserialize(stream); pblockindex = chainActive.Tip(); } if (!fVerbose) { CDataStream ssBlock(SER_NETWORK, PROTOCOL_VERSION | RPCSerializationFlags()); ssBlock << block; std::string strHex = HexStr(ssBlock.begin(), ssBlock.end()); return strHex; } return blockToJSON(block, pblockindex, false, queuedBlock != nullptr); } // RPC commands related to sync checkpoints // get information of sync-checkpoint (first introduced in ppcoin) UniValue getcheckpoint(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 0) throw std::runtime_error( "getcheckpoint\n" "Show info of synchronized checkpoint.\n"); UniValue result(UniValue::VARR); UniValue entry(UniValue::VOBJ); CBlockIndex* pindexCheckpoint; entry.push_back(Pair("synccheckpoint", hashSyncCheckpoint.ToString().c_str())); if (mapBlockIndex.count(hashSyncCheckpoint)) { pindexCheckpoint = mapBlockIndex[hashSyncCheckpoint]; entry.push_back(Pair("height", pindexCheckpoint->nHeight)); entry.push_back(Pair("timestamp", (boost::int64_t) pindexCheckpoint->GetBlockTime())); } if (IsArgSet("-checkpointkey")) entry.push_back(Pair("checkpointmaster", true)); result.push_back(entry); return result; } UniValue sendcheckpoint(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 1) throw std::runtime_error( "sendcheckpoint <blockhash>\n" "Send a synchronized checkpoint.\n"); if (IsArgSet("-checkpointkey") || CSyncCheckpoint::strMasterPrivKey.empty()) throw std::runtime_error("Not a checkpointmaster node, first set checkpointkey in configuration and restart client. "); std::string strHash = request.params[0].get_str(); uint256 hash = uint256S(strHash); if (!SendSyncCheckpoint(hash)) throw std::runtime_error("Failed to send checkpoint, check log. "); UniValue result(UniValue::VARR); UniValue entry(UniValue::VOBJ); CBlockIndex* pindexCheckpoint; entry.push_back(Pair("synccheckpoint", hashSyncCheckpoint.ToString().c_str())); if (mapBlockIndex.count(hashSyncCheckpoint)) { pindexCheckpoint = mapBlockIndex[hashSyncCheckpoint]; entry.push_back(Pair("height", pindexCheckpoint->nHeight)); entry.push_back(Pair("timestamp", (boost::int64_t) pindexCheckpoint->GetBlockTime())); } if (IsArgSet("-checkpointkey")) entry.push_back(Pair("checkpointmaster", true)); result.push_back(entry); return result; } struct CCoinsStats { int nHeight; uint256 hashBlock; uint64_t nTransactions; uint64_t nTransactionOutputs; uint64_t nSerializedSize; uint256 hashSerialized; CAmount nTotalAmount; CCoinsStats() : nHeight(0), nTransactions(0), nTransactionOutputs(0), nSerializedSize(0), nTotalAmount(0) {} }; //! Calculate statistics about the unspent transaction output set static bool GetUTXOStats(CCoinsView *view, CCoinsStats &stats) { std::unique_ptr<CCoinsViewCursor> pcursor(view->Cursor()); CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION); stats.hashBlock = pcursor->GetBestBlock(); { LOCK(cs_main); stats.nHeight = mapBlockIndex.find(stats.hashBlock)->second->nHeight; } ss << stats.hashBlock; CAmount nTotalAmount = 0; while (pcursor->Valid()) { boost::this_thread::interruption_point(); uint256 key; CCoins coins; if (pcursor->GetKey(key) && pcursor->GetValue(coins)) { stats.nTransactions++; ss << key; for (unsigned int i=0; i<coins.vout.size(); i++) { const CTxOut &out = coins.vout[i]; if (!out.IsNull()) { stats.nTransactionOutputs++; ss << VARINT(i+1); ss << out; nTotalAmount += out.nValue; } } stats.nSerializedSize += 32 + pcursor->GetValueSize(); ss << VARINT(0); } else { return error("%s: unable to read value", __func__); } pcursor->Next(); } stats.hashSerialized = ss.GetHash(); stats.nTotalAmount = nTotalAmount; return true; } UniValue pruneblockchain(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 1) throw runtime_error( "pruneblockchain\n" "\nArguments:\n" "1. \"height\" (numeric, required) The block height to prune up to. May be set to a discrete height, or a unix timestamp\n" " to prune blocks whose block time is at least 2 hours older than the provided timestamp.\n" "\nResult:\n" "n (numeric) Height of the last block pruned.\n" "\nExamples:\n" + HelpExampleCli("pruneblockchain", "1000") + HelpExampleRpc("pruneblockchain", "1000")); if (!fPruneMode) throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Cannot prune blocks because node is not in prune mode."); LOCK(cs_main); int heightParam = request.params[0].get_int(); if (heightParam < 0) throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative block height."); // Height value more than a billion is too high to be a block height, and // too low to be a block time (corresponds to timestamp from Sep 2001). if (heightParam > 1000000000) { // Add a 2 hour buffer to include blocks which might have had old timestamps CBlockIndex* pindex = chainActive.FindEarliestAtLeast(heightParam - 7200); if (!pindex) { throw JSONRPCError(RPC_INTERNAL_ERROR, "Could not find block with at least the specified timestamp."); } heightParam = pindex->nHeight; } unsigned int height = (unsigned int) heightParam; unsigned int chainHeight = (unsigned int) chainActive.Height(); if (chainHeight < Params().PruneAfterHeight()) throw JSONRPCError(RPC_INTERNAL_ERROR, "Blockchain is too short for pruning."); else if (height > chainHeight) throw JSONRPCError(RPC_INVALID_PARAMETER, "Blockchain is shorter than the attempted prune height."); else if (height > chainHeight - MIN_BLOCKS_TO_KEEP) { LogPrint("rpc", "Attempt to prune blocks close to the tip. Retaining the minimum number of blocks."); height = chainHeight - MIN_BLOCKS_TO_KEEP; } PruneBlockFilesManual(height); return uint64_t(height); } UniValue gettxoutsetinfo(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 0) throw runtime_error( "gettxoutsetinfo\n" "\nReturns statistics about the unspent transaction output set.\n" "Note this call may take some time.\n" "\nResult:\n" "{\n" " \"height\":n, (numeric) The current block height (index)\n" " \"bestblock\": \"hex\", (string) the best block hash hex\n" " \"transactions\": n, (numeric) The number of transactions\n" " \"txouts\": n, (numeric) The number of output transactions\n" " \"bytes_serialized\": n, (numeric) The serialized size\n" " \"hash_serialized\": \"hash\", (string) The serialized hash\n" " \"total_amount\": x.xxx (numeric) The total amount\n" "}\n" "\nExamples:\n" + HelpExampleCli("gettxoutsetinfo", "") + HelpExampleRpc("gettxoutsetinfo", "") ); UniValue ret(UniValue::VOBJ); CCoinsStats stats; FlushStateToDisk(); if (GetUTXOStats(pcoinsTip, stats)) { ret.push_back(Pair("height", (int64_t)stats.nHeight)); ret.push_back(Pair("bestblock", stats.hashBlock.GetHex())); ret.push_back(Pair("transactions", (int64_t)stats.nTransactions)); ret.push_back(Pair("txouts", (int64_t)stats.nTransactionOutputs)); ret.push_back(Pair("bytes_serialized", (int64_t)stats.nSerializedSize)); ret.push_back(Pair("hash_serialized", stats.hashSerialized.GetHex())); ret.push_back(Pair("total_amount", ValueFromAmount(stats.nTotalAmount))); } else { throw JSONRPCError(RPC_INTERNAL_ERROR, "Unable to read UTXO set"); } return ret; } UniValue gettxout(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() < 2 || request.params.size() > 3) throw runtime_error( "gettxout \"txid\" n ( include_mempool )\n" "\nReturns details about an unspent transaction output.\n" "\nArguments:\n" "1. \"txid\" (string, required) The transaction id\n" "2. n (numeric, required) vout number\n" "3. include_mempool (boolean, optional) Whether to include the mempool\n" "\nResult:\n" "{\n" " \"bestblock\" : \"hash\", (string) the block hash\n" " \"confirmations\" : n, (numeric) The number of confirmations\n" " \"value\" : x.xxx, (numeric) The transaction value in " + CURRENCY_UNIT + "\n" " \"scriptPubKey\" : { (json object)\n" " \"asm\" : \"code\", (string) \n" " \"hex\" : \"hex\", (string) \n" " \"reqSigs\" : n, (numeric) Number of required signatures\n" " \"type\" : \"pubkeyhash\", (string) The type, eg pubkeyhash\n" " \"addresses\" : [ (array of string) array of goldcoin addresses\n" " \"address\" (string) goldcoin address\n" " ,...\n" " ]\n" " },\n" " \"version\" : n, (numeric) The version\n" " \"coinbase\" : true|false (boolean) Coinbase or not\n" "}\n" "\nExamples:\n" "\nGet unspent transactions\n" + HelpExampleCli("listunspent", "") + "\nView the details\n" + HelpExampleCli("gettxout", "\"txid\" 1") + "\nAs a json rpc call\n" + HelpExampleRpc("gettxout", "\"txid\", 1") ); LOCK(cs_main); UniValue ret(UniValue::VOBJ); std::string strHash = request.params[0].get_str(); uint256 hash(uint256S(strHash)); int n = request.params[1].get_int(); bool fMempool = true; if (request.params.size() > 2) fMempool = request.params[2].get_bool(); CCoins coins; if (fMempool) { LOCK(mempool.cs); CCoinsViewMemPool view(pcoinsTip, mempool); if (!view.GetCoins(hash, coins)) return NullUniValue; mempool.pruneSpent(hash, coins); // TODO: this should be done by the CCoinsViewMemPool } else { if (!pcoinsTip->GetCoins(hash, coins)) return NullUniValue; } if (n<0 || (unsigned int)n>=coins.vout.size() || coins.vout[n].IsNull()) return NullUniValue; BlockMap::iterator it = mapBlockIndex.find(pcoinsTip->GetBestBlock()); CBlockIndex *pindex = it->second; ret.push_back(Pair("bestblock", pindex->GetBlockHash().GetHex())); if ((unsigned int)coins.nHeight == MEMPOOL_HEIGHT) ret.push_back(Pair("confirmations", 0)); else ret.push_back(Pair("confirmations", pindex->nHeight - coins.nHeight + 1)); ret.push_back(Pair("value", ValueFromAmount(coins.vout[n].nValue))); UniValue o(UniValue::VOBJ); ScriptPubKeyToJSON(coins.vout[n].scriptPubKey, o, true); ret.push_back(Pair("scriptPubKey", o)); ret.push_back(Pair("version", coins.nVersion)); ret.push_back(Pair("coinbase", coins.fCoinBase)); return ret; } UniValue verifychain(const JSONRPCRequest& request) { int nCheckLevel = GetArg("-checklevel", DEFAULT_CHECKLEVEL); int nCheckDepth = GetArg("-checkblocks", DEFAULT_CHECKBLOCKS); if (request.fHelp || request.params.size() > 2) throw runtime_error( "verifychain ( checklevel nblocks )\n" "\nVerifies blockchain database.\n" "\nArguments:\n" "1. checklevel (numeric, optional, 0-4, default=" + strprintf("%d", nCheckLevel) + ") How thorough the block verification is.\n" "2. nblocks (numeric, optional, default=" + strprintf("%d", nCheckDepth) + ", 0=all) The number of blocks to check.\n" "\nResult:\n" "true|false (boolean) Verified or not\n" "\nExamples:\n" + HelpExampleCli("verifychain", "") + HelpExampleRpc("verifychain", "") ); LOCK(cs_main); if (request.params.size() > 0) nCheckLevel = request.params[0].get_int(); if (request.params.size() > 1) nCheckDepth = request.params[1].get_int(); return CVerifyDB().VerifyDB(Params(), pcoinsTip, nCheckLevel, nCheckDepth); } /** Implementation of IsSuperMajority with better feedback */ static UniValue SoftForkMajorityDesc(int version, CBlockIndex* pindex, const Consensus::Params& consensusParams) { UniValue rv(UniValue::VOBJ); bool activated = false; bool hasSuperMajority = pindex->nHeight >= consensusParams.BIP65Height ? true : CBlockIndex::IsSuperMajority(4, pindex->pprev, consensusParams, consensusParams.nEnforceBlockUpgradeMajority); switch(version) { case 2: activated = pindex->nHeight >= consensusParams.BIP34Height || hasSuperMajority; break; case 3: activated = pindex->nHeight >= consensusParams.BIP66Height|| hasSuperMajority; break; case 4: activated = pindex->nHeight >= consensusParams.BIP65Height|| hasSuperMajority; break; } rv.push_back(Pair("status", activated)); return rv; } static UniValue SoftForkDesc(const std::string &name, int version, CBlockIndex* pindex, const Consensus::Params& consensusParams) { UniValue rv(UniValue::VOBJ); rv.push_back(Pair("id", name)); rv.push_back(Pair("version", version)); rv.push_back(Pair("reject", SoftForkMajorityDesc(version, pindex, consensusParams))); return rv; } static UniValue BIP9SoftForkDesc(const Consensus::Params& consensusParams, Consensus::DeploymentPos id) { UniValue rv(UniValue::VOBJ); const ThresholdState thresholdState = VersionBitsTipState(consensusParams, id); switch (thresholdState) { case THRESHOLD_DEFINED: rv.push_back(Pair("status", "defined")); break; case THRESHOLD_STARTED: rv.push_back(Pair("status", "started")); break; case THRESHOLD_LOCKED_IN: rv.push_back(Pair("status", "locked_in")); break; case THRESHOLD_ACTIVE: rv.push_back(Pair("status", "active")); break; case THRESHOLD_FAILED: rv.push_back(Pair("status", "failed")); break; } if (THRESHOLD_STARTED == thresholdState) { rv.push_back(Pair("bit", consensusParams.vDeployments[id].bit)); } rv.push_back(Pair("startTime", consensusParams.vDeployments[id].nStartTime)); rv.push_back(Pair("timeout", consensusParams.vDeployments[id].nTimeout)); rv.push_back(Pair("since", VersionBitsTipStateSinceHeight(consensusParams, id))); return rv; } void BIP9SoftForkDescPushBack(UniValue& bip9_softforks, const std::string &name, const Consensus::Params& consensusParams, Consensus::DeploymentPos id) { // Deployments with timeout value of 0 are hidden. // A timeout value of 0 guarantees a softfork will never be activated. // This is used when softfork codes are merged without specifying the deployment schedule. if (consensusParams.vDeployments[id].nTimeout > 0) bip9_softforks.push_back(Pair(name, BIP9SoftForkDesc(consensusParams, id))); } UniValue getblockchaininfo(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 0) throw runtime_error( "getblockchaininfo\n" "Returns an object containing various state info regarding blockchain processing.\n" "\nResult:\n" "{\n" " \"chain\": \"xxxx\", (string) current network name as defined in BIP70 (main, test, regtest)\n" " \"blocks\": xxxxxx, (numeric) the current number of blocks processed in the server\n" " \"headers\": xxxxxx, (numeric) the current number of headers we have validated\n" " \"bestblockhash\": \"...\", (string) the hash of the currently best block\n" " \"difficulty\": xxxxxx, (numeric) the current difficulty\n" " \"mediantime\": xxxxxx, (numeric) median time for the current best block\n" " \"verificationprogress\": xxxx, (numeric) estimate of verification progress [0..1]\n" " \"chainwork\": \"xxxx\" (string) total amount of work in active chain, in hexadecimal\n" " \"pruned\": xx, (boolean) if the blocks are subject to pruning\n" " \"pruneheight\": xxxxxx, (numeric) lowest-height complete block stored\n" " \"softforks\": [ (array) status of softforks in progress\n" " {\n" " \"id\": \"xxxx\", (string) name of softfork\n" " \"version\": xx, (numeric) block version\n" " \"reject\": { (object) progress toward rejecting pre-softfork blocks\n" " \"status\": xx, (boolean) true if threshold reached\n" " },\n" " }, ...\n" " ],\n" " \"bip9_softforks\": { (object) status of BIP9 softforks in progress\n" " \"xxxx\" : { (string) name of the softfork\n" " \"status\": \"xxxx\", (string) one of \"defined\", \"started\", \"locked_in\", \"active\", \"failed\"\n" " \"bit\": xx, (numeric) the bit (0-28) in the block version field used to signal this softfork (only for \"started\" status)\n" " \"startTime\": xx, (numeric) the minimum median time past of a block at which the bit gains its meaning\n" " \"timeout\": xx, (numeric) the median time past of a block at which the deployment is considered failed if not yet locked in\n" " \"since\": xx (numeric) height of the first block to which the status applies\n" " }\n" " }\n" "}\n" "\nExamples:\n" + HelpExampleCli("getblockchaininfo", "") + HelpExampleRpc("getblockchaininfo", "") ); LOCK(cs_main); UniValue obj(UniValue::VOBJ); obj.push_back(Pair("chain", Params().NetworkIDString())); obj.push_back(Pair("blocks", (int)chainActive.Height())); obj.push_back(Pair("headers", pindexBestHeader ? pindexBestHeader->nHeight : -1)); obj.push_back(Pair("bestblockhash", chainActive.Tip()->GetBlockHash().GetHex())); obj.push_back(Pair("difficulty", (double)GetDifficulty())); obj.push_back(Pair("mediantime", (int64_t)chainActive.Tip()->GetMedianTimePast())); obj.push_back(Pair("verificationprogress", GuessVerificationProgress(Params().TxData(), chainActive.Tip()))); obj.push_back(Pair("chainwork", chainActive.Tip()->nChainWork.GetHex())); obj.push_back(Pair("pruned", fPruneMode)); const Consensus::Params& consensusParams = Params().GetConsensus(); CBlockIndex* tip = chainActive.Tip(); UniValue softforks(UniValue::VARR); UniValue bip9_softforks(UniValue::VOBJ); softforks.push_back(SoftForkDesc("bip34", 2, tip, consensusParams)); softforks.push_back(SoftForkDesc("bip66", 3, tip, consensusParams)); softforks.push_back(SoftForkDesc("bip65", 4, tip, consensusParams)); BIP9SoftForkDescPushBack(bip9_softforks, "csv", consensusParams, Consensus::DEPLOYMENT_CSV); obj.push_back(Pair("softforks", softforks)); obj.push_back(Pair("bip9_softforks", bip9_softforks)); if (fPruneMode) { CBlockIndex *block = chainActive.Tip(); while (block && block->pprev && (block->pprev->nStatus & BLOCK_HAVE_DATA)) block = block->pprev; obj.push_back(Pair("pruneheight", block->nHeight)); } return obj; } /** Comparison function for sorting the getchaintips heads. */ struct CompareBlocksByHeight { bool operator()(const CBlockIndex* a, const CBlockIndex* b) const { /* Make sure that unequal blocks with the same height do not compare equal. Use the pointers themselves to make a distinction. */ if (a->nHeight != b->nHeight) return (a->nHeight > b->nHeight); return a < b; } }; UniValue getchaintips(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 0) throw runtime_error( "getchaintips\n" "Return information about all known tips in the block tree," " including the main chain as well as orphaned branches.\n" "\nResult:\n" "[\n" " {\n" " \"height\": xxxx, (numeric) height of the chain tip\n" " \"hash\": \"xxxx\", (string) block hash of the tip\n" " \"branchlen\": 0 (numeric) zero for main chain\n" " \"status\": \"active\" (string) \"active\" for the main chain\n" " },\n" " {\n" " \"height\": xxxx,\n" " \"hash\": \"xxxx\",\n" " \"branchlen\": 1 (numeric) length of branch connecting the tip to the main chain\n" " \"status\": \"xxxx\" (string) status of the chain (active, valid-fork, valid-headers, headers-only, invalid)\n" " }\n" "]\n" "Possible values for status:\n" "1. \"invalid\" This branch contains at least one invalid block\n" "2. \"headers-only\" Not all blocks for this branch are available, but the headers are valid\n" "3. \"valid-headers\" All blocks are available for this branch, but they were never fully validated\n" "4. \"valid-fork\" This branch is not part of the active chain, but is fully validated\n" "5. \"active\" This is the tip of the active main chain, which is certainly valid\n" "\nExamples:\n" + HelpExampleCli("getchaintips", "") + HelpExampleRpc("getchaintips", "") ); LOCK(cs_main); /* * Idea: the set of chain tips is chainActive.tip, plus orphan blocks which do not have another orphan building off of them. * Algorithm: * - Make one pass through mapBlockIndex, picking out the orphan blocks, and also storing a set of the orphan block's pprev pointers. * - Iterate through the orphan blocks. If the block isn't pointed to by another orphan, it is a chain tip. * - add chainActive.Tip() */ std::set<const CBlockIndex*, CompareBlocksByHeight> setTips; std::set<const CBlockIndex*> setOrphans; std::set<const CBlockIndex*> setPrevs; BOOST_FOREACH(const PAIRTYPE(const uint256, CBlockIndex*)& item, mapBlockIndex) { if (!chainActive.Contains(item.second)) { setOrphans.insert(item.second); setPrevs.insert(item.second->pprev); } } for (std::set<const CBlockIndex*>::iterator it = setOrphans.begin(); it != setOrphans.end(); ++it) { if (setPrevs.erase(*it) == 0) { setTips.insert(*it); } } // Always report the currently active tip. setTips.insert(chainActive.Tip()); /* Construct the output array. */ UniValue res(UniValue::VARR); BOOST_FOREACH(const CBlockIndex* block, setTips) { UniValue obj(UniValue::VOBJ); obj.push_back(Pair("height", block->nHeight)); obj.push_back(Pair("hash", block->phashBlock->GetHex())); const int branchLen = block->nHeight - chainActive.FindFork(block)->nHeight; obj.push_back(Pair("branchlen", branchLen)); string status; if (chainActive.Contains(block)) { // This block is part of the currently active chain. status = "active"; } else if (block->nStatus & BLOCK_FAILED_MASK) { // This block or one of its ancestors is invalid. status = "invalid"; } else if (block->nChainTx == 0) { // This block cannot be connected because full block data for it or one of its parents is missing. status = "headers-only"; } else if (block->IsValid(BLOCK_VALID_SCRIPTS)) { // This block is fully validated, but no longer part of the active chain. It was probably the active block once, but was reorganized. status = "valid-fork"; } else if (block->IsValid(BLOCK_VALID_TREE)) { // The headers for this block are valid, but it has not been validated. It was probably never part of the most-work chain. status = "valid-headers"; } else { // No clue. status = "unknown"; } obj.push_back(Pair("status", status)); res.push_back(obj); } return res; } UniValue mempoolInfoToJSON() { UniValue ret(UniValue::VOBJ); ret.push_back(Pair("size", (int64_t) mempool.size())); ret.push_back(Pair("bytes", (int64_t) mempool.GetTotalTxSize())); ret.push_back(Pair("usage", (int64_t) mempool.DynamicMemoryUsage())); size_t maxmempool = GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000; ret.push_back(Pair("maxmempool", (int64_t) maxmempool)); ret.push_back(Pair("mempoolminfee", ValueFromAmount(mempool.GetMinFee(maxmempool).GetFeePerK()))); return ret; } UniValue getmempoolinfo(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 0) throw runtime_error( "getmempoolinfo\n" "\nReturns details on the active state of the TX memory pool.\n" "\nResult:\n" "{\n" " \"size\": xxxxx, (numeric) Current tx count\n" " \"bytes\": xxxxx, (numeric) Sum of all serialized transaction sizes\n" " \"usage\": xxxxx, (numeric) Total memory usage for the mempool\n" " \"maxmempool\": xxxxx, (numeric) Maximum memory usage for the mempool\n" " \"mempoolminfee\": xxxxx (numeric) Minimum fee for tx to be accepted\n" "}\n" "\nExamples:\n" + HelpExampleCli("getmempoolinfo", "") + HelpExampleRpc("getmempoolinfo", "") ); return mempoolInfoToJSON(); } UniValue preciousblock(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 1) throw runtime_error( "preciousblock \"blockhash\"\n" "\nTreats a block as if it were received before others with the same work.\n" "\nA later preciousblock call can override the effect of an earlier one.\n" "\nThe effects of preciousblock are not retained across restarts.\n" "\nArguments:\n" "1. \"blockhash\" (string, required) the hash of the block to mark as precious\n" "\nResult:\n" "\nExamples:\n" + HelpExampleCli("preciousblock", "\"blockhash\"") + HelpExampleRpc("preciousblock", "\"blockhash\"") ); std::string strHash = request.params[0].get_str(); uint256 hash(uint256S(strHash)); CBlockIndex* pblockindex; { LOCK(cs_main); if (mapBlockIndex.count(hash) == 0) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found"); pblockindex = mapBlockIndex[hash]; } CValidationState state; PreciousBlock(state, Params(), pblockindex); if (!state.IsValid()) { throw JSONRPCError(RPC_DATABASE_ERROR, state.GetRejectReason()); } return NullUniValue; } UniValue invalidateblock(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 1) throw runtime_error( "invalidateblock \"blockhash\"\n" "\nPermanently marks a block as invalid, as if it violated a consensus rule.\n" "\nArguments:\n" "1. \"blockhash\" (string, required) the hash of the block to mark as invalid\n" "\nResult:\n" "\nExamples:\n" + HelpExampleCli("invalidateblock", "\"blockhash\"") + HelpExampleRpc("invalidateblock", "\"blockhash\"") ); std::string strHash = request.params[0].get_str(); uint256 hash(uint256S(strHash)); CValidationState state; { LOCK(cs_main); if (mapBlockIndex.count(hash) == 0) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found"); CBlockIndex* pblockindex = mapBlockIndex[hash]; InvalidateBlock(state, Params(), pblockindex); } if (state.IsValid()) { ActivateBestChain(state, Params()); } if (!state.IsValid()) { throw JSONRPCError(RPC_DATABASE_ERROR, state.GetRejectReason()); } return NullUniValue; } UniValue reconsiderblock(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 1) throw runtime_error( "reconsiderblock \"blockhash\"\n" "\nRemoves invalidity status of a block and its descendants, reconsider them for activation.\n" "This can be used to undo the effects of invalidateblock.\n" "\nArguments:\n" "1. \"blockhash\" (string, required) the hash of the block to reconsider\n" "\nResult:\n" "\nExamples:\n" + HelpExampleCli("reconsiderblock", "\"blockhash\"") + HelpExampleRpc("reconsiderblock", "\"blockhash\"") ); std::string strHash = request.params[0].get_str(); uint256 hash(uint256S(strHash)); { LOCK(cs_main); if (mapBlockIndex.count(hash) == 0) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found"); CBlockIndex* pblockindex = mapBlockIndex[hash]; ResetBlockFailureFlags(pblockindex); } CValidationState state; ActivateBestChain(state, Params()); if (!state.IsValid()) { throw JSONRPCError(RPC_DATABASE_ERROR, state.GetRejectReason()); } return NullUniValue; } static const CRPCCommand commands[] = { // category name actor (function) okSafe argNames // --------------------- ------------------------ ----------------------- ------ ---------- { "blockchain", "getblockchaininfo", &getblockchaininfo, true, {} }, { "blockchain", "getbestblockhash", &getbestblockhash, true, {} }, { "blockchain", "getblockcount", &getblockcount, true, {} }, { "blockchain", "getblock", &getblock, true, {"blockhash","verbose"} }, { "blockchain", "getblockhash", &getblockhash, true, {"height"} }, { "blockchain", "getblockheader", &getblockheader, true, {"blockhash","verbose"} }, { "blockchain", "getcheckpoint", &getcheckpoint, true, {} }, { "blockchain", "sendcheckpoint", &sendcheckpoint, true, {"blockhash"} }, { "blockchain", "getchaintips", &getchaintips, true, {} }, { "blockchain", "getdifficulty", &getdifficulty, true, {} }, { "blockchain", "getmempoolancestors", &getmempoolancestors, true, {"txid","verbose"} }, { "blockchain", "getmempooldescendants", &getmempooldescendants, true, {"txid","verbose"} }, { "blockchain", "getmempoolentry", &getmempoolentry, true, {"txid"} }, { "blockchain", "getmempoolinfo", &getmempoolinfo, true, {} }, { "blockchain", "getrawmempool", &getrawmempool, true, {"verbose"} }, { "blockchain", "gettxout", &gettxout, true, {"txid","n","include_mempool"} }, { "blockchain", "gettxoutsetinfo", &gettxoutsetinfo, true, {} }, { "blockchain", "pruneblockchain", &pruneblockchain, true, {"height"} }, { "blockchain", "verifychain", &verifychain, true, {"checklevel","nblocks"} }, { "blockchain", "preciousblock", &preciousblock, true, {"blockhash"} }, /* Not shown in help */ { "hidden", "invalidateblock", &invalidateblock, true, {"blockhash"} }, { "hidden", "reconsiderblock", &reconsiderblock, true, {"blockhash"} }, { "hidden", "waitfornewblock", &waitfornewblock, true, {"timeout"} }, { "hidden", "waitforblock", &waitforblock, true, {"blockhash","timeout"} }, { "hidden", "waitforblockheight", &waitforblockheight, true, {"height","timeout"} }, }; void RegisterBlockchainRPCCommands(CRPCTable &t) { for (unsigned int vcidx = 0; vcidx < ARRAYLEN(commands); vcidx++) t.appendCommand(commands[vcidx].name, &commands[vcidx]); }
goldcoin/Goldcoin-GLD
src/rpc/blockchain.cpp
C++
mit
65,642
package silent // silent import - e.g. only referenced in Go code, not in json imports // frizz type Silent interface { Silent() }
kego/ke
tests/packer/silent/silent.go
GO
mit
134
module.exports = Transport; var C = { // Transport status codes STATUS_READY: 0, STATUS_DISCONNECTED: 1, STATUS_ERROR: 2 }; /** * Expose C object. */ Transport.C = C; /** * Dependencies. */ var debug = require('debug')('JsSIP:Transport'); var debugerror = require('debug')('JsSIP:ERROR:Transport'); debugerror.log = console.warn.bind(console); var JsSIP_C = require('./Constants'); var Parser = require('./Parser'); var UA = require('./UA'); var SIPMessage = require('./SIPMessage'); var sanityCheck = require('./sanityCheck'); // 'websocket' module uses the native WebSocket interface when bundled to run in a browser. var W3CWebSocket = require('websocket').w3cwebsocket; function Transport(ua, server) { this.ua = ua; this.ws = null; this.server = server; this.reconnection_attempts = 0; this.closed = false; this.connected = false; this.reconnectTimer = null; this.lastTransportError = {}; /** * Options for the Node "websocket" library. */ this.node_websocket_options = this.ua.configuration.node_websocket_options || {}; // Add our User-Agent header. this.node_websocket_options.headers = this.node_websocket_options.headers || {}; this.node_websocket_options.headers['User-Agent'] = JsSIP_C.USER_AGENT; } Transport.prototype = { /** * Connect socket. */ connect: function() { var transport = this; if(this.ws && (this.ws.readyState === this.ws.OPEN || this.ws.readyState === this.ws.CONNECTING)) { debug('WebSocket ' + this.server.ws_uri + ' is already connected'); return false; } if(this.ws) { this.ws.close(); } debug('connecting to WebSocket ' + this.server.ws_uri); this.ua.onTransportConnecting(this, (this.reconnection_attempts === 0)?1:this.reconnection_attempts); try { // Hack in case W3CWebSocket is not the class exported by Node-WebSocket // (may just happen if the above `var W3CWebSocket` line is overriden by // `var W3CWebSocket = global.W3CWebSocket`). if (W3CWebSocket.length > 3) { this.ws = new W3CWebSocket(this.server.ws_uri, 'sip', this.node_websocket_options.origin, this.node_websocket_options.headers, this.node_websocket_options.requestOptions, this.node_websocket_options.clientConfig); } else { this.ws = new W3CWebSocket(this.server.ws_uri, 'sip'); } this.ws.binaryType = 'arraybuffer'; this.ws.onopen = function() { transport.onOpen(); }; this.ws.onclose = function(e) { transport.onClose(e); }; this.ws.onmessage = function(e) { transport.onMessage(e); }; this.ws.onerror = function(e) { transport.onError(e); }; } catch(e) { debugerror('error connecting to WebSocket ' + this.server.ws_uri + ': ' + e); this.lastTransportError.code = null; this.lastTransportError.reason = e.message; this.ua.onTransportError(this); } }, /** * Disconnect socket. */ disconnect: function() { if(this.ws) { // Clear reconnectTimer clearTimeout(this.reconnectTimer); // TODO: should make this.reconnectTimer = null here? this.closed = true; debug('closing WebSocket ' + this.server.ws_uri); this.ws.close(); } // TODO: Why this?? if (this.reconnectTimer !== null) { clearTimeout(this.reconnectTimer); this.reconnectTimer = null; this.ua.onTransportDisconnected({ transport: this, code: this.lastTransportError.code, reason: this.lastTransportError.reason }); } }, /** * Send a message. */ send: function(msg) { var message = msg.toString(); if(this.ws && this.ws.readyState === this.ws.OPEN) { debug('sending WebSocket message:\n%s\n', message); this.ws.send(message); return true; } else { debugerror('unable to send message, WebSocket is not open'); return false; } }, // Transport Event Handlers onOpen: function() { this.connected = true; debug('WebSocket ' + this.server.ws_uri + ' connected'); // Clear reconnectTimer since we are not disconnected if (this.reconnectTimer !== null) { clearTimeout(this.reconnectTimer); this.reconnectTimer = null; } // Reset reconnection_attempts this.reconnection_attempts = 0; // Disable closed this.closed = false; // Trigger onTransportConnected callback this.ua.onTransportConnected(this); }, onClose: function(e) { var connected_before = this.connected; this.connected = false; this.lastTransportError.code = e.code; this.lastTransportError.reason = e.reason; debug('WebSocket disconnected (code: ' + e.code + (e.reason? '| reason: ' + e.reason : '') +')'); if(e.wasClean === false) { debugerror('WebSocket abrupt disconnection'); } // Transport was connected if (connected_before === true) { this.ua.onTransportClosed(this); // Check whether the user requested to close. if(!this.closed) { this.reConnect(); } } else { // This is the first connection attempt // May be a network error (or may be UA.stop() was called) this.ua.onTransportError(this); } }, onMessage: function(e) { var message, transaction, data = e.data; // CRLF Keep Alive response from server. Ignore it. if(data === '\r\n') { debug('received WebSocket message with CRLF Keep Alive response'); return; } // WebSocket binary message. else if (typeof data !== 'string') { try { data = String.fromCharCode.apply(null, new Uint8Array(data)); } catch(evt) { debugerror('received WebSocket binary message failed to be converted into string, message discarded'); return; } debug('received WebSocket binary message:\n%s\n', data); } // WebSocket text message. else { debug('received WebSocket text message:\n%s\n', data); } message = Parser.parseMessage(data, this.ua); if (! message) { return; } if(this.ua.status === UA.C.STATUS_USER_CLOSED && message instanceof SIPMessage.IncomingRequest) { return; } // Do some sanity check if(! sanityCheck(message, this.ua, this)) { return; } if(message instanceof SIPMessage.IncomingRequest) { message.transport = this; this.ua.receiveRequest(message); } else if(message instanceof SIPMessage.IncomingResponse) { /* Unike stated in 18.1.2, if a response does not match * any transaction, it is discarded here and no passed to the core * in order to be discarded there. */ switch(message.method) { case JsSIP_C.INVITE: transaction = this.ua.transactions.ict[message.via_branch]; if(transaction) { transaction.receiveResponse(message); } break; case JsSIP_C.ACK: // Just in case ;-) break; default: transaction = this.ua.transactions.nict[message.via_branch]; if(transaction) { transaction.receiveResponse(message); } break; } } }, onError: function(e) { debugerror('WebSocket connection error: %o', e); }, /** * Reconnection attempt logic. */ reConnect: function() { var transport = this; this.reconnection_attempts += 1; if(this.reconnection_attempts > this.ua.configuration.ws_server_max_reconnection) { debugerror('maximum reconnection attempts for WebSocket ' + this.server.ws_uri); this.ua.onTransportError(this); } else { debug('trying to reconnect to WebSocket ' + this.server.ws_uri + ' (reconnection attempt ' + this.reconnection_attempts + ')'); this.reconnectTimer = setTimeout(function() { transport.connect(); transport.reconnectTimer = null; }, this.ua.configuration.ws_server_reconnection_timeout * 1000); } } };
rusekr/JsSIP
lib/Transport.js
JavaScript
mit
8,034
import { async, fakeAsync, tick, ComponentFixture, TestBed } from '@angular/core/testing'; import { TagsRelatedToTagsComponent } from './tags-related-to-tags.component'; import { Component, EventEmitter, Input, Output } from '@angular/core'; import { By } from '@angular/platform-browser'; import * as _ from 'lodash'; import { Tag } from '../../shared/types'; import { ModelService } from '../../model.service'; @Component({ selector: 'app-select-tags', template: '' }) class SelectTagsStubComponent { // tslint:disable-next-line:no-output-on-prefix @Output() onSelected = new EventEmitter<Tag[]>(); } @Component({ selector: 'app-tag-list', template: '' }) class TagListStubComponent { @Input() tags: Tag[] = []; } class ModelStubService { async findTagsByTags(tagsIn: Tag[]): Promise<Tag[]> { const allTags: Tag[] = [ { tagname: 'tag0' }, { tagname: 'tag1' }, { tagname: 'tag2' }, { tagname: 'tag3' }, { tagname: 'tag4' }, { tagname: 'tag5' }, { tagname: 'tag6' } ]; const tagnamesIn = _.map(tagsIn, (tag: Tag) => tag.tagname); const tagsOut: Tag[] = _.filter(allTags, (tag: Tag) => { return tagnamesIn.indexOf(tag.tagname) === -1; }); return tagsOut; } } describe('TagsRelatedToTagsComponent', () => { let component: TagsRelatedToTagsComponent; let fixture: ComponentFixture<TagsRelatedToTagsComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ TagsRelatedToTagsComponent, SelectTagsStubComponent, TagListStubComponent ], providers: [ { provide: ModelService, useClass: ModelStubService } ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(TagsRelatedToTagsComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should be created', () => { expect(component).toBeTruthy(); }); it('should contain tag selecting component', () => { const tagSelector = fixture.debugElement.query(By.css('app-select-tags')); expect(tagSelector).toBeTruthy(); }); it('should contain tag list component', () => { const tagList = fixture.debugElement.query(By.css('app-tag-list')); expect(tagList).toBeTruthy(); }); it('when tags are selected, related tags should be found and provided to app-tag-list', fakeAsync(() => { const selectTagsComponent = fixture.debugElement.query(By.css('app-select-tags')).componentInstance; const emitter = selectTagsComponent.onSelected; emitter.emit([ { tagname: 'tag0' }, { tagname: 'tag1' }, { tagname: 'tag2' }, { tagname: 'tag3' } ]); const tagListComponent = fixture.debugElement.query(By.css('app-tag-list')).componentInstance; fixture.detectChanges(); tick(); fixture.detectChanges(); expect(tagListComponent.tags.length).toEqual(3); })); });
ditup/ditapp-ng
src/app/tags/tags-related-to-tags/tags-related-to-tags.component.spec.ts
TypeScript
mit
2,949
using System.Collections.Generic; using System.Linq; using Xunit; using static LanguageExt.Prelude; namespace LanguageExt.Tests.Transformer.Traverse.IEnumerableT.Collections { public class QueIEnumerable { [Fact] public void EmptyEmptyIsEmptyEmpty() { Que<IEnumerable<int>> ma = Empty; var mb = ma.Traverse(identity); var mc = Enumerable.Empty<Que<int>>(); Assert.True(mb.ToSeq() == mc.ToSeq()); } [Fact] public void QueIEnumerableCrossProduct() { var ma = Queue<IEnumerable<int>>(Seq(1, 2), Seq(10, 20, 30)); var mb = ma.Traverse(identity); var mc = new[] { Queue(1, 10), Queue(1, 20), Queue(1, 30), Queue(2, 10), Queue(2, 20), Queue(2, 30) } .AsEnumerable(); Assert.True(mb.ToSeq() == mc.ToSeq()); } [Fact] public void QueOfEmptiesAndNonEmptiesIsEmpty() { var ma = Queue<IEnumerable<int>>(Seq<int>(), Seq<int>(1, 2, 3)); var mb = ma.Traverse(identity); var mc = Enumerable.Empty<Que<int>>(); Assert.True(mb.ToSeq() == mc.ToSeq()); } [Fact] public void QueOfEmptiesIsEmpty() { var ma = Queue<IEnumerable<int>>(Seq<int>(), Seq<int>()); var mb = ma.Traverse(identity); var mc = Enumerable.Empty<Que<int>>(); Assert.True(mb.ToSeq() == mc.ToSeq()); } } }
StanJav/language-ext
LanguageExt.Tests/Transformer/Traverse/IEnumerable/Collections/Que.cs
C#
mit
1,668
require File.expand_path('../helper', __FILE__) begin require 'radius' class RadiusTest < Minitest::Test def radius_app(&block) mock_app do set :views, File.dirname(__FILE__) + '/views' get('/', &block) end get '/' end it 'renders inline radius strings' do radius_app { radius '<h1>Hiya</h1>' } assert ok? assert_equal "<h1>Hiya</h1>", body end it 'renders .radius files in views path' do radius_app { radius :hello } assert ok? assert_equal "<h1>Hello From Radius</h1>\n", body end it "renders with inline layouts" do mock_app do layout { "<h1>THIS. IS. <r:yield /></h1>" } get('/') { radius '<EM>SPARTA</EM>' } end get '/' assert ok? assert_equal "<h1>THIS. IS. <EM>SPARTA</EM></h1>", body end it "renders with file layouts" do radius_app { radius 'Hello World', :layout => :layout2 } assert ok? assert_equal "<h1>Radius Layout!</h1>\n<p>Hello World</p>\n", body end it "raises error if template not found" do mock_app { get('/') { radius :no_such_template } } assert_raises(Errno::ENOENT) { get('/') } end it "allows passing locals" do radius_app { radius '<r:value />', :locals => { :value => 'foo' } } assert ok? assert_equal 'foo', body end end rescue LoadError warn "#{$!}: skipping radius tests" end
JonMidhir/sinatra
test/radius_test.rb
Ruby
mit
1,369
# Be sure to restart your server when you modify this file. Rails.application.config.session_store :cookie_store, key: '_demo_project_mysql_session'
yevheniyc/Autodidact
1o_RonR_ET_Lynda/test/demo_project_mysql/config/initializers/session_store.rb
Ruby
mit
150
'use strict'; require('../../../lib/common/init'); var assert = require('assert'), request = require('supertest'), danf = require('../../../lib/server/app')(require('../../fixture/http/danf'), null, {environment: 'test', verbosity: 0, cluster: null}) ; danf.buildServer(function(app) { describe('SessionHandler', function() { it('should allow to get and set values in session', function(done) { request(app) .get('/session/0') .expect(204) .end(function(err, res) { if (err) { if (res) { console.log(res.text); } else { console.log(err); } throw err; } done(); }) ; }) it('should allow to regenerate the session', function(done) { request(app) .get('/session/1') .expect(204) .end(function(err, res) { if (err) { if (res) { console.log(res.text); } else { console.log(err); } throw err; } done(); }) ; }) it('should allow to destroy a session', function(done) { request(app) .get('/session/2') .expect(500) .end(function(err, res) { if (err) { if (res) { /^The session does not exist or has been destroyed\./.test(res.text); } else { /^The session does not exist or has been destroyed\./.test(err); } throw err; } done(); }) ; }) it('should allow to save and reload a session', function(done) { request(app) .get('/session/3') .expect(204) .end(function(err, res) { if (err) { if (res) { console.log(res.text); } else { console.log(err); } throw err; } done(); }) ; }) }) });
Gnucki/danf
test/unit/http/session-handler.js
JavaScript
mit
2,669
require 'uri' module Biller::WHMCSAutoAuth def self.redirect_url(email, action) ensure_autoauth_params time = Time.now.to_i query= ["email=#{email}","timestamp=#{time}", "hash="+ autoauth_hash(email, time), "goto="+ URI.encode("clientarea.php?action=#{action}")].join('&') return [SiteSetting.whmcs_autoauth_url, query].join("?") end private def self.ensure_autoauth_params raise Nilavu::NotFound unless SiteSetting.whmcs_autoauth_url && SiteSetting.whmcs_autoauth_key end def self.autoauth_hash(email, time) Digest::SHA1([email, time,SiteSetting.whmcs_autoauth_key].join('')) end end
jaeko44/nilavu
lib/biller/whmcs_auto_auth.rb
Ruby
mit
701
require 'test_helper' describe Factree::Aggregate do describe ".alternatives" do let(:facts) { :facts } let(:nil_decision) { -> (_) { nil } } let(:final_decision) { -> (_) { conclusion } } let(:conclusion) { Factree::Conclusion.new(:b) } let(:decisions) { [] } subject { Factree::Aggregate.alternatives(facts, *decisions) } describe "with a nil decision followed by a final decision" do let(:decisions) { [nil_decision, final_decision] } it "decides on conclusion" do assert_equal subject, conclusion end end describe "with a final decision followed by a nil decision" do let(:decisions) { [final_decision, nil_decision] } it "decides on conclusion" do assert_equal subject, conclusion end end describe "with only a nil decision" do let(:decisions) { [nil_decision] } it "decides on nil" do assert_nil subject end end it "returns a nil decision" do assert_nil subject end describe "with a mock decision" do let(:mock_decision) { Minitest::Mock.new } let(:decisions) { [mock_decision] } it "passes facts through to decision procs" do mock_decision.expect(:call, nil, [facts]) subject mock_decision.verify end end end end
ConsultingMD/factree
test/factree/aggregate_test.rb
Ruby
mit
1,330
<?php use yii\helpers\Html; /* @var $this yii\web\View */ /* @var $model core\models\Station */ $this->title = 'Create Station'; $this->params['breadcrumbs'][] = ['label' => 'Stations', 'url' => ['index']]; $this->params['breadcrumbs'][] = $this->title; ?> <div class="station-create"> <h1><?= Html::encode($this->title) ?></h1> <?= $this->render('_form', [ 'model' => $model, ]) ?> </div>
tony-wuhongtao/OurYincart2
star-core/modules/station/views/default/create.php
PHP
mit
417
/** * @author Richard Davey <rich@photonstorm.com> * @copyright 2019 Photon Storm Ltd. * @license {@link https://opensource.org/licenses/MIT|MIT License} */ var CONST = require('../../const'); var Smoothing = require('./Smoothing'); // The pool into which the canvas elements are placed. var pool = []; // Automatically apply smoothing(false) to created Canvas elements var _disableContextSmoothing = false; /** * The CanvasPool is a global static object, that allows Phaser to recycle and pool 2D Context Canvas DOM elements. * It does not pool WebGL Contexts, because once the context options are set they cannot be modified again, * which is useless for some of the Phaser pipelines / renderer. * * This singleton is instantiated as soon as Phaser loads, before a Phaser.Game instance has even been created. * Which means all instances of Phaser Games on the same page can share the one single pool. * * @namespace Phaser.Display.Canvas.CanvasPool * @since 3.0.0 */ var CanvasPool = function () { /** * Creates a new Canvas DOM element, or pulls one from the pool if free. * * @function Phaser.Display.Canvas.CanvasPool.create * @since 3.0.0 * * @param {*} parent - The parent of the Canvas object. * @param {integer} [width=1] - The width of the Canvas. * @param {integer} [height=1] - The height of the Canvas. * @param {integer} [canvasType=Phaser.CANVAS] - The type of the Canvas. Either `Phaser.CANVAS` or `Phaser.WEBGL`. * @param {boolean} [selfParent=false] - Use the generated Canvas element as the parent? * * @return {HTMLCanvasElement} The canvas element that was created or pulled from the pool */ var create = function (parent, width, height, canvasType, selfParent) { if (width === undefined) { width = 1; } if (height === undefined) { height = 1; } if (canvasType === undefined) { canvasType = CONST.CANVAS; } if (selfParent === undefined) { selfParent = false; } var canvas; var container = first(canvasType); if (container === null) { container = { parent: parent, canvas: document.createElement('canvas'), type: canvasType }; if (canvasType === CONST.CANVAS) { pool.push(container); } canvas = container.canvas; } else { container.parent = parent; canvas = container.canvas; } if (selfParent) { container.parent = canvas; } canvas.width = width; canvas.height = height; if (_disableContextSmoothing && canvasType === CONST.CANVAS) { Smoothing.disable(canvas.getContext('2d')); } return canvas; }; /** * Creates a new Canvas DOM element, or pulls one from the pool if free. * * @function Phaser.Display.Canvas.CanvasPool.create2D * @since 3.0.0 * * @param {*} parent - The parent of the Canvas object. * @param {integer} [width=1] - The width of the Canvas. * @param {integer} [height=1] - The height of the Canvas. * * @return {HTMLCanvasElement} The created canvas. */ var create2D = function (parent, width, height) { return create(parent, width, height, CONST.CANVAS); }; /** * Creates a new Canvas DOM element, or pulls one from the pool if free. * * @function Phaser.Display.Canvas.CanvasPool.createWebGL * @since 3.0.0 * * @param {*} parent - The parent of the Canvas object. * @param {integer} [width=1] - The width of the Canvas. * @param {integer} [height=1] - The height of the Canvas. * * @return {HTMLCanvasElement} The created WebGL canvas. */ var createWebGL = function (parent, width, height) { return create(parent, width, height, CONST.WEBGL); }; /** * Gets the first free canvas index from the pool. * * @function Phaser.Display.Canvas.CanvasPool.first * @since 3.0.0 * * @param {integer} [canvasType=Phaser.CANVAS] - The type of the Canvas. Either `Phaser.CANVAS` or `Phaser.WEBGL`. * * @return {HTMLCanvasElement} The first free canvas, or `null` if a WebGL canvas was requested or if the pool doesn't have free canvases. */ var first = function (canvasType) { if (canvasType === undefined) { canvasType = CONST.CANVAS; } if (canvasType === CONST.WEBGL) { return null; } for (var i = 0; i < pool.length; i++) { var container = pool[i]; if (!container.parent && container.type === canvasType) { return container; } } return null; }; /** * Looks up a canvas based on its parent, and if found puts it back in the pool, freeing it up for re-use. * The canvas has its width and height set to 1, and its parent attribute nulled. * * @function Phaser.Display.Canvas.CanvasPool.remove * @since 3.0.0 * * @param {*} parent - The canvas or the parent of the canvas to free. */ var remove = function (parent) { // Check to see if the parent is a canvas object var isCanvas = parent instanceof HTMLCanvasElement; pool.forEach(function (container) { if ((isCanvas && container.canvas === parent) || (!isCanvas && container.parent === parent)) { container.parent = null; container.canvas.width = 1; container.canvas.height = 1; } }); }; /** * Gets the total number of used canvas elements in the pool. * * @function Phaser.Display.Canvas.CanvasPool.total * @since 3.0.0 * * @return {integer} The number of used canvases. */ var total = function () { var c = 0; pool.forEach(function (container) { if (container.parent) { c++; } }); return c; }; /** * Gets the total number of free canvas elements in the pool. * * @function Phaser.Display.Canvas.CanvasPool.free * @since 3.0.0 * * @return {integer} The number of free canvases. */ var free = function () { return pool.length - total(); }; /** * Disable context smoothing on any new Canvas element created. * * @function Phaser.Display.Canvas.CanvasPool.disableSmoothing * @since 3.0.0 */ var disableSmoothing = function () { _disableContextSmoothing = true; }; /** * Enable context smoothing on any new Canvas element created. * * @function Phaser.Display.Canvas.CanvasPool.enableSmoothing * @since 3.0.0 */ var enableSmoothing = function () { _disableContextSmoothing = false; }; return { create2D: create2D, create: create, createWebGL: createWebGL, disableSmoothing: disableSmoothing, enableSmoothing: enableSmoothing, first: first, free: free, pool: pool, remove: remove, total: total }; }; // If we export the called function here, it'll only be invoked once (not every time it's required). module.exports = CanvasPool();
mahill/phaser
src/display/canvas/CanvasPool.js
JavaScript
mit
7,526