repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
xijunlee/leetcode
94.py
695
#!/usr/bin/env python # coding=utf-8 # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): ret = [] def inorderTraversal(self, root): """ :type root: TreeNode :rtype: List[int] """ self.dfs(root) return self.ret def dfs(self, node): if not node: return self.dfs(node.left) self.ret.append(node.val) self.dfs(node.right) return if __name__ == '__main__': s = Solution() print s.inorderTraversal([1,null,2,3])
mit
memorycoin/memorycoin
src/qt/locale/bitcoin_cs.ts
118217
<?xml version="1.0" ?><!DOCTYPE TS><TS language="cs" version="2.0"> <defaultcodec>UTF-8</defaultcodec> <context> <name>AboutDialog</name> <message> <location filename="../forms/aboutdialog.ui" line="+14"/> <source>About Bitcoin</source> <translation>O Bitcoinu</translation> </message> <message> <location line="+39"/> <source>&lt;b&gt;Bitcoin&lt;/b&gt; version</source> <translation>&lt;b&gt;Bitcoin&lt;/b&gt; verze</translation> </message> <message> <location line="+57"/> <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> Tohle je experimentální program. Šířen pod licencí MIT/X11, viz přiložený soubor COPYING nebo http://www.opensource.org/licenses/mit-license.php. Tento produkt zahrnuje programy vyvinuté OpenSSL Projektem pro použití v OpenSSL Toolkitu (http://www.openssl.org/) a kryptografický program od Erika Younga (eay@cryptsoft.com) a program UPnP od Thomase Bernarda.</translation> </message> <message> <location filename="../aboutdialog.cpp" line="+14"/> <source>Copyright</source> <translation>Copyright</translation> </message> <message> <location line="+0"/> <source>The Bitcoin developers</source> <translation>Vývojáři Bitcoinu</translation> </message> </context> <context> <name>AddressBookPage</name> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>Address Book</source> <translation>Adresář</translation> </message> <message> <location line="+19"/> <source>Double-click to edit address or label</source> <translation>Dvojklikem myši začneš upravovat označení adresy</translation> </message> <message> <location line="+27"/> <source>Create a new address</source> <translation>Vytvoř novou adresu</translation> </message> <message> <location line="+14"/> <source>Copy the currently selected address to the system clipboard</source> <translation>Zkopíruj aktuálně vybranou adresu do systémové schránky</translation> </message> <message> <location line="-11"/> <source>&amp;New Address</source> <translation>Nová &amp;adresa</translation> </message> <message> <location filename="../addressbookpage.cpp" line="+63"/> <source>These are your Bitcoin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source> <translation>Tohle jsou tvé Bitcoinové adresy pro příjem plateb. Můžeš dát pokaždé každému plátci novou adresu, abys věděl, kdo ti kdy kolik platil.</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>&amp;Copy Address</source> <translation>&amp;Kopíruj adresu</translation> </message> <message> <location line="+11"/> <source>Show &amp;QR Code</source> <translation>Zobraz &amp;QR kód</translation> </message> <message> <location line="+11"/> <source>Sign a message to prove you own a Bitcoin address</source> <translation>Podepiš zprávu, čímž prokážeš, že jsi vlastníkem Bitcoinové adresy</translation> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation>Po&amp;depiš zprávu</translation> </message> <message> <location line="+25"/> <source>Delete the currently selected address from the list</source> <translation>Smaž zvolenou adresu ze seznamu</translation> </message> <message> <location line="+27"/> <source>Export the data in the current tab to a file</source> <translation>Exportuj data z tohoto panelu do souboru</translation> </message> <message> <location line="+3"/> <source>&amp;Export</source> <translation>&amp;Export</translation> </message> <message> <location line="-44"/> <source>Verify a message to ensure it was signed with a specified Bitcoin address</source> <translation>Ověř zprávu, aby ses ujistil, že byla podepsána danou Bitcoinovou adresou</translation> </message> <message> <location line="+3"/> <source>&amp;Verify Message</source> <translation>&amp;Ověř zprávu</translation> </message> <message> <location line="+14"/> <source>&amp;Delete</source> <translation>S&amp;maž</translation> </message> <message> <location filename="../addressbookpage.cpp" line="-5"/> <source>These are your Bitcoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source> <translation>Tohle jsou tvé Bitcoinové adresy pro posílání plateb. Před odesláním mincí si vždy zkontroluj částku a cílovou adresu.</translation> </message> <message> <location line="+13"/> <source>Copy &amp;Label</source> <translation>Kopíruj &amp;označení</translation> </message> <message> <location line="+1"/> <source>&amp;Edit</source> <translation>&amp;Uprav</translation> </message> <message> <location line="+1"/> <source>Send &amp;Coins</source> <translation>Pošli min&amp;ce</translation> </message> <message> <location line="+260"/> <source>Export Address Book Data</source> <translation>Exportuj data adresáře</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>CSV formát (*.csv)</translation> </message> <message> <location line="+13"/> <source>Error exporting</source> <translation>Chyba při exportu</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>Nemohu zapisovat do souboru %1.</translation> </message> </context> <context> <name>AddressTableModel</name> <message> <location filename="../addresstablemodel.cpp" line="+144"/> <source>Label</source> <translation>Označení</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Adresa</translation> </message> <message> <location line="+36"/> <source>(no label)</source> <translation>(bez označení)</translation> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <location filename="../forms/askpassphrasedialog.ui" line="+26"/> <source>Passphrase Dialog</source> <translation>Změna hesla</translation> </message> <message> <location line="+21"/> <source>Enter passphrase</source> <translation>Zadej platné heslo</translation> </message> <message> <location line="+14"/> <source>New passphrase</source> <translation>Zadej nové heslo</translation> </message> <message> <location line="+14"/> <source>Repeat new passphrase</source> <translation>Totéž heslo ještě jednou</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="+33"/> <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>Zadej nové heslo k peněžence.&lt;br/&gt;Použij &lt;b&gt;alespoň 10 náhodných znaků&lt;/b&gt; nebo &lt;b&gt;alespoň osm slov&lt;/b&gt;.</translation> </message> <message> <location line="+1"/> <source>Encrypt wallet</source> <translation>Zašifruj peněženku</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation>K provedení této operace musíš zadat heslo k peněžence, aby se mohla odemknout.</translation> </message> <message> <location line="+5"/> <source>Unlock wallet</source> <translation>Odemkni peněženku</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation>K provedení této operace musíš zadat heslo k peněžence, aby se mohla dešifrovat.</translation> </message> <message> <location line="+5"/> <source>Decrypt wallet</source> <translation>Dešifruj peněženku</translation> </message> <message> <location line="+3"/> <source>Change passphrase</source> <translation>Změň heslo</translation> </message> <message> <location line="+1"/> <source>Enter the old and new passphrase to the wallet.</source> <translation>Zadej staré a nové heslo k peněžence.</translation> </message> <message> <location line="+46"/> <source>Confirm wallet encryption</source> <translation>Potvrď zašifrování peněženky</translation> </message> <message> <location line="+1"/> <source>Warning: If you encrypt your wallet and lose your passphrase, you will &lt;b&gt;LOSE ALL OF YOUR BITCOINS&lt;/b&gt;!</source> <translation>Varování: Pokud si zašifruješ peněženku a ztratíš či zapomeneš heslo, &lt;b&gt;PŘIJDEŠ O VŠECHNY BITCOINY&lt;/b&gt;!</translation> </message> <message> <location line="+0"/> <source>Are you sure you wish to encrypt your wallet?</source> <translation>Jsi si jistý, že chceš peněženku zašifrovat?</translation> </message> <message> <location line="+15"/> <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>DŮLEŽITÉ: Všechny předchozí zálohy peněženky by měly být nahrazeny nově vygenerovanou, zašifrovanou peněženkou. Z bezpečnostních důvodů budou předchozí zálohy nešifrované peněženky nepoužitelné, jakmile začneš používat novou zašifrovanou peněženku.</translation> </message> <message> <location line="+100"/> <location line="+24"/> <source>Warning: The Caps Lock key is on!</source> <translation>Upozornění: Caps Lock je zapnutý!</translation> </message> <message> <location line="-130"/> <location line="+58"/> <source>Wallet encrypted</source> <translation>Peněženka je zašifrována</translation> </message> <message> <location line="-56"/> <source>Bitcoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your bitcoins from being stolen by malware infecting your computer.</source> <translation>Bitcoin se teď ukončí, aby dokončil zašifrování. Pamatuj však, že pouhé zašifrování peněženky úplně nezabraňuje krádeži tvých bitcoinů malwarem, kterým se může počítač nakazit.</translation> </message> <message> <location line="+13"/> <location line="+7"/> <location line="+42"/> <location line="+6"/> <source>Wallet encryption failed</source> <translation>Zašifrování peněženky selhalo</translation> </message> <message> <location line="-54"/> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation>Zašifrování peněženky selhalo kvůli vnitřní chybě. Tvá peněženka tedy nebyla zašifrována.</translation> </message> <message> <location line="+7"/> <location line="+48"/> <source>The supplied passphrases do not match.</source> <translation>Zadaná hesla nejsou shodná.</translation> </message> <message> <location line="-37"/> <source>Wallet unlock failed</source> <translation>Odemčení peněženky selhalo</translation> </message> <message> <location line="+1"/> <location line="+11"/> <location line="+19"/> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation>Nezadal jsi správné heslo pro dešifrování peněženky.</translation> </message> <message> <location line="-20"/> <source>Wallet decryption failed</source> <translation>Dešifrování peněženky selhalo</translation> </message> <message> <location line="+14"/> <source>Wallet passphrase was successfully changed.</source> <translation>Heslo k peněžence bylo v pořádku změněno.</translation> </message> </context> <context> <name>BitcoinGUI</name> <message> <location filename="../bitcoingui.cpp" line="+233"/> <source>Sign &amp;message...</source> <translation>Po&amp;depiš zprávu...</translation> </message> <message> <location line="+280"/> <source>Synchronizing with network...</source> <translation>Synchronizuji se se sítí...</translation> </message> <message> <location line="-349"/> <source>&amp;Overview</source> <translation>&amp;Přehled</translation> </message> <message> <location line="+1"/> <source>Show general overview of wallet</source> <translation>Zobraz celkový přehled peněženky</translation> </message> <message> <location line="+20"/> <source>&amp;Transactions</source> <translation>&amp;Transakce</translation> </message> <message> <location line="+1"/> <source>Browse transaction history</source> <translation>Procházej historii transakcí</translation> </message> <message> <location line="+7"/> <source>Edit the list of stored addresses and labels</source> <translation>Uprav seznam uložených adres a jejich označení</translation> </message> <message> <location line="-14"/> <source>Show the list of addresses for receiving payments</source> <translation>Zobraz seznam adres pro příjem plateb</translation> </message> <message> <location line="+31"/> <source>E&amp;xit</source> <translation>&amp;Konec</translation> </message> <message> <location line="+1"/> <source>Quit application</source> <translation>Ukonči aplikaci</translation> </message> <message> <location line="+4"/> <source>Show information about Bitcoin</source> <translation>Zobraz informace o Bitcoinu</translation> </message> <message> <location line="+2"/> <source>About &amp;Qt</source> <translation>O &amp;Qt</translation> </message> <message> <location line="+1"/> <source>Show information about Qt</source> <translation>Zobraz informace o Qt</translation> </message> <message> <location line="+2"/> <source>&amp;Options...</source> <translation>&amp;Možnosti...</translation> </message> <message> <location line="+6"/> <source>&amp;Encrypt Wallet...</source> <translation>Zaši&amp;fruj peněženku...</translation> </message> <message> <location line="+3"/> <source>&amp;Backup Wallet...</source> <translation>&amp;Zazálohuj peněženku...</translation> </message> <message> <location line="+2"/> <source>&amp;Change Passphrase...</source> <translation>Změň &amp;heslo...</translation> </message> <message> <location line="+285"/> <source>Importing blocks from disk...</source> <translation>Importuji bloky z disku...</translation> </message> <message> <location line="+3"/> <source>Reindexing blocks on disk...</source> <translation>Vytvářím nový index bloků na disku...</translation> </message> <message> <location line="-347"/> <source>Send coins to a Bitcoin address</source> <translation>Pošli mince na Bitcoinovou adresu</translation> </message> <message> <location line="+49"/> <source>Modify configuration options for Bitcoin</source> <translation>Uprav nastavení Bitcoinu</translation> </message> <message> <location line="+9"/> <source>Backup wallet to another location</source> <translation>Zazálohuj peněženku na jiné místo</translation> </message> <message> <location line="+2"/> <source>Change the passphrase used for wallet encryption</source> <translation>Změň heslo k šifrování peněženky</translation> </message> <message> <location line="+6"/> <source>&amp;Debug window</source> <translation>&amp;Ladicí okno</translation> </message> <message> <location line="+1"/> <source>Open debugging and diagnostic console</source> <translation>Otevři ladicí a diagnostickou konzoli</translation> </message> <message> <location line="-4"/> <source>&amp;Verify message...</source> <translation>&amp;Ověř zprávu...</translation> </message> <message> <location line="-165"/> <location line="+530"/> <source>Bitcoin</source> <translation>Bitcoin</translation> </message> <message> <location line="-530"/> <source>Wallet</source> <translation>Peněženka</translation> </message> <message> <location line="+101"/> <source>&amp;Send</source> <translation>&amp;Pošli</translation> </message> <message> <location line="+7"/> <source>&amp;Receive</source> <translation>Při&amp;jmi</translation> </message> <message> <location line="+14"/> <source>&amp;Addresses</source> <translation>&amp;Adresy</translation> </message> <message> <location line="+22"/> <source>&amp;About Bitcoin</source> <translation>O &amp;Bitcoinu</translation> </message> <message> <location line="+9"/> <source>&amp;Show / Hide</source> <translation>&amp;Zobraz/Skryj</translation> </message> <message> <location line="+1"/> <source>Show or hide the main Window</source> <translation>Zobraz nebo skryj hlavní okno</translation> </message> <message> <location line="+3"/> <source>Encrypt the private keys that belong to your wallet</source> <translation>Zašifruj soukromé klíče ve své peněžence</translation> </message> <message> <location line="+7"/> <source>Sign messages with your Bitcoin addresses to prove you own them</source> <translation>Podepiš zprávy svými Bitcoinovými adresami, čímž prokážeš, že jsi jejich vlastníkem</translation> </message> <message> <location line="+2"/> <source>Verify messages to ensure they were signed with specified Bitcoin addresses</source> <translation>Ověř zprávy, aby ses ujistil, že byly podepsány danými Bitcoinovými adresami</translation> </message> <message> <location line="+28"/> <source>&amp;File</source> <translation>&amp;Soubor</translation> </message> <message> <location line="+7"/> <source>&amp;Settings</source> <translation>&amp;Nastavení</translation> </message> <message> <location line="+6"/> <source>&amp;Help</source> <translation>Ná&amp;pověda</translation> </message> <message> <location line="+9"/> <source>Tabs toolbar</source> <translation>Panel s listy</translation> </message> <message> <location line="+17"/> <location line="+10"/> <source>[testnet]</source> <translation>[testnet]</translation> </message> <message> <location line="+47"/> <source>Bitcoin client</source> <translation>Bitcoin klient</translation> </message> <message numerus="yes"> <location line="+141"/> <source>%n active connection(s) to Bitcoin network</source> <translation><numerusform>%n aktivní spojení do Bitcoinové sítě</numerusform><numerusform>%n aktivní spojení do Bitcoinové sítě</numerusform><numerusform>%n aktivních spojení do Bitcoinové sítě</numerusform></translation> </message> <message> <location line="+22"/> <source>No block source available...</source> <translation>Není dostupný žádný zdroj bloků...</translation> </message> <message> <location line="+12"/> <source>Processed %1 of %2 (estimated) blocks of transaction history.</source> <translation>Zpracováno %1 z přibližně %2 bloků transakční historie.</translation> </message> <message> <location line="+4"/> <source>Processed %1 blocks of transaction history.</source> <translation>Zpracováno %1 bloků transakční historie.</translation> </message> <message numerus="yes"> <location line="+20"/> <source>%n hour(s)</source> <translation><numerusform>hodinu</numerusform><numerusform>%n hodiny</numerusform><numerusform>%n hodin</numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n day(s)</source> <translation><numerusform>den</numerusform><numerusform>%n dny</numerusform><numerusform>%n dnů</numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n week(s)</source> <translation><numerusform>týden</numerusform><numerusform>%n týdny</numerusform><numerusform>%n týdnů</numerusform></translation> </message> <message> <location line="+4"/> <source>%1 behind</source> <translation>Stahuji ještě bloky transakcí za poslední %1</translation> </message> <message> <location line="+14"/> <source>Last received block was generated %1 ago.</source> <translation>Poslední stažený blok byl vygenerován %1 zpátky.</translation> </message> <message> <location line="+2"/> <source>Transactions after this will not yet be visible.</source> <translation>Následné transakce ještě nebudou vidět.</translation> </message> <message> <location line="+22"/> <source>Error</source> <translation>Chyba</translation> </message> <message> <location line="+3"/> <source>Warning</source> <translation>Upozornění</translation> </message> <message> <location line="+3"/> <source>Information</source> <translation>Informace</translation> </message> <message> <location line="+70"/> <source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source> <translation>Tahle transakce přesahuje velikostní limit. I tak ji ale můžeš poslat, pokud za ni zaplatíš poplatek %1, který půjde uzlům, které tvou transakci zpracují, a navíc tak podpoříš síť. Chceš zaplatit poplatek?</translation> </message> <message> <location line="-140"/> <source>Up to date</source> <translation>Aktuální</translation> </message> <message> <location line="+31"/> <source>Catching up...</source> <translation>Stahuji...</translation> </message> <message> <location line="+113"/> <source>Confirm transaction fee</source> <translation>Potvrď transakční poplatek</translation> </message> <message> <location line="+8"/> <source>Sent transaction</source> <translation>Odeslané transakce</translation> </message> <message> <location line="+0"/> <source>Incoming transaction</source> <translation>Příchozí transakce</translation> </message> <message> <location line="+1"/> <source>Date: %1 Amount: %2 Type: %3 Address: %4 </source> <translation>Datum: %1 Částka: %2 Typ: %3 Adresa: %4 </translation> </message> <message> <location line="+33"/> <location line="+23"/> <source>URI handling</source> <translation>Zpracování URI</translation> </message> <message> <location line="-23"/> <location line="+23"/> <source>URI can not be parsed! This can be caused by an invalid Bitcoin address or malformed URI parameters.</source> <translation>Nepodařilo se analyzovat URI! Důvodem může být neplatná Bitcoinová adresa nebo poškozené parametry URI.</translation> </message> <message> <location line="+17"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation>Peněženka je &lt;b&gt;zašifrovaná&lt;/b&gt; a momentálně &lt;b&gt;odemčená&lt;/b&gt;</translation> </message> <message> <location line="+8"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation>Peněženka je &lt;b&gt;zašifrovaná&lt;/b&gt; a momentálně &lt;b&gt;zamčená&lt;/b&gt;</translation> </message> <message> <location filename="../bitcoin.cpp" line="+111"/> <source>A fatal error occurred. Bitcoin can no longer continue safely and will quit.</source> <translation>Stala se fatální chyba. Bitcoin nemůže bezpečně pokračovat v činnosti, a proto skončí.</translation> </message> </context> <context> <name>ClientModel</name> <message> <location filename="../clientmodel.cpp" line="+104"/> <source>Network Alert</source> <translation>Upozornění sítě</translation> </message> </context> <context> <name>EditAddressDialog</name> <message> <location filename="../forms/editaddressdialog.ui" line="+14"/> <source>Edit Address</source> <translation>Uprav adresu</translation> </message> <message> <location line="+11"/> <source>&amp;Label</source> <translation>&amp;Označení</translation> </message> <message> <location line="+10"/> <source>The label associated with this address book entry</source> <translation>Označení spojené s tímto záznamem v adresáři</translation> </message> <message> <location line="+7"/> <source>&amp;Address</source> <translation>&amp;Adresa</translation> </message> <message> <location line="+10"/> <source>The address associated with this address book entry. This can only be modified for sending addresses.</source> <translation>Adresa spojená s tímto záznamem v adresáři. Lze upravovat jen pro odesílací adresy.</translation> </message> <message> <location filename="../editaddressdialog.cpp" line="+21"/> <source>New receiving address</source> <translation>Nová přijímací adresa</translation> </message> <message> <location line="+4"/> <source>New sending address</source> <translation>Nová odesílací adresa</translation> </message> <message> <location line="+3"/> <source>Edit receiving address</source> <translation>Uprav přijímací adresu</translation> </message> <message> <location line="+4"/> <source>Edit sending address</source> <translation>Uprav odesílací adresu</translation> </message> <message> <location line="+76"/> <source>The entered address &quot;%1&quot; is already in the address book.</source> <translation>Zadaná adresa &quot;%1&quot; už v adresáři je.</translation> </message> <message> <location line="-5"/> <source>The entered address &quot;%1&quot; is not a valid Bitcoin address.</source> <translation>Zadaná adresa &quot;%1&quot; není platná Bitcoinová adresa.</translation> </message> <message> <location line="+10"/> <source>Could not unlock wallet.</source> <translation>Nemohu odemknout peněženku.</translation> </message> <message> <location line="+5"/> <source>New key generation failed.</source> <translation>Nepodařilo se mi vygenerovat nový klíč.</translation> </message> </context> <context> <name>GUIUtil::HelpMessageBox</name> <message> <location filename="../guiutil.cpp" line="+424"/> <location line="+12"/> <source>Bitcoin-Qt</source> <translation>Bitcoin-Qt</translation> </message> <message> <location line="-12"/> <source>version</source> <translation>verze</translation> </message> <message> <location line="+2"/> <source>Usage:</source> <translation>Užití:</translation> </message> <message> <location line="+1"/> <source>command-line options</source> <translation>možnosti příkazové řádky</translation> </message> <message> <location line="+4"/> <source>UI options</source> <translation>Možnosti UI</translation> </message> <message> <location line="+1"/> <source>Set language, for example &quot;de_DE&quot; (default: system locale)</source> <translation>Nastavit jazyk, například &quot;de_DE&quot; (výchozí: systémové nastavení)</translation> </message> <message> <location line="+1"/> <source>Start minimized</source> <translation>Nastartovat minimalizovaně</translation> </message> <message> <location line="+1"/> <source>Show splash screen on startup (default: 1)</source> <translation>Zobrazit startovací obrazovku (výchozí: 1)</translation> </message> </context> <context> <name>OptionsDialog</name> <message> <location filename="../forms/optionsdialog.ui" line="+14"/> <source>Options</source> <translation>Možnosti</translation> </message> <message> <location line="+16"/> <source>&amp;Main</source> <translation>&amp;Hlavní</translation> </message> <message> <location line="+6"/> <source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB.</source> <translation>Dobrovolný transakční poplatek za každý započatý kB dopomáhá k rychlému zpracování tvých transakcí. Většina transakcí má do 1 kB.</translation> </message> <message> <location line="+15"/> <source>Pay transaction &amp;fee</source> <translation>Platit &amp;transakční poplatek</translation> </message> <message> <location line="+31"/> <source>Automatically start Bitcoin after logging in to the system.</source> <translation>Automaticky spustí Bitcoin po přihlášení do systému.</translation> </message> <message> <location line="+3"/> <source>&amp;Start Bitcoin on system login</source> <translation>S&amp;pustit Bitcoin po přihlášení do systému</translation> </message> <message> <location line="+35"/> <source>Reset all client options to default.</source> <translation>Vrátí všechny volby na výchozí hodnoty.</translation> </message> <message> <location line="+3"/> <source>&amp;Reset Options</source> <translation>&amp;Obnovit nastavení</translation> </message> <message> <location line="+13"/> <source>&amp;Network</source> <translation>&amp;Síť</translation> </message> <message> <location line="+6"/> <source>Automatically open the Bitcoin client port on the router. This only works when your router supports UPnP and it is enabled.</source> <translation>Automaticky otevře potřebný port na routeru. Tohle funguje jen za předpokladu, že tvůj router podporuje UPnP a že je UPnP povolené.</translation> </message> <message> <location line="+3"/> <source>Map port using &amp;UPnP</source> <translation>Namapovat port přes &amp;UPnP</translation> </message> <message> <location line="+7"/> <source>Connect to the Bitcoin network through a SOCKS proxy (e.g. when connecting through Tor).</source> <translation>Připojí se do Bitcoinové sítě přes SOCKS proxy (např. když se připojuje přes Tor).</translation> </message> <message> <location line="+3"/> <source>&amp;Connect through SOCKS proxy:</source> <translation>&amp;Připojit přes SOCKS proxy:</translation> </message> <message> <location line="+9"/> <source>Proxy &amp;IP:</source> <translation>&amp;IP adresa proxy:</translation> </message> <message> <location line="+19"/> <source>IP address of the proxy (e.g. 127.0.0.1)</source> <translation>IP adresa proxy (např. 127.0.0.1)</translation> </message> <message> <location line="+7"/> <source>&amp;Port:</source> <translation>Por&amp;t:</translation> </message> <message> <location line="+19"/> <source>Port of the proxy (e.g. 9050)</source> <translation>Port proxy (např. 9050)</translation> </message> <message> <location line="+7"/> <source>SOCKS &amp;Version:</source> <translation>&amp;Verze SOCKS:</translation> </message> <message> <location line="+13"/> <source>SOCKS version of the proxy (e.g. 5)</source> <translation>Verze SOCKS proxy (např. 5)</translation> </message> <message> <location line="+36"/> <source>&amp;Window</source> <translation>O&amp;kno</translation> </message> <message> <location line="+6"/> <source>Show only a tray icon after minimizing the window.</source> <translation>Po minimalizaci okna zobrazí pouze ikonu v panelu.</translation> </message> <message> <location line="+3"/> <source>&amp;Minimize to the tray instead of the taskbar</source> <translation>&amp;Minimalizovávat do ikony v panelu</translation> </message> <message> <location line="+7"/> <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>Zavřením se aplikace minimalizuje. Pokud je tato volba zaškrtnuta, tak se aplikace ukončí pouze zvolením Konec v menu.</translation> </message> <message> <location line="+3"/> <source>M&amp;inimize on close</source> <translation>Za&amp;vřením minimalizovat</translation> </message> <message> <location line="+21"/> <source>&amp;Display</source> <translation>Zobr&amp;azení</translation> </message> <message> <location line="+8"/> <source>User Interface &amp;language:</source> <translation>&amp;Jazyk uživatelského rozhraní:</translation> </message> <message> <location line="+13"/> <source>The user interface language can be set here. This setting will take effect after restarting Bitcoin.</source> <translation>Tady lze nastavit jazyk uživatelského rozhraní. Nastavení se projeví až po restartování Bitcoinu.</translation> </message> <message> <location line="+11"/> <source>&amp;Unit to show amounts in:</source> <translation>J&amp;ednotka pro částky: </translation> </message> <message> <location line="+13"/> <source>Choose the default subdivision unit to show in the interface and when sending coins.</source> <translation>Zvol výchozí podjednotku, která se bude zobrazovat v programu a při posílání mincí.</translation> </message> <message> <location line="+9"/> <source>Whether to show Bitcoin addresses in the transaction list or not.</source> <translation>Zda ukazovat bitcoinové adresy ve výpisu transakcí nebo ne.</translation> </message> <message> <location line="+3"/> <source>&amp;Display addresses in transaction list</source> <translation>Ukazo&amp;vat adresy ve výpisu transakcí</translation> </message> <message> <location line="+71"/> <source>&amp;OK</source> <translation>&amp;Budiž</translation> </message> <message> <location line="+7"/> <source>&amp;Cancel</source> <translation>&amp;Zrušit</translation> </message> <message> <location line="+10"/> <source>&amp;Apply</source> <translation>&amp;Uložit</translation> </message> <message> <location filename="../optionsdialog.cpp" line="+53"/> <source>default</source> <translation>výchozí</translation> </message> <message> <location line="+130"/> <source>Confirm options reset</source> <translation>Potvrzení obnovení nastavení</translation> </message> <message> <location line="+1"/> <source>Some settings may require a client restart to take effect.</source> <translation>Některá nastavení mohou vyžadovat restart klienta, aby se mohly projevit.</translation> </message> <message> <location line="+0"/> <source>Do you want to proceed?</source> <translation>Chceš pokračovat?</translation> </message> <message> <location line="+42"/> <location line="+9"/> <source>Warning</source> <translation>Upozornění</translation> </message> <message> <location line="-9"/> <location line="+9"/> <source>This setting will take effect after restarting Bitcoin.</source> <translation>Nastavení se projeví až po restartování Bitcoinu.</translation> </message> <message> <location line="+29"/> <source>The supplied proxy address is invalid.</source> <translation>Zadaná adresa proxy je neplatná.</translation> </message> </context> <context> <name>OverviewPage</name> <message> <location filename="../forms/overviewpage.ui" line="+14"/> <source>Form</source> <translation>Formulář</translation> </message> <message> <location line="+50"/> <location line="+166"/> <source>The displayed information may be out of date. Your wallet automatically synchronizes with the Bitcoin network after a connection is established, but this process has not completed yet.</source> <translation>Zobrazené informace nemusí být aktuální. Tvá peněženka se automaticky sesynchronizuje s Bitcoinovou sítí, jakmile se s ní spojí. Zatím ale ještě není synchronizace dokončena.</translation> </message> <message> <location line="-124"/> <source>Balance:</source> <translation>Stav účtu:</translation> </message> <message> <location line="+29"/> <source>Unconfirmed:</source> <translation>Nepotvrzeno:</translation> </message> <message> <location line="-78"/> <source>Wallet</source> <translation>Peněženka</translation> </message> <message> <location line="+107"/> <source>Immature:</source> <translation>Nedozráno:</translation> </message> <message> <location line="+13"/> <source>Mined balance that has not yet matured</source> <translation>Vytěžené mince, které ještě nejsou zralé</translation> </message> <message> <location line="+46"/> <source>&lt;b&gt;Recent transactions&lt;/b&gt;</source> <translation>&lt;b&gt;Poslední transakce&lt;/b&gt;</translation> </message> <message> <location line="-101"/> <source>Your current balance</source> <translation>Aktuální stav tvého účtu</translation> </message> <message> <location line="+29"/> <source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source> <translation>Celkem z transakcí, které ještě nejsou potvrzené a které se ještě nezapočítávají do celkového stavu účtu</translation> </message> <message> <location filename="../overviewpage.cpp" line="+116"/> <location line="+1"/> <source>out of sync</source> <translation>nesynchronizováno</translation> </message> </context> <context> <name>PaymentServer</name> <message> <location filename="../paymentserver.cpp" line="+107"/> <source>Cannot start bitcoin: click-to-pay handler</source> <translation>Nemůžu spustit bitcoin: obsluha click-to-pay</translation> </message> </context> <context> <name>QRCodeDialog</name> <message> <location filename="../forms/qrcodedialog.ui" line="+14"/> <source>QR Code Dialog</source> <translation>QR kód</translation> </message> <message> <location line="+59"/> <source>Request Payment</source> <translation>Požadovat platbu</translation> </message> <message> <location line="+56"/> <source>Amount:</source> <translation>Částka:</translation> </message> <message> <location line="-44"/> <source>Label:</source> <translation>Označení:</translation> </message> <message> <location line="+19"/> <source>Message:</source> <translation>Zpráva:</translation> </message> <message> <location line="+71"/> <source>&amp;Save As...</source> <translation>&amp;Ulož jako...</translation> </message> <message> <location filename="../qrcodedialog.cpp" line="+62"/> <source>Error encoding URI into QR Code.</source> <translation>Chyba při kódování URI do QR kódu.</translation> </message> <message> <location line="+40"/> <source>The entered amount is invalid, please check.</source> <translation>Zadaná částka je neplatná, překontroluj ji prosím.</translation> </message> <message> <location line="+23"/> <source>Resulting URI too long, try to reduce the text for label / message.</source> <translation>Výsledná URI je příliš dlouhá, zkus zkrátit text označení / zprávy.</translation> </message> <message> <location line="+25"/> <source>Save QR Code</source> <translation>Ulož QR kód</translation> </message> <message> <location line="+0"/> <source>PNG Images (*.png)</source> <translation>PNG obrázky (*.png)</translation> </message> </context> <context> <name>RPCConsole</name> <message> <location filename="../forms/rpcconsole.ui" line="+46"/> <source>Client name</source> <translation>Název klienta</translation> </message> <message> <location line="+10"/> <location line="+23"/> <location line="+26"/> <location line="+23"/> <location line="+23"/> <location line="+36"/> <location line="+53"/> <location line="+23"/> <location line="+23"/> <location filename="../rpcconsole.cpp" line="+339"/> <source>N/A</source> <translation>N/A</translation> </message> <message> <location line="-217"/> <source>Client version</source> <translation>Verze klienta</translation> </message> <message> <location line="-45"/> <source>&amp;Information</source> <translation>&amp;Informace</translation> </message> <message> <location line="+68"/> <source>Using OpenSSL version</source> <translation>Používaná verze OpenSSL</translation> </message> <message> <location line="+49"/> <source>Startup time</source> <translation>Čas spuštění</translation> </message> <message> <location line="+29"/> <source>Network</source> <translation>Síť</translation> </message> <message> <location line="+7"/> <source>Number of connections</source> <translation>Počet spojení</translation> </message> <message> <location line="+23"/> <source>On testnet</source> <translation>V testnetu</translation> </message> <message> <location line="+23"/> <source>Block chain</source> <translation>Řetězec bloků</translation> </message> <message> <location line="+7"/> <source>Current number of blocks</source> <translation>Aktuální počet bloků</translation> </message> <message> <location line="+23"/> <source>Estimated total blocks</source> <translation>Odhad celkového počtu bloků</translation> </message> <message> <location line="+23"/> <source>Last block time</source> <translation>Čas posledního bloku</translation> </message> <message> <location line="+52"/> <source>&amp;Open</source> <translation>&amp;Otevřít</translation> </message> <message> <location line="+16"/> <source>Command-line options</source> <translation>Argumenty z příkazové řádky</translation> </message> <message> <location line="+7"/> <source>Show the Bitcoin-Qt help message to get a list with possible Bitcoin command-line options.</source> <translation>Seznam parametrů Bitcoinu pro příkazovou řádku získáš v nápovědě Bitcoinu Qt.</translation> </message> <message> <location line="+3"/> <source>&amp;Show</source> <translation>&amp;Zobrazit</translation> </message> <message> <location line="+24"/> <source>&amp;Console</source> <translation>&amp;Konzole</translation> </message> <message> <location line="-260"/> <source>Build date</source> <translation>Datum kompilace</translation> </message> <message> <location line="-104"/> <source>Bitcoin - Debug window</source> <translation>Bitcoin - ladicí okno</translation> </message> <message> <location line="+25"/> <source>Bitcoin Core</source> <translation>Jádro Bitcoinu</translation> </message> <message> <location line="+279"/> <source>Debug log file</source> <translation>Soubor s ladicími záznamy</translation> </message> <message> <location line="+7"/> <source>Open the Bitcoin debug log file from the current data directory. This can take a few seconds for large log files.</source> <translation>Otevři soubor s ladicími záznamy Bitcoinu z aktuálního datového adresáře. U velkých logů to může pár vteřin zabrat.</translation> </message> <message> <location line="+102"/> <source>Clear console</source> <translation>Vyčistit konzoli</translation> </message> <message> <location filename="../rpcconsole.cpp" line="-30"/> <source>Welcome to the Bitcoin RPC console.</source> <translation>Vítej v Bitcoinové RPC konzoli.</translation> </message> <message> <location line="+1"/> <source>Use up and down arrows to navigate history, and &lt;b&gt;Ctrl-L&lt;/b&gt; to clear screen.</source> <translation>V historii se pohybuješ šipkami nahoru a dolů a pomocí &lt;b&gt;Ctrl-L&lt;/b&gt; čistíš obrazovku.</translation> </message> <message> <location line="+1"/> <source>Type &lt;b&gt;help&lt;/b&gt; for an overview of available commands.</source> <translation>Napsáním &lt;b&gt;help&lt;/b&gt; si vypíšeš přehled dostupných příkazů.</translation> </message> </context> <context> <name>SendCoinsDialog</name> <message> <location filename="../forms/sendcoinsdialog.ui" line="+14"/> <location filename="../sendcoinsdialog.cpp" line="+124"/> <location line="+5"/> <location line="+5"/> <location line="+5"/> <location line="+6"/> <location line="+5"/> <location line="+5"/> <source>Send Coins</source> <translation>Pošli mince</translation> </message> <message> <location line="+50"/> <source>Send to multiple recipients at once</source> <translation>Pošli více příjemcům naráz</translation> </message> <message> <location line="+3"/> <source>Add &amp;Recipient</source> <translation>Při&amp;dej příjemce</translation> </message> <message> <location line="+20"/> <source>Remove all transaction fields</source> <translation>Smaž všechny transakční formuláře</translation> </message> <message> <location line="+3"/> <source>Clear &amp;All</source> <translation>Všechno s&amp;maž</translation> </message> <message> <location line="+22"/> <source>Balance:</source> <translation>Stav účtu:</translation> </message> <message> <location line="+10"/> <source>123.456 BTC</source> <translation>123.456 BTC</translation> </message> <message> <location line="+31"/> <source>Confirm the send action</source> <translation>Potvrď odeslání</translation> </message> <message> <location line="+3"/> <source>S&amp;end</source> <translation>P&amp;ošli</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="-59"/> <source>&lt;b&gt;%1&lt;/b&gt; to %2 (%3)</source> <translation>&lt;b&gt;%1&lt;/b&gt; pro %2 (%3)</translation> </message> <message> <location line="+5"/> <source>Confirm send coins</source> <translation>Potvrď odeslání mincí</translation> </message> <message> <location line="+1"/> <source>Are you sure you want to send %1?</source> <translation>Jsi si jistý, že chceš poslat %1?</translation> </message> <message> <location line="+0"/> <source> and </source> <translation> a </translation> </message> <message> <location line="+23"/> <source>The recipient address is not valid, please recheck.</source> <translation>Adresa příjemce je neplatná, překontroluj ji prosím.</translation> </message> <message> <location line="+5"/> <source>The amount to pay must be larger than 0.</source> <translation>Odesílaná částka musí být větší než 0.</translation> </message> <message> <location line="+5"/> <source>The amount exceeds your balance.</source> <translation>Částka překračuje stav účtu.</translation> </message> <message> <location line="+5"/> <source>The total exceeds your balance when the %1 transaction fee is included.</source> <translation>Celková částka při připočítání poplatku %1 překročí stav účtu.</translation> </message> <message> <location line="+6"/> <source>Duplicate address found, can only send to each address once per send operation.</source> <translation>Zaznamenána duplikovaná adresa; každá adresa může být v odesílané platbě pouze jednou.</translation> </message> <message> <location line="+5"/> <source>Error: Transaction creation failed!</source> <translation>Chyba: Vytvoření transakce selhalo!</translation> </message> <message> <location line="+5"/> <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>Chyba: Transakce byla odmítnuta. Tohle může nastat, pokud nějaké mince z tvé peněženky už jednou byly utraceny, například pokud používáš kopii souboru wallet.dat a mince byly utraceny v druhé kopii, ale nebyly označeny jako utracené v této.</translation> </message> </context> <context> <name>SendCoinsEntry</name> <message> <location filename="../forms/sendcoinsentry.ui" line="+14"/> <source>Form</source> <translation>Formulář</translation> </message> <message> <location line="+15"/> <source>A&amp;mount:</source> <translation>Čás&amp;tka:</translation> </message> <message> <location line="+13"/> <source>Pay &amp;To:</source> <translation>&amp;Komu:</translation> </message> <message> <location line="+34"/> <source>The address to send the payment to (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation>Adresa příjemce (např. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation> </message> <message> <location line="+60"/> <location filename="../sendcoinsentry.cpp" line="+26"/> <source>Enter a label for this address to add it to your address book</source> <translation>Zadej označení této adresy; obojí se ti pak uloží do adresáře</translation> </message> <message> <location line="-78"/> <source>&amp;Label:</source> <translation>O&amp;značení:</translation> </message> <message> <location line="+28"/> <source>Choose address from address book</source> <translation>Vyber adresu z adresáře</translation> </message> <message> <location line="+10"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location line="+7"/> <source>Paste address from clipboard</source> <translation>Vlož adresu ze schránky</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location line="+7"/> <source>Remove this recipient</source> <translation>Smaž tohoto příjemce</translation> </message> <message> <location filename="../sendcoinsentry.cpp" line="+1"/> <source>Enter a Bitcoin address (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation>Zadej Bitcoinovou adresu (např. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation> </message> </context> <context> <name>SignVerifyMessageDialog</name> <message> <location filename="../forms/signverifymessagedialog.ui" line="+14"/> <source>Signatures - Sign / Verify a Message</source> <translation>Podpisy - podepsat/ověřit zprávu</translation> </message> <message> <location line="+13"/> <source>&amp;Sign Message</source> <translation>&amp;Podepiš zprávu</translation> </message> <message> <location line="+6"/> <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>Podepsáním zprávy svými adresami můžeš prokázat, že je skutečně vlastníš. Buď opatrný a nepodepisuj nic vágního; například při phishingových útocích můžeš být lákán, abys něco takového podepsal. Podepisuj pouze zcela úplná a detailní prohlášení, se kterými souhlasíš.</translation> </message> <message> <location line="+18"/> <source>The address to sign the message with (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation>Adresa, kterou se zpráva podepíše (např. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation> </message> <message> <location line="+10"/> <location line="+213"/> <source>Choose an address from the address book</source> <translation>Vyber adresu z adresáře</translation> </message> <message> <location line="-203"/> <location line="+213"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location line="-203"/> <source>Paste address from clipboard</source> <translation>Vlož adresu ze schránky</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location line="+12"/> <source>Enter the message you want to sign here</source> <translation>Sem vepiš zprávu, kterou chceš podepsat</translation> </message> <message> <location line="+7"/> <source>Signature</source> <translation>Podpis</translation> </message> <message> <location line="+27"/> <source>Copy the current signature to the system clipboard</source> <translation>Zkopíruj aktuálně vybraný podpis do systémové schránky</translation> </message> <message> <location line="+21"/> <source>Sign the message to prove you own this Bitcoin address</source> <translation>Podepiš zprávu, čímž prokážeš, že jsi vlastníkem této Bitcoinové adresy</translation> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation>Po&amp;depiš zprávu</translation> </message> <message> <location line="+14"/> <source>Reset all sign message fields</source> <translation>Vymaž všechna pole formuláře pro podepsání zrávy</translation> </message> <message> <location line="+3"/> <location line="+146"/> <source>Clear &amp;All</source> <translation>Všechno &amp;smaž</translation> </message> <message> <location line="-87"/> <source>&amp;Verify Message</source> <translation>&amp;Ověř zprávu</translation> </message> <message> <location line="+6"/> <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>K ověření podpisu zprávy zadej podepisující adresu, zprávu (ověř si, že správně kopíruješ zalomení řádků, mezery, tabulátory apod.) a podpis. Dávej pozor na to, abys nezkopíroval do podpisu víc, než co je v samotné podepsané zprávě, abys nebyl napálen man-in-the-middle útokem.</translation> </message> <message> <location line="+21"/> <source>The address the message was signed with (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation>Adresa, kterou je zpráva podepsána (např. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation> </message> <message> <location line="+40"/> <source>Verify the message to ensure it was signed with the specified Bitcoin address</source> <translation>Ověř zprávu, aby ses ujistil, že byla podepsána danou Bitcoinovou adresou</translation> </message> <message> <location line="+3"/> <source>Verify &amp;Message</source> <translation>O&amp;věř zprávu</translation> </message> <message> <location line="+14"/> <source>Reset all verify message fields</source> <translation>Vymaž všechna pole formuláře pro ověření zrávy</translation> </message> <message> <location filename="../signverifymessagedialog.cpp" line="+27"/> <location line="+3"/> <source>Enter a Bitcoin address (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation>Zadej Bitcoinovou adresu (např. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation> </message> <message> <location line="-2"/> <source>Click &quot;Sign Message&quot; to generate signature</source> <translation>Kliknutím na &quot;Podepiš zprávu&quot; vygeneruješ podpis</translation> </message> <message> <location line="+3"/> <source>Enter Bitcoin signature</source> <translation>Vlož Bitcoinový podpis</translation> </message> <message> <location line="+82"/> <location line="+81"/> <source>The entered address is invalid.</source> <translation>Zadaná adresa je neplatná.</translation> </message> <message> <location line="-81"/> <location line="+8"/> <location line="+73"/> <location line="+8"/> <source>Please check the address and try again.</source> <translation>Zkontroluj ji prosím a zkus to pak znovu.</translation> </message> <message> <location line="-81"/> <location line="+81"/> <source>The entered address does not refer to a key.</source> <translation>Zadaná adresa nepasuje ke klíči.</translation> </message> <message> <location line="-73"/> <source>Wallet unlock was cancelled.</source> <translation>Odemčení peněženky bylo zrušeno.</translation> </message> <message> <location line="+8"/> <source>Private key for the entered address is not available.</source> <translation>Soukromý klíč pro zadanou adresu není dostupný.</translation> </message> <message> <location line="+12"/> <source>Message signing failed.</source> <translation>Podepisování zprávy selhalo.</translation> </message> <message> <location line="+5"/> <source>Message signed.</source> <translation>Zpráv podepsána.</translation> </message> <message> <location line="+59"/> <source>The signature could not be decoded.</source> <translation>Podpis nejde dekódovat.</translation> </message> <message> <location line="+0"/> <location line="+13"/> <source>Please check the signature and try again.</source> <translation>Zkontroluj ho prosím a zkus to pak znovu.</translation> </message> <message> <location line="+0"/> <source>The signature did not match the message digest.</source> <translation>Podpis se neshoduje s hašem zprávy.</translation> </message> <message> <location line="+7"/> <source>Message verification failed.</source> <translation>Ověřování zprávy selhalo.</translation> </message> <message> <location line="+5"/> <source>Message verified.</source> <translation>Zpráva ověřena.</translation> </message> </context> <context> <name>SplashScreen</name> <message> <location filename="../splashscreen.cpp" line="+22"/> <source>The Bitcoin developers</source> <translation>Vývojáři Bitcoinu</translation> </message> <message> <location line="+1"/> <source>[testnet]</source> <translation>[testnet]</translation> </message> </context> <context> <name>TransactionDesc</name> <message> <location filename="../transactiondesc.cpp" line="+20"/> <source>Open until %1</source> <translation>Otřevřeno dokud %1</translation> </message> <message> <location line="+6"/> <source>%1/offline</source> <translation>%1/offline</translation> </message> <message> <location line="+2"/> <source>%1/unconfirmed</source> <translation>%1/nepotvrzeno</translation> </message> <message> <location line="+2"/> <source>%1 confirmations</source> <translation>%1 potvrzení</translation> </message> <message> <location line="+18"/> <source>Status</source> <translation>Stav</translation> </message> <message numerus="yes"> <location line="+7"/> <source>, broadcast through %n node(s)</source> <translation><numerusform>, rozesláno přes 1 uzel</numerusform><numerusform>, rozesláno přes %n uzly</numerusform><numerusform>, rozesláno přes %n uzlů</numerusform></translation> </message> <message> <location line="+4"/> <source>Date</source> <translation>Datum</translation> </message> <message> <location line="+7"/> <source>Source</source> <translation>Zdroj</translation> </message> <message> <location line="+0"/> <source>Generated</source> <translation>Vygenerováno</translation> </message> <message> <location line="+5"/> <location line="+17"/> <source>From</source> <translation>Od</translation> </message> <message> <location line="+1"/> <location line="+22"/> <location line="+58"/> <source>To</source> <translation>Pro</translation> </message> <message> <location line="-77"/> <location line="+2"/> <source>own address</source> <translation>vlastní adresa</translation> </message> <message> <location line="-2"/> <source>label</source> <translation>označení</translation> </message> <message> <location line="+37"/> <location line="+12"/> <location line="+45"/> <location line="+17"/> <location line="+30"/> <source>Credit</source> <translation>Příjem</translation> </message> <message numerus="yes"> <location line="-102"/> <source>matures in %n more block(s)</source> <translation><numerusform>dozraje po jednom bloku</numerusform><numerusform>dozraje po %n blocích</numerusform><numerusform>dozraje po %n blocích</numerusform></translation> </message> <message> <location line="+2"/> <source>not accepted</source> <translation>neakceptováno</translation> </message> <message> <location line="+44"/> <location line="+8"/> <location line="+15"/> <location line="+30"/> <source>Debit</source> <translation>Výdaj</translation> </message> <message> <location line="-39"/> <source>Transaction fee</source> <translation>Transakční poplatek</translation> </message> <message> <location line="+16"/> <source>Net amount</source> <translation>Čistá částka</translation> </message> <message> <location line="+6"/> <source>Message</source> <translation>Zpráva</translation> </message> <message> <location line="+2"/> <source>Comment</source> <translation>Komentář</translation> </message> <message> <location line="+2"/> <source>Transaction ID</source> <translation>ID transakce</translation> </message> <message> <location line="+3"/> <source>Generated coins must mature a certain number of 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>Vygenerované mince musí čekat 120 bloků, než mohou být utraceny. Když jsi vygeneroval tenhle blok, tak byl rozposlán do sítě, aby byl přidán do řetězce bloků. Pokud se mu nepodaří dostat se do řetězce, změní se na &quot;neakceptovaný&quot; a nepůjde utratit. To se občas může stát, pokud jiný uzel vygeneruje blok zhruba ve stejném okamžiku jako ty.</translation> </message> <message> <location line="+7"/> <source>Debug information</source> <translation>Ladicí informace</translation> </message> <message> <location line="+8"/> <source>Transaction</source> <translation>Transakce</translation> </message> <message> <location line="+3"/> <source>Inputs</source> <translation>Vstupy</translation> </message> <message> <location line="+23"/> <source>Amount</source> <translation>Částka</translation> </message> <message> <location line="+1"/> <source>true</source> <translation>true</translation> </message> <message> <location line="+0"/> <source>false</source> <translation>false</translation> </message> <message> <location line="-209"/> <source>, has not been successfully broadcast yet</source> <translation>, ještě nebylo rozesláno</translation> </message> <message numerus="yes"> <location line="-35"/> <source>Open for %n more block(s)</source> <translation><numerusform>Otevřeno pro 1 další blok</numerusform><numerusform>Otevřeno pro %n další bloky</numerusform><numerusform>Otevřeno pro %n dalších bloků</numerusform></translation> </message> <message> <location line="+70"/> <source>unknown</source> <translation>neznámo</translation> </message> </context> <context> <name>TransactionDescDialog</name> <message> <location filename="../forms/transactiondescdialog.ui" line="+14"/> <source>Transaction details</source> <translation>Detaily transakce</translation> </message> <message> <location line="+6"/> <source>This pane shows a detailed description of the transaction</source> <translation>Toto okno zobrazuje detailní popis transakce</translation> </message> </context> <context> <name>TransactionTableModel</name> <message> <location filename="../transactiontablemodel.cpp" line="+225"/> <source>Date</source> <translation>Datum</translation> </message> <message> <location line="+0"/> <source>Type</source> <translation>Typ</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Adresa</translation> </message> <message> <location line="+0"/> <source>Amount</source> <translation>Částka</translation> </message> <message numerus="yes"> <location line="+57"/> <source>Open for %n more block(s)</source> <translation><numerusform>Otevřeno pro 1 další blok</numerusform><numerusform>Otevřeno pro %n další bloky</numerusform><numerusform>Otevřeno pro %n dalších bloků</numerusform></translation> </message> <message> <location line="+3"/> <source>Open until %1</source> <translation>Otřevřeno dokud %1</translation> </message> <message> <location line="+3"/> <source>Offline (%1 confirmations)</source> <translation>Offline (%1 potvrzení)</translation> </message> <message> <location line="+3"/> <source>Unconfirmed (%1 of %2 confirmations)</source> <translation>Nepotvrzeno (%1 z %2 potvrzení)</translation> </message> <message> <location line="+3"/> <source>Confirmed (%1 confirmations)</source> <translation>Potvrzeno (%1 potvrzení)</translation> </message> <message numerus="yes"> <location line="+8"/> <source>Mined balance will be available when it matures in %n more block(s)</source> <translation><numerusform>Vytěžené mince budou použitelné po dozrání, tj. po jednom bloku</numerusform><numerusform>Vytěžené mince budou použitelné po dozrání, tj. po %n blocích</numerusform><numerusform>Vytěžené mince budou použitelné po dozrání, tj. po %n blocích</numerusform></translation> </message> <message> <location line="+5"/> <source>This block was not received by any other nodes and will probably not be accepted!</source> <translation>Tento blok nedostal žádný jiný uzel a pravděpodobně nebude akceptován!</translation> </message> <message> <location line="+3"/> <source>Generated but not accepted</source> <translation>Vygenerováno, ale neakceptováno</translation> </message> <message> <location line="+43"/> <source>Received with</source> <translation>Přijato do</translation> </message> <message> <location line="+2"/> <source>Received from</source> <translation>Přijato od</translation> </message> <message> <location line="+3"/> <source>Sent to</source> <translation>Posláno na</translation> </message> <message> <location line="+2"/> <source>Payment to yourself</source> <translation>Platba sama sobě</translation> </message> <message> <location line="+2"/> <source>Mined</source> <translation>Vytěženo</translation> </message> <message> <location line="+38"/> <source>(n/a)</source> <translation>(n/a)</translation> </message> <message> <location line="+199"/> <source>Transaction status. Hover over this field to show number of confirmations.</source> <translation>Stav transakce. Najetím myši na toto políčko si zobrazíš počet potvrzení.</translation> </message> <message> <location line="+2"/> <source>Date and time that the transaction was received.</source> <translation>Datum a čas přijetí transakce.</translation> </message> <message> <location line="+2"/> <source>Type of transaction.</source> <translation>Druh transakce.</translation> </message> <message> <location line="+2"/> <source>Destination address of transaction.</source> <translation>Cílová adresa transakce.</translation> </message> <message> <location line="+2"/> <source>Amount removed from or added to balance.</source> <translation>Částka odečtená z nebo přičtená k účtu.</translation> </message> </context> <context> <name>TransactionView</name> <message> <location filename="../transactionview.cpp" line="+52"/> <location line="+16"/> <source>All</source> <translation>Vše</translation> </message> <message> <location line="-15"/> <source>Today</source> <translation>Dnes</translation> </message> <message> <location line="+1"/> <source>This week</source> <translation>Tento týden</translation> </message> <message> <location line="+1"/> <source>This month</source> <translation>Tento měsíc</translation> </message> <message> <location line="+1"/> <source>Last month</source> <translation>Minulý měsíc</translation> </message> <message> <location line="+1"/> <source>This year</source> <translation>Letos</translation> </message> <message> <location line="+1"/> <source>Range...</source> <translation>Rozsah...</translation> </message> <message> <location line="+11"/> <source>Received with</source> <translation>Přijato</translation> </message> <message> <location line="+2"/> <source>Sent to</source> <translation>Posláno</translation> </message> <message> <location line="+2"/> <source>To yourself</source> <translation>Sám sobě</translation> </message> <message> <location line="+1"/> <source>Mined</source> <translation>Vytěženo</translation> </message> <message> <location line="+1"/> <source>Other</source> <translation>Ostatní</translation> </message> <message> <location line="+7"/> <source>Enter address or label to search</source> <translation>Zadej adresu nebo označení pro její vyhledání</translation> </message> <message> <location line="+7"/> <source>Min amount</source> <translation>Minimální částka</translation> </message> <message> <location line="+34"/> <source>Copy address</source> <translation>Kopíruj adresu</translation> </message> <message> <location line="+1"/> <source>Copy label</source> <translation>Kopíruj její označení</translation> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation>Kopíruj částku</translation> </message> <message> <location line="+1"/> <source>Copy transaction ID</source> <translation>Kopíruj ID transakce</translation> </message> <message> <location line="+1"/> <source>Edit label</source> <translation>Uprav označení</translation> </message> <message> <location line="+1"/> <source>Show transaction details</source> <translation>Zobraz detaily transakce</translation> </message> <message> <location line="+139"/> <source>Export Transaction Data</source> <translation>Exportuj transakční data</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>CSV formát (*.csv)</translation> </message> <message> <location line="+8"/> <source>Confirmed</source> <translation>Potvrzeno</translation> </message> <message> <location line="+1"/> <source>Date</source> <translation>Datum</translation> </message> <message> <location line="+1"/> <source>Type</source> <translation>Typ</translation> </message> <message> <location line="+1"/> <source>Label</source> <translation>Označení</translation> </message> <message> <location line="+1"/> <source>Address</source> <translation>Adresa</translation> </message> <message> <location line="+1"/> <source>Amount</source> <translation>Částka</translation> </message> <message> <location line="+1"/> <source>ID</source> <translation>ID</translation> </message> <message> <location line="+4"/> <source>Error exporting</source> <translation>Chyba při exportu</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>Nemohu zapisovat do souboru %1.</translation> </message> <message> <location line="+100"/> <source>Range:</source> <translation>Rozsah:</translation> </message> <message> <location line="+8"/> <source>to</source> <translation>až</translation> </message> </context> <context> <name>WalletModel</name> <message> <location filename="../walletmodel.cpp" line="+193"/> <source>Send Coins</source> <translation>Pošli mince</translation> </message> </context> <context> <name>WalletView</name> <message> <location filename="../walletview.cpp" line="+42"/> <source>&amp;Export</source> <translation>&amp;Export</translation> </message> <message> <location line="+1"/> <source>Export the data in the current tab to a file</source> <translation>Exportuj data z tohoto panelu do souboru</translation> </message> <message> <location line="+193"/> <source>Backup Wallet</source> <translation>Záloha peněženky</translation> </message> <message> <location line="+0"/> <source>Wallet Data (*.dat)</source> <translation>Data peněženky (*.dat)</translation> </message> <message> <location line="+3"/> <source>Backup Failed</source> <translation>Zálohování selhalo</translation> </message> <message> <location line="+0"/> <source>There was an error trying to save the wallet data to the new location.</source> <translation>Při ukládání peněženky na nové místo se přihodila nějaká chyba.</translation> </message> <message> <location line="+4"/> <source>Backup Successful</source> <translation>Úspěšně zazálohováno</translation> </message> <message> <location line="+0"/> <source>The wallet data was successfully saved to the new location.</source> <translation>Data z peněženky byla v pořádku uložena na nové místo.</translation> </message> </context> <context> <name>bitcoin-core</name> <message> <location filename="../bitcoinstrings.cpp" line="+94"/> <source>Bitcoin version</source> <translation>Verze Bitcoinu</translation> </message> <message> <location line="+102"/> <source>Usage:</source> <translation>Užití:</translation> </message> <message> <location line="-29"/> <source>Send command to -server or bitcoind</source> <translation>Poslat příkaz pro -server nebo bitcoind</translation> </message> <message> <location line="-23"/> <source>List commands</source> <translation>Výpis příkazů</translation> </message> <message> <location line="-12"/> <source>Get help for a command</source> <translation>Získat nápovědu pro příkaz</translation> </message> <message> <location line="+24"/> <source>Options:</source> <translation>Možnosti:</translation> </message> <message> <location line="+24"/> <source>Specify configuration file (default: bitcoin.conf)</source> <translation>Konfigurační soubor (výchozí: bitcoin.conf)</translation> </message> <message> <location line="+3"/> <source>Specify pid file (default: bitcoind.pid)</source> <translation>PID soubor (výchozí: bitcoind.pid)</translation> </message> <message> <location line="-1"/> <source>Specify data directory</source> <translation>Adresář pro data</translation> </message> <message> <location line="-9"/> <source>Set database cache size in megabytes (default: 25)</source> <translation>Nastavit velikost databázové vyrovnávací paměti v megabajtech (výchozí: 25)</translation> </message> <message> <location line="-28"/> <source>Listen for connections on &lt;port&gt; (default: 8333 or testnet: 18333)</source> <translation>Čekat na spojení na &lt;portu&gt; (výchozí: 8333 nebo testnet: 18333)</translation> </message> <message> <location line="+5"/> <source>Maintain at most &lt;n&gt; connections to peers (default: 125)</source> <translation>Povolit nejvýše &lt;n&gt; připojení k uzlům (výchozí: 125)</translation> </message> <message> <location line="-48"/> <source>Connect to a node to retrieve peer addresses, and disconnect</source> <translation>Připojit se k uzlu, získat adresy jeho protějšků a odpojit se</translation> </message> <message> <location line="+82"/> <source>Specify your own public address</source> <translation>Specifikuj svou veřejnou adresu</translation> </message> <message> <location line="+3"/> <source>Threshold for disconnecting misbehaving peers (default: 100)</source> <translation>Práh pro odpojování zlobivých uzlů (výchozí: 100)</translation> </message> <message> <location line="-134"/> <source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source> <translation>Doba ve vteřinách, po kterou se nebudou moci zlobivé uzly znovu připojit (výchozí: 86400)</translation> </message> <message> <location line="-29"/> <source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source> <translation>Při nastavování naslouchacího RPC portu %i pro IPv4 nastala chyba: %s</translation> </message> <message> <location line="+27"/> <source>Listen for JSON-RPC connections on &lt;port&gt; (default: 8332 or testnet: 18332)</source> <translation>Čekat na JSON RPC spojení na &lt;portu&gt; (výchozí: 8332 nebo testnet: 18332)</translation> </message> <message> <location line="+37"/> <source>Accept command line and JSON-RPC commands</source> <translation>Akceptovat příkazy z příkazové řádky a přes JSON-RPC</translation> </message> <message> <location line="+76"/> <source>Run in the background as a daemon and accept commands</source> <translation>Běžet na pozadí jako démon a akceptovat příkazy</translation> </message> <message> <location line="+37"/> <source>Use the test network</source> <translation>Použít testovací síť (testnet)</translation> </message> <message> <location line="-112"/> <source>Accept connections from outside (default: 1 if no -proxy or -connect)</source> <translation>Přijímat spojení zvenčí (výchozí: 1, pokud není zadáno -proxy nebo -connect)</translation> </message> <message> <location line="-80"/> <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;Bitcoin Alert&quot; admin@foo.com </source> <translation>%s, musíš nastavit rpcpassword v konfiguračním souboru: %s Je vhodné použít následující náhodné heslo: rpcuser=bitcoinrpc rpcpassword=%s (není potřeba si ho pamatovat) rpcuser a rpcpassword NESMÍ být stejné. Pokud konfigurační soubor ještě neexistuje, vytvoř ho tak, aby ho mohl číst pouze vlastník. Je také doporučeno si nastavit alertnotify, abys byl upozorněn na případné problémy; například: alertnotify=echo %%s | mail -s &quot;Bitcoin Alert&quot; admin@foo.com </translation> </message> <message> <location line="+17"/> <source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source> <translation>Při nastavování naslouchacího RPC portu %u pro IPv6 nastala chyba, vracím se k IPv4: %s</translation> </message> <message> <location line="+3"/> <source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source> <translation>Poslouchat na zadané adrese. Pro zápis IPv6 adresy použij notaci [adresa]:port</translation> </message> <message> <location line="+3"/> <source>Cannot obtain a lock on data directory %s. Bitcoin is probably already running.</source> <translation>Nedaří se mi získat zámek na datový adresář %s. Bitcoin pravděpodobně už jednou běží.</translation> </message> <message> <location line="+3"/> <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>Chyba: Transakce byla odmítnuta! Tohle může nastat, pokud nějaké mince z tvé peněženky už jednou byly utraceny, například pokud používáš kopii souboru wallet.dat a mince byly utraceny v druhé kopii, ale nebyly označeny jako utracené v této.</translation> </message> <message> <location line="+4"/> <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>Chyba: Tahle transakce vyžaduje transakční poplatek nejméně %s kvůli velikosti zasílané částky, komplexnosti nebo použití nedávno přijatých mincí!</translation> </message> <message> <location line="+3"/> <source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source> <translation>Spustit příkaz po přijetí relevantního hlášení (%s se v příkazu nahradí za zprávu)</translation> </message> <message> <location line="+3"/> <source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source> <translation>Spustit příkaz, když se objeví transakce týkající se peněženky (%s se v příkazu nahradí za TxID)</translation> </message> <message> <location line="+11"/> <source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source> <translation>Nastavit maximální velikost prioritních/nízkopoplatkových transakcí v bajtech (výchozí: 27000)</translation> </message> <message> <location line="+6"/> <source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source> <translation>Tohle je testovací verze – používej ji jen na vlastní riziko, ale rozhodně ji nepoužívej k těžbě nebo pro obchodní aplikace</translation> </message> <message> <location line="+5"/> <source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source> <translation>Upozornění: -paytxfee je nastaveno velmi vysoko! Toto je transakční poplatek, který zaplatíš za každou poslanou transakci.</translation> </message> <message> <location line="+3"/> <source>Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.</source> <translation>Upozornění: Zobrazené transakce nemusí být správné! Možná potřebuješ aktualizovat nebo ostatní uzly potřebují aktualizovat.</translation> </message> <message> <location line="+3"/> <source>Warning: Please check that your computer&apos;s date and time are correct! If your clock is wrong Bitcoin will not work properly.</source> <translation>Upozornění: Zkontroluj, že máš v počítači správně nastavený datum a čas! Pokud jsou nastaveny špatně, Bitcoin nebude fungovat správně.</translation> </message> <message> <location line="+3"/> <source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source> <translation>Upozornění: nastala chyba při čtení souboru wallet.dat! Všechny klíče se přečetly správně, ale data o transakcích nebo záznamy v adresáři mohou chybět či být nesprávné.</translation> </message> <message> <location line="+3"/> <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>Upozornění: soubor wallet.dat je poškozený, data jsou však zachráněna! Původní soubor wallet.dat je uložený jako wallet.{timestamp}.bak v %s. Pokud je stav tvého účtu nebo transakce nesprávné, zřejmě bys měl obnovit zálohu.</translation> </message> <message> <location line="+14"/> <source>Attempt to recover private keys from a corrupt wallet.dat</source> <translation>Pokusit se zachránit soukromé klíče z poškozeného souboru wallet.dat</translation> </message> <message> <location line="+2"/> <source>Block creation options:</source> <translation>Možnosti vytvoření bloku:</translation> </message> <message> <location line="+5"/> <source>Connect only to the specified node(s)</source> <translation>Připojit se pouze k zadanému uzlu (příp. zadaným uzlům)</translation> </message> <message> <location line="+3"/> <source>Corrupted block database detected</source> <translation>Bylo zjištěno poškození databáze bloků</translation> </message> <message> <location line="+1"/> <source>Discover own IP address (default: 1 when listening and no -externalip)</source> <translation>Zjistit vlastní IP adresu (výchozí: 1, pokud naslouchá a není zadáno -externalip)</translation> </message> <message> <location line="+1"/> <source>Do you want to rebuild the block database now?</source> <translation>Chceš přestavět databázi bloků hned teď?</translation> </message> <message> <location line="+2"/> <source>Error initializing block database</source> <translation>Chyba při zakládání databáze bloků</translation> </message> <message> <location line="+1"/> <source>Error initializing wallet database environment %s!</source> <translation>Chyba při vytváření databázového prostředí %s pro peněženku!</translation> </message> <message> <location line="+1"/> <source>Error loading block database</source> <translation>Chyba při načítání databáze bloků</translation> </message> <message> <location line="+4"/> <source>Error opening block database</source> <translation>Chyba při otevírání databáze bloků</translation> </message> <message> <location line="+2"/> <source>Error: Disk space is low!</source> <translation>Problém: Na disku je málo místa!</translation> </message> <message> <location line="+1"/> <source>Error: Wallet locked, unable to create transaction!</source> <translation>Chyba: Peněženka je zamčená, nemohu vytvořit transakci!</translation> </message> <message> <location line="+1"/> <source>Error: system error: </source> <translation>Chyba: systémová chyba: </translation> </message> <message> <location line="+1"/> <source>Failed to listen on any port. Use -listen=0 if you want this.</source> <translation>Nepodařilo se naslouchat na žádném portu. Použij -listen=0, pokud to byl tvůj záměr.</translation> </message> <message> <location line="+1"/> <source>Failed to read block info</source> <translation>Nepodařilo se přečíst informace o bloku</translation> </message> <message> <location line="+1"/> <source>Failed to read block</source> <translation>Nepodařilo se přečíst blok</translation> </message> <message> <location line="+1"/> <source>Failed to sync block index</source> <translation>Nepodařilo se sesynchronizovat index bloků</translation> </message> <message> <location line="+1"/> <source>Failed to write block index</source> <translation>Nepodařilo se zapsat index bloků</translation> </message> <message> <location line="+1"/> <source>Failed to write block info</source> <translation>Nepodařilo se zapsat informace o bloku</translation> </message> <message> <location line="+1"/> <source>Failed to write block</source> <translation>Nepodařilo se zapsat blok</translation> </message> <message> <location line="+1"/> <source>Failed to write file info</source> <translation>Nepodařilo se zapsat informace o souboru</translation> </message> <message> <location line="+1"/> <source>Failed to write to coin database</source> <translation>Selhal zápis do databáze mincí</translation> </message> <message> <location line="+1"/> <source>Failed to write transaction index</source> <translation>Nepodařilo se zapsat index transakcí</translation> </message> <message> <location line="+1"/> <source>Failed to write undo data</source> <translation>Nepodařilo se zapsat data o vracení změn</translation> </message> <message> <location line="+2"/> <source>Find peers using DNS lookup (default: 1 unless -connect)</source> <translation>Hledat uzly přes DNS (výchozí: 1, pokud není zadáno -connect)</translation> </message> <message> <location line="+1"/> <source>Generate coins (default: 0)</source> <translation>Generovat mince (výchozí: 0)</translation> </message> <message> <location line="+2"/> <source>How many blocks to check at startup (default: 288, 0 = all)</source> <translation>Kolik bloků při startu zkontrolovat (výchozí: 288, 0 = všechny)</translation> </message> <message> <location line="+1"/> <source>How thorough the block verification is (0-4, default: 3)</source> <translation>Jak moc důkladná má být verifikace bloků (0-4, výchozí: 3)</translation> </message> <message> <location line="+19"/> <source>Not enough file descriptors available.</source> <translation>Je nedostatek deskriptorů souborů.</translation> </message> <message> <location line="+8"/> <source>Rebuild block chain index from current blk000??.dat files</source> <translation>Znovu vytvořit index řetězce bloků z aktuálních blk000??.dat souborů</translation> </message> <message> <location line="+16"/> <source>Set the number of threads to service RPC calls (default: 4)</source> <translation>Nastavení počtu vláken pro servisní RPC volání (výchozí: 4)</translation> </message> <message> <location line="+26"/> <source>Verifying blocks...</source> <translation>Ověřuji bloky...</translation> </message> <message> <location line="+1"/> <source>Verifying wallet...</source> <translation>Kontroluji peněženku...</translation> </message> <message> <location line="-69"/> <source>Imports blocks from external blk000??.dat file</source> <translation>Importovat bloky z externího souboru blk000??.dat</translation> </message> <message> <location line="-76"/> <source>Set the number of script verification threads (up to 16, 0 = auto, &lt;0 = leave that many cores free, default: 0)</source> <translation>Nastavení počtu vláken pro verifikaci skriptů (max. 16, 0 = automaticky, &lt;0 = nechat daný počet jader volný, výchozí: 0)</translation> </message> <message> <location line="+77"/> <source>Information</source> <translation>Informace</translation> </message> <message> <location line="+3"/> <source>Invalid -tor address: &apos;%s&apos;</source> <translation>Neplatná -tor adresa: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Invalid amount for -minrelaytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation>Neplatná částka pro -minrelaytxfee=&lt;částka&gt;: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Invalid amount for -mintxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation>Neplatná částka pro -mintxfee=&lt;částka&gt;: &apos;%s&apos;</translation> </message> <message> <location line="+8"/> <source>Maintain a full transaction index (default: 0)</source> <translation>Spravovat úplný index transakcí (výchozí: 0)</translation> </message> <message> <location line="+2"/> <source>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: 5000)</source> <translation>Maximální velikost přijímacího bufferu pro každé spojení, &lt;n&gt;*1000 bajtů (výchozí: 5000)</translation> </message> <message> <location line="+1"/> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: 1000)</source> <translation>Maximální velikost odesílacího bufferu pro každé spojení, &lt;n&gt;*1000 bajtů (výchozí: 1000)</translation> </message> <message> <location line="+2"/> <source>Only accept block chain matching built-in checkpoints (default: 1)</source> <translation>Uznávat pouze řetěz bloků, který odpovídá vnitřním kontrolním bodům (výchozí: 1)</translation> </message> <message> <location line="+1"/> <source>Only connect to nodes in network &lt;net&gt; (IPv4, IPv6 or Tor)</source> <translation>Připojit se pouze k uzlům v &lt;net&gt; síti (IPv4, IPv6 nebo Tor)</translation> </message> <message> <location line="+2"/> <source>Output extra debugging information. Implies all other -debug* options</source> <translation>Tisknout speciální ladicí informace. Implikuje použití všech -debug* voleb</translation> </message> <message> <location line="+1"/> <source>Output extra network debugging information</source> <translation>Tisknout speciální ladicí informace o síti</translation> </message> <message> <location line="+2"/> <source>Prepend debug output with timestamp</source> <translation>Připojit před ladicí výstup časové razítko</translation> </message> <message> <location line="+5"/> <source>SSL options: (see the Bitcoin Wiki for SSL setup instructions)</source> <translation>Možnosti SSL: (viz instrukce nastavení SSL v Bitcoin Wiki)</translation> </message> <message> <location line="+1"/> <source>Select the version of socks proxy to use (4-5, default: 5)</source> <translation>Zvol verzi socks proxy (4-5, výchozí: 5)</translation> </message> <message> <location line="+3"/> <source>Send trace/debug info to console instead of debug.log file</source> <translation>Posílat stopovací/ladicí informace do konzole místo do souboru debug.log</translation> </message> <message> <location line="+1"/> <source>Send trace/debug info to debugger</source> <translation>Posílat stopovací/ladicí informace do debuggeru</translation> </message> <message> <location line="+5"/> <source>Set maximum block size in bytes (default: 250000)</source> <translation>Nastavit maximální velikost bloku v bajtech (výchozí: 250000)</translation> </message> <message> <location line="+1"/> <source>Set minimum block size in bytes (default: 0)</source> <translation>Nastavit minimální velikost bloku v bajtech (výchozí: 0)</translation> </message> <message> <location line="+2"/> <source>Shrink debug.log file on client startup (default: 1 when no -debug)</source> <translation>Při spuštění klienta zmenšit soubor debug.log (výchozí: 1, pokud není zadáno -debug)</translation> </message> <message> <location line="+1"/> <source>Signing transaction failed</source> <translation>Podepisování transakce selhalo</translation> </message> <message> <location line="+2"/> <source>Specify connection timeout in milliseconds (default: 5000)</source> <translation>Zadej časový limit spojení v milisekundách (výchozí: 5000)</translation> </message> <message> <location line="+4"/> <source>System error: </source> <translation>Systémová chyba: </translation> </message> <message> <location line="+4"/> <source>Transaction amount too small</source> <translation>Částka v transakci je příliš malá</translation> </message> <message> <location line="+1"/> <source>Transaction amounts must be positive</source> <translation>Částky v transakci musí být kladné</translation> </message> <message> <location line="+1"/> <source>Transaction too large</source> <translation>Transace je příliš velká</translation> </message> <message> <location line="+7"/> <source>Use UPnP to map the listening port (default: 0)</source> <translation>Použít UPnP k namapování naslouchacího portu (výchozí: 0)</translation> </message> <message> <location line="+1"/> <source>Use UPnP to map the listening port (default: 1 when listening)</source> <translation>Použít UPnP k namapování naslouchacího portu (výchozí: 1, pokud naslouchá)</translation> </message> <message> <location line="+1"/> <source>Use proxy to reach tor hidden services (default: same as -proxy)</source> <translation>Použít proxy k připojení ke skryté služby (výchozí: stejné jako -proxy)</translation> </message> <message> <location line="+2"/> <source>Username for JSON-RPC connections</source> <translation>Uživatelské jméno pro JSON-RPC spojení</translation> </message> <message> <location line="+4"/> <source>Warning</source> <translation>Upozornění</translation> </message> <message> <location line="+1"/> <source>Warning: This version is obsolete, upgrade required!</source> <translation>Upozornění: tahle verze je zastaralá, měl bys ji aktualizovat!</translation> </message> <message> <location line="+1"/> <source>You need to rebuild the databases using -reindex to change -txindex</source> <translation>Je třeba přestavět databázi použitím -reindex, aby bylo možné změnit -txindex</translation> </message> <message> <location line="+1"/> <source>wallet.dat corrupt, salvage failed</source> <translation>Soubor wallet.dat je poškozen, jeho záchrana se nezdařila</translation> </message> <message> <location line="-50"/> <source>Password for JSON-RPC connections</source> <translation>Heslo pro JSON-RPC spojení</translation> </message> <message> <location line="-67"/> <source>Allow JSON-RPC connections from specified IP address</source> <translation>Povolit JSON-RPC spojení ze specifikované IP adresy</translation> </message> <message> <location line="+76"/> <source>Send commands to node running on &lt;ip&gt; (default: 127.0.0.1)</source> <translation>Posílat příkazy uzlu běžícím na &lt;ip&gt; (výchozí: 127.0.0.1)</translation> </message> <message> <location line="-120"/> <source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source> <translation>Spustit příkaz, když se změní nejlepší blok (%s se v příkazu nahradí hashem bloku)</translation> </message> <message> <location line="+147"/> <source>Upgrade wallet to latest format</source> <translation>Převést peněženku na nejnovější formát</translation> </message> <message> <location line="-21"/> <source>Set key pool size to &lt;n&gt; (default: 100)</source> <translation>Nastavit zásobník klíčů na velikost &lt;n&gt; (výchozí: 100)</translation> </message> <message> <location line="-12"/> <source>Rescan the block chain for missing wallet transactions</source> <translation>Přeskenovat řetězec bloků na chybějící transakce tvé pěněženky</translation> </message> <message> <location line="+35"/> <source>Use OpenSSL (https) for JSON-RPC connections</source> <translation>Použít OpenSSL (https) pro JSON-RPC spojení</translation> </message> <message> <location line="-26"/> <source>Server certificate file (default: server.cert)</source> <translation>Soubor se serverovým certifikátem (výchozí: server.cert)</translation> </message> <message> <location line="+1"/> <source>Server private key (default: server.pem)</source> <translation>Soubor se serverovým soukromým klíčem (výchozí: server.pem)</translation> </message> <message> <location line="-151"/> <source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source> <translation>Akceptovatelné šifry (výchozí: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</translation> </message> <message> <location line="+165"/> <source>This help message</source> <translation>Tato nápověda</translation> </message> <message> <location line="+6"/> <source>Unable to bind to %s on this computer (bind returned error %d, %s)</source> <translation>Nedaří se mi připojit na %s na tomhle počítači (operace bind vrátila chybu %d, %s)</translation> </message> <message> <location line="-91"/> <source>Connect through socks proxy</source> <translation>Připojit se přes socks proxy</translation> </message> <message> <location line="-10"/> <source>Allow DNS lookups for -addnode, -seednode and -connect</source> <translation>Povolit DNS dotazy pro -addnode (přidání uzlu), -seednode a -connect (připojení)</translation> </message> <message> <location line="+55"/> <source>Loading addresses...</source> <translation>Načítám adresy...</translation> </message> <message> <location line="-35"/> <source>Error loading wallet.dat: Wallet corrupted</source> <translation>Chyba při načítání wallet.dat: peněženka je poškozená</translation> </message> <message> <location line="+1"/> <source>Error loading wallet.dat: Wallet requires newer version of Bitcoin</source> <translation>Chyba při načítání wallet.dat: peněženka vyžaduje novější verzi Bitcoinu</translation> </message> <message> <location line="+93"/> <source>Wallet needed to be rewritten: restart Bitcoin to complete</source> <translation>Soubor s peněženkou potřeboval přepsat: restartuj Bitcoin, aby se operace dokončila</translation> </message> <message> <location line="-95"/> <source>Error loading wallet.dat</source> <translation>Chyba při načítání wallet.dat</translation> </message> <message> <location line="+28"/> <source>Invalid -proxy address: &apos;%s&apos;</source> <translation>Neplatná -proxy adresa: &apos;%s&apos;</translation> </message> <message> <location line="+56"/> <source>Unknown network specified in -onlynet: &apos;%s&apos;</source> <translation>V -onlynet byla uvedena neznámá síť: &apos;%s&apos;</translation> </message> <message> <location line="-1"/> <source>Unknown -socks proxy version requested: %i</source> <translation>V -socks byla požadována neznámá verze proxy: %i</translation> </message> <message> <location line="-96"/> <source>Cannot resolve -bind address: &apos;%s&apos;</source> <translation>Nemohu přeložit -bind adresu: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Cannot resolve -externalip address: &apos;%s&apos;</source> <translation>Nemohu přeložit -externalip adresu: &apos;%s&apos;</translation> </message> <message> <location line="+44"/> <source>Invalid amount for -paytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation>Neplatná částka pro -paytxfee=&lt;částka&gt;: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Invalid amount</source> <translation>Neplatná částka</translation> </message> <message> <location line="-6"/> <source>Insufficient funds</source> <translation>Nedostatek prostředků</translation> </message> <message> <location line="+10"/> <source>Loading block index...</source> <translation>Načítám index bloků...</translation> </message> <message> <location line="-57"/> <source>Add a node to connect to and attempt to keep the connection open</source> <translation>Přidat uzel, ke kterému se připojit a snažit se spojení udržet</translation> </message> <message> <location line="-25"/> <source>Unable to bind to %s on this computer. Bitcoin is probably already running.</source> <translation>Nedaří se mi připojit na %s na tomhle počítači. Bitcoin už pravděpodobně jednou běží.</translation> </message> <message> <location line="+64"/> <source>Fee per KB to add to transactions you send</source> <translation>Poplatek za kB, který se přidá ke každé odeslané transakci</translation> </message> <message> <location line="+19"/> <source>Loading wallet...</source> <translation>Načítám peněženku...</translation> </message> <message> <location line="-52"/> <source>Cannot downgrade wallet</source> <translation>Nemohu převést peněženku do staršího formátu</translation> </message> <message> <location line="+3"/> <source>Cannot write default address</source> <translation>Nemohu napsat výchozí adresu</translation> </message> <message> <location line="+64"/> <source>Rescanning...</source> <translation>Přeskenovávám...</translation> </message> <message> <location line="-57"/> <source>Done loading</source> <translation>Načítání dokončeno</translation> </message> <message> <location line="+82"/> <source>To use the %s option</source> <translation>K použití volby %s</translation> </message> <message> <location line="-74"/> <source>Error</source> <translation>Chyba</translation> </message> <message> <location line="-31"/> <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>Musíš nastavit rpcpassword=&lt;heslo&gt; v konfiguračním souboru: %s Pokud konfigurační soubor ještě neexistuje, vytvoř ho tak, aby ho mohl číst pouze vlastník.</translation> </message> </context> </TS>
mit
karunasagark/ps
TopCoder-C#/tchs17/Properties/AssemblyInfo.cs
1388
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("tchs17")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("tchs17")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("0e2740df-1500-419e-8023-9b7a1ccbd5de")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
mit
rpbaltazar/mocker
spec/mocker/name_spec.rb
2156
require "spec_helper" describe Mocker::Name do let(:available_names){ I18n.t 'names.famous_people' } let(:female_names) { I18n.t 'names.first.female' } let(:male_names) { I18n.t 'names.first.male' } let(:first_names){ female_names + male_names } let(:last_names){ I18n.t 'names.last' } describe "famous_person" do it "returns a name of an existing person from the list" do famous_person = Mocker::Name.famous_person expect(available_names).to include famous_person end end describe "first_name" do it "returns a first name from the list" do first_name = Mocker::Name.first_name expect(first_names).to include first_name end end describe "last_name" do it "returns a last name from the list" do last_name = Mocker::Name.last_name expect(last_names).to include last_name end end describe "full_name" do it "returns a first name + last name from the list" do full_name = Mocker::Name.full_name name_parts = full_name.split ' ' expect(first_names).to include name_parts[0] expect(last_names).to include name_parts[1] end end describe "female_name" do it "returns a female first name and any last name from the list" do female_name = Mocker::Name.full_name("female") name_parts = female_name.split ' ' expect(female_names).to include name_parts[0] expect(last_names).to include name_parts[1] end end describe "female_first" do it "returns a female first name from the list" do female_name = Mocker::Name.first_name("female") expect(female_names).to include female_name end end describe "male_name" do it "returns a male first name and any last name from the list" do male_name = Mocker::Name.full_name("male") name_parts = male_name.split ' ' expect(male_names).to include name_parts[0] expect(last_names).to include name_parts[1] end end describe "male_first" do it "returns a male first name from the list" do male_name = Mocker::Name.first_name("male") expect(male_names).to include male_name end end end
mit
pablobrady/survey_tool
server/app.js
2088
var express = require('express'); var path = require('path'); var favicon = require('serve-favicon'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); // Mongo/Monk Database var mongo = require('mongodb'); var monk = require('monk'); // Remote Mongo Database var db = monk('mongodb://' + process.env.SURVEY_TOOL_DB_LOGIN + ':' + process.env.SURVEY_TOOL_DB_PASS + '@ds053794.mlab.com:53794/' + process.env.SURVEY_TOOL_DB_NAME ); var routes = require('./routes/routes'); // /server/routes/routes.js - Routes master var users = require('./routes/users'); // /server/routes/user.js - User DB access var app = express(); // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'jade'); // uncomment after placing your favicon in /public // app.use(favicon(path.join(__dirname, 'public', 'favicon.ico'))); app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(cookieParser()); app.use(express.static(path.join(__dirname, '../public'))); // Make our Mongo 'db' accessible to our router (just below...) app.use(function(req,res,next){ // Currently, adds to *EVERY* req object req.db = db; next(); }); // MIDDLEWARE for Express app.use('/', routes); app.use('/users', users); // catch 404 and forward to error handler app.use(function(req, res, next) { console.log("new ERROR - NOT FOUND!!!!") var err = new Error('Not Found'); err.status = 404; next(err); }); // error handlers // development error handler // will print stacktrace if (app.get('env') === 'development') { app.use(function(err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: err }); }); } // production error handler // no stacktraces leaked to user app.use(function(err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: {} }); }); module.exports = app;
mit
yneves/node-bauer-plugin-glob
lib/worker.js
1086
/*! ** bauer-plugin-glob -- Plugin for bauer-crawler to list files with node-glob. ** Copyright (c) 2015 Yuri Neves Silveira <http://yneves.com> ** Licensed under The MIT License <http://opensource.org/licenses/MIT> ** Distributed on <http://github.com/yneves/node-bauer-plugin-glob> */ // - -------------------------------------------------------------------- - // "use strict"; var fs = require("fs"); var path = require("path"); var glob = require("glob"); var factory = require("bauer-factory"); // - -------------------------------------------------------------------- - // module.exports = function(worker,config) { worker.on("request",function(request,response) { var options = factory.merge(config.options, request.options); glob(request.pattern, options, function(error,files) { if (error) { response.sendError(error); } else { response.sendOk({ files: files }); } }) }); worker.sendReady(); }; // - -------------------------------------------------------------------- - //
mit
Azure/azure-sdk-for-java
sdk/videoanalyzer/azure-media-videoanalyzer-edge/src/main/java/com/azure/media/videoanalyzer/edge/models/SpatialAnalysisOperationEventBase.java
1774
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.media.videoanalyzer.edge.models; import com.azure.core.annotation.Fluent; import com.fasterxml.jackson.annotation.JsonProperty; /** Defines the Azure Cognitive Services Spatial Analysis operation eventing configuration. */ @Fluent public class SpatialAnalysisOperationEventBase { /* * The event threshold. */ @JsonProperty(value = "threshold") private String threshold; /* * The operation focus type. */ @JsonProperty(value = "focus") private SpatialAnalysisOperationFocus focus; /** * Get the threshold property: The event threshold. * * @return the threshold value. */ public String getThreshold() { return this.threshold; } /** * Set the threshold property: The event threshold. * * @param threshold the threshold value to set. * @return the SpatialAnalysisOperationEventBase object itself. */ public SpatialAnalysisOperationEventBase setThreshold(String threshold) { this.threshold = threshold; return this; } /** * Get the focus property: The operation focus type. * * @return the focus value. */ public SpatialAnalysisOperationFocus getFocus() { return this.focus; } /** * Set the focus property: The operation focus type. * * @param focus the focus value to set. * @return the SpatialAnalysisOperationEventBase object itself. */ public SpatialAnalysisOperationEventBase setFocus(SpatialAnalysisOperationFocus focus) { this.focus = focus; return this; } }
mit
maku77/sample_mongoose_restful
memodb.js
742
var mongoose = require('mongoose'); var DB_URL = 'mongodb://localhost/memodb'; // Create models. var MemoSchema = new mongoose.Schema({ title: String, body: String, created: { type: Date, default: Date.now } }); var Memo = mongoose.model('Memo', MemoSchema); // Error handlers. mongoose.connection.on('error', function (err) { console.log('ERROR:', err.message); }); // Connect to the DB. mongoose.connect(DB_URL); // Create sample data. Memo.count(function (err, count) { if (count > 0) { return; } Memo.create({title: 'Title 1'}, function() {}); Memo.create({title: 'Title 2'}, function() {}); Memo.create({title: 'Title 3'}, function() {}); }); // Export interfaces. exports.Memo = Memo;
mit
KleeGroup/focus-components
src/page/mixin/cartridge-behaviour.js
1467
import isFunction from 'lodash/lang/isFunction'; import { setHeader } from 'focus-core/application'; const cartridgeBehaviour = { /** * Updates the cartridge using the cartridgeConfiguration. */ _registerCartridge(props = this.props) { const cartridgeConfiguration = this.cartridgeConfiguration || props.cartridgeConfiguration; const hasCartridge = isFunction(cartridgeConfiguration); if (!hasCartridge) { console.warn(` Your detail page does not have any cartrige configuration, this is not mandarory but recommended. It should be a component attribute return by a function. function cartridgeConfiguration(){ var cartridgeConfiguration = { summary: {component: "A React Component", props: {id: this.props.id}}, cartridge: {component: "A React Component"}, actions: {components: "react actions"} }; return cartridgeConfiguration; } `); } const config = hasCartridge ? cartridgeConfiguration() : {}; setHeader(config); }, /** * Registers the cartridge upon mounting. */ componentWillMount() { this._registerCartridge(); }, componentWillReceiveProps(nextProps) { this._registerCartridge(nextProps); } }; export default cartridgeBehaviour;
mit
robotex82/ecm_cms
app/models/ecm/cms.rb
70
module Ecm::Cms def self.table_name_prefix 'ecm_cms_' end end
mit
charlesmunger/jpregel-aws
src/main/java/edu/ucsb/jpregel/system/Part.java
6122
package edu.ucsb.jpregel.system; import api.Aggregator; import api.Vertex; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.Set; import org.infinispan.util.concurrent.jdk8backported.ConcurrentHashMapV8; /** * * @author Peter Cappello */ public final class Part { private final int partId; private final Job job; private Worker worker; private Map<Object, VertexImpl> vertexIdToVertexMap = new ConcurrentHashMapV8<Object, VertexImpl>( 8000 , 0.9f, 2); private OntoMap<Set<VertexImpl>> superstepToActiveSetMap = new OntoMap<Set<VertexImpl>>( new ActiveSet() ); // superStep parameters private long superStep; private Map<Integer, Map<Object, MessageQ>> workerNumToVertexIdToMessageQMapMap; private ComputeInput computeInput; // superStep parameters modified by each vertex.compute() private Aggregator problemAggregator; private Aggregator stepAggregator; private int numMessagesSent; Part( int partId, Job job, Worker worker ) { this.partId = partId; this.job = job; this.worker = worker; } /* * FIXME: For graph mutation (add vertex), also need void addVertexToActiveSet( Long superStep, VertexImpl vertex ) */ void add( VertexImpl vertex ) { vertex.setPart( this ); vertexIdToVertexMap.put( vertex.getVertexId(), vertex ); if ( vertex.isInitiallyActive() ) { addToActiveSet( 0L, vertex ); } } void addToActiveSet( long superStep, VertexImpl vertex ) { superstepToActiveSetMap.get( superStep ).add( vertex ); } void aggregateOutputProblemAggregator( Aggregator aggregator ) { problemAggregator.aggregate(aggregator); } void aggregateOutputStepAggregator( Aggregator aggregator ) { stepAggregator.aggregate(aggregator); } ComputeOutput doSuperStep( long superStep, ComputeInput computeInput ) { this.superStep = superStep; this.computeInput = computeInput; workerNumToVertexIdToMessageQMapMap = new HashMap<Integer, Map<Object, MessageQ>>(); numMessagesSent = 0; stepAggregator = job.makeStepAggregator(); problemAggregator = job.makeProblemAggregator(); Set<VertexImpl> activeSet = superstepToActiveSetMap.get( superStep ); for ( VertexImpl vertex : activeSet ) { vertex.compute(); vertex.removeMessageQ( superStep ); // MessageQ now is garbage } superstepToActiveSetMap.remove( superStep ); // active vertex set now is garbage boolean thereIsNextStep = numMessagesSent > 0; return new ComputeOutput( thereIsNextStep, workerNumToVertexIdToMessageQMapMap, stepAggregator, problemAggregator ); } ComputeInput getComputeInput() { return computeInput; } int getPartId() { return partId; } Aggregator getStepAggregator() { return stepAggregator; } long getSuperStep() { return superStep; } Vertex getVertex( int vertexId ) { return vertexIdToVertexMap.get( vertexId ); } Map<Object, VertexImpl> getVertexIdToVertexMap() { return vertexIdToVertexMap; } public Collection<VertexImpl> getVertices() { return vertexIdToVertexMap.values(); } void incrementNumMessagesSent() { numMessagesSent++; } void receiveMessage( Object vertexId, Message message, long superStep ) { VertexImpl vertex = vertexIdToVertexMap.get( vertexId ); assert vertex != null : vertexId; if ( vertex == null ) { System.out.println( "VertexID null: " + vertexId ); } vertex.receiveMessage( message, superStep ); addToActiveSet( superStep, vertex ); } void receiveMessageQ( Object vertexId, MessageQ messageQ, long superStep ) { VertexImpl vertex = vertexIdToVertexMap.get( vertexId ); vertex.receiveMessageQ( messageQ, superStep ); addToActiveSet( superStep, vertex ); } void removeFromActiveSet( long superStep, VertexImpl vertex ) { superstepToActiveSetMap.get( superStep ).remove( vertex ); } void removeVertex( Object vertexId ) { vertexIdToVertexMap.remove( vertexId ); worker.removeVertex(); } void sendMessage( Object receivingVertexId, Message message, long superStep ) { numMessagesSent++; int receivingPartId = job.getPartId( receivingVertexId ); if ( receivingPartId == partId ) { // message is for vertex in this Part receiveMessage( receivingVertexId, message, superStep ); return; } // message is for a vertex in another part Part receivingPart = worker.getPart( receivingPartId ); if ( receivingPart != null ) { // receivingPart is internal to this Worker receivingPart.receiveMessage( receivingVertexId, message, superStep ); return; } // receivingPart is external to this Worker int workerNum = worker.getWorkerNum( receivingPartId ); assert workerNum != worker.getWorkerNum(); // get vertexIdToMessageQMap for destination Worker Map<Object, MessageQ> vertexIdToMessageQMap = workerNumToVertexIdToMessageQMapMap.get( workerNum ); if ( vertexIdToMessageQMap == null ) { vertexIdToMessageQMap = new HashMap<Object, MessageQ>(); workerNumToVertexIdToMessageQMapMap.put( workerNum, vertexIdToMessageQMap ); } // get receivingVertex's MessageQ MessageQ receivingVertexMessageQ = vertexIdToMessageQMap.get( receivingVertexId ); if ( receivingVertexMessageQ == null ) { receivingVertexMessageQ = new MessageQ( job.getVertexFactory().getCombiner() ); vertexIdToMessageQMap.put( receivingVertexId, receivingVertexMessageQ ); } receivingVertexMessageQ.add( message ); } }
mit
vikfroberg/make
db/migrate/20140612222325_create_comments.rb
189
class CreateComments < ActiveRecord::Migration def change create_table :comments do |t| t.text :body t.references :task, index: true t.timestamps end end end
mit
rstacruz/ractive
src/Ractive/prototype/observe/PatternObserver.js
2576
import runloop from 'global/runloop'; import isEqual from 'utils/isEqual'; import getPattern from 'Ractive/prototype/observe/getPattern'; var PatternObserver, wildcard = /\*/, slice = Array.prototype.slice; PatternObserver = function ( ractive, keypath, callback, options ) { this.root = ractive; this.callback = callback; this.defer = options.defer; this.keypath = keypath; this.regex = new RegExp( '^' + keypath.replace( /\./g, '\\.' ).replace( /\*/g, '([^\\.]+)' ) + '$' ); this.values = {}; if ( this.defer ) { this.proxies = []; } // Observers are notified before any DOM changes take place (though // they can defer execution until afterwards) this.priority = 'pattern'; // default to root as context, but allow it to be overridden this.context = ( options && options.context ? options.context : ractive ); }; PatternObserver.prototype = { init: function ( immediate ) { var values, keypath; values = getPattern( this.root, this.keypath ); if ( immediate !== false ) { for ( keypath in values ) { if ( values.hasOwnProperty( keypath ) ) { this.update( keypath ); } } } else { this.values = values; } }, update: function ( keypath ) { var values; if ( wildcard.test( keypath ) ) { values = getPattern( this.root, keypath ); for ( keypath in values ) { if ( values.hasOwnProperty( keypath ) ) { this.update( keypath ); } } return; } // special case - array mutation should not trigger `array.*` // pattern observer with `array.length` if ( this.root.viewmodel.implicitChanges[ keypath ] ) { return; } if ( this.defer && this.ready ) { runloop.addObserver( this.getProxy( keypath ) ); return; } this.reallyUpdate( keypath ); }, reallyUpdate: function ( keypath ) { var value, keys, args; value = this.root.viewmodel.get( keypath ); // Prevent infinite loops if ( this.updating ) { this.values[ keypath ] = value; return; } this.updating = true; if ( !isEqual( value, this.values[ keypath ] ) || !this.ready ) { keys = slice.call( this.regex.exec( keypath ), 1 ); args = [ value, this.values[ keypath ], keypath ].concat( keys ); this.callback.apply( this.context, args ); this.values[ keypath ] = value; } this.updating = false; }, getProxy: function ( keypath ) { var self = this; if ( !this.proxies[ keypath ] ) { this.proxies[ keypath ] = { update: function () { self.reallyUpdate( keypath ); } }; } return this.proxies[ keypath ]; } }; export default PatternObserver;
mit
SLedunois/personal-website
public/src/admin/nav/Nav.react.js
937
import React, { Component } from 'react'; import { Link } from 'react-router-dom'; class Nav extends Component { render() { return ( <header className="nav"> <ul> <li className={this.props.location.hash === '#/' ? 'active' : null}> <Link to="/">Content<span className="decoration" /></Link> </li> <li className={this.props.location.hash === '#/blog' ? 'active' : null} > <Link to="/blog">Blog<span className="decoration" /></Link> </li> <li className={ this.props.location.hash === '#/metrics' ? 'active' : null } > <Link to="/metrics">Metrics<span className="decoration" /></Link> </li> </ul> <ul className="right"> <li><a href="/auth/logout">Logout</a></li> </ul> </header> ); } } export default Nav;
mit
tomrijnbeek/utilities
src/SpaceTime/undirected/Unit.cs
6496
using System; using Bearded.Utilities.Math; using OpenTK; namespace Bearded.Utilities.SpaceTime { /// <summary> /// A type-safe representation of an undirected signed distance or length. /// </summary> public struct Unit : IEquatable<Unit>, IComparable<Unit> { private readonly float value; #region construction /// <summary> /// Creates a new instance of the Unit type. /// </summary> public Unit(float value) { this.value = value; } #endregion #region properties /// <summary> /// Returns the numeric value of the unit value. /// </summary> public float NumericValue { get { return this.value; } } /// <summary> /// Returns the type-safe square of the unit value. /// </summary> public Squared<Unit> Squared { get { return Squared<Unit>.FromRoot(this.value); } } /// <summary> /// Returns a Unit type with value 0. /// </summary> public static Unit Zero { get { return new Unit(0); } } /// <summary> /// Returns a Unit type with value 1. /// </summary> public static Unit One { get { return new Unit(1); } } #endregion #region methods #region equality and hashcode public bool Equals(Unit other) { return this.value == other.value; } public override bool Equals(object obj) { return obj is Unit && this.Equals((Unit)obj); } public override int GetHashCode() { return this.value.GetHashCode(); } #endregion #region compare public int CompareTo(Unit other) { return this.value.CompareTo(other.value); } #endregion #endregion #region operators #region algebra /// <summary> /// Adds two unit values. /// </summary> public static Unit operator +(Unit u0, Unit u1) { return new Unit(u0.value + u1.value); } /// <summary> /// Subtracts a unit value from another. /// </summary> public static Unit operator -(Unit u0, Unit u1) { return new Unit(u0.value - u1.value); } #endregion #region scaling /// <summary> /// Inverts the unit value. /// </summary> public static Unit operator -(Unit u) { return new Unit(-u.value); } /// <summary> /// Multiples the unit value with a scalar. /// </summary> public static Unit operator *(Unit u, float scalar) { return new Unit(u.value * scalar); } /// <summary> /// Multiples the unit value with a scalar. /// </summary> public static Unit operator *(float scalar, Unit u) { return new Unit(u.value * scalar); } /// <summary> /// Divides the unit value by a divisor. /// </summary> public static Unit operator /(Unit u, float divisor) { return new Unit(u.value / divisor); } #endregion #region ratio /// <summary> /// Devides a unit value by another, returning a type-less fraction. /// </summary> public static float operator /(Unit dividend, Unit divisor) { return dividend.value / divisor.value; } #endregion #region differentiate /// <summary> /// Divides a unit value by a timespan, returning a speed. /// </summary> public static Speed operator /(Unit u, TimeSpan t) { return new Speed(u.value / (float)t.NumericValue); } #endregion #region add dimension /// <summary> /// Multiplies a direction with a unit value, returning a typed vector of the given direction and length. /// </summary> public static Difference2 operator *(Unit u, Direction2 d) { return new Difference2(d.Vector * u.value); } /// <summary> /// Multiplies a direction with a unit value, returning a typed vector of the given direction and length. /// </summary> public static Difference2 operator *(Direction2 d, Unit u) { return new Difference2(d.Vector * u.value); } /// <summary> /// Multiplies a unit value with an untyped vector, returning a typed vector. /// </summary> public static Difference2 operator *(Unit u, Vector2 v) { return new Difference2(v * u.value); } /// <summary> /// Multiplies a unit value with an untyped vector, returning a typed vector. /// </summary> public static Difference2 operator *(Vector2 v, Unit u) { return new Difference2(v * u.value); } #endregion #region comparision /// <summary> /// Compares two unit values for equality. /// </summary> public static bool operator ==(Unit u0, Unit u1) { return u0.Equals(u1); } /// <summary> /// Compares two unit values for inequality. /// </summary> public static bool operator !=(Unit u0, Unit u1) { return !(u0 == u1); } /// <summary> /// Checks if one unit value is smaller than another. /// </summary> public static bool operator <(Unit u0, Unit u1) { return u0.value < u1.value; } /// <summary> /// Checks if one unit value is larger than another. /// </summary> public static bool operator >(Unit u0, Unit u1) { return u0.value > u1.value; } /// <summary> /// Checks if one unit value is smaller or equal to another. /// </summary> public static bool operator <=(Unit u0, Unit u1) { return u0.value <= u1.value; } /// <summary> /// Checks if one unit value is larger or equal to another. /// </summary> public static bool operator >=(Unit u0, Unit u1) { return u0.value >= u1.value; } #endregion #endregion } }
mit
pegurnee-edu/cosc211-fa16
source_code/src/edu/emich/cosc211/lab2/EmichPerson.java
526
package edu.emich.cosc211.lab2; /** * Contains information about a given emich person. Base class for both Teacher and Student. * * @author eddie gurnee * */ public class EmichPerson { private static int currentId = 1; private String eid; private String name; public EmichPerson(String name) { this.name = name; this.eid = "E" + String.format("%08d", EmichPerson.currentId); EmichPerson.currentId++; } public String getEid() { return this.eid; } public String getName() { return this.name; } }
mit
therightsol/myshopping
application/models/Setting.php
282
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class Setting extends My_Model{ const DB_TablePK = 'id'; const DB_TableName = "settings"; public $key = ""; public $value = ''; public $createdAt = null; public $updatedAt = null; }
mit
micheljansen/locomotive
app/controllers/plugin_properties.rb
2173
module Locomotive class PluginProperties < Locomotive::Application # GET /plugin_properties # GET /plugin_properties.xml def index @plugin_properties = Locomotive::PluginProperty.all display @plugin_properties end # GET /plugin_properties/1 # GET /plugin_properties/1.xml def show(id) @plugin_property = Locomotive::PluginProperty.get(id) raise NotFound unless @plugin_property display @plugin_property end # GET /plugin_properties/new def new only_provides :html @plugin_property = Locomotive::PluginProperty.new display @plugin_property end # GET /plugin_properties/1/edit def edit(id) only_provides :html @plugin_property = Locomotive::PluginProperty.get(id) raise NotFound unless @plugin_property display @plugin_property end # POST /plugin_properties # POST /plugin_properties.xml def create(plugin_property) @plugin_property = Locomotive::PluginProperty.new(plugin_property) if @plugin_property.save redirect resource(@plugin_property), :message => {:notice => "Plugin property was successfully created"} else render :new end end # PUT /plugin_properties/1 # PUT /plugin_properties/1.xml def update(id, plugin_property) @plugin_property = Locomotive::PluginProperty.get(id) raise NotFound unless @plugin_property if @plugin_property.update_attributes(plugin_property) redirect resource(@plugin_property), :message => {:notice => "Plugin property was successfully updated"} else render :edit end end def delete(id) @plugin_property = Locomotive::PluginProperty.get(id) raise NotFound unless @plugin_property display @plugin_property end # DELETE /plugin_properties/1 # DELETE /plugin_properties/1.xml def destroy(id) @plugin_property = Locomotive::PluginProperty.get(id) raise NotFound unless @plugin_property if @plugin_property.destroy redirect resource(:plugin_instances) else raise InternalServerError end end end end
mit
retailcrm/api-client-php
src/Model/Entity/Integration/Currency.php
739
<?php /** * PHP version 7.3 * * @category Currency * @package RetailCrm\Api\Model\Entity\Integration */ namespace RetailCrm\Api\Model\Entity\Integration; use RetailCrm\Api\Component\Serializer\Annotation as JMS; /** * Class Currency * * @category IntegrationModuleEditInfo * @package RetailCrm\Api\Model\Entity\Integration */ class Currency { /** * @var string * * @JMS\Type("string") * @JMS\SerializedName("name") */ public $name; /** * @var string * * @JMS\Type("string") * @JMS\SerializedName("shortName") */ public $shortName; /** * @var string * * @JMS\Type("string") * @JMS\SerializedName("code") */ public $code; }
mit
Alec-WAM/CrystalMod
src/main/java/alec_wam/CrystalMod/tiles/chest/CrystalChestType.java
7880
package alec_wam.CrystalMod.tiles.chest; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import alec_wam.CrystalMod.items.ItemIngot.IngotType; import alec_wam.CrystalMod.items.ModItems; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.Slot; import net.minecraft.item.ItemStack; import net.minecraft.util.IStringSerializable; import net.minecraftforge.fml.common.registry.GameRegistry; import net.minecraftforge.oredict.ShapedOreRecipe; public enum CrystalChestType implements IStringSerializable { BLUE(54, 9, true, "Blue Crystal Chest", "bluechest.png", 0, Arrays.asList("ingotBlue"), TileEntityBlueCrystalChest.class, "mmmmCmmmm"), RED(72, 9, true, "Red Crystal Chest", "redchest.png", 1, Arrays.asList("ingotRed"), TileEntityRedCrystalChest.class, "mmmm0mmmm"), GREEN(81, 9, true, "Green Crystal Chest", "greenchest.png", 2, Arrays.asList("ingotGreen"), TileEntityGreenCrystalChest.class, "mmmm1mmmm"), DARK(108, 12, true, "Dark Crystal Chest", "darkchest.png", 3, Arrays.asList("ingotDark"), TileEntityDarkCrystalChest.class, "mmmm2mmmm"), PURE(108, 12, true, "Pure Crystal Chest", "purechest.png", 4, Arrays.asList("ingotPure"), TileEntityPureCrystalChest.class, "mmmm3mmmm"), DARKIRON(45, 9, false, "Dark Iron Chest", "dironchest.png", 5, Arrays.asList("ingotDarkIron"), TileEntityDarkIronChest.class, "mmmmCmmmm"); public int size; private int rowLength; public String friendlyName; private boolean tieredChest; private String modelTexture; private int textureRow; public Class<? extends TileEntityBlueCrystalChest> clazz; private String[] recipes; private ArrayList<String> matList; CrystalChestType(int size, int rowLength, boolean tieredChest, String friendlyName, String modelTexture, int textureRow, List<String> mats, Class<? extends TileEntityBlueCrystalChest> clazz, String... recipes) { this.size = size; this.rowLength = rowLength; this.tieredChest = tieredChest; this.friendlyName = friendlyName; this.modelTexture = modelTexture; this.textureRow = textureRow; this.clazz = clazz; this.recipes = recipes; this.matList = new ArrayList<String>(); matList.addAll(mats); } @Override public String getName() { return name().toLowerCase(); } public String getModelTexture() { return modelTexture; } public int getTextureRow() { return textureRow; } public static TileEntityBlueCrystalChest makeEntity(int metadata) { // Compatibility int chesttype = validateMeta(metadata); if (chesttype == metadata) { try { TileEntityBlueCrystalChest te = values()[chesttype].clazz.newInstance(); return te; } catch (InstantiationException e) { // unpossible e.printStackTrace(); } catch (IllegalAccessException e) { // unpossible e.printStackTrace(); } } return null; } public static void registerBlocksAndRecipes(BlockCrystalChest blockResult) { Object previous = "chestWood"; for (CrystalChestType typ : values()) { generateRecipesForType(blockResult, previous, typ); ItemStack chest = new ItemStack(blockResult, 1, typ.ordinal()); if (typ.tieredChest) previous = chest; } } public static void generateRecipesForType(BlockCrystalChest blockResult, Object previousTier, CrystalChestType type) { for (String recipe : type.recipes) { String[] recipeSplit = new String[] { recipe.substring(0, 3), recipe.substring(3, 6), recipe.substring(6, 9) }; Object mainMaterial = null; for (String mat : type.matList) { mainMaterial = translateOreName(mat); ItemStack chestStack = new ItemStack(blockResult, 1, type.ordinal()); addRecipe(chestStack, recipeSplit, 'm', mainMaterial, 'P', previousTier, /* previous tier of chest */ 'G', "blockGlass", 'C', "chestWood", '0', new ItemStack(blockResult, 1, 0), /* Blue Chest */ '1', new ItemStack(blockResult, 1, 1), /* Red Chest */ '2', new ItemStack(blockResult, 1, 2), /* Green Chest */ '3', new ItemStack(blockResult, 1, 3), /* Dark Chest */ '4', new ItemStack(blockResult, 1, 4) /* Pure Chest */ ); addRecipe(new ItemStack(ModItems.chestMinecart, 1, type.ordinal()), "C", "M", 'C', chestStack, 'M', Items.MINECART ); addRecipe(new ItemStack(ModItems.chestMinecart, 1, type.ordinal()), "III", "IMI", "III", 'I', mainMaterial, 'M', getPreviousMinecart(type) /* previous tier of minecart */ ); } } } public static Object getPreviousMinecart(CrystalChestType type){ if(type == CrystalChestType.BLUE || !type.tieredChest){ return Items.CHEST_MINECART; } return new ItemStack(ModItems.chestMinecart, 1, type.ordinal()-1); } public static Object translateOreName(String mat) { if(mat.equalsIgnoreCase("ingotBlue")){ return new ItemStack(ModItems.ingots, 1, IngotType.BLUE.getMeta()); } else if(mat.equalsIgnoreCase("ingotRed")){ return new ItemStack(ModItems.ingots, 1, IngotType.RED.getMeta()); } else if(mat.equalsIgnoreCase("ingotGreen")){ return new ItemStack(ModItems.ingots, 1, IngotType.GREEN.getMeta()); } else if(mat.equalsIgnoreCase("ingotDark")){ return new ItemStack(ModItems.ingots, 1, IngotType.DARK.getMeta()); } else if(mat.equalsIgnoreCase("ingotPure")){ return new ItemStack(ModItems.ingots, 1, IngotType.PURE.getMeta()); } else if(mat.equalsIgnoreCase("ingotDarkIron")){ return new ItemStack(ModItems.ingots, 1, IngotType.DARK_IRON.getMeta()); } else if (mat.equals("obsidian")) { return Blocks.OBSIDIAN; } else if (mat.equals("dirt")) { return Blocks.DIRT; } return mat; } public static void addRecipe(ItemStack is, Object... parts) { ShapedOreRecipe oreRecipe = new ShapedOreRecipe(is, parts); GameRegistry.addRecipe(oreRecipe); } public int getRowCount() { return size / rowLength; } public int getRowLength() { return rowLength; } public boolean isTransparent() { return this == PURE; } public List<String> getMatList() { return matList; } public static int validateMeta(int i) { if (i < values().length && values()[i].size > 0) { return i; } else { return 0; } } public boolean isValidForCreativeMode() { return validateMeta(ordinal()) == ordinal(); } public boolean isExplosionResistant() { return this == PURE; } public Slot makeSlot(IInventory chestInventory, int index, int x, int y) { return new Slot(chestInventory, index, x, y); } }
mit
garywong89/food-hub
config/application.rb
1260
require File.expand_path('../boot', __FILE__) require "rails" # Pick the frameworks you want: require "active_model/railtie" require "active_job/railtie" # require "active_record/railtie" require "action_controller/railtie" require "action_mailer/railtie" require "action_view/railtie" require "sprockets/railtie" require "rails/test_unit/railtie" # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(*Rails.groups) module FoodHub class Application < Rails::Application # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC. # config.time_zone = 'Central Time (US & Canada)' # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s] # config.i18n.default_locale = :de end end
mit
yogeshsaroya/new-cdnjs
ajax/libs/openlayers/2.11/lib/OpenLayers/Layer/HTTPRequest.min.js
129
version https://git-lfs.github.com/spec/v1 oid sha256:65b14568f3b8ee7923d45684544723fff0400798e6c372df8f3613328c28aa55 size 1517
mit
SuperJMN/OmniXAML
OmniXaml.Tests/Model/TextWrapping.cs
108
namespace OmniXaml.Tests.Model { public enum TextWrapping { Wrap, NoWrap, } }
mit
mdub/console_logger
test/test_helper.rb
107
require "minitest/autorun" require "minitest/pride" $LOAD_PATH << File.expand_path("../../lib", __FILE__)
mit
ninjablocks/ninja-sentinel
yeoman/test/spec/controllers/history.js
487
'use strict'; describe('Controller: HistoryCtrl', function() { // load the controller's module beforeEach(module('yeomanApp')); var HistoryCtrl, scope; // Initialize the controller and a mock scope beforeEach(inject(function($controller) { scope = {}; HistoryCtrl = $controller('HistoryCtrl', { $scope: scope }); })); it('should attach a list of awesomeThings to the scope', function() { expect(scope.awesomeThings.length).toBe(3); }); });
mit
AntoineToubhans/trellearn
main.py
389
#!/usr/bin/env python import sys import src.json_importing as I import src.data_training as T import src.data_cross_validation as V import src.extract_feature_multilabel as EML if __name__ == '__main__': print('Hello, I am Trellearn') jsonFileName = sys.argv[1] cards = I.parseJSON(jsonFileName) X, Y, cv, mlb = EML.extract(cards) V.validateML(X, Y) exit(0)
mit
bluebill1049/react-simple-animate
src/useAnimate.test.tsx
957
import * as React from 'react'; import useAnimate from './useAnimate'; import { mount } from 'enzyme'; import { act } from 'react-dom/test-utils'; let UseAnimate; describe('useAnimate', () => { let componentStyle; const TestHook = ({ callback }) => { const { style } = callback(); componentStyle = style; return <div style={style}>errors</div>; }; const TestComponent = callback => { mount(<TestHook callback={callback} />); }; beforeEach(() => { TestComponent(() => { UseAnimate = useAnimate({ end: { opacity: 1 } }); return UseAnimate; }); jest.resetAllMocks(); }); it('should toggle style correctly', () => { act(() => { expect(UseAnimate.play(true)).toBeUndefined(); expect(componentStyle).toEqual({ transition: 'all 0.3s linear 0s', }); }); expect(componentStyle).toEqual({ opacity: 1, transition: 'all 0.3s linear 0s', }); }); });
mit
GWTReact/gwt-react
src/gwt/react/client/api/ReactDOM.java
3159
package gwt.react.client.api; /* The MIT License (MIT) Copyright (c) 2016 GWT React 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. */ import gwt.interop.utils.shared.functional.JsRunnable; import gwt.react.client.elements.ReactElement; import jsinterop.annotations.JsPackage; import jsinterop.annotations.JsType; @JsType(isNative = true, namespace = JsPackage.GLOBAL) public class ReactDOM { /** * This is a static class. */ private ReactDOM() { } /** * <p>Render a ReactElement&lt;?, ?&gt; into the DOM in the supplied container and return a reference to * the component (or returns nothing for stateless components).</p> * * <p>If the ReactElement&lt;?, ?&gt; was previously rendered into container, this will perform an update * on it and only mutate the DOM as necessary to reflect the latest React component.</p> * * <p>If the optional callback is provided, it will be executed after the component is rendered * or updated.</p> * * @param element the react element to render * @param container the DOM container to render into * @return a reference to the component or returns nothing for stateless components */ public static native <C> ReactElement render(ReactElement element, C container); public static native <C> ReactElement render(ReactElement element, C container, JsRunnable onUpdate); /** * Render children into a DOM node that exists outside the DOM hierarchy of the parent component * @param element * @param container * @param <C> * @return */ public static native <C> ReactElement createPortal(ReactElement element, C container); public static native <C> ReactElement createPortal(String element, C container); /** * Remove a mounted React component from the DOM and clean up its event handlers and state. If * no component was mounted in the container, calling this function does nothing. * * @param container the DOM container containing the react component to unmount * @return <code>true</code> if the the component was unmounted */ public static native <C> boolean unmountComponentAtNode(C container); }
mit
Gozala/fs-reduce
test/exists.js
2067
"use strict"; var fs = require("fs") var exists = require("../exists") var fixtures = require("./fixtures") var fold = require("reducers/fold") var capture = require("reducers/capture") exports["test async dir exists"] = function(assert, done) { var async = false var actual = exists(fixtures.join(".")) fold(actual, function(actual) { assert.ok(true, "directory exists") assert.ok(async, "operation should be async") done() }) async = true } exports["test sync dir exists"] = function(assert, done) { var async = false var actual = exists(fixtures.join("."), { sync: true }) fold(actual, function(actual) { assert.ok(true, "directory exists") assert.ok(!async, "operation should be sync") done() }) async = true } exports["test async file exists"] = function(assert, done) { var async = false var actual = exists(fixtures.join("elipses.txt")) fold(actual, function(actual) { assert.ok(true, "file exists") assert.ok(async, "operation should be async") done() }) async = true } exports["test sync file exists"] = function(assert, done) { var async = false var actual = exists(fixtures.join("elipses.txt"), { sync: true }) fold(actual, function(actual) { assert.ok(true, "file exists") assert.ok(!async, "operation should be sync") done() }) async = true } exports["test async does not exists"] = function(assert, done) { var async = false var actual = exists(fixtures.join("does-not-exists")) fold(actual, function(actual) { assert.equal(actual, false, "directory does not exists") assert.ok(async, "operation should be async") done() }) async = true } exports["test sync does not exists"] = function(assert, done) { var async = false var actual = exists(fixtures.join("does-not-exists"), { sync: true }) fold(actual, function(actual) { assert.equal(actual, false, "directory does not exists") assert.ok(!async, "operation should be sync") done() }) async = true } if (module == require.main) require("test").run(exports)
mit
rosmantorres/GitHubProject
lib/model/doctrine/Trabajo.class.php
2027
<?php /** * Trabajo * * This class has been auto-generated by the Doctrine ORM Framework * * @package PROYECTO_PRUEBA * @subpackage model * @author ROSMAN_TORRES * @version SVN: $Id: Builder.php 7490 2010-03-29 19:53:27Z jwage $ */ class Trabajo extends BaseTrabajo { /* * Cuando necesitas hacer algo automáticamente antes que un objeto Doctrine * sea guardado en la base de datos, puedes sobreescribir el método save() * de la clase del modelo: */ public function save(Doctrine_Connection $conn = null) { // El método isNew() devuelve true cuando el objeto no ha sido serializado // aún en la base de datos, if ($this->isNew() && !$this->getExpiraEl()) { $now = $this->getCreatedAt() ? $this->getDateTimeObject('created_at')->format('U') : time(); $this->setExpiraEl(date('Y-m-d H:i:s', $now + 86400 * sfConfig::get('app_dias_activo'))); } if (!$this->getToken()) { $this->setToken(sha1($this->getCorreo() . rand(11111, 99999))); } return parent::save($conn); } /* * "Slugeando" valores de columnas mediante la sustitución de todos los * caracteres no ASCII por un -. */ public function getCompaniaSlug() { return Jobeet::slugear($this->getCompania()); } public function getPosicionSlug() { return Jobeet::slugear($this->getPosicion()); } public function getLocalizacionSlug() { return Jobeet::slugear($this->getLocalizacion()); } public function getTypeName() { $types = Doctrine_Core::getTable('Tipo')->getTypes(); return $this->getType() ? $types[$this->getType()] : ''; } public function isExpired() { return $this->getDaysBeforeExpires() < 0; } public function expiresSoon() { return $this->getDaysBeforeExpires() < 5; } public function getDaysBeforeExpires() { return ceil(($this->getDateTimeObject('expira_el')->format('U') - time()) / 86400); } }
mit
cloudtek/dynamodb-odm
lib/Cloudtek/DynamoDM/Expression/Condition/Operator/Between.php
3131
<?php namespace Cloudtek\DynamoDM\Expression\Condition\Operator; use Cloudtek\DynamoDM\Expression\Condition\Condition; use Cloudtek\DynamoDM\Expression\Operand\OperandInterface; use Cloudtek\DynamoDM\Expression\Operand\Value; use Cloudtek\DynamoDM\Schema\Index\CompositeIndex; use Cloudtek\DynamoDM\Schema\Index\Index; /** * Expression class for the BETWEEN operator. * * @author Aaron Miller <aaronm@cldtk.com> */ class Between extends Operator { /** * @var string */ const _STRING = '%s BETWEEN %s AND %s'; /** * @var OperandInterface */ private $maximum; /** * @var OperandInterface */ private $minimum; /** * @var OperandInterface */ private $value; /** * Create a BETWEEN comparison with the given arguments. * * @param OperandInterface $value * @param OperandInterface $minimum * @param OperandInterface $maximum */ public function __construct(OperandInterface $value, OperandInterface $minimum, OperandInterface $maximum) { $this->value = $value; $this->minimum = $minimum; $this->maximum = $maximum; $this->doMapping(); } /** * {@inheritdoc} */ protected function doMapping() { $operands = [$this->value, $this->minimum, $this->maximum]; list($mappings, $values) = $this->getMappingsAndValues($operands); if (count($mappings) > 0) { $this->validateMappings($mappings, false); /** @var Value $value */ foreach ($values as $value) { $value->setMapping($mappings[0]); //mappings are compatible, just grab the first } } } /** * {@inheritdoc} */ public function getAttributes() { return array_merge( $this->value->getAttributes(), $this->minimum->getAttributes(), $this->maximum->getAttributes() ); } /** * {@inheritdoc} */ public function getExpression() { return sprintf( self::_STRING, $this->value->getExpression(), $this->minimum->getExpression(), $this->maximum->getExpression() ); } /** * {@inheritdoc} */ public function getHashKeyCondition(Index $index) { return null; } /** * {@inheritdoc} */ public function getRangeKeyCondition(CompositeIndex $index, $requireEquality = false) { //TODO: implement } /** * {@inheritdoc} */ public function getTokens() { return array_merge( $this->value->getTokens(), $this->minimum->getTokens(), $this->maximum->getTokens() ); } /** * {@inheritdoc} */ public function isEquivalent(Condition $condition) { return $condition instanceof self && $this->value->isEquivalent($condition->value) && $this->minimum->isEquivalent($condition->minimum) && $this->maximum->isEquivalent($condition->maximum); } }
mit
vmateixeira/vframework-commons
src/test/java/com/vframework/commons/util/DateUtilsTest.java
71
package com.vframework.commons.util; public class DateUtilsTest { }
mit
jugstalt/gViewGisOS
gView.Plugins.Tools/Plugins/ExTools/Dialogs/FormDeleteExObjects.Designer.cs
6580
namespace gView.Plugins.ExTools.Dialogs { partial class FormDeleteExObjects { /// <summary> /// Erforderliche Designervariable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Verwendete Ressourcen bereinigen. /// </summary> /// <param name="disposing">True, wenn verwaltete Ressourcen gelöscht werden sollen; andernfalls False.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Vom Windows Form-Designer generierter Code /// <summary> /// Erforderliche Methode für die Designerunterstützung. /// Der Inhalt der Methode darf nicht mit dem Code-Editor geändert werden. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FormDeleteExObjects)); this.panel1 = new System.Windows.Forms.Panel(); this.label1 = new System.Windows.Forms.Label(); this.panel2 = new System.Windows.Forms.Panel(); this.panel3 = new System.Windows.Forms.Panel(); this.btnOk = new System.Windows.Forms.Button(); this.btnCancel = new System.Windows.Forms.Button(); this.lstObjects = new System.Windows.Forms.ListView(); this.IL = new System.Windows.Forms.ImageList(this.components); this.panel1.SuspendLayout(); this.panel2.SuspendLayout(); this.panel3.SuspendLayout(); this.SuspendLayout(); // // panel1 // this.panel1.AccessibleDescription = null; this.panel1.AccessibleName = null; resources.ApplyResources(this.panel1, "panel1"); this.panel1.BackgroundImage = null; this.panel1.Controls.Add(this.label1); this.panel1.Font = null; this.panel1.Name = "panel1"; // // label1 // this.label1.AccessibleDescription = null; this.label1.AccessibleName = null; resources.ApplyResources(this.label1, "label1"); this.label1.Font = null; this.label1.Name = "label1"; // // panel2 // this.panel2.AccessibleDescription = null; this.panel2.AccessibleName = null; resources.ApplyResources(this.panel2, "panel2"); this.panel2.BackgroundImage = null; this.panel2.Controls.Add(this.panel3); this.panel2.Controls.Add(this.btnCancel); this.panel2.Font = null; this.panel2.Name = "panel2"; // // panel3 // this.panel3.AccessibleDescription = null; this.panel3.AccessibleName = null; resources.ApplyResources(this.panel3, "panel3"); this.panel3.BackgroundImage = null; this.panel3.Controls.Add(this.btnOk); this.panel3.Font = null; this.panel3.Name = "panel3"; // // btnOk // this.btnOk.AccessibleDescription = null; this.btnOk.AccessibleName = null; resources.ApplyResources(this.btnOk, "btnOk"); this.btnOk.BackgroundImage = null; this.btnOk.DialogResult = System.Windows.Forms.DialogResult.OK; this.btnOk.Font = null; this.btnOk.Name = "btnOk"; this.btnOk.UseVisualStyleBackColor = true; // // btnCancel // this.btnCancel.AccessibleDescription = null; this.btnCancel.AccessibleName = null; resources.ApplyResources(this.btnCancel, "btnCancel"); this.btnCancel.BackgroundImage = null; this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.btnCancel.Font = null; this.btnCancel.Name = "btnCancel"; this.btnCancel.UseVisualStyleBackColor = true; // // lstObjects // this.lstObjects.AccessibleDescription = null; this.lstObjects.AccessibleName = null; resources.ApplyResources(this.lstObjects, "lstObjects"); this.lstObjects.BackgroundImage = null; this.lstObjects.CheckBoxes = true; this.lstObjects.Font = null; this.lstObjects.Name = "lstObjects"; this.lstObjects.SmallImageList = this.IL; this.lstObjects.UseCompatibleStateImageBehavior = false; this.lstObjects.View = System.Windows.Forms.View.List; // // IL // this.IL.ColorDepth = System.Windows.Forms.ColorDepth.Depth8Bit; resources.ApplyResources(this.IL, "IL"); this.IL.TransparentColor = System.Drawing.Color.Transparent; // // FormDeleteExObjects // this.AccessibleDescription = null; this.AccessibleName = null; resources.ApplyResources(this, "$this"); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackgroundImage = null; this.Controls.Add(this.lstObjects); this.Controls.Add(this.panel2); this.Controls.Add(this.panel1); this.Font = null; this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.SizableToolWindow; this.Icon = null; this.Name = "FormDeleteExObjects"; this.panel1.ResumeLayout(false); this.panel1.PerformLayout(); this.panel2.ResumeLayout(false); this.panel3.ResumeLayout(false); this.ResumeLayout(false); } #endregion private System.Windows.Forms.Panel panel1; private System.Windows.Forms.Label label1; private System.Windows.Forms.Panel panel2; private System.Windows.Forms.Panel panel3; private System.Windows.Forms.Button btnOk; private System.Windows.Forms.Button btnCancel; private System.Windows.Forms.ListView lstObjects; private System.Windows.Forms.ImageList IL; } }
mit
Alec-WAM/CrystalMod
src/main/java/alec_wam/CrystalMod/tiles/tank/BlockTank.java
9331
package alec_wam.CrystalMod.tiles.tank; import java.util.List; import java.util.Locale; import alec_wam.CrystalMod.CrystalMod; import alec_wam.CrystalMod.blocks.EnumBlock; import alec_wam.CrystalMod.blocks.ICustomModel; import alec_wam.CrystalMod.blocks.ModBlocks; import alec_wam.CrystalMod.proxy.ClientProxy; import alec_wam.CrystalMod.util.BlockUtil; import alec_wam.CrystalMod.util.ItemStackTools; import alec_wam.CrystalMod.util.tool.ToolUtil; import net.minecraft.block.ITileEntityProvider; import net.minecraft.block.SoundType; import net.minecraft.block.material.Material; import net.minecraft.block.properties.PropertyEnum; import net.minecraft.block.state.IBlockState; import net.minecraft.client.renderer.block.model.ModelResourceLocation; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.BlockRenderLayer; import net.minecraft.util.EnumBlockRenderType; import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumHand; import net.minecraft.util.IStringSerializable; import net.minecraft.util.NonNullList; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.RayTraceResult; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; import net.minecraftforge.client.model.ModelLoader; import net.minecraftforge.fluids.FluidTank; import net.minecraftforge.fluids.FluidUtil; import net.minecraftforge.fluids.capability.IFluidHandlerItem; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; public class BlockTank extends EnumBlock<BlockTank.TankType> implements ITileEntityProvider, ICustomModel { public static final PropertyEnum<TankType> TYPE = PropertyEnum.<TankType>create("type", TankType.class); public static int[] tankCaps = new int[]{8, 16, 32, 64, 128, 1}; public BlockTank(){ super(Material.GLASS, TYPE, TankType.class); setSoundType(SoundType.GLASS); setHardness(2f).setResistance(20F); setLightOpacity(0); setCreativeTab(CrystalMod.tabBlocks); setDefaultState(this.blockState.getBaseState().withProperty(TYPE, TankType.BLUE)); } @Override @SideOnly(Side.CLIENT) public void initModel() { ModelResourceLocation inv = new ModelResourceLocation(getRegistryName(), "inventory"); ClientProxy.registerCustomModel(inv, ModelTank.INSTANCE); for(TankType type : TankType.values()){ ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(this), type.getMeta(), inv); ClientProxy.registerCustomModel(new ModelResourceLocation(getRegistryName(), "type="+type.getName()), ModelTank.INSTANCE); } } @SideOnly(Side.CLIENT) @Override public void getSubBlocks(Item item, CreativeTabs tab, NonNullList<ItemStack> list){ for(TankType type : TankType.values()){ list.add(new ItemStack(item, 1, type.getMeta())); } } @Override public IBlockState getExtendedState(final IBlockState state, final IBlockAccess world, final BlockPos pos) { TileEntity tile = world.getTileEntity(pos); return new FakeTankState(state, world, pos, (tile !=null && tile instanceof TileEntityTank) ? (TileEntityTank)tile : null); } @Override public boolean removedByPlayer(IBlockState state, World world, BlockPos pos, EntityPlayer player, boolean willHarvest) { if (willHarvest) { return true; } return super.removedByPlayer(state, world, pos, player, willHarvest); } @Override public void harvestBlock(World worldIn, EntityPlayer player, BlockPos pos, IBlockState state, TileEntity te, ItemStack stack) { super.harvestBlock(worldIn, player, pos, state, te, stack); worldIn.setBlockToAir(pos); } @Override public ItemStack getPickBlock(IBlockState state, RayTraceResult target, World world, BlockPos pos, EntityPlayer player) { if(world == null || pos == null)return super.getPickBlock(state, target, world, pos, player); ItemStack tank = new ItemStack(ModBlocks.crystalTank, 1, state.getValue(TYPE).getMeta()); TileEntity tile = world.getTileEntity(pos); if(tile !=null && tile instanceof TileEntityTank){ TileEntityTank tiletank = (TileEntityTank) tile; ItemBlockTank.saveTank(tank, tiletank.tank); } return tank; } @Override public List<ItemStack> getDrops(IBlockAccess world, BlockPos pos, IBlockState state, int fortune) { List<ItemStack> ret = new java.util.ArrayList<ItemStack>(); ItemStack tank = new ItemStack(ModBlocks.crystalTank, 1, state.getValue(TYPE).getMeta()); TileEntity tile = world.getTileEntity(pos); if(tile !=null && tile instanceof TileEntityTank){ TileEntityTank tiletank = (TileEntityTank) tile; ItemBlockTank.saveTank(tank, tiletank.tank); } ret.add(tank); return ret; } @Override public void onBlockPlacedBy(World world, BlockPos pos, IBlockState state, EntityLivingBase entity, ItemStack stack) { super.onBlockPlacedBy(world, pos, state, entity, stack); TileEntity tile = world.getTileEntity(pos); if(tile !=null && tile instanceof TileEntityTank){ TileEntityTank tank = (TileEntityTank) tile; FluidTank tankSaved = null; if(stack.hasTagCompound()){ NBTTagCompound nbt = stack.getTagCompound().copy(); tankSaved = ItemBlockTank.loadTank(nbt); } if(tankSaved !=null){ tank.tank.setFluid(tankSaved.getFluid()); BlockUtil.markBlockForUpdate(world, pos); } if(tank.creative){ BlockUtil.markBlockForUpdate(world, pos); } } } @Override public boolean isOpaqueCube(IBlockState state) { return false; } @Override public boolean isFullCube(IBlockState state) { return true; } @Override @SideOnly(Side.CLIENT) public boolean isTranslucent(IBlockState state) { return true; } @Override public boolean isSideSolid(IBlockState base_state, IBlockAccess world, BlockPos pos, EnumFacing side) { if(side.getAxis().isVertical())return true; return super.isSideSolid(base_state, world, pos, side); } @Override public boolean onBlockActivated(World world, BlockPos pos, IBlockState state, EntityPlayer entityplayer, EnumHand hand, EnumFacing side, float par7, float par8, float par9) { ItemStack current = entityplayer.getHeldItem(hand); TileEntity tile = world.getTileEntity(pos); if (tile instanceof TileEntityTank) { if (ItemStackTools.isValid(current)) { if(ToolUtil.isToolEquipped(entityplayer, hand)){ return ToolUtil.breakBlockWithTool(this, world, pos, entityplayer, hand); } IFluidHandlerItem containerFluidHandler = FluidUtil.getFluidHandler(current); if (containerFluidHandler != null) { if(FluidUtil.interactWithFluidHandler(entityplayer, hand, world, pos, side)){ return true; } } } } return false; } @Override public int getLightValue(IBlockState state, IBlockAccess world, BlockPos pos) { TileEntity tile = world.getTileEntity(pos); if (tile instanceof TileEntityTank) { TileEntityTank tank = (TileEntityTank) tile; return tank.getFluidLightLevel(); } return super.getLightValue(state, world, pos); } @Override public boolean hasComparatorInputOverride(IBlockState state) { return true; } @Override public int getComparatorInputOverride(IBlockState state, World world, BlockPos pos) { TileEntity tile = world.getTileEntity(pos); if (tile instanceof TileEntityTank) { TileEntityTank tank = (TileEntityTank) tile; return tank.getComparatorInputOverride(); } return 0; } @Override @SideOnly(Side.CLIENT) public BlockRenderLayer getBlockLayer() { return BlockRenderLayer.CUTOUT; } @Override @SideOnly(Side.CLIENT) public EnumBlockRenderType getRenderType(IBlockState state){ return EnumBlockRenderType.MODEL; } public static enum TankType implements IStringSerializable, alec_wam.CrystalMod.util.IEnumMeta{ BLUE, RED, GREEN, DARK, PURE, CREATIVE; final int meta; TankType(){ meta = ordinal(); } @Override public int getMeta() { return meta; } @Override public String getName() { return this.toString().toLowerCase(Locale.US); } } @Override public TileEntity createNewTileEntity(World world, int meta) { if(meta == 5){ return new TileEntityTank(tankCaps[5], true); } if(meta < tankCaps.length){ return new TileEntityTank(tankCaps[meta]); } return null; } }
mit
plotly/plotly.py
packages/python/plotly/plotly/validators/contour/_yperiod.py
469
import _plotly_utils.basevalidators class YperiodValidator(_plotly_utils.basevalidators.AnyValidator): def __init__(self, plotly_name="yperiod", parent_name="contour", **kwargs): super(YperiodValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "calc"), implied_edits=kwargs.pop("implied_edits", {"ytype": "scaled"}), **kwargs )
mit
51reboot/actual_09_homework
11/jinderui/cmdb/user/ssh.py
662
#coding:utf8 import paramiko import getpass def ssh_command(host,port,username,password,cmd): ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) try: ssh.connect(host,port,username,password) stdin,stdout,stderr = ssh.exec_command(cmd) if not stderr.read(): return stdout.read() else: return "command:%s error" %(cmd) except BaseException as e: print e return str(e) finally: ssh.close() if __name__ == '__main__': host = '192.168.192.75' port = 22 username = 'root' password = getpass.getpass('input you password: ') cmd = 'ifconfiga' print ssh_command(host,port,username,password,cmd)
mit
andyw8/reek
lib/reek/tree_walker.rb
5746
require_relative 'context/method_context' require_relative 'context/module_context' require_relative 'context/root_context' require_relative 'context/singleton_method_context' require_relative 'context/attribute_context' require_relative 'ast/node' module Reek # # Traverses an abstract syntax tree and fires events whenever it encounters # specific node types. # # SMELL: This class is responsible for counting statements and for feeding # each context to the smell repository. # # TODO: Make TreeWalker responsible only for creating Context objects, and # loop over the created set of contexts elsewhere. # # :reek:TooManyMethods: { max_methods: 29 } class TreeWalker def initialize(smell_repository, exp) @smell_repository = smell_repository @exp = exp @element = Context::RootContext.new(exp) @context_tree = process(exp) end def walk context_tree.each do |element| smell_repository.examine(element) end end private private_attr_accessor :element private_attr_reader :exp, :smell_repository, :context_tree # Processes the given AST, memoizes it and returns a tree of nested # contexts. # # For example this ruby code: # class Car; def drive; end; end # would get compiled into this AST: # (class # (const nil :Car) nil # (def :drive # (args) nil)) # Processing this AST would result in a context tree where each node # contains the outer context, the AST and the child contexts. The top # node is always Reek::Context::RootContext. Using the example above, # the tree would look like this: # # RootContext -> children: 1 ModuleContext -> children: 1 MethodContext # # @return [Reek::Context::RootContext] tree of nested contexts def process(exp) context_processor = "process_#{exp.type}" if context_processor_exists?(context_processor) send(context_processor, exp) else process_default exp end element end def process_module(exp) inside_new_context(Context::ModuleContext, exp) do process_default(exp) end end alias_method :process_class, :process_module def process_casgn(exp) if exp.defines_module? process_module(exp) else process_default(exp) end end def process_def(exp) inside_new_context(Context::MethodContext, exp) do count_clause(exp.body) process_default(exp) end end def process_defs(exp) inside_new_context(Context::SingletonMethodContext, exp) do count_clause(exp.body) process_default(exp) end end def process_default(exp) exp.children.each do |child| process(child) if child.is_a? AST::Node end end def process_args(_) end # :reek:TooManyStatements: { max_statements: 6 } # :reek:FeatureEnvy def process_send(exp) if exp.visibility_modifier? element.track_visibility(exp.method_name, exp.arg_names) end if exp.attribute_writer? exp.args.each do |arg| next unless arg.type == :sym new_context(Context::AttributeContext, arg, exp) end end element.record_call_to(exp) process_default(exp) end def process_attrasgn(exp) element.record_call_to(exp) process_default(exp) end alias_method :process_op_asgn, :process_attrasgn def process_ivar(exp) element.record_use_of_self process_default(exp) end alias_method :process_ivasgn, :process_ivar def process_self(_) element.record_use_of_self end alias_method :process_zsuper, :process_self # # Statement counting # def process_block(exp) count_clause(exp.block) process_default(exp) end def process_begin(exp) count_statement_list(exp.children) element.count_statements(-1) process_default(exp) end alias_method :process_kwbegin, :process_begin def process_if(exp) children = exp.children count_clause(children[1]) count_clause(children[2]) element.count_statements(-1) process_default(exp) end def process_while(exp) count_clause(exp.children[1]) element.count_statements(-1) process_default(exp) end alias_method :process_until, :process_while def process_for(exp) count_clause(exp.children[2]) element.count_statements(-1) process_default(exp) end def process_rescue(exp) count_clause(exp.children.first) element.count_statements(-1) process_default(exp) end def process_resbody(exp) count_statement_list(exp.children[1..-1].compact) process_default(exp) end def process_case(exp) count_clause(exp.else_body) element.count_statements(-1) process_default(exp) end def process_when(exp) count_clause(exp.body) process_default(exp) end def context_processor_exists?(name) self.class.private_method_defined?(name) end # :reek:ControlParameter def count_clause(sexp) element.count_statements(1) if sexp end def count_statement_list(statement_list) element.count_statements statement_list.length end def inside_new_context(klass, exp) push(new_context(klass, exp)) do yield end end def new_context(klass, *args) klass.new(element, *args).tap do |scope| element.append_child_context(scope) end end def push(scope) orig = element self.element = scope yield self.element = orig end end end
mit
sbalkum/HighIronRanch.Cqrs.EventStore.MongoDb
src/HighIronRanch.Cqrs.EventStore.MongoDb/MongoEventStore.cs
3865
using System; using System.Collections.Generic; using System.Linq; using MongoDB.Bson; using MongoDB.Bson.Serialization; using MongoDB.Driver; using MongoDB.Driver.Builders; using MongoDB.Driver.Linq; using SimpleCqrs.Eventing; namespace HighIronRanch.Cqrs.EventStore.MongoDb { public class MongoEventStore : IEventStore { private readonly string _connectionString; private readonly string _database; public MongoEventStore(IMongoEventStoreSettings settings) { _connectionString = settings.MongoDbEventStoreConnectionString; _database = settings.MongoDbEventStoreDatabase; BsonClassMap.RegisterClassMap<DomainEvent>(); var assemblies = AppDomain.CurrentDomain.GetAssemblies(); var domainEventSubclasses = new List<Type>(); foreach (var a in assemblies) { var types = a.GetTypes().Where(t => typeof (DomainEvent).IsAssignableFrom(t)); domainEventSubclasses.AddRange(types); } foreach (var subclass in domainEventSubclasses) { BsonClassMap.LookupClassMap(subclass); } } protected MongoDatabase GetDatabase() { var client = new MongoClient(_connectionString); return client.GetServer().GetDatabase(_database); } protected MongoCollection<DomainEvent> GetEventsCollection() { return GetDatabase().GetCollection<DomainEvent>("events"); } public IEnumerable<DomainEvent> GetEvents(Guid aggregateRootId, int startSequence) { return IOExceptionRetriable.Run(() => GetEventsCollection() .AsQueryable<DomainEvent>() .Where(e => e.AggregateRootId == aggregateRootId) .Where(e => e.Sequence >= startSequence) .ToList()); } public void Insert(IEnumerable<DomainEvent> domainEvents) { if (domainEvents.Any()) { IOExceptionRetriable.Run(() => GetEventsCollection().InsertBatch(domainEvents)); } } public IEnumerable<DomainEvent> GetEventsByEventTypes(IEnumerable<Type> domainEventTypes) { var array = domainEventTypes.Select(t => t.Name); var selector = Query.In("_t", new BsonArray(array)); return IOExceptionRetriable.Run(() => GetEventsCollection().Find(selector)); } public IEnumerable<DomainEvent> GetEventsByEventTypes(IEnumerable<Type> domainEventTypes, Guid aggregateRootId) { var selector = Query.And(Query.In("_t", new BsonArray(domainEventTypes.Select(t => t.Name))), Query.EQ("AggregateRootId", aggregateRootId)); return IOExceptionRetriable.Run(() => GetEventsCollection().Find(selector)); } public IEnumerable<DomainEvent> GetEventsByEventTypes(IEnumerable<Type> domainEventTypes, DateTime startDate, DateTime endDate) { var selector = Query.And(Query.In("_t", new BsonArray(domainEventTypes.Select(t => t.Name))), Query.GTE("EventDate", startDate), Query.LT("EventDate", endDate)); return IOExceptionRetriable.Run(() => GetEventsCollection().Find(selector)); } public void DeleteEventsByEventType(IEnumerable<Type> domainEventTypes) { var selector = Query.In("_t", new BsonArray(domainEventTypes.Select(t => t.Name))); IOExceptionRetriable.Run(() => GetEventsCollection().Remove(selector)); } public IEnumerable<Guid> GetAggregateRootIds(DateTime startTime, DateTime endTime) { var distinctIds = GetEventsCollection() .AsQueryable<DomainEvent>() .Where(e => e.EventDate >= startTime && e.EventDate < endTime) .Select(e => e.AggregateRootId) .Distinct(); return distinctIds; } public IOrderedQueryable<DomainEvent> GetEventsByAggregateRootId(Guid aggregateRootId) { var events = GetEventsCollection() .AsQueryable<DomainEvent>() .Where(e => e.AggregateRootId == aggregateRootId) .OrderBy(e => e.Sequence) .ThenBy(e => e.EventDate); return events; } } }
mit
mariuszs/txt2srt
library/src/main/java/net/sf/txt2srt/Subtitles.java
1128
package net.sf.txt2srt; import java.util.Collections; import java.util.Map; import java.util.TreeMap; public class Subtitles { private String sourceFormat; private String sourceFilePath; public Subtitles(String sourceType) { super(); this.sourceFormat = sourceType; } // maps start time in ms to single subtitle protected TreeMap<Long, Subtitle> subtitles = new TreeMap<Long, Subtitle>(); public void addSubtitle(long start, String text, long duration) { subtitles.put(start, new Subtitle(text, duration)); } public Map<Long, Subtitle> getSubtitles() { return Collections.unmodifiableMap(subtitles); } public int size() { return subtitles.size(); } @Override public String toString() { return subtitles.toString(); } public String getSourceFormat() { return sourceFormat; } public long getDuration() { return subtitles.get(subtitles.size() - 1).getDuration(); } public String getSourceFilePath() { return sourceFilePath; } public void setSourceFilePath(String sourceFilePath) { this.sourceFilePath = sourceFilePath; } }
mit
EmiiFont/SaveMe
SaveMe/SaveMeProject/MyScene.cs
4841
#region Using Statements using System; using SaveMeProject.Helpers; using WaveEngine.Common; using WaveEngine.Common.Graphics; using WaveEngine.Common.Math; using WaveEngine.Components.Animation; using WaveEngine.Components.Graphics2D; using WaveEngine.Components.Graphics3D; using WaveEngine.Framework; using WaveEngine.Framework.Graphics; using WaveEngine.Framework.Physics2D; using WaveEngine.Framework.Physics3D; using WaveEngine.Framework.Services; using WaveEngine.Materials; #endregion namespace SaveMeProject { public class MyScene : Scene { private const string GroundTexture = "Content/GroundSprite.wpk"; protected override void CreateScene() { RenderManager.BackgroundColor = Color.CornflowerBlue; EntityManager.Add(CreateGround("floor1", 0, WaveServices.Platform.ScreenHeight, 0)); EntityManager.Add(CreateGround("floor2", WaveServices.Platform.ScreenWidth / 2, WaveServices.Platform.ScreenHeight, 0)); EntityManager.Add(CreateGround("floor3", WaveServices.Platform.ScreenWidth, WaveServices.Platform.ScreenHeight, 0)); //EntityManager.Add(CreateSaver("people", WaveServices.Platform.ScreenWidth / 3, //WaveServices.Platform.ScreenHeight - 30)); EntityManager.Add(CreateRug("rug", WaveServices.Platform.ScreenWidth / 3, WaveServices.Platform.ScreenHeight - 100)); //EntityManager.Add(CreateVictim("viticm", WaveServices.Platform.ScreenWidth / 3, 0, 1f )); var instances = 0; //Timer to create crates WaveServices.TimerFactory.CreateTimer("FallingCratesTimer", TimeSpan.FromSeconds(3f), () => { var box = CreateVictim("Crate" + instances++, WaveServices.Platform.ScreenWidth/2, -10, 0.5f); EntityManager.Add(box); if (instances > 9) { EntityManager.Remove("Crate" + (instances - 10)); //WaveServices.TimerFactory.RemoveTimer("FallingCratesTimer"); } }); } /// <summary> /// This method creates the floor, with collisions, especifying the coordinates. /// </summary> /// <param name="name"></param> /// <param name="x"></param> /// <param name="y"></param> /// <param name="angle"></param> /// <returns></returns> private static Entity CreateGround(string name, float x, float y, float angle) { Entity sprite = new Entity(name) .AddComponent(new Transform2D() { X = x, Y = y }) .AddComponent(new RectangleCollider()) .AddComponent(new Sprite(GroundTexture)) .AddComponent(new RigidBody2D() { IsKinematic = true }) .AddComponent(new SpriteRenderer(DefaultLayers.Opaque)); sprite.FindComponent<RigidBody2D>().Rotation = angle; return sprite; } private static Entity CreateVictim(string name, float x = 0, float y = 0, float mass = 5f) { var victim = new Entity(name) .AddComponent(new Transform2D() {X = x, Y = y}) //.AddComponent(new Transform3D(){ Position = new Vector3(x,y,0)}) .AddComponent(new RectangleCollider()) .AddComponent(new Sprite("Content/Crate.wpk")) //.AddComponent(Model.CreateSphere()) .AddComponent(new RigidBody2D { IsKinematic = false, Mass = mass, Restitution = 1f, CollisionCategories = Physic2DCategory.All }) //.AddComponent(new MaterialsMap(new BasicMaterial(Color.Black))) .AddComponent(new SpriteRenderer(DefaultLayers.Alpha)); //.AddComponent(new ModelRenderer()); return victim; } private static Entity CreateRug(string name, float x = 0, float y = 0) { var rug = new Entity(name) .AddComponent(new Transform2D() { X = x, Y = y, XScale = 10, YScale = 1 }) .AddComponent(new RectangleCollider()) .AddComponent(new Sprite("Content/Wood.wpk")) .AddComponent(new RigidBody2D() { IsKinematic = true, CollisionCategories = Physic2DCategory.All, Mass = 1f }) .AddComponent(new SpriteRenderer(DefaultLayers.Alpha)) .AddComponent(new SaverBehavior()); return rug; } } }
mit
psiphp/content-type
src/Standard/Field/BirthdayField.php
961
<?php declare(strict_types=1); namespace Psi\Component\ContentType\Standard\Field; use Psi\Component\ContentType\FieldInterface; use Psi\Component\ContentType\OptionsResolver\FieldOptionsResolver; use Psi\Component\ContentType\Standard\Storage as Storage; use Psi\Component\ContentType\Standard\View as View; use Symfony\Component\Form\Extension\Core\Type as Form; class BirthdayField implements FieldInterface { public function getViewType(): string { return View\DateTimeType::class; } public function getFormType(): string { return Form\BirthdayType::class; } public function getStorageType(): string { return Storage\DateTimeType::class; } public function configureOptions(FieldOptionsResolver $resolver) { $resolver->setViewMapper(function ($options) { return array_merge([ 'time_format' => 'none', ], $options); }); } }
mit
Oktopost/Aquarium
tests/Aquarium/Resources/DefinitionStrategy/ClassMethodsTest.php
2439
<?php namespace Aquarium\Resources\DefinitionStrategy; use Aquarium\Resources\Package; use Aquarium\Resources\Utils\PackageBuilder; use Aquarium\Resources\Package\IPackageBuilder; class ClassMethodsTestHelper { public function Package_a_b(IPackageBuilder $b) { $b->script('a'); $b->style('b'); $b->package('n'); } public function Package_c_d(IPackageBuilder $b) { $b->script('a'); $b->style('b'); $b->package('n'); } public function Package_case_TEST(IPackageBuilder $b) { } } class ClassMethodsTest extends \PHPUnit_Framework_TestCase { public function setUp() { PackageBuilder::setTestMode(true); } public function test_has_Found() { $cm = new ClassMethods(ClassMethodsTestHelper::class); $this->assertTrue($cm->has('a/b')); $this->assertTrue($cm->has('c/d')); $this->assertFalse($cm->has('not/found')); } public function test_getNames() { $cm = new ClassMethods(ClassMethodsTestHelper::class); $result = $cm->getNames(); $this->assertCount(3, $result); $this->assertTrue(array_search('a/b', $result) !== false); $this->assertTrue(array_search('c/d', $result) !== false); $this->assertTrue(array_search('case/TEST', $result) !== false); } public function test_get_PackageReturned() { $cm = new ClassMethods(ClassMethodsTestHelper::class); $this->assertInstanceOf(Package::class, $cm->get('a/b')); } public function test_get_PackageDefinedCorrectly() { $cm = new ClassMethods(ClassMethodsTestHelper::class); $p = $cm->get('a/b'); $this->assertEquals(['a'], $p->Scripts->get()); $this->assertEquals(['b'], $p->Styles->get()); $this->assertEquals(['n'], $p->Requires->get()); } public function test_get_PackageCached() { $cm = new ClassMethods(ClassMethodsTestHelper::class); $this->assertSame($cm->get('a/b'), $cm->get('a/b')); } public function test_get_DifferentPackage() { $cm = new ClassMethods(ClassMethodsTestHelper::class); $this->assertNotSame($cm->get('c/d'), $cm->get('a/b')); } /** * @expectedException \Exception */ public function test_get_PackageNotFound_ErrorThrown() { $cm = new ClassMethods(ClassMethodsTestHelper::class); $cm->get('not/found'); } public function test_methodNameCaseTest() { $cm = new ClassMethods(ClassMethodsTestHelper::class); $this->assertTrue($cm->has('case/test')); $this->assertInstanceOf(Package::class, $cm->get('case/test')); } }
mit
moonlight2/stuff
src/Flash/Bundle/DefaultBundle/Form/EventType.php
1005
<?php namespace Flash\Bundle\DefaultBundle\Form; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolverInterface; class EventType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('name') ->add('description') ->add('city') ->add('country') ->add('isConfirmed') ->add('image') ; $builder->add('date', 'date', array( 'widget' => 'single_text', 'format' => 'dd-MM-yyyy hh:mm' )); } public function setDefaultOptions(OptionsResolverInterface $resolver) { $resolver->setDefaults(array( 'data_class' => 'Flash\Bundle\DefaultBundle\Entity\Event', 'csrf_protection' => false, )); } public function getName() { return 'event'; } }
mit
arjanfrans/realtime-multiplayer-in-html5
server/Client.js
1074
'use strict'; const uuid = require('node-uuid'); function Client ({ socket, name }) { const id = uuid.v4(); let currentRoom = null; function emit (event, data) { socket.emit(event, data); } function on (event, listener) { socket.on(event, listener); } function send (message) { socket.send(message); } function setCurrentRoom (room) { currentRoom = room; } function getCurrentRoom () { return currentRoom; } function isInRoom () { return currentRoom ? true : false; } function getName () { return name; } function getId () { return id; } function toJSON () { return { currentRoom: currentRoom ? currentRoom.toJSON() : null, id, name }; } return Object.freeze({ getId, getName, getCurrentRoom, isInRoom, emit, on, send, setCurrentRoom, toJSON }); } module.exports = { create: Client };
mit
anchorchat/anchor-ui
src/modal/get-styles.js
602
import styles from './styles'; import combineStyles from '../internal/combine-styles'; import colors from '../settings/colors'; const root = overrideStyle => combineStyles(styles.root, overrideStyle); const content = overrideStyle => combineStyles(styles.content, overrideStyle); const footer = (color = colors.theme, overrideStyle) => { const style = combineStyles(styles.footer, { backgroundColor: color }); return combineStyles(style, overrideStyle); }; const header = overrideStyle => combineStyles(styles.header, overrideStyle); export default { root, header, content, footer };
mit
ministryofjustice/wmt-web
test/integration/services/data/test-get-reduction-by-id.js
2070
const expect = require('chai').expect const moment = require('moment') const getReductionById = require('../../../../app/services/data/get-reduction-by-id') const insertReduction = require('../../../../app/services/data/insert-reduction') const Reduction = require('../../../../app/services/domain/reduction') const dataHelper = require('../../../helpers/data/aggregated-data-helper') const reductionResult = { table: 'reductions', id: 0 } const reductionReason = { maxAllowanceHours: 0 } const activeStartDate = moment().subtract(30, 'days').toDate() const activeEndDate = moment().add(30, 'days').toDate() const testReduction = new Reduction('1', '5', [activeStartDate.getDate(), activeStartDate.getMonth() + 1, activeStartDate.getFullYear()], [activeEndDate.getDate(), activeEndDate.getMonth() + 1, activeEndDate.getFullYear()], 'Test Note', reductionReason) let workloadOwnerId let addedReductionId let inserts = [] describe('/services/data/get-reduction-by-id', function () { before(function () { return dataHelper.addWorkloadCapacitiesForOffenderManager() .then(function (result) { inserts = result return dataHelper.getAnyExistingWorkloadOwnerId() .then(function (id) { workloadOwnerId = id return dataHelper.getAnyExistingReductionReasonId() .then(function (id) { testReduction.reasonForReductionId = id return insertReduction(workloadOwnerId, testReduction) .then(function (reductionId) { addedReductionId = reductionId[0] }) }) }) }) }) it('should get reduction by id', function () { return getReductionById(addedReductionId) .then(function (result) { // Store the id so that we can delete it after the test is complete reductionResult.id = result.id expect(result.id).to.be.a('number') }) }) after(function () { inserts.push(reductionResult) return dataHelper.removeInsertedData(inserts) }) })
mit
cscfa/bartleby
library/logBack/logback-1.1.3/logback-classic/src/main/java/ch/qos/logback/classic/db/DBAppender.java
10733
/** * Logback: the reliable, generic, fast and flexible logging framework. * Copyright (C) 1999-2015, QOS.ch. All rights reserved. * * This program and the accompanying materials are dual-licensed under * either the terms of the Eclipse Public License v1.0 as published by * the Eclipse Foundation * * or (per the licensee's choosing) * * under the terms of the GNU Lesser General Public License version 2.1 * as published by the Free Software Foundation. */ package ch.qos.logback.classic.db; import static ch.qos.logback.core.db.DBHelper.closeStatement; import java.lang.reflect.Method; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.HashMap; import java.util.Map; import java.util.Set; import ch.qos.logback.classic.db.names.DBNameResolver; import ch.qos.logback.classic.db.names.DefaultDBNameResolver; import ch.qos.logback.classic.spi.*; import ch.qos.logback.core.CoreConstants; import ch.qos.logback.core.db.DBAppenderBase; /** * The DBAppender inserts logging events into three database tables in a format * independent of the Java programming language. * * For more information about this appender, please refer to the online manual * at http://logback.qos.ch/manual/appenders.html#DBAppender * * @author Ceki G&uuml;lc&uuml; * @author Ray DeCampo * @author S&eacute;bastien Pennec */ public class DBAppender extends DBAppenderBase<ILoggingEvent> { protected String insertPropertiesSQL; protected String insertExceptionSQL; protected String insertSQL; protected static final Method GET_GENERATED_KEYS_METHOD; private DBNameResolver dbNameResolver; static final int TIMESTMP_INDEX = 1; static final int FORMATTED_MESSAGE_INDEX = 2; static final int LOGGER_NAME_INDEX = 3; static final int LEVEL_STRING_INDEX = 4; static final int THREAD_NAME_INDEX = 5; static final int REFERENCE_FLAG_INDEX = 6; static final int ARG0_INDEX = 7; static final int ARG1_INDEX = 8; static final int ARG2_INDEX = 9; static final int ARG3_INDEX = 10; static final int CALLER_FILENAME_INDEX = 11; static final int CALLER_CLASS_INDEX = 12; static final int CALLER_METHOD_INDEX = 13; static final int CALLER_LINE_INDEX = 14; static final int EVENT_ID_INDEX = 15; static final StackTraceElement EMPTY_CALLER_DATA = CallerData.naInstance(); static { // PreparedStatement.getGeneratedKeys() method was added in JDK 1.4 Method getGeneratedKeysMethod; try { // the getGeneratedKeysMethod = PreparedStatement.class.getMethod( "getGeneratedKeys", (Class[]) null); } catch (Exception ex) { getGeneratedKeysMethod = null; } GET_GENERATED_KEYS_METHOD = getGeneratedKeysMethod; } public void setDbNameResolver(DBNameResolver dbNameResolver) { this.dbNameResolver = dbNameResolver; } @Override public void start() { if (dbNameResolver == null) dbNameResolver = new DefaultDBNameResolver(); insertExceptionSQL = SQLBuilder.buildInsertExceptionSQL(dbNameResolver); insertPropertiesSQL = SQLBuilder.buildInsertPropertiesSQL(dbNameResolver); insertSQL = SQLBuilder.buildInsertSQL(dbNameResolver); super.start(); } @Override protected void subAppend(ILoggingEvent event, Connection connection, PreparedStatement insertStatement) throws Throwable { bindLoggingEventWithInsertStatement(insertStatement, event); bindLoggingEventArgumentsWithPreparedStatement(insertStatement, event.getArgumentArray()); // This is expensive... should we do it every time? bindCallerDataWithPreparedStatement(insertStatement, event.getCallerData()); int updateCount = insertStatement.executeUpdate(); if (updateCount != 1) { addWarn("Failed to insert loggingEvent"); } } protected void secondarySubAppend(ILoggingEvent event, Connection connection, long eventId) throws Throwable { Map<String, String> mergedMap = mergePropertyMaps(event); insertProperties(mergedMap, connection, eventId); if (event.getThrowableProxy() != null) { insertThrowable(event.getThrowableProxy(), connection, eventId); } } void bindLoggingEventWithInsertStatement(PreparedStatement stmt, ILoggingEvent event) throws SQLException { stmt.setLong(TIMESTMP_INDEX, event.getTimeStamp()); stmt.setString(FORMATTED_MESSAGE_INDEX, event.getFormattedMessage()); stmt.setString(LOGGER_NAME_INDEX, event.getLoggerName()); stmt.setString(LEVEL_STRING_INDEX, event.getLevel().toString()); stmt.setString(THREAD_NAME_INDEX, event.getThreadName()); stmt.setShort(REFERENCE_FLAG_INDEX, DBHelper.computeReferenceMask(event)); } void bindLoggingEventArgumentsWithPreparedStatement(PreparedStatement stmt, Object[] argArray) throws SQLException { int arrayLen = argArray != null ? argArray.length : 0; for(int i = 0; i < arrayLen && i < 4; i++) { stmt.setString(ARG0_INDEX+i, asStringTruncatedTo254(argArray[i])); } if(arrayLen < 4) { for(int i = arrayLen; i < 4; i++) { stmt.setString(ARG0_INDEX+i, null); } } } String asStringTruncatedTo254(Object o) { String s = null; if(o != null) { s= o.toString(); } if(s == null) { return null; } if(s.length() <= 254) { return s; } else { return s.substring(0, 254); } } void bindCallerDataWithPreparedStatement(PreparedStatement stmt, StackTraceElement[] callerDataArray) throws SQLException { StackTraceElement caller = extractFirstCaller(callerDataArray); stmt.setString(CALLER_FILENAME_INDEX, caller.getFileName()); stmt.setString(CALLER_CLASS_INDEX, caller.getClassName()); stmt.setString(CALLER_METHOD_INDEX, caller.getMethodName()); stmt.setString(CALLER_LINE_INDEX, Integer.toString(caller.getLineNumber())); } private StackTraceElement extractFirstCaller(StackTraceElement[] callerDataArray) { StackTraceElement caller = EMPTY_CALLER_DATA; if(hasAtLeastOneNonNullElement(callerDataArray)) caller = callerDataArray[0]; return caller; } private boolean hasAtLeastOneNonNullElement(StackTraceElement[] callerDataArray) { return callerDataArray != null && callerDataArray.length > 0 && callerDataArray[0] != null; } Map<String, String> mergePropertyMaps(ILoggingEvent event) { Map<String, String> mergedMap = new HashMap<String, String>(); // we add the context properties first, then the event properties, since // we consider that event-specific properties should have priority over // context-wide properties. Map<String, String> loggerContextMap = event.getLoggerContextVO() .getPropertyMap(); Map<String, String> mdcMap = event.getMDCPropertyMap(); if (loggerContextMap != null) { mergedMap.putAll(loggerContextMap); } if (mdcMap != null) { mergedMap.putAll(mdcMap); } return mergedMap; } @Override protected Method getGeneratedKeysMethod() { return GET_GENERATED_KEYS_METHOD; } @Override protected String getInsertSQL() { return insertSQL; } protected void insertProperties(Map<String, String> mergedMap, Connection connection, long eventId) throws SQLException { Set<String> propertiesKeys = mergedMap.keySet(); if (propertiesKeys.size() > 0) { PreparedStatement insertPropertiesStatement = null; try { insertPropertiesStatement = connection .prepareStatement(insertPropertiesSQL); for (String key : propertiesKeys) { String value = mergedMap.get(key); insertPropertiesStatement.setLong(1, eventId); insertPropertiesStatement.setString(2, key); insertPropertiesStatement.setString(3, value); if (cnxSupportsBatchUpdates) { insertPropertiesStatement.addBatch(); } else { insertPropertiesStatement.execute(); } } if (cnxSupportsBatchUpdates) { insertPropertiesStatement.executeBatch(); } } finally { closeStatement(insertPropertiesStatement); } } } /** * Add an exception statement either as a batch or execute immediately if * batch updates are not supported. */ void updateExceptionStatement(PreparedStatement exceptionStatement, String txt, short i, long eventId) throws SQLException { exceptionStatement.setLong(1, eventId); exceptionStatement.setShort(2, i); exceptionStatement.setString(3, txt); if (cnxSupportsBatchUpdates) { exceptionStatement.addBatch(); } else { exceptionStatement.execute(); } } short buildExceptionStatement(IThrowableProxy tp, short baseIndex, PreparedStatement insertExceptionStatement, long eventId) throws SQLException { StringBuilder buf = new StringBuilder(); ThrowableProxyUtil.subjoinFirstLine(buf, tp); updateExceptionStatement(insertExceptionStatement, buf.toString(), baseIndex++, eventId); int commonFrames = tp.getCommonFrames(); StackTraceElementProxy[] stepArray = tp.getStackTraceElementProxyArray(); for (int i = 0; i < stepArray.length - commonFrames; i++) { StringBuilder sb = new StringBuilder(); sb.append(CoreConstants.TAB); ThrowableProxyUtil.subjoinSTEP(sb, stepArray[i]); updateExceptionStatement(insertExceptionStatement, sb.toString(), baseIndex++, eventId); } if (commonFrames > 0) { StringBuilder sb = new StringBuilder(); sb.append(CoreConstants.TAB).append("... ").append(commonFrames).append( " common frames omitted"); updateExceptionStatement(insertExceptionStatement, sb.toString(), baseIndex++, eventId); } return baseIndex; } protected void insertThrowable(IThrowableProxy tp, Connection connection, long eventId) throws SQLException { PreparedStatement exceptionStatement = null; try { exceptionStatement = connection.prepareStatement(insertExceptionSQL); short baseIndex = 0; while (tp != null) { baseIndex = buildExceptionStatement(tp, baseIndex, exceptionStatement, eventId); tp = tp.getCause(); } if (cnxSupportsBatchUpdates) { exceptionStatement.executeBatch(); } } finally { closeStatement(exceptionStatement); } } }
mit
luiscbr92/algorithmic-challenges
AceptaElReto/Volumen2(200-299)/216/code.cpp
219
#include <iostream> using namespace std; int main(){ int cases, total; cin >> cases; while(cases--){ cin >> total; printf("%02d:%02d:%02d\n", total /3600, total /60 %60, total %60); } return 0; }
mit
aureliano/verbum-domini
verbum-domini-core-mongo/src/main/java/com/github/aureliano/verbum_domini/core/impl/codec/BibleCodec.java
2851
package com.github.aureliano.verbum_domini.core.impl.codec; import org.bson.BsonInt32; import org.bson.BsonReader; import org.bson.BsonValue; import org.bson.BsonWriter; import org.bson.Document; import org.bson.codecs.Codec; import org.bson.codecs.CollectibleCodec; import org.bson.codecs.DecoderContext; import org.bson.codecs.DocumentCodec; import org.bson.codecs.EncoderContext; import com.github.aureliano.verbum_domini.core.impl.bean.BibleBeanImpl; import com.github.aureliano.verbum_domini.core.impl.dao.DaoHelper; public class BibleCodec implements CollectibleCodec<BibleBeanImpl> { private Codec<Document> documentCodec; public BibleCodec() { this.documentCodec = new DocumentCodec(); } public BibleCodec(Codec<Document> codec) { this.documentCodec = codec; } @Override public void encode(BsonWriter writer, BibleBeanImpl bean, EncoderContext context) { Document document = new Document(); document.put("_id", bean.getId()); document.put("copyright", bean.getCopyright()); document.put("edition", bean.getEdition()); document.put("eletronic_transcription_source", bean.getEletronicTranscriptionSource()); document.put("eletronic_transcription_source_url", bean.getEletronicTranscriptionSourceUrl()); document.put("language", bean.getLanguage()); document.put("name", bean.getName()); document.put("printed_source", bean.getPrintedSource()); document.put("url", bean.getUrl()); this.documentCodec.encode(writer, document, context); } @Override public Class<BibleBeanImpl> getEncoderClass() { return BibleBeanImpl.class; } @Override public BibleBeanImpl decode(BsonReader reader, DecoderContext context) { Document document = this.documentCodec.decode(reader, context); BibleBeanImpl bean = new BibleBeanImpl(); bean.setId(document.getInteger("_id")); bean.setCopyright(document.getString("copyright")); bean.setEdition(document.getString("edition")); bean.setEletronicTranscriptionSource(document.getString("eletronic_transcription_source")); bean.setEletronicTranscriptionSourceUrl(document.getString("eletronic_transcription_source_url")); bean.setLanguage(document.getString("language")); bean.setName(document.getString("name")); bean.setPrintedSource(document.getString("printed_source")); bean.setUrl(document.getString("url")); return bean; } @Override public boolean documentHasId(BibleBeanImpl bean) { return bean.getId() != null; } @Override public BibleBeanImpl generateIdIfAbsentFromDocument(BibleBeanImpl bean) { if (!this.documentHasId(bean)) { bean.setId(DaoHelper.nextId(bean)); } return bean; } @Override public BsonValue getDocumentId(BibleBeanImpl bean) { if (!documentHasId(bean)) { throw new IllegalStateException("The document does not contain an _id"); } return new BsonInt32(bean.getId()); } }
mit
51test2003/composer_vendor
phpoffice/phppowerpoint/src/PhpPowerpoint/Writer/ODPresentation/Content.php
44305
<?php /** * This file is part of PHPPowerPoint - A pure PHP library for reading and writing * presentations documents. * * PHPPowerPoint is free software distributed under the terms of the GNU Lesser * General Public License version 3 as published by the Free Software Foundation. * * For the full copyright and license information, please read the LICENSE * file that was distributed with this source code. For the full list of * contributors, visit https://github.com/PHPOffice/PHPWord/contributors. * * @link https://github.com/PHPOffice/PHPPowerPoint * @copyright 2009-2014 PHPPowerPoint contributors * @license http://www.gnu.org/licenses/lgpl.txt LGPL version 3 */ namespace PhpOffice\PhpPowerpoint\Writer\ODPresentation; use PhpOffice\PhpPowerpoint\PhpPowerpoint; use PhpOffice\PhpPowerpoint\Shape\AbstractDrawing; use PhpOffice\PhpPowerpoint\Shape\Chart; use PhpOffice\PhpPowerpoint\Shape\Drawing as ShapeDrawing; use PhpOffice\PhpPowerpoint\Shape\Line; use PhpOffice\PhpPowerpoint\Shape\MemoryDrawing; use PhpOffice\PhpPowerpoint\Shape\RichText\BreakElement; use PhpOffice\PhpPowerpoint\Shape\RichText\Run; use PhpOffice\PhpPowerpoint\Shape\RichText\TextElement; use PhpOffice\PhpPowerpoint\Shape\RichText; use PhpOffice\PhpPowerpoint\Shape\Table; use PhpOffice\PhpPowerpoint\Shape\Table\Cell; use PhpOffice\PhpPowerpoint\Shape\Table\Row; use PhpOffice\PhpPowerpoint\Shared\Drawing as SharedDrawing; use PhpOffice\PhpPowerpoint\Shared\String; use PhpOffice\PhpPowerpoint\Shared\XMLWriter; use PhpOffice\PhpPowerpoint\Style\Alignment; use PhpOffice\PhpPowerpoint\Style\Border; use PhpOffice\PhpPowerpoint\Style\Fill; /** * \PhpOffice\PhpPowerpoint\Writer\ODPresentation\Content */ class Content extends AbstractPart { /** * Write content file to XML format * * @param PHPPowerPoint $pPHPPowerPoint * @return string XML Output * @throws \Exception */ public function writePart(PhpPowerpoint $pPHPPowerPoint) { // Create XML writer $objWriter = $this->getXMLWriter(); // XML header $objWriter->startDocument('1.0', 'UTF-8'); // office:document-content $objWriter->startElement('office:document-content'); $objWriter->writeAttribute('xmlns:office', 'urn:oasis:names:tc:opendocument:xmlns:office:1.0'); $objWriter->writeAttribute('xmlns:style', 'urn:oasis:names:tc:opendocument:xmlns:style:1.0'); $objWriter->writeAttribute('xmlns:text', 'urn:oasis:names:tc:opendocument:xmlns:text:1.0'); $objWriter->writeAttribute('xmlns:table', 'urn:oasis:names:tc:opendocument:xmlns:table:1.0'); $objWriter->writeAttribute('xmlns:draw', 'urn:oasis:names:tc:opendocument:xmlns:drawing:1.0'); $objWriter->writeAttribute('xmlns:fo', 'urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0'); $objWriter->writeAttribute('xmlns:xlink', 'http://www.w3.org/1999/xlink'); $objWriter->writeAttribute('xmlns:dc', 'http://purl.org/dc/elements/1.1/'); $objWriter->writeAttribute('xmlns:meta', 'urn:oasis:names:tc:opendocument:xmlns:meta:1.0'); $objWriter->writeAttribute('xmlns:number', 'urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0'); $objWriter->writeAttribute('xmlns:presentation', 'urn:oasis:names:tc:opendocument:xmlns:presentation:1.0'); $objWriter->writeAttribute('xmlns:svg', 'urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0'); $objWriter->writeAttribute('xmlns:chart', 'urn:oasis:names:tc:opendocument:xmlns:chart:1.0'); $objWriter->writeAttribute('xmlns:dr3d', 'urn:oasis:names:tc:opendocument:xmlns:dr3d:1.0'); $objWriter->writeAttribute('xmlns:math', 'http://www.w3.org/1998/Math/MathML'); $objWriter->writeAttribute('xmlns:form', 'urn:oasis:names:tc:opendocument:xmlns:form:1.0'); $objWriter->writeAttribute('xmlns:script', 'urn:oasis:names:tc:opendocument:xmlns:script:1.0'); $objWriter->writeAttribute('xmlns:ooo', 'http://openoffice.org/2004/office'); $objWriter->writeAttribute('xmlns:ooow', 'http://openoffice.org/2004/writer'); $objWriter->writeAttribute('xmlns:oooc', 'http://openoffice.org/2004/calc'); $objWriter->writeAttribute('xmlns:dom', 'http://www.w3.org/2001/xml-events'); $objWriter->writeAttribute('xmlns:xforms', 'http://www.w3.org/2002/xforms'); $objWriter->writeAttribute('xmlns:xsd', 'http://www.w3.org/2001/XMLSchema'); $objWriter->writeAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance'); $objWriter->writeAttribute('xmlns:smil', 'urn:oasis:names:tc:opendocument:xmlns:smil-compatible:1.0'); $objWriter->writeAttribute('xmlns:anim', 'urn:oasis:names:tc:opendocument:xmlns:animation:1.0'); $objWriter->writeAttribute('xmlns:rpt', 'http://openoffice.org/2005/report'); $objWriter->writeAttribute('xmlns:of', 'urn:oasis:names:tc:opendocument:xmlns:of:1.2'); $objWriter->writeAttribute('xmlns:rdfa', 'http://docs.oasis-open.org/opendocument/meta/rdfa#'); $objWriter->writeAttribute('xmlns:field', 'urn:openoffice:names:experimental:ooo-ms-interop:xmlns:field:1.0'); $objWriter->writeAttribute('office:version', '1.2'); //=============================================== // Styles //=============================================== $arrStyleBullet = array(); $arrStyleParagraph = array(); $arrStyleTextFont = array(); // office:automatic-styles $objWriter->startElement('office:automatic-styles'); $shapeId = 0; foreach ($pPHPPowerPoint->getAllSlides() as $pSlide) { // Images $shapes = $pSlide->getShapeCollection(); foreach ($shapes as $shape) { // Increment $shapeId ++$shapeId; // Check type if ($shape instanceof RichText) { // style:style $objWriter->startElement('style:style'); $objWriter->writeAttribute('style:name', 'gr' . $shapeId); $objWriter->writeAttribute('style:family', 'graphic'); $objWriter->writeAttribute('style:parent-style-name', 'standard'); // style:graphic-properties $objWriter->startElement('style:graphic-properties'); $objWriter->writeAttribute('draw:auto-grow-height', 'true'); $objWriter->writeAttribute('fo:wrap-option', 'wrap'); $objWriter->endElement(); $objWriter->endElement(); $paragraphs = $shape->getParagraphs(); $paragraphId = 0; foreach ($paragraphs as $paragraph) { ++$paragraphId; // Style des paragraphes if (!isset($arrStyleParagraph[$paragraph->getHashCode()])) { $arrStyleParagraph[$paragraph->getHashCode()] = $paragraph; } // Style des listes if (!isset($arrStyleBullet[$paragraph->getBulletStyle()->getHashCode()])) { $arrStyleBullet[$paragraph->getBulletStyle()->getHashCode()]['oStyle'] = $paragraph->getBulletStyle(); $arrStyleBullet[$paragraph->getBulletStyle()->getHashCode()]['level'] = ''; } if (strpos($arrStyleBullet[$paragraph->getBulletStyle()->getHashCode()]['level'], ';' . $paragraph->getAlignment()->getLevel()) === false) { $arrStyleBullet[$paragraph->getBulletStyle()->getHashCode()]['level'] .= ';' . $paragraph->getAlignment()->getLevel(); $arrStyleBullet[$paragraph->getBulletStyle()->getHashCode()]['oAlign_' . $paragraph->getAlignment()->getLevel()] = $paragraph->getAlignment(); } $richtexts = $paragraph->getRichTextElements(); $richtextId = 0; foreach ($richtexts as $richtext) { ++$richtextId; // Not a line break if ($richtext instanceof Run) { // Style des font text if (!isset($arrStyleTextFont[$richtext->getFont()->getHashCode()])) { $arrStyleTextFont[$richtext->getFont()->getHashCode()] = $richtext->getFont(); } } } } } if ($shape instanceof AbstractDrawing) { if ($shape->getShadow()->isVisible()) { // style:style $objWriter->startElement('style:style'); $objWriter->writeAttribute('style:name', 'gr' . $shapeId); $objWriter->writeAttribute('style:family', 'graphic'); $objWriter->writeAttribute('style:parent-style-name', 'standard'); // style:graphic-properties $objWriter->startElement('style:graphic-properties'); $objWriter->writeAttribute('draw:stroke', 'none'); $objWriter->writeAttribute('draw:fill', 'none'); $objWriter->writeAttribute('draw:shadow', 'visible'); $objWriter->writeAttribute('draw:shadow-color', '#' . $shape->getShadow()->getColor()->getRGB()); if ($shape->getShadow()->getDirection() == 0 || $shape->getShadow()->getDirection() == 360) { $objWriter->writeAttribute('draw:shadow-offset-x', SharedDrawing::pixelsToCentimeters($shape->getShadow()->getDistance()) . 'cm'); $objWriter->writeAttribute('draw:shadow-offset-y', '0cm'); } elseif ($shape->getShadow()->getDirection() == 45) { $objWriter->writeAttribute('draw:shadow-offset-x', SharedDrawing::pixelsToCentimeters($shape->getShadow()->getDistance()) . 'cm'); $objWriter->writeAttribute('draw:shadow-offset-y', SharedDrawing::pixelsToCentimeters($shape->getShadow()->getDistance()) . 'cm'); } elseif ($shape->getShadow()->getDirection() == 90) { $objWriter->writeAttribute('draw:shadow-offset-x', '0cm'); $objWriter->writeAttribute('draw:shadow-offset-y', SharedDrawing::pixelsToCentimeters($shape->getShadow()->getDistance()) . 'cm'); } elseif ($shape->getShadow()->getDirection() == 135) { $objWriter->writeAttribute('draw:shadow-offset-x', '-' . SharedDrawing::pixelsToCentimeters($shape->getShadow()->getDistance()) . 'cm'); $objWriter->writeAttribute('draw:shadow-offset-y', SharedDrawing::pixelsToCentimeters($shape->getShadow()->getDistance()) . 'cm'); } elseif ($shape->getShadow()->getDirection() == 180) { $objWriter->writeAttribute('draw:shadow-offset-x', '-' . SharedDrawing::pixelsToCentimeters($shape->getShadow()->getDistance()) . 'cm'); $objWriter->writeAttribute('draw:shadow-offset-y', '0cm'); } elseif ($shape->getShadow()->getDirection() == 225) { $objWriter->writeAttribute('draw:shadow-offset-x', '-' . SharedDrawing::pixelsToCentimeters($shape->getShadow()->getDistance()) . 'cm'); $objWriter->writeAttribute('draw:shadow-offset-y', '-' . SharedDrawing::pixelsToCentimeters($shape->getShadow()->getDistance()) . 'cm'); } elseif ($shape->getShadow()->getDirection() == 270) { $objWriter->writeAttribute('draw:shadow-offset-x', '0cm'); $objWriter->writeAttribute('draw:shadow-offset-y', '-' . SharedDrawing::pixelsToCentimeters($shape->getShadow()->getDistance()) . 'cm'); } elseif ($shape->getShadow()->getDirection() == 315) { $objWriter->writeAttribute('draw:shadow-offset-x', SharedDrawing::pixelsToCentimeters($shape->getShadow()->getDistance()) . 'cm'); $objWriter->writeAttribute('draw:shadow-offset-y', '-' . SharedDrawing::pixelsToCentimeters($shape->getShadow()->getDistance()) . 'cm'); } $objWriter->writeAttribute('draw:shadow-opacity', (100 - $shape->getShadow()->getAlpha()) . '%'); $objWriter->writeAttribute('style:mirror', 'none'); $objWriter->endElement(); $objWriter->endElement(); } } if ($shape instanceof Line) { // style:style $objWriter->startElement('style:style'); $objWriter->writeAttribute('style:name', 'gr' . $shapeId); $objWriter->writeAttribute('style:family', 'graphic'); $objWriter->writeAttribute('style:parent-style-name', 'standard'); // style:graphic-properties $objWriter->startElement('style:graphic-properties'); $objWriter->writeAttribute('draw:fill', 'none'); switch ($shape->getBorder()->getLineStyle()) { case Border::LINE_NONE: $objWriter->writeAttribute('draw:stroke', 'none'); break; case Border::LINE_SINGLE: $objWriter->writeAttribute('draw:stroke', 'solid'); break; default: $objWriter->writeAttribute('draw:stroke', 'none'); break; } $objWriter->writeAttribute('svg:stroke-color', '#'.$shape->getBorder()->getColor()->getRGB()); $objWriter->writeAttribute('svg:stroke-width', String::numberFormat(SharedDrawing::pixelsToCentimeters((SharedDrawing::pointsToPixels($shape->getBorder()->getLineWidth()))), 3).'cm'); $objWriter->endElement(); $objWriter->endElement(); } if ($shape instanceof Table) { foreach ($shape->getRows() as $keyRow => $shapeRow) { // style:style $objWriter->startElement('style:style'); $objWriter->writeAttribute('style:name', 'gr' . $shapeId.'r'.$keyRow); $objWriter->writeAttribute('style:family', 'table-row'); // style:table-row-properties $objWriter->startElement('style:table-row-properties'); $objWriter->writeAttribute('style:row-height', String::numberFormat(SharedDrawing::pixelsToCentimeters(SharedDrawing::pointsToPixels($shapeRow->getHeight())), 3).'cm'); $objWriter->endElement(); $objWriter->endElement(); foreach ($shapeRow->getCells() as $keyCell => $shapeCell) { // style:style $objWriter->startElement('style:style'); $objWriter->writeAttribute('style:name', 'gr' . $shapeId.'r'.$keyRow.'c'.$keyCell); $objWriter->writeAttribute('style:family', 'table-cell'); // style:graphic-properties $objWriter->startElement('style:graphic-properties'); if ($shapeCell->getFill()->getFillType() == Fill::FILL_SOLID) { $objWriter->writeAttribute('draw:fill', 'solid'); $objWriter->writeAttribute('draw:fill-color', '#'.$shapeCell->getFill()->getStartColor()->getRGB()); } if ($shapeCell->getFill()->getFillType() == Fill::FILL_GRADIENT_LINEAR) { $objWriter->writeAttribute('draw:fill', 'gradient'); $objWriter->writeAttribute('draw:fill-gradient-name', 'gradient_'.$shapeCell->getFill()->getHashCode()); } $objWriter->endElement(); // <style:graphic-properties // style:paragraph-properties $objWriter->startElement('style:paragraph-properties'); if ($shapeCell->getBorders()->getBottom()->getHashCode() == $shapeCell->getBorders()->getTop()->getHashCode() && $shapeCell->getBorders()->getBottom()->getHashCode() == $shapeCell->getBorders()->getLeft()->getHashCode() && $shapeCell->getBorders()->getBottom()->getHashCode() == $shapeCell->getBorders()->getRight()->getHashCode()) { $lineStyle = 'none'; $lineWidth = String::numberFormat($shapeCell->getBorders()->getBottom()->getLineWidth() / 1.75, 2); $lineColor = $shapeCell->getBorders()->getBottom()->getColor()->getRGB(); switch ($shapeCell->getBorders()->getBottom()->getLineStyle()){ case Border::LINE_SINGLE: $lineStyle = 'solid'; } $objWriter->writeAttribute('fo:border', $lineWidth.'pt '.$lineStyle.' #'.$lineColor); } else { $lineStyle = 'none'; $lineWidth = String::numberFormat($shapeCell->getBorders()->getBottom()->getLineWidth() / 1.75, 2); $lineColor = $shapeCell->getBorders()->getBottom()->getColor()->getRGB(); switch ($shapeCell->getBorders()->getBottom()->getLineStyle()){ case Border::LINE_SINGLE: $lineStyle = 'solid'; } $objWriter->writeAttribute('fo:border-bottom', $lineWidth.'pt '.$lineStyle.' #'.$lineColor); // TOP $lineStyle = 'none'; $lineWidth = String::numberFormat($shapeCell->getBorders()->getTop()->getLineWidth() / 1.75, 2); $lineColor = $shapeCell->getBorders()->getTop()->getColor()->getRGB(); switch ($shapeCell->getBorders()->getTop()->getLineStyle()){ case Border::LINE_SINGLE: $lineStyle = 'solid'; } $objWriter->writeAttribute('fo:border-top', $lineWidth.'pt '.$lineStyle.' #'.$lineColor); // RIGHT $lineStyle = 'none'; $lineWidth = String::numberFormat($shapeCell->getBorders()->getRight()->getLineWidth() / 1.75, 2); $lineColor = $shapeCell->getBorders()->getRight()->getColor()->getRGB(); switch ($shapeCell->getBorders()->getRight()->getLineStyle()){ case Border::LINE_SINGLE: $lineStyle = 'solid'; } $objWriter->writeAttribute('fo:border-right', $lineWidth.'pt '.$lineStyle.' #'.$lineColor); // LEFT $lineStyle = 'none'; $lineWidth = String::numberFormat($shapeCell->getBorders()->getLeft()->getLineWidth() / 1.75, 2); $lineColor = $shapeCell->getBorders()->getLeft()->getColor()->getRGB(); switch ($shapeCell->getBorders()->getLeft()->getLineStyle()){ case Border::LINE_SINGLE: $lineStyle = 'solid'; } $objWriter->writeAttribute('fo:border-left', $lineWidth.'pt '.$lineStyle.' #'.$lineColor); } $objWriter->endElement(); $objWriter->endElement(); foreach ($shapeCell->getParagraphs() as $shapeParagraph) { foreach ($shapeParagraph->getRichTextElements() as $shapeRichText) { if ($shapeRichText instanceof Run) { // Style des font text if (!isset($arrStyleTextFont[$shapeRichText->getFont()->getHashCode()])) { $arrStyleTextFont[$shapeRichText->getFont()->getHashCode()] = $shapeRichText->getFont(); } } } } } } } } } // Style : Bullet if (!empty($arrStyleBullet)) { foreach ($arrStyleBullet as $key => $item) { $oStyle = $item['oStyle']; $arrLevel = explode(';', $item['level']); // style:style $objWriter->startElement('text:list-style'); $objWriter->writeAttribute('style:name', 'L_' . $key); foreach ($arrLevel as $level) { if ($level != '') { $oAlign = $item['oAlign_' . $level]; // text:list-level-style-bullet $objWriter->startElement('text:list-level-style-bullet'); $objWriter->writeAttribute('text:level', $level + 1); $objWriter->writeAttribute('text:bullet-char', $oStyle->getBulletChar()); // style:list-level-properties $objWriter->startElement('style:list-level-properties'); if ($oAlign->getIndent() < 0) { $objWriter->writeAttribute('text:space-before', SharedDrawing::pixelsToCentimeters($oAlign->getMarginLeft() - (-1 * $oAlign->getIndent())) . 'cm'); $objWriter->writeAttribute('text:min-label-width', SharedDrawing::pixelsToCentimeters(-1 * $oAlign->getIndent()) . 'cm'); } else { $objWriter->writeAttribute('text:space-before', (SharedDrawing::pixelsToCentimeters($oAlign->getMarginLeft() - $oAlign->getIndent())) . 'cm'); $objWriter->writeAttribute('text:min-label-width', SharedDrawing::pixelsToCentimeters($oAlign->getIndent()) . 'cm'); } $objWriter->endElement(); // style:text-properties $objWriter->startElement('style:text-properties'); $objWriter->writeAttribute('fo:font-family', $oStyle->getBulletFont()); $objWriter->writeAttribute('style:font-family-generic', 'swiss'); $objWriter->writeAttribute('style:use-window-font-color', 'true'); $objWriter->writeAttribute('fo:font-size', '100'); $objWriter->endElement(); $objWriter->endElement(); } } $objWriter->endElement(); } } // Style : Paragraph if (!empty($arrStyleParagraph)) { foreach ($arrStyleParagraph as $key => $item) { // style:style $objWriter->startElement('style:style'); $objWriter->writeAttribute('style:name', 'P_' . $key); $objWriter->writeAttribute('style:family', 'paragraph'); // style:paragraph-properties $objWriter->startElement('style:paragraph-properties'); switch ($item->getAlignment()->getHorizontal()) { case Alignment::HORIZONTAL_LEFT: $objWriter->writeAttribute('fo:text-align', 'left'); break; case Alignment::HORIZONTAL_RIGHT: $objWriter->writeAttribute('fo:text-align', 'right'); break; case Alignment::HORIZONTAL_CENTER: $objWriter->writeAttribute('fo:text-align', 'center'); break; case Alignment::HORIZONTAL_JUSTIFY: $objWriter->writeAttribute('fo:text-align', 'justify'); break; case Alignment::HORIZONTAL_DISTRIBUTED: $objWriter->writeAttribute('fo:text-align', 'justify'); break; default: $objWriter->writeAttribute('fo:text-align', 'left'); break; } $objWriter->endElement(); $objWriter->endElement(); } } // Style : Text : Font if (!empty($arrStyleTextFont)) { foreach ($arrStyleTextFont as $key => $item) { // style:style $objWriter->startElement('style:style'); $objWriter->writeAttribute('style:name', 'T_' . $key); $objWriter->writeAttribute('style:family', 'text'); // style:text-properties $objWriter->startElement('style:text-properties'); $objWriter->writeAttribute('fo:color', '#' . $item->getColor()->getRGB()); $objWriter->writeAttribute('fo:font-family', $item->getName()); $objWriter->writeAttribute('fo:font-size', $item->getSize() . 'pt'); // @todo : fo:font-style if ($item->isBold()) { $objWriter->writeAttribute('fo:font-weight', 'bold'); } // @todo : style:text-underline-style $objWriter->endElement(); $objWriter->endElement(); } } $objWriter->endElement(); //=============================================== // Body //=============================================== // office:body $objWriter->startElement('office:body'); // office:presentation $objWriter->startElement('office:presentation'); // Write slides $slideCount = $pPHPPowerPoint->getSlideCount(); $shapeId = 0; for ($i = 0; $i < $slideCount; ++$i) { $pSlide = $pPHPPowerPoint->getSlide($i); $objWriter->startElement('draw:page'); $objWriter->writeAttribute('draw:name', 'page' . $i); $objWriter->writeAttribute('draw:master-page-name', 'Standard'); // Images $shapes = $pSlide->getShapeCollection(); foreach ($shapes as $shape) { // Increment $shapeId ++$shapeId; // Check type if ($shape instanceof RichText) { $this->writeShapeTxt($objWriter, $shape, $shapeId); } elseif ($shape instanceof Table) { $this->writeShapeTable($objWriter, $shape, $shapeId); } elseif ($shape instanceof Line) { $this->writeShapeLine($objWriter, $shape, $shapeId); } elseif ($shape instanceof Chart) { $this->writeShapeChart($objWriter, $shape, $shapeId); } elseif ($shape instanceof AbstractDrawing) { $this->writeShapePic($objWriter, $shape, $shapeId); } } $objWriter->endElement(); } $objWriter->endElement(); $objWriter->endElement(); $objWriter->endElement(); // Return return $objWriter->getData(); } /** * Write picture * * @param \PhpOffice\PhpPowerpoint\Shared\XMLWriter $objWriter * @param \PhpOffice\PhpPowerpoint\Shape\AbstractDrawing $shape * @param int $shapeId */ public function writeShapePic(XMLWriter $objWriter, AbstractDrawing $shape, $shapeId) { // draw:frame $objWriter->startElement('draw:frame'); $objWriter->writeAttribute('draw:name', $shape->getName()); $objWriter->writeAttribute('svg:width', String::numberFormat(SharedDrawing::pixelsToCentimeters($shape->getWidth()), 3) . 'cm'); $objWriter->writeAttribute('svg:height', String::numberFormat(SharedDrawing::pixelsToCentimeters($shape->getHeight()), 3) . 'cm'); $objWriter->writeAttribute('svg:x', String::numberFormat(SharedDrawing::pixelsToCentimeters($shape->getOffsetX()), 3) . 'cm'); $objWriter->writeAttribute('svg:y', String::numberFormat(SharedDrawing::pixelsToCentimeters($shape->getOffsetY()), 3) . 'cm'); if ($shape->getShadow()->isVisible()) { $objWriter->writeAttribute('draw:style-name', 'gr' . $shapeId); } // draw:image $objWriter->startElement('draw:image'); if ($shape instanceof ShapeDrawing) { $objWriter->writeAttribute('xlink:href', 'Pictures/' . md5($shape->getPath()) . '.' . $shape->getExtension()); } elseif ($shape instanceof MemoryDrawing) { $objWriter->writeAttribute('xlink:href', 'Pictures/' . $shape->getIndexedFilename()); } $objWriter->writeAttribute('xlink:type', 'simple'); $objWriter->writeAttribute('xlink:show', 'embed'); $objWriter->writeAttribute('xlink:actuate', 'onLoad'); $objWriter->writeElement('text:p'); $objWriter->endElement(); $objWriter->endElement(); } /** * Write text * * @param \PhpOffice\PhpPowerpoint\Shared\XMLWriter $objWriter * @param \PhpOffice\PhpPowerpoint\Shape\RichText $shape * @param int $shapeId */ public function writeShapeTxt(XMLWriter $objWriter, RichText $shape, $shapeId) { // draw:custom-shape $objWriter->startElement('draw:custom-shape'); $objWriter->writeAttribute('draw:style-name', 'gr' . $shapeId); $objWriter->writeAttribute('svg:width', String::numberFormat(SharedDrawing::pixelsToCentimeters($shape->getWidth()), 3) . 'cm'); $objWriter->writeAttribute('svg:height', String::numberFormat(SharedDrawing::pixelsToCentimeters($shape->getHeight()), 3) . 'cm'); $objWriter->writeAttribute('svg:x', String::numberFormat(SharedDrawing::pixelsToCentimeters($shape->getOffsetX()), 3) . 'cm'); $objWriter->writeAttribute('svg:y', String::numberFormat(SharedDrawing::pixelsToCentimeters($shape->getOffsetY()), 3) . 'cm'); $paragraphs = $shape->getParagraphs(); $paragraphId = 0; $sCstShpLastBullet = ''; $iCstShpLastBulletLvl = 0; $bCstShpHasBullet = false; foreach ($paragraphs as $paragraph) { // Close the bullet list if ($sCstShpLastBullet != 'bullet' && $bCstShpHasBullet == true) { for ($iInc = $iCstShpLastBulletLvl; $iInc >= 0; $iInc--) { // text:list-item $objWriter->endElement(); // text:list $objWriter->endElement(); } } //=============================================== // Paragraph //=============================================== if ($paragraph->getBulletStyle()->getBulletType() == 'none') { ++$paragraphId; // text:p $objWriter->startElement('text:p'); $objWriter->writeAttribute('text:style-name', 'P_' . $paragraph->getHashCode()); // Loop trough rich text elements $richtexts = $paragraph->getRichTextElements(); $richtextId = 0; foreach ($richtexts as $richtext) { ++$richtextId; if ($richtext instanceof TextElement || $richtext instanceof Run) { // text:span $objWriter->startElement('text:span'); if ($richtext instanceof Run) { $objWriter->writeAttribute('text:style-name', 'T_' . $richtext->getFont()->getHashCode()); } if ($richtext->hasHyperlink() == true && $richtext->getHyperlink()->getUrl() != '') { // text:a $objWriter->startElement('text:a'); $objWriter->writeAttribute('xlink:href', $richtext->getHyperlink()->getUrl()); $objWriter->text($richtext->getText()); $objWriter->endElement(); } else { $objWriter->text($richtext->getText()); } $objWriter->endElement(); } elseif ($richtext instanceof BreakElement) { // text:span $objWriter->startElement('text:span'); // text:line-break $objWriter->startElement('text:line-break'); $objWriter->endElement(); $objWriter->endElement(); } else { //echo '<pre>'.print_r($richtext, true).'</pre>'; } } $objWriter->endElement(); //=============================================== // Bullet list //=============================================== } elseif ($paragraph->getBulletStyle()->getBulletType() == 'bullet') { $bCstShpHasBullet = true; // Open the bullet list if ($sCstShpLastBullet != 'bullet' || ($sCstShpLastBullet == $paragraph->getBulletStyle()->getBulletType() && $iCstShpLastBulletLvl < $paragraph->getAlignment()->getLevel())) { // text:list $objWriter->startElement('text:list'); $objWriter->writeAttribute('text:style-name', 'L_' . $paragraph->getBulletStyle()->getHashCode()); } if ($sCstShpLastBullet == 'bullet') { if ($iCstShpLastBulletLvl == $paragraph->getAlignment()->getLevel()) { // text:list-item $objWriter->endElement(); } elseif ($iCstShpLastBulletLvl > $paragraph->getAlignment()->getLevel()) { // text:list-item $objWriter->endElement(); // text:list $objWriter->endElement(); // text:list-item $objWriter->endElement(); } } // text:list-item $objWriter->startElement('text:list-item'); ++$paragraphId; // text:p $objWriter->startElement('text:p'); $objWriter->writeAttribute('text:style-name', 'P_' . $paragraph->getHashCode()); // Loop trough rich text elements $richtexts = $paragraph->getRichTextElements(); $richtextId = 0; foreach ($richtexts as $richtext) { ++$richtextId; if ($richtext instanceof TextElement || $richtext instanceof Run) { // text:span $objWriter->startElement('text:span'); if ($richtext instanceof Run) { $objWriter->writeAttribute('text:style-name', 'T_' . $richtext->getFont()->getHashCode()); } if ($richtext->hasHyperlink() == true && $richtext->getHyperlink()->getUrl() != '') { // text:a $objWriter->startElement('text:a'); $objWriter->writeAttribute('xlink:href', $richtext->getHyperlink()->getUrl()); $objWriter->text($richtext->getText()); $objWriter->endElement(); } else { $objWriter->text($richtext->getText()); } $objWriter->endElement(); } elseif ($richtext instanceof BreakElement) { // text:span $objWriter->startElement('text:span'); // text:line-break $objWriter->startElement('text:line-break'); $objWriter->endElement(); $objWriter->endElement(); } else { //echo '<pre>'.print_r($richtext, true).'</pre>'; } } $objWriter->endElement(); } $sCstShpLastBullet = $paragraph->getBulletStyle()->getBulletType(); $iCstShpLastBulletLvl = $paragraph->getAlignment()->getLevel(); } // Close the bullet list if ($sCstShpLastBullet == 'bullet' && $bCstShpHasBullet == true) { for ($iInc = $iCstShpLastBulletLvl; $iInc >= 0; $iInc--) { // text:list-item $objWriter->endElement(); // text:list $objWriter->endElement(); } } $objWriter->endElement(); } /** * * @param XMLWriter $objWriter * @param Line $shape * @param integer $shapeId */ public function writeShapeLine(XMLWriter $objWriter, Line $shape, $shapeId) { // draw:line $objWriter->startElement('draw:line'); $objWriter->writeAttribute('draw:style-name', 'gr' . $shapeId); $objWriter->writeAttribute('svg:x1', String::numberFormat(SharedDrawing::pixelsToCentimeters($shape->getOffsetX()), 3) . 'cm'); $objWriter->writeAttribute('svg:y1', String::numberFormat(SharedDrawing::pixelsToCentimeters($shape->getOffsetY()), 3) . 'cm'); $objWriter->writeAttribute('svg:x2', String::numberFormat(SharedDrawing::pixelsToCentimeters($shape->getOffsetX()+$shape->getWidth()), 3) . 'cm'); $objWriter->writeAttribute('svg:y2', String::numberFormat(SharedDrawing::pixelsToCentimeters($shape->getOffsetY()+$shape->getHeight()), 3) . 'cm'); // text:p $objWriter->writeElement('text:p'); $objWriter->endElement(); } /** * Write table Shape * @param XMLWriter $objWriter * @param Table $shape * @param integer $shapeId */ public function writeShapeTable(XMLWriter $objWriter, Table $shape, $shapeId) { // draw:frame $objWriter->startElement('draw:frame'); $objWriter->writeAttribute('svg:x', String::numberFormat(SharedDrawing::pixelsToCentimeters($shape->getOffsetX()), 3) . 'cm'); $objWriter->writeAttribute('svg:y', String::numberFormat(SharedDrawing::pixelsToCentimeters($shape->getOffsetY()), 3) . 'cm'); $objWriter->writeAttribute('svg:height', String::numberFormat(SharedDrawing::pixelsToCentimeters($shape->getHeight()), 3) . 'cm'); $objWriter->writeAttribute('svg:width', String::numberFormat(SharedDrawing::pixelsToCentimeters($shape->getWidth()), 3) . 'cm'); // table:table $objWriter->startElement('table:table'); foreach ($shape->getRows() as $keyRow => $shapeRow) { // table:table-row $objWriter->startElement('table:table-row'); $objWriter->writeAttribute('table:style-name', 'gr'.$shapeId.'r'.$keyRow); //@todo getFill $numColspan = 0; foreach ($shapeRow->getCells() as $keyCell => $shapeCell) { if ($numColspan == 0) { // table:table-cell $objWriter->startElement('table:table-cell'); $objWriter->writeAttribute('table:style-name', 'gr' . $shapeId.'r'.$keyRow.'c'.$keyCell); if ($shapeCell->getColspan() > 1) { $objWriter->writeAttribute('table:number-columns-spanned', $shapeCell->getColspan()); $numColspan = $shapeCell->getColspan() - 1; } // text:p $objWriter->startElement('text:p'); // text:span foreach ($shapeCell->getParagraphs() as $shapeParagraph) { foreach ($shapeParagraph->getRichTextElements() as $shapeRichText) { $objWriter->startElement('text:span'); $objWriter->writeAttribute('text:style-name', 'T_' . $shapeRichText->getFont()->getHashCode()); $objWriter->text($shapeRichText->getText()); $objWriter->endElement(); } } // > text:p $objWriter->endElement(); // > table:table-cell $objWriter->endElement(); } else { // table:covered-table-cell $objWriter->writeElement('table:covered-table-cell'); $numColspan--; } } // > table:table-row $objWriter->endElement(); } // > table:table $objWriter->endElement(); // > draw:frame $objWriter->endElement(); } /** * Write table Chart * @param XMLWriter $objWriter * @param Chart $shape * @param integer $shapeId */ public function writeShapeChart(XMLWriter $objWriter, Chart $shape, $shapeId) { $this->getParentWriter()->chartArray[$shapeId] = $shape; // draw:frame $objWriter->startElement('draw:frame'); $objWriter->writeAttribute('draw:name', $shape->getTitle()->getText()); $objWriter->writeAttribute('svg:x', String::numberFormat(SharedDrawing::pixelsToCentimeters($shape->getOffsetX()), 3) . 'cm'); $objWriter->writeAttribute('svg:y', String::numberFormat(SharedDrawing::pixelsToCentimeters($shape->getOffsetY()), 3) . 'cm'); $objWriter->writeAttribute('svg:height', String::numberFormat(SharedDrawing::pixelsToCentimeters($shape->getHeight()), 3) . 'cm'); $objWriter->writeAttribute('svg:width', String::numberFormat(SharedDrawing::pixelsToCentimeters($shape->getWidth()), 3) . 'cm'); // draw:object $objWriter->startElement('draw:object'); $objWriter->writeAttribute('xlink:href', './Object '.$shapeId); $objWriter->writeAttribute('xlink:type', 'simple'); $objWriter->writeAttribute('xlink:show', 'embed'); // > draw:object $objWriter->endElement(); // > draw:frame $objWriter->endElement(); } }
mit
FICTURE7/CoCSharp
src/CoCSharp/Network/MessageDirection.cs
454
using System; namespace CoCSharp.Network { /// <summary> /// Defines the direction of a <see cref="Message"/>. /// </summary> [Flags] public enum MessageDirection : byte { /// <summary> /// <see cref="Message"/> is going to the client. /// </summary> Client = 2, /// <summary> /// <see cref="Message"/> is going to the server. /// </summary> Server = 3 } }
mit
gregf/podfetcher
src/database/database.go
6319
package database import ( "fmt" "log" "os" "path/filepath" "github.com/jinzhu/gorm" gohome "gopkg.in/caarlos0/gohome.v1" // required by gorm _ "github.com/jinzhu/gorm/dialects/sqlite" ) // Datastore interface type Datastore interface { FindEpisodesWithPodcastTitle() (map[string][]string, error) FindPodcastTitleByURL(url string) (title string) FindEpisodeTitleByURL(url string) (title string) FindNewEpisodes() (urls []string, err error) FindAllPodcasts() (ids []int, titles []string) FindPodcastTitle(id int) (title string) SetDownloadedByURL(url string) AddPodcast(title, rssurl string) AddItem(items map[string]string) TogglePause(id int) (paused bool) CatchUp(id int) } // DB struct type DB struct { *gorm.DB } const appName = "podfetcher" // Podcast struct type Podcast struct { ID int `sql:"index"` Title string RssURL string `sql:"unique_index"` Paused bool Episodes []Episode } // Episode struct type Episode struct { ID int `sql:"index"` PodcastID int Title string EnclosureURL string `sql:"unique_index"` Downloaded bool GUID string `sql:"unique_index"` PubDate string } func databasePath() (path string) { path = gohome.Cache(appName) os.MkdirAll(path, 0755) return filepath.Join(path, "cache.db") } // NewDB establishes a connection with the database and sets the DB struct func NewDB() (*DB, error) { var err error db, err := gorm.Open("sqlite3", databasePath()) if err != nil { return nil, err } db.LogMode(false) db.CreateTable(&Podcast{Paused: false}) db.CreateTable(&Episode{}) db.AutoMigrate(&Podcast{}, &Episode{}) return &DB{db}, nil } // SetDownloadedByURL updates all downloaded columns to be true func (db *DB) SetDownloadedByURL(url string) { db.Table("episodes"). Where("enclosure_url = ?", url). UpdateColumn("downloaded", true) } // FindEpisodeTitleByURL finds episode titles by url func (db *DB) FindEpisodeTitleByURL(url string) (title string) { row := db.Table("episodes"). Where("enclosure_url = ?", url). Select("title"). Row() row.Scan(&title) return title } // FindPodcastTitleByURL finds podcast titles by URL func (db *DB) FindPodcastTitleByURL(url string) (title string) { var podcastID int row := db.Table("episodes").Where("enclosure_url = ?", url).Select("podcast_id").Row() row.Scan(&podcastID) prow := db.Table("podcasts"). Where("id = ?", podcastID). Select("title"). Row() prow.Scan(&title) return title } // FindNewEpisodes finds episodes where downloaded = false func (db *DB) FindNewEpisodes() (urls []string, err error) { rows, err := db.Table("episodes"). Where("downloaded = ?", false). Select("podcast_id, enclosure_url"). Rows() defer rows.Close() for rows.Next() { var enclosureURL string var podcastID int rows.Scan(&podcastID, &enclosureURL) paused := db.FindPodcastPausedState(podcastID) if paused { return nil, nil } urls = append(urls, enclosureURL) } return urls, err } // FindAllPodcasts Find all podcasts and their IDs func (db *DB) FindAllPodcasts() (ids []int, titles []string) { rows, err := db.Table("podcasts").Select("id, title").Rows() if err != nil { log.Fatal(err) } defer rows.Close() for rows.Next() { var ID int var title string rows.Scan(&ID, &title) ids = append(ids, ID) titles = append(titles, title) } return ids, titles } // findPodcastID locates podcast ID by rssURL func (db *DB) findPodcastID(rssurl string) (podcastID int) { row := db.Table("podcasts"). Where("rss_url = ?", rssurl). Select("id"). Row() row.Scan(&podcastID) return podcastID } // AddPodcast Inserts a new podcast into the database func (db *DB) AddPodcast(title, rssurl string) { podcast := Podcast{ Title: title, RssURL: rssurl, } if db.NewRecord(&podcast) { db.Create(&podcast) } } // AddItem takes a map[string]string of episode items to be inserted into the // database. // // item[rssURL] item[title], item[enclosureURL], item[guid], items[pubdate] func (db *DB) AddItem(items map[string]string) { podcastID := db.findPodcastID(items["rssURL"]) episode := Episode{ Title: items["title"], EnclosureURL: items["enclosureURL"], Downloaded: false, PodcastID: podcastID, GUID: items["guid"], PubDate: items["pubdate"], } if db.NewRecord(&episode) { db.Create(&episode) } } // CatchUp Marks all downloaded = false to be downloaded = true func (db *DB) CatchUp(id int) { if id == 0 { db.Table("episodes").Where("downloaded = ?", false). UpdateColumn("downloaded", true) } else { db.Table("episodes").Where("podcast_id = ?", id). Where("downloaded = ?", false). UpdateColumn("downloaded", true) } } // FindEpisodesWithPodcastTitle Finds episodes with their podcast title and // returns a map[string]string func (db *DB) FindEpisodesWithPodcastTitle() (map[string][]string, error) { rows, err := db.Table("Episodes"). Where("downloaded = ?", false). Select("title, podcast_id, ID"). Rows() if err != nil { return nil, err } m := make(map[string][]string) for rows.Next() { var eptitle string var podcastID int var title string var ID int rows.Scan(&eptitle, &podcastID, &ID) row := db.Table("podcasts"). Where("id =?", podcastID). Select("title"). Row() row.Scan(&title) paused := db.FindPodcastPausedState(podcastID) if paused { return nil, nil } pt := fmt.Sprintf("%d:%v", podcastID, title) et := fmt.Sprintf("%d:%v", ID, eptitle) m[pt] = append(m[pt], et) } return m, nil } //FindPodcastPausedState finds out wether or not a podcast is paused func (db *DB) FindPodcastPausedState(id int) (paused bool) { row := db.Table("podcasts").Where("id = ?", id).Select("paused").Row() row.Scan(&paused) return paused } //TogglePause toggles between paused states true and false func (db *DB) TogglePause(id int) (paused bool) { state := db.FindPodcastPausedState(id) paused = false if state == false { paused = true } db.Table("podcasts").Where("id = ?", id). UpdateColumn("paused", paused) return paused } // FindPodcastTitle looks up a podcast title by its id func (db *DB) FindPodcastTitle(id int) (title string) { row := db.Table("podcasts").Where("id = ?", id).Select("title").Row() row.Scan(&title) return title }
mit
pixelballoon/pixelboost
tools/editor/source/command/base.cpp
2781
#include <sstream> #include <string> #include "command/base.h" std::string Trim(const std::string& str) { std::string::size_type a = str.find_first_not_of(' '); std::string::size_type b = str.find_last_not_of(' '); return str.substr(a == std::string::npos ? 0 : a, b == std::string::npos ? str.length() - 1 : b - a + 1); } Command::~Command() { } bool Command::IsArgumentSet(const std::string& argument) { ArgumentMap::iterator it = _Arguments.find(argument); if (it == _Arguments.end()) return false; return true; } unsigned long Command::GetArgumentCount(const std::string& argument) { ArgumentMap::iterator it = _Arguments.find(argument); if (it == _Arguments.end()) return 0; return it->second.size(); } std::string Command::GetArgument(const std::string& argument, unsigned long index) { ArgumentMap::iterator it = _Arguments.find(argument); if (it == _Arguments.end()) return ""; std::vector<std::string>& values = it->second; if (index < values.size()) return values[index]; return ""; } void Command::SetArguments(const std::string& arguments) { enum State { kStateArg, kStateTag }; State state = kStateTag; std::vector<std::string> argList; std::string tag = ""; std::ostringstream arg; for (int i=0; i<arguments.length(); i++) { char c = arguments.at(i); switch (state) { case kStateArg: if (c == '-') { state = kStateTag; tag = arguments.at(i+1); i++; } break; case kStateTag: if (c == ',') { argList.push_back(Trim(arg.str())); arg.str(""); } else if (c == '-' && (i == 0 || arguments[i-1] == ' ') && (i == arguments.length() || (arguments[i+1] > '0' && arguments[i+1] > '9'))) { if (arg.str().length()) { argList.push_back(Trim(arg.str())); arg.str(""); } _Arguments[tag] = argList; argList.clear(); state = kStateArg; i--; } else { arg << c; } break; } } if (arg.str().length() > 0) { argList.push_back(Trim(arg.str())); } _Arguments[tag] = argList; } bool Command::CanUndo() { return false; } bool Command::Undo() { return false; }
mit
Adyen/adyen-java-api-library
src/main/java/com/adyen/model/marketpay/UpdateAccountResponse.java
9146
/* * ###### * ###### * ############ ####( ###### #####. ###### ############ ############ * ############# #####( ###### #####. ###### ############# ############# * ###### #####( ###### #####. ###### ##### ###### ##### ###### * ###### ###### #####( ###### #####. ###### ##### ##### ##### ###### * ###### ###### #####( ###### #####. ###### ##### ##### ###### * ############# ############# ############# ############# ##### ###### * ############ ############ ############# ############ ##### ###### * ###### * ############# * ############ * * Adyen Java API Library * * Copyright (c) 2020 Adyen B.V. * This file is open source and available under the MIT license. * See the LICENSE file for more info. */ package com.adyen.model.marketpay; import com.google.gson.annotations.SerializedName; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import static com.adyen.util.Util.toIndentedString; /** * UpdateAccountResponse */ public class UpdateAccountResponse { @SerializedName("accountCode") private String accountCode = null; @SerializedName("description") private String description = null; @SerializedName("invalidFields") private List<ErrorFieldType> invalidFields = null; @SerializedName("metadata") private Map<String, String> metadata = null; @SerializedName("payoutSchedule") private PayoutScheduleResponse payoutSchedule = null; @SerializedName("pspReference") private String pspReference = null; @SerializedName("resultCode") private String resultCode = null; @SerializedName("bankAccountUUID") private String bankAccountUUID = null; @SerializedName("payoutMethodCode") private String payoutMethodCode = null; @SerializedName("payoutSpeed") private PayoutSpeedEnum payoutSpeed = null; public UpdateAccountResponse accountCode(String accountCode) { this.accountCode = accountCode; return this; } /** * The code of the account. * * @return accountCode **/ public String getAccountCode() { return accountCode; } public void setAccountCode(String accountCode) { this.accountCode = accountCode; } public UpdateAccountResponse description(String description) { this.description = description; return this; } /** * The description of the account. * * @return description **/ public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public UpdateAccountResponse invalidFields(List<ErrorFieldType> invalidFields) { this.invalidFields = invalidFields; return this; } public UpdateAccountResponse addInvalidFieldsItem(ErrorFieldType invalidFieldsItem) { if (this.invalidFields == null) { this.invalidFields = new ArrayList<>(); } this.invalidFields.add(invalidFieldsItem); return this; } /** * A list of fields that caused the &#x60;/updateAccount&#x60; request to fail. * * @return invalidFields **/ public List<ErrorFieldType> getInvalidFields() { return invalidFields; } public void setInvalidFields(List<ErrorFieldType> invalidFields) { this.invalidFields = invalidFields; } public UpdateAccountResponse metadata(Map<String, String> metadata) { this.metadata = metadata; return this; } public UpdateAccountResponse putMetadataItem(String key, String metadataItem) { if (this.metadata == null) { this.metadata = new HashMap<>(); } this.metadata.put(key, metadataItem); return this; } /** * Get metadata * * @return metadata **/ public Map<String, String> getMetadata() { return metadata; } public void setMetadata(Map<String, String> metadata) { this.metadata = metadata; } public UpdateAccountResponse payoutSchedule(PayoutScheduleResponse payoutSchedule) { this.payoutSchedule = payoutSchedule; return this; } /** * Get payoutSchedule * * @return payoutSchedule **/ public PayoutScheduleResponse getPayoutSchedule() { return payoutSchedule; } public void setPayoutSchedule(PayoutScheduleResponse payoutSchedule) { this.payoutSchedule = payoutSchedule; } public UpdateAccountResponse pspReference(String pspReference) { this.pspReference = pspReference; return this; } /** * The reference of a request. Can be used to uniquely identify the request. * * @return pspReference **/ public String getPspReference() { return pspReference; } public void setPspReference(String pspReference) { this.pspReference = pspReference; } public UpdateAccountResponse resultCode(String resultCode) { this.resultCode = resultCode; return this; } /** * The result code. * * @return resultCode **/ public String getResultCode() { return resultCode; } public void setResultCode(String resultCode) { this.resultCode = resultCode; } public UpdateAccountResponse bankAccountUUID(String bankAccountUUID) { this.bankAccountUUID = bankAccountUUID; return this; } public String getBankAccountUUID() { return bankAccountUUID; } public void setBankAccountUUID(String bankAccountUUID) { this.bankAccountUUID = bankAccountUUID; } public UpdateAccountResponse payoutMethodCode(String payoutMethodCode) { this.payoutMethodCode = payoutMethodCode; return this; } public String getPayoutMethodCode() { return payoutMethodCode; } public void setPayoutMethodCode(String payoutMethodCode) { this.payoutMethodCode = payoutMethodCode; } public UpdateAccountResponse payoutSpeed(PayoutSpeedEnum payoutSpeed) { this.payoutSpeed = payoutSpeed; return this; } public PayoutSpeedEnum getPayoutSpeed() { return payoutSpeed; } public void setPayoutSpeed(PayoutSpeedEnum payoutSpeed) { this.payoutSpeed = payoutSpeed; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } UpdateAccountResponse updateAccountResponse = (UpdateAccountResponse) o; return Objects.equals(this.accountCode, updateAccountResponse.accountCode) && Objects.equals(this.description, updateAccountResponse.description) && Objects.equals(this.invalidFields, updateAccountResponse.invalidFields) && Objects.equals(this.metadata, updateAccountResponse.metadata) && Objects.equals(this.payoutSchedule, updateAccountResponse.payoutSchedule) && Objects.equals(this.pspReference, updateAccountResponse.pspReference) && Objects.equals(this.resultCode, updateAccountResponse.resultCode) && Objects.equals(this.bankAccountUUID, updateAccountResponse.bankAccountUUID) && Objects.equals(this.payoutMethodCode, updateAccountResponse.payoutMethodCode) && Objects.equals(this.payoutSpeed, updateAccountResponse.payoutSpeed); } @Override public int hashCode() { return Objects.hash(accountCode, description, invalidFields, metadata, payoutSchedule, pspReference, resultCode, bankAccountUUID, payoutMethodCode, payoutSpeed); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class UpdateAccountResponse {\n"); sb.append(" accountCode: ").append(toIndentedString(accountCode)).append("\n"); sb.append(" description: ").append(toIndentedString(description)).append("\n"); sb.append(" invalidFields: ").append(toIndentedString(invalidFields)).append("\n"); sb.append(" metadata: ").append(toIndentedString(metadata)).append("\n"); sb.append(" payoutSchedule: ").append(toIndentedString(payoutSchedule)).append("\n"); sb.append(" pspReference: ").append(toIndentedString(pspReference)).append("\n"); sb.append(" resultCode: ").append(toIndentedString(resultCode)).append("\n"); sb.append(" bankAccountUUID").append(toIndentedString(bankAccountUUID)).append("\n"); sb.append(" payoutMethodCode").append(toIndentedString(payoutMethodCode)).append("\n"); sb.append(" payoutSpeed").append(toIndentedString(payoutSpeed)).append("\n"); sb.append("}"); return sb.toString(); } }
mit
Dubpubber/DManager
src/main/java/com/loneboat/dmanager/misc/ResourceAccessor.java
967
package com.loneboat.dmanager.misc; /* * com.loneboat.dmanager.misc.ResourceAccessor in DManager * Created by Tyler Crowe on 6/14/2017. * Website: https://loneboat.com * GitHub: https://github.com/Dubpubber * Machine Time: 2:52 PM */ import java.net.URL; /** * Helper class for fetching resources from the resources folder created by Maven. */ public class ResourceAccessor { public enum ScreenID { DM_MainInterface(getResource("DManager_MainInterface.fxml")), DMT_SpellSearcher(getResource("DManagerTool_SpellSearcher.fxml")); private URL path; ScreenID(URL path) { this.path = path; } public URL getURL() { return path; } } public static URL getResource(String fileName) { URL path = ResourceAccessor.class.getClassLoader().getResource(fileName); if(path != null && !path.getFile().isEmpty()) return path; else return null; } }
mit
highchair/hcd-trunk
models/page.php
11955
<?php class Pages extends ModelBase { function FindAll( $orderby = " id ASC" ) { return MyActiveRecord::FindAll('Pages', NULL, $orderby); } function FindById($id) { return MyActiveRecord::FindById('Pages', $id); } function FindByAreaAndName($area, $name) { $result = array_shift(MyActiveRecord::FindBySql('Pages', "SELECT p.* FROM pages p INNER JOIN areas_pages ap ON ap.pages_id = p.id INNER JOIN areas a ON a.id = ap.areas_id WHERE p.name like '" . $name . "' AND a.name like '" . $area->name . "' ORDER BY id ASC")); return ( ! empty($result) ) ? $result : false; } function FindPageOrIndex($area, $name, $isdraft=false) { $draftcond = ""; if ($isdraft) { $draftcond = "AND p.content_file = 'draft'"; } // if the page name is index and a specific "index" page isn't found, return the first page in the area as the index $found_pages = MyActiveRecord::FindBySql('Pages', "SELECT p.* FROM pages p INNER JOIN areas_pages ap ON ap.pages_id = p.id INNER JOIN areas a ON a.id = ap.areas_id WHERE p.name like '" . $name . "' $draftcond AND a.name like '" . $area->name . "' ORDER BY id ASC"); // index not found. select all pages ordered by display_order if($name == "index" && count($found_pages) == 0) { $found_pages = Pages::FindByArea($area); } else if(count($found_pages) == 0) { $all_area_pages = MyActiveRecord::FindBySql('Pages', "SELECT p.* FROM pages p INNER JOIN areas_pages ap ON ap.pages_id = p.id INNER JOIN areas a ON a.id = ap.areas_id WHERE a.name like '" . $area->name . "' ORDER BY id ASC"); if(SUB_PAGES) { foreach($all_area_pages as $page) { $all_children = $page->get_all_children(); foreach($all_children as $child) { if($child->name == $name) { return $child; } } } } } $page = array_shift($found_pages); // Now that we have a page, allow users logged in to see non-public pages. $user = Users::GetCurrentUser(); $logged_in = false; if($user) { $logged_in = true; } // If not logged in, make sure the first page returned is not a non-public page. Could throw an error. if(!$logged_in) { while ($page && $page->public == false) { $page = array_shift($found_pages); } } return $page; } function FindByArea($area, $public=false) { $public_condition = ( $public ) ? ' AND p.public = 1' : ''; return MyActiveRecord::FindBySql('Pages', "SELECT p.* FROM pages p INNER JOIN areas_pages ap ON ap.pages_id = p.id INNER JOIN areas a ON a.id = ap.areas_id WHERE a.name like '" . $area->name . "' AND p.name NOT LIKE '%-draft'".$public_condition." ORDER BY ap.display_order, id ASC"); } function delete($deleteChildren = true) { // unattach all the areas $areas = $this->getAreas(); foreach($areas as $area) { $this->detach($area); } $this->destroy(); } // ! - - - - - Get functions on the page object - - - - - function getContent() { /* * Trying to depreciate this function in favor of a more global get_content() but if a site has a blog or other static content, we get an error: * Fatal error: Call to undefined method StaticPage::the_content() in /htdocs/www/newsite/content/layouts/default.php on line 8 * So, we still need to use this function from time to time, esp on page objects */ if( $this->hasContentFile() ) { // We Need This! Used for static paths defined in the Routes require_once("../content/".$this->content_file.".php"); display_page_content(); } else { $this->the_content(); } } function displayPage( $pageid, $filtered=true ) { $page = Pages::FindById( $pageid ); if ( $filtered && $page->public ) { return $page->getContent(); } elseif ( $page->public ) { return $page->content; } } function getAreas() // returns more than one area (multi-dimensional array) even if page is only in one area { $parent = $this->get_parent(); if($parent) { return $parent->getAreas(); } return $this->find_linked('areas'); } function getOrderInArea($area) { if($area) { $query = "SELECT display_order FROM areas_pages WHERE pages_id = " . $this->id . " AND areas_id = " . $area->id; $result = mysql_Query($query, MyActiveRecord::Connection()); $data = @mysql_fetch_array($result); return $data["display_order"]; } } function updateSelectedAreas($changed_areas) // Used when edit_pages changes the areas a page is in { $selected_areas = $this->getAreas(); // look for added areas foreach($changed_areas as $changed_area) { $found = false; foreach($selected_areas as $selected_area) { if($selected_area->id == $changed_area) { $found = true; } } if(!$found) { $tmp_area = Areas::FindById($changed_area); $this->attach($tmp_area); } } // look for deleted areas foreach($selected_areas as $selected_area) { if(!in_array($selected_area->id, $changed_areas)) { //the user has removed this area $tmp_area = Areas::FindById($selected_area->id); $this->detach($tmp_area); } } } function get_parent() { return MyActiveRecord::FindById('Pages', $this->parent_page_id); } function get_children() { return MyActiveRecord::FindAll('Pages', "parent_page_id={$this->id}", 'display_order ASC'); } function get_all_children() { $children = $this->get_children(); foreach($children as $child) { array_merge($children, $child->get_children()); } return $children; } // ! - - - - - Sorting/Display functions - - - - - function updateOrderInArea($area, $order = 1) { if($area != null) { $updateQuery = "UPDATE areas_pages SET display_order = " . $order . " WHERE pages_id = " . $this->id . " AND areas_id = " . $area->id; $result = mysql_Query($updateQuery, MyActiveRecord::Connection()) or die(print_r($area)); } } function setDisplayOrderInArea() { $areas = $this->getAreas(); foreach ($areas as $area) { $query = "UPDATE areas_pages SET display_order = 1 WHERE pages_id = {$this->id} AND areas_id = {$area->id};"; mysql_query($query, MyActiveRecord::Connection()); // only update pages in the area that the page is in $display_order = 2; $pages = $area->findPages(true); foreach ($pages as $page) { if ($page->id != $this->id) { $query = "UPDATE areas_pages SET display_order = $display_order WHERE pages_id = {$page->id} AND areas_id = {$area->id};"; mysql_query($query, MyActiveRecord::Connection()); $display_order++; } } } } // ! - - - - - Templating functions - - - - - function hasContentFile() { if($this->content_file != "") { //return true; } return false; } function initialize() { if($this->hasContentFile()) { require_once("../content/$this->content_file.php"); initialize_page(); } } function getTemplateForArea($area) { // CYA if(!isset($area)) { return "default"; } // this page has an explicit template selected if($this->template != '') { return $this->template; } // this page inherits from either an area or a parent page if($this->parent_page_id > 0) { $parent = $this->get_parent(); return $parent->getTemplateForArea($area); } else { return $area->template; } } function getRelativeLinkPath() // Used when? { $parent = $this->get_parent(); if($parent) { return $parent->getRelativeLinkPath() . "/{$this->name}"; } if($this->name == "index") { return ""; } else { return "" . $this->name; } } function getDirectLinkPath( $withURL=false ) { // Return any area... we can't return a specific area with this function $area = $this->getAreas(); if ($withURL): return "http://".SITE_URL."/".$area->name."/".$this->name; else: return $area->name."/".$this->name; endif; } function isInPrivateArea() { $page_areas = $this->getAreas(); foreach($page_areas as $area) { if($area->public == 0) { return true; } } return false; } // ! - - - - - Draft Functions - - - - - function hasDraft() { $query = "SELECT * FROM pages WHERE content_file = 'draft' AND name = '{$this->name}' LIMIT 1;"; return MyActiveRecord::FindBySql('Pages', $query); } function killDraft() { $page_query = "SELECT * FROM pages WHERE content_file = '' AND name = '{$this->name}' LIMIT 1;"; $page = MyActiveRecord::FindBySql('Pages', $page_query); $query = "DELETE FROM pages WHERE id = {$this->id}"; mysql_query($query ,MyActiveRecord::Connection()) or die($query); return array_shift($page); } // ! - - - - - Clean Ups when the names of Insertables change - - - - - function UpdateImageReferences($oldName, $newName) { $pages = Pages::FindAll(); $anyImagePattern = "/([>{2}<{2}])$oldName([>{2}<{2}])/"; // The updateContent function is found in content_filter.php foreach($pages as $page) { $replacement = '$1' . $newName . '$2'; $page->content = updateContent($page->content, $anyImagePattern, $replacement); $page->save(); } } function UpdateDocumentReferences($oldName, $newName) { $pages = Pages::FindAll(); $anyDocumentPattern = "/{{2}(document:$oldName+){{2}/"; foreach($pages as $page) { $replacement = '{{document:' . $newName . '{{'; $page->content = updateContent($page->content, $anyDocumentPattern, $replacement); $page->save(); } } function UpdateProductReferences($oldName, $newName) { $pages = Pages::FindAll(); $anyProductPattern = "/{{2}(product:$oldName+){{2}/"; foreach($pages as $page) { $replacement = '{{product:' . $newName . '{{'; $page->content = updateContent($page->content, $anyProductPattern, $replacement); $page->save(); } } // Added Mar 18 2011 - WordPress-like edit button function function getPageEditLinks($area, $additional_button="") { if ( IsUserLoggedIn() ) { echo "<div id=\"admin-pane-controls\">\n"; echo "\t<h3>Admin Controls:</h3>\n"; echo "\t<a href=\"".get_link("admin/")."\">Dashboard</a>\n"; echo "\t<a href=\"".get_link("admin/edit_page/".$this->id)."\">Edit this Page</a>\n"; if ( $area->id != "1" ) { echo "\t<a href=\"".get_link("admin/edit_area/".$area->id)."\">Edit this Area</a>\n"; } echo "\t<a href=\"".get_link("admin/list_pages/")."\">List Pages</a>\n"; echo "\t<a href=\"".get_link("admin/add_page")."\">Add a Page</a>\n"; echo "\t<a href=\"".get_link("admin/edit_area/add")."\">Add an Area</a>\n"; if ( $additional_button != "" ) { echo $additional_button; } echo "\t<a href=\"".get_link( "admin/logout")."\">Logout</a>\n"; echo "</div>\n"; } } // Added January 19, 2012 - Make it easier to escape names all the time. Use the WordPress standard of "get" and "the" for return and echo, respectively. // Depreciated. Use the functions in common/model_base.php instead. function get_displayname() { return $this->get_title(); } function the_displayname() { echo $this->get_title(); } // ! - - - - - Alias function - - - - - Needed by the display_template function to check and see if we should redirect or not function checkAlias($selected_areas, $name) { foreach ($selected_areas as $areaid) { $area = Areas::FindById($areaid); $aliases = Alias::FindBySql('alias', "SELECT * FROM alias WHERE path LIKE '/{$area->name}/{$name}%' OR path LIKE '{$area->name}/{$name}%'"); if (count($aliases)) { foreach ($aliases as $alias) { $alias->path = "/{$area->name}/".$this->name; $alias->save(); } } } return false; } } ?>
mit
shunobaka/Negwork
Client/Negwork.Client.App/scripts/app/identity/register-controller.js
1143
(function () { 'use strict'; function RegisterController($location, notifier, auth) { var vm = this; vm.registerUser = function(user, form) { if (form.$valid) { user.gender = user.gender || "1"; auth.register(user) .then(function () { $location.path('/identity/login'); notifier.success('Registration successful!'); }, function (err) { var errorsModelState = err.data.ModelState; for (var modelError in errorsModelState) { for (var errorIndex in errorsModelState[modelError]) { notifier.error(errorsModelState[modelError][errorIndex]); } } }); } else { notifier.error('You shouldn\'t be doing this!'); } } } angular.module('negwork.controllers') .controller('RegisterController', ['$location', 'notifier', 'auth', RegisterController]); }());
mit
romanman/ethereumj-obsolete-prototype
src/main/java/org/ethereum/gui/BlockChainTable.java
4949
package org.ethereum.gui; import org.ethereum.core.Block; import org.ethereum.manager.WorldManager; import javax.swing.*; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.TableCellRenderer; import java.awt.*; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.StringSelection; import java.awt.event.*; /** * www.ethereumJ.com * @author: Roman Mandeleil * Created on: 15/05/14 12:36 */ public class BlockChainTable extends JFrame { private JPanel topPanel; private JTable table; private JScrollPane scrollPane; private int lastFindIndex = 0; ToolBar toolBar; public BlockChainTable(ToolBar toolBar) { this.toolBar = toolBar; addCloseAction(); final BlockChainTable blockchainTable = this; setTitle("Block Chain Table"); setSize(700, 400); setLocation(315, 180); setBackground(Color.gray); java.net.URL url = ClassLoader.getSystemResource("ethereum-icon.png"); Toolkit kit = Toolkit.getDefaultToolkit(); Image img = kit.createImage(url); this.setIconImage(img); // Create a panel to hold all other components topPanel = new JPanel(); topPanel.setLayout(new BorderLayout()); getContentPane().add(topPanel); // Create a new table getInstance() table = new JTable(); table.setModel(new BlockTableModel()); table.setFont(new Font("Courier New", Font.PLAIN, 13)); table.setForeground(Color.GRAY); table.setTableHeader(null); TableCellRenderer tcr = table.getDefaultRenderer(String.class); DefaultTableCellRenderer renderer = (DefaultTableCellRenderer) tcr; renderer.setHorizontalAlignment(SwingConstants.LEFT); renderer.setVerticalAlignment(SwingConstants.TOP); table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); table.setCellSelectionEnabled(true); table.setRowMargin(3); table.setRowHeight(420); table.getColumnModel().getColumn(0).setCellRenderer(new TableCellLongTextRenderer()); table.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_C, KeyEvent.CTRL_DOWN_MASK), "Copy"); table.getActionMap().put("Copy", new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { if (WorldManager.getInstance().getBlockchain().getSize() - 1 < lastFindIndex) return; Block block = WorldManager.getInstance().getBlockchain().getByNumber(lastFindIndex); StringSelection stsel = new StringSelection(block.toString()); Clipboard system = Toolkit.getDefaultToolkit().getSystemClipboard(); system.setContents(stsel,stsel); } }); table.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_F, KeyEvent.CTRL_DOWN_MASK), "Find"); table.getActionMap().put("Find", new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { String toFind = JOptionPane.showInputDialog(blockchainTable, "Find:", "Find in BlockChain", JOptionPane.QUESTION_MESSAGE); if (toFind.equals("")) { lastFindIndex = 0; return; } for (int i = lastFindIndex + 1; i < WorldManager.getInstance().getBlockchain().getSize(); ++i) { if (WorldManager.getInstance().getBlockchain().getSize() - 1 < i) return; Block block = WorldManager.getInstance().getBlockchain().getByNumber(i); boolean found = block.toString().toLowerCase().contains(toFind.toLowerCase()); if (found) { // TODO: now we find the first occur // TODO: in the future I should keep // TODO: all of them and allow to jump over them table.scrollRectToVisible(table.getCellRect(i, 0, true)); lastFindIndex = i; break; } } } }); table.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { lastFindIndex = ((JTable) (e.getSource())).rowAtPoint(e.getPoint()); super.mouseClicked(e); } }); // Add the table to a scrolling pane scrollPane = new JScrollPane(table); topPanel.add(scrollPane, BorderLayout.CENTER); } public void addCloseAction() { this.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { toolBar.chainToggle.setSelected(false); } }); } public static void main(String args[]) { BlockChainTable mainFrame = new BlockChainTable(null); mainFrame.setVisible(true); mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } }
mit
mandrive/YAK.Base
Yak.Services/Interfaces/IUserValidationService.cs
187
using Yak.DTO; namespace Yak.Services.Interfaces { public interface IUserValidationService : IService<User> { bool Validate(string username, string password); } }
mit
kedashoe/ramda
source/into.js
2033
import _clone from './internal/_clone'; import _curry3 from './internal/_curry3'; import _isTransformer from './internal/_isTransformer'; import _reduce from './internal/_reduce'; import _stepCat from './internal/_stepCat'; /** * Transforms the items of the list with the transducer and appends the * transformed items to the accumulator using an appropriate iterator function * based on the accumulator type. * * The accumulator can be an array, string, object or a transformer. Iterated * items will be appended to arrays and concatenated to strings. Objects will * be merged directly or 2-item arrays will be merged as key, value pairs. * * The accumulator can also be a transformer object that provides a 2-arity * reducing iterator function, step, 0-arity initial value function, init, and * 1-arity result extraction function result. The step function is used as the * iterator function in reduce. The result function is used to convert the * final accumulator into the return type and in most cases is R.identity. The * init function is used to provide the initial accumulator. * * The iteration is performed with [`R.reduce`](#reduce) after initializing the * transducer. * * @func * @memberOf R * @since v0.12.0 * @category List * @sig a -> (b -> b) -> [c] -> a * @param {*} acc The initial accumulator value. * @param {Function} xf The transducer function. Receives a transformer and returns a transformer. * @param {Array} list The list to iterate over. * @return {*} The final, accumulated value. * @example * * var numbers = [1, 2, 3, 4]; * var transducer = R.compose(R.map(R.add(1)), R.take(2)); * * R.into([], transducer, numbers); //=> [2, 3] * * var intoArray = R.into([]); * intoArray(transducer, numbers); //=> [2, 3] */ var into = _curry3(function into(acc, xf, list) { return _isTransformer(acc) ? _reduce(xf(acc), acc['@@transducer/init'](), list) : _reduce(xf(_stepCat(acc)), _clone(acc, [], [], false), list); }); export default into;
mit
fabiolourenzipucrs/scaling-journey
Monopoly3/edu/ncsu/monopoly/RailRoadCellTest.java
1947
package edu.ncsu.monopoly; import junit.framework.TestCase; public class RailRoadCellTest extends TestCase { GameMaster gameMaster; protected void setUp() { gameMaster = GameMaster.instance(); gameMaster.setGameBoard(new GameBoardRailRoad()); gameMaster.setNumberOfPlayers(2); gameMaster.reset(); gameMaster.setGUI(new MockGUI()); } public void testPlayerAction() { RailRoadCell cell = (RailRoadCell) gameMaster.getGameBoard().queryCell("Railroad A"); int cellIndex = gameMaster.getGameBoard().queryCellIndex("Railroad A"); gameMaster.movePlayer(0, cellIndex); gameMaster.getPlayer(0).purchase(); gameMaster.switchTurn(); gameMaster.movePlayer(1, cellIndex); cell.playAction(); assertEquals( 1500 - cell.getRent(), gameMaster.getPlayer(1).getMoney()); assertEquals( 1300 + cell.getRent(), gameMaster.getPlayer(0).getMoney()); } public void testPurchaseRailroad() { assertEquals(0, gameMaster.getPlayer(0).numberOfRR()); int cellIndex = gameMaster.getGameBoard().queryCellIndex("Railroad A"); gameMaster.movePlayer(0, cellIndex); gameMaster.getPlayer(0).purchase(); assertEquals(1300, gameMaster.getPlayer(0).getMoney()); assertEquals(1, gameMaster.getPlayer(0).numberOfRR()); } public void testRent() { RailRoadCell rr1 = (RailRoadCell) gameMaster.getGameBoard().queryCell("Railroad A"); int cellIndex1 = gameMaster.getGameBoard().queryCellIndex("Railroad A"); gameMaster.movePlayer(0, cellIndex1); gameMaster.getPlayer(0).purchase(); assertEquals(25, rr1.getRent()); RailRoadCell rr2 = (RailRoadCell) gameMaster.getGameBoard().queryCell("Railroad B"); int cellIndex2 = gameMaster.getGameBoard().queryCellIndex("Railroad B"); gameMaster.movePlayer(0, cellIndex2 - cellIndex1); gameMaster.getPlayer(0).purchase(); assertEquals(50, rr1.getRent()); assertEquals(50, rr2.getRent()); } }
mit
ylorant/HedgeBot
Core/Data/Provider.php
4359
<?php namespace HedgeBot\Core\Data; use ReflectionClass; /** * Class Provider * @package HedgeBot\Core\Data */ abstract class Provider { public $readonly = false; ///< Boolean, prevents writing to the data storage. protected static $classCache = []; ///< Storage class cache const STORAGE_NAME = ""; const STORAGE_PARAMETERS = ["readonly"]; /** * Loads a key from the storage. * The implemented method will allow to load data from the storage, in a transparent manner. * The user only has to provide the key to retrieve, * and the storage should be able to retrieve the data and all its children. * * @param $key The key to retrieve. * * @return mixed A mixed value containing the data. */ abstract public function get($key = null); /** * Saves a specific key into the storage. * The implemented version of this prototype must allow to store * a single key or a complex key in a completely transparent manner for the user. * * @param $key The key name to save the data as. String is preferred. * @param $data The data to save. Could be a scalar value like a complex value. * * @return bool True if the save succeeded, False otherwise. */ abstract public function set($key, $data); /** * Removes a specific key from the storage. * The implemented version of this prototype must allow to remove a single key, or to remove a tree * of nested complex data just by removing it's base branch. * * @param $key The key of the data to remove. String is preferred. * * @return bool True if the data has been deleted successfully, false otherwise. */ abstract public function remove($key = null); /** * Connects to the data source. * The method implementing this prototype will be used to connect to the data source. * * @param $parameters The data source parameters to connect with. Content can vary between data providers. * @return bool True if the connection to the source succeeded, False otherwise. */ abstract public function connect($parameters); /** * Resolves a storage from its name and returns its class name. * * @param $name The storage name. * @return bool|string The storage class if found, false if not. * * @throws \ReflectionException */ public static function resolveStorage($name) { $storageClasses = self::getStorageClasses(); if(!empty($storageClasses[$name])) { return $storageClasses[$name]; } return false; } /** * Gets the list of available storages. * */ public static function getStorageList() { $storageClasses = self::getStorageClasses(); return array_keys($storageClasses); } protected static function getStorageClasses() { // Refresh the storage classes cache if needed if(empty(self::$classCache)) { // Getting the current namespace to be able to load classes correctly $reflectionClass = new ReflectionClass(self::class); $currentNamespace = $reflectionClass->getNamespaceName(); // Classes to be ignored $ignoreClasses = array( 'ObjectAccess', 'Provider' ); // Scanning the directory of this file, which contains the other classes. $currentDir = scandir(__DIR__); foreach ($currentDir as $file) { if (!is_file(__DIR__ . '/' . $file)) { continue; } $className = str_replace('.php', '', $file); if (in_array($className, $ignoreClasses)) { continue; } $className = $currentNamespace . "\\" . $className; $storageName = $className::getName(); self::$classCache[$storageName] = $className; } } return self::$classCache; } /** * @return string */ public static function getName() { return static::STORAGE_NAME; } public static function getParameters() { return array_unique(array_merge(self::STORAGE_PARAMETERS, static::STORAGE_PARAMETERS)); } }
mit
Axodoss/FreeSLW4J
src/main/java/com/lukasheise/freeslw4j/openal/OpenALStaticSound.java
4872
package com.lukasheise.freeslw4j.openal; import com.lukasheise.freeslw4j.AudioFormat; import com.lukasheise.freeslw4j.Group; import com.lukasheise.freeslw4j.Priority; import com.lukasheise.freeslw4j.Sound; import com.lukasheise.freeslw4j.util.Fade; import static org.lwjgl.openal.AL10.*; import static org.lwjgl.openal.AL11.*; public class OpenALStaticSound implements Sound, OpenALSound { private OpenALAudioInterface ai; private Source source; private Buffer buffer; private Priority priority; private Group group; private Fade fade; public OpenALStaticSound(OpenALAudioInterface ai, Buffer buffer, Priority priority, Group group) { this.buffer = buffer; this.priority = priority; this.group = group; this.ai = ai; this.fade = new Fade(); this.source = new Source(); } @Override public void release() { OpenALConfiguration.getStaticSounds().remove(this); stop(); buffer.release(); } public Source getSource() { return source; } public Buffer getBuffer() { return buffer; } @Override public void update(float deltaTime) { if (fade.isActive() && isPlaying()) { source.setGainScale(fade.update(deltaTime)); } } @Override public String getName() { return buffer.getName(); } @Override public int getFrequency() { return buffer.getFrequency(); } @Override public AudioFormat getFormat() { return buffer.getFormat(); } @Override public boolean isStream() { return false; } @Override public void setGroup(Group id) { group = id; if (!ai.isGroupActive(id) && isPlaying()) { pause(); } } @Override public Group getGroup() { return group; } @Override public void setPriority(Priority priority) { this.priority = priority; } @Override public Priority getPriority() { return priority; } @Override public void play() { if (isPlaying()) { return; } if (source.beginSource(group,priority,buffer,true,true)) { alSourcePlay(source.getSource().sourceId); OpenALConfiguration.getPlayingSounds().add(this); } } @Override public void resume() { if (isPaused()) { alSourcePlay(source.getSource().sourceId); OpenALConfiguration.getPlayingSounds().add(this); } } @Override public void rewind() { if (source.hasSource()) { alSourceRewind(source.getSource().sourceId); } } @Override public void stop() { if (source.hasSource()) { alSourceStop(source.getSource().sourceId); source.endSource(); OpenALConfiguration.getPlayingSounds().remove(this); } } @Override public void pause() { if (source.hasSource()) { alSourcePause(source.getSource().sourceId); OpenALConfiguration.getPlayingSounds().remove(this); } } @Override public boolean isPlaying() { if (source.hasSource()) { int state = alGetSourcei(source.getSource().sourceId,AL_SOURCE_STATE); return (state == AL_PLAYING); } return false; } @Override public boolean isPaused() { if (source.hasSource()) { int state = alGetSourcei(source.getSource().sourceId,AL_SOURCE_STATE); return (state == AL_PAUSED); } return false; } @Override public void setLooping(boolean doLoop) { source.setLooping(doLoop,true); } @Override public boolean isLooping() { return source.isLooping(); } @Override public void setPosition(float x, float y, float z) { source.setPosition(x,y,z); } @Override public float[] getPosition() { return source.getPosition(); } @Override public void setVelocity(float x, float y, float z) { source.setVelocity(x,y,z); } @Override public float[] getVelocity() { return source.getVelocity(); } @Override public void setPitch(float p) { source.setPitch(p); } @Override public float getPitch() { return source.getPitch(); } @Override public void setGain(float g) { source.setGain(g); } @Override public float getGain() { return source.getGain(); } @Override public void setRolloff(float r) { source.setRolloff(r); } @Override public float getRolloff() { return source.getRolloff(); } @Override public void setDistance(float refDistance, float maxDistance) { source.setRefDistance(refDistance); source.setMaxDistance(maxDistance); } @Override public float[] getDistance() { return new float[] { source.getRefDistance(), source.getMaxDistance() }; } @Override public float getPlayDuration() { return (float)buffer.getLength() / 1000.0f; } @Override public float getPlayTime() { if (source.hasSource()) { return alGetSourcef(source.getSource().sourceId,AL_SEC_OFFSET); } return 0.0f; } @Override public void setPlayTime(float seconds) { if (source.hasSource()) { alSourcef(source.getSource().sourceId,AL_SEC_OFFSET,seconds); } } @Override public void fadeIn(float duration) { fade.begin(true,duration); } @Override public void fadeOut(float duration) { fade.begin(false,duration); } }
mit
FreeAllMedia/stimpak
es5/lib/stimpak/stimpak.render.js
2251
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = render; var _async = require("async"); var _async2 = _interopRequireDefault(_async); var _globToFileNames = require("../steps/globToFileNames.js"); var _globToFileNames2 = _interopRequireDefault(_globToFileNames); var _fileNamesToJobs = require("../steps/fileNamesToJobs.js"); var _fileNamesToJobs2 = _interopRequireDefault(_fileNamesToJobs); var _addMergeStrategiesToJobs = require("../steps/addMergeStrategiesToJobs.js"); var _addMergeStrategiesToJobs2 = _interopRequireDefault(_addMergeStrategiesToJobs); var _writeFileMixers = require("../steps/writeFileMixers.js"); var _writeFileMixers2 = _interopRequireDefault(_writeFileMixers); var _sortFileMixersByPathLength = require("../steps/sortFileMixersByPathLength.js"); var _sortFileMixersByPathLength2 = _interopRequireDefault(_sortFileMixersByPathLength); var _jobsToFileMixers = require("../steps/jobsToFileMixers.js"); var _jobsToFileMixers2 = _interopRequireDefault(_jobsToFileMixers); var _renderJobPaths = require("../steps/renderJobPaths.js"); var _renderJobPaths2 = _interopRequireDefault(_renderJobPaths); var _removeSkippedJobs = require("../steps/removeSkippedJobs.js"); var _removeSkippedJobs2 = _interopRequireDefault(_removeSkippedJobs); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function render(globString, directoryPath) { this.then(function (stimpak, thenDone) { _async2.default.waterfall([apply(_globToFileNames2.default, globString, directoryPath), apply(_fileNamesToJobs2.default, globString, directoryPath), apply(_removeSkippedJobs2.default, stimpak), apply(_renderJobPaths2.default, stimpak), apply(_removeSkippedJobs2.default, stimpak), apply(_addMergeStrategiesToJobs2.default, stimpak), apply(_jobsToFileMixers2.default, stimpak), _sortFileMixersByPathLength2.default, apply(_writeFileMixers2.default, stimpak)], thenDone); }); return this; } function apply(step) { for (var _len = arguments.length, values = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { values[_key - 1] = arguments[_key]; } return _async2.default.apply.apply(_async2.default, [step].concat(values)); }
mit
OpenTl/OpenTl.Schema
src/OpenTl.Schema/_generated/_Entities/MessageAction/TMessageActionPaymentSent.cs
821
// ReSharper disable All namespace OpenTl.Schema { using System; using System.Collections; using System.Text; using OpenTl.Schema; using OpenTl.Schema.Serialization.Attributes; [Serialize(0x40699cd0)] public sealed class TMessageActionPaymentSent : IMessageAction { /// <summary>Binary representation for the 'Currency' property</summary> [SerializationOrder(0)] public byte[] CurrencyAsBinary { get => _CurrencyAsBinary; set { _Currency = Encoding.UTF8.GetString(value); _CurrencyAsBinary = value; }} private byte[] _CurrencyAsBinary; private string _Currency; public string Currency { get => _Currency; set { CurrencyAsBinary = Encoding.UTF8.GetBytes(value); _Currency = value; }} [SerializationOrder(1)] public long TotalAmount {get; set;} } }
mit
GHoning/LevelswitcherIV
js/game.js
2052
/* Game namespace */ var game = { // an object where to store game information data : { // game levelList : ["level1", "level2", "level3"], levelIncrement : 0, score : 0, // menu selectedLevel : 0, }, // Run on page load. "onload" : function () { // Initialize the video. if (!me.video.init("screen", me.video.CANVAS, 640, 480,true, 'auto')) { alert("Your browser does not support HTML5 canvas."); return; } // add "#debug" to the URL to enable the debug Panel if (document.location.hash === "#debug") { window.onReady(function () { me.plugin.register.defer(this, me.debug.Panel, "debug", me.input.KEY.V); }); } // Set a callback to run when loading is complete. me.loader.onload = this.loaded.bind(this); // Load the resources. me.loader.preload(game.resources); // Initialize melonJS and display a loading screen. me.state.change(me.state.LOADING); }, // Run on game resources loaded. "loaded" : function () { me.state.set(me.state.MENU, new game.TitleScreen()); me.state.set(me.state.SETTINGS, new game.SettingsScreen()); me.state.set(me.state.USER, new game.LevelSetupScreen()); me.state.set(me.state.PLAY, new game.PlayScreen()); // add our player entity in the entity pool me.pool.register("mainPlayer", game.PlayerEntity); me.pool.register("CoinEntity", game.CoinEntity); me.pool.register("EnemyEntity", game.EnemyEntity); me.pool.register("LevelSwitchEntity", game.LevelSwitchEntity); // enable the keyboard me.input.bindKey(me.input.KEY.LEFT, "left"); me.input.bindKey(me.input.KEY.A, "left"); me.input.bindKey(me.input.KEY.RIGHT, "right"); me.input.bindKey(me.input.KEY.D, "right"); me.input.bindKey(me.input.KEY.X, "jump", true); me.input.bindKey(me.input.KEY.SPACE, "jump", true); me.input.bindKey(me.input.KEY.W, "jump", true); // Start the game. me.state.change(me.state.MENU); } };
mit
revnode/todo
todo-ui/js/todo.js
2127
var todo = r.singleton({ use: [ pages_login, pages_register, pages_todo ], 'private local': { token: null, todos: [], sort: { column: 'priority', order: 'ASC' } }, 'private dom': { content: r.$('div#content'), form: null, message: null }, 'public initialize': function() { this.render_login(); }, 'public rpc': function(response) { if(response.code) { this.render_error(response.reason, 'error'); } else { switch(response.method + ' ' + response.entity) { case 'POST token': case 'GET token': this.local.user = response.user; this.local.token = response.token; r.xhr.rpc('todos', 'GET', {user:this.local.user, token:this.local.token}, this.rpc, this); break; case 'GET todos': this.local.todos = response.todos; this.render_todo(); break; case 'DELETE todo': delete this.local.todos[response.id]; this.render_todo(); break; case 'PUT todo': case 'POST todo': delete response.method; delete response.entity; var id = response.id; delete response.id; this.local.todos[id] = response; this.render_todo(); break; } } }, 'private render_error': function(message, type) { r.inject( div({c:['message', (type || 'info')]}, div({c:'table'}, div({c:'column_10'}, '&nbsp;'), div({c:'column_80'}, message ), div({c:['column_10', 'align_right']}, a({ c:['none', 'font_large', 'font_bold'], href:'#', e: { click: function(event) { event.preventDefault(); r._(this.dom.message); }.bind(this) } }, '×' ) ) ) ), r._(this.dom.message) ); return this; } });
mit
tomitrescak/meteor-boilerplate-typescript
src/lib/libImports.d.ts
390
/// <reference path="../../typescript/meteor/meteor.d.ts" /> /// <reference path="../../typescript/packages/subsManager.d.ts" /> /// <reference path="../../typescript/packages/jquery.d.ts" /> /// <reference path="../../typescript/packages/ironRouter.d.ts" /> /// <reference path="../../typescript/packages/roles.d.ts" /> /// <reference path="../../typescript/packages/messageFormat.d.ts" />
mit
jackjoe/laravel-yaml-translation
src/JackJoe/Core/Translation/TranslationServiceProvider.php
517
<?php namespace JackJoe\Core\Translation; use \Illuminate\Translation\TranslationServiceProvider as IlluminateTranslationServiceProvider; class TranslationServiceProvider extends IlluminateTranslationServiceProvider { /** * Register the translation line loader. * Add support for YAML files. * * @return void */ protected function registerLoader() { $this->app->singleton('translation.loader', function($app) { return new YamlFileLoader($app['files'], $app['path.lang']); }); } }
mit
olykken/CMS_VR
Resources/ItemContainer.cs
732
using UnityEngine; using System.Collections; using System.Collections.Generic; using System.Xml.Serialization; using System.IO; [XmlRoot("ItemCollection")] public class ItemContainer { [XmlArray("Items")] [XmlArrayItem("Item")] public List<Item> items = new List<Item>(); public static ItemContainer Load(string path) { TextAsset _xml = Resources.Load<TextAsset>(path); Debug.Log ("path = " + path); Debug.Log ("text = " + _xml.text); XmlSerializer serializer = new XmlSerializer (typeof(ItemContainer)); StringReader reader = new StringReader (_xml.text); ItemContainer items = serializer.Deserialize (reader) as ItemContainer; reader.Close (); return items; } }
mit
yugui/rubyspec
1.8/core/array/eql_spec.rb
1103
require File.dirname(__FILE__) + '/../../spec_helper' require File.dirname(__FILE__) + '/fixtures/classes' describe "Array#eql?" do it "returns true if other is the same array" do a, b = [1], [2] a.should_not eql(b) a.should eql(a) end it "returns true if other has the same length and elements" do a = [1, 2, 3, 4] b = [1, 2, 3, 4] c = [1, 2] d = ['a', 'b', 'c', 'd'] a.should eql(b) a.should_not eql(c) a.should_not eql(d) [].should eql([]) end it "properly handles recursive arrays" do empty = ArraySpecs.empty_recursive_array empty2 = []; empty2 << empty2 empty.should eql(empty.dup) empty.should_not eql(empty2) array = ArraySpecs.recursive_array array.should eql(array) array.should eql(array.dup) array.should_not eql(empty) array.should_not eql([1, 2]) end it "ignores array class differences" do ArraySpecs::MyArray[1, 2, 3].should eql([1, 2, 3]) ArraySpecs::MyArray[1, 2, 3].should eql(ArraySpecs::MyArray[1, 2, 3]) [1, 2, 3].should eql(ArraySpecs::MyArray[1, 2, 3]) end end
mit
Infragistics/zero-blocks
projects/igniteui-angular/src/lib/data-operations/grouping-strategy.ts
700
import { IGroupByRecord } from './groupby-record.interface'; import { IgxSorting } from './sorting-strategy'; import { IGroupingState } from './groupby-state.interface'; import { IGroupByResult } from './grouping-result.interface'; export class IgxGrouping extends IgxSorting { public groupBy(data: any[], state: IGroupingState, grid?: any, groupsRecords?: any[], fullResult: IGroupByResult = { data: [], metadata: [] }): IGroupByResult { const metadata: IGroupByRecord[] = []; const grouping = this.groupDataRecursive(data, state, 0, null, metadata, grid, groupsRecords, fullResult); return { data: grouping, metadata }; } }
mit
stivalet/PHP-Vulnerability-test-suite
XSS/CWE_79/unsafe/CWE_79__array-GET__no_sanitizing__Use_untrusted_data_script-doublequoted_Event_Handler.php
1350
<!-- Unsafe sample input : get the $_GET['userData'] in an array sanitize : none File : use of untrusted data in a double quoted event handler in a script --> <!--Copyright 2015 Bertrand STIVALET Permission is hereby granted, without written agreement or royalty fee, to use, copy, modify, and distribute this software and its documentation for any purpose, provided that the above copyright notice and the following three paragraphs appear in all copies of this software. IN NO EVENT SHALL AUTHORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. AUTHORS SPECIFICALLY DISCLAIM ANY WARRANTIES INCLUDING, BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THE SOFTWARE IS PROVIDED ON AN "AS-IS" BASIS AND AUTHORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.--> <!DOCTYPE html> <html> <head/> <body> <?php $array = array(); $array[] = 'safe' ; $array[] = $_GET['userData'] ; $array[] = 'safe' ; $tainted = $array[1] ; //no_sanitizing //flaw echo "<div onmouseover=\"x=\"". $tainted ."\"\>"; ?> <h1>Hello World!</h1> </div> </body> </html>
mit
bellycard/crud_client
lib/init.rb
93
Kernel::silence_warnings { Imprint::Tracer.const_set('TRACER_HEADER', 'HTTP_X_B3_TRACEID') }
mit
yogeshsaroya/new-cdnjs
ajax/libs/yui/3.17.0/node-load/node-load-coverage.js
129
version https://git-lfs.github.com/spec/v1 oid sha256:d43b821a7d61860a6cdf1bcdfdd1edc25aa8628e0f937efccfdc3bf76fadd23e size 6811
mit
erikringsmuth/suri
app-built/bower_components/ace/lib/ace/snippets/tcl.js
157
define(["require","exports","module","../requirejs/text!./tcl.snippets"],function(e,t,n){t.snippetText=e("../requirejs/text!./tcl.snippets"),t.scope="tcl"});
mit
pezra/hal-client
spec/hal_client/representation_future_spec.rb
1809
require 'hal-client' RSpec.describe HalClient::RepresentationFuture do describe ".new" do specify { expect( HalClient::RepresentationFuture.new("http://example.com", HalClient.new) ).to behave_like_a HalClient::Representation } end subject { HalClient::RepresentationFuture.new("http://example.com", HalClient.new) } describe "#href" do it "doesn't make a request" do req = stub_request(:get, "http://example.com") subject.href expect(req).not_to have_been_made end specify { expect( subject.href ).to eq "http://example.com" } end describe "#location" do it "doesn't make a request" do req = stub_request(:get, "http://example.com") subject.location expect(req).not_to have_been_made end specify { expect( subject.location ).to eq "http://example.com" } end describe "#to_s" do it "doesn't make a request" do req = stub_request(:get, "http://example.com") subject.to_s expect(req).not_to have_been_made end specify { expect( subject.to_s ).to include "http://example.com" } end describe "#inspect" do it "doesn't make a request" do req = stub_request(:get, "http://example.com") subject.inspect expect(req).not_to have_been_made end specify { expect( subject.inspect ).to include "http://example.com" } end describe "#pretty_print" do it "doesn't make a request" do req = stub_request(:get, "http://example.com") pp_str(subject) expect(req).not_to have_been_made end specify { expect( pp_str(subject) ).to include "http://example.com" } def pp_str(obj) out = "" pp = PrettyPrint.new(out) obj.pretty_print(pp) pp.flush out end end end
mit
louk/prototype
src/prototype/dom/layout.js
58428
(function() { // Converts a CSS percentage value to a decimal. // Ex: toDecimal("30%"); // -> 0.3 function toDecimal(pctString) { var match = pctString.match(/^(\d+)%?$/i); if (!match) return null; return (Number(match[1]) / 100); } // A bare-bones version of Element.getStyle. Needed because getStyle is // public-facing and too user-friendly for our tastes. We need raw, // non-normalized values. // // Camel-cased property names only. function getRawStyle(element, style) { element = $(element); // Try inline styles first. var value = element.style[style]; if (!value || value === 'auto') { // Reluctantly retrieve the computed style. var css = document.defaultView.getComputedStyle(element, null); value = css ? css[style] : null; } if (style === 'opacity') return value ? parseFloat(value) : 1.0; return value === 'auto' ? null : value; } function getRawStyle_IE(element, style) { // Try inline styles first. var value = element.style[style]; if (!value && element.currentStyle) { // Reluctantly retrieve the current style. value = element.currentStyle[style]; } return value; } // Quickly figures out the content width of an element. Used instead of // `element.measure('width')` in several places below; we don't want to // call back into layout code recursively if we don't have to. // // But this means it doesn't handle edge cases. Use it when you know the // element in question is visible and will give accurate measurements. function getContentWidth(element, context) { var boxWidth = element.offsetWidth; var bl = getPixelValue(element, 'borderLeftWidth', context) || 0; var br = getPixelValue(element, 'borderRightWidth', context) || 0; var pl = getPixelValue(element, 'paddingLeft', context) || 0; var pr = getPixelValue(element, 'paddingRight', context) || 0; return boxWidth - bl - br - pl - pr; } if ('currentStyle' in document.documentElement) { getRawStyle = getRawStyle_IE; } // Can be called like this: // getPixelValue("11px"); // Or like this: // getPixelValue(someElement, 'paddingTop'); function getPixelValue(value, property, context) { var element = null; if (Object.isElement(value)) { element = value; value = getRawStyle(element, property); } if (value === null || Object.isUndefined(value)) { return null; } // Non-IE browsers will always return pixels if possible. // (We use parseFloat instead of parseInt because Firefox can return // non-integer pixel values.) if ((/^(?:-)?\d+(\.\d+)?(px)?$/i).test(value)) { return window.parseFloat(value); } var isPercentage = value.include('%'), isViewport = (context === document.viewport); // When IE gives us something other than a pixel value, this technique // (invented by Dean Edwards) will convert it to pixels. // // (This doesn't work for percentage values on elements with `position: fixed` // because those percentages are relative to the viewport.) if (/\d/.test(value) && element && element.runtimeStyle && !(isPercentage && isViewport)) { var style = element.style.left, rStyle = element.runtimeStyle.left; element.runtimeStyle.left = element.currentStyle.left; element.style.left = value || 0; value = element.style.pixelLeft; element.style.left = style; element.runtimeStyle.left = rStyle; return value; } // For other browsers, we have to do a bit of work. // (At this point, only percentages should be left; all other CSS units // are converted to pixels by getComputedStyle.) if (element && isPercentage) { // The `context` argument comes into play for percentage units; it's // the thing that the unit represents a percentage of. When an // absolutely-positioned element has a width of 50%, we know that's // 50% of its offset parent. If it's `position: fixed` instead, we know // it's 50% of the viewport. And so on. context = context || element.parentNode; var decimal = toDecimal(value), whole = null; var isHorizontal = property.include('left') || property.include('right') || property.include('width'); var isVertical = property.include('top') || property.include('bottom') || property.include('height'); if (context === document.viewport) { if (isHorizontal) { whole = document.viewport.getWidth(); } else if (isVertical) { whole = document.viewport.getHeight(); } } else { if (isHorizontal) { whole = $(context).measure('width'); } else if (isVertical) { whole = $(context).measure('height'); } } return (whole === null) ? 0 : whole * decimal; } // If we get this far, we should probably give up. return 0; } // Turns plain numbers into pixel measurements. function toCSSPixels(number) { if (Object.isString(number) && number.endsWith('px')) return number; return number + 'px'; } // Shortcut for figuring out if an element is `display: none` or not. function isDisplayed(element) { while (element && element.parentNode) { var display = element.getStyle('display'); if (display === 'none') { return false; } element = $(element.parentNode); } return true; } // In IE6-7, positioned elements often need hasLayout triggered before they // report accurate measurements. var hasLayout = Prototype.K; if ('currentStyle' in document.documentElement) { hasLayout = function(element) { if (!element.currentStyle.hasLayout) { element.style.zoom = 1; } return element; }; } // Converts the layout hash property names back to the CSS equivalents. // For now, only the border properties differ. function cssNameFor(key) { if (key.include('border')) key = key + '-width'; return key.camelize(); } /** * class Element.Layout < Hash * * A set of key/value pairs representing measurements of various * dimensions of an element. * * <h4>Overview</h4> * * The `Element.Layout` class is a specialized way to measure elements. * It helps mitigate: * * * The convoluted steps often needed to get common measurements for * elements. * * The tendency of browsers to report measurements in non-pixel units. * * The quirks that lead some browsers to report inaccurate measurements. * * The difficulty of measuring elements that are hidden. * * <h4>Usage</h4> * * Instantiate an `Element.Layout` class by passing an element into the * constructor: * * var layout = new Element.Layout(someElement); * * You can also use [[Element.getLayout]], if you prefer. * * Once you have a layout object, retrieve properties using [[Hash]]'s * familiar `get` and `set` syntax. * * layout.get('width'); //-> 400 * layout.get('top'); //-> 180 * * The following are the CSS-related properties that can be retrieved. * Nearly all of them map directly to their property names in CSS. (The * only exception is for borders — e.g., `border-width` instead of * `border-left-width`.) * * * `height` * * `width` * * `top` * * `left` * * `right` * * `bottom` * * `border-left` * * `border-right` * * `border-top` * * `border-bottom` * * `padding-left` * * `padding-right` * * `padding-top` * * `padding-bottom` * * `margin-top` * * `margin-bottom` * * `margin-left` * * `margin-right` * * In addition, these "composite" properties can be retrieved: * * * `padding-box-width` (width of the content area, from the beginning of * the left padding to the end of the right padding) * * `padding-box-height` (height of the content area, from the beginning * of the top padding to the end of the bottom padding) * * `border-box-width` (width of the content area, from the outer edge of * the left border to the outer edge of the right border) * * `border-box-height` (height of the content area, from the outer edge * of the top border to the outer edge of the bottom border) * * `margin-box-width` (width of the content area, from the beginning of * the left margin to the end of the right margin) * * `margin-box-height` (height of the content area, from the beginning * of the top margin to the end of the bottom margin) * * <h4>Caching</h4> * * Because these properties can be costly to retrieve, `Element.Layout` * behaves differently from an ordinary [[Hash]]. * * First: by default, values are "lazy-loaded" — they aren't computed * until they're retrieved. To measure all properties at once, pass * a second argument into the constructor: * * var layout = new Element.Layout(someElement, true); * * Second: once a particular value is computed, it's cached. Asking for * the same property again will return the original value without * re-computation. This means that **an instance of `Element.Layout` * becomes stale when the element's dimensions change**. When this * happens, obtain a new instance. * * <h4>Hidden elements</h4> * * Because it's a common case to want the dimensions of a hidden element * (e.g., for animations), it's possible to measure elements that are * hidden with `display: none`. * * However, **it's only possible to measure a hidden element if its parent * is visible**. If its parent (or any other ancestor) is hidden, any * width and height measurements will return `0`, as will measurements for * `top|bottom|left|right`. * **/ Element.Layout = Class.create(Hash, { /** * new Element.Layout(element[, preCompute = false]) * - element (Element): The element to be measured. * - preCompute (Boolean): Whether to compute all values at once. Default * is `false`. * * Declare a new layout hash. * * The `preCompute` argument determines whether measurements will be * lazy-loaded or not. If you plan to use many different measurements, * it's often more performant to pre-compute, as it minimizes the * amount of overhead needed to measure. If you need only one or two * measurements, it's probably not worth it. **/ initialize: function($super, element, preCompute) { $super(); this.element = $(element); // nullify all properties keys Element.Layout.PROPERTIES.each( function(property) { this._set(property, null); }, this); // The 'preCompute' boolean tells us whether we should fetch all values // at once. If so, we should do setup/teardown only once. We set a flag // so that we can ignore calls to `_begin` and `_end` elsewhere. if (preCompute) { this._preComputing = true; this._begin(); Element.Layout.PROPERTIES.each( this._compute, this ); this._end(); this._preComputing = false; } }, _set: function(property, value) { return Hash.prototype.set.call(this, property, value); }, // TODO: Investigate. set: function(property, value) { throw "Properties of Element.Layout are read-only."; }, /** * Element.Layout#get(property) -> Number * - property (String): One of the properties defined in * [[Element.Layout.PROPERTIES]]. * * Retrieve the measurement specified by `property`. Will throw an error * if the property is invalid. * * ##### Caveats * * * `Element.Layout` can measure the dimensions of an element hidden with * CSS (`display: none`), but _only_ if its parent element is visible. **/ get: function($super, property) { // Try to fetch from the cache. var value = $super(property); return value === null ? this._compute(property) : value; }, // `_begin` and `_end` are two functions that are called internally // before and after any measurement is done. In certain conditions (e.g., // when hidden), elements need a "preparation" phase that ensures // accuracy of measurements. _begin: function() { if (this._isPrepared()) return; var element = this.element; if (isDisplayed(element)) { this._setPrepared(true); return; } // If we get this far, it means this element is hidden. To get usable // measurements, we must remove `display: none`, but in a manner that // isn't noticeable to the user. That means we also set // `visibility: hidden` to make it invisible, and `position: absolute` // so that it won't alter the document flow when displayed. // // Once we do this, the element is "prepared," and we can make our // measurements. When we're done, the `_end` method cleans up our // changes. // Remember the original values for some styles we're going to alter. var originalStyles = { position: element.style.position || '', width: element.style.width || '', visibility: element.style.visibility || '', display: element.style.display || '' }; // We store them so that the `_end` method can retrieve them later. element.store('prototype_original_styles', originalStyles); var position = getRawStyle(element, 'position'), width = element.offsetWidth; if (width === 0 || width === null) { // Opera/IE won't report the true width of the element through // `getComputedStyle` if it's hidden. If we got a nonsensical value, // we need to show the element and try again. element.style.display = 'block'; width = element.offsetWidth; } // Preserve the context in case we get a percentage value. var context = (position === 'fixed') ? document.viewport : element.parentNode; var tempStyles = { visibility: 'hidden', display: 'block' }; // If the element's `position: fixed`, it's already out of the document // flow, so it's both unnecessary and inaccurate to set // `position: absolute`. if (position !== 'fixed') tempStyles.position = 'absolute'; element.setStyle(tempStyles); var positionedWidth = element.offsetWidth, newWidth; if (width && (positionedWidth === width)) { // If the element's width is the same both before and after // we set absolute positioning, that means: // (a) it was already absolutely-positioned; or // (b) it has an explicitly-set width, instead of width: auto. // Either way, it means the element is the width it needs to be // in order to report an accurate height. newWidth = getContentWidth(element, context); } else if (position === 'absolute' || position === 'fixed') { // Absolute- and fixed-position elements' dimensions don't depend // upon those of their parents. newWidth = getContentWidth(element, context); } else { // Otherwise, the element's width depends upon the width of its // parent. var parent = element.parentNode, pLayout = $(parent).getLayout(); newWidth = pLayout.get('width') - this.get('margin-left') - this.get('border-left') - this.get('padding-left') - this.get('padding-right') - this.get('border-right') - this.get('margin-right'); } // Whatever the case, we've now figured out the correct `width` value // for the element. element.setStyle({ width: newWidth + 'px' }); // The element is now ready for measuring. this._setPrepared(true); }, _end: function() { var element = this.element; var originalStyles = element.retrieve('prototype_original_styles'); element.store('prototype_original_styles', null); element.setStyle(originalStyles); this._setPrepared(false); }, _compute: function(property) { var COMPUTATIONS = Element.Layout.COMPUTATIONS; if (!(property in COMPUTATIONS)) { throw "Property not found."; } return this._set(property, COMPUTATIONS[property].call(this, this.element)); }, _isPrepared: function() { return this.element.retrieve('prototype_element_layout_prepared', false); }, _setPrepared: function(bool) { return this.element.store('prototype_element_layout_prepared', bool); }, /** * Element.Layout#toObject([keys...]) -> Object * - keys (String): A space-separated list of keys to include. * * Converts the layout hash to a plain object of key/value pairs, * optionally including only the given keys. * * Keys can be passed into this method as individual arguments _or_ * separated by spaces within a string. * * // Equivalent statements: * someLayout.toObject('top', 'bottom', 'left', 'right'); * someLayout.toObject('top bottom left right'); **/ toObject: function() { var args = $A(arguments); var keys = (args.length === 0) ? Element.Layout.PROPERTIES : args.join(' ').split(' '); var obj = {}; keys.each( function(key) { // Key needs to be a valid Element.Layout property. if (!Element.Layout.PROPERTIES.include(key)) return; var value = this.get(key); if (value != null) obj[key] = value; }, this); return obj; }, /** * Element.Layout#toHash([keys...]) -> Hash * - keys (String): A space-separated list of keys to include. * * Converts the layout hash to an ordinary hash of key/value pairs, * optionally including only the given keys. * * Keys can be passed into this method as individual arguments _or_ * separated by spaces within a string. * * // Equivalent statements: * someLayout.toHash('top', 'bottom', 'left', 'right'); * someLayout.toHash('top bottom left right'); **/ toHash: function() { var obj = this.toObject.apply(this, arguments); return new Hash(obj); }, /** * Element.Layout#toCSS([keys...]) -> Object * - keys (String): A space-separated list of keys to include. * * Converts the layout hash to a plain object of CSS property/value * pairs, optionally including only the given keys. * * Keys can be passed into this method as individual arguments _or_ * separated by spaces within a string. * * // Equivalent statements: * someLayout.toCSS('top', 'bottom', 'left', 'right'); * someLayout.toCSS('top bottom left right'); * * Useful for passing layout properties to [[Element.setStyle]]. **/ toCSS: function() { var args = $A(arguments); var keys = (args.length === 0) ? Element.Layout.PROPERTIES : args.join(' ').split(' '); var css = {}; keys.each( function(key) { // Key needs to be a valid Element.Layout property... if (!Element.Layout.PROPERTIES.include(key)) return; // ...but not a composite property. if (Element.Layout.COMPOSITE_PROPERTIES.include(key)) return; var value = this.get(key); if (value != null) css[cssNameFor(key)] = value + 'px'; }, this); return css; }, inspect: function() { return "#<Element.Layout>"; } }); Object.extend(Element.Layout, { /** * Element.Layout.PROPERTIES = Array * * A list of all measurable properties. **/ PROPERTIES: $w('height width top left right bottom border-left border-right border-top border-bottom padding-left padding-right padding-top padding-bottom margin-top margin-bottom margin-left margin-right padding-box-width padding-box-height border-box-width border-box-height margin-box-width margin-box-height'), /** * Element.Layout.COMPOSITE_PROPERTIES = Array * * A list of all composite properties. Composite properties don't map * directly to CSS properties — they're combinations of other * properties. **/ COMPOSITE_PROPERTIES: $w('padding-box-width padding-box-height margin-box-width margin-box-height border-box-width border-box-height'), COMPUTATIONS: { 'height': function(element) { if (!this._preComputing) this._begin(); var bHeight = this.get('border-box-height'); if (bHeight <= 0) { if (!this._preComputing) this._end(); return 0; } var bTop = this.get('border-top'), bBottom = this.get('border-bottom'); var pTop = this.get('padding-top'), pBottom = this.get('padding-bottom'); if (!this._preComputing) this._end(); return bHeight - bTop - bBottom - pTop - pBottom; }, 'width': function(element) { if (!this._preComputing) this._begin(); var bWidth = this.get('border-box-width'); if (bWidth <= 0) { if (!this._preComputing) this._end(); return 0; } var bLeft = this.get('border-left'), bRight = this.get('border-right'); var pLeft = this.get('padding-left'), pRight = this.get('padding-right'); if (!this._preComputing) this._end(); return bWidth - bLeft - bRight - pLeft - pRight; }, 'padding-box-height': function(element) { var height = this.get('height'), pTop = this.get('padding-top'), pBottom = this.get('padding-bottom'); return height + pTop + pBottom; }, 'padding-box-width': function(element) { var width = this.get('width'), pLeft = this.get('padding-left'), pRight = this.get('padding-right'); return width + pLeft + pRight; }, 'border-box-height': function(element) { if (!this._preComputing) this._begin(); var height = element.offsetHeight; if (!this._preComputing) this._end(); return height; }, 'border-box-width': function(element) { if (!this._preComputing) this._begin(); var width = element.offsetWidth; if (!this._preComputing) this._end(); return width; }, 'margin-box-height': function(element) { var bHeight = this.get('border-box-height'), mTop = this.get('margin-top'), mBottom = this.get('margin-bottom'); if (bHeight <= 0) return 0; return bHeight + mTop + mBottom; }, 'margin-box-width': function(element) { var bWidth = this.get('border-box-width'), mLeft = this.get('margin-left'), mRight = this.get('margin-right'); if (bWidth <= 0) return 0; return bWidth + mLeft + mRight; }, 'top': function(element) { var offset = element.positionedOffset(); return offset.top; }, 'bottom': function(element) { var offset = element.positionedOffset(), parent = element.getOffsetParent(), pHeight = parent.measure('height'); var mHeight = this.get('border-box-height'); return pHeight - mHeight - offset.top; // // return getPixelValue(element, 'bottom'); }, 'left': function(element) { var offset = element.positionedOffset(); return offset.left; }, 'right': function(element) { var offset = element.positionedOffset(), parent = element.getOffsetParent(), pWidth = parent.measure('width'); var mWidth = this.get('border-box-width'); return pWidth - mWidth - offset.left; // // return getPixelValue(element, 'right'); }, 'padding-top': function(element) { return getPixelValue(element, 'paddingTop'); }, 'padding-bottom': function(element) { return getPixelValue(element, 'paddingBottom'); }, 'padding-left': function(element) { return getPixelValue(element, 'paddingLeft'); }, 'padding-right': function(element) { return getPixelValue(element, 'paddingRight'); }, 'border-top': function(element) { return getPixelValue(element, 'borderTopWidth'); }, 'border-bottom': function(element) { return getPixelValue(element, 'borderBottomWidth'); }, 'border-left': function(element) { return getPixelValue(element, 'borderLeftWidth'); }, 'border-right': function(element) { return getPixelValue(element, 'borderRightWidth'); }, 'margin-top': function(element) { return getPixelValue(element, 'marginTop'); }, 'margin-bottom': function(element) { return getPixelValue(element, 'marginBottom'); }, 'margin-left': function(element) { return getPixelValue(element, 'marginLeft'); }, 'margin-right': function(element) { return getPixelValue(element, 'marginRight'); } } }); // An easier way to compute right and bottom offsets. if ('getBoundingClientRect' in document.documentElement) { Object.extend(Element.Layout.COMPUTATIONS, { 'right': function(element) { var parent = hasLayout(element.getOffsetParent()); var rect = element.getBoundingClientRect(), pRect = parent.getBoundingClientRect(); return (pRect.right - rect.right).round(); }, 'bottom': function(element) { var parent = hasLayout(element.getOffsetParent()); var rect = element.getBoundingClientRect(), pRect = parent.getBoundingClientRect(); return (pRect.bottom - rect.bottom).round(); } }); } /** * class Element.Offset * * A representation of the top- and left-offsets of an element relative to * another. * * All methods that compute offsets return an instance of `Element.Offset`. * **/ Element.Offset = Class.create({ /** * new Element.Offset(left, top) * * Instantiates an [[Element.Offset]]. You shouldn't need to call this * directly. **/ initialize: function(left, top) { this.left = left.round(); this.top = top.round(); // Act like an array. this[0] = this.left; this[1] = this.top; }, /** * Element.Offset#relativeTo(offset) -> Element.Offset * - offset (Element.Offset): Another offset to compare to. * * Returns a new [[Element.Offset]] with its origin at the given * `offset`. Useful for determining an element's distance from another * arbitrary element. **/ relativeTo: function(offset) { return new Element.Offset( this.left - offset.left, this.top - offset.top ); }, /** * Element.Offset#inspect() -> String * * Returns a debug-friendly representation of the offset. **/ inspect: function() { return "#<Element.Offset left: #{left} top: #{top}>".interpolate(this); }, /** * Element.Offset#toString() -> String **/ toString: function() { return "[#{left}, #{top}]".interpolate(this); }, /** * Element.Offset#toArray() -> Array * * Returns an array representation fo the offset in [x, y] format. **/ toArray: function() { return [this.left, this.top]; } }); /** * Element.getLayout(@element[, preCompute = false]) -> Element.Layout * - element (Element): The element to be measured. * - preCompute (Boolean): Whether to compute all values at once. Default * is `false`. * * Returns an instance of [[Element.Layout]] for measuring an element's * dimensions. * * Note that this method returns a _new_ `Element.Layout` object each time * it's called. If you want to take advantage of measurement caching, * retain a reference to one `Element.Layout` object, rather than calling * `Element.getLayout` whenever you need a measurement. You should call * `Element.getLayout` again only when the values in an existing * `Element.Layout` object have become outdated. * * If the `preCompute` argument is `true`, all properties will be measured * when the layout object is instantiated. If you plan to measure several * properties of an element's dimensions, it's probably worth it to get a * pre-computed hash. * * ##### Examples * * var layout = $('troz').getLayout(); * * layout.get('width'); //-> 150 * layout.get('height'); //-> 500 * layout.get('padding-left'); //-> 10 * layout.get('margin-left'); //-> 25 * layout.get('border-top'); //-> 5 * layout.get('border-bottom'); //-> 5 * * // Won't re-compute width; remembers value from first time. * layout.get('width'); //-> 150 * * // Composite values obtained by adding together other properties; * // will re-use any values we've already looked up above. * layout.get('padding-box-width'); //-> 170 * layout.get('border-box-height'); //-> 510 * * ##### Caveats * * * Instances of `Element.Layout` can measure the dimensions of an * element hidden with CSS (`display: none`), but _only_ if its parent * element is visible. **/ function getLayout(element, preCompute) { return new Element.Layout(element, preCompute); } /** * Element.measure(@element, property) -> Number * * Gives the pixel value of `element`'s dimension specified by * `property`. * * Useful for one-off measurements of elements. If you find yourself * calling this method frequently over short spans of code, you might want * to call [[Element.getLayout]] and operate on the [[Element.Layout]] * object itself (thereby taking advantage of measurement caching). * * ##### Examples * * $('troz').measure('width'); //-> 150 * $('troz').measure('border-top'); //-> 5 * $('troz').measure('top'); //-> 226 * * ##### Caveats * * * `Element.measure` can measure the dimensions of an element hidden with * CSS (`display: none`), but _only_ if its parent element is visible. **/ function measure(element, property) { return $(element).getLayout().get(property); } /** * Element.getHeight(@element) -> Number * * Returns the height of `element`. * * This method returns correct values on elements whose display is set to * `none` either in an inline style rule or in an CSS stylesheet. * * For performance reasons, if you need to query both width _and_ height of * `element`, you should consider using [[Element.getDimensions]] instead. * * Note that the value returned is a _number only_ although it is * _expressed in pixels_. * * ##### Examples * * language: html * <div id="rectangle" style="font-size: 10px; width: 20em; height: 10em"></div> * * Then: * * $('rectangle').getHeight(); * // -> 100 **/ function getHeight(element) { return Element.getDimensions(element).height; } /** * Element.getWidth(@element) -> Number * * Returns the width of `element`. * * This method returns correct values on elements whose display is set to * `none` either in an inline style rule or in an CSS stylesheet. * * For performance reasons, if you need to query both width _and_ height of * `element`, you should consider using [[Element.getDimensions]] instead. * * Note that the value returned is a _number only_ although it is * _expressed in pixels_. * * ##### Examples * * language: html * <div id="rectangle" style="font-size: 10px; width: 20em; height: 10em"></div> * * Then: * * $('rectangle').getWidth(); * // -> 200 **/ function getWidth(element) { return Element.getDimensions(element).width; } /** * Element.getDimensions(@element) -> Object * * Finds the computed width and height of `element` and returns them as * key/value pairs of an object. * * For backwards-compatibility, these dimensions represent the dimensions * of the element's "border box" (including CSS padding and border). This * is equivalent to the built-in `offsetWidth` and `offsetHeight` * browser properties. * * Note that all values are returned as _numbers only_ although they are * _expressed in pixels_. * * ##### Caveats * * * If the element is hidden via `display: none` in CSS, this method will * attempt to measure the element by temporarily removing that CSS and * applying `visibility: hidden` and `position: absolute`. This gives * the element dimensions without making it visible or affecting the * positioning of surrounding elements &mdash; but may not give accurate * results in some cases. [[Element.measure]] is designed to give more * accurate results. * * * In order to avoid calling the method twice, you should consider * caching the returned values in a variable, as shown in the example * below. * * * For more complex use cases, use [[Element.measure]], which is able * to measure many different aspects of an element's dimensions and * offsets. * * ##### Examples * * language: html * <div id="rectangle" style="font-size: 10px; width: 20em; height: 10em"></div> * * Then: * * var dimensions = $('rectangle').getDimensions(); * // -> {width: 200, height: 100} * * dimensions.width; * // -> 200 * * dimensions.height; * // -> 100 **/ function getDimensions(element) { element = $(element); var display = Element.getStyle(element, 'display'); if (display && display !== 'none') { return { width: element.offsetWidth, height: element.offsetHeight }; } // All *Width and *Height properties give 0 on elements with // `display: none`, so show the element temporarily. var style = element.style; var originalStyles = { visibility: style.visibility, position: style.position, display: style.display }; var newStyles = { visibility: 'hidden', display: 'block' }; // Switching `fixed` to `absolute` causes issues in Safari. if (originalStyles.position !== 'fixed') newStyles.position = 'absolute'; Element.setStyle(element, newStyles); var dimensions = { width: element.offsetWidth, height: element.offsetHeight }; Element.setStyle(element, originalStyles); return dimensions; } /** * Element.getOffsetParent(@element) -> Element * * Returns `element`'s closest _positioned_ ancestor. If none is found, the * `body` element is returned. **/ function getOffsetParent(element) { element = $(element); // For unusual cases like these, we standardize on returning the BODY // element as the offset parent. if (isDocument(element) || isDetached(element) || isBody(element) || isHtml(element)) return $(document.body); // IE reports offset parent incorrectly for inline elements. var isInline = (Element.getStyle(element, 'display') === 'inline'); if (!isInline && element.offsetParent) return $(element.offsetParent); while ((element = element.parentNode) && element !== document.body) { if (Element.getStyle(element, 'position') !== 'static') { return isHtml(element) ? $(document.body) : $(element); } } return $(document.body); } /** * Element.cumulativeOffset(@element) -> Element.Offset * * Returns the offsets of `element` from the top left corner of the * document. **/ function cumulativeOffset(element) { element = $(element); var valueT = 0, valueL = 0; if (element.parentNode) { do { valueT += element.offsetTop || 0; valueL += element.offsetLeft || 0; element = element.offsetParent; } while (element); } return new Element.Offset(valueL, valueT); } /** * Element.positionedOffset(@element) -> Element.Offset * * Returns `element`'s offset relative to its closest positioned ancestor * (the element that would be returned by [[Element.getOffsetParent]]). **/ function positionedOffset(element) { element = $(element); // Account for the margin of the element. var layout = element.getLayout(); var valueT = 0, valueL = 0; do { valueT += element.offsetTop || 0; valueL += element.offsetLeft || 0; element = element.offsetParent; if (element) { if (isBody(element)) break; var p = Element.getStyle(element, 'position'); if (p !== 'static') break; } } while (element); valueL -= layout.get('margin-top'); valueT -= layout.get('margin-left'); return new Element.Offset(valueL, valueT); } /** * Element.cumulativeScrollOffset(@element) -> Element.Offset * * Calculates the cumulative scroll offset of an element in nested * scrolling containers. **/ function cumulativeScrollOffset(element) { var valueT = 0, valueL = 0; do { valueT += element.scrollTop || 0; valueL += element.scrollLeft || 0; element = element.parentNode; } while (element); return new Element.Offset(valueL, valueT); } /** * Element.viewportOffset(@element) -> Element.Offset * * Returns the X/Y coordinates of element relative to the viewport. **/ function viewportOffset(forElement) { element = $(element); var valueT = 0, valueL = 0, docBody = document.body; var element = forElement; do { valueT += element.offsetTop || 0; valueL += element.offsetLeft || 0; // Safari fix if (element.offsetParent == docBody && Element.getStyle(element, 'position') == 'absolute') break; } while (element = element.offsetParent); element = forElement; do { // Opera < 9.5 sets scrollTop/Left on both HTML and BODY elements. // Other browsers set it only on the HTML element. The BODY element // can be skipped since its scrollTop/Left should always be 0. if (element != docBody) { valueT -= element.scrollTop || 0; valueL -= element.scrollLeft || 0; } } while (element = element.parentNode); return new Element.Offset(valueL, valueT); } /** * Element.absolutize(@element) -> Element * * Turns `element` into an absolutely-positioned element _without_ * changing its position in the page layout. **/ function absolutize(element) { element = $(element); if (Element.getStyle(element, 'position') === 'absolute') { return element; } var offsetParent = getOffsetParent(element); var eOffset = element.viewportOffset(), pOffset = offsetParent.viewportOffset(); var offset = eOffset.relativeTo(pOffset); var layout = element.getLayout(); element.store('prototype_absolutize_original_styles', { left: element.getStyle('left'), top: element.getStyle('top'), width: element.getStyle('width'), height: element.getStyle('height') }); element.setStyle({ position: 'absolute', top: offset.top + 'px', left: offset.left + 'px', width: layout.get('width') + 'px', height: layout.get('height') + 'px' }); return element; } /** * Element.relativize(@element) -> Element * * Turns `element` into a relatively-positioned element without changing * its position in the page layout. * * Used to undo a call to [[Element.absolutize]]. **/ function relativize(element) { element = $(element); if (Element.getStyle(element, 'position') === 'relative') { return element; } // Restore the original styles as captured by Element#absolutize. var originalStyles = element.retrieve('prototype_absolutize_original_styles'); if (originalStyles) element.setStyle(originalStyles); return element; } /** * Element.scrollTo(@element) -> Element * * Scrolls the window so that `element` appears at the top of the viewport. * * This has a similar effect than what would be achieved using * [HTML anchors](http://www.w3.org/TR/html401/struct/links.html#h-12.2.3) * (except the browser's history is not modified). * * ##### Example * * $(element).scrollTo(); * // -> Element **/ function scrollTo(element) { element = $(element); var pos = Element.cumulativeOffset(element); window.scrollTo(pos.left, pos.top); return element; } /** * Element.makePositioned(@element) -> Element * * Allows for the easy creation of a CSS containing block by setting * `element`'s CSS `position` to `relative` if its initial position is * either `static` or `undefined`. * * To revert back to `element`'s original CSS position, use * [[Element.undoPositioned]]. **/ function makePositioned(element) { element = $(element); var position = Element.getStyle(element, 'position'), styles = {}; if (position === 'static' || !position) { styles.position = 'relative'; // When an element is `position: relative` with an undefined `top` and // `left`, Opera returns the offset relative to positioning context. if (Prototype.Browser.Opera) { styles.top = 0; styles.left = 0; } Element.setStyle(element, styles); Element.store(element, 'prototype_made_positioned', true); } return element; } /** * Element.undoPositioned(@element) -> Element * * Sets `element` back to the state it was in _before_ * [[Element.makePositioned]] was applied to it. * * `element`'s absolutely positioned children will now have their positions * set relatively to `element`'s nearest ancestor with a CSS `position` of * `'absolute'`, `'relative'` or `'fixed'`. **/ function undoPositioned(element) { element = $(element); var storage = Element.getStorage(element), madePositioned = storage.get('prototype_made_positioned'); if (madePositioned) { storage.unset('prototype_made_positioned'); Element.setStyle(element, { position: '', top: '', bottom: '', left: '', right: '' }); } return element; } /** * Element.makeClipping(@element) -> Element * * Simulates the poorly-supported CSS `clip` property by setting `element`'s * `overflow` value to `hidden`. * * To undo clipping, use [[Element.undoClipping]]. * * The visible area is determined by `element`'s width and height. * * ##### Example * * language:html * <div id="framer"> * <img src="/assets/2007/1/14/chairs.jpg" alt="example" /> * </div> * * Then: * * $('framer').makeClipping().setStyle({width: '100px', height: '100px'}); * // -> Element * * Another example: * * language: html * <a id="clipper" href="#">Click me to try it out.</a> * * <div id="framer"> * <img src="/assets/2007/2/24/chairs.jpg" alt="example" /> * </div> * * <script type="text/javascript" charset="utf-8"> * var Example = { * clip: function(){ * $('clipper').update('undo clipping!'); * $('framer').makeClipping().setStyle({width: '100px', height: '100px'}); * }, * unClip: function(){ * $('clipper').update('clip!'); * $('framer').undoClipping(); * }, * toggleClip: function(event){ * if($('clipper').innerHTML == 'undo clipping!') Example.unClip(); * else Example.clip(); * Event.stop(event); * } * }; * Event.observe('clipper', 'click', Example.toggleClip); * </script> **/ function makeClipping(element) { element = $(element); var storage = Element.getStorage(element), madeClipping = storage.get('prototype_made_clipping'); // The "prototype_made_clipping" storage key is meant to hold the // original CSS overflow value. A string value or `null` means that we've // called `makeClipping` already. An `undefined` value means we haven't. if (Object.isUndefined(madeClipping)) { var overflow = Element.getStyle(element, 'overflow'); storage.set('prototype_made_clipping', overflow); if (overflow !== 'hidden') element.style.overflow = 'hidden'; } return element; } /** * Element.undoClipping(@element) -> Element * * Sets `element`'s CSS `overflow` property back to the value it had * _before_ [[Element.makeClipping]] was applied. * * ##### Example * * language: html * <div id="framer"> * <img src="/assets/2007/1/14/chairs.jpg" alt="example" /> * </div> * * Then: * * $('framer').undoClipping(); * // -> Element (and sets the CSS overflow property to its original value). * * Another example: * * language: html * <a id="clipper" href="#">Click me to try it out.</a> * * <div id="framer"> * <img src="/assets/2007/2/24/chairs_1.jpg" alt="example" /> * </div> * * <script type="text/javascript" charset="utf-8"> * var Example = { * clip: function(){ * $('clipper').update('undo clipping!'); * $('framer').makeClipping().setStyle({width: '100px', height: '100px'}); * }, * unClip: function(){ * $('clipper').update('clip!'); * $('framer').undoClipping(); * }, * toggleClip: function(event){ * if($('clipper').innerHTML == 'clip!') Example.clip(); * else Example.unClip(); * Event.stop(event); * } * }; * $('framer').makeClipping().setStyle({width: '100px', height: '100px'}); * Event.observe('clipper', 'click', Example.toggleClip); * </script> **/ function undoClipping(element) { element = $(element); var storage = Element.getStorage(element), overflow = storage.get('prototype_made_clipping'); if (!Object.isUndefined(overflow)) { storage.unset('prototype_made_clipping'); element.style.overflow = overflow || ''; } return element; } /** * Element.clonePosition(@element, source[, options]) -> Element * - source (Element | String): The source element (or its ID). * - options (Object): The position fields to clone. * * Clones the position and/or dimensions of `source` onto the element as * defined by `options`, with an optional offset for the `left` and `top` * properties. * * Note that the element will be positioned exactly like `source` whether or * not it is part of the same [CSS containing * block](http://www.w3.org/TR/CSS21/visudet.html#containing-block-details). * * ##### Options * * <table class='options'> * <thead> * <tr> * <th style='text-align: left; padding-right: 1em'>Name</th> * <th style='text-align: left; padding-right: 1em'>Default</th> * <th style='text-align: left; padding-right: 1em'>Description</th> * </tr> * </thead> * <tbody> * <tr> * <td><code>setLeft</code></td> * <td><code>true</code></td> * <td>Clones <code>source</code>'s <code>left</code> CSS property onto <code>element</code>.</td> * </tr> * <tr> * <td><code>setTop</code></td> * <td><code>true</code></td> * <td>Clones <code>source</code>'s <code>top</code> CSS property onto <code>element</code>.</td> * </tr> * <tr> * <td><code>setWidth</code></td> * <td><code>true</code></td> * <td>Clones <code>source</code>'s <code>width</code> onto <code>element</code>.</td> * </tr> * <tr> * <td><code>setHeight</code></td> * <td><code>true</code></td> * <td>Clones <code>source</code>'s <code>width</code> onto <code>element</code>.</td> * </tr> * <tr> * <td><code>offsetLeft</code></td> * <td><code>0</code></td> * <td>Number by which to offset <code>element</code>'s <code>left</code> CSS property.</td> * </tr> * <tr> * <td><code>offsetTop</code></td> * <td><code>0</code></td> * <td>Number by which to offset <code>element</code>'s <code>top</code> CSS property.</td> * </tr> * </tbody> * </table> **/ function clonePosition(element, source, options) { options = Object.extend({ setLeft: true, setTop: true, setWidth: true, setHeight: true, offsetTop: 0, offsetLeft: 0 }, options || {}); // Find page position of source. source = $(source); element = $(element); var p, delta, layout, styles = {}; if (options.setLeft || options.setTop) { p = Element.viewportOffset(source); delta = [0, 0]; // A delta of 0/0 will work for `positioned: fixed` elements, but // for `position: absolute` we need to get the parent's offset. if (Element.getStyle(element, 'position') === 'absolute') { var parent = Element.getOffsetParent(element); if (parent !== document.body) delta = Element.viewportOffset(parent); } } if (options.setWidth || options.setHeight) { layout = Element.getLayout(source); } // Set position. if (options.setLeft) styles.left = (p[0] - delta[0] + options.offsetLeft) + 'px'; if (options.setTop) styles.top = (p[1] - delta[1] + options.offsetTop) + 'px'; if (options.setWidth) styles.width = layout.get('border-box-width') + 'px'; if (options.setHeight) styles.height = layout.get('border-box-height') + 'px'; return Element.setStyle(element, styles); } if (Prototype.Browser.IE) { // IE doesn't report offsets correctly for static elements, so we change them // to "relative" to get the values, then change them back. getOffsetParent = getOffsetParent.wrap( function(proceed, element) { element = $(element); // For unusual cases like these, we standardize on returning the BODY // element as the offset parent. if (isDocument(element) || isDetached(element) || isBody(element) || isHtml(element)) return $(document.body); var position = element.getStyle('position'); if (position !== 'static') return proceed(element); element.setStyle({ position: 'relative' }); var value = proceed(element); element.setStyle({ position: position }); return value; } ); positionedOffset = positionedOffset.wrap(function(proceed, element) { element = $(element); if (!element.parentNode) return new Element.Offset(0, 0); var position = element.getStyle('position'); if (position !== 'static') return proceed(element); // Trigger hasLayout on the offset parent so that IE6 reports // accurate offsetTop and offsetLeft values for position: fixed. var offsetParent = element.getOffsetParent(); if (offsetParent && offsetParent.getStyle('position') === 'fixed') hasLayout(offsetParent); element.setStyle({ position: 'relative' }); var value = proceed(element); element.setStyle({ position: position }); return value; }); } else if (Prototype.Browser.Webkit) { // Safari returns margins on body which is incorrect if the child is absolutely // positioned. For performance reasons, redefine Element#cumulativeOffset for // KHTML/WebKit only. cumulativeOffset = function(element) { element = $(element); var valueT = 0, valueL = 0; do { valueT += element.offsetTop || 0; valueL += element.offsetLeft || 0; if (element.offsetParent == document.body) { if (Element.getStyle(element, 'position') == 'absolute') break; } element = element.offsetParent; } while (element); return new Element.Offset(valueL, valueT); }; } Element.addMethods({ getLayout: getLayout, measure: measure, getWidth: getWidth, getHeight: getHeight, getDimensions: getDimensions, getOffsetParent: getOffsetParent, cumulativeOffset: cumulativeOffset, positionedOffset: positionedOffset, cumulativeScrollOffset: cumulativeScrollOffset, viewportOffset: viewportOffset, absolutize: absolutize, relativize: relativize, scrollTo: scrollTo, makePositioned: makePositioned, undoPositioned: undoPositioned, makeClipping: makeClipping, undoClipping: undoClipping, clonePosition: clonePosition }); function isBody(element) { return element.nodeName.toUpperCase() === 'BODY'; } function isHtml(element) { return element.nodeName.toUpperCase() === 'HTML'; } function isDocument(element) { return element.nodeType === Node.DOCUMENT_NODE; } function isDetached(element) { return element !== document.body && !Element.descendantOf(element, document.body); } // If the browser supports the nonstandard `getBoundingClientRect` // (currently only IE and Firefox), it becomes far easier to obtain // true offsets. if ('getBoundingClientRect' in document.documentElement) { Element.addMethods({ viewportOffset: function(element) { element = $(element); if (isDetached(element)) return new Element.Offset(0, 0); var rect = element.getBoundingClientRect(), docEl = document.documentElement; // The HTML element on IE < 8 has a 2px border by default, giving // an incorrect offset. We correct this by subtracting clientTop // and clientLeft. return new Element.Offset(rect.left - docEl.clientLeft, rect.top - docEl.clientTop); } }); } })(); (function() { /** * document.viewport * * The `document.viewport` namespace contains methods that return information * about the viewport &mdash; the rectangle that represents the portion of a web * page within view. In other words, it's the browser window minus all chrome. **/ var IS_OLD_OPERA = Prototype.Browser.Opera && (window.parseFloat(window.opera.version()) < 9.5); var ROOT = null; function getRootElement() { if (ROOT) return ROOT; ROOT = IS_OLD_OPERA ? document.body : document.documentElement; return ROOT; } /** * document.viewport.getDimensions() -> Object * * Returns an object containing viewport dimensions in the form * `{ width: Number, height: Number }`. * * The _viewport_ is the subset of the browser window that a page occupies * &mdash; the "usable" space in a browser window. * * ##### Example * * document.viewport.getDimensions(); * //-> { width: 776, height: 580 } **/ function getDimensions() { return { width: this.getWidth(), height: this.getHeight() }; } /** * document.viewport.getWidth() -> Number * * Returns the width of the viewport. * * Equivalent to calling `document.viewport.getDimensions().width`. **/ function getWidth() { return getRootElement().clientWidth; } /** * document.viewport.getHeight() -> Number * * Returns the height of the viewport. * * Equivalent to `document.viewport.getDimensions().height`. **/ function getHeight() { return getRootElement().clientHeight; } /** * document.viewport.getScrollOffsets() -> Array * * Returns the viewport's horizontal and vertical scroll offsets. * * Returns an array in the form of `[leftValue, topValue]`. Also accessible * as properties: `{ left: leftValue, top: topValue }`. * * ##### Examples * * document.viewport.getScrollOffsets(); * //-> { left: 0, top: 0 } * * window.scrollTo(0, 120); * document.viewport.getScrollOffsets(); * //-> { left: 0, top: 120 } **/ function getScrollOffsets() { var x = window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft; var y = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop; return new Element.Offset(x, y); } document.viewport = { getDimensions: getDimensions, getWidth: getWidth, getHeight: getHeight, getScrollOffsets: getScrollOffsets }; })();
mit
ssepulveda/ICB_TT
sources/imuMonitor/www/server.py
4750
import sys from twisted.internet.defer import inlineCallbacks from autobahn import wamp from autobahn.twisted.wamp import ApplicationSession from mainProcess import MainProcess ## IMU class to access data # # Defines callbacks and register events for WAMP server # @param ApplicationSession WAMP instance class Imu(ApplicationSession): ## onJoin event (server connected) # # Starts the MainProcess when server starts, initing the communication # thread with the IMU # @param self The object pointer. # @param details WAMP data @inlineCallbacks def onJoin(self, details): yield self.register(self) print("Server connected") # start imu server self.app = MainProcess() ## onLeave event (server disconnected) # # Stops the MainProcess when server stops. # @param self The object pointer. # @param details WAMP data @inlineCallbacks def onLeave(self, details): print("Server disconnected") if self.app.is_alive(): self.app.join() ## test function # # Checks the WAMP and WebSocket working with a defined Value # @param self The object pointer. # @param arg Expected data from the WebSocket # @return Server status @wamp.register(u'com.example.imu.test') def test(self, arg=None): return str("Servidor operativo") ## Detects the number of connected IMUs # # @param self The object pointer. # @param arg Expected data from the WebSocket # @return number of IMUs detected @wamp.register(u'com.example.imu.detect') def detectImu(self, arg=None): resp = self.app.detectImu() countImu = 0 if not resp: return str("No imu detected !") else: for n, r in enumerate(resp): if r is True: countImu += 1 return str(countImu) ## Sets filename for the CSV export # # @param self The object pointer. # @param arg file name @wamp.register(u'com.example.imu.filename') def setFileName(self, arg): print arg self.app.setFileName(str(arg)) ## Gets filename of the current CSV export # # @param self The object pointer. # @param arg Expected data from the WebSocket # @return file name def getFileName(self, arg=None): return self.app.getFileName() ## Starts adquisition # # Inits data adquisition from the detected IMUs in another thread # @param self The object pointer. # @param arg Expected data from the WebSocket @wamp.register(u'com.example.imu.startimu') def startImu(self, arg=None): print("Start") self.app.start() ## Stops adquisition # # Stops data adquisition and the corresponding thread # @param self The object pointer. # @param arg Expected data from the WebSocket @wamp.register(u'com.example.imu.stopimu') def stoptImu(self, arg=None): print("Stop") self.app.stop() self.app.join(1) ## Get data # # Gets the current data from the current enabled sensor # @param self The object pointer. # @param arg Expected data from the WebSocket # @return sensor data @wamp.register(u'com.example.imu.getdata') def getImuData(self, arg=None): data = self.app.getData() print data return data if __name__ == '__main__': import sys import argparse # parse command line arguments parser = argparse.ArgumentParser() parser.add_argument("-d", "--debug", action="store_true", help="Enable debug output.") parser.add_argument("--web", type=int, default=8080, help='Web port to use for embedded Web server. Use 0 to disable.') parser.add_argument("--router", type=str, default=None, help='If given, connect to this WAMP router. Else run an embedded router on 9000.') args = parser.parse_args() if args.debug: from twisted.python import log log.startLogging(sys.stdout) # import Twisted reactor from twisted.internet import reactor # create embedded web server for static file if args.web: from twisted.web.server import Site from twisted.web.static import File reactor.listenTCP(args.web, Site(File("."))) # run WAMP application component from autobahn.twisted.wamp import ApplicationRunner router = args.router or 'ws://localhost:9000' runner = ApplicationRunner(router, u"realm1", standalone=not args.router, debug=False, # low-level logging debug_wamp=args.debug, # WAMP level logging debug_app=args.debug) # app-level logging # start the component and the Twisted reactor .. runner.run(Imu)
mit
exercism/python
exercises/concept/little-sisters-vocab/strings_test.py
5162
import unittest import pytest from strings import (add_prefix_un, make_word_groups, remove_suffix_ness, adjective_to_verb) class LittleSistersVocabTest(unittest.TestCase): @pytest.mark.task(taskno=1) def test_add_prefix_un(self): input_data = ['happy', 'manageable', 'fold', 'eaten', 'avoidable', 'usual'] result_data = [f'un{item}' for item in input_data] number_of_variants = range(1, len(input_data) + 1) for variant, word, result in zip(number_of_variants, input_data, result_data): with self.subTest(f'variation #{variant}', word=word, result=result): self.assertEqual(add_prefix_un(word), result, msg=f'Expected: {result} but got a different word instead.') @pytest.mark.task(taskno=2) def test_make_word_groups_en(self): input_data = ['en', 'circle', 'fold', 'close', 'joy', 'lighten', 'tangle', 'able', 'code', 'culture'] result_data = ('en :: encircle :: enfold :: enclose :: enjoy :: enlighten ::' ' entangle :: enable :: encode :: enculture') self.assertEqual(make_word_groups(input_data), result_data, msg=f'Expected {result_data} but got something else instead.') @pytest.mark.task(taskno=2) def test_make_word_groups_pre(self): input_data = ['pre', 'serve', 'dispose', 'position', 'requisite', 'digest', 'natal', 'addressed', 'adolescent', 'assumption', 'mature', 'compute'] result_data = ('pre :: preserve :: predispose :: preposition :: prerequisite :: ' 'predigest :: prenatal :: preaddressed :: preadolescent :: preassumption :: ' 'premature :: precompute') self.assertEqual(make_word_groups(input_data), result_data, msg=f'Expected {result_data} but got something else instead.') @pytest.mark.task(taskno=2) def test_make_word_groups_auto(self): input_data = ['auto', 'didactic', 'graph', 'mate', 'chrome', 'centric', 'complete', 'echolalia', 'encoder', 'biography'] result_data = ('auto :: autodidactic :: autograph :: automate :: autochrome :: ' 'autocentric :: autocomplete :: autoecholalia :: autoencoder :: ' 'autobiography') self.assertEqual(make_word_groups(input_data), result_data, msg=f'Expected {result_data} but got something else instead.') @pytest.mark.task(taskno=2) def test_make_words_groups_inter(self): input_data = ['inter', 'twine', 'connected', 'dependent', 'galactic', 'action', 'stellar', 'cellular', 'continental', 'axial', 'operative', 'disciplinary'] result_data = ('inter :: intertwine :: interconnected :: interdependent :: ' 'intergalactic :: interaction :: interstellar :: intercellular :: ' 'intercontinental :: interaxial :: interoperative :: interdisciplinary') self.assertEqual(make_word_groups(input_data), result_data, msg=f'Expected {result_data} but got something else instead.') @pytest.mark.task(taskno=3) def test_remove_suffix_ness(self): input_data = ['heaviness', 'sadness', 'softness', 'crabbiness', 'lightness', 'artiness', 'edginess'] result_data = ['heavy', 'sad', 'soft', 'crabby', 'light', 'arty', 'edgy'] number_of_variants = range(1, len(input_data) + 1) for variant, word, result in zip(number_of_variants, input_data, result_data): with self.subTest(f'variation #{variant}', word=word, result=result): self.assertEqual(remove_suffix_ness(word), result, msg=f'Expected: {result} but got a different word instead.') @pytest.mark.task(taskno=4) def test_adjective_to_verb(self): input_data = ['Look at the bright sky.', 'His expression went dark.', 'The bread got hard after sitting out.', 'The butter got soft in the sun.', 'Her eyes were light blue.', 'The morning fog made everything damp with mist.', 'He cut the fence pickets short by mistake.', 'Charles made weak crying noises.', 'The black oil got on the white dog.'] index_data = [-2, -1, 3, 3, -2, -3, 5, 2, 1] result_data = ['brighten', 'darken', 'harden', 'soften', 'lighten', 'dampen', 'shorten', 'weaken', 'blacken'] number_of_variants = range(1, len(input_data) + 1) for variant, sentence, index, result in zip(number_of_variants, input_data, index_data, result_data): with self.subTest(f'variation #{variant}', sentence=sentence, index=index, result=result): self.assertEqual(adjective_to_verb(sentence, index), result, msg=f'Expected: {result} but got a different word instead.')
mit
ManuelOverdijk/myonodebluetooth
lib/util/deserialise.js
6504
/** This Source Code is licensed under the MIT license. If a copy of the MIT-license was not distributed with this file, You can obtain one at: http://opensource.org/licenses/mit-license.html. @author: Manuel Overdijk (manueloverdijk) @license MIT @copyright Manuel Overdijk, 2015 */ "use strict" class Deserialise { constructor() { this.scaling = { 'ORIENTATION_SCALE': 16384.0, ///< See myohw_imu_data_t::orientation 'ACCELEROMETER_SCALE': 2048.0, ///< See myohw_imu_data_t::accelerometer 'GYROSCOPE_SCALE': 16.0 ///< See myohw_imu_data_t::gyroscope }; this.poses = { 'pose_rest': 0x0000, 'pose_fist': 0x0001, 'pose_wave_in': 0x0002, 'pose_wave_out': 0x0003, 'pose_fingers_spread': 0x0004, 'pose_double_tap': 0x0005, 'pose_unknown': 0xffff }; // identifying the myo armband on the right or left hand this.arm = { 'arm_right': 0x01, 'arm_left': 0x02, 'arm_unknown': 0xff }; // direction of the Myo armband on the forarm this.arm_direction = { 'x_direction_toward_wrist': 0x01, 'x_direction_toward_elbow': 0x02, 'x_direction_unknown': 0xff }; // result of a sync gesture this.sync_result = { 'sync_failed_too_hard': 0x01 ///< Sync gesture was performed too hard. } } /** * Info data * @param Buffer * @returns {{serial_number: Buffer, unlock_pose: Number, active_classifier_type: *, active_classifier_index: *, has_custom_classifier: *, stream_indicating: *, sku: *, reserved: Buffer}} */ info_t(Buffer) { console.log('got Buffer', Buffer); if (Buffer.length < 20) { console.log('error!'); return null; } return { serial_number: Buffer.slice(0, 6), unlock_pose: Buffer.readUInt16LE(6), active_classifier_type: Buffer.readUInt8(8), active_classifier_index: Buffer.readUInt8(9), has_custom_classifier: Buffer.readUInt8(10), stream_indicating: Buffer.readUInt8(11), sku: Buffer.readUInt8(12), reserved: Buffer.slice(13, 7) } } /** * Version data * @param Buffer * @returns {{major: Number, minor: Number, patch: Number, hardware_rev: Number}} */ version_t(Buffer) { if (Buffer.length < 8) { //error return null; } return { major: Buffer.readUInt16LE(0), minor: Buffer.readUInt16LE(2), patch: Buffer.readUInt16LE(4), hardware_rev: Buffer.readUInt16LE(6) } } /** * IMU data * @param Buffer * @returns {{orientation: {w: *, x: *, y: *, z: *}, accelerometer: Array, gyroscope: Array}} */ imu_data_t(Buffer) { if (Buffer.length < 20) { //error return null; } return { orientation: { w: Buffer.readInt16LE(0)/this.scaling.ORIENTATION_SCALE, x: Buffer.readInt16LE(2)/this.scaling.ORIENTATION_SCALE, y: Buffer.readInt16LE(4)/this.scaling.ORIENTATION_SCALE, z: Buffer.readInt16LE(6)/this.scaling.ORIENTATION_SCALE }, accelerometer:[ Buffer.readInt16LE(8)/this.scaling.ACCELEROMETER_SCALE, Buffer.readInt16LE(10)/this.scaling.ACCELEROMETER_SCALE, Buffer.readInt16LE(12)/this.scaling.ACCELEROMETER_SCALE ], gyroscope: [ Buffer.readInt16LE(14)/this.scaling.GYROSCOPE_SCALE, Buffer.readInt16LE(16)/this.scaling.GYROSCOPE_SCALE, Buffer.readInt16LE(18)/this.scaling.GYROSCOPE_SCALE ] } } /** * Not yet tested * @param Buffer * @returns {*} */ motion_event_t(Buffer){ if(Buffer.length <3){ //error return null; } return { type: Buffer.readUInt8(0), // type should be 0x00 tap_direction: Buffer.readUInt8(1), tap_count: Buffer.readUInt8(2) } } /** * Classifier event * @param Buffer * @returns {*} */ classifier_event_t(Buffer){ //event pose recieved if(Buffer.readUInt8(0) == 3){ return { type: Buffer.readUInt8(0), pose: Buffer.readUInt16LE(1) }; // arm synced TODO: Not tested } else if (Buffer.readUInt8(0) == 1){ return { type: Buffer.readUInt8(0), arm: Buffer.readUInt8(1), x_direction: Buffer.readUInt8(2) }; // syc failed TODO: Not tested } else if(Buffer.readUInt8(0) == 6){ return { type: Buffer.readUInt8(0), sync_result: Buffer.readUint8(1) }; } return { type: Buffer.readUInt8(0), pose: Buffer.readUInt16LE(1) }; } /** * Emg data, 4 streams * @param Buffer * @returns {*} */ emg_data_t(Buffer){ if(Buffer.length < 16){ //error return null; } return { sample1: [ Buffer.readInt8(0), Buffer.readInt8(1), Buffer.readInt8(2), Buffer.readInt8(3), Buffer.readInt8(4), Buffer.readInt8(5), Buffer.readInt8(6), Buffer.readInt8(7) ], sample2: [ Buffer.readInt8(8), Buffer.readInt8(9), Buffer.readInt8(10), Buffer.readInt8(11), Buffer.readInt8(12), Buffer.readInt8(13), Buffer.readInt8(14), Buffer.readInt8(15) ] } } /** * Battery info * @param Buffer * @returns {{batteryLevel: Number}} */ battery_t(Buffer){ return { batteryLevel: Buffer.readUInt8() } } } module.exports = Deserialise;
mit
jjaffeux/MotionJsonApi
test/test_helper.rb
311
require 'pp' require 'minitest/autorun' require './lib/motion-json-api.rb' require 'resources/blog_resource.rb' require 'resources/user_resource.rb' require 'resources/service_resource.rb' require 'resources/contribution_resource.rb' require 'resources/url_resource.rb' require 'resources/activity_resource.rb'
mit
rlindskog/vueniverse
template/backpack.config.js
492
const path = require('path') module.exports = { webpack: (config, options, webpack) => { config.entry.main = path.resolve(__dirname, 'src', 'server', 'index.js') config.output.path = path.resolve(__dirname, 'dist', 'server') config.resolve.alias = { '~/middleware': path.resolve(__dirname, 'src', 'server', 'middleware'), '~/util': path.resolve(__dirname, 'src', 'server', 'util'), '~/': path.resolve(__dirname, 'src', 'server') } return config } }
mit
smourier/brotli
WinBrotli/WinBrotli/WinBrotli.cpp
2967
/* Copyright 2016 Simon Mourier. All Rights Reserved. Distributed under MIT license. See file LICENSE for detail or copy at https://opensource.org/licenses/MIT */ #define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers #define NOMINMAX #include "windows.h" #include "objidl.h" // for ISequentialStream #include "strsafe.h" #include "../../dec/decode.h" #include "../../enc/encode.h" void CDECL TraceFormat(PCWSTR pszFormat, ...) { WCHAR szTrace[0x2000]; va_list args; va_start(args, pszFormat); StringCchVPrintf(szTrace, ARRAYSIZE(szTrace), pszFormat, args); va_end(args); OutputDebugString(szTrace); } // adapter classes class BrotliStreamIn : public brotli::BrotliIn { ISequentialStream *_pStream; char *_pBuffer; int _bufferSize; public: BrotliStreamIn(ISequentialStream *pStream, int bufferSize) { _pStream = pStream; _bufferSize = bufferSize; _pBuffer = new char[bufferSize]; } BrotliStreamIn::~BrotliStreamIn(void) { if (_pBuffer) delete[] _pBuffer; } const void* Read(size_t n, size_t* bytes_read) { if (!_pBuffer) { return NULL; } if (n > _bufferSize) { n = _bufferSize; } ULONG read; _pStream->Read(_pBuffer, (ULONG)n, &read); *bytes_read = read; // brotli semantics are a bit strange, read the doc. if (!read && n) { delete[] _pBuffer; _pBuffer = NULL; return NULL; } return _pBuffer; } }; class BrotliStreamOut : public brotli::BrotliOut { ISequentialStream *_pStream; public: BrotliStreamOut(ISequentialStream *pStream) { _pStream = pStream; } bool Write(const void* buf, size_t n) { return !_pStream->Write(buf, (ULONG)n, NULL); } }; STDAPI CreateState(LPVOID *ppState) { if (!ppState) return E_INVALIDARG; BrotliState* pState = BrotliCreateState(NULL, NULL, NULL); if (!pState) return E_OUTOFMEMORY; *ppState = pState; return S_OK; } STDAPI DestroyState(LPVOID pState) { if (!pState) return E_INVALIDARG; BrotliDestroyState((BrotliState*)pState); return S_OK; } // note: we have added offset_in & offset_out so it's better suited for .NET p/invoke bindings (avoid unsafe casts and buffer copies) STDAPI_(BrotliResult) DecompressStream( size_t* available_in, uint8_t* next_in, size_t* offset_in, size_t* available_out, uint8_t* next_out, size_t* offset_out, size_t* total_out, BrotliState* pState) { const uint8_t* pin = next_in; uint8_t* pout = next_out; *offset_in = 0; *offset_out = 0; BrotliResult result = BrotliDecompressStream(available_in, &pin, available_out, &pout, total_out, pState); *offset_in = (pin - next_in) / sizeof(uint8_t); *offset_out = (pout - next_out) / sizeof(uint8_t); return result; } STDAPI_(int) CompressStream(brotli::BrotliParams *bp, ISequentialStream *read, ISequentialStream *write) { if (!bp || !read || !write) return E_INVALIDARG; BrotliStreamIn in(read, 1 << 16); BrotliStreamOut out(write); return brotli::BrotliCompress(*bp, &in, &out); }
mit
jjuiddong/KarlSims
Common/thread/Task.cpp
42
#include "stdafx.h" #include "Task.h"
mit
joergjo/BookLibrary-NetCore
src/BookLibrary/Models/Keyword.cs
189
using System.Text.Json.Serialization; namespace BookLibrary.Models { public class Keyword { [JsonPropertyName("keyword")] public string? Name { get; set; } } }
mit
mugpet/skkgrav
user/plugins/error/error.php
1664
<?php namespace Grav\Plugin; use Grav\Common\Plugin; use Grav\Common\Grav; use Grav\Common\Page\Page; use Grav\Common\Page\Pages; use Grav\Common\Page\Types; use RocketTheme\Toolbox\Event\Event; class ErrorPlugin extends Plugin { /** * @return array */ public static function getSubscribedEvents() { return [ 'onPageNotFound' => ['onPageNotFound', 0], 'onGetPageTemplates' => ['onGetPageTemplates', 0], 'onTwigTemplatePaths' => ['onTwigTemplatePaths', -10] ]; } /** * Display error page if no page was found for the current route. * * @param Event $event */ public function onPageNotFound(Event $event) { /** @var Pages $pages */ $pages = $this->grav['pages']; // Try to load user error page. $page = $pages->dispatch($this->config->get('plugins.error.routes.404', '/error'), true); if (!$page) { // If none provided use built in error page. $page = new Page; $page->init(new \SplFileInfo(__DIR__ . '/pages/error.md')); } $event->page = $page; $event->stopPropagation(); } /** * Add page template types. */ public function onGetPageTemplates(Event $event) { /** @var Types $types */ $types = $event->types; $types->register('error'); } /** * Add current directory to twig lookup paths. */ public function onTwigTemplatePaths() { $this->grav['twig']->twig_paths[] = __DIR__ . '/templates'; } }
mit
xkoma/restoo
app/src/users/UserController.js
2764
(function () { angular .module('users') .controller('UserController', [ 'userService', '$mdSidenav', '$mdBottomSheet', '$log', '$q', UserController ]); /** * Controleur des users * @param userService * @param $mdSidenav * @param $mdBottomSheet * @param $log * @param $q * @constructor */ function UserController(userService, $mdSidenav, $mdBottomSheet, $log, $q) { var self = this; self.users = []; self.selectedUser = null; self.selectUser = selectUser; self.showContactOptions = showContactOptions; // Load all registered users userService .loadAllUsers() .then(function (users) { self.users = [].concat(users); self.selectedUser = users[0]; }); // ********************************* // Internal methods // ********************************* /** * Selectionne le user passé en paramètre * @param user */ function selectUser(user) { console.log("selectUser("+user+")"); self.selectedUser = angular.isNumber(user) ? $scope.users[user] : user; console.log("selectedUser = ",self.selectedUser); } /** * Show the bottom sheet */ function showContactOptions($event) { var user = self.selected; return $mdBottomSheet.show({ parent: angular.element(document.getElementById('content')), templateUrl: './src/users/view/contactSheet.html', controller: ['$mdBottomSheet', ContactPanelController], controllerAs: "cp", bindToController: true, targetEvent: $event }).then(function (clickedItem) { clickedItem && $log.debug(clickedItem.name + ' clicked!'); }); /** * Bottom Sheet controller for the Avatar Actions */ function ContactPanelController($mdBottomSheet) { this.user = user; this.actions = [ {name: 'Phone', icon: 'phone', icon_url: 'assets/svg/phone.svg'}, {name: 'Twitter', icon: 'twitter', icon_url: 'assets/svg/twitter.svg'}, {name: 'Google+', icon: 'google_plus', icon_url: 'assets/svg/google_plus.svg'}, {name: 'Hangout', icon: 'hangouts', icon_url: 'assets/svg/hangouts.svg'} ]; this.submitContact = function (action) { $mdBottomSheet.hide(action); }; } } } })();
mit
gheeres/Ricoh.NET
Models/DeviceObject.cs
3859
using System; using System.Collections.Generic; using System.Linq; using Ricoh.ricoh.deviceManagement; namespace Ricoh.Models { /// <summary> /// Represents the base type of an object retrieved from the external device. /// </summary> public abstract class DeviceObject { private static object _mutex = new object(); private IList<IDeviceField> _fields; /// <summary>The unique object id for the user on the device.</summary> public virtual uint Id { get; set; } /// <summary>The index of the entry.</summary> public abstract uint Index { get; } /// <summary>The unique authentication token for the user.</summary> public string Authentication { get; set; } /// <summary>The name of the user.</summary> public string Username { get; set; } /// <summary>The counters for the specified user.</summary> internal IEnumerable<IDeviceField> Fields { get { return (_fields ?? (_fields = new List<IDeviceField>())); } private set { _fields = new List<IDeviceField>(value); } } /// <summary> /// Extracts the index from the ObjectId. The Index is the last characters at the end of /// ObjectId with the baseValue stripped from the beginning. /// </summary> /// <param name="objectId">The complete objectId with the embedded name / index.</param> /// <param name="baseValue">The base value for the objectId that should be removed.</param> /// <returns>The extracted name or index for the value.</returns> public static uint ExtractIndexFromObjectId(uint objectId, uint baseValue) { // The index is the last digits of the Id with the baseValue stripped from the beginning???? // Using arithmetic instead of string conversion/substring selection uint digits = Convert.ToUInt32(Math.Floor(Math.Log10(objectId) + 1)); uint powersOf10 = Convert.ToUInt32(Math.Pow(10, digits - 6)); return (objectId - (baseValue * powersOf10)); } /// <param name="id">The unique id for the user on the device.</param> protected DeviceObject(uint id) { Id = id; } /// <param name="id">The unique id for the user on the device.</param> /// <param name="fields">The raw data returned from the service</param> /// <param name="capabilities">The capabilities and limits of the fields.</param> protected DeviceObject(uint id, IEnumerable<field> fields, IEnumerable<fieldCapability> capabilities): this(id) { if (fields == null) throw new ArgumentNullException(); // Map the fields to functions. IDictionary<string, Action<field>> map = new Dictionary<string, Action<field>>() { { "authname", (field) => Authentication = field.value }, { "username", (field) => Username = field.value }, }.WithDefaultValue((field) => OnUnknownField(field, capabilities.Get(field.name))); fields.AsParallel().ForAll(f => { if (f == null) return; var fieldName = f.name.ToLower(); map[fieldName](f); }); } /// <summary> /// Occurs when an unknown field is detected. /// </summary> /// <param name="field">The unknown field.</param> /// <param name="capability">The capabilities and limits describing the field.</param> protected virtual void OnUnknownField(field field, fieldCapability capability) { Add(DeviceFieldFactory.Create(field, capability)); } /// <summary> /// Add the specified field item to the list of field. Null field items are ignored. /// </summary> /// <param name="field">The field to add. If null, then the field is ignored.</param> protected virtual void Add(IDeviceField field) { if (field == null) return; lock (_mutex) { if (_fields == null) _fields = new List<IDeviceField>(); _fields.Add(field); } } } }
mit
JustinWomack/worg
src/reducers/eventCreate.js
741
import {combineReducers} from 'redux'; import { EVENT_CREATE, EVENT_CREATE_SUCCESS, EVENT_CREATE_ERROR } from '../actions'; // @FIXME Enable eslint rules /*eslint-disable no-unused-vars */ function loading(state = false, action) { switch(action.type) { //Define any action types I want to listen for. //Check that the redux actions change under the action tab of redux tools. case EVENT_CREATE: return true; case EVENT_CREATE_SUCCESS: case EVENT_CREATE_ERROR: return false; } return state; } function error(state = null, action) { switch (action.type) { case EVENT_CREATE_ERROR: return action.message; } return state; } export default combineReducers({ loading, error });
mit
sim1hill/volunteer-app
db/migrate/20150603150012_create_projects.rb
271
class CreateProjects < ActiveRecord::Migration def change create_table :projects do |t| t.string :name t.string :neighborhood t.text :description t.belongs_to :user t.belongs_to :topic t.timestamps null: false end end end
mit
timothyb89/deconstruction-engine
src/main/java/net/asrex/dx/api/zone/chat/ChatZoneMessage.java
442
package net.asrex.dx.api.zone.chat; import lombok.Data; import net.asrex.dx.api.entity.Entity; /** * Defines the basic properties for a ChatMessage. * @author timothyb89 */ @Data public class ChatZoneMessage { public static final String TYPE_ACTION = "action"; public static final String TYPE_NORMAL = "shout"; private final ChatZone zone; private final Entity sender; private final String text; private final String type; }
mit
kaidenho/spellcaster
app/src/main/java/com/kaidenho/gamelooptest/BaseObject.java
671
package com.kaidenho.gamelooptest; import android.content.Context; import android.media.SoundPool; /** * BaseObjects are updatable objects. * * Created by Kaiden Ho on 2016-09-26. */ public abstract class BaseObject { // TODO: should these be getter and setterized? static RenderSystem renderSystem = new RenderSystem(); static SoundSystem soundSystem = new SoundSystem(); static Game gameSystem; static float scrollDistance; static int scrollSpeed = 300; // Update should be overridden in all children classes; otherwise, use the normal Object class public void update(long timeDelta) { // Base class does nothing } }
mit
cskiwi/angular-seed
app/services/searchService.js
197
/* global define */ define(['app'], function (app) { 'use strict'; app.factory('searchService', function ($resource) { return $resource('api/search'); }); });
mit
miaoxing/member
src/Job/MemberUpdateLevel.php
354
<?php namespace Miaoxing\Member\Job; use Miaoxing\Queue\Job; use Miaoxing\Queue\Service\BaseJob; class MemberUpdateLevel extends Job { public function __invoke(BaseJob $job, $data) { $member = wei()->member()->findById($data['id']); wei()->event->trigger('asyncMemberUpdateLevel', [$member]); $job->delete(); } }
mit
policygenius/athenaeum
src/atoms/Img/index.js
5223
/* eslint-disable complexity */ import React from 'react'; import PropTypes from 'prop-types'; import cx from 'classnames'; import styles from './img.module.scss'; const checkLS = () => typeof window === 'undefined' || !!window.lazySizes; const strParams = '?fit=max&auto=format&ch=Width,DPR&w={width}'; const imgixSrcStr = (src) => `https://policygenius-images.imgix.net/${src}${strParams}`; const imgixSrcset = (src) => ` https://policygenius-images.imgix.net/${src}${strParams}&dpr=1 1x, https://policygenius-images.imgix.net/${src}${strParams}&dpr=2 2x, https://policygenius-images.imgix.net/${src}${strParams}&dpr=3 3x, `; const createName = (str) => { let filename = ''; if (typeof str === 'string') { filename = str.match(/([^/]*)(?=\.)/); } return filename ? filename[0].replace(/(\W+|_)/g, ' ').trim() : 'PolicyGenius'; }; function Img(props) { const { className, src, srcSet, imgixSrc, alt, title, mobileSrc, tabletSrc, mobileImgixSrc, tabletImgixSrc, lazy, ...rest } = props; const isLazy = lazy && checkLS(); const isPicture = mobileSrc !== undefined || tabletSrc !== undefined || mobileImgixSrc !== undefined || tabletImgixSrc !== undefined; const classes = cx( styles['img'], isLazy && 'lazyload', className, ); const pictureClasses = cx( styles['picture'], (mobileImgixSrc === null || mobileSrc === null) && styles['hide-mobile-image'], (tabletImgixSrc === null || tabletSrc === null) && styles['hide-tablet-image'], className, ); const srcset = (() => { if (srcSet) { return srcSet; } if (src) { return undefined; } return imgixSrcset(`${imgixSrc}`); })(); // TODO: Consider adding a noscript tag to handle a situation where lazysizes doesn't work. if (isPicture) { const defaultSrc = src || imgixSrcStr(imgixSrc); return ( <picture className={cx(pictureClasses, isLazy && 'lazyload')}> { ( mobileImgixSrc || mobileSrc ) && ( <source srcSet={isLazy ? undefined : mobileSrc || imgixSrcStr(mobileImgixSrc)} data-srcset={isLazy ? mobileSrc || imgixSrcStr(mobileImgixSrc) : undefined} media='(max-width: 767px)' /> ) } { ( tabletImgixSrc || tabletSrc ) && ( <source srcSet={isLazy ? undefined : tabletSrc || imgixSrcStr(tabletImgixSrc)} data-srcset={isLazy ? tabletSrc || imgixSrcStr(tabletImgixSrc) : undefined} media='(max-width: 1024px)' /> ) } <img className={cx(styles.img, isLazy && 'lazyload')} alt={alt || createName(src || imgixSrc)} title={title || alt || createName(src || imgixSrc)} data-src={defaultSrc} data-sizes='auto' src={isLazy ? undefined : defaultSrc} {...rest} /> </picture> ); } return ( <img className={classes} alt={alt || createName(src || imgixSrc)} title={title || alt || createName(src || imgixSrc)} data-src={src || imgixSrcStr(imgixSrc)} data-srcset={srcset} data-sizes={isLazy ? 'auto' : '100vw'} src={isLazy ? undefined : src || imgixSrcStr(imgixSrc)} {...rest} /> ); } Img.propTypes = { /** * This prop will add a new className to any inherent classNames * provided in the component's index.js file. */ className: PropTypes.string, /** * Recommended: The Imgix base url for the image. Will handle all optomizations automagically. * https://docs.imgix.com/apis/url/adjustment/usmrad */ imgixSrc: PropTypes.string, /** * The src url for the image. If you use this, it will override the Imgix src. */ src: PropTypes.string, /** * The srcset for the image. If you use this, it will override the Imgix src. */ srcSet: PropTypes.string, /** * The img alt for the image. Defaults to an improved version of the filename. */ alt: PropTypes.string, /** * The img title for the image. Defaults to whatever has been set as the alt. */ title: PropTypes.string, /** * When used, will create a <source> for a <picture> element for mobile. * If null, the image will not display on mobile */ mobileSrc: PropTypes.string, /** * When used, will create a <source> for a <picture> element for tablet * If null, the image will not display on tablet */ tabletSrc: PropTypes.string, /** * Alternate image for mobile. When used, will create a <source> for a <picture> element for mobile. Will use imgix custom string. * If null, the image will not display on mobile */ mobileImgixSrc: PropTypes.string, /** * Alternate image for tablet. When used, will create a <source> for a <picture> element for tablet. Will use imgix. Will use imgix custom string. * If null, the image will not display on tablet */ tabletImgixSrc: PropTypes.string, /** * Set to false to turn off lazyloading */ lazy: PropTypes.bool, }; Img.defaultProps = { alt: '', imgixSrc: 'photos/alexander-dummer-150646.jpg', lazy: true }; export default Img;
mit
mniizuma/c5test
concrete/core/models/attribute/type.php
10396
<?php defined('C5_EXECUTE') or die("Access Denied."); class Concrete5_Model_AttributeType extends Object { public function getAttributeTypeID() {return $this->atID;} public function getAttributeTypeHandle() {return $this->atHandle;} public function getAttributeTypeName() {return t($this->atName);} public function getController() {return $this->controller;} public static function getByID($atID) { $db = Loader::db(); $row = $db->GetRow('select atID, pkgID, atHandle, atName from AttributeTypes where atID = ?', array($atID)); $at = new AttributeType(); $at->setPropertiesFromArray($row); $at->loadController(); return $at; } public function __destruct() { unset($this->controller); } public static function getList($akCategoryHandle = false) { $db = Loader::db(); $list = array(); if ($akCategoryHandle == false) { $r = $db->Execute('select atID from AttributeTypes order by atID asc'); } else { $r = $db->Execute('select atID from AttributeTypeCategories inner join AttributeKeyCategories on AttributeTypeCategories.akCategoryID = AttributeKeyCategories.akCategoryID and AttributeKeyCategories.akCategoryHandle = ? order by atID asc', array($akCategoryHandle)); } while ($row = $r->FetchRow()) { $list[] = AttributeType::getByID($row['atID']); } $r->Close(); return $list; } public static function exportList($xml) { $attribs = AttributeType::getList(); $db = Loader::db(); $axml = $xml->addChild('attributetypes'); foreach($attribs as $at) { $atype = $axml->addChild('attributetype'); $atype->addAttribute('handle', $at->getAttributeTypeHandle()); $atype->addAttribute('package', $at->getPackageHandle()); $categories = $db->GetCol('select akCategoryHandle from AttributeKeyCategories inner join AttributeTypeCategories where AttributeKeyCategories.akCategoryID = AttributeTypeCategories.akCategoryID and AttributeTypeCategories.atID = ?', array($at->getAttributeTypeID())); if (count($categories) > 0) { $cat = $atype->addChild('categories'); foreach($categories as $catHandle) { $cat->addChild('category')->addAttribute('handle', $catHandle); } } } } public function delete() { $db = Loader::db(); if (method_exists($this->controller, 'deleteType')) { $this->controller->deleteType(); } $db->Execute("delete from AttributeTypes where atID = ?", array($this->atID)); $db->Execute("delete from AttributeTypeCategories where atID = ?", array($this->atID)); } public static function getListByPackage($pkg) { $db = Loader::db(); $list = array(); $r = $db->Execute('select atID from AttributeTypes where pkgID = ? order by atID asc', array($pkg->getPackageID())); while ($row = $r->FetchRow()) { $list[] = AttributeType::getByID($row['atID']); } $r->Close(); return $list; } public function getPackageID() { return $this->pkgID;} public function getPackageHandle() { return PackageList::getHandle($this->pkgID); } public function isAssociatedWithCategory($cat) { $db = Loader::db(); $r = $db->GetOne("select count(akCategoryID) from AttributeTypeCategories where akCategoryID = ? and atID = ?", array($cat->getAttributeKeyCategoryID(), $this->getAttributeTypeID())); return $r > 0; } public static function getByHandle($atHandle) { // Handle legacy handles switch($atHandle) { case 'date': $atHandle = 'date_time'; break; } $db = Loader::db(); $row = $db->GetRow('select atID, pkgID, atHandle, atName from AttributeTypes where atHandle = ?', array($atHandle)); if ($row['atID']) { $at = new AttributeType(); $at->setPropertiesFromArray($row); $at->loadController(); return $at; } } public static function add($atHandle, $atName, $pkg = false) { $pkgID = 0; if (is_object($pkg)) { $pkgID = $pkg->getPackageID(); } $db = Loader::db(); $db->Execute('insert into AttributeTypes (atHandle, atName, pkgID) values (?, ?, ?)', array($atHandle, $atName, $pkgID)); $id = $db->Insert_ID(); $est = AttributeType::getByID($id); $path = $est->getAttributeTypeFilePath(FILENAME_ATTRIBUTE_DB); if ($path) { Package::installDB($path); } return $est; } public function getValue($avID) { $cnt = $this->getController(); return $cnt->getValue($avID); } public function render($view, $ak = false, $value = false, $return = false) { // local scope Loader::library('attribute/view'); $av = new AttributeTypeView($this, $ak, $value); $resp = $av->render($view, $return); if ($return) { return $resp; } } public function getAttributeTypeIconSRC() { $ff = '/' . FILENAME_BLOCK_ICON; if ($this->getPackageID() > 0) { $db = Loader::db(); $h = $this->getPackageHandle(); $url = (is_dir(DIR_PACKAGES . '/' . $h)) ? BASE_URL . DIR_REL : ASSETS_URL; $url = $url . '/' . DIRNAME_PACKAGES . '/' . $h . '/' . DIRNAME_MODELS . '/' . DIRNAME_ATTRIBUTES . '/' . DIRNAME_ATTRIBUTE_TYPES . '/' . $this->getAttributeTypeHandle() . $ff; } else if (file_exists(DIR_MODELS_CORE . '/' . DIRNAME_ATTRIBUTES . '/' . DIRNAME_ATTRIBUTE_TYPES . '/' . $this->getAttributeTypeHandle() . $ff)) { $url = ASSETS_URL . '/' . DIRNAME_MODELS . '/' . DIRNAME_ATTRIBUTES . '/' . DIRNAME_ATTRIBUTE_TYPES . '/' . $this->getAttributeTypeHandle() . $ff; } else if (file_exists(DIR_MODELS . '/' . DIRNAME_ATTRIBUTES . '/' . DIRNAME_ATTRIBUTE_TYPES . '/' . $this->getAttributeTypeHandle() . $ff)) { $url = BASE_URL . DIR_REL . '/' . DIRNAME_MODELS . '/' . DIRNAME_ATTRIBUTES . '/' . DIRNAME_ATTRIBUTE_TYPES . '/' . $this->getAttributeTypeHandle() . $ff; } else { $url = ASSETS_URL . '/' . DIRNAME_MODELS . '/' . DIRNAME_ATTRIBUTES . '/' . DIRNAME_ATTRIBUTE_TYPES . '/default' . $ff; } return $url; } public function getAttributeTypeFilePath($_file) { $f = $this->mapAttributeTypeFilePath($_file); if (is_object($f)) { return $f->file; } } public function getAttributeTypeFileURL($_file) { $f = $this->mapAttributeTypeFilePath($_file); if (is_object($f)) { return $f->url; } } protected function mapAttributeTypeFilePath($_file) { $atHandle = $this->atHandle; if (file_exists(DIR_MODELS . '/' . DIRNAME_ATTRIBUTES . '/' . DIRNAME_ATTRIBUTE_TYPES . '/' . $atHandle . '/' . $_file)) { $file = DIR_MODELS . '/' . DIRNAME_ATTRIBUTES . '/' . DIRNAME_ATTRIBUTE_TYPES . '/' . $atHandle . '/' . $_file; $url = BASE_URL . DIR_REL . '/' . DIRNAME_MODELS . '/' . DIRNAME_ATTRIBUTES . '/' . DIRNAME_ATTRIBUTE_TYPES . '/' . $atHandle . '/' . $_file; } else if ($_file == FILENAME_ATTRIBUTE_CONTROLLER && file_exists(DIR_MODELS . '/' . DIRNAME_ATTRIBUTES . '/' . DIRNAME_ATTRIBUTE_TYPES . '/' . $atHandle . '.php')) { $file = DIR_MODELS . '/' . DIRNAME_ATTRIBUTES . '/' . DIRNAME_ATTRIBUTE_TYPES . '/' . $atHandle . '.php'; } $pkgID = $this->pkgID; if (!isset($file) && $pkgID > 0) { $pkgHandle = PackageList::getHandle($pkgID); $dirp = is_dir(DIR_PACKAGES . '/' . $pkgHandle) ? DIR_PACKAGES . '/' . $pkgHandle : DIR_PACKAGES_CORE . '/' . $pkgHandle; if (file_exists($dirp . '/' . DIRNAME_MODELS . '/' . DIRNAME_ATTRIBUTES . '/' . DIRNAME_ATTRIBUTE_TYPES . '/' . $atHandle . '/' . $_file)) { $file = $dirp . '/' . DIRNAME_MODELS . '/' . DIRNAME_ATTRIBUTES . '/' . DIRNAME_ATTRIBUTE_TYPES . '/' . $atHandle . '/' . $_file; $url = BASE_URL . DIR_REL . '/' .DIRNAME_PACKAGES. '/' .$pkgHandle . '/' . DIRNAME_MODELS . '/' . DIRNAME_ATTRIBUTES . '/' . DIRNAME_ATTRIBUTE_TYPES . '/' . $atHandle . '/' . $_file; } else if ($_file == FILENAME_ATTRIBUTE_CONTROLLER && file_exists($dirp . '/' . DIRNAME_MODELS . '/' . DIRNAME_ATTRIBUTES . '/' . DIRNAME_ATTRIBUTE_TYPES . '/' . $atHandle . '.php')) { $file = $dirp . '/' . DIRNAME_MODELS . '/' . DIRNAME_ATTRIBUTES . '/' . DIRNAME_ATTRIBUTE_TYPES . '/' . $atHandle . '.php'; } } if (!isset($file)) { if (file_exists(DIR_MODELS_CORE . '/' . DIRNAME_ATTRIBUTES . '/' . DIRNAME_ATTRIBUTE_TYPES . '/' . $atHandle . '/' . $_file)) { $file = DIR_MODELS_CORE . '/' . DIRNAME_ATTRIBUTES . '/' . DIRNAME_ATTRIBUTE_TYPES . '/' . $atHandle . '/' . $_file; $url = ASSETS_URL . '/' . DIRNAME_MODELS . '/' . DIRNAME_ATTRIBUTES . '/' . DIRNAME_ATTRIBUTE_TYPES . '/' . $atHandle . '/' . $_file; } else if ($_file == FILENAME_ATTRIBUTE_CONTROLLER && file_exists(DIR_MODELS_CORE . '/' . DIRNAME_ATTRIBUTES . '/' . DIRNAME_ATTRIBUTE_TYPES . '/' . $atHandle . '.php')) { $file = DIR_MODELS_CORE . '/' . DIRNAME_ATTRIBUTES . '/' . DIRNAME_ATTRIBUTE_TYPES . '/' . $atHandle . '.php'; } } if (isset($file)) { $obj = new stdClass; $obj->file = $file; $obj->url = $url; return $obj; } else { return false; } } protected function loadController() { // local scope $atHandle = $this->atHandle; $txt = Loader::helper('text'); $className = $txt->camelcase($this->atHandle) . 'AttributeTypeController'; $file = $this->mapAttributeTypeFilePath(FILENAME_ATTRIBUTE_CONTROLLER); if (!$file) { $cont = DIR_MODELS_CORE . '/' . DIRNAME_ATTRIBUTES . '/' . DIRNAME_ATTRIBUTE_TYPES . '/default/' . FILENAME_ATTRIBUTE_CONTROLLER; $className = 'DefaultAttributeTypeController'; } else { $cont = $file->file; } require_once($cont); $this->controller = new $className($this); } } class Concrete5_Model_PendingAttributeType extends Concrete5_Model_AttributeType { public static function getList() { $db = Loader::db(); $atHandles = $db->GetCol("select atHandle from AttributeTypes"); $dh = Loader::helper('file'); $available = array(); if (is_dir(DIR_MODELS . '/' . DIRNAME_ATTRIBUTES . '/' . DIRNAME_ATTRIBUTE_TYPES)) { $contents = $dh->getDirectoryContents(DIR_MODELS . '/' . DIRNAME_ATTRIBUTES . '/' . DIRNAME_ATTRIBUTE_TYPES); foreach($contents as $atHandle) { if (!in_array($atHandle, $atHandles)) { $available[] = PendingAttributeType::getByHandle($atHandle); } } } return $available; } public static function getByHandle($atHandle) { $th = Loader::helper('text'); if (file_exists(DIR_MODELS . '/' . DIRNAME_ATTRIBUTES . '/' . DIRNAME_ATTRIBUTE_TYPES . '/' . $atHandle)) { $at = new PendingAttributeType(); $at->atID = 0; $at->atHandle = $atHandle; $at->atName = $th->unhandle($atHandle); return $at; } } public function install() { $at = parent::add($this->atHandle, $this->atName); } }
mit
Jorka7a13/SoftUni_CSharpBasics
03. Operators-Expressions-Statements-Homework/Problem 18. OddEvenSum/OddEvenSum.cs
820
using System; class OddEvenSum { static void Main() { int evenSum = 0, oddSum = 0; int n = int.Parse(Console.ReadLine()); for (int i = 1; i < 2 * n + 1; i++) { int number = int.Parse(Console.ReadLine()); if (i % 2 == 0) { evenSum += number; } else { oddSum += number; } } if (evenSum == oddSum) { Console.WriteLine("Yes, sum=" + evenSum); } else { if (evenSum > oddSum) { Console.WriteLine("No, diff=" + (evenSum - oddSum)); } else { Console.WriteLine("No, diff=" + (oddSum - evenSum)); } } } }
mit
it-workshop/caroline
core/ply_saver.cc
1846
// Copyright (c) 2014 The Caroline authors. All rights reserved. // Use of this source file is governed by a MIT license that can be found in the // LICENSE file. /// @author Glazachev Vladimir <glazachev.vladimir@gmail.com> #include <fstream> // NOLINT #include <vector> #include "core/ply_saver.h" namespace core { PlySaver::PlySaver() { name_ = "mesh"; comment_ = ""; } void PlySaver::Save(Mesh *mesh) { if (!mesh) { return; } std::string file_name = name_ + ".ply"; std::ofstream outfile; outfile.open(file_name); if (!outfile.is_open()) { return; } std::vector<cv::Point3d> vertexes = mesh->vertexes(); std::vector<Triangle> faces = mesh->faces(); outfile << "ply\n"; outfile << "format ascii 1.0\n"; if (!author_.empty()) { outfile << "comment author: " << author_ << "\n"; } if (!comment_.empty()) { outfile << "comment object: " << comment_ << "\n"; } outfile << "element vertex " << vertexes.size() << "\n"; outfile << "property float x\n"; outfile << "property float y\n"; outfile << "property float z\n"; outfile << "element face " << faces.size() << "\n"; outfile << "property list uchar int vertex_index\n"; outfile << "end_header\n"; for (size_t i = 0; i < vertexes.size(); i++) { cv::Point3d point = vertexes.at(i); outfile << point.x << " " << point.y << " " << point.z << "\n"; } for (size_t i = 0; i < faces.size(); i++) { Triangle face = faces.at(i); outfile << face.Point1() << " " << face.Point2() << " " << face.Point3() << "\n"; } outfile.close(); } void PlySaver::Save(const std::string &name, const std::string &comment, const std::string& author, Mesh *mesh) { name_ = name; comment_ = comment; author_ = author; Save(mesh); } } // namespace core
mit
emanuelespies/alura
Python/01/cadastro_perfis.py
204
def cadastrar(nomes): print 'Digite o nome:' nome = raw_input() nomes.append(nome) def remover(nomes): print 'Qual nome você gostaria de remover?' nome = raw_input() nomes.remove(nome) nomes = []
mit