code_text
stringlengths 604
999k
| repo_name
stringlengths 4
100
| file_path
stringlengths 4
873
| language
stringclasses 23
values | license
stringclasses 15
values | size
int32 1.02k
999k
|
---|---|---|---|---|---|
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Validate
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Com.php 23775 2011-03-01 17:25:24Z ralph $
*/
/**
* Ressource file for com and net idn validation
*
* @category Zend
* @package Zend_Validate
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
return array(
1 => '/^[\x{002d}0-9\x{0400}-\x{052f}]{1,63}$/iu',
2 => '/^[\x{002d}0-9\x{0370}-\x{03ff}]{1,63}$/iu',
3 => '/^[\x{002d}0-9a-z\x{ac00}-\x{d7a3}]{1,17}$/iu',
4 => '/^[\x{002d}0-9a-z·à-öø-ÿāăąćĉċčďđēĕėęěĝğġģĥħĩīĭįıĵķĸĺļľłńņňŋōŏőœŕŗřśŝşšţťŧũūŭůűųŵŷźżž]{1,63}$/iu',
5 => '/^[\x{002d}0-9A-Za-z\x{3400}-\x{3401}\x{3404}-\x{3406}\x{340C}\x{3416}\x{341C}' .
'\x{3421}\x{3424}\x{3428}-\x{3429}\x{342B}-\x{342E}\x{3430}-\x{3434}\x{3436}' .
'\x{3438}-\x{343C}\x{343E}\x{3441}-\x{3445}\x{3447}\x{3449}-\x{3451}\x{3453}' .
'\x{3457}-\x{345F}\x{3463}-\x{3467}\x{346E}-\x{3471}\x{3473}-\x{3477}\x{3479}-\x{348E}\x{3491}-\x{3497}' .
'\x{3499}-\x{34A1}\x{34A4}-\x{34AD}\x{34AF}-\x{34B0}\x{34B2}-\x{34BF}\x{34C2}-\x{34C5}\x{34C7}-\x{34CC}' .
'\x{34CE}-\x{34D1}\x{34D3}-\x{34D8}\x{34DA}-\x{34E4}\x{34E7}-\x{34E9}\x{34EC}-\x{34EF}\x{34F1}-\x{34FE}' .
'\x{3500}-\x{3507}\x{350A}-\x{3513}\x{3515}\x{3517}-\x{351A}\x{351C}-\x{351E}\x{3520}-\x{352A}' .
'\x{352C}-\x{3552}\x{3554}-\x{355C}\x{355E}-\x{3567}\x{3569}-\x{3573}\x{3575}-\x{357C}\x{3580}-\x{3588}' .
'\x{358F}-\x{3598}\x{359E}-\x{35AB}\x{35B4}-\x{35CD}\x{35D0}\x{35D3}-\x{35DC}\x{35E2}-\x{35ED}' .
'\x{35F0}-\x{35F6}\x{35FB}-\x{3602}\x{3605}-\x{360E}\x{3610}-\x{3611}\x{3613}-\x{3616}\x{3619}-\x{362D}' .
'\x{362F}-\x{3634}\x{3636}-\x{363B}\x{363F}-\x{3645}\x{3647}-\x{364B}\x{364D}-\x{3653}\x{3655}' .
'\x{3659}-\x{365E}\x{3660}-\x{3665}\x{3667}-\x{367C}\x{367E}\x{3680}-\x{3685}\x{3687}' .
'\x{3689}-\x{3690}\x{3692}-\x{3698}\x{369A}\x{369C}-\x{36AE}\x{36B0}-\x{36BF}\x{36C1}-\x{36C5}' .
'\x{36C9}-\x{36CA}\x{36CD}-\x{36DE}\x{36E1}-\x{36E2}\x{36E5}-\x{36FE}\x{3701}-\x{3713}\x{3715}-\x{371E}' .
'\x{3720}-\x{372C}\x{372E}-\x{3745}\x{3747}-\x{3748}\x{374A}\x{374C}-\x{3759}\x{375B}-\x{3760}' .
'\x{3762}-\x{3767}\x{3769}-\x{3772}\x{3774}-\x{378C}\x{378F}-\x{379C}\x{379F}\x{37A1}-\x{37AD}' .
'\x{37AF}-\x{37B7}\x{37B9}-\x{37C1}\x{37C3}-\x{37C5}\x{37C7}-\x{37D4}\x{37D6}-\x{37E0}\x{37E2}' .
'\x{37E5}-\x{37ED}\x{37EF}-\x{37F6}\x{37F8}-\x{3802}\x{3804}-\x{381D}\x{3820}-\x{3822}\x{3825}-\x{382A}' .
'\x{382D}-\x{382F}\x{3831}-\x{3832}\x{3834}-\x{384C}\x{384E}-\x{3860}\x{3862}-\x{3863}\x{3865}-\x{386B}' .
'\x{386D}-\x{3886}\x{3888}-\x{38A1}\x{38A3}\x{38A5}-\x{38AA}\x{38AC}\x{38AE}-\x{38B0}' .
'\x{38B2}-\x{38B6}\x{38B8}\x{38BA}-\x{38BE}\x{38C0}-\x{38C9}\x{38CB}-\x{38D4}\x{38D8}-\x{38E0}' .
'\x{38E2}-\x{38E6}\x{38EB}-\x{38ED}\x{38EF}-\x{38F2}\x{38F5}-\x{38F7}\x{38FA}-\x{38FF}\x{3901}-\x{392A}' .
'\x{392C}\x{392E}-\x{393B}\x{393E}-\x{3956}\x{395A}-\x{3969}\x{396B}-\x{397A}\x{397C}-\x{3987}' .
'\x{3989}-\x{3998}\x{399A}-\x{39B0}\x{39B2}\x{39B4}-\x{39D0}\x{39D2}-\x{39DA}\x{39DE}-\x{39DF}' .
'\x{39E1}-\x{39EF}\x{39F1}-\x{3A17}\x{3A19}-\x{3A2A}\x{3A2D}-\x{3A40}\x{3A43}-\x{3A4E}\x{3A50}' .
'\x{3A52}-\x{3A5E}\x{3A60}-\x{3A6D}\x{3A6F}-\x{3A77}\x{3A79}-\x{3A82}\x{3A84}-\x{3A85}\x{3A87}-\x{3A89}' .
'\x{3A8B}-\x{3A8F}\x{3A91}-\x{3A93}\x{3A95}-\x{3A96}\x{3A9A}\x{3A9C}-\x{3AA6}\x{3AA8}-\x{3AA9}' .
'\x{3AAB}-\x{3AB1}\x{3AB4}-\x{3ABC}\x{3ABE}-\x{3AC5}\x{3ACA}-\x{3ACB}\x{3ACD}-\x{3AD5}\x{3AD7}-\x{3AE1}' .
'\x{3AE4}-\x{3AE7}\x{3AE9}-\x{3AEC}\x{3AEE}-\x{3AFD}\x{3B01}-\x{3B10}\x{3B12}-\x{3B15}\x{3B17}-\x{3B1E}' .
'\x{3B20}-\x{3B23}\x{3B25}-\x{3B27}\x{3B29}-\x{3B36}\x{3B38}-\x{3B39}\x{3B3B}-\x{3B3C}\x{3B3F}' .
'\x{3B41}-\x{3B44}\x{3B47}-\x{3B4C}\x{3B4E}\x{3B51}-\x{3B55}\x{3B58}-\x{3B62}\x{3B68}-\x{3B72}' .
'\x{3B78}-\x{3B88}\x{3B8B}-\x{3B9F}\x{3BA1}\x{3BA3}-\x{3BBA}\x{3BBC}\x{3BBF}-\x{3BD0}' .
'\x{3BD3}-\x{3BE6}\x{3BEA}-\x{3BFB}\x{3BFE}-\x{3C12}\x{3C14}-\x{3C1B}\x{3C1D}-\x{3C37}\x{3C39}-\x{3C4F}' .
'\x{3C52}\x{3C54}-\x{3C5C}\x{3C5E}-\x{3C68}\x{3C6A}-\x{3C76}\x{3C78}-\x{3C8F}\x{3C91}-\x{3CA8}' .
'\x{3CAA}-\x{3CAD}\x{3CAF}-\x{3CBE}\x{3CC0}-\x{3CC8}\x{3CCA}-\x{3CD3}\x{3CD6}-\x{3CE0}\x{3CE4}-\x{3CEE}' .
'\x{3CF3}-\x{3D0A}\x{3D0E}-\x{3D1E}\x{3D20}-\x{3D21}\x{3D25}-\x{3D38}\x{3D3B}-\x{3D46}\x{3D4A}-\x{3D59}' .
'\x{3D5D}-\x{3D7B}\x{3D7D}-\x{3D81}\x{3D84}-\x{3D88}\x{3D8C}-\x{3D8F}\x{3D91}-\x{3D98}\x{3D9A}-\x{3D9C}' .
'\x{3D9E}-\x{3DA1}\x{3DA3}-\x{3DB0}\x{3DB2}-\x{3DB5}\x{3DB9}-\x{3DBC}\x{3DBE}-\x{3DCB}\x{3DCD}-\x{3DDB}' .
'\x{3DDF}-\x{3DE8}\x{3DEB}-\x{3DF0}\x{3DF3}-\x{3DF9}\x{3DFB}-\x{3DFC}\x{3DFE}-\x{3E05}\x{3E08}-\x{3E33}' .
'\x{3E35}-\x{3E3E}\x{3E40}-\x{3E47}\x{3E49}-\x{3E67}\x{3E6B}-\x{3E6F}\x{3E71}-\x{3E85}\x{3E87}-\x{3E8C}' .
'\x{3E8E}-\x{3E98}\x{3E9A}-\x{3EA1}\x{3EA3}-\x{3EAE}\x{3EB0}-\x{3EB5}\x{3EB7}-\x{3EBA}\x{3EBD}' .
'\x{3EBF}-\x{3EC4}\x{3EC7}-\x{3ECE}\x{3ED1}-\x{3ED7}\x{3ED9}-\x{3EDA}\x{3EDD}-\x{3EE3}\x{3EE7}-\x{3EE8}' .
'\x{3EEB}-\x{3EF2}\x{3EF5}-\x{3EFF}\x{3F01}-\x{3F02}\x{3F04}-\x{3F07}\x{3F09}-\x{3F44}\x{3F46}-\x{3F4E}' .
'\x{3F50}-\x{3F53}\x{3F55}-\x{3F72}\x{3F74}-\x{3F75}\x{3F77}-\x{3F7B}\x{3F7D}-\x{3FB0}\x{3FB6}-\x{3FBF}' .
'\x{3FC1}-\x{3FCF}\x{3FD1}-\x{3FD3}\x{3FD5}-\x{3FDF}\x{3FE1}-\x{400B}\x{400D}-\x{401C}\x{401E}-\x{4024}' .
'\x{4027}-\x{403F}\x{4041}-\x{4060}\x{4062}-\x{4069}\x{406B}-\x{408A}\x{408C}-\x{40A7}\x{40A9}-\x{40B4}' .
'\x{40B6}-\x{40C2}\x{40C7}-\x{40CF}\x{40D1}-\x{40DE}\x{40E0}-\x{40E7}\x{40E9}-\x{40EE}\x{40F0}-\x{40FB}' .
'\x{40FD}-\x{4109}\x{410B}-\x{4115}\x{4118}-\x{411D}\x{411F}-\x{4122}\x{4124}-\x{4133}\x{4136}-\x{4138}' .
'\x{413A}-\x{4148}\x{414A}-\x{4169}\x{416C}-\x{4185}\x{4188}-\x{418B}\x{418D}-\x{41AD}\x{41AF}-\x{41B3}' .
'\x{41B5}-\x{41C3}\x{41C5}-\x{41C9}\x{41CB}-\x{41F2}\x{41F5}-\x{41FE}\x{4200}-\x{4227}\x{422A}-\x{4246}' .
'\x{4248}-\x{4263}\x{4265}-\x{428B}\x{428D}-\x{42A1}\x{42A3}-\x{42C4}\x{42C8}-\x{42DC}\x{42DE}-\x{430A}' .
'\x{430C}-\x{4335}\x{4337}\x{4342}-\x{435F}\x{4361}-\x{439A}\x{439C}-\x{439D}\x{439F}-\x{43A4}' .
'\x{43A6}-\x{43EC}\x{43EF}-\x{4405}\x{4407}-\x{4429}\x{442B}-\x{4455}\x{4457}-\x{4468}\x{446A}-\x{446D}' .
'\x{446F}-\x{4476}\x{4479}-\x{447D}\x{447F}-\x{4486}\x{4488}-\x{4490}\x{4492}-\x{4498}\x{449A}-\x{44AD}' .
'\x{44B0}-\x{44BD}\x{44C1}-\x{44D3}\x{44D6}-\x{44E7}\x{44EA}\x{44EC}-\x{44FA}\x{44FC}-\x{4541}' .
'\x{4543}-\x{454F}\x{4551}-\x{4562}\x{4564}-\x{4575}\x{4577}-\x{45AB}\x{45AD}-\x{45BD}\x{45BF}-\x{45D5}' .
'\x{45D7}-\x{45EC}\x{45EE}-\x{45F2}\x{45F4}-\x{45FA}\x{45FC}-\x{461A}\x{461C}-\x{461D}\x{461F}-\x{4631}' .
'\x{4633}-\x{4649}\x{464C}\x{464E}-\x{4652}\x{4654}-\x{466A}\x{466C}-\x{4675}\x{4677}-\x{467A}' .
'\x{467C}-\x{4694}\x{4696}-\x{46A3}\x{46A5}-\x{46AB}\x{46AD}-\x{46D2}\x{46D4}-\x{4723}\x{4729}-\x{4732}' .
'\x{4734}-\x{4758}\x{475A}\x{475C}-\x{478B}\x{478D}\x{4791}-\x{47B1}\x{47B3}-\x{47F1}' .
'\x{47F3}-\x{480B}\x{480D}-\x{4815}\x{4817}-\x{4839}\x{483B}-\x{4870}\x{4872}-\x{487A}\x{487C}-\x{487F}' .
'\x{4883}-\x{488E}\x{4890}-\x{4896}\x{4899}-\x{48A2}\x{48A4}-\x{48B9}\x{48BB}-\x{48C8}\x{48CA}-\x{48D1}' .
'\x{48D3}-\x{48E5}\x{48E7}-\x{48F2}\x{48F4}-\x{48FF}\x{4901}-\x{4922}\x{4924}-\x{4928}\x{492A}-\x{4931}' .
'\x{4933}-\x{495B}\x{495D}-\x{4978}\x{497A}\x{497D}\x{4982}-\x{4983}\x{4985}-\x{49A8}' .
'\x{49AA}-\x{49AF}\x{49B1}-\x{49B7}\x{49B9}-\x{49BD}\x{49C1}-\x{49C7}\x{49C9}-\x{49CE}\x{49D0}-\x{49E8}' .
'\x{49EA}\x{49EC}\x{49EE}-\x{4A19}\x{4A1B}-\x{4A43}\x{4A45}-\x{4A4D}\x{4A4F}-\x{4A9E}' .
'\x{4AA0}-\x{4AA9}\x{4AAB}-\x{4B4E}\x{4B50}-\x{4B5B}\x{4B5D}-\x{4B69}\x{4B6B}-\x{4BC2}\x{4BC6}-\x{4BE8}' .
'\x{4BEA}-\x{4BFA}\x{4BFC}-\x{4C06}\x{4C08}-\x{4C2D}\x{4C2F}-\x{4C32}\x{4C34}-\x{4C35}\x{4C37}-\x{4C69}' .
'\x{4C6B}-\x{4C73}\x{4C75}-\x{4C86}\x{4C88}-\x{4C97}\x{4C99}-\x{4C9C}\x{4C9F}-\x{4CA3}\x{4CA5}-\x{4CB5}' .
'\x{4CB7}-\x{4CF8}\x{4CFA}-\x{4D27}\x{4D29}-\x{4DAC}\x{4DAE}-\x{4DB1}\x{4DB3}-\x{4DB5}\x{4E00}-\x{4E54}' .
'\x{4E56}-\x{4E89}\x{4E8B}-\x{4EEC}\x{4EEE}-\x{4FAC}\x{4FAE}-\x{503C}\x{503E}-\x{51E5}\x{51E7}-\x{5270}' .
'\x{5272}-\x{56A1}\x{56A3}-\x{5840}\x{5842}-\x{58B5}\x{58B7}-\x{58CB}\x{58CD}-\x{5BC8}\x{5BCA}-\x{5C01}' .
'\x{5C03}-\x{5C25}\x{5C27}-\x{5D5B}\x{5D5D}-\x{5F08}\x{5F0A}-\x{61F3}\x{61F5}-\x{63BA}\x{63BC}-\x{6441}' .
'\x{6443}-\x{657C}\x{657E}-\x{663E}\x{6640}-\x{66FC}\x{66FE}-\x{6728}\x{672A}-\x{6766}\x{6768}-\x{67A8}' .
'\x{67AA}-\x{685B}\x{685D}-\x{685E}\x{6860}-\x{68B9}\x{68BB}-\x{6AC8}\x{6ACA}-\x{6BB0}\x{6BB2}-\x{6C16}' .
'\x{6C18}-\x{6D9B}\x{6D9D}-\x{6E12}\x{6E14}-\x{6E8B}\x{6E8D}-\x{704D}\x{704F}-\x{7113}\x{7115}-\x{713B}' .
'\x{713D}-\x{7154}\x{7156}-\x{729F}\x{72A1}-\x{731E}\x{7320}-\x{7362}\x{7364}-\x{7533}\x{7535}-\x{7551}' .
'\x{7553}-\x{7572}\x{7574}-\x{75E8}\x{75EA}-\x{7679}\x{767B}-\x{783E}\x{7840}-\x{7A62}\x{7A64}-\x{7AC2}' .
'\x{7AC4}-\x{7B06}\x{7B08}-\x{7B79}\x{7B7B}-\x{7BCE}\x{7BD0}-\x{7D99}\x{7D9B}-\x{7E49}\x{7E4C}-\x{8132}' .
'\x{8134}\x{8136}-\x{81D2}\x{81D4}-\x{8216}\x{8218}-\x{822D}\x{822F}-\x{83B4}\x{83B6}-\x{841F}' .
'\x{8421}-\x{86CC}\x{86CE}-\x{874A}\x{874C}-\x{877E}\x{8780}-\x{8A32}\x{8A34}-\x{8B71}\x{8B73}-\x{8B8E}' .
'\x{8B90}-\x{8DE4}\x{8DE6}-\x{8E9A}\x{8E9C}-\x{8EE1}\x{8EE4}-\x{8F0B}\x{8F0D}-\x{8FB9}\x{8FBB}-\x{9038}' .
'\x{903A}-\x{9196}\x{9198}-\x{91A3}\x{91A5}-\x{91B7}\x{91B9}-\x{91C7}\x{91C9}-\x{91E0}\x{91E2}-\x{91FB}' .
'\x{91FD}-\x{922B}\x{922D}-\x{9270}\x{9272}-\x{9420}\x{9422}-\x{9664}\x{9666}-\x{9679}\x{967B}-\x{9770}' .
'\x{9772}-\x{982B}\x{982D}-\x{98ED}\x{98EF}-\x{99C4}\x{99C6}-\x{9A11}\x{9A14}-\x{9A27}\x{9A29}-\x{9D0D}' .
'\x{9D0F}-\x{9D2B}\x{9D2D}-\x{9D8E}\x{9D90}-\x{9DC5}\x{9DC7}-\x{9E77}\x{9E79}-\x{9EB8}\x{9EBB}-\x{9F20}' .
'\x{9F22}-\x{9F61}\x{9F63}-\x{9FA5}\x{FA28}]{1,20}$/iu',
6 => '/^[\x{002d}0-9A-Za-z]{1,63}$/iu',
7 => '/^[\x{00A1}-\x{00FF}]{1,63}$/iu',
8 => '/^[\x{0100}-\x{017f}]{1,63}$/iu',
9 => '/^[\x{0180}-\x{024f}]{1,63}$/iu',
10 => '/^[\x{0250}-\x{02af}]{1,63}$/iu',
11 => '/^[\x{02b0}-\x{02ff}]{1,63}$/iu',
12 => '/^[\x{0300}-\x{036f}]{1,63}$/iu',
13 => '/^[\x{0370}-\x{03ff}]{1,63}$/iu',
14 => '/^[\x{0400}-\x{04ff}]{1,63}$/iu',
15 => '/^[\x{0500}-\x{052f}]{1,63}$/iu',
16 => '/^[\x{0530}-\x{058F}]{1,63}$/iu',
17 => '/^[\x{0590}-\x{05FF}]{1,63}$/iu',
18 => '/^[\x{0600}-\x{06FF}]{1,63}$/iu',
19 => '/^[\x{0700}-\x{074F}]{1,63}$/iu',
20 => '/^[\x{0780}-\x{07BF}]{1,63}$/iu',
21 => '/^[\x{0900}-\x{097F}]{1,63}$/iu',
22 => '/^[\x{0980}-\x{09FF}]{1,63}$/iu',
23 => '/^[\x{0A00}-\x{0A7F}]{1,63}$/iu',
24 => '/^[\x{0A80}-\x{0AFF}]{1,63}$/iu',
25 => '/^[\x{0B00}-\x{0B7F}]{1,63}$/iu',
26 => '/^[\x{0B80}-\x{0BFF}]{1,63}$/iu',
27 => '/^[\x{0C00}-\x{0C7F}]{1,63}$/iu',
28 => '/^[\x{0C80}-\x{0CFF}]{1,63}$/iu',
29 => '/^[\x{0D00}-\x{0D7F}]{1,63}$/iu',
30 => '/^[\x{0D80}-\x{0DFF}]{1,63}$/iu',
31 => '/^[\x{0E00}-\x{0E7F}]{1,63}$/iu',
32 => '/^[\x{0E80}-\x{0EFF}]{1,63}$/iu',
33 => '/^[\x{0F00}-\x{0FFF}]{1,63}$/iu',
34 => '/^[\x{1000}-\x{109F}]{1,63}$/iu',
35 => '/^[\x{10A0}-\x{10FF}]{1,63}$/iu',
36 => '/^[\x{1100}-\x{11FF}]{1,63}$/iu',
37 => '/^[\x{1200}-\x{137F}]{1,63}$/iu',
38 => '/^[\x{13A0}-\x{13FF}]{1,63}$/iu',
39 => '/^[\x{1400}-\x{167F}]{1,63}$/iu',
40 => '/^[\x{1680}-\x{169F}]{1,63}$/iu',
41 => '/^[\x{16A0}-\x{16FF}]{1,63}$/iu',
42 => '/^[\x{1700}-\x{171F}]{1,63}$/iu',
43 => '/^[\x{1720}-\x{173F}]{1,63}$/iu',
44 => '/^[\x{1740}-\x{175F}]{1,63}$/iu',
45 => '/^[\x{1760}-\x{177F}]{1,63}$/iu',
46 => '/^[\x{1780}-\x{17FF}]{1,63}$/iu',
47 => '/^[\x{1800}-\x{18AF}]{1,63}$/iu',
48 => '/^[\x{1E00}-\x{1EFF}]{1,63}$/iu',
49 => '/^[\x{1F00}-\x{1FFF}]{1,63}$/iu',
50 => '/^[\x{2070}-\x{209F}]{1,63}$/iu',
51 => '/^[\x{2100}-\x{214F}]{1,63}$/iu',
52 => '/^[\x{2150}-\x{218F}]{1,63}$/iu',
53 => '/^[\x{2460}-\x{24FF}]{1,63}$/iu',
54 => '/^[\x{2E80}-\x{2EFF}]{1,63}$/iu',
55 => '/^[\x{2F00}-\x{2FDF}]{1,63}$/iu',
56 => '/^[\x{2FF0}-\x{2FFF}]{1,63}$/iu',
57 => '/^[\x{3040}-\x{309F}]{1,63}$/iu',
58 => '/^[\x{30A0}-\x{30FF}]{1,63}$/iu',
59 => '/^[\x{3100}-\x{312F}]{1,63}$/iu',
60 => '/^[\x{3130}-\x{318F}]{1,63}$/iu',
61 => '/^[\x{3190}-\x{319F}]{1,63}$/iu',
62 => '/^[\x{31A0}-\x{31BF}]{1,63}$/iu',
63 => '/^[\x{31F0}-\x{31FF}]{1,63}$/iu',
64 => '/^[\x{3200}-\x{32FF}]{1,63}$/iu',
65 => '/^[\x{3300}-\x{33FF}]{1,63}$/iu',
66 => '/^[\x{3400}-\x{4DBF}]{1,63}$/iu',
67 => '/^[\x{4E00}-\x{9FFF}]{1,63}$/iu',
68 => '/^[\x{A000}-\x{A48F}]{1,63}$/iu',
69 => '/^[\x{A490}-\x{A4CF}]{1,63}$/iu',
70 => '/^[\x{AC00}-\x{D7AF}]{1,63}$/iu',
71 => '/^[\x{D800}-\x{DB7F}]{1,63}$/iu',
72 => '/^[\x{DC00}-\x{DFFF}]{1,63}$/iu',
73 => '/^[\x{F900}-\x{FAFF}]{1,63}$/iu',
74 => '/^[\x{FB00}-\x{FB4F}]{1,63}$/iu',
75 => '/^[\x{FB50}-\x{FDFF}]{1,63}$/iu',
76 => '/^[\x{FE20}-\x{FE2F}]{1,63}$/iu',
77 => '/^[\x{FE70}-\x{FEFF}]{1,63}$/iu',
78 => '/^[\x{FF00}-\x{FFEF}]{1,63}$/iu',
79 => '/^[\x{20000}-\x{2A6DF}]{1,63}$/iu',
80 => '/^[\x{2F800}-\x{2FA1F}]{1,63}$/iu'
); | AhmadAbdelNaser/zf | library/Zend/Validate/Hostname/Com.php | PHP | bsd-3-clause | 13,660 |
<?php
/**
* Application requirement checker script.
*
* In order to run this script use the following console command:
* php requirements.php
*
* In order to run this script from the web, you should copy it to the web root.
* If you are using Linux you can create a hard link instead, using the following command:
* ln requirements.php ../requirements.php
*/
// you may need to adjust this path to the correct Yii framework path
$frameworkPath = dirname(__FILE__) . '/vendor/yiisoft/yii2';
if (!is_dir($frameworkPath)) {
echo '<h1>Error</h1>';
echo '<p><strong>The path to yii framework seems to be incorrect.</strong></p>';
echo '<p>You need to install Yii framework via composer or adjust the framework path in file <abbr title="' . __FILE__ . '">' . basename(__FILE__) . '</abbr>.</p>';
echo '<p>Please refer to the <abbr title="' . dirname(__FILE__) . '/README.md">README</abbr> on how to install Yii.</p>';
}
require_once($frameworkPath . '/requirements/YiiRequirementChecker.php');
$requirementsChecker = new YiiRequirementChecker();
$gdMemo = $imagickMemo = 'Either GD PHP extension with FreeType support or ImageMagick PHP extension with PNG support is required for image CAPTCHA.';
$gdOK = $imagickOK = false;
if (extension_loaded('imagick')) {
$imagick = new Imagick();
$imagickFormats = $imagick->queryFormats('PNG');
if (in_array('PNG', $imagickFormats)) {
$imagickOK = true;
} else {
$imagickMemo = 'Imagick extension should be installed with PNG support in order to be used for image CAPTCHA.';
}
}
if (extension_loaded('gd')) {
$gdInfo = gd_info();
if (!empty($gdInfo['FreeType Support'])) {
$gdOK = true;
} else {
$gdMemo = 'GD extension should be installed with FreeType support in order to be used for image CAPTCHA.';
}
}
/**
* Adjust requirements according to your application specifics.
*/
$requirements = array(
// Database :
array(
'name' => 'PDO extension',
'mandatory' => true,
'condition' => extension_loaded('pdo'),
'by' => 'All DB-related classes',
),
array(
'name' => 'PDO SQLite extension',
'mandatory' => false,
'condition' => extension_loaded('pdo_sqlite'),
'by' => 'All DB-related classes',
'memo' => 'Required for SQLite database.',
),
array(
'name' => 'PDO MySQL extension',
'mandatory' => false,
'condition' => extension_loaded('pdo_mysql'),
'by' => 'All DB-related classes',
'memo' => 'Required for MySQL database.',
),
array(
'name' => 'PDO PostgreSQL extension',
'mandatory' => false,
'condition' => extension_loaded('pdo_pgsql'),
'by' => 'All DB-related classes',
'memo' => 'Required for PostgreSQL database.',
),
// Cache :
array(
'name' => 'Memcache extension',
'mandatory' => false,
'condition' => extension_loaded('memcache') || extension_loaded('memcached'),
'by' => '<a href="http://www.yiiframework.com/doc-2.0/yii-caching-memcache.html">MemCache</a>',
'memo' => extension_loaded('memcached') ? 'To use memcached set <a href="http://www.yiiframework.com/doc-2.0/yii-caching-memcache.html#$useMemcached-detail">MemCache::useMemcached</a> to <code>true</code>.' : ''
),
array(
'name' => 'APC extension',
'mandatory' => false,
'condition' => extension_loaded('apc'),
'by' => '<a href="http://www.yiiframework.com/doc-2.0/yii-caching-apccache.html">ApcCache</a>',
),
// CAPTCHA:
array(
'name' => 'GD PHP extension with FreeType support',
'mandatory' => false,
'condition' => $gdOK,
'by' => '<a href="http://www.yiiframework.com/doc-2.0/yii-captcha-captcha.html">Captcha</a>',
'memo' => $gdMemo,
),
array(
'name' => 'ImageMagick PHP extension with PNG support',
'mandatory' => false,
'condition' => $imagickOK,
'by' => '<a href="http://www.yiiframework.com/doc-2.0/yii-captcha-captcha.html">Captcha</a>',
'memo' => $imagickMemo,
),
// PHP ini :
'phpExposePhp' => array(
'name' => 'Expose PHP',
'mandatory' => false,
'condition' => $requirementsChecker->checkPhpIniOff("expose_php"),
'by' => 'Security reasons',
'memo' => '"expose_php" should be disabled at php.ini',
),
'phpAllowUrlInclude' => array(
'name' => 'PHP allow url include',
'mandatory' => false,
'condition' => $requirementsChecker->checkPhpIniOff("allow_url_include"),
'by' => 'Security reasons',
'memo' => '"allow_url_include" should be disabled at php.ini',
),
'phpSmtp' => array(
'name' => 'PHP mail SMTP',
'mandatory' => false,
'condition' => strlen(ini_get('SMTP')) > 0,
'by' => 'Email sending',
'memo' => 'PHP mail SMTP server required',
),
);
$requirementsChecker->checkYii()->check($requirements)->render();
| sebfrab/restobar | requirements.php | PHP | bsd-3-clause | 5,051 |
#!/bin/bash
#
# This script can be used to generate the required, machine-specific
# configuration file: GeminiHello-[MACHINE_NAME].conf
#
# The intent is that developers would run this script once as part
# of their initial setup. On Windows, the script can be run through
# Git bash.
export JAVA_HOME=/usr/lib/jvm/java-1.7.0-openjdk-amd64
export RESIN_HOME=${IROOT}/resin-4.0.41
projectName="GeminiHello"
machineNameUpper="`echo $HOSTNAME|tr '[a-z]' '[A-Z]'`"
machineNameLower="`echo $HOSTNAME|tr '[A-Z]' '[a-z]'`"
directoryName=$(cd `dirname $0` && pwd)
user=`echo \`id -nu\``
# If the file we wanted to generate already exists, don't bother
# creating a new one.
configurationFile=$directoryName/Docroot/WEB-INF/$projectName-$machineNameUpper.conf;
if [ -f $configurationFile ]
then
echo "The configuration file $configurationFile already exists. Exiting."
exit 0
else
echo "Creating configuration file: $configurationFile"
fi
# Write the required configuration attributes to the file.
echo "# -----------------------------------------------------------------------" > $configurationFile
echo "# GEMINIHELLO configuration file " >> $configurationFile
echo "# " >> $configurationFile
echo "# MACHINE-SPECIFIC CONFIGURATION " >> $configurationFile
echo "# " >> $configurationFile
echo "# The configuration attributes specified in this file are specific to a " >> $configurationFile
echo "# single development-environment machine. " >> $configurationFile
echo "# -----------------------------------------------------------------------" >> $configurationFile
echo "" >> $configurationFile
echo "# Extend the development configuration, which in turn extends the " >> $configurationFile
echo "# baseline configuration." >> $configurationFile
echo "Extends = $projectName-Dev.conf" >> $configurationFile
echo "" >> $configurationFile
echo "# Now set any attributes that are specific to this machine." >> $configurationFile
echo "StandardDomain = http://$machineNameLower.techempower.com" >> $configurationFile
echo "SecureDomain = https://$machineNameLower.techempower.com" >> $configurationFile
echo "#OutboundMailEnabled = yes" >> $configurationFile
echo "StartupMailAuthor = $user@techempower.com" >> $configurationFile
echo "FromEmailAddress = $user@techempower.com" >> $configurationFile
echo "PasswordReset.FromAddress = $user@techempower.com" >> $configurationFile
echo "EmailExceptionHandler.ToEmailAddress = $user@techempower.com" >> $configurationFile
echo "EmailExceptionHandler.FromEmailAddress = $user@techempower.com" >> $configurationFile
exit 0
| donovanmuller/FrameworkBenchmarks | frameworks/Java/gemini/setup.sh | Shell | bsd-3-clause | 2,835 |
# -*- coding: utf-8 -*-
"""
BR-specific Form helpers
"""
from django.core.validators import EMPTY_VALUES
from django.forms import ValidationError
from django.forms.fields import Field, RegexField, CharField, Select
from django.utils.encoding import smart_unicode
from django.utils.translation import ugettext_lazy as _
import re
phone_digits_re = re.compile(r'^(\d{2})[-\.]?(\d{4})[-\.]?(\d{4})$')
class BRZipCodeField(RegexField):
default_error_messages = {
'invalid': _('Enter a zip code in the format XXXXX-XXX.'),
}
def __init__(self, *args, **kwargs):
super(BRZipCodeField, self).__init__(r'^\d{5}-\d{3}$',
max_length=None, min_length=None, *args, **kwargs)
class BRPhoneNumberField(Field):
default_error_messages = {
'invalid': _('Phone numbers must be in XX-XXXX-XXXX format.'),
}
def clean(self, value):
super(BRPhoneNumberField, self).clean(value)
if value in EMPTY_VALUES:
return u''
value = re.sub('(\(|\)|\s+)', '', smart_unicode(value))
m = phone_digits_re.search(value)
if m:
return u'%s-%s-%s' % (m.group(1), m.group(2), m.group(3))
raise ValidationError(self.error_messages['invalid'])
class BRStateSelect(Select):
"""
A Select widget that uses a list of Brazilian states/territories
as its choices.
"""
def __init__(self, attrs=None):
from br_states import STATE_CHOICES
super(BRStateSelect, self).__init__(attrs, choices=STATE_CHOICES)
class BRStateChoiceField(Field):
"""
A choice field that uses a list of Brazilian states as its choices.
"""
widget = Select
default_error_messages = {
'invalid': _(u'Select a valid brazilian state. That state is not one of the available states.'),
}
def __init__(self, required=True, widget=None, label=None,
initial=None, help_text=None):
super(BRStateChoiceField, self).__init__(required, widget, label,
initial, help_text)
from br_states import STATE_CHOICES
self.widget.choices = STATE_CHOICES
def clean(self, value):
value = super(BRStateChoiceField, self).clean(value)
if value in EMPTY_VALUES:
value = u''
value = smart_unicode(value)
if value == u'':
return value
valid_values = set([smart_unicode(k) for k, v in self.widget.choices])
if value not in valid_values:
raise ValidationError(self.error_messages['invalid'])
return value
def DV_maker(v):
if v >= 2:
return 11 - v
return 0
class BRCPFField(CharField):
"""
This field validate a CPF number or a CPF string. A CPF number is
compounded by XXX.XXX.XXX-VD. The two last digits are check digits.
More information:
http://en.wikipedia.org/wiki/Cadastro_de_Pessoas_F%C3%ADsicas
"""
default_error_messages = {
'invalid': _("Invalid CPF number."),
'max_digits': _("This field requires at most 11 digits or 14 characters."),
'digits_only': _("This field requires only numbers."),
}
def __init__(self, *args, **kwargs):
super(BRCPFField, self).__init__(max_length=14, min_length=11, *args, **kwargs)
def clean(self, value):
"""
Value can be either a string in the format XXX.XXX.XXX-XX or an
11-digit number.
"""
value = super(BRCPFField, self).clean(value)
if value in EMPTY_VALUES:
return u''
orig_value = value[:]
if not value.isdigit():
value = re.sub("[-\.]", "", value)
try:
int(value)
except ValueError:
raise ValidationError(self.error_messages['digits_only'])
if len(value) != 11:
raise ValidationError(self.error_messages['max_digits'])
orig_dv = value[-2:]
new_1dv = sum([i * int(value[idx]) for idx, i in enumerate(range(10, 1, -1))])
new_1dv = DV_maker(new_1dv % 11)
value = value[:-2] + str(new_1dv) + value[-1]
new_2dv = sum([i * int(value[idx]) for idx, i in enumerate(range(11, 1, -1))])
new_2dv = DV_maker(new_2dv % 11)
value = value[:-1] + str(new_2dv)
if value[-2:] != orig_dv:
raise ValidationError(self.error_messages['invalid'])
return orig_value
class BRCNPJField(Field):
default_error_messages = {
'invalid': _("Invalid CNPJ number."),
'digits_only': _("This field requires only numbers."),
'max_digits': _("This field requires at least 14 digits"),
}
def clean(self, value):
"""
Value can be either a string in the format XX.XXX.XXX/XXXX-XX or a
group of 14 characters.
"""
value = super(BRCNPJField, self).clean(value)
if value in EMPTY_VALUES:
return u''
orig_value = value[:]
if not value.isdigit():
value = re.sub("[-/\.]", "", value)
try:
int(value)
except ValueError:
raise ValidationError(self.error_messages['digits_only'])
if len(value) != 14:
raise ValidationError(self.error_messages['max_digits'])
orig_dv = value[-2:]
new_1dv = sum([i * int(value[idx]) for idx, i in enumerate(range(5, 1, -1) + range(9, 1, -1))])
new_1dv = DV_maker(new_1dv % 11)
value = value[:-2] + str(new_1dv) + value[-1]
new_2dv = sum([i * int(value[idx]) for idx, i in enumerate(range(6, 1, -1) + range(9, 1, -1))])
new_2dv = DV_maker(new_2dv % 11)
value = value[:-1] + str(new_2dv)
if value[-2:] != orig_dv:
raise ValidationError(self.error_messages['invalid'])
return orig_value
| makacodewalker/etsgh | django/contrib/localflavor/br/forms.py | Python | bsd-3-clause | 5,803 |
from datetime import datetime
from django.core.exceptions import ObjectDoesNotExist
from django.db import models, DEFAULT_DB_ALIAS, connection
from django.db.models.fields import FieldDoesNotExist
from django.test import TestCase, skipIfDBFeature, skipUnlessDBFeature
from models import Article
class ModelTest(TestCase):
def test_lookup(self):
# No articles are in the system yet.
self.assertQuerysetEqual(Article.objects.all(), [])
# Create an Article.
a = Article(
id=None,
headline='Area man programs in Python',
pub_date=datetime(2005, 7, 28),
)
# Save it into the database. You have to call save() explicitly.
a.save()
# Now it has an ID.
self.assertTrue(a.id != None)
# Models have a pk property that is an alias for the primary key
# attribute (by default, the 'id' attribute).
self.assertEqual(a.pk, a.id)
# Access database columns via Python attributes.
self.assertEqual(a.headline, 'Area man programs in Python')
self.assertEqual(a.pub_date, datetime(2005, 7, 28, 0, 0))
# Change values by changing the attributes, then calling save().
a.headline = 'Area woman programs in Python'
a.save()
# Article.objects.all() returns all the articles in the database.
self.assertQuerysetEqual(Article.objects.all(),
['<Article: Area woman programs in Python>'])
# Django provides a rich database lookup API.
self.assertEqual(Article.objects.get(id__exact=a.id), a)
self.assertEqual(Article.objects.get(headline__startswith='Area woman'), a)
self.assertEqual(Article.objects.get(pub_date__year=2005), a)
self.assertEqual(Article.objects.get(pub_date__year=2005, pub_date__month=7), a)
self.assertEqual(Article.objects.get(pub_date__year=2005, pub_date__month=7, pub_date__day=28), a)
self.assertEqual(Article.objects.get(pub_date__week_day=5), a)
# The "__exact" lookup type can be omitted, as a shortcut.
self.assertEqual(Article.objects.get(id=a.id), a)
self.assertEqual(Article.objects.get(headline='Area woman programs in Python'), a)
self.assertQuerysetEqual(
Article.objects.filter(pub_date__year=2005),
['<Article: Area woman programs in Python>'],
)
self.assertQuerysetEqual(
Article.objects.filter(pub_date__year=2004),
[],
)
self.assertQuerysetEqual(
Article.objects.filter(pub_date__year=2005, pub_date__month=7),
['<Article: Area woman programs in Python>'],
)
self.assertQuerysetEqual(
Article.objects.filter(pub_date__week_day=5),
['<Article: Area woman programs in Python>'],
)
self.assertQuerysetEqual(
Article.objects.filter(pub_date__week_day=6),
[],
)
# Django raises an Article.DoesNotExist exception for get() if the
# parameters don't match any object.
self.assertRaisesRegexp(
ObjectDoesNotExist,
"Article matching query does not exist.",
Article.objects.get,
id__exact=2000,
)
self.assertRaisesRegexp(
ObjectDoesNotExist,
"Article matching query does not exist.",
Article.objects.get,
pub_date__year=2005,
pub_date__month=8,
)
self.assertRaisesRegexp(
ObjectDoesNotExist,
"Article matching query does not exist.",
Article.objects.get,
pub_date__week_day=6,
)
# Lookup by a primary key is the most common case, so Django
# provides a shortcut for primary-key exact lookups.
# The following is identical to articles.get(id=a.id).
self.assertEqual(Article.objects.get(pk=a.id), a)
# pk can be used as a shortcut for the primary key name in any query.
self.assertQuerysetEqual(Article.objects.filter(pk__in=[a.id]),
["<Article: Area woman programs in Python>"])
# Model instances of the same type and same ID are considered equal.
a = Article.objects.get(pk=a.id)
b = Article.objects.get(pk=a.id)
self.assertEqual(a, b)
def test_object_creation(self):
# Create an Article.
a = Article(
id=None,
headline='Area man programs in Python',
pub_date=datetime(2005, 7, 28),
)
# Save it into the database. You have to call save() explicitly.
a.save()
# You can initialize a model instance using positional arguments,
# which should match the field order as defined in the model.
a2 = Article(None, 'Second article', datetime(2005, 7, 29))
a2.save()
self.assertNotEqual(a2.id, a.id)
self.assertEqual(a2.headline, 'Second article')
self.assertEqual(a2.pub_date, datetime(2005, 7, 29, 0, 0))
# ...or, you can use keyword arguments.
a3 = Article(
id=None,
headline='Third article',
pub_date=datetime(2005, 7, 30),
)
a3.save()
self.assertNotEqual(a3.id, a.id)
self.assertNotEqual(a3.id, a2.id)
self.assertEqual(a3.headline, 'Third article')
self.assertEqual(a3.pub_date, datetime(2005, 7, 30, 0, 0))
# You can also mix and match position and keyword arguments, but
# be sure not to duplicate field information.
a4 = Article(None, 'Fourth article', pub_date=datetime(2005, 7, 31))
a4.save()
self.assertEqual(a4.headline, 'Fourth article')
# Don't use invalid keyword arguments.
self.assertRaisesRegexp(
TypeError,
"'foo' is an invalid keyword argument for this function",
Article,
id=None,
headline='Invalid',
pub_date=datetime(2005, 7, 31),
foo='bar',
)
# You can leave off the value for an AutoField when creating an
# object, because it'll get filled in automatically when you save().
a5 = Article(headline='Article 6', pub_date=datetime(2005, 7, 31))
a5.save()
self.assertEqual(a5.headline, 'Article 6')
# If you leave off a field with "default" set, Django will use
# the default.
a6 = Article(pub_date=datetime(2005, 7, 31))
a6.save()
self.assertEqual(a6.headline, u'Default headline')
# For DateTimeFields, Django saves as much precision (in seconds)
# as you give it.
a7 = Article(
headline='Article 7',
pub_date=datetime(2005, 7, 31, 12, 30),
)
a7.save()
self.assertEqual(Article.objects.get(id__exact=a7.id).pub_date,
datetime(2005, 7, 31, 12, 30))
a8 = Article(
headline='Article 8',
pub_date=datetime(2005, 7, 31, 12, 30, 45),
)
a8.save()
self.assertEqual(Article.objects.get(id__exact=a8.id).pub_date,
datetime(2005, 7, 31, 12, 30, 45))
# Saving an object again doesn't create a new object -- it just saves
# the old one.
current_id = a8.id
a8.save()
self.assertEqual(a8.id, current_id)
a8.headline = 'Updated article 8'
a8.save()
self.assertEqual(a8.id, current_id)
# Check that != and == operators behave as expecte on instances
self.assertTrue(a7 != a8)
self.assertFalse(a7 == a8)
self.assertEqual(a8, Article.objects.get(id__exact=a8.id))
self.assertTrue(Article.objects.get(id__exact=a8.id) != Article.objects.get(id__exact=a7.id))
self.assertFalse(Article.objects.get(id__exact=a8.id) == Article.objects.get(id__exact=a7.id))
# You can use 'in' to test for membership...
self.assertTrue(a8 in Article.objects.all())
# ... but there will often be more efficient ways if that is all you need:
self.assertTrue(Article.objects.filter(id=a8.id).exists())
# dates() returns a list of available dates of the given scope for
# the given field.
self.assertQuerysetEqual(
Article.objects.dates('pub_date', 'year'),
["datetime.datetime(2005, 1, 1, 0, 0)"])
self.assertQuerysetEqual(
Article.objects.dates('pub_date', 'month'),
["datetime.datetime(2005, 7, 1, 0, 0)"])
self.assertQuerysetEqual(
Article.objects.dates('pub_date', 'day'),
["datetime.datetime(2005, 7, 28, 0, 0)",
"datetime.datetime(2005, 7, 29, 0, 0)",
"datetime.datetime(2005, 7, 30, 0, 0)",
"datetime.datetime(2005, 7, 31, 0, 0)"])
self.assertQuerysetEqual(
Article.objects.dates('pub_date', 'day', order='ASC'),
["datetime.datetime(2005, 7, 28, 0, 0)",
"datetime.datetime(2005, 7, 29, 0, 0)",
"datetime.datetime(2005, 7, 30, 0, 0)",
"datetime.datetime(2005, 7, 31, 0, 0)"])
self.assertQuerysetEqual(
Article.objects.dates('pub_date', 'day', order='DESC'),
["datetime.datetime(2005, 7, 31, 0, 0)",
"datetime.datetime(2005, 7, 30, 0, 0)",
"datetime.datetime(2005, 7, 29, 0, 0)",
"datetime.datetime(2005, 7, 28, 0, 0)"])
# dates() requires valid arguments.
self.assertRaisesRegexp(
TypeError,
"dates\(\) takes at least 3 arguments \(1 given\)",
Article.objects.dates,
)
self.assertRaisesRegexp(
FieldDoesNotExist,
"Article has no field named 'invalid_field'",
Article.objects.dates,
"invalid_field",
"year",
)
self.assertRaisesRegexp(
AssertionError,
"'kind' must be one of 'year', 'month' or 'day'.",
Article.objects.dates,
"pub_date",
"bad_kind",
)
self.assertRaisesRegexp(
AssertionError,
"'order' must be either 'ASC' or 'DESC'.",
Article.objects.dates,
"pub_date",
"year",
order="bad order",
)
# Use iterator() with dates() to return a generator that lazily
# requests each result one at a time, to save memory.
dates = []
for article in Article.objects.dates('pub_date', 'day', order='DESC').iterator():
dates.append(article)
self.assertEqual(dates, [
datetime(2005, 7, 31, 0, 0),
datetime(2005, 7, 30, 0, 0),
datetime(2005, 7, 29, 0, 0),
datetime(2005, 7, 28, 0, 0)])
# You can combine queries with & and |.
s1 = Article.objects.filter(id__exact=a.id)
s2 = Article.objects.filter(id__exact=a2.id)
self.assertQuerysetEqual(s1 | s2,
["<Article: Area man programs in Python>",
"<Article: Second article>"])
self.assertQuerysetEqual(s1 & s2, [])
# You can get the number of objects like this:
self.assertEqual(len(Article.objects.filter(id__exact=a.id)), 1)
# You can get items using index and slice notation.
self.assertEqual(Article.objects.all()[0], a)
self.assertQuerysetEqual(Article.objects.all()[1:3],
["<Article: Second article>", "<Article: Third article>"])
s3 = Article.objects.filter(id__exact=a3.id)
self.assertQuerysetEqual((s1 | s2 | s3)[::2],
["<Article: Area man programs in Python>",
"<Article: Third article>"])
# Slicing works with longs.
self.assertEqual(Article.objects.all()[0L], a)
self.assertQuerysetEqual(Article.objects.all()[1L:3L],
["<Article: Second article>", "<Article: Third article>"])
self.assertQuerysetEqual((s1 | s2 | s3)[::2L],
["<Article: Area man programs in Python>",
"<Article: Third article>"])
# And can be mixed with ints.
self.assertQuerysetEqual(Article.objects.all()[1:3L],
["<Article: Second article>", "<Article: Third article>"])
# Slices (without step) are lazy:
self.assertQuerysetEqual(Article.objects.all()[0:5].filter(),
["<Article: Area man programs in Python>",
"<Article: Second article>",
"<Article: Third article>",
"<Article: Article 6>",
"<Article: Default headline>"])
# Slicing again works:
self.assertQuerysetEqual(Article.objects.all()[0:5][0:2],
["<Article: Area man programs in Python>",
"<Article: Second article>"])
self.assertQuerysetEqual(Article.objects.all()[0:5][:2],
["<Article: Area man programs in Python>",
"<Article: Second article>"])
self.assertQuerysetEqual(Article.objects.all()[0:5][4:],
["<Article: Default headline>"])
self.assertQuerysetEqual(Article.objects.all()[0:5][5:], [])
# Some more tests!
self.assertQuerysetEqual(Article.objects.all()[2:][0:2],
["<Article: Third article>", "<Article: Article 6>"])
self.assertQuerysetEqual(Article.objects.all()[2:][:2],
["<Article: Third article>", "<Article: Article 6>"])
self.assertQuerysetEqual(Article.objects.all()[2:][2:3],
["<Article: Default headline>"])
# Using an offset without a limit is also possible.
self.assertQuerysetEqual(Article.objects.all()[5:],
["<Article: Fourth article>",
"<Article: Article 7>",
"<Article: Updated article 8>"])
# Also, once you have sliced you can't filter, re-order or combine
self.assertRaisesRegexp(
AssertionError,
"Cannot filter a query once a slice has been taken.",
Article.objects.all()[0:5].filter,
id=a.id,
)
self.assertRaisesRegexp(
AssertionError,
"Cannot reorder a query once a slice has been taken.",
Article.objects.all()[0:5].order_by,
'id',
)
try:
Article.objects.all()[0:1] & Article.objects.all()[4:5]
self.fail('Should raise an AssertionError')
except AssertionError, e:
self.assertEqual(str(e), "Cannot combine queries once a slice has been taken.")
except Exception, e:
self.fail('Should raise an AssertionError, not %s' % e)
# Negative slices are not supported, due to database constraints.
# (hint: inverting your ordering might do what you need).
try:
Article.objects.all()[-1]
self.fail('Should raise an AssertionError')
except AssertionError, e:
self.assertEqual(str(e), "Negative indexing is not supported.")
except Exception, e:
self.fail('Should raise an AssertionError, not %s' % e)
error = None
try:
Article.objects.all()[0:-5]
except Exception, e:
error = e
self.assertTrue(isinstance(error, AssertionError))
self.assertEqual(str(error), "Negative indexing is not supported.")
# An Article instance doesn't have access to the "objects" attribute.
# That's only available on the class.
self.assertRaisesRegexp(
AttributeError,
"Manager isn't accessible via Article instances",
getattr,
a7,
"objects",
)
# Bulk delete test: How many objects before and after the delete?
self.assertQuerysetEqual(Article.objects.all(),
["<Article: Area man programs in Python>",
"<Article: Second article>",
"<Article: Third article>",
"<Article: Article 6>",
"<Article: Default headline>",
"<Article: Fourth article>",
"<Article: Article 7>",
"<Article: Updated article 8>"])
Article.objects.filter(id__lte=a4.id).delete()
self.assertQuerysetEqual(Article.objects.all(),
["<Article: Article 6>",
"<Article: Default headline>",
"<Article: Article 7>",
"<Article: Updated article 8>"])
@skipUnlessDBFeature('supports_microsecond_precision')
def test_microsecond_precision(self):
# In PostgreSQL, microsecond-level precision is available.
a9 = Article(
headline='Article 9',
pub_date=datetime(2005, 7, 31, 12, 30, 45, 180),
)
a9.save()
self.assertEqual(Article.objects.get(pk=a9.pk).pub_date,
datetime(2005, 7, 31, 12, 30, 45, 180))
@skipIfDBFeature('supports_microsecond_precision')
def test_microsecond_precision_not_supported(self):
# In MySQL, microsecond-level precision isn't available. You'll lose
# microsecond-level precision once the data is saved.
a9 = Article(
headline='Article 9',
pub_date=datetime(2005, 7, 31, 12, 30, 45, 180),
)
a9.save()
self.assertEqual(Article.objects.get(id__exact=a9.id).pub_date,
datetime(2005, 7, 31, 12, 30, 45))
def test_manually_specify_primary_key(self):
# You can manually specify the primary key when creating a new object.
a101 = Article(
id=101,
headline='Article 101',
pub_date=datetime(2005, 7, 31, 12, 30, 45),
)
a101.save()
a101 = Article.objects.get(pk=101)
self.assertEqual(a101.headline, u'Article 101')
def test_create_method(self):
# You can create saved objects in a single step
a10 = Article.objects.create(
headline="Article 10",
pub_date=datetime(2005, 7, 31, 12, 30, 45),
)
self.assertEqual(Article.objects.get(headline="Article 10"), a10)
def test_year_lookup_edge_case(self):
# Edge-case test: A year lookup should retrieve all objects in
# the given year, including Jan. 1 and Dec. 31.
a11 = Article.objects.create(
headline='Article 11',
pub_date=datetime(2008, 1, 1),
)
a12 = Article.objects.create(
headline='Article 12',
pub_date=datetime(2008, 12, 31, 23, 59, 59, 999999),
)
self.assertQuerysetEqual(Article.objects.filter(pub_date__year=2008),
["<Article: Article 11>", "<Article: Article 12>"])
def test_unicode_data(self):
# Unicode data works, too.
a = Article(
headline=u'\u6797\u539f \u3081\u3050\u307f',
pub_date=datetime(2005, 7, 28),
)
a.save()
self.assertEqual(Article.objects.get(pk=a.id).headline,
u'\u6797\u539f \u3081\u3050\u307f')
def test_hash_function(self):
# Model instances have a hash function, so they can be used in sets
# or as dictionary keys. Two models compare as equal if their primary
# keys are equal.
a10 = Article.objects.create(
headline="Article 10",
pub_date=datetime(2005, 7, 31, 12, 30, 45),
)
a11 = Article.objects.create(
headline='Article 11',
pub_date=datetime(2008, 1, 1),
)
a12 = Article.objects.create(
headline='Article 12',
pub_date=datetime(2008, 12, 31, 23, 59, 59, 999999),
)
s = set([a10, a11, a12])
self.assertTrue(Article.objects.get(headline='Article 11') in s)
def test_extra_method_select_argument_with_dashes_and_values(self):
# The 'select' argument to extra() supports names with dashes in
# them, as long as you use values().
a10 = Article.objects.create(
headline="Article 10",
pub_date=datetime(2005, 7, 31, 12, 30, 45),
)
a11 = Article.objects.create(
headline='Article 11',
pub_date=datetime(2008, 1, 1),
)
a12 = Article.objects.create(
headline='Article 12',
pub_date=datetime(2008, 12, 31, 23, 59, 59, 999999),
)
dicts = Article.objects.filter(
pub_date__year=2008).extra(
select={'dashed-value': '1'}
).values('headline', 'dashed-value')
self.assertEqual([sorted(d.items()) for d in dicts],
[[('dashed-value', 1), ('headline', u'Article 11')], [('dashed-value', 1), ('headline', u'Article 12')]])
def test_extra_method_select_argument_with_dashes(self):
# If you use 'select' with extra() and names containing dashes on a
# query that's *not* a values() query, those extra 'select' values
# will silently be ignored.
a10 = Article.objects.create(
headline="Article 10",
pub_date=datetime(2005, 7, 31, 12, 30, 45),
)
a11 = Article.objects.create(
headline='Article 11',
pub_date=datetime(2008, 1, 1),
)
a12 = Article.objects.create(
headline='Article 12',
pub_date=datetime(2008, 12, 31, 23, 59, 59, 999999),
)
articles = Article.objects.filter(
pub_date__year=2008).extra(
select={'dashed-value': '1', 'undashedvalue': '2'})
self.assertEqual(articles[0].undashedvalue, 2)
| django-nonrel/django-nonrel | tests/modeltests/basic/tests.py | Python | bsd-3-clause | 21,594 |
(function($) {
/**
* @class File manager (main controller)
* @author dio dio@std42.ru
**/
elFinder = function(el, o) {
var self = this, id;
this.log = function(m) {
window.console && window.console.log && window.console.log(m);
}
/**
* Object. File manager configuration
**/
this.options = $.extend({}, this.options, o||{});
if (!this.options.url) {
alert('Invalid configuration! You have to set URL option.');
return;
}
/**
* String. element id, create random if not set;
**/
this.id = '';
if ((id = $(el).attr('id'))) {
this.id = id;
} else {
// this.id = 'el-finder-'+Math.random().toString().substring(2);
}
/**
* String. Version number;
**/
this.version = '1.2';
/**
* String. jQuery version;
**/
this.jquery = $.fn.jquery.split('.').join('');
/**
* Object. Current Working Dir info
**/
this.cwd = {};
/**
* Object. Current Dir Content. Files/folders info
**/
this.cdc = {};
/**
* Object. Buffer for copied files
**/
this.buffer = {};
/**
* Array. Selected files IDs
**/
this.selected = [];
/**
* Array. Folder navigation history
**/
this.history = [];
/**
* Boolean. Enable/disable actions
**/
this.locked = false;
/**
* Number. Max z-index on page + 1, need for contextmenu and quicklook
**/
this.zIndex = 2;
/**
* DOMElement. jQueryUI dialog
**/
this.dialog = null;
/**
* DOMElement. For docked mode - place where fm is docked
**/
this.anchor = this.options.docked ? $('<div/>').hide().insertBefore(el) : null;
/**
* Object. Some options get from server
**/
this.params = { dotFiles : false, arc : '', uplMaxSize : '' };
this.vCookie = 'el-finder-view-'+this.id;
this.pCookie = 'el-finder-places-'+this.id;
this.lCookie = 'el-finder-last-'+this.id;
/**
* Object. View. After init we can accessel as this.view.win
**/
this.view = new this.view(this, el);
/**
* Object. User Iterface. Controller for commands/buttons/contextmenu
**/
this.ui = new this.ui(this);
/**
* Object. Set/update events
**/
this.eventsManager = new this.eventsManager(this);
/**
* Object. Quick Look like in MacOS X :)
**/
this.quickLook = new this.quickLook(this);
/**
* Set/get cookie value
*
* @param String name cookie name
* @param String value cookie value, null to unset
**/
this.cookie = function(name, value) {
if (typeof value == 'undefined') {
if (document.cookie && document.cookie != '') {
var i, c = document.cookie.split(';');
name += '=';
for (i=0; i<c.length; i++) {
c[i] = $.trim(c[i]);
if (c[i].substring(0, name.length) == name) {
return decodeURIComponent(c[i].substring(name.length));
}
}
}
return '';
} else {
var d, o = $.extend({}, this.options.cookie);
if (value===null) {
value = '';
o.expires = -1;
}
if (typeof(o.expires) == 'number') {
d = new Date();
d.setTime(d.getTime()+(o.expires * 24 * 60 * 60 * 1000));
o.expires = d;
}
document.cookie = name+'='+encodeURIComponent(value)+'; expires='+o.expires.toUTCString()+(o.path ? '; path='+o.path : '')+(o.domain ? '; domain='+o.domain : '')+(o.secure ? '; secure' : '');
}
}
/**
* Set/unset this.locked flag
*
* @param Boolean state
**/
this.lock = function(l) {
this.view.spinner((this.locked = l||false));
this.eventsManager.lock = this.locked;
}
/**
* Set/unset lock for keyboard shortcuts
*
* @param Boolean state
**/
this.lockShortcuts = function(l) {
this.eventsManager.lock = !!l;
}
/**
* Set file manager view type (list|icons)
*
* @param String v view name
**/
this.setView = function(v) {
if (v == 'list' || v == 'icons') {
this.options.view = v;
this.cookie(this.vCookie, v);
}
}
/**
* make ajax request, show message on error, call callback on success
*
* @param Object. data for ajax request
* @param Function
* @param Object overrwrite some options
*/
this.ajax = function(data, callback, options) {
var opts = {
url : this.options.url,
async : true,
type : 'GET',
data : data,
dataType : 'json',
cache : false,
lock : true,
force : false,
silent : false
}
if (typeof(options) == 'object') {
opts = $.extend({}, opts, options);
}
if (!opts.silent) {
opts.error = self.view.fatal;
}
opts.success = function(data) {
opts.lock && self.lock();
if (data) {
data.debug && self.log(data.debug);
if (data.error) {
!opts.silent && self.view.error(data.error, data.errorData);
if (!opts.force) {
return;
}
}
callback(data);
delete data;
}
}
opts.lock && this.lock(true);
$.ajax(opts);
}
/**
* Load generated thumbnails in background
*
**/
this.tmb = function() {
this.ajax({cmd : 'tmb', current : self.cwd.hash}, function(data) {
if (self.options.view == 'icons' && data.images && data.current == self.cwd.hash) {
for (var i in data.images) {
if (self.cdc[i]) {
self.cdc[i].tmb = data.images[i];
$('div[key="'+i+'"]>p', self.view.cwd).css('background', ' url("'+data.images[i]+'") 0 0 no-repeat');
}
}
data.tmb && self.tmb();
}
}, {lock : false, silent : true});
}
/**
* Return folders in places IDs
*
* @return Array
**/
this.getPlaces = function() {
var pl = [], p = this.cookie(this.pCookie);
if (p.length) {
if (p.indexOf(':')!=-1) {
pl = p.split(':');
} else {
pl.push(p);
}
}
return pl;
}
/**
* Add new folder to places
*
* @param String Folder ID
* @return Boolean
**/
this.addPlace = function(id) {
var p = this.getPlaces();
if ($.inArray(id, p) == -1) {
p.push(id);
this.savePlaces(p);
return true;
}
}
/**
* Remove folder from places
*
* @param String Folder ID
* @return Boolean
**/
this.removePlace = function(id) {
var p = this.getPlaces();
if ($.inArray(id, p) != -1) {
this.savePlaces($.map(p, function(o) { return o == id?null:o; }));
return true;
}
}
/**
* Save new places data in cookie
*
* @param Array Folders IDs
**/
this.savePlaces = function(p) {
this.cookie(this.pCookie, p.join(':'));
}
/**
* Update file manager content
*
* @param Object Data from server
**/
this.reload = function(data) {
var i;
this.cwd = data.cwd;
this.cdc = {};
for (i=0; i<data.cdc.length ; i++) {
if (data.cdc[i].hash && data.cdc[i].name) {
this.cdc[data.cdc[i].hash] = data.cdc[i];
this.cwd.size += data.cdc[i].size;
}
}
if (data.tree) {
this.view.renderNav(data.tree);
this.eventsManager.updateNav();
}
this.updateCwd();
/* tell connector to generate thumbnails */
if (data.tmb && !self.locked && self.options.view == 'icons') {
self.tmb();
}
/* have to select some files */
if (data.select && data.select.length) {
var l = data.select.length;
while (l--) {
this.cdc[data.select[l]] && this.selectById(data.select[l]);
}
}
this.lastDir(this.cwd.hash);
if (this.options.autoReload>0) {
this.iID && clearInterval(this.iID);
this.iID = setInterval(function() { !self.locked && self.ui.exec('reload'); }, this.options.autoReload*60000);
}
}
/**
* Redraw current directory
*
*/
this.updateCwd = function() {
this.lockShortcuts(true);
this.selected = [];
this.view.renderCwd();
this.eventsManager.updateCwd();
this.view.tree.find('a[key="'+this.cwd.hash+'"]').trigger('select');
this.lockShortcuts();
}
/**
* Execute after files was dropped onto folder
*
* @param Object drop event
* @param Object drag helper object
* @param String target folder ID
*/
this.drop = function(e, ui, target) {
if (ui.helper.find('[key="'+target+'"]').length) {
return self.view.error('Unable to copy into itself');
}
var ids = [];
ui.helper.find('div:not(.noaccess):has(>label):not(:has(em[class="readonly"],em[class=""]))').each(function() {
ids.push($(this).hide().attr('key'));
});
if (!ui.helper.find('div:has(>label):visible').length) {
ui.helper.hide();
}
if (ids.length) {
self.setBuffer(ids, e.shiftKey?0:1, target);
if (self.buffer.files) {
/* some strange jquery ui bug (in list view) */
setTimeout(function() {self.ui.exec('paste'); self.buffer = {}}, 300);
}
} else {
$(this).removeClass('el-finder-droppable');
}
}
/**
* Return selected files data
*
* @param Number if set, returns only element with this index or empty object
* @return Array|Object
*/
this.getSelected = function(ndx) {
var i, s = [];
if (ndx>=0) {
return this.cdc[this.selected[ndx]]||{};
}
for (i=0; i<this.selected.length; i++) {
this.cdc[this.selected[i]] && s.push(this.cdc[this.selected[i]]);
}
return s;
}
this.select = function(el, reset) {
reset && $('.ui-selected', self.view.cwd).removeClass('ui-selected');
el.addClass('ui-selected');
self.updateSelect();
}
this.selectById = function(id) {
var el = $('[key="'+id+'"]', this.view.cwd);
if (el.length) {
this.select(el);
this.checkSelectedPos();
}
}
this.unselect = function(el) {
el.removeClass('ui-selected');
self.updateSelect();
}
this.toggleSelect = function(el) {
el.toggleClass('ui-selected');
this.updateSelect();
}
this.selectAll = function() {
$('[key]', self.view.cwd).addClass('ui-selected')
self.updateSelect();
}
this.unselectAll = function() {
$('.ui-selected', self.view.cwd).removeClass('ui-selected');
self.updateSelect();
}
this.updateSelect = function() {
self.selected = [];
$('.ui-selected', self.view.cwd).each(function() {
self.selected.push($(this).attr('key'));
});
self.view.selectedInfo();
self.ui.update();
self.quickLook.update();
}
/**
* Scroll selected element in visible position
*
* @param Boolean check last or first selected element?
*/
this.checkSelectedPos = function(last) {
var s = self.view.cwd.find('.ui-selected:'+(last ? 'last' : 'first')).eq(0),
p = s.position(),
h = s.outerHeight(),
ph = self.view.cwd.height();
if (p.top < 0) {
self.view.cwd.scrollTop(p.top+self.view.cwd.scrollTop()-2);
} else if (ph - p.top < h) {
self.view.cwd.scrollTop(p.top+h-ph+self.view.cwd.scrollTop());
}
}
/**
* Add files to clipboard buffer
*
* @param Array files IDs
* @param Boolean copy or cut files?
* @param String destination folder ID
*/
this.setBuffer = function(files, cut, dst) {
var i, id, f;
this.buffer = {
src : this.cwd.hash,
dst : dst,
files : [],
names : [],
cut : cut||0
};
for (i=0; i<files.length; i++) {
id = files[i];
f = this.cdc[id];
if (f && f.read && f.type != 'link') {
this.buffer.files.push(f.hash);
this.buffer.names.push(f.name);
}
}
if (!this.buffer.files.length) {
this.buffer = {};
}
}
/**
* Return true if file name is acceptable
*
* @param String file/folder name
* @return Boolean
*/
this.isValidName = function(n) {
if (!this.cwd.dotFiles && n.indexOf('.') == 0) {
return false;
}
return n.match(/^[^\\\/\<\>:]+$/);
}
/**
* Return true if file with this name exists
*
* @param String file/folder name
* @return Boolean
*/
this.fileExists = function(n) {
for (var i in this.cdc) {
if (this.cdc[i].name == n) {
return i;
}
}
return false;
}
/**
* Return name for new file/folder
*
* @param String base name (i18n)
* @param String extension for file
* @return String
*/
this.uniqueName = function(n, ext) {
n = self.i18n(n);
var name = n, i = 0, ext = ext||'';
if (!this.fileExists(name+ext)) {
return name+ext;
}
while (i++<100) {
if (!this.fileExists(name+i+ext)) {
return name+i+ext;
}
}
return name.replace('100', '')+Math.random()+ext;
}
/**
* Get/set last opened dir
*
* @param String dir hash
* @return String
*/
this.lastDir = function(dir) {
if (this.options.rememberLastDir) {
return dir ? this.cookie(this.lCookie, dir) : this.cookie(this.lCookie);
}
}
/**
* Resize file manager
*
* @param Number width
* @param Number height
*/
function resize(w, h) {
w && self.view.win.width(w);
h && self.view.nav.add(self.view.cwd).height(h);
}
/**
* Resize file manager in dialog window while it resize
*
*/
function dialogResize() {
resize(null, self.dialog.height()-self.view.tlb.parent().height()-($.browser.msie ? 47 : 32))
}
this.time = function() {
return new Date().getMilliseconds();
}
/* here we init file manager */
this.setView(this.cookie(this.vCookie));
resize(self.options.width, self.options.height);
/* dialog or docked mode */
if (this.options.dialog || this.options.docked) {
this.options.dialog = $.extend({width : 570, dialogClass : '', minWidth : 480, minHeight: 330}, this.options.dialog || {});
this.options.dialog.open = function() {
setTimeout(function() {
$('<input type="text" value="f"/>').appendTo(self.view.win).focus().select().remove()
}, 200)
}
this.options.dialog.dialogClass += 'el-finder-dialog';
this.options.dialog.resize = dialogResize;
if (this.options.docked) {
/* docked mode - create dialog and store size */
this.options.dialog.close = function() { self.dock(); };
this.view.win.data('size', {width : this.view.win.width(), height : this.view.nav.height()});
} else {
this.options.dialog.close = function() {
self.destroy();
}
this.dialog = $('<div/>').append(this.view.win).dialog(this.options.dialog);
}
}
this.ajax({
cmd : 'open',
target : this.lastDir()||'',
init : true,
tree : true
},
function(data) {
if (data.cwd) {
self.eventsManager.init();
self.reload(data);
$.extend(self.params, data.params||{});
$('*', document.body).each(function() {
var z = parseInt($(this).css('z-index'));
if (z >= self.zIndex) {
self.zIndex = z+1;
}
});
self.ui.init(data.disabled);
}
}, {force : true});
this.open = function() {
this.dialog ? this.dialog.dialog('open') : this.view.win.show();
this.eventsManager.lock = false;
}
this.close = function() {
this.quickLook.hide();
if (this.options.docked && this.view.win.attr('undocked')) {
this.dock();
} else {
this.dialog ? this.dialog.dialog('close') : this.view.win.hide();
}
this.eventsManager.lock = true;
}
this.destroy = function() {
this.eventsManager.lock = true;
this.quickLook.hide();
this.quickLook.win.remove();
if (this.dialog) {
this.dialog.dialog('destroy');
this.view.win.parent().remove();
} else {
this.view.win.remove();
}
this.ui.menu.remove();
}
this.dock = function() {
if (this.options.docked && this.view.win.attr('undocked')) {
this.quickLook.hide();
var s =this.view.win.data('size');
this.view.win.insertAfter(this.anchor).removeAttr('undocked');
resize(s.width, s.height);
this.dialog.dialog('destroy');
this.dialog = null;
}
}
this.undock = function() {
if (this.options.docked && !this.view.win.attr('undocked')) {
this.quickLook.hide();
this.dialog = $('<div/>').append(this.view.win.css('width', '100%').attr('undocked', true).show()).dialog(this.options.dialog);
dialogResize();
}
}
}
/**
* Translate message into selected language
*
* @param String message in english
* @param String translated or original message
*/
elFinder.prototype.i18n = function(m) {
return this.options.i18n[this.options.lang] && this.options.i18n[this.options.lang][m] ? this.options.i18n[this.options.lang][m] : m;
}
/**
* Default config
*
*/
elFinder.prototype.options = {
/* connector url. Required! */
url : '',
/* interface language */
lang : 'en',
/* additional css class for filemanager container */
cssClass : '',
/* characters number to wrap file name in icons view. set to 0 to disable wrap */
wrap : 14,
/* Name for places/favorites (i18n), set to '' to disable places */
places : 'Places',
/* show places before navigation? */
placesFirst : true,
/* callback to get file url (for wswing editors) */
editorCallback : null,
/* string to cut from file url begin before pass it to editorCallback. variants: '' - nothing to cut, 'root' - cut root url, 'http://...' - string if it exists in the beginig of url */
cutURL : '',
/* close elfinder after editorCallback */
closeOnEditorCallback : true,
/* i18 messages. not set manually! */
i18n : {},
/* fm view (icons|list) */
view : 'icons',
/* width to overwrite css options */
width : '',
/* height to overwrite css options. Attenion! this is heigt of navigation/cwd panels! not total fm height */
height : '',
/* disable shortcuts exclude arrows/space */
disableShortcuts : false,
/* open last visited dir after reload page or close and open browser */
rememberLastDir : true,
/* cookie options */
cookie : {
expires : 30,
domain : '',
path : '/',
secure : false
},
/* buttons on toolbar */
toolbar : [
['back', 'reload'],
['select', 'open'],
['mkdir', 'mkfile', 'upload'],
['copy', 'paste', 'rm'],
['rename', 'edit'],
['info', 'quicklook', 'resize'],
['icons', 'list'],
['help']
],
/* contextmenu commands */
contextmenu : {
'cwd' : ['reload', 'delim', 'mkdir', 'mkfile', 'upload', 'delim', 'paste', 'delim', 'info'],
'file' : ['select', 'open', 'quicklook', 'delim', 'copy', 'cut', 'rm', 'delim', 'duplicate', 'rename', 'edit', 'resize', 'archive', 'extract', 'delim', 'info'],
'group' : ['select', 'copy', 'cut', 'rm', 'delim', 'archive', 'extract', 'delim', 'info']
},
/* jqueryUI dialog options */
dialog : null,
/* docked mode */
docked : false,
/* auto reload time (min) */
autoReload : 0,
/* set to true if you need to select several files at once from editorCallback */
selectMultiple : false
}
$.fn.elfinder = function(o) {
return this.each(function() {
var cmd = typeof(o) == 'string' ? o : '';
if (!this.elfinder) {
this.elfinder = new elFinder(this, typeof(o) == 'object' ? o : {})
}
switch(cmd) {
case 'close':
case 'hide':
this.elfinder.close();
break;
case 'open':
case 'show':
this.elfinder.open();
break;
case 'dock':
this.elfinder.dock();
break;
case 'undock':
this.elfinder.undock();
break;
case'destroy':
this.elfinder.destroy();
break;
}
})
}
})(jQuery);
(function($) {
elFinder.prototype.view = function(fm, el) {
var self = this;
this.fm = fm;
/**
* Object. Mimetypes to kinds mapping
**/
this.kinds = {
'unknown' : 'Unknown',
'directory' : 'Folder',
'symlink' : 'Alias',
'symlink-broken' : 'Broken alias',
'application/x-empty' : 'Plain text',
'application/postscript' : 'Postscript document',
'application/octet-stream' : 'Application',
'application/vnd.ms-office' : 'Microsoft Office document',
'application/vnd.ms-word' : 'Microsoft Word document',
'application/vnd.ms-excel' : 'Microsoft Excel document',
'application/vnd.ms-powerpoint' : 'Microsoft Powerpoint presentation',
'application/pdf' : 'Portable Document Format (PDF)',
'application/vnd.oasis.opendocument.text' : 'Open Office document',
'application/x-shockwave-flash' : 'Flash application',
'application/xml' : 'XML document',
'application/x-bittorrent' : 'Bittorrent file',
'application/x-7z-compressed' : '7z archive',
'application/x-tar' : 'TAR archive',
'application/x-gzip' : 'GZIP archive',
'application/x-bzip2' : 'BZIP archive',
'application/zip' : 'ZIP archive',
'application/x-rar' : 'RAR archive',
'application/javascript' : 'Javascript application',
'text/plain' : 'Plain text',
'text/x-php' : 'PHP source',
'text/html' : 'HTML document',
'text/javascript' : 'Javascript source',
'text/css' : 'CSS style sheet',
'text/rtf' : 'Rich Text Format (RTF)',
'text/rtfd' : 'RTF with attachments (RTFD)',
'text/x-c' : 'C source',
'text/x-c++' : 'C++ source',
'text/x-shellscript' : 'Unix shell script',
'text/x-python' : 'Python source',
'text/x-java' : 'Java source',
'text/x-ruby' : 'Ruby source',
'text/x-perl' : 'Perl script',
'text/xml' : 'XML document',
'image/x-ms-bmp' : 'BMP image',
'image/jpeg' : 'JPEG image',
'image/gif' : 'GIF Image',
'image/png' : 'PNG image',
'image/x-targa' : 'TGA image',
'image/tiff' : 'TIFF image',
'image/vnd.adobe.photoshop' : 'Adobe Photoshop image',
'audio/mpeg' : 'MPEG audio',
'audio/midi' : 'MIDI audio',
'audio/ogg' : 'Ogg Vorbis audio',
'audio/mp4' : 'MP4 audio',
'audio/wav' : 'WAV audio',
'video/x-dv' : 'DV video',
'video/mp4' : 'MP4 video',
'video/mpeg' : 'MPEG video',
'video/x-msvideo' : 'AVI video',
'video/quicktime' : 'Quicktime video',
'video/x-ms-wmv' : 'WM video',
'video/x-flv' : 'Flash video',
'video/x-matroska' : 'Matroska video'
}
this.tlb = $('<ul />');
this.nav = $('<div class="el-finder-nav"/>').resizable({handles : 'e', autoHide : true, minWidth : 200, maxWidth: 500});
this.cwd = $('<div class="el-finder-cwd"/>').attr('unselectable', 'on');
this.spn = $('<div class="el-finder-spinner"/>');
this.err = $('<p class="el-finder-err"><strong/></p>').click(function() { $(this).hide(); });
this.nfo = $('<div class="el-finder-stat"/>');
this.pth = $('<div class="el-finder-path"/>');
this.sel = $('<div class="el-finder-sel"/>');
this.stb = $('<div class="el-finder-statusbar"/>')
.append(this.pth)
.append(this.nfo)
.append(this.sel);
this.wrz = $('<div class="el-finder-workzone" />')
.append(this.nav)
.append(this.cwd)
.append(this.spn)
.append(this.err)
.append('<div style="clear:both" />');
this.win = $(el).empty().attr('id', this.fm.id).addClass('el-finder '+(fm.options.cssClass||''))
.append($('<div class="el-finder-toolbar" />').append(this.tlb))
.append(this.wrz)
.append(this.stb);
this.tree = $('<ul class="el-finder-tree"></ul>').appendTo(this.nav);
this.plc = $('<ul class="el-finder-places"><li><a href="#" class="el-finder-places-root"><div/>'+this.fm.i18n(this.fm.options.places)+'</a><ul/></li></ul>').hide();
this.nav[this.fm.options.placesFirst ? 'prepend' : 'append'](this.plc);
/*
* Render ajax spinner
*/
this.spinner = function(show) {
this.win.toggleClass('el-finder-disabled', show);
this.spn.toggle(show);
}
/*
* Display ajax error
*/
this.fatal = function(t) {
self.error(t.status != '404' ? 'Invalid backend configuration' : 'Unable to connect to backend')
}
/*
* Render error
*/
this.error = function(err, data) {
this.fm.lock();
this.err.show().children('strong').html(this.fm.i18n(err)+'!'+this.formatErrorData(data));
setTimeout(function() { self.err.fadeOut('slow'); }, 4000);
}
/*
* Render navigation panel with dirs tree
*/
this.renderNav = function(tree) {
var d = tree.dirs.length ? traverse(tree.dirs) : '',
li = '<li><a href="#" class="el-finder-tree-root" key="'+tree.hash+'"><div'+(d ? ' class="collapsed expanded"' : '')+'/>'+tree.name+'</a>'+d+'</li>';
this.tree.html(li);
this.fm.options.places && this.renderPlaces();
function traverse(tree) {
var i, hash, c, html = '<ul style="display:none">';
for (i=0; i < tree.length; i++) {
if (!tree[i].name || !tree[i].hash) {
continue;
}
c = '';
if (!tree[i].read && !tree[i].write) {
c = 'noaccess';
} else if (!tree[i].read) {
c = 'dropbox';
} else if (!tree[i].write) {
c = 'readonly';
}
html += '<li><a href="#" class="'+c+'" key="'+tree[i].hash+'"><div'+(tree[i].dirs.length ? ' class="collapsed"' : '')+'/>'+tree[i].name+'</a>';
if (tree[i].dirs.length) {
html += traverse(tree[i].dirs);
}
html += '</li>';
}
return html +'</ul>';
}
}
/*
* Render places
*/
this.renderPlaces = function() {
var i, c,
pl = this.fm.getPlaces(),
ul = this.plc.show().find('ul').empty().hide();
$('div:first', this.plc).removeClass('collapsed expanded');
if (pl.length) {
pl.sort(function(a, b) {
var _a = self.tree.find('a[key="'+a+'"]').text()||'',
_b = self.tree.find('a[key="'+b+'"]').text()||'';
return _a.localeCompare(_b);
});
for (i=0; i < pl.length; i++) {
if ((c = this.tree.find('a[key="'+pl[i]+'"]:not(.dropbox)').parent()) && c.length) {
ul.append(c.clone().children('ul').remove().end().find('div').removeClass('collapsed expanded').end());
} else {
this.fm.removePlace(pl[i]);
}
};
ul.children().length && $('div:first', this.plc).addClass('collapsed');
}
}
/*
* Render current directory
*/
this.renderCwd = function() {
this.cwd.empty();
var num = 0, size = 0, html = '';
for (var hash in this.fm.cdc) {
num++;
size += this.fm.cdc[hash].size;
html += this.fm.options.view == 'icons'
? this.renderIcon(this.fm.cdc[hash])
: this.renderRow(this.fm.cdc[hash], num%2);
}
if (this.fm.options.view == 'icons') {
this.cwd.append(html);
} else {
this.cwd.append('<table><tr><th colspan="2">'+this.fm.i18n('Name')+'</th><th>'+this.fm.i18n('Permissions')+'</th><th>'+this.fm.i18n('Modified')+'</th><th class="size">'+this.fm.i18n('Size')+'</th><th>'+this.fm.i18n('Kind')+'</th></tr>'+html+'</table>');
}
this.pth.text(fm.cwd.rel);
this.nfo.text(fm.i18n('items')+': '+num+', '+this.formatSize(size));
this.sel.empty();
}
/*
* Render one file as icon
*/
this.renderIcon = function(f) {
var str = '<p'+(f.tmb ? ' style="'+"background:url('"+f.tmb+"') 0 0 no-repeat"+'"' : '')+'/><label>'+this.formatName(f.name)+'</label>';
if (f.link || f.mime == 'symlink-broken') {
str += '<em/>';
}
if (!f.read && !f.write) {
str += '<em class="noaccess"/>';
} else if (f.read && !f.write) {
str += '<em class="readonly"/>';
} else if (!f.read && f.write) {
str += '<em class="'+(f.mime == 'directory' ? 'dropbox' :'noread')+'" />';
}
return '<div class="'+this.mime2class(f.mime)+'" key="'+f.hash+'">'+str+'</div>';
}
/*
* Render one file as table row
*/
this.renderRow = function(f, odd) {
var str = f.link || f.mime =='symlink-broken' ? '<em/>' : '';
if (!f.read && !f.write) {
str += '<em class="noaccess"/>';
} else if (f.read && !f.write) {
str += '<em class="readonly"/>';
} else if (!f.read && f.write) {
str += '<em class="'+(f.mime == 'directory' ? 'dropbox' :'noread')+'" />';
}
return '<tr key="'+f.hash+'" class="'+self.mime2class(f.mime)+(odd ? ' el-finder-row-odd' : '')+'"><td class="icon"><p>'+str+'</p></td><td>'+f.name+'</td><td>'+self.formatPermissions(f.read, f.write, f.rm)+'</td><td>'+self.formatDate(f.date)+'</td><td class="size">'+self.formatSize(f.size)+'</td><td>'+self.mime2kind(f.link ? 'symlink' : f.mime)+'</td></tr>';
}
/*
* Re-render file (after editing)
*/
this.updateFile = function(f) {
var e = this.cwd.find('[key="'+f.hash+'"]');
e.replaceWith(e[0].nodeName == 'DIV' ? this.renderIcon(f) : this.renderRow(f));
}
/*
* Update info about selected files
*/
this.selectedInfo = function() {
var i, s = 0, sel;
if (self.fm.selected.length) {
sel = this.fm.getSelected();
for (i=0; i<sel.length; i++) {
s += sel[i].size;
}
}
this.sel.text(i>0 ? this.fm.i18n('selected items')+': '+sel.length+', '+this.formatSize(s) : '');
}
/*
* Return wraped file name if needed
*/
this.formatName = function(n) {
var w = self.fm.options.wrap;
if (w>0) {
if (n.length > w*2) {
return n.substr(0, w)+"­"+n.substr(w, w-5)+"…"+n.substr(n.length-3);
} else if (n.length > w) {
return n.substr(0, w)+"­"+n.substr(w);
}
}
return n;
}
/*
* Return error message
*/
this.formatErrorData = function(data) {
var i, err = ''
if (typeof(data) == 'object') {
err = '<br />';
for (i in data) {
err += i+' '+self.fm.i18n(data[i])+'<br />';
}
}
return err;
}
/*
* Convert mimetype into css class
*/
this.mime2class = function(mime) {
return mime.replace('/' , ' ').replace(/\./g, '-');
}
/*
* Return localized date
*/
this.formatDate = function(d) {
return d.replace(/([a-z]+)\s/i, function(a1, a2) { return self.fm.i18n(a2)+' '; });
}
/*
* Return formated file size
*/
this.formatSize = function(s) {
var n = 1, u = 'bytes';
if (s > 1073741824) {
n = 1073741824;
u = 'Gb';
} else if (s > 1048576) {
n = 1048576;
u = 'Mb';
} else if (s > 1024) {
n = 1024;
u = 'Kb';
}
return Math.round(s/n)+' '+u;
}
/*
* Return localized string with file permissions
*/
this.formatPermissions = function(r, w, rm) {
var p = [];
r && p.push(self.fm.i18n('read'));
w && p.push(self.fm.i18n('write'));
rm && p.push(self.fm.i18n('remove'));
return p.join('/');
}
/*
* Return kind of file
*/
this.mime2kind = function(mime) {
return this.fm.i18n(this.kinds[mime]||'unknown');
}
}
})(jQuery);
/**
* @class elFinder user Interface.
* @author dio dio@std42.ru
**/
(function($) {
elFinder.prototype.ui = function(fm) {
var self = this;
this.fm = fm;
this.cmd = {};
this.buttons = {};
this.menu = $('<div class="el-finder-contextmenu" />').appendTo(document.body).hide();
this.dockButton = $('<div class="el-finder-dock-button" title="'+self.fm.i18n('Dock/undock filemanager window')+'" />');
this.exec = function(cmd, arg) {
if (this.cmd[cmd]) {
if (cmd != 'open' && !this.cmd[cmd].isAllowed()) {
return this.fm.view.error('Command not allowed');
}
if (!this.fm.locked) {
this.fm.quickLook.hide();
$('.el-finder-info').remove();
this.cmd[cmd].exec(arg);
this.update();
}
}
}
this.cmdName = function(cmd) {
if (this.cmd[cmd] && this.cmd[cmd].name) {
return cmd == 'archive' && this.fm.params.archives.length == 1
? this.fm.i18n('Create')+' '+this.fm.view.mime2kind(this.fm.params.archives[0]).toLowerCase()
: this.fm.i18n(this.cmd[cmd].name);
}
return cmd;
}
this.isCmdAllowed = function(cmd) {
return self.cmd[cmd] && self.cmd[cmd].isAllowed();
}
this.execIfAllowed = function(cmd) {
this.isCmdAllowed(cmd) && this.exec(cmd);
}
this.includeInCm = function(cmd, t) {
return this.isCmdAllowed(cmd) && this.cmd[cmd].cm(t);
}
this.showMenu = function(e) {
var t, win, size, id = '';
this.hideMenu();
if (!self.fm.selected.length) {
t = 'cwd';
} else if (self.fm.selected.length == 1) {
t = 'file';
} else {
t = 'group';
}
menu(t);
win = $(window);
size = {
height : win.height(),
width : win.width(),
sT : win.scrollTop(),
cW : this.menu.width(),
cH : this.menu.height()
};
this.menu.css({
left : ((e.clientX + size.cW) > size.width ? ( e.clientX - size.cW) : e.clientX),
top : ((e.clientY + size.cH) > size.height && e.clientY > size.cH ? (e.clientY + size.sT - size.cH) : e.clientY + size.sT)
})
.show()
.find('div[name]')
.hover(
function() {
var t = $(this), s = t.children('div'), w;
t.addClass('hover');
if (s.length) {
if (!s.attr('pos')) {
w = t.outerWidth();
s.css($(window).width() - w - t.offset().left > s.width() ? 'left' : 'right', w-5).attr('pos', true);
}
s.show();
}
},
function() { $(this).removeClass('hover').children('div').hide(); }
).click(function(e) {
e.stopPropagation();
var t = $(this);
if (!t.children('div').length) {
self.hideMenu();
self.exec(t.attr('name'), t.attr('argc'));
}
});
function menu(t) {
var i, j, a, html, l, src = self.fm.options.contextmenu[t]||[];
for (i=0; i < src.length; i++) {
if (src[i] == 'delim') {
self.menu.children().length && !self.menu.children(':last').hasClass('delim') && self.menu.append('<div class="delim" />');
} else if (self.fm.ui.includeInCm(src[i], t)) {
a = self.cmd[src[i]].argc();
html = '';
if (a.length) {
html = '<span/><div class="el-finder-contextmenu-sub" style="z-index:'+(parseInt(self.menu.css('z-index'))+1)+'">';
for (var j=0; j < a.length; j++) {
html += '<div name="'+src[i]+'" argc="'+a[j].argc+'" class="'+a[j]['class']+'">'+a[j].text+'</div>';
};
html += '</div>';
}
self.menu.append('<div class="'+src[i]+'" name="'+src[i]+'">'+html+self.cmdName(src[i])+'</div>');
}
};
}
}
this.hideMenu = function() {
this.menu.hide().empty();
}
this.update = function() {
for (var i in this.buttons) {
this.buttons[i].toggleClass('disabled', !this.cmd[i].isAllowed());
}
}
this.init = function(disabled) {
var i, j, n, c=false, zindex = 2, z, t = this.fm.options.toolbar;
/* disable select command if there is no callback for it */
if (!this.fm.options.editorCallback) {
disabled.push('select');
}
/* disable archive command if no archivers enabled */
if (!this.fm.params.archives.length && $.inArray('archive', disabled) == -1) {
disabled.push('archive');
}
for (i in this.commands) {
if ($.inArray(i, disabled) == -1) {
this.commands[i].prototype = this.command.prototype;
this.cmd[i] = new this.commands[i](this.fm);
}
}
for (i=0; i<t.length; i++) {
if (c) {
this.fm.view.tlb.append('<li class="delim" />');
}
c = false;
for (j=0; j<t[i].length; j++) {
n = t[i][j];
if (this.cmd[n]) {
c = true;
this.buttons[n] = $('<li class="'+n+'" title="'+this.cmdName(n)+'" name="'+n+'" />')
.appendTo(this.fm.view.tlb)
.click(function(e) { e.stopPropagation(); })
.bind('click', (function(ui){ return function() {
!$(this).hasClass('disabled') && ui.exec($(this).attr('name'));
} })(this)
).hover(
function() { !$(this).hasClass('disabled') && $(this).addClass('el-finder-tb-hover')},
function() { $(this).removeClass('el-finder-tb-hover')}
);
}
}
}
this.update();
/* set z-index for context menu */
this.menu.css('z-index', this.fm.zIndex);
if (this.fm.options.docked) {
this.dockButton.hover(
function() { $(this).addClass('el-finder-dock-button-hover')},
function() { $(this).removeClass('el-finder-dock-button-hover')}
).click(function() {
self.fm.view.win.attr('undocked') ? self.fm.dock() : self.fm.undock();
$(this).trigger('mouseout');
}).prependTo(this.fm.view.tlb);
}
}
}
/**
* @class elFinder user Interface Command.
* @author dio dio@std42.ru
**/
elFinder.prototype.ui.prototype.command = function(fm) { }
/**
* Return true if command can be applied now
* @return Boolean
**/
elFinder.prototype.ui.prototype.command.prototype.isAllowed = function() {
return true;
}
/**
* Return true if command can be included in contextmenu of required type
* @param String contextmenu type (cwd|group|file)
* @return Boolean
**/
elFinder.prototype.ui.prototype.command.prototype.cm = function(t) {
return false;
}
/**
* Return not empty array if command required submenu in contextmenu
* @return Array
**/
elFinder.prototype.ui.prototype.command.prototype.argc = function(t) {
return [];
}
elFinder.prototype.ui.prototype.commands = {
/**
* @class Go into previous folder
* @param Object elFinder
**/
back : function(fm) {
var self = this;
this.name = 'Back';
this.fm = fm;
this.exec = function() {
if (this.fm.history.length) {
this.fm.ajax({ cmd : 'open', target : this.fm.history.pop() }, function(data) {
self.fm.reload(data);
});
}
}
this.isAllowed = function() {
return this.fm.history.length
}
},
/**
* @class Reload current directory and navigation panel
* @param Object elFinder
**/
reload : function(fm) {
var self = this;
this.name = 'Reload';
this.fm = fm;
this.exec = function() {
this.fm.ajax({ cmd : 'open', target : this.fm.cwd.hash, tree : true }, function(data) {
self.fm.reload(data);
});
}
this.cm = function(t) {
return t == 'cwd';
}
},
/**
* @class Open file/folder
* @param Object elFinder
**/
open : function(fm) {
var self = this;
this.name = 'Open';
this.fm = fm;
/**
* Open file/folder
* @param String file/folder id (only from click on nav tree)
**/
this.exec = function(dir) {
var t = null;
if (dir) {
t = {
hash : $(dir).attr('key'),
mime : 'directory',
read : !$(dir).hasClass('noaccess') && !$(dir).hasClass('dropbox')
}
} else {
t = this.fm.getSelected(0);
}
if (!t.hash) {
return;
}
if (!t.read) {
return this.fm.view.error('Access denied');
}
if (t.type == 'link' && !t.link) {
return this.fm.view.error('Unable to open broken link');
}
if (t.mime == 'directory') {
openDir(t.link||t.hash);
} else {
openFile(t);
}
function openDir(id) {
self.fm.history.push(self.fm.cwd.hash);
self.fm.ajax({ cmd : 'open', target : id }, function(data) {
self.fm.reload(data);
});
}
function openFile(f) {
var s, ws = '';
if (f.dim) {
s = f.dim.split('x');
ws = 'width='+(parseInt(s[0])+20)+',height='+(parseInt(s[1])+20)+',';
}
window.open(f.url||self.fm.options.url+'?cmd=open¤t='+(f.parent||self.fm.cwd.hash)+'&target='+(f.link||f.hash), false, 'top=50,left=50,'+ws+'scrollbars=yes,resizable=yes');
}
}
this.isAllowed = function() {
return this.fm.selected.length == 1 && this.fm.getSelected(0).read;
}
this.cm = function(t) {
return t == 'file';
}
},
/**
* @class. Return file url
* @param Object elFinder
**/
select : function(fm) {
this.name = 'Select file';
this.fm = fm;
if (fm.options.selectMultiple) {
this.exec = function() {
var selected = $(fm.getSelected()).map(function() {
return fm.options.cutURL == 'root' ? this.url.substr(fm.params.url.length) : this.url.replace(new RegExp('^('+fm.options.cutURL+')'), '');
});
fm.options.editorCallback(selected);
if (fm.options.closeOnEditorCallback) {
fm.dock();
fm.close();
}
}
} else {
this.exec = function() {
var f = this.fm.getSelected(0);
if (!f.url) {
return this.fm.view.error('File URL disabled by connector config');
}
this.fm.options.editorCallback(this.fm.options.cutURL == 'root' ? f.url.substr(this.fm.params.url.length) : f.url.replace(new RegExp('^('+this.fm.options.cutURL+')'), ''));
if (this.fm.options.closeOnEditorCallback) {
this.fm.dock();
this.fm.close();
this.fm.destroy();
}
}
}
this.isAllowed = function() {
return ((this.fm.options.selectMultiple && this.fm.selected.length >= 1) || this.fm.selected.length == 1) && !/(symlink\-broken|directory)/.test(this.fm.getSelected(0).mime);
}
this.cm = function(t) {
return t != 'cwd';
// return t == 'file';
}
},
/**
* @class. Open/close quickLook window
* @param Object elFinder
**/
quicklook : function(fm) {
var self = this;
this.name = 'Preview with Quick Look';
this.fm = fm;
this.exec = function() {
self.fm.quickLook.toggle();
}
this.isAllowed = function() {
return this.fm.selected.length == 1;
}
this.cm = function() {
return true;
}
},
/**
* @class Display files/folders info in dialog window
* @param Object elFinder
**/
info : function(fm) {
var self = this;
this.name = 'Get info';
this.fm = fm;
/**
* Open dialog windows for each selected file/folder or for current folder
**/
this.exec = function() {
var f, s, cnt = this.fm.selected.length, w = $(window).width(), h = $(window).height();
this.fm.lockShortcuts(true);
if (!cnt) {
/** nothing selected - show cwd info **/
info(self.fm.cwd);
} else {
/** show info for each selected obj **/
$.each(this.fm.getSelected(), function() {
info(this);
});
}
function info(f) {
var p = ['50%', '50%'], x, y, d,
tb = '<table cellspacing="0"><tr><td>'+self.fm.i18n('Name')+'</td><td>'+f.name+'</td></tr><tr><td>'+self.fm.i18n('Kind')+'</td><td>'+self.fm.view.mime2kind(f.link ? 'symlink' : f.mime)+'</td></tr><tr><td>'+self.fm.i18n('Size')+'</td><td>'+self.fm.view.formatSize(f.size)+'</td></tr><tr><td>'+self.fm.i18n('Modified')+'</td><td>'+self.fm.view.formatDate(f.date)+'</td></tr><tr><td>'+self.fm.i18n('Permissions')+'</td><td>'+self.fm.view.formatPermissions(f.read, f.write, f.rm)+'</td></tr>';
if (f.link) {
tb += '<tr><td>'+self.fm.i18n('Link to')+'</td><td>'+f.linkTo+'</td></tr>';
}
if (f.dim) {
tb += '<tr><td>'+self.fm.i18n('Dimensions')+'</td><td>'+f.dim+' px.</td></tr>';
}
if (f.url) {
tb += '<tr><td>'+self.fm.i18n('URL')+'</td><td><a href="'+f.url+'" target="_blank">'+f.url+'</a></td></tr>';
}
if (cnt>1) {
d = $('.el-finder-dialog-info:last');
if (!d.length) {
x = Math.round(((w-350)/2)-(cnt*10));
y = Math.round(((h-300)/2)-(cnt*10));
p = [x>20?x:20, y>20?y:20];
} else {
x = d.offset().left+10;
y = d.offset().top+10;
p = [x<w-350 ? x : 20, y<h-300 ? y : 20];
}
}
$('<div />').append(tb+'</table>').dialog({
dialogClass : 'el-finder-dialog el-finder-dialog-info',
width : 390,
position : p,
title : self.fm.i18n(f.mime == 'directory' ? 'Folder info' : 'File info'),
close : function() { if (--cnt <= 0) { self.fm.lockShortcuts(); } $(this).dialog('destroy'); },
buttons : { Ok : function() { $(this).dialog('close'); }}
});
}
}
this.cm = function(t) {
return true;
}
},
/**
* @class Rename file/folder
* @param Object elFinder
**/
rename : function(fm) {
var self = this;
this.name = 'Rename';
this.fm = fm;
this.exec = function() {
var s = this.fm.getSelected(), el, c, input, f, n;
if (s.length == 1) {
f = s[0];
el = this.fm.view.cwd.find('[key="'+f.hash+'"]');
c = this.fm.options.view == 'icons' ? el.children('label') : el.find('td').eq(1);
n = c.html();
input = $('<input type="text" />').val(f.name).appendTo(c.empty())
.bind('change blur', rename)
.keydown(function(e) {
e.stopPropagation();
if (e.keyCode == 27) {
restore();
} else if (e.keyCode == 13) {
if (f.name == input.val()) {
restore();
} else {
$(this).trigger('change');
}
}
})
.click(function(e) { e.stopPropagation(); })
.select()
.focus();
this.fm.lockShortcuts(true);
}
function restore() {
c.html(n);
self.fm.lockShortcuts();
}
function rename() {
if (!self.fm.locked) {
var err, name = input.val();
if (f.name == input.val()) {
return restore();
}
if (!self.fm.isValidName(name)) {
err = 'Invalid name';
} else if (self.fm.fileExists(name)) {
err = 'File or folder with the same name already exists';
}
if (err) {
self.fm.view.error(err);
el.addClass('ui-selected');
self.fm.lockShortcuts(true);
return input.select().focus();
}
self.fm.ajax({cmd : 'rename', current : self.fm.cwd.hash, target : f.hash, name : name}, function(data) {
if (data.error) {
restore();
} else {
f.mime == 'directory' && self.fm.removePlace(f.hash) && self.fm.addPlace(data.target);
self.fm.reload(data);
}
}, { force : true });
}
}
}
/**
* Return true if only one file selected and has write perms and current dir has write perms
* @return Boolean
*/
this.isAllowed = function() {
return this.fm.cwd.write && this.fm.getSelected(0).write;
}
this.cm = function(t) {
return t == 'file';
}
},
/**
* @class Copy file/folder to "clipboard"
* @param Object elFinder
**/
copy : function(fm) {
this.name = 'Copy';
this.fm = fm;
this.exec = function() {
this.fm.setBuffer(this.fm.selected);
}
this.isAllowed = function() {
if (this.fm.selected.length) {
var s = this.fm.getSelected(), l = s.length;
while (l--) {
if (s[l].read) {
return true;
}
}
}
return false;
}
this.cm = function(t) {
return t != 'cwd';
}
},
/**
* @class Cut file/folder to "clipboard"
* @param Object elFinder
**/
cut : function(fm) {
this.name = 'Cut';
this.fm = fm;
this.exec = function() {
this.fm.setBuffer(this.fm.selected, 1);
}
this.isAllowed = function() {
if (this.fm.selected.length) {
var s = this.fm.getSelected(), l = s.length;
while (l--) {
if (s[l].read && s[l].rm) {
return true;
}
}
}
return false;
}
this.cm = function(t) {
return t != 'cwd';
}
},
/**
* @class Paste file/folder from "clipboard"
* @param Object elFinder
**/
paste : function(fm) {
var self = this;
this.name = 'Paste';
this.fm = fm;
this.exec = function() {
var i, d, f, r, msg = '';
if (!this.fm.buffer.dst) {
this.fm.buffer.dst = this.fm.cwd.hash;
}
d = this.fm.view.tree.find('[key="'+this.fm.buffer.dst+'"]');
if (!d.length || d.hasClass('noaccess') || d.hasClass('readonly')) {
return this.fm.view.error('Access denied');
}
if (this.fm.buffer.src == this.fm.buffer.dst) {
return this.fm.view.error('Unable to copy into itself');
}
var o = {
cmd : 'paste',
current : this.fm.cwd.hash,
src : this.fm.buffer.src,
dst : this.fm.buffer.dst,
cut : this.fm.buffer.cut
};
if (this.fm.jquery>132) {
o.targets = this.fm.buffer.files;
} else {
o['targets[]'] = this.fm.buffer.files;
}
this.fm.ajax(o, function(data) {
data.cdc && self.fm.reload(data);
}, {force : true});
}
this.isAllowed = function() {
return this.fm.buffer.files;
}
this.cm = function(t) {
return t == 'cwd';
}
},
/**
* @class Remove files/folders
* @param Object elFinder
**/
rm : function(fm) {
var self = this;
this.name = 'Remove';
this.fm = fm;
this.exec = function() {
var i, ids = [], s =this.fm.getSelected();
for (var i=0; i < s.length; i++) {
if (!s[i].rm) {
return this.fm.view.error(s[i].name+': '+this.fm.i18n('Access denied'));
}
ids.push(s[i].hash);
};
if (ids.length) {
this.fm.lockShortcuts(true);
$('<div><div class="ui-state-error ui-corner-all"><span class="ui-icon ui-icon-alert"/><strong>'+this.fm.i18n('Are you sure you want to remove files?<br /> This cannot be undone!')+'</strong></div></div>')
.dialog({
title : this.fm.i18n('Confirmation required'),
dialogClass : 'el-finder-dialog',
width : 350,
close : function() { self.fm.lockShortcuts(); },
buttons : {
Cancel : function() { $(this).dialog('close'); },
Ok : function() {
$(this).dialog('close');
var o = { cmd : 'rm', current : self.fm.cwd.hash };
if (self.fm.jquery > 132) {
o.targets = ids;
} else {
o['targets[]'] = ids;
}
self.fm.ajax(o, function(data) { data.tree && self.fm.reload(data); }, {force : true});
}
}
});
}
}
this.isAllowed = function(f) {
if (this.fm.selected.length) {
var s = this.fm.getSelected(), l = s.length;
while (l--) {
if (s[l].rm) {
return true;
}
}
}
return false;
}
this.cm = function(t) {
return t != 'cwd';
}
},
/**
* @class Create new folder
* @param Object elFinder
**/
mkdir : function(fm) {
var self = this;
this.name = 'New folder';
this.fm = fm;
this.exec = function() {
self.fm.unselectAll();
var n = this.fm.uniqueName('untitled folder');
input = $('<input type="text"/>').val(n);
prev = this.fm.view.cwd.find('.directory:last');
f = {name : n, hash : '', mime :'directory', read : true, write : true, date : '', size : 0},
el = this.fm.options.view == 'list'
? $(this.fm.view.renderRow(f)).children('td').eq(1).empty().append(input).end().end()
: $(this.fm.view.renderIcon(f)).children('label').empty().append(input).end()
el.addClass('directory ui-selected');
if (prev.length) {
el.insertAfter(prev);
} else if (this.fm.options.view == 'list') {
el.insertAfter(this.fm.view.cwd.find('tr').eq(0))
} else {
el.prependTo(this.fm.view.cwd)
}
self.fm.checkSelectedPos();
input.select().focus()
.click(function(e) { e.stopPropagation(); })
.bind('change blur', mkdir)
.keydown(function(e) {
e.stopPropagation();
if (e.keyCode == 27) {
el.remove();
self.fm.lockShortcuts();
} else if (e.keyCode == 13) {
mkdir();
}
});
self.fm.lockShortcuts(true);
function mkdir() {
if (!self.fm.locked) {
var err, name = input.val();
if (!self.fm.isValidName(name)) {
err = 'Invalid name';
} else if (self.fm.fileExists(name)) {
err = 'File or folder with the same name already exists';
}
if (err) {
self.fm.view.error(err);
self.fm.lockShortcuts(true);
el.addClass('ui-selected');
return input.select().focus();
}
self.fm.ajax({cmd : 'mkdir', current : self.fm.cwd.hash, name : name}, function(data) {
if (data.error) {
el.addClass('ui-selected');
return input.select().focus();
}
self.fm.reload(data);
}, {force : true});
}
}
}
this.isAllowed = function() {
return this.fm.cwd.write;
}
this.cm = function(t) {
return t == 'cwd';
}
},
/**
* @class Create new text file
* @param Object elFinder
**/
mkfile : function(fm) {
var self = this;
this.name = 'New text file';
this.fm = fm;
this.exec = function() {
self.fm.unselectAll();
var n = this.fm.uniqueName('untitled file', '.txt'),
input = $('<input type="text"/>').val(n),
f = {name : n, hash : '', mime :'text/plain', read : true, write : true, date : '', size : 0},
el = this.fm.options.view == 'list'
? $(this.fm.view.renderRow(f)).children('td').eq(1).empty().append(input).end().end()
: $(this.fm.view.renderIcon(f)).children('label').empty().append(input).end();
el.addClass('text ui-selected').appendTo(this.fm.options.view == 'list' ? self.fm.view.cwd.children('table') : self.fm.view.cwd);
input.select().focus()
.bind('change blur', mkfile)
.click(function(e) { e.stopPropagation(); })
.keydown(function(e) {
e.stopPropagation();
if (e.keyCode == 27) {
el.remove();
self.fm.lockShortcuts();
} else if (e.keyCode == 13) {
mkfile();
}
});
self.fm.lockShortcuts(true);
function mkfile() {
if (!self.fm.locked) {
var err, name = input.val();
if (!self.fm.isValidName(name)) {
err = 'Invalid name';
} else if (self.fm.fileExists(name)) {
err = 'File or folder with the same name already exists';
}
if (err) {
self.fm.view.error(err);
self.fm.lockShortcuts(true);
el.addClass('ui-selected');
return input.select().focus();
}
self.fm.ajax({cmd : 'mkfile', current : self.fm.cwd.hash, name : name}, function(data) {
if (data.error) {
el.addClass('ui-selected');
return input.select().focus();
}
self.fm.reload(data);
}, {force : true });
}
}
}
this.isAllowed = function(f) {
return this.fm.cwd.write;
}
this.cm = function(t) {
return t == 'cwd';
}
},
/**
* @class Upload files
* @param Object elFinder
**/
upload : function(fm) {
var self = this;
this.name = 'Upload files';
this.fm = fm;
this.exec = function() {
var id = 'el-finder-io-'+(new Date().getTime()),
e = $('<div class="ui-state-error ui-corner-all"><span class="ui-icon ui-icon-alert"/><div/></div>'),
m = this.fm.params.uplMaxSize ? '<p>'+this.fm.i18n('Maximum allowed files size')+': '+this.fm.params.uplMaxSize+'</p>' : '',
b = $('<p class="el-finder-add-field"><span class="ui-state-default ui-corner-all"><em class="ui-icon ui-icon-circle-plus"/></span>'+this.fm.i18n('Add field')+'</p>')
.click(function() { $(this).before('<p><input type="file" name="upload[]"/></p>'); }),
f = '<form method="post" enctype="multipart/form-data" action="'+self.fm.options.url+'" target="'+id+'"><input type="hidden" name="cmd" value="upload" /><input type="hidden" name="current" value="'+self.fm.cwd.hash+'" />',
d = $('<div/>'),
i = 3;
while (i--) { f += '<p><input type="file" name="upload[]"/></p>'; }
// Rails csrf meta tag (for XSS protection), see #256
var rails_csrf_token = $('meta[name=csrf-token]').attr('content');
var rails_csrf_param = $('meta[name=csrf-param]').attr('content');
if (rails_csrf_param != null && rails_csrf_token != null) {
f += '<input name="'+rails_csrf_param+'" value="'+rails_csrf_token+'" type="hidden" />';
}
f = $(f+'</form>');
d.append(f.append(e.hide()).prepend(m).append(b)).dialog({
dialogClass : 'el-finder-dialog',
title : self.fm.i18n('Upload files'),
modal : true,
resizable : false,
close : function() { self.fm.lockShortcuts(); },
buttons : {
Cancel : function() { $(this).dialog('close'); },
Ok : function() {
if (!$(':file[value]', f).length) {
return error(self.fm.i18n('Select at least one file to upload'));
}
setTimeout(function() {
self.fm.lock();
if ($.browser.safari) {
$.ajax({
url : self.fm.options.url,
data : {cmd : 'ping'},
error : submit,
success : submit
});
} else {
submit();
}
});
$(this).dialog('close');
}
}
});
self.fm.lockShortcuts(true);
function error(err) {
e.show().find('div').empty().text(err);
}
function submit() {
var $io = $('<iframe name="'+id+'" name="'+id+'" src="about:blank"/>'),
io = $io[0],
cnt = 50,
doc, html, data;
$io.css({ position: 'absolute', top: '-1000px', left: '-1000px' })
.appendTo('body').bind('load', function() {
$io.unbind('load');
result();
});
self.fm.lock(true);
f.submit();
function result() {
try {
doc = io.contentWindow ? io.contentWindow.document : io.contentDocument ? io.contentDocument : io.document;
/* opera */
if (doc.body == null || doc.body.innerHTML == '') {
if (--cnt) {
return setTimeout(result, 100);
} else {
complite();
return self.fm.view.error('Unable to access iframe DOM after 50 tries');
}
}
/* get server response */
html = $(doc.body).html();
if (self.fm.jquery>=141) {
data = $.parseJSON(html);
} else if ( /^[\],:{}\s]*$/.test(html.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, "@")
.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, "]")
.replace(/(?:^|:|,)(?:\s*\[)+/g, "")) ) {
/* get from jQuery 1.4 */
data = window.JSON && window.JSON.parse ? window.JSON.parse(html) : (new Function("return " + html))();
} else {
data = { error : 'Unable to parse server response' };
}
} catch(e) {
data = { error : 'Unable to parse server response' };
}
complite();
data.error && self.fm.view.error(data.error, data.errorData);
data.cwd && self.fm.reload(data);
data.tmb && self.fm.tmb();
}
function complite() {
self.fm.lock();
$io.remove();
}
}
}
this.isAllowed = function() {
return this.fm.cwd.write;
}
this.cm = function(t) {
return t == 'cwd';
}
},
/**
* @class Make file/folder copy
* @param Object elFinder
**/
duplicate : function(fm) {
var self = this;
this.name = 'Duplicate';
this.fm = fm;
this.exec = function() {
this.fm.ajax({
cmd : 'duplicate',
current : this.fm.cwd.hash,
target : this.fm.selected[0]
},
function(data) {
self.fm.reload(data);
});
}
this.isAllowed = function() {
return this.fm.cwd.write && this.fm.selected.length == 1 && this.fm.getSelected()[0].read;
}
this.cm = function(t) {
return t == 'file';
}
},
/**
* @class Edit text file
* @param Object elFinder
**/
edit : function(fm) {
var self = this;
this.name = 'Edit text file';
this.fm = fm;
this.exec = function() {
var f = this.fm.getSelected(0);
this.fm.lockShortcuts(true);
this.fm.ajax({
cmd : 'read',
current : this.fm.cwd.hash,
target : f.hash
}, function(data) {
self.fm.lockShortcuts(true);
var ta = $('<textarea/>').val(data.content||'').keydown(function(e) {
e.stopPropagation();
if (e.keyCode == 9) {
e.preventDefault();
if ($.browser.msie) {
var r = document.selection.createRange();
r.text = "\t"+r.text;
this.focus();
} else {
var before = this.value.substr(0, this.selectionStart),
after = this.value.substr(this.selectionEnd);
this.value = before+"\t"+after;
this.setSelectionRange(before.length+1, before.length+1);
}
}
});
$('<div/>').append(ta)
.dialog({
dialogClass : 'el-finder-dialog',
title : self.fm.i18n(self.name),
modal : true,
width : 500,
close : function() { self.fm.lockShortcuts(); },
buttons : {
Cancel : function() { $(this).dialog('close'); },
Ok : function() {
var c = ta.val();
$(this).dialog('close');
self.fm.ajax({
cmd : 'edit',
current : self.fm.cwd.hash,
target : f.hash,
content : c
}, function(data) {
if (data.target) {
self.fm.cdc[data.target.hash] = data.target;
self.fm.view.updateFile(data.target);
self.fm.selectById(data.target.hash);
}
}, {type : 'POST'});
}
}
});
});
}
this.isAllowed = function() {
if (self.fm.selected.length == 1) {
var f = this.fm.getSelected()[0];
return f.write && f.read && (f.mime.indexOf('text') == 0 || f.mime == 'application/x-empty' || f.mime == 'application/xml');
}
}
this.cm = function(t) {
return t == 'file';
}
},
/**
* @class Create archive
* @param Object elFinder
**/
archive : function(fm) {
var self = this;
this.name = 'Create archive';
this.fm = fm;
this.exec = function(t) {
var o = {
cmd : 'archive',
current : self.fm.cwd.hash,
type : $.inArray(t, this.fm.params.archives) != -1 ? t : this.fm.params.archives[0],
name : self.fm.i18n('Archive')
};
if (this.fm.jquery>132) {
o.targets = self.fm.selected;
} else {
o['targets[]'] = self.fm.selected;
}
this.fm.ajax(o, function(data) { self.fm.reload(data); });
}
this.isAllowed = function() {
if (this.fm.cwd.write && this.fm.selected.length) {
var s = this.fm.getSelected(), l = s.length;
while (l--) {
if (s[l].read) {
return true;
}
}
}
return false;
}
this.cm = function(t) {
return t != 'cwd';
}
this.argc = function() {
var i, v = [];
for (i=0; i < self.fm.params.archives.length; i++) {
v.push({
'class' : 'archive',
'argc' : self.fm.params.archives[i],
'text' : self.fm.view.mime2kind(self.fm.params.archives[i])
});
};
return v;
}
},
/**
* @class Extract files from archive
* @param Object elFinder
**/
extract : function(fm) {
var self = this;
this.name = 'Uncompress archive';
this.fm = fm;
this.exec = function() {
this.fm.ajax({
cmd : 'extract',
current : this.fm.cwd.hash,
target : this.fm.getSelected(0).hash
}, function(data) {
self.fm.reload(data);
})
}
this.isAllowed = function() {
var extract = this.fm.params.extract,
cnt = extract && extract.length;
return this.fm.cwd.write && this.fm.selected.length == 1 && this.fm.getSelected(0).read && cnt && $.inArray(this.fm.getSelected(0).mime, extract) != -1;
}
this.cm = function(t) {
return t == 'file';
}
},
/**
* @class Resize image
* @param Object elFinder
**/
resize : function(fm) {
var self = this;
this.name = 'Resize image';
this.fm = fm;
this.exec = function() {
var s = this.fm.getSelected();
if (s[0] && s[0].write && s[0].dim) {
var size = s[0].dim.split('x'),
w = parseInt(size[0]),
h = parseInt(size[1]), rel = w/h
iw = $('<input type="text" size="9" value="'+w+'" name="width"/>'),
ih = $('<input type="text" size="9" value="'+h+'" name="height"/>'),
f = $('<form/>').append(iw).append(' x ').append(ih).append(' px');
iw.add(ih).bind('change', calc);
self.fm.lockShortcuts(true);
var d = $('<div/>').append($('<div/>').text(self.fm.i18n('Dimensions')+':')).append(f).dialog({
title : self.fm.i18n('Resize image'),
dialogClass : 'el-finder-dialog',
width : 230,
modal : true,
close : function() { self.fm.lockShortcuts(); },
buttons : {
Cancel : function() { $(this).dialog('close'); },
Ok : function() {
var _w = parseInt(iw.val()) || 0,
_h = parseInt(ih.val()) || 0;
if (_w>0 && _w != w && _h>0 && _h != h) {
self.fm.ajax({
cmd : 'resize',
current : self.fm.cwd.hash,
target : s[0].hash,
width : _w,
height : _h
},
function (data) {
self.fm.reload(data);
});
}
$(this).dialog('close');
}
}
});
}
function calc() {
var _w = parseInt(iw.val()) || 0,
_h = parseInt(ih.val()) || 0;
if (_w<=0 || _h<=0) {
_w = w;
_h = h;
} else if (this == iw.get(0)) {
_h = parseInt(_w/rel);
} else {
_w = parseInt(_h*rel);
}
iw.val(_w);
ih.val(_h);
}
}
this.isAllowed = function() {
return this.fm.selected.length == 1 && this.fm.cdc[this.fm.selected[0]].write && this.fm.cdc[this.fm.selected[0]].read && this.fm.cdc[this.fm.selected[0]].resize;
}
this.cm = function(t) {
return t == 'file';
}
},
/**
* @class Switch elFinder into icon view
* @param Object elFinder
**/
icons : function(fm) {
this.name = 'View as icons';
this.fm = fm;
this.exec = function() {
this.fm.view.win.addClass('el-finder-disabled');
this.fm.setView('icons');
this.fm.updateCwd();
this.fm.view.win.removeClass('el-finder-disabled');
$('div.image', this.fm.view.cwd).length && this.fm.tmb();
}
this.isAllowed = function() {
return this.fm.options.view != 'icons';
}
this.cm = function(t) {
return t == 'cwd';
}
},
/**
* @class Switch elFinder into list view
* @param Object elFinder
**/
list : function(fm) {
this.name = 'View as list';
this.fm = fm;
this.exec = function() {
this.fm.view.win.addClass('el-finder-disabled');
this.fm.setView('list');
this.fm.updateCwd();
this.fm.view.win.removeClass('el-finder-disabled');
}
this.isAllowed = function() {
return this.fm.options.view != 'list';
}
this.cm = function(t) {
return t == 'cwd';
}
},
help : function(fm) {
this.name = 'Help';
this.fm = fm;
this.exec = function() {
var h, ht = this.fm.i18n('helpText'), a, s, tabs;
h = '<div class="el-finder-logo"/><strong>'+this.fm.i18n('elFinder: Web file manager')+'</strong><br/>'+this.fm.i18n('Version')+': '+this.fm.version+'<br/>'
+'jQuery/jQueryUI: '+$().jquery+'/'+$.ui.version+'<br clear="all"/>'
+'<p><strong><a href="http://elrte.org/'+this.fm.options.lang+'/elfinder" target="_blank">'+this.fm.i18n('Donate to support project development')+'</a></strong></p>'
+ '<p><a href="http://elrte.org/redmine/projects/elfinder/wiki" target="_blank">'+this.fm.i18n('elFinder documentation')+'</a></p>';
h += '<p>'+(ht != 'helpText' ? ht : 'elFinder works similar to file manager on your computer. <br /> To make actions on files/folders use icons on top panel. If icon action it is not clear for you, hold mouse cursor over it to see the hint. <br /> Manipulations with existing files/folders can be done through the context menu (mouse right-click).<br/> To copy/delete a group of files/folders, select them using Shift/Alt(Command) + mouse left-click.')+'</p>';
h += '<p>'
+ '<strong>'+this.fm.i18n('elFinder support following shortcuts')+':</strong><ul>'
+ '<li><kbd>Ctrl+A</kbd> - '+this.fm.i18n('Select all files')+'</li>'
+ '<li><kbd>Ctrl+C/Ctrl+X/Ctrl+V</kbd> - '+this.fm.i18n('Copy/Cut/Paste files')+'</li>'
+ '<li><kbd>Enter</kbd> - '+this.fm.i18n('Open selected file/folder')+'</li>'
+ '<li><kbd>Space</kbd> - '+this.fm.i18n('Open/close QuickLook window')+'</li>'
+ '<li><kbd>Delete/Cmd+Backspace</kbd> - '+this.fm.i18n('Remove selected files')+'</li>'
+ '<li><kbd>Ctrl+I</kbd> - '+this.fm.i18n('Selected files or current directory info')+'</li>'
+ '<li><kbd>Ctrl+N</kbd> - '+this.fm.i18n('Create new directory')+'</li>'
+ '<li><kbd>Ctrl+U</kbd> - '+this.fm.i18n('Open upload files form')+'</li>'
+ '<li><kbd>Left arrow</kbd> - '+this.fm.i18n('Select previous file')+'</li>'
+ '<li><kbd>Right arrow </kbd> - '+this.fm.i18n('Select next file')+'</li>'
+ '<li><kbd>Ctrl+Right arrow</kbd> - '+this.fm.i18n('Open selected file/folder')+'</li>'
+ '<li><kbd>Ctrl+Left arrow</kbd> - '+this.fm.i18n('Return into previous folder')+'</li>'
+ '<li><kbd>Shift+arrows</kbd> - '+this.fm.i18n('Increase/decrease files selection')+'</li></ul>'
+ '</p><p>'
+ this.fm.i18n('Contacts us if you need help integrating elFinder in you products')+': dev@std42.ru</p>';
a = '<div class="el-finder-help-std"/>'
+'<p>'+this.fm.i18n('Javascripts/PHP programming: Dmitry (dio) Levashov, dio@std42.ru')+'</p>'
+'<p>'+this.fm.i18n('Python programming, techsupport: Troex Nevelin, troex@fury.scancode.ru')+'</p>'
+'<p>'+this.fm.i18n('Design: Valentin Razumnih')+'</p>'
+'<p>'+this.fm.i18n('Chezh localization')+': Roman Matěna, info@romanmatena.cz</p>'
+'<p>'+this.fm.i18n('Chinese (traditional) localization')+': Tad, tad0616@gmail.com</p>'
+'<p>'+this.fm.i18n('Dutch localization')+': Kurt Aerts, <a href="http://ilabsolutions.net/" target="_blank">http://ilabsolutions.net</a></p>'
+'<p>'+this.fm.i18n('Greek localization')+': Panagiotis Skarvelis</p>'
+'<p>'+this.fm.i18n('Hungarian localization')+': Viktor Tamas, tamas.viktor@totalstudio.hu</p>'
+'<p>'+this.fm.i18n('Italian localization')+': Ugo Punzolo, sadraczerouno@gmail.com</p>'
+'<p>'+this.fm.i18n('Latvian localization')+': Uldis Plotiņš, uldis.plotins@gmail.com</p>'
+'<p>'+this.fm.i18n('Poland localization')+': Darek Wapiński, darek@wapinski.us</p>'
+'<p>'+this.fm.i18n('Spanish localization')+': Alex (xand) Vavilin, xand@xand.es, <a href="http://xand.es" target="_blank">http://xand.es</a></p>'
+'<p>'+this.fm.i18n('Icons')+': <a href="http://pixelmixer.ru/" target="_blank">pixelmixer</a>, <a href="http://www.famfamfam.com/lab/icons/silk/" target="_blank">Famfam silk icons</a>, <a href="http://www.fatcow.com/free-icons/" target="_blank">Fatcow icons</a>'+'</p>'
+'<p>'+this.fm.i18n('Copyright: <a href="http://www.std42.ru" target="_blank">Studio 42 LTD</a>')+'</p>'
+'<p>'+this.fm.i18n('License: BSD License')+'</p>'
+'<p>'+this.fm.i18n('Web site: <a href="http://elrte.org/elfinder/" target="_blank">elrte.org/elfinder</a>')+'</p>';
s = '<div class="el-finder-logo"/><strong><a href="http://www.eldorado-cms.ru" target="_blank">ELDORADO.CMS</a></strong><br/>'
+this.fm.i18n('Simple and usefull Content Management System')
+'<hr/>'
+ this.fm.i18n('Support project development and we will place here info about you');
tabs = '<ul><li><a href="#el-finder-help-h">'+this.fm.i18n('Help')+'</a></li><li><a href="#el-finder-help-a">'+this.fm.i18n('Authors')+'</a><li><a href="#el-finder-help-sp">'+this.fm.i18n('Sponsors')+'</a></li></ul>'
+'<div id="el-finder-help-h"><p>'+h+'</p></div>'
+'<div id="el-finder-help-a"><p>'+a+'</p></div>'
+'<div id="el-finder-help-sp"><p>'+s+'</p></div>';
var d = $('<div/>').html(tabs).dialog({
width : 617,
title : this.fm.i18n('Help'),
dialogClass : 'el-finder-dialog',
modal : true,
close : function() { d.tabs('destroy').dialog('destroy').remove() },
buttons : {
Ok : function() { $(this).dialog('close'); }
}
}).tabs()
}
this.cm = function(t) {
return t == 'cwd';
}
}
}
})(jQuery);
/**
* @class Create quick look window (similar to MacOS X Quick Look)
* @author dio dio@std42.ru
**/
(function($) {
elFinder.prototype.quickLook = function(fm, el) {
var self = this;
this.fm = fm;
this._hash = '';
this.title = $('<strong/>');
this.ico = $('<p/>');
this.info = $('<label/>');
this.media = $('<div class="el-finder-ql-media"/>').hide()
this.name = $('<span class="el-finder-ql-name"/>')
this.kind = $('<span class="el-finder-ql-kind"/>')
this.size = $('<span class="el-finder-ql-size"/>')
this.date = $('<span class="el-finder-ql-date"/>')
this.url = $('<a href="#"/>').hide().click(function(e) {
e.preventDefault();
window.open($(this).attr('href'));
self.hide();
});
this.add = $('<div/>')
this.content = $('<div class="el-finder-ql-content"/>')
this.win = $('<div class="el-finder-ql"/>').hide()
.append($('<div class="el-finder-ql-drag-handle"/>').append($('<span class="ui-icon ui-icon-circle-close"/>').click(function() { self.hide(); })).append(this.title))
.append(this.ico)
.append(this.media)
.append(this.content.append(this.name).append(this.kind).append(this.size).append(this.date).append(this.url).append(this.add))
// .appendTo(this.fm.view.win)
.appendTo('body')
.draggable({handle : '.el-finder-ql-drag-handle'})
.resizable({
minWidth : 420,
minHeight : 150,
resize : function() {
if (self.media.children().length) {
var t = self.media.children(':first');
switch (t[0].nodeName) {
case 'IMG':
var w = t.width(),
h = t.height(),
_w = self.win.width(),
_h = self.win.css('height') == 'auto' ? 350 : self.win.height()-self.content.height()-self.th,
r = w>_w || h>_h
? Math.min(Math.min(_w, w)/w, Math.min(_h, h)/h)
: Math.min(Math.max(_w, w)/w, Math.max(_h, h)/h);
t.css({
width : Math.round(t.width()*r),
height : Math.round(t.height()*r)
})
break;
case 'IFRAME':
case 'EMBED':
t.css('height', self.win.height()-self.content.height()-self.th);
break;
case 'OBJECT':
t.children('embed').css('height', self.win.height()-self.content.height()-self.th);
}
}
}
});
this.th = parseInt(this.win.children(':first').css('height'))||18;
/* All browsers do it, but some is shy to says about it. baka da ne! */
this.mimes = {
'image/jpeg' : 'jpg',
'image/gif' : 'gif',
'image/png' : 'png'
};
for (var i=0; i<navigator.mimeTypes.length; i++) {
var t = navigator.mimeTypes[i].type;
if (t && t != '*') {
this.mimes[t] = navigator.mimeTypes[i].suffixes;
}
}
if (($.browser.safari && navigator.platform.indexOf('Mac') != -1) || $.browser.msie) {
/* not booletproof, but better then nothing */
this.mimes['application/pdf'] = 'pdf';
} else {
for (var n=0; n < navigator.plugins.length; n++) {
for (var m=0; m < navigator.plugins[n].length; m++) {
var e = navigator.plugins[n][m].description.toLowerCase();
if (e.substring(0, e.indexOf(" ")) == 'pdf') {
this.mimes['application/pdf'] = 'pdf';
break;
}
}
}
}
if (this.mimes['image/x-bmp']) {
this.mimes['image/x-ms-bmp'] = 'bmp';
}
if ($.browser.msie && !this.mimes['application/x-shockwave-flash']) {
this.mimes['application/x-shockwave-flash'] = 'swf';
}
// self.fm.log(this.mimes)
/**
* Open quickLook window
**/
this.show = function() {
if (this.win.is(':hidden') && self.fm.selected.length == 1) {
update();
var id = self.fm.selected[0],
el = self.fm.view.cwd.find('[key="'+id+'"]'),
o = el.offset();
self.fm.lockShortcuts(true);
this.win.css({
width : el.width()-20,
height : el.height(),
left : o.left,
top : o.top,
opacity : 0
}).show().animate({
width : 420,
height : 150,
opacity : 1,
top : Math.round($(window).height()/5),
left : $(window).width()/2-210
}, 450, function() {
self.win.css({height: 'auto'});
self.fm.lockShortcuts();
});
}
}
/**
* Close quickLook window
**/
this.hide = function() {
if (this.win.is(':visible')) {
var o, el = self.fm.view.cwd.find('[key="'+this._hash+'"]');
if (el) {
o = el.offset();
this.media.hide(200)//.empty()
this.win.animate({
width : el.width()-20,
height : el.height(),
left : o.left,
top : o.top,
opacity : 0
}, 350, function() {
self.fm.lockShortcuts();
reset();
self.win.hide().css('height', 'auto');
});
} else {
this.win.fadeOut(200);
reset();
self.fm.lockShortcuts();
}
}
}
/**
* Open/close quickLook window
**/
this.toggle = function() {
if (this.win.is(':visible')) {
this.hide();
} else {
this.show();
}
}
/**
* Update quickLook window content if only one file selected,
* otherwise close window
**/
this.update = function() {
if (this.fm.selected.length != 1) {
this.hide();
} else if (this.win.is(':visible') && this.fm.selected[0] != this._hash) {
update();
}
}
/**
* Return height of this.media block
* @return Number
**/
this.mediaHeight = function() {
return this.win.is(':animated') || this.win.css('height') == 'auto' ? 315 : this.win.height()-this.content.height()-this.th;
}
/**
* Clean quickLook window DOM elements
**/
function reset() {
self.media.hide().empty();
self.win.attr('class', 'el-finder-ql').css('z-index', self.fm.zIndex);
self.title.empty();
self.ico.attr('style', '').show();
self.add.hide().empty();
self._hash = '';
}
/**
* Update quickLook window content
**/
function update() {
var f = self.fm.getSelected(0);
reset();
self._hash = f.hash;
self.title.text(f.name);
self.win.addClass(self.fm.view.mime2class(f.mime));
self.name.text(f.name);
self.kind.text(self.fm.view.mime2kind(f.link ? 'symlink' : f.mime));
self.size.text(self.fm.view.formatSize(f.size));
self.date.text(self.fm.i18n('Modified')+': '+self.fm.view.formatDate(f.date));
f.dim && self.add.append('<span>'+f.dim+' px</span>').show();
f.tmb && self.ico.css('background', 'url("'+f.tmb+'") 0 0 no-repeat');
if (f.url) {
self.url.text(f.url).attr('href', f.url).show();
for (var i in self.plugins) {
if (self.plugins[i].test && self.plugins[i].test(f.mime, self.mimes, f.name)) {
self.plugins[i].show(self, f);
return;
}
}
} else {
self.url.hide();
}
self.win.css({
width : '420px',
height : 'auto'
});
}
}
elFinder.prototype.quickLook.prototype.plugins = {
image : new function() {
this.test = function(mime, mimes) {
return mime.match(/^image\//);
}
this.show = function(ql, f) {
var url, t;
if (ql.mimes[f.mime] && f.hash == ql._hash) {
$('<img/>').hide().appendTo(ql.media.show()).attr('src', f.url+($.browser.msie || $.browser.opera ? '?'+Math.random() : '')).load(function() {
t = $(this).unbind('load');
if (f.hash == ql._hash) {
ql.win.is(':animated') ? setTimeout(function() { preview(t); }, 330) : preview(t);
}
});
}
function preview(img) {
var w = img.width(),
h = img.height(),
a = ql.win.is(':animated'),
_w = a ? 420 : ql.win.width(),
_h = a || ql.win.css('height') == 'auto' ? 315 : ql.win.height()-ql.content.height()-ql.th,
r = w>_w || h>_h
? Math.min(Math.min(_w, w)/w, Math.min(_h, h)/h)
: Math.min(Math.max(_w, w)/w, Math.max(_h, h)/h);
ql.fm.lockShortcuts(true);
ql.ico.hide();
img.css({
width : ql.ico.width(),
height : ql.ico.height()
}).show().animate({
width : Math.round(r*w),
height : Math.round(r*h)
}, 450, function() {
ql.fm.lockShortcuts();
});
}
}
},
text : new function() {
this.test = function(mime, mimes) {
return (mime.indexOf('text') == 0 && mime.indexOf('rtf') == -1) || mime.match(/application\/(xml|javascript|json)/);
}
this.show = function(ql, f) {
if (f.hash == ql._hash) {
ql.ico.hide();
ql.media.append('<iframe src="'+f.url+'" style="height:'+ql.mediaHeight()+'px" />').show();
}
}
},
swf : new function() {
this.test = function(mime, mimes) {
return mime == 'application/x-shockwave-flash' && mimes[mime];
}
this.show = function(ql, f) {
if (f.hash == ql._hash) {
ql.ico.hide();
// ql.media.append('<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0"><param name="quality" value="high" /><param name="movie" value="'+url+'" /><embed pluginspage="http://www.macromedia.com/go/getflashplayer" quality="high" src="'+url+'" type="application/x-shockwave-flash" style="width:100%;height:'+ql.mediaHeight()+'px"></embed></object>')
// .slideDown(400);
var e = ql.media.append('<embed pluginspage="http://www.macromedia.com/go/getflashplayer" quality="high" src="'+f.url+'" style="width:100%;height:'+ql.mediaHeight()+'px" type="application/x-shockwave-flash" />');
if (ql.win.is(':animated')) {
e.slideDown(450)
} else {
e.show()
}
}
}
},
audio : new function() {
this.test = function(mime, mimes) {
return mime.indexOf('audio') == 0 && mimes[mime];
}
this.show = function(ql, f) {
if (f.hash == ql._hash) {
ql.ico.hide();
var h = ql.win.is(':animated') || ql.win.css('height') == 'auto' ? 100 : ql.win.height()-ql.content.height()-ql.th;
ql.media.append('<embed src="'+f.url+'" style="width:100%;height:'+h+'px" />').show();
}
}
},
video : new function() {
this.test = function(mime, mimes) {
return mime.indexOf('video') == 0 && mimes[mime];
}
this.show = function(ql, f) {
if (f.hash == ql._hash) {
ql.ico.hide();
ql.media.append('<embed src="'+f.url+'" style="width:100%;height:'+ql.mediaHeight()+'px" />').show();
}
}
},
pdf : new function() {
this.test = function(mime, mimes) {
return mime == 'application/pdf' && mimes[mime];
}
this.show = function(ql, f) {
if (f.hash == ql._hash) {
ql.ico.hide();
ql.media.append('<embed src="'+f.url+'" style="width:100%;height:'+ql.mediaHeight()+'px" />').show();
}
}
}
}
})(jQuery);
/**
* @class Bind/update events
* @author dio dio@std42.ru
**/
(function($) {
elFinder.prototype.eventsManager = function(fm, el) {
var self = this;
this.lock = false;
this.fm = fm;
this.ui = fm.ui;
this.tree = fm.view.tree
this.cwd = fm.view.cwd;
this.pointer = '';
/**
* Initial events binding
*
**/
this.init = function() {
var self = this, ignore = false;
self.lock = false;
this.cwd
.bind('click', function(e) {
var t = $(e.target);
if (t.hasClass('ui-selected')) {
self.fm.unselectAll();
} else {
if (!t.attr('key')) {
t = t.parent('[key]');
}
if (e.ctrlKey || e.metaKey) {
self.fm.toggleSelect(t);
} else {
self.fm.select(t, true);
}
}
})
.bind(window.opera?'click':'contextmenu', function(e) {
if (window.opera && !e.ctrlKey) {
return;
}
e.preventDefault();
e.stopPropagation();
var t = $(e.target);
if ($.browser.mozilla) {
ignore = true;
}
if (t.hasClass('el-finder-cwd')) {
self.fm.unselectAll();
} else {
self.fm.select(t.attr('key') ? t : t.parent('[key]'));
}
self.fm.quickLook.hide();
self.fm.ui.showMenu(e);
})
.selectable({
filter : '[key]',
delay : 300,
stop : function() { self.fm.updateSelect(); self.fm.log('mouseup') }
});
$(document).bind('click', function(e) {
!ignore && self.fm.ui.hideMenu();
ignore = false
$('input', self.cwd).trigger('change');
if (!$(e.target).is('input,textarea,select')) {
$('input,textarea').blur();
}
});
$('input,textarea').live('focus', function(e) {
self.lock = true;
}).live('blur', function(e) {
self.lock = false;
});
/* open parents dir in tree */
this.tree.bind('select', function(e) {
self.tree.find('a').removeClass('selected');
$(e.target).addClass('selected').parents('li:has(ul)').children('ul').show().prev().children('div').addClass('expanded');
});
/* make places droppable */
if (this.fm.options.places) {
this.fm.view.plc.click(function(e) {
e.preventDefault();
var t = $(e.target),
h = t.attr('key'), ul;
if (h) {
h != self.fm.cwd.hash && self.ui.exec('open', e.target)
} else if (e.target.nodeName == 'A' || e.target.nodeName == 'DIV') {
ul = self.fm.view.plc.find('ul');
if (ul.children().length) {
ul.toggle(300);
self.fm.view.plc.children('li').find('div').toggleClass('expanded');
}
}
});
this.fm.view.plc.droppable({
accept : '(div,tr).directory',
tolerance : 'pointer',
over : function() { $(this).addClass('el-finder-droppable'); },
out : function() { $(this).removeClass('el-finder-droppable'); },
drop : function(e, ui) {
$(this).removeClass('el-finder-droppable');
var upd = false;
/* accept only folders with read access */
ui.helper.children('.directory:not(.noaccess,.dropbox)').each(function() {
if (self.fm.addPlace($(this).attr('key'))) {
upd = true;
$(this).hide();
}
});
/* update places id's and view */
if (upd) {
self.fm.view.renderPlaces();
self.updatePlaces();
self.fm.view.plc.children('li').children('div').trigger('click');
}
/* hide helper if empty */
if (!ui.helper.children('div:visible').length) {
ui.helper.hide();
}
}
});
}
/* bind shortcuts */
$(document).bind($.browser.mozilla || $.browser.opera ? 'keypress' : 'keydown', function(e) {
var meta = e.ctrlKey||e.metaKey;
if (self.lock) {
return;
}
switch(e.keyCode) {
/* arrows left/up. with Ctrl - exec "back", w/o - move selection */
case 37:
case 38:
e.stopPropagation();
e.preventDefault();
if (e.keyCode == 37 && meta) {
self.ui.execIfAllowed('back');
} else {
moveSelection(false, !e.shiftKey);
}
break;
/* arrows right/down. with Ctrl - exec "open", w/o - move selection */
case 39:
case 40:
e.stopPropagation();
e.preventDefault();
if (meta) {
self.ui.execIfAllowed('open');
} else {
moveSelection(true, !e.shiftKey);
}
break;
}
});
$(document).bind($.browser.opera ? 'keypress' : 'keydown', function(e) {
if (self.lock) {
return;
}
switch(e.keyCode) {
/* Space - QuickLook */
case 32:
e.preventDefault();
e.stopPropagation();
self.fm.quickLook.toggle();
break;
/* Esc */
case 27:
self.fm.quickLook.hide();
break;
}
});
if (!this.fm.options.disableShortcuts) {
$(document).bind('keydown', function(e) {
var meta = e.ctrlKey||e.metaKey;
if (self.lock) {
return;
}
switch (e.keyCode) {
/* Meta+Backspace - delete */
case 8:
if (meta && self.ui.isCmdAllowed('rm')) {
e.preventDefault();
self.ui.exec('rm');
}
break;
/* Enter - exec "select" command if enabled, otherwise exec "open" */
case 13:
if (self.ui.isCmdAllowed('select')) {
return self.ui.exec('select');
}
self.ui.execIfAllowed('open');
break;
/* Delete */
case 46:
self.ui.execIfAllowed('rm');
break;
/* Ctrl+A */
case 65:
if (meta) {
e.preventDefault();
self.fm.selectAll();
}
break;
/* Ctrl+C */
case 67:
meta && self.ui.execIfAllowed('copy');
break;
/* Ctrl+I - get info */
case 73:
if (meta) {
e.preventDefault();
self.ui.exec('info');
}
break;
/* Ctrl+N - new folder */
case 78:
if (meta) {
e.preventDefault();
self.ui.execIfAllowed('mkdir');
}
break;
/* Ctrl+U - upload files */
case 85:
if (meta) {
e.preventDefault();
self.ui.execIfAllowed('upload');
}
break;
/* Ctrl+V */
case 86:
meta && self.ui.execIfAllowed('paste');
break;
/* Ctrl+X */
case 88:
meta && self.ui.execIfAllowed('cut');
break;
case 113:
self.ui.execIfAllowed('rename');
break;
}
});
}
}
/**
* Update navigation droppable/draggable
*
**/
this.updateNav = function() {
$('a', this.tree).click(function(e) {
e.preventDefault();
var t = $(this), c;
if (e.target.nodeName == 'DIV' && $(e.target).hasClass('collapsed')) {
$(e.target).toggleClass('expanded').parent().next('ul').toggle(300);
} else if (t.attr('key') != self.fm.cwd.hash) {
if (t.hasClass('noaccess') || t.hasClass('dropbox')) {
self.fm.view.error('Access denied');
} else {
self.ui.exec('open', t.trigger('select')[0]);
}
} else {
c = t.children('.collapsed');
if (c.length) {
c.toggleClass('expanded');
t.next('ul').toggle(300);
}
}
});
$('a:not(.noaccess,.readonly)', this.tree).droppable({
tolerance : 'pointer',
accept : 'div[key],tr[key]',
over : function() { $(this).addClass('el-finder-droppable'); },
out : function() { $(this).removeClass('el-finder-droppable'); },
drop : function(e, ui) { $(this).removeClass('el-finder-droppable'); self.fm.drop(e, ui, $(this).attr('key')); }
});
this.fm.options.places && this.updatePlaces();
}
/**
* Update places draggable
*
**/
this.updatePlaces = function() {
this.fm.view.plc.children('li').find('li').draggable({
scroll : false,
stop : function() {
if (self.fm.removePlace($(this).children('a').attr('key'))) {
$(this).remove();
if (!$('li', self.fm.view.plc.children('li')).length) {
self.fm.view.plc.children('li').find('div').removeClass('collapsed expanded').end().children('ul').hide();
}
}
}
});
}
/**
* Update folders droppable & files/folders draggable
**/
this.updateCwd = function() {
$('[key]', this.cwd)
.bind('dblclick', function(e) {
self.fm.select($(this), true);
self.ui.exec(self.ui.isCmdAllowed('select') ? 'select' : 'open');
})
.draggable({
delay : 3,
addClasses : false,
appendTo : '.el-finder-cwd',
revert : true,
drag : function(e, ui) {
ui.helper.toggleClass('el-finder-drag-copy', e.shiftKey||e.ctrlKey);
},
helper : function() {
var t = $(this),
h = $('<div class="el-finder-drag-helper"/>'),
c = 0;
!t.hasClass('ui-selected') && self.fm.select(t, true);
self.cwd.find('.ui-selected').each(function(i) {
var el = self.fm.options.view == 'icons' ? $(this).clone().removeClass('ui-selected') : $(self.fm.view.renderIcon(self.fm.cdc[$(this).attr('key')]))
if (c++ == 0 || c%12 == 0) {
el.css('margin-left', 0);
}
h.append(el);
});
return h.css('width', (c<=12 ? 85+(c-1)*29 : 387)+'px');
}
})
.filter('.directory')
.droppable({
tolerance : 'pointer',
accept : 'div[key],tr[key]',
over : function() { $(this).addClass('el-finder-droppable'); },
out : function() { $(this).removeClass('el-finder-droppable'); },
drop : function(e, ui) { $(this).removeClass('el-finder-droppable'); self.fm.drop(e, ui, $(this).attr('key')); }
});
if ($.browser.msie) {
$('*', this.cwd).attr('unselectable', 'on')
.filter('[key]')
.bind('dragstart', function() { self.cwd.selectable('disable').removeClass('ui-state-disabled ui-selectable-disabled'); })
.bind('dragstop', function() { self.cwd.selectable('enable'); });
}
}
/**
* Move selection in current dir
*
* @param Boolean move forward?
* @param Boolean clear current selection?
**/
function moveSelection(forward, reset) {
var p, _p, cur;
if (!$('[key]', self.cwd).length) {
return;
}
if (self.fm.selected.length == 0) {
p = $('[key]:'+(forward ? 'first' : 'last'), self.cwd);
self.fm.select(p);
} else if (reset) {
p = $('.ui-selected:'+(forward ? 'last' : 'first'), self.cwd);
_p = p[forward ? 'next' : 'prev']('[key]');
if (_p.length) {
p = _p;
}
self.fm.select(p, true);
} else {
if (self.pointer) {
cur = $('[key="'+self.pointer+'"].ui-selected', self.cwd);
}
if (!cur || !cur.length) {
cur = $('.ui-selected:'+(forward ? 'last' : 'first'), self.cwd);
}
p = cur[forward ? 'next' : 'prev']('[key]');
if (!p.length) {
p = cur;
} else {
if (!p.hasClass('ui-selected')) {
self.fm.select(p);
} else {
if (!cur.hasClass('ui-selected')) {
self.fm.unselect(p);
} else {
_p = cur[forward ? 'prev' : 'next']('[key]')
if (!_p.length || !_p.hasClass('ui-selected')) {
self.fm.unselect(cur);
} else {
while ((_p = forward ? p.next('[key]') : p.prev('[key]')) && p.hasClass('ui-selected')) {
p = _p;
}
self.fm.select(p);
}
}
}
}
}
self.pointer = p.attr('key');
self.fm.checkSelectedPos(forward);
}
}
})(jQuery); | merwill/seguridad-uti | public/jquery4php-assets/js/plugins/elfinder/jquery.elfinder.full.js | JavaScript | bsd-3-clause | 92,542 |
{{+bindTo:partials.standard_nacl_api}}
<h1>text_input_controller.h File Reference</h1>
<div id="doxygen-ref">
{{- dummy div to appease doxygen -}}
<div>
<!-- Generated by Doxygen 1.7.6.1 -->
</div>
<!--header-->
<div class="contents">
<div class="textblock"><div class="dynheader">
Include dependency graph for text_input_controller.h:</div>
<div class="dyncontent">
<div class="center"><img src="text__input__controller_8h__incl.png" border="0" usemap="#text__input__controller_8h" alt="" /></div>
<map name="text__input__controller_8h" id="text__input__controller_8h">
</map>
</div>
</div><h2>
Classes</h2><table class="memberdecls">
<tr><td class="memItemLeft" align="right" valign="top">class  </td><td class="memItemRight" valign="bottom"><a class="el" href="classpp_1_1_text_input_controller.html">pp::TextInputController</a></td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">This class can be used for giving hints to the browser about the text input status of plugins. <a href="classpp_1_1_text_input_controller.html#details">More...</a><br /></td></tr>
</table><h2>
Namespaces</h2><table class="memberdecls">
<tr><td class="memItemLeft" align="right" valign="top">namespace  </td><td class="memItemRight" valign="bottom"><a class="el" href="namespacepp.html">pp</a></td></tr>
</table>
<hr /><a name="details" id="details"></a><h2>Detailed Description</h2>
<div class="textblock"><p>This file defines the APIs for text input handling. </p>
</div></div><!-- contents -->
</div>
{{/partials.standard_nacl_api}}
| dednal/chromium.src | native_client_sdk/doc_generated/pepper_dev/cpp/text__input__controller_8h.html | HTML | bsd-3-clause | 1,553 |
<?php
/**
* Unified diff generator for PHP DiffLib.
*
* PHP version 5
*
* Copyright (c) 2009 Chris Boulton <chris.boulton@interspire.com>
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* - Neither the name of the Chris Boulton nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* @package DiffLib
* @author Chris Boulton <chris.boulton@interspire.com>
* @copyright (c) 2009 Chris Boulton
* @license New BSD License http://www.opensource.org/licenses/bsd-license.php
* @version 1.1
* @link http://github.com/chrisboulton/php-diff
*/
require_once dirname(__FILE__).'/../Abstract.php';
class Diff_Renderer_Text_Unified extends Diff_Renderer_Abstract
{
/**
* Render and return a unified diff.
*
* @return string The unified diff.
*/
public function render()
{
$diff = '';
$opCodes = $this->diff->getGroupedOpcodes();
foreach($opCodes as $group) {
$lastItem = count($group)-1;
$i1 = $group[0][1];
$i2 = $group[$lastItem][2];
$j1 = $group[0][3];
$j2 = $group[$lastItem][4];
if($i1 == 0 && $i2 == 0) {
$i1 = -1;
$i2 = -1;
}
$diff .= '@@ -'.($i1 + 1).','.($i2 - $i1).' +'.($j1 + 1).','.($j2 - $j1)." @@\n";
foreach($group as $code) {
list($tag, $i1, $i2, $j1, $j2) = $code;
if($tag == 'equal') {
$diff .= ' '.implode("\n ", $this->diff->GetA($i1, $i2))."\n";
}
else {
if($tag == 'replace' || $tag == 'delete') {
$diff .= '-'.implode("\n-", $this->diff->GetA($i1, $i2))."\n";
}
if($tag == 'replace' || $tag == 'insert') {
$diff .= '+'.implode("\n+", $this->diff->GetB($j1, $j2))."\n";
}
}
}
}
return $diff;
}
} | andrikurniawan/immmweb | vendor/phpspec/php-diff/lib/Diff/Renderer/Text/Unified.php | PHP | bsd-3-clause | 3,047 |
div > * {background:#F00; color:#FFF; font-weight:bold; padding:0.2em; margin:0.1em;}
#core-attributes #core-attributes-id,
#core-attributes .core-attributes-class,
#core-attributes div[title='tooltip'],
#core-attributes div[lang='en'],
#core-attributes div[onclick="alert('foo');"],
#module-text abbr,
#module-text acronym,
#module-text div blockquote,
#module-text blockquote[cite='http://www.example.com'],
#module-text br,
#module-text cite,
#module-text code,
#module-text dfn,
#module-text em,
#module-text h1,
#module-text h2,
#module-text h3,
#module-text h4,
#module-text h5,
#module-text h6,
#module-text kbd,
#module-text p,
#module-text pre,
#module-text span q,
#module-text q[cite='http://www.example.com'],
#module-text samp,
#module-text strong,
#module-text var,
#module-hypertext span a,
#module-hypertext a[accesskey='q'],
#module-hypertext a[charset='UTF-8'],
#module-hypertext a[href='http://www.example.com/'],
#module-hypertext a[hreflang='en'],
#module-hypertext a[rel='nofollow'],
#module-hypertext a[rev='index'],
#module-hypertext a[tabindex='1'],
#module-hypertext a[type='text/plain'],
#module-list dl,
#module-list ul,
#module-list ol,
#module-list li,
#module-list dd,
#module-list dt,
.insert-declarations-above
{background:#008000; margin:0; padding:0.2em;}
#module-text span, #module-text div {padding:0; margin:0.1em;}
#module-list li, #module-list dd, #module-list dt {border:1px solid #FFF;}
/* vim: et sw=4 sts=4 */
| Youxiang11/lvmeida | vendor/ezyang/htmlpurifier/smoketests/basic/allElements.css | CSS | bsd-3-clause | 1,456 |
(function() {
var mode = CodeMirror.getMode({indentUnit: 2}, "text/x-scss");
function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1), "scss"); }
MT('url_with_quotation',
"[tag foo] { [property background]:[atom url]([string test.jpg]) }");
MT('url_with_double_quotes',
"[tag foo] { [property background]:[atom url]([string \"test.jpg\"]) }");
MT('url_with_single_quotes',
"[tag foo] { [property background]:[atom url]([string \'test.jpg\']) }");
MT('string',
"[def @import] [string \"compass/css3\"]");
MT('important_keyword',
"[tag foo] { [property background]:[atom url]([string \'test.jpg\']) [keyword !important] }");
MT('variable',
"[variable-2 $blue]:[atom #333]");
MT('variable_as_attribute',
"[tag foo] { [property color]:[variable-2 $blue] }");
MT('numbers',
"[tag foo] { [property padding]:[number 10px] [number 10] [number 10em] [number 8in] }");
MT('number_percentage',
"[tag foo] { [property width]:[number 80%] }");
MT('selector',
"[builtin #hello][qualifier .world]{}");
MT('singleline_comment',
"[comment // this is a comment]");
MT('multiline_comment',
"[comment /*foobar*/]");
MT('attribute_with_hyphen',
"[tag foo] { [property font-size]:[number 10px] }");
MT('string_after_attribute',
"[tag foo] { [property content]:[string \"::\"] }");
MT('directives',
"[def @include] [qualifier .mixin]");
MT('basic_structure',
"[tag p] { [property background]:[keyword red]; }");
MT('nested_structure',
"[tag p] { [tag a] { [property color]:[keyword red]; } }");
MT('mixin',
"[def @mixin] [tag table-base] {}");
MT('number_without_semicolon',
"[tag p] {[property width]:[number 12]}",
"[tag a] {[property color]:[keyword red];}");
MT('atom_in_nested_block',
"[tag p] { [tag a] { [property color]:[atom #000]; } }");
MT('interpolation_in_property',
"[tag foo] { #{[variable-2 $hello]}:[number 2]; }");
MT('interpolation_in_selector',
"[tag foo]#{[variable-2 $hello]} { [property color]:[atom #000]; }");
MT('interpolation_error',
"[tag foo]#{[error foo]} { [property color]:[atom #000]; }");
MT("divide_operator",
"[tag foo] { [property width]:[number 4] [operator /] [number 2] }");
MT('nested_structure_with_id_selector',
"[tag p] { [builtin #hello] { [property color]:[keyword red]; } }");
MT('indent_mixin',
"[def @mixin] [tag container] (",
" [variable-2 $a]: [number 10],",
" [variable-2 $b]: [number 10])",
"{}");
MT('indent_nested',
"[tag foo] {",
" [tag bar] {",
" }",
"}");
MT('indent_parentheses',
"[tag foo] {",
" [property color]: [variable darken]([variable-2 $blue],",
" [number 9%]);",
"}");
MT('indent_vardef',
"[variable-2 $name]:",
" [string 'val'];",
"[tag tag] {",
" [tag inner] {",
" [property margin]: [number 3px];",
" }",
"}");
})();
| 2947721120/chromedeveditor | cde-polymer-designer.dart/lib/src/polymer_designer/components/code-mirror/codemirror-4.0/mode/css/scss_test.js | JavaScript | bsd-3-clause | 2,997 |
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2013 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Authentication\Adapter;
use stdClass;
use Zend\Authentication\Result as AuthenticationResult;
use Zend\Ldap as ZendLdap;
use Zend\Ldap\Exception\LdapException;
class Ldap extends AbstractAdapter
{
/**
* The Zend\Ldap\Ldap context.
*
* @var ZendLdap\Ldap
*/
protected $ldap = null;
/**
* The array of arrays of Zend\Ldap\Ldap options passed to the constructor.
*
* @var array
*/
protected $options = null;
/**
* The DN of the authenticated account. Used to retrieve the account entry on request.
*
* @var string
*/
protected $authenticatedDn = null;
/**
* Constructor
*
* @param array $options An array of arrays of Zend\Ldap\Ldap options
* @param string $identity The username of the account being authenticated
* @param string $credential The password of the account being authenticated
*/
public function __construct(array $options = array(), $identity = null, $credential = null)
{
$this->setOptions($options);
if ($identity !== null) {
$this->setIdentity($identity);
}
if ($credential !== null) {
$this->setCredential($credential);
}
}
/**
* Returns the array of arrays of Zend\Ldap\Ldap options of this adapter.
*
* @return array|null
*/
public function getOptions()
{
return $this->options;
}
/**
* Sets the array of arrays of Zend\Ldap\Ldap options to be used by
* this adapter.
*
* @param array $options The array of arrays of Zend\Ldap\Ldap options
* @return Ldap Provides a fluent interface
*/
public function setOptions($options)
{
$this->options = is_array($options) ? $options : array();
if (array_key_exists('identity', $this->options)) {
$this->options['username'] = $this->options['identity'];
}
if (array_key_exists('credential', $this->options)) {
$this->options['password'] = $this->options['credential'];
}
return $this;
}
/**
* Returns the username of the account being authenticated, or
* NULL if none is set.
*
* @return string|null
*/
public function getUsername()
{
return $this->getIdentity();
}
/**
* Sets the username for binding
*
* @param string $username The username for binding
* @return Ldap Provides a fluent interface
*/
public function setUsername($username)
{
return $this->setIdentity($username);
}
/**
* Returns the password of the account being authenticated, or
* NULL if none is set.
*
* @return string|null
*/
public function getPassword()
{
return $this->getCredential();
}
/**
* Sets the password for the account
*
* @param string $password The password of the account being authenticated
* @return Ldap Provides a fluent interface
*/
public function setPassword($password)
{
return $this->setCredential($password);
}
/**
* Returns the LDAP Object
*
* @return ZendLdap\Ldap The Zend\Ldap\Ldap object used to authenticate the credentials
*/
public function getLdap()
{
if ($this->ldap === null) {
$this->ldap = new ZendLdap\Ldap();
}
return $this->ldap;
}
/**
* Set an Ldap connection
*
* @param ZendLdap\Ldap $ldap An existing Ldap object
* @return Ldap Provides a fluent interface
*/
public function setLdap(ZendLdap\Ldap $ldap)
{
$this->ldap = $ldap;
$this->setOptions(array($ldap->getOptions()));
return $this;
}
/**
* Returns a domain name for the current LDAP options. This is used
* for skipping redundant operations (e.g. authentications).
*
* @return string
*/
protected function getAuthorityName()
{
$options = $this->getLdap()->getOptions();
$name = $options['accountDomainName'];
if (!$name)
$name = $options['accountDomainNameShort'];
return $name ? $name : '';
}
/**
* Authenticate the user
*
* @return AuthenticationResult
* @throws Exception\ExceptionInterface
*/
public function authenticate()
{
$messages = array();
$messages[0] = ''; // reserved
$messages[1] = ''; // reserved
$username = $this->identity;
$password = $this->credential;
if (!$username) {
$code = AuthenticationResult::FAILURE_IDENTITY_NOT_FOUND;
$messages[0] = 'A username is required';
return new AuthenticationResult($code, '', $messages);
}
if (!$password) {
/* A password is required because some servers will
* treat an empty password as an anonymous bind.
*/
$code = AuthenticationResult::FAILURE_CREDENTIAL_INVALID;
$messages[0] = 'A password is required';
return new AuthenticationResult($code, '', $messages);
}
$ldap = $this->getLdap();
$code = AuthenticationResult::FAILURE;
$messages[0] = "Authority not found: $username";
$failedAuthorities = array();
/* Iterate through each server and try to authenticate the supplied
* credentials against it.
*/
foreach ($this->options as $options) {
if (!is_array($options)) {
throw new Exception\InvalidArgumentException('Adapter options array not an array');
}
$adapterOptions = $this->prepareOptions($ldap, $options);
$dname = '';
try {
if ($messages[1])
$messages[] = $messages[1];
$messages[1] = '';
$messages[] = $this->optionsToString($options);
$dname = $this->getAuthorityName();
if (isset($failedAuthorities[$dname])) {
/* If multiple sets of server options for the same domain
* are supplied, we want to skip redundant authentications
* where the identity or credentials where found to be
* invalid with another server for the same domain. The
* $failedAuthorities array tracks this condition (and also
* serves to supply the original error message).
* This fixes issue ZF-4093.
*/
$messages[1] = $failedAuthorities[$dname];
$messages[] = "Skipping previously failed authority: $dname";
continue;
}
$canonicalName = $ldap->getCanonicalAccountName($username);
$ldap->bind($canonicalName, $password);
/*
* Fixes problem when authenticated user is not allowed to retrieve
* group-membership information or own account.
* This requires that the user specified with "username" and optionally
* "password" in the Zend\Ldap\Ldap options is able to retrieve the required
* information.
*/
$requireRebind = false;
if (isset($options['username'])) {
$ldap->bind();
$requireRebind = true;
}
$dn = $ldap->getCanonicalAccountName($canonicalName, ZendLdap\Ldap::ACCTNAME_FORM_DN);
$groupResult = $this->checkGroupMembership($ldap, $canonicalName, $dn, $adapterOptions);
if ($groupResult === true) {
$this->authenticatedDn = $dn;
$messages[0] = '';
$messages[1] = '';
$messages[] = "$canonicalName authentication successful";
if ($requireRebind === true) {
// rebinding with authenticated user
$ldap->bind($dn, $password);
}
return new AuthenticationResult(AuthenticationResult::SUCCESS, $canonicalName, $messages);
} else {
$messages[0] = 'Account is not a member of the specified group';
$messages[1] = $groupResult;
$failedAuthorities[$dname] = $groupResult;
}
} catch (LdapException $zle) {
/* LDAP based authentication is notoriously difficult to diagnose. Therefore
* we bend over backwards to capture and record every possible bit of
* information when something goes wrong.
*/
$err = $zle->getCode();
if ($err == LdapException::LDAP_X_DOMAIN_MISMATCH) {
/* This error indicates that the domain supplied in the
* username did not match the domains in the server options
* and therefore we should just skip to the next set of
* server options.
*/
continue;
} elseif ($err == LdapException::LDAP_NO_SUCH_OBJECT) {
$code = AuthenticationResult::FAILURE_IDENTITY_NOT_FOUND;
$messages[0] = "Account not found: $username";
$failedAuthorities[$dname] = $zle->getMessage();
} elseif ($err == LdapException::LDAP_INVALID_CREDENTIALS) {
$code = AuthenticationResult::FAILURE_CREDENTIAL_INVALID;
$messages[0] = 'Invalid credentials';
$failedAuthorities[$dname] = $zle->getMessage();
} else {
$line = $zle->getLine();
$messages[] = $zle->getFile() . "($line): " . $zle->getMessage();
$messages[] = preg_replace(
'/\b'.preg_quote(substr($password, 0, 15), '/').'\b/',
'*****',
$zle->getTraceAsString()
);
$messages[0] = 'An unexpected failure occurred';
}
$messages[1] = $zle->getMessage();
}
}
$msg = isset($messages[1]) ? $messages[1] : $messages[0];
$messages[] = "$username authentication failed: $msg";
return new AuthenticationResult($code, $username, $messages);
}
/**
* Sets the LDAP specific options on the Zend\Ldap\Ldap instance
*
* @param ZendLdap\Ldap $ldap
* @param array $options
* @return array of auth-adapter specific options
*/
protected function prepareOptions(ZendLdap\Ldap $ldap, array $options)
{
$adapterOptions = array(
'group' => null,
'groupDn' => $ldap->getBaseDn(),
'groupScope' => ZendLdap\Ldap::SEARCH_SCOPE_SUB,
'groupAttr' => 'cn',
'groupFilter' => 'objectClass=groupOfUniqueNames',
'memberAttr' => 'uniqueMember',
'memberIsDn' => true
);
foreach ($adapterOptions as $key => $value) {
if (array_key_exists($key, $options)) {
$value = $options[$key];
unset($options[$key]);
switch ($key) {
case 'groupScope':
$value = (int) $value;
if (in_array($value, array(ZendLdap\Ldap::SEARCH_SCOPE_BASE,
ZendLdap\Ldap::SEARCH_SCOPE_ONE, ZendLdap\Ldap::SEARCH_SCOPE_SUB), true)) {
$adapterOptions[$key] = $value;
}
break;
case 'memberIsDn':
$adapterOptions[$key] = ($value === true ||
$value === '1' || strcasecmp($value, 'true') == 0);
break;
default:
$adapterOptions[$key] = trim($value);
break;
}
}
}
$ldap->setOptions($options);
return $adapterOptions;
}
/**
* Checks the group membership of the bound user
*
* @param ZendLdap\Ldap $ldap
* @param string $canonicalName
* @param string $dn
* @param array $adapterOptions
* @return string|true
*/
protected function checkGroupMembership(ZendLdap\Ldap $ldap, $canonicalName, $dn, array $adapterOptions)
{
if ($adapterOptions['group'] === null) {
return true;
}
if ($adapterOptions['memberIsDn'] === false) {
$user = $canonicalName;
} else {
$user = $dn;
}
$groupName = ZendLdap\Filter::equals($adapterOptions['groupAttr'], $adapterOptions['group']);
$membership = ZendLdap\Filter::equals($adapterOptions['memberAttr'], $user);
$group = ZendLdap\Filter::andFilter($groupName, $membership);
$groupFilter = $adapterOptions['groupFilter'];
if (!empty($groupFilter)) {
$group = $group->addAnd($groupFilter);
}
$result = $ldap->count($group, $adapterOptions['groupDn'], $adapterOptions['groupScope']);
if ($result === 1) {
return true;
}
return 'Failed to verify group membership with ' . $group->toString();
}
/**
* getAccountObject() - Returns the result entry as a stdClass object
*
* This resembles the feature {@see Zend\Authentication\Adapter\DbTable::getResultRowObject()}.
* Closes ZF-6813
*
* @param array $returnAttribs
* @param array $omitAttribs
* @return stdClass|bool
*/
public function getAccountObject(array $returnAttribs = array(), array $omitAttribs = array())
{
if (!$this->authenticatedDn) {
return false;
}
$returnObject = new stdClass();
$omitAttribs = array_map('strtolower', $omitAttribs);
$entry = $this->getLdap()->getEntry($this->authenticatedDn, $returnAttribs, true);
foreach ($entry as $attr => $value) {
if (in_array($attr, $omitAttribs)) {
// skip attributes marked to be omitted
continue;
}
if (is_array($value)) {
$returnObject->$attr = (count($value) > 1) ? $value : $value[0];
} else {
$returnObject->$attr = $value;
}
}
return $returnObject;
}
/**
* Converts options to string
*
* @param array $options
* @return string
*/
private function optionsToString(array $options)
{
$str = '';
foreach ($options as $key => $val) {
if ($key === 'password' || $key === 'credential') {
$val = '*****';
}
if ($str) {
$str .= ',';
}
$str .= $key . '=' . $val;
}
return $str;
}
}
| duyluong89/myzend | vendor/zendframework/zendframework/library/Zend/Authentication/Adapter/Ldap.php | PHP | bsd-3-clause | 15,557 |
<!DOCTYPE html>
<html>
<head>
<script>
if (window.testRunner)
testRunner.dumpAsText();
function log(msg)
{
document.getElementById('console').appendChild(document.createTextNode(msg + "\n"));
}
var families = [
"serif",
"sans-serif",
"cursive",
"fantasy",
"monospace"
];
window.onload = function()
{
for (var i = 0; i < families.length; i++) {
var family = families[i];
var div = document.createElement("div");
div.setAttribute("style", "font-family: " + family);
document.body.appendChild(div);
var returnedFamily = window.getComputedStyle(div).fontFamily
if (family == returnedFamily)
log("PASS: The computed style for a specified font-family of '" + family + "' matched.");
else
log("FAIL: The computed style for a specified font-family of '" + family + "' did not match. Actual result was '" + returnedFamily + "'.");
}
}
</script>
</head>
<body>
<pre id="console"></pre>
</body>
</html>
| hgl888/blink-crosswalk-efl | LayoutTests/fast/css/font-family-builtins.html | HTML | bsd-3-clause | 1,125 |
from sympy import (hyper, meijerg, S, Tuple, pi, I, exp, log,
cos, sqrt, symbols, oo, Derivative, gamma, O)
from sympy.series.limits import limit
from sympy.abc import x, z, k
from sympy.utilities.pytest import raises, slow
from sympy.utilities.randtest import (
random_complex_number as randcplx,
verify_numerically as tn,
test_derivative_numerically as td)
def test_TupleParametersBase():
# test that our implementation of the chain rule works
p = hyper((), (), z**2)
assert p.diff(z) == p*2*z
def test_hyper():
raises(TypeError, lambda: hyper(1, 2, z))
assert hyper((1, 2), (1,), z) == hyper(Tuple(1, 2), Tuple(1), z)
h = hyper((1, 2), (3, 4, 5), z)
assert h.ap == Tuple(1, 2)
assert h.bq == Tuple(3, 4, 5)
assert h.argument == z
assert h.is_commutative is True
# just a few checks to make sure that all arguments go where they should
assert tn(hyper(Tuple(), Tuple(), z), exp(z), z)
assert tn(z*hyper((1, 1), Tuple(2), -z), log(1 + z), z)
# differentiation
h = hyper(
(randcplx(), randcplx(), randcplx()), (randcplx(), randcplx()), z)
assert td(h, z)
a1, a2, b1, b2, b3 = symbols('a1:3, b1:4')
assert hyper((a1, a2), (b1, b2, b3), z).diff(z) == \
a1*a2/(b1*b2*b3) * hyper((a1 + 1, a2 + 1), (b1 + 1, b2 + 1, b3 + 1), z)
# differentiation wrt parameters is not supported
assert hyper([z], [], z).diff(z) == Derivative(hyper([z], [], z), z)
# hyper is unbranched wrt parameters
from sympy import polar_lift
assert hyper([polar_lift(z)], [polar_lift(k)], polar_lift(x)) == \
hyper([z], [k], polar_lift(x))
def test_expand_func():
# evaluation at 1 of Gauss' hypergeometric function:
from sympy.abc import a, b, c
from sympy import gamma, expand_func
a1, b1, c1 = randcplx(), randcplx(), randcplx() + 5
assert expand_func(hyper([a, b], [c], 1)) == \
gamma(c)*gamma(-a - b + c)/(gamma(-a + c)*gamma(-b + c))
assert abs(expand_func(hyper([a1, b1], [c1], 1)).n()
- hyper([a1, b1], [c1], 1).n()) < 1e-10
# hyperexpand wrapper for hyper:
assert expand_func(hyper([], [], z)) == exp(z)
assert expand_func(hyper([1, 2, 3], [], z)) == hyper([1, 2, 3], [], z)
assert expand_func(meijerg([[1, 1], []], [[1], [0]], z)) == log(z + 1)
assert expand_func(meijerg([[1, 1], []], [[], []], z)) == \
meijerg([[1, 1], []], [[], []], z)
def replace_dummy(expr, sym):
from sympy import Dummy
dum = expr.atoms(Dummy)
if not dum:
return expr
assert len(dum) == 1
return expr.xreplace({dum.pop(): sym})
def test_hyper_rewrite_sum():
from sympy import RisingFactorial, factorial, Dummy, Sum
_k = Dummy("k")
assert replace_dummy(hyper((1, 2), (1, 3), x).rewrite(Sum), _k) == \
Sum(x**_k / factorial(_k) * RisingFactorial(2, _k) /
RisingFactorial(3, _k), (_k, 0, oo))
assert hyper((1, 2, 3), (-1, 3), z).rewrite(Sum) == \
hyper((1, 2, 3), (-1, 3), z)
def test_radius_of_convergence():
assert hyper((1, 2), [3], z).radius_of_convergence == 1
assert hyper((1, 2), [3, 4], z).radius_of_convergence == oo
assert hyper((1, 2, 3), [4], z).radius_of_convergence == 0
assert hyper((0, 1, 2), [4], z).radius_of_convergence == oo
assert hyper((-1, 1, 2), [-4], z).radius_of_convergence == 0
assert hyper((-1, -2, 2), [-1], z).radius_of_convergence == oo
assert hyper((-1, 2), [-1, -2], z).radius_of_convergence == 0
assert hyper([-1, 1, 3], [-2, 2], z).radius_of_convergence == 1
assert hyper([-1, 1], [-2, 2], z).radius_of_convergence == oo
assert hyper([-1, 1, 3], [-2], z).radius_of_convergence == 0
assert hyper((-1, 2, 3, 4), [], z).radius_of_convergence == oo
assert hyper([1, 1], [3], 1).convergence_statement == True
assert hyper([1, 1], [2], 1).convergence_statement == False
assert hyper([1, 1], [2], -1).convergence_statement == True
assert hyper([1, 1], [1], -1).convergence_statement == False
def test_meijer():
raises(TypeError, lambda: meijerg(1, z))
raises(TypeError, lambda: meijerg(((1,), (2,)), (3,), (4,), z))
assert meijerg(((1, 2), (3,)), ((4,), (5,)), z) == \
meijerg(Tuple(1, 2), Tuple(3), Tuple(4), Tuple(5), z)
g = meijerg((1, 2), (3, 4, 5), (6, 7, 8, 9), (10, 11, 12, 13, 14), z)
assert g.an == Tuple(1, 2)
assert g.ap == Tuple(1, 2, 3, 4, 5)
assert g.aother == Tuple(3, 4, 5)
assert g.bm == Tuple(6, 7, 8, 9)
assert g.bq == Tuple(6, 7, 8, 9, 10, 11, 12, 13, 14)
assert g.bother == Tuple(10, 11, 12, 13, 14)
assert g.argument == z
assert g.nu == 75
assert g.delta == -1
assert g.is_commutative is True
assert meijerg([1, 2], [3], [4], [5], z).delta == S(1)/2
# just a few checks to make sure that all arguments go where they should
assert tn(meijerg(Tuple(), Tuple(), Tuple(0), Tuple(), -z), exp(z), z)
assert tn(sqrt(pi)*meijerg(Tuple(), Tuple(),
Tuple(0), Tuple(S(1)/2), z**2/4), cos(z), z)
assert tn(meijerg(Tuple(1, 1), Tuple(), Tuple(1), Tuple(0), z),
log(1 + z), z)
# differentiation
g = meijerg((randcplx(),), (randcplx() + 2*I,), Tuple(),
(randcplx(), randcplx()), z)
assert td(g, z)
g = meijerg(Tuple(), (randcplx(),), Tuple(),
(randcplx(), randcplx()), z)
assert td(g, z)
g = meijerg(Tuple(), Tuple(), Tuple(randcplx()),
Tuple(randcplx(), randcplx()), z)
assert td(g, z)
a1, a2, b1, b2, c1, c2, d1, d2 = symbols('a1:3, b1:3, c1:3, d1:3')
assert meijerg((a1, a2), (b1, b2), (c1, c2), (d1, d2), z).diff(z) == \
(meijerg((a1 - 1, a2), (b1, b2), (c1, c2), (d1, d2), z)
+ (a1 - 1)*meijerg((a1, a2), (b1, b2), (c1, c2), (d1, d2), z))/z
assert meijerg([z, z], [], [], [], z).diff(z) == \
Derivative(meijerg([z, z], [], [], [], z), z)
# meijerg is unbranched wrt parameters
from sympy import polar_lift as pl
assert meijerg([pl(a1)], [pl(a2)], [pl(b1)], [pl(b2)], pl(z)) == \
meijerg([a1], [a2], [b1], [b2], pl(z))
# integrand
from sympy.abc import a, b, c, d, s
assert meijerg([a], [b], [c], [d], z).integrand(s) == \
z**s*gamma(c - s)*gamma(-a + s + 1)/(gamma(b - s)*gamma(-d + s + 1))
def test_meijerg_derivative():
assert meijerg([], [1, 1], [0, 0, x], [], z).diff(x) == \
log(z)*meijerg([], [1, 1], [0, 0, x], [], z) \
+ 2*meijerg([], [1, 1, 1], [0, 0, x, 0], [], z)
y = randcplx()
a = 5 # mpmath chokes with non-real numbers, and Mod1 with floats
assert td(meijerg([x], [], [], [], y), x)
assert td(meijerg([x**2], [], [], [], y), x)
assert td(meijerg([], [x], [], [], y), x)
assert td(meijerg([], [], [x], [], y), x)
assert td(meijerg([], [], [], [x], y), x)
assert td(meijerg([x], [a], [a + 1], [], y), x)
assert td(meijerg([x], [a + 1], [a], [], y), x)
assert td(meijerg([x, a], [], [], [a + 1], y), x)
assert td(meijerg([x, a + 1], [], [], [a], y), x)
b = S(3)/2
assert td(meijerg([a + 2], [b], [b - 3, x], [a], y), x)
def test_meijerg_period():
assert meijerg([], [1], [0], [], x).get_period() == 2*pi
assert meijerg([1], [], [], [0], x).get_period() == 2*pi
assert meijerg([], [], [0], [], x).get_period() == 2*pi # exp(x)
assert meijerg(
[], [], [0], [S(1)/2], x).get_period() == 2*pi # cos(sqrt(x))
assert meijerg(
[], [], [S(1)/2], [0], x).get_period() == 4*pi # sin(sqrt(x))
assert meijerg([1, 1], [], [1], [0], x).get_period() == oo # log(1 + x)
def test_hyper_unpolarify():
from sympy import exp_polar
a = exp_polar(2*pi*I)*x
b = x
assert hyper([], [], a).argument == b
assert hyper([0], [], a).argument == a
assert hyper([0], [0], a).argument == b
assert hyper([0, 1], [0], a).argument == a
@slow
def test_hyperrep():
from sympy.functions.special.hyper import (HyperRep, HyperRep_atanh,
HyperRep_power1, HyperRep_power2, HyperRep_log1, HyperRep_asin1,
HyperRep_asin2, HyperRep_sqrts1, HyperRep_sqrts2, HyperRep_log2,
HyperRep_cosasin, HyperRep_sinasin)
# First test the base class works.
from sympy import Piecewise, exp_polar
a, b, c, d, z = symbols('a b c d z')
class myrep(HyperRep):
@classmethod
def _expr_small(cls, x):
return a
@classmethod
def _expr_small_minus(cls, x):
return b
@classmethod
def _expr_big(cls, x, n):
return c*n
@classmethod
def _expr_big_minus(cls, x, n):
return d*n
assert myrep(z).rewrite('nonrep') == Piecewise((0, abs(z) > 1), (a, True))
assert myrep(exp_polar(I*pi)*z).rewrite('nonrep') == \
Piecewise((0, abs(z) > 1), (b, True))
assert myrep(exp_polar(2*I*pi)*z).rewrite('nonrep') == \
Piecewise((c, abs(z) > 1), (a, True))
assert myrep(exp_polar(3*I*pi)*z).rewrite('nonrep') == \
Piecewise((d, abs(z) > 1), (b, True))
assert myrep(exp_polar(4*I*pi)*z).rewrite('nonrep') == \
Piecewise((2*c, abs(z) > 1), (a, True))
assert myrep(exp_polar(5*I*pi)*z).rewrite('nonrep') == \
Piecewise((2*d, abs(z) > 1), (b, True))
assert myrep(z).rewrite('nonrepsmall') == a
assert myrep(exp_polar(I*pi)*z).rewrite('nonrepsmall') == b
def t(func, hyp, z):
""" Test that func is a valid representation of hyp. """
# First test that func agrees with hyp for small z
if not tn(func.rewrite('nonrepsmall'), hyp, z,
a=S(-1)/2, b=S(-1)/2, c=S(1)/2, d=S(1)/2):
return False
# Next check that the two small representations agree.
if not tn(
func.rewrite('nonrepsmall').subs(
z, exp_polar(I*pi)*z).replace(exp_polar, exp),
func.subs(z, exp_polar(I*pi)*z).rewrite('nonrepsmall'),
z, a=S(-1)/2, b=S(-1)/2, c=S(1)/2, d=S(1)/2):
return False
# Next check continuity along exp_polar(I*pi)*t
expr = func.subs(z, exp_polar(I*pi)*z).rewrite('nonrep')
if abs(expr.subs(z, 1 + 1e-15).n() - expr.subs(z, 1 - 1e-15).n()) > 1e-10:
return False
# Finally check continuity of the big reps.
def dosubs(func, a, b):
rv = func.subs(z, exp_polar(a)*z).rewrite('nonrep')
return rv.subs(z, exp_polar(b)*z).replace(exp_polar, exp)
for n in [0, 1, 2, 3, 4, -1, -2, -3, -4]:
expr1 = dosubs(func, 2*I*pi*n, I*pi/2)
expr2 = dosubs(func, 2*I*pi*n + I*pi, -I*pi/2)
if not tn(expr1, expr2, z):
return False
expr1 = dosubs(func, 2*I*pi*(n + 1), -I*pi/2)
expr2 = dosubs(func, 2*I*pi*n + I*pi, I*pi/2)
if not tn(expr1, expr2, z):
return False
return True
# Now test the various representatives.
a = S(1)/3
assert t(HyperRep_atanh(z), hyper([S(1)/2, 1], [S(3)/2], z), z)
assert t(HyperRep_power1(a, z), hyper([-a], [], z), z)
assert t(HyperRep_power2(a, z), hyper([a, a - S(1)/2], [2*a], z), z)
assert t(HyperRep_log1(z), -z*hyper([1, 1], [2], z), z)
assert t(HyperRep_asin1(z), hyper([S(1)/2, S(1)/2], [S(3)/2], z), z)
assert t(HyperRep_asin2(z), hyper([1, 1], [S(3)/2], z), z)
assert t(HyperRep_sqrts1(a, z), hyper([-a, S(1)/2 - a], [S(1)/2], z), z)
assert t(HyperRep_sqrts2(a, z),
-2*z/(2*a + 1)*hyper([-a - S(1)/2, -a], [S(1)/2], z).diff(z), z)
assert t(HyperRep_log2(z), -z/4*hyper([S(3)/2, 1, 1], [2, 2], z), z)
assert t(HyperRep_cosasin(a, z), hyper([-a, a], [S(1)/2], z), z)
assert t(HyperRep_sinasin(a, z), 2*a*z*hyper([1 - a, 1 + a], [S(3)/2], z), z)
@slow
def test_meijerg_eval():
from sympy import besseli, exp_polar
from sympy.abc import l
a = randcplx()
arg = x*exp_polar(k*pi*I)
expr1 = pi*meijerg([[], [(a + 1)/2]], [[a/2], [-a/2, (a + 1)/2]], arg**2/4)
expr2 = besseli(a, arg)
# Test that the two expressions agree for all arguments.
for x_ in [0.5, 1.5]:
for k_ in [0.0, 0.1, 0.3, 0.5, 0.8, 1, 5.751, 15.3]:
assert abs((expr1 - expr2).n(subs={x: x_, k: k_})) < 1e-10
assert abs((expr1 - expr2).n(subs={x: x_, k: -k_})) < 1e-10
# Test continuity independently
eps = 1e-13
expr2 = expr1.subs(k, l)
for x_ in [0.5, 1.5]:
for k_ in [0.5, S(1)/3, 0.25, 0.75, S(2)/3, 1.0, 1.5]:
assert abs((expr1 - expr2).n(
subs={x: x_, k: k_ + eps, l: k_ - eps})) < 1e-10
assert abs((expr1 - expr2).n(
subs={x: x_, k: -k_ + eps, l: -k_ - eps})) < 1e-10
expr = (meijerg(((0.5,), ()), ((0.5, 0, 0.5), ()), exp_polar(-I*pi)/4)
+ meijerg(((0.5,), ()), ((0.5, 0, 0.5), ()), exp_polar(I*pi)/4)) \
/(2*sqrt(pi))
assert (expr - pi/exp(1)).n(chop=True) == 0
def test_limits():
k, x = symbols('k, x')
assert hyper((1,), (S(4)/3, S(5)/3), k**2).series(k) == \
hyper((1,), (S(4)/3, S(5)/3), 0) + \
9*k**2*hyper((2,), (S(7)/3, S(8)/3), 0)/20 + \
81*k**4*hyper((3,), (S(10)/3, S(11)/3), 0)/1120 + \
O(k**6) # issue 6350
assert limit(meijerg((), (), (1,), (0,), -x), x, 0) == \
meijerg(((), ()), ((1,), (0,)), 0) # issue 6052
| kumarkrishna/sympy | sympy/functions/special/tests/test_hyper.py | Python | bsd-3-clause | 13,415 |
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2013 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\EventManager;
/**
* Static version of EventManager
*/
class StaticEventManager extends SharedEventManager
{
/**
* @var StaticEventManager
*/
protected static $instance;
/**
* Singleton
*
* @return void
*/
protected function __construct()
{
}
/**
* Singleton
*
* @return void
*/
private function __clone()
{
}
/**
* Retrieve instance
*
* @return StaticEventManager
*/
public static function getInstance()
{
if (null === static::$instance) {
static::setInstance(new static());
}
return static::$instance;
}
/**
* Set the singleton to a specific SharedEventManagerInterface instance
*
* @param SharedEventManagerInterface $instance
* @return void
*/
public static function setInstance(SharedEventManagerInterface $instance)
{
static::$instance = $instance;
}
/**
* Is a singleton instance defined?
*
* @return bool
*/
public static function hasInstance()
{
return (static::$instance instanceof SharedEventManagerInterface);
}
/**
* Reset the singleton instance
*
* @return void
*/
public static function resetInstance()
{
static::$instance = null;
}
}
| bendriss/application-absence | vendor/ZF2/library/Zend/EventManager/StaticEventManager.php | PHP | bsd-3-clause | 1,683 |
<?php
/**
* Message translations.
*
* This file is automatically generated by 'yii message' command.
* It contains the localizable messages extracted from source code.
* You may modify this file by translating the extracted messages.
*
* Each array element represents the translation (value) of a message (key).
* If the value is empty, the message is considered as not translated.
* Messages that no longer need translation will have their translations
* enclosed between a pair of '@@' marks.
*
* Message string can be used with plural forms format. Check i18n section
* of the guide for details.
*
* NOTE: this file must be saved in UTF-8 encoding.
*/
return [
'(not set)' => '(설정되어있지않습니다)',
'An internal server error occurred.' => '서버 오류가 발생하였습니다.',
'Delete' => '삭제',
'Error' => '오류',
'File upload failed.' => '파일 업로드 실패하였습니다.',
'Home' => '홈',
'Invalid data received for parameter "{param}".' => '매개변수"{param}"를 위한 데이터가 잘못된 데이터입니다.',
'Login Required' => '로그인이 필요합니다.',
'Missing required arguments: {params}' => '필요한 인수가 없습니다: {params}',
'Missing required parameters: {params}' => '필요한 매개변수가 없습니다: {params}',
'No' => '아니오',
'No help for unknown command "{command}".' => '알 수 없는 명령 "{command}"에 대한 도움말이 없습니다.',
'No help for unknown sub-command "{command}".' => '알 수 없는 하위명령 "{command}"에 대한 도움말이 없습니다.',
'No results found.' => '결과가 없습니다.',
'Only files with these extensions are allowed: {extensions}.' => '다음의 확장명을 가진 파일만 허용됩니다: {extensions}',
'Page not found.' => '페이지를 찾을 수 없습니다.',
'Please fix the following errors:' => '다음 오류를 수정하십시오:',
'Please upload a file.' => '파일을 업로드하십시오.',
'Showing <b>{begin, number}-{end, number}</b> of <b>{totalCount, number}</b> {totalCount, plural, one{item} other{items}}.' => '{totalCount} 중 {begin} 에서 {end} 까지 표시하고 있습니다.',
'The file "{file}" is not an image.' => '파일 "{file}"은 이미지 파일이 아닙니다.',
'The file "{file}" is too big. Its size cannot exceed {limit, number} {limit, plural, one{byte} other{bytes}}.' => '파일 "{file}"는 크기가 너무 큽니다. 파일 크기는 {limit} 바이트를 초과할 수 없습니다.',
'The file "{file}" is too small. Its size cannot be smaller than {limit, number} {limit, plural, one{byte} other{bytes}}.' => '파일 "{file}"는 크기가 너무 작습니다. 크기는 {limit} 바이트 보다 작을 수 없습니다.',
'The format of {attribute} is invalid.' => '{attribute}의 형식이 올바르지 않습니다.',
'The image "{file}" is too large. The height cannot be larger than {limit, number} {limit, plural, one{pixel} other{pixels}}.' => '이미지 "{file}"가 너무 큽니다. 높이는 {limit} 보다 클 수 없습니다.',
'The image "{file}" is too large. The width cannot be larger than {limit, number} {limit, plural, one{pixel} other{pixels}}.' => '이미지 "{file}"가 너무 큽니다. 넓이는 {limit} 보다 클 수 없습니다.',
'The image "{file}" is too small. The height cannot be smaller than {limit, number} {limit, plural, one{pixel} other{pixels}}.' => '이미지 "{file}"가 너무 작습니다. 높이는 {limit} 보다 작을 수 없습니다.',
'The image "{file}" is too small. The width cannot be smaller than {limit, number} {limit, plural, one{pixel} other{pixels}}.' => '이미지 "{file}"가 너무 작습니다. 넒이는 {limit} 보다 작을 수 없습니다.',
'The verification code is incorrect.' => '확인코드가 올바르지않습니다.',
'Total <b>{count, number}</b> {count, plural, one{item} other{items}}.' => '모두 {count} 개',
'Unable to verify your data submission.' => '데이터 전송을 확인하지 못했습니다.',
'Unknown command "{command}".' => '알 수 없는 명령 "{command}".',
'Unknown option: --{name}' => '알 수 없는 옵션: --{name}',
'Update' => '갱신',
'View' => '보기',
'Yes' => '예',
'You are not allowed to perform this action.' => '이 작업의 실행을 허가받지못하였습니다.',
'You can upload at most {limit, number} {limit, plural, one{file} other{files}}.' => '최대 {limit} 개의 파일을 업로드할 수 있습니다.',
'the input value' => '입력 값',
'{attribute} "{value}" has already been taken.' => '{attribute}에 "{value}"이 이미 사용되고 있습니다.',
'{attribute} cannot be blank.' => '{attribute}는 공백일 수 없습니다.',
'{attribute} is invalid.' => '{attribute}가 잘못되었습니다.',
'{attribute} is not a valid URL.' => '{attribute}는 올바른 URL 형식이 아닙니다.',
'{attribute} is not a valid email address.' => '{attribute}는 올바른 이메일 주소 형식이 아닙니다.',
'{attribute} must be "{requiredValue}".' => '{attribute}는 {value}이어야 합니다.',
'{attribute} must be a number.' => '{attribute}는 반드시 숫자이어야 합니다.',
'{attribute} must be a string.' => '{attribute}는 반드시 문자이어야 합니다.',
'{attribute} must be an integer.' => '{attribute}는 반드시 정수이어야 합니다.',
'{attribute} must be either "{true}" or "{false}".' => '{attribute}는 {true} 또는 {false} 이어야 합니다.',
'{attribute} must be greater than "{compareValue}".' => '{attribute}는 "{compareValue}" 보다 커야 합니다.',
'{attribute} must be greater than or equal to "{compareValue}".' => '{attribute}는 "{compareValue}" 보다 크거나 같아야 합니다.',
'{attribute} must be less than "{compareValue}".' => '{attribute}는 "{compareValue}" 보다 작아야 합니다.',
'{attribute} must be less than or equal to "{compareValue}".' => '{attribute}는 "{compareValue}" 보다 작거나 같아야 합니다.',
'{attribute} must be no greater than {max}.' => '{attribute}는 "{compareValue}" 보다 클 수 없습니다.',
'{attribute} must be no less than {min}.' => '{attribute}는 "{compareValue}" 보다 작을 수 없습니다.',
'{attribute} must be repeated exactly.' => '{attribute}는 정확하게 반복합니다.',
'{attribute} must not be equal to "{compareValue}".' => '{attribute}는 "{compareValue}"와 같을 수 없습니다.',
'{attribute} should contain at least {min, number} {min, plural, one{character} other{characters}}.' => '{attribute}는 최소 {min}자 이어야합니다.',
'{attribute} should contain at most {max, number} {max, plural, one{character} other{characters}}.' => '{attribute}는 최대 {max}자 이어야합니다.',
'{attribute} should contain {length, number} {length, plural, one{character} other{characters}}.' => '{attribute}는 {length}자 이어야합니다.',
];
| softdevelop/yiirestful-ember | vendor/yiisoft/yii2/messages/ko/yii.php | PHP | bsd-3-clause | 7,102 |
// Copyright 2004-present Facebook. All Rights Reserved.
#include <fb/CpuCapabilities.h>
#include <cpu-features.h>
#include <fb/Environment.h>
#include <glog/logging.h>
#include <jni/Registration.h>
namespace facebook { namespace jni {
// =========================================
// returns true if this device supports NEON calls, false otherwise
jboolean nativeDeviceSupportsNeon(JNIEnv* env, jobject obj) {
if (android_getCpuFamily() != ANDROID_CPU_FAMILY_ARM) {
VLOG(2) << "NEON disabled, not an ARM CPU";
return false;
}
uint64_t cpufeatures = android_getCpuFeatures();
if ((cpufeatures & ANDROID_CPU_ARM_FEATURE_ARMv7) == 0) {
VLOG(2) << "NEON disabled, not an ARMv7 CPU";
return false;
}
if ((cpufeatures & ANDROID_CPU_ARM_FEATURE_NEON) == 0) {
VLOG(2) << "NEON disabled, not supported";
return false;
}
VLOG(2) << "NEON supported and enabled";
return true;
}
// =========================================
// returns true if this device supports VFP_FP16, false otherwise.
jboolean nativeDeviceSupportsVFPFP16(JNIEnv *env, jobject obj) {
uint64_t cpufeatures = android_getCpuFeatures();
if ((cpufeatures & ANDROID_CPU_ARM_FEATURE_VFP_FP16) == 0) {
VLOG(2) << "VPF_FP16 disabled, not supported";
return false;
}
VLOG(2) << "VFP_FP16 supported and enabled";
return true;
}
// =========================================
// returns true if this device is x86 based, false otherwise
jboolean nativeDeviceSupportsX86(JNIEnv* env, jobject obj) {
return (android_getCpuFamily() == ANDROID_CPU_FAMILY_X86);
}
// =========================================
// register native methods
void initialize_cpucapabilities() {
facebook::jni::registerNatives(
Environment::current(),
"com/facebook/jni/CpuCapabilitiesJni",
{
{ "nativeDeviceSupportsNeon",
"()Z",
(void*) nativeDeviceSupportsNeon },
{ "nativeDeviceSupportsVFPFP16",
"()Z",
(void*) nativeDeviceSupportsVFPFP16 },
{ "nativeDeviceSupportsX86",
"()Z",
(void*) nativeDeviceSupportsX86 },
}
);
}
} } // namespace facebook::jni
| formatlos/react-native | ReactAndroid/src/main/jni/first-party/fb/jni/android/CpuCapabilities.cpp | C++ | bsd-3-clause | 2,154 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<!-- testcase: th_valign_top.html -->
<!-- description: TH element, VALIGN attribute, TOP value -->
<!-- Author: Chris Petersen Date: 8/7/98 -->
<!-- Modified: Christine Dreckman: 3/18/99 -->
<!-- ***** BEGIN LICENSE BLOCK *****
- Version: MPL 1.1/GPL 2.0/LGPL 2.1
-
- The contents of this file are subject to the Mozilla Public License Version
- 1.1 (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
- http://www.mozilla.org/MPL/
-
- Software distributed under the License is distributed on an "AS IS" basis,
- WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
- for the specific language governing rights and limitations under the
- License.
-
- The Original Code is table layout tests.
-
- The Initial Developer of the Original Code is
- Netscape Communications Corp.
- Portions created by the Initial Developer are Copyright (C) 1998
- the Initial Developer. All Rights Reserved.
-
- Contributor(s):
-
- Alternatively, the contents of this file may be used under the terms of
- either the GNU General Public License Version 2 or later (the "GPL"), or
- the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
- in which case the provisions of the GPL or the LGPL are applicable instead
- of those above. If you wish to allow use of your version of this file only
- under the terms of either the GPL or the LGPL, and not to allow others to
- use your version of this file under the terms of the MPL, indicate your
- decision by deleting the provisions above and replace them with the notice
- and other provisions required by the LGPL or the GPL. If you do not delete
- the provisions above, a recipient may use your version of this file under
- the terms of any one of the MPL, the GPL or the LGPL.
-
- ***** END LICENSE BLOCK ***** -->
<!-- Purpose: To test the TH element with the VALIGN attribute, assigning a value of 'top'-->
<!-- Expected result: There is one row and 3 columns. The cell in the first column contains an image. The text in the second and third column cells should be vertically aligned to the top -->
<title>th_align_top</title>
</head>
<body>
TH VALIGN=TOP
<table border=1>
<tr>
<th><img SRC="../images/raptor.jpg" alt=image height=185 width=300></td>
<th valign=top>This text should be vertically aligned to the top</th>
<th valign=top>This text should be vertically aligned to the top</th>
</tr>
</table>
</body>
</html>
| smishenk/blink-crosswalk | LayoutTests/tables/mozilla/marvin/th_valign_top.html | HTML | bsd-3-clause | 2,695 |
// (c) ammap.com | SVG (in JSON format) map of Hungary - Low
// areas: {id:"HU-BK"},{id:"HU-BA"},{id:"HU-BE"},{id:"HU-BC"},{id:"HU-BZ"},{id:"HU-BU"},{id:"HU-CS"},{id:"HU-DE"},{id:"HU-DU"},{id:"HU-EG"},{id:"HU-FE"},{id:"HU-GY"},{id:"HU-GS"},{id:"HU-HB"},{id:"HU-HE"},{id:"HU-HV"},{id:"HU-JN"},{id:"HU-KV"},{id:"HU-KM"},{id:"HU-KE"},{id:"HU-MI"},{id:"HU-NK"},{id:"HU-NO"},{id:"HU-NY"},{id:"HU-PS"},{id:"HU-PE"},{id:"HU-SO"},{id:"HU-SN"},{id:"HU-SZ"},{id:"HU-SD"},{id:"HU-SF"},{id:"HU-SK"},{id:"HU-SH"},{id:"HU-TB"},{id:"HU-TO"},{id:"HU-VA"},{id:"HU-VE"},{id:"HU-VM"},{id:"HU-ZA"},{id:"HU-ZE"}
AmCharts.maps.hungaryLow={
"svg": {
"defs": {
"amcharts:ammap": {
"projection":"mercator",
"leftLongitude":"16.113634",
"topLatitude":"48.586316",
"rightLongitude":"22.897693",
"bottomLatitude":"45.736783"
}
},
"g":{
"path":[
{
"id":"HU-BK",
"title":"Békéscsaba",
"d":"M257.38,208.68L258.1,206.83L256.41,203.96L262.41,205.31L266.46,207.94L275.03,199.65L278.34,199.78L279.15,201.03L281.18,196.37L284.6,194.4L291.61,200.09L286.96,207.67L290.67,212.95L293.26,208.12L298.9,204.03L303.29,205.31L305.96,196.55L311.04,198.44L313.25,196.39L318.3,208.29L322.34,212.86L322.34,212.86L319.12,214.2L311.55,211.9L307.93,216.77L306.93,215.72L304.39,218.17L309.45,224.35L309.99,228.21L312.03,228.23L315.48,230.84L318.66,234.63L318.28,236.36L322.17,236.12L323.88,233.05L328.91,231.88L329.93,229.67L333.32,232.63L337.69,226.64L335.33,219.88L335.33,219.88L339.39,212.96L349.1,217.39L350.39,212.57L356.79,210.01L359.08,211.51L359.08,211.51L363.26,214.65L362.74,217.51L360.28,218.67L360.29,220.08L363.57,220.52L365.11,223.35L358.56,228.65L355.95,228.36L354.82,230.89L353.88,230.01L350.35,231.92L351.85,233.94L354,233.52L354.34,234.65L351.21,235.22L351.09,237.4L353.76,239.16L353.54,236.12L354.6,235.61L356.17,238.2L356.17,238.2L347.71,248.22L351.62,252.44L348.85,260.14L350.06,261.8L350.06,266.12L345.35,271.62L340.65,267.72L330.64,274.02L333.28,277.3L336.9,276.62L341.01,280.62L341.54,283.14L340.02,285.36L341.6,288.51L339.77,293.03L337.66,294.82L334.22,292.5L327.42,297.75L325.42,296.2L319.47,298.1L322.66,303.55L317.73,308.85L323.21,318.8L323.21,318.8L321.96,319.66L320.2,318.45L317.56,321.04L311.41,320.05L310.49,322L305.99,324.43L307.8,327.66L302.42,330.77L302.46,332.63L297.93,337.14L294.83,338.47L293.35,336.48L286,341.15L287.25,344.55L286.23,343.48L273.81,343.51L272.73,338.47L270.07,338.01L266.4,343.08L267.66,347.69L261.65,347.81L260,349.86L261.18,352.9L252.01,351.49L249.55,353.94L248.09,353.39L248.46,354.7L243.54,354.92L243.54,354.92L242.14,353.67L242.83,352.01L247.16,350.51L244.85,348.42L248.37,340.83L246.4,337.92L248.58,337.05L246.07,335.79L245.19,331.36L246.44,329.97L243.74,328.85L243.74,328.85L243.65,327.44L244.89,328L245.68,325.84L242.06,324.76L242.14,322.47L244.49,321.02L244.77,324.35L246.77,318.73L248.52,318.13L248.73,314.62L245.41,316.93L244.24,316.13L248.96,312.18L248.12,308.21L252.3,309.25L253.29,303.34L251.17,299.76L249.96,291.52L253.21,284.62L253.25,280.83L250.87,275.17L250.62,269.58L247.69,263.5L249.77,260.27L257.36,257.67L260.61,252.71L257.81,242.17L253.6,236.56L253.44,231.14L253.44,231.14L256.41,223.09L256.41,223.09L256.74,212.01L256.74,212.01z"
},
{
"id":"HU-BA",
"title":"Baranya",
"d":"M174.87,304.5l2.1,0.76l2.27,-1.21l1.94,2.54l0.68,-0.94l-1.46,-0.66l-0.09,-2.97l1.75,-0.86l1.56,1l4.53,-2.97l-1.42,-7.47l3.76,-1.6l3.68,0.84l4.25,-2.01l2.83,2.49l0.47,4.86l3.28,1.69l-1.05,7.02l3.52,0.4l0.56,1.5l-1.75,4.83l-3.61,1.5l0.79,1.52l8.66,-4.84l1.28,-1.86l-0.13,-3.97l2.6,1.33l1.46,2.56l0.98,-0.99l0.53,0.81l-0.86,5.52l3.83,1.16l-0.69,1.31l2.17,3.72l1.94,-1.01l6.8,8.19l0.7,-0.64l5.07,3.04l5.93,-0.22l0,0l2.7,1.12l-1.25,1.39l0.88,4.43l2.51,1.26l-2.18,0.87l1.98,2.92l-3.53,7.59l2.32,2.1l-4.33,1.5l-0.69,1.66l1.4,1.25l0,0l-0.39,3.84l-1.3,0.18l-8.02,-5.08l-3.99,0.12l0.14,2.56l-1.9,1.1l1.11,1.64l-1.36,1.03l-0.69,-1.12l-1.44,2.92l0.7,1.79l-4.43,3.18l0.01,1.83l-1.42,-0.35l-3.33,2.58l-2.75,-1.43l-0.84,3.65l-3.2,0.54l0.13,3.15l-3.66,-0.42l-3.84,-4.21l-2.4,3.42l-3.68,-1.8l-4.77,-0.17l-1.28,-2.19l-3.9,-1.11L185.42,372l-4.2,-1.66l-1.69,2.63l-1.94,0.49l-7.61,-3.78l-6.26,1.34l-2.07,-0.82l-4.02,3.37l-3.37,-5.7l-5.99,-0.28l-1.72,-2.32l-6.27,-0.66l-1.57,-1.65l0,0l1.59,-0.52l1.47,-2.78l0.81,1.85l0.72,-1.07l2.17,0.39l0.64,-1.73l-0.13,-2.73l-3.14,-3.48l0.04,-1.84l-2.84,-0.1l-0.72,-1.6l0.14,2.21l-1.44,-0.15l-1.78,-6.37l2.72,-0.78l-2.29,-6.85l4.03,-2.35l0.53,-3.67l-1.36,-1.49l1.86,-0.99l0.16,-6.19l3.46,-6.48l-0.91,-1.88l1.75,-1.33l1.25,3.55l1.81,0.6l2.26,-3.34l4.54,2.26l2.98,-2.08l3.67,0.27l1.11,-0.96l-0.35,-3.6l2.18,-6.25L174.87,304.5zM188.27,324.91L188.27,324.91l-3.12,2.18l0,0l0.66,2.23l-3.79,0.12l1.69,4.36l-0.52,2.63l3.66,2.11l2.98,3.69l0,0l5.16,-2.02l0.79,-4.37l0,0l3.1,-4.58l3.83,0.58l0.77,-1.23l-1.41,-3.94l0,0l-3.12,-4.11l-6.89,3.35L188.27,324.91z"
},
{
"id":"HU-BE",
"title":" Békés",
"d":"M438.62,182l3.93,0.69l2.87,4.46l1.19,-2.09l5.66,4.47l6.5,0.86l2.71,2.34l6.55,-0.34l-0.13,4.24l-1.37,1.04l0.62,3.21l-5.23,3.9l0.88,3.08l-1.2,1.86l11.27,5.59l7.53,1.03l-1.53,3.97l1.99,-1.84l3.33,1.92l1.58,-1.75l6.15,-0.94l0.1,-5.38l3.17,0.55l2.35,-3.22l0.94,-0.55l0.25,1.31l1.49,-1.07l0,0l1.76,0.77l0.91,2.26l-1.9,3.84l1.24,1.09l-3.9,3.98l-3.41,0.79l1.34,5.45l-1.2,2.87l-7.21,3.59l-0.12,4.75l-3.2,4.62l3.8,3.56l0.17,2.48l-3.2,4.51l-1.88,-1.25l-3.62,0.2l2.15,4.09l-3.19,2.17l-0.89,3.04l-3.9,-1.92l-4.79,2.57l-1.02,3.52l1.56,1.14l-2.59,4.74l-1.43,0.52l-1.33,5.32l1.2,3.17l1.99,0.16l1.45,4.45l-2.08,3.43l0.5,1.11l-6.48,-0.89l-1.52,1.49l-0.69,7.26l-2.2,2.28l0.58,3.14l-6.02,0.56l-1.06,4.93l-3.53,2.42l-2.45,-0.74l-1.16,-2.18l-6.47,0.31l-0.61,-1.79l-1.77,0.27l-0.73,1.77l-3.93,-3.25l-8.71,1.6l0,0l-2.44,-1.87l0.86,-7.97l-1.75,-4.43l-4.2,0.65l-0.91,3.7l-5.29,0.05l-4.2,-2.08l-2.66,-3.44l0,0l3.09,-1.83l-0.07,-4.29l0,0v-1.74l2.22,-0.7l0.82,-9.03l-3.9,-3.71l-0.12,-11.4l0.63,-4.68l1.23,-0.03l-0.96,-5.95l1.47,-4.37l-2.99,-2.34l-5.13,0.05l-4.94,-4.81l-2.73,1.08l0,0l-1.37,-7.23l4.53,-5.05l5.03,0.21l2.6,-1.13l0.75,-1.78l4.23,-0.1l3.97,2.32l5.57,-2.15l2.13,-5.12l-2.08,-0.32l1.98,-0.26l-0.27,-1.96l-1.25,-0.45l0.02,-7.2l1.48,0.13l2.8,-2.76l0.23,2.18l4.44,-0.03l0.21,-1.61l3.16,-2.55l1.52,0.58l-1.84,-5.88l0.24,-1.31l2.01,-0.46l-1.77,-3.58l8.89,-5.15L438.62,182zM446.26,247L446.26,247l-7.46,2.66l-2.21,-1.51l-3.7,3.32l2.11,2.57l1.43,-0.03l2.74,4.19l-2.15,5.29l15.11,-4.14l3.22,-3.38l2.16,0.85l2.29,-1.39l-0.28,-2.62l-2.42,-2.89l-2.18,-0.1l-1.47,-1.64l-5.73,1.97L446.26,247z"
},
{
"id":"HU-BC",
"title":"Békéscsaba",
"d":"M446.76,247.83L447.71,250.16L447.71,250.16L453.44,248.19L454.92,249.83L457.1,249.94L459.52,252.82L459.8,255.45L457.5,256.83L455.35,255.98L452.13,259.37L437.02,263.5L439.17,258.21L436.43,254.02L435,254.04L432.89,251.47L436.59,248.15L438.8,249.66L446.26,247L446.26,247z"
},
{
"id":"HU-BZ",
"title":"Borsod-Abaúj-Zemplén",
"d":"M480.64,0.01L487.44,4.89L489.87,10.6L496.21,10.29L500.75,25.73L504.44,27.65L506.54,32.16L515.24,34.49L516.58,30.05L518.27,30.06L518.93,31.51L521.02,30.89L521.13,29.3L521.41,30.28L521.9,29.33L524.61,30.47L526.53,28.18L529.9,28.49L533.73,26.29L536.26,28.33L538.1,27.11L539.03,29.04L539.87,27.8L541.9,28.2L541.9,28.2L542.38,30.7L540.61,30.76L542.28,31.86L538.5,35.46L539.36,37.76L537.14,37.49L537.19,38.88L535.63,37.95L536.72,39.13L536.03,40.1L534.22,38.07L534.31,39.26L532.29,39.29L533.33,37.37L532.2,37.52L529.53,39.95L529.38,42.26L528.42,41.86L526.17,44.49L525.51,43.82L523.77,47.05L521.67,46.18L517.63,46.98L516.72,49.11L515.7,46.63L515.3,48L514.21,46.91L513.17,50.35L511.63,51.89L510.46,51.26L508.61,53.58L508.69,51.83L506.23,52.04L505.9,53.62L500.87,53.53L496.05,52.97L492.9,51.12L487.39,54.28L487.75,55.6L484.04,54.98L483.21,56.83L480.7,55.24L478.13,62.8L481.38,67.02L479.81,67.36L480.19,68.8L482.46,69.53L480.23,70.36L480.14,72.86L478.02,72.18L477.49,74.76L472.66,74.77L471.09,76.33L467.57,75.27L467.46,74.01L464.75,74.09L463.69,71.87L460.96,74.01L460.52,76.2L456.09,75.74L455.72,73.31L452.7,72.93L447.86,78.57L451.75,84.45L451.75,84.45L450.77,88.51L449.04,89.97L452.06,90.95L448.29,93.91L448.3,97.46L445.8,99L447.9,103.45L444.67,112.46L440.67,112.29L440.7,116.57L436.21,117.5L434.92,120.35L431.93,121.47L430.44,119.74L430.59,122.3L431.95,122.68L427.37,123.1L429.66,126.3L429.08,127.12L425.28,123.73L425.28,123.73L422.24,121.97L419.48,124.01L420.09,125.62L420.09,125.62L414.21,120.98L408.27,121.26L403.01,118.09L402.19,117.01L404.26,114.23L396.11,105.93L396.08,97.76L392.58,96.21L391,93.45L391,93.45L393.21,91.32L393.21,91.32L395.76,91.92L394.99,90.66L397.39,88.87L391.2,83.43L394.78,76.2L393.79,71.45L396.14,70.09L396.14,70.09L407.29,69.22L410.97,72.19L414.27,73L415.75,76.12L419.27,74.26L423.74,74.17L426.93,72.04L428.06,68.38L426.86,67.86L427.2,63.69L425.65,61.11L421.47,59.88L419.2,60.5L416.85,58.09L415.84,59.25L409.78,58.91L404.76,61.97L397.67,61.71L393.84,63.63L393.84,63.63L391.21,58.99L386.95,58.59L385.58,59.15L385.91,60.86L383.55,63.69L382.9,66.87L379.27,62.75L376.51,62.8L375.78,66.15L372.65,67.22L366.01,63.99L365.29,61.07L358.89,60L358.89,60L355.15,56.59L355.15,56.59L357.72,54.59L356.81,53.73L357.59,52.77L362.52,49.19L362.88,45.07L369.37,45.36L368.97,44.06L371.27,43.88L371.17,41.86L372.4,41.42L376.49,43.95L380.09,42.49L381.15,38.87L387.76,29.82L388.4,22.49L396.57,13.13L396.07,7.6L397.53,6.65L399.13,7.94L400.16,5.68L403.6,7.01L410.06,3.44L426.98,0.29L426.38,1.35L428.87,4.64L433.53,3.79L437.1,8.58L439.29,9.28L442.21,7.26L446.82,8.06L449.37,9.31L449.94,11.88L451.82,12.76L454.42,9.43L457.08,9.15L460.83,6.54L468.5,8.54L469.88,3.32L478.39,3.62L479.09,0.86z"
},
{
"id":"HU-BU",
"title":"Budapest",
"d":"M270.25,131.44L274.37,134.88L273.59,135.86L276.19,137.6L275.02,138.28L275.02,138.28L277.15,140.52L279.36,140.8L279.36,140.8L280.36,141.85L282.58,141.24L284.27,145.04L289.23,144.13L288.84,147.12L290.63,151.02L287.63,151.93L285.79,154.72L284.4,154.44L279.03,160.08L276.63,164.66L273.02,166.2L269.19,162.32L269.82,161.29L267.88,158.9L263.24,161.82L262.23,160.65L256.55,162.76L256.52,156.86L258.24,155.27L257.7,152.66L258.78,151.32L257.05,148.48L254.59,147.28L255.47,146.28L254.39,145.25L255.19,143.66L253.75,143.19L254.58,140.38L253.71,140.4L255,139.36L254,136.58L263.46,134.57L262.67,132.22L264.21,131.44L267.39,131.85L267.07,134.5L269.05,131.46L269.05,131.46z"
},
{
"id":"HU-CS",
"title":"Csongrád",
"d":"M358.93,320.7l2.06,-3.99l1.95,0.59l3.55,-1.49l5.35,11.22l0,0l-4.87,-4.5l-3.73,1.84l-2.83,-2.12l-0.46,-1.96L358.93,320.7zM400.03,292.12l2.66,3.44l4.21,2.09l5.29,-0.05l0.91,-3.7l4.21,-0.65l1.75,4.43l-0.86,7.97l2.44,1.87l0,0l-2.27,3.54l0.83,5.53l-2.75,-0.32l-1.4,5.5l-3.31,2.84l-1.9,-0.95l-1.51,3.17l-8.52,-6.87l-4.11,-1.68l-0.41,2.87l-2.81,3.17l-7.51,-1.8l-1.23,1.18l-1.17,-2.51l-5.95,3.09l-3,3.8l-0.53,-0.66l0,0l1.41,-0.71l1.3,-8.8l-5.34,0.13l-1,-5.2l8.11,0.47l-0.12,-8.49l0,0l8.19,-1.04L400.03,292.12zM388.64,238.37l2.73,-1.08l4.95,4.81l5.13,-0.05l2.99,2.34l-1.47,4.37l0.96,5.95l-1.23,0.03l-0.63,4.68l0.12,11.4l3.9,3.71l-0.82,9.03l-2.22,0.71v1.74l0,0l-6.36,-0.13l-4.8,-6.7l-1.56,0.21l-1.46,-2.42l-3.96,2.18l-1.29,-2.27l-6.06,0.24l0.57,2.88l-3.99,0.95l1.52,2.7l-4.01,3.97l-2.03,-0.81l-0.04,-4.12l-1.67,0.82l-1.55,7.65l0,0l0,0l0,0l-2.18,0.84l0.11,3.86l2.4,1.79l-0.97,2.61l-8,-2.08l-0.49,5.78l-4.54,-1.67l-4.53,4.21l3.24,2.64l5.98,1.98l-2.15,3.56l1.53,4.47l-3.93,1.91l0,0l-8.33,-0.65l-10.31,6.14l-5.18,-2.35l-5.77,-5.36l0,0l-5.49,-9.96l4.94,-5.3l-3.19,-5.44l5.96,-1.9l1.99,1.55l6.8,-5.25l3.44,2.32l2.11,-1.79l1.83,-4.53l-1.58,-3.14l1.52,-2.22l-0.53,-2.52l-4.11,-4l-3.62,0.68l-2.64,-3.28l10.01,-6.3l4.71,3.9l4.7,-5.49l0.01,-4.32l-1.22,-1.66l2.77,-7.69l-3.91,-4.22l8.46,-10.02l0,0l2.61,5.5l1.53,-0.55l0.34,-2.4l5.67,4.18l5.32,-5.95l2.12,0.56l3.2,3.49l3.27,0.85l1.91,-3.11l4.68,-0.12L388.64,238.37z"
},
{
"id":"HU-DE",
"title":"Debrecen",
"d":"M480.27,142.57L480.09,139.84L482.97,132.84L491.71,131.35L498.13,128.15L496.92,132.41L500,129.33L506.61,131.05L504.57,137.62L508.93,138.16L514.67,134.16L519.22,137.96L518.11,144.99L514.76,151.09L512.6,150.81L509.13,154.07L502.12,156.37L500.92,152.98L499.36,152.29L495.75,152.59L490.89,155.96L488.35,143.86z"
},
{
"id":"HU-DU",
"title":"Dunaújváros",
"d":"M256.41,223.09L249.66,224.01L243.19,214.24L247.67,212.37L256.74,212.01L256.74,212.01z"
},
{
"id":"HU-EG",
"title":"Eger",
"d":"M391,93.45L388.65,94L388.16,97.97L382.27,98.64L382.56,96.87L379.18,93.17L380.05,92.22L377.86,83.14L380.37,78.18L385.24,80.61L384.66,83.26L386.67,87.13L389.27,88.82L391,87.42L392.35,88.19L393.21,91.32L393.21,91.32z"
},
{
"id":"HU-FE",
"title":" Fejér",
"d":"M232.29,135.76l0.54,6.16l2.94,5.33l2.21,0.04l2.98,4.5l0.33,3.99l-2.82,3.3l9.44,10.97l-0.24,2.15l1.73,0.41l0.16,2.94l3.56,0.72l-4.15,16.17l2.36,10.18l6.05,6.07l0,0l-0.64,3.34l0,0l-9.07,0.36l-4.48,1.87l6.47,9.76l6.75,-0.92l0,0l-2.97,8.06l0,0l-5.71,1.3l1.42,1.32l-1.25,2.19l-5.99,4.26l-0.1,2.38l-4.26,0.47l-2.72,2.09l1.26,3.03l-7.15,5.13l-2.14,-0.26l-1.28,-7.27l-3.68,-1.64l-1.63,-3.19l-4.48,2.48l0.55,2.31l-4.13,0.72l-3.59,-0.91l-0.38,-5.49l-1.36,-1.97l-0.18,4.58l-2.17,-2.72l-1.41,1.72l-4.54,-1.72l-0.81,-3.61l-5.12,4.56l-3.53,0.72l0,0l-1.29,-5.44l1.06,-2.12l-0.88,-3.73l0.96,-0.49l-1.83,-0.64l2.3,-1.96l-1.91,-5.69l-2.79,-3.65l0,0l6.66,-7.38l2.37,-0.71l-2.36,-0.29l-2.86,-7.45l2.75,-2.18l-2,-8.16l1.08,-7.81l-4.4,-3.14l-1.57,-3.43l-4.57,2.17l-2.86,-4.19l-1.6,0.41l-0.89,-3.62l1.66,-1.98l-1.93,-0.29l-0.72,-1.67l0,0l1.55,-2.19l2.97,-0.94l-0.67,-1.86l2.5,-3.65l0.78,-6.06l2.11,-1l1.27,1.65l2.66,-0.41l1.07,-1.21l-0.59,-3.22l4.92,2.4l0.5,3.05l5.81,4.65l1.61,-1.94l4.15,-0.36l-2.31,-2.53l0.42,-1.12l1.68,-1.94l1.66,1.3l3.04,-4.62l2.25,-1.04l0,0l3.29,-2.6l-1.16,-1.85l1.6,-0.31l-0.64,-2.93l3.68,-0.68l0,0l4.39,-2.53l3.66,1.32L232.29,135.76zM208.95,174.85l-1.8,0.92l0,0l-0.42,2.63l-7.5,7.9l4.02,7.17l1.68,0.89l0.32,5.83l5.35,-2.06l1.07,1.39l3.41,-4.11l4.67,-1.36l-1.85,-4.39l-1.89,0.12l1.1,-2.83l-1.89,-3.51l1.55,-2.16l-2.74,-3.1l-2.99,0.2L208.95,174.85z"
},
{
"id":"HU-GY",
"title":"Győr",
"d":"M135.48,117.76L140.19,114.51L142.64,116.38L149.02,115.67L152.77,118.05L154.69,123.34L142.31,129.89L139.42,128.99L136.4,134.3L130.56,133.81L126.93,132L126.27,129.51L130.63,128.49L131.55,122.25z"
},
{
"id":"HU-GS",
"title":"Győr-Moson-Sopron",
"d":"M102.16,76.95l1.85,2.8l6.11,0.32l8.44,9.11l2.62,5.65l6.7,2.84l3.07,6l3.98,-0.56l9.29,8.74l6.41,2.29l6.94,-0.88l3.13,0.9l0,0l0.84,5.14l-1.44,8.58l3.85,2.71l-2.38,7.62l2.9,1.57l-2.54,0.92l-2.34,-1l2.48,6.89l-2.04,0.87l0.14,1.76l-1.41,-0.03l1.17,1.93l-1.39,0.83l0,0l-3.61,-4.67l-1.87,2.49l-1.33,-2.36l-3.75,4.64l-2.49,-2.29l0.29,2.71l-2.35,0.43l-0.19,-2.87l-2.53,-0.11l-3.01,2.69l-1.86,-1.76l-1.44,1.13l-3.27,-4.1l-2.86,2.72l-8.69,-2.87l-1.82,1.46l-3.09,-0.78l-1.86,5.43l-8.99,1.73l-3.27,-1.16l-0.82,0.97l-2.24,-1.69l-1.89,1.58l0,0l-2.63,-0.74l-1.75,2.73l-6.83,3.07l1.79,-6.15l-1.51,-2.67l-7.96,5.88l-1.94,2.78l-2.99,-3.14l-2.44,0.69l-3.14,-4.65l-3.46,1.88l-0.56,-1.17l-1.4,0.94l-0.54,-0.89l-6.19,4.19l-3.28,-1.12l-2.86,-3.48l0,0l2.14,-3.69l-1.58,-3.45l3.34,-1.38l2.37,-3.93l-4.64,-3.75l1.07,-1.44l-0.38,-3.49l-1.65,-2.35l-7.52,-0.21l0,0l4.19,-2.23l6.49,-1.19l2.03,1.06l3.29,-5.7l0,0l7.33,0.2l3.48,-5.09l0.54,4.14l1.04,0.2l18.71,-2.66l-1.82,-2.54l-1.66,-8.78l1.99,-2.09l-2.37,-2.61l0.42,-1.34l-3.73,-2.84l0.65,-1.22l6.03,-0.8l1.44,-2.66l-0.38,-1.68l1.6,-2.6l-1.97,-1.24l2.18,-3.38l-1.93,-1.42l6.92,-5.54L102.16,76.95zM131.55,122.25l-0.92,6.24l-4.55,1.95l0.85,1.56l7.3,2.64l2.17,-0.33l3.02,-5.31l2.89,0.9l12.39,-6.54l-1.92,-5.29l-3.75,-2.38l-6.38,0.71l-2.44,-1.87l-6.07,5.07L131.55,122.25z"
},
{
"id":"HU-HB",
"title":"Hajdú-Bihar",
"d":"M451.75,84.45l6.57,0.52l5.9,4.28l1.06,2.97l4.42,-2.13l15.86,-0.66l1.9,-2.35l2.27,0.89l0,0l1.98,0.83l-0.81,1.72l0,0l0.84,3.84l-2.02,12.93l5.23,2.5l3.4,5.98l6.1,-0.41l1.21,3.28l4.76,0.31l-0.43,2.17l5.85,2.86l4.78,-4.25l0.3,-3.5l3.28,-0.94l5.52,3.86l-0.46,3.66l2.61,1.56l-0.69,2.62l1.6,3.06l4.9,-6.65l2.58,1.62l2.39,8.24l0,0l-2.98,4.92l-3.67,1.49l1.35,1.63l-0.83,1.08l-1.43,-1.37l-2.23,3.05l-1.23,5.34l2.23,3.34l0.2,5.17l-2.22,4.7l-6.31,0.45l-5.48,11.35l0.79,1.9l-3.28,4.81l0.62,6.53l-3.71,2.16l-2.32,8.53l-5.9,1.19l-3.99,6.93l-2.92,0.59l0.86,2.3l0,0l-1.49,1.07l-0.25,-1.31l-0.94,0.55l-2.35,3.22l-3.17,-0.55l-0.1,5.38l-6.15,0.94l-1.58,1.75l-3.33,-1.92l-1.99,1.85l1.53,-3.97l-7.52,-1.03l-11.27,-5.59l1.2,-1.86l-0.88,-3.08l5.23,-3.9l-0.62,-3.21l1.37,-1.04l0.13,-4.24l-6.55,0.34l-2.71,-2.34l-6.5,-0.86l-5.66,-4.47l-1.19,2.09l-2.87,-4.46l-3.92,-0.69l0,0l3.98,-2.85l1.05,-12.03l-3.45,-17.12l1.06,-2.46l-1.52,-2.3l0.1,-7.87l-4.14,-3.92l-4.78,1.92l-4.4,-2l-1.71,-5.63l0.49,-3.99l0,0l3.8,3.39l0.58,-0.83l-2.29,-3.19l4.58,-0.43l-1.36,-0.37l-0.14,-2.57l1.49,1.74l2.99,-1.12l1.29,-2.85l4.49,-0.94l-0.04,-4.28l4.01,0.17l3.23,-9.01l-2.1,-4.45l2.5,-1.54l-0.01,-3.55l3.76,-2.95l-3.01,-0.98l1.73,-1.46L451.75,84.45zM488.35,143.86l2.54,12.1l4.85,-3.36l3.62,-0.31l1.56,0.69l1.2,3.39l7,-2.3l3.48,-3.26l2.16,0.28l3.36,-6.1l1.11,-7.03l-4.56,-3.8l-5.74,4l-4.36,-0.53l2.04,-6.58l-6.6,-1.72l-3.09,3.08l1.21,-4.26l-6.42,3.2l-8.74,1.48l-3.18,8.68l0.48,1.05l4.94,0.79L488.35,143.86z"
},
{
"id":"HU-HE",
"title":"Heves",
"d":"M358.89,60L365.29,61.07L366.01,63.99L372.65,67.22L375.78,66.15L376.51,62.8L379.27,62.75L382.9,66.87L383.55,63.69L385.91,60.86L385.58,59.15L386.95,58.59L391.21,58.99L393.84,63.63L393.84,63.63L394.01,66.9L396.14,70.09L396.14,70.09L393.79,71.45L394.78,76.2L391.2,83.43L397.39,88.87L394.99,90.66L395.76,91.92L393.21,91.32L393.21,91.32L392.35,88.19L391,87.42L389.27,88.82L386.67,87.13L384.66,83.26L385.24,80.61L380.37,78.18L377.86,83.14L380.05,92.22L379.18,93.17L382.56,96.87L382.27,98.64L388.16,97.97L388.65,94L391,93.45L391,93.45L392.58,96.21L396.08,97.76L396.11,105.93L404.26,114.23L402.19,117.01L403.01,118.09L408.27,121.26L414.21,120.98L420.09,125.62L420.09,125.62L419.01,127.31L415.08,128.5L415.19,131.78L413.47,132.97L414,136.25L402.59,144.39L397.57,146.14L395.81,150.57L392.07,150.2L392.87,147.32L390,148.4L390.62,153.99L386.74,156.54L384.67,155.88L384.88,153.32L382.18,154.29L379.56,152.37L376.61,148.09L377.86,145.13L376.58,140.97L371.23,137.93L369.17,131.77L359.65,134.24L362.55,137.49L360.51,139.06L352.48,135.45L351.18,133.69L352.27,130.74L350.21,123.09L348.03,122.61L342.87,125.5L339.35,123.88L338.82,128.81L336.55,129.82L334.14,133.52L328.27,130.06L324.03,131.79L323.67,135.06L320.47,134.41L320.47,134.41L317.98,126.67L316.26,126.18L313.67,121.09L315.05,117.75L311.9,114.63L311.9,114.63L315.79,111.14L316.91,111.91L318.44,110.74L317.37,105.27L319.24,104.34L320.17,106.28L322.37,103.52L325.26,103.67L326.13,100.19L329.04,97.35L329.6,92.32L335.08,96.28L336.56,95.58L337.3,93.52L333.27,91.42L332.89,89.67L339.07,88.62L341.31,90.39L343.96,90.31L345.3,87.06L347.64,85.78L347.39,83.07L349.29,82.08L348.93,79.56L353.32,77.98L351.81,76.44L352.07,72.02L347.98,68.99L347.76,67.22L353.95,65.06L354.63,62.85L356.97,63.1z"
},
{
"id":"HU-HV",
"title":"Hódmezővásárhely",
"d":"M366.34,291.14L367.9,283.5L369.56,282.67L369.6,286.8L371.63,287.61L375.65,283.64L374.12,280.94L378.11,279.98L377.54,277.11L383.6,276.87L384.9,279.15L388.86,276.96L390.32,279.38L391.88,279.17L396.68,285.87L403.04,286L403.04,286L403.11,290.29L400.03,292.12L400.03,292.12L385.64,303.76L377.45,304.8L377.45,304.8L377.94,302.65L372.81,301.32z"
},
{
"id":"HU-JN",
"title":"Jász-Nagykun-Szolnok",
"d":"M425.28,123.73L424.8,127.73L426.51,133.36L430.91,135.36L435.7,133.44L439.84,137.36L439.74,145.23L441.25,147.54L440.2,150L443.65,167.12L442.6,179.15L438.62,182L438.62,182L435.82,187.7L426.93,192.85L428.7,196.43L426.69,196.9L426.46,198.2L428.3,204.08L426.77,203.5L423.61,206.05L423.41,207.66L418.97,207.69L418.73,205.51L415.94,208.27L414.46,208.14L414.44,215.34L415.69,215.79L415.96,217.75L413.99,218.01L416.07,218.33L413.94,223.45L408.37,225.6L404.4,223.28L400.17,223.39L399.42,225.17L396.82,226.3L391.8,226.09L387.27,231.14L388.64,238.37L388.64,238.37L386.83,240.66L382.14,240.78L380.23,243.89L376.96,243.03L373.76,239.54L371.64,238.98L366.32,244.93L360.65,240.75L360.31,243.15L358.77,243.7L356.17,238.2L356.17,238.2L354.6,235.61L353.54,236.12L353.76,239.16L351.09,237.4L351.21,235.22L354.34,234.65L354,233.52L351.85,233.94L350.35,231.92L353.88,230.01L354.82,230.89L355.95,228.36L358.56,228.65L365.11,223.35L363.57,220.52L360.29,220.08L360.28,218.67L362.74,217.51L363.26,214.65L359.08,211.51L359.08,211.51L360.66,208.02L358.64,206.91L355.5,198.43L354.93,195.86L356.33,192.52L356.33,192.52L361.31,195.72L360.67,196.54L362.09,198.09L366.55,198.39L369.76,201.49L372.63,201.52L376.3,197.97L374.86,193.82L371.96,192.36L374.48,185.96L371.71,186.3L373.15,185.11L371.41,182.7L369.43,182.78L363.72,179.13L358.21,184.92L358.21,184.92L354.63,180.92L349.5,179.11L352.22,172.36L349.6,166.48L335.24,155.77L332.48,151.44L327.89,147.54L331.66,141.9L326.85,141.51L323.77,143.98L319.17,139.9L320.47,134.41L320.47,134.41L323.67,135.06L324.03,131.79L328.27,130.06L334.14,133.52L336.55,129.82L338.82,128.81L339.35,123.88L342.87,125.5L348.03,122.61L350.21,123.09L352.27,130.74L351.18,133.69L352.48,135.45L360.51,139.06L362.55,137.49L359.65,134.24L369.17,131.77L371.23,137.93L376.58,140.97L377.86,145.13L376.61,148.09L379.56,152.37L382.18,154.29L384.88,153.32L384.67,155.88L386.74,156.54L390.62,153.99L390,148.4L392.87,147.32L392.07,150.2L395.81,150.57L397.57,146.14L402.59,144.39L414,136.25L413.47,132.97L415.19,131.78L415.08,128.5L419.01,127.31L420.09,125.62L420.09,125.62L419.48,124.01L422.24,121.97z"
},
{
"id":"HU-KV",
"title":"Kaposvár",
"d":"M150.67,288.3L150.8,288.98L150.8,288.98L153.31,286.2L156.79,290.7L157.94,297.44L155.36,298L154.83,299.25L155.6,300.44L154.4,306.75L152.81,306.32L152.11,303.61L149.89,304.11L149.42,306.39L149.42,306.39L147.5,305.66L147.28,302.52L147.28,302.52L144.82,296.14L145.83,292.75L145.1,287.56L145.1,287.56L146.23,285.62z"
},
{
"id":"HU-KM",
"title":"Kecskemét",
"d":"M335.33,219.88L337.69,226.64L333.32,232.63L329.93,229.67L328.91,231.88L323.88,233.05L322.17,236.12L318.28,236.36L318.66,234.63L315.48,230.84L312.03,228.23L309.99,228.21L309.45,224.35L304.39,218.17L306.93,215.72L307.93,216.77L311.55,211.9L319.12,214.2L322.34,212.86L322.34,212.86L330.75,219.11L332.71,218.33z"
},
{
"id":"HU-KE",
"title":"Komárom-Esztergom",
"d":"M242.96,103.13L246.27,103.76L246.27,103.76L251.44,106.01L253.05,114.25L255.04,116.11L253.25,118.09L251.23,116.61L246.92,117.71L247.93,125.87L240.23,123.29L240.32,124.68L237.58,124.67L240.59,127.59L237,129.73L235.14,131.61L235.13,133.48L232.29,135.76L232.29,135.76L225.62,137.57L221.95,136.25L217.56,138.78L217.56,138.78L217.31,136.54L213.44,133.12L208.92,131.58L204.14,132.44L201.73,136.77L203.33,139.94L204.68,139.45L205.11,141.79L209.6,144.59L210.79,147.15L210.79,147.15L208.55,148.19L205.5,152.81L203.84,151.5L202.17,153.44L201.74,154.56L204.05,157.09L199.9,157.45L198.29,159.39L192.48,154.73L191.99,151.69L187.07,149.29L187.66,152.51L186.58,153.72L183.92,154.14L182.65,152.49L180.54,153.48L179.76,159.55L177.26,163.2L177.93,165.06L174.96,166L173.41,168.19L173.41,168.19L166.67,168.27L166.45,166.19L163.91,164.49L165.51,163.9L165.55,162.4L159.09,160.45L161.19,156.12L158.53,151.93L158.53,151.93L159.92,151.1L158.75,149.17L160.15,149.2L160.02,147.44L162.06,146.58L159.58,139.69L161.91,140.69L164.45,139.77L161.55,138.2L163.93,130.58L160.08,127.87L161.53,119.3L160.69,114.16L160.69,114.16L165.44,113.48L167.76,111.73L170.57,113.24L172.99,111.87L176.99,111.89L196.54,115.27L211.04,110.82L215.02,112.48L219.08,110.82L228.52,111.58L235.33,108.06L236.88,104.38z"
},
{
"id":"HU-MI",
"title":"Miskolc",
"d":"M393.84,63.63L397.67,61.71L404.76,61.97L409.78,58.91L415.84,59.25L416.85,58.09L419.2,60.5L421.47,59.88L425.65,61.11L427.2,63.69L426.86,67.86L428.06,68.38L426.93,72.04L423.74,74.17L419.27,74.26L415.75,76.12L414.27,73L410.97,72.19L407.29,69.22L396.14,70.09L396.14,70.09L394.01,66.9z"
},
{
"id":"HU-NK",
"title":"Nagykanizsa",
"d":"M82.73,291.99L79.14,294.6L78.81,298.13L75.5,297.4L74.4,298.36L71.94,294.79L74.67,280.14L77.36,280.35L77.16,275.27L78.32,274.81L79.06,275.93L82.03,273.12L84.02,273.68L83.89,280.67L87.04,283.26L86.64,285.69L88.07,286.32L88.32,288.49L88.32,288.49L86.06,290.83L83.39,288.94z"
},
{
"id":"HU-NO",
"title":"Nógrád",
"d":"M319.2,47.07L321.07,46.91L323.33,51.69L326.01,51.88L327.99,50.08L332.76,52.99L333.37,54.44L331.34,57.01L332.52,58.5L334.65,56.32L336.75,57.3L337.82,55.17L338.25,56.29L341.67,56.81L343.03,59.37L341.87,62.36L345.27,61.25L348.63,56.91L353.52,55.39L355.15,56.59L355.15,56.59L358.89,60L358.89,60L356.97,63.1L354.63,62.85L353.95,65.06L347.76,67.22L347.98,68.99L352.07,72.02L351.81,76.44L353.32,77.98L348.93,79.56L349.29,82.08L347.39,83.07L347.64,85.78L345.3,87.06L343.96,90.31L341.31,90.39L339.07,88.62L332.89,89.67L333.27,91.42L337.3,93.52L336.56,95.58L335.08,96.28L329.6,92.32L329.04,97.35L326.13,100.19L325.26,103.67L322.37,103.52L320.17,106.28L319.24,104.34L317.37,105.27L318.44,110.74L316.91,111.91L315.79,111.14L311.9,114.63L311.9,114.63L309.15,113.24L304.61,117.6L306.56,119.76L303.63,121.06L300.98,115.95L300.59,110.35L297.71,109.99L298.9,106.6L300.56,105.8L298.63,103.83L292.7,103.6L289.58,101.79L281.13,102.74L276.18,99.32L275.24,100.42L270.17,99.51L267.61,100.41L266.12,98.16L265.27,98.65L264.19,95.4L255.18,87.56L255.74,85.07L259.65,82.25L261.1,77.09L259.42,75.33L256.62,75.26L254.12,71.49L254.12,71.49L258.91,71.71L261.98,68.84L265.83,71.34L267.86,69.62L270.07,70.6L272.57,69.41L282.27,72L283.43,69.85L287.44,67.52L295.24,66.89L296.54,68.08L300.5,65.63L302.83,68.02L302.96,66.5L304.72,65.8L308.02,51.92L312.93,49.94L317.51,45.56z"
},
{
"id":"HU-NY",
"title":"Nyíregyháza",
"d":"M489.74,87.97L494.3,78.57L497.28,79.71L501.17,79.17L502.65,75.45L500.85,73.5L501.23,72L504.58,71.63L507.23,73.52L510.97,73.03L512.28,76.48L511.21,79.23L512.84,79.4L513.03,80.75L517.37,80.57L519.45,89.38L518.8,91.25L516.59,91.44L516,93.4L512.9,91.8L512.77,97.59L514.93,98.01L513.82,100.6L512.06,101.15L509.95,97.84L502.62,98.44L500.55,95.62L497.09,94.97L496.33,92.95L490.91,90.52L490.91,90.52L491.72,88.81z"
},
{
"id":"HU-PS",
"title":"Pécs",
"d":"M201.06,325.62L202.06,326.67L202.06,326.67L203.47,330.62L202.7,331.85L198.87,331.27L195.77,335.84L195.77,335.84L194.69,340.56L189.82,342.23L189.82,342.23L186.84,338.54L183.18,336.42L183.7,333.79L182.02,329.44L185.81,329.32L185.15,327.09L185.15,327.09L188.27,324.91L188.27,324.91L192.04,325.91L192.04,325.91L198.94,322.56z"
},
{
"id":"HU-PE",
"title":"Pest",
"d":"M252.12,72.19l2,-0.7l0,0l2.5,3.77l2.8,0.07l1.68,1.76l-1.44,5.16l-3.92,2.82l-0.56,2.48l9.01,7.84l1.07,3.26l0.86,-0.5l1.49,2.25l2.56,-0.9l5.07,0.91l0.94,-1.1l4.95,3.42l8.46,-0.95l3.12,1.81l5.93,0.23l1.92,1.97l-1.65,0.8l-1.19,3.39l2.88,0.36l0.39,5.61l2.65,5.11l2.93,-1.3l-1.96,-2.17l4.55,-4.36l2.74,1.39l0,0l3.15,3.12l-1.38,3.34l2.59,5.09l1.72,0.49l2.49,7.74l0,0l-1.3,5.49l4.6,4.08l3.08,-2.46l4.81,0.39l-3.77,5.63l4.59,3.9l2.76,4.34l14.36,10.71l2.62,5.88l-2.73,6.75l5.14,1.82l3.58,4l0,0l1.45,3.57l-3.34,4.02l0,0l-1.4,3.35l0.57,2.56l3.14,8.48l2.02,1.11l-1.58,3.5l0,0l-2.29,-1.5l-6.4,2.56l-1.29,4.83l-9.71,-4.43l-4.06,6.92l0,0l-2.62,-1.55l-1.97,0.78l-8.41,-6.25l0,0l-4.03,-4.56l-5.05,-11.9l-2.21,2.05l-5.08,-1.89l-2.67,8.76l-4.38,-1.28l-5.64,4.09l-2.59,4.83l-3.71,-5.28l4.65,-7.58l-7.01,-5.7l-3.42,1.97l-2.03,4.67l-0.81,-1.25l-3.31,-0.13l-8.56,8.29l-4.05,-2.63l-6,-1.35l1.69,2.87l-0.72,1.85l0,0l-6.04,-6.07l-2.36,-10.18l4.15,-16.17l-3.56,-0.72l-0.16,-2.94l-1.73,-0.41l0.24,-2.15l-9.44,-10.97l2.82,-3.3l-0.33,-3.99l-2.98,-4.5l-2.21,-0.04l-2.94,-5.33l-0.54,-6.16l0,0l2.84,-2.28l0.01,-1.87l1.87,-1.88l3.58,-2.14l-3,-2.92l2.73,0.01l-0.09,-1.39l7.71,2.58l-1.01,-8.16l4.3,-1.1l2.02,1.48l1.8,-1.98l-1.99,-1.86l-1.61,-8.24l-5.17,-2.25l0,0l0.79,-1.18l-2.6,-3.24l-5.39,-2.67l-0.32,-6.53l1.7,-4.5l-1.77,-2.83l1.37,-1.84l2.59,0.35l1.32,-1.17l1.32,-7.18l4.66,-0.38l0.42,-1.31L252.12,72.19zM267.07,134.5l0.33,-2.65l-3.18,-0.41l-1.54,0.79l0.79,2.35l-9.46,2.01l0.99,2.77l-1.29,1.04l0.88,-0.01l-0.83,2.81l1.44,0.47l-0.79,1.59l1.07,1.04l-0.87,1l2.46,1.2l1.72,2.83l-1.07,1.34l0.53,2.61l-1.71,1.6l0.03,5.9l5.69,-2.11l1.01,1.17l4.64,-2.92l1.94,2.39l-0.63,1.04l3.83,3.88l3.6,-1.54l2.41,-4.58l5.37,-5.64l1.39,0.28l1.84,-2.79l3,-0.9l-1.79,-3.9l0.39,-3l-4.96,0.92l-1.69,-3.81l-2.22,0.61l-1,-1.05l0,0l-1.61,0.11l-2.72,-2.62l0,0l1.17,-0.68l-2.6,-1.73l0.78,-0.99l-4.12,-3.44l0,0l-1.19,0.03L267.07,134.5z"
},
{
"id":"HU-SO",
"title":"Somogy",
"d":"M117.69,245.31l6.3,-0.31l32.6,-16.48l3.2,0.21l2.19,-2.01l-0.05,-3.37l13.64,-6.3l9.09,0.87l0,0l2.79,3.65l1.91,5.69l-2.3,1.96l1.83,0.65l-0.96,0.49l0.88,3.74l-1.06,2.12l1.29,5.44l0,0l-3.87,1.43l0.4,3.26l-5.33,1.58l1.44,3.42l1.33,0.37l-6.42,10.51l1.3,3.56l-1.25,3.89l-1.94,1.27l-1.19,-0.65l-0.69,7.71l3.32,10l-5.65,3.08l0.83,2.2l3.41,-1.2l1.16,3.57l1.5,-0.33l0.51,4.96l-3.03,4.23l0,0l-9.24,-1.03l-2.18,6.25l0.35,3.6l-1.11,0.96l-3.67,-0.27l-2.98,2.08l-4.54,-2.26l-2.26,3.34l-1.8,-0.6l-1.25,-3.55l-1.75,1.33l0.91,1.89l-3.46,6.48l-0.16,6.19l-1.86,0.99l1.36,1.49l-0.53,3.67l-4.03,2.35l2.29,6.85l-2.72,0.78l1.78,6.37l1.44,0.16l-0.13,-2.21l0.72,1.6l2.84,0.1l-0.04,1.84l3.14,3.48l0.13,2.73l-0.64,1.73l-2.17,-0.39l-0.72,1.07l-0.81,-1.85l-1.47,2.78l-1.59,0.52l0,0l-2.72,-7.26l-5.03,-4.32l-3.48,0.34l-8.38,-2.07l-0.75,3l-1.56,-1.62l-2.08,0.87l-0.32,-1.91l-3.45,0.66l-0.04,-2.42l0.67,1.03l3.24,-0.85l-2.61,-0.23l0.02,-1.12l1.24,-0.03l-0.15,-2.42l-1.63,1.96l-2.14,-2.74l0.36,3.03l-2.01,0.56l1.06,-2.81l-2.26,0.74l0.81,-2.43l-2.19,0.13l-2.12,-1.63l3.26,-2.18l-3.59,0.13l1.44,-3.51l-3.53,-0.45l1.85,-0.45l-1.5,-1.98l-2.91,0.18l2.61,-2.81l-2.01,0.03l0.26,-1.95l-3.15,0.83l0.43,-5.54l-2.08,-1.1l0.1,-1.4l-3.09,0.12l-2.09,-2.48l-1.73,0.25l-6.6,-4.52l-3.19,-0.49l-0.32,-2.38l-1.78,0.33l-6.09,-4.63l-0.98,-6.56l0,0l2.49,1.93l3.01,-0.61l0.47,3.32l4.07,-3.2l3.54,0.81l3.11,-5.29l-2.44,-5.74l0,0l0.66,-3.05l2.67,1.89l2.26,-2.33l0,0l2.98,1.88l1.19,-0.4l0.14,-2.56l4.08,-0.29l0.27,-7.14l3.2,-3.41l-0.24,-20.22l3.15,-2.96l1.07,-5.94l8.55,0.39L117.69,245.31zM147.1,305.03l2.32,1.35l0,0l0.47,-2.28l2.22,-0.49l0.7,2.71l1.59,0.43l1.2,-6.31l-0.77,-1.19l0.53,-1.25l2.58,-0.56l-1.15,-6.74l-3.48,-4.5l-2.51,2.78l0,0l-4.32,-3.51l-1.37,2.09l0,0l0.73,5.19l-1.01,3.39l2.45,6.38L147.1,305.03z"
},
{
"id":"HU-SN",
"title":"Sopron",
"d":"M45.6,111.98L54.65,115.14L57.07,121.62L57.07,121.62L53.78,127.32L51.75,126.27L45.26,127.46L41.07,129.69L41.07,129.69L36.17,126.75L33.67,127.52L33.15,126.19L27.88,124.15L29.68,123.08L30.06,119.96L32.51,122.08L34.58,119.23L38.51,118.03L39.15,112.69z"
},
{
"id":"HU-SZ",
"title":"Szabolcs-Szatmár-Bereg",
"d":"M552.48,23.8L555,23.94L552.82,27.08L555.23,30.67L559.96,31.9L559.31,35.34L565.46,47.37L567.26,45.42L570.14,45.15L572.49,46.52L575.38,44.93L579.07,50.98L582.58,52.65L581.96,55.25L585.02,59.85L584.15,60.18L584.43,64.62L591.66,66.87L597.62,63.06L599.5,63.1L600.54,64.54L600.97,62.82L603.54,62.76L603.98,64.87L605.72,63.52L606.79,68.34L608.94,69.57L609.55,72.47L610.73,72.11L609.31,77.76L606.68,80.71L611.44,83.46L612,85.72L607.15,91.67L602.47,94L599.32,93.83L600.97,100.48L595.25,101.47L592.39,107.78L586.07,109.91L580.59,109.84L574.5,104.72L571.48,105.65L569.82,114.01L563.08,112.89L559.62,110.54L559.58,113.75L554.86,115.42L554.31,119.66L551.56,120.77L546.75,133.78L542.66,133.25L542.66,133.25L540.27,125.01L537.68,123.4L532.79,130.05L531.19,126.99L531.87,124.37L529.27,122.81L529.73,119.15L524.2,115.28L520.92,116.22L520.62,119.72L515.84,123.97L509.99,121.11L510.43,118.95L505.67,118.64L504.46,115.36L498.36,115.78L494.96,109.8L489.73,107.3L491.75,94.36L490.91,90.52L490.91,90.52L496.33,92.95L497.09,94.97L500.55,95.62L502.62,98.44L509.95,97.84L512.06,101.15L513.82,100.6L514.93,98.01L512.77,97.59L512.9,91.8L516,93.4L516.59,91.44L518.8,91.25L519.45,89.38L517.37,80.57L513.03,80.75L512.84,79.4L511.21,79.23L512.28,76.48L510.97,73.03L507.23,73.52L504.58,71.63L501.23,72L500.85,73.5L502.65,75.45L501.17,79.17L497.28,79.71L494.3,78.57L489.74,87.97L489.74,87.97L487.47,87.09L485.57,89.44L469.7,90.09L465.28,92.23L464.22,89.26L458.32,84.98L451.75,84.45L451.75,84.45L447.86,78.57L452.7,72.93L455.72,73.31L456.09,75.74L460.52,76.2L460.96,74.01L463.69,71.87L464.75,74.09L467.46,74.01L467.57,75.27L471.09,76.33L472.66,74.77L477.49,74.76L478.02,72.18L480.14,72.86L480.23,70.36L482.46,69.53L480.19,68.8L479.81,67.36L481.38,67.02L478.13,62.8L480.7,55.24L483.21,56.83L484.04,54.98L487.75,55.6L487.39,54.28L492.9,51.12L496.05,52.97L500.87,53.53L505.9,53.62L506.23,52.04L508.69,51.83L508.61,53.58L510.46,51.26L511.63,51.89L513.17,50.35L514.21,46.91L515.3,48L515.7,46.63L516.72,49.11L517.63,46.98L521.67,46.18L523.77,47.05L525.51,43.82L526.17,44.49L528.42,41.86L529.38,42.26L529.53,39.95L532.2,37.52L533.33,37.37L532.29,39.29L534.31,39.26L534.22,38.07L536.03,40.1L536.72,39.13L535.63,37.95L537.19,38.88L537.14,37.49L539.36,37.76L538.5,35.46L542.28,31.86L540.61,30.76L542.38,30.7L541.9,28.2L541.9,28.2L543.52,27.85L543.04,26.48L544.91,25.68L545.28,23.81L549.54,21.74z"
},
{
"id":"HU-SD",
"title":"Szeged",
"d":"M366.34,291.14L372.81,301.32L377.94,302.65L377.45,304.8L377.45,304.8L377.57,313.29L369.46,312.83L370.46,318.02L375.8,317.89L374.5,326.7L373.09,327.41L373.09,327.41L372.96,326.31L371.83,327.02L371.83,327.02L366.48,315.8L362.93,317.3L360.98,316.71L358.93,320.7L358.93,320.7L356.44,324.28L353.99,324.12L352.8,321.02L352.8,321.02L356.73,319.12L355.21,314.65L357.36,311.08L351.37,309.11L348.13,306.46L352.66,302.26L357.2,303.93L357.69,298.14L365.69,300.23L366.67,297.62L364.27,295.84L364.16,291.98z"
},
{
"id":"HU-SF",
"title":"Székesfehérvár",
"d":"M210.27,176.97L211.03,178.35L211.03,178.35L214.01,178.15L216.76,181.25L215.2,183.41L217.1,186.92L216,189.75L217.89,189.64L219.74,194.03L215.08,195.39L211.67,199.5L210.59,198.11L205.24,200.17L204.93,194.34L203.25,193.46L199.22,186.29L206.72,178.39L207.15,175.77L207.15,175.77L208.95,174.85z"
},
{
"id":"HU-SK",
"title":"Szolnok",
"d":"M358.21,184.92L363.72,179.13L369.43,182.78L371.41,182.7L373.15,185.11L371.71,186.3L374.48,185.96L371.96,192.36L374.86,193.82L376.3,197.97L372.63,201.52L369.76,201.49L366.55,198.39L362.09,198.09L360.67,196.54L361.31,195.72L356.33,192.52L356.33,192.52L359.67,188.5z"
},
{
"id":"HU-SH",
"title":"Szombathely",
"d":"M43.31,178.58L43.11,177.41L46.02,177.31L49.2,179.35L51.51,177.85L52.61,181.06L50.29,183.19L51.45,185.25L51.39,191.94L47.98,190.1L44.67,193.75L41.27,191.2L39.2,181.64L36.11,178.72L38,178.01L39.61,179.27L39.61,179.27z"
},
{
"id":"HU-TB",
"title":"Tatabánya",
"d":"M210.79,147.15L209.6,144.59L205.11,141.79L204.68,139.45L203.33,139.94L201.73,136.77L204.14,132.44L208.92,131.58L213.44,133.12L217.31,136.54L217.56,138.78L217.56,138.78L213.88,139.46L214.52,142.4L212.92,142.7L214.09,144.55z"
},
{
"id":"HU-TO",
"title":"Tolna",
"d":"M189.06,241.63L192.58,240.91L197.71,236.35L198.52,239.96L203.06,241.68L204.47,239.96L206.64,242.68L206.82,238.1L208.18,240.07L208.56,245.56L212.15,246.46L216.29,245.74L215.74,243.43L220.22,240.95L221.85,244.14L225.54,245.78L226.82,253.05L228.96,253.31L236.1,248.18L234.84,245.15L237.55,243.06L241.81,242.59L241.91,240.21L247.9,235.95L249.15,233.76L247.73,232.44L253.44,231.14L253.44,231.14L253.6,236.56L257.81,242.17L260.61,252.71L257.36,257.67L249.77,260.27L247.69,263.5L250.62,269.58L250.87,275.17L253.25,280.83L253.21,284.62L249.96,291.52L251.17,299.76L253.29,303.34L252.3,309.25L248.12,308.21L248.96,312.18L244.24,316.13L245.41,316.93L248.73,314.62L248.52,318.13L246.77,318.73L244.77,324.35L244.49,321.02L242.14,322.47L242.06,324.76L245.68,325.84L244.89,328L243.65,327.44L243.74,328.85L243.74,328.85L237.82,329.07L232.75,326.04L232.04,326.67L225.24,318.48L223.3,319.49L221.12,315.78L221.81,314.46L217.97,313.31L218.83,307.79L218.3,306.98L217.32,307.97L215.86,305.41L213.26,304.08L213.39,308.05L212.11,309.91L203.45,314.75L202.66,313.23L206.27,311.73L208.02,306.91L207.46,305.41L203.94,305.01L204.99,297.99L201.71,296.29L201.25,291.43L198.42,288.94L194.17,290.95L190.49,290.11L186.73,291.72L188.14,299.19L183.61,302.15L182.05,301.15L180.3,302.01L180.39,304.98L181.85,305.64L181.18,306.58L179.24,304.04L176.97,305.25L174.87,304.5L174.87,304.5L177.9,300.27L177.39,295.3L175.89,295.63L174.73,292.06L171.32,293.26L170.49,291.05L176.13,287.97L172.81,277.97L173.51,270.26L174.7,270.91L176.64,269.64L177.89,265.76L176.59,262.19L183.02,251.68L181.69,251.32L180.25,247.89L185.58,246.32L185.18,243.06z"
},
{
"id":"HU-VA",
"title":"Vas",
"d":"M47.92,153.38l2.86,3.48l3.29,1.12l6.19,-4.19l0.54,0.89l1.4,-0.94l0.56,1.17l3.46,-1.87l3.14,4.65l2.44,-0.69l2.99,3.14l1.94,-2.78l7.96,-5.88l1.51,2.67l-1.79,6.16l6.83,-3.07l1.75,-2.73l2.63,0.75l0,0l0.91,3.39l2.12,1.91l-1.77,1.38l2.27,2.72l7.3,4.49l-6.23,2.44l-0.66,3.44l-1.54,1.26l1.12,8.79l-1.54,8.4l1.76,8.27l-2.46,2.05l-3.98,-1.8l-6.21,1.74l-0.2,2.44l0,0l0.05,3.01l-1.61,-0.88l-1.33,0.98L83.32,207l-3.12,0.74l1.25,4.51l-3.28,5.23l-5.06,-0.25l-2.32,-1.65l-4.36,0.66l-0.42,-1l-3.45,3.69l-1.84,0.36l-0.82,2.98l-8.33,-1.55l-3.14,2.21l-1.82,-0.67l-5.72,9.11l-5.9,3.04l-0.04,3.88l-1.28,1.18l-4.12,2.6l-3.46,-1.65l-3.46,1.12l-0.01,1.43l3.52,-1.06l0.23,1.01L23,248.94l0,0l-1.15,1.01l-3.46,-5.39l0.97,-2.86l-1.61,-0.42l0.39,-2.26l2.23,-0.95l0.64,-4.35l-4.79,-4.43l-5.12,-0.5l-7.29,2.8L0,229.75l5.84,-5.07l1.62,-4.25l2.24,0.45l2.82,-3.43l1.9,-0.01l1.61,-6.74l0.88,2.02l3.56,0.38l0.74,-1.87l2.08,1.52l3.57,-0.9l1.68,1.64l1.47,-0.24l0.19,-1.41l3.19,1.45l2.5,-0.92l-4.1,-3.88l-1.68,1.03l-0.81,-0.91l0.29,-1.07l7.06,-2.59l-4.29,-2.13l-0.96,-2.69l3.42,-2.09l0.13,-1.82l2.52,-0.41l-1.18,-2.84l-5.6,0.75l0.8,-3.43l-0.87,-2.62l-2.3,0.41l-1.12,-2.71l2.08,-1.6l-0.66,-4.57l3.25,-0.12l1.99,-3.66l-2.3,-7.27l-2.7,-2.31l1.69,-0.56l0.86,-3.35l-1.37,-3.41l3.53,0.15l1.05,2.27l1.24,-2.6l5.63,0.47l1.31,-2.3L47.92,153.38zM39.61,179.27L39.61,179.27l-1.61,-1.26l-1.89,0.72l3.09,2.92l2.08,9.56l3.4,2.55l3.3,-3.65l3.41,1.84l0.06,-6.68l-1.16,-2.07l2.33,-2.13l-1.1,-3.21l-2.32,1.5l-3.18,-2.04l-2.91,0.11l0.2,1.17L39.61,179.27z"
},
{
"id":"HU-VE",
"title":"Veszprém",
"d":"M95.6,155.25l1.89,-1.58l2.24,1.69l0.82,-0.97l3.27,1.16l8.99,-1.73l1.86,-5.43l3.1,0.79l1.82,-1.46l8.69,2.88l2.86,-2.71l3.27,4.1l1.44,-1.13l1.86,1.76l3.01,-2.69l2.53,0.11l0.19,2.87l2.35,-0.43l-0.29,-2.71l2.49,2.29l3.75,-4.64l1.33,2.36l1.87,-2.49l3.61,4.67l0,0l2.66,4.19l-2.1,4.33l6.46,1.95l-0.04,1.5l-1.61,0.58l2.54,1.7l0.22,2.08l6.74,-0.08l0,0l0.72,1.67l1.93,0.29l-1.66,1.98l0.89,3.62l1.6,-0.41l2.86,4.19l4.58,-2.17l1.57,3.43l4.4,3.14l-1.08,7.81l2,8.16l-2.75,2.18l2.86,7.45l2.36,0.29l-2.37,0.71l-6.66,7.38l0,0l-9.09,-0.87l-13.64,6.3l0.05,3.37l-2.19,2.01l-3.2,-0.21l-32.6,16.48l-6.3,0.32l0,0l-5.38,-5.58l-3.17,-5.39l1.33,-2.92l-1.91,-2.18l0.27,-2.67l-3.44,-3.48l-2.44,0.67l-2.57,-1.18l2.16,-4.64l-2.43,-4.31l-1.71,-1.5l-1.99,1.06l-2.82,-0.71l-7.1,-6.28l0,0l0.2,-2.44l6.21,-1.74l3.98,1.8l2.46,-2.05l-1.76,-8.27l1.54,-8.4l-1.12,-8.78l1.54,-1.26l0.66,-3.44l6.24,-2.44l-7.3,-4.49l-2.26,-2.72l1.77,-1.38l-2.12,-1.91L95.6,155.25zM158.93,209.11l3.29,-0.28l0,0l1.61,-3.71l0,0l3.78,-0.12l1.25,-4.95l0,0l-0.52,-1.06l0,0l0.85,-1.03l-4.24,-7.26l-3.52,-3.32l0,0l-2.08,-0.63l-3.17,3.64l-3,0.26l3.63,2.67l0.5,3.5l-3.7,3.91l5.14,5.45L158.93,209.11z"
},
{
"id":"HU-VM",
"title":"Veszprém",
"d":"M163.8,189.38L168.68,196.71L168.32,199L168.32,199L168.84,200.05L168.84,200.05L167.39,205.23L163.82,205.13L163.82,205.13L162.21,208.84L162.21,208.84L159.53,209.53L158.73,206.2L158.73,206.2L153.58,200.74L157.28,196.83L156.79,193.33L153.16,190.65L156.17,190.39L159.33,186.75L161.41,187.39L161.41,187.39z"
},
{
"id":"HU-ZA",
"title":"Zala",
"d":"M86.48,206.18l7.1,6.28l2.83,0.71l1.99,-1.05l1.71,1.5l2.43,4.31l-2.16,4.64l2.57,1.19l2.44,-0.67l3.44,3.48l-0.27,2.67l1.91,2.18l-1.33,2.92l3.17,5.39l5.38,5.58l0,0l-5,2.53l-8.54,-0.39l-1.06,5.94l-3.15,2.96l0.24,20.22l-3.2,3.41l-0.27,7.14l-4.08,0.29l-0.14,2.56l-1.19,0.4l-2.98,-1.88l0,0l-0.25,-2.18l-1.42,-0.63l0.4,-2.43l-3.15,-2.59l0.14,-6.99l-1.99,-0.56l-2.97,2.81l-0.74,-1.12l-1.16,0.46l0.2,5.08l-2.69,-0.21l-2.72,14.65l2.45,3.57l1.1,-0.96l3.31,0.73l0.33,-3.53l3.59,-2.61l0,0l2.44,5.74l-3.11,5.29l-3.54,-0.81l-4.07,3.2l-0.47,-3.32l-3,0.61l-2.49,-1.93l0,0l-0.71,-3.58l-1.28,-0.1l-1.38,-2.63l-0.92,0.95l-2.83,-2.49l-3.08,0.86l-2.46,-2.74l-1.26,1.06l-4.21,-7.28l-1.31,0.39l0.6,-1.7l-3.62,-1.32l-2.51,0.52l-1.72,-2.46l-4.98,-2.66l0.84,-3.58l-1.22,-0.54l-0.59,-3.28l-2.56,-0.82l-3.45,-5.71l-2.15,-0.5l-3.24,-4.1l0.6,-2.5l2.42,0.71l0.91,-4.76l-4.96,-0.76L23,248.94l0,0l3.36,-6.04l-0.23,-1.01l-3.52,1.06l0.01,-1.43l3.47,-1.12l3.46,1.66l4.12,-2.6l1.28,-1.18l0.04,-3.88l5.9,-3.04l5.72,-9.11l1.82,0.67l3.14,-2.21l8.33,1.55l0.82,-2.98l1.84,-0.36l3.45,-3.69l0.42,1l4.36,-0.66l2.32,1.65l5.06,0.25l3.29,-5.23l-1.25,-4.51L83.32,207l0.26,2.28l1.34,-0.98l1.62,0.88L86.48,206.18zM60.85,227.05L60.85,227.05l-0.98,4.57l1.24,1.16l-0.63,3.8l1.63,2.46l-1.66,2.65l1.7,2.23l2.27,-1.61l7.09,-0.55l0.3,-6.6l-1.71,-2.76l0.46,-1.5l-3.02,-1.58l-0.87,-2.13l0,0l-2.37,-0.26l0,0l-1.3,0.67L60.85,227.05z"
},
{
"id":"HU-ZE",
"title":"Zalaegerszeg",
"d":"M65.26,227.35L66.65,227.18L66.65,227.18L67.52,229.31L70.54,230.89L70.08,232.39L71.8,235.15L71.5,241.75L64.41,242.3L62.14,243.91L60.45,241.68L62.11,239.03L60.47,236.57L61.11,232.77L59.87,231.61L60.85,227.05L60.85,227.05L62.98,227.59L62.98,227.59L64.28,226.92L64.28,226.92z"
}
]
}
}
}; | development2015/pos | frontend/web/metronic/global/plugins/amcharts/ammap/maps/js/hungaryLow.js | JavaScript | bsd-3-clause | 41,476 |
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule BoxInspector
* @flow
*/
'use strict';
var React = require('React');
var StyleSheet = require('StyleSheet');
var Text = require('Text');
var View = require('View');
var resolveBoxStyle = require('resolveBoxStyle');
var blank = {
top: 0,
left: 0,
right: 0,
bottom: 0,
};
class BoxInspector extends React.Component {
render() {
var frame = this.props.frame;
var style = this.props.style;
var margin = style && resolveBoxStyle('margin', style) || blank;
var padding = style && resolveBoxStyle('padding', style) || blank;
return (
<BoxContainer title="margin" titleStyle={styles.marginLabel} box={margin}>
<BoxContainer title="padding" box={padding}>
<View>
<Text style={styles.innerText}>
({frame.left}, {frame.top})
</Text>
<Text style={styles.innerText}>
{frame.width} × {frame.height}
</Text>
</View>
</BoxContainer>
</BoxContainer>
);
}
}
class BoxContainer extends React.Component {
render() {
var box = this.props.box;
return (
<View style={styles.box}>
<View style={styles.row}>
<Text style={[this.props.titleStyle, styles.label]}>{this.props.title}</Text>
<Text style={styles.boxText}>{box.top}</Text>
</View>
<View style={styles.row}>
<Text style={styles.boxText}>{box.left}</Text>
{this.props.children}
<Text style={styles.boxText}>{box.right}</Text>
</View>
<Text style={styles.boxText}>{box.bottom}</Text>
</View>
);
}
}
var styles = StyleSheet.create({
row: {
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-around',
},
marginLabel: {
width: 60,
},
label: {
fontSize: 10,
color: 'rgb(255,100,0)',
marginLeft: 5,
flex: 1,
textAlign: 'left',
top: -3,
},
buffer: {
fontSize: 10,
color: 'yellow',
flex: 1,
textAlign: 'center',
},
innerText: {
color: 'yellow',
fontSize: 12,
textAlign: 'center',
width: 70,
},
box: {
borderWidth: 1,
borderColor: 'grey',
},
boxText: {
color: 'white',
fontSize: 12,
marginHorizontal: 3,
marginVertical: 2,
textAlign: 'center',
},
});
module.exports = BoxInspector;
| wdxgtsh/react-native | Libraries/Inspector/BoxInspector.js | JavaScript | bsd-3-clause | 2,668 |
/*
* Copyright (C) 2004, 2005, 2007 Nikolas Zimmermann <zimmermann@kde.org>
* Copyright (C) 2004, 2005, 2006, 2010 Rob Buis <buis@kde.org>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "config.h"
#if ENABLE(SVG)
#include "SVGTSpanElement.h"
#include "RenderInline.h"
#include "RenderSVGTSpan.h"
#include "SVGNames.h"
namespace WebCore {
inline SVGTSpanElement::SVGTSpanElement(const QualifiedName& tagName, Document* document)
: SVGTextPositioningElement(tagName, document)
{
}
PassRefPtr<SVGTSpanElement> SVGTSpanElement::create(const QualifiedName& tagName, Document* document)
{
return adoptRef(new SVGTSpanElement(tagName, document));
}
RenderObject* SVGTSpanElement::createRenderer(RenderArena* arena, RenderStyle*)
{
return new (arena) RenderSVGTSpan(this);
}
bool SVGTSpanElement::childShouldCreateRenderer(Node* child) const
{
if (child->isTextNode()
|| child->hasTagName(SVGNames::aTag)
#if ENABLE(SVG_FONTS)
|| child->hasTagName(SVGNames::altGlyphTag)
#endif
|| child->hasTagName(SVGNames::trefTag)
|| child->hasTagName(SVGNames::tspanTag))
return true;
return false;
}
bool SVGTSpanElement::rendererIsNeeded(RenderStyle* style)
{
if (parentNode()
&& (parentNode()->hasTagName(SVGNames::aTag)
#if ENABLE(SVG_FONTS)
|| parentNode()->hasTagName(SVGNames::altGlyphTag)
#endif
|| parentNode()->hasTagName(SVGNames::textTag)
|| parentNode()->hasTagName(SVGNames::textPathTag)
|| parentNode()->hasTagName(SVGNames::tspanTag)))
return StyledElement::rendererIsNeeded(style);
return false;
}
AttributeToPropertyTypeMap& SVGTSpanElement::attributeToPropertyTypeMap()
{
DEFINE_STATIC_LOCAL(AttributeToPropertyTypeMap, s_attributeToPropertyTypeMap, ());
return s_attributeToPropertyTypeMap;
}
void SVGTSpanElement::fillAttributeToPropertyTypeMap()
{
SVGTextPositioningElement::fillPassedAttributeToPropertyTypeMap(attributeToPropertyTypeMap());
}
}
#endif // ENABLE(SVG)
// vim:ts=4:noet
| mafintosh/phantomjs | src/qt/src/3rdparty/webkit/Source/WebCore/svg/SVGTSpanElement.cpp | C++ | bsd-3-clause | 2,799 |
<?php
namespace Faker\Provider\ar_JO;
class Text extends \Faker\Provider\Text
{
protected static function validStart($word)
{
return preg_match('/^\p{Arabic}/u', $word);
}
/**
* License: Attribution-ShareAlike 3.0 Unported (CC BY-SA 3.0)
*
* Title: حي بن يقظان
* Author: ابن الطفيل
* Language: Arabic
*
* @see https://ar.wikisource.org/wiki/%D8%A7%D8%A8%D9%86_%D8%A7%D9%84%D8%B7%D9%81%D9%8A%D9%84_-_%D8%AD%D9%8A_%D8%A8%D9%86_%D9%8A%D9%82%D8%B8%D8%A7%D9%86
* @var string
*/
protected static $baseText = <<<'EOT'
ذكر سلفنا الصالح - رضي الله عنهم - أن جزيرة من جزائر الهند التي تحت خط الاستواء، وهي الجزيرة التي يتولد بها الإنسان من غير أم ولا أب، وبها شجر يثمر نساء، وهي التي ذكر المسعودي أنها جزيرة الوقواق لان تلك الجزيرة اعدل بقاع الأرض هواء؛ أتممها لشروق النور الأعلى عليها استعدادً، وان كان ذلك خلاف ما يراه جمهور الفلاسفة وكبار الأطباء، فانهم يرون إن اعدل ما في المعمورة الإقليم الرابع، فان كانوا قالوا ذلك لأنه صح عندهم انه ليس على خط الاستواء عمارة لمانع من الموانع الأرضية، فلقولهم: أن الإقليم الرابع اعدل بقاع الأرض وجه، وان كانوا إنما أرادوا بذلك إن ما على خط الاستواء شديد الحرارة، كالذي يصرح به أكثرهم فهو خطأ يقوم البرهان على خلافه.
وذلك أنه قد تبرهن في العلوم الطبيعية أنه لا سبب لتكون الحرارة إلا الحركة أو ملاقاة الأجسام الحارة والإضاءة؛ وتبين فيها أيضاً إن الشمس بذاتها غير حارة ولا متكيفة بشيء من هذه الكيفيات المزاجية؛ وقد تبين فيها أيضاً إن الأجسام التي تقبل الإضاءة أتم القبول، هي الأجسام الصقيلة غير الشفافة، ويليها في قبول ذلك الأجسام الكثيفة غير الصقيلة، فأما الأجسام الشفافة التي لاشيء فيها من الكثافة فلا تقبل الضوء بوجه.
وهذا وحده مما برهنه الشيخ أبو علي خاصة، ولم يذكره من تقدمه، فإذا صحت هذه المقدمات، فاللازم عنها أن الشمس لا تسخن الأرض كما تسخن الأجسام الحارة أجسام أخر تماسها، لان الشمس في ذاتها غير حارة ولا الأرض أيضاً تسخن بالحركة لأنها ساكنة وعلى حالة واحدة في شروق الشمس عليها وفي وقت مغيبها عنها وأحوالها في التسخين والتبريد، ظاهرة الاختلاف للحس في هذين الوقتين.
ولا الشمس أيضاً تسخن الهواء أولاً ثم تسخن بعد ذلك الأرض بتوسط سخونة الهواء، وكيف يكون ذلك ونحن نجد أن ما قرب من الهواء من الأرض في وقت الحر، أسخن كثيراً من الهواء الذي يبعد منه علواً؟ فبقي أن تسخين الشمس للأرض إنما هو على سبيل الإضاءة لا غير، فان الحرارة تتبع الضوء أبداً: حتى إن الضوء إذا افرط في المرأة المقعرة، أشعل ما حاذاها.
وقد ثبت في علوم التعاليم بالبراهين القطعية، أن الشمس كروية الشكل، وأن الأرض كذلك، وأن الشمس أعظم من الأرض كثيراً، وأن الذي يستضيء من الشمس أبداً هو أعظم من نصفها، وأن هذا النصف المضيء من الأرض في كل وقت أشد ما يكون الضوء في وسطه، لأنه أبعد المواضع من المظلمة، ولأنه يقابل من الشمس أجزاءاً أكثر، وما قرب من المحيط كان أقل ضوءاً حتى ينتهي إلى الظلمة عند محيط الدائرة الذي ما أضاء موقعه من الأرض قط، وإنما يكون الموضع وسط دائرة الضياء إذا كانت الشمس على سمت رؤوس الساكنين فيه، وحينئذ تكون الحرارة في ذلك الموضع أشد ما يكون فان كان الموضع مما تبعد الشمس عن مسامتة رؤوس أهله، كان شديد البرودة جداً، وان كان مما تدوم فيه المسامتة كان شديد الحرارة، وقد ثبت في علم الهيئة أن بقاع الأرض التي على خط الاستواء لا تسامت الشمس رؤوس أهلها سوى مرتين في العام: عند حلولها برأس الحمل؛ وعند حلولها برأس الميزان.
وهي في سائر العام ستة أشهر جنوباً منهم، وستة أشهر شمالاً منهم: فليس عندهم حر مفرط، ولا برد مفرط. وأحوالهم بسبب ذلك متشابهة.
وهذا القول يحتاج إلى بيان أكثر من هذا، لا يليق بما نحن بسبيله؛ وإنما نبهناك عليه، لأنه من الأمور التي تشهد بصحة ما ذكر من تجويز تولد الإنسان بتلك البقعة من غير أم ولا أب.
فمنهم من بت الحكم وجزم القضية بأن حي بن يقظان من جملة من تكون في تلك البقعة من غير أم ولا أب، ومنهم من أنكر ذلك وروى من أمره خبراً نقصه عليك، فقال: انه كان بازاء تلك الجزيرة، جزيرة عظيمة متسعة الأكتاف، كثيرة الفوائد، عامرة بالناس، يملكها رجل منهم شديد الأنفة والغيرة، وكانت له أخت ذات جمال وحسن باهر فعضلها ومنعها الأزواج إذا لم يجد لها كفواً. وكان له قريب يسمى يقظان فتزوجها سراً على وجه جائز في مذهبهم المشهور في زمنهم.
ثم إنها حملت منه ووضعت طفلاً. فلما خافت أن يفتضح أمرها وينكشف سرها، وضعته في تابوت أحكمت زمه بعد أن أروته من الرضاع؛ وخرجت به في أول الليل في جملة من خدمها وثقاتها إلى ساحل البحر، وقلبها يحترق صبابةً به، وخوفاً عليه، ثم إنها ودعته وقالت: "اللهم انك خلقت هذا الطفل ولم يكن شيئاً مذكوراً، ورزقته في ظلمات الأحشاء، وتكفلت به حتى تم واستوى. وأنا قد سلمته إلى لطفك، ورجوت له فضلك، خوفاً من هذا الملك الغشوم الجبار العنيد.
فكن له، ولا تسلمه، يا أرحم الراحمين" ثم قذفت به في اليم. فصادف ذلك جري الماء بقوة المد، فاحتمله من ليلته إلى ساحل الجزيرة الأخرى المتقدم ذكرها. وكان المد يصل في ذلك الوقت إلى موضع لا يصل إليه بعد علم. فأدخله الماء بقوته إلى أجمة ملتفة الشجر عذبة التربة، مستورة عن الرياح والمطر، محجوبة عن الشمس تزاور عنها إذا طلعت، وتميل إذا غربت. ثم أخذ الماء في الجزر.
وبقي التابوت في ذلك الموضع، وعلت الرمال بهبوب الرياح، وتراكمت بعد ذلك حتى سدت مدخل الماء إلى تلك الأجمة. فكان المد لا ينتهي إليها، وكانت مسامير التابوت قد فلقت، وألواحه قد اضطربت عند رمي الماء في تلك الأجمة. فلما أشتد الجوع بذلك الطفل، بكى واستغاث وعالج الحركة، فوقع صوته في أذن ظبية فقدت طلاها، خرج من كناسه فحمله العقاب، فلما سمعت الصوت ظنته ولدها.
فتتبعت الصوت وهي تتخيل طلاها حتى وصلت إلى التابوت، ففحصت عنه بأظلافها وهو ينوء ويئن من داخله، حتى طار عن التابوت لوح من أعلاه. فحنت الظبية وحنت عليه ورئفت به، وألقمه حلمتها وأروته لبناً سائغاً. ومازالت تتعهده وتربيه وتدفع عنه الأذى. هذا ما كان من ابتداء أمره عند من ينكره التولد. ونحن نصف هنا كيف تربى وكيف أنتقل في أحواله حتى يبلغ المبلغ العظيم. وأما الذين زعموا أنه تولد من الأرض فانهم قالوا إن بطناً من أرض تلك الجزيرة تخمرت فيه طينه على مر السنين والأعوام، حتى امتزج فيها الحار بالبارد، والرطب باليابس، امتزاج تكافؤ وتعادل في القوى. وكانت هذه الطينة المتخمرة كبيرة جداً وكان بعضها يفضل بعضاً في اعتدال المزاج والتهيؤ لتكون الأمشاج.
وكان الوسط منها أعدل ما فيها وأتمه مشابهة بمزاج الإنسان: فتمخضت تلك الطينة، وحدث فيها شبه نفاخات الغليان لشدة لزوجتها: وحدث في الوسط منها لزوجة ونفاخة صغيرة جداً، منقسمة بقسمين، بينها حجاب رقيق، ممتلئة بجسم لطيف هوائي في غاية من الاعتدال اللائق به، فتعلق به عند ذلك الروح الذي هو من أمر الله تعالى وتشبث به تشبثاً يعسر انفصاله عنه عند الحس وعند العقل؛ إذ قد تبين أن هذا الروح دائم الفيضان من عند الله عز وجل، وأنه بمنزلة نور الشمس الذي هو دائم الفيضان على العالم.
فمن الأجسام ما لا يستضيء به، وهو الهواء الشفاف جداً؛ ومنها ما يستضيء به بعض الاستضاءة، وهي الأجسام الكثيفة غير الصقيلة وهذه تختلف في قبول الضياء، وتختلف بحسب ذلك ألوانها، ومنها ما يستضيء به غاية الاستضاءة وهي الأجسام الصقيلة كالمرأة ونحوها.
فإذا كانت هذه المرأة مقعرة على شكل مخصوص، حدث فيها النار لإفراط الضياء. الذي هو الروح، الذي هو من أمر الله تعالى، فياض أبداً على جميع الموجودات؛ فمنها ما لا يظهر أثره فيه اعدم الأستعداد، وهي الجمادات التي لا حياة لها، وهذه بمنزلة الهواء في المثال المتقدم، ومنها ما يظهر أثره فيه، وهي أنواع النبات بحسب استعداداتها وهذه بمنزلة الأجسام الكثيفة في المثال المتقدم؛ ومنها ما يظهر أثره فيه ظهوراً كثيراً، وهي الأجسام الصقيلة في المثال المتقدم.
ومن هذه الأجسام الصقيلة ما يزيد على شدة قبوله لضياء الشمس أنه يحكي صورة الشمس، ومثالها. وكذلك أيضاً من الحيوان ما يزيد على شدة قبوله للروح أنه يحكي الروح ويتصور بصورته وهو الإنسان خاصة.
واليه الإشارة بقوله صلى الله عليه وسلم: "إن الله خلق أدم على صورته". فان قويت في هذه الصورة حتى تتلاشى جميع الصور في حقها، وتبقى هي وحدها، وتحرق سبحات نورها كل ما أدركته، كانت حينئذ بمنزلة المرأة المنعكسة على نفسها المحرقة لسوها وهذا لا يكون إلا للأنبياء صلوات الله عليهم أجمعين. وهذا كله مبين في مواضعه اللائقة به، فليرجع إلى تمام ما حكوه من وصف ذلك التخلق.
قالوا: فلما تعلق هذا الروح بتلك القرارة، خضعت له جميع القوى وسجدت له وسخرت بأمر الله تعالى في كمالها، فتكون بازاء تلك القرارة نفاخة أخرى منقسمة إلى ثلاث قرارت بينهما حجب لطيفة، ومسالك نافذة، وامتلأت بمثل ذلك الهوائي الذي امتلأت منه القرارة الأولى؛ إلا أنه ألطف منه. وفي هذه البطون الثلاثة المنقسمة من واحد، طائفة من تلك القوى التي خضعت له وتوكلت بحراستها والقيام عليها، وإنهاء ما يطرأ فيها من دقيق الأشياء وجليلها إلى الروح الأول المتعلق بالقرارة الأولى.
وتكون بازاء هذه القرارة من الجهة المقابلة للقراءة الثانية، نفاخة ثالثة مملوءة جسماً هوائياً، إلا أنه أغلظ من الأولين وسكن في هذه القرارة فريق من تلك القوى الخاضعة، وتوكلت بحفظها و القيام عليها؛ فكانت هذه القرارة الأولى والثانية والثالثة، أول ما تخلق من تلك الطينة المتحمرة على الترتيب الذي ذكرناه. واحتاج بعضها إلى بعض: فالأولى منها حاجتها إلى الآخرين، حاجة استخدام وتسخير.
والأخريان حاجتهما إلى الأولى حاجة المرؤوس إلى الرئيس، والمدبر إلى المدبر؛ وكلاهما لما يتخلق بعدهما من الأعضاء رئيس لا مرؤوس. وأحدهما، وهو الثاني، أتمم رئاسة من الثالث فالأول منهما لما تعلق به الروح، واشتعلت حرارته تشكل بشكل النار لصنوبري وتشكل أيضاً الجسم الغليظ المحدق به على شكله، وتكون لحماً صلباً، وصار عليه غلاف صفيق يحفظه وسمي العضو كله قلباً واحتاج لما يتبع الحرارة من التحليل وافناء الرطوبات إلى شيء يمده ويغذوه، ويخلف ما تحلل منه على الدوام، وإلا لم يطل بقاؤه، واحتاج أيضاً إلى تحسس بما يلائمه فيجذبه، وبما يخالفه فيدفعه. فتكفل له العضو الواحد بما فيه من القوى التي أصلها منه بحاجته الواحدة، وتكفل له العضو الآخر بحاجته الأخرى.
وكان المتكفل بالحس هو الدماغو المتكفل بالغذاء هو الكبد؛ واحتاج كل واحد من هذين إليه في أن يمدها بحرارته، وبالقوى المخصوصة بهما التي أصلها منه ، فانتسجت بينهما لذلك كله مسالك وطرق: بعضها أوسع من بعض بحسب ما تدعواليه الضرورة، فكانت الشرايين و العروق. وصفه الطبيعيون في خلقة الجنين في الرحم، لم يغادروا من ذلك شيئاً، إلى أن كمل خلقه، وتمت أعضاؤه، وحصل في حد خروج الجنين من البطن، واستعانوا في وصف كمال ذلك بتلك الطينة الكبيرة المتخمرة، وأنها كانت قد تهيأت لان يتخلق منها كل ما يحتاج إليه في خلق الإنسان من الأغشية المجللة لجملة بدنه وغيرها فلما كمل انشقت عنه تلك الأغشية، بشبه المخاض، وتصدع باقي الطينة إذ كان قد لحقه الجفاف.
ثم استغاث ذلك الطفل عند فناء مادة غذائه واشتداد جوعه، فلبته ظبية فقدت طلاها. ثم استوى عبد ما وصفه هؤلاء بعد هذا الموضع، وما وصفه الطائفة الأولى في معنى التربية؛ فقالوا جميعاً: إن الظبية التي تكفلت به وافقت خصباً ومرعى أثيثاً، فكثر لحمها وكثر لبنها، حتى قام بغذاء ذلك الطفل أحسن قيام. وكانت معه لا تبعد عنه إلا لضرورة الرعي. وألف الطفل تلك الظبية حتى كان بحيث إذا هي أبطأت عنه اشتد بكاؤه فطارت إليه.
ولم يكن بتلك الجزيرة شيء من السباع العادية، فتربى الطفل ونما واغتذى بلبن تلك الظبية إلى أن تم له حولان، وتدرج في المشي وأثغر فكان يتبع تلك الظبية، وكانت هي ترفق به و ترحمه وتحمله إلى مواضع فيها شجر مثمر فكانت تطعمه ما تساقط من ثمراتها الحلوة النضيجة؛ وما كان منها صلب القشر كسرته له بطواحنها؛ ومتى عاد إلى اللبن أروته، ومتى ظمئ إلى الماء أرودته، متى ضحا ظللته؛ ومتى خصر أدفأته.
وإذا جن الليل صرفته إلى مكان الأول وجللته بنفسها وبريش كان هناك؛ مما ملئ به التابوت أولاً في وقت وضع الطفل فيه. وكان في غدوهما ورواحهما قد ألفهما ربرب يسرح ويبيت معهما حيث مبيتهما. فما زال الطفل مع الظباء على تلك الحال: يحكي نغمتها بصوته حتى لا يكاد يفرق بينهما؛ وكذلك كان يحكي جميع ما يسمعه من أصوات الطير وأنواع سائر الحيوان محاكاة شديدة لقوة انفعاله لما يريده ما كانت محاكاته لأصوات الظباء في الاستصراخ والاستئلاف والاستدعاء والاستدفاع. إذ للحيوانات في هذه الأحوال المختلفة أصوات مختلفة فألفته الوحوش وألفها؛ ولم تنكره ولا أنكرها.
فلما ثبت في نفسه أمثلة الأشياء بعد مغيبها عن مشاهدته، حدث له نزوغ إلى بعضها؛ وكراهية لبعض. وكان في ذلك كله ينظر إلى جميع الحيوانات فيراها كاسية بالاوبار و الأشعار و أنواع الريش، وكان يرى ما لها من العدو وقوة البطش، وما لها من الأسلحة المعدة لمدافعة من ينازعها، مثل القرون و الأنياب و الحوافر و الصياصي و المخالب. ثم يرجع إلى نفسه، فيرى ما به من العري وعدم السلاح، وضعف العدو، وقلة البطش، عندما كانت تنازعه الوحوش أكل الثمرات، وتستبد بها دونه، وتغلبه عليها، فلا يستطيع المدافعة عن نفسه، ولا الفرار عن شيء منها. وكان يرى أترابه من أولاد الظباء، قد تبتت لها قرون، بعد أن لم تكن، وصارت قوية بعد ضعفها في العدو.
ولم ير لنفسه شيئاً من ذلك فكان يفكر في ذلك ولا يدري ما سببه. وكان ينظر إلى ذوي العاهات والخلق الناقص فلا يجد لنفسه شبيهاً فيهم. وكان أيضاً ينظر إلى مخارج الفضول من سائر الحيوانات، فيراها مستورة: أما مخرج أغلظ الفضلتين فبالاذناب، وأما مخرج وأما مخرج أرقهما فبالاوبار وما أشبههما. ولأنها كانت أيضاً اخفى قضباناً منه. فكان ذلك ما يكربه ويسؤه.
فلما طال همه في ذلك كله، وهو قد قارب سبعة اعوام، ويئس من أن يكمل له ما قد أضر به نقصه، اتخذ من أوراق الشجر العريضة شيئاً جعل بعضه خلفه و بعضه قدمه، وعمل من الخوض والحلفاء شبه حزام على وسطه، علق به تلك الأوراق فلم يلبث إلا يسيراً حتى ذوى ذلك الورق وجف وتساقط. فما زال يتخذ غيره ويخصف بعضه ببعض طاقات مضاعفة، وربما كان ذلك أطول لبقائه إلا انه على كل حال قصير المدة.
واتخذ من أغصان الشجر عصياً وسوى أطرافها وعدل متنها. وكان بها على الوحوش المنازعة له، فيحمل على الضعيف منها، ويقاوم القوي منها، فنبل بذلك قدره عند نفسه بعض نباله، ورأى أن ليده فضلاً كثيراً على أيديها: إذ أمكن له بها ستر عورته واتخاذ العصي التي يدافع بها عن حوزته، ما استغنى به عما أراده من الذنب والعذاب الطبيعي. وفي خلال ذلك ترعرع واربى على السبع سنين، وطال به العناء في تجديد الأوراق التي كان يستتر بها.
فكانت نفسه عند ذلك تنازعه إلى اتخاذ ذنب من ذنوب الوحوش الميتة ليعلقه على نفسه، إلا أنه كان يرى أحياء الوحوش تتحامى ميتها وتفر عنه فلا يتأتى له الأقدام على ذلك الفعل، إلى أن صادف في الأيام نسراً ميتاً فهدي إلى نيل أمله منه، واغتنم الفرصة في، إذ لم ير للوحوش عنه نفرةً فأقدم عليه، وقطع جناحيه وذنبه صحاحاً كما هي، وفتح ريشها وسواها، وسلخ عنه سائر جلده، وفصله على قطعتين: ربط إحداهما على ظهره، وأخرى على سرته وما تحتها، وعلق الذنب من خلفه، وعلق الجناحين على عضديه، فأكسبه ذلك ستراً ودفئاً ومهابة في نفوس جميع الوحوش، حتى كانت لا تنازعه ولا تعارضه. فصار لايدنو إليه شيء منها سوى الظبية التي كانت أرضعته وربته: فانها لم تفارقه ولا فارقها، إلى أن اسنت وضعغت، فكان يرتاد بها المراعي الخصبة ويجتني لها الثمرات الحلوة، ويطعمها.
ومازل الهزل والضعف يستولي عليها ويتوالى، إلى أن أدركها الموت، فسكنت حركاتها بالجملة، وتعطلت جميع أفعالها. فلما رأها الصبي على تلك الحالة، جزع جزعاً شديداً، وكادت نفسه تفيض أسفاً عليها. فكان يناديها بالصوت الذي كانت عادتها أن تجيبه عند سماعه، ويصيح بأشد ما يقدر عليه، فلا لها عند ذلك حركة ولا تغييراً. فكان ينظر إلى أذنيها والى عينيها فلا يرى بها آفة ظاهرة، وكذلك كان ينظر إلى جميع أعضائها فلا يرى بشيء منها آفة.
فكان يطمع إن يعثر على موضع الآفة فيزيلها عنها، فترجع إلى ما كانت عليه فلم ياتت له شيء من ذلك ولا استطاعة. وكان الذي أرشده لهذا الرأي ما كان قد اعتبره في نفسه قبل ذلك: لانه كان يرى انه إذا غمض عينيه أو حجبهما بشيء لا يبصر حتى نزول ذلك العائق، وكذلك كان يرى انه اذا ادخل إصبعه في أذنيه وسدها لا يسمع شيئاً حتى يزول ذلك العارض، وإذا امسك أنفه بيده لا يشم شيئاً من الروائح حتى يفتح أنفه. فاعتقد من اجل ذلك إن جميع ماله من الادراكات و الأفعال قد تكون لها عوائق تعوقها، فإذا أزيلت العوائق عادت الأفعال.
فلما نظر إلى جميع أعضاء الظاهرة ولم ير فيها آفة ظاهرة - وكان يرى مع ذلك العطلة قد اشتملها ولم يختص بها عضو دون عضو - وقع في خاطرة أن الآفة التي نزلت بها، إنما هي العضو غائب عن العيان مستكن في باطن الجسد، وان ذلك العضو لا يغني عنه في فعله شيء من هذه الأعضاء الظاهرة. فلما نزلت به الآفة عمت المضرة، وشملت العطلة، وطمع لو أنه عثر على ذلك العضو وأزال عنه ما يزال به لاستقامت أحواله وفاض على سائر البدن نفعه، وعادت الأفعال إلى ما كانت عليه.
وكان قد شاهد قبل ذلك في الأشباح الميتة من الوحوش وسواها أن جميع أعضائها مصمتة لا تجويف فيها إلا القحف، والصدر، والبطن. فوقع في نفسه أن العضو الذي بتلك الصفة لن يعدو أحد هذه المواضع الثلاثة، وكان يغلب على ظنه غلبة قوية أنه إنما هو في الموضع المتوسط من هذه المواضع الثلاثة، إذ استقر في نفسه أن جميع الأعضاء محتاجة إليه، وأن الواجب بحسب ذلك أن يكون مسكنه في الوسط.
وكان أيضاً إذا رجع إلى ذاته، شعر بمثل هذا العضو في صدره لانه كان يعترض سائراً اعضائه كاليد، والرجل، والأذن، والانف، والعين، ويقدر مفارقتها، فيتاى له أنه كان يستغني عنها، وكان يقدر في رأسه مثل ذلك ويظن أنه يستغني عنه، فإذا فكر في الشيء الذي يجده في صدره، لم يتأت له الاستغناء عنه طرفة عين.
وكذلك كان عند محاربته للوحوش أكثر ما كان يتقي من صياصيهم على صدره، لشعوره بالشيء الذي فيه. فلما جزم الحكم بان العضو الذي نزلت به الآفة إنما هو في صدورها، اجمع على البحث عليه والتنقير عنه، لعله يظفر به، ويرى آفته فيزيلها ثم انه خاف أنه يكون نفس فعله هذا أعظم من الآفة التي نزلت بها أولاً فيكون سعيه عليها. ثم أنه تفكر: هل رأى من الوحوش وسواها، من ضار في مثل تلك الحال، ثم عاد إلى مثل حاله الأول؟ فلم يجد شيئاً! فحصل له من ذلك، اليأس من رجوعها إلى حالها الأولى إن هو تركها، وبقي له بعض الرجاء في رجوعها إلى تلك الحال إن هو وجد ذلك العضو وأزال الآفة عنه. فعزم على شق صدرها وتفتيش ما فيه، فاتخذ من كسور الأحجار الصلدة وشقوق القصب اليابسة، أشباه السكاكين، وشق بها بين أضلاعها حتى قطع اللحم الذي بين الأضلاع، وأفضى إلى الحجاب المستبطن للأضلاع فراه قوياً، فقوي ظنه مثل ذلك الحجاب لا يكون إلا لمثل ذلك العضو وطمع بأنه إذا تجاوزه ألفى مطلوبه فحاول شقه، فصعب عليه، لعدم الآلات، ولأنها لم تكن إلا من الحجارة والقصب، فاستجدها ثانية واستحدها وتلطف في خرق الحجاب حتى انخرق له، فأفضى إلى الرئة فظن أنها مطلوبه، فما زال يقلبها ويطلب موضع الآفة بها.
وكان أولاً نصفها الذي هو في الجانب الواحد. فلما راها مائلة إلى جهة واحدة، وكان قد اعتقد أن ذلك العضو لا يكون إلا في الوسط في عرض البدن، كما في الوسط في طوله. فمازال يفتش في وسط الصدر حتى ألفى القلب وهو مجلل بغشاء في غاية القوة مربوط بعلائق في غاية الوثاقة، والرثة مطيفة به من الجهة التي بدأ بالشق منها، فقال في نفسه: إن كان لهذا العضو من الجهة الأخرى مثل ما له من الجهة فهو في حقيقة الوسط، ولا محالة أنه مطلوبي. لا سيما مع ما أرى له حسن الوضع، وجمال الشكل، وقلة التشتت، وقوة اللحم، وأنه محجوب بمثل هذا الحجاب الذي لم أر مثله لشيء من الأعضاء. فبحث عن الجانب الآخر من الصدر، فوجد فيه الحجاب المستبطن للأضلاع، ووجد الرئة كمثل ما وجد من هذه الجهة.
فحكم بان ذلك العضو هو مطلوبه، فحاول هتك حجابه، وشق شغافه، فبكد واستكراه ما، قدر على ذلك، بعد استفراغ مجهوده. وجرد القلب فراه مصمتاً من كل جهة، فنظر هل يرى فيه آفة ظاهرة؟ فلم ير فيه شيئاً! فشد على يده، فتبين له أن فيه تجويفاً، فقال: لعل مطلوبي الأقصى إنما هو في داخل هذا العضو، وأنا حتى الآن لم أصل إليه. فشق عليه، فألقى فيه تجويفين اثنين احدهما من الجهة اليمنى والآخر من الجهة اليسرى، والذي من الجهة اليمنى مملوء بعقد منعقد، والذي من الجهة اليسرى خال لا شيء به.
فقال: لن يعدو مطلوبي أن يكون مسكنه أحد هذين البيتين. ثم قال: أما هذا البيت الأيمن، فلا أرى فيه إلا هذا الدم المنعقد. ولا شك أنه لم ينعقد حتى صار الجسد كله إلى هذا الحال - إذ كان قد شاهد الدماء متى سالت وخرجت انعقدت وجمدت ولم يكن هذا إلا دماً كسائر الدماء - وأنا أرى أن هذا الدم موجود في سائر الأعضاء لا يختص به عضو دون أخر، وأنا ليس مطلوبي شيئاً بهذه الصفة إنما مطلوبي الشيء الذي يختص به هذا الموضع الذي أجدني لا أستغني عنه طرفة العين، واليه كان انبعاثي من أول. واما هذا الدم فكم مرة جرحتني الوحوش في المحاربة فسال مني كثير منه فما ضرني ذلك ولا افقدني شيئاً من أفعالي، فهذا بيت ليس فيه مطلوبي. وأما هذا البيت الأيسر فأراه خالياً لاشيء فيه، وما أرى ذلك لباطل، فاني رأيت كل عضو من الأعضاء إنما لفعل يختص به، فكيف يكون هذا البيت على ما شاهدت من شرفه باطلاً؟ ما أرى إلا أن مطلوبي كان فيه! فارتحل عنه وأخلاه. وعند ذلك، طرأ على هذا الجسد من العطلة ما طرأ، ففقد الإدراك وعدم الحراك. فلما رأى أن الساكن في ذلك البيت قد ارتحل قبل انهدامه وتركه وهو بحاله، تحقق أنه أحرى أن لا يعود إليه بعد أن حدث فيه من الخراب والتخريق ما حدث. فصار عنده الجسد كله خسيساً لا قدر له بالإضافة إلى ذلك الشيء الذي اعتقد في نفسه أنه يسكنه مدة ويرحل عنه بعد ذلك.
فاقتصر على الفكرة في ذلك الشيء ما هو؟ وكيف هو؟ وما الذي ربطه بهذا الجسد؟ والى اين صار؟ ومن أي الأبواب خرج عند خروجه من الجسد؟ وما السبب الذي أزعجه إن كان خرج كارهاً؟ وما السبب الذي كره إليه الجسد، حتى فارقه إن كان خرج مختاراً؟ وتشتت فكره في ذلك كله، وسلا عن الجسد وطرحه، وعلم أن أمه التي عطفت عليه وأرضعته، إنما كانت ذلك الشيء المرتحل، وعنه كانت تصدر تلك الأفعال كلها، لا هذا الجسد العاطل وأن هذا الجسد بجملته، إنما هو كالآلة وبمنزلة العصي التي اتخذها هو لقتال الوحوش. فانتقلت علاقته عن الجسد إلى صاحب الجسد ومحركه، ولم يبق له شوق إلا إليه. وفي خلال ذلك نتن ذلك الجسد، وقامت منه روائح كريهة، فزادت نفرته عنه، وود أن لا يراه ثم انه سنح لنظره غرابان يقتتلان حتى صرع أحدهما الآخر ميتاً. ثم جعل الحي يبحث في الأرض حتى حفر حفرة فوارى فيها ذلك الميت بالتراب فقال في نفسه: ما أحسن ما صنع هذا الغراب في مواراة جيفة صاحبه وان كان قد أساء في قتله اياه! وأنا كنت أحق بالاهتداء إلى هذا الفعل بآمي! فحفر حفرة وألقى فيها جسد أمه، وحثا عليها التراب.
وبقي يتفكر في ذلك الشيء المصرف للجسد لا يدري ما هو! غير أنه كان ينظر إلى أشخاص الظباء كلها، فيراها على شكل أمه، وعلى صورتها فكان يغلب على ظنه، أن كل واحد منها إنما يحركه ويصرفه شيء هو مثل الشيء الذي كان يحرك أمه ويصرفها، فكان يألف الظباء ويحن إليها لمكان ذلك الشبه. وبقي على ذلك برهة من الزمن، يتصفح أنواع الحيوان والنبات ويطوف بساحل تلك الجزيرة، ويتطلب هل يرى أو يجد لنفسه شبيهاً حسبما يرى لكل واحد من أشخاص الحيوان والنبات أشباهاً كثيرة، فلا يجد شيئاً من ذلك. وكان يرى البحر قد أحدق بالجزيرة من كل جهة، فيعتقد أنه ليس في الوجود أرض سوى جزيرته تلك.
واتفق في بعض الاحيان أن انقدحت نار في أجمة قلخ على سبيل المحاكة. فلما بصر بها رأى منظراً هاله، وخلقاً لم يعهده قبل، فوقف يتعجب منها ملياً، ومازال يدنو منها شيئاً فشيئاً، فرأى ما للنار من الضوء الثاقب والفعل الغالب حتى لا تعلق بشيء إلا أتت عليه وأحالته إلى نفسها، فحمله، العجب بها، وبما ركب الله تعالى في طباعه من الجراءة و القوة، على أن يده إليها، وأراد أن يأخذ منها شيئاً فلما باشرها أحرقت يده فلم يستطع القبض عليها فاهتدى إلى أن يأخذ قبساً لم تستول النار على جميعه، فأخذ بطرفه السليم والنار في طرفه الآخر، فتاتي له ذلك وحمله إلى موضعه الذي كان يأوي إليه - وكان قد خلا في جحر استحسنه للسكنى قبل ذلك. ثم مازال يمد تلك النار بالحشيش والحطب الجزل، ويتعهدهاً ليلاً ونهاراً استحساناً منه وتعجباً منها.
وكان يزيد انسه بها ليلاً، لأنها كانت تقوم له مقام الشمس في الضياء و الدفء، فعظم بها ولوعه، واعتقد أنها أفضل الأشياء التي لديه: وكان دائماً يراها تتحرك إلى جهة فوق وتطلب العلو، فغلب على ظنه أنها من جملة الجواهر السماوية التي كان يشاهدها. وكان يختبر قوتها في جميع الأشياء بأن يلقيها فيها، فيراها مستولية عليه أما بسرعة واما ببطء بحسب قوة استعداد الجسم الذي كان يلقيه للاحتراق أو ضعفه. وكان من جملة ما القى فيها على سبيل الاختبار لقوتها، شيء من أصناف الحيوانات البحرية - كان قد ألقاه البحر إلى ساحله - فلما أنضجت ذلك الحيوان وسطع قتاره تحركت شهوته إليه، فأكل منه شيئاً فاستطابه، فاعتاد بذلك أكل اللحم، فصرف الحيلة في صيد البر والبحر، حتى مهر في ذلك. وزادت محبته للنار، إذ تأتي له بها من وجوه الاغتذاء الطيب شيء لم يتأت له قبل ذلك.
فلما اشتد شغفه بها لما رأى من أحسن آثارها وقوة اقتدارها، وقع في نفسه أن الشيء الذي ارتحل من قلب أمه الظبية التي أنشأته، كان من جوهر هذا الوجود أو من شيء يجانسه، وأكد ذلك في ظنه، ما كان يراه من حرارة الحيوان طول مدة حياته، وبرودته من بعد موته، وكل هذا دائم لا يختل، وما كان يجده في نفسه من شدة الحرارة عند صدره، بازاء الموضع الذي كان قد شق عليه من الظبية، فوقع في نفسه أنه لو أخذ حيواناً حياً وشق قلبه ونظر إلى ذلك التجويف الذي صادفه خالياً عندما شق عليه في أمه الظبية، لرأه في الحيوان الحي وهو مملوء بذلك الشيء الساكن فيه وتحقق هل هو من جوهر النار؟ وهل فيه شيء من الضوء والحرارة، آم لا؟ فعمد إلى بعد الوحوش واستوثق منه كتافاً وشقه على الصفة التي شق بها الظبية حتى وصل القلب. فقصد أولاً إلى الجهة اليسرى منه وشقها، فرأى ذلك الفراغ مملوءاً بهواء بخاري، يشبه الضباب الابيض، فأدخل إصبعه فيه، فوجده من الحرارة في حد كاد يحرقه، ومات ذلك الحيوان على الفور.
فصح عنده أن ذلك البخار الحار هو الذي كان يحرك هذا الحيوان، وأن في كل شخص من أشخاص الحيوانات مثل ذلك، ومتى انفصل عن الحيوان مات. ثم تحركت في نفسه الشهوة للبحث عن سائر أعضاء الحيوان وترتيبها وأوضاعها وكميتها وكيفية ارتباط بعضها ببعض، وكيف تستمد من هذا البخار الحار حتى تستمر لها الحياة به، وكيف بقاء هذا البخار المدة التي يبقى، ومن أين يستمد، وكيف لا تنفذ حرارته؟ فتتبع ذلك كله بتشريح الحيوانات الأحياء و الاموات، ولم يزل ينعم النظر فيها ويجيد الفكرة، حتى بلغ في ذلك كله مبلغ كبار الطبيعيين، فتبين له أن كل شخص من أشخاص الحيوان، وان كان كثيراً بأعضائه وتفنن حواسه وحركاته فانه واحد بذلك الروح الذي مبدؤه من قرار واحد، وانقسامه وانقسامه في سائر الأعضاء منبعث منه. وأن جميع الأعضاء إنما هي خادمة له، أو مؤدية عنه، وأن منزلة ذلك الروح في تصريف الجسد، كمنزلة من يحارب الأعداء بالسلاح التام، ويصيد جميع صيد البر والبحر، فيمد لكل جنس آلة يصيده بها والتي يحارب بها تنقسم: إلى ما يدفع به نكيلة غيره، والى ما ينكي بها غيره.
وكذلك آلات الصيد تنقسم: إلى ما يصلح لحيوان البحر، والى ما يصلح لحيوان البر، وكذلك الأشياء التي يشرح بها تنقسم: إلى ما يصلح للشق، والى ما يصلح للكسر، والى ما يصلح للثقب، والبدن الواحد، وهو يصرف ذلك أنحاء من التصريف بحسب ما تصلح له كل آلة، وبحسب الغايات التي تلتمس بذلك التصرف. كذلك؛ ذلك الروح الحيواني واحد، وإذا عمل بالة العين كان فعله أبصاراً، وإذا عمل بآلة الآذن كان فعله سمعاً، وإذا عمل بآلة الآنف كان فعله شماً، وإذا عمل بآلة اللسان كان فعله ذوقاً، وإذا عمل بالجلد واللحم كان فعله لمساً، وإذا عمل بالعضد كان فعله حركه، وإذا عمل بالكبد كان فعله غذاء واغتذاء.
ولكل واحد من هذه، أعضاء تخدمه. ولا يتم لشيء من هذه فعل إلا بما يصل إليها من ذلك الروح، على الطريق التي تسمى عصباً. ومتى انقطعت تلك الطرق أو انسدت، تعطل فعل ذلك العضو. وهذه الأعصاب إنما تستمد الروح من بطون الدماغ يستمد الروح من القلب، والدماغ فيه أرواح كثير، لانه موضع تتوزع فيه أقسام كثيرة: فآي عضو عدم هذا الروح بسبب من الأسباب تعطل فعله وصار بمنزلة الآلة المطرحة، التي يصرفها الفاعل ولا ينتفع بها. فان خرج هذا الروح بجملته عن الجسد، أو فني، أو تحلل بوجه من الوجوه، تعطل الجسد كله، وصار إلى حالة الموت، فانتهى به إلى هذا من منشئه، وذلك أحد وعشرون عاماً.
وفي خلال هذه المدة المذكورة تفنن في وجوه حيله، واكتسى بجلود الحيوانات التي كان يشرحها، واحتذى بها، واتخذ الخيوط من الأشعار ولحا قصب الخطمية والخباري والقنب، وكل نبات ذي خيط. وكان أصل اهتدائه إلى ذلك، أنه أخذ من الحلفاء وعمل خطاطيف من الشوك القوي والقصب المحدد على الحجارة.
واهتدى إلى البناء بما رأى من فعل الخطاطيف فاتخذ مخزناً وبيتاً لفضلة غذائه، وحصن عليه بباب من القصب المربوط بعضه إلى بعض، لئلا يصل إليه شيء من الحيوانات عند مغيبه عن تلك الجهة في بعض شؤونه. واستألف جوانح الطير ليستعين بها في الصيد، واتخذ الدواجن ببيضها وفراخها، واتخذ من الصياصي البقر الوحشية شبه الاسنة، وركبها في القصب القوي، وفي عصي الزان وغيرها، واستعان في ذلك بالنار وبحروف الحجارة، حتى صارت شبه الرماح، واتخذ ترسه من جلود مضاعة: كل ذلك لما رأى من عدمه السلاح الطبيعي. ولما رأى أن يده تفي له بكل ما فاته من ذلك، وكان لا يقاومه شيء من الحيوانات على اختلاف أنواعها، إلا أنها كانت عنه فتعجزه هرباً، فكر في وجه الحيلة في ذلك، فلم ير شيئاً أنجع له من أن يتالف بعض الحيوانات الشديدة العدو، ويحسن إليها بأعداد الغذاء الذي يصلح لها، حتى يتأتى له الركوب عليها ومطاردة سائر الأصناف بها.
وكان بتلك الجزيرة خيل البرية وحمر وحشية، فاتخذ منها ما يصلح له، وراضها حتى كمل بها غرضه، وعمل عليها من الشرك والجلود أمثال الشكائم والسروج فتاتي له بذلك ما امله من طرد الحيوانات التي صعبت عليه الحيلة في أخذها. وانما تفنن في هذه الأمور كلها ف وقت اشتغاله التشريح، وشهوته في وقوفه على خصائص أعضاء الحيوان، وبماذا تختلف، وذلك في المدة التي حددنا منتهاها بأحد وعشرين عاماً. ثم انه بعد ذلك أخذ في مآخذ أخر من النظر، فتصفح جميع الأجسام التي في عالم الكون والفساد: من الحيوانات على اختلاف أنواعها، والنبات والمعادن وأصناف الحجارة والتراب والماء والبخار والثلج والبرد، والدخان واللهيب والجمر، فرأى لها أصوافاً كثيرة وأفعالاً مختلفة، وحركات متفقة ومضادة، وأنعم النظر في ذلك والتثبت، فرأى أنها تتفق ببعض الصفات وتختلف ببعض، وأنها من الجهة التي تتفق بها واحدة، ومن الجهة التي تختلف فيها متغايرة ومتكثرة فكان تارة ينظر خصائص الأشياء وما يتفرد به بعضها عن بعض، فتكثر عنده كثرة تخرج عن الحصر، وينتشر له الوجود انتشار لا يضبط. كل عضو منها فيرى أنه يحتمل القسمة إلى أجزاء كثيرة جداً، فيحكم على ذاته بالكثرة، وكذلك على ذات كل شيء.
ثم كان يرجع إلى نظر آخر من طريق ثان، فيرى أن أعضاءه، وان كانت كثيرة فهي متصلة كلها بعضها ببعض، لا انفصال بينها بوجه، فهي في الحكم الواحد، وأنها لا تختلف إلا بحسب اختلاف أفعالها، أن ذلك الاختلاف إنما هو بسبب ما يصل إليها من قوة الروح الحيواني، الذي انتهى إليه نظره أولاً، وأن ذلك الروح واحد ذاته، وهو حقيقة الذات، وسائر الأعضاء كلها كالآلات، فكانت تتحد عنده ذاته بهذا الطريق.
ثم أنه كان ينتقل إلى جميع أنواع الحيوانات، فيرى كل شخص منها واحداً بهذا النوع من النظر. ثم كان ينظر إلى نوع منها: كالظباء والخيل وأصناف الطير صنفاً صنفاً، فكان يرى أشخاص كل نوع يشبه بعضه بعضاً في الأعضاء الظاهرة والباطنة الادراكات والحركات والمنازع، ولا يرى بينها اختلافاً إلا في أشياء يسيرة بالإضافة إلى ما اتفقت فيه.
وكان يحكم بان الروح الذي لجميع ذلك النوع شيء واحد، وأنه لم يختلف إلا أنه انقسم على قلوب كثيرة، وأنه لو أمكن أن يجمع جميع الذي افترق في تلك القلوب منه ويجعل في وعاء واحد، لكان كله شيئاً واحداً، بمنزلة ماء واحد، أو شراب واحد، يفرق على أوان كثيرة، ثم يجمع بعد ذلك. فهو في حالتي تفريقه وجمعه شيء واحد، إنما الغرض له التكثر بوجه ما، فكان يرى النوع بهذا النظر واحداً، ويجعل كثرة أشخاصه بمنزلة كثيرة أعضاء الشخص الواحد، التي لم تكن كثرة في الحقيقة.
ثم كان يحضر أنواع الحيوانات كلها في نفسه ويتأملها فيراها تتفق في أنها تحس، وتغتذي، وتتحرك بالإرادة إلى أي جهة شاءت، وكان قد علم أن هذه الأفعال هي أخص أفعال الروح الحيواني، وأن سائر الأشياء التي تختلف بها بعد هذا الاتفاق، ليست شديدة الاختصاص بالروح الحيواني. فظهر له بهذا التأمل، أن الروح الحيواني الذي لجميع جنس الحيوان واحد بالحقيقة، وان كان فيه اختلاف يسير، اختص به نوع دون نوع: بمنزلة ماء واحد مقسوم على أوان كثيرة، بعضه أبرد من بعض.
وهو في أصله واحد وكل ما كان في طبقة واحدة من البرودة، فهو بمنزلة اختصاص ذلك الروح الحيواني بنوع واحد، وان عرض له التكثر بوجه ما. فكان يرى جنس الحيوان كله واحداً بهذا النوع من النظر. ثم كان يرجع إلى أنواع النبات على اختلافها. فيرى كل نوع منها تشبه أشخاصه بعضها بعضاً في الأغصان، والورق، والزهر والثمر، والأفعال فكان يقيسها بالحيوان، ويعلم أن لها شيئاً واحداً فيه: هو لها بمنزلة الروح الحيواني وأنها بذلك الشيء واحد. وكذلك كان ينظر إلى جنس النبات كله، فيحكم باتحاده بحسب ما يراه من اتفاق فعله في أنه يتغذى وينمو.
ثم كان يجمع في نفسه جنس الحيوان وجنس النبات، فيراهما جميعاً متفقين في الاغتذاء والنمو، ألا أن الحيوان يزيد على النبات، بفضل الحس والادراك والتحرك؛ وربما ظهر في النبات شيء شبيه به، مثل تحول وجوه الزهر إلى جهة الشمس، وتحرك عروقه إلى الغذاء، بسبب شيء واحد مشترك بينهما، هو في أحدهما أتمم وأكمل، وفي الآخر قد عاقه عائق ما، وأن ذلك بمنزلة ماء واحد قسم بقسمين، أحدهما جامد والآخر سيال، فيتحد عنده النبات والحيوان. ثم ينظر إلى الأجسام التي لا تحس ولا تغتذي ولا تنمو، من الحجارة، والتراب، والماء، والهواء، واللهب، فيرى أنها أجسام مقدر لها الطول وعرض وعمق وأنها لاتختلف، إلا أن بعضها ذو لون وبعضها لا لون له وبعضها حار والآخر بارد، ونحو ذلك من الاختلافات وكان يرى أن الحار منها يصير بارداً، والبارد يصير حار وكان يرى الماء يصير بخاراً والبخار ماء، والأشياء المحترقة تصير جمراً، ورماداً، ولهيباً، ودخاناً، والدخان إذا وافق في صعوده قبة حجر انعقد فيه وصار بمنزلة سائر الأشياء الأرضية، فيظهر له بهذا التأمل، أن جميعها شيء واحد في الحقيقة، وان لحقتها الكثرة بوجه ما، فذلك مثل ما لحقت الكثرة للحيوان والنبات.
ثم ينظر إلى الشيء الذي اتحد به عند النبات والحيوان، فيرى أنه جسم ما مثل هذه الأجسام: له طول وعرض وعمق، وهو إما حار واما بارد، كواحد من هذه الأجسام التي لا تحس ولا تتغذى، وانما خالفها بأفعاله التي تظهر عنه بالآلات الحيوانية والنباتية لا غير، ولعل تلك الأفعال ليست ذاتية، وانما تسري إليه من شيء آخر ولو سرت إلى هذه الأجسام الآخر، لكانت مثله فكان ينظر إليه بذاته مجرداً عن هذه الأفعال، التي تظهر ببادئ الرأي، أنها صادرة عنه، فكان يرى أنه ليس إلا جسماً من هذه الأجسام، فيظهر له بهذا التأمل، أن الأجسام كلها شيء واحد: حيها وجمادها، متحركها وساكنها، إلا أنه يظهر أن لبعضها أفعالاً بالات، ولا يدري هل تلك الأفعال ذاتية لها، أو سارية أليها من غيرها. وكان في هذه الحال لا يرى شيئاً غير الأجسام فكان بهذا الطريق يرى الوجود كله شيئاً واحداً، وبالنظر الأول كثرة لا تنحصر ولا تتناهى. وبقي بحكم هذه الحالة مدة.
ثم انه تأمل جميع الأجسام حيها وجامدها. وهي التي هي عنده تارةً شيء واحد وتارةً كثيرة كثرة لا نهاية لها، فرأى إن كل واحد منها، لا يخلو من أحد أمرين: إما أن يتحرك إلى جهة العلو مثل الدخان واللهيب والهواء، إذا حصل تحت الماء واما أن يتحرك إلى الجهة المضادة لتلك الجهة، وهي جهة السفل، مثل الماء، وأجزاء الحيوان و النبات، وأن كل جسم من هذه الأجسام لن يعرى عن إحدى هاتين الحركتين وأنه لا يسكن إلا إذا منعه مانع يعوقه عن طريقه، مثل الحجر النازل يصادف وجه الأرض صلباً، فلا يمكن أن يخرقه، ولو أمكنه ذلك لما انثنى عن حركته فيما يظهر، ولذلك إذا رفعته، وجدته يتحامل عليك بميله إلى جهة السفل، طالباً للنزول. وكذلك الدخان في صعوده، لا ينثني إلا أن يصادف قبة صلبة تحبسه، فحينئذً ينعطف يميناً وشمالاً ثم إذا تخلص من تلك القبة، خرق الهواء صاعداً لأن الهواء لا يمكنه أن يحبسه.
وكان يرى إن الهواء إذا ملئ به زق جلد، وربط ثم غوص تحت الماء طلب الصعود وتحامل على من يمسكه تحت الماء، ولا يزال يفعل ذلك حتى يوافي موضع الهواء، وذلك بخروجه من تحت الماء فحينئذً يسكن ويزول عنه ذلك التحامل والميل إلى جهة العلو الذي كان يوجد منه قبل ذلك. ونظر هل يجد جسماً يعرى عن إحدى هاتين الحركتين أو الميل إلى إحداهما في الوقت ما؟ فلم يجد ذلك في الأجسام التي لديه، وانما طلب ذلك، لانه طمع أن يجده، فيرى طبيعة الجسم من حيث هو جسم، دون أن تقترن به وصف من الأوصاف، التي هي منشأ التكثر. فلما أعياه ذلك ونظر إلى الأجسام التي هي أقل الأجسام حملاً للأوصاف فلم يرها تعرى عن أحد هذين الوصفين بوجه، وهما اللذان يعبر عنهما بالثقل والخفة فنظر إلى الثقل والخفة، هل هما للجسم من حيث هو جسم؟ أو هما لمعنى زائد على الجسمية؟ فظهر له أنهما لمعنى زائد على الجسمية لانهما لو كانا للجسم من حيث هو جسم، لما وجد إلا وهما له.
ونحن نجد الثقيل لا توجد فيه الخفة، والخفيف لا يوجد فيه الثقل، وهما لا محالة جسمان ولكل واحد منهما معنى منفرد به عن الأخر زائد على جسميته. وذلك المعنى، الذي به غاير كل واحد منهما الآخر، ولولا ذلك لكانا شيئاً واحداً من جميع الوجوه.
فتبين له أن حقيقة كل واحد من الثقيل والخفيف، مركبة من معنيين: أحدهما ما يقع فيه الاشتراك منهما جميعاً، وهو معنى الجسمية؛ والآخر ما تنفرد به حقيقة كل واحد منهما على الاخر، وهما أما الثقل في احدهما واما الخفة في الاخر، المقترنان بمعنى الجسمية، أي المعنى الذي يحرك أحدهما الأخر علواً والأخر سفلاً. وكذلك نظر إلى سائر الأجسام من الجمادات والأحياء، فرأى أن حقيقة وجود كل واحد منهما مركبة من معنى الجسمية، ومن شيء أخر زائد على الجسمية: أما واحد، واما أكثر من واحد؛ فلاحت له صور الأجسام على اختلافها وهو أول ما لاح له من العالم الروحاني، اذ هي صور لا تدرك بالحس، وانما تدرك بضرب ما من النظر العقلي.
ولاح له في جملة ما لاح من ذلك، أن الروح الحيواني الذي مسكنه القلب - وهو الذي تقدم شرحه أولاً - لابد له أيضاً من معنى زائد على جسميته يصلح بذلك المعنى لأن يعمل هذه الأعمال الغريبة، التي تختص به من ضروب الاحساسات، وفنون الادراكات وأصناف الحركات، وذلك المعنى هو صورته وفضله الذي انفصل به عن سائر الأجسام، وهو الذي يعبر عنه النظار بالنفس الحيوانية. وكذلك ايضاً للشيء الذي يقوم للنبات مقام الحار الغريزي للحيوان، شيء يخصه هو صورته، وهو الذي يعبر عنه النظار بالنفس النباتية. وكذلك لجميع الأجسام الجمادات: وهي ما عدا الحيوان والنبات مما في عالم الكون والفساد شيء يخصها به، يفعل كل واحد منها فعله الذي يختص به مثل صنوف الحركات وضروب الكيفيات المحسوسة عنها، وذلك الشيء هو صورة كل واحد منها، وهو الذي يعبر النظار عنه بالطبيعة.
فلما وقف بهذا النظر على ان حقيقة الروح الحيواني، الذي كان تشوقه اليه ابداً، مركبة من معنى الجسمية، ومن معنى أخر زائد على الجسمية، وان معنى الجسمية مشترك، ولسائر الأجسام، والمعنى الأخر المقترن به هو وحده، هان عنده معنى الجسمية فاطرحه، وتعلق فكره بالمعنى الثاني، وهو الذي يعبر عنه النفس؛ فتشوق إلى التحقق به فالتزم الفكرة فيه، وجعل مبدأ النظر في ذلك تصفح الأجسام كلها، لا من جهة ما هي أجسام، بل من وجهة ما هي ذوات صور تلزم عنها خواص، ينفصل بها بعضها ببعض. فتتبع ذلك وحصره في نفسه، فرأى جملة من الأجسام، تشترك في صورة ما يصدر عنها فعل ما، أو أفعال ما، ورأى فريقاً من تلك الجملة، مع أنه يشارك الجملة بتلك الصورة، يزيد عليها بصورة أخرى، يصدر عنها ما، ورأى طائفة من ذلك الفريق، مع أنها تشارك الفريق في الصورة الأولى والثانية، تزيد عليه بصوره ثالثة، تصدر عنها أفعال ما خاصة بها. مثال ذلك: إن الأجسام الأرضية، مثل التراب والحجارة والمعادن والنبات والحيوان، وسائر الأجسام الثقيلة، وهي جملة واحدة تشترك في صورة واحدة تصدر عنها الحركة إلى الأسفل، ما لم يعقها عائق عن النزول: ومتى تحركت إلى جهة العلو بالقسر ثم تركت، تحركت بصورتها إلى الأسفل. وفريق من هذه الجملة، وهو النبات والحيوان، مع مشاركة الجملة المتقدمة في تلك الصورة، يزيد عليها صورة أخرى، يصدر عنها التغذي والنمو. والتغذي: هو أن يخلف المتغذي، بدل ما تحلل منه، بان يحيل إلى ما التشبه بجوهره مادة قريبة منه، يجتذبها إلى نفسه.
والنمو: هو الحركة في الأقطار الثلاثة، على نسبة محفوظة في الطول والعرض والعمق.
فهذان الفعلان عامان للنبات والحيوان، وهما لا محالة صادران عن صورة مشتركة لهما، وهي المعبر عنها بالنفس النباتية. وطائفة من هذا الفريق، وهو الحيوان خاصة، مع مشاركته الفريق المتقدم في الصورة الأولى والثانية، تزيد عليه بصورة ثالثة، يصدر عنها الحس والتنقل من حين إلى أخر. ورأى أيضاً كل نوع من أنواع الحيوان، له خاصية ينحاز بها عن سائر الأنواع، وينفصل بها متميزاً عنها. فعلم إن ذلك صادر عن صورة له تخصه هي زائدة عن معنى الصورة المشتركة له ولسائر الحيوان، وكذلك لكل واحد من أنواع النبات مثل ذلك. فتبين له إن الأجسام المحسوسة التي في عالم الكون والفساد، بعضها تلتئم حقيقته من معان كثيرة، زائدة على معنى الجسمية، وبعضها من معان اقل؛ وعلم إن معرفة الأقل أسهل من معرفة الأكثر؛ فطلب أولاً الوقوف على الحقيقة لشيء الذي تلتئم حقيقته من اقل الأشياء، ورأى إن الحيوان والنبات، لا تلتئم حقائقها إلا من معان كثيرة، لتفنن أفعالها؛ فأخر التفكير في صورهما. وكذلك رأى إن أجزاء الأرض بعضها ابسط من بعض، فقصد منها إلى ابسط ما قدر عليه وكذلك رأى إن الماء شيء قليل التركيب، لقلة ما يصدر عن صورته من أفعال، وكذلك راى النار والهواء. وكان قد سبق إلى ظنه أولاً، أن هذه الأربعة يستحيل بعضها إلى بعض، وان لها شيئاً واحداً تشترك فيه، وهو معنى الجسمية، وان ذلك الشيء ينبغي إن يكون خلواً من المعاني التي تميز بها كل واحد من هذه الأربعة عن الأخر، فلا يمكن أن يتحرك إلى فوق ولا إلى اسفل، ولا إن يكون حاراً ولا يكون بارداً، ولا يكون رطباً، ولا يابساً، لان كل واحد من هذه الاوصاف، لا يعم جميع الأجسام، فليست إذن للجسم بما هو جسم.
فإذا أمكن وجود جسم لا صورة فيه زائدة على الجسمية، فليس تكون فيه صفة من هذه الصفات، ولا يمكن إن تكون فيه صفة إلا وهي تعم سائر الأجسام المتصورة، بضروب الصور. فنظر هل يجد وصفاً واحداً يعم جميع الأجسام: حيها وجمادها، فلم يجد شيئاً يعم الأجسام كلها. إلا معنى الامتداد الموجود في جميعها في الأقطار الثلاثة، التي يعبر عنها بالطول، والعرض، والعمق، فعلم هذا المعنى هو للجسم من حيث هو جسم، لكنه لم يتأت له بالحس وجود جسم بهذه الصفة وحدها، حتى لا يكون فيه معنى زائد على الامتداد المذكور ويكون بالجملة خلواً من سائر الصور. ثم تفكر في هذا الامتداد إلى الأقطار الثلاثة، هل هو معنى الجسم بعينه، وليس ثم معنى أخر أو ليس الأمر كذلك، فرأى أن وراء هذا الامتداد معنى أخر، هو الذي يوجد فيه هذا الامتداد، وان الامتداد وحده لا يمكن إن يقوم بنفسه كما إن ذلك الشيء الممتد، لا يمكن أن تقوم دون امتداد. واعتبر ذلك ببعض هذه الأجسام المحسوسة ذوات الصور، كالطين مثلاً، كان له طول وعرض وعمق على قدر ما.
ثم إن تلك الكرة بعينها لو أخذت وردت إلى شكل مكعب أو بيض، لتبدل ذلك الطول وذلك العرض وذلك العمق، وصارت على قدر أخر. غير الذي كانت عليه، والطين واحد بعينه لم يتبدل، غير أنه لا بد له من طول وعرض وعمق على أي قدر كان، ولا يمكن إن يعرى عنها؛ غير أنها لتعاقبها عليه، تبين له أنها معنى على حياله؛ ولكونه لا يعرى بالجملة عنها، تبين له أنها من حقيقة. فلاح له بهذا الاعتبار، إن الجسم، بما هو جسم، مركب على الحقيقة من معنين: أحدهما يقوم منه مقام الطين للكرة في هذا المثال. والأخر: يقوم مقام طول الكرة وعرضها وعمقها، أو المكعب، أو أي شكل كان له. وانه لا يفهم الجسم إلا مركباً من هذين المعنين، وان احدهما لا يستغني عن الأخر. ولكن الذي يمكن أن يتبدل ويتعاقب على أوجه كثيرة، وهو معنى الامتداد يشبه الصورة التي لسائر الأجسام ذوات الصور، والذي يثبت على حال واحدة، وهو الذي ينزل منزلة الطين في المثال المتقدم، يشبه معنى الجسمية التي لسائر الأجسام ذوات الصور.
وهذا الشيء الذي هو بمنزلة الطين في هذا المثال هو الذي يسميه النظار المادة والهيولى وهي عارية عن الصورة جملة. فلما نظره إلى هذا الحد، وفارق المحسوس بعض مفارقة، وأشرف على تخوم العالم العقلي، استوحش وحن إلى ما ألفه من عالم الحس، فتقهقر قليلاً وترك الجسم على الإطلاق، إذ هو أمر لا يدركه الحس، ولا يقدر على تناوله. فاخذ أبسط الأجسام المحسوسة التي شاهدها، وهي تلك الأربعة التي كان قد وقف نظره عليها.
فأول ما نظر إلى الماء فرأى انه إذا خلي وما تقتضيه صورته، ظهر منه برد محسوس، وطلب النزول إلى اسفل فإذا سخن أما بالنار واما بحرارة الشمس، زال عنه البرد أولاً وبقي فيه طلب النزول، فإذا أفرط عليه بالتسخين، زال عنه طلب النزول إلى اسفل. وصار يطلب الصعود إلى فوق. فزال عنه بالجملة الوصفان اللذان كانا أبداً يصدران عن صورته، ولم يعرف من صورته أكثر من صدور هذين الفعلين عنها. فلما زال هذان الفعلان بطل حكم الصورة، فزالت الصورة المائية عن ذلك الجسم عندما ظهرت منه أفعال من شأنها أن تصدر عن صورة أخرى، وحدثت له صورة أخرى، بعد أن لم تكن، وصدر عنه بها أفعال لم يكن من شأنها أن تصدر عنه وهو بصورته الأولى. فعلم بالضرورة أن كل حادث لا بد له من محدث. فارتسم في نفسه بهذا الاعتبار، فاعل للصورة، ارتساماً على العموم دون تفصيل. ثم أنه تتبع الصور التي كان قد عاينها قبل ذلك، صورة صورة، فرأى أنها كلها حادثة، وأنها لا بد لها من فاعل. ثم نظر إلى ذوات، الصور، فلم ير أنها شيء أكثر من استعداد الجسم لان يصدر عنه ذلك الفعل، مثل الماء، فانه إذا افرط عليه التسخين، استعد للحركة إلى فوق وصلح لها.
فذلك الاستعداد هو صورته، إذ ليس ها هنا إلا جسم وأشياء تحس عنه، بعد أن لم تكن؛ فصلوح الجسم لبعض الحركات دون بعض، واستعداده بصورته، ولاح له مثل ذلك في جميع الصور، فتبين له أن الأفعال الصادرة عنها، ليست في الحقيقة لها، وانما هي لفاعل يفعل بها الأفعال المنسوبة إليها؛ وهذا المعنى الذي لاح له، هو قول الرسول الله عليه الصلاة والسلام: "كنت سمعه الذي يسمع به وبصره الذي يبصر به" وفي محكم التنزيل: "بسم الله الرحمن الرحيم" فان تقتلوهم ولكن الله قتلهم؛ وما رميت إذا رميت، ولكن الله رمى! صدق الله العظيم. فلما لاح له من أمر هذا الفاعل، ما لاح على الإجمال دون تفصيل، حدث له شوق حثيث إلى معرفته على التفصيل، ولانه لم يكن بعد فارق عالم الحس، جعل يطلب هذا الفاعل على جهة المحسوسات، وهو لا يعلم بعد هل هو واحد أو كثير؟ فتصفح جميع الأجسام التي لديه، وهي التي كانت فكرته أبداً فيها، فرأها كلها تتكون تارة وتفسد أخرى، وما لم يقف على فساد جملته، وقف على الفساد أجزائه مثل الماء والأرض، فانه راى أجزاءهما تفسد بالنار، وكذلك الهواء رآه يفسد بشدة البرد، حتى بتكون منه الثلج فيسيل ماء. وكذلك سائر الأجسام التي كانت لديه، ولم ير منها شيئاً بريئاً عن الحدوث والافتقار إلى الفاعل المختار، فاطرحها كلها وانتقلت فكرته إلى الأجسام السماوية.
وانتهى إلى هذا النظر على رأس أربعة أسابيع من منشئه، وذلك ثمانية وعشرون عاماً. فعلم إن السماء وما فيها من كواكب الأجسام، لأنها ممتدة في الأقطار الثلاثة: الطول، والعرض، والعمق؛ لا ينفك شيء منها عن هذه الصفة، وكل ما لا ينفك عن هذه الصفة، فهو جسم؛ فهي إذن كلها أجسام. ثم تفكر هل هي ممتدة إلى ما لا نهاية، وذاهبة أبداً في الطول والعرض والعمق إلى ما لا نهاية، أو هي متناهية محدودة بحدود تنقطع عندها، ولا يمكن أن يكون وراءها شيء من الامتداد؟ فتحير بعد ذلك بعض الحيرة. ثم انه بقوة فطرته، وذكاء خاطره، راى أن جسماً لا نهاية له أمر باطل، وشيء لا يمكن، ومعنى لا يعقل، وتقوى هذا الحكم عنده بحجج كثيرة، سنحت له بينه وبين نفسه وذلك أنه قال: أما الجسم السماوي فهو متناه من الجهة التي تليني والناحية التي وقع عليها حسي، فهذا لا شك فيه لأنني أدركه ببصر، وأما الجهة التي تقابل هذه الجهة، وهي التي يداخلني فيها الشك، فاني أيضاً أعلم من المحال أن تمتد إلى غير نهاية، لأني إن تخيلت أن خطين اثنين، يبتدئان من هذه الجهة المتناهية، ويمران في سمك الجسم إلى غير نهاية حسب امتداد الجسم، ثم تخيلت أن أحد هذين الخطين، قطع منه جزء كبير من ناحية طرفه المتناهي، ثم أخذ ما بقي منه شيء واطبق الخط المقطوع منه على الخط الذي لم يقطع منه شيء، وذهب الذهن كذلك معهما إلى الجهة التي يقال إنها غير متناهية، فأما أن نجد خطين أبداً يمتدان إلى غير نهاية ولا ينقص أحدهما عن الأخر، فيكون الذي قطع منه جزء مساوياً للذي لم يقطع منه شيء وهو محال، كما أن الكل مثل الجزء المحال؛ واما أن لا يمتد الناقص معه ابداً، بل ينقطع دون مذهبه ويقف عن الامتدادمعه، فيكون متناهياً، فإذا رد عليه القدر الذي قطع منه أولاً، وقد كان متناهياً، صار كله أيضاً متناهياً، وحينئذ لا يقصر عن الخط الأخر الذي يقطع منه شيء، ولا يفضل عليه فيكون إذن مثله وهو متناه، فذلك أيضاً متناه، فالجسم الذي تفرض فيه هذه الخطوط متناه، وكل جسم يمكن أن تفرض فيه هذه الخطوط، فكل جسم متناه.
فإذا فرضنا أن جسماً غير متناه، فقد فرضنا باطلاً ومحالاً. فلما صح عنده بفطرته الفائقة التي لمثل هذه الجهة، أن جسم السماء متناه، أراد أن يعرف على أي شكل هو، وكيفية انقطاعه بالسطوح التي تحده. فنظر أولاً إلى الشمس والقمر وسائر الكواكب، فرأها كلها تطلع من جهة المشرق، وتغرب من جهة المغرب، فما كان يمر على سمت رأسه، رأه يقطع دائرة عظمى، وما مال عن سمت رأسه إلى الشمال أو إلى الجنوب، رأه يقطع دائرة أصغر من تلك. وما كان أبعد عن سمت الرأس إلى أحد الجانبين، كانت دائرته أصغر من دائرة ما هو أقرب. حتى كانت أصغر الدوائر التي تتحرك عليها الكواكب، دائرتين اثنتين: إحداهما حول القطب الجنوبي، وهي مدار سهيل، والاخرى حول القطب الشمالي، وهي المدار الفرقدين. ولما كان مسكنه على خط الاستواء الذي وصفناه أولاً، كانت هذه الدوائر كلها على سطح آفة. ومتشابهة في الجنوب والشمال وكان القطبان معاً ظاهرين له، وكان يترقب إذا طلع كوكب من الكواكب على دائرة كبيرة، وطلع كوكب آخر على دائرة صغيرة، وكان طلوعهما معاً، فكان يرى غروبهما معاً. واطرد له في ذلك جميع الكواكب وفي جميع الأوقات، فتبين له بذلك أن الفلك على شكل الكرة، وقوى ذلك في اعتقاده، ما رآه من رجوع الشمس والقمر وسائر الكواكب إلى المشرق، بعد مغيبها بالمغرب، وما رآه أيضاً من أنها تظهر لبصره على قدر واحد من العظم في حال طلوعها وتوسطها وغروبها، وأنها لو كانت حركتها على غير شكل الكرة لكانت لا محالة في بعض الأوقات، أقرب إلى بصره منها في وقت آخر، ولو كانت كذلك، لكانت مقاديرها واعظامها تختلف عند بصره فيراها في حال القرب أعظم مما يراها في حال البعد، لاختلاف أبعادها عن مركزه حينئذ بخلافها على الأول.
فلما لم يكن شيء من ذلك؛ تحقق عنده كروية الشكل. وما زال يتصفح حركة القمر، فيراها آخذه من المغرب إلى المشرق وحركات الكواكب السيارة كذلك، حتى تبين له قدر كبير من علم الهيئة، وظهر له أن حركتها لا تكون إلا بأفلاك كثيرة، كلها مضمنة في فلك واحد، هو أعلاها. وهو الذي يحرك الكل من المشرق إلى المغرب في اليوم والليلة. وشرح كيفية انتقاله. ومعرفة ذلك يطول؛ وهو مثبت في الكتب، ولا يحتاج منه في غرضنا إلا للقدر الذي أردناه. فلما انتهى إلى هذه المعرفة، ووقف على أن الفلك بجملته وما يحتوي عليه، كشيء واحد متصل بعضه ببعض، وأن جميع الأجسام التي كان ينظر فيها أولاً: كالأرض والماء والهواء والنبات والحيوان وما شاكلها، هي كلها في ضمنه وغير خارجة عنه، وأنه كله أشبه شيء بشخص من أشخاص الحيوان؛ وما فيه من الكواكب المنيرة هي بمنزلة حواس الحيوان؛ وما فيه من ضروب الأفلاك، المتصل بعضها ببعض، هي بمنزلة أعضاء الحيوان؛ وما في داخله من الكون والفساد هي بمنزلة ما في جوف الحيوان من أصناف الفضول والرطوبات، التي كثيراً ما يتكون فيها أيضاً حيوان، كما يتكون في العالم الأكبر. فلما تبين له أنه كله كشخص واحد في الحقيقة، واتحدت عنده أجزاؤه الكثيرة بنوع من النظر الذي اتحدت به عنده الأجسام التي في عالم الكون والفساد، تفكر في العالم بجملته، هل هو شيء حدث بعد إن لم يكن، وخرج إلى الوجود بعد العدم؟ أو هو أمر كان موجوداً فيما سلف، ولم يسبقه العدم بوجه من الوجوه؟ فتشك في ذلك ولم يترجح عنده أحد الحكمين على الآخر. وذلك أنه كان إذا أزمع على اعتقاد القدم، اعترضه عوارض كثيرة، من استحالة وجود ما لا نهاية له، بمثل الذي استحال عنده به وجود جسم لا نهاية وكذلك أيضاً كان يرى أن هذا الوجود لا يخلو من الحوادث، فهو لا يمكن تقدمه عليها، وما لا يمكن أن يتقدم على الحوادث، فهو أيضاً محدث. وإذا أزمع على اعتقاد الحدوث، اعترضته عوارض أخرى، وذلك أنه كان يرى أن معنى حدوثه، بعد أن لم يكن لا يفهم إلا على أن الزمان تقدمه، والزمان من جملة العالم وغير منفك عنه، فإذن لا يفهم تأخر العالم عن الزمان. وكذلك أيضاً كان يقول: إذا كان حادثاً، فلا بد له من محدث؛ وهذا المحدث الذي أحدثه، لم أحدثه الآن ولم يحدثه قبل ذلك، الطارئ طرأ عليه ولا شيء هناك غيره، أم لتغير حدث في ذاته؟ فان كان فما الذي احدث ذلك التغيير؟ وما زال يتفكر في ذلك عدة سنين.
فتتعارض عنده الحجج، ولا يترجح عنده أحد الاعتقادين على الآخر. فلما أعياه ذلك، جعل يتفكر ما الذي يلزم عن كل واحد من الاعتقادين، فلعل اللازم عنهما يكون شيئاً واحداً. فرأى انه إن اعتقد حدوث العالم خروجه إلى الوجود بعد العدم، فاللازم عن ذلك ضرورة، انه لا يمكن أن يخرج إلى الوجود بنفسه، وانه لا بد له من فاعل يخرجه إلى الوجود، وان ذلك الفاعل لا يمكن إن يدرك بشيء من الحواس، لانه لو أدرك بشيء من الحواس لكان جسماً من الأجسام، ولو كان جسماً من الأجسام لكان من جملة العالم، وكان حادثاً واحتاج إلى محدث، ولو كان ذلك المحدث الثاني أيضاً جسماً، لحتاج إلى محدث ثالث، والثالث إلى رابع، ويتسلسل ذلك إلى غير نهايةً وهو باطل. فإذن لابد للعالم من فاعل ليس بجسم، وإذا لم يكن جسماً فليس إلى إدراكه لشيء من الحواس سبيل، الآن الحواس الخمس لا تدرك إلا الأجسام، وإذا لا يمكن أن يحس فلا يمكن أن يتخيل، لان التخيل ليس شيئاً إلا إحضار صور المحسوسات بعد غيبتها، وإذا لم يكن جسماً فصفات الأجسام كلها تستحيل عليه، وأول صفات الأجسام هو الامتداد في الطول والعرض والعمق، وهو منزه عن ذلك، وعن جميع ما يتبع هذا الوصف من صفات الأجسام. وإذا كان فاعلاً للعالم فهو لا محالة قادر عليه وعالم به "بسم الله الرحمن الرحيم" إلا يعلم من خلق، وهو اللطيف الخبير؟ صدق الله العظيم. وراى أيضاً انه إن اعتقد قدم العالم، وان العدم لم يسبقه، وانه لم يزل كما هو، فان اللازم عن ذلك أن حركته قديمة لا نهاية لها من جهة الابتداء، إذ لم يسبقها سكون يكون مبدؤها منه، وكل حركة فلابد لها من محرك ضرورة، والمحرك أما أن يكون قوة سارية في جسم من الأجسام - أما جسم المتحرك نفسه، واما جسم أخر خارج عنه - واما أن تكون قوة ليست سارية ولا شائعة قي جسم. وكل قوى سارية في جسم وشائعه فيه، فانها تنقسم بانقسامه، وتتضاعف بتضاعفه، مثل الثقل بالحجر مثلاً. المحرك إلى الأسفل.
فانه إن قسم الحجر نصفين. وان زيد عليه أخر مثله، زاد في الثقل أخر مثله، فان أمكن أن يتزايد الحجر إلى غير نهاية، كتزايد هذا الثقل إلى غير نهاية، وان وصل الحجر إلى حد ما من العظم ووقف، وصل الثقل إلى ذلك الحد ووقف، لكنه قد تبرهن أن كل جسم فانه لا محالة متناه، فإذن كل قوة في الجسم فهي لا محالة متناهية. فان وجدناها قوة تفعل فعلاً لا نهاية له، فهي قوة ليست في جسم، وقد وجدنا الفلك يتحرك أبداً حركة لانهاية لها ولا انقطاع إذ فرضناه قديماً لا ابتداء له فالواجب على ذلك أن تكون القوة التي تحرك ليست في جسمه، ولا في جسم خارج عنه. فهي إذا لشيء بريء عن الأجسام، وغير موصوف بشيء من أوصاف الجسمية، وقد كان لاح له في نظره الأول في عالم الكون والفساد إن حقيقة وجود كل جسم، إنما هي من جهة صورته التي هي استعداده لضروب الحركات، وان وجوده الذي له من جهة مادته وجود ضعيف لا يكاد يدرك؛ فان وجود العالم كله إنما هو من جهة استعداده لتحريك هذا المحرك البريء عن المادة، وعن صفات الأجسام، المنزه عن أن يدركه حس، أو يتطرق إليه خيال، سبحانه، وإذا كان فاعلاً لحركات الفلك على اختلاف أنواعها، فعلاً لا تفاوت فيه ولا فتور فيه ولا قصور، فهو لا محالة قادر عليها وعالم بها.
فانتهى نظره بهذا الطريق إلى ما انتهى إليه بالطريق الأول، ولم يضره في ذلك تشككه في قدم العالم أو حدوثه، وصح له على الوجهين جميعاً وجود فاعل غير الجسم، ولا متصل بجسم ولا منفصل عنه، ولا داخل فيه، ولا خارج عنه، إذ: الاتصال، والانفصال، والدخول، هي كلمات من صفات الأجسام، وهو منزه عنها. ولما كانت المادة في كل جسم مفتقرة إلى الصورة، إذ لا تقوم إلا بها ولا تثبت لها حقيقة دونها، وكانت الصورة لا يصح وجودها إلا من فعل هذا الفاعل تبين له افتقار جميع الموجودات في وجودها إلى هذا الفاعل وأنه لا قيام لشيء منها إلا به فهو إذن علة لها، وهي معلومة له، سواء كانت محدثة الوجود، بعد أن سبقها العدم، أو كانت الابتداء لها من جهة الزمان، ولم يسبقها العدم قط، فانها على كلا الحالتين معلولة، ومفتقرة إلى الفاعل، متعلقة الوجود به، ولولا دوامه لم تدم، ولولا وجوده لم توجد، ولولا قدمه لم تكن قديمة، وهو في ذاته غني عنها وبريء منها! وكيف لا يكون كذلك وقد تبرهن أن قدرته غير متناهية، وأن جميع الأجسام وما يتصل بها أو يتعلق بها، ولو بعض التعلق، هو متناه منقطع. فإذن العالم كله بما في السماوات والأرض والكواكب، وما بينها، وما فوقها، وما تحتها، فعله وخلقه؛ ومتأخر عليه بالذات، وان كانت غير ماخرة عليها بالزمان. كما انك إذا أخذت في قبضتك جسماً من الأجسام، ثم حركت يدك، فان ذلك الجسم لا محالة يتحرك تابعاً لحركة يدك، حركة متأخرة عن حركة يدك، تأخراً بالذات؛ وان كانت لم تتأخر بالزمان عنها، بل كان ابتداؤهما معاً، فكذلك العالم كله، معلول ومخلوق لهذا الفاعل بغير زمان "بسم الله الرحمن الرحيم" إنما أمره إذا أراد شيئاً أن يقول له كن فيكون صدق الله العظيم. فلما راى إن جميع الموجودات فعله، تصفحها من بعد ذا تصفحاً على طريق الاعتبار في قدرة فاعلها؛ والتعجب من غريب صنعته، ولطيف حكمته، ودقيق علمه فتبين له في اقل الأشياء الموجودة، فضلاً عن أكثرها من أثار الحكمة، وبدائع الصنعة، ما قضى منه كل العجب، وتحقق عنده إن ذلك لا يصدر إلا عن فاعل مختار في غاية الكمال وفوق الكمال "بسم الله الرحمن الرحيم" لا يغرب عنه مثقال ذرة في السموات ولا في الأرض ولا اصغر من ذلك ولا أكبر صدق الله العظيم.
ثمتأمل في جميع أصناف الحيوان، كيف "بسم الله الرحمن الرحيم" أعطى كل شيء خلقه، ثم هداه صدق الله العظيم لاستعماله، فلولا أنه هداه لاستعمال تلك الأعضاء التي خلقت له في وجوه المنافع المقصود بها، لما انتفع بها الحيوان، وكانت كلاً عليه، فعلم بذلك أنه أكرم الكرماء، وارحم الرحماء. من فيض ذلك الفاعل المختار - جل جلاله - ومن وجوده، ومن فعله، فعلم أن الذي هو في ذاته أعظم منها، وأكمل، واتمم وأحسن، وأبهى وأجمل وأدوم، وأنه لا نسبة لهذه إلى تلك. فما زال يتتبع صفات الكمال كلها، فيراها له وصادرة عنه، ويرى أنه أحق بها من كل ما يوصف بها دونه. وتتبع صفات النقص كلها فرآه بريئاً منها، ومنزهاً عنها؛ وكيف لا يكون بريئاً منها وليس معنى النقص إلا العدم المحض، أو ما يتعلق بالعدم؟ وكيف يكون العدم تعلق أو تلبس، بمن هو الموجود المحض، الواجب الوجود بذاته، المعطي لكل ذي وجود وجوده، فلا وجود إلا هو: فهو الوجود، وهو الكمال، وهو التمام، وهو الحسن، وهو البهاء، وهو القدرة، وهو العلم، وهو هو، و "بسم الله الرحمن الرحيم" كل شيء هالك إلا وجهه صدق الله العظيم. فانتهت به المعرفة إلى هذا الحد، على رأس خمسة أسابيع من منشئه، وذلك خمسة وثلاثون عاماً، وقد رسخ في قلبه من هذا الفاعل، ما شغله عن الفكرة في كل شيء إلا فيه، وذهل عما كان فيه تصفح الموجودات والبحث عنها، حتى صار بحيث لا يقع بصره على شيء من الأشياء، إلا ويرى فيه أثر الصنعة، ومن حينه، فينتقل بفكره على الفور إلى الصانع ويترك المصنوع، حتى اشتد شوقه إليه، وانزعج قلبه بالكلية عن العالم الأدنى المحسوس، وتعلق بالعالم الأرفع المعقول. فلما حصل له العلم بهذا الموجود الرفيع الثابت الوجود الذي لا سبب لوجود جميع الأشياء، أراد أن يعلم بأي شيء حصل له هذا العالم، وبأي قوة أدرك هذا الموجود: فتصفح حواسه كلها وهي: السمع، والبصر، والشم، والذوق، واللمس، فرأى أنها لا تدرك شيئاً إلا جسماً، أو ما هو في الجسم، وذلك أن السمع لا يدرك المسموعات، وهي ما يحدث من تموج الهواء عند تصادم الأجسام، والبصر إنما يدرك الألوان، والشم يدرك الروائح، والذوق يدرك الطعوم، واللمس يدرك الأمزجة والصلابة واللين، والخشونة والملاسة، وكذلك القوة الخيالية لا تدرك شيئاً إلا أن يكون له طول وعرض وعمق؛ وهذه المدركات كلها من صفات الأجسام، وليس لهذه الحواس أدراك شيء سواها، وذلك لأنها قوى شائعة في الأجسام، ومنقسمة بانقسامها، فهي لذلك لا تدرك إلا جسماً منقسماً، لان هذه القوة إذا كانت شائعة في شيء منقسم، فلا محالة أنها إذا أدركت شيئاً من الأشياء، فانه ينقسم بانقسامها؛ فإذن كل قوة في جسم، فانها لا محالة لا تدرك إلا جسماً أو ما هو جسم.
وقد تبين إن هذا الموجود الواجب الوجود، بريء من صفات الأجسام من جميع الاتجاهات، فإذن لا سبيل إلى إدراكه إلا بشيء ليس بجسم، ولا هو قوة في جسم، ولا تعلق له وجه من الوجوه بالأجسام، ولا هو داخل فيها ولا خارج عنها، ولا متصل بها ولا منفصل عنها. وقد كان تبين له أن أدركه بذاته، ورسخت المعرفة به عنده، فتبين له بذلك أن ذاته التي أدركه بها أمر غير جسماني، ولا يجوز عليه شيء من صفات الأجسام، وان كل ما يدركه من ظاهر ذاته من الجسمانية فانها ليست حقيقة ذاته، وانما حقيقة ذاته ذلك الشيء الذي أدرك به الموجود المطلق الواجب الوجود. فلما علم أن ذاته ليست هذه المتجسمة التي يدركها بحواسه، ويحيط بها أديمه، هان عنده بالجملة جسمه، وجعل يتفكر في تلك الذات الشريفة، التي أدرك بها ذلك الموجود الشريف الواجب الوجود، ونظر في ذاته تلك الشريفة، هل يمكن أن تبيد أو تفسد وتضمحل، أو هي دائمة البقاء؟ فرأى إن الفساد والاضمحلال إنما هو من صفات الأجسام بأن تخلع صورة وتلبس صورة أخرى، مثل الماء إذا صار هواء، والهواء إذا صار ماء، والنبات إذا صار تراباً، والتراب إذا صار نباتاً، هذا هو معنى الفساد.
وأما الشيء الذي ليس بجسم، ولا يحتاج في قوامه إلى جسم، وهو منزه بالجملة عن الجسمانية، فلا يتصور فساده البتة. فلما ثبت له أن ذاته الحقيقة لا يمكن فسادها، أراد إن يعلم كيف يكون حالها إذا اطرح البدن وتخلت عنه، وقد كان تبين له أنها لا تطرحه إلا إذا لم يصلح آلة لها، فتصفح جميع القوى المدركة، فرأى أن كل واحدة منها تارةً تكون مدركة بالقوة، وتارةً تكون مدرة بالفعل: مثل العين في حال تغميضها أو أعراضها عن البصر، فانها تكون مدركة بالقوة - ومعنى مدركه بالقوة أنها لا تدرك الآن وتدرك في المستقبل - وفي حال فتحها واستقبالها للمبصر، تكون مدركه بالفعل - ومعنى مدركة بالفعل أنها الآن تدرك - وكذلك كل واحدة من هذه القوى تكون مدركة بالقوة وتكون مدركة بالفعل، وكل واحدة من هذه القوى إن كانت لم تدرك قط بالفعل، فهي ما دامت بالقوة لا تتشوق إلى إدراك الشيء المخصوص بها لأنها لم تتعرف به بعد، مثل من خلق مكفوف البصر؛ وان كانت قد أدركت بالفعل تارةً، ثم صارت بالقوة، فانها ما دامت بالقوة تشتاق إلى الإدراك بالفعل لأنها قد تعرفت إلى المدرك، وتعلقت به، وحنت إليه، مثل من كان يصيراً ثم عمي فانه لا يزال يشتاق إلى المبصرات. وبحسب ما يكون الشيء المدرك أتم وأبهى وأحسن، يكون الشوق أكثر؛ والتألم لفقده اعظم، ولذلك كان تألم من يفقد بصره بعد الرؤية أعظم من تألم من يفقد شمه، إذ الأشياء التي يدركها البصر أتم وأحسن من التي يدركها الشم، فان كان في الأشياء شيء لا نهاية لكماله، ولا غاية لحسنه وجماله وبهائه، وهو فوق الكمال والبهاء والجمال، وليس في الوجود كمال، ولا حسن، ولا بهاء، ولا جمال إلا صادر من جهته، وفائض من قبله، فمن فقد إدراك ذلك الشيء بعد إن تعرف به، فلا محالة أنهما ما دام فاقد له، يكون في ألام لا نهاية لها، كما أن من كان مدركاً له على الدوام، فانه يكون في لذة لا انفصام لها، وغبطة لا غاية لها ورائها، وبهجة وسرور لا نهاية لهما. وقد تبين له أن الموجود الواجب الوجود.
متصف بأوصاف الكمال كلها، ومنزه عن الصفات النقص وبريء منها. وتبين له أن الشيء الذي به يتوصل إلى أدركه أمر لا يشبه الأجسام، ولا يفسد لفسادها؛ فظهر له بذلك أن من كانت له مثل هذه الذات، المعدة لمثل هذا الإدراك؛ فانه إذا أطرح البدن بالموت؛ فإما أن يكون قبل ذلك - في مدة تصريفه للبدن - لم يتعرف قط بهذا الموجود الواجب الوجود؛ ولا اتصل به؛ ولا سمع عنه؛ فهذا إذا فارق البدن لا يشتاق إلى ذلك الموجود ولا يتألم لفقده. واما جميع القوى الجسمانية، فانها تبطل ببطلان الجسم؛ فلا تشتاق أيضاً إلى مقتضيات تلك القوى، ولا تحن إليها، ولا تتألم لفقدها. وهذه حال البهائم غير الناطقة كلها: سواء كانت من صورة الإنسان أو لم تكن. واما إن يكون قبل ذلك - في مدة تصريفه للبدن - قد تعرف بهذا الموجود، وعلم ما هو عليه من الكمال والعظمة والسلطان والحسن إلا انه أعرض عنه واتبع هواه، حتى وافته منيته وهو على تلك الحال، فيحرم المشاهدة، وعنده الشوق إليها فيبقى في عذاب طويل، وألام لا نهاية لها. فأما من يتخلص من تلك الآلام بعد جهد طويل، ويشاهد ما تشوق إليه قبل ذلك، واما أن يبقى في آلامه بقاءً سرمدياً، بحسب استعداده لكل واحد من الوجهين لحياته الجسمانية.
واما من تعرف بهذا الموجود الواجب الوجود، قبل أن يفارق البدن، واقبل بكليته عليه والتزم الفكرة في جلاله وحسن بهائه، ولم يعرض عنه حتى وافته منيته، وهذا على حال من الإقبال والمشاهدة بالفعل. فهذا إذا فارق البدن بقي في لذة لا نهاية لها، وغبطة وسرور وفرح دائم، لاتصال مشاهدته لذلك الموجود الواجب الوجود، وسلامة تلك المشاهدة من الكدر والشوائب؛ ويزول عنه ما تقتضيه هذه القوى الجسمانية من الأمور الحسية التي هي - بالإضافة إلى تلك الحال - ألام وشرور وعوائق. فلما تبين له أن كمال ذاته ولذتها إنما هو بمشاهدة ذلك الموجود الواجب الوجود على الدوام، مشاهدة بالفعل أبداً، حتى لا يعرض عنه طرفة عين لكي توافيه منيته، وهو في حال المشاهدة بالفعل، فتتصل لذته دون أن يتخللها ألم. ثم جعل يتفكر كيف يتأتى له دوام هذه المشاهدة بالفعل، حتى لا يقع منه أعراض فكان يلازم الفكرة في ذلك الموجود كل ساعة، فما هو إلا يسنح لبصره محسوس ما من المحسوسات، أو يخرق سمعه صوت بعض الحيوان، أو يتعرضه خيال من الخيالات، أو يناله ألم في أحد اعضائه، أو يصيبه الجوع أو العطش أو البرد أو الحر، أو يحتاج القيام لدفع فضوله؛ فتختل فكرته، ويزول عما كان فيه، ويتعذر عليه الرجوع إلى ما كان عليه من حال المشاهدة، إلا بعد جهد. وكان يخاف أن تفاجأه منيته وهو في حال الأعراض، فيفضي إلى الشقاء الدائم، وألم الحجاب.
فساءه حاله ذلك، وأعياء الدواء. فجعل يتصفح أنواع الحيوانات كلها، وينظر أفعالها وما تسعى فيه، لعله يتفطن في بعضها أنها شعرت بهذا الموجود، وجعلت تسعى نحوه، فيتعلم منها ما يكون في سبب نجاته. فرآها كلها إنما تسعى في تحصيل غذائها، ومقتضى شهواتها من المطعوم والمشروب والمنكوح، والاستظلال والاستدفاء، وتجد في ذلك ليلها ونهارها إلى حين مماتها وانقضاء مدتها. ولم ير شيئاً منها ينحرف عن هذا الرأي، ولا يسعى لغيره في وقت من الأوقات، فبان له بذلك أنها لم تشعر بذلك الموجود ولا اشتاقت إليه، ولا تعرفت إليه بوجه من الوجوه، وأنها كلها صائرة إلى العدم، أو إلى حال شبيه بالعدم. فلما حكم على ذلك بالحيوان، علم أن الحكم على النبات أولى، إذ ليس للنبات من الادراكات إلا بعض ما للحيوان. وإذا كان الأكمل إدراكاً لم يصل إلى هذه المعرفة، فالأنقص إدراكاً أحرى أن لا يصل، مع انه رأى أيضاً أن أفعال النبات كلها لا تتعدى الغذاء والتوليد. ثم انه بعد ذلك نظر إلى الكواكب والأفلاك فرآها كلها منتظمة الحركات، جارية على نسق؛ ورآها شفافة ومضيئة بعيدة عن قبول التغيير والفساد، فحدس حدساً قوياً أن لها ذوات سوى أجسامها، تعرف ذلك الموجود الواجب الوجود، وأن تلك الذوات العارفة ليست بأجسام، ولا منطبعة في أجسام مثل ذاته، هو، العارفة، وكيف لا يكون لها مثل تلك الذوات البريئة عن الجسمانية، ويكون لمثله على ما به من الضعف وشدة الاحتياج إلى الأمور المحسوسة، وأنه من جملة الأجسام الفاسدة؟ ومع ما به من النقص، فلم يعقه ذلك عن أن تكون ذاته بريئة عن الأجسام لا تفسد، فتبين له بذلك أن الأجسام السماوية أولى بذلك، وعلم أنها تعرف ذلك الموجود الواجب الوجود وتشاهد على الدوام بالفعل، لأن العوائق التي قطعت به هو عن الدوام المشاهدة من العوارض المحسوسة، لا يوجد مثلها للأجسام السماوية.
ثم انه تفكر: لم اختص هو من بين سائر أنواع الحيوانات بهذه الذات التي أشبه بها الأجسام السماوية. وقد كان تبين له أولاً من آمر العناصر واستحالة بعضها إلى بعض، وأن جميع ما على وجه الأرض لا يبقى على صورته؛ بل الكون والفساد متعاقبان عليه أبداً، وأن أكثر هذه الأجسام مختلطة مركبة من أشياء متضادة، ولذلك تؤول إلى الفساد، وانه لا يوجد منه شيء صرفاً، وما كان منها قريباً من أن يكون صرفاً خالصاً لا شائبة فيه، فهو بعيد عن الفساد جداً مثل الذهب والياقوت، وأن الأجسام البسيطة صرفة، ولذلك هي بعيدة عن الفساد، والصور لا تتعاقب عليها. وتبين له هنالك أن جميع الأجسام التي في عالم الكون والفساد، منها ما تتقوم حقيقتها بصورة واحدة زائدة على معنى الجسمية - وهذه هي الاسطقسات الأربع - ومنها ما تتقوم حقيقتها أكثر من ذلك كالحيوان والنبات. فما كان قوام حقيقته بصور أقل، كانت أفعاله أقل، وبعده عن الحياة أكثر، فان عدم الصورة جملة لم يكن فيه إلى الحياة طريق، وصار في حال شبيه بالعدم، وما كان قوام حقيقته بصور أكثر، كانت أفعاله أكثر، ودخوله في حال الحياة أبلغ؛ وان كانت تلك الصورة بحيث لا سبيل إلى مفارقتها لمادتها التي اختصت بها كانت الحياة حينئذ كامل الظهور والكمال والقوة. فالشيء العديم للصورة جملة هو الهيولى والمادة، ولا شيء من الحياة فيها وهي شبيهة بالعدم، والشيء المتقوم بصورة واحدة هي الاسطقسات الأربع وهي في أول مراتب الوجود في عالم الكون والفساد ومنها تتركب الأشياء ذوات الصور الكثيرة. وهذه الاسطقسات ضعيفة الحياة جداً، إذ ليست تتحرك إلا حركة واحدة، وانما كانت ضعيفة الحياة لان لكل واحد منها ضداً ظاهر العناد يخالفه في مقتضى طبيعته، ويطلب أن يغير صورته.
فوجوده لذلك غير متمكن، وحياته ضعيف، والبات أقوى حياة منه والحيوان أظهر حياة منه. وذلك أن ما كان من هذه المركبات تغلب عليه طبيعة أسطقس واحد، فلقوته فيه يغلب طبائع الاسطقسات الباقية، ويبطل قواها، ويصير ذلك المركب في حكم الاسطقس الغالب، فلا يستأهل لاجل ذلك من الحياة آل شيئا يسيراً، كما إن ذلك الاسطقس لا يستأهل من الحياة إلا يسيراً ضعيفاً وما كان من هذه المركبات لا تغلب عليه طبيعة أسطقس واحد منها، فان الاسطقسات تكون فيه متعادلة متكافئة، فإذن لا يبطل لأحدهما الآخر قوة الآخر بأكثر مما يبطل ذلك الآخر قوته، بل يفعل بعضها في بعض فعلاً متساوياً، فلا يكون فعل أحد الاسطقسات أظهر فيه، ولا يستولي عليه أحدها، فيكون بعيد الشبه من كل واحد من الاسطقسات، فكأنه لا مضادة لصورته، فيستأهل الحياة بذلك. ومتى زاد هذا الاعتدال وكان أتم وأبعد من الانحراف، كان بعده عن أن يوجد له ضد أكثر، وكانت حياته أكمل. ولما كان الروح الحيواني الذي مسكنه القلب، شديد الاعتدال، لانه ألطف من الأرض والماء وأغلظ من النار والهواء، صار في حكم الوسط ولم يضاده شيء من الاسطقسات مضادة بينه.
فاستعد بذلك الصورة الحيوانية، فرأى أن الواجب إلى ذلك أن يكون أعدل ما في هذه الأرواح الحيوانية مستعداً لاتمم ما يكون من الحياة في عالم الكون والفساد، وأن يكون ذلك الروح قريباً من أن يقال أنه لا ضد لصورته، فيشبه لذلك هذه الأجسام السماوية التي لا ضد لصورها؛ ويكون روح ذلك الحيوان، وكأنه وسط بالحقيقة بين الاسطقسات التي لا تتحرك إلى جهة العلو على الإطلاق، ولا إلى جهة السفل، بل لو أمكن أن يجعل في وسط المسافة بين المراكز وأعلى ما تنتهي إليه النار في جهة العلو ولم يطرأ عليه الفساد، لثبت هناك ولم يطلب الصعود ولا نزول. ولو تحرك في المكان، لتحرك حول الوسط كما تتحرك الأجسام السماوية، ولو تحرك في الوضع، لتحرك على نفسه، وكان كروي الشكل إذ لا يمكن غير ذلك، فإذن هو شديد الشبه بالأجسام السماوية. ولما كان قد اعتقد أن أحوال الحيوان، ولم ير فيها ما يظن به انه شعر بالموجود الواجب الوجود، وقد كان علم من ذاتها قد شعرت به، قطع ذلك على أنه هو الحيوان المعتدل الروح، الشيبة بالأجسام السماوية وتبين لو انه نوع مباين لسائر الحيوان، وانه إنما خلق لغاية أخرى، وأعد لامر عظيم، لم يعد له شيء من أنواع الحيوان، وكفى به شرفاً أن يكون أحس جزأيه - وهو الجسماني - أشبه الأشياء بالجواهر السماوية الخارجة عن عالم الكون والفساد، المنزهة عن الحوادث النقص والاستحالة والتغيير. وأما أشرف جزأيه، فهو الشيء الذي به عرف الموجود الواجب الوجود، وهذا الشيء العارف، أمر رباني الهي يستحيل ولا يلحقه الفساد، ولا يوصف بشيء مما توصف به الأجسام، ولا يدرك بشيء من الحواس، ولا يتخيل، ولا يتوصل إلى معرفته بآلة سواه، بل يتوصل إليه به؛ فهو العارف والمعروف، والمعرفة؛ وهو العالم، والمعلوم، والعلم؛ لا يتباين في شيء من ذلك، إذ التباين والانفصال من صفات الأجسام ولواحقها، ولا جسم هنالك ولا صفة جسم ولا لاحق بجسم! فلما تبين له الوجه الذي اختص به من بين سائر أصناف الحيوان بمشابهة الأجسام السماوية، رأى إن الواجب عليه أن يتقبلها ويحاكي أفعالها ويتشبه بها جهده. وكذلك رأى أنه بجزئه الاشرف الذي به عرف الموجود الواجب الوجود، فيه شبه ما منه من حيث هو منزه عن صفات الأجسام، وكما أن الواجب الوجود منزه عنها، فرأى ايضاً انه يجب عليه أن يسعى في تحصيل صفاته لنفسه من أي وجه أمكن، وان يتخلق بأخلاقه ويقتدي بأفعاله، ويجد في تنفيذ إرادته، ويسلم الآمر له، ويرضى بجميع حكمه، رضى من قلبه ظاهراً وباطناً، بحيث يسر به وان كان مؤلماً لجسمه وضاراً به ومتلفتاً لبدنه بالجملة. وكذلك رأى فيه شبهاً من سائر أنواع الحيوان بجزئه الخسيس الذي هو من عالم الكون والفساد، وهو البدن المظلم والكثيف، الذي يطالبه بأنواع المحسوسات من المطعوم والمشروب والمنكوح، ورأى أيضاً أن ذلك البدن لم يخلق له عبثاً ولا قرن به لامر باطل، ويجب عليه أن يتفقده ويصلح من شأنه. هذا التفقد لا يكون منه إلا بفعل يشبه أفعال سائر الحيوان. فاتجهت عنده الأعمال التي يجب عليه أن يفعلها نحو ثلاثة أغراض: أما عمل يتشبه بالحيوان الغير الناطق.
واما عمل يتشبه به بالأجسام السماوية. واما عمل يتشبه به بالموجود الواجب الوجود. فالتشبه الأول: يجب عليه من حيث البدن المظلم ذو الأعضاء المنقسمة، والقوى المختلفة، والمنازع المتفننة. والتشبه الثاني: يجب عليه من حيث له الروح الحيواني الذي مسكنه القلب، وهو مبدأ لسائر البدن، ولما فيه من القوى. والتشبه الثالث: يجب عليه من حيث هو، أي: من حيث هو الذات التي بها عرف ذلك الموجود الواجب الوجود. وكان أولاً قد وقف على أن سعادته وفوزه من الشقاء، إنما هي في دوام المشاهدة لهذا الموجود الواجب الوجود، حتى يكون بحيث لا يعرض بطرفة عين. ثم أنه نظر بالوجه الذي يتأتى له به هذا الدوام، فأخر له النظر أنه يجب عليه الاعتمال في هذه الأقسام الثلاثة من التشبيهات: آما التشبه الأول، فلا يحصل له به شيء من هذه المشاهدة، بل هو صارف عنها وعائق دونها، إذ هو تصرف في الأمور المحسوسة، والأمور المحسوسة كلها حجب معترضة دون تلك المشاهدة؛ وانما احتيج إلى هذا التشبه لاستدامة هذا الروح الحيواني الذي يحصل به التشبه الثاني بالأجسام السماوية.
فالضرورة تدعو إليه من هذا الطريق،ولو كان لا يخلو من تلك المضرة. واما التشبه الثاني، فيحصل له به حظ عظيم من المشاهدة على الدوام، لكنها مشاهدة يخالطها شوب؛ اذ من يشاهد ذلك النحو من المشاهدة على الدوام فهو مع تلك المشاهدة يعقل ذاته ويلتفت إليه حسبما يتبين بعد هذا. واما التشبه الثالث، فتحصل به المشاهدة الصرفة، والاستغراق المحض الذي لا التفات فيه بوجه من الوجوه الا إلى الموجود الواجب الوجود، والذي يشاهد هذه المشاهدة قد غابت عنه ذات نفسه وفنيت وتلاشت. وكذلك سائر الذوات، كثيرة كانت أو قليلة، إلا ذات الواحد الحق الواجب الوجود - جل وتعالى وعز. فلما تبين له أن مطلوبه الأقصى هو هذا التشبه الثالث، وأنه لا يحصل له إلا بعد التمرن والاعتمال مدة طويلة في التشبه الثاني، وان هذه المدة لا تدوم له بالتشبه الأول، وعلم أن التشبه الأول - وان كان ضرورياً، فانه عائق بذاته وان كان معيناً بالعرض لا بالذات لكنه ضروري- فألزم نفسه أن لا يجعل لها حظاً من هذا التشبه الأول، إلا بقدر الضرورة، وهي الكفاية التي لا بقاء للروح الحيواني بأقل منها. ووجد ما تدعو إليه الضرورة في بقاء هذا الروح أمرين: أحدهما: ما يمده من الداخل، ويخلف عليه بدل ما يتخلل منه وهو الغذاء. والأخر: ما يقيه من الخارج، ويدفع عنه وجوه الأذى: من البرد والحر والمطر ولفح الشمس والحيوانات المؤذية ونحو ذلك. ورأى أنه إن تناول ضرورية من هذه جزافاً كيفما اتفق، ربما وقع في السرف واخذ فوق الكفاية. فكان سعيه على نفسه من حيث لا يشعر، فرأى أن الحزم له أن يفرض لنفسه فيها حدوداً لا يتعداها، ومقادير لا يتجاوزها، وبأن له الفرض يجب أن يكون في جنس ما يتغذى به. وأي شيء يكون وفي مقداره وفي المدة التي تكون بين العبادات إليه. فنظر أولاً إلى أجناس ما به يتغذى، فرآها ثلاثة أضرب: أولاً: أما نبات لم يكمل بعد نضجه ولم ينته إلى غاية تمامه، وهي أصناف البقول الرطبة التي يمكن الاغتذاء بها.
ثانياً: واما ثمرات النبات الذي تم وانتهى وأخرج بذرة ليتكون منه أخر من نوعه حفظاً له، وهي أصناف الفواكه رطبها ويابسها. ثالثاً: واما حيوان من الحيوانات التي يتغذى بها: أما البرية واما البحرية. وكان قد صح عنده أن هذه الأجناس كلها، من فعل ذلك الموجود الواجب الوجود الذي تبين له أن سعادته في القرب منه، وطلب التشبه به، ولا محالة أن الاغتذاء بها مما يقطعها عن كمالها ويحول بينها وبين الغاية القصوى المقصودة بها. فكان ذلك اعتراض على فعل الفاعل. وهذا الاعتراض مضاد لما يطلبه من القرب منه والتشبه به. فرأى أن الصواب كان له لو أمكن أن يمتنع عن الغذاء جملة واحدة، لكنه لما لم يمكنه ذلك، لانه أن امتنع عنه أل ذلك إلى فساد جسمه، فيكون ذلك اعتراضاً على فاعله أشد من الأول، إذ هو أشرف من تلك الأشياء الآخر التي يكون فسادها سبباً لبقائه.
فاستهل أيسر الضررين، وتسامح في اخف الاعتراضين، ورأى إن يأخذ من هذه الأجناس إذا عدمت آيها تيسر له، بالقدر الذي يتبين له بعد هذا. فأما إن كانت كلها موجودة فينبغي له حينئذ إن يتثبت ويتخير منها ما لم يكن في أخذه كبير اعتراض على فعل فاعل، وذلك مثل لحوم الفواكه التي قد تناهت في الطيب، وصلح ما فيها لتوليد البزر على الشرط التحفظ على ذلك البزر، بان لا يأكله ولا يفسده ولا يلقيه في موضع لا يصلح للنبات، مثل الصفاة والسبخة ونحوهما. فان تعذر عليه وجود مثل هذه الثمرات ذات الطعم الغاذي، كالتفاح والكمثرى والأجاص ونحوها، كان له عند ذلك إن يأكل آما الثمرات التي لا يغذو منها إلا نفس البزر، كالجوز والقسطل، واما من البقول التي لم تصل بعد حد كمالها. والشرط عليه في هذين لأن يقصد أكثرها وجوداً وأقواها توليداً، وان لا يستأصل أصولها ولا يفني بزرها. فان عدم هذه، فله أن يأخذ من الحيوان آو من بيضه، والشرط عليه من الحيوان إن يأخذ من أكثره وجوداً، ويستأصل منه نوعاً بأسره. هذا ما رأى في جنس ما يتغذى به. واما المقدر فرأى أن يكون بحسب ما يسد خلة الجوع ولا يزيد عليها. واما الزمان الذي بين كل عودتين، فرأى انه إذا اخذ حاجته من الغذاء، أن يقيم عليه ولا يتعرض لسواه، حتى يلحقه ضعف يقطع به بعض الأعمال التي تجب عليه في التشبه الثاني، وهي التي يأتي ذكرها بعد هذا. فأما ما تدعو إليه الضرورة في بقاء الروح الحيواني مما يقيه من خارج، فكان الخطب فيه يسيراً: إذ كان مكتسياً بالجلود، وقد كان له مسكن يقيه مما يرد عليه من خارج، فاكتفى بذلك ولم يرى الاشتغال به، والتزم في غذائه القوانين التي رسمها لنفسه، وهي التي تقدم شرحها. ثم اخذ في العمل الثاني، وهو التشبه بالأجسام السماوية والاقتداء بها، والتقبل أوصافها، فانحصرت عنده في ثلاثة أضرب: الضرب الأول: أوصاف لها بالإضافة إلى ما تحتها من عالم الكون والفساد، وهي ما تعطيه إياه من التسخين بالذات، آو التبريد بالعرض، والإضاءة والتلطيف والتكثيف، إلى سائر ما تفعل فيه من الأمور التي بها يستعد لفيضان الصور الروحانية عليه من عند الفاعل الواجب الوجود. والضرب الثاني: أوصاف لها في ذاتها، مثل كونها شفافة وناصعة وطاهرة منزهة عن الكدر وضروب الرجس، ومتحركة بالاستدارة بعضها على مركز نفسها، وبعضها على مركز غيرها.
والضرب الثالث: أوصاف لها بالإضافة إلى الموجود الواجب الوجود، مثل كونها تشاهد مشاهدة دائمة، وتعرض عنه، وتتشوق إليه، وتتصرف بحكمه، وتتسخر في تتميم إرادته، ولا تتحرك إلا بمشيئته وفي قبضته. فجعل يتشبه بها جهده في كل من هذه الاضرب الثلاثة. آما الضرب الأول: فكان تشبه بها فيه: إن ألزم نفسه إن لا يرى ذا حاجة آو عاهة آو مضرة، أو ذا عائق من الحيوان أو النبات، وهو يقدر على أزالتها عنه إلا ويزيلها. فمتى وقع بصره على نبات قد حجبه عن الشمس حاجب آو تعلق به نبات آخر يؤذيه، أو عطش عطشاً يكاد يفسده، أزال عنه ذلك الحاجب إن كان ما يزال، وفصل بينه وبين ذلك المؤذي بفاصل لا يضر المؤذي، وتهده بالسقي ما أمكنه. ومتى وقع بصره على حيوان قد أرهقه سبع آو نشب به ناشب، آو تعلق به شوك، آو سقط على عينيه آو آذنيه شيء يؤذيه، آو مسه ظمأ آو جوع، تكفل بإزالة ذلك كله عنه جهده واطعمه وسقاه. ومتى وقع بصره على ماء يسيل إلى سقي نبات أو حيوان وقد عاقه عن ممره ذلك عائق، من حجر سقط فيه، آو جرف انهار عليه، ازال ذلك كله عنه. وما زال يمعن في هذا النوع من ضروب التشبه حتى بلغ فيه الغاية. واما الضرب الثاني: فكان تشبهه بها فيه إن الزم نفسه دوام الطهارة وإزالة الدنس والرجس عن جسمه والاغتسال بالماء في أكثر الأوقات، وتنظيف ما كان من أظافره واسنانه ومغابن بدنه، وتطيبها بما أمكن من طيبات النبات وصنوف الدهون العطرة، وتعهد لباسه بالتنظيف والتطييب حتى كان يتلألأ حسناً وجمالاً ونظافة وطيباً. والتزم مع ذلك ضروب الحركة على الاستدارة: فتارةً كان يطوف بالجزيرة، ويدور على ساحلها ويسيح باكنافها، وتارةً كان يطوف ببيته، او ببعض الكدى أدوارا معدوده: آما مشياً، آما هرولة؛ وتارة يدور على نفسه حتى يغشه عليه.
وأما الضرب الثالث: فكان تشبهه بها فيه، إن كان يلازم الفكرة في تلك الموجود الواجب الوجود، ثم يقطع علائق المحسوسات. ويغمض عينيه، ويسد أذنيه، ويضرب جهده عن تتبع الخيال، ويروم بمبلغ طاقته إن لا يفكر في شيء سواه، ولا يشترك به احداً ويستعين على ذلك بالاستدارة على نفسه والاستحثاث فيها.
فكان اذا اشتد في الاستدارة، غابت عنه جميع المحسوسات، وضعف الخيال وسائر القوى التي إلى الألأت الجسمانية، وقوي فعل ذاته - التي هي بريئة من الجسم - فكانت في بعض الأوقات فكرته قد تخلص عن الشوب ويشاهد بها الموجود الواجب الوجود، ثم تكر عليه القوى الجسمانية فتفسد عليه حاله، وترده إلى اسفل السافلين. ويعود من ذي قبل، فان لحقه ضعف يقطع به عن غرضه تناول بعض الأغذية عن الشرائط المذكورة. ثم انتقل إلى شأنه من التشبه بالأجسام السماوية بالأضرب الثلاثة المذكورة. ودأب على ذلك مدة وهو يجاهد قواه الجسمانية وتجاهده، وينازعها وتنازعه في الأوقات التي يكون له عليها الظهور، وتتخلص فكرته عن الشوب، يلوح له شيء من أحوال أهل التشبه الثالث.
ثم جعل يطلب التشبه الثالث، ويسعى في تحصيله، فينظر في صفات الموجود الواجب الوجود. وقد كان تبين له أثناء نظره العلمي قبل الشروع في العمل، إنها على ضربين: آما صفة ثبوت: كالعلم والقدرة والحكمة.
وأما صففة سلب: كتنزه عن الجسمانية وعن صفات الأجسام ولواحقها، وما يتعلق بها، ولو على بعد.
وأن صفات الثبوت يشترط فيها هذا التنزيه حتى لا يكون فيها شيء من صفات الأجسام التي من جملتها الكثرة، فلا تتكثر ذاته بهذه الصفات الثبوتية، ثم ترجع كلها إلى معنى واحد هي حقيقة ذاته. فجعل يطلب كيف يتشبه به في كل واحد من هذين الضربين. آما صفات الاجاب، فلما علم انها كلها راجعة إلى حقيقة ذاته، وانه لا كثرة فيها بوجه من الوجوه، إذ الكثرة من صفات الأجسام؛ وعلم إن علمه بذاته؛ ليس معنى زائداً على ذاته، بل ذاته هي علمه لذاته؛ وعلمه بذاته هو ذاته، تبين له انه إن أمكنه هو إن يعلم ذاته، فليس ذلك العلم الذي علم به ذاته معنى زائداً على ذاته، بل هو هو! فرأى إن التشبه به من صفات الاجاب، هو ان يعلمه فقط دون إن يشرك به شيئاً من صفات الأجسام؛ فاخذ نفسه بذلك. واما صقات السلب، فانها كلها راجعة إلى التنزه عن الجسمية. فجعل يطرح اوصاف الجسمية عن ذاته. وكان قد طرح منها كثيراً في رياضته المتقدمة التي كان ينحو بها بالتشبه بالأجسام السماوية. إلا انه أبقى منها بقايا كثيرة: كحركة الاستدارة - والحركة من أخص صفات الأجسام - وكل الاعتناء بأمر الحيوان والنبات والرحمة لها، والاهتمام بإزالة عوائقها. فان هذه أيضاً من صفات الأجسام، إذ لا يراها أولاً إلا بقوة جسمانية، ثم يكدح بأمرها بقوة جسمانية أيضاً. فاخذ في طرح ذلك كله عن نفسه، إذ هي بجملتها مما لا يليق بهذه الحالة التي يطلبها الآن.
وما زال يقتصر على السكون في قصر مغارته مطرقاً، غاضاً بصره، معرضاً عن جميع المحسوسات والقوى الجسمانية، مجتمع الهم والفكرة في الموجود الواجب الوجود وحده دون شركه؛ فمتى سنح بخياله سانح سواه، طرده عن خياله جهده، ودافعه وراض نفسه على ذلك، ودأب فيه مدة طويلة، بحيث تمر عليه عدة أيام لا يتغذى فيها ولا يتحرك. وفي خلال شدة مجاهدته هذه ربما كانت تغيب عن ذكره وفكره جميع الأشياء إلا ذاته، فانها كانت لا تغيب عنه في وقت استغراقه بمشاهدة الموجود الأول الحق الواجب الوجود.
فكان يسوءه ذلك، ويعلم انه شوب في المشاهدة المحضة، وشركه في الملاحظة. ومازال يطلب الفناء عن نفسه والإخلاص في مشاهدة الحق حتى تأتى له ذلك، وغابت عن ذكره وفكره السموات والأرض وما بينهما، وجميع الصور الروحانية والقوى الجسمانية، وجميع القوى المفارقة للمواد، والتي هي الذوات العارفه بالموجود الحق؛ وغابت ذاته في جملة تلك الذوات، وتلاشى الكل واضمحل، وصار هباءً منثوراً، ولم يبقى إلا الواحد الحق الموجود الثابت الوجود.
وهو يقول بقوله الذي ليس معنى زائداً على ذاته: "بسم الله الرحمن الرحيم" لمن الملك اليوم لله الواحد القهار صدق الله العظيم ففهم كلامه وسمع ندائه ولم يمنعه عن فهمه كونه لا يعرف الكلام، ولا يتكلم.
واستغرق في حالته هذه وشاهد ما لا عين رأت ولا إذن سمعت! ولا خطر على قلب بشر. فلا تعلق قلبك بوصف آمر لم يخطر على قلب بشر، فان كثيراً من الأمور التي تخطر على قلوب البشر قد يتعذر وصفه، فكيف بأمر لا سبيل إلى خطورة على القلب، ولا هو من عالمه ولا من طوره!؟ ولست أعني بالقلب جسم القلب، ولا الروح التي في تجويفه بل أعني صورة تلك الروح الفائضة بقواها على بدن الإنسان، فان كل واحد من هذه الثلاثة قد يقال له قلب ولكن لا سبيل لخطور ذلك الآمر على واحد من هذه الثلاثة، ولا يتأتى التعبير إلا عما الخطر علها.
ومن رام التعبير عن تلك الحال، فقد رام مستحيلاً وهو بمنزلة من يريد أن يذوق الألوان من حيث هي الألوان، ويطلب أن يكون السواد مثلاً حلواً أو حامضاً.
لكنا، مع ذلك، لا نخيلك عن إشارات نومئ بها إلى ما شاهده من عجائب ذلك المقام، على سبيل ضرب المثل، لا على سبيل قرع باب الحقيقية. إذ لا سبيل إلى التحقق بما في ذلك المقام إلا بالوصول إليه.
فأصغ الآن بسمع قلبك، وحدق ييصر إلى ما أشير به اليك لعلك أن تجد منه هدياً يلقيك على جادة الطريق! وشرطي عليك أن لا تطلب مني في هذا الوقت مزيد بيان بالمشافهة على ما أودعه هذه الاوراق فان المجال ضيق، والتحكم بالألفاظ على آمر ليس من شأنه أن يلفظ به خطر.
فأقول: انه لما فني عن ذاتهوعن جميع وعن جميع الذوات ولم ير في الوجود إلا الواحد القيوم، وشاهد ما شاهد، ثم عاد إلى ملاحظة الاغيار عندما آفاق من حالة تلك التي شبيه بالسكر، خطر بباله انه لا ذات له يغاير بها ذات الحق تعالى، وان حقيقة ذاته هي ذات الحق، وان الشيء الذي كان يظن أولاً انه ذات المغايرة لذات الحق، ليس شيئاً في الحقيقة، بل ليس ثم شيء إلا ذات الحق، وان ذلك بمنزلة نور الشمس الذي يقع على الأجسام الكثيفة فتراه يظهر فيها.
فإنه وإن نسب إلى الجسم الذي يظهر فيه، فليس هو في الحقيقية شيئاً سوى نور الشمس. وان زال ذلك الجسم زال نوره، وبقي نور الشمس بحاله لم ينقص عند حضور ذلك الجسم ولم يزد عند مغيبه.
ومتى حدث جسم يصلح لقبول ذلك النور، قبله، فإذا عدم الجسم عدم ذلك القبول، ولك يكن له معنى، عنده هذا الظن بما قد بان له من إن ذات الحق، عز وجل، لا تتكثر بوجهه من الوجوه، وأن علمه بذاته، وهو ذاته بعينها.
فلزم عنده من هذا أن حصل عنده العلم بذاته، فقد حصلت عنده ذاته، وقد كان حصل عنده العلم فحصلت عنده الذات.
وهذه الذات لا تحصل إلا عند ذاتها، ونفس حصولها هو الذات؛ فإذن هو الذات بعينها. وكذلك جميع الذوات المفارقة للمادة العارفة بتلك الذات الحقه التي كان يراها أولاً كثيرة، وصارت عنده بهذا الظن شيئاً واحداً. وكادت هذه الشبه ترسخ في نفسه لولا أن تداركه الله برحمته وتلافاه بهدايته، فعلم إن الشبهة انما ثارت عنده من بقايا ظلمة الأجسام، وكدورة المحسوسات. فان الكثير والقليل والواحد والوحدة، والجمع والاجتماع، والافتراق، هي كلها من صفات الأجسام، وتلك الذوات المفارقة العارفة بذات الحق، عز وجل، لبرائتها عن المادة، لا يجب إن يقال انها كثيرة، ولا واحدة، لان الكثرة انما هي مغايرة الذوات بعضها لبعض، والوحدة أيضاً لا تكون إلا بالاتصال. ولا يفهم شيء من ذلك إلا في المعاني المركبة المتلبسة بالمادة. غير إن العبارة في هذا الموضع قد تضيق جداً لانك إن عبرت عن تلك الذوات المفارقة بصيغة الجمع حسب لفظنا هذا، أوهم ذلك معنى الكثرة فيها، وهي بريئة عن الكثرة. وان أنت عبرت بصيغة الإفراد، اوهم ذلك معنى الاتحاد، وهو مستحيل عليها. وكأني بمن يقف على هذا الموضع من الخفافيش الذين تظلم الشمس في أعينهم يتحرك في سلسلة جنونه، ويقول: لقد افرطت في تدقيقك حتى انك قد انخلعت عن غريزة العقلاء، واطرحت حكم معقول، فان من أحكام العقل إن الشيء آما واحد واما كثير، فليتئد في غلوائه، وليكف من غرب لسانه وليتهم نفسه، وليعتبر بالعالم المحسوس الخسيس الذي هو أطباقه بنحو ما اعتبر به حي بن يقظان حيث كان بنظر فيه بنظر فيراه كثيراً كثرة لا تنحصر ولا تدخل تحت حد، ثم ينظر فيه بنظر آخر، فيراه واحداً. وبقي في ذلك متردداً ولم يكنه إن يقطع بأحد الوصفين دون الآخر. هذا فالعالم المحسوس منشأ الجمع والإفراد، وفيه الانفصال والاتصال، والتحيز والمغايرة، والاتفاق والاختلاف، فما ظنه بالعالم الإلهي الذي لا يقال فيه كل ولا بعض، ولا ينطق في أمره بلفظ من الألفاظ المسموعة، إلا وتوهم فيه شيء على خلاف الحقيقة، فلا يعرفه إلا من شاهده؛ ولا تثبت حقيقته إلا عند من حصل فيه. واما قوله: حتى انخلعت عن غريزة العقلاء، واطرحت حكم المعقول. فنحن نسلم له ذلك، ونتركه مع عقله وعقلائه، فان العقل الذي يعنيه هو أمثاله، انما هو القوة الناطقة التي تتصفح أشخاص الموجودات المحسوسة، وتقتنص منها المعنى الكلي. والعقلاء الذين يعنيهم، هم ينظرون من هذا النظر والنمط الذي كلامنا فيه فوق هذا كله، فليسد عنه سمعه من لا يعرف سوى المحسوسات وكلياتها، وليرجع إلى فريقه الذين "بسم الله الرحمن الرحيم" يعملون ظاهراً من الحياة الدنيا. وهم عن الآخرة هم غافلون. صدق الله العظيم. فان كنت ممن يقتنع بهذا النوع من التلويح والإشارة إلى ما في العالم الإلهي، ولا تحمل ألفاظاً من المعاني على ما جرت العادة بها في تحميلها إياه، فنحن نزيدك شيئاً مما شاهده حي بن يقظان في مقام أولي الصدق الذي تقدم ذكره، فتقول: انه بعض الاستغراق المحض، والفناء التام، وحقيقة الوصول، وشاهد للفلك الأعلى، الذي لا جسم له، ورأى ذاتاً بريئة عن المادة، ليست هي ذات الواحد الحق، ولا هي نفس الفلك، ولا هي غيرها؛ وكأنها صورة الشمس التي تظهر في مرآة من المرائي الصقيلة، فانها ليست هي الشمس ولا المرأة ولا غيرهما. وراى لذات ذلك الفلك المفارقة من الكمال والبهاء والحسن، ما يعظم عن إن يوصف بلسان، ويدق إن يكسى بحرف آو صوت، وراه في غاية من اللذة والسرور، والغبطة والفرح، بمشاهدة ذات الحق جل جلاله. وشاهد ايضاً للفلك الذي يليه، وهو فلك الكواكب الثابتة، ذاتاً بريئة عن المادة أيضاً، ليست هي ذات الواحد الحق، ولا ذات الفلك الأعلى المفارقة، ولا نفسه، ولا هي غيرها. وكأنها صورة الشمس التي تظهر في المرآة قد انعكست إليها من مرآة أخرى مقابلة للشمس، ورأى لهذه الذات ايضاً من البهاء والحسن واللذة مثل ما راى لتلك التي للفلك الأعلى. وشاهد ايضاً للفلك الذي يلي هذا، وهو فلك زحل ذاتاً مفارقة للمادة ليست هي شيئاً من الدواب التي شاهدها قبله ولا هي غيرها؛ وكأنها صورة الشمس التي تظهر في مرآة قد انعكست إليها الصورة من مرآة مقابلة للشمس؛ وراى لهذه الذات ايضاً مثل ما راى آمل قبلها من البهاء واللذة. ومازال يشاهد لكل فلك ذاتاً مفارقة بريئة عن المادة ليست هي شيئاً من الذوات التي قبلها ولا هي غيرها وكأنها صورة الشمس التي تنعكس من مرآة على مرآة، على رتب مرتبة بحسب ترتيب الأفلاك. وشاهد لكل ذات من هذه الذوات من الحسن والبهاء، واللذة والفرح، ما لا عين رأت، ولا أذن سمعت، ولا خطر على قلب بشر. إلى أن انتهى إلى عالم الكون والفساد، وهو جميعه حشو فلك القمر. فرأى له ذاتاً بريئة عن المادة ليست شيئاً من الذوات التي شاهدها قبلها، ولا هي سواها. ولهذه سبعون ألف وجه، في كل وجه سبعون ألف فم، في كل فم سبعون ألف لسان، يسبح بها ذات الواحد الحق، ويقدسها ويمجدها، لا يفتر؛ ورأى لهذه الذات، التي توهم فيها الكثرة وليست كثيرة، من الكمال واللذة، مثل الذي رآه لما قبلها. وكأن هذه الذات صورة الشمس التي تظهر في ماء مترجرج، وقد انعكست إليها الصورة من آخر المرايا التي انتهى إليها الانعكاس على الترتيب المتقدم من المرآة الأولى التي قابلت الشمس بعينها. ثم شاهد لنفسه ذاتاً مفارقة، لو جاز إن تتبعض ذات السبعين ألف وجه، لقلنا انها بعضها. ولولا إن هذه الذات حدثت بعد إن لم تكن، لقلنا إنها هي! ولولا اختصاصها ببدنه عند حدوثه، لقلنا إنها لم تحدث! وشاهد في هذه الرتبة ذواتاً، مثل ذاته، لاجسام كانت ثم اضمحلت، ولاجسام لم تزل معه في الوجود، وهي من الكثرة في حد بحيث لا تتناهى إن جاز أن يقال لها كثيرة، أو هي كلها متحدة إن جاز إن يقال لها واحدة. وراى لذاته ولتلك الذوات التي في رتبته من الحسن والبهاء واللذة غير المتناهية، ما لا عين رأت ولا أذن سمعت، ولا خطر على قلب بشر، ولا يصفه الواصفون، ولا يعقله إلا الواصلون العارفون. وشاهد ذواتاً كثيرة مفارقة للمادة كأنها مرايا صدئة، قد ران عليها الخبث، وهي مع ذلك مستدبرة للمرايا الصقيلة التي ارتسمت فيها صورة الشمس، ومولية عنها بوجوهها، وراى لهذه الذوات من القبح والنقص ما لم يقم بباله قط؛ وراها في ألام لا تنقضي، وحسرات لا تنمحي؛ قد أحاط بها سرادق العذاب، وأحرقتها نار الحجاب، ونشرت بمناشير بين الانزعاج والانجذاب. وشاهد هنا ذواتاً سوى هذه المعذبة تلوح ثم تضمحل، وتنعقد ثم تنحل، فتثبت فيها وأنعم النظر إليها، فرأى هولاً عظيماً وخطباً جسيماً، وخلقاً حثيثاً، وأحكاماً بليغة، وتسوية ونفخاً وإنشاء ونسخاً. فما هو إلا إن تثبت قليلاً، فعادت إليه حواسه، وتنبه من حاله تلك التي كانت شبيهة بالغشي، وزلت قدمه عن ذلك المقام، ولاح له العالم المحسوس، وغاب عنه العالم الإلهي: إذ لم يكن اجتماعهما في حال واحدة، إذ الأخرى والدنيا كضرتين، إن أرضيت احدهما أسخطت الأخرى، فان قلت يظهر مما حكيته من هذه المشاهدة، إن الذوات المفارقة إن كانت لجسم دائم الوجود لا يفسد، كالأفلاك، كانت هي دائمة الوجود؛ وان كانت لجسم يؤول إلى الفساد كالحيوان الناطق، فسدت هي واضمحلت وتلاشت، حسبما مثلث به في المرايا الانعكاس، فان الصورة لا ثبات لها إلا ثبات بثبات المرآة، فإذا فسدت المرآة صح فساد الصورة واضمحلت هي؛ فأقول لك: ما لأسرع ما نسيت العهد، وحلت عن الربط، ألم نقدم إليك إن مجال العبارة هنا ضيق، وان الألفاظ على كل حال توهم غير الحقيقة وذلك الذي توهمته إنما أوقعك فيه، إن جعلت المثال والممثل به على حكم واحد من جميع الوجوه. ولا ينبغي أن يفعل ذلك في أصناف المخاطبات المعتادة، فكيف ها هنا والشمس ونورها، وصورتها وتشكلها والمرايا والصور الحاصلة فيها، كلها أمور غير مفارقة للأجسام، ولا قوام لها إلا بها وفيها؟ فلذلك افتقرت في وجودها إليها وبطلت ببطلانها. واما الذوات الإلهية، والأرواح الربانية، فانها كلها بريئة عن الأجسام ولواحقها ومنزهة غاية التنزيه عنها، فلا ارتباط ولا تعلق لها بها، وسواء بالإضافة إليها بطلان الأجسام أو ثبوتها، ووجودها أو عدمها؛ وانما ارتباطها وتعلقها بذات الواحد الحق الموجود الواجب الوجود، الذي هو أولها ومبدؤها وسببها وموجدها، وهو يعطيها الدوام ويمدها بالبقاء والتسرمد؛ ولا حاجة بها إلى الأجسام بل الأجسام المحتاجة إليها. ولو جاز عدمها لعدمت الأجسام فانها هي مبديها، كما انه لو جاز إن تعدم ذات الواحد الحق - تعالى وتقدس عن ذلك؛ لا اله إلا هو! - لعدمت هذه الذوات كلها، ولعدمت الأجسام، ولعدم العالم الحسي بآسره، ولم يبق موجود، إذ الكل مرتبط بعضه ببعض. والعالم المحسوس وان كان تابعاً للعالم الإلهي، شبيه الظل له؛ والعالم الإلهي مستغن عنه وبريء منه فانه مع ذلك قد يستحيل فرض عدمه، إذ هو لا محالة تابع للعالم الإلهي، وانما فساده إن يبدل، لا إن يعدم بالجملة، وبذلك نطق الكتاب العزيز حيثما وقع هذا المعنى منه في تسيير الجبال وتسييرها كالعهن والناس كالفراش. وتكوير الشمس والقمر، وتفجيرالبحار يوم تبدل الارض غير الأرض والسموات. فهذا القدر هو الذي امكنني الآن أن أشير إليك به فيما شاهده حي بن يقظان في ذلك المقام الكريم فلا تلتمس الزيادة عليه من جهة الألفاظ فان ذلك كالمعتذر. واما تمام خبره - فسأتلوه عليك إن شاء الله تعالى: وهو انه لما عاد إلى العالم المحسوس، وذلك بعد جولا نه حيث جال، سئم تكاليف الحياة الدنيا، واشتد شوقه إلى الحياة الدنيا، واشتد شوقه إلى الحياة القصوى، فجعل يطلب العود إلى ذلك المقام بالنحو الذي طلبه أولاً حتى وصل إليه بأيسر من السعي الذي وصل به أولاً ودام فيه ثانياً مدة أطول من الأولى. ثم عاد إلى عالم الحس. ثم تكلف الوصول إلى مقامه بعد ذلك فكان ايسر عليه من الأولى والثانية وكان دوامه أطول. وما زال الوصول إلى ذلك المقام الكريم يزيد عليه سهولة، والدوام يزيد فيه طولاً مدة بعد مدة، حتى صار يصل إليه متى شاء، ولا ينفصل عنه إلا متى شاء؛ فكان يلازم مقامه ذلك ولا ينثني عنه إلا لضرورة بدنه التي كان قد قللها، حتى كان لا يوجد اقل منها. وهو في كل ذلك كله يريد إن يريحه الله عز وجل من كل بدنه الذي يدعوه إلى مفارقة مقامه ذلك، فيتخلص إلى لذته تخلصاً دائماً، ويبرأ عما يجده من الألم عند الأعراض عن مقامه ذلك إلى ضرورة البدن. وبقي على حالته تلك حتى أناف على سبعة أسابيع من منشئه وذلك خمسون عاماً. وحينئذ اتفقت له صحبة أسال وكان من قصته معه ما يأتي ذكره بعد هذا إن شاء الله تعالى. ذكروا: إن جزيرة قريبة من الجزيرة التي ولد بها حي بن يقظان على أحد القولين المختلفين على صفة مبدئه، انتقلت إليه ملة من الملل الصحيحة الماخوذه على بعض الأنبياء المتقدمين، صلوات الله عليهم. وكانت ملة محاكية لجميع الموجودات الحقيقية بالأمثال المضروبة التي خيالات تلك الأشياء، وتثبت رسومها في النفوس، حسبما جرت به العادة في مخاطبة الجمهور؛ فما زالت تلك الملة تنتشر بتلك الجزيرة وتقوى وتظهر، حتى قام بها ملكها وحمل الناس على التزامها. وكان قد نشأ بها فتيان من أهل الفضل والخير، يسمى أحدهما أسال والآخر سلامان فتلقيا هذه الملة وقبلاها احسن قبول، واخذ على أنفسهما على بالتزام جميع شرائعها والموظبة على جميع أعمالها، واصطحبا على ذلك. وكانا يتفقهان في بعض الأوقات فيما ورد من ألفاظ تلك الشريعة في صفة الله عز وجل وملائكته، وصفات الميعاد والثواب والعقاب. فأما أسال فكان أشد غوصاً على الباطن، وأكثر عثوراً على المعاني الروحانية واطمع في التأويل. واما سلامان صاحبه فكان أكثر احتفاظاً بالظاهر، وأشد بعداً عن التأويل، وأوقف عن التصرف والتأمل؛ وكلاهما مجد في الأعمال الظاهرة، ومحاسبة النفس، ومجاهدة الهوى. وكان في تلك الشريعة أقوال تحمل عن العزلة والانفراد، وتدل على إن الفوز والنجاة فيهما؛ واقوال أخر تحمل على المعاشرة وملازمة الجماعة. فتعلق أسال بطلب العزلة، ورجح القول فيها لما كان في طباعه من دوام الفكرة، وملازمة العبرة، والغوص على المعاني، وأكثر ما كان يتأتى له أمله من ذلك بالانفراد. وتعلق سلامان بملازمة الجماعة، ورجح القول فيها لما كان في طباعه من الجبن عن الفكرة والتصرف. فكانت ملازمته الجماعة عنده مما يدرأ الوسواس، ويزيل الظنون المعترضة ويعيد من همزات الشياطين. وكان اختلافهما في هذا الرأي سبب افتراقهما. وكان أسال قد سمع عن الجزيرة التي ذكر أن حي بن يقظان تكون بها وعرف ما بها من الخصب والمرافق والهواء المعتدل، وان الانفراد بها يتأتى لملتمسه، فأجمع إن يرتحل إليها ويعتزل الناس بها بقية عمره. فجمع ما كان له من المال، واشترى ببعضه مركباً تحمله إلى تلك الجزيرة، وفرق باقيه على المساكين، وودع صاحبه سلامان وركب متن البحر؛ فحمله الملاحون إلى تلك الجزيرة؛ ووضعوه بساحلها؛ وانفصلوا عنها. فبقي أسال بتلك الجزيرة يعبد الله عز وجل؛ ويعظمه ويقدسه؛ ويفكر في اسمائه الحسنى وصفاته العليا؛ فلا ينقطع خاطره؛ ولا تتكدر فكرته. واذا احتاج إلى غذاء تناول من ثمرات تلك الجزيرة وصيدها ما يسد بها جوعته. وأقام على تلك الحال مدة وهو في أتم غبطة وأعظم أنس بمناجاة ربه. وكان كل يوم يشاهد من ألطافه ومزايا تحفة وتيسره عليه في مطلبه وغذائه ما يثبت يقينه ويقر عينه. وكان في تلك المدة حي بن يقظان شديد الاستغراق في مقاماته الكريمة؛ فكان لا يبرح عن مغارته إلا مرة في الاسبوع لتناول ما سنح من الغذاء، فلذلك لم يعثر عليه أسال لأول وهلة، بل كان يتطوف بأكناف تلك الجزيرة ويسبح في أرجائها، فلا يرى أنسياً ولا يشاهد أثراً فيزيد بذلك أنسه وتنبسط نفسه لما كان قد عزم عليه من التناهي في طلب العزلة والانفراد. إلى إن اتفق في بعض تلك الأوقات إن خرج حي بن يقظان لالتماس غذائه وأسال قد ألم بتلك الجهة، فوقع بصر كل منهما على الآخر. فإما أسال فلم يشك أنه من العباد المنقطعين، وصل تلك الجزيرة لطلب العزلة عن الناس كما وصل هو إليها. فخشي إن هو تعرض له وتعرف به إن يكون سبباً في فساد حاله وعائقاً بينه وبين أمله. واما حي بن يقظان فلم يدر ما هو، لانه لم يره على صورة شيء من الحيوانات التي كان قد عاينها قبل ذلك. وكان عليه مدرعة سوداء من الشعر والصوف، فظن إنها لباس طبيعي. فوقف يتعجب منه ملياً. وولى أسال هارباً منه خيفة أن يشغله عن حاله، فاقتفى حي بن يقظان أثره لما كان في طباعه من البحث عن الحقائق. فلما رآه يشتد في الهرب. خنس عنه وتوارى له، حتى ظن أسال انه قد انصرف عنه وتباعد من تلك الجهة. فشرع أسال في الصلاة والقراءة، والدعاء والبكاء، والتضرع والتواجد، حتى شغله ذلك عن كل شيء. فجعل حي بن يقظان يتقرب منه قليلاً قليلاً، وأسال لا يشعر به حتى دنا منه بحيث يسمع قراءته وتسبيحه، ويشاهد خضوعه وبكائه. فسمع صوتاً حسناً وحروف منظمة، لم يعهد مثلها من شيء من أصناف الحيوان. ونظر إلى أشكاله وتخطيطه فرآه على صورته، وتبين له أن المدرعة التي عليه ليست جلداً طبيعياً، وانما هي لباس متخذ مثل لباسه هو، ولما رأى حسن خشوعه وتضرعه وبكائه لم يشك في انه من الذوات العارفة بالحق؛ فتشوق إليه واراد إن يرى ما عنده، وما الذي أوجب بكاءه وتضرعه؛ فزاد في الدنو منه حتى أحس به أسال؛ فاشتد في العدو، واشتد حي بن يقظان في أثره حتى التحق به - لما كان أعطاه الله من القوة والبسطة في العلم والجسم - فالتزمه وقبض عليه؛ ولم يمكنه من البراح. فلما نظر إليه أسال وهو مكتس بجلود الحيوان ذوات الاوبار؛ وشعره قد طال حتى جلل كثيراً منه، ورأى ما عنده من سرعة العدو وقوة البطش، فرق منه فرقاً شديداً، وجعل يستعطفه ويرغب إليه بكلام لا يفهمه حي بن يقظان ولا يدري ما هو، غير أنه يميز فيه شمائل الجزع. فكان يؤنسه بأصوات كان قد تعلمها من الحيوانات، ويجر يده على رأسه، ويمسح أعطافه. ويتملق إليه، ويظهر البشر والفرح به. حتى سكن جأش أسال وعلم أنه لا يريد به سوءاً. كان أسال قديماً لمحبته في علم التأويل. قد تعلم أكثر الألسن، ومهر فيها. فجعل يكلم حي بن يقظان ويسائله عن شأنه بكل لسان يعلمه ويعالج أفهامه فلا يستطيع، وحي بن يقظان في ذلك كله يتعجب مما يسمع ولا يدري ما هو. غير أنه يظهر له البشر والقبول. فاستغرب كل واحد منهما أمر صاحبه. وكان عند أسال من زاد كان قد اصطحبه من الجزيرة المعمورة، فقربه إلى حي بن يقظان فلم يدر ما هو، لانه لم يكن شاهده قبل ذلك. فأكل منه أسال وأشار إليه ليأكل ففكر حي بن يقظان فيما كان ألزم نفسه من الشروط لتناول الغذاء، ولم يدر اصل ذلك الشيء الذي قدم له ما هو، وهل يجوز له تناوله أم لا! فامتنع عن الآكل. ولم يزل أسال يرغب إليه ويستعطفه. وقد كان اولع به حي بن يقظان فخشي إن دام على امتناعه إن يوحشه، فاقدم على ذلك الزاد وأكل منه. فلما ذاقه واستطابه بدا له سوء ما صنع من نقض عهوده في شرط غذاء، وندم على فعله، وأراد الانفصال عن أسال والإقبال على شأنه من طلب الرجوع إلى مقامه الكريم، فلما تتأت له المشاهدة بسرعة. فرأى أن يقيم مع أسال في عالم الحس حتى يقف على حقيقة شأنه، ولا يبقي في نفسه هو نزوع إليه، وينصرف بعد ذلك إلى مقامه دون إن يشغله شاغل. فالتزم صحبة أسال ولما رأى أسال أيضاً انه لا يتكلم، آمن من غلوائه على دينه، ورجا أن يعلمه الكلام والعلم والدين، فيكون له بذلك أعظم أجر وزلفى عند الله. فشرع أسال في تعليمه الكلام أولاً بأن كان يشير له إلى أعيان الموجودات وينطق بأسمائها ويكرر ذلك عليه ويحمله على النطق، فينطق بها مقترناً بالاشارة، حتى علمه الأسماء كلها، ودرجه قليلاً قليلاً حتى تكلم في أقرب مدة. فجعل أسال يسأله عن شأنه ومن أين صار إلى تلك الجزيرة، فأعلمه حي بن يقظان انه لا يدري لنفسه ابتداء ولا أباً ولا أماً أكثر من الظبية التي ربته، ووصف له شأنه كله وكيف ترقى بالمعرفة، حتى انتهى إلى درجة الوصول.
فلما سمع أسال منه وصف تلك الحقائق والذوات المفارقة لعالم الحس العارفة بذات الحق عز وجل، ووصفه ذلك الحق تعالى وجل بأوصافه الحسنى، ووصف له ما أمكنه وصفه مما شاهده عند الوصول من لذات الواصلين وألام المحجوبين، لم يشك أسال في أن جميع الأشياء التي وردت في شريعته من أمر الله عز وجل، وملائكته، وكتبه، ورسله، واليوم الآخر، وجنته وناره، هي أمثلة هذه التي شاهدها حي بن يقظان؛ فانفتح بصر قلبه وانقدحت نار خطره وتطابق عنده المعقول والمنقول، وقربت عليه طرق التأويل، ولم يبق عليه مشكل في الشرع إلا تبين له، ولا مغلق إلا انفتح، ولا غامض إلا اتضح، وصار من أولى الألباب. وعند ذلك نظر إلى حي بن يقظان بعين التعظيم والتوقير، وتحقق عنده أنه من أولياء الله الذين لا خوف عليهم ولا هم يحزنون. فالتزم خدمته والاقتداء به بإشارته فيما تعارض عنده من الأعمال الشرعية التي قد تعلمها في ملته. وجعل حي بن يقظان يستفصحه عن أمره وشأنه، فجعل أسال يصف له شأن جزيرته وما فيها من العالم، وكيف كانت سيرهم قبل وصول الملة اليهم.
وكيف هي الآن بعد وصولها إليهم، وصف له جميع ما ورد في الشريعة من وصف العالم الإلهي، والجنة والنار، والبعث والنشور، والحشر والحساب، والميزان والصراط. ففهم حي بن يقظان ذلك كله ولم ير فيه شيء على خلاف ما شاهده في مقامه الكريم. فعلم أن الذي وصف ذلك وجاء به محق في وصفه، صادق في قوله، ورسول من عند ربه؛ فأمن به وصدقه وشهد برسالته.
ثم جاء يسأله عما جاء به من الفرائض، ووضعه من العبادات؛ فوصف له الصلاة والزكاة، والصيام والحج، وما أشبهها من الأعمال الظاهرة؛ فتلقى ذلك والتزمه، وأخذ نفسه بأدائه امتثالاً للآمر الذي صح عنده صدق قوله.
إلا انه بقي في نفسه أمران كان يتعجب منهما ولا يدري وجه الحكمة فيهما: أحدهما - لما ضرب هذا الرسول الأمثال للناس في أكثر ما وصفه من أمر العالم الإلهي، وأضرب عن المكاشفة حتى وقع الناس في أمر عظيم من التجسيم، واعتقاد أشياء في ذات الحق هو منزه عنها وبريء منها؟ وكذلك في أمر الثواب والعقاب! والآمر الآخر - لم اقتصر على هذه الفرائض ووظائف العبادات وأباح الاقتناء للأموال والتوسع في المأكل، حتى بفرغ الناس بالاشتغال بالباطل، والأعراض عن الحق؟ وكان رأيه هو لا يتناول أحد شيئاً إلا ما يقيم به من الرمق؛ واما الأموال فلم تكن لها عنده معنى.
وكان يرى ما في الشرع من الأحكام في أمر الأموال: كالزكاة وتشعبها، والبيوع والربا والحدود والعقوبات، فكان يستغرب هذا كله ويراه تطويلاً، ويقول: إن الناس لو فهموا الآمر على حقيقته لاعرضوا عن هذه البواطل، وأقبلو على الحق، واستغنوا عن هذا كله، ولم يكن لاحد اختصاص بمال يسأل عن زكاته، أو تقطع الأيدي على سرقته، أو تذهب النفوس على أخذه مجاهرة.
وكان الذي أوقعه في ذلك ظنه، أن الناس كلهم ذوو فطر فائقة، وأذهان ثاقبة، ونفوس عازمة، ولم يكن يدري ما هم عليه من البلادة والنقص، وسوء الرأي وضعف العزم، وأنهم كالأنعام بل هم أضل سبيلاً.
فلما اشتد إشفاقه على الناس، وطمع أن تكون نجاتهم على يديه، حدثت له النية في الوصول إليهم، وإيضاح الحق لديهم، وتبييه لهم ففاوض في ذلك صاحبه أسال وسأله: هل تمكنه حيلة في الوصول اليهم؟ فأعلمه بما هم فيه من نقص الفطرة والأعراض عن آمر الله فلم يتأت له فهم ذلك، وبقي في نفسه تعلق بما كان قد أمله.
وطمع أسال أيضاً أن يهدي الله على يديه طائفة من معارفه المريدين الذين كانوا أقرب من التخلص من سواهم، فساعده على رأيه، ورأيا أن يلتزما ساحل البحر ولا يفارقاه ليلاً ولا نهاراً، لعل الله إن السني لهما عبور البحر فالتزما ذلك وابتهلا الله تعالى أن يهيء لهما من أمرهما رشدأً.
فكان من أمر الله عز وجل أن سفينة ضلت مسلكها، ودفعها الرياح وتلاطم الأمواج إلى ساحلها. فلما قربت من البر رأى أهلها الرجلين على الشاطئ.
فدنوا منها فكلمهم أسال وسألهم أن يحملوهما معهم، فأجابوهما إلى ذلك، وأدخلوهما السفينة، فأرسل الله إليهم ريحاً رخاء حملت السفينة في أقرب مدة إلى الجزيرة التي أملاها فنزلا بها، ودخلا مدينتها، واجتمع أصحاب أسال به، فعرفهم شأن حي بن يقظان، فاشتملوا عليه شديداً وأكبروا آمره، واجتمعوا إليه واعظموه وبجلوه، وأعلمه أسال أن تلك الطائفة هم أن تلك الطائفة هم أقرب إلى الفهم والذكاء من جميع الناس، وانه إن عجز عن تعليمهم فهو عن تعليم الجمهور أعجز.
وكان رأس تلك الجزيرة سلامان وهو صاحب أسال الذي كان يراه ملازمة الجماعة، ويقول بتحريم العزلة، فشرع حي بن يقظان في تعليمهم وبث أسرار الحكمة إليهم.
فما هو إلا أن ترقى عن الظاهر قليلاً وأخذ في وصف ما سبق إلى فهمهم خلافه، فجعلوا ينقبضون منه وتشمئز نفوسهم مما يأتي به، ويتسخطونه بقلوبهم، وان اظهروا له الرضا في وجهه اكراماً لغربته فيهم، ومراعاة لحق صاحبهم أسال! وما زال حي بن يقظان يستلطفهم ليلاً ونهاراً، ويبن لهم الحق سراً وجهاراً، فلا يزيدهم ذلك إلا نبوأً ونفاراً، مع أنهم كانوا محبين للخير، راغبين في الحق، إلا انهم لنقص فطرتهم كانوا لا يطلبون الحق من طريقة ولا يأخذونه لجهة تحقيقه، ولا يلتمسونه من بابه، بل كانوا لا يريدون معرفته من طريق أربابه. فيأس من أصلاحهم، وانقطع رجائه من صلاحهم لقلة قبولهم.
وتصفح طبقات الناس بعد ذلك، فرأى كل حزب بما لديهم فرحون، قد اتخذوا ألههم هواهم، ومعبودهم شهواتهم، وتهالكوا في جميع حطام الدنيا، ألهاهم التكاثر حتى زاروا المقابر، لا تنجح فيهم الموعظة ولا تعمل فيهم الكلمة الحسنة، ولا يزدادون بالجدل إلا إصرارا.
واما الحكمة فلا سبيل لهم إليها، ولا حظ لهم منه، قد غمرتهم الجهالة وران على قلوبهم ما يكسبون ختم الله على قلوبهم وعلى سمعهم وعلى أبصارهم غشاوةً ولهم عذاب عظيم.
فلما رأى سرادق العذاب قد أحاط بهم، الظالمات الحجب قد تغشتهم، والكل منهم - إلا اليسير - لا يتمسكون من ملتهم إلا بالدنيا، وقد نبذوا أعمالهم على خفتها وسهولتها وراء ظهورهم، واشتروا بها ثمناً قليلاً، وألهاهم عن ذكر الله تعالى التجارة والبيع، ولم يخافوا يوماً تنقلب فيه القلوب والابصار، لأن له وتحقق على القطع، أن مخاطبتهم بطريق المكاشفة لا تمكن وأن تكليفهم من العمل فوق هذا القدر لا يتفق، وأن حظ أكثر الجمهور من الانتفاع بالشريعة إنما هو في حياتهم الدنيا لا يستقيم له معاشه، ولا يتعدى عليه سواه فيما اختص هو به، وانه لا يفوز منه بالسعادة الأخروية إلا الشاذ النادر، وهو من أراد حرث الآخرة وسعى لها سعياً وهو مؤمن.
وأما من طغى وأثر الحياة الدنيا فان الجحيم هي المأوى، وأي تعب أعظم وشقاوةً أطم ممن إذا تصفحت أعماله من وقت انتباهه من نومه إلى حين رجوعه إلى الكره لا تجد منها شيئاً إلا وهو يلتمس به تحصيل غايةً من هذه الأمور المحسوسة الخسيسة آما مال يجمعه أو لذة ينالها أو شهوة يقضيها أو غيطاً يتشفه به أو جاه يحرزه أو عمل من أعمال الشرع يتزين به أو يدافع عن رقبته، وهي كلها ظلمات بعضها فوق بعض في بحر لجي وان منكم إلا واردها كان على ربك حتماً مقضياً.
فلما فهم أحوال الناس وان أكثرهم بمنزلة الحيوان غير الناطق علم أن الحكمة كلها والهداية والتوفيق فيما نطقت به الرسل ووردت به الشريعة لا يمكن غير ذلك ولا يحتمل المزيد عليه ولكل عمل رجال وكل ميسر لما خلق له "بسم الله الرحمن الرحيم" سنة الله التي قد خلت من قبل ولن تجد لسنة الله تبديلاً صدق الله العظيم.
فانصرف إلى سلامان وأصحابه، فاعتذر عما تكلم به معه وتبرأ إليهم منه وأعلمهم أنه قد رآه مثل رأيهم واهتدى بمثل هديهم، وأوصاهم بملازمة ما هم عليه من التزام حدود الشرع والأعمال الظاهرة مقلة الخوض فيما لا يعنيهم، والإيمان بالمتشابهات والتسليم لها، والأعراض عن البدع والأهواء والاقتداء بالسلف الصالح والترك لمحدثات الأمور، وأمرهم بمجانبة ما عليه جمهور العوام من إهمال الشريعة والإقبال على الدنيا، وحذرهم عنه غاية التحذير، وعلم هو وصاحبه أسال أن هذه الطائفة المريدة القاصرة لا نجاة لها إلا بهذا الطريق، وأنها إن رفعت عنه إلى يفاع الاستبصار اختل ما هي عليه ولم يمكنها أن تلحق بدرجة السعداء وتذبذبت وانتكست وساءت عاقبتها. وان هي دامت على ما هي عليه حتى يوافيها اليقين فازت بالآمن وكانت من أصحاب اليمين، والسابقون السابقون أولئك المقربون. فو دعاهم وانفصلا عنهم وتلطفا في العود إلى جزيرتهما حتى يسر الله عز وجل عليهما العبور إليها. وطلب حي بن يقظان مقامه الكريم بالنحو الذي طلبه أولاً حتى عاد إليه، واقتدى به أسال حتى قرب من أو كاد وعبدا الله في تلك الجزيرة حتى أتاهما اليقين. هذا - أيدنا الله وأياك بروح منه - ما كان من نبأ حي بن يقظان وأسال وسلامان وقد أشتمل على حظ من الكلام لا يوجد في كتاب ولا يسمع في معتاد خطاب، وهو من العلم المكنون الذي لا يقبله إلا أهل المعرفة بالله، ولا يجهله إلا أهل الغرة بالله. وقد خالفنا فيه طريق السلف الصالح في الضنانا به والشح عليه. إلا أن الذي سهل علينا إفشاء هذا السر وهتك الحجاب، ما ظهر في زماننا من أراء فاسده نبغت بها متفلسفة العصر وصرحت بها، حتى انتشرت في البلدان وعما ضررها وخشينا على الضعفاء الذين اطرحوا تقليد الأنبياء صلوات الله عليهم، وأرادوا تقليد السفهاء والأغبياء أن يظنوا أن تلك الآراء هي الأسرار المضنون بها على غير أهلها، فيزيد بذلك حبهم فيها وولعهم فيها. فرأينا أن نلمح إليهم بطرف من سر الأسرار لنجتذبهم إلى جانب التحقيق، ثم نصدهم عن ذلك الطريق. ولم نخل مع ذلك ما أودعناه هذه الأوراق اليسيره من الأسرار عن حجاب رقيق وستر لطيف ينتهك سريعاً لمن هو أهله، ويتكاثف لمن لا يستحق تجاوزه حتى لا يتعداه. وأنا أسئل إخواني الواقفين على هذا الكلام، أن يقبلو عذري فيما تسائلت في تبينه وتسامحت في تثبيته، فلم أفعل ذلك إلا لأني تسمنت شواهق يزل الطرف عن مرآها. وأردت تقريب الكلام فيها على وجه الترغيب والتشويق في دخول الطريق. وأسأل الله التجاوز والعفو، وأن يوردنا من المعرفة به الصفو، إنه منعم كريم. والسلام عليك أيها الأخ المفترض إسعافه ورحمت الله وبركاته.
EOT;
}
| DevsNote/vehicles | _protected/vendor/fzaninotto/faker/src/Faker/Provider/ar_JO/Text.php | PHP | bsd-3-clause | 176,203 |
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Validator;
use Traversable;
class Barcode extends AbstractValidator
{
const INVALID = 'barcodeInvalid';
const FAILED = 'barcodeFailed';
const INVALID_CHARS = 'barcodeInvalidChars';
const INVALID_LENGTH = 'barcodeInvalidLength';
protected $messageTemplates = [
self::FAILED => "The input failed checksum validation",
self::INVALID_CHARS => "The input contains invalid characters",
self::INVALID_LENGTH => "The input should have a length of %length% characters",
self::INVALID => "Invalid type given. String expected",
];
/**
* Additional variables available for validation failure messages
*
* @var array
*/
protected $messageVariables = [
'length' => ['options' => 'length'],
];
protected $options = [
'adapter' => null, // Barcode adapter Zend\Validator\Barcode\AbstractAdapter
'options' => null, // Options for this adapter
'length' => null,
'useChecksum' => null,
];
/**
* Constructor for barcodes
*
* @param array|string $options Options to use
*/
public function __construct($options = null)
{
if ($options === null) {
$options = [];
}
if (!is_array($options) && !($options instanceof Traversable)) {
$options = ['adapter' => $options];
}
if (array_key_exists('options', $options)) {
$options['options'] = ['options' => $options['options']];
}
parent::__construct($options);
}
/**
* Returns the set adapter
*
* @return Barcode\AbstractAdapter
*/
public function getAdapter()
{
if (!($this->options['adapter'] instanceof Barcode\AdapterInterface)) {
$this->setAdapter('Ean13');
}
return $this->options['adapter'];
}
/**
* Sets a new barcode adapter
*
* @param string|Barcode\AbstractAdapter $adapter Barcode adapter to use
* @param array $options Options for this adapter
* @return Barcode
* @throws Exception\InvalidArgumentException
*/
public function setAdapter($adapter, $options = null)
{
if (is_string($adapter)) {
$adapter = ucfirst(strtolower($adapter));
$adapter = 'Zend\\Validator\\Barcode\\' . $adapter;
if (!class_exists($adapter)) {
throw new Exception\InvalidArgumentException('Barcode adapter matching "' . $adapter . '" not found');
}
$adapter = new $adapter($options);
}
if (!$adapter instanceof Barcode\AdapterInterface) {
throw new Exception\InvalidArgumentException(
sprintf(
"Adapter %s does not implement Zend\\Validator\\Barcode\\AdapterInterface",
(is_object($adapter) ? get_class($adapter) : gettype($adapter))
)
);
}
$this->options['adapter'] = $adapter;
return $this;
}
/**
* Returns the checksum option
*
* @return string
*/
public function getChecksum()
{
return $this->getAdapter()->getChecksum();
}
/**
* Sets if checksum should be validated, if no value is given the actual setting is returned
*
* @param bool $checksum
* @return bool
*/
public function useChecksum($checksum = null)
{
return $this->getAdapter()->useChecksum($checksum);
}
/**
* Defined by Zend\Validator\ValidatorInterface
*
* Returns true if and only if $value contains a valid barcode
*
* @param string $value
* @return bool
*/
public function isValid($value)
{
if (!is_string($value)) {
$this->error(self::INVALID);
return false;
}
$this->setValue($value);
$adapter = $this->getAdapter();
$this->options['length'] = $adapter->getLength();
$result = $adapter->hasValidLength($value);
if (!$result) {
if (is_array($this->options['length'])) {
$temp = $this->options['length'];
$this->options['length'] = "";
foreach ($temp as $length) {
$this->options['length'] .= "/";
$this->options['length'] .= $length;
}
$this->options['length'] = substr($this->options['length'], 1);
}
$this->error(self::INVALID_LENGTH);
return false;
}
$result = $adapter->hasValidCharacters($value);
if (!$result) {
$this->error(self::INVALID_CHARS);
return false;
}
if ($this->useChecksum(null)) {
$result = $adapter->hasValidChecksum($value);
if (!$result) {
$this->error(self::FAILED);
return false;
}
}
return true;
}
}
| nawelAb/kwaret | vendor/zendframework/zend-validator/src/Barcode.php | PHP | bsd-3-clause | 5,387 |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>HTML Test: dir=auto, start with script, then L</title>
<link rel="match" href="dir_auto-contained-script-L-ref.html" />
<link rel="author" title="Matitiahu Allouche" href="mailto:matitiahu.allouche@google.com" />
<link rel="author" title="Oren Roth" href="mailto:oren.roth@gmail.com" />
<link rel="author" title="HTML5 bidi test WG" href="mailto:html5bidi@googlegroups.com" />
<link rel="help" href="https://html.spec.whatwg.org/multipage/#the-dir-attribute" />
<meta name="assert" content="
When dir='auto', the direction is set according to the first strong character
of descendant text while ignoring descendant script elements.
In this test, it is the Latin letter A, thus the direction must be
resolved as LTR." />
<style>
input, textarea {
font-size:1em;
}
body {
font-size:2em;
}
.test, .ref {
border: medium solid gray;
width: 400px;
margin: 20px;
}
.comments {
display: none;
}
</style>
</head>
<body>
<div class="instructions" style="display:none"><p>Test passes if the two boxes below look exactly the same.</p></div>
<div class="comments">
Key to entities used below:
א - The Hebrew letter Alef (strongly RTL).
ב - The Hebrew letter Bet (strongly RTL).
ג - The Hebrew letter Gimel (strongly RTL).
</div>
<div class="test">
<div dir="ltr">
<div dir="ltr"><script>א = 3;</script>ABCאבג.</div>
</div>
<div dir="rtl">
<div dir="ltr"><script>א = 3;</script>ABCאבג.</div>
</div>
</div>
<div class="ref">
<div dir="ltr">
<div dir="ltr"><script>א = 3;</script>ABCאבג.</div>
</div>
<div dir="rtl">
<div dir="ltr"><script>א = 3;</script>ABCאבג.</div>
</div>
</div>
</body>
</html>
| was4444/chromium.src | third_party/WebKit/LayoutTests/imported/web-platform-tests/html/dom/elements/global-attributes/dir_auto-contained-script-L-ref.html | HTML | bsd-3-clause | 2,078 |
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2013 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\File\Transfer\Adapter;
use Zend\File\Transfer;
use Zend\File\Transfer\Exception;
use Zend\ProgressBar;
use Zend\ProgressBar\Adapter;
/**
* File transfer adapter class for the HTTP protocol
*
*/
class Http extends AbstractAdapter
{
protected static $callbackApc = 'apc_fetch';
protected static $callbackUploadProgress = 'uploadprogress_get_info';
/**
* Constructor for Http File Transfers
*
* @param array $options OPTIONAL Options to set
* @throws Exception\PhpEnvironmentException if file uploads are not allowed
*/
public function __construct($options = array())
{
if (ini_get('file_uploads') == false) {
throw new Exception\PhpEnvironmentException('File uploads are not allowed in your php config!');
}
$this->setOptions($options);
$this->prepareFiles();
$this->addValidator('Upload', false, $this->files);
}
/**
* Sets a validator for the class, erasing all previous set
*
* @param array $validators Validator to set
* @param string|array $files Files to limit this validator to
* @return AbstractAdapter
*/
public function setValidators(array $validators, $files = null)
{
$this->clearValidators();
return $this->addValidators($validators, $files);
}
/**
* Remove an individual validator
*
* @param string $name
* @return AbstractAdapter
*/
public function removeValidator($name)
{
if ($name == 'Upload') {
return $this;
}
return parent::removeValidator($name);
}
/**
* Clear the validators
*
* @return AbstractAdapter
*/
public function clearValidators()
{
parent::clearValidators();
$this->addValidator('Upload', false, $this->files);
return $this;
}
/**
* Send the file to the client (Download)
*
* @param string|array $options Options for the file(s) to send
* @return void
* @throws Exception\BadMethodCallException Not implemented
*/
public function send($options = null)
{
throw new Exception\BadMethodCallException('Method not implemented');
}
/**
* Checks if the files are valid
*
* @param string|array $files (Optional) Files to check
* @return bool True if all checks are valid
*/
public function isValid($files = null)
{
// Workaround for WebServer not conforming HTTP and omitting CONTENT_LENGTH
$content = 0;
if (isset($_SERVER['CONTENT_LENGTH'])) {
$content = $_SERVER['CONTENT_LENGTH'];
} elseif (!empty($_POST)) {
$content = serialize($_POST);
}
// Workaround for a PHP error returning empty $_FILES when form data exceeds php settings
if (empty($this->files) && ($content > 0)) {
if (is_array($files)) {
$files = current($files);
}
$temp = array($files => array(
'name' => $files,
'error' => 1));
$validator = $this->validators['Zend\Validator\File\Upload'];
$validator->setTranslator($this->getTranslator())
->setFiles($temp)
->isValid($files, null);
$this->messages += $validator->getMessages();
return false;
}
return parent::isValid($files);
}
/**
* Receive the file from the client (Upload)
*
* @param string|array $files (Optional) Files to receive
* @return bool
*/
public function receive($files = null)
{
if (!$this->isValid($files)) {
return false;
}
$check = $this->getFiles($files);
foreach ($check as $file => $content) {
if (!$content['received']) {
$directory = '';
$destination = $this->getDestination($file);
if ($destination !== null) {
$directory = $destination . DIRECTORY_SEPARATOR;
}
$filename = $directory . $content['name'];
$rename = $this->getFilter('Rename');
if ($rename !== null) {
$tmp = $rename->getNewName($content['tmp_name']);
if ($tmp != $content['tmp_name']) {
$filename = $tmp;
}
if (dirname($filename) == '.') {
$filename = $directory . $filename;
}
$key = array_search(get_class($rename), $this->files[$file]['filters']);
unset($this->files[$file]['filters'][$key]);
}
// Should never return false when it's tested by the upload validator
if (!move_uploaded_file($content['tmp_name'], $filename)) {
if ($content['options']['ignoreNoFile']) {
$this->files[$file]['received'] = true;
$this->files[$file]['filtered'] = true;
continue;
}
$this->files[$file]['received'] = false;
return false;
}
if ($rename !== null) {
$this->files[$file]['destination'] = dirname($filename);
$this->files[$file]['name'] = basename($filename);
}
$this->files[$file]['tmp_name'] = $filename;
$this->files[$file]['received'] = true;
}
if (!$content['filtered']) {
if (!$this->filter($file)) {
$this->files[$file]['filtered'] = false;
return false;
}
$this->files[$file]['filtered'] = true;
}
}
return true;
}
/**
* Checks if the file was already sent
*
* @param string|array $files Files to check
* @return bool
* @throws Exception\BadMethodCallException Not implemented
*/
public function isSent($files = null)
{
throw new Exception\BadMethodCallException('Method not implemented');
}
/**
* Checks if the file was already received
*
* @param string|array $files (Optional) Files to check
* @return bool
*/
public function isReceived($files = null)
{
$files = $this->getFiles($files, false, true);
if (empty($files)) {
return false;
}
foreach ($files as $content) {
if ($content['received'] !== true) {
return false;
}
}
return true;
}
/**
* Checks if the file was already filtered
*
* @param string|array $files (Optional) Files to check
* @return bool
*/
public function isFiltered($files = null)
{
$files = $this->getFiles($files, false, true);
if (empty($files)) {
return false;
}
foreach ($files as $content) {
if ($content['filtered'] !== true) {
return false;
}
}
return true;
}
/**
* Has a file been uploaded ?
*
* @param array|string|null $files
* @return bool
*/
public function isUploaded($files = null)
{
$files = $this->getFiles($files, false, true);
if (empty($files)) {
return false;
}
foreach ($files as $file) {
if (empty($file['name'])) {
return false;
}
}
return true;
}
/**
* Returns the actual progress of file up-/downloads
*
* @param string|array $id The upload to get the progress for
* @return array|null
* @throws Exception\PhpEnvironmentException whether APC nor UploadProgress extension installed
* @throws Exception\RuntimeException
*/
public static function getProgress($id = null)
{
if (!static::isApcAvailable() && !static::isUploadProgressAvailable()) {
throw new Exception\PhpEnvironmentException('Neither APC nor UploadProgress extension installed');
}
$session = 'Zend\File\Transfer\Adapter\Http\ProgressBar';
$status = array(
'total' => 0,
'current' => 0,
'rate' => 0,
'message' => '',
'done' => false
);
if (is_array($id)) {
if (isset($id['progress'])) {
$adapter = $id['progress'];
}
if (isset($id['session'])) {
$session = $id['session'];
}
if (isset($id['id'])) {
$id = $id['id'];
} else {
unset($id);
}
}
if (!empty($id) && (($id instanceof Adapter\AbstractAdapter) || ($id instanceof ProgressBar\ProgressBar))) {
$adapter = $id;
unset($id);
}
if (empty($id)) {
if (!isset($_GET['progress_key'])) {
$status['message'] = 'No upload in progress';
$status['done'] = true;
} else {
$id = $_GET['progress_key'];
}
}
if (!empty($id)) {
if (static::isApcAvailable()) {
$call = call_user_func(static::$callbackApc, ini_get('apc.rfc1867_prefix') . $id);
if (is_array($call)) {
$status = $call + $status;
}
} elseif (static::isUploadProgressAvailable()) {
$call = call_user_func(static::$callbackUploadProgress, $id);
if (is_array($call)) {
$status = $call + $status;
$status['total'] = $status['bytes_total'];
$status['current'] = $status['bytes_uploaded'];
$status['rate'] = $status['speed_average'];
if ($status['total'] == $status['current']) {
$status['done'] = true;
}
}
}
if (!is_array($call)) {
$status['done'] = true;
$status['message'] = 'Failure while retrieving the upload progress';
} elseif (!empty($status['cancel_upload'])) {
$status['done'] = true;
$status['message'] = 'The upload has been canceled';
} else {
$status['message'] = static::toByteString($status['current']) . " - " . static::toByteString($status['total']);
}
$status['id'] = $id;
}
if (isset($adapter) && isset($status['id'])) {
if ($adapter instanceof Adapter\AbstractAdapter) {
$adapter = new ProgressBar\ProgressBar($adapter, 0, $status['total'], $session);
}
if (!($adapter instanceof ProgressBar\ProgressBar)) {
throw new Exception\RuntimeException('Unknown Adapter given');
}
if ($status['done']) {
$adapter->finish();
} else {
$adapter->update($status['current'], $status['message']);
}
$status['progress'] = $adapter;
}
return $status;
}
/**
* Checks the APC extension for progress information
*
* @return bool
*/
public static function isApcAvailable()
{
return (bool) ini_get('apc.enabled') && (bool) ini_get('apc.rfc1867') && is_callable(static::$callbackApc);
}
/**
* Checks the UploadProgress extension for progress information
*
* @return bool
*/
public static function isUploadProgressAvailable()
{
return is_callable(static::$callbackUploadProgress);
}
/**
* Prepare the $_FILES array to match the internal syntax of one file per entry
*
* @return Http
*/
protected function prepareFiles()
{
$this->files = array();
foreach ($_FILES as $form => $content) {
if (is_array($content['name'])) {
foreach ($content as $param => $file) {
foreach ($file as $number => $target) {
$this->files[$form . '_' . $number . '_'][$param] = $target;
$this->files[$form]['multifiles'][$number] = $form . '_' . $number . '_';
}
}
$this->files[$form]['name'] = $form;
foreach ($this->files[$form]['multifiles'] as $key => $value) {
$this->files[$value]['options'] = $this->options;
$this->files[$value]['validated'] = false;
$this->files[$value]['received'] = false;
$this->files[$value]['filtered'] = false;
$mimetype = $this->detectMimeType($this->files[$value]);
$this->files[$value]['type'] = $mimetype;
$filesize = $this->detectFileSize($this->files[$value]);
$this->files[$value]['size'] = $filesize;
if ($this->options['detectInfos']) {
$_FILES[$form]['type'][$key] = $mimetype;
$_FILES[$form]['size'][$key] = $filesize;
}
}
} else {
$this->files[$form] = $content;
$this->files[$form]['options'] = $this->options;
$this->files[$form]['validated'] = false;
$this->files[$form]['received'] = false;
$this->files[$form]['filtered'] = false;
$mimetype = $this->detectMimeType($this->files[$form]);
$this->files[$form]['type'] = $mimetype;
$filesize = $this->detectFileSize($this->files[$form]);
$this->files[$form]['size'] = $filesize;
if ($this->options['detectInfos']) {
$_FILES[$form]['type'] = $mimetype;
$_FILES[$form]['size'] = $filesize;
}
}
}
return $this;
}
}
| yuhaya/FastZF2 | vendor/ZF2/library/Zend/File/Transfer/Adapter/Http.php | PHP | bsd-3-clause | 14,662 |
from __future__ import unicode_literals
from django.forms.models import inlineformset_factory
from django.test import TestCase, skipUnlessDBFeature
from django.utils import six
from .models import Child, Parent, Poem, Poet, School
class DeletionTests(TestCase):
def test_deletion(self):
PoemFormSet = inlineformset_factory(Poet, Poem, can_delete=True, fields="__all__")
poet = Poet.objects.create(name='test')
poem = poet.poem_set.create(name='test poem')
data = {
'poem_set-TOTAL_FORMS': '1',
'poem_set-INITIAL_FORMS': '1',
'poem_set-MAX_NUM_FORMS': '0',
'poem_set-0-id': str(poem.pk),
'poem_set-0-poet': str(poet.pk),
'poem_set-0-name': 'test',
'poem_set-0-DELETE': 'on',
}
formset = PoemFormSet(data, instance=poet)
formset.save()
self.assertTrue(formset.is_valid())
self.assertEqual(Poem.objects.count(), 0)
def test_add_form_deletion_when_invalid(self):
"""
Make sure that an add form that is filled out, but marked for deletion
doesn't cause validation errors.
"""
PoemFormSet = inlineformset_factory(Poet, Poem, can_delete=True, fields="__all__")
poet = Poet.objects.create(name='test')
data = {
'poem_set-TOTAL_FORMS': '1',
'poem_set-INITIAL_FORMS': '0',
'poem_set-MAX_NUM_FORMS': '0',
'poem_set-0-id': '',
'poem_set-0-poem': '1',
'poem_set-0-name': 'x' * 1000,
}
formset = PoemFormSet(data, instance=poet)
# Make sure this form doesn't pass validation.
self.assertEqual(formset.is_valid(), False)
self.assertEqual(Poem.objects.count(), 0)
# Then make sure that it *does* pass validation and delete the object,
# even though the data isn't actually valid.
data['poem_set-0-DELETE'] = 'on'
formset = PoemFormSet(data, instance=poet)
self.assertEqual(formset.is_valid(), True)
formset.save()
self.assertEqual(Poem.objects.count(), 0)
def test_change_form_deletion_when_invalid(self):
"""
Make sure that a change form that is filled out, but marked for deletion
doesn't cause validation errors.
"""
PoemFormSet = inlineformset_factory(Poet, Poem, can_delete=True, fields="__all__")
poet = Poet.objects.create(name='test')
poem = poet.poem_set.create(name='test poem')
data = {
'poem_set-TOTAL_FORMS': '1',
'poem_set-INITIAL_FORMS': '1',
'poem_set-MAX_NUM_FORMS': '0',
'poem_set-0-id': six.text_type(poem.id),
'poem_set-0-poem': six.text_type(poem.id),
'poem_set-0-name': 'x' * 1000,
}
formset = PoemFormSet(data, instance=poet)
# Make sure this form doesn't pass validation.
self.assertEqual(formset.is_valid(), False)
self.assertEqual(Poem.objects.count(), 1)
# Then make sure that it *does* pass validation and delete the object,
# even though the data isn't actually valid.
data['poem_set-0-DELETE'] = 'on'
formset = PoemFormSet(data, instance=poet)
self.assertEqual(formset.is_valid(), True)
formset.save()
self.assertEqual(Poem.objects.count(), 0)
def test_save_new(self):
"""
Make sure inlineformsets respect commit=False
regression for #10750
"""
# exclude some required field from the forms
ChildFormSet = inlineformset_factory(School, Child, exclude=['father', 'mother'])
school = School.objects.create(name='test')
mother = Parent.objects.create(name='mother')
father = Parent.objects.create(name='father')
data = {
'child_set-TOTAL_FORMS': '1',
'child_set-INITIAL_FORMS': '0',
'child_set-MAX_NUM_FORMS': '0',
'child_set-0-name': 'child',
}
formset = ChildFormSet(data, instance=school)
self.assertEqual(formset.is_valid(), True)
objects = formset.save(commit=False)
for obj in objects:
obj.mother = mother
obj.father = father
obj.save()
self.assertEqual(school.child_set.count(), 1)
class InlineFormsetFactoryTest(TestCase):
def test_inline_formset_factory(self):
"""
These should both work without a problem.
"""
inlineformset_factory(Parent, Child, fk_name='mother', fields="__all__")
inlineformset_factory(Parent, Child, fk_name='father', fields="__all__")
def test_exception_on_unspecified_foreign_key(self):
"""
Child has two ForeignKeys to Parent, so if we don't specify which one
to use for the inline formset, we should get an exception.
"""
six.assertRaisesRegex(
self,
ValueError,
"'inline_formsets.Child' has more than one ForeignKey to 'inline_formsets.Parent'.",
inlineformset_factory, Parent, Child
)
def test_fk_name_not_foreign_key_field_from_child(self):
"""
If we specify fk_name, but it isn't a ForeignKey from the child model
to the parent model, we should get an exception.
"""
self.assertRaises(
Exception,
"fk_name 'school' is not a ForeignKey to <class 'inline_formsets.models.Parent'>",
inlineformset_factory, Parent, Child, fk_name='school'
)
def test_non_foreign_key_field(self):
"""
If the field specified in fk_name is not a ForeignKey, we should get an
exception.
"""
six.assertRaisesRegex(
self, ValueError,
"'inline_formsets.Child' has no field named 'test'.",
inlineformset_factory, Parent, Child, fk_name='test'
)
def test_any_iterable_allowed_as_argument_to_exclude(self):
# Regression test for #9171.
inlineformset_factory(
Parent, Child, exclude=['school'], fk_name='mother'
)
inlineformset_factory(
Parent, Child, exclude=('school',), fk_name='mother'
)
@skipUnlessDBFeature('allows_auto_pk_0')
def test_zero_primary_key(self):
# Regression test for #21472
poet = Poet.objects.create(id=0, name='test')
poet.poem_set.create(name='test poem')
PoemFormSet = inlineformset_factory(Poet, Poem, fields="__all__", extra=0)
formset = PoemFormSet(None, instance=poet)
self.assertEqual(len(formset.forms), 1)
| jaywreddy/django | tests/inline_formsets/tests.py | Python | bsd-3-clause | 6,656 |
/**
* This is the common logic for both the Node.js and web browser
* implementations of `debug()`.
*
* Expose `debug()` as the module.
*/
exports = module.exports = debug;
exports.coerce = coerce;
exports.disable = disable;
exports.enable = enable;
exports.enabled = enabled;
exports.humanize = require('ms');
/**
* The currently active debug mode names, and names to skip.
*/
exports.names = [];
exports.skips = [];
/**
* Map of special "%n" handling functions, for the debug "format" argument.
*
* Valid key names are a single, lowercased letter, i.e. "n".
*/
exports.formatters = {};
/**
* Previously assigned color.
*/
var prevColor = 0;
/**
* Previous log timestamp.
*/
var prevTime;
/**
* Select a color.
*
* @return {Number}
* @api private
*/
function selectColor() {
return exports.colors[prevColor++ % exports.colors.length];
}
/**
* Create a debugger with the given `namespace`.
*
* @param {String} namespace
* @return {Function}
* @api public
*/
function debug(namespace) {
// define the `disabled` version
function disabled() {
}
disabled.enabled = false;
// define the `enabled` version
function enabled() {
var self = enabled;
// set `diff` timestamp
var curr = +new Date();
var ms = curr - (prevTime || curr);
self.diff = ms;
self.prev = prevTime;
self.curr = curr;
prevTime = curr;
// add the `color` if not set
if (null == self.useColors) self.useColors = exports.useColors();
if (null == self.color && self.useColors) self.color = selectColor();
var args = Array.prototype.slice.call(arguments);
args[0] = exports.coerce(args[0]);
if ('string' !== typeof args[0]) {
// anything else let's inspect with %o
args = ['%o'].concat(args);
}
// apply any `formatters` transformations
var index = 0;
args[0] = args[0].replace(/%([a-z%])/g, function(match, format) {
// if we encounter an escaped % then don't increase the array index
if (match === '%%') return match;
index++;
var formatter = exports.formatters[format];
if ('function' === typeof formatter) {
var val = args[index];
match = formatter.call(self, val);
// now we need to remove `args[index]` since it's inlined in the `format`
args.splice(index, 1);
index--;
}
return match;
});
if ('function' === typeof exports.formatArgs) {
args = exports.formatArgs.apply(self, args);
}
var logFn = enabled.log || exports.log || console.log.bind(console);
logFn.apply(self, args);
}
enabled.enabled = true;
var fn = exports.enabled(namespace) ? enabled : disabled;
fn.namespace = namespace;
return fn;
}
/**
* Enables a debug mode by namespaces. This can include modes
* separated by a colon and wildcards.
*
* @param {String} namespaces
* @api public
*/
function enable(namespaces) {
exports.save(namespaces);
var split = (namespaces || '').split(/[\s,]+/);
var len = split.length;
for (var i = 0; i < len; i++) {
if (!split[i]) continue; // ignore empty strings
namespaces = split[i].replace(/\*/g, '.*?');
if (namespaces[0] === '-') {
exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
} else {
exports.names.push(new RegExp('^' + namespaces + '$'));
}
}
}
/**
* Disable debug output.
*
* @api public
*/
function disable() {
exports.enable('');
}
/**
* Returns true if the given mode name is enabled, false otherwise.
*
* @param {String} name
* @return {Boolean}
* @api public
*/
function enabled(name) {
var i, len;
for (i = 0, len = exports.skips.length; i < len; i++) {
if (exports.skips[i].test(name)) {
return false;
}
}
for (i = 0, len = exports.names.length; i < len; i++) {
if (exports.names[i].test(name)) {
return true;
}
}
return false;
}
/**
* Coerce `val`.
*
* @param {Mixed} val
* @return {Mixed}
* @api private
*/
function coerce(val) {
if (val instanceof Error) return val.stack || val.message;
return val;
}
| truveris/WebDriverAgent | Inspector/node_modules/webpack-dev-server/node_modules/socket.io-client/node_modules/engine.io-client/node_modules/debug/debug.js | JavaScript | bsd-3-clause | 4,096 |
<?php defined('SYSPATH') or die('No direct script access.');
/**
* Security helper class.
*
* @package Kohana
* @category Security
* @author Kohana Team
* @copyright (c) 2007-2011 Kohana Team
* @license http://kohanaframework.org/license
*/
class Kohana_Security {
/**
* @var string key name used for token storage
*/
public static $token_name = 'security_token';
/**
* Generate and store a unique token which can be used to help prevent
* [CSRF](http://wikipedia.org/wiki/Cross_Site_Request_Forgery) attacks.
*
* $token = Security::token();
*
* You can insert this token into your forms as a hidden field:
*
* echo Form::hidden('csrf', Security::token());
*
* And then check it when using [Validation]:
*
* $array->rules('csrf', array(
* 'not_empty' => NULL,
* 'Security::check' => NULL,
* ));
*
* This provides a basic, but effective, method of preventing CSRF attacks.
*
* @param boolean force a new token to be generated?
* @return string
* @uses Session::instance
*/
public static function token($new = FALSE)
{
$session = Session::instance();
// Get the current token
$token = $session->get(Security::$token_name);
if ($new === TRUE OR ! $token)
{
// Generate a new unique token
$token = sha1(uniqid(NULL, TRUE));
// Store the new token
$session->set(Security::$token_name, $token);
}
return $token;
}
/**
* Check that the given token matches the currently stored security token.
*
* if (Security::check($token))
* {
* // Pass
* }
*
* @param string token to check
* @return boolean
* @uses Security::token
*/
public static function check($token)
{
return Security::token() === $token;
}
/**
* Remove image tags from a string.
*
* $str = Security::strip_image_tags($str);
*
* @param string string to sanitize
* @return string
*/
public static function strip_image_tags($str)
{
return preg_replace('#<img\s.*?(?:src\s*=\s*["\']?([^"\'<>\s]*)["\']?[^>]*)?>#is', '$1', $str);
}
/**
* Encodes PHP tags in a string.
*
* $str = Security::encode_php_tags($str);
*
* @param string string to sanitize
* @return string
*/
public static function encode_php_tags($str)
{
return str_replace(array('<?', '?>'), array('<?', '?>'), $str);
}
} // End security
| bqevin/saidika | system/classes/kohana/security.php | PHP | bsd-3-clause | 2,424 |
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Http;
/**
* Http static client
*/
class ClientStatic
{
protected static $client;
/**
* Get the static HTTP client
*
* @return Client
*/
protected static function getStaticClient()
{
if (!isset(static::$client)) {
static::$client = new Client();
}
return static::$client;
}
/**
* HTTP GET METHOD (static)
*
* @param string $url
* @param array $query
* @param array $headers
* @param mixed $body
* @return Response|bool
*/
public static function get($url, $query = array(), $headers = array(), $body = null)
{
if (empty($url)) {
return false;
}
$request= new Request();
$request->setUri($url);
$request->setMethod(Request::METHOD_GET);
if (!empty($query) && is_array($query)) {
$request->getQuery()->fromArray($query);
}
if (!empty($headers) && is_array($headers)) {
$request->getHeaders()->addHeaders($headers);
}
if (!empty($body)) {
$request->setContent($body);
}
return static::getStaticClient()->send($request);
}
/**
* HTTP POST METHOD (static)
*
* @param string $url
* @param array $params
* @param array $headers
* @param mixed $body
* @throws Exception\InvalidArgumentException
* @return Response|bool
*/
public static function post($url, $params, $headers = array(), $body = null)
{
if (empty($url)) {
return false;
}
$request= new Request();
$request->setUri($url);
$request->setMethod(Request::METHOD_POST);
if (!empty($params) && is_array($params)) {
$request->getPost()->fromArray($params);
} else {
throw new Exception\InvalidArgumentException('The array of post parameters is empty');
}
if (!isset($headers['Content-Type'])) {
$headers['Content-Type']= Client::ENC_URLENCODED;
}
if (!empty($headers) && is_array($headers)) {
$request->getHeaders()->addHeaders($headers);
}
if (!empty($body)) {
$request->setContent($body);
}
return static::getStaticClient()->send($request);
}
}
| alucard98/ZendSkeletorApplication | vendor/zendframework2/zendframework2/library/Zend/Http/ClientStatic.php | PHP | bsd-3-clause | 2,672 |
/*
Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.lang['ms']={"editor":"Rich Text Editor","common":{"editorHelp":"Press ALT 0 for help","browseServer":"Browse Server","url":"URL","protocol":"Protokol","upload":"Muat Naik","uploadSubmit":"Hantar ke Server","image":"Gambar","flash":"Flash","form":"Borang","checkbox":"Checkbox","radio":"Butang Radio","textField":"Text Field","textarea":"Textarea","hiddenField":"Field Tersembunyi","button":"Butang","select":"Field Pilihan","imageButton":"Butang Bergambar","notSet":"<tidak di set>","id":"Id","name":"Nama","langDir":"Arah Tulisan","langDirLtr":"Kiri ke Kanan (LTR)","langDirRtl":"Kanan ke Kiri (RTL)","langCode":"Kod Bahasa","longDescr":"Butiran Panjang URL","cssClass":"Kelas-kelas Stylesheet","advisoryTitle":"Tajuk Makluman","cssStyle":"Stail","ok":"OK","cancel":"Batal","close":"Close","preview":"Prebiu","resize":"Resize","generalTab":"General","advancedTab":"Advanced","validateNumberFailed":"This value is not a number.","confirmNewPage":"Any unsaved changes to this content will be lost. Are you sure you want to load new page?","confirmCancel":"Some of the options have been changed. Are you sure to close the dialog?","options":"Options","target":"Sasaran","targetNew":"New Window (_blank)","targetTop":"Topmost Window (_top)","targetSelf":"Same Window (_self)","targetParent":"Parent Window (_parent)","langDirLTR":"Kiri ke Kanan (LTR)","langDirRTL":"Kanan ke Kiri (RTL)","styles":"Stail","cssClasses":"Kelas-kelas Stylesheet","width":"Lebar","height":"Tinggi","align":"Jajaran","alignLeft":"Kiri","alignRight":"Kanan","alignCenter":"Tengah","alignTop":"Atas","alignMiddle":"Pertengahan","alignBottom":"Bawah","invalidValue":"Invalid value.","invalidHeight":"Height must be a number.","invalidWidth":"Width must be a number.","invalidCssLength":"Value specified for the \"%1\" field must be a positive number with or without a valid CSS measurement unit (px, %, in, cm, mm, em, ex, pt, or pc).","invalidHtmlLength":"Value specified for the \"%1\" field must be a positive number with or without a valid HTML measurement unit (px or %).","invalidInlineStyle":"Value specified for the inline style must consist of one or more tuples with the format of \"name : value\", separated by semi-colons.","cssLengthTooltip":"Enter a number for a value in pixels or a number with a valid CSS unit (px, %, in, cm, mm, em, ex, pt, or pc).","unavailable":"%1<span class=\"cke_accessibility\">, unavailable</span>"},"about":{"copy":"Copyright © $1. All rights reserved.","dlgTitle":"About CKEditor","help":"Check $1 for help.","moreInfo":"For licensing information please visit our web site:","title":"About CKEditor","userGuide":"CKEditor User's Guide"},"basicstyles":{"bold":"Bold","italic":"Italic","strike":"Strike Through","subscript":"Subscript","superscript":"Superscript","underline":"Underline"},"bidi":{"ltr":"Text direction from left to right","rtl":"Text direction from right to left"},"blockquote":{"toolbar":"Block Quote"},"clipboard":{"copy":"Salin","copyError":"Keselamatan perisian browser anda tidak membenarkan operasi salinan text/imej. Sila gunakan papan kekunci (Ctrl/Cmd+C).","cut":"Potong","cutError":"Keselamatan perisian browser anda tidak membenarkan operasi suntingan text/imej. Sila gunakan papan kekunci (Ctrl/Cmd+X).","paste":"Tampal","pasteArea":"Paste Area","pasteMsg":"Please paste inside the following box using the keyboard (<strong>Ctrl/Cmd+V</strong>) and hit OK","securityMsg":"Because of your browser security settings, the editor is not able to access your clipboard data directly. You are required to paste it again in this window.","title":"Tampal"},"colorbutton":{"auto":"Otomatik","bgColorTitle":"Warna Latarbelakang","colors":{"000":"Black","800000":"Maroon","8B4513":"Saddle Brown","2F4F4F":"Dark Slate Gray","008080":"Teal","000080":"Navy","4B0082":"Indigo","696969":"Dark Gray","B22222":"Fire Brick","A52A2A":"Brown","DAA520":"Golden Rod","006400":"Dark Green","40E0D0":"Turquoise","0000CD":"Medium Blue","800080":"Purple","808080":"Gray","F00":"Red","FF8C00":"Dark Orange","FFD700":"Gold","008000":"Green","0FF":"Cyan","00F":"Blue","EE82EE":"Violet","A9A9A9":"Dim Gray","FFA07A":"Light Salmon","FFA500":"Orange","FFFF00":"Yellow","00FF00":"Lime","AFEEEE":"Pale Turquoise","ADD8E6":"Light Blue","DDA0DD":"Plum","D3D3D3":"Light Grey","FFF0F5":"Lavender Blush","FAEBD7":"Antique White","FFFFE0":"Light Yellow","F0FFF0":"Honeydew","F0FFFF":"Azure","F0F8FF":"Alice Blue","E6E6FA":"Lavender","FFF":"White"},"more":"Warna lain-lain...","panelTitle":"Colors","textColorTitle":"Warna Text"},"colordialog":{"clear":"Clear","highlight":"Highlight","options":"Color Options","selected":"Selected Color","title":"Select color"},"templates":{"button":"Templat","emptyListMsg":"(Tiada Templat Disimpan)","insertOption":"Replace actual contents","options":"Template Options","selectPromptMsg":"Sila pilih templat untuk dibuka oleh editor<br>(kandungan sebenar akan hilang):","title":"Templat Kandungan"},"contextmenu":{"options":"Context Menu Options"},"div":{"IdInputLabel":"Id","advisoryTitleInputLabel":"Advisory Title","cssClassInputLabel":"Stylesheet Classes","edit":"Edit Div","inlineStyleInputLabel":"Inline Style","langDirLTRLabel":"Left to Right (LTR)","langDirLabel":"Language Direction","langDirRTLLabel":"Right to Left (RTL)","languageCodeInputLabel":" Language Code","remove":"Remove Div","styleSelectLabel":"Style","title":"Create Div Container","toolbar":"Create Div Container"},"toolbar":{"toolbarCollapse":"Collapse Toolbar","toolbarExpand":"Expand Toolbar","toolbarGroups":{"document":"Document","clipboard":"Clipboard/Undo","editing":"Editing","forms":"Forms","basicstyles":"Basic Styles","paragraph":"Paragraph","links":"Links","insert":"Insert","styles":"Styles","colors":"Colors","tools":"Tools"},"toolbars":"Editor toolbars"},"elementspath":{"eleLabel":"Elements path","eleTitle":"%1 element"},"find":{"find":"Cari","findOptions":"Find Options","findWhat":"Perkataan yang dicari:","matchCase":"Padanan case huruf","matchCyclic":"Match cyclic","matchWord":"Padana Keseluruhan perkataan","notFoundMsg":"Text yang dicari tidak dijumpai.","replace":"Ganti","replaceAll":"Ganti semua","replaceSuccessMsg":"%1 occurrence(s) replaced.","replaceWith":"Diganti dengan:","title":"Find and Replace"},"fakeobjects":{"anchor":"Anchor","flash":"Flash Animation","hiddenfield":"Hidden Field","iframe":"IFrame","unknown":"Unknown Object"},"flash":{"access":"Script Access","accessAlways":"Always","accessNever":"Never","accessSameDomain":"Same domain","alignAbsBottom":"Bawah Mutlak","alignAbsMiddle":"Pertengahan Mutlak","alignBaseline":"Garis Dasar","alignTextTop":"Atas Text","bgcolor":"Warna Latarbelakang","chkFull":"Allow Fullscreen","chkLoop":"Loop","chkMenu":"Enable Flash Menu","chkPlay":"Auto Play","flashvars":"Variables for Flash","hSpace":"Ruang Melintang","properties":"Flash Properties","propertiesTab":"Properties","quality":"Quality","qualityAutoHigh":"Auto High","qualityAutoLow":"Auto Low","qualityBest":"Best","qualityHigh":"High","qualityLow":"Low","qualityMedium":"Medium","scale":"Scale","scaleAll":"Show all","scaleFit":"Exact Fit","scaleNoBorder":"No Border","title":"Flash Properties","vSpace":"Ruang Menegak","validateHSpace":"HSpace must be a number.","validateSrc":"Sila taip sambungan URL","validateVSpace":"VSpace must be a number.","windowMode":"Window mode","windowModeOpaque":"Opaque","windowModeTransparent":"Transparent","windowModeWindow":"Window"},"font":{"fontSize":{"label":"Saiz","voiceLabel":"Font Size","panelTitle":"Saiz"},"label":"Font","panelTitle":"Font","voiceLabel":"Font"},"forms":{"button":{"title":"Ciri-ciri Butang","text":"Teks (Nilai)","type":"Jenis","typeBtn":"Button","typeSbm":"Submit","typeRst":"Reset"},"checkboxAndRadio":{"checkboxTitle":"Ciri-ciri Checkbox","radioTitle":"Ciri-ciri Butang Radio","value":"Nilai","selected":"Dipilih"},"form":{"title":"Ciri-ciri Borang","menu":"Ciri-ciri Borang","action":"Tindakan borang","method":"Cara borang dihantar","encoding":"Encoding"},"hidden":{"title":"Ciri-ciri Field Tersembunyi","name":"Nama","value":"Nilai"},"select":{"title":"Ciri-ciri Selection Field","selectInfo":"Select Info","opAvail":"Pilihan sediada","value":"Nilai","size":"Saiz","lines":"garisan","chkMulti":"Benarkan pilihan pelbagai","opText":"Teks","opValue":"Nilai","btnAdd":"Tambah Pilihan","btnModify":"Ubah Pilihan","btnUp":"Naik ke atas","btnDown":"Turun ke bawah","btnSetValue":"Set sebagai nilai terpilih","btnDelete":"Padam"},"textarea":{"title":"Ciri-ciri Textarea","cols":"Lajur","rows":"Baris"},"textfield":{"title":"Ciri-ciri Text Field","name":"Nama","value":"Nilai","charWidth":"Lebar isian","maxChars":"Isian Maksimum","type":"Jenis","typeText":"Teks","typePass":"Kata Laluan","typeEmail":"Email","typeSearch":"Search","typeTel":"Telephone Number","typeUrl":"URL"}},"format":{"label":"Format","panelTitle":"Format","tag_address":"Alamat","tag_div":"Perenggan (DIV)","tag_h1":"Heading 1","tag_h2":"Heading 2","tag_h3":"Heading 3","tag_h4":"Heading 4","tag_h5":"Heading 5","tag_h6":"Heading 6","tag_p":"Normal","tag_pre":"Telah Diformat"},"horizontalrule":{"toolbar":"Masukkan Garisan Membujur"},"iframe":{"border":"Show frame border","noUrl":"Please type the iframe URL","scrolling":"Enable scrollbars","title":"IFrame Properties","toolbar":"IFrame"},"image":{"alertUrl":"Sila taip URL untuk fail gambar","alt":"Text Alternatif","border":"Border","btnUpload":"Hantar ke Server","button2Img":"Do you want to transform the selected image button on a simple image?","hSpace":"Ruang Melintang","img2Button":"Do you want to transform the selected image on a image button?","infoTab":"Info Imej","linkTab":"Sambungan","lockRatio":"Tetapkan Nisbah","menu":"Ciri-ciri Imej","resetSize":"Saiz Set Semula","title":"Ciri-ciri Imej","titleButton":"Ciri-ciri Butang Bergambar","upload":"Muat Naik","urlMissing":"Image source URL is missing.","vSpace":"Ruang Menegak","validateBorder":"Border must be a whole number.","validateHSpace":"HSpace must be a whole number.","validateVSpace":"VSpace must be a whole number."},"indent":{"indent":"Tambahkan Inden","outdent":"Kurangkan Inden"},"smiley":{"options":"Smiley Options","title":"Masukkan Smiley","toolbar":"Smiley"},"justify":{"block":"Jajaran Blok","center":"Jajaran Tengah","left":"Jajaran Kiri","right":"Jajaran Kanan"},"link":{"acccessKey":"Kunci Akses","advanced":"Advanced","advisoryContentType":"Jenis Kandungan Makluman","advisoryTitle":"Tajuk Makluman","anchor":{"toolbar":"Masukkan/Sunting Pautan","menu":"Ciri-ciri Pautan","title":"Ciri-ciri Pautan","name":"Nama Pautan","errorName":"Sila taip nama pautan","remove":"Remove Anchor"},"anchorId":"dengan menggunakan ID elemen","anchorName":"dengan menggunakan nama pautan","charset":"Linked Resource Charset","cssClasses":"Kelas-kelas Stylesheet","emailAddress":"Alamat E-Mail","emailBody":"Isi Kandungan Mesej","emailSubject":"Subjek Mesej","id":"Id","info":"Butiran Sambungan","langCode":"Arah Tulisan","langDir":"Arah Tulisan","langDirLTR":"Kiri ke Kanan (LTR)","langDirRTL":"Kanan ke Kiri (RTL)","menu":"Sunting Sambungan","name":"Nama","noAnchors":"(Tiada pautan terdapat dalam dokumen ini)","noEmail":"Sila taip alamat e-mail","noUrl":"Sila taip sambungan URL","other":"<lain>","popupDependent":"Bergantungan (Netscape)","popupFeatures":"Ciri Tetingkap Popup","popupFullScreen":"Skrin Penuh (IE)","popupLeft":"Posisi Kiri","popupLocationBar":"Bar Lokasi","popupMenuBar":"Bar Menu","popupResizable":"Resizable","popupScrollBars":"Bar-bar skrol","popupStatusBar":"Bar Status","popupToolbar":"Toolbar","popupTop":"Posisi Atas","rel":"Relationship","selectAnchor":"Sila pilih pautan","styles":"Stail","tabIndex":"Indeks Tab ","target":"Sasaran","targetFrame":"<bingkai>","targetFrameName":"Nama Bingkai Sasaran","targetPopup":"<tetingkap popup>","targetPopupName":"Nama Tetingkap Popup","title":"Sambungan","toAnchor":"Pautan dalam muka surat ini","toEmail":"E-Mail","toUrl":"URL","toolbar":"Masukkan/Sunting Sambungan","type":"Jenis Sambungan","unlink":"Buang Sambungan","upload":"Muat Naik"},"list":{"bulletedlist":"Senarai tidak bernombor","numberedlist":"Senarai bernombor"},"liststyle":{"armenian":"Armenian numbering","bulletedTitle":"Bulleted List Properties","circle":"Circle","decimal":"Decimal (1, 2, 3, etc.)","decimalLeadingZero":"Decimal leading zero (01, 02, 03, etc.)","disc":"Disc","georgian":"Georgian numbering (an, ban, gan, etc.)","lowerAlpha":"Lower Alpha (a, b, c, d, e, etc.)","lowerGreek":"Lower Greek (alpha, beta, gamma, etc.)","lowerRoman":"Lower Roman (i, ii, iii, iv, v, etc.)","none":"None","notset":"<not set>","numberedTitle":"Numbered List Properties","square":"Square","start":"Start","type":"Type","upperAlpha":"Upper Alpha (A, B, C, D, E, etc.)","upperRoman":"Upper Roman (I, II, III, IV, V, etc.)","validateStartNumber":"List start number must be a whole number."},"magicline":{"title":"Insert paragraph here"},"maximize":{"maximize":"Maximize","minimize":"Minimize"},"newpage":{"toolbar":"Helaian Baru"},"pagebreak":{"alt":"Page Break","toolbar":"Insert Page Break for Printing"},"pastetext":{"button":"Tampal sebagai text biasa","title":"Tampal sebagai text biasa"},"pastefromword":{"confirmCleanup":"The text you want to paste seems to be copied from Word. Do you want to clean it before pasting?","error":"It was not possible to clean up the pasted data due to an internal error","title":"Tampal dari Word","toolbar":"Tampal dari Word"},"preview":{"preview":"Prebiu"},"print":{"toolbar":"Cetak"},"removeformat":{"toolbar":"Buang Format"},"save":{"toolbar":"Simpan"},"selectall":{"toolbar":"Pilih Semua"},"showblocks":{"toolbar":"Show Blocks"},"sourcearea":{"toolbar":"Sumber"},"specialchar":{"options":"Special Character Options","title":"Sila pilih huruf istimewa","toolbar":"Masukkan Huruf Istimewa"},"scayt":{"about":"About SCAYT","aboutTab":"About","addWord":"Add Word","allCaps":"Ignore All-Caps Words","dic_create":"Create","dic_delete":"Delete","dic_field_name":"Dictionary name","dic_info":"Initially the User Dictionary is stored in a Cookie. However, Cookies are limited in size. When the User Dictionary grows to a point where it cannot be stored in a Cookie, then the dictionary may be stored on our server. To store your personal dictionary on our server you should specify a name for your dictionary. If you already have a stored dictionary, please type its name and click the Restore button.","dic_rename":"Rename","dic_restore":"Restore","dictionariesTab":"Dictionaries","disable":"Disable SCAYT","emptyDic":"Dictionary name should not be empty.","enable":"Enable SCAYT","ignore":"Ignore","ignoreAll":"Ignore All","ignoreDomainNames":"Ignore Domain Names","langs":"Languages","languagesTab":"Languages","mixedCase":"Ignore Words with Mixed Case","mixedWithDigits":"Ignore Words with Numbers","moreSuggestions":"More suggestions","opera_title":"Not supported by Opera","options":"Options","optionsTab":"Options","title":"Spell Check As You Type","toggle":"Toggle SCAYT","noSuggestions":"No suggestion"},"stylescombo":{"label":"Stail","panelTitle":"Formatting Styles","panelTitle1":"Block Styles","panelTitle2":"Inline Styles","panelTitle3":"Object Styles"},"table":{"border":"Saiz Border","caption":"Keterangan","cell":{"menu":"Cell","insertBefore":"Insert Cell Before","insertAfter":"Insert Cell After","deleteCell":"Buangkan Sel-sel","merge":"Cantumkan Sel-sel","mergeRight":"Merge Right","mergeDown":"Merge Down","splitHorizontal":"Split Cell Horizontally","splitVertical":"Split Cell Vertically","title":"Cell Properties","cellType":"Cell Type","rowSpan":"Rows Span","colSpan":"Columns Span","wordWrap":"Word Wrap","hAlign":"Horizontal Alignment","vAlign":"Vertical Alignment","alignBaseline":"Baseline","bgColor":"Background Color","borderColor":"Border Color","data":"Data","header":"Header","yes":"Yes","no":"No","invalidWidth":"Cell width must be a number.","invalidHeight":"Cell height must be a number.","invalidRowSpan":"Rows span must be a whole number.","invalidColSpan":"Columns span must be a whole number.","chooseColor":"Choose"},"cellPad":"Tambahan Ruang Sel","cellSpace":"Ruangan Antara Sel","column":{"menu":"Column","insertBefore":"Insert Column Before","insertAfter":"Insert Column After","deleteColumn":"Buangkan Lajur"},"columns":"Jaluran","deleteTable":"Delete Table","headers":"Headers","headersBoth":"Both","headersColumn":"First column","headersNone":"None","headersRow":"First Row","invalidBorder":"Border size must be a number.","invalidCellPadding":"Cell padding must be a positive number.","invalidCellSpacing":"Cell spacing must be a positive number.","invalidCols":"Number of columns must be a number greater than 0.","invalidHeight":"Table height must be a number.","invalidRows":"Number of rows must be a number greater than 0.","invalidWidth":"Table width must be a number.","menu":"Ciri-ciri Jadual","row":{"menu":"Row","insertBefore":"Insert Row Before","insertAfter":"Insert Row After","deleteRow":"Buangkan Baris"},"rows":"Barisan","summary":"Summary","title":"Ciri-ciri Jadual","toolbar":"Jadual","widthPc":"peratus","widthPx":"piksel-piksel","widthUnit":"width unit"},"undo":{"redo":"Ulangkan","undo":"Batalkan"},"wsc":{"btnIgnore":"Biar","btnIgnoreAll":"Biarkan semua","btnReplace":"Ganti","btnReplaceAll":"Gantikan Semua","btnUndo":"Batalkan","changeTo":"Tukarkan kepada","errorLoading":"Error loading application service host: %s.","ieSpellDownload":"Pemeriksa ejaan tidak dipasang. Adakah anda mahu muat turun sekarang?","manyChanges":"Pemeriksaan ejaan siap: %1 perkataan diubah","noChanges":"Pemeriksaan ejaan siap: Tiada perkataan diubah","noMispell":"Pemeriksaan ejaan siap: Tiada salah ejaan","noSuggestions":"- Tiada cadangan -","notAvailable":"Sorry, but service is unavailable now.","notInDic":"Tidak terdapat didalam kamus","oneChange":"Pemeriksaan ejaan siap: Satu perkataan telah diubah","progress":"Pemeriksaan ejaan sedang diproses...","title":"Spell Check","toolbar":"Semak Ejaan"}}; | XQ-quadrant/gbii | frontend/web/cloude/js/ckeditor/lang/ms.js | JavaScript | bsd-3-clause | 18,086 |
<?php
class Swift_Mime_Headers_IdentificationHeaderTest extends \PHPUnit_Framework_TestCase
{
public function testTypeIsIdHeader()
{
$header = $this->_getHeader('Message-ID');
$this->assertEquals(Swift_Mime_Header::TYPE_ID, $header->getFieldType());
}
public function testValueMatchesMsgIdSpec()
{
/* -- RFC 2822, 3.6.4.
message-id = "Message-ID:" msg-id CRLF
in-reply-to = "In-Reply-To:" 1*msg-id CRLF
references = "References:" 1*msg-id CRLF
msg-id = [CFWS] "<" id-left "@" id-right ">" [CFWS]
id-left = dot-atom-text / no-fold-quote / obs-id-left
id-right = dot-atom-text / no-fold-literal / obs-id-right
no-fold-quote = DQUOTE *(qtext / quoted-pair) DQUOTE
no-fold-literal = "[" *(dtext / quoted-pair) "]"
*/
$header = $this->_getHeader('Message-ID');
$header->setId('id-left@id-right');
$this->assertEquals('<id-left@id-right>', $header->getFieldBody());
}
public function testIdCanBeRetrievedVerbatim()
{
$header = $this->_getHeader('Message-ID');
$header->setId('id-left@id-right');
$this->assertEquals('id-left@id-right', $header->getId());
}
public function testMultipleIdsCanBeSet()
{
$header = $this->_getHeader('References');
$header->setIds(array('a@b', 'x@y'));
$this->assertEquals(array('a@b', 'x@y'), $header->getIds());
}
public function testSettingMultipleIdsProducesAListValue()
{
/* -- RFC 2822, 3.6.4.
The "References:" and "In-Reply-To:" field each contain one or more
unique message identifiers, optionally separated by CFWS.
.. SNIP ..
in-reply-to = "In-Reply-To:" 1*msg-id CRLF
references = "References:" 1*msg-id CRLF
*/
$header = $this->_getHeader('References');
$header->setIds(array('a@b', 'x@y'));
$this->assertEquals('<a@b> <x@y>', $header->getFieldBody());
}
public function testIdLeftCanBeQuoted()
{
/* -- RFC 2822, 3.6.4.
id-left = dot-atom-text / no-fold-quote / obs-id-left
*/
$header = $this->_getHeader('References');
$header->setId('"ab"@c');
$this->assertEquals('"ab"@c', $header->getId());
$this->assertEquals('<"ab"@c>', $header->getFieldBody());
}
public function testIdLeftCanContainAnglesAsQuotedPairs()
{
/* -- RFC 2822, 3.6.4.
no-fold-quote = DQUOTE *(qtext / quoted-pair) DQUOTE
*/
$header = $this->_getHeader('References');
$header->setId('"a\\<\\>b"@c');
$this->assertEquals('"a\\<\\>b"@c', $header->getId());
$this->assertEquals('<"a\\<\\>b"@c>', $header->getFieldBody());
}
public function testIdLeftCanBeDotAtom()
{
$header = $this->_getHeader('References');
$header->setId('a.b+&%$.c@d');
$this->assertEquals('a.b+&%$.c@d', $header->getId());
$this->assertEquals('<a.b+&%$.c@d>', $header->getFieldBody());
}
public function testInvalidIdLeftThrowsException()
{
try {
$header = $this->_getHeader('References');
$header->setId('a b c@d');
$this->fail(
'Exception should be thrown since "a b c" is not valid id-left.'
);
} catch (Exception $e) {
}
}
public function testIdRightCanBeDotAtom()
{
/* -- RFC 2822, 3.6.4.
id-right = dot-atom-text / no-fold-literal / obs-id-right
*/
$header = $this->_getHeader('References');
$header->setId('a@b.c+&%$.d');
$this->assertEquals('a@b.c+&%$.d', $header->getId());
$this->assertEquals('<a@b.c+&%$.d>', $header->getFieldBody());
}
public function testIdRightCanBeLiteral()
{
/* -- RFC 2822, 3.6.4.
no-fold-literal = "[" *(dtext / quoted-pair) "]"
*/
$header = $this->_getHeader('References');
$header->setId('a@[1.2.3.4]');
$this->assertEquals('a@[1.2.3.4]', $header->getId());
$this->assertEquals('<a@[1.2.3.4]>', $header->getFieldBody());
}
public function testInvalidIdRightThrowsException()
{
try {
$header = $this->_getHeader('References');
$header->setId('a@b c d');
$this->fail(
'Exception should be thrown since "b c d" is not valid id-right.'
);
} catch (Exception $e) {
}
}
public function testMissingAtSignThrowsException()
{
/* -- RFC 2822, 3.6.4.
msg-id = [CFWS] "<" id-left "@" id-right ">" [CFWS]
*/
try {
$header = $this->_getHeader('References');
$header->setId('abc');
$this->fail(
'Exception should be thrown since "abc" is does not contain @.'
);
} catch (Exception $e) {
}
}
public function testSetBodyModel()
{
$header = $this->_getHeader('Message-ID');
$header->setFieldBodyModel('a@b');
$this->assertEquals(array('a@b'), $header->getIds());
}
public function testGetBodyModel()
{
$header = $this->_getHeader('Message-ID');
$header->setId('a@b');
$this->assertEquals(array('a@b'), $header->getFieldBodyModel());
}
public function testStringValue()
{
$header = $this->_getHeader('References');
$header->setIds(array('a@b', 'x@y'));
$this->assertEquals('References: <a@b> <x@y>'."\r\n", $header->toString());
}
private function _getHeader($name)
{
return new Swift_Mime_Headers_IdentificationHeader($name, new Swift_Mime_Grammar());
}
}
| pipop1150/choke | vendor/swiftmailer/swiftmailer/tests/unit/Swift/Mime/Headers/IdentificationHeaderTest.php | PHP | bsd-3-clause | 5,861 |
import numpy as np
import scipy.sparse as sp
from sklearn.utils.testing import (assert_array_almost_equal, assert_less,
assert_equal, assert_not_equal,
assert_raises)
from sklearn.decomposition import PCA, KernelPCA
from sklearn.datasets import make_circles
from sklearn.linear_model import Perceptron
from sklearn.pipeline import Pipeline
from sklearn.model_selection import GridSearchCV
from sklearn.metrics.pairwise import rbf_kernel
def test_kernel_pca():
rng = np.random.RandomState(0)
X_fit = rng.random_sample((5, 4))
X_pred = rng.random_sample((2, 4))
def histogram(x, y, **kwargs):
# Histogram kernel implemented as a callable.
assert_equal(kwargs, {}) # no kernel_params that we didn't ask for
return np.minimum(x, y).sum()
for eigen_solver in ("auto", "dense", "arpack"):
for kernel in ("linear", "rbf", "poly", histogram):
# histogram kernel produces singular matrix inside linalg.solve
# XXX use a least-squares approximation?
inv = not callable(kernel)
# transform fit data
kpca = KernelPCA(4, kernel=kernel, eigen_solver=eigen_solver,
fit_inverse_transform=inv)
X_fit_transformed = kpca.fit_transform(X_fit)
X_fit_transformed2 = kpca.fit(X_fit).transform(X_fit)
assert_array_almost_equal(np.abs(X_fit_transformed),
np.abs(X_fit_transformed2))
# non-regression test: previously, gamma would be 0 by default,
# forcing all eigenvalues to 0 under the poly kernel
assert_not_equal(X_fit_transformed.size, 0)
# transform new data
X_pred_transformed = kpca.transform(X_pred)
assert_equal(X_pred_transformed.shape[1],
X_fit_transformed.shape[1])
# inverse transform
if inv:
X_pred2 = kpca.inverse_transform(X_pred_transformed)
assert_equal(X_pred2.shape, X_pred.shape)
def test_kernel_pca_invalid_parameters():
assert_raises(ValueError, KernelPCA, 10, fit_inverse_transform=True,
kernel='precomputed')
def test_kernel_pca_consistent_transform():
# X_fit_ needs to retain the old, unmodified copy of X
state = np.random.RandomState(0)
X = state.rand(10, 10)
kpca = KernelPCA(random_state=state).fit(X)
transformed1 = kpca.transform(X)
X_copy = X.copy()
X[:, 0] = 666
transformed2 = kpca.transform(X_copy)
assert_array_almost_equal(transformed1, transformed2)
def test_kernel_pca_sparse():
rng = np.random.RandomState(0)
X_fit = sp.csr_matrix(rng.random_sample((5, 4)))
X_pred = sp.csr_matrix(rng.random_sample((2, 4)))
for eigen_solver in ("auto", "arpack"):
for kernel in ("linear", "rbf", "poly"):
# transform fit data
kpca = KernelPCA(4, kernel=kernel, eigen_solver=eigen_solver,
fit_inverse_transform=False)
X_fit_transformed = kpca.fit_transform(X_fit)
X_fit_transformed2 = kpca.fit(X_fit).transform(X_fit)
assert_array_almost_equal(np.abs(X_fit_transformed),
np.abs(X_fit_transformed2))
# transform new data
X_pred_transformed = kpca.transform(X_pred)
assert_equal(X_pred_transformed.shape[1],
X_fit_transformed.shape[1])
# inverse transform
# X_pred2 = kpca.inverse_transform(X_pred_transformed)
# assert_equal(X_pred2.shape, X_pred.shape)
def test_kernel_pca_linear_kernel():
rng = np.random.RandomState(0)
X_fit = rng.random_sample((5, 4))
X_pred = rng.random_sample((2, 4))
# for a linear kernel, kernel PCA should find the same projection as PCA
# modulo the sign (direction)
# fit only the first four components: fifth is near zero eigenvalue, so
# can be trimmed due to roundoff error
assert_array_almost_equal(
np.abs(KernelPCA(4).fit(X_fit).transform(X_pred)),
np.abs(PCA(4).fit(X_fit).transform(X_pred)))
def test_kernel_pca_n_components():
rng = np.random.RandomState(0)
X_fit = rng.random_sample((5, 4))
X_pred = rng.random_sample((2, 4))
for eigen_solver in ("dense", "arpack"):
for c in [1, 2, 4]:
kpca = KernelPCA(n_components=c, eigen_solver=eigen_solver)
shape = kpca.fit(X_fit).transform(X_pred).shape
assert_equal(shape, (2, c))
def test_remove_zero_eig():
X = np.array([[1 - 1e-30, 1], [1, 1], [1, 1 - 1e-20]])
# n_components=None (default) => remove_zero_eig is True
kpca = KernelPCA()
Xt = kpca.fit_transform(X)
assert_equal(Xt.shape, (3, 0))
kpca = KernelPCA(n_components=2)
Xt = kpca.fit_transform(X)
assert_equal(Xt.shape, (3, 2))
kpca = KernelPCA(n_components=2, remove_zero_eig=True)
Xt = kpca.fit_transform(X)
assert_equal(Xt.shape, (3, 0))
def test_kernel_pca_precomputed():
rng = np.random.RandomState(0)
X_fit = rng.random_sample((5, 4))
X_pred = rng.random_sample((2, 4))
for eigen_solver in ("dense", "arpack"):
X_kpca = KernelPCA(4, eigen_solver=eigen_solver).\
fit(X_fit).transform(X_pred)
X_kpca2 = KernelPCA(
4, eigen_solver=eigen_solver, kernel='precomputed').fit(
np.dot(X_fit, X_fit.T)).transform(np.dot(X_pred, X_fit.T))
X_kpca_train = KernelPCA(
4, eigen_solver=eigen_solver,
kernel='precomputed').fit_transform(np.dot(X_fit, X_fit.T))
X_kpca_train2 = KernelPCA(
4, eigen_solver=eigen_solver, kernel='precomputed').fit(
np.dot(X_fit, X_fit.T)).transform(np.dot(X_fit, X_fit.T))
assert_array_almost_equal(np.abs(X_kpca),
np.abs(X_kpca2))
assert_array_almost_equal(np.abs(X_kpca_train),
np.abs(X_kpca_train2))
def test_kernel_pca_invalid_kernel():
rng = np.random.RandomState(0)
X_fit = rng.random_sample((2, 4))
kpca = KernelPCA(kernel="tototiti")
assert_raises(ValueError, kpca.fit, X_fit)
def test_gridsearch_pipeline():
# Test if we can do a grid-search to find parameters to separate
# circles with a perceptron model.
X, y = make_circles(n_samples=400, factor=.3, noise=.05,
random_state=0)
kpca = KernelPCA(kernel="rbf", n_components=2)
pipeline = Pipeline([("kernel_pca", kpca), ("Perceptron", Perceptron())])
param_grid = dict(kernel_pca__gamma=2. ** np.arange(-2, 2))
grid_search = GridSearchCV(pipeline, cv=3, param_grid=param_grid)
grid_search.fit(X, y)
assert_equal(grid_search.best_score_, 1)
def test_gridsearch_pipeline_precomputed():
# Test if we can do a grid-search to find parameters to separate
# circles with a perceptron model using a precomputed kernel.
X, y = make_circles(n_samples=400, factor=.3, noise=.05,
random_state=0)
kpca = KernelPCA(kernel="precomputed", n_components=2)
pipeline = Pipeline([("kernel_pca", kpca), ("Perceptron", Perceptron())])
param_grid = dict(Perceptron__n_iter=np.arange(1, 5))
grid_search = GridSearchCV(pipeline, cv=3, param_grid=param_grid)
X_kernel = rbf_kernel(X, gamma=2.)
grid_search.fit(X_kernel, y)
assert_equal(grid_search.best_score_, 1)
def test_nested_circles():
# Test the linear separability of the first 2D KPCA transform
X, y = make_circles(n_samples=400, factor=.3, noise=.05,
random_state=0)
# 2D nested circles are not linearly separable
train_score = Perceptron().fit(X, y).score(X, y)
assert_less(train_score, 0.8)
# Project the circles data into the first 2 components of a RBF Kernel
# PCA model.
# Note that the gamma value is data dependent. If this test breaks
# and the gamma value has to be updated, the Kernel PCA example will
# have to be updated too.
kpca = KernelPCA(kernel="rbf", n_components=2,
fit_inverse_transform=True, gamma=2.)
X_kpca = kpca.fit_transform(X)
# The data is perfectly linearly separable in that space
train_score = Perceptron().fit(X_kpca, y).score(X_kpca, y)
assert_equal(train_score, 1.0)
| IshankGulati/scikit-learn | sklearn/decomposition/tests/test_kernel_pca.py | Python | bsd-3-clause | 8,472 |
window.JSON||(window.JSON={}),function(){function f(a){return a<10?"0"+a:a}function quote(a){return escapable.lastIndex=0,escapable.test(a)?'"'+a.replace(escapable,function(a){var b=meta[a];return typeof b=="string"?b:"\\u"+("0000"+a.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+a+'"'}function str(a,b){var c,d,e,f,g=gap,h,i=b[a];i&&typeof i=="object"&&typeof i.toJSON=="function"&&(i=i.toJSON(a)),typeof rep=="function"&&(i=rep.call(b,a,i));switch(typeof i){case"string":return quote(i);case"number":return isFinite(i)?String(i):"null";case"boolean":case"null":return String(i);case"object":if(!i)return"null";gap+=indent,h=[];if(Object.prototype.toString.apply(i)==="[object Array]"){f=i.length;for(c=0;c<f;c+=1)h[c]=str(c,i)||"null";return e=h.length===0?"[]":gap?"[\n"+gap+h.join(",\n"+gap)+"\n"+g+"]":"["+h.join(",")+"]",gap=g,e}if(rep&&typeof rep=="object"){f=rep.length;for(c=0;c<f;c+=1)d=rep[c],typeof d=="string"&&(e=str(d,i),e&&h.push(quote(d)+(gap?": ":":")+e))}else for(d in i)Object.hasOwnProperty.call(i,d)&&(e=str(d,i),e&&h.push(quote(d)+(gap?": ":":")+e));return e=h.length===0?"{}":gap?"{\n"+gap+h.join(",\n"+gap)+"\n"+g+"}":"{"+h.join(",")+"}",gap=g,e}}"use strict",typeof Date.prototype.toJSON!="function"&&(Date.prototype.toJSON=function(a){return isFinite(this.valueOf())?this.getUTCFullYear()+"-"+f(this.getUTCMonth()+1)+"-"+f(this.getUTCDate())+"T"+f(this.getUTCHours())+":"+f(this.getUTCMinutes())+":"+f(this.getUTCSeconds())+"Z":null},String.prototype.toJSON=Number.prototype.toJSON=Boolean.prototype.toJSON=function(a){return this.valueOf()});var JSON=window.JSON,cx=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,escapable=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,gap,indent,meta={"\b":"\\b","\t":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"},rep;typeof JSON.stringify!="function"&&(JSON.stringify=function(a,b,c){var d;gap="",indent="";if(typeof c=="number")for(d=0;d<c;d+=1)indent+=" ";else typeof c=="string"&&(indent=c);rep=b;if(!b||typeof b=="function"||typeof b=="object"&&typeof b.length=="number")return str("",{"":a});throw new Error("JSON.stringify")}),typeof JSON.parse!="function"&&(JSON.parse=function(text,reviver){function walk(a,b){var c,d,e=a[b];if(e&&typeof e=="object")for(c in e)Object.hasOwnProperty.call(e,c)&&(d=walk(e,c),d!==undefined?e[c]=d:delete e[c]);return reviver.call(a,b,e)}var j;text=String(text),cx.lastIndex=0,cx.test(text)&&(text=text.replace(cx,function(a){return"\\u"+("0000"+a.charCodeAt(0).toString(16)).slice(-4)}));if(/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,"@").replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,"]").replace(/(?:^|:|,)(?:\s*\[)+/g,"")))return j=eval("("+text+")"),typeof reviver=="function"?walk({"":j},""):j;throw new SyntaxError("JSON.parse")})}(),function(a,b){"use strict";var c=a.History=a.History||{},d=a.MooTools,e=a.Element;if(typeof c.Adapter!="undefined")throw new Error("History.js Adapter has already been loaded...");Object.append(e.NativeEvents,{popstate:2,hashchange:2}),c.Adapter={bind:function(a,b,c){var d=typeof a=="string"?document.id(a):a;d.addEvent(b,c)},trigger:function(a,b,c){var d=typeof a=="string"?document.id(a):a;d.fireEvent(b,c)},extractEventData:function(a,c){var d=c&&c.event&&c.event[a]||c&&c[a]||b;return d},onDomLoad:function(b){a.addEvent("domready",b)}},typeof c.init!="undefined"&&c.init()}(window),function(a,b){"use strict";var c=a.document,d=a.setTimeout||d,e=a.clearTimeout||e,f=a.setInterval||f,g=a.History=a.History||{};if(typeof g.initHtml4!="undefined")throw new Error("History.js HTML4 Support has already been loaded...");g.initHtml4=function(){if(typeof g.initHtml4.initialized!="undefined")return!1;g.initHtml4.initialized=!0,g.enabled=!0,g.savedHashes=[],g.isLastHash=function(a){var b=g.getHashByIndex(),c;return c=a===b,c},g.saveHash=function(a){return g.isLastHash(a)?!1:(g.savedHashes.push(a),!0)},g.getHashByIndex=function(a){var b=null;return typeof a=="undefined"?b=g.savedHashes[g.savedHashes.length-1]:a<0?b=g.savedHashes[g.savedHashes.length+a]:b=g.savedHashes[a],b},g.discardedHashes={},g.discardedStates={},g.discardState=function(a,b,c){var d=g.getHashByState(a),e;return e={discardedState:a,backState:c,forwardState:b},g.discardedStates[d]=e,!0},g.discardHash=function(a,b,c){var d={discardedHash:a,backState:c,forwardState:b};return g.discardedHashes[a]=d,!0},g.discardedState=function(a){var b=g.getHashByState(a),c;return c=g.discardedStates[b]||!1,c},g.discardedHash=function(a){var b=g.discardedHashes[a]||!1;return b},g.recycleState=function(a){var b=g.getHashByState(a);return g.discardedState(a)&&delete g.discardedStates[b],!0},g.emulated.hashChange&&(g.hashChangeInit=function(){g.checkerFunction=null;var b="",d,e,h,i;return g.isInternetExplorer()?(d="historyjs-iframe",e=c.createElement("iframe"),e.setAttribute("id",d),e.style.display="none",c.body.appendChild(e),e.contentWindow.document.open(),e.contentWindow.document.close(),h="",i=!1,g.checkerFunction=function(){if(i)return!1;i=!0;var c=g.getHash()||"",d=g.unescapeHash(e.contentWindow.document.location.hash)||"";return c!==b?(b=c,d!==c&&(h=d=c,e.contentWindow.document.open(),e.contentWindow.document.close(),e.contentWindow.document.location.hash=g.escapeHash(c)),g.Adapter.trigger(a,"hashchange")):d!==h&&(h=d,g.setHash(d,!1)),i=!1,!0}):g.checkerFunction=function(){var c=g.getHash();return c!==b&&(b=c,g.Adapter.trigger(a,"hashchange")),!0},g.intervalList.push(f(g.checkerFunction,g.options.hashChangeInterval)),!0},g.Adapter.onDomLoad(g.hashChangeInit)),g.emulated.pushState&&(g.onHashChange=function(b){var d=b&&b.newURL||c.location.href,e=g.getHashByUrl(d),f=null,h=null,i=null,j;return g.isLastHash(e)?(g.busy(!1),!1):(g.doubleCheckComplete(),g.saveHash(e),e&&g.isTraditionalAnchor(e)?(g.Adapter.trigger(a,"anchorchange"),g.busy(!1),!1):(f=g.extractState(g.getFullUrl(e||c.location.href,!1),!0),g.isLastSavedState(f)?(g.busy(!1),!1):(h=g.getHashByState(f),j=g.discardedState(f),j?(g.getHashByIndex(-2)===g.getHashByState(j.forwardState)?g.back(!1):g.forward(!1),!1):(g.pushState(f.data,f.title,f.url,!1),!0))))},g.Adapter.bind(a,"hashchange",g.onHashChange),g.pushState=function(b,d,e,f){if(g.getHashByUrl(e))throw new Error("History.js does not support states with fragement-identifiers (hashes/anchors).");if(f!==!1&&g.busy())return g.pushQueue({scope:g,callback:g.pushState,args:arguments,queue:f}),!1;g.busy(!0);var h=g.createStateObject(b,d,e),i=g.getHashByState(h),j=g.getState(!1),k=g.getHashByState(j),l=g.getHash();return g.storeState(h),g.expectedStateId=h.id,g.recycleState(h),g.setTitle(h),i===k?(g.busy(!1),!1):i!==l&&i!==g.getShortUrl(c.location.href)?(g.setHash(i,!1),!1):(g.saveState(h),g.Adapter.trigger(a,"statechange"),g.busy(!1),!0)},g.replaceState=function(a,b,c,d){if(g.getHashByUrl(c))throw new Error("History.js does not support states with fragement-identifiers (hashes/anchors).");if(d!==!1&&g.busy())return g.pushQueue({scope:g,callback:g.replaceState,args:arguments,queue:d}),!1;g.busy(!0);var e=g.createStateObject(a,b,c),f=g.getState(!1),h=g.getStateByIndex(-2);return g.discardState(f,e,h),g.pushState(e.data,e.title,e.url,!1),!0}),g.emulated.pushState&&g.getHash()&&!g.emulated.hashChange&&g.Adapter.onDomLoad(function(){g.Adapter.trigger(a,"hashchange")})},typeof g.init!="undefined"&&g.init()}(window),function(a,b){"use strict";var c=a.console||b,d=a.document,e=a.navigator,f=a.sessionStorage||!1,g=a.setTimeout,h=a.clearTimeout,i=a.setInterval,j=a.clearInterval,k=a.JSON,l=a.alert,m=a.History=a.History||{},n=a.history;k.stringify=k.stringify||k.encode,k.parse=k.parse||k.decode;if(typeof m.init!="undefined")throw new Error("History.js Core has already been loaded...");m.init=function(){return typeof m.Adapter=="undefined"?!1:(typeof m.initCore!="undefined"&&m.initCore(),typeof m.initHtml4!="undefined"&&m.initHtml4(),!0)},m.initCore=function(){if(typeof m.initCore.initialized!="undefined")return!1;m.initCore.initialized=!0,m.options=m.options||{},m.options.hashChangeInterval=m.options.hashChangeInterval||100,m.options.safariPollInterval=m.options.safariPollInterval||500,m.options.doubleCheckInterval=m.options.doubleCheckInterval||500,m.options.storeInterval=m.options.storeInterval||1e3,m.options.busyDelay=m.options.busyDelay||250,m.options.debug=m.options.debug||!1,m.options.initialTitle=m.options.initialTitle||d.title,m.intervalList=[],m.clearAllIntervals=function(){var a,b=m.intervalList;if(typeof b!="undefined"&&b!==null){for(a=0;a<b.length;a++)j(b[a]);m.intervalList=null}},m.debug=function(){(m.options.debug||!1)&&m.log.apply(m,arguments)},m.log=function(){var a=typeof c!="undefined"&&typeof c.log!="undefined"&&typeof c.log.apply!="undefined",b=d.getElementById("log"),e,f,g,h,i;a?(h=Array.prototype.slice.call(arguments),e=h.shift(),typeof c.debug!="undefined"?c.debug.apply(c,[e,h]):c.log.apply(c,[e,h])):e="\n"+arguments[0]+"\n";for(f=1,g=arguments.length;f<g;++f){i=arguments[f];if(typeof i=="object"&&typeof k!="undefined")try{i=k.stringify(i)}catch(j){}e+="\n"+i+"\n"}return b?(b.value+=e+"\n-----\n",b.scrollTop=b.scrollHeight-b.clientHeight):a||l(e),!0},m.getInternetExplorerMajorVersion=function(){var a=m.getInternetExplorerMajorVersion.cached=typeof m.getInternetExplorerMajorVersion.cached!="undefined"?m.getInternetExplorerMajorVersion.cached:function(){var a=3,b=d.createElement("div"),c=b.getElementsByTagName("i");while((b.innerHTML="<!--[if gt IE "+ ++a+"]><i></i><![endif]-->")&&c[0]);return a>4?a:!1}();return a},m.isInternetExplorer=function(){var a=m.isInternetExplorer.cached=typeof m.isInternetExplorer.cached!="undefined"?m.isInternetExplorer.cached:Boolean(m.getInternetExplorerMajorVersion());return a},m.emulated={pushState:!Boolean(a.history&&a.history.pushState&&a.history.replaceState&&!/ Mobile\/([1-7][a-z]|(8([abcde]|f(1[0-8]))))/i.test(e.userAgent)&&!/AppleWebKit\/5([0-2]|3[0-2])/i.test(e.userAgent)),hashChange:Boolean(!("onhashchange"in a||"onhashchange"in d)||m.isInternetExplorer()&&m.getInternetExplorerMajorVersion()<8)},m.enabled=!m.emulated.pushState,m.bugs={setHash:Boolean(!m.emulated.pushState&&e.vendor==="Apple Computer, Inc."&&/AppleWebKit\/5([0-2]|3[0-3])/.test(e.userAgent)),safariPoll:Boolean(!m.emulated.pushState&&e.vendor==="Apple Computer, Inc."&&/AppleWebKit\/5([0-2]|3[0-3])/.test(e.userAgent)),ieDoubleCheck:Boolean(m.isInternetExplorer()&&m.getInternetExplorerMajorVersion()<8),hashEscape:Boolean(m.isInternetExplorer()&&m.getInternetExplorerMajorVersion()<7)},m.isEmptyObject=function(a){for(var b in a)return!1;return!0},m.cloneObject=function(a){var b,c;return a?(b=k.stringify(a),c=k.parse(b)):c={},c},m.getRootUrl=function(){var a=d.location.protocol+"//"+(d.location.hostname||d.location.host);if(d.location.port||!1)a+=":"+d.location.port;return a+="/",a},m.getBaseHref=function(){var a=d.getElementsByTagName("base"),b=null,c="";return a.length===1&&(b=a[0],c=b.href.replace(/[^\/]+$/,"")),c=c.replace(/\/+$/,""),c&&(c+="/"),c},m.getBaseUrl=function(){var a=m.getBaseHref()||m.getBasePageUrl()||m.getRootUrl();return a},m.getPageUrl=function(){var a=m.getState(!1,!1),b=(a||{}).url||d.location.href,c;return c=b.replace(/\/+$/,"").replace(/[^\/]+$/,function(a,b,c){return/\./.test(a)?a:a+"/"}),c},m.getBasePageUrl=function(){var a=d.location.href.replace(/[#\?].*/,"").replace(/[^\/]+$/,function(a,b,c){return/[^\/]$/.test(a)?"":a}).replace(/\/+$/,"")+"/";return a},m.getFullUrl=function(a,b){var c=a,d=a.substring(0,1);return b=typeof b=="undefined"?!0:b,/[a-z]+\:\/\//.test(a)||(d==="/"?c=m.getRootUrl()+a.replace(/^\/+/,""):d==="#"?c=m.getPageUrl().replace(/#.*/,"")+a:d==="?"?c=m.getPageUrl().replace(/[\?#].*/,"")+a:b?c=m.getBaseUrl()+a.replace(/^(\.\/)+/,""):c=m.getBasePageUrl()+a.replace(/^(\.\/)+/,"")),c.replace(/\#$/,"")},m.getShortUrl=function(a){var b=a,c=m.getBaseUrl(),d=m.getRootUrl();return m.emulated.pushState&&(b=b.replace(c,"")),b=b.replace(d,"/"),m.isTraditionalAnchor(b)&&(b="./"+b),b=b.replace(/^(\.\/)+/g,"./").replace(/\#$/,""),b},m.store={},m.idToState=m.idToState||{},m.stateToId=m.stateToId||{},m.urlToId=m.urlToId||{},m.storedStates=m.storedStates||[],m.savedStates=m.savedStates||[],m.normalizeStore=function(){m.store.idToState=m.store.idToState||{},m.store.urlToId=m.store.urlToId||{},m.store.stateToId=m.store.stateToId||{}},m.getState=function(a,b){typeof a=="undefined"&&(a=!0),typeof b=="undefined"&&(b=!0);var c=m.getLastSavedState();return!c&&b&&(c=m.createStateObject()),a&&(c=m.cloneObject(c),c.url=c.cleanUrl||c.url),c},m.getIdByState=function(a){var b=m.extractId(a.url),c;if(!b){c=m.getStateString(a);if(typeof m.stateToId[c]!="undefined")b=m.stateToId[c];else if(typeof m.store.stateToId[c]!="undefined")b=m.store.stateToId[c];else{for(;;){b=(new Date).getTime()+String(Math.random()).replace(/\D/g,"");if(typeof m.idToState[b]=="undefined"&&typeof m.store.idToState[b]=="undefined")break}m.stateToId[c]=b,m.idToState[b]=a}}return b},m.normalizeState=function(a){var b,c;if(!a||typeof a!="object")a={};if(typeof a.normalized!="undefined")return a;if(!a.data||typeof a.data!="object")a.data={};b={},b.normalized=!0,b.title=a.title||"",b.url=m.getFullUrl(m.unescapeString(a.url||d.location.href)),b.hash=m.getShortUrl(b.url),b.data=m.cloneObject(a.data),b.id=m.getIdByState(b),b.cleanUrl=b.url.replace(/\??\&_suid.*/,""),b.url=b.cleanUrl,c=!m.isEmptyObject(b.data);if(b.title||c)b.hash=m.getShortUrl(b.url).replace(/\??\&_suid.*/,""),/\?/.test(b.hash)||(b.hash+="?"),b.hash+="&_suid="+b.id;return b.hashedUrl=m.getFullUrl(b.hash),(m.emulated.pushState||m.bugs.safariPoll)&&m.hasUrlDuplicate(b)&&(b.url=b.hashedUrl),b},m.createStateObject=function(a,b,c){var d={data:a,title:b,url:c};return d=m.normalizeState(d),d},m.getStateById=function(a){a=String(a);var c=m.idToState[a]||m.store.idToState[a]||b;return c},m.getStateString=function(a){var b,c,d;return b=m.normalizeState(a),c={data:b.data,title:a.title,url:a.url},d=k.stringify(c),d},m.getStateId=function(a){var b,c;return b=m.normalizeState(a),c=b.id,c},m.getHashByState=function(a){var b,c;return b=m.normalizeState(a),c=b.hash,c},m.extractId=function(a){var b,c,d;return c=/(.*)\&_suid=([0-9]+)$/.exec(a),d=c?c[1]||a:a,b=c?String(c[2]||""):"",b||!1},m.isTraditionalAnchor=function(a){var b=!/[\/\?\.]/.test(a);return b},m.extractState=function(a,b){var c=null,d,e;return b=b||!1,d=m.extractId(a),d&&(c=m.getStateById(d)),c||(e=m.getFullUrl(a),d=m.getIdByUrl(e)||!1,d&&(c=m.getStateById(d)),!c&&b&&!m.isTraditionalAnchor(a)&&(c=m.createStateObject(null,null,e))),c},m.getIdByUrl=function(a){var c=m.urlToId[a]||m.store.urlToId[a]||b;return c},m.getLastSavedState=function(){return m.savedStates[m.savedStates.length-1]||b},m.getLastStoredState=function(){return m.storedStates[m.storedStates.length-1]||b},m.hasUrlDuplicate=function(a){var b=!1,c;return c=m.extractState(a.url),b=c&&c.id!==a.id,b},m.storeState=function(a){return m.urlToId[a.url]=a.id,m.storedStates.push(m.cloneObject(a)),a},m.isLastSavedState=function(a){var b=!1,c,d,e;return m.savedStates.length&&(c=a.id,d=m.getLastSavedState(),e=d.id,b=c===e),b},m.saveState=function(a){return m.isLastSavedState(a)?!1:(m.savedStates.push(m.cloneObject(a)),!0)},m.getStateByIndex=function(a){var b=null;return typeof a=="undefined"?b=m.savedStates[m.savedStates.length-1]:a<0?b=m.savedStates[m.savedStates.length+a]:b=m.savedStates[a],b},m.getHash=function(){var a=m.unescapeHash(d.location.hash);return a},m.unescapeString=function(b){var c=b,d;for(;;){d=a.unescape(c);if(d===c)break;c=d}return c},m.unescapeHash=function(a){var b=m.normalizeHash(a);return b=m.unescapeString(b),b},m.normalizeHash=function(a){var b=a.replace(/[^#]*#/,"").replace(/#.*/,"");return b},m.setHash=function(a,b){var c,e,f;return b!==!1&&m.busy()?(m.pushQueue({scope:m,callback:m.setHash,args:arguments,queue:b}),!1):(c=m.escapeHash(a),m.busy(!0),e=m.extractState(a,!0),e&&!m.emulated.pushState?m.pushState(e.data,e.title,e.url,!1):d.location.hash!==c&&(m.bugs.setHash?(f=m.getPageUrl(),m.pushState(null,null,f+"#"+c,!1)):d.location.hash=c),m)},m.escapeHash=function(b){var c=m.normalizeHash(b);return c=a.escape(c),m.bugs.hashEscape||(c=c.replace(/\%21/g,"!").replace(/\%26/g,"&").replace(/\%3D/g,"=").replace(/\%3F/g,"?")),c},m.getHashByUrl=function(a){var b=String(a).replace(/([^#]*)#?([^#]*)#?(.*)/,"$2");return b=m.unescapeHash(b),b},m.setTitle=function(a){var b=a.title,c;b||(c=m.getStateByIndex(0),c&&c.url===a.url&&(b=c.title||m.options.initialTitle));try{d.getElementsByTagName("title")[0].innerHTML=b.replace("<","<").replace(">",">").replace(" & "," & ")}catch(e){}return d.title=b,m},m.queues=[],m.busy=function(a){typeof a!="undefined"?m.busy.flag=a:typeof m.busy.flag=="undefined"&&(m.busy.flag=!1);if(!m.busy.flag){h(m.busy.timeout);var b=function(){var a,c,d;if(m.busy.flag)return;for(a=m.queues.length-1;a>=0;--a){c=m.queues[a];if(c.length===0)continue;d=c.shift(),m.fireQueueItem(d),m.busy.timeout=g(b,m.options.busyDelay)}};m.busy.timeout=g(b,m.options.busyDelay)}return m.busy.flag},m.busy.flag=!1,m.fireQueueItem=function(a){return a.callback.apply(a.scope||m,a.args||[])},m.pushQueue=function(a){return m.queues[a.queue||0]=m.queues[a.queue||0]||[],m.queues[a.queue||0].push(a),m},m.queue=function(a,b){return typeof a=="function"&&(a={callback:a}),typeof b!="undefined"&&(a.queue=b),m.busy()?m.pushQueue(a):m.fireQueueItem(a),m},m.clearQueue=function(){return m.busy.flag=!1,m.queues=[],m},m.stateChanged=!1,m.doubleChecker=!1,m.doubleCheckComplete=function(){return m.stateChanged=!0,m.doubleCheckClear(),m},m.doubleCheckClear=function(){return m.doubleChecker&&(h(m.doubleChecker),m.doubleChecker=!1),m},m.doubleCheck=function(a){return m.stateChanged=!1,m.doubleCheckClear(),m.bugs.ieDoubleCheck&&(m.doubleChecker=g(function(){return m.doubleCheckClear(),m.stateChanged||a(),!0},m.options.doubleCheckInterval)),m},m.safariStatePoll=function(){var b=m.extractState(d.location.href),c;if(!m.isLastSavedState(b))c=b;else return;return c||(c=m.createStateObject()),m.Adapter.trigger(a,"popstate"),m},m.back=function(a){return a!==!1&&m.busy()?(m.pushQueue({scope:m,callback:m.back,args:arguments,queue:a}),!1):(m.busy(!0),m.doubleCheck(function(){m.back(!1)}),n.go(-1),!0)},m.forward=function(a){return a!==!1&&m.busy()?(m.pushQueue({scope:m,callback:m.forward,args:arguments,queue:a}),!1):(m.busy(!0),m.doubleCheck(function(){m.forward(!1)}),n.go(1),!0)},m.go=function(a,b){var c;if(a>0)for(c=1;c<=a;++c)m.forward(b);else{if(!(a<0))throw new Error("History.go: History.go requires a positive or negative integer passed.");for(c=-1;c>=a;--c)m.back(b)}return m};if(m.emulated.pushState){var o=function(){};m.pushState=m.pushState||o,m.replaceState=m.replaceState||o}else m.onPopState=function(b,c){var e=!1,f=!1,g,h;return m.doubleCheckComplete(),g=m.getHash(),g?(h=m.extractState(g||d.location.href,!0),h?m.replaceState(h.data,h.title,h.url,!1):(m.Adapter.trigger(a,"anchorchange"),m.busy(!1)),m.expectedStateId=!1,!1):(e=m.Adapter.extractEventData("state",b,c)||!1,e?f=m.getStateById(e):m.expectedStateId?f=m.getStateById(m.expectedStateId):f=m.extractState(d.location.href),f||(f=m.createStateObject(null,null,d.location.href)),m.expectedStateId=!1,m.isLastSavedState(f)?(m.busy(!1),!1):(m.storeState(f),m.saveState(f),m.setTitle(f),m.Adapter.trigger(a,"statechange"),m.busy(!1),!0))},m.Adapter.bind(a,"popstate",m.onPopState),m.pushState=function(b,c,d,e){if(m.getHashByUrl(d)&&m.emulated.pushState)throw new Error("History.js does not support states with fragement-identifiers (hashes/anchors).");if(e!==!1&&m.busy())return m.pushQueue({scope:m,callback:m.pushState,args:arguments,queue:e}),!1;m.busy(!0);var f=m.createStateObject(b,c,d);return m.isLastSavedState(f)?m.busy(!1):(m.storeState(f),m.expectedStateId=f.id,n.pushState(f.id,f.title,f.url),m.Adapter.trigger(a,"popstate")),!0},m.replaceState=function(b,c,d,e){if(m.getHashByUrl(d)&&m.emulated.pushState)throw new Error("History.js does not support states with fragement-identifiers (hashes/anchors).");if(e!==!1&&m.busy())return m.pushQueue({scope:m,callback:m.replaceState,args:arguments,queue:e}),!1;m.busy(!0);var f=m.createStateObject(b,c,d);return m.isLastSavedState(f)?m.busy(!1):(m.storeState(f),m.expectedStateId=f.id,n.replaceState(f.id,f.title,f.url),m.Adapter.trigger(a,"popstate")),!0};if(f){try{m.store=k.parse(f.getItem("History.store"))||{}}catch(p){m.store={}}m.normalizeStore()}else m.store={},m.normalizeStore();m.Adapter.bind(a,"beforeunload",m.clearAllIntervals),m.Adapter.bind(a,"unload",m.clearAllIntervals),m.saveState(m.storeState(m.extractState(d.location.href,!0))),f&&(m.onUnload=function(){var a,b;try{a=k.parse(f.getItem("History.store"))||{}}catch(c){a={}}a.idToState=a.idToState||{},a.urlToId=a.urlToId||{},a.stateToId=a.stateToId||{};for(b in m.idToState){if(!m.idToState.hasOwnProperty(b))continue;a.idToState[b]=m.idToState[b]}for(b in m.urlToId){if(!m.urlToId.hasOwnProperty(b))continue;a.urlToId[b]=m.urlToId[b]}for(b in m.stateToId){if(!m.stateToId.hasOwnProperty(b))continue;a.stateToId[b]=m.stateToId[b]}m.store=a,m.normalizeStore(),f.setItem("History.store",k.stringify(a))},m.intervalList.push(i(m.onUnload,m.options.storeInterval)),m.Adapter.bind(a,"beforeunload",m.onUnload),m.Adapter.bind(a,"unload",m.onUnload));if(!m.emulated.pushState){m.bugs.safariPoll&&m.intervalList.push(i(m.safariStatePoll,m.options.safariPollInterval));if(e.vendor==="Apple Computer, Inc."||(e.appCodeName||"")==="Mozilla")m.Adapter.bind(a,"hashchange",function(){m.Adapter.trigger(a,"popstate")}),m.getHash()&&m.Adapter.onDomLoad(function(){m.Adapter.trigger(a,"hashchange")})}},m.init()}(window) | drpheltright/history.js | scripts/bundled/html4+html5/mootools.history.js | JavaScript | bsd-3-clause | 21,727 |
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Feed\Writer;
use Traversable;
abstract class FeedFactory
{
/**
* Create and return a Feed based on data provided.
*
* @param array|Traversable $data
* @throws Exception\InvalidArgumentException
* @return Feed
*/
public static function factory($data)
{
if (!is_array($data) && !$data instanceof Traversable) {
throw new Exception\InvalidArgumentException(sprintf(
'%s expects an array or Traversable argument; received "%s"',
__METHOD__,
(is_object($data) ? get_class($data) : gettype($data))
));
}
$feed = new Feed();
foreach ($data as $key => $value) {
// Setters
$key = static::convertKey($key);
$method = 'set' . $key;
if (method_exists($feed, $method)) {
switch ($method) {
case 'setfeedlink':
if (!is_array($value)) {
// Need an array
break;
}
if (!array_key_exists('link', $value) || !array_key_exists('type', $value)) {
// Need both keys to set this correctly
break;
}
$feed->setFeedLink($value['link'], $value['type']);
break;
default:
$feed->$method($value);
break;
}
continue;
}
// Entries
if ('entries' == $key) {
static::createEntries($value, $feed);
continue;
}
}
return $feed;
}
/**
* Normalize a key
*
* @param string $key
* @return string
*/
protected static function convertKey($key)
{
$key = str_replace('_', '', strtolower($key));
return $key;
}
/**
* Create and attach entries to a feed
*
* @param array|Traversable $entries
* @param Feed $feed
* @throws Exception\InvalidArgumentException
* @return void
*/
protected static function createEntries($entries, Feed $feed)
{
if (!is_array($entries) && !$entries instanceof Traversable) {
throw new Exception\InvalidArgumentException(sprintf(
'%s::factory expects the "entries" value to be an array or Traversable; received "%s"',
get_called_class(),
(is_object($entries) ? get_class($entries) : gettype($entries))
));
}
foreach ($entries as $data) {
if (!is_array($data) && !$data instanceof Traversable && !$data instanceof Entry) {
throw new Exception\InvalidArgumentException(sprintf(
'%s expects an array, Traversable, or Zend\Feed\Writer\Entry argument; received "%s"',
__METHOD__,
(is_object($data) ? get_class($data) : gettype($data))
));
}
// Use case 1: Entry item
if ($data instanceof Entry) {
$feed->addEntry($data);
continue;
}
// Use case 2: iterate item and populate entry
$entry = $feed->createEntry();
foreach ($data as $key => $value) {
$key = static::convertKey($key);
$method = 'set' . $key;
if (!method_exists($entry, $method)) {
continue;
}
$entry->$method($value);
}
$feed->addEntry($entry);
}
}
}
| jsowndarrajan/IntegrationTest | vendor/zendframework/zendframework/library/Zend/Feed/Writer/FeedFactory.php | PHP | bsd-3-clause | 4,075 |
import six
import cherrypy
from social.strategies.base import BaseStrategy, BaseTemplateStrategy
class CherryPyJinja2TemplateStrategy(BaseTemplateStrategy):
def __init__(self, strategy):
self.strategy = strategy
self.env = cherrypy.tools.jinja2env
def render_template(self, tpl, context):
return self.env.get_template(tpl).render(context)
def render_string(self, html, context):
return self.env.from_string(html).render(context)
class CherryPyStrategy(BaseStrategy):
DEFAULT_TEMPLATE_STRATEGY = CherryPyJinja2TemplateStrategy
def get_setting(self, name):
return cherrypy.config[name]
def request_data(self, merge=True):
if merge:
data = cherrypy.request.params
elif cherrypy.request.method == 'POST':
data = cherrypy.body.params
else:
data = cherrypy.request.params
return data
def request_host(self):
return cherrypy.request.base
def redirect(self, url):
raise cherrypy.HTTPRedirect(url)
def html(self, content):
return content
def authenticate(self, backend, *args, **kwargs):
kwargs['strategy'] = self
kwargs['storage'] = self.storage
kwargs['backend'] = backend
return backend.authenticate(*args, **kwargs)
def session_get(self, name, default=None):
return cherrypy.session.get(name, default)
def session_set(self, name, value):
cherrypy.session[name] = value
def session_pop(self, name):
cherrypy.session.pop(name, None)
def session_setdefault(self, name, value):
return cherrypy.session.setdefault(name, value)
def build_absolute_uri(self, path=None):
return cherrypy.url(path or '')
def is_response(self, value):
return isinstance(value, six.string_types) or \
isinstance(value, cherrypy.CherryPyException)
| JJediny/python-social-auth | social/strategies/cherrypy_strategy.py | Python | bsd-3-clause | 1,924 |
/*!
* jQuery UI CSS Framework 1.9.1
* http://jqueryui.com
*
* Copyright 2012 jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*
* http://docs.jquery.com/UI/Theming/API
*
* To view and modify this theme, visit http://jqueryui.com/themeroller/?ffDefault=Helvetica%2CArial%2Csans-serif&fwDefault=normal&fsDefault=1.1em&cornerRadius=6px&bgColorHeader=cb842e&bgTextureHeader=02_glass.png&bgImgOpacityHeader=25&borderColorHeader=d49768&fcHeader=ffffff&iconColorHeader=ffffff&bgColorContent=f4f0ec&bgTextureContent=05_inset_soft.png&bgImgOpacityContent=100&borderColorContent=e0cfc2&fcContent=1e1b1d&iconColorContent=c47a23&bgColorDefault=ede4d4&bgTextureDefault=02_glass.png&bgImgOpacityDefault=70&borderColorDefault=cdc3b7&fcDefault=3f3731&iconColorDefault=f08000&bgColorHover=f5f0e5&bgTextureHover=02_glass.png&bgImgOpacityHover=100&borderColorHover=f5ad66&fcHover=a46313&iconColorHover=f08000&bgColorActive=f4f0ec&bgTextureActive=04_highlight_hard.png&bgImgOpacityActive=100&borderColorActive=e0cfc2&fcActive=b85700&iconColorActive=f35f07&bgColorHighlight=f5f5b5&bgTextureHighlight=04_highlight_hard.png&bgImgOpacityHighlight=75&borderColorHighlight=d9bb73&fcHighlight=060200&iconColorHighlight=cb672b&bgColorError=fee4bd&bgTextureError=04_highlight_hard.png&bgImgOpacityError=65&borderColorError=f8893f&fcError=592003&iconColorError=ff7519&bgColorOverlay=aaaaaa&bgTextureOverlay=01_flat.png&bgImgOpacityOverlay=75&opacityOverlay=30&bgColorShadow=aaaaaa&bgTextureShadow=01_flat.png&bgImgOpacityShadow=75&opacityShadow=30&thicknessShadow=8px&offsetTopShadow=-8px&offsetLeftShadow=-8px&cornerRadiusShadow=8px
*/
/* Component containers
----------------------------------*/
.ui-widget { font-family: Helvetica,Arial,sans-serif; font-size: 1.1em; }
.ui-widget .ui-widget { font-size: 1em; }
.ui-widget input, .ui-widget select, .ui-widget textarea, .ui-widget button { font-family: Helvetica,Arial,sans-serif; font-size: 1em; }
.ui-widget-content { border: 1px solid #e0cfc2; background: #f4f0ec url(images/ui-bg_inset-soft_100_f4f0ec_1x100.png) 50% bottom repeat-x; color: #1e1b1d; }
.ui-widget-content a { color: #1e1b1d; }
.ui-widget-header { border: 1px solid #d49768; background: #cb842e url(images/ui-bg_glass_25_cb842e_1x400.png) 50% 50% repeat-x; color: #ffffff; font-weight: bold; }
.ui-widget-header a { color: #ffffff; }
/* Interaction states
----------------------------------*/
.ui-state-default, .ui-widget-content .ui-state-default, .ui-widget-header .ui-state-default { border: 1px solid #cdc3b7; background: #ede4d4 url(images/ui-bg_glass_70_ede4d4_1x400.png) 50% 50% repeat-x; font-weight: normal; color: #3f3731; }
.ui-state-default a, .ui-state-default a:link, .ui-state-default a:visited { color: #3f3731; text-decoration: none; }
.ui-state-hover, .ui-widget-content .ui-state-hover, .ui-widget-header .ui-state-hover, .ui-state-focus, .ui-widget-content .ui-state-focus, .ui-widget-header .ui-state-focus { border: 1px solid #f5ad66; background: #f5f0e5 url(images/ui-bg_glass_100_f5f0e5_1x400.png) 50% 50% repeat-x; font-weight: normal; color: #a46313; }
.ui-state-hover a, .ui-state-hover a:hover, .ui-state-hover a:link, .ui-state-hover a:visited { color: #a46313; text-decoration: none; }
.ui-state-active, .ui-widget-content .ui-state-active, .ui-widget-header .ui-state-active { border: 1px solid #e0cfc2; background: #f4f0ec url(images/ui-bg_highlight-hard_100_f4f0ec_1x100.png) 50% 50% repeat-x; font-weight: normal; color: #b85700; }
.ui-state-active a, .ui-state-active a:link, .ui-state-active a:visited { color: #b85700; text-decoration: none; }
/* Interaction Cues
----------------------------------*/
.ui-state-highlight, .ui-widget-content .ui-state-highlight, .ui-widget-header .ui-state-highlight {border: 1px solid #d9bb73; background: #f5f5b5 url(images/ui-bg_highlight-hard_75_f5f5b5_1x100.png) 50% top repeat-x; color: #060200; }
.ui-state-highlight a, .ui-widget-content .ui-state-highlight a,.ui-widget-header .ui-state-highlight a { color: #060200; }
.ui-state-error, .ui-widget-content .ui-state-error, .ui-widget-header .ui-state-error {border: 1px solid #f8893f; background: #fee4bd url(images/ui-bg_highlight-hard_65_fee4bd_1x100.png) 50% top repeat-x; color: #592003; }
.ui-state-error a, .ui-widget-content .ui-state-error a, .ui-widget-header .ui-state-error a { color: #592003; }
.ui-state-error-text, .ui-widget-content .ui-state-error-text, .ui-widget-header .ui-state-error-text { color: #592003; }
.ui-priority-primary, .ui-widget-content .ui-priority-primary, .ui-widget-header .ui-priority-primary { font-weight: bold; }
.ui-priority-secondary, .ui-widget-content .ui-priority-secondary, .ui-widget-header .ui-priority-secondary { opacity: .7; filter:Alpha(Opacity=70); font-weight: normal; }
.ui-state-disabled, .ui-widget-content .ui-state-disabled, .ui-widget-header .ui-state-disabled { opacity: .35; filter:Alpha(Opacity=35); background-image: none; }
.ui-state-disabled .ui-icon { filter:Alpha(Opacity=35); } /* For IE8 - See #6059 */
/* Icons
----------------------------------*/
/* states and images */
.ui-icon { width: 16px; height: 16px; background-image: url(images/ui-icons_c47a23_256x240.png); }
.ui-widget-content .ui-icon {background-image: url(images/ui-icons_c47a23_256x240.png); }
.ui-widget-header .ui-icon {background-image: url(images/ui-icons_ffffff_256x240.png); }
.ui-state-default .ui-icon { background-image: url(images/ui-icons_f08000_256x240.png); }
.ui-state-hover .ui-icon, .ui-state-focus .ui-icon {background-image: url(images/ui-icons_f08000_256x240.png); }
.ui-state-active .ui-icon {background-image: url(images/ui-icons_f35f07_256x240.png); }
.ui-state-highlight .ui-icon {background-image: url(images/ui-icons_cb672b_256x240.png); }
.ui-state-error .ui-icon, .ui-state-error-text .ui-icon {background-image: url(images/ui-icons_ff7519_256x240.png); }
/* positioning */
.ui-icon-carat-1-n { background-position: 0 0; }
.ui-icon-carat-1-ne { background-position: -16px 0; }
.ui-icon-carat-1-e { background-position: -32px 0; }
.ui-icon-carat-1-se { background-position: -48px 0; }
.ui-icon-carat-1-s { background-position: -64px 0; }
.ui-icon-carat-1-sw { background-position: -80px 0; }
.ui-icon-carat-1-w { background-position: -96px 0; }
.ui-icon-carat-1-nw { background-position: -112px 0; }
.ui-icon-carat-2-n-s { background-position: -128px 0; }
.ui-icon-carat-2-e-w { background-position: -144px 0; }
.ui-icon-triangle-1-n { background-position: 0 -16px; }
.ui-icon-triangle-1-ne { background-position: -16px -16px; }
.ui-icon-triangle-1-e { background-position: -32px -16px; }
.ui-icon-triangle-1-se { background-position: -48px -16px; }
.ui-icon-triangle-1-s { background-position: -64px -16px; }
.ui-icon-triangle-1-sw { background-position: -80px -16px; }
.ui-icon-triangle-1-w { background-position: -96px -16px; }
.ui-icon-triangle-1-nw { background-position: -112px -16px; }
.ui-icon-triangle-2-n-s { background-position: -128px -16px; }
.ui-icon-triangle-2-e-w { background-position: -144px -16px; }
.ui-icon-arrow-1-n { background-position: 0 -32px; }
.ui-icon-arrow-1-ne { background-position: -16px -32px; }
.ui-icon-arrow-1-e { background-position: -32px -32px; }
.ui-icon-arrow-1-se { background-position: -48px -32px; }
.ui-icon-arrow-1-s { background-position: -64px -32px; }
.ui-icon-arrow-1-sw { background-position: -80px -32px; }
.ui-icon-arrow-1-w { background-position: -96px -32px; }
.ui-icon-arrow-1-nw { background-position: -112px -32px; }
.ui-icon-arrow-2-n-s { background-position: -128px -32px; }
.ui-icon-arrow-2-ne-sw { background-position: -144px -32px; }
.ui-icon-arrow-2-e-w { background-position: -160px -32px; }
.ui-icon-arrow-2-se-nw { background-position: -176px -32px; }
.ui-icon-arrowstop-1-n { background-position: -192px -32px; }
.ui-icon-arrowstop-1-e { background-position: -208px -32px; }
.ui-icon-arrowstop-1-s { background-position: -224px -32px; }
.ui-icon-arrowstop-1-w { background-position: -240px -32px; }
.ui-icon-arrowthick-1-n { background-position: 0 -48px; }
.ui-icon-arrowthick-1-ne { background-position: -16px -48px; }
.ui-icon-arrowthick-1-e { background-position: -32px -48px; }
.ui-icon-arrowthick-1-se { background-position: -48px -48px; }
.ui-icon-arrowthick-1-s { background-position: -64px -48px; }
.ui-icon-arrowthick-1-sw { background-position: -80px -48px; }
.ui-icon-arrowthick-1-w { background-position: -96px -48px; }
.ui-icon-arrowthick-1-nw { background-position: -112px -48px; }
.ui-icon-arrowthick-2-n-s { background-position: -128px -48px; }
.ui-icon-arrowthick-2-ne-sw { background-position: -144px -48px; }
.ui-icon-arrowthick-2-e-w { background-position: -160px -48px; }
.ui-icon-arrowthick-2-se-nw { background-position: -176px -48px; }
.ui-icon-arrowthickstop-1-n { background-position: -192px -48px; }
.ui-icon-arrowthickstop-1-e { background-position: -208px -48px; }
.ui-icon-arrowthickstop-1-s { background-position: -224px -48px; }
.ui-icon-arrowthickstop-1-w { background-position: -240px -48px; }
.ui-icon-arrowreturnthick-1-w { background-position: 0 -64px; }
.ui-icon-arrowreturnthick-1-n { background-position: -16px -64px; }
.ui-icon-arrowreturnthick-1-e { background-position: -32px -64px; }
.ui-icon-arrowreturnthick-1-s { background-position: -48px -64px; }
.ui-icon-arrowreturn-1-w { background-position: -64px -64px; }
.ui-icon-arrowreturn-1-n { background-position: -80px -64px; }
.ui-icon-arrowreturn-1-e { background-position: -96px -64px; }
.ui-icon-arrowreturn-1-s { background-position: -112px -64px; }
.ui-icon-arrowrefresh-1-w { background-position: -128px -64px; }
.ui-icon-arrowrefresh-1-n { background-position: -144px -64px; }
.ui-icon-arrowrefresh-1-e { background-position: -160px -64px; }
.ui-icon-arrowrefresh-1-s { background-position: -176px -64px; }
.ui-icon-arrow-4 { background-position: 0 -80px; }
.ui-icon-arrow-4-diag { background-position: -16px -80px; }
.ui-icon-extlink { background-position: -32px -80px; }
.ui-icon-newwin { background-position: -48px -80px; }
.ui-icon-refresh { background-position: -64px -80px; }
.ui-icon-shuffle { background-position: -80px -80px; }
.ui-icon-transfer-e-w { background-position: -96px -80px; }
.ui-icon-transferthick-e-w { background-position: -112px -80px; }
.ui-icon-folder-collapsed { background-position: 0 -96px; }
.ui-icon-folder-open { background-position: -16px -96px; }
.ui-icon-document { background-position: -32px -96px; }
.ui-icon-document-b { background-position: -48px -96px; }
.ui-icon-note { background-position: -64px -96px; }
.ui-icon-mail-closed { background-position: -80px -96px; }
.ui-icon-mail-open { background-position: -96px -96px; }
.ui-icon-suitcase { background-position: -112px -96px; }
.ui-icon-comment { background-position: -128px -96px; }
.ui-icon-person { background-position: -144px -96px; }
.ui-icon-print { background-position: -160px -96px; }
.ui-icon-trash { background-position: -176px -96px; }
.ui-icon-locked { background-position: -192px -96px; }
.ui-icon-unlocked { background-position: -208px -96px; }
.ui-icon-bookmark { background-position: -224px -96px; }
.ui-icon-tag { background-position: -240px -96px; }
.ui-icon-home { background-position: 0 -112px; }
.ui-icon-flag { background-position: -16px -112px; }
.ui-icon-calendar { background-position: -32px -112px; }
.ui-icon-cart { background-position: -48px -112px; }
.ui-icon-pencil { background-position: -64px -112px; }
.ui-icon-clock { background-position: -80px -112px; }
.ui-icon-disk { background-position: -96px -112px; }
.ui-icon-calculator { background-position: -112px -112px; }
.ui-icon-zoomin { background-position: -128px -112px; }
.ui-icon-zoomout { background-position: -144px -112px; }
.ui-icon-search { background-position: -160px -112px; }
.ui-icon-wrench { background-position: -176px -112px; }
.ui-icon-gear { background-position: -192px -112px; }
.ui-icon-heart { background-position: -208px -112px; }
.ui-icon-star { background-position: -224px -112px; }
.ui-icon-link { background-position: -240px -112px; }
.ui-icon-cancel { background-position: 0 -128px; }
.ui-icon-plus { background-position: -16px -128px; }
.ui-icon-plusthick { background-position: -32px -128px; }
.ui-icon-minus { background-position: -48px -128px; }
.ui-icon-minusthick { background-position: -64px -128px; }
.ui-icon-close { background-position: -80px -128px; }
.ui-icon-closethick { background-position: -96px -128px; }
.ui-icon-key { background-position: -112px -128px; }
.ui-icon-lightbulb { background-position: -128px -128px; }
.ui-icon-scissors { background-position: -144px -128px; }
.ui-icon-clipboard { background-position: -160px -128px; }
.ui-icon-copy { background-position: -176px -128px; }
.ui-icon-contact { background-position: -192px -128px; }
.ui-icon-image { background-position: -208px -128px; }
.ui-icon-video { background-position: -224px -128px; }
.ui-icon-script { background-position: -240px -128px; }
.ui-icon-alert { background-position: 0 -144px; }
.ui-icon-info { background-position: -16px -144px; }
.ui-icon-notice { background-position: -32px -144px; }
.ui-icon-help { background-position: -48px -144px; }
.ui-icon-check { background-position: -64px -144px; }
.ui-icon-bullet { background-position: -80px -144px; }
.ui-icon-radio-on { background-position: -96px -144px; }
.ui-icon-radio-off { background-position: -112px -144px; }
.ui-icon-pin-w { background-position: -128px -144px; }
.ui-icon-pin-s { background-position: -144px -144px; }
.ui-icon-play { background-position: 0 -160px; }
.ui-icon-pause { background-position: -16px -160px; }
.ui-icon-seek-next { background-position: -32px -160px; }
.ui-icon-seek-prev { background-position: -48px -160px; }
.ui-icon-seek-end { background-position: -64px -160px; }
.ui-icon-seek-start { background-position: -80px -160px; }
/* ui-icon-seek-first is deprecated, use ui-icon-seek-start instead */
.ui-icon-seek-first { background-position: -80px -160px; }
.ui-icon-stop { background-position: -96px -160px; }
.ui-icon-eject { background-position: -112px -160px; }
.ui-icon-volume-off { background-position: -128px -160px; }
.ui-icon-volume-on { background-position: -144px -160px; }
.ui-icon-power { background-position: 0 -176px; }
.ui-icon-signal-diag { background-position: -16px -176px; }
.ui-icon-signal { background-position: -32px -176px; }
.ui-icon-battery-0 { background-position: -48px -176px; }
.ui-icon-battery-1 { background-position: -64px -176px; }
.ui-icon-battery-2 { background-position: -80px -176px; }
.ui-icon-battery-3 { background-position: -96px -176px; }
.ui-icon-circle-plus { background-position: 0 -192px; }
.ui-icon-circle-minus { background-position: -16px -192px; }
.ui-icon-circle-close { background-position: -32px -192px; }
.ui-icon-circle-triangle-e { background-position: -48px -192px; }
.ui-icon-circle-triangle-s { background-position: -64px -192px; }
.ui-icon-circle-triangle-w { background-position: -80px -192px; }
.ui-icon-circle-triangle-n { background-position: -96px -192px; }
.ui-icon-circle-arrow-e { background-position: -112px -192px; }
.ui-icon-circle-arrow-s { background-position: -128px -192px; }
.ui-icon-circle-arrow-w { background-position: -144px -192px; }
.ui-icon-circle-arrow-n { background-position: -160px -192px; }
.ui-icon-circle-zoomin { background-position: -176px -192px; }
.ui-icon-circle-zoomout { background-position: -192px -192px; }
.ui-icon-circle-check { background-position: -208px -192px; }
.ui-icon-circlesmall-plus { background-position: 0 -208px; }
.ui-icon-circlesmall-minus { background-position: -16px -208px; }
.ui-icon-circlesmall-close { background-position: -32px -208px; }
.ui-icon-squaresmall-plus { background-position: -48px -208px; }
.ui-icon-squaresmall-minus { background-position: -64px -208px; }
.ui-icon-squaresmall-close { background-position: -80px -208px; }
.ui-icon-grip-dotted-vertical { background-position: 0 -224px; }
.ui-icon-grip-dotted-horizontal { background-position: -16px -224px; }
.ui-icon-grip-solid-vertical { background-position: -32px -224px; }
.ui-icon-grip-solid-horizontal { background-position: -48px -224px; }
.ui-icon-gripsmall-diagonal-se { background-position: -64px -224px; }
.ui-icon-grip-diagonal-se { background-position: -80px -224px; }
/* Misc visuals
----------------------------------*/
/* Corner radius */
.ui-corner-all, .ui-corner-top, .ui-corner-left, .ui-corner-tl { -moz-border-radius-topleft: 6px; -webkit-border-top-left-radius: 6px; -khtml-border-top-left-radius: 6px; border-top-left-radius: 6px; }
.ui-corner-all, .ui-corner-top, .ui-corner-right, .ui-corner-tr { -moz-border-radius-topright: 6px; -webkit-border-top-right-radius: 6px; -khtml-border-top-right-radius: 6px; border-top-right-radius: 6px; }
.ui-corner-all, .ui-corner-bottom, .ui-corner-left, .ui-corner-bl { -moz-border-radius-bottomleft: 6px; -webkit-border-bottom-left-radius: 6px; -khtml-border-bottom-left-radius: 6px; border-bottom-left-radius: 6px; }
.ui-corner-all, .ui-corner-bottom, .ui-corner-right, .ui-corner-br { -moz-border-radius-bottomright: 6px; -webkit-border-bottom-right-radius: 6px; -khtml-border-bottom-right-radius: 6px; border-bottom-right-radius: 6px; }
/* Overlays */
.ui-widget-overlay { background: #aaaaaa url(images/ui-bg_flat_75_aaaaaa_40x100.png) 50% 50% repeat-x; opacity: .3;filter:Alpha(Opacity=30); }
.ui-widget-shadow { margin: -8px 0 0 -8px; padding: 8px; background: #aaaaaa url(images/ui-bg_flat_75_aaaaaa_40x100.png) 50% 50% repeat-x; opacity: .3;filter:Alpha(Opacity=30); -moz-border-radius: 8px; -khtml-border-radius: 8px; -webkit-border-radius: 8px; border-radius: 8px; } | anjalymehla/airmozilla | airmozilla/popcorn/static/popcorn/PopcornEditor/static/bower/jquery-ui/themes/humanity/jquery.ui.theme.css | CSS | bsd-3-clause | 17,643 |
#!/usr/bin/perl -w
use warnings;
use strict;
my @audiotypes = qw(
U8
S8
U16LSB
S16LSB
U16MSB
S16MSB
S32LSB
S32MSB
F32LSB
F32MSB
);
my @channels = ( 1, 2, 4, 6, 8 );
my %funcs;
my $custom_converters = 0;
sub getTypeConvertHashId {
my ($from, $to) = @_;
return "TYPECONVERTER $from/$to";
}
sub getResamplerHashId {
my ($from, $channels, $upsample, $multiple) = @_;
return "RESAMPLER $from/$channels/$upsample/$multiple";
}
sub outputHeader {
print <<EOF;
/* DO NOT EDIT! This file is generated by sdlgenaudiocvt.pl */
/*
Simple DirectMedia Layer
Copyright (C) 1997-2014 Sam Lantinga <slouken\@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#include "../SDL_internal.h"
#include "SDL_audio.h"
#include "SDL_audio_c.h"
#ifndef DEBUG_CONVERT
#define DEBUG_CONVERT 0
#endif
/* If you can guarantee your data and need space, you can eliminate code... */
/* Just build the arbitrary resamplers if you're saving code space. */
#ifndef LESS_RESAMPLERS
#define LESS_RESAMPLERS 0
#endif
/* Don't build any resamplers if you're REALLY saving code space. */
#ifndef NO_RESAMPLERS
#define NO_RESAMPLERS 0
#endif
/* Don't build any type converters if you're saving code space. */
#ifndef NO_CONVERTERS
#define NO_CONVERTERS 0
#endif
/* *INDENT-OFF* */
EOF
my @vals = ( 127, 32767, 2147483647 );
foreach (@vals) {
my $val = $_;
my $fval = 1.0 / $val;
print("#define DIVBY${val} ${fval}f\n");
}
print("\n");
}
sub outputFooter {
print <<EOF;
/* $custom_converters converters generated. */
/* *INDENT-ON* */
/* vi: set ts=4 sw=4 expandtab: */
EOF
}
sub splittype {
my $t = shift;
my ($signed, $size, $endian) = $t =~ /([USF])(\d+)([LM]SB|)/;
my $float = ($signed eq 'F') ? 1 : 0;
$signed = (($float) or ($signed eq 'S')) ? 1 : 0;
$endian = 'NONE' if ($endian eq '');
my $ctype = '';
if ($float) {
$ctype = (($size == 32) ? 'float' : 'double');
} else {
$ctype = (($signed) ? 'S' : 'U') . "int${size}";
}
return ($signed, $float, $size, $endian, $ctype);
}
sub getSwapFunc {
my ($size, $signed, $float, $endian, $val) = @_;
my $BEorLE = (($endian eq 'MSB') ? 'BE' : 'LE');
my $code = '';
if ($float) {
$code = "SDL_SwapFloat${BEorLE}($val)";
} else {
if ($size > 8) {
$code = "SDL_Swap${BEorLE}${size}($val)";
} else {
$code = $val;
}
if (($signed) and (!$float)) {
$code = "((Sint${size}) $code)";
}
}
return "${code}";
}
sub maxIntVal {
my $size = shift;
if ($size == 8) {
return 0x7F;
} elsif ($size == 16) {
return 0x7FFF;
} elsif ($size == 32) {
return 0x7FFFFFFF;
}
die("bug in script.\n");
}
sub getFloatToIntMult {
my $size = shift;
my $val = maxIntVal($size) . '.0';
$val .= 'f' if ($size < 32);
return $val;
}
sub getIntToFloatDivBy {
my $size = shift;
return 'DIVBY' . maxIntVal($size);
}
sub getSignFlipVal {
my $size = shift;
if ($size == 8) {
return '0x80';
} elsif ($size == 16) {
return '0x8000';
} elsif ($size == 32) {
return '0x80000000';
}
die("bug in script.\n");
}
sub buildCvtFunc {
my ($from, $to) = @_;
my ($fsigned, $ffloat, $fsize, $fendian, $fctype) = splittype($from);
my ($tsigned, $tfloat, $tsize, $tendian, $tctype) = splittype($to);
my $diffs = 0;
$diffs++ if ($fsize != $tsize);
$diffs++ if ($fsigned != $tsigned);
$diffs++ if ($ffloat != $tfloat);
$diffs++ if ($fendian ne $tendian);
return if ($diffs == 0);
my $hashid = getTypeConvertHashId($from, $to);
if (1) { # !!! FIXME: if ($diffs > 1) {
my $sym = "SDL_Convert_${from}_to_${to}";
$funcs{$hashid} = $sym;
$custom_converters++;
# Always unsigned for ints, for possible byteswaps.
my $srctype = (($ffloat) ? 'float' : "Uint${fsize}");
print <<EOF;
static void SDLCALL
${sym}(SDL_AudioCVT * cvt, SDL_AudioFormat format)
{
int i;
const $srctype *src;
$tctype *dst;
#if DEBUG_CONVERT
fprintf(stderr, "Converting AUDIO_${from} to AUDIO_${to}.\\n");
#endif
EOF
if ($fsize < $tsize) {
my $mult = $tsize / $fsize;
print <<EOF;
src = ((const $srctype *) (cvt->buf + cvt->len_cvt)) - 1;
dst = (($tctype *) (cvt->buf + cvt->len_cvt * $mult)) - 1;
for (i = cvt->len_cvt / sizeof ($srctype); i; --i, --src, --dst) {
EOF
} else {
print <<EOF;
src = (const $srctype *) cvt->buf;
dst = ($tctype *) cvt->buf;
for (i = cvt->len_cvt / sizeof ($srctype); i; --i, ++src, ++dst) {
EOF
}
# Have to convert to/from float/int.
# !!! FIXME: cast through double for int32<->float?
my $code = getSwapFunc($fsize, $fsigned, $ffloat, $fendian, '*src');
if ($ffloat != $tfloat) {
if ($ffloat) {
my $mult = getFloatToIntMult($tsize);
if (!$tsigned) { # bump from -1.0f/1.0f to 0.0f/2.0f
$code = "($code + 1.0f)";
}
$code = "(($tctype) ($code * $mult))";
} else {
# $divby will be the reciprocal, to avoid pipeline stalls
# from floating point division...so multiply it.
my $divby = getIntToFloatDivBy($fsize);
$code = "(((float) $code) * $divby)";
if (!$fsigned) { # bump from 0.0f/2.0f to -1.0f/1.0f.
$code = "($code - 1.0f)";
}
}
} else {
# All integer conversions here.
if ($fsigned != $tsigned) {
my $signflipval = getSignFlipVal($fsize);
$code = "(($code) ^ $signflipval)";
}
my $shiftval = abs($fsize - $tsize);
if ($fsize < $tsize) {
$code = "((($tctype) $code) << $shiftval)";
} elsif ($fsize > $tsize) {
$code = "(($tctype) ($code >> $shiftval))";
}
}
my $swap = getSwapFunc($tsize, $tsigned, $tfloat, $tendian, 'val');
print <<EOF;
const $tctype val = $code;
*dst = ${swap};
}
EOF
if ($fsize > $tsize) {
my $divby = $fsize / $tsize;
print(" cvt->len_cvt /= $divby;\n");
} elsif ($fsize < $tsize) {
my $mult = $tsize / $fsize;
print(" cvt->len_cvt *= $mult;\n");
}
print <<EOF;
if (cvt->filters[++cvt->filter_index]) {
cvt->filters[cvt->filter_index] (cvt, AUDIO_$to);
}
}
EOF
} else {
if ($fsigned != $tsigned) {
$funcs{$hashid} = 'SDL_ConvertSigned';
} elsif ($ffloat != $tfloat) {
$funcs{$hashid} = 'SDL_ConvertFloat';
} elsif ($fsize != $tsize) {
$funcs{$hashid} = 'SDL_ConvertSize';
} elsif ($fendian ne $tendian) {
$funcs{$hashid} = 'SDL_ConvertEndian';
} else {
die("error in script.\n");
}
}
}
sub buildTypeConverters {
print "#if !NO_CONVERTERS\n\n";
foreach (@audiotypes) {
my $from = $_;
foreach (@audiotypes) {
my $to = $_;
buildCvtFunc($from, $to);
}
}
print "#endif /* !NO_CONVERTERS */\n\n\n";
print "const SDL_AudioTypeFilters sdl_audio_type_filters[] =\n{\n";
print "#if !NO_CONVERTERS\n";
foreach (@audiotypes) {
my $from = $_;
foreach (@audiotypes) {
my $to = $_;
if ($from ne $to) {
my $hashid = getTypeConvertHashId($from, $to);
my $sym = $funcs{$hashid};
print(" { AUDIO_$from, AUDIO_$to, $sym },\n");
}
}
}
print "#endif /* !NO_CONVERTERS */\n";
print(" { 0, 0, NULL }\n");
print "};\n\n\n";
}
sub getBiggerCtype {
my ($isfloat, $size) = @_;
if ($isfloat) {
if ($size == 32) {
return 'double';
}
die("bug in script.\n");
}
if ($size == 8) {
return 'Sint16';
} elsif ($size == 16) {
return 'Sint32'
} elsif ($size == 32) {
return 'Sint64'
}
die("bug in script.\n");
}
# These handle arbitrary resamples...44100Hz to 48000Hz, for example.
# Man, this code is skanky.
sub buildArbitraryResampleFunc {
# !!! FIXME: we do a lot of unnecessary and ugly casting in here, due to getSwapFunc().
my ($from, $channels, $upsample) = @_;
my ($fsigned, $ffloat, $fsize, $fendian, $fctype) = splittype($from);
my $bigger = getBiggerCtype($ffloat, $fsize);
my $interp = ($ffloat) ? '* 0.5' : '>> 1';
my $resample = ($upsample) ? 'Upsample' : 'Downsample';
my $hashid = getResamplerHashId($from, $channels, $upsample, 0);
my $sym = "SDL_${resample}_${from}_${channels}c";
$funcs{$hashid} = $sym;
$custom_converters++;
my $fudge = $fsize * $channels * 2; # !!! FIXME
my $eps_adjust = ($upsample) ? 'dstsize' : 'srcsize';
my $incr = '';
my $incr2 = '';
# !!! FIXME: DEBUG_CONVERT should report frequencies.
print <<EOF;
static void SDLCALL
${sym}(SDL_AudioCVT * cvt, SDL_AudioFormat format)
{
#if DEBUG_CONVERT
fprintf(stderr, "$resample arbitrary (x%f) AUDIO_${from}, ${channels} channels.\\n", cvt->rate_incr);
#endif
const int srcsize = cvt->len_cvt - $fudge;
const int dstsize = (int) (((double)cvt->len_cvt) * cvt->rate_incr);
register int eps = 0;
EOF
my $endcomparison = '!=';
# Upsampling (growing the buffer) needs to work backwards, since we
# overwrite the buffer as we go.
if ($upsample) {
$endcomparison = '>='; # dst > target
print <<EOF;
$fctype *dst = (($fctype *) (cvt->buf + dstsize)) - $channels;
const $fctype *src = (($fctype *) (cvt->buf + cvt->len_cvt)) - $channels;
const $fctype *target = ((const $fctype *) cvt->buf);
EOF
} else {
$endcomparison = '<'; # dst < target
print <<EOF;
$fctype *dst = ($fctype *) cvt->buf;
const $fctype *src = ($fctype *) cvt->buf;
const $fctype *target = (const $fctype *) (cvt->buf + dstsize);
EOF
}
for (my $i = 0; $i < $channels; $i++) {
my $idx = ($upsample) ? (($channels - $i) - 1) : $i;
my $val = getSwapFunc($fsize, $fsigned, $ffloat, $fendian, "src[$idx]");
print <<EOF;
$fctype sample${idx} = $val;
EOF
}
for (my $i = 0; $i < $channels; $i++) {
my $idx = ($upsample) ? (($channels - $i) - 1) : $i;
print <<EOF;
$fctype last_sample${idx} = sample${idx};
EOF
}
print <<EOF;
while (dst $endcomparison target) {
EOF
if ($upsample) {
for (my $i = 0; $i < $channels; $i++) {
# !!! FIXME: don't do this swap every write, just when the samples change.
my $idx = (($channels - $i) - 1);
my $val = getSwapFunc($fsize, $fsigned, $ffloat, $fendian, "sample${idx}");
print <<EOF;
dst[$idx] = $val;
EOF
}
$incr = ($channels == 1) ? 'dst--' : "dst -= $channels";
$incr2 = ($channels == 1) ? 'src--' : "src -= $channels";
print <<EOF;
$incr;
eps += srcsize;
if ((eps << 1) >= dstsize) {
$incr2;
EOF
} else { # downsample.
$incr = ($channels == 1) ? 'src++' : "src += $channels";
print <<EOF;
$incr;
eps += dstsize;
if ((eps << 1) >= srcsize) {
EOF
for (my $i = 0; $i < $channels; $i++) {
my $val = getSwapFunc($fsize, $fsigned, $ffloat, $fendian, "sample${i}");
print <<EOF;
dst[$i] = $val;
EOF
}
$incr = ($channels == 1) ? 'dst++' : "dst += $channels";
print <<EOF;
$incr;
EOF
}
for (my $i = 0; $i < $channels; $i++) {
my $idx = ($upsample) ? (($channels - $i) - 1) : $i;
my $swapped = getSwapFunc($fsize, $fsigned, $ffloat, $fendian, "src[$idx]");
print <<EOF;
sample${idx} = ($fctype) (((($bigger) $swapped) + (($bigger) last_sample${idx})) $interp);
EOF
}
for (my $i = 0; $i < $channels; $i++) {
my $idx = ($upsample) ? (($channels - $i) - 1) : $i;
print <<EOF;
last_sample${idx} = sample${idx};
EOF
}
print <<EOF;
eps -= $eps_adjust;
}
}
EOF
print <<EOF;
cvt->len_cvt = dstsize;
if (cvt->filters[++cvt->filter_index]) {
cvt->filters[cvt->filter_index] (cvt, format);
}
}
EOF
}
# These handle clean resamples...doubling and quadrupling the sample rate, etc.
sub buildMultipleResampleFunc {
# !!! FIXME: we do a lot of unnecessary and ugly casting in here, due to getSwapFunc().
my ($from, $channels, $upsample, $multiple) = @_;
my ($fsigned, $ffloat, $fsize, $fendian, $fctype) = splittype($from);
my $bigger = getBiggerCtype($ffloat, $fsize);
my $interp = ($ffloat) ? '* 0.5' : '>> 1';
my $interp2 = ($ffloat) ? '* 0.25' : '>> 2';
my $mult3 = ($ffloat) ? '3.0' : '3';
my $lencvtop = ($upsample) ? '*' : '/';
my $resample = ($upsample) ? 'Upsample' : 'Downsample';
my $hashid = getResamplerHashId($from, $channels, $upsample, $multiple);
my $sym = "SDL_${resample}_${from}_${channels}c_x${multiple}";
$funcs{$hashid} = $sym;
$custom_converters++;
# !!! FIXME: DEBUG_CONVERT should report frequencies.
print <<EOF;
static void SDLCALL
${sym}(SDL_AudioCVT * cvt, SDL_AudioFormat format)
{
#if DEBUG_CONVERT
fprintf(stderr, "$resample (x${multiple}) AUDIO_${from}, ${channels} channels.\\n");
#endif
const int dstsize = cvt->len_cvt $lencvtop $multiple;
EOF
my $endcomparison = '!=';
# Upsampling (growing the buffer) needs to work backwards, since we
# overwrite the buffer as we go.
if ($upsample) {
$endcomparison = '>='; # dst > target
print <<EOF;
$fctype *dst = (($fctype *) (cvt->buf + dstsize)) - $channels * $multiple;
const $fctype *src = (($fctype *) (cvt->buf + cvt->len_cvt)) - $channels;
const $fctype *target = ((const $fctype *) cvt->buf);
EOF
} else {
$endcomparison = '<'; # dst < target
print <<EOF;
$fctype *dst = ($fctype *) cvt->buf;
const $fctype *src = ($fctype *) cvt->buf;
const $fctype *target = (const $fctype *) (cvt->buf + dstsize);
EOF
}
for (my $i = 0; $i < $channels; $i++) {
my $idx = ($upsample) ? (($channels - $i) - 1) : $i;
my $val = getSwapFunc($fsize, $fsigned, $ffloat, $fendian, "src[$idx]");
print <<EOF;
$bigger last_sample${idx} = ($bigger) $val;
EOF
}
print <<EOF;
while (dst $endcomparison target) {
EOF
for (my $i = 0; $i < $channels; $i++) {
my $idx = ($upsample) ? (($channels - $i) - 1) : $i;
my $val = getSwapFunc($fsize, $fsigned, $ffloat, $fendian, "src[$idx]");
print <<EOF;
const $bigger sample${idx} = ($bigger) $val;
EOF
}
my $incr = '';
if ($upsample) {
$incr = ($channels == 1) ? 'src--' : "src -= $channels";
} else {
my $amount = $channels * $multiple;
$incr = "src += $amount"; # can't ever be 1, so no "++" version.
}
print <<EOF;
$incr;
EOF
# !!! FIXME: This really begs for some Altivec or SSE, etc.
if ($upsample) {
if ($multiple == 2) {
for (my $i = $channels-1; $i >= 0; $i--) {
my $dsti = $i + $channels;
print <<EOF;
dst[$dsti] = ($fctype) ((sample${i} + last_sample${i}) $interp);
EOF
}
for (my $i = $channels-1; $i >= 0; $i--) {
my $dsti = $i;
print <<EOF;
dst[$dsti] = ($fctype) sample${i};
EOF
}
} elsif ($multiple == 4) {
for (my $i = $channels-1; $i >= 0; $i--) {
my $dsti = $i + ($channels * 3);
print <<EOF;
dst[$dsti] = ($fctype) ((sample${i} + ($mult3 * last_sample${i})) $interp2);
EOF
}
for (my $i = $channels-1; $i >= 0; $i--) {
my $dsti = $i + ($channels * 2);
print <<EOF;
dst[$dsti] = ($fctype) ((sample${i} + last_sample${i}) $interp);
EOF
}
for (my $i = $channels-1; $i >= 0; $i--) {
my $dsti = $i + ($channels * 1);
print <<EOF;
dst[$dsti] = ($fctype) ((($mult3 * sample${i}) + last_sample${i}) $interp2);
EOF
}
for (my $i = $channels-1; $i >= 0; $i--) {
my $dsti = $i + ($channels * 0);
print <<EOF;
dst[$dsti] = ($fctype) sample${i};
EOF
}
} else {
die('bug in program.'); # we only handle x2 and x4.
}
} else { # downsample.
if ($multiple == 2) {
for (my $i = 0; $i < $channels; $i++) {
print <<EOF;
dst[$i] = ($fctype) ((sample${i} + last_sample${i}) $interp);
EOF
}
} elsif ($multiple == 4) {
# !!! FIXME: interpolate all 4 samples?
for (my $i = 0; $i < $channels; $i++) {
print <<EOF;
dst[$i] = ($fctype) ((sample${i} + last_sample${i}) $interp);
EOF
}
} else {
die('bug in program.'); # we only handle x2 and x4.
}
}
for (my $i = 0; $i < $channels; $i++) {
my $idx = ($upsample) ? (($channels - $i) - 1) : $i;
print <<EOF;
last_sample${idx} = sample${idx};
EOF
}
if ($upsample) {
my $amount = $channels * $multiple;
$incr = "dst -= $amount"; # can't ever be 1, so no "--" version.
} else {
$incr = ($channels == 1) ? 'dst++' : "dst += $channels";
}
print <<EOF;
$incr;
}
cvt->len_cvt = dstsize;
if (cvt->filters[++cvt->filter_index]) {
cvt->filters[cvt->filter_index] (cvt, format);
}
}
EOF
}
sub buildResamplers {
print "#if !NO_RESAMPLERS\n\n";
foreach (@audiotypes) {
my $from = $_;
foreach (@channels) {
my $channel = $_;
buildArbitraryResampleFunc($from, $channel, 1);
buildArbitraryResampleFunc($from, $channel, 0);
}
}
print "\n#if !LESS_RESAMPLERS\n\n";
foreach (@audiotypes) {
my $from = $_;
foreach (@channels) {
my $channel = $_;
for (my $multiple = 2; $multiple <= 4; $multiple += 2) {
buildMultipleResampleFunc($from, $channel, 1, $multiple);
buildMultipleResampleFunc($from, $channel, 0, $multiple);
}
}
}
print "#endif /* !LESS_RESAMPLERS */\n";
print "#endif /* !NO_RESAMPLERS */\n\n\n";
print "const SDL_AudioRateFilters sdl_audio_rate_filters[] =\n{\n";
print "#if !NO_RESAMPLERS\n";
foreach (@audiotypes) {
my $from = $_;
foreach (@channels) {
my $channel = $_;
for (my $upsample = 0; $upsample <= 1; $upsample++) {
my $hashid = getResamplerHashId($from, $channel, $upsample, 0);
my $sym = $funcs{$hashid};
print(" { AUDIO_$from, $channel, $upsample, 0, $sym },\n");
}
}
}
print "#if !LESS_RESAMPLERS\n";
foreach (@audiotypes) {
my $from = $_;
foreach (@channels) {
my $channel = $_;
for (my $multiple = 2; $multiple <= 4; $multiple += 2) {
for (my $upsample = 0; $upsample <= 1; $upsample++) {
my $hashid = getResamplerHashId($from, $channel, $upsample, $multiple);
my $sym = $funcs{$hashid};
print(" { AUDIO_$from, $channel, $upsample, $multiple, $sym },\n");
}
}
}
}
print "#endif /* !LESS_RESAMPLERS */\n";
print "#endif /* !NO_RESAMPLERS */\n";
print(" { 0, 0, 0, 0, NULL }\n");
print "};\n\n";
}
# mainline ...
outputHeader();
buildTypeConverters();
buildResamplers();
outputFooter();
exit 0;
# end of sdlgenaudiocvt.pl ...
| JeffProgrammer/D3D11Test | thirdparty/SDL2/src/audio/sdlgenaudiocvt.pl | Perl | bsd-3-clause | 21,094 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html>
<head>
<title>CSS 2.1 Test Suite: Floating Elements</title>
<style type="text/css">
p { color: navy; }
.control { padding: 1em; }
.control div { width: 10em; background: navy; color: yellow; }
.control div.right { margin-left: 5em; text-align: right; }
.test { width: 15em; margin: 1em; }
.test div { margin: 0; padding: 0; background: red; }
.test p { margin: 0; padding: 0; width: 10em; background: navy; color: yellow; }
.test p.left { float: left; text-align: left; }
.test p.right { float: right; text-align: right; }
</style>
<link rel="help" href="http://www.w3.org/TR/CSS21/visuren.html#floats" title="9.5 Floats">
<link rel="help" href="http://www.w3.org/TR/CSS21/text.html#alignment-prop" title="16.2 Alignment: the 'text-align' property">
</head>
<body>
<p>The two patterns below should be identical, with no red present.</p>
<div class="control">
<div class="left"> * </div>
<div class="right"> * </div>
</div>
<div class="test">
<div>
<p class="left"> * </p>
<p class="right"> * </p>
</div>
</div>
</body>
</html> | PeterWangIntel/blink-crosswalk | LayoutTests/css2.1/t0905-c414-flt-00-d.html | HTML | bsd-3-clause | 1,166 |
<?php
namespace GuzzleHttp\Psr7;
use Psr\Http\Message\MessageInterface;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\StreamInterface;
use Psr\Http\Message\UriInterface;
/**
* Returns the string representation of an HTTP message.
*
* @param MessageInterface $message Message to convert to a string.
*
* @return string
*/
function str(MessageInterface $message)
{
if ($message instanceof RequestInterface) {
$msg = trim($message->getMethod() . ' '
. $message->getRequestTarget())
. ' HTTP/' . $message->getProtocolVersion();
if (!$message->hasHeader('host')) {
$msg .= "\r\nHost: " . $message->getUri()->getHost();
}
} elseif ($message instanceof ResponseInterface) {
$msg = 'HTTP/' . $message->getProtocolVersion() . ' '
. $message->getStatusCode() . ' '
. $message->getReasonPhrase();
} else {
throw new \InvalidArgumentException('Unknown message type');
}
foreach ($message->getHeaders() as $name => $values) {
$msg .= "\r\n{$name}: " . implode(', ', $values);
}
return "{$msg}\r\n\r\n" . $message->getBody();
}
/**
* Returns a UriInterface for the given value.
*
* This function accepts a string or {@see Psr\Http\Message\UriInterface} and
* returns a UriInterface for the given value. If the value is already a
* `UriInterface`, it is returned as-is.
*
* @param string|UriInterface $uri
*
* @return UriInterface
* @throws \InvalidArgumentException
*/
function uri_for($uri)
{
if ($uri instanceof UriInterface) {
return $uri;
} elseif (is_string($uri)) {
return new Uri($uri);
}
throw new \InvalidArgumentException('URI must be a string or UriInterface');
}
/**
* Create a new stream based on the input type.
*
* Options is an associative array that can contain the following keys:
* - metadata: Array of custom metadata.
* - size: Size of the stream.
*
* @param resource|string|null|int|float|bool|StreamInterface|callable $resource Entity body data
* @param array $options Additional options
*
* @return Stream
* @throws \InvalidArgumentException if the $resource arg is not valid.
*/
function stream_for($resource = '', array $options = [])
{
if (is_scalar($resource)) {
$stream = fopen('php://temp', 'r+');
if ($resource !== '') {
fwrite($stream, $resource);
fseek($stream, 0);
}
return new Stream($stream, $options);
}
switch (gettype($resource)) {
case 'resource':
return new Stream($resource, $options);
case 'object':
if ($resource instanceof StreamInterface) {
return $resource;
} elseif ($resource instanceof \Iterator) {
return new PumpStream(function () use ($resource) {
if (!$resource->valid()) {
return false;
}
$result = $resource->current();
$resource->next();
return $result;
}, $options);
} elseif (method_exists($resource, '__toString')) {
return stream_for((string) $resource, $options);
}
break;
case 'NULL':
return new Stream(fopen('php://temp', 'r+'), $options);
}
if (is_callable($resource)) {
return new PumpStream($resource, $options);
}
throw new \InvalidArgumentException('Invalid resource type: ' . gettype($resource));
}
/**
* Parse an array of header values containing ";" separated data into an
* array of associative arrays representing the header key value pair
* data of the header. When a parameter does not contain a value, but just
* contains a key, this function will inject a key with a '' string value.
*
* @param string|array $header Header to parse into components.
*
* @return array Returns the parsed header values.
*/
function parse_header($header)
{
static $trimmed = "\"' \n\t\r";
$params = $matches = [];
foreach (normalize_header($header) as $val) {
$part = [];
foreach (preg_split('/;(?=([^"]*"[^"]*")*[^"]*$)/', $val) as $kvp) {
if (preg_match_all('/<[^>]+>|[^=]+/', $kvp, $matches)) {
$m = $matches[0];
if (isset($m[1])) {
$part[trim($m[0], $trimmed)] = trim($m[1], $trimmed);
} else {
$part[] = trim($m[0], $trimmed);
}
}
}
if ($part) {
$params[] = $part;
}
}
return $params;
}
/**
* Converts an array of header values that may contain comma separated
* headers into an array of headers with no comma separated values.
*
* @param string|array $header Header to normalize.
*
* @return array Returns the normalized header field values.
*/
function normalize_header($header)
{
if (!is_array($header)) {
return array_map('trim', explode(',', $header));
}
$result = [];
foreach ($header as $value) {
foreach ((array) $value as $v) {
if (strpos($v, ',') === false) {
$result[] = $v;
continue;
}
foreach (preg_split('/,(?=([^"]*"[^"]*")*[^"]*$)/', $v) as $vv) {
$result[] = trim($vv);
}
}
}
return $result;
}
/**
* Clone and modify a request with the given changes.
*
* The changes can be one of:
* - method: (string) Changes the HTTP method.
* - set_headers: (array) Sets the given headers.
* - remove_headers: (array) Remove the given headers.
* - body: (mixed) Sets the given body.
* - uri: (UriInterface) Set the URI.
* - query: (string) Set the query string value of the URI.
* - version: (string) Set the protocol version.
*
* @param RequestInterface $request Request to clone and modify.
* @param array $changes Changes to apply.
*
* @return RequestInterface
*/
function modify_request(RequestInterface $request, array $changes)
{
if (!$changes) {
return $request;
}
$headers = $request->getHeaders();
if (!isset($changes['uri'])) {
$uri = $request->getUri();
} else {
// Remove the host header if one is on the URI
if ($host = $changes['uri']->getHost()) {
$changes['set_headers']['Host'] = $host;
if ($port = $changes['uri']->getPort()) {
$standardPorts = ['http' => 80, 'https' => 443];
$scheme = $changes['uri']->getScheme();
if (isset($standardPorts[$scheme]) && $port != $standardPorts[$scheme]) {
$changes['set_headers']['Host'] .= ':'.$port;
}
}
}
$uri = $changes['uri'];
}
if (!empty($changes['remove_headers'])) {
$headers = _caseless_remove($changes['remove_headers'], $headers);
}
if (!empty($changes['set_headers'])) {
$headers = _caseless_remove(array_keys($changes['set_headers']), $headers);
$headers = $changes['set_headers'] + $headers;
}
if (isset($changes['query'])) {
$uri = $uri->withQuery($changes['query']);
}
if ($request instanceof ServerRequestInterface) {
return new ServerRequest(
isset($changes['method']) ? $changes['method'] : $request->getMethod(),
$uri,
$headers,
isset($changes['body']) ? $changes['body'] : $request->getBody(),
isset($changes['version'])
? $changes['version']
: $request->getProtocolVersion(),
$request->getServerParams()
);
}
return new Request(
isset($changes['method']) ? $changes['method'] : $request->getMethod(),
$uri,
$headers,
isset($changes['body']) ? $changes['body'] : $request->getBody(),
isset($changes['version'])
? $changes['version']
: $request->getProtocolVersion()
);
}
/**
* Attempts to rewind a message body and throws an exception on failure.
*
* The body of the message will only be rewound if a call to `tell()` returns a
* value other than `0`.
*
* @param MessageInterface $message Message to rewind
*
* @throws \RuntimeException
*/
function rewind_body(MessageInterface $message)
{
$body = $message->getBody();
if ($body->tell()) {
$body->rewind();
}
}
/**
* Safely opens a PHP stream resource using a filename.
*
* When fopen fails, PHP normally raises a warning. This function adds an
* error handler that checks for errors and throws an exception instead.
*
* @param string $filename File to open
* @param string $mode Mode used to open the file
*
* @return resource
* @throws \RuntimeException if the file cannot be opened
*/
function try_fopen($filename, $mode)
{
$ex = null;
set_error_handler(function () use ($filename, $mode, &$ex) {
$ex = new \RuntimeException(sprintf(
'Unable to open %s using mode %s: %s',
$filename,
$mode,
func_get_args()[1]
));
});
$handle = fopen($filename, $mode);
restore_error_handler();
if ($ex) {
/** @var $ex \RuntimeException */
throw $ex;
}
return $handle;
}
/**
* Copy the contents of a stream into a string until the given number of
* bytes have been read.
*
* @param StreamInterface $stream Stream to read
* @param int $maxLen Maximum number of bytes to read. Pass -1
* to read the entire stream.
* @return string
* @throws \RuntimeException on error.
*/
function copy_to_string(StreamInterface $stream, $maxLen = -1)
{
$buffer = '';
if ($maxLen === -1) {
while (!$stream->eof()) {
$buf = $stream->read(1048576);
// Using a loose equality here to match on '' and false.
if ($buf == null) {
break;
}
$buffer .= $buf;
}
return $buffer;
}
$len = 0;
while (!$stream->eof() && $len < $maxLen) {
$buf = $stream->read($maxLen - $len);
// Using a loose equality here to match on '' and false.
if ($buf == null) {
break;
}
$buffer .= $buf;
$len = strlen($buffer);
}
return $buffer;
}
/**
* Copy the contents of a stream into another stream until the given number
* of bytes have been read.
*
* @param StreamInterface $source Stream to read from
* @param StreamInterface $dest Stream to write to
* @param int $maxLen Maximum number of bytes to read. Pass -1
* to read the entire stream.
*
* @throws \RuntimeException on error.
*/
function copy_to_stream(
StreamInterface $source,
StreamInterface $dest,
$maxLen = -1
) {
if ($maxLen === -1) {
while (!$source->eof()) {
if (!$dest->write($source->read(1048576))) {
break;
}
}
return;
}
$bytes = 0;
while (!$source->eof()) {
$buf = $source->read($maxLen - $bytes);
if (!($len = strlen($buf))) {
break;
}
$bytes += $len;
$dest->write($buf);
if ($bytes == $maxLen) {
break;
}
}
}
/**
* Calculate a hash of a Stream
*
* @param StreamInterface $stream Stream to calculate the hash for
* @param string $algo Hash algorithm (e.g. md5, crc32, etc)
* @param bool $rawOutput Whether or not to use raw output
*
* @return string Returns the hash of the stream
* @throws \RuntimeException on error.
*/
function hash(
StreamInterface $stream,
$algo,
$rawOutput = false
) {
$pos = $stream->tell();
if ($pos > 0) {
$stream->rewind();
}
$ctx = hash_init($algo);
while (!$stream->eof()) {
hash_update($ctx, $stream->read(1048576));
}
$out = hash_final($ctx, (bool) $rawOutput);
$stream->seek($pos);
return $out;
}
/**
* Read a line from the stream up to the maximum allowed buffer length
*
* @param StreamInterface $stream Stream to read from
* @param int $maxLength Maximum buffer length
*
* @return string|bool
*/
function readline(StreamInterface $stream, $maxLength = null)
{
$buffer = '';
$size = 0;
while (!$stream->eof()) {
// Using a loose equality here to match on '' and false.
if (null == ($byte = $stream->read(1))) {
return $buffer;
}
$buffer .= $byte;
// Break when a new line is found or the max length - 1 is reached
if ($byte === "\n" || ++$size === $maxLength - 1) {
break;
}
}
return $buffer;
}
/**
* Parses a request message string into a request object.
*
* @param string $message Request message string.
*
* @return Request
*/
function parse_request($message)
{
$data = _parse_message($message);
$matches = [];
if (!preg_match('/^[\S]+\s+([a-zA-Z]+:\/\/|\/).*/', $data['start-line'], $matches)) {
throw new \InvalidArgumentException('Invalid request string');
}
$parts = explode(' ', $data['start-line'], 3);
$version = isset($parts[2]) ? explode('/', $parts[2])[1] : '1.1';
$request = new Request(
$parts[0],
$matches[1] === '/' ? _parse_request_uri($parts[1], $data['headers']) : $parts[1],
$data['headers'],
$data['body'],
$version
);
return $matches[1] === '/' ? $request : $request->withRequestTarget($parts[1]);
}
/**
* Parses a response message string into a response object.
*
* @param string $message Response message string.
*
* @return Response
*/
function parse_response($message)
{
$data = _parse_message($message);
if (!preg_match('/^HTTP\/.* [0-9]{3} .*/', $data['start-line'])) {
throw new \InvalidArgumentException('Invalid response string');
}
$parts = explode(' ', $data['start-line'], 3);
return new Response(
$parts[1],
$data['headers'],
$data['body'],
explode('/', $parts[0])[1],
isset($parts[2]) ? $parts[2] : null
);
}
/**
* Parse a query string into an associative array.
*
* If multiple values are found for the same key, the value of that key
* value pair will become an array. This function does not parse nested
* PHP style arrays into an associative array (e.g., foo[a]=1&foo[b]=2 will
* be parsed into ['foo[a]' => '1', 'foo[b]' => '2']).
*
* @param string $str Query string to parse
* @param bool|string $urlEncoding How the query string is encoded
*
* @return array
*/
function parse_query($str, $urlEncoding = true)
{
$result = [];
if ($str === '') {
return $result;
}
if ($urlEncoding === true) {
$decoder = function ($value) {
return rawurldecode(str_replace('+', ' ', $value));
};
} elseif ($urlEncoding == PHP_QUERY_RFC3986) {
$decoder = 'rawurldecode';
} elseif ($urlEncoding == PHP_QUERY_RFC1738) {
$decoder = 'urldecode';
} else {
$decoder = function ($str) { return $str; };
}
foreach (explode('&', $str) as $kvp) {
$parts = explode('=', $kvp, 2);
$key = $decoder($parts[0]);
$value = isset($parts[1]) ? $decoder($parts[1]) : null;
if (!isset($result[$key])) {
$result[$key] = $value;
} else {
if (!is_array($result[$key])) {
$result[$key] = [$result[$key]];
}
$result[$key][] = $value;
}
}
return $result;
}
/**
* Build a query string from an array of key value pairs.
*
* This function can use the return value of parse_query() to build a query
* string. This function does not modify the provided keys when an array is
* encountered (like http_build_query would).
*
* @param array $params Query string parameters.
* @param int|false $encoding Set to false to not encode, PHP_QUERY_RFC3986
* to encode using RFC3986, or PHP_QUERY_RFC1738
* to encode using RFC1738.
* @return string
*/
function build_query(array $params, $encoding = PHP_QUERY_RFC3986)
{
if (!$params) {
return '';
}
if ($encoding === false) {
$encoder = function ($str) { return $str; };
} elseif ($encoding === PHP_QUERY_RFC3986) {
$encoder = 'rawurlencode';
} elseif ($encoding === PHP_QUERY_RFC1738) {
$encoder = 'urlencode';
} else {
throw new \InvalidArgumentException('Invalid type');
}
$qs = '';
foreach ($params as $k => $v) {
$k = $encoder($k);
if (!is_array($v)) {
$qs .= $k;
if ($v !== null) {
$qs .= '=' . $encoder($v);
}
$qs .= '&';
} else {
foreach ($v as $vv) {
$qs .= $k;
if ($vv !== null) {
$qs .= '=' . $encoder($vv);
}
$qs .= '&';
}
}
}
return $qs ? (string) substr($qs, 0, -1) : '';
}
/**
* Determines the mimetype of a file by looking at its extension.
*
* @param $filename
*
* @return null|string
*/
function mimetype_from_filename($filename)
{
return mimetype_from_extension(pathinfo($filename, PATHINFO_EXTENSION));
}
/**
* Maps a file extensions to a mimetype.
*
* @param $extension string The file extension.
*
* @return string|null
* @link http://svn.apache.org/repos/asf/httpd/httpd/branches/1.3.x/conf/mime.types
*/
function mimetype_from_extension($extension)
{
static $mimetypes = [
'7z' => 'application/x-7z-compressed',
'aac' => 'audio/x-aac',
'ai' => 'application/postscript',
'aif' => 'audio/x-aiff',
'asc' => 'text/plain',
'asf' => 'video/x-ms-asf',
'atom' => 'application/atom+xml',
'avi' => 'video/x-msvideo',
'bmp' => 'image/bmp',
'bz2' => 'application/x-bzip2',
'cer' => 'application/pkix-cert',
'crl' => 'application/pkix-crl',
'crt' => 'application/x-x509-ca-cert',
'css' => 'text/css',
'csv' => 'text/csv',
'cu' => 'application/cu-seeme',
'deb' => 'application/x-debian-package',
'doc' => 'application/msword',
'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'dvi' => 'application/x-dvi',
'eot' => 'application/vnd.ms-fontobject',
'eps' => 'application/postscript',
'epub' => 'application/epub+zip',
'etx' => 'text/x-setext',
'flac' => 'audio/flac',
'flv' => 'video/x-flv',
'gif' => 'image/gif',
'gz' => 'application/gzip',
'htm' => 'text/html',
'html' => 'text/html',
'ico' => 'image/x-icon',
'ics' => 'text/calendar',
'ini' => 'text/plain',
'iso' => 'application/x-iso9660-image',
'jar' => 'application/java-archive',
'jpe' => 'image/jpeg',
'jpeg' => 'image/jpeg',
'jpg' => 'image/jpeg',
'js' => 'text/javascript',
'json' => 'application/json',
'latex' => 'application/x-latex',
'log' => 'text/plain',
'm4a' => 'audio/mp4',
'm4v' => 'video/mp4',
'mid' => 'audio/midi',
'midi' => 'audio/midi',
'mov' => 'video/quicktime',
'mp3' => 'audio/mpeg',
'mp4' => 'video/mp4',
'mp4a' => 'audio/mp4',
'mp4v' => 'video/mp4',
'mpe' => 'video/mpeg',
'mpeg' => 'video/mpeg',
'mpg' => 'video/mpeg',
'mpg4' => 'video/mp4',
'oga' => 'audio/ogg',
'ogg' => 'audio/ogg',
'ogv' => 'video/ogg',
'ogx' => 'application/ogg',
'pbm' => 'image/x-portable-bitmap',
'pdf' => 'application/pdf',
'pgm' => 'image/x-portable-graymap',
'png' => 'image/png',
'pnm' => 'image/x-portable-anymap',
'ppm' => 'image/x-portable-pixmap',
'ppt' => 'application/vnd.ms-powerpoint',
'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
'ps' => 'application/postscript',
'qt' => 'video/quicktime',
'rar' => 'application/x-rar-compressed',
'ras' => 'image/x-cmu-raster',
'rss' => 'application/rss+xml',
'rtf' => 'application/rtf',
'sgm' => 'text/sgml',
'sgml' => 'text/sgml',
'svg' => 'image/svg+xml',
'swf' => 'application/x-shockwave-flash',
'tar' => 'application/x-tar',
'tif' => 'image/tiff',
'tiff' => 'image/tiff',
'torrent' => 'application/x-bittorrent',
'ttf' => 'application/x-font-ttf',
'txt' => 'text/plain',
'wav' => 'audio/x-wav',
'webm' => 'video/webm',
'wma' => 'audio/x-ms-wma',
'wmv' => 'video/x-ms-wmv',
'woff' => 'application/x-font-woff',
'wsdl' => 'application/wsdl+xml',
'xbm' => 'image/x-xbitmap',
'xls' => 'application/vnd.ms-excel',
'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'xml' => 'application/xml',
'xpm' => 'image/x-xpixmap',
'xwd' => 'image/x-xwindowdump',
'yaml' => 'text/yaml',
'yml' => 'text/yaml',
'zip' => 'application/zip',
];
$extension = strtolower($extension);
return isset($mimetypes[$extension])
? $mimetypes[$extension]
: null;
}
/**
* Parses an HTTP message into an associative array.
*
* The array contains the "start-line" key containing the start line of
* the message, "headers" key containing an associative array of header
* array values, and a "body" key containing the body of the message.
*
* @param string $message HTTP request or response to parse.
*
* @return array
* @internal
*/
function _parse_message($message)
{
if (!$message) {
throw new \InvalidArgumentException('Invalid message');
}
// Iterate over each line in the message, accounting for line endings
$lines = preg_split('/(\\r?\\n)/', $message, -1, PREG_SPLIT_DELIM_CAPTURE);
$result = ['start-line' => array_shift($lines), 'headers' => [], 'body' => ''];
array_shift($lines);
for ($i = 0, $totalLines = count($lines); $i < $totalLines; $i += 2) {
$line = $lines[$i];
// If two line breaks were encountered, then this is the end of body
if (empty($line)) {
if ($i < $totalLines - 1) {
$result['body'] = implode('', array_slice($lines, $i + 2));
}
break;
}
if (strpos($line, ':')) {
$parts = explode(':', $line, 2);
$key = trim($parts[0]);
$value = isset($parts[1]) ? trim($parts[1]) : '';
$result['headers'][$key][] = $value;
}
}
return $result;
}
/**
* Constructs a URI for an HTTP request message.
*
* @param string $path Path from the start-line
* @param array $headers Array of headers (each value an array).
*
* @return string
* @internal
*/
function _parse_request_uri($path, array $headers)
{
$hostKey = array_filter(array_keys($headers), function ($k) {
return strtolower($k) === 'host';
});
// If no host is found, then a full URI cannot be constructed.
if (!$hostKey) {
return $path;
}
$host = $headers[reset($hostKey)][0];
$scheme = substr($host, -4) === ':443' ? 'https' : 'http';
return $scheme . '://' . $host . '/' . ltrim($path, '/');
}
/** @internal */
function _caseless_remove($keys, array $data)
{
$result = [];
foreach ($keys as &$key) {
$key = strtolower($key);
}
foreach ($data as $k => $v) {
if (!in_array(strtolower($k), $keys)) {
$result[$k] = $v;
}
}
return $result;
}
| gorobetssergey/BBC.test | vendor/guzzlehttp/psr7/src/functions.php | PHP | bsd-3-clause | 24,180 |
/* eslint-env mocha */
/* eslint no-template-curly-in-string: 0 */
import assert from 'assert';
import { extractProp } from '../helper';
import getPropValue from '../../src/getPropValue';
describe('getPropValue', () => {
it('should export a function', () => {
const expected = 'function';
const actual = typeof getPropValue;
assert.equal(expected, actual);
});
it('should return undefined when not provided with a JSXAttribute', () => {
const expected = undefined;
const actual = getPropValue(1);
assert.equal(expected, actual);
});
it('should throw error when trying to get value from unknown node type', () => {
const prop = {
type: 'JSXAttribute',
value: {
type: 'JSXExpressionContainer',
},
};
assert.throws(() => {
getPropValue(prop);
}, Error);
});
describe('Null', () => {
it('should return true when no value is given', () => {
const prop = extractProp('<div foo />');
const expected = true;
const actual = getPropValue(prop);
assert.equal(expected, actual);
});
});
describe('Literal', () => {
it('should return correct string if value is a string', () => {
const prop = extractProp('<div foo="bar" />');
const expected = 'bar';
const actual = getPropValue(prop);
assert.equal(expected, actual);
});
it('should return correct string if value is a string expression', () => {
const prop = extractProp('<div foo={"bar"} />');
const expected = 'bar';
const actual = getPropValue(prop);
assert.equal(expected, actual);
});
it('should return correct integer if value is a integer expression', () => {
const prop = extractProp('<div foo={1} />');
const expected = 1;
const actual = getPropValue(prop);
assert.equal(expected, actual);
});
it('should convert "true" to boolean type', () => {
const prop = extractProp('<div foo="true" />');
const expected = true;
const actual = getPropValue(prop);
assert.equal(expected, actual);
});
it('should convert "false" to boolean type', () => {
const prop = extractProp('<div foo="false" />');
const expected = false;
const actual = getPropValue(prop);
assert.equal(expected, actual);
});
});
describe('JSXElement', () => {
it('should return correct representation of JSX element as a string', () => {
const prop = extractProp('<div foo=<bar /> />');
const expected = '<bar />';
const actual = getPropValue(prop);
assert.equal(expected, actual);
});
});
describe('Identifier', () => {
it('should return string representation of variable identifier', () => {
const prop = extractProp('<div foo={bar} />');
const expected = 'bar';
const actual = getPropValue(prop);
assert.equal(expected, actual);
});
it('should return undefined when identifier is literally `undefined`', () => {
const prop = extractProp('<div foo={undefined} />');
const expected = undefined;
const actual = getPropValue(prop);
assert.equal(expected, actual);
});
it('should return String object when using a reserved JavaScript object', () => {
const prop = extractProp('<div foo={String} />');
const expected = String;
const actual = getPropValue(prop);
assert.equal(expected, actual);
});
it('should return Array object when using a reserved JavaScript object', () => {
const prop = extractProp('<div foo={Array} />');
const expected = Array;
const actual = getPropValue(prop);
assert.equal(expected, actual);
});
it('should return Date object when using a reserved JavaScript object', () => {
const prop = extractProp('<div foo={Date} />');
const expected = Date;
const actual = getPropValue(prop);
assert.equal(expected, actual);
});
it('should return Infinity object when using a reserved JavaScript object', () => {
const prop = extractProp('<div foo={Infinity} />');
const expected = Infinity;
const actual = getPropValue(prop);
assert.equal(expected, actual);
});
it('should return Math object when using a reserved JavaScript object', () => {
const prop = extractProp('<div foo={Math} />');
const expected = Math;
const actual = getPropValue(prop);
assert.equal(expected, actual);
});
it('should return Number object when using a reserved JavaScript object', () => {
const prop = extractProp('<div foo={Number} />');
const expected = Number;
const actual = getPropValue(prop);
assert.equal(expected, actual);
});
it('should return Object object when using a reserved JavaScript object', () => {
const prop = extractProp('<div foo={Object} />');
const expected = Object;
const actual = getPropValue(prop);
assert.equal(expected, actual);
});
});
describe('Template literal', () => {
it('should return template literal with vars wrapped in curly braces', () => {
const prop = extractProp('<div foo={`bar ${baz}`} />');
const expected = 'bar {baz}';
const actual = getPropValue(prop);
assert.equal(expected, actual);
});
it('should drop variables in template literals that are literally undefined', () => {
const prop = extractProp('<div foo={`bar ${undefined}`} />');
const expected = 'bar ';
const actual = getPropValue(prop);
assert.equal(expected, actual);
});
it('should return template literal with expression type wrapped in curly braces', () => {
const prop = extractProp('<div foo={`bar ${baz()}`} />');
const expected = 'bar {CallExpression}';
const actual = getPropValue(prop);
assert.equal(expected, actual);
});
it('should ignore non-expressions in the template literal', () => {
const prop = extractProp('<div foo={`bar ${<baz />}`} />');
const expected = 'bar ';
const actual = getPropValue(prop);
assert.equal(expected, actual);
});
});
describe('Tagged Template literal', () => {
it('should return template literal with vars wrapped in curly braces', () => {
const prop = extractProp('<div foo={noop`bar ${baz}`} />');
const expected = 'bar {baz}';
const actual = getPropValue(prop);
assert.equal(expected, actual);
});
it('should drop variables in template literals that are literally undefined', () => {
const prop = extractProp('<div foo={noop`bar ${undefined}`} />');
const expected = 'bar ';
const actual = getPropValue(prop);
assert.equal(expected, actual);
});
it('should return template literal with expression type wrapped in curly braces', () => {
const prop = extractProp('<div foo={noop`bar ${baz()}`} />');
const expected = 'bar {CallExpression}';
const actual = getPropValue(prop);
assert.equal(expected, actual);
});
it('should ignore non-expressions in the template literal', () => {
const prop = extractProp('<div foo={noop`bar ${<baz />}`} />');
const expected = 'bar ';
const actual = getPropValue(prop);
assert.equal(expected, actual);
});
});
describe('Arrow function expression', () => {
it('should return a function', () => {
const prop = extractProp('<div foo={ () => { return "bar"; }} />');
const expected = 'function';
const actual = getPropValue(prop);
assert.equal(expected, typeof actual);
// For code coverage ¯\_(ツ)_/¯
actual();
});
});
describe('Function expression', () => {
it('should return a function', () => {
const prop = extractProp('<div foo={ function() { return "bar"; } } />');
const expected = 'function';
const actual = getPropValue(prop);
assert.equal(expected, typeof actual);
// For code coverage ¯\_(ツ)_/¯
actual();
});
});
describe('Logical expression', () => {
it('should correctly infer result of && logical expression based on derived values', () => {
const prop = extractProp('<div foo={bar && baz} />');
const expected = 'baz';
const actual = getPropValue(prop);
assert.equal(expected, actual);
});
it('should return undefined when evaluating `undefined && undefined` ', () => {
const prop = extractProp('<div foo={undefined && undefined} />');
const expected = undefined;
const actual = getPropValue(prop);
assert.equal(expected, actual);
});
it('should correctly infer result of || logical expression based on derived values', () => {
const prop = extractProp('<div foo={bar || baz} />');
const expected = 'bar';
const actual = getPropValue(prop);
assert.equal(expected, actual);
});
it('should correctly infer result of || logical expression based on derived values', () => {
const prop = extractProp('<div foo={undefined || baz} />');
const expected = 'baz';
const actual = getPropValue(prop);
assert.equal(expected, actual);
});
it('should return undefined when evaluating `undefined || undefined` ', () => {
const prop = extractProp('<div foo={undefined || undefined} />');
const expected = undefined;
const actual = getPropValue(prop);
assert.equal(expected, actual);
});
});
describe('Member expression', () => {
it('should return string representation of form `object.property`', () => {
const prop = extractProp('<div foo={bar.baz} />');
const expected = 'bar.baz';
const actual = getPropValue(prop);
assert.equal(expected, actual);
});
});
describe('Call expression', () => {
it('should return string representation of callee', () => {
const prop = extractProp('<div foo={bar()} />');
const expected = 'bar';
const actual = getPropValue(prop);
assert.equal(expected, actual);
});
it('should return string representation of callee', () => {
const prop = extractProp('<div foo={bar.call()} />');
const expected = 'bar.call';
const actual = getPropValue(prop);
assert.equal(expected, actual);
});
});
describe('Unary expression', () => {
it('should correctly evaluate an expression that prefixes with -', () => {
const prop = extractProp('<div foo={-bar} />');
// -"bar" => NaN
const expected = true;
const actual = isNaN(getPropValue(prop));
assert.equal(expected, actual);
});
it('should correctly evaluate an expression that prefixes with -', () => {
const prop = extractProp('<div foo={-42} />');
const expected = -42;
const actual = getPropValue(prop);
assert.equal(expected, actual);
});
it('should correctly evaluate an expression that prefixes with +', () => {
const prop = extractProp('<div foo={+bar} />');
// +"bar" => NaN
const expected = true;
const actual = isNaN(getPropValue(prop));
assert.equal(expected, actual);
});
it('should correctly evaluate an expression that prefixes with +', () => {
const prop = extractProp('<div foo={+42} />');
const expected = 42;
const actual = getPropValue(prop);
assert.equal(expected, actual);
});
it('should correctly evaluate an expression that prefixes with !', () => {
const prop = extractProp('<div foo={!bar} />');
const expected = false; // !"bar" === false
const actual = getPropValue(prop);
assert.equal(expected, actual);
});
it('should correctly evaluate an expression that prefixes with ~', () => {
const prop = extractProp('<div foo={~bar} />');
const expected = -1; // ~"bar" === -1
const actual = getPropValue(prop);
assert.equal(expected, actual);
});
it('should return true when evaluating `delete foo`', () => {
const prop = extractProp('<div foo={delete x} />');
const expected = true;
const actual = getPropValue(prop);
assert.equal(expected, actual);
});
it('should return undefined when evaluating `void foo`', () => {
const prop = extractProp('<div foo={void x} />');
const expected = undefined;
const actual = getPropValue(prop);
assert.equal(expected, actual);
});
// TODO: We should fix this to check to see if we can evaluate it.
it('should return undefined when evaluating `typeof foo`', () => {
const prop = extractProp('<div foo={typeof x} />');
const expected = undefined;
const actual = getPropValue(prop);
assert.equal(expected, actual);
});
});
describe('Update expression', () => {
it('should correctly evaluate an expression that prefixes with ++', () => {
const prop = extractProp('<div foo={++bar} />');
// ++"bar" => NaN
const expected = true;
const actual = isNaN(getPropValue(prop));
assert.equal(expected, actual);
});
it('should correctly evaluate an expression that prefixes with --', () => {
const prop = extractProp('<div foo={--bar} />');
const expected = true;
const actual = isNaN(getPropValue(prop));
assert.equal(expected, actual);
});
it('should correctly evaluate an expression that suffixes with ++', () => {
const prop = extractProp('<div foo={bar++} />');
// "bar"++ => NaN
const expected = true;
const actual = isNaN(getPropValue(prop));
assert.equal(expected, actual);
});
it('should correctly evaluate an expression that suffixes with --', () => {
const prop = extractProp('<div foo={bar--} />');
const expected = true;
const actual = isNaN(getPropValue(prop));
assert.equal(expected, actual);
});
});
describe('This expression', () => {
it('should return string value `this`', () => {
const prop = extractProp('<div foo={this} />');
const expected = 'this';
const actual = getPropValue(prop);
assert.equal(expected, actual);
});
});
describe('Conditional expression', () => {
it('should evaluate the conditional based on the derived values correctly', () => {
const prop = extractProp('<div foo={bar ? baz : bam} />');
const expected = 'baz';
const actual = getPropValue(prop);
assert.equal(expected, actual);
});
it('should evaluate the conditional based on the derived values correctly', () => {
const prop = extractProp('<div foo={undefined ? baz : bam} />');
const expected = 'bam';
const actual = getPropValue(prop);
assert.equal(expected, actual);
});
it('should evaluate the conditional based on the derived values correctly', () => {
const prop = extractProp('<div foo={(1 > 2) ? baz : bam} />');
const expected = 'bam';
const actual = getPropValue(prop);
assert.equal(expected, actual);
});
});
describe('Binary expression', () => {
it('should evaluate the `==` operator correctly', () => {
const trueProp = extractProp('<div foo={1 == "1"} />');
const falseProp = extractProp('<div foo={1 == bar} />');
const trueVal = getPropValue(trueProp);
const falseVal = getPropValue(falseProp);
assert.equal(true, trueVal);
assert.equal(false, falseVal);
});
it('should evaluate the `!=` operator correctly', () => {
const trueProp = extractProp('<div foo={1 != "2"} />');
const falseProp = extractProp('<div foo={1 != "1"} />');
const trueVal = getPropValue(trueProp);
const falseVal = getPropValue(falseProp);
assert.equal(true, trueVal);
assert.equal(false, falseVal);
});
it('should evaluate the `===` operator correctly', () => {
const trueProp = extractProp('<div foo={1 === 1} />');
const falseProp = extractProp('<div foo={1 === "1"} />');
const trueVal = getPropValue(trueProp);
const falseVal = getPropValue(falseProp);
assert.equal(true, trueVal);
assert.equal(false, falseVal);
});
it('should evaluate the `!==` operator correctly', () => {
const trueProp = extractProp('<div foo={1 !== "1"} />');
const falseProp = extractProp('<div foo={1 !== 1} />');
const trueVal = getPropValue(trueProp);
const falseVal = getPropValue(falseProp);
assert.equal(true, trueVal);
assert.equal(false, falseVal);
});
it('should evaluate the `<` operator correctly', () => {
const trueProp = extractProp('<div foo={1 < 2} />');
const falseProp = extractProp('<div foo={1 < 0} />');
const trueVal = getPropValue(trueProp);
const falseVal = getPropValue(falseProp);
assert.equal(true, trueVal);
assert.equal(false, falseVal);
});
it('should evaluate the `>` operator correctly', () => {
const trueProp = extractProp('<div foo={1 > 0} />');
const falseProp = extractProp('<div foo={1 > 2} />');
const trueVal = getPropValue(trueProp);
const falseVal = getPropValue(falseProp);
assert.equal(true, trueVal);
assert.equal(false, falseVal);
});
it('should evaluate the `<=` operator correctly', () => {
const trueProp = extractProp('<div foo={1 <= 1} />');
const falseProp = extractProp('<div foo={1 <= 0} />');
const trueVal = getPropValue(trueProp);
const falseVal = getPropValue(falseProp);
assert.equal(true, trueVal);
assert.equal(false, falseVal);
});
it('should evaluate the `>=` operator correctly', () => {
const trueProp = extractProp('<div foo={1 >= 1} />');
const falseProp = extractProp('<div foo={1 >= 2} />');
const trueVal = getPropValue(trueProp);
const falseVal = getPropValue(falseProp);
assert.equal(true, trueVal);
assert.equal(false, falseVal);
});
it('should evaluate the `<<` operator correctly', () => {
const prop = extractProp('<div foo={1 << 2} />');
const expected = 4;
const actual = getPropValue(prop);
assert.equal(expected, actual);
});
it('should evaluate the `>>` operator correctly', () => {
const prop = extractProp('<div foo={1 >> 2} />');
const expected = 0;
const actual = getPropValue(prop);
assert.equal(expected, actual);
});
it('should evaluate the `>>>` operator correctly', () => {
const prop = extractProp('<div foo={2 >>> 1} />');
const expected = 1;
const actual = getPropValue(prop);
assert.equal(expected, actual);
});
it('should evaluate the `+` operator correctly', () => {
const prop = extractProp('<div foo={1 + 1} />');
const expected = 2;
const actual = getPropValue(prop);
assert.equal(expected, actual);
});
it('should evaluate the `-` operator correctly', () => {
const prop = extractProp('<div foo={1 - 1} />');
const expected = 0;
const actual = getPropValue(prop);
assert.equal(expected, actual);
});
it('should evaluate the `*` operator correctly', () => {
const prop = extractProp('<div foo={10 * 10} />');
const expected = 100;
const actual = getPropValue(prop);
assert.equal(expected, actual);
});
it('should evaluate the `/` operator correctly', () => {
const prop = extractProp('<div foo={10 / 2} />');
const expected = 5;
const actual = getPropValue(prop);
assert.equal(expected, actual);
});
it('should evaluate the `%` operator correctly', () => {
const prop = extractProp('<div foo={10 % 3} />');
const expected = 1;
const actual = getPropValue(prop);
assert.equal(expected, actual);
});
it('should evaluate the `|` operator correctly', () => {
const prop = extractProp('<div foo={10 | 1} />');
const expected = 11;
const actual = getPropValue(prop);
assert.equal(expected, actual);
});
it('should evaluate the `^` operator correctly', () => {
const prop = extractProp('<div foo={10 ^ 1} />');
const expected = 11;
const actual = getPropValue(prop);
assert.equal(expected, actual);
});
it('should evaluate the `&` operator correctly', () => {
const prop = extractProp('<div foo={10 & 1} />');
const expected = 0;
const actual = getPropValue(prop);
assert.equal(expected, actual);
});
it('should evaluate the `in` operator correctly', () => {
const prop = extractProp('<div foo={foo in bar} />');
const expected = false;
const actual = getPropValue(prop);
assert.equal(expected, actual);
});
it('should evaluate the `instanceof` operator correctly', () => {
const prop = extractProp('<div foo={{} instanceof Object} />');
const expected = true;
const actual = getPropValue(prop);
assert.equal(expected, actual);
});
it('should evaluate the `instanceof` operator when right side is not a function', () => {
const prop = extractProp('<div foo={"bar" instanceof Baz} />');
const expected = false;
const actual = getPropValue(prop);
assert.equal(expected, actual);
});
});
describe('Object expression', () => {
it('should evaluate to a correct representation of the object in props', () => {
const prop = extractProp('<div foo={ { bar: "baz" } } />');
const expected = { bar: 'baz' };
const actual = getPropValue(prop);
assert.deepEqual(expected, actual);
});
});
describe('New expression', () => {
it('should return a new empty object', () => {
const prop = extractProp('<div foo={new Bar()} />');
const expected = {};
const actual = getPropValue(prop);
assert.deepEqual(expected, actual);
});
});
describe('Array expression', () => {
it('should evaluate to correct representation of the the array in props', () => {
const prop = extractProp('<div foo={["bar", 42, null]} />');
const expected = ['bar', 42, null];
const actual = getPropValue(prop);
assert.deepEqual(expected, actual);
});
});
it('should return an empty array provided an empty array in props', () => {
const prop = extractProp('<div foo={[]} />');
const expected = [];
const actual = getPropValue(prop);
assert.deepEqual(expected, actual);
});
});
| TripleDip/draft-js | node_modules/jsx-ast-utils/__tests__/src/getPropValue-test.js | JavaScript | bsd-3-clause | 22,587 |
// Karma configuration
// Generated on Sun Jun 30 2013 00:14:30 GMT-0700 (PDT)
// base path, that will be used to resolve files and exclude
basePath = '';
preprocessors = {
'src/**/*.js': 'coverage'
};
// list of files / patterns to load in the browser
files = [
'bower_components/jquery/jquery.js',
'src/common/utils.js',
'src/bloodhound/version.js',
'src/bloodhound/tokenizers.js',
'src/bloodhound/lru_cache.js',
'src/bloodhound/persistent_storage.js',
'src/bloodhound/transport.js',
'src/bloodhound/search_index.js',
'src/bloodhound/options_parser.js',
'src/bloodhound/bloodhound.js',
'src/typeahead/html.js',
'src/typeahead/css.js',
'src/typeahead/event_bus.js',
'src/typeahead/event_emitter.js',
'src/typeahead/highlight.js',
'src/typeahead/input.js',
'src/typeahead/dataset.js',
'src/typeahead/dropdown.js',
'src/typeahead/typeahead.js',
'src/typeahead/plugin.js',
JASMINE,
JASMINE_ADAPTER,
'test/fixtures/**/*',
'bower_components/jasmine-jquery/lib/jasmine-jquery.js',
'bower_components/jasmine-ajax/lib/mock-ajax.js',
'test/helpers/**/*',
'test/*_spec.js'
];
// list of files to exclude
exclude = [
];
// test results reporter to use
// possible values: 'dots', 'progress', 'junit'
reporters = ['progress', 'coverage'];
// web server port
port = 9876;
// cli runner port
runnerPort = 9100;
// code coverage configs
coverageReporter = {
type : 'html',
dir : 'test/coverage/'
}
// enable / disable colors in the output (reporters and logs)
colors = true;
// level of logging
// possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
logLevel = LOG_INFO;
// enable / disable watching file and executing tests whenever any file changes
autoWatch = true;
// Start these browsers, currently available:
// - Chrome
// - ChromeCanary
// - Firefox
// - Opera
// - Safari (only Mac)
// - PhantomJS
// - IE (only Windows)
browsers = ['Chrome'];
// If browser does not capture in given timeout [ms], kill it
captureTimeout = 60000;
// Continuous Integration mode
// if true, it capture browsers, run tests and exit
singleRun = false;
| luhaoz/mcwiki | vendor/bower/typeahead.js/karma.conf.js | JavaScript | bsd-3-clause | 2,137 |
/* ========================================================================
* Bootstrap: affix.js v3.0.0
* http://twbs.github.com/bootstrap/javascript.html#affix
* ========================================================================
* Copyright 2012 Twitter, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ======================================================================== */
+function ($) { "use strict";
// AFFIX CLASS DEFINITION
// ======================
var Affix = function (element, options) {
this.options = $.extend({}, Affix.DEFAULTS, options)
this.$window = $(window)
.on('scroll.bs.affix.data-api', $.proxy(this.checkPosition, this))
.on('click.bs.affix.data-api', $.proxy(this.checkPositionWithEventLoop, this))
this.$element = $(element)
this.affixed =
this.unpin = null
this.checkPosition()
}
Affix.RESET = 'affix affix-top affix-bottom'
Affix.DEFAULTS = {
offset: 0
}
Affix.prototype.checkPositionWithEventLoop = function () {
setTimeout($.proxy(this.checkPosition, this), 1)
}
Affix.prototype.checkPosition = function () {
if (!this.$element.is(':visible')) return
var scrollHeight = $(document).height()
var scrollTop = this.$window.scrollTop()
var position = this.$element.offset()
var offset = this.options.offset
var offsetTop = offset.top
var offsetBottom = offset.bottom
if (typeof offset != 'object') offsetBottom = offsetTop = offset
if (typeof offsetTop == 'function') offsetTop = offset.top()
if (typeof offsetBottom == 'function') offsetBottom = offset.bottom()
var affix = this.unpin != null && (scrollTop + this.unpin <= position.top) ? false :
offsetBottom != null && (position.top + this.$element.height() >= scrollHeight - offsetBottom) ? 'bottom' :
offsetTop != null && (scrollTop <= offsetTop) ? 'top' : false
if (this.affixed === affix) return
if (this.unpin) this.$element.css('top', '')
this.affixed = affix
this.unpin = affix == 'bottom' ? position.top - scrollTop : null
this.$element.removeClass(Affix.RESET).addClass('affix' + (affix ? '-' + affix : ''))
if (affix == 'bottom') {
this.$element.offset({ top: document.body.offsetHeight - offsetBottom - this.$element.height() })
}
}
// AFFIX PLUGIN DEFINITION
// =======================
var old = $.fn.affix
$.fn.affix = function (option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.affix')
var options = typeof option == 'object' && option
if (!data) $this.data('bs.affix', (data = new Affix(this, options)))
if (typeof option == 'string') data[option]()
})
}
$.fn.affix.Constructor = Affix
// AFFIX NO CONFLICT
// =================
$.fn.affix.noConflict = function () {
$.fn.affix = old
return this
}
// AFFIX DATA-API
// ==============
$(window).on('load', function () {
$('[data-spy="affix"]').each(function () {
var $spy = $(this)
var data = $spy.data()
data.offset = data.offset || {}
if (data.offsetBottom) data.offset.bottom = data.offsetBottom
if (data.offsetTop) data.offset.top = data.offsetTop
$spy.affix(data)
})
})
}(window.jQuery);
| manpreetabhaypal/psdm | html/flex/themes.startbootstrap.com/flex-admin-v1.2/js/plugins/bootstrap-tokenfield/affix.js | JavaScript | bsd-3-clause | 3,881 |
@import url("basic.css");
/* -- page layout ----------------------------------------------------------- */
body {
font-family: 'goudy old style', 'minion pro', 'bell mt', Georgia, 'Hiragino Mincho Pro', serif;
font-size: 17px;
background-color: white;
color: #000;
margin: 0;
padding: 0;
}
div.document {
width: 940px;
margin: 30px auto 0 auto;
}
div.documentwrapper {
float: left;
width: 100%;
}
div.bodywrapper {
margin: 0 0 0 220px;
}
div.sphinxsidebar {
width: 220px;
font-size: 14px;
line-height: 1.5;
}
hr {
border: 1px solid #B1B4B6;
}
div.body {
background-color: #ffffff;
color: #3E4349;
padding: 0 30px 0 30px;
}
div.body > .section {
text-align: left;
}
div.footer {
width: 940px;
margin: 20px auto 30px auto;
font-size: 14px;
color: #888;
text-align: right;
}
div.footer a {
color: #888;
}
p.caption {
font-family: ;
font-size: inherit;
}
div.relations {
display: none;
}
div.sphinxsidebar a {
color: #444;
text-decoration: none;
border-bottom: 1px dotted #999;
}
div.sphinxsidebar a:hover {
border-bottom: 1px solid #999;
}
div.sphinxsidebarwrapper {
padding: 18px 10px;
}
div.sphinxsidebarwrapper p.logo {
padding: 0;
margin: -10px 0 0 0px;
text-align: center;
}
div.sphinxsidebarwrapper h1.logo {
margin-top: -10px;
text-align: center;
margin-bottom: 5px;
text-align: left;
}
div.sphinxsidebarwrapper h1.logo-name {
margin-top: 0px;
}
div.sphinxsidebarwrapper p.blurb {
margin-top: 0;
font-style: normal;
}
div.sphinxsidebar h3,
div.sphinxsidebar h4 {
font-family: 'Garamond', 'Georgia', serif;
color: #444;
font-size: 24px;
font-weight: normal;
margin: 0 0 5px 0;
padding: 0;
}
div.sphinxsidebar h4 {
font-size: 20px;
}
div.sphinxsidebar h3 a {
color: #444;
}
div.sphinxsidebar p.logo a,
div.sphinxsidebar h3 a,
div.sphinxsidebar p.logo a:hover,
div.sphinxsidebar h3 a:hover {
border: none;
}
div.sphinxsidebar p {
color: #555;
margin: 10px 0;
}
div.sphinxsidebar ul {
margin: 10px 0;
padding: 0;
color: #000;
}
div.sphinxsidebar ul li.toctree-l1 > a {
font-size: 120%;
}
div.sphinxsidebar ul li.toctree-l2 > a {
font-size: 110%;
}
div.sphinxsidebar input {
border: 1px solid #CCC;
font-family: 'goudy old style', 'minion pro', 'bell mt', Georgia, 'Hiragino Mincho Pro', serif;
font-size: 1em;
}
div.sphinxsidebar hr {
border: none;
height: 1px;
color: #AAA;
background: #AAA;
text-align: left;
margin-left: 0;
width: 50%;
}
/* -- body styles ----------------------------------------------------------- */
a {
color: #004B6B;
text-decoration: underline;
}
a:hover {
color: #6D4100;
text-decoration: underline;
}
div.body h1,
div.body h2,
div.body h3,
div.body h4,
div.body h5,
div.body h6 {
font-family: 'Garamond', 'Georgia', serif;
font-weight: normal;
margin: 30px 0px 10px 0px;
padding: 0;
}
div.body h1 { margin-top: 0; padding-top: 0; font-size: 240%; }
div.body h2 { font-size: 180%; }
div.body h3 { font-size: 150%; }
div.body h4 { font-size: 130%; }
div.body h5 { font-size: 100%; }
div.body h6 { font-size: 100%; }
a.headerlink {
color: #DDD;
padding: 0 4px;
text-decoration: none;
}
a.headerlink:hover {
color: #444;
background: #EAEAEA;
}
div.body p, div.body dd, div.body li {
line-height: 1.4em;
}
div.admonition {
margin: 20px 0px;
padding: 10px 30px;
background-color: #FCC;
border: 1px solid #FAA;
}
div.admonition tt.xref, div.admonition a tt {
border-bottom: 1px solid #fafafa;
}
dd div.admonition {
margin-left: -60px;
padding-left: 60px;
}
div.admonition p.admonition-title {
font-family: 'Garamond', 'Georgia', serif;
font-weight: normal;
font-size: 24px;
margin: 0 0 10px 0;
padding: 0;
line-height: 1;
}
div.admonition p.last {
margin-bottom: 0;
}
div.highlight {
background-color: white;
}
dt:target, .highlight {
background: #FAF3E8;
}
div.note {
background-color: #EEE;
border: 1px solid #CCC;
}
div.seealso {
background-color: #EEE;
border: 1px solid #CCC;
}
div.topic {
background-color: #eee;
}
p.admonition-title {
display: inline;
}
p.admonition-title:after {
content: ":";
}
pre, tt, code {
font-family: 'Consolas', 'Menlo', 'Deja Vu Sans Mono', 'Bitstream Vera Sans Mono', monospace;
font-size: 0.9em;
}
.hll {
background-color: #FFC;
margin: 0 -12px;
padding: 0 12px;
display: block;
}
img.screenshot {
}
tt.descname, tt.descclassname, code.descname, code.descclassname {
font-size: 0.95em;
}
tt.descname, code.descname {
padding-right: 0.08em;
}
img.screenshot {
-moz-box-shadow: 2px 2px 4px #eee;
-webkit-box-shadow: 2px 2px 4px #eee;
box-shadow: 2px 2px 4px #eee;
}
table.docutils {
border: 1px solid #888;
-moz-box-shadow: 2px 2px 4px #eee;
-webkit-box-shadow: 2px 2px 4px #eee;
box-shadow: 2px 2px 4px #eee;
}
table.docutils td, table.docutils th {
border: 1px solid #888;
padding: 0.25em 0.7em;
}
table.field-list, table.footnote {
border: none;
-moz-box-shadow: none;
-webkit-box-shadow: none;
box-shadow: none;
}
table.footnote {
margin: 15px 0;
width: 100%;
border: 1px solid #EEE;
background: #FDFDFD;
font-size: 0.9em;
}
table.footnote + table.footnote {
margin-top: -15px;
border-top: none;
}
table.field-list th {
padding: 0 0.8em 0 0;
}
table.field-list td {
padding: 0;
}
table.field-list p {
margin-bottom: 0.8em;
}
table.footnote td.label {
width: .1px;
padding: 0.3em 0 0.3em 0.5em;
}
table.footnote td {
padding: 0.3em 0.5em;
}
dl {
margin: 0;
padding: 0;
}
dl dd {
margin-left: 30px;
}
blockquote {
margin: 0 0 0 30px;
padding: 0;
}
ul, ol {
/* Matches the 30px from the narrow-screen "li > ul" selector below */
margin: 10px 0 10px 30px;
padding: 0;
}
pre {
background: #EEE;
padding: 7px 30px;
margin: 15px 0px;
line-height: 1.3em;
}
dl pre, blockquote pre, li pre {
margin-left: 0;
padding-left: 30px;
}
dl dl pre {
margin-left: -90px;
padding-left: 90px;
}
tt, code {
background-color: #ecf0f3;
color: #222;
/* padding: 1px 2px; */
}
tt.xref, code.xref, a tt {
background-color: #FBFBFB;
border-bottom: 1px solid white;
}
a.reference {
text-decoration: none;
border-bottom: 1px dotted #004B6B;
}
/* Don't put an underline on images */
a.image-reference, a.image-reference:hover {
border-bottom: none;
}
a.reference:hover {
border-bottom: 1px solid #6D4100;
}
a.footnote-reference {
text-decoration: none;
font-size: 0.7em;
vertical-align: top;
border-bottom: 1px dotted #004B6B;
}
a.footnote-reference:hover {
border-bottom: 1px solid #6D4100;
}
a:hover tt, a:hover code {
background: #EEE;
}
@media screen and (max-width: 870px) {
div.sphinxsidebar {
display: none;
}
div.document {
width: 100%;
}
div.documentwrapper {
margin-left: 0;
margin-top: 0;
margin-right: 0;
margin-bottom: 0;
}
div.bodywrapper {
margin-top: 0;
margin-right: 0;
margin-bottom: 0;
margin-left: 0;
}
ul {
margin-left: 0;
}
li > ul {
/* Matches the 30px from the "ul, ol" selector above */
margin-left: 30px;
}
.document {
width: auto;
}
.footer {
width: auto;
}
.bodywrapper {
margin: 0;
}
.footer {
width: auto;
}
.github {
display: none;
}
}
@media screen and (max-width: 875px) {
body {
margin: 0;
padding: 20px 30px;
}
div.documentwrapper {
float: none;
background: white;
}
div.sphinxsidebar {
display: block;
float: none;
width: 102.5%;
margin: 50px -30px -20px -30px;
padding: 10px 20px;
background: #333;
color: #FFF;
}
div.sphinxsidebar h3, div.sphinxsidebar h4, div.sphinxsidebar p,
div.sphinxsidebar h3 a {
color: white;
}
div.sphinxsidebar a {
color: #AAA;
}
div.sphinxsidebar p.logo {
display: none;
}
div.document {
width: 100%;
margin: 0;
}
div.footer {
display: none;
}
div.bodywrapper {
margin: 0;
}
div.body {
min-height: 0;
padding: 0;
}
.rtd_doc_footer {
display: none;
}
.document {
width: auto;
}
.footer {
width: auto;
}
.footer {
width: auto;
}
.github {
display: none;
}
}
/* misc. */
.revsys-inline {
display: none!important;
}
/* Make nested-list/multi-paragraph items look better in Releases changelog
* pages. Without this, docutils' magical list fuckery causes inconsistent
* formatting between different release sub-lists.
*/
div#changelog > div.section > ul > li > p:only-child {
margin-bottom: 0;
}
/* Hide fugly table cell borders in ..bibliography:: directive output */
table.docutils.citation, table.docutils.citation td, table.docutils.citation th {
border: none;
/* Below needed in some edge cases; if not applied, bottom shadows appear */
-moz-box-shadow: none;
-webkit-box-shadow: none;
box-shadow: none;
} | nguy/artview | docs/build/html/_static/alabaster.css | CSS | bsd-3-clause | 9,544 |
<?php
return
array (
0 =>
array (
'type' => 'polygon',
'points' =>
array (
0 =>
array (
0 => 53,
1 => 0,
),
1 =>
array (
0 => 0,
1 => 30,
),
2 =>
array (
0 => 90,
1 => 185,
),
3 =>
array (
0 => 143,
1 => 155,
),
),
'color' => 16777215,
'filled' => true,
),
1 =>
array (
'type' => 'polygon',
'points' =>
array (
0 =>
array (
0 => 58,
1 => 8,
),
1 =>
array (
0 => 15,
1 => 33,
),
2 =>
array (
0 => 16,
1 => 35,
),
3 =>
array (
0 => 59,
1 => 10,
),
),
'color' => 0,
'filled' => true,
),
2 =>
array (
'type' => 'polygon',
'points' =>
array (
0 =>
array (
0 => 60,
1 => 12,
),
1 =>
array (
0 => 17,
1 => 37,
),
2 =>
array (
0 => 18,
1 => 38,
),
3 =>
array (
0 => 61,
1 => 13,
),
),
'color' => 0,
'filled' => true,
),
3 =>
array (
'type' => 'polygon',
'points' =>
array (
0 =>
array (
0 => 62,
1 => 15,
),
1 =>
array (
0 => 19,
1 => 40,
),
2 =>
array (
0 => 19,
1 => 40,
),
3 =>
array (
0 => 62,
1 => 15,
),
),
'color' => 0,
'filled' => true,
),
4 =>
array (
'type' => 'polygon',
'points' =>
array (
0 =>
array (
0 => 63,
1 => 17,
),
1 =>
array (
0 => 20,
1 => 42,
),
2 =>
array (
0 => 20,
1 => 42,
),
3 =>
array (
0 => 63,
1 => 17,
),
),
'color' => 0,
'filled' => true,
),
5 =>
array (
'type' => 'polygon',
'points' =>
array (
0 =>
array (
0 => 64,
1 => 19,
),
1 =>
array (
0 => 21,
1 => 44,
),
2 =>
array (
0 => 21,
1 => 44,
),
3 =>
array (
0 => 64,
1 => 19,
),
),
'color' => 0,
'filled' => true,
),
6 =>
array (
'type' => 'polygon',
'points' =>
array (
0 =>
array (
0 => 65,
1 => 20,
),
1 =>
array (
0 => 22,
1 => 45,
),
2 =>
array (
0 => 23,
1 => 47,
),
3 =>
array (
0 => 66,
1 => 22,
),
),
'color' => 0,
'filled' => true,
),
7 =>
array (
'type' => 'polygon',
'points' =>
array (
0 =>
array (
0 => 67,
1 => 24,
),
1 =>
array (
0 => 24,
1 => 49,
),
2 =>
array (
0 => 25,
1 => 50,
),
3 =>
array (
0 => 68,
1 => 25,
),
),
'color' => 0,
'filled' => true,
),
8 =>
array (
'type' => 'polygon',
'points' =>
array (
0 =>
array (
0 => 69,
1 => 27,
),
1 =>
array (
0 => 26,
1 => 52,
),
2 =>
array (
0 => 26,
1 => 52,
),
3 =>
array (
0 => 69,
1 => 27,
),
),
'color' => 0,
'filled' => true,
),
9 =>
array (
'type' => 'polygon',
'points' =>
array (
0 =>
array (
0 => 70,
1 => 29,
),
1 =>
array (
0 => 27,
1 => 54,
),
2 =>
array (
0 => 28,
1 => 56,
),
3 =>
array (
0 => 71,
1 => 31,
),
),
'color' => 0,
'filled' => true,
),
10 =>
array (
'type' => 'polygon',
'points' =>
array (
0 =>
array (
0 => 72,
1 => 32,
),
1 =>
array (
0 => 29,
1 => 57,
),
2 =>
array (
0 => 29,
1 => 57,
),
3 =>
array (
0 => 72,
1 => 32,
),
),
'color' => 0,
'filled' => true,
),
11 =>
array (
'type' => 'polygon',
'points' =>
array (
0 =>
array (
0 => 73,
1 => 34,
),
1 =>
array (
0 => 30,
1 => 59,
),
2 =>
array (
0 => 30,
1 => 59,
),
3 =>
array (
0 => 73,
1 => 34,
),
),
'color' => 0,
'filled' => true,
),
12 =>
array (
'type' => 'polygon',
'points' =>
array (
0 =>
array (
0 => 74,
1 => 36,
),
1 =>
array (
0 => 31,
1 => 61,
),
2 =>
array (
0 => 31,
1 => 61,
),
3 =>
array (
0 => 74,
1 => 36,
),
),
'color' => 0,
'filled' => true,
),
13 =>
array (
'type' => 'polygon',
'points' =>
array (
0 =>
array (
0 => 75,
1 => 38,
),
1 =>
array (
0 => 32,
1 => 63,
),
2 =>
array (
0 => 33,
1 => 64,
),
3 =>
array (
0 => 76,
1 => 39,
),
),
'color' => 0,
'filled' => true,
),
14 =>
array (
'type' => 'polygon',
'points' =>
array (
0 =>
array (
0 => 77,
1 => 41,
),
1 =>
array (
0 => 34,
1 => 66,
),
2 =>
array (
0 => 34,
1 => 66,
),
3 =>
array (
0 => 77,
1 => 41,
),
),
'color' => 0,
'filled' => true,
),
15 =>
array (
'type' => 'polygon',
'points' =>
array (
0 =>
array (
0 => 78,
1 => 43,
),
1 =>
array (
0 => 35,
1 => 68,
),
2 =>
array (
0 => 36,
1 => 70,
),
3 =>
array (
0 => 79,
1 => 45,
),
),
'color' => 0,
'filled' => true,
),
16 =>
array (
'type' => 'polygon',
'points' =>
array (
0 =>
array (
0 => 80,
1 => 46,
),
1 =>
array (
0 => 37,
1 => 71,
),
2 =>
array (
0 => 37,
1 => 71,
),
3 =>
array (
0 => 80,
1 => 46,
),
),
'color' => 0,
'filled' => true,
),
17 =>
array (
'type' => 'polygon',
'points' =>
array (
0 =>
array (
0 => 81,
1 => 48,
),
1 =>
array (
0 => 38,
1 => 73,
),
2 =>
array (
0 => 38,
1 => 73,
),
3 =>
array (
0 => 81,
1 => 48,
),
),
'color' => 0,
'filled' => true,
),
18 =>
array (
'type' => 'polygon',
'points' =>
array (
0 =>
array (
0 => 82,
1 => 50,
),
1 =>
array (
0 => 39,
1 => 75,
),
2 =>
array (
0 => 40,
1 => 76,
),
3 =>
array (
0 => 83,
1 => 51,
),
),
'color' => 0,
'filled' => true,
),
19 =>
array (
'type' => 'polygon',
'points' =>
array (
0 =>
array (
0 => 84,
1 => 53,
),
1 =>
array (
0 => 41,
1 => 78,
),
2 =>
array (
0 => 42,
1 => 80,
),
3 =>
array (
0 => 85,
1 => 55,
),
),
'color' => 0,
'filled' => true,
),
20 =>
array (
'type' => 'polygon',
'points' =>
array (
0 =>
array (
0 => 86,
1 => 57,
),
1 =>
array (
0 => 43,
1 => 82,
),
2 =>
array (
0 => 44,
1 => 83,
),
3 =>
array (
0 => 87,
1 => 58,
),
),
'color' => 0,
'filled' => true,
),
21 =>
array (
'type' => 'polygon',
'points' =>
array (
0 =>
array (
0 => 88,
1 => 60,
),
1 =>
array (
0 => 45,
1 => 85,
),
2 =>
array (
0 => 45,
1 => 85,
),
3 =>
array (
0 => 88,
1 => 60,
),
),
'color' => 0,
'filled' => true,
),
22 =>
array (
'type' => 'polygon',
'points' =>
array (
0 =>
array (
0 => 89,
1 => 62,
),
1 =>
array (
0 => 46,
1 => 87,
),
2 =>
array (
0 => 46,
1 => 87,
),
3 =>
array (
0 => 89,
1 => 62,
),
),
'color' => 0,
'filled' => true,
),
23 =>
array (
'type' => 'polygon',
'points' =>
array (
0 =>
array (
0 => 90,
1 => 64,
),
1 =>
array (
0 => 47,
1 => 89,
),
2 =>
array (
0 => 47,
1 => 89,
),
3 =>
array (
0 => 90,
1 => 64,
),
),
'color' => 0,
'filled' => true,
),
24 =>
array (
'type' => 'polygon',
'points' =>
array (
0 =>
array (
0 => 91,
1 => 65,
),
1 =>
array (
0 => 48,
1 => 90,
),
2 =>
array (
0 => 48,
1 => 90,
),
3 =>
array (
0 => 91,
1 => 65,
),
),
'color' => 0,
'filled' => true,
),
25 =>
array (
'type' => 'polygon',
'points' =>
array (
0 =>
array (
0 => 92,
1 => 67,
),
1 =>
array (
0 => 49,
1 => 92,
),
2 =>
array (
0 => 49,
1 => 92,
),
3 =>
array (
0 => 92,
1 => 67,
),
),
'color' => 0,
'filled' => true,
),
26 =>
array (
'type' => 'polygon',
'points' =>
array (
0 =>
array (
0 => 93,
1 => 69,
),
1 =>
array (
0 => 50,
1 => 94,
),
2 =>
array (
0 => 51,
1 => 96,
),
3 =>
array (
0 => 94,
1 => 71,
),
),
'color' => 0,
'filled' => true,
),
27 =>
array (
'type' => 'polygon',
'points' =>
array (
0 =>
array (
0 => 95,
1 => 72,
),
1 =>
array (
0 => 52,
1 => 97,
),
2 =>
array (
0 => 52,
1 => 97,
),
3 =>
array (
0 => 95,
1 => 72,
),
),
'color' => 0,
'filled' => true,
),
28 =>
array (
'type' => 'polygon',
'points' =>
array (
0 =>
array (
0 => 96,
1 => 74,
),
1 =>
array (
0 => 53,
1 => 99,
),
2 =>
array (
0 => 54,
1 => 101,
),
3 =>
array (
0 => 97,
1 => 76,
),
),
'color' => 0,
'filled' => true,
),
29 =>
array (
'type' => 'polygon',
'points' =>
array (
0 =>
array (
0 => 98,
1 => 77,
),
1 =>
array (
0 => 55,
1 => 102,
),
2 =>
array (
0 => 56,
1 => 104,
),
3 =>
array (
0 => 99,
1 => 79,
),
),
'color' => 0,
'filled' => true,
),
30 =>
array (
'type' => 'polygon',
'points' =>
array (
0 =>
array (
0 => 100,
1 => 81,
),
1 =>
array (
0 => 57,
1 => 106,
),
2 =>
array (
0 => 57,
1 => 106,
),
3 =>
array (
0 => 100,
1 => 81,
),
),
'color' => 0,
'filled' => true,
),
31 =>
array (
'type' => 'polygon',
'points' =>
array (
0 =>
array (
0 => 101,
1 => 83,
),
1 =>
array (
0 => 58,
1 => 108,
),
2 =>
array (
0 => 59,
1 => 109,
),
3 =>
array (
0 => 102,
1 => 84,
),
),
'color' => 0,
'filled' => true,
),
32 =>
array (
'type' => 'polygon',
'points' =>
array (
0 =>
array (
0 => 103,
1 => 86,
),
1 =>
array (
0 => 60,
1 => 111,
),
2 =>
array (
0 => 60,
1 => 111,
),
3 =>
array (
0 => 103,
1 => 86,
),
),
'color' => 0,
'filled' => true,
),
33 =>
array (
'type' => 'polygon',
'points' =>
array (
0 =>
array (
0 => 104,
1 => 88,
),
1 =>
array (
0 => 61,
1 => 113,
),
2 =>
array (
0 => 61,
1 => 113,
),
3 =>
array (
0 => 104,
1 => 88,
),
),
'color' => 0,
'filled' => true,
),
34 =>
array (
'type' => 'polygon',
'points' =>
array (
0 =>
array (
0 => 105,
1 => 90,
),
1 =>
array (
0 => 62,
1 => 115,
),
2 =>
array (
0 => 62,
1 => 115,
),
3 =>
array (
0 => 105,
1 => 90,
),
),
'color' => 0,
'filled' => true,
),
35 =>
array (
'type' => 'polygon',
'points' =>
array (
0 =>
array (
0 => 106,
1 => 91,
),
1 =>
array (
0 => 63,
1 => 116,
),
2 =>
array (
0 => 64,
1 => 118,
),
3 =>
array (
0 => 107,
1 => 93,
),
),
'color' => 0,
'filled' => true,
),
36 =>
array (
'type' => 'polygon',
'points' =>
array (
0 =>
array (
0 => 108,
1 => 95,
),
1 =>
array (
0 => 65,
1 => 120,
),
2 =>
array (
0 => 66,
1 => 121,
),
3 =>
array (
0 => 109,
1 => 96,
),
),
'color' => 0,
'filled' => true,
),
37 =>
array (
'type' => 'polygon',
'points' =>
array (
0 =>
array (
0 => 110,
1 => 98,
),
1 =>
array (
0 => 67,
1 => 123,
),
2 =>
array (
0 => 67,
1 => 123,
),
3 =>
array (
0 => 110,
1 => 98,
),
),
'color' => 0,
'filled' => true,
),
38 =>
array (
'type' => 'polygon',
'points' =>
array (
0 =>
array (
0 => 111,
1 => 100,
),
1 =>
array (
0 => 68,
1 => 125,
),
2 =>
array (
0 => 68,
1 => 125,
),
3 =>
array (
0 => 111,
1 => 100,
),
),
'color' => 0,
'filled' => true,
),
39 =>
array (
'type' => 'polygon',
'points' =>
array (
0 =>
array (
0 => 112,
1 => 102,
),
1 =>
array (
0 => 69,
1 => 127,
),
2 =>
array (
0 => 69,
1 => 127,
),
3 =>
array (
0 => 112,
1 => 102,
),
),
'color' => 0,
'filled' => true,
),
40 =>
array (
'type' => 'polygon',
'points' =>
array (
0 =>
array (
0 => 113,
1 => 103,
),
1 =>
array (
0 => 70,
1 => 128,
),
2 =>
array (
0 => 70,
1 => 128,
),
3 =>
array (
0 => 113,
1 => 103,
),
),
'color' => 0,
'filled' => true,
),
41 =>
array (
'type' => 'polygon',
'points' =>
array (
0 =>
array (
0 => 114,
1 => 105,
),
1 =>
array (
0 => 71,
1 => 130,
),
2 =>
array (
0 => 71,
1 => 130,
),
3 =>
array (
0 => 114,
1 => 105,
),
),
'color' => 0,
'filled' => true,
),
42 =>
array (
'type' => 'polygon',
'points' =>
array (
0 =>
array (
0 => 115,
1 => 107,
),
1 =>
array (
0 => 72,
1 => 132,
),
2 =>
array (
0 => 73,
1 => 134,
),
3 =>
array (
0 => 116,
1 => 109,
),
),
'color' => 0,
'filled' => true,
),
43 =>
array (
'type' => 'polygon',
'points' =>
array (
0 =>
array (
0 => 117,
1 => 110,
),
1 =>
array (
0 => 74,
1 => 135,
),
2 =>
array (
0 => 75,
1 => 137,
),
3 =>
array (
0 => 118,
1 => 112,
),
),
'color' => 0,
'filled' => true,
),
44 =>
array (
'type' => 'polygon',
'points' =>
array (
0 =>
array (
0 => 119,
1 => 114,
),
1 =>
array (
0 => 76,
1 => 139,
),
2 =>
array (
0 => 77,
1 => 141,
),
3 =>
array (
0 => 120,
1 => 116,
),
),
'color' => 0,
'filled' => true,
),
45 =>
array (
'type' => 'polygon',
'points' =>
array (
0 =>
array (
0 => 121,
1 => 117,
),
1 =>
array (
0 => 78,
1 => 142,
),
2 =>
array (
0 => 78,
1 => 142,
),
3 =>
array (
0 => 121,
1 => 117,
),
),
'color' => 0,
'filled' => true,
),
46 =>
array (
'type' => 'polygon',
'points' =>
array (
0 =>
array (
0 => 122,
1 => 119,
),
1 =>
array (
0 => 79,
1 => 144,
),
2 =>
array (
0 => 79,
1 => 144,
),
3 =>
array (
0 => 122,
1 => 119,
),
),
'color' => 0,
'filled' => true,
),
47 =>
array (
'type' => 'polygon',
'points' =>
array (
0 =>
array (
0 => 123,
1 => 121,
),
1 =>
array (
0 => 80,
1 => 146,
),
2 =>
array (
0 => 81,
1 => 147,
),
3 =>
array (
0 => 124,
1 => 122,
),
),
'color' => 0,
'filled' => true,
),
48 =>
array (
'type' => 'polygon',
'points' =>
array (
0 =>
array (
0 => 125,
1 => 124,
),
1 =>
array (
0 => 82,
1 => 149,
),
2 =>
array (
0 => 82,
1 => 149,
),
3 =>
array (
0 => 125,
1 => 124,
),
),
'color' => 0,
'filled' => true,
),
49 =>
array (
'type' => 'polygon',
'points' =>
array (
0 =>
array (
0 => 126,
1 => 126,
),
1 =>
array (
0 => 83,
1 => 151,
),
2 =>
array (
0 => 83,
1 => 151,
),
3 =>
array (
0 => 126,
1 => 126,
),
),
'color' => 0,
'filled' => true,
),
50 =>
array (
'type' => 'polygon',
'points' =>
array (
0 =>
array (
0 => 127,
1 => 128,
),
1 =>
array (
0 => 84,
1 => 153,
),
2 =>
array (
0 => 85,
1 => 154,
),
3 =>
array (
0 => 128,
1 => 129,
),
),
'color' => 0,
'filled' => true,
),
51 =>
array (
'type' => 'polygon',
'points' =>
array (
0 =>
array (
0 => 129,
1 => 131,
),
1 =>
array (
0 => 86,
1 => 156,
),
2 =>
array (
0 => 86,
1 => 156,
),
3 =>
array (
0 => 129,
1 => 131,
),
),
'color' => 0,
'filled' => true,
),
52 =>
array (
'type' => 'polygon',
'points' =>
array (
0 =>
array (
0 => 130,
1 => 133,
),
1 =>
array (
0 => 87,
1 => 158,
),
2 =>
array (
0 => 88,
1 => 160,
),
3 =>
array (
0 => 131,
1 => 135,
),
),
'color' => 0,
'filled' => true,
),
53 =>
array (
'type' => 'polygon',
'points' =>
array (
0 =>
array (
0 => 132,
1 => 136,
),
1 =>
array (
0 => 89,
1 => 161,
),
2 =>
array (
0 => 89,
1 => 161,
),
3 =>
array (
0 => 132,
1 => 136,
),
),
'color' => 0,
'filled' => true,
),
54 =>
array (
'type' => 'polygon',
'points' =>
array (
0 =>
array (
0 => 133,
1 => 138,
),
1 =>
array (
0 => 90,
1 => 163,
),
2 =>
array (
0 => 91,
1 => 165,
),
3 =>
array (
0 => 134,
1 => 140,
),
),
'color' => 0,
'filled' => true,
),
55 =>
array (
'type' => 'polygon',
'points' =>
array (
0 =>
array (
0 => 135,
1 => 142,
),
1 =>
array (
0 => 92,
1 => 167,
),
2 =>
array (
0 => 92,
1 => 167,
),
3 =>
array (
0 => 135,
1 => 142,
),
),
'color' => 0,
'filled' => true,
),
56 =>
array (
'type' => 'polygon',
'points' =>
array (
0 =>
array (
0 => 136,
1 => 143,
),
1 =>
array (
0 => 93,
1 => 168,
),
2 =>
array (
0 => 94,
1 => 170,
),
3 =>
array (
0 => 137,
1 => 145,
),
),
'color' => 0,
'filled' => true,
),
57 =>
array (
'type' => 'text',
'text' => '0',
'size' => 10,
'position' =>
array (
0 => 9,
1 => 46,
),
'font' => '',
'color' => 0,
'alignment' => 'center',
'orientation' => -60,
),
58 =>
array (
'type' => 'text',
'text' => '1',
'size' => 10,
'position' =>
array (
0 => 17,
1 => 59,
),
'font' => '',
'color' => 0,
'alignment' => 'center',
'orientation' => -60,
),
59 =>
array (
'type' => 'text',
'text' => '2',
'size' => 10,
'position' =>
array (
0 => 25,
1 => 73,
),
'font' => '',
'color' => 0,
'alignment' => 'center',
'orientation' => -60,
),
60 =>
array (
'type' => 'text',
'text' => '3',
'size' => 10,
'position' =>
array (
0 => 33,
1 => 87,
),
'font' => '',
'color' => 0,
'alignment' => 'center',
'orientation' => -60,
),
61 =>
array (
'type' => 'text',
'text' => '4',
'size' => 10,
'position' =>
array (
0 => 41,
1 => 101,
),
'font' => '',
'color' => 0,
'alignment' => 'center',
'orientation' => -60,
),
62 =>
array (
'type' => 'text',
'text' => '5',
'size' => 10,
'position' =>
array (
0 => 49,
1 => 115,
),
'font' => '',
'color' => 0,
'alignment' => 'center',
'orientation' => -60,
),
63 =>
array (
'type' => 'text',
'text' => '6',
'size' => 10,
'position' =>
array (
0 => 57,
1 => 129,
),
'font' => '',
'color' => 0,
'alignment' => 'center',
'orientation' => -60,
),
64 =>
array (
'type' => 'text',
'text' => '7',
'size' => 10,
'position' =>
array (
0 => 65,
1 => 143,
),
'font' => '',
'color' => 0,
'alignment' => 'center',
'orientation' => -60,
),
65 =>
array (
'type' => 'text',
'text' => '8',
'size' => 10,
'position' =>
array (
0 => 73,
1 => 156,
),
'font' => '',
'color' => 0,
'alignment' => 'center',
'orientation' => -60,
),
66 =>
array (
'type' => 'text',
'text' => '9',
'size' => 10,
'position' =>
array (
0 => 81,
1 => 170,
),
'font' => '',
'color' => 0,
'alignment' => 'center',
'orientation' => -60,
),
);
| fisdap/zf1 | tests/Zend/Barcode/Object/_files/Code25_0123456789_stretchtext_oriented_instructions.php | PHP | bsd-3-clause | 25,452 |
<?php
use Codeception\Lib\Parser;
/**
* @group core
* Class ParserTest
*/
class ParserTest extends \Codeception\Test\Unit
{
/**
* @var Parser
*/
protected $parser;
/**
* @var \Codeception\Scenario
*/
protected $scenario;
protected $testMetadata;
protected function _before()
{
$cept = new \Codeception\Test\Cept('demo', 'DemoCept.php');
$this->testMetadata = $cept->getMetadata();
$this->scenario = new Codeception\Scenario($cept);
$this->parser = new Parser($this->scenario, $this->testMetadata);
}
public function testParsingFeature()
{
$code = "<?php\n \\\$I->wantTo('run this test'); ";
$this->parser->parseFeature($code);
$this->assertEquals('run this test', $this->scenario->getFeature());
$code = "<?php\n \\\$I->wantToTest('this run'); ";
$this->parser->parseFeature($code);
$this->assertEquals('test this run', $this->scenario->getFeature());
}
public function testParsingWithWhitespace()
{
$code = "<?php\n \\\$I->wantTo( 'run this test' ); ";
$this->parser->parseFeature($code);
$this->assertEquals('run this test', $this->scenario->getFeature());
}
public function testScenarioOptions()
{
$code = <<<EOF
<?php
// @group davert
// @env windows
\$I = new AcceptanceTeser(\$scenario);
EOF;
$this->parser->parseScenarioOptions($code);
$this->assertContains('davert', $this->testMetadata->getGroups());
$this->assertContains('windows', $this->testMetadata->getEnv());
}
public function testCommentedInBlockScenarioOptions()
{
$code = <<<EOF
<?php
/**
* @skip
*/
EOF;
$this->parser->parseScenarioOptions($code);
$this->assertTrue($this->testMetadata->isBlocked());
}
public function testFeatureCommented()
{
$code = "<?php\n //\\\$I->wantTo('run this test'); ";
$this->parser->parseFeature($code);
$this->assertNull($this->scenario->getFeature());
$code = "<?php\n /*\n \\\$I->wantTo('run this test'); \n */";
$this->parser->parseFeature($code);
$this->assertNull($this->scenario->getFeature());
}
public function testScenarioSkipOptionsHandled()
{
$code = "<?php\n // @skip pass along";
$this->parser->parseScenarioOptions($code);
$this->assertTrue($this->testMetadata->isBlocked());
}
public function testScenarioIncompleteOptionHandled()
{
$code = "<?php\n // @incomplete not ready yet";
$this->parser->parseScenarioOptions($code);
$this->assertTrue($this->testMetadata->isBlocked());
}
public function testSteps()
{
$code = file_get_contents(\Codeception\Configuration::projectDir().'tests/cli/UnitCept.php');
$this->assertContains('$I->seeInThisFile', $code);
$this->parser->parseSteps($code);
$text = $this->scenario->getText();
$this->assertContains("I see in this file", $text);
}
public function testStepsWithFriends()
{
$code = file_get_contents(\Codeception\Configuration::projectDir().'tests/web/FriendsCept.php');
$this->assertContains('$I->haveFriend', $code);
$this->parser->parseSteps($code);
$text = $this->scenario->getText();
$this->assertContains("jon does", $text);
$this->assertContains("I have friend", $text);
$this->assertContains("back to me", $text);
}
public function testParseFile()
{
$classes = Parser::getClassesFromFile(codecept_data_dir('SimpleTest.php'));
$this->assertEquals(['SampleTest'], $classes);
}
public function testParseFileWithClass()
{
if (version_compare(PHP_VERSION, '5.5.0', '<')) {
$this->markTestSkipped('only for php 5.5');
}
$classes = Parser::getClassesFromFile(codecept_data_dir('php55Test'));
$this->assertEquals(['php55Test'], $classes);
}
public function testParseFileWithAnonymousClass()
{
if (version_compare(PHP_VERSION, '7.0.0', '<')) {
$this->markTestSkipped('only for php 7');
}
$classes = Parser::getClassesFromFile(codecept_data_dir('php70Test'));
$this->assertEquals(['php70Test'], $classes);
}
/*
* https://github.com/Codeception/Codeception/issues/1779
*/
public function testParseFileWhichUnsetsFileVariable()
{
$classes = Parser::getClassesFromFile(codecept_data_dir('unsetFile.php'));
$this->assertEquals([], $classes);
}
/**
* @group core
* @throws \Codeception\Exception\TestParseException
*/
public function testModernValidation()
{
if (PHP_MAJOR_VERSION < 7) {
$this->markTestSkipped();
}
$this->setExpectedException('Codeception\Exception\TestParseException');
Parser::load(codecept_data_dir('Invalid.php'));
}
/**
* @group core
*/
public function testClassesFromFile()
{
$classes = Parser::getClassesFromFile(codecept_data_dir('DummyClass.php'));
$this->assertContains('DummyClass', $classes);
$classes = Parser::getClassesFromFile(codecept_data_dir('SimpleWithDependencyInjectionCest.php'));
$this->assertContains('simpleDI\\LoadedTestWithDependencyInjectionCest', $classes);
$this->assertContains('simpleDI\\AnotherCest', $classes);
}
}
| djc1103617718/weMedia | vendor/codeception/base/tests/unit/Codeception/Lib/ParserTest.php | PHP | bsd-3-clause | 5,495 |
import random
from sympy import Integer, Matrix, Rational, sqrt, symbols
from sympy.core.compatibility import range
from sympy.physics.quantum.qubit import (measure_all, measure_partial,
matrix_to_qubit, matrix_to_density,
qubit_to_matrix, IntQubit,
IntQubitBra, QubitBra)
from sympy.physics.quantum.gate import (HadamardGate, CNOT, XGate, YGate,
ZGate, PhaseGate)
from sympy.physics.quantum.qapply import qapply
from sympy.physics.quantum.represent import represent
from sympy.physics.quantum.shor import Qubit
from sympy.utilities.pytest import raises
from sympy.physics.quantum.density import Density
from sympy.core.trace import Tr
x, y = symbols('x,y')
epsilon = .000001
def test_Qubit():
array = [0, 0, 1, 1, 0]
qb = Qubit('00110')
assert qb.flip(0) == Qubit('00111')
assert qb.flip(1) == Qubit('00100')
assert qb.flip(4) == Qubit('10110')
assert qb.qubit_values == (0, 0, 1, 1, 0)
assert qb.dimension == 5
for i in range(5):
assert qb[i] == array[4 - i]
assert len(qb) == 5
qb = Qubit('110')
def test_QubitBra():
qb = Qubit(0)
qb_bra = QubitBra(0)
assert qb.dual_class() == QubitBra
assert qb_bra.dual_class() == Qubit
qb = Qubit(1, 1, 0)
qb_bra = QubitBra(1, 1, 0)
assert represent(qb, nqubits=3).H == represent(qb_bra, nqubits=3)
qb = Qubit(0, 1)
qb_bra = QubitBra(1,0)
assert qb._eval_innerproduct_QubitBra(qb_bra) == Integer(0)
qb_bra = QubitBra(0, 1)
assert qb._eval_innerproduct_QubitBra(qb_bra) == Integer(1)
def test_IntQubit():
iqb = IntQubit(8)
assert iqb.as_int() == 8
assert iqb.qubit_values == (1, 0, 0, 0)
iqb = IntQubit(7, 4)
assert iqb.qubit_values == (0, 1, 1, 1)
assert IntQubit(3) == IntQubit(3, 2)
#test Dual Classes
iqb = IntQubit(3)
iqb_bra = IntQubitBra(3)
assert iqb.dual_class() == IntQubitBra
assert iqb_bra.dual_class() == IntQubit
iqb = IntQubit(5)
iqb_bra = IntQubitBra(5)
assert iqb._eval_innerproduct_IntQubitBra(iqb_bra) == Integer(1)
iqb = IntQubit(4)
iqb_bra = IntQubitBra(5)
assert iqb._eval_innerproduct_IntQubitBra(iqb_bra) == Integer(0)
raises(ValueError, lambda: IntQubit(4, 1))
def test_superposition_of_states():
state = 1/sqrt(2)*Qubit('01') + 1/sqrt(2)*Qubit('10')
state_gate = CNOT(0, 1)*HadamardGate(0)*state
state_expanded = Qubit('01')/2 + Qubit('00')/2 - Qubit('11')/2 + Qubit('10')/2
assert qapply(state_gate).expand() == state_expanded
assert matrix_to_qubit(represent(state_gate, nqubits=2)) == state_expanded
#test apply methods
def test_apply_represent_equality():
gates = [HadamardGate(int(3*random.random())),
XGate(int(3*random.random())), ZGate(int(3*random.random())),
YGate(int(3*random.random())), ZGate(int(3*random.random())),
PhaseGate(int(3*random.random()))]
circuit = Qubit(int(random.random()*2), int(random.random()*2),
int(random.random()*2), int(random.random()*2), int(random.random()*2),
int(random.random()*2))
for i in range(int(random.random()*6)):
circuit = gates[int(random.random()*6)]*circuit
mat = represent(circuit, nqubits=6)
states = qapply(circuit)
state_rep = matrix_to_qubit(mat)
states = states.expand()
state_rep = state_rep.expand()
assert state_rep == states
def test_matrix_to_qubits():
qb = Qubit(0, 0, 0, 0)
mat = Matrix([1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
assert matrix_to_qubit(mat) == qb
assert qubit_to_matrix(qb) == mat
state = 2*sqrt(2)*(Qubit(0, 0, 0) + Qubit(0, 0, 1) + Qubit(0, 1, 0) +
Qubit(0, 1, 1) + Qubit(1, 0, 0) + Qubit(1, 0, 1) +
Qubit(1, 1, 0) + Qubit(1, 1, 1))
ones = sqrt(2)*2*Matrix([1, 1, 1, 1, 1, 1, 1, 1])
assert matrix_to_qubit(ones) == state.expand()
assert qubit_to_matrix(state) == ones
def test_measure_normalize():
a, b = symbols('a b')
state = a*Qubit('110') + b*Qubit('111')
assert measure_partial(state, (0,), normalize=False) == \
[(a*Qubit('110'), a*a.conjugate()), (b*Qubit('111'), b*b.conjugate())]
assert measure_all(state, normalize=False) == \
[(Qubit('110'), a*a.conjugate()), (Qubit('111'), b*b.conjugate())]
def test_measure_partial():
#Basic test of collapse of entangled two qubits (Bell States)
state = Qubit('01') + Qubit('10')
assert measure_partial(state, (0,)) == \
[(Qubit('10'), Rational(1, 2)), (Qubit('01'), Rational(1, 2))]
assert measure_partial(state, (0,)) == \
measure_partial(state, (1,))[::-1]
#Test of more complex collapse and probability calculation
state1 = sqrt(2)/sqrt(3)*Qubit('00001') + 1/sqrt(3)*Qubit('11111')
assert measure_partial(state1, (0,)) == \
[(sqrt(2)/sqrt(3)*Qubit('00001') + 1/sqrt(3)*Qubit('11111'), 1)]
assert measure_partial(state1, (1, 2)) == measure_partial(state1, (3, 4))
assert measure_partial(state1, (1, 2, 3)) == \
[(Qubit('00001'), Rational(2, 3)), (Qubit('11111'), Rational(1, 3))]
#test of measuring multiple bits at once
state2 = Qubit('1111') + Qubit('1101') + Qubit('1011') + Qubit('1000')
assert measure_partial(state2, (0, 1, 3)) == \
[(Qubit('1000'), Rational(1, 4)), (Qubit('1101'), Rational(1, 4)),
(Qubit('1011')/sqrt(2) + Qubit('1111')/sqrt(2), Rational(1, 2))]
assert measure_partial(state2, (0,)) == \
[(Qubit('1000'), Rational(1, 4)),
(Qubit('1111')/sqrt(3) + Qubit('1101')/sqrt(3) +
Qubit('1011')/sqrt(3), Rational(3, 4))]
def test_measure_all():
assert measure_all(Qubit('11')) == [(Qubit('11'), 1)]
state = Qubit('11') + Qubit('10')
assert measure_all(state) == [(Qubit('10'), Rational(1, 2)),
(Qubit('11'), Rational(1, 2))]
state2 = Qubit('11')/sqrt(5) + 2*Qubit('00')/sqrt(5)
assert measure_all(state2) == \
[(Qubit('00'), Rational(4, 5)), (Qubit('11'), Rational(1, 5))]
def test_eval_trace():
q1 = Qubit('10110')
q2 = Qubit('01010')
d = Density([q1, 0.6], [q2, 0.4])
t = Tr(d)
assert t.doit() == 1
# extreme bits
t = Tr(d, 0)
assert t.doit() == (0.4*Density([Qubit('0101'), 1]) +
0.6*Density([Qubit('1011'), 1]))
t = Tr(d, 4)
assert t.doit() == (0.4*Density([Qubit('1010'), 1]) +
0.6*Density([Qubit('0110'), 1]))
# index somewhere in between
t = Tr(d, 2)
assert t.doit() == (0.4*Density([Qubit('0110'), 1]) +
0.6*Density([Qubit('1010'), 1]))
#trace all indices
t = Tr(d, [0, 1, 2, 3, 4])
assert t.doit() == 1
# trace some indices, initialized in
# non-canonical order
t = Tr(d, [2, 1, 3])
assert t.doit() == (0.4*Density([Qubit('00'), 1]) +
0.6*Density([Qubit('10'), 1]))
# mixed states
q = (1/sqrt(2)) * (Qubit('00') + Qubit('11'))
d = Density( [q, 1.0] )
t = Tr(d, 0)
assert t.doit() == (0.5*Density([Qubit('0'), 1]) +
0.5*Density([Qubit('1'), 1]))
def test_matrix_to_density():
mat = Matrix([[0, 0], [0, 1]])
assert matrix_to_density(mat) == Density([Qubit('1'), 1])
mat = Matrix([[1, 0], [0, 0]])
assert matrix_to_density(mat) == Density([Qubit('0'), 1])
mat = Matrix([[0, 0], [0, 0]])
assert matrix_to_density(mat) == 0
mat = Matrix([[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 0]])
assert matrix_to_density(mat) == Density([Qubit('10'), 1])
mat = Matrix([[1, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]])
assert matrix_to_density(mat) == Density([Qubit('00'), 1])
| ga7g08/sympy | sympy/physics/quantum/tests/test_qubit.py | Python | bsd-3-clause | 7,934 |
/*! UIkit 2.24.0 | http://www.getuikit.com | (c) 2014 YOOtheme | MIT License */
!function(t){var i;window.UIkit&&(i=t(UIkit)),"function"==typeof define&&define.amd&&define("uikit-slider",["uikit"],function(){return i||t(UIkit)})}(function(t){"use strict";var i,e,s,n,a={};return t.component("slider",{defaults:{center:!1,threshold:10,infinite:!0,autoplay:!1,autoplayInterval:7e3,pauseOnHover:!0,activecls:"uk-active"},boot:function(){t.ready(function(i){setTimeout(function(){t.$("[data-uk-slider]",i).each(function(){var i=t.$(this);i.data("slider")||t.slider(i,t.Utils.options(i.attr("data-uk-slider")))})},0)})},init:function(){var o=this;this.container=this.element.find(".uk-slider"),this.focus=0,t.$win.on("resize load",t.Utils.debounce(function(){o.resize(!0)},100)),this.on("click.uikit.slider","[data-uk-slider-item]",function(i){i.preventDefault();var e=t.$(this).attr("data-uk-slider-item");if(o.focus!=e)switch(o.stop(),e){case"next":case"previous":o["next"==e?"next":"previous"]();break;default:o.updateFocus(parseInt(e,10))}}),this.container.on({"touchstart mousedown":function(h){h.originalEvent&&h.originalEvent.touches&&(h=h.originalEvent.touches[0]),h.button&&2==h.button||!o.active||(o.stop(),s=t.$(h.target).is("a")?t.$(h.target):t.$(h.target).parents("a:first"),n=!1,s.length&&s.one("click",function(t){n&&t.preventDefault()}),e=function(t){n=!0,i=o,a={touchx:parseInt(t.pageX,10),dir:1,focus:o.focus,base:o.options.center?"center":"area"},t.originalEvent&&t.originalEvent.touches&&(t=t.originalEvent.touches[0]),i.element.data({"pointer-start":{x:parseInt(t.pageX,10),y:parseInt(t.pageY,10)},"pointer-pos-start":o.pos}),o.container.addClass("uk-drag"),e=!1},e.x=parseInt(h.pageX,10),e.threshold=o.options.threshold)},mouseenter:function(){o.options.pauseOnHover&&(o.hovering=!0)},mouseleave:function(){o.hovering=!1}}),this.resize(!0),this.on("display.uk.check",function(){o.element.is(":visible")&&o.resize(!0)}),this.element.find("a,img").attr("draggable","false"),this.options.autoplay&&this.start()},resize:function(i){var e,s,n,a,o=this,h=0,r=0;return this.items=this.container.children().filter(":visible"),this.vp=this.element[0].getBoundingClientRect().width,this.container.css({"min-width":"","min-height":""}),this.items.each(function(i){e=t.$(this),a=e.css({left:"",width:""})[0].getBoundingClientRect(),s=a.width,n=e.width(),r=Math.max(r,a.height),e.css({left:h,width:s}).data({idx:i,left:h,width:s,cwidth:n,area:h+s,center:h-(o.vp/2-n/2)}),h+=s}),this.container.css({"min-width":h,"min-height":r}),this.options.infinite&&h<=2*this.vp&&!this.itemsResized?(this.container.children().each(function(t){o.container.append(o.items.eq(t).clone(!0).attr("id",""))}).each(function(t){o.container.append(o.items.eq(t).clone(!0).attr("id",""))}),this.itemsResized=!0,this.resize()):(this.cw=h,this.pos=0,this.active=h>=this.vp,this.container.css({"-ms-transform":"","-webkit-transform":"",transform:""}),i&&this.updateFocus(this.focus),void 0)},updatePos:function(t){this.pos=t,this.container.css({"-ms-transform":"translateX("+t+"px)","-webkit-transform":"translateX("+t+"px)",transform:"translateX("+t+"px)"})},updateFocus:function(t,i){if(this.active){i=i||(t>this.focus?1:-1);var e,s,n=this.items.eq(t);if(this.options.infinite&&this.infinite(t,i),this.options.center)this.updatePos(-1*n.data("center")),this.items.filter("."+this.options.activecls).removeClass(this.options.activecls),n.addClass(this.options.activecls);else if(this.options.infinite)this.updatePos(-1*n.data("left"));else{for(e=0,s=t;s<this.items.length;s++)e+=this.items.eq(s).data("width");if(e>this.vp)this.updatePos(-1*n.data("left"));else if(1==i){for(e=0,s=this.items.length-1;s>=0;s--){if(e+=this.items.eq(s).data("width"),e==this.vp){t=s;break}if(e>this.vp){t=s<this.items.length-1?s+1:s;break}}e>this.vp?this.updatePos(-1*(this.container.width()-this.vp)):this.updatePos(-1*this.items.eq(t).data("left"))}}this.focus=t,this.trigger("focusitem.uk.slider",[t,this.items.eq(t),this])}},next:function(){var t=this.items[this.focus+1]?this.focus+1:this.options.infinite?0:this.focus;this.updateFocus(t,1)},previous:function(){var t=this.items[this.focus-1]?this.focus-1:this.options.infinite?this.items[this.focus-1]?this.items-1:this.items.length-1:this.focus;this.updateFocus(t,-1)},start:function(){this.stop();var t=this;this.interval=setInterval(function(){t.hovering||t.next()},this.options.autoplayInterval)},stop:function(){this.interval&&clearInterval(this.interval)},infinite:function(t,i){var e,s=this,n=this.items.eq(t),a=t,o=[],h=0;if(1==i){for(e=0;e<this.items.length&&(a!=t&&(h+=this.items.eq(a).data("width"),o.push(this.items.eq(a))),!(h>this.vp));e++)a=a+1==this.items.length?0:a+1;o.length&&o.forEach(function(t){var i=n.data("area");t.css({left:i}).data({left:i,area:i+t.data("width"),center:i-(s.vp/2-t.data("cwidth")/2)}),n=t})}else{for(e=this.items.length-1;e>-1&&(h+=this.items.eq(a).data("width"),a!=t&&o.push(this.items.eq(a)),!(h>this.vp));e--)a=a-1==-1?this.items.length-1:a-1;o.length&&o.forEach(function(t){var i=n.data("left")-t.data("width");t.css({left:i}).data({left:i,area:i+t.data("width"),center:i-(s.vp/2-t.data("cwidth")/2)}),n=t})}}}),t.$doc.on("mousemove.uikit.slider touchmove.uikit.slider",function(t){if(t.originalEvent&&t.originalEvent.touches&&(t=t.originalEvent.touches[0]),e&&Math.abs(t.pageX-e.x)>e.threshold&&(window.getSelection().toString()?i=e=!1:e(t)),i){var s,n,o,h,r,c,f,u,d,l;if(t.clientX||t.clientY?s=t.clientX:(t.pageX||t.pageY)&&(s=t.pageX-document.body.scrollLeft-document.documentElement.scrollLeft),r=a.focus,n=s-i.element.data("pointer-start").x,o=i.element.data("pointer-pos-start")+n,h=s>i.element.data("pointer-start").x?-1:1,c=i.items.eq(a.focus),1==h)for(f=c.data("left")+Math.abs(n),u=0,d=a.focus;u<i.items.length;u++){if(l=i.items.eq(d),d!=a.focus&&l.data("left")<f&&l.data("area")>f){r=d;break}d=d+1==i.items.length?0:d+1}else for(f=c.data("left")-Math.abs(n),u=0,d=a.focus;u<i.items.length;u++){if(l=i.items.eq(d),d!=a.focus&&l.data("area")<=c.data("left")&&l.data("center")<f){r=d;break}d=d-1==-1?i.items.length-1:d-1}i.options.infinite&&r!=a._focus&&i.infinite(r,h),i.updatePos(o),a.dir=h,a._focus=r,a.touchx=parseInt(t.pageX,10),a.diff=f}}),t.$doc.on("mouseup.uikit.slider touchend.uikit.slider",function(){if(i){i.container.removeClass("uk-drag"),i.items.eq(a.focus);var t,s,n,o=!1;if(1==a.dir)for(s=0,n=a.focus;s<i.items.length;s++){if(t=i.items.eq(n),n!=a.focus&&t.data("left")>a.diff){o=n;break}n=n+1==i.items.length?0:n+1}else for(s=0,n=a.focus;s<i.items.length;s++){if(t=i.items.eq(n),n!=a.focus&&t.data("left")<a.diff){o=n;break}n=n-1==-1?i.items.length-1:n-1}i.updateFocus(o!==!1?o:a._focus)}i=e=!1}),t.slider}); | ProNWE/version-1.0 | misteritmo/assest/uikit/js/components/slider.min.js | JavaScript | bsd-3-clause | 6,696 |
/****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtCore module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL21$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qbasictimer.h"
#include "qabstracteventdispatcher.h"
#include "qabstracteventdispatcher_p.h"
QT_BEGIN_NAMESPACE
/*!
\class QBasicTimer
\inmodule QtCore
\brief The QBasicTimer class provides timer events for objects.
\ingroup events
This is a fast, lightweight, and low-level class used by Qt
internally. We recommend using the higher-level QTimer class
rather than this class if you want to use timers in your
applications. Note that this timer is a repeating timer that
will send subsequent timer events unless the stop() function is called.
To use this class, create a QBasicTimer, and call its start()
function with a timeout interval and with a pointer to a QObject
subclass. When the timer times out it will send a timer event to
the QObject subclass. The timer can be stopped at any time using
stop(). isActive() returns \c true for a timer that is running;
i.e. it has been started, has not reached the timeout time, and
has not been stopped. The timer's ID can be retrieved using
timerId().
The \l{widgets/wiggly}{Wiggly} example uses QBasicTimer to repaint
a widget at regular intervals.
\sa QTimer, QTimerEvent, QObject::timerEvent(), Timers, {Wiggly Example}
*/
/*!
\fn QBasicTimer::QBasicTimer()
Contructs a basic timer.
\sa start()
*/
/*!
\fn QBasicTimer::~QBasicTimer()
Destroys the basic timer.
*/
/*!
\fn bool QBasicTimer::isActive() const
Returns \c true if the timer is running and has not been stopped; otherwise
returns \c false.
\sa start(), stop()
*/
/*!
\fn int QBasicTimer::timerId() const
Returns the timer's ID.
\sa QTimerEvent::timerId()
*/
/*!
\fn void QBasicTimer::start(int msec, QObject *object)
Starts (or restarts) the timer with a \a msec milliseconds timeout. The
timer will be a Qt::CoarseTimer. See Qt::TimerType for information on the
different timer types.
The given \a object will receive timer events.
\sa stop(), isActive(), QObject::timerEvent(), Qt::CoarseTimer
*/
void QBasicTimer::start(int msec, QObject *obj)
{
QAbstractEventDispatcher *eventDispatcher = QAbstractEventDispatcher::instance();
if (Q_UNLIKELY(!eventDispatcher)) {
qWarning("QBasicTimer::start: QBasicTimer can only be used with threads started with QThread");
return;
}
if (Q_UNLIKELY(obj && obj->thread() != eventDispatcher->thread())) {
qWarning("QBasicTimer::start: Timers cannot be started from another thread");
return;
}
if (id) {
if (Q_LIKELY(eventDispatcher->unregisterTimer(id)))
QAbstractEventDispatcherPrivate::releaseTimerId(id);
else
qWarning("QBasicTimer::start: Stopping previous timer failed. Possibly trying to stop from a different thread");
}
id = 0;
if (obj)
id = eventDispatcher->registerTimer(msec, Qt::CoarseTimer, obj);
}
/*!
\overload
Starts (or restarts) the timer with a \a msec milliseconds timeout and the
given \a timerType. See Qt::TimerType for information on the different
timer types.
\a obj will receive timer events.
\sa stop(), isActive(), QObject::timerEvent(), Qt::TimerType
*/
void QBasicTimer::start(int msec, Qt::TimerType timerType, QObject *obj)
{
QAbstractEventDispatcher *eventDispatcher = QAbstractEventDispatcher::instance();
if (Q_UNLIKELY(msec < 0)) {
qWarning("QBasicTimer::start: Timers cannot have negative timeouts");
return;
}
if (Q_UNLIKELY(!eventDispatcher)) {
qWarning("QBasicTimer::start: QBasicTimer can only be used with threads started with QThread");
return;
}
if (Q_UNLIKELY(obj && obj->thread() != eventDispatcher->thread())) {
qWarning("QBasicTimer::start: Timers cannot be started from another thread");
return;
}
if (id) {
if (Q_LIKELY(eventDispatcher->unregisterTimer(id)))
QAbstractEventDispatcherPrivate::releaseTimerId(id);
else
qWarning("QBasicTimer::start: Stopping previous timer failed. Possibly trying to stop from a different thread");
}
id = 0;
if (obj)
id = eventDispatcher->registerTimer(msec, timerType, obj);
}
/*!
Stops the timer.
\sa start(), isActive()
*/
void QBasicTimer::stop()
{
if (id) {
QAbstractEventDispatcher *eventDispatcher = QAbstractEventDispatcher::instance();
if (eventDispatcher) {
if (Q_UNLIKELY(!eventDispatcher->unregisterTimer(id))) {
qWarning("QBasicTimer::stop: Failed. Possibly trying to stop from a different thread");
return;
}
QAbstractEventDispatcherPrivate::releaseTimerId(id);
}
}
id = 0;
}
QT_END_NAMESPACE
| martonw/phantomjs | src/qt/qtbase/src/corelib/kernel/qbasictimer.cpp | C++ | bsd-3-clause | 6,417 |
using Orchard.Layouts.Elements;
using Orchard.Layouts.Framework.Display;
using Orchard.Layouts.Framework.Drivers;
using Orchard.Layouts.Helpers;
using Orchard.Layouts.Services;
using Orchard.Layouts.ViewModels;
namespace Orchard.Layouts.Drivers {
public class HeadingElementDriver : ElementDriver<Heading> {
private readonly IElementFilterProcessor _processor;
public HeadingElementDriver(IElementFilterProcessor processor) {
_processor = processor;
}
protected override EditorResult OnBuildEditor(Heading element, ElementEditorContext context) {
var viewModel = new HeadingEditorViewModel {
Text = element.Content,
Level = element.Level
};
var editor = context.ShapeFactory.EditorTemplate(TemplateName: "Elements.Heading", Model: viewModel);
if (context.Updater != null) {
context.Updater.TryUpdateModel(viewModel, context.Prefix, null, null);
element.Content = viewModel.Text;
element.Level = viewModel.Level;
}
return Editor(context, editor);
}
protected override void OnDisplaying(Heading element, ElementDisplayingContext context) {
context.ElementShape.ProcessedContent = _processor.ProcessContent(element.Content, "html", context.GetTokenData());
context.ElementShape.Level = element.Level;
}
}
} | xiaobudian/Orchard | src/Orchard.Web/Modules/Orchard.Layouts/Drivers/HeadingElementDriver.cs | C# | bsd-3-clause | 1,476 |
/**
* The examples provided by Facebook are for non-commercial testing and
* evaluation purposes only.
*
* Facebook reserves all rights not expressly granted.
*
* 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 NON INFRINGEMENT. IN NO EVENT SHALL
* FACEBOOK 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 <XCTest/XCTest.h>
#import "RCTConvert.h"
@interface RCTConvert_UIFontTests : XCTestCase
@end
@implementation RCTConvert_UIFontTests
#define RCTAssertEqualFonts(font1, font2) { \
XCTAssertEqualObjects(font1, font2); \
}
- (void)testWeight
{
{
UIFont *expected = [UIFont systemFontOfSize:14 weight:UIFontWeightBold];
UIFont *result = [RCTConvert UIFont:@{@"fontWeight": @"bold"}];
RCTAssertEqualFonts(expected, result);
}
{
UIFont *expected = [UIFont systemFontOfSize:14 weight:UIFontWeightMedium];
UIFont *result = [RCTConvert UIFont:@{@"fontWeight": @"500"}];
RCTAssertEqualFonts(expected, result);
}
{
UIFont *expected = [UIFont systemFontOfSize:14 weight:UIFontWeightUltraLight];
UIFont *result = [RCTConvert UIFont:@{@"fontWeight": @"100"}];
RCTAssertEqualFonts(expected, result);
}
{
UIFont *expected = [UIFont systemFontOfSize:14 weight:UIFontWeightRegular];
UIFont *result = [RCTConvert UIFont:@{@"fontWeight": @"normal"}];
RCTAssertEqualFonts(expected, result);
}
}
- (void)testSize
{
{
UIFont *expected = [UIFont systemFontOfSize:18.5];
UIFont *result = [RCTConvert UIFont:@{@"fontSize": @18.5}];
RCTAssertEqualFonts(expected, result);
}
}
- (void)testFamily
{
{
UIFont *expected = [UIFont fontWithName:@"Cochin" size:14];
UIFont *result = [RCTConvert UIFont:@{@"fontFamily": @"Cochin"}];
RCTAssertEqualFonts(expected, result);
}
{
UIFont *expected = [UIFont fontWithName:@"HelveticaNeue" size:14];
UIFont *result = [RCTConvert UIFont:@{@"fontFamily": @"Helvetica Neue"}];
RCTAssertEqualFonts(expected, result);
}
{
UIFont *expected = [UIFont fontWithName:@"HelveticaNeue-Italic" size:14];
UIFont *result = [RCTConvert UIFont:@{@"fontFamily": @"HelveticaNeue-Italic"}];
RCTAssertEqualFonts(expected, result);
}
}
- (void)testStyle
{
{
UIFont *font = [UIFont systemFontOfSize:14];
UIFontDescriptor *fontDescriptor = [font fontDescriptor];
UIFontDescriptorSymbolicTraits symbolicTraits = fontDescriptor.symbolicTraits;
symbolicTraits |= UIFontDescriptorTraitItalic;
fontDescriptor = [fontDescriptor fontDescriptorWithSymbolicTraits:symbolicTraits];
UIFont *expected = [UIFont fontWithDescriptor:fontDescriptor size:14];
UIFont *result = [RCTConvert UIFont:@{@"fontStyle": @"italic"}];
RCTAssertEqualFonts(expected, result);
}
{
UIFont *expected = [UIFont systemFontOfSize:14];
UIFont *result = [RCTConvert UIFont:@{@"fontStyle": @"normal"}];
RCTAssertEqualFonts(expected, result);
}
}
- (void)testStyleAndWeight
{
{
UIFont *font = [UIFont systemFontOfSize:14 weight:UIFontWeightUltraLight];
UIFontDescriptor *fontDescriptor = [font fontDescriptor];
UIFontDescriptorSymbolicTraits symbolicTraits = fontDescriptor.symbolicTraits;
symbolicTraits |= UIFontDescriptorTraitItalic;
fontDescriptor = [fontDescriptor fontDescriptorWithSymbolicTraits:symbolicTraits];
UIFont *expected = [UIFont fontWithDescriptor:fontDescriptor size:14];
UIFont *result = [RCTConvert UIFont:@{@"fontStyle": @"italic", @"fontWeight": @"100"}];
RCTAssertEqualFonts(expected, result);
}
{
UIFont *font = [UIFont systemFontOfSize:14 weight:UIFontWeightBold];
UIFontDescriptor *fontDescriptor = [font fontDescriptor];
UIFontDescriptorSymbolicTraits symbolicTraits = fontDescriptor.symbolicTraits;
symbolicTraits |= UIFontDescriptorTraitItalic;
fontDescriptor = [fontDescriptor fontDescriptorWithSymbolicTraits:symbolicTraits];
UIFont *expected = [UIFont fontWithDescriptor:fontDescriptor size:14];
UIFont *result = [RCTConvert UIFont:@{@"fontStyle": @"italic", @"fontWeight": @"bold"}];
RCTAssertEqualFonts(expected, result);
}
}
- (void)testFamilyAndWeight
{
{
UIFont *expected = [UIFont fontWithName:@"HelveticaNeue-Bold" size:14];
UIFont *result = [RCTConvert UIFont:@{@"fontFamily": @"Helvetica Neue", @"fontWeight": @"bold"}];
RCTAssertEqualFonts(expected, result);
}
{
UIFont *expected = [UIFont fontWithName:@"HelveticaNeue" size:14];
UIFont *result = [RCTConvert UIFont:@{@"fontFamily": @"HelveticaNeue-Bold", @"fontWeight": @"normal"}];
RCTAssertEqualFonts(expected, result);
}
{
UIFont *expected = [UIFont fontWithName:@"Cochin-Bold" size:14];
UIFont *result = [RCTConvert UIFont:@{@"fontFamily": @"Cochin", @"fontWeight": @"700"}];
RCTAssertEqualFonts(expected, result);
}
{
UIFont *expected = [UIFont fontWithName:@"Cochin" size:14];
UIFont *result = [RCTConvert UIFont:@{@"fontFamily": @"Cochin", @"fontWeight": @"100"}];
RCTAssertEqualFonts(expected, result);
}
}
- (void)testFamilyAndStyle
{
{
UIFont *expected = [UIFont fontWithName:@"HelveticaNeue-Italic" size:14];
UIFont *result = [RCTConvert UIFont:@{@"fontFamily": @"Helvetica Neue", @"fontStyle": @"italic"}];
RCTAssertEqualFonts(expected, result);
}
{
UIFont *expected = [UIFont fontWithName:@"HelveticaNeue" size:14];
UIFont *result = [RCTConvert UIFont:@{@"fontFamily": @"HelveticaNeue-Italic", @"fontStyle": @"normal"}];
RCTAssertEqualFonts(expected, result);
}
}
- (void)testFamilyStyleAndWeight
{
{
UIFont *expected = [UIFont fontWithName:@"HelveticaNeue-LightItalic" size:14];
UIFont *result = [RCTConvert UIFont:@{@"fontFamily": @"Helvetica Neue", @"fontStyle": @"italic", @"fontWeight": @"300"}];
RCTAssertEqualFonts(expected, result);
}
{
UIFont *expected = [UIFont fontWithName:@"HelveticaNeue-Bold" size:14];
UIFont *result = [RCTConvert UIFont:@{@"fontFamily": @"HelveticaNeue-Italic", @"fontStyle": @"normal", @"fontWeight": @"bold"}];
RCTAssertEqualFonts(expected, result);
}
{
UIFont *expected = [UIFont fontWithName:@"HelveticaNeue" size:14];
UIFont *result = [RCTConvert UIFont:@{@"fontFamily": @"HelveticaNeue-Italic", @"fontStyle": @"normal", @"fontWeight": @"normal"}];
RCTAssertEqualFonts(expected, result);
}
}
- (void)testInvalidFont
{
{
UIFont *expected = [UIFont systemFontOfSize:14];
UIFont *result = [RCTConvert UIFont:@{@"fontFamily": @"foobar"}];
RCTAssertEqualFonts(expected, result);
}
{
UIFont *expected = [UIFont systemFontOfSize:14 weight:UIFontWeightBold];
UIFont *result = [RCTConvert UIFont:@{@"fontFamily": @"foobar", @"fontWeight": @"bold"}];
RCTAssertEqualFonts(expected, result);
}
}
@end
| YueRuo/react-native | Examples/UIExplorer/UIExplorerUnitTests/RCTConvert_UIFontTests.m | Matlab | bsd-3-clause | 7,058 |
/*
DJANGO Admin styles
*/
body {
margin: 0;
padding: 0;
font-size: 12px;
font-family: "Lucida Grande","DejaVu Sans","Bitstream Vera Sans",Verdana,Arial,sans-serif;
color: #333;
background: #fff;
}
/* LINKS */
a:link, a:visited {
color: #5b80b2;
text-decoration: none;
}
a:hover {
color: #036;
}
a img {
border: none;
}
a.section:link, a.section:visited {
color: #fff;
text-decoration: none;
}
/* GLOBAL DEFAULTS */
p, ol, ul, dl {
margin: .2em 0 .8em 0;
}
p {
padding: 0;
line-height: 140%;
}
h1,h2,h3,h4,h5 {
font-weight: bold;
}
h1 {
font-size: 18px;
color: #666;
padding: 0 6px 0 0;
margin: 0 0 .2em 0;
}
h2 {
font-size: 16px;
margin: 1em 0 .5em 0;
}
h2.subhead {
font-weight: normal;
margin-top: 0;
}
h3 {
font-size: 14px;
margin: .8em 0 .3em 0;
color: #666;
font-weight: bold;
}
h4 {
font-size: 12px;
margin: 1em 0 .8em 0;
padding-bottom: 3px;
}
h5 {
font-size: 10px;
margin: 1.5em 0 .5em 0;
color: #666;
text-transform: uppercase;
letter-spacing: 1px;
}
ul li {
list-style-type: square;
padding: 1px 0;
}
ul.plainlist {
margin-left: 0 !important;
}
ul.plainlist li {
list-style-type: none;
}
li ul {
margin-bottom: 0;
}
li, dt, dd {
font-size: 11px;
line-height: 14px;
}
dt {
font-weight: bold;
margin-top: 4px;
}
dd {
margin-left: 0;
}
form {
margin: 0;
padding: 0;
}
fieldset {
margin: 0;
padding: 0;
}
blockquote {
font-size: 11px;
color: #777;
margin-left: 2px;
padding-left: 10px;
border-left: 5px solid #ddd;
}
code, pre {
font-family: "Bitstream Vera Sans Mono", Monaco, "Courier New", Courier, monospace;
color: #666;
font-size: 11px;
}
pre.literal-block {
margin: 10px;
background: #eee;
padding: 6px 8px;
}
code strong {
color: #930;
}
hr {
clear: both;
color: #eee;
background-color: #eee;
height: 1px;
border: none;
margin: 0;
padding: 0;
font-size: 1px;
line-height: 1px;
}
/* TEXT STYLES & MODIFIERS */
.small {
font-size: 11px;
}
.tiny {
font-size: 10px;
}
p.tiny {
margin-top: -2px;
}
.mini {
font-size: 9px;
}
p.mini {
margin-top: -3px;
}
.help, p.help {
font-size: 10px !important;
color: #999;
}
img.help-tooltip {
cursor: help;
}
p img, h1 img, h2 img, h3 img, h4 img, td img {
vertical-align: middle;
}
.quiet, a.quiet:link, a.quiet:visited {
color: #999 !important;
font-weight: normal !important;
}
.quiet strong {
font-weight: bold !important;
}
.float-right {
float: right;
}
.float-left {
float: left;
}
.clear {
clear: both;
}
.align-left {
text-align: left;
}
.align-right {
text-align: right;
}
.example {
margin: 10px 0;
padding: 5px 10px;
background: #efefef;
}
.nowrap {
white-space: nowrap;
}
/* TABLES */
table {
border-collapse: collapse;
border-color: #ccc;
}
td, th {
font-size: 11px;
line-height: 13px;
border-bottom: 1px solid #eee;
vertical-align: top;
padding: 5px;
font-family: "Lucida Grande", Verdana, Arial, sans-serif;
}
th {
text-align: left;
font-size: 12px;
font-weight: bold;
}
thead th,
tfoot td {
color: #666;
padding: 2px 5px;
font-size: 11px;
background: #e1e1e1 url(../img/nav-bg.gif) top left repeat-x;
border-left: 1px solid #ddd;
border-bottom: 1px solid #ddd;
}
tfoot td {
border-bottom: none;
border-top: 1px solid #ddd;
}
thead th:first-child,
tfoot td:first-child {
border-left: none !important;
}
thead th.optional {
font-weight: normal !important;
}
fieldset table {
border-right: 1px solid #eee;
}
tr.row-label td {
font-size: 9px;
padding-top: 2px;
padding-bottom: 0;
border-bottom: none;
color: #666;
margin-top: -1px;
}
tr.alt {
background: #f6f6f6;
}
.row1 {
background: #EDF3FE;
}
.row2 {
background: #fff;
}
/* SORTABLE TABLES */
thead th {
padding: 2px 5px;
line-height: normal;
}
thead th a:link, thead th a:visited {
color: #666;
}
thead th.sorted {
background: #c5c5c5 url(../img/nav-bg-selected.gif) top left repeat-x;
}
thead th.sorted .text {
padding-right: 42px;
}
table thead th .text span {
padding: 2px 5px;
display:block;
}
table thead th .text a {
display: block;
cursor: pointer;
padding: 2px 5px;
}
table thead th.sortable:hover {
background: #fff url(../img/nav-bg-reverse.gif) 0 -5px repeat-x;
}
thead th.sorted a.sortremove {
visibility: hidden;
}
table thead th.sorted:hover a.sortremove {
visibility: visible;
}
table thead th.sorted .sortoptions {
display: block;
padding: 4px 5px 0 5px;
float: right;
text-align: right;
}
table thead th.sorted .sortpriority {
font-size: .8em;
min-width: 12px;
text-align: center;
vertical-align: top;
}
table thead th.sorted .sortoptions a {
width: 14px;
height: 12px;
display: inline-block;
}
table thead th.sorted .sortoptions a.sortremove {
background: url(../img/sorting-icons.gif) -4px -5px no-repeat;
}
table thead th.sorted .sortoptions a.sortremove:hover {
background: url(../img/sorting-icons.gif) -4px -27px no-repeat;
}
table thead th.sorted .sortoptions a.ascending {
background: url(../img/sorting-icons.gif) -5px -50px no-repeat;
}
table thead th.sorted .sortoptions a.ascending:hover {
background: url(../img/sorting-icons.gif) -5px -72px no-repeat;
}
table thead th.sorted .sortoptions a.descending {
background: url(../img/sorting-icons.gif) -5px -94px no-repeat;
}
table thead th.sorted .sortoptions a.descending:hover {
background: url(../img/sorting-icons.gif) -5px -115px no-repeat;
}
/* ORDERABLE TABLES */
table.orderable tbody tr td:hover {
cursor: move;
}
table.orderable tbody tr td:first-child {
padding-left: 14px;
background-image: url(../img/nav-bg-grabber.gif);
background-repeat: repeat-y;
}
table.orderable-initalized .order-cell, body>tr>td.order-cell {
display: none;
}
/* FORM DEFAULTS */
input, textarea, select, .form-row p, form .button {
margin: 2px 0;
padding: 2px 3px;
vertical-align: middle;
font-family: "Lucida Grande", Verdana, Arial, sans-serif;
font-weight: normal;
font-size: 11px;
}
textarea {
vertical-align: top !important;
}
input[type=text], input[type=password], input[type=email], input[type=url], input[type=number],
textarea, select, .vTextField {
border: 1px solid #ccc;
}
/* FORM BUTTONS */
.button, input[type=submit], input[type=button], .submit-row input, a.button {
background: #fff url(../img/nav-bg.gif) bottom repeat-x;
padding: 3px 5px;
color: black;
border: 1px solid #bbb;
border-color: #ddd #aaa #aaa #ddd;
}
a.button {
padding: 4px 5px;
}
.button:active, input[type=submit]:active, input[type=button]:active {
background-image: url(../img/nav-bg-reverse.gif);
background-position: top;
}
.button[disabled], input[type=submit][disabled], input[type=button][disabled] {
background-image: url(../img/nav-bg.gif);
background-position: bottom;
opacity: 0.4;
}
.button.default, input[type=submit].default, .submit-row input.default {
border: 2px solid #5b80b2;
background: #7CA0C7 url(../img/default-bg.gif) bottom repeat-x;
font-weight: bold;
color: #fff;
float: right;
}
.button.default:active, input[type=submit].default:active {
background-image: url(../img/default-bg-reverse.gif);
background-position: top;
}
.button[disabled].default, input[type=submit][disabled].default, input[type=button][disabled].default {
background-image: url(../img/default-bg.gif);
background-position: bottom;
opacity: 0.4;
}
/* MODULES */
.module {
border: 1px solid #ccc;
margin-bottom: 5px;
background: #fff;
}
.module p, .module ul, .module h3, .module h4, .module dl, .module pre {
padding-left: 10px;
padding-right: 10px;
}
.module blockquote {
margin-left: 12px;
}
.module ul, .module ol {
margin-left: 1.5em;
}
.module h3 {
margin-top: .6em;
}
.module h2, .module caption, .inline-group h2 {
margin: 0;
padding: 2px 5px 3px 5px;
font-size: 11px;
text-align: left;
font-weight: bold;
background: #7CA0C7 url(../img/default-bg.gif) top left repeat-x;
color: #fff;
}
.module table {
border-collapse: collapse;
}
/* MESSAGES & ERRORS */
ul.messagelist {
padding: 0;
margin: 0;
}
ul.messagelist li {
font-size: 12px;
font-weight: bold;
display: block;
padding: 5px 5px 4px 25px;
margin: 0 0 3px 0;
border-bottom: 1px solid #ddd;
color: #666;
background: #dfd url(../img/icon_success.gif) 5px .3em no-repeat;
}
ul.messagelist li.warning {
background: #ffc url(../img/icon_alert.gif) 5px .3em no-repeat;
}
ul.messagelist li.error {
background: #ffefef url(../img/icon_error.gif) 5px .3em no-repeat;
}
.errornote {
font-size: 12px !important;
font-weight: bold;
display: block;
padding: 5px 5px 4px 25px;
margin: 0 0 3px 0;
border: 1px solid #c22;
color: #c11;
background: #ffefef url(../img/icon_error.gif) 5px .38em no-repeat;
}
.errornote, ul.errorlist {
border-radius: 1px;
}
ul.errorlist {
margin: 0 0 4px !important;
padding: 0 !important;
color: #fff;
background: #c11;
}
ul.errorlist li {
font-size: 12px !important;
display: block;
padding: 5px 5px 4px 7px;
margin: 3px 0 0 0;
}
ul.errorlist li:first-child {
margin-top: 0;
}
ul.errorlist li a {
color: #fff;
text-decoration: underline;
}
td ul.errorlist {
margin: 0 !important;
padding: 0 !important;
}
td ul.errorlist li {
margin: 0 !important;
}
.errors, .form-row.errors {
background: #ffefef;
}
.form-row.errors {
border: 1px solid #c22;
margin: -1px;
}
.errors input, .errors select, .errors textarea {
border: 1px solid #c11;
}
div.system-message {
background: #ffc;
margin: 10px;
padding: 6px 8px;
font-size: .8em;
}
div.system-message p.system-message-title {
padding: 4px 5px 4px 25px;
margin: 0;
color: #c11;
background: #ffefef url(../img/icon_error.gif) 5px .3em no-repeat;
}
.description {
font-size: 12px;
padding: 5px 0 0 12px;
}
/* BREADCRUMBS */
div.breadcrumbs {
background: #fff url(../img/nav-bg-reverse.gif) 0 -10px repeat-x;
padding: 2px 8px 3px 8px;
font-size: 11px;
color: #999;
border-top: 1px solid #fff;
border-bottom: 1px solid #ddd;
text-align: left;
}
/* ACTION ICONS */
.addlink {
padding-left: 12px;
background: url(../img/icon_addlink.gif) 0 .2em no-repeat;
}
.changelink, .inlinechangelink {
padding-left: 12px;
background: url(../img/icon_changelink.gif) 0 .2em no-repeat;
}
.deletelink {
padding-left: 12px;
background: url(../img/icon_deletelink.gif) 0 .25em no-repeat;
}
a.deletelink:link, a.deletelink:visited {
color: #CC3434;
}
a.deletelink:hover {
color: #993333;
}
/* OBJECT TOOLS */
.object-tools {
font-size: 10px;
font-weight: bold;
font-family: Arial,Helvetica,sans-serif;
padding-left: 0;
float: right;
position: relative;
margin-top: -2.4em;
margin-bottom: -2em;
}
.form-row .object-tools {
margin-top: 5px;
margin-bottom: 5px;
float: none;
height: 2em;
padding-left: 3.5em;
}
.object-tools li {
display: block;
float: left;
margin-left: 5px;
height: 16px;
}
.object-tools a {
border-radius: 15px;
}
.object-tools a:link, .object-tools a:visited {
display: block;
float: left;
color: #fff;
padding: .2em 10px;
background: #999;
}
.object-tools a:hover, .object-tools li:hover a {
background-color: #5b80b2;
}
.object-tools a.viewsitelink, .object-tools a.golink {
background: #999 url(../img/tooltag-arrowright.png) 95% center no-repeat;
padding-right: 26px;
}
.object-tools a.addlink {
background: #999 url(../img/tooltag-add.png) 95% center no-repeat;
padding-right: 26px;
}
/* OBJECT HISTORY */
table#change-history {
width: 100%;
}
table#change-history tbody th {
width: 16em;
}
/* PAGE STRUCTURE */
#container {
position: relative;
width: 100%;
min-width: 760px;
padding: 0;
}
#content {
margin: 10px 15px;
}
#content-main {
float: left;
width: 100%;
}
#content-related {
float: right;
width: 18em;
position: relative;
margin-right: -19em;
}
#footer {
clear: both;
padding: 10px;
}
/* COLUMN TYPES */
.colMS {
margin-right: 20em !important;
}
.colSM {
margin-left: 20em !important;
}
.colSM #content-related {
float: left;
margin-right: 0;
margin-left: -19em;
}
.colSM #content-main {
float: right;
}
.popup .colM {
width: 95%;
}
.subcol {
float: left;
width: 46%;
margin-right: 15px;
}
.dashboard #content {
width: 500px;
}
/* HEADER */
#header {
width: 100%;
background: #417690;
color: #ffc;
overflow: hidden;
}
#header a:link, #header a:visited {
color: #fff;
}
#header a:hover {
text-decoration: underline;
}
#branding {
float: left;
}
#branding h1 {
padding: 0 10px;
font-size: 18px;
margin: 8px 0;
font-weight: normal;
}
#branding h1, #branding h1 a:link, #branding h1 a:visited {
color: #f4f379;
}
#branding h2 {
padding: 0 10px;
font-size: 14px;
margin: -8px 0 8px 0;
font-weight: normal;
color: #ffc;
}
#branding a:hover {
text-decoration: none;
}
#user-tools {
float: right;
padding: 1.2em 10px;
font-size: 11px;
text-align: right;
}
/* SIDEBAR */
#content-related h3 {
font-size: 12px;
color: #666;
margin-bottom: 3px;
}
#content-related h4 {
font-size: 11px;
}
#content-related .module h2 {
background: #eee url(../img/nav-bg.gif) bottom left repeat-x;
color: #666;
}
| ulope/django | django/contrib/admin/static/admin/css/base.css | CSS | bsd-3-clause | 14,049 |
/*
* Copyright 2014 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "gm.h"
#include "SkCanvas.h"
#include "SkRRect.h"
#include "SkPath.h"
class DRRectGM : public skiagm::GM {
public:
DRRectGM() {}
protected:
virtual uint32_t onGetFlags() const SK_OVERRIDE {
return kSkipTiled_Flag;
}
virtual SkString onShortName() SK_OVERRIDE {
return SkString("drrect");
}
virtual SkISize onISize() SK_OVERRIDE {
return SkISize::Make(640, 480);
}
virtual void onDraw(SkCanvas* canvas) SK_OVERRIDE {
SkPaint paint;
paint.setAntiAlias(true);
SkRRect outers[4];
// like squares/circles, to exercise fast-cases in GPU
SkRect r = { 0, 0, 100, 100 };
SkVector radii[4] = {
{ 0, 0 }, { 30, 1 }, { 10, 40 }, { 40, 40 }
};
const SkScalar dx = r.width() + 16;
const SkScalar dy = r.height() + 16;
outers[0].setRect(r);
outers[1].setOval(r);
outers[2].setRectXY(r, 20, 20);
outers[3].setRectRadii(r, radii);
SkRRect inners[5];
r.inset(25, 25);
inners[0].setEmpty();
inners[1].setRect(r);
inners[2].setOval(r);
inners[3].setRectXY(r, 20, 20);
inners[4].setRectRadii(r, radii);
canvas->translate(16, 16);
for (size_t j = 0; j < SK_ARRAY_COUNT(inners); ++j) {
for (size_t i = 0; i < SK_ARRAY_COUNT(outers); ++i) {
canvas->save();
canvas->translate(dx * j, dy * i);
canvas->drawDRRect(outers[i], inners[j], paint);
canvas->restore();
}
}
}
private:
typedef GM INHERITED;
};
DEF_GM( return new DRRectGM; )
| FusionSP/android_external_skia | gm/drrect.cpp | C++ | bsd-3-clause | 1,822 |
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2013 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Cache\Storage\Adapter;
use APCIterator as BaseApcIterator;
use Zend\Cache\Storage\IteratorInterface;
class ApcIterator implements IteratorInterface
{
/**
* The apc storage instance
*
* @var Apc
*/
protected $storage;
/**
* The iterator mode
*
* @var int
*/
protected $mode = IteratorInterface::CURRENT_AS_KEY;
/**
* The base APCIterator instance
*
* @var BaseApcIterator
*/
protected $baseIterator;
/**
* The length of the namespace prefix
*
* @var int
*/
protected $prefixLength;
/**
* Constructor
*
* @param Apc $storage
* @param BaseApcIterator $baseIterator
* @param string $prefix
*/
public function __construct(Apc $storage, BaseApcIterator $baseIterator, $prefix)
{
$this->storage = $storage;
$this->baseIterator = $baseIterator;
$this->prefixLength = strlen($prefix);
}
/**
* Get storage instance
*
* @return Apc
*/
public function getStorage()
{
return $this->storage;
}
/**
* Get iterator mode
*
* @return int Value of IteratorInterface::CURRENT_AS_*
*/
public function getMode()
{
return $this->mode;
}
/**
* Set iterator mode
*
* @param int $mode
* @return ApcIterator Fluent interface
*/
public function setMode($mode)
{
$this->mode = (int) $mode;
return $this;
}
/* Iterator */
/**
* Get current key, value or metadata.
*
* @return mixed
*/
public function current()
{
if ($this->mode == IteratorInterface::CURRENT_AS_SELF) {
return $this;
}
$key = $this->key();
if ($this->mode == IteratorInterface::CURRENT_AS_VALUE) {
return $this->storage->getItem($key);
} elseif ($this->mode == IteratorInterface::CURRENT_AS_METADATA) {
return $this->storage->getMetadata($key);
}
return $key;
}
/**
* Get current key
*
* @return string
*/
public function key()
{
$key = $this->baseIterator->key();
// remove namespace prefix
return substr($key, $this->prefixLength);
}
/**
* Move forward to next element
*
* @return void
*/
public function next()
{
$this->baseIterator->next();
}
/**
* Checks if current position is valid
*
* @return bool
*/
public function valid()
{
return $this->baseIterator->valid();
}
/**
* Rewind the Iterator to the first element.
*
* @return void
*/
public function rewind()
{
return $this->baseIterator->rewind();
}
}
| timmike/test | vendor/ZF2/library/Zend/Cache/Storage/Adapter/ApcIterator.php | PHP | bsd-3-clause | 3,170 |
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2013 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Log\Filter;
use Traversable;
use Zend\Log\Exception;
class Priority implements FilterInterface
{
/**
* @var int
*/
protected $priority;
/**
* @var string
*/
protected $operator;
/**
* Filter logging by $priority. By default, it will accept any log
* event whose priority value is less than or equal to $priority.
*
* @param int|array|Traversable $priority Priority
* @param string $operator Comparison operator
* @return Priority
* @throws Exception\InvalidArgumentException
*/
public function __construct($priority, $operator = null)
{
if ($priority instanceof Traversable) {
$priority = iterator_to_array($priority);
}
if (is_array($priority)) {
$operator = isset($priority['operator']) ? $priority['operator'] : null;
$priority = isset($priority['priority']) ? $priority['priority'] : null;
}
if (!is_int($priority)) {
throw new Exception\InvalidArgumentException(sprintf(
'Priority must be an integer; received "%s"',
gettype($priority)
));
}
$this->priority = $priority;
$this->operator = $operator === null ? '<=' : $operator;
}
/**
* Returns TRUE to accept the message, FALSE to block it.
*
* @param array $event event data
* @return bool accepted?
*/
public function filter(array $event)
{
return version_compare($event['priority'], $this->priority, $this->operator);
}
}
| fjcorona/modeloybd2 | vendor/zendframework/zendframework/library/Zend/Log/Filter/Priority.php | PHP | bsd-3-clause | 1,910 |
/**
* jQuery Yii plugin file.
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @link http://www.yiiframework.com/
* @copyright Copyright © 2008-2010 Yii Software LLC
* @license http://www.yiiframework.com/license/
* @version $Id$
*/
;(function($) {
$.extend($.fn, {
yiitab: function() {
function activate(id) {
var pos = id.indexOf("#");
if (pos>=0) {
id = id.substring(pos);
}
var $tab=$(id);
var $container=$tab.parent();
$container.find('>ul a').removeClass('active');
$container.find('>ul a[href="'+id+'"]').addClass('active');
$container.children('div').hide();
$tab.show();
}
this.find('>ul a').click(function(event) {
var href=$(this).attr('href');
var pos=href.indexOf('#');
activate(href);
if(pos==0 || (pos>0 && (window.location.pathname=='' || window.location.pathname==href.substring(0,pos))))
return false;
});
// activate a tab based on the current anchor
var url = decodeURI(window.location);
var pos = url.indexOf("#");
if (pos >= 0) {
var id = url.substring(pos);
if (this.find('>ul a[href="'+id+'"]').length > 0) {
activate(id);
return;
}
}
}
});
})(jQuery);
| motin/yii-bootstrap | demo/yii/web/js/source/jquery.yiitab.js | JavaScript | bsd-3-clause | 1,210 |
/*
* pthread_spin_unlock.c
*
* Description:
* This translation unit implements spin lock primitives.
*
* --------------------------------------------------------------------------
*
* Pthreads-win32 - POSIX Threads Library for Win32
* Copyright(C) 1998 John E. Bossom
* Copyright(C) 1999,2005 Pthreads-win32 contributors
*
* Contact Email: rpj@callisto.canberra.edu.au
*
* The current list of contributors is contained
* in the file CONTRIBUTORS included with the source
* code distribution. The list can also be seen at the
* following World Wide Web location:
* http://sources.redhat.com/pthreads-win32/contributors.html
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library in the file COPYING.LIB;
* if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
*/
#include "pthread.h"
#include "implement.h"
int
pthread_spin_unlock (pthread_spinlock_t * lock)
{
register pthread_spinlock_t s;
if (NULL == lock || NULL == *lock)
{
return (EINVAL);
}
s = *lock;
if (s == PTHREAD_SPINLOCK_INITIALIZER)
{
return EPERM;
}
switch ((long)
PTW32_INTERLOCKED_COMPARE_EXCHANGE_LONG ((PTW32_INTERLOCKED_LONGPTR) &s->interlock,
(PTW32_INTERLOCKED_LONG) PTW32_SPIN_UNLOCKED,
(PTW32_INTERLOCKED_LONG) PTW32_SPIN_LOCKED))
{
case PTW32_SPIN_LOCKED:
case PTW32_SPIN_UNLOCKED:
return 0;
case PTW32_SPIN_USE_MUTEX:
return pthread_mutex_unlock (&(s->u.mutex));
}
return EINVAL;
}
| joone/chromium-crosswalk | native_client_sdk/src/libraries/third_party/pthreads-win32/pthread_spin_unlock.c | C | bsd-3-clause | 2,220 |
<!DOCTYPE html>
<!--
Copyright (c) 2013 Intel Corporation.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of works must retain the original copyright notice, this list
of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the original copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of Intel Corporation nor the names of its contributors
may be used to endorse or promote products derived from this work without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY INTEL CORPORATION "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL INTEL CORPORATION BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Authors:
-->
<!doctype>
<html>
<title>homepageexist</title>
<body>Home Page Exist</body>
<!-- Startup configuration -->
<link rel="manifest" href="manifest.json">
<!-- Application metadata -->
<meta name="application-name" content="Store Finder">
<link rel="icon" sizes="16x16 32x32 117x117" href="icon.png">
<link rel="icon" sizes="512x512" href="hd_hi.jpg">
| XiaosongWei/crosswalk-test-suite | wrt/wrt-manifest-android-tests/tcs/manifest69-positive/homepageexist.html | HTML | bsd-3-clause | 1,810 |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>AdminLTE 2 | Buttons</title>
<!-- Tell the browser to be responsive to screen width -->
<meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
<!-- Bootstrap 3.3.6 -->
<link rel="stylesheet" href="../../bootstrap/css/bootstrap.min.css">
<!-- Font Awesome -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.5.0/css/font-awesome.min.css">
<!-- Ionicons -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/ionicons/2.0.1/css/ionicons.min.css">
<!-- Theme style -->
<link rel="stylesheet" href="../../dist/css/AdminLTE.min.css">
<!-- AdminLTE Skins. Choose a skin from the css/skins
folder instead of downloading all of them to reduce the load. -->
<link rel="stylesheet" href="../../dist/css/skins/_all-skins.min.css">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body class="hold-transition skin-blue sidebar-mini">
<div class="wrapper">
<header class="main-header">
<!-- Logo -->
<a href="../../index2.html" class="logo">
<!-- mini logo for sidebar mini 50x50 pixels -->
<span class="logo-mini"><b>A</b>LT</span>
<!-- logo for regular state and mobile devices -->
<span class="logo-lg"><b>Admin</b>LTE</span>
</a>
<!-- Header Navbar: style can be found in header.less -->
<nav class="navbar navbar-static-top">
<!-- Sidebar toggle button-->
<a href="#" class="sidebar-toggle" data-toggle="offcanvas" role="button">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</a>
<div class="navbar-custom-menu">
<ul class="nav navbar-nav">
<!-- Messages: style can be found in dropdown.less-->
<li class="dropdown messages-menu">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
<i class="fa fa-envelope-o"></i>
<span class="label label-success">4</span>
</a>
<ul class="dropdown-menu">
<li class="header">You have 4 messages</li>
<li>
<!-- inner menu: contains the actual data -->
<ul class="menu">
<li><!-- start message -->
<a href="#">
<div class="pull-left">
<img src="../../dist/img/user2-160x160.jpg" class="img-circle" alt="User Image">
</div>
<h4>
Support Team
<small><i class="fa fa-clock-o"></i> 5 mins</small>
</h4>
<p>Why not buy a new awesome theme?</p>
</a>
</li>
<!-- end message -->
<li>
<a href="#">
<div class="pull-left">
<img src="../../dist/img/user3-128x128.jpg" class="img-circle" alt="User Image">
</div>
<h4>
AdminLTE Design Team
<small><i class="fa fa-clock-o"></i> 2 hours</small>
</h4>
<p>Why not buy a new awesome theme?</p>
</a>
</li>
<li>
<a href="#">
<div class="pull-left">
<img src="../../dist/img/user4-128x128.jpg" class="img-circle" alt="User Image">
</div>
<h4>
Developers
<small><i class="fa fa-clock-o"></i> Today</small>
</h4>
<p>Why not buy a new awesome theme?</p>
</a>
</li>
<li>
<a href="#">
<div class="pull-left">
<img src="../../dist/img/user3-128x128.jpg" class="img-circle" alt="User Image">
</div>
<h4>
Sales Department
<small><i class="fa fa-clock-o"></i> Yesterday</small>
</h4>
<p>Why not buy a new awesome theme?</p>
</a>
</li>
<li>
<a href="#">
<div class="pull-left">
<img src="../../dist/img/user4-128x128.jpg" class="img-circle" alt="User Image">
</div>
<h4>
Reviewers
<small><i class="fa fa-clock-o"></i> 2 days</small>
</h4>
<p>Why not buy a new awesome theme?</p>
</a>
</li>
</ul>
</li>
<li class="footer"><a href="#">See All Messages</a></li>
</ul>
</li>
<!-- Notifications: style can be found in dropdown.less -->
<li class="dropdown notifications-menu">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
<i class="fa fa-bell-o"></i>
<span class="label label-warning">10</span>
</a>
<ul class="dropdown-menu">
<li class="header">You have 10 notifications</li>
<li>
<!-- inner menu: contains the actual data -->
<ul class="menu">
<li>
<a href="#">
<i class="fa fa-users text-aqua"></i> 5 new members joined today
</a>
</li>
<li>
<a href="#">
<i class="fa fa-warning text-yellow"></i> Very long description here that may not fit into the
page and may cause design problems
</a>
</li>
<li>
<a href="#">
<i class="fa fa-users text-red"></i> 5 new members joined
</a>
</li>
<li>
<a href="#">
<i class="fa fa-shopping-cart text-green"></i> 25 sales made
</a>
</li>
<li>
<a href="#">
<i class="fa fa-user text-red"></i> You changed your username
</a>
</li>
</ul>
</li>
<li class="footer"><a href="#">View all</a></li>
</ul>
</li>
<!-- Tasks: style can be found in dropdown.less -->
<li class="dropdown tasks-menu">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
<i class="fa fa-flag-o"></i>
<span class="label label-danger">9</span>
</a>
<ul class="dropdown-menu">
<li class="header">You have 9 tasks</li>
<li>
<!-- inner menu: contains the actual data -->
<ul class="menu">
<li><!-- Task item -->
<a href="#">
<h3>
Design some buttons
<small class="pull-right">20%</small>
</h3>
<div class="progress xs">
<div class="progress-bar progress-bar-aqua" style="width: 20%" role="progressbar" aria-valuenow="20" aria-valuemin="0" aria-valuemax="100">
<span class="sr-only">20% Complete</span>
</div>
</div>
</a>
</li>
<!-- end task item -->
<li><!-- Task item -->
<a href="#">
<h3>
Create a nice theme
<small class="pull-right">40%</small>
</h3>
<div class="progress xs">
<div class="progress-bar progress-bar-green" style="width: 40%" role="progressbar" aria-valuenow="20" aria-valuemin="0" aria-valuemax="100">
<span class="sr-only">40% Complete</span>
</div>
</div>
</a>
</li>
<!-- end task item -->
<li><!-- Task item -->
<a href="#">
<h3>
Some task I need to do
<small class="pull-right">60%</small>
</h3>
<div class="progress xs">
<div class="progress-bar progress-bar-red" style="width: 60%" role="progressbar" aria-valuenow="20" aria-valuemin="0" aria-valuemax="100">
<span class="sr-only">60% Complete</span>
</div>
</div>
</a>
</li>
<!-- end task item -->
<li><!-- Task item -->
<a href="#">
<h3>
Make beautiful transitions
<small class="pull-right">80%</small>
</h3>
<div class="progress xs">
<div class="progress-bar progress-bar-yellow" style="width: 80%" role="progressbar" aria-valuenow="20" aria-valuemin="0" aria-valuemax="100">
<span class="sr-only">80% Complete</span>
</div>
</div>
</a>
</li>
<!-- end task item -->
</ul>
</li>
<li class="footer">
<a href="#">View all tasks</a>
</li>
</ul>
</li>
<!-- User Account: style can be found in dropdown.less -->
<li class="dropdown user user-menu">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
<img src="../../dist/img/user2-160x160.jpg" class="user-image" alt="User Image">
<span class="hidden-xs">Alexander Pierce</span>
</a>
<ul class="dropdown-menu">
<!-- User image -->
<li class="user-header">
<img src="../../dist/img/user2-160x160.jpg" class="img-circle" alt="User Image">
<p>
Alexander Pierce - Web Developer
<small>Member since Nov. 2012</small>
</p>
</li>
<!-- Menu Body -->
<li class="user-body">
<div class="row">
<div class="col-xs-4 text-center">
<a href="#">Followers</a>
</div>
<div class="col-xs-4 text-center">
<a href="#">Sales</a>
</div>
<div class="col-xs-4 text-center">
<a href="#">Friends</a>
</div>
</div>
<!-- /.row -->
</li>
<!-- Menu Footer-->
<li class="user-footer">
<div class="pull-left">
<a href="#" class="btn btn-default btn-flat">Profile</a>
</div>
<div class="pull-right">
<a href="#" class="btn btn-default btn-flat">Sign out</a>
</div>
</li>
</ul>
</li>
<!-- Control Sidebar Toggle Button -->
<li>
<a href="#" data-toggle="control-sidebar"><i class="fa fa-gears"></i></a>
</li>
</ul>
</div>
</nav>
</header>
<!-- Left side column. contains the logo and sidebar -->
<aside class="main-sidebar">
<!-- sidebar: style can be found in sidebar.less -->
<section class="sidebar">
<!-- Sidebar user panel -->
<div class="user-panel">
<div class="pull-left image">
<img src="../../dist/img/user2-160x160.jpg" class="img-circle" alt="User Image">
</div>
<div class="pull-left info">
<p>Alexander Pierce</p>
<a href="#"><i class="fa fa-circle text-success"></i> Online</a>
</div>
</div>
<!-- search form -->
<form action="#" method="get" class="sidebar-form">
<div class="input-group">
<input type="text" name="q" class="form-control" placeholder="Search...">
<span class="input-group-btn">
<button type="submit" name="search" id="search-btn" class="btn btn-flat"><i class="fa fa-search"></i>
</button>
</span>
</div>
</form>
<!-- /.search form -->
<!-- sidebar menu: : style can be found in sidebar.less -->
<ul class="sidebar-menu">
<li class="header">MAIN NAVIGATION</li>
<li class="treeview">
<a href="#">
<i class="fa fa-dashboard"></i> <span>Dashboard</span> <i class="fa fa-angle-left pull-right"></i>
</a>
<ul class="treeview-menu">
<li><a href="../../index.html"><i class="fa fa-circle-o"></i> Dashboard v1</a></li>
<li><a href="../../index2.html"><i class="fa fa-circle-o"></i> Dashboard v2</a></li>
</ul>
</li>
<li class="treeview">
<a href="#">
<i class="fa fa-files-o"></i>
<span>Layout Options</span>
<span class="label label-primary pull-right">4</span>
</a>
<ul class="treeview-menu">
<li><a href="../layout/top-nav.html"><i class="fa fa-circle-o"></i> Top Navigation</a></li>
<li><a href="../layout/boxed.html"><i class="fa fa-circle-o"></i> Boxed</a></li>
<li><a href="../layout/fixed.html"><i class="fa fa-circle-o"></i> Fixed</a></li>
<li><a href="../layout/collapsed-sidebar.html"><i class="fa fa-circle-o"></i> Collapsed Sidebar</a></li>
</ul>
</li>
<li>
<a href="../widgets.html">
<i class="fa fa-th"></i> <span>Widgets</span>
<small class="label pull-right bg-green">new</small>
</a>
</li>
<li class="treeview">
<a href="#">
<i class="fa fa-pie-chart"></i>
<span>Charts</span>
<i class="fa fa-angle-left pull-right"></i>
</a>
<ul class="treeview-menu">
<li><a href="../charts/chartjs.html"><i class="fa fa-circle-o"></i> ChartJS</a></li>
<li><a href="../charts/morris.html"><i class="fa fa-circle-o"></i> Morris</a></li>
<li><a href="../charts/flot.html"><i class="fa fa-circle-o"></i> Flot</a></li>
<li><a href="../charts/inline.html"><i class="fa fa-circle-o"></i> Inline charts</a></li>
</ul>
</li>
<li class="treeview active">
<a href="#">
<i class="fa fa-laptop"></i>
<span>UI Elements</span>
<i class="fa fa-angle-left pull-right"></i>
</a>
<ul class="treeview-menu">
<li><a href="general.html"><i class="fa fa-circle-o"></i> General</a></li>
<li><a href="icons.html"><i class="fa fa-circle-o"></i> Icons</a></li>
<li class="active"><a href="buttons.html"><i class="fa fa-circle-o"></i> Buttons</a></li>
<li><a href="sliders.html"><i class="fa fa-circle-o"></i> Sliders</a></li>
<li><a href="timeline.html"><i class="fa fa-circle-o"></i> Timeline</a></li>
<li><a href="modals.html"><i class="fa fa-circle-o"></i> Modals</a></li>
</ul>
</li>
<li class="treeview">
<a href="#">
<i class="fa fa-edit"></i> <span>Forms</span>
<i class="fa fa-angle-left pull-right"></i>
</a>
<ul class="treeview-menu">
<li><a href="../forms/general.html"><i class="fa fa-circle-o"></i> General Elements</a></li>
<li><a href="../forms/advanced.html"><i class="fa fa-circle-o"></i> Advanced Elements</a></li>
<li><a href="../forms/editors.html"><i class="fa fa-circle-o"></i> Editors</a></li>
</ul>
</li>
<li class="treeview">
<a href="#">
<i class="fa fa-table"></i> <span>Tables</span>
<i class="fa fa-angle-left pull-right"></i>
</a>
<ul class="treeview-menu">
<li><a href="../tables/simple.html"><i class="fa fa-circle-o"></i> Simple tables</a></li>
<li><a href="../tables/data.html"><i class="fa fa-circle-o"></i> Data tables</a></li>
</ul>
</li>
<li>
<a href="../calendar.html">
<i class="fa fa-calendar"></i> <span>Calendar</span>
<small class="label pull-right bg-red">3</small>
</a>
</li>
<li>
<a href="../mailbox/mailbox.html">
<i class="fa fa-envelope"></i> <span>Mailbox</span>
<small class="label pull-right bg-yellow">12</small>
</a>
</li>
<li class="treeview">
<a href="#">
<i class="fa fa-folder"></i> <span>Examples</span>
<i class="fa fa-angle-left pull-right"></i>
</a>
<ul class="treeview-menu">
<li><a href="../examples/invoice.html"><i class="fa fa-circle-o"></i> Invoice</a></li>
<li><a href="../examples/profile.html"><i class="fa fa-circle-o"></i> Profile</a></li>
<li><a href="../examples/login.html"><i class="fa fa-circle-o"></i> Login</a></li>
<li><a href="../examples/register.html"><i class="fa fa-circle-o"></i> Register</a></li>
<li><a href="../examples/lockscreen.html"><i class="fa fa-circle-o"></i> Lockscreen</a></li>
<li><a href="../examples/404.html"><i class="fa fa-circle-o"></i> 404 Error</a></li>
<li><a href="../examples/500.html"><i class="fa fa-circle-o"></i> 500 Error</a></li>
<li><a href="../examples/blank.html"><i class="fa fa-circle-o"></i> Blank Page</a></li>
<li><a href="../examples/pace.html"><i class="fa fa-circle-o"></i> Pace Page</a></li>
</ul>
</li>
<li class="treeview">
<a href="#">
<i class="fa fa-share"></i> <span>Multilevel</span>
<i class="fa fa-angle-left pull-right"></i>
</a>
<ul class="treeview-menu">
<li><a href="#"><i class="fa fa-circle-o"></i> Level One</a></li>
<li>
<a href="#"><i class="fa fa-circle-o"></i> Level One <i class="fa fa-angle-left pull-right"></i></a>
<ul class="treeview-menu">
<li><a href="#"><i class="fa fa-circle-o"></i> Level Two</a></li>
<li>
<a href="#"><i class="fa fa-circle-o"></i> Level Two <i class="fa fa-angle-left pull-right"></i></a>
<ul class="treeview-menu">
<li><a href="#"><i class="fa fa-circle-o"></i> Level Three</a></li>
<li><a href="#"><i class="fa fa-circle-o"></i> Level Three</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#"><i class="fa fa-circle-o"></i> Level One</a></li>
</ul>
</li>
<li><a href="../../documentation/index.html"><i class="fa fa-book"></i> <span>Documentation</span></a></li>
<li class="header">LABELS</li>
<li><a href="#"><i class="fa fa-circle-o text-red"></i> <span>Important</span></a></li>
<li><a href="#"><i class="fa fa-circle-o text-yellow"></i> <span>Warning</span></a></li>
<li><a href="#"><i class="fa fa-circle-o text-aqua"></i> <span>Information</span></a></li>
</ul>
</section>
<!-- /.sidebar -->
</aside>
<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
<!-- Content Header (Page header) -->
<section class="content-header">
<h1>
Buttons
<small>Control panel</small>
</h1>
<ol class="breadcrumb">
<li><a href="#"><i class="fa fa-dashboard"></i> Home</a></li>
<li><a href="#">UI</a></li>
<li class="active">Buttons</li>
</ol>
</section>
<!-- Main content -->
<section class="content">
<div class="row">
<div class="col-md-12">
<div class="box box-primary">
<div class="box-header">
<i class="fa fa-edit"></i>
<h3 class="box-title">Buttons</h3>
</div>
<div class="box-body pad table-responsive">
<p>Various types of buttons. Using the base class <code>.btn</code></p>
<table class="table table-bordered text-center">
<tr>
<th>Normal</th>
<th>Large <code>.btn-lg</code></th>
<th>Small <code>.btn-sm</code></th>
<th>X-Small <code>.btn-xs</code></th>
<th>Flat <code>.btn-flat</code></th>
<th>Disabled <code>.disabled</code></th>
</tr>
<tr>
<td>
<button type="button" class="btn btn-block btn-default">Default</button>
</td>
<td>
<button type="button" class="btn btn-block btn-default btn-lg">Default</button>
</td>
<td>
<button type="button" class="btn btn-block btn-default btn-sm">Default</button>
</td>
<td>
<button type="button" class="btn btn-block btn-default btn-xs">Default</button>
</td>
<td>
<button type="button" class="btn btn-block btn-default btn-flat">Default</button>
</td>
<td>
<button type="button" class="btn btn-block btn-default disabled">Default</button>
</td>
</tr>
<tr>
<td>
<button type="button" class="btn btn-block btn-primary">Primary</button>
</td>
<td>
<button type="button" class="btn btn-block btn-primary btn-lg">Primary</button>
</td>
<td>
<button type="button" class="btn btn-block btn-primary btn-sm">Primary</button>
</td>
<td>
<button type="button" class="btn btn-block btn-primary btn-xs">Primary</button>
</td>
<td>
<button type="button" class="btn btn-block btn-primary btn-flat">Primary</button>
</td>
<td>
<button type="button" class="btn btn-block btn-primary disabled">Primary</button>
</td>
</tr>
<tr>
<td>
<button type="button" class="btn btn-block btn-success">Success</button>
</td>
<td>
<button type="button" class="btn btn-block btn-success btn-lg">Success</button>
</td>
<td>
<button type="button" class="btn btn-block btn-success btn-sm">Success</button>
</td>
<td>
<button type="button" class="btn btn-block btn-success btn-xs">Success</button>
</td>
<td>
<button type="button" class="btn btn-block btn-success btn-flat">Success</button>
</td>
<td>
<button type="button" class="btn btn-block btn-success disabled">Success</button>
</td>
</tr>
<tr>
<td>
<button type="button" class="btn btn-block btn-info">Info</button>
</td>
<td>
<button type="button" class="btn btn-block btn-info btn-lg">Info</button>
</td>
<td>
<button type="button" class="btn btn-block btn-info btn-sm">Info</button>
</td>
<td>
<button type="button" class="btn btn-block btn-info btn-xs">Info</button>
</td>
<td>
<button type="button" class="btn btn-block btn-info btn-flat">Info</button>
</td>
<td>
<button type="button" class="btn btn-block btn-info disabled">Info</button>
</td>
</tr>
<tr>
<td>
<button type="button" class="btn btn-block btn-danger">Danger</button>
</td>
<td>
<button type="button" class="btn btn-block btn-danger btn-lg">Danger</button>
</td>
<td>
<button type="button" class="btn btn-block btn-danger btn-sm">Danger</button>
</td>
<td>
<button type="button" class="btn btn-block btn-danger btn-xs">Danger</button>
</td>
<td>
<button type="button" class="btn btn-block btn-danger btn-flat">Danger</button>
</td>
<td>
<button type="button" class="btn btn-block btn-danger disabled">Danger</button>
</td>
</tr>
<tr>
<td>
<button type="button" class="btn btn-block btn-warning">Warning</button>
</td>
<td>
<button type="button" class="btn btn-block btn-warning btn-lg">Warning</button>
</td>
<td>
<button type="button" class="btn btn-block btn-warning btn-sm">Warning</button>
</td>
<td>
<button type="button" class="btn btn-block btn-warning btn-xs">Warning</button>
</td>
<td>
<button type="button" class="btn btn-block btn-warning btn-flat">Warning</button>
</td>
<td>
<button type="button" class="btn btn-block btn-warning disabled">Warning</button>
</td>
</tr>
</table>
</div>
<!-- /.box -->
</div>
</div>
<!-- /.col -->
</div>
<!-- ./row -->
<div class="row">
<div class="col-md-6">
<!-- Block buttons -->
<div class="box">
<div class="box-header">
<h3 class="box-title">Block Buttons</h3>
</div>
<div class="box-body">
<button type="button" class="btn btn-default btn-block">.btn-block</button>
<button type="button" class="btn btn-default btn-block btn-flat">.btn-block .btn-flat</button>
<button type="button" class="btn btn-default btn-block btn-sm">.btn-block .btn-sm</button>
</div>
</div>
<!-- /.box -->
<!-- Horizontal grouping -->
<div class="box">
<div class="box-header">
<h3 class="box-title">Horizontal Button Group</h3>
</div>
<div class="box-body table-responsive pad">
<p>
Horizontal button groups are easy to create with bootstrap. Just add your buttons
inside <code><div class="btn-group"></div></code>
</p>
<table class="table table-bordered">
<tr>
<th>Button</th>
<th>Icons</th>
<th>Flat</th>
<th>Dropdown</th>
</tr>
<!-- Default -->
<tr>
<td>
<div class="btn-group">
<button type="button" class="btn btn-default">Left</button>
<button type="button" class="btn btn-default">Middle</button>
<button type="button" class="btn btn-default">Right</button>
</div>
</td>
<td>
<div class="btn-group">
<button type="button" class="btn btn-default"><i class="fa fa-align-left"></i></button>
<button type="button" class="btn btn-default"><i class="fa fa-align-center"></i></button>
<button type="button" class="btn btn-default"><i class="fa fa-align-right"></i></button>
</div>
</td>
<td>
<div class="btn-group">
<button type="button" class="btn btn-default btn-flat"><i class="fa fa-align-left"></i></button>
<button type="button" class="btn btn-default btn-flat"><i class="fa fa-align-center"></i></button>
<button type="button" class="btn btn-default btn-flat"><i class="fa fa-align-right"></i></button>
</div>
</td>
<td>
<div class="btn-group">
<button type="button" class="btn btn-default">1</button>
<button type="button" class="btn btn-default">2</button>
<div class="btn-group">
<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
<span class="caret"></span>
</button>
<ul class="dropdown-menu">
<li><a href="#">Dropdown link</a></li>
<li><a href="#">Dropdown link</a></li>
</ul>
</div>
</div>
</td>
</tr>
<!-- ./default -->
<!-- Info -->
<tr>
<td>
<div class="btn-group">
<button type="button" class="btn btn-info">Left</button>
<button type="button" class="btn btn-info">Middle</button>
<button type="button" class="btn btn-info">Right</button>
</div>
</td>
<td>
<div class="btn-group">
<button type="button" class="btn btn-info"><i class="fa fa-align-left"></i></button>
<button type="button" class="btn btn-info"><i class="fa fa-align-center"></i></button>
<button type="button" class="btn btn-info"><i class="fa fa-align-right"></i></button>
</div>
</td>
<td>
<div class="btn-group">
<button type="button" class="btn btn-info btn-flat"><i class="fa fa-align-left"></i></button>
<button type="button" class="btn btn-info btn-flat"><i class="fa fa-align-center"></i></button>
<button type="button" class="btn btn-info btn-flat"><i class="fa fa-align-right"></i></button>
</div>
</td>
<td>
<div class="btn-group">
<button type="button" class="btn btn-info">1</button>
<button type="button" class="btn btn-info">2</button>
<div class="btn-group">
<button type="button" class="btn btn-info dropdown-toggle" data-toggle="dropdown">
<span class="caret"></span>
</button>
<ul class="dropdown-menu">
<li><a href="#">Dropdown link</a></li>
<li><a href="#">Dropdown link</a></li>
</ul>
</div>
</div>
</td>
</tr>
<!-- /. info -->
<!-- /.danger -->
<tr>
<td>
<div class="btn-group">
<button type="button" class="btn btn-danger">Left</button>
<button type="button" class="btn btn-danger">Middle</button>
<button type="button" class="btn btn-danger">Right</button>
</div>
</td>
<td>
<div class="btn-group">
<button type="button" class="btn btn-danger"><i class="fa fa-align-left"></i></button>
<button type="button" class="btn btn-danger"><i class="fa fa-align-center"></i></button>
<button type="button" class="btn btn-danger"><i class="fa fa-align-right"></i></button>
</div>
</td>
<td>
<div class="btn-group">
<button type="button" class="btn btn-danger btn-flat"><i class="fa fa-align-left"></i></button>
<button type="button" class="btn btn-danger btn-flat"><i class="fa fa-align-center"></i></button>
<button type="button" class="btn btn-danger btn-flat"><i class="fa fa-align-right"></i></button>
</div>
</td>
<td>
<div class="btn-group">
<button type="button" class="btn btn-danger">1</button>
<button type="button" class="btn btn-danger">2</button>
<div class="btn-group">
<button type="button" class="btn btn-danger dropdown-toggle" data-toggle="dropdown">
<span class="caret"></span>
</button>
<ul class="dropdown-menu">
<li><a href="#">Dropdown link</a></li>
<li><a href="#">Dropdown link</a></li>
</ul>
</div>
</div>
</td>
</tr>
<!-- /.danger -->
<!-- warning -->
<tr>
<td>
<div class="btn-group">
<button type="button" class="btn btn-warning">Left</button>
<button type="button" class="btn btn-warning">Middle</button>
<button type="button" class="btn btn-warning">Right</button>
</div>
</td>
<td>
<div class="btn-group">
<button type="button" class="btn btn-warning"><i class="fa fa-align-left"></i></button>
<button type="button" class="btn btn-warning"><i class="fa fa-align-center"></i></button>
<button type="button" class="btn btn-warning"><i class="fa fa-align-right"></i></button>
</div>
</td>
<td>
<div class="btn-group">
<button type="button" class="btn btn-warning btn-flat"><i class="fa fa-align-left"></i></button>
<button type="button" class="btn btn-warning btn-flat"><i class="fa fa-align-center"></i></button>
<button type="button" class="btn btn-warning btn-flat"><i class="fa fa-align-right"></i></button>
</div>
</td>
<td>
<div class="btn-group">
<button type="button" class="btn btn-warning">1</button>
<button type="button" class="btn btn-warning">2</button>
<div class="btn-group">
<button type="button" class="btn btn-warning dropdown-toggle" data-toggle="dropdown">
<span class="caret"></span>
</button>
<ul class="dropdown-menu">
<li><a href="#">Dropdown link</a></li>
<li><a href="#">Dropdown link</a></li>
</ul>
</div>
</div>
</td>
</tr>
<!-- /.warning -->
<!-- success -->
<tr>
<td>
<div class="btn-group">
<button type="button" class="btn btn-success">Left</button>
<button type="button" class="btn btn-success">Middle</button>
<button type="button" class="btn btn-success">Right</button>
</div>
</td>
<td>
<div class="btn-group">
<button type="button" class="btn btn-success"><i class="fa fa-align-left"></i></button>
<button type="button" class="btn btn-success"><i class="fa fa-align-center"></i></button>
<button type="button" class="btn btn-success"><i class="fa fa-align-right"></i></button>
</div>
</td>
<td>
<div class="btn-group">
<button type="button" class="btn btn-success btn-flat"><i class="fa fa-align-left"></i></button>
<button type="button" class="btn btn-success btn-flat"><i class="fa fa-align-center"></i></button>
<button type="button" class="btn btn-success btn-flat"><i class="fa fa-align-right"></i></button>
</div>
</td>
<td>
<div class="btn-group">
<button type="button" class="btn btn-success">1</button>
<button type="button" class="btn btn-success">2</button>
<div class="btn-group">
<button type="button" class="btn btn-success dropdown-toggle" data-toggle="dropdown">
<span class="caret"></span>
</button>
<ul class="dropdown-menu">
<li><a href="#">Dropdown link</a></li>
<li><a href="#">Dropdown link</a></li>
</ul>
</div>
</div>
</td>
</tr>
<!-- /.success -->
</table>
</div>
</div>
<!-- /.box -->
<div class="box">
<div class="box-header">
<h3 class="box-title">Button Addon</h3>
</div>
<div class="box-body">
<p>With dropdown</p>
<div class="input-group margin">
<div class="input-group-btn">
<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">Action
<span class="fa fa-caret-down"></span></button>
<ul class="dropdown-menu">
<li><a href="#">Action</a></li>
<li><a href="#">Another action</a></li>
<li><a href="#">Something else here</a></li>
<li class="divider"></li>
<li><a href="#">Separated link</a></li>
</ul>
</div>
<!-- /btn-group -->
<input type="text" class="form-control">
</div>
<!-- /input-group -->
<p>Normal</p>
<div class="input-group margin">
<div class="input-group-btn">
<button type="button" class="btn btn-danger">Action</button>
</div>
<!-- /btn-group -->
<input type="text" class="form-control">
</div>
<!-- /input-group -->
<p>Flat</p>
<div class="input-group margin">
<input type="text" class="form-control">
<span class="input-group-btn">
<button type="button" class="btn btn-info btn-flat">Go!</button>
</span>
</div>
<!-- /input-group -->
</div>
<!-- /.box-body -->
</div>
<!-- /.box -->
<!-- split buttons box -->
<div class="box">
<div class="box-header">
<h3 class="box-title">Split buttons</h3>
</div>
<div class="box-body">
<!-- Split button -->
<p>Normal split buttons:</p>
<div class="margin">
<div class="btn-group">
<button type="button" class="btn btn-default">Action</button>
<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
<span class="caret"></span>
<span class="sr-only">Toggle Dropdown</span>
</button>
<ul class="dropdown-menu" role="menu">
<li><a href="#">Action</a></li>
<li><a href="#">Another action</a></li>
<li><a href="#">Something else here</a></li>
<li class="divider"></li>
<li><a href="#">Separated link</a></li>
</ul>
</div>
<div class="btn-group">
<button type="button" class="btn btn-info">Action</button>
<button type="button" class="btn btn-info dropdown-toggle" data-toggle="dropdown">
<span class="caret"></span>
<span class="sr-only">Toggle Dropdown</span>
</button>
<ul class="dropdown-menu" role="menu">
<li><a href="#">Action</a></li>
<li><a href="#">Another action</a></li>
<li><a href="#">Something else here</a></li>
<li class="divider"></li>
<li><a href="#">Separated link</a></li>
</ul>
</div>
<div class="btn-group">
<button type="button" class="btn btn-danger">Action</button>
<button type="button" class="btn btn-danger dropdown-toggle" data-toggle="dropdown">
<span class="caret"></span>
<span class="sr-only">Toggle Dropdown</span>
</button>
<ul class="dropdown-menu" role="menu">
<li><a href="#">Action</a></li>
<li><a href="#">Another action</a></li>
<li><a href="#">Something else here</a></li>
<li class="divider"></li>
<li><a href="#">Separated link</a></li>
</ul>
</div>
<div class="btn-group">
<button type="button" class="btn btn-success">Action</button>
<button type="button" class="btn btn-success dropdown-toggle" data-toggle="dropdown">
<span class="caret"></span>
<span class="sr-only">Toggle Dropdown</span>
</button>
<ul class="dropdown-menu" role="menu">
<li><a href="#">Action</a></li>
<li><a href="#">Another action</a></li>
<li><a href="#">Something else here</a></li>
<li class="divider"></li>
<li><a href="#">Separated link</a></li>
</ul>
</div>
<div class="btn-group">
<button type="button" class="btn btn-warning">Action</button>
<button type="button" class="btn btn-warning dropdown-toggle" data-toggle="dropdown">
<span class="caret"></span>
<span class="sr-only">Toggle Dropdown</span>
</button>
<ul class="dropdown-menu" role="menu">
<li><a href="#">Action</a></li>
<li><a href="#">Another action</a></li>
<li><a href="#">Something else here</a></li>
<li class="divider"></li>
<li><a href="#">Separated link</a></li>
</ul>
</div>
</div>
<!-- flat split buttons -->
<p>Flat split buttons:</p>
<div class="margin">
<div class="btn-group">
<button type="button" class="btn btn-default btn-flat">Action</button>
<button type="button" class="btn btn-default btn-flat dropdown-toggle" data-toggle="dropdown">
<span class="caret"></span>
<span class="sr-only">Toggle Dropdown</span>
</button>
<ul class="dropdown-menu" role="menu">
<li><a href="#">Action</a></li>
<li><a href="#">Another action</a></li>
<li><a href="#">Something else here</a></li>
<li class="divider"></li>
<li><a href="#">Separated link</a></li>
</ul>
</div>
<div class="btn-group">
<button type="button" class="btn btn-info btn-flat">Action</button>
<button type="button" class="btn btn-info btn-flat dropdown-toggle" data-toggle="dropdown">
<span class="caret"></span>
<span class="sr-only">Toggle Dropdown</span>
</button>
<ul class="dropdown-menu" role="menu">
<li><a href="#">Action</a></li>
<li><a href="#">Another action</a></li>
<li><a href="#">Something else here</a></li>
<li class="divider"></li>
<li><a href="#">Separated link</a></li>
</ul>
</div>
<div class="btn-group">
<button type="button" class="btn btn-danger btn-flat">Action</button>
<button type="button" class="btn btn-danger btn-flat dropdown-toggle" data-toggle="dropdown">
<span class="caret"></span>
<span class="sr-only">Toggle Dropdown</span>
</button>
<ul class="dropdown-menu" role="menu">
<li><a href="#">Action</a></li>
<li><a href="#">Another action</a></li>
<li><a href="#">Something else here</a></li>
<li class="divider"></li>
<li><a href="#">Separated link</a></li>
</ul>
</div>
<div class="btn-group">
<button type="button" class="btn btn-success btn-flat">Action</button>
<button type="button" class="btn btn-success btn-flat dropdown-toggle" data-toggle="dropdown">
<span class="caret"></span>
<span class="sr-only">Toggle Dropdown</span>
</button>
<ul class="dropdown-menu" role="menu">
<li><a href="#">Action</a></li>
<li><a href="#">Another action</a></li>
<li><a href="#">Something else here</a></li>
<li class="divider"></li>
<li><a href="#">Separated link</a></li>
</ul>
</div>
<div class="btn-group">
<button type="button" class="btn btn-warning btn-flat">Action</button>
<button type="button" class="btn btn-warning btn-flat dropdown-toggle" data-toggle="dropdown">
<span class="caret"></span>
<span class="sr-only">Toggle Dropdown</span>
</button>
<ul class="dropdown-menu" role="menu">
<li><a href="#">Action</a></li>
<li><a href="#">Another action</a></li>
<li><a href="#">Something else here</a></li>
<li class="divider"></li>
<li><a href="#">Separated link</a></li>
</ul>
</div>
</div>
</div>
<!-- /.box-body -->
</div>
<!-- end split buttons box -->
<!-- social buttons -->
<div class="box">
<div class="box-header">
<h3 class="box-title">Social Buttons (By <a href="https://github.com/lipis/bootstrap-social">Lipis</a>)
</h3>
</div>
<div class="box-body">
<a class="btn btn-block btn-social btn-bitbucket">
<i class="fa fa-bitbucket"></i> Sign in with Bitbucket
</a>
<a class="btn btn-block btn-social btn-dropbox">
<i class="fa fa-dropbox"></i> Sign in with Dropbox
</a>
<a class="btn btn-block btn-social btn-facebook">
<i class="fa fa-facebook"></i> Sign in with Facebook
</a>
<a class="btn btn-block btn-social btn-flickr">
<i class="fa fa-flickr"></i> Sign in with Flickr
</a>
<a class="btn btn-block btn-social btn-foursquare">
<i class="fa fa-foursquare"></i> Sign in with Foursquare
</a>
<a class="btn btn-block btn-social btn-github">
<i class="fa fa-github"></i> Sign in with GitHub
</a>
<a class="btn btn-block btn-social btn-google">
<i class="fa fa-google-plus"></i> Sign in with Google
</a>
<a class="btn btn-block btn-social btn-instagram">
<i class="fa fa-instagram"></i> Sign in with Instagram
</a>
<a class="btn btn-block btn-social btn-linkedin">
<i class="fa fa-linkedin"></i> Sign in with LinkedIn
</a>
<a class="btn btn-block btn-social btn-tumblr">
<i class="fa fa-tumblr"></i> Sign in with Tumblr
</a>
<a class="btn btn-block btn-social btn-twitter">
<i class="fa fa-twitter"></i> Sign in with Twitter
</a>
<a class="btn btn-block btn-social btn-vk">
<i class="fa fa-vk"></i> Sign in with VK
</a>
<br>
<div class="text-center">
<a class="btn btn-social-icon btn-bitbucket"><i class="fa fa-bitbucket"></i></a>
<a class="btn btn-social-icon btn-dropbox"><i class="fa fa-dropbox"></i></a>
<a class="btn btn-social-icon btn-facebook"><i class="fa fa-facebook"></i></a>
<a class="btn btn-social-icon btn-flickr"><i class="fa fa-flickr"></i></a>
<a class="btn btn-social-icon btn-foursquare"><i class="fa fa-foursquare"></i></a>
<a class="btn btn-social-icon btn-github"><i class="fa fa-github"></i></a>
<a class="btn btn-social-icon btn-google"><i class="fa fa-google-plus"></i></a>
<a class="btn btn-social-icon btn-instagram"><i class="fa fa-instagram"></i></a>
<a class="btn btn-social-icon btn-linkedin"><i class="fa fa-linkedin"></i></a>
<a class="btn btn-social-icon btn-tumblr"><i class="fa fa-tumblr"></i></a>
<a class="btn btn-social-icon btn-twitter"><i class="fa fa-twitter"></i></a>
<a class="btn btn-social-icon btn-vk"><i class="fa fa-vk"></i></a>
</div>
</div>
</div>
<!-- /.box -->
</div>
<!-- /.col -->
<div class="col-md-6">
<!-- Application buttons -->
<div class="box">
<div class="box-header">
<h3 class="box-title">Application Buttons</h3>
</div>
<div class="box-body">
<p>Add the classes <code>.btn.btn-app</code> to an <code><a></code> tag to achieve the following:</p>
<a class="btn btn-app">
<i class="fa fa-edit"></i> Edit
</a>
<a class="btn btn-app">
<i class="fa fa-play"></i> Play
</a>
<a class="btn btn-app">
<i class="fa fa-repeat"></i> Repeat
</a>
<a class="btn btn-app">
<i class="fa fa-pause"></i> Pause
</a>
<a class="btn btn-app">
<i class="fa fa-save"></i> Save
</a>
<a class="btn btn-app">
<span class="badge bg-yellow">3</span>
<i class="fa fa-bullhorn"></i> Notifications
</a>
<a class="btn btn-app">
<span class="badge bg-green">300</span>
<i class="fa fa-barcode"></i> Products
</a>
<a class="btn btn-app">
<span class="badge bg-purple">891</span>
<i class="fa fa-users"></i> Users
</a>
<a class="btn btn-app">
<span class="badge bg-teal">67</span>
<i class="fa fa-inbox"></i> Orders
</a>
<a class="btn btn-app">
<span class="badge bg-aqua">12</span>
<i class="fa fa-envelope"></i> Inbox
</a>
<a class="btn btn-app">
<span class="badge bg-red">531</span>
<i class="fa fa-heart-o"></i> Likes
</a>
</div>
<!-- /.box-body -->
</div>
<!-- /.box -->
<!-- Various colors -->
<div class="box">
<div class="box-header">
<h3 class="box-title">Different colors</h3>
</div>
<div class="box-body">
<p>Mix and match with various background colors. Use base class <code>.btn</code> and add any available
<code>.bg-*</code> class</p>
<!-- You may notice a .margin class added
here but that's only to make the content
display correctly without having to use a table-->
<p>
<button type="button" class="btn bg-maroon btn-flat margin">.btn.bg-maroon.btn-flat</button>
<button type="button" class="btn bg-purple btn-flat margin">.btn.bg-purple.btn-flat</button>
<button type="button" class="btn bg-navy btn-flat margin">.btn.bg-navy.btn-flat</button>
<button type="button" class="btn bg-orange btn-flat margin">.btn.bg-orange.btn-flat</button>
<button type="button" class="btn bg-olive btn-flat margin">.btn.bg-olive.btn-flat</button>
</p>
<p>
<button type="button" class="btn bg-maroon margin">.btn.bg-maroon</button>
<button type="button" class="btn bg-purple margin">.btn.bg-purple</button>
<button type="button" class="btn bg-navy margin">.btn.bg-navy</button>
<button type="button" class="btn bg-orange margin">.btn.bg-orange</button>
<button type="button" class="btn bg-olive margin">.btn.bg-olive</button>
</p>
</div>
</div>
<!-- /.box -->
<!-- Vertical grouping -->
<div class="box">
<div class="box-header">
<h3 class="box-title">Vertical Button Group</h3>
</div>
<div class="box-body table-responsive pad">
<p>
Vertical button groups are easy to create with bootstrap. Just add your buttons
inside <code><div class="btn-group-vertical"></div></code>
</p>
<table class="table table-bordered">
<tr>
<th>Button</th>
<th>Icons</th>
<th>Flat</th>
<th>Dropdown</th>
</tr>
<!-- Default -->
<tr>
<td>
<div class="btn-group-vertical">
<button type="button" class="btn btn-default">Top</button>
<button type="button" class="btn btn-default">Middle</button>
<button type="button" class="btn btn-default">Bottom</button>
</div>
</td>
<td>
<div class="btn-group-vertical">
<button type="button" class="btn btn-default"><i class="fa fa-align-left"></i></button>
<button type="button" class="btn btn-default"><i class="fa fa-align-center"></i></button>
<button type="button" class="btn btn-default"><i class="fa fa-align-right"></i></button>
</div>
</td>
<td>
<div class="btn-group-vertical">
<button type="button" class="btn btn-default btn-flat"><i class="fa fa-align-left"></i></button>
<button type="button" class="btn btn-default btn-flat"><i class="fa fa-align-center"></i></button>
<button type="button" class="btn btn-default btn-flat"><i class="fa fa-align-right"></i></button>
</div>
</td>
<td>
<div class="btn-group-vertical">
<button type="button" class="btn btn-default">1</button>
<button type="button" class="btn btn-default">2</button>
<div class="btn-group">
<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
<span class="caret"></span>
</button>
<ul class="dropdown-menu">
<li><a href="#">Dropdown link</a></li>
<li><a href="#">Dropdown link</a></li>
</ul>
</div>
</div>
</td>
</tr>
<!-- ./default -->
<!-- Info -->
<tr>
<td>
<div class="btn-group-vertical">
<button type="button" class="btn btn-info">Top</button>
<button type="button" class="btn btn-info">Middle</button>
<button type="button" class="btn btn-info">Bottom</button>
</div>
</td>
<td>
<div class="btn-group-vertical">
<button type="button" class="btn btn-info"><i class="fa fa-align-left"></i></button>
<button type="button" class="btn btn-info"><i class="fa fa-align-center"></i></button>
<button type="button" class="btn btn-info"><i class="fa fa-align-right"></i></button>
</div>
</td>
<td>
<div class="btn-group-vertical">
<button type="button" class="btn btn-info btn-flat"><i class="fa fa-align-left"></i></button>
<button type="button" class="btn btn-info btn-flat"><i class="fa fa-align-center"></i></button>
<button type="button" class="btn btn-info btn-flat"><i class="fa fa-align-right"></i></button>
</div>
</td>
<td>
<div class="btn-group-vertical">
<button type="button" class="btn btn-info">1</button>
<button type="button" class="btn btn-info">2</button>
<div class="btn-group">
<button type="button" class="btn btn-info dropdown-toggle" data-toggle="dropdown">
<span class="caret"></span>
</button>
<ul class="dropdown-menu">
<li><a href="#">Dropdown link</a></li>
<li><a href="#">Dropdown link</a></li>
</ul>
</div>
</div>
</td>
</tr>
<!-- /. info -->
<!-- /.danger -->
<tr>
<td>
<div class="btn-group-vertical">
<button type="button" class="btn btn-danger">Top</button>
<button type="button" class="btn btn-danger">Middle</button>
<button type="button" class="btn btn-danger">Bottom</button>
</div>
</td>
<td>
<div class="btn-group-vertical">
<button type="button" class="btn btn-danger"><i class="fa fa-align-left"></i></button>
<button type="button" class="btn btn-danger"><i class="fa fa-align-center"></i></button>
<button type="button" class="btn btn-danger"><i class="fa fa-align-right"></i></button>
</div>
</td>
<td>
<div class="btn-group-vertical">
<button type="button" class="btn btn-danger btn-flat"><i class="fa fa-align-left"></i></button>
<button type="button" class="btn btn-danger btn-flat"><i class="fa fa-align-center"></i></button>
<button type="button" class="btn btn-danger btn-flat"><i class="fa fa-align-right"></i></button>
</div>
</td>
<td>
<div class="btn-group-vertical">
<button type="button" class="btn btn-danger">1</button>
<button type="button" class="btn btn-danger">2</button>
<div class="btn-group">
<button type="button" class="btn btn-danger dropdown-toggle" data-toggle="dropdown">
<span class="caret"></span>
</button>
<ul class="dropdown-menu">
<li><a href="#">Dropdown link</a></li>
<li><a href="#">Dropdown link</a></li>
</ul>
</div>
</div>
</td>
</tr>
<!-- /.danger -->
<!-- warning -->
<tr>
<td>
<div class="btn-group-vertical">
<button type="button" class="btn btn-warning">Top</button>
<button type="button" class="btn btn-warning">Middle</button>
<button type="button" class="btn btn-warning">Bottom</button>
</div>
</td>
<td>
<div class="btn-group-vertical">
<button type="button" class="btn btn-warning"><i class="fa fa-align-left"></i></button>
<button type="button" class="btn btn-warning"><i class="fa fa-align-center"></i></button>
<button type="button" class="btn btn-warning"><i class="fa fa-align-right"></i></button>
</div>
</td>
<td>
<div class="btn-group-vertical">
<button type="button" class="btn btn-warning btn-flat"><i class="fa fa-align-left"></i></button>
<button type="button" class="btn btn-warning btn-flat"><i class="fa fa-align-center"></i></button>
<button type="button" class="btn btn-warning btn-flat"><i class="fa fa-align-right"></i></button>
</div>
</td>
<td>
<div class="btn-group-vertical">
<button type="button" class="btn btn-warning">1</button>
<button type="button" class="btn btn-warning">2</button>
<div class="btn-group">
<button type="button" class="btn btn-warning dropdown-toggle" data-toggle="dropdown">
<span class="caret"></span>
</button>
<ul class="dropdown-menu">
<li><a href="#">Dropdown link</a></li>
<li><a href="#">Dropdown link</a></li>
</ul>
</div>
</div>
</td>
</tr>
<!-- /.warning -->
<!-- success -->
<tr>
<td>
<div class="btn-group-vertical">
<button type="button" class="btn btn-success">Top</button>
<button type="button" class="btn btn-success">Middle</button>
<button type="button" class="btn btn-success">Bottom</button>
</div>
</td>
<td>
<div class="btn-group-vertical">
<button type="button" class="btn btn-success"><i class="fa fa-align-left"></i></button>
<button type="button" class="btn btn-success"><i class="fa fa-align-center"></i></button>
<button type="button" class="btn btn-success"><i class="fa fa-align-right"></i></button>
</div>
</td>
<td>
<div class="btn-group-vertical">
<button type="button" class="btn btn-success btn-flat"><i class="fa fa-align-left"></i></button>
<button type="button" class="btn btn-success btn-flat"><i class="fa fa-align-center"></i></button>
<button type="button" class="btn btn-success btn-flat"><i class="fa fa-align-right"></i></button>
</div>
</td>
<td>
<div class="btn-group-vertical">
<button type="button" class="btn btn-success">1</button>
<button type="button" class="btn btn-success">2</button>
<div class="btn-group">
<button type="button" class="btn btn-success dropdown-toggle" data-toggle="dropdown">
<span class="caret"></span>
</button>
<ul class="dropdown-menu">
<li><a href="#">Dropdown link</a></li>
<li><a href="#">Dropdown link</a></li>
</ul>
</div>
</div>
</td>
</tr>
<!-- /.success -->
</table>
</div>
<!-- /.box-body -->
</div>
<!-- /.box -->
</div>
<!-- /.col -->
</div>
<!-- /. row -->
</section>
<!-- /.content -->
</div>
<!-- /.content-wrapper -->
<footer class="main-footer">
<div class="pull-right hidden-xs">
<b>Version</b> 2.3.3
</div>
<strong>Copyright © 2014-2015 <a href="http://almsaeedstudio.com">Almsaeed Studio</a>.</strong> All rights
reserved.
</footer>
<!-- Control Sidebar -->
<aside class="control-sidebar control-sidebar-dark">
<!-- Create the tabs -->
<ul class="nav nav-tabs nav-justified control-sidebar-tabs">
<li><a href="#control-sidebar-home-tab" data-toggle="tab"><i class="fa fa-home"></i></a></li>
<li><a href="#control-sidebar-settings-tab" data-toggle="tab"><i class="fa fa-gears"></i></a></li>
</ul>
<!-- Tab panes -->
<div class="tab-content">
<!-- Home tab content -->
<div class="tab-pane" id="control-sidebar-home-tab">
<h3 class="control-sidebar-heading">Recent Activity</h3>
<ul class="control-sidebar-menu">
<li>
<a href="javascript:void(0)">
<i class="menu-icon fa fa-birthday-cake bg-red"></i>
<div class="menu-info">
<h4 class="control-sidebar-subheading">Langdon's Birthday</h4>
<p>Will be 23 on April 24th</p>
</div>
</a>
</li>
<li>
<a href="javascript:void(0)">
<i class="menu-icon fa fa-user bg-yellow"></i>
<div class="menu-info">
<h4 class="control-sidebar-subheading">Frodo Updated His Profile</h4>
<p>New phone +1(800)555-1234</p>
</div>
</a>
</li>
<li>
<a href="javascript:void(0)">
<i class="menu-icon fa fa-envelope-o bg-light-blue"></i>
<div class="menu-info">
<h4 class="control-sidebar-subheading">Nora Joined Mailing List</h4>
<p>nora@example.com</p>
</div>
</a>
</li>
<li>
<a href="javascript:void(0)">
<i class="menu-icon fa fa-file-code-o bg-green"></i>
<div class="menu-info">
<h4 class="control-sidebar-subheading">Cron Job 254 Executed</h4>
<p>Execution time 5 seconds</p>
</div>
</a>
</li>
</ul>
<!-- /.control-sidebar-menu -->
<h3 class="control-sidebar-heading">Tasks Progress</h3>
<ul class="control-sidebar-menu">
<li>
<a href="javascript:void(0)">
<h4 class="control-sidebar-subheading">
Custom Template Design
<span class="label label-danger pull-right">70%</span>
</h4>
<div class="progress progress-xxs">
<div class="progress-bar progress-bar-danger" style="width: 70%"></div>
</div>
</a>
</li>
<li>
<a href="javascript:void(0)">
<h4 class="control-sidebar-subheading">
Update Resume
<span class="label label-success pull-right">95%</span>
</h4>
<div class="progress progress-xxs">
<div class="progress-bar progress-bar-success" style="width: 95%"></div>
</div>
</a>
</li>
<li>
<a href="javascript:void(0)">
<h4 class="control-sidebar-subheading">
Laravel Integration
<span class="label label-warning pull-right">50%</span>
</h4>
<div class="progress progress-xxs">
<div class="progress-bar progress-bar-warning" style="width: 50%"></div>
</div>
</a>
</li>
<li>
<a href="javascript:void(0)">
<h4 class="control-sidebar-subheading">
Back End Framework
<span class="label label-primary pull-right">68%</span>
</h4>
<div class="progress progress-xxs">
<div class="progress-bar progress-bar-primary" style="width: 68%"></div>
</div>
</a>
</li>
</ul>
<!-- /.control-sidebar-menu -->
</div>
<!-- /.tab-pane -->
<!-- Stats tab content -->
<div class="tab-pane" id="control-sidebar-stats-tab">Stats Tab Content</div>
<!-- /.tab-pane -->
<!-- Settings tab content -->
<div class="tab-pane" id="control-sidebar-settings-tab">
<form method="post">
<h3 class="control-sidebar-heading">General Settings</h3>
<div class="form-group">
<label class="control-sidebar-subheading">
Report panel usage
<input type="checkbox" class="pull-right" checked>
</label>
<p>
Some information about this general settings option
</p>
</div>
<!-- /.form-group -->
<div class="form-group">
<label class="control-sidebar-subheading">
Allow mail redirect
<input type="checkbox" class="pull-right" checked>
</label>
<p>
Other sets of options are available
</p>
</div>
<!-- /.form-group -->
<div class="form-group">
<label class="control-sidebar-subheading">
Expose author name in posts
<input type="checkbox" class="pull-right" checked>
</label>
<p>
Allow the user to show his name in blog posts
</p>
</div>
<!-- /.form-group -->
<h3 class="control-sidebar-heading">Chat Settings</h3>
<div class="form-group">
<label class="control-sidebar-subheading">
Show me as online
<input type="checkbox" class="pull-right" checked>
</label>
</div>
<!-- /.form-group -->
<div class="form-group">
<label class="control-sidebar-subheading">
Turn off notifications
<input type="checkbox" class="pull-right">
</label>
</div>
<!-- /.form-group -->
<div class="form-group">
<label class="control-sidebar-subheading">
Delete chat history
<a href="javascript:void(0)" class="text-red pull-right"><i class="fa fa-trash-o"></i></a>
</label>
</div>
<!-- /.form-group -->
</form>
</div>
<!-- /.tab-pane -->
</div>
</aside>
<!-- /.control-sidebar -->
<!-- Add the sidebar's background. This div must be placed
immediately after the control sidebar -->
<div class="control-sidebar-bg"></div>
</div>
<!-- ./wrapper -->
<!-- jQuery 2.2.0 -->
<script src="../../plugins/jQuery/jQuery-2.2.0.min.js"></script>
<!-- Bootstrap 3.3.6 -->
<script src="../../bootstrap/js/bootstrap.min.js"></script>
<!-- FastClick -->
<script src="../../plugins/fastclick/fastclick.js"></script>
<!-- AdminLTE App -->
<script src="../../dist/js/app.min.js"></script>
<!-- AdminLTE for demo purposes -->
<script src="../../dist/js/demo.js"></script>
</body>
</html>
| hung101/kbs | frontend/web/assets/95b14de9/backend/pages/UI/buttons.html | HTML | bsd-3-clause | 76,008 |
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\debug\panels;
use Yii;
use yii\helpers\Html;
use yii\debug\Panel;
use yii\web\AssetBundle;
use yii\web\AssetManager;
/**
* Debugger panel that collects and displays asset bundles data.
*
* @author Artur Fursa <arturfursa@gmail.com>
* @since 2.0
*/
class AssetPanel extends Panel
{
/**
* @inheritdoc
*/
public function getName()
{
return 'Asset Bundles';
}
/**
* @inheritdoc
*/
public function getSummary()
{
return Yii::$app->view->render('panels/assets/summary', ['panel' => $this]);
}
/**
* @inheritdoc
*/
public function getDetail()
{
return Yii::$app->view->render('panels/assets/detail', ['panel' => $this]);
}
/**
* @inheritdoc
*/
public function save()
{
$bundles = Yii::$app->view->assetManager->bundles;
if (empty($bundles)) { // bundles can be false
return [];
}
$data = [];
foreach ($bundles as $name => $bundle) {
if ($bundle instanceof AssetBundle) {
$bundleData = (array) $bundle;
if (isset($bundleData['publishOptions']['beforeCopy']) && $bundleData['publishOptions']['beforeCopy'] instanceof \Closure) {
$bundleData['publishOptions']['beforeCopy'] = '\Closure';
}
if (isset($bundleData['publishOptions']['afterCopy']) && $bundleData['publishOptions']['afterCopy'] instanceof \Closure) {
$bundleData['publishOptions']['afterCopy'] = '\Closure';
}
$data[$name] = $bundleData;
}
}
return $data;
}
/**
* Additional formatting for view.
*
* @param AssetBundle[] $bundles Array of bundles to formatting.
*
* @return AssetManager
*/
protected function format(array $bundles)
{
foreach ($bundles as $bundle) {
$this->cssCount += count($bundle->css);
$this->jsCount += count($bundle->js);
array_walk($bundle->css, function(&$file, $key, $userdata) {
$file = Html::a($file, $userdata->baseUrl . '/' . $file, ['target' => '_blank']);
}, $bundle);
array_walk($bundle->js, function(&$file, $key, $userdata) {
$file = Html::a($file, $userdata->baseUrl . '/' . $file, ['target' => '_blank']);
}, $bundle);
array_walk($bundle->depends, function(&$depend) {
$depend = Html::a($depend, '#' . $depend);
});
$this->formatOptions($bundle->publishOptions);
$this->formatOptions($bundle->jsOptions);
$this->formatOptions($bundle->cssOptions);
}
return $bundles;
}
/**
* Format associative array of params to simple value.
*
* @param array $params
*
* @return array
*/
protected function formatOptions(array &$params)
{
if (!is_array($params)) {
return $params;
}
foreach ($params as $param => $value) {
$params[$param] = Html::tag('strong', '\'' . $param . '\' => ') . (string) $value;
}
return $params;
}
}
| henrique-r-luz/portal | vendor/yiisoft/yii2-debug/panels/AssetPanel.php | PHP | bsd-3-clause | 3,403 |
package com.facebook.react.animated;
import com.facebook.react.bridge.JSApplicationIllegalArgumentException;
import com.facebook.react.bridge.ReadableArray;
import com.facebook.react.bridge.ReadableMap;
import javax.annotation.Nullable;
/**
* Animated node that corresponds to {@code AnimatedInterpolation} from AnimatedImplementation.js.
*
* Currently only a linear interpolation is supported on an input range of an arbitrary size.
*/
/*package*/ class InterpolationAnimatedNode extends ValueAnimatedNode {
public static final String EXTRAPOLATE_TYPE_IDENTITY = "identity";
public static final String EXTRAPOLATE_TYPE_CLAMP = "clamp";
public static final String EXTRAPOLATE_TYPE_EXTEND = "extend";
private static double[] fromDoubleArray(ReadableArray ary) {
double[] res = new double[ary.size()];
for (int i = 0; i < res.length; i++) {
res[i] = ary.getDouble(i);
}
return res;
}
private static double interpolate(
double value,
double inputMin,
double inputMax,
double outputMin,
double outputMax,
String extrapolateLeft,
String extrapolateRight) {
double result = value;
// Extrapolate
if (result < inputMin) {
switch (extrapolateLeft) {
case EXTRAPOLATE_TYPE_IDENTITY:
return result;
case EXTRAPOLATE_TYPE_CLAMP:
result = inputMin;
break;
case EXTRAPOLATE_TYPE_EXTEND:
break;
default:
throw new JSApplicationIllegalArgumentException(
"Invalid extrapolation type " + extrapolateLeft + "for left extrapolation");
}
}
if (result > inputMax) {
switch (extrapolateRight) {
case EXTRAPOLATE_TYPE_IDENTITY:
return result;
case EXTRAPOLATE_TYPE_CLAMP:
result = inputMax;
break;
case EXTRAPOLATE_TYPE_EXTEND:
break;
default:
throw new JSApplicationIllegalArgumentException(
"Invalid extrapolation type " + extrapolateRight + "for right extrapolation");
}
}
return outputMin + (outputMax - outputMin) *
(result - inputMin) / (inputMax - inputMin);
}
/*package*/ static double interpolate(
double value,
double[] inputRange,
double[] outputRange,
String extrapolateLeft,
String extrapolateRight
) {
int rangeIndex = findRangeIndex(value, inputRange);
return interpolate(
value,
inputRange[rangeIndex],
inputRange[rangeIndex + 1],
outputRange[rangeIndex],
outputRange[rangeIndex + 1],
extrapolateLeft,
extrapolateRight);
}
private static int findRangeIndex(double value, double[] ranges) {
int index;
for (index = 1; index < ranges.length - 1; index++) {
if (ranges[index] >= value) {
break;
}
}
return index - 1;
}
private final double mInputRange[];
private final double mOutputRange[];
private final String mExtrapolateLeft;
private final String mExtrapolateRight;
private @Nullable ValueAnimatedNode mParent;
public InterpolationAnimatedNode(ReadableMap config) {
mInputRange = fromDoubleArray(config.getArray("inputRange"));
mOutputRange = fromDoubleArray(config.getArray("outputRange"));
mExtrapolateLeft = config.getString("extrapolateLeft");
mExtrapolateRight = config.getString("extrapolateRight");
}
@Override
public void onAttachedToNode(AnimatedNode parent) {
if (mParent != null) {
throw new IllegalStateException("Parent already attached");
}
if (!(parent instanceof ValueAnimatedNode)) {
throw new IllegalArgumentException("Parent is of an invalid type");
}
mParent = (ValueAnimatedNode) parent;
}
@Override
public void onDetachedFromNode(AnimatedNode parent) {
if (parent != mParent) {
throw new IllegalArgumentException("Invalid parent node provided");
}
mParent = null;
}
@Override
public void update() {
if (mParent == null) {
throw new IllegalStateException("Trying to update interpolation node that has not been " +
"attached to the parent");
}
mValue = interpolate(mParent.getValue(), mInputRange, mOutputRange, mExtrapolateLeft, mExtrapolateRight);
}
}
| ptomasroos/react-native | ReactAndroid/src/main/java/com/facebook/react/animated/InterpolationAnimatedNode.java | Java | bsd-3-clause | 4,263 |
//
// Copyright (c) 2002-2014 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
//
// Create symbols that declare built-in definitions, add built-ins that
// cannot be expressed in the files, and establish mappings between
// built-in functions and operators.
//
#include "compiler/translator/Initialize.h"
#include "compiler/translator/IntermNode.h"
#include "angle_gl.h"
void InsertBuiltInFunctions(sh::GLenum type, ShShaderSpec spec, const ShBuiltInResources &resources, TSymbolTable &symbolTable)
{
TType *float1 = new TType(EbtFloat);
TType *float2 = new TType(EbtFloat, 2);
TType *float3 = new TType(EbtFloat, 3);
TType *float4 = new TType(EbtFloat, 4);
TType *int1 = new TType(EbtInt);
TType *int2 = new TType(EbtInt, 2);
TType *int3 = new TType(EbtInt, 3);
TType *int4 = new TType(EbtInt, 4);
//
// Angle and Trigonometric Functions.
//
symbolTable.insertBuiltIn(COMMON_BUILTINS, float1, "radians", float1);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float2, "radians", float2);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float3, "radians", float3);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float4, "radians", float4);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float1, "degrees", float1);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float2, "degrees", float2);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float3, "degrees", float3);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float4, "degrees", float4);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float1, "sin", float1);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float2, "sin", float2);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float3, "sin", float3);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float4, "sin", float4);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float1, "cos", float1);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float2, "cos", float2);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float3, "cos", float3);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float4, "cos", float4);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float1, "tan", float1);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float2, "tan", float2);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float3, "tan", float3);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float4, "tan", float4);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float1, "asin", float1);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float2, "asin", float2);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float3, "asin", float3);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float4, "asin", float4);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float1, "acos", float1);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float2, "acos", float2);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float3, "acos", float3);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float4, "acos", float4);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float1, "atan", float1, float1);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float2, "atan", float2, float2);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float3, "atan", float3, float3);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float4, "atan", float4, float4);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float1, "atan", float1);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float2, "atan", float2);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float3, "atan", float3);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float4, "atan", float4);
//
// Exponential Functions.
//
symbolTable.insertBuiltIn(COMMON_BUILTINS, float1, "pow", float1, float1);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float2, "pow", float2, float2);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float3, "pow", float3, float3);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float4, "pow", float4, float4);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float1, "exp", float1);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float2, "exp", float2);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float3, "exp", float3);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float4, "exp", float4);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float1, "log", float1);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float2, "log", float2);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float3, "log", float3);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float4, "log", float4);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float1, "exp2", float1);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float2, "exp2", float2);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float3, "exp2", float3);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float4, "exp2", float4);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float1, "log2", float1);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float2, "log2", float2);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float3, "log2", float3);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float4, "log2", float4);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float1, "sqrt", float1);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float2, "sqrt", float2);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float3, "sqrt", float3);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float4, "sqrt", float4);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float1, "inversesqrt", float1);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float2, "inversesqrt", float2);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float3, "inversesqrt", float3);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float4, "inversesqrt", float4);
//
// Common Functions.
//
symbolTable.insertBuiltIn(COMMON_BUILTINS, float1, "abs", float1);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float2, "abs", float2);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float3, "abs", float3);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float4, "abs", float4);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float1, "sign", float1);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float2, "sign", float2);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float3, "sign", float3);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float4, "sign", float4);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float1, "floor", float1);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float2, "floor", float2);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float3, "floor", float3);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float4, "floor", float4);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float1, "ceil", float1);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float2, "ceil", float2);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float3, "ceil", float3);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float4, "ceil", float4);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float1, "fract", float1);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float2, "fract", float2);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float3, "fract", float3);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float4, "fract", float4);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float1, "mod", float1, float1);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float2, "mod", float2, float1);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float3, "mod", float3, float1);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float4, "mod", float4, float1);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float2, "mod", float2, float2);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float3, "mod", float3, float3);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float4, "mod", float4, float4);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float1, "min", float1, float1);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float2, "min", float2, float1);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float3, "min", float3, float1);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float4, "min", float4, float1);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float2, "min", float2, float2);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float3, "min", float3, float3);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float4, "min", float4, float4);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float1, "max", float1, float1);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float2, "max", float2, float1);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float3, "max", float3, float1);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float4, "max", float4, float1);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float2, "max", float2, float2);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float3, "max", float3, float3);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float4, "max", float4, float4);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float1, "clamp", float1, float1, float1);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float2, "clamp", float2, float1, float1);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float3, "clamp", float3, float1, float1);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float4, "clamp", float4, float1, float1);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float2, "clamp", float2, float2, float2);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float3, "clamp", float3, float3, float3);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float4, "clamp", float4, float4, float4);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float1, "mix", float1, float1, float1);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float2, "mix", float2, float2, float1);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float3, "mix", float3, float3, float1);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float4, "mix", float4, float4, float1);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float2, "mix", float2, float2, float2);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float3, "mix", float3, float3, float3);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float4, "mix", float4, float4, float4);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float1, "step", float1, float1);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float2, "step", float2, float2);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float3, "step", float3, float3);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float4, "step", float4, float4);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float2, "step", float1, float2);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float3, "step", float1, float3);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float4, "step", float1, float4);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float1, "smoothstep", float1, float1, float1);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float2, "smoothstep", float2, float2, float2);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float3, "smoothstep", float3, float3, float3);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float4, "smoothstep", float4, float4, float4);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float2, "smoothstep", float1, float1, float2);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float3, "smoothstep", float1, float1, float3);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float4, "smoothstep", float1, float1, float4);
//
// Geometric Functions.
//
symbolTable.insertBuiltIn(COMMON_BUILTINS, float1, "length", float1);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float1, "length", float2);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float1, "length", float3);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float1, "length", float4);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float1, "distance", float1, float1);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float1, "distance", float2, float2);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float1, "distance", float3, float3);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float1, "distance", float4, float4);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float1, "dot", float1, float1);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float1, "dot", float2, float2);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float1, "dot", float3, float3);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float1, "dot", float4, float4);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float3, "cross", float3, float3);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float1, "normalize", float1);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float2, "normalize", float2);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float3, "normalize", float3);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float4, "normalize", float4);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float1, "faceforward", float1, float1, float1);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float2, "faceforward", float2, float2, float2);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float3, "faceforward", float3, float3, float3);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float4, "faceforward", float4, float4, float4);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float1, "reflect", float1, float1);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float2, "reflect", float2, float2);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float3, "reflect", float3, float3);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float4, "reflect", float4, float4);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float1, "refract", float1, float1, float1);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float2, "refract", float2, float2, float1);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float3, "refract", float3, float3, float1);
symbolTable.insertBuiltIn(COMMON_BUILTINS, float4, "refract", float4, float4, float1);
TType *mat2 = new TType(EbtFloat, 2, 2);
TType *mat3 = new TType(EbtFloat, 3, 3);
TType *mat4 = new TType(EbtFloat, 4, 4);
//
// Matrix Functions.
//
symbolTable.insertBuiltIn(COMMON_BUILTINS, mat2, "matrixCompMult", mat2, mat2);
symbolTable.insertBuiltIn(COMMON_BUILTINS, mat3, "matrixCompMult", mat3, mat3);
symbolTable.insertBuiltIn(COMMON_BUILTINS, mat4, "matrixCompMult", mat4, mat4);
TType *bool1 = new TType(EbtBool);
TType *bool2 = new TType(EbtBool, 2);
TType *bool3 = new TType(EbtBool, 3);
TType *bool4 = new TType(EbtBool, 4);
//
// Vector relational functions.
//
symbolTable.insertBuiltIn(COMMON_BUILTINS, bool2, "lessThan", float2, float2);
symbolTable.insertBuiltIn(COMMON_BUILTINS, bool3, "lessThan", float3, float3);
symbolTable.insertBuiltIn(COMMON_BUILTINS, bool4, "lessThan", float4, float4);
symbolTable.insertBuiltIn(COMMON_BUILTINS, bool2, "lessThan", int2, int2);
symbolTable.insertBuiltIn(COMMON_BUILTINS, bool3, "lessThan", int3, int3);
symbolTable.insertBuiltIn(COMMON_BUILTINS, bool4, "lessThan", int4, int4);
symbolTable.insertBuiltIn(COMMON_BUILTINS, bool2, "lessThanEqual", float2, float2);
symbolTable.insertBuiltIn(COMMON_BUILTINS, bool3, "lessThanEqual", float3, float3);
symbolTable.insertBuiltIn(COMMON_BUILTINS, bool4, "lessThanEqual", float4, float4);
symbolTable.insertBuiltIn(COMMON_BUILTINS, bool2, "lessThanEqual", int2, int2);
symbolTable.insertBuiltIn(COMMON_BUILTINS, bool3, "lessThanEqual", int3, int3);
symbolTable.insertBuiltIn(COMMON_BUILTINS, bool4, "lessThanEqual", int4, int4);
symbolTable.insertBuiltIn(COMMON_BUILTINS, bool2, "greaterThan", float2, float2);
symbolTable.insertBuiltIn(COMMON_BUILTINS, bool3, "greaterThan", float3, float3);
symbolTable.insertBuiltIn(COMMON_BUILTINS, bool4, "greaterThan", float4, float4);
symbolTable.insertBuiltIn(COMMON_BUILTINS, bool2, "greaterThan", int2, int2);
symbolTable.insertBuiltIn(COMMON_BUILTINS, bool3, "greaterThan", int3, int3);
symbolTable.insertBuiltIn(COMMON_BUILTINS, bool4, "greaterThan", int4, int4);
symbolTable.insertBuiltIn(COMMON_BUILTINS, bool2, "greaterThanEqual", float2, float2);
symbolTable.insertBuiltIn(COMMON_BUILTINS, bool3, "greaterThanEqual", float3, float3);
symbolTable.insertBuiltIn(COMMON_BUILTINS, bool4, "greaterThanEqual", float4, float4);
symbolTable.insertBuiltIn(COMMON_BUILTINS, bool2, "greaterThanEqual", int2, int2);
symbolTable.insertBuiltIn(COMMON_BUILTINS, bool3, "greaterThanEqual", int3, int3);
symbolTable.insertBuiltIn(COMMON_BUILTINS, bool4, "greaterThanEqual", int4, int4);
symbolTable.insertBuiltIn(COMMON_BUILTINS, bool2, "equal", float2, float2);
symbolTable.insertBuiltIn(COMMON_BUILTINS, bool3, "equal", float3, float3);
symbolTable.insertBuiltIn(COMMON_BUILTINS, bool4, "equal", float4, float4);
symbolTable.insertBuiltIn(COMMON_BUILTINS, bool2, "equal", int2, int2);
symbolTable.insertBuiltIn(COMMON_BUILTINS, bool3, "equal", int3, int3);
symbolTable.insertBuiltIn(COMMON_BUILTINS, bool4, "equal", int4, int4);
symbolTable.insertBuiltIn(COMMON_BUILTINS, bool2, "equal", bool2, bool2);
symbolTable.insertBuiltIn(COMMON_BUILTINS, bool3, "equal", bool3, bool3);
symbolTable.insertBuiltIn(COMMON_BUILTINS, bool4, "equal", bool4, bool4);
symbolTable.insertBuiltIn(COMMON_BUILTINS, bool2, "notEqual", float2, float2);
symbolTable.insertBuiltIn(COMMON_BUILTINS, bool3, "notEqual", float3, float3);
symbolTable.insertBuiltIn(COMMON_BUILTINS, bool4, "notEqual", float4, float4);
symbolTable.insertBuiltIn(COMMON_BUILTINS, bool2, "notEqual", int2, int2);
symbolTable.insertBuiltIn(COMMON_BUILTINS, bool3, "notEqual", int3, int3);
symbolTable.insertBuiltIn(COMMON_BUILTINS, bool4, "notEqual", int4, int4);
symbolTable.insertBuiltIn(COMMON_BUILTINS, bool2, "notEqual", bool2, bool2);
symbolTable.insertBuiltIn(COMMON_BUILTINS, bool3, "notEqual", bool3, bool3);
symbolTable.insertBuiltIn(COMMON_BUILTINS, bool4, "notEqual", bool4, bool4);
symbolTable.insertBuiltIn(COMMON_BUILTINS, bool1, "any", bool2);
symbolTable.insertBuiltIn(COMMON_BUILTINS, bool1, "any", bool3);
symbolTable.insertBuiltIn(COMMON_BUILTINS, bool1, "any", bool4);
symbolTable.insertBuiltIn(COMMON_BUILTINS, bool1, "all", bool2);
symbolTable.insertBuiltIn(COMMON_BUILTINS, bool1, "all", bool3);
symbolTable.insertBuiltIn(COMMON_BUILTINS, bool1, "all", bool4);
symbolTable.insertBuiltIn(COMMON_BUILTINS, bool2, "not", bool2);
symbolTable.insertBuiltIn(COMMON_BUILTINS, bool3, "not", bool3);
symbolTable.insertBuiltIn(COMMON_BUILTINS, bool4, "not", bool4);
TType *sampler2D = new TType(EbtSampler2D);
TType *samplerCube = new TType(EbtSamplerCube);
//
// Texture Functions for GLSL ES 1.0
//
symbolTable.insertBuiltIn(ESSL1_BUILTINS, float4, "texture2D", sampler2D, float2);
symbolTable.insertBuiltIn(ESSL1_BUILTINS, float4, "texture2DProj", sampler2D, float3);
symbolTable.insertBuiltIn(ESSL1_BUILTINS, float4, "texture2DProj", sampler2D, float4);
symbolTable.insertBuiltIn(ESSL1_BUILTINS, float4, "textureCube", samplerCube, float3);
if (resources.OES_EGL_image_external)
{
TType *samplerExternalOES = new TType(EbtSamplerExternalOES);
symbolTable.insertBuiltIn(ESSL1_BUILTINS, float4, "texture2D", samplerExternalOES, float2);
symbolTable.insertBuiltIn(ESSL1_BUILTINS, float4, "texture2DProj", samplerExternalOES, float3);
symbolTable.insertBuiltIn(ESSL1_BUILTINS, float4, "texture2DProj", samplerExternalOES, float4);
}
if (resources.ARB_texture_rectangle)
{
TType *sampler2DRect = new TType(EbtSampler2DRect);
symbolTable.insertBuiltIn(ESSL1_BUILTINS, float4, "texture2DRect", sampler2DRect, float2);
symbolTable.insertBuiltIn(ESSL1_BUILTINS, float4, "texture2DRectProj", sampler2DRect, float3);
symbolTable.insertBuiltIn(ESSL1_BUILTINS, float4, "texture2DRectProj", sampler2DRect, float4);
}
if (resources.EXT_shader_texture_lod)
{
/* The *Grad* variants are new to both vertex and fragment shaders; the fragment
* shader specific pieces are added separately below.
*/
symbolTable.insertBuiltIn(ESSL1_BUILTINS, float4, "texture2DGradEXT", sampler2D, float2, float2, float2);
symbolTable.insertBuiltIn(ESSL1_BUILTINS, float4, "texture2DProjGradEXT", sampler2D, float3, float2, float2);
symbolTable.insertBuiltIn(ESSL1_BUILTINS, float4, "texture2DProjGradEXT", sampler2D, float4, float2, float2);
symbolTable.insertBuiltIn(ESSL1_BUILTINS, float4, "textureCubeGradEXT", samplerCube, float3, float3, float3);
}
if (type == GL_FRAGMENT_SHADER)
{
symbolTable.insertBuiltIn(ESSL1_BUILTINS, float4, "texture2D", sampler2D, float2, float1);
symbolTable.insertBuiltIn(ESSL1_BUILTINS, float4, "texture2DProj", sampler2D, float3, float1);
symbolTable.insertBuiltIn(ESSL1_BUILTINS, float4, "texture2DProj", sampler2D, float4, float1);
symbolTable.insertBuiltIn(ESSL1_BUILTINS, float4, "textureCube", samplerCube, float3, float1);
if (resources.OES_standard_derivatives)
{
symbolTable.insertBuiltIn(ESSL1_BUILTINS, float1, "dFdx", float1);
symbolTable.insertBuiltIn(ESSL1_BUILTINS, float2, "dFdx", float2);
symbolTable.insertBuiltIn(ESSL1_BUILTINS, float3, "dFdx", float3);
symbolTable.insertBuiltIn(ESSL1_BUILTINS, float4, "dFdx", float4);
symbolTable.insertBuiltIn(ESSL1_BUILTINS, float1, "dFdy", float1);
symbolTable.insertBuiltIn(ESSL1_BUILTINS, float2, "dFdy", float2);
symbolTable.insertBuiltIn(ESSL1_BUILTINS, float3, "dFdy", float3);
symbolTable.insertBuiltIn(ESSL1_BUILTINS, float4, "dFdy", float4);
symbolTable.insertBuiltIn(ESSL1_BUILTINS, float1, "fwidth", float1);
symbolTable.insertBuiltIn(ESSL1_BUILTINS, float2, "fwidth", float2);
symbolTable.insertBuiltIn(ESSL1_BUILTINS, float3, "fwidth", float3);
symbolTable.insertBuiltIn(ESSL1_BUILTINS, float4, "fwidth", float4);
}
if (resources.EXT_shader_texture_lod)
{
symbolTable.insertBuiltIn(ESSL1_BUILTINS, float4, "texture2DLodEXT", sampler2D, float2, float1);
symbolTable.insertBuiltIn(ESSL1_BUILTINS, float4, "texture2DProjLodEXT", sampler2D, float3, float1);
symbolTable.insertBuiltIn(ESSL1_BUILTINS, float4, "texture2DProjLodEXT", sampler2D, float4, float1);
symbolTable.insertBuiltIn(ESSL1_BUILTINS, float4, "textureCubeLodEXT", samplerCube, float3, float1);
}
}
if(type == GL_VERTEX_SHADER)
{
symbolTable.insertBuiltIn(ESSL1_BUILTINS, float4, "texture2DLod", sampler2D, float2, float1);
symbolTable.insertBuiltIn(ESSL1_BUILTINS, float4, "texture2DProjLod", sampler2D, float3, float1);
symbolTable.insertBuiltIn(ESSL1_BUILTINS, float4, "texture2DProjLod", sampler2D, float4, float1);
symbolTable.insertBuiltIn(ESSL1_BUILTINS, float4, "textureCubeLod", samplerCube, float3, float1);
}
TType *gvec4 = new TType(EbtGVec4);
TType *gsampler2D = new TType(EbtGSampler2D);
TType *gsamplerCube = new TType(EbtGSamplerCube);
TType *gsampler3D = new TType(EbtGSampler3D);
TType *gsampler2DArray = new TType(EbtGSampler2DArray);
//
// Texture Functions for GLSL ES 3.0
//
symbolTable.insertBuiltIn(ESSL3_BUILTINS, gvec4, "texture", gsampler2D, float2);
symbolTable.insertBuiltIn(ESSL3_BUILTINS, gvec4, "texture", gsampler3D, float3);
symbolTable.insertBuiltIn(ESSL3_BUILTINS, gvec4, "texture", gsamplerCube, float3);
symbolTable.insertBuiltIn(ESSL3_BUILTINS, gvec4, "texture", gsampler2DArray, float3);
symbolTable.insertBuiltIn(ESSL3_BUILTINS, gvec4, "textureProj", gsampler2D, float3);
symbolTable.insertBuiltIn(ESSL3_BUILTINS, gvec4, "textureProj", gsampler2D, float4);
symbolTable.insertBuiltIn(ESSL3_BUILTINS, gvec4, "textureProj", gsampler3D, float4);
symbolTable.insertBuiltIn(ESSL3_BUILTINS, gvec4, "textureLod", gsampler2D, float2, float1);
symbolTable.insertBuiltIn(ESSL3_BUILTINS, gvec4, "textureLod", gsampler3D, float3, float1);
symbolTable.insertBuiltIn(ESSL3_BUILTINS, gvec4, "textureLod", gsamplerCube, float3, float1);
symbolTable.insertBuiltIn(ESSL3_BUILTINS, gvec4, "textureLod", gsampler2DArray, float3, float1);
if (type == GL_FRAGMENT_SHADER)
{
symbolTable.insertBuiltIn(ESSL3_BUILTINS, gvec4, "texture", gsampler2D, float2, float1);
symbolTable.insertBuiltIn(ESSL3_BUILTINS, gvec4, "texture", gsampler3D, float3, float1);
symbolTable.insertBuiltIn(ESSL3_BUILTINS, gvec4, "texture", gsamplerCube, float3, float1);
symbolTable.insertBuiltIn(ESSL3_BUILTINS, gvec4, "texture", gsampler2DArray, float3, float1);
symbolTable.insertBuiltIn(ESSL3_BUILTINS, gvec4, "textureProj", gsampler2D, float3, float1);
symbolTable.insertBuiltIn(ESSL3_BUILTINS, gvec4, "textureProj", gsampler2D, float4, float1);
symbolTable.insertBuiltIn(ESSL3_BUILTINS, gvec4, "textureProj", gsampler3D, float4, float1);
}
TType *sampler2DShadow = new TType(EbtSampler2DShadow);
TType *samplerCubeShadow = new TType(EbtSamplerCubeShadow);
TType *sampler2DArrayShadow = new TType(EbtSampler2DArrayShadow);
symbolTable.insertBuiltIn(ESSL3_BUILTINS, float1, "texture", sampler2DShadow, float3);
symbolTable.insertBuiltIn(ESSL3_BUILTINS, float1, "texture", samplerCubeShadow, float4);
symbolTable.insertBuiltIn(ESSL3_BUILTINS, float1, "texture", sampler2DArrayShadow, float4);
symbolTable.insertBuiltIn(ESSL3_BUILTINS, float1, "textureProj", sampler2DShadow, float4);
symbolTable.insertBuiltIn(ESSL3_BUILTINS, float1, "textureLod", sampler2DShadow, float3, float1);
if (type == GL_FRAGMENT_SHADER)
{
symbolTable.insertBuiltIn(ESSL3_BUILTINS, float1, "texture", sampler2DShadow, float3, float1);
symbolTable.insertBuiltIn(ESSL3_BUILTINS, float1, "texture", samplerCubeShadow, float4, float1);
symbolTable.insertBuiltIn(ESSL3_BUILTINS, float1, "textureProj", sampler2DShadow, float4, float1);
}
symbolTable.insertBuiltIn(ESSL3_BUILTINS, int2, "textureSize", gsampler2D, int1);
symbolTable.insertBuiltIn(ESSL3_BUILTINS, int3, "textureSize", gsampler3D, int1);
symbolTable.insertBuiltIn(ESSL3_BUILTINS, int2, "textureSize", gsamplerCube, int1);
symbolTable.insertBuiltIn(ESSL3_BUILTINS, int3, "textureSize", gsampler2DArray, int1);
symbolTable.insertBuiltIn(ESSL3_BUILTINS, int2, "textureSize", sampler2DShadow, int1);
symbolTable.insertBuiltIn(ESSL3_BUILTINS, int2, "textureSize", samplerCubeShadow, int1);
symbolTable.insertBuiltIn(ESSL3_BUILTINS, int3, "textureSize", sampler2DArrayShadow, int1);
if(type == GL_FRAGMENT_SHADER)
{
symbolTable.insertBuiltIn(ESSL3_BUILTINS, float1, "dFdx", float1);
symbolTable.insertBuiltIn(ESSL3_BUILTINS, float2, "dFdx", float2);
symbolTable.insertBuiltIn(ESSL3_BUILTINS, float3, "dFdx", float3);
symbolTable.insertBuiltIn(ESSL3_BUILTINS, float4, "dFdx", float4);
symbolTable.insertBuiltIn(ESSL3_BUILTINS, float1, "dFdy", float1);
symbolTable.insertBuiltIn(ESSL3_BUILTINS, float2, "dFdy", float2);
symbolTable.insertBuiltIn(ESSL3_BUILTINS, float3, "dFdy", float3);
symbolTable.insertBuiltIn(ESSL3_BUILTINS, float4, "dFdy", float4);
symbolTable.insertBuiltIn(ESSL3_BUILTINS, float1, "fwidth", float1);
symbolTable.insertBuiltIn(ESSL3_BUILTINS, float2, "fwidth", float2);
symbolTable.insertBuiltIn(ESSL3_BUILTINS, float3, "fwidth", float3);
symbolTable.insertBuiltIn(ESSL3_BUILTINS, float4, "fwidth", float4);
}
symbolTable.insertBuiltIn(ESSL3_BUILTINS, gvec4, "textureOffset", gsampler2D, float2, int2);
symbolTable.insertBuiltIn(ESSL3_BUILTINS, gvec4, "textureOffset", gsampler3D, float3, int3);
symbolTable.insertBuiltIn(ESSL3_BUILTINS, float1, "textureOffset", sampler2DShadow, float3, int2);
symbolTable.insertBuiltIn(ESSL3_BUILTINS, gvec4, "textureOffset", gsampler2DArray, float3, int2);
if(type == GL_FRAGMENT_SHADER)
{
symbolTable.insertBuiltIn(ESSL3_BUILTINS, gvec4, "textureOffset", gsampler2D, float2, int2, float1);
symbolTable.insertBuiltIn(ESSL3_BUILTINS, gvec4, "textureOffset", gsampler3D, float3, int3, float1);
symbolTable.insertBuiltIn(ESSL3_BUILTINS, float1, "textureOffset", sampler2DShadow, float3, int2, float1);
symbolTable.insertBuiltIn(ESSL3_BUILTINS, gvec4, "textureOffset", gsampler2DArray, float3, int2, float1);
}
symbolTable.insertBuiltIn(ESSL3_BUILTINS, gvec4, "textureProjOffset", gsampler2D, float3, int2);
symbolTable.insertBuiltIn(ESSL3_BUILTINS, gvec4, "textureProjOffset", gsampler2D, float4, int2);
symbolTable.insertBuiltIn(ESSL3_BUILTINS, gvec4, "textureProjOffset", gsampler3D, float4, int3);
symbolTable.insertBuiltIn(ESSL3_BUILTINS, float1, "textureProjOffset", sampler2DShadow, float4, int2);
if(type == GL_FRAGMENT_SHADER)
{
symbolTable.insertBuiltIn(ESSL3_BUILTINS, gvec4, "textureProjOffset", gsampler2D, float3, int2, float1);
symbolTable.insertBuiltIn(ESSL3_BUILTINS, gvec4, "textureProjOffset", gsampler2D, float4, int2, float1);
symbolTable.insertBuiltIn(ESSL3_BUILTINS, gvec4, "textureProjOffset", gsampler3D, float4, int3, float1);
symbolTable.insertBuiltIn(ESSL3_BUILTINS, float1, "textureProjOffset", sampler2DShadow, float4, int2, float1);
}
symbolTable.insertBuiltIn(ESSL3_BUILTINS, gvec4, "textureLodOffset", gsampler2D, float2, float1, int2);
symbolTable.insertBuiltIn(ESSL3_BUILTINS, gvec4, "textureLodOffset", gsampler3D, float3, float1, int3);
symbolTable.insertBuiltIn(ESSL3_BUILTINS, float1, "textureLodOffset", sampler2DShadow, float3, float1, int2);
symbolTable.insertBuiltIn(ESSL3_BUILTINS, gvec4, "textureLodOffset", gsampler2DArray, float3, float1, int2);
symbolTable.insertBuiltIn(ESSL3_BUILTINS, gvec4, "textureProjLod", gsampler2D, float3, float1);
symbolTable.insertBuiltIn(ESSL3_BUILTINS, gvec4, "textureProjLod", gsampler2D, float4, float1);
symbolTable.insertBuiltIn(ESSL3_BUILTINS, gvec4, "textureProjLod", gsampler3D, float4, float1);
symbolTable.insertBuiltIn(ESSL3_BUILTINS, float1, "textureProjLod", sampler2DShadow, float4, float1);
symbolTable.insertBuiltIn(ESSL3_BUILTINS, gvec4, "textureProjLodOffset", gsampler2D, float3, float1, int2);
symbolTable.insertBuiltIn(ESSL3_BUILTINS, gvec4, "textureProjLodOffset", gsampler2D, float4, float1, int2);
symbolTable.insertBuiltIn(ESSL3_BUILTINS, gvec4, "textureProjLodOffset", gsampler3D, float4, float1, int3);
symbolTable.insertBuiltIn(ESSL3_BUILTINS, float1, "textureProjLodOffset", sampler2DShadow, float4, float1, int2);
symbolTable.insertBuiltIn(ESSL3_BUILTINS, gvec4, "texelFetch", gsampler2D, int2, int1);
symbolTable.insertBuiltIn(ESSL3_BUILTINS, gvec4, "texelFetch", gsampler3D, int3, int1);
symbolTable.insertBuiltIn(ESSL3_BUILTINS, gvec4, "texelFetch", gsampler2DArray, int3, int1);
symbolTable.insertBuiltIn(ESSL3_BUILTINS, gvec4, "texelFetchOffset", gsampler2D, int2, int1, int2);
symbolTable.insertBuiltIn(ESSL3_BUILTINS, gvec4, "texelFetchOffset", gsampler3D, int3, int1, int3);
symbolTable.insertBuiltIn(ESSL3_BUILTINS, gvec4, "texelFetchOffset", gsampler2DArray, int3, int1, int2);
symbolTable.insertBuiltIn(ESSL3_BUILTINS, gvec4, "textureGrad", gsampler2D, float2, float2, float2);
symbolTable.insertBuiltIn(ESSL3_BUILTINS, gvec4, "textureGrad", gsampler3D, float3, float3, float3);
symbolTable.insertBuiltIn(ESSL3_BUILTINS, gvec4, "textureGrad", gsamplerCube, float3, float3, float3);
symbolTable.insertBuiltIn(ESSL3_BUILTINS, float1, "textureGrad", sampler2DShadow, float3, float2, float2);
symbolTable.insertBuiltIn(ESSL3_BUILTINS, float1, "textureGrad", samplerCubeShadow, float4, float3, float3);
symbolTable.insertBuiltIn(ESSL3_BUILTINS, gvec4, "textureGrad", gsampler2DArray, float3, float2, float2);
symbolTable.insertBuiltIn(ESSL3_BUILTINS, float1, "textureGrad", sampler2DArrayShadow, float4, float2, float2);
symbolTable.insertBuiltIn(ESSL3_BUILTINS, gvec4, "textureGradOffset", gsampler2D, float2, float2, float2, int2);
symbolTable.insertBuiltIn(ESSL3_BUILTINS, gvec4, "textureGradOffset", gsampler3D, float3, float3, float3, int3);
symbolTable.insertBuiltIn(ESSL3_BUILTINS, float1, "textureGradOffset", sampler2DShadow, float3, float2, float2, int2);
symbolTable.insertBuiltIn(ESSL3_BUILTINS, gvec4, "textureGradOffset", gsampler2DArray, float3, float2, float2, int2);
symbolTable.insertBuiltIn(ESSL3_BUILTINS, float1, "textureGradOffset", sampler2DArrayShadow, float4, float2, float2, int2);
symbolTable.insertBuiltIn(ESSL3_BUILTINS, gvec4, "textureProjGrad", gsampler2D, float3, float2, float2);
symbolTable.insertBuiltIn(ESSL3_BUILTINS, gvec4, "textureProjGrad", gsampler2D, float4, float2, float2);
symbolTable.insertBuiltIn(ESSL3_BUILTINS, gvec4, "textureProjGrad", gsampler3D, float4, float3, float3);
symbolTable.insertBuiltIn(ESSL3_BUILTINS, float1, "textureProjGrad", sampler2DShadow, float4, float2, float2);
symbolTable.insertBuiltIn(ESSL3_BUILTINS, gvec4, "textureProjGradOffset", gsampler2D, float3, float2, float2, int2);
symbolTable.insertBuiltIn(ESSL3_BUILTINS, gvec4, "textureProjGradOffset", gsampler2D, float4, float2, float2, int2);
symbolTable.insertBuiltIn(ESSL3_BUILTINS, gvec4, "textureProjGradOffset", gsampler3D, float4, float3, float3, int3);
symbolTable.insertBuiltIn(ESSL3_BUILTINS, float1, "textureProjGradOffset", sampler2DShadow, float4, float2, float2, int2);
//
// Depth range in window coordinates
//
TFieldList *fields = NewPoolTFieldList();
TSourceLoc zeroSourceLoc = {0, 0, 0, 0};
TField *near = new TField(new TType(EbtFloat, EbpHigh, EvqGlobal, 1), NewPoolTString("near"), zeroSourceLoc);
TField *far = new TField(new TType(EbtFloat, EbpHigh, EvqGlobal, 1), NewPoolTString("far"), zeroSourceLoc);
TField *diff = new TField(new TType(EbtFloat, EbpHigh, EvqGlobal, 1), NewPoolTString("diff"), zeroSourceLoc);
fields->push_back(near);
fields->push_back(far);
fields->push_back(diff);
TStructure *depthRangeStruct = new TStructure(NewPoolTString("gl_DepthRangeParameters"), fields);
TVariable *depthRangeParameters = new TVariable(&depthRangeStruct->name(), depthRangeStruct, true);
symbolTable.insert(COMMON_BUILTINS, depthRangeParameters);
TVariable *depthRange = new TVariable(NewPoolTString("gl_DepthRange"), TType(depthRangeStruct));
depthRange->setQualifier(EvqUniform);
symbolTable.insert(COMMON_BUILTINS, depthRange);
//
// Implementation dependent built-in constants.
//
symbolTable.insertConstInt(COMMON_BUILTINS, "gl_MaxVertexAttribs", resources.MaxVertexAttribs);
symbolTable.insertConstInt(COMMON_BUILTINS, "gl_MaxVertexUniformVectors", resources.MaxVertexUniformVectors);
symbolTable.insertConstInt(COMMON_BUILTINS, "gl_MaxVertexTextureImageUnits", resources.MaxVertexTextureImageUnits);
symbolTable.insertConstInt(COMMON_BUILTINS, "gl_MaxCombinedTextureImageUnits", resources.MaxCombinedTextureImageUnits);
symbolTable.insertConstInt(COMMON_BUILTINS, "gl_MaxTextureImageUnits", resources.MaxTextureImageUnits);
symbolTable.insertConstInt(COMMON_BUILTINS, "gl_MaxFragmentUniformVectors", resources.MaxFragmentUniformVectors);
symbolTable.insertConstInt(ESSL1_BUILTINS, "gl_MaxVaryingVectors", resources.MaxVaryingVectors);
if (spec != SH_CSS_SHADERS_SPEC)
{
symbolTable.insertConstInt(COMMON_BUILTINS, "gl_MaxDrawBuffers", resources.MaxDrawBuffers);
}
symbolTable.insertConstInt(ESSL3_BUILTINS, "gl_MaxVertexOutputVectors", resources.MaxVertexOutputVectors);
symbolTable.insertConstInt(ESSL3_BUILTINS, "gl_MaxFragmentInputVectors", resources.MaxFragmentInputVectors);
symbolTable.insertConstInt(ESSL3_BUILTINS, "gl_MinProgramTexelOffset", resources.MinProgramTexelOffset);
symbolTable.insertConstInt(ESSL3_BUILTINS, "gl_MaxProgramTexelOffset", resources.MaxProgramTexelOffset);
}
void IdentifyBuiltIns(sh::GLenum type, ShShaderSpec spec,
const ShBuiltInResources &resources,
TSymbolTable &symbolTable)
{
//
// First, insert some special built-in variables that are not in
// the built-in header files.
//
switch(type) {
case GL_FRAGMENT_SHADER:
symbolTable.insert(COMMON_BUILTINS, new TVariable(NewPoolTString("gl_FragCoord"), TType(EbtFloat, EbpMedium, EvqFragCoord, 4)));
symbolTable.insert(COMMON_BUILTINS, new TVariable(NewPoolTString("gl_FrontFacing"), TType(EbtBool, EbpUndefined, EvqFrontFacing, 1)));
symbolTable.insert(COMMON_BUILTINS, new TVariable(NewPoolTString("gl_PointCoord"), TType(EbtFloat, EbpMedium, EvqPointCoord, 2)));
//
// In CSS Shaders, gl_FragColor, gl_FragData, and gl_MaxDrawBuffers are not available.
// Instead, css_MixColor and css_ColorMatrix are available.
//
if (spec != SH_CSS_SHADERS_SPEC) {
symbolTable.insert(ESSL1_BUILTINS, new TVariable(NewPoolTString("gl_FragColor"), TType(EbtFloat, EbpMedium, EvqFragColor, 4)));
symbolTable.insert(ESSL1_BUILTINS, new TVariable(NewPoolTString("gl_FragData[gl_MaxDrawBuffers]"), TType(EbtFloat, EbpMedium, EvqFragData, 4)));
if (resources.EXT_frag_depth) {
symbolTable.insert(ESSL1_BUILTINS, new TVariable(NewPoolTString("gl_FragDepthEXT"), TType(EbtFloat, resources.FragmentPrecisionHigh ? EbpHigh : EbpMedium, EvqFragDepth, 1)));
symbolTable.relateToExtension(ESSL1_BUILTINS, "gl_FragDepthEXT", "GL_EXT_frag_depth");
}
} else {
symbolTable.insert(ESSL1_BUILTINS, new TVariable(NewPoolTString("css_MixColor"), TType(EbtFloat, EbpMedium, EvqGlobal, 4)));
symbolTable.insert(ESSL1_BUILTINS, new TVariable(NewPoolTString("css_ColorMatrix"), TType(EbtFloat, EbpMedium, EvqGlobal, 4, 4)));
}
break;
case GL_VERTEX_SHADER:
symbolTable.insert(COMMON_BUILTINS, new TVariable(NewPoolTString("gl_Position"), TType(EbtFloat, EbpHigh, EvqPosition, 4)));
symbolTable.insert(COMMON_BUILTINS, new TVariable(NewPoolTString("gl_PointSize"), TType(EbtFloat, EbpMedium, EvqPointSize, 1)));
break;
default: assert(false && "Language not supported");
}
//
// Next, identify which built-ins from the already loaded headers have
// a mapping to an operator. Those that are not identified as such are
// expected to be resolved through a library of functions, versus as
// operations.
//
symbolTable.relateToOperator(COMMON_BUILTINS, "matrixCompMult", EOpMul);
symbolTable.relateToOperator(COMMON_BUILTINS, "equal", EOpVectorEqual);
symbolTable.relateToOperator(COMMON_BUILTINS, "notEqual", EOpVectorNotEqual);
symbolTable.relateToOperator(COMMON_BUILTINS, "lessThan", EOpLessThan);
symbolTable.relateToOperator(COMMON_BUILTINS, "greaterThan", EOpGreaterThan);
symbolTable.relateToOperator(COMMON_BUILTINS, "lessThanEqual", EOpLessThanEqual);
symbolTable.relateToOperator(COMMON_BUILTINS, "greaterThanEqual", EOpGreaterThanEqual);
symbolTable.relateToOperator(COMMON_BUILTINS, "radians", EOpRadians);
symbolTable.relateToOperator(COMMON_BUILTINS, "degrees", EOpDegrees);
symbolTable.relateToOperator(COMMON_BUILTINS, "sin", EOpSin);
symbolTable.relateToOperator(COMMON_BUILTINS, "cos", EOpCos);
symbolTable.relateToOperator(COMMON_BUILTINS, "tan", EOpTan);
symbolTable.relateToOperator(COMMON_BUILTINS, "asin", EOpAsin);
symbolTable.relateToOperator(COMMON_BUILTINS, "acos", EOpAcos);
symbolTable.relateToOperator(COMMON_BUILTINS, "atan", EOpAtan);
symbolTable.relateToOperator(COMMON_BUILTINS, "pow", EOpPow);
symbolTable.relateToOperator(COMMON_BUILTINS, "exp2", EOpExp2);
symbolTable.relateToOperator(COMMON_BUILTINS, "log", EOpLog);
symbolTable.relateToOperator(COMMON_BUILTINS, "exp", EOpExp);
symbolTable.relateToOperator(COMMON_BUILTINS, "log2", EOpLog2);
symbolTable.relateToOperator(COMMON_BUILTINS, "sqrt", EOpSqrt);
symbolTable.relateToOperator(COMMON_BUILTINS, "inversesqrt", EOpInverseSqrt);
symbolTable.relateToOperator(COMMON_BUILTINS, "abs", EOpAbs);
symbolTable.relateToOperator(COMMON_BUILTINS, "sign", EOpSign);
symbolTable.relateToOperator(COMMON_BUILTINS, "floor", EOpFloor);
symbolTable.relateToOperator(COMMON_BUILTINS, "ceil", EOpCeil);
symbolTable.relateToOperator(COMMON_BUILTINS, "fract", EOpFract);
symbolTable.relateToOperator(COMMON_BUILTINS, "mod", EOpMod);
symbolTable.relateToOperator(COMMON_BUILTINS, "min", EOpMin);
symbolTable.relateToOperator(COMMON_BUILTINS, "max", EOpMax);
symbolTable.relateToOperator(COMMON_BUILTINS, "clamp", EOpClamp);
symbolTable.relateToOperator(COMMON_BUILTINS, "mix", EOpMix);
symbolTable.relateToOperator(COMMON_BUILTINS, "step", EOpStep);
symbolTable.relateToOperator(COMMON_BUILTINS, "smoothstep", EOpSmoothStep);
symbolTable.relateToOperator(COMMON_BUILTINS, "length", EOpLength);
symbolTable.relateToOperator(COMMON_BUILTINS, "distance", EOpDistance);
symbolTable.relateToOperator(COMMON_BUILTINS, "dot", EOpDot);
symbolTable.relateToOperator(COMMON_BUILTINS, "cross", EOpCross);
symbolTable.relateToOperator(COMMON_BUILTINS, "normalize", EOpNormalize);
symbolTable.relateToOperator(COMMON_BUILTINS, "faceforward", EOpFaceForward);
symbolTable.relateToOperator(COMMON_BUILTINS, "reflect", EOpReflect);
symbolTable.relateToOperator(COMMON_BUILTINS, "refract", EOpRefract);
symbolTable.relateToOperator(COMMON_BUILTINS, "any", EOpAny);
symbolTable.relateToOperator(COMMON_BUILTINS, "all", EOpAll);
symbolTable.relateToOperator(COMMON_BUILTINS, "not", EOpVectorLogicalNot);
// Map language-specific operators.
switch(type) {
case GL_VERTEX_SHADER:
break;
case GL_FRAGMENT_SHADER:
if (resources.OES_standard_derivatives)
{
symbolTable.relateToOperator(ESSL1_BUILTINS, "dFdx", EOpDFdx);
symbolTable.relateToOperator(ESSL1_BUILTINS, "dFdy", EOpDFdy);
symbolTable.relateToOperator(ESSL1_BUILTINS, "fwidth", EOpFwidth);
symbolTable.relateToExtension(ESSL1_BUILTINS, "dFdx", "GL_OES_standard_derivatives");
symbolTable.relateToExtension(ESSL1_BUILTINS, "dFdy", "GL_OES_standard_derivatives");
symbolTable.relateToExtension(ESSL1_BUILTINS, "fwidth", "GL_OES_standard_derivatives");
}
if (resources.EXT_shader_texture_lod)
{
symbolTable.relateToExtension(ESSL1_BUILTINS, "texture2DLodEXT", "GL_EXT_shader_texture_lod");
symbolTable.relateToExtension(ESSL1_BUILTINS, "texture2DProjLodEXT", "GL_EXT_shader_texture_lod");
symbolTable.relateToExtension(ESSL1_BUILTINS, "textureCubeLodEXT", "GL_EXT_shader_texture_lod");
}
break;
default: break;
}
symbolTable.relateToOperator(ESSL3_BUILTINS, "dFdx", EOpDFdx);
symbolTable.relateToOperator(ESSL3_BUILTINS, "dFdy", EOpDFdy);
symbolTable.relateToOperator(ESSL3_BUILTINS, "fwidth", EOpFwidth);
if (resources.EXT_shader_texture_lod)
{
symbolTable.relateToExtension(ESSL1_BUILTINS, "texture2DGradEXT", "GL_EXT_shader_texture_lod");
symbolTable.relateToExtension(ESSL1_BUILTINS, "texture2DProjGradEXT", "GL_EXT_shader_texture_lod");
symbolTable.relateToExtension(ESSL1_BUILTINS, "textureCubeGradEXT", "GL_EXT_shader_texture_lod");
}
// Finally add resource-specific variables.
switch(type) {
case GL_FRAGMENT_SHADER:
if (spec != SH_CSS_SHADERS_SPEC) {
// Set up gl_FragData. The array size.
TType fragData(EbtFloat, EbpMedium, EvqFragData, 4, 1, true);
fragData.setArraySize(resources.MaxDrawBuffers);
symbolTable.insert(ESSL1_BUILTINS, new TVariable(NewPoolTString("gl_FragData"), fragData));
}
break;
default: break;
}
}
void InitExtensionBehavior(const ShBuiltInResources& resources,
TExtensionBehavior& extBehavior)
{
if (resources.OES_standard_derivatives)
extBehavior["GL_OES_standard_derivatives"] = EBhUndefined;
if (resources.OES_EGL_image_external)
extBehavior["GL_OES_EGL_image_external"] = EBhUndefined;
if (resources.ARB_texture_rectangle)
extBehavior["GL_ARB_texture_rectangle"] = EBhUndefined;
if (resources.EXT_draw_buffers)
extBehavior["GL_EXT_draw_buffers"] = EBhUndefined;
if (resources.EXT_frag_depth)
extBehavior["GL_EXT_frag_depth"] = EBhUndefined;
if (resources.EXT_shader_texture_lod)
extBehavior["GL_EXT_shader_texture_lod"] = EBhUndefined;
}
| dongritengfei/phantomjs | src/qt/qtbase/src/3rdparty/angle/src/compiler/translator/Initialize.cpp | C++ | bsd-3-clause | 45,457 |
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Db\Adapter\Driver\Oci8;
use Zend\Db\Adapter\Driver\StatementInterface;
use Zend\Db\Adapter\Exception;
use Zend\Db\Adapter\ParameterContainer;
use Zend\Db\Adapter\Profiler;
class Statement implements StatementInterface, Profiler\ProfilerAwareInterface
{
/**
* @var resource
*/
protected $oci8 = null;
/**
* @var Oci8
*/
protected $driver = null;
/**
* @var Profiler\ProfilerInterface
*/
protected $profiler = null;
/**
* @var string
*/
protected $sql = '';
/**
* Parameter container
*
* @var ParameterContainer
*/
protected $parameterContainer = null;
/**
* @var resource
*/
protected $resource = null;
/**
* Is prepared
*
* @var bool
*/
protected $isPrepared = false;
/**
* @var bool
*/
protected $bufferResults = false;
/**
* Set driver
*
* @param Oci8 $driver
* @return Statement
*/
public function setDriver($driver)
{
$this->driver = $driver;
return $this;
}
/**
* @param Profiler\ProfilerInterface $profiler
* @return Statement
*/
public function setProfiler(Profiler\ProfilerInterface $profiler)
{
$this->profiler = $profiler;
return $this;
}
/**
* @return null|Profiler\ProfilerInterface
*/
public function getProfiler()
{
return $this->profiler;
}
/**
* Initialize
*
* @param resource $oci8
* @return Statement
*/
public function initialize($oci8)
{
$this->oci8 = $oci8;
return $this;
}
/**
* Set sql
*
* @param string $sql
* @return Statement
*/
public function setSql($sql)
{
$this->sql = $sql;
return $this;
}
/**
* Set Parameter container
*
* @param ParameterContainer $parameterContainer
* @return Statement
*/
public function setParameterContainer(ParameterContainer $parameterContainer)
{
$this->parameterContainer = $parameterContainer;
return $this;
}
/**
* Get resource
*
* @return mixed
*/
public function getResource()
{
return $this->resource;
}
/**
* Set resource
*
* @param resource $oci8Statement
* @return Statement
*/
public function setResource($oci8Statement)
{
$type = oci_statement_type($oci8Statement);
if (false === $type || 'UNKNOWN' == $type) {
throw new Exception\InvalidArgumentException(sprintf(
'Invalid statement provided to %s',
__METHOD__
));
}
$this->resource = $oci8Statement;
$this->isPrepared = true;
return $this;
}
/**
* Get sql
*
* @return string
*/
public function getSql()
{
return $this->sql;
}
/**
* @return ParameterContainer
*/
public function getParameterContainer()
{
return $this->parameterContainer;
}
/**
* @return bool
*/
public function isPrepared()
{
return $this->isPrepared;
}
/**
* @param string $sql
* @return Statement
*/
public function prepare($sql = null)
{
if ($this->isPrepared) {
throw new Exception\RuntimeException('This statement has already been prepared');
}
$sql = ($sql) ?: $this->sql;
// get oci8 statement resource
$this->resource = oci_parse($this->oci8, $sql);
if (!$this->resource) {
$e = oci_error($this->oci8);
throw new Exception\InvalidQueryException(
'Statement couldn\'t be produced with sql: ' . $sql,
null,
new Exception\ErrorException($e['message'], $e['code'])
);
}
$this->isPrepared = true;
return $this;
}
/**
* Execute
*
* @param ParameterContainer $parameters
* @return mixed
*/
public function execute($parameters = null)
{
if (!$this->isPrepared) {
$this->prepare();
}
/** START Standard ParameterContainer Merging Block */
if (!$this->parameterContainer instanceof ParameterContainer) {
if ($parameters instanceof ParameterContainer) {
$this->parameterContainer = $parameters;
$parameters = null;
} else {
$this->parameterContainer = new ParameterContainer();
}
}
if (is_array($parameters)) {
$this->parameterContainer->setFromArray($parameters);
}
if ($this->parameterContainer->count() > 0) {
$this->bindParametersFromContainer();
}
/** END Standard ParameterContainer Merging Block */
if ($this->profiler) {
$this->profiler->profilerStart($this);
}
if ($this->driver->getConnection()->inTransaction()) {
$ret = @oci_execute($this->resource, OCI_NO_AUTO_COMMIT);
} else {
$ret = @oci_execute($this->resource, OCI_COMMIT_ON_SUCCESS);
}
if ($this->profiler) {
$this->profiler->profilerFinish();
}
if ($ret === false) {
$e = oci_error($this->resource);
throw new Exception\RuntimeException($e['message'], $e['code']);
}
$result = $this->driver->createResult($this->resource);
return $result;
}
/**
* Bind parameters from container
*
* @param ParameterContainer $pContainer
*/
protected function bindParametersFromContainer()
{
$parameters = $this->parameterContainer->getNamedArray();
foreach ($parameters as $name => &$value) {
if ($this->parameterContainer->offsetHasErrata($name)) {
switch ($this->parameterContainer->offsetGetErrata($name)) {
case ParameterContainer::TYPE_NULL:
$type = null;
$value = null;
break;
case ParameterContainer::TYPE_DOUBLE:
case ParameterContainer::TYPE_INTEGER:
$type = SQLT_INT;
if (is_string($value)) {
$value = (int) $value;
}
break;
case ParameterContainer::TYPE_BINARY:
$type = SQLT_BIN;
break;
case ParameterContainer::TYPE_LOB:
$type = OCI_B_CLOB;
$clob = oci_new_descriptor($this->driver->getConnection()->getResource(), OCI_DTYPE_LOB);
$clob->writetemporary($value, OCI_TEMP_CLOB);
$value = $clob;
break;
case ParameterContainer::TYPE_STRING:
default:
$type = SQLT_CHR;
break;
}
} else {
$type = SQLT_CHR;
}
oci_bind_by_name($this->resource, $name, $value, -1, $type);
}
}
}
| pepeam/zend | library/Zend/Db/Adapter/Driver/Oci8/Statement.php | PHP | bsd-3-clause | 7,670 |
/**
* @license
* Lo-Dash 2.4.2 <https://lodash.com/>
* Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
* Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
* Available under MIT license <https://lodash.com/license>
*/
;(function() {
/** Used as a safe reference for `undefined` in pre ES5 environments */
var undefined;
/** Used to pool arrays and objects used internally */
var arrayPool = [],
objectPool = [];
/** Used to generate unique IDs */
var idCounter = 0;
/** Used internally to indicate various things */
var indicatorObject = {};
/** Used to prefix keys to avoid issues with `__proto__` and properties on `Object.prototype` */
var keyPrefix = +new Date + '';
/** Used as the size when optimizations are enabled for large arrays */
var largeArraySize = 75;
/** Used as the max size of the `arrayPool` and `objectPool` */
var maxPoolSize = 40;
/** Used to detect and test whitespace */
var whitespace = (
// whitespace
' \t\x0B\f\xA0\ufeff' +
// line terminators
'\n\r\u2028\u2029' +
// unicode category "Zs" space separators
'\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000'
);
/** Used to match empty string literals in compiled template source */
var reEmptyStringLeading = /\b__p \+= '';/g,
reEmptyStringMiddle = /\b(__p \+=) '' \+/g,
reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g;
/**
* Used to match ES6 template delimiters
* http://people.mozilla.org/~jorendorff/es6-draft.html#sec-literals-string-literals
*/
var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g;
/** Used to match regexp flags from their coerced string values */
var reFlags = /\w*$/;
/** Used to detected named functions */
var reFuncName = /^\s*function[ \n\r\t]+\w/;
/** Used to match "interpolate" template delimiters */
var reInterpolate = /<%=([\s\S]+?)%>/g;
/** Used to match leading whitespace and zeros to be removed */
var reLeadingSpacesAndZeros = RegExp('^[' + whitespace + ']*0+(?=.$)');
/** Used to ensure capturing order of template delimiters */
var reNoMatch = /($^)/;
/** Used to detect functions containing a `this` reference */
var reThis = /\bthis\b/;
/** Used to match unescaped characters in compiled string literals */
var reUnescapedString = /['\n\r\t\u2028\u2029\\]/g;
/** Used to assign default `context` object properties */
var contextProps = [
'Array', 'Boolean', 'Date', 'Error', 'Function', 'Math', 'Number', 'Object',
'RegExp', 'String', '_', 'attachEvent', 'clearTimeout', 'isFinite', 'isNaN',
'parseInt', 'setTimeout'
];
/** Used to fix the JScript [[DontEnum]] bug */
var shadowedProps = [
'constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable',
'toLocaleString', 'toString', 'valueOf'
];
/** Used to make template sourceURLs easier to identify */
var templateCounter = 0;
/** `Object#toString` result shortcuts */
var argsClass = '[object Arguments]',
arrayClass = '[object Array]',
boolClass = '[object Boolean]',
dateClass = '[object Date]',
errorClass = '[object Error]',
funcClass = '[object Function]',
numberClass = '[object Number]',
objectClass = '[object Object]',
regexpClass = '[object RegExp]',
stringClass = '[object String]';
/** Used to identify object classifications that `_.clone` supports */
var cloneableClasses = {};
cloneableClasses[funcClass] = false;
cloneableClasses[argsClass] = cloneableClasses[arrayClass] =
cloneableClasses[boolClass] = cloneableClasses[dateClass] =
cloneableClasses[numberClass] = cloneableClasses[objectClass] =
cloneableClasses[regexpClass] = cloneableClasses[stringClass] = true;
/** Used as an internal `_.debounce` options object */
var debounceOptions = {
'leading': false,
'maxWait': 0,
'trailing': false
};
/** Used as the property descriptor for `__bindData__` */
var descriptor = {
'configurable': false,
'enumerable': false,
'value': null,
'writable': false
};
/** Used as the data object for `iteratorTemplate` */
var iteratorData = {
'args': '',
'array': null,
'bottom': '',
'firstArg': '',
'init': '',
'keys': null,
'loop': '',
'shadowedProps': null,
'support': null,
'top': '',
'useHas': false
};
/** Used to determine if values are of the language type Object */
var objectTypes = {
'boolean': false,
'function': true,
'object': true,
'number': false,
'string': false,
'undefined': false
};
/** Used to escape characters for inclusion in compiled string literals */
var stringEscapes = {
'\\': '\\',
"'": "'",
'\n': 'n',
'\r': 'r',
'\t': 't',
'\u2028': 'u2028',
'\u2029': 'u2029'
};
/** Used as a reference to the global object */
var root = (objectTypes[typeof window] && window) || this;
/** Detect free variable `exports` */
var freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports;
/** Detect free variable `module` */
var freeModule = objectTypes[typeof module] && module && !module.nodeType && module;
/** Detect the popular CommonJS extension `module.exports` */
var moduleExports = freeModule && freeModule.exports === freeExports && freeExports;
/** Detect free variable `global` from Node.js or Browserified code and use it as `root` */
var freeGlobal = objectTypes[typeof global] && global;
if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) {
root = freeGlobal;
}
/*--------------------------------------------------------------------------*/
/**
* The base implementation of `_.indexOf` without support for binary searches
* or `fromIndex` constraints.
*
* @private
* @param {Array} array The array to search.
* @param {*} value The value to search for.
* @param {number} [fromIndex=0] The index to search from.
* @returns {number} Returns the index of the matched value or `-1`.
*/
function baseIndexOf(array, value, fromIndex) {
var index = (fromIndex || 0) - 1,
length = array ? array.length : 0;
while (++index < length) {
if (array[index] === value) {
return index;
}
}
return -1;
}
/**
* An implementation of `_.contains` for cache objects that mimics the return
* signature of `_.indexOf` by returning `0` if the value is found, else `-1`.
*
* @private
* @param {Object} cache The cache object to inspect.
* @param {*} value The value to search for.
* @returns {number} Returns `0` if `value` is found, else `-1`.
*/
function cacheIndexOf(cache, value) {
var type = typeof value;
cache = cache.cache;
if (type == 'boolean' || value == null) {
return cache[value] ? 0 : -1;
}
if (type != 'number' && type != 'string') {
type = 'object';
}
var key = type == 'number' ? value : keyPrefix + value;
cache = (cache = cache[type]) && cache[key];
return type == 'object'
? (cache && baseIndexOf(cache, value) > -1 ? 0 : -1)
: (cache ? 0 : -1);
}
/**
* Adds a given value to the corresponding cache object.
*
* @private
* @param {*} value The value to add to the cache.
*/
function cachePush(value) {
var cache = this.cache,
type = typeof value;
if (type == 'boolean' || value == null) {
cache[value] = true;
} else {
if (type != 'number' && type != 'string') {
type = 'object';
}
var key = type == 'number' ? value : keyPrefix + value,
typeCache = cache[type] || (cache[type] = {});
if (type == 'object') {
(typeCache[key] || (typeCache[key] = [])).push(value);
} else {
typeCache[key] = true;
}
}
}
/**
* Used by `_.max` and `_.min` as the default callback when a given
* collection is a string value.
*
* @private
* @param {string} value The character to inspect.
* @returns {number} Returns the code unit of given character.
*/
function charAtCallback(value) {
return value.charCodeAt(0);
}
/**
* Used by `sortBy` to compare transformed `collection` elements, stable sorting
* them in ascending order.
*
* @private
* @param {Object} a The object to compare to `b`.
* @param {Object} b The object to compare to `a`.
* @returns {number} Returns the sort order indicator of `1` or `-1`.
*/
function compareAscending(a, b) {
var ac = a.criteria,
bc = b.criteria,
index = -1,
length = ac.length;
while (++index < length) {
var value = ac[index],
other = bc[index];
if (value !== other) {
if (value > other || typeof value == 'undefined') {
return 1;
}
if (value < other || typeof other == 'undefined') {
return -1;
}
}
}
// Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications
// that causes it, under certain circumstances, to return the same value for
// `a` and `b`. See https://github.com/jashkenas/underscore/pull/1247
//
// This also ensures a stable sort in V8 and other engines.
// See http://code.google.com/p/v8/issues/detail?id=90
return a.index - b.index;
}
/**
* Creates a cache object to optimize linear searches of large arrays.
*
* @private
* @param {Array} [array=[]] The array to search.
* @returns {null|Object} Returns the cache object or `null` if caching should not be used.
*/
function createCache(array) {
var index = -1,
length = array.length,
first = array[0],
mid = array[(length / 2) | 0],
last = array[length - 1];
if (first && typeof first == 'object' &&
mid && typeof mid == 'object' && last && typeof last == 'object') {
return false;
}
var cache = getObject();
cache['false'] = cache['null'] = cache['true'] = cache['undefined'] = false;
var result = getObject();
result.array = array;
result.cache = cache;
result.push = cachePush;
while (++index < length) {
result.push(array[index]);
}
return result;
}
/**
* Used by `template` to escape characters for inclusion in compiled
* string literals.
*
* @private
* @param {string} match The matched character to escape.
* @returns {string} Returns the escaped character.
*/
function escapeStringChar(match) {
return '\\' + stringEscapes[match];
}
/**
* Gets an array from the array pool or creates a new one if the pool is empty.
*
* @private
* @returns {Array} The array from the pool.
*/
function getArray() {
return arrayPool.pop() || [];
}
/**
* Gets an object from the object pool or creates a new one if the pool is empty.
*
* @private
* @returns {Object} The object from the pool.
*/
function getObject() {
return objectPool.pop() || {
'array': null,
'cache': null,
'criteria': null,
'false': false,
'index': 0,
'null': false,
'number': null,
'object': null,
'push': null,
'string': null,
'true': false,
'undefined': false,
'value': null
};
}
/**
* Checks if `value` is a DOM node in IE < 9.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if the `value` is a DOM node, else `false`.
*/
function isNode(value) {
// IE < 9 presents DOM nodes as `Object` objects except they have `toString`
// methods that are `typeof` "string" and still can coerce nodes to strings
return typeof value.toString != 'function' && typeof (value + '') == 'string';
}
/**
* Releases the given array back to the array pool.
*
* @private
* @param {Array} [array] The array to release.
*/
function releaseArray(array) {
array.length = 0;
if (arrayPool.length < maxPoolSize) {
arrayPool.push(array);
}
}
/**
* Releases the given object back to the object pool.
*
* @private
* @param {Object} [object] The object to release.
*/
function releaseObject(object) {
var cache = object.cache;
if (cache) {
releaseObject(cache);
}
object.array = object.cache = object.criteria = object.object = object.number = object.string = object.value = null;
if (objectPool.length < maxPoolSize) {
objectPool.push(object);
}
}
/**
* Slices the `collection` from the `start` index up to, but not including,
* the `end` index.
*
* Note: This function is used instead of `Array#slice` to support node lists
* in IE < 9 and to ensure dense arrays are returned.
*
* @private
* @param {Array|Object|string} collection The collection to slice.
* @param {number} start The start index.
* @param {number} end The end index.
* @returns {Array} Returns the new array.
*/
function slice(array, start, end) {
start || (start = 0);
if (typeof end == 'undefined') {
end = array ? array.length : 0;
}
var index = -1,
length = end - start || 0,
result = Array(length < 0 ? 0 : length);
while (++index < length) {
result[index] = array[start + index];
}
return result;
}
/*--------------------------------------------------------------------------*/
/**
* Create a new `lodash` function using the given context object.
*
* @static
* @memberOf _
* @category Utilities
* @param {Object} [context=root] The context object.
* @returns {Function} Returns the `lodash` function.
*/
function runInContext(context) {
// Avoid issues with some ES3 environments that attempt to use values, named
// after built-in constructors like `Object`, for the creation of literals.
// ES5 clears this up by stating that literals must use built-in constructors.
// See http://es5.github.io/#x11.1.5.
context = context ? _.defaults(root.Object(), context, _.pick(root, contextProps)) : root;
/** Native constructor references */
var Array = context.Array,
Boolean = context.Boolean,
Date = context.Date,
Error = context.Error,
Function = context.Function,
Math = context.Math,
Number = context.Number,
Object = context.Object,
RegExp = context.RegExp,
String = context.String,
TypeError = context.TypeError;
/**
* Used for `Array` method references.
*
* Normally `Array.prototype` would suffice, however, using an array literal
* avoids issues in Narwhal.
*/
var arrayRef = [];
/** Used for native method references */
var errorProto = Error.prototype,
objectProto = Object.prototype,
stringProto = String.prototype;
/** Used to restore the original `_` reference in `noConflict` */
var oldDash = context._;
/** Used to resolve the internal [[Class]] of values */
var toString = objectProto.toString;
/** Used to detect if a method is native */
var reNative = RegExp('^' +
String(toString)
.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
.replace(/toString| for [^\]]+/g, '.*?') + '$'
);
/** Native method shortcuts */
var ceil = Math.ceil,
clearTimeout = context.clearTimeout,
floor = Math.floor,
fnToString = Function.prototype.toString,
getPrototypeOf = isNative(getPrototypeOf = Object.getPrototypeOf) && getPrototypeOf,
hasOwnProperty = objectProto.hasOwnProperty,
push = arrayRef.push,
propertyIsEnumerable = objectProto.propertyIsEnumerable,
setTimeout = context.setTimeout,
splice = arrayRef.splice,
unshift = arrayRef.unshift;
/** Used to set meta data on functions */
var defineProperty = (function() {
// IE 8 only accepts DOM elements
try {
var o = {},
func = isNative(func = Object.defineProperty) && func,
result = func(o, o, o) && func;
} catch(e) { }
return result;
}());
/* Native method shortcuts for methods with the same name as other `lodash` methods */
var nativeCreate = isNative(nativeCreate = Object.create) && nativeCreate,
nativeIsArray = isNative(nativeIsArray = Array.isArray) && nativeIsArray,
nativeIsFinite = context.isFinite,
nativeIsNaN = context.isNaN,
nativeKeys = isNative(nativeKeys = Object.keys) && nativeKeys,
nativeMax = Math.max,
nativeMin = Math.min,
nativeParseInt = context.parseInt,
nativeRandom = Math.random;
/** Used to lookup a built-in constructor by [[Class]] */
var ctorByClass = {};
ctorByClass[arrayClass] = Array;
ctorByClass[boolClass] = Boolean;
ctorByClass[dateClass] = Date;
ctorByClass[funcClass] = Function;
ctorByClass[objectClass] = Object;
ctorByClass[numberClass] = Number;
ctorByClass[regexpClass] = RegExp;
ctorByClass[stringClass] = String;
/** Used to avoid iterating non-enumerable properties in IE < 9 */
var nonEnumProps = {};
nonEnumProps[arrayClass] = nonEnumProps[dateClass] = nonEnumProps[numberClass] = { 'constructor': true, 'toLocaleString': true, 'toString': true, 'valueOf': true };
nonEnumProps[boolClass] = nonEnumProps[stringClass] = { 'constructor': true, 'toString': true, 'valueOf': true };
nonEnumProps[errorClass] = nonEnumProps[funcClass] = nonEnumProps[regexpClass] = { 'constructor': true, 'toString': true };
nonEnumProps[objectClass] = { 'constructor': true };
(function() {
var length = shadowedProps.length;
while (length--) {
var key = shadowedProps[length];
for (var className in nonEnumProps) {
if (hasOwnProperty.call(nonEnumProps, className) && !hasOwnProperty.call(nonEnumProps[className], key)) {
nonEnumProps[className][key] = false;
}
}
}
}());
/*--------------------------------------------------------------------------*/
/**
* Creates a `lodash` object which wraps the given value to enable intuitive
* method chaining.
*
* In addition to Lo-Dash methods, wrappers also have the following `Array` methods:
* `concat`, `join`, `pop`, `push`, `reverse`, `shift`, `slice`, `sort`, `splice`,
* and `unshift`
*
* Chaining is supported in custom builds as long as the `value` method is
* implicitly or explicitly included in the build.
*
* The chainable wrapper functions are:
* `after`, `assign`, `bind`, `bindAll`, `bindKey`, `chain`, `compact`,
* `compose`, `concat`, `countBy`, `create`, `createCallback`, `curry`,
* `debounce`, `defaults`, `defer`, `delay`, `difference`, `filter`, `flatten`,
* `forEach`, `forEachRight`, `forIn`, `forInRight`, `forOwn`, `forOwnRight`,
* `functions`, `groupBy`, `indexBy`, `initial`, `intersection`, `invert`,
* `invoke`, `keys`, `map`, `max`, `memoize`, `merge`, `min`, `object`, `omit`,
* `once`, `pairs`, `partial`, `partialRight`, `pick`, `pluck`, `pull`, `push`,
* `range`, `reject`, `remove`, `rest`, `reverse`, `shuffle`, `slice`, `sort`,
* `sortBy`, `splice`, `tap`, `throttle`, `times`, `toArray`, `transform`,
* `union`, `uniq`, `unshift`, `unzip`, `values`, `where`, `without`, `wrap`,
* and `zip`
*
* The non-chainable wrapper functions are:
* `clone`, `cloneDeep`, `contains`, `escape`, `every`, `find`, `findIndex`,
* `findKey`, `findLast`, `findLastIndex`, `findLastKey`, `has`, `identity`,
* `indexOf`, `isArguments`, `isArray`, `isBoolean`, `isDate`, `isElement`,
* `isEmpty`, `isEqual`, `isFinite`, `isFunction`, `isNaN`, `isNull`, `isNumber`,
* `isObject`, `isPlainObject`, `isRegExp`, `isString`, `isUndefined`, `join`,
* `lastIndexOf`, `mixin`, `noConflict`, `parseInt`, `pop`, `random`, `reduce`,
* `reduceRight`, `result`, `shift`, `size`, `some`, `sortedIndex`, `runInContext`,
* `template`, `unescape`, `uniqueId`, and `value`
*
* The wrapper functions `first` and `last` return wrapped values when `n` is
* provided, otherwise they return unwrapped values.
*
* Explicit chaining can be enabled by using the `_.chain` method.
*
* @name _
* @constructor
* @category Chaining
* @param {*} value The value to wrap in a `lodash` instance.
* @returns {Object} Returns a `lodash` instance.
* @example
*
* var wrapped = _([1, 2, 3]);
*
* // returns an unwrapped value
* wrapped.reduce(function(sum, num) {
* return sum + num;
* });
* // => 6
*
* // returns a wrapped value
* var squares = wrapped.map(function(num) {
* return num * num;
* });
*
* _.isArray(squares);
* // => false
*
* _.isArray(squares.value());
* // => true
*/
function lodash(value) {
// don't wrap if already wrapped, even if wrapped by a different `lodash` constructor
return (value && typeof value == 'object' && !isArray(value) && hasOwnProperty.call(value, '__wrapped__'))
? value
: new lodashWrapper(value);
}
/**
* A fast path for creating `lodash` wrapper objects.
*
* @private
* @param {*} value The value to wrap in a `lodash` instance.
* @param {boolean} chainAll A flag to enable chaining for all methods
* @returns {Object} Returns a `lodash` instance.
*/
function lodashWrapper(value, chainAll) {
this.__chain__ = !!chainAll;
this.__wrapped__ = value;
}
// ensure `new lodashWrapper` is an instance of `lodash`
lodashWrapper.prototype = lodash.prototype;
/**
* An object used to flag environments features.
*
* @static
* @memberOf _
* @type Object
*/
var support = lodash.support = {};
(function() {
var ctor = function() { this.x = 1; },
object = { '0': 1, 'length': 1 },
props = [];
ctor.prototype = { 'valueOf': 1, 'y': 1 };
for (var key in new ctor) { props.push(key); }
for (key in arguments) { }
/**
* Detect if an `arguments` object's [[Class]] is resolvable (all but Firefox < 4, IE < 9).
*
* @memberOf _.support
* @type boolean
*/
support.argsClass = toString.call(arguments) == argsClass;
/**
* Detect if `arguments` objects are `Object` objects (all but Narwhal and Opera < 10.5).
*
* @memberOf _.support
* @type boolean
*/
support.argsObject = arguments.constructor == Object && !(arguments instanceof Array);
/**
* Detect if `name` or `message` properties of `Error.prototype` are
* enumerable by default. (IE < 9, Safari < 5.1)
*
* @memberOf _.support
* @type boolean
*/
support.enumErrorProps = propertyIsEnumerable.call(errorProto, 'message') || propertyIsEnumerable.call(errorProto, 'name');
/**
* Detect if `prototype` properties are enumerable by default.
*
* Firefox < 3.6, Opera > 9.50 - Opera < 11.60, and Safari < 5.1
* (if the prototype or a property on the prototype has been set)
* incorrectly sets a function's `prototype` property [[Enumerable]]
* value to `true`.
*
* @memberOf _.support
* @type boolean
*/
support.enumPrototypes = propertyIsEnumerable.call(ctor, 'prototype');
/**
* Detect if functions can be decompiled by `Function#toString`
* (all but PS3 and older Opera mobile browsers & avoided in Windows 8 apps).
*
* @memberOf _.support
* @type boolean
*/
support.funcDecomp = !isNative(context.WinRTError) && reThis.test(runInContext);
/**
* Detect if `Function#name` is supported (all but IE).
*
* @memberOf _.support
* @type boolean
*/
support.funcNames = typeof Function.name == 'string';
/**
* Detect if `arguments` object indexes are non-enumerable
* (Firefox < 4, IE < 9, PhantomJS, Safari < 5.1).
*
* @memberOf _.support
* @type boolean
*/
support.nonEnumArgs = key != 0;
/**
* Detect if properties shadowing those on `Object.prototype` are non-enumerable.
*
* In IE < 9 an objects own properties, shadowing non-enumerable ones, are
* made non-enumerable as well (a.k.a the JScript [[DontEnum]] bug).
*
* @memberOf _.support
* @type boolean
*/
support.nonEnumShadows = !/valueOf/.test(props);
/**
* Detect if own properties are iterated after inherited properties (all but IE < 9).
*
* @memberOf _.support
* @type boolean
*/
support.ownLast = props[0] != 'x';
/**
* Detect if `Array#shift` and `Array#splice` augment array-like objects correctly.
*
* Firefox < 10, IE compatibility mode, and IE < 9 have buggy Array `shift()`
* and `splice()` functions that fail to remove the last element, `value[0]`,
* of array-like objects even though the `length` property is set to `0`.
* The `shift()` method is buggy in IE 8 compatibility mode, while `splice()`
* is buggy regardless of mode in IE < 9 and buggy in compatibility mode in IE 9.
*
* @memberOf _.support
* @type boolean
*/
support.spliceObjects = (arrayRef.splice.call(object, 0, 1), !object[0]);
/**
* Detect lack of support for accessing string characters by index.
*
* IE < 8 can't access characters by index and IE 8 can only access
* characters by index on string literals.
*
* @memberOf _.support
* @type boolean
*/
support.unindexedChars = ('x'[0] + Object('x')[0]) != 'xx';
/**
* Detect if a DOM node's [[Class]] is resolvable (all but IE < 9)
* and that the JS engine errors when attempting to coerce an object to
* a string without a `toString` function.
*
* @memberOf _.support
* @type boolean
*/
try {
support.nodeClass = !(toString.call(document) == objectClass && !({ 'toString': 0 } + ''));
} catch(e) {
support.nodeClass = true;
}
}(1));
/**
* By default, the template delimiters used by Lo-Dash are similar to those in
* embedded Ruby (ERB). Change the following template settings to use alternative
* delimiters.
*
* @static
* @memberOf _
* @type Object
*/
lodash.templateSettings = {
/**
* Used to detect `data` property values to be HTML-escaped.
*
* @memberOf _.templateSettings
* @type RegExp
*/
'escape': /<%-([\s\S]+?)%>/g,
/**
* Used to detect code to be evaluated.
*
* @memberOf _.templateSettings
* @type RegExp
*/
'evaluate': /<%([\s\S]+?)%>/g,
/**
* Used to detect `data` property values to inject.
*
* @memberOf _.templateSettings
* @type RegExp
*/
'interpolate': reInterpolate,
/**
* Used to reference the data object in the template text.
*
* @memberOf _.templateSettings
* @type string
*/
'variable': '',
/**
* Used to import variables into the compiled template.
*
* @memberOf _.templateSettings
* @type Object
*/
'imports': {
/**
* A reference to the `lodash` function.
*
* @memberOf _.templateSettings.imports
* @type Function
*/
'_': lodash
}
};
/*--------------------------------------------------------------------------*/
/**
* The template used to create iterator functions.
*
* @private
* @param {Object} data The data object used to populate the text.
* @returns {string} Returns the interpolated text.
*/
var iteratorTemplate = template(
// the `iterable` may be reassigned by the `top` snippet
'var index, iterable = <%= firstArg %>, ' +
// assign the `result` variable an initial value
'result = <%= init %>;\n' +
// exit early if the first argument is falsey
'if (!iterable) return result;\n' +
// add code before the iteration branches
'<%= top %>;' +
// array-like iteration:
'<% if (array) { %>\n' +
'var length = iterable.length; index = -1;\n' +
'if (<%= array %>) {' +
// add support for accessing string characters by index if needed
' <% if (support.unindexedChars) { %>\n' +
' if (isString(iterable)) {\n' +
" iterable = iterable.split('')\n" +
' }' +
' <% } %>\n' +
// iterate over the array-like value
' while (++index < length) {\n' +
' <%= loop %>;\n' +
' }\n' +
'}\n' +
'else {' +
// object iteration:
// add support for iterating over `arguments` objects if needed
' <% } else if (support.nonEnumArgs) { %>\n' +
' var length = iterable.length; index = -1;\n' +
' if (length && isArguments(iterable)) {\n' +
' while (++index < length) {\n' +
" index += '';\n" +
' <%= loop %>;\n' +
' }\n' +
' } else {' +
' <% } %>' +
// avoid iterating over `prototype` properties in older Firefox, Opera, and Safari
' <% if (support.enumPrototypes) { %>\n' +
" var skipProto = typeof iterable == 'function';\n" +
' <% } %>' +
// avoid iterating over `Error.prototype` properties in older IE and Safari
' <% if (support.enumErrorProps) { %>\n' +
' var skipErrorProps = iterable === errorProto || iterable instanceof Error;\n' +
' <% } %>' +
// define conditions used in the loop
' <%' +
' var conditions = [];' +
' if (support.enumPrototypes) { conditions.push(\'!(skipProto && index == "prototype")\'); }' +
' if (support.enumErrorProps) { conditions.push(\'!(skipErrorProps && (index == "message" || index == "name"))\'); }' +
' %>' +
// iterate own properties using `Object.keys`
' <% if (useHas && keys) { %>\n' +
' var ownIndex = -1,\n' +
' ownProps = objectTypes[typeof iterable] && keys(iterable),\n' +
' length = ownProps ? ownProps.length : 0;\n\n' +
' while (++ownIndex < length) {\n' +
' index = ownProps[ownIndex];\n<%' +
" if (conditions.length) { %> if (<%= conditions.join(' && ') %>) {\n <% } %>" +
' <%= loop %>;' +
' <% if (conditions.length) { %>\n }<% } %>\n' +
' }' +
// else using a for-in loop
' <% } else { %>\n' +
' for (index in iterable) {\n<%' +
' if (useHas) { conditions.push("hasOwnProperty.call(iterable, index)"); }' +
" if (conditions.length) { %> if (<%= conditions.join(' && ') %>) {\n <% } %>" +
' <%= loop %>;' +
' <% if (conditions.length) { %>\n }<% } %>\n' +
' }' +
// Because IE < 9 can't set the `[[Enumerable]]` attribute of an
// existing property and the `constructor` property of a prototype
// defaults to non-enumerable, Lo-Dash skips the `constructor`
// property when it infers it's iterating over a `prototype` object.
' <% if (support.nonEnumShadows) { %>\n\n' +
' if (iterable !== objectProto) {\n' +
" var ctor = iterable.constructor,\n" +
' isProto = iterable === (ctor && ctor.prototype),\n' +
' className = iterable === stringProto ? stringClass : iterable === errorProto ? errorClass : toString.call(iterable),\n' +
' nonEnum = nonEnumProps[className];\n' +
' <% for (k = 0; k < 7; k++) { %>\n' +
" index = '<%= shadowedProps[k] %>';\n" +
' if ((!(isProto && nonEnum[index]) && hasOwnProperty.call(iterable, index))<%' +
' if (!useHas) { %> || (!nonEnum[index] && iterable[index] !== objectProto[index])<% }' +
' %>) {\n' +
' <%= loop %>;\n' +
' }' +
' <% } %>\n' +
' }' +
' <% } %>' +
' <% } %>' +
' <% if (array || support.nonEnumArgs) { %>\n}<% } %>\n' +
// add code to the bottom of the iteration function
'<%= bottom %>;\n' +
// finally, return the `result`
'return result'
);
/*--------------------------------------------------------------------------*/
/**
* The base implementation of `_.bind` that creates the bound function and
* sets its meta data.
*
* @private
* @param {Array} bindData The bind data array.
* @returns {Function} Returns the new bound function.
*/
function baseBind(bindData) {
var func = bindData[0],
partialArgs = bindData[2],
thisArg = bindData[4];
function bound() {
// `Function#bind` spec
// http://es5.github.io/#x15.3.4.5
if (partialArgs) {
// avoid `arguments` object deoptimizations by using `slice` instead
// of `Array.prototype.slice.call` and not assigning `arguments` to a
// variable as a ternary expression
var args = slice(partialArgs);
push.apply(args, arguments);
}
// mimic the constructor's `return` behavior
// http://es5.github.io/#x13.2.2
if (this instanceof bound) {
// ensure `new bound` is an instance of `func`
var thisBinding = baseCreate(func.prototype),
result = func.apply(thisBinding, args || arguments);
return isObject(result) ? result : thisBinding;
}
return func.apply(thisArg, args || arguments);
}
setBindData(bound, bindData);
return bound;
}
/**
* The base implementation of `_.clone` without argument juggling or support
* for `thisArg` binding.
*
* @private
* @param {*} value The value to clone.
* @param {boolean} [isDeep=false] Specify a deep clone.
* @param {Function} [callback] The function to customize cloning values.
* @param {Array} [stackA=[]] Tracks traversed source objects.
* @param {Array} [stackB=[]] Associates clones with source counterparts.
* @returns {*} Returns the cloned value.
*/
function baseClone(value, isDeep, callback, stackA, stackB) {
if (callback) {
var result = callback(value);
if (typeof result != 'undefined') {
return result;
}
}
// inspect [[Class]]
var isObj = isObject(value);
if (isObj) {
var className = toString.call(value);
if (!cloneableClasses[className] || (!support.nodeClass && isNode(value))) {
return value;
}
var ctor = ctorByClass[className];
switch (className) {
case boolClass:
case dateClass:
return new ctor(+value);
case numberClass:
case stringClass:
return new ctor(value);
case regexpClass:
result = ctor(value.source, reFlags.exec(value));
result.lastIndex = value.lastIndex;
return result;
}
} else {
return value;
}
var isArr = isArray(value);
if (isDeep) {
// check for circular references and return corresponding clone
var initedStack = !stackA;
stackA || (stackA = getArray());
stackB || (stackB = getArray());
var length = stackA.length;
while (length--) {
if (stackA[length] == value) {
return stackB[length];
}
}
result = isArr ? ctor(value.length) : {};
}
else {
result = isArr ? slice(value) : assign({}, value);
}
// add array properties assigned by `RegExp#exec`
if (isArr) {
if (hasOwnProperty.call(value, 'index')) {
result.index = value.index;
}
if (hasOwnProperty.call(value, 'input')) {
result.input = value.input;
}
}
// exit for shallow clone
if (!isDeep) {
return result;
}
// add the source value to the stack of traversed objects
// and associate it with its clone
stackA.push(value);
stackB.push(result);
// recursively populate clone (susceptible to call stack limits)
(isArr ? baseEach : forOwn)(value, function(objValue, key) {
result[key] = baseClone(objValue, isDeep, callback, stackA, stackB);
});
if (initedStack) {
releaseArray(stackA);
releaseArray(stackB);
}
return result;
}
/**
* The base implementation of `_.create` without support for assigning
* properties to the created object.
*
* @private
* @param {Object} prototype The object to inherit from.
* @returns {Object} Returns the new object.
*/
function baseCreate(prototype, properties) {
return isObject(prototype) ? nativeCreate(prototype) : {};
}
// fallback for browsers without `Object.create`
if (!nativeCreate) {
baseCreate = (function() {
function Object() {}
return function(prototype) {
if (isObject(prototype)) {
Object.prototype = prototype;
var result = new Object;
Object.prototype = null;
}
return result || context.Object();
};
}());
}
/**
* The base implementation of `_.createCallback` without support for creating
* "_.pluck" or "_.where" style callbacks.
*
* @private
* @param {*} [func=identity] The value to convert to a callback.
* @param {*} [thisArg] The `this` binding of the created callback.
* @param {number} [argCount] The number of arguments the callback accepts.
* @returns {Function} Returns a callback function.
*/
function baseCreateCallback(func, thisArg, argCount) {
if (typeof func != 'function') {
return identity;
}
// exit early for no `thisArg` or already bound by `Function#bind`
if (typeof thisArg == 'undefined' || !('prototype' in func)) {
return func;
}
var bindData = func.__bindData__;
if (typeof bindData == 'undefined') {
if (support.funcNames) {
bindData = !func.name;
}
bindData = bindData || !support.funcDecomp;
if (!bindData) {
var source = fnToString.call(func);
if (!support.funcNames) {
bindData = !reFuncName.test(source);
}
if (!bindData) {
// checks if `func` references the `this` keyword and stores the result
bindData = reThis.test(source);
setBindData(func, bindData);
}
}
}
// exit early if there are no `this` references or `func` is bound
if (bindData === false || (bindData !== true && bindData[1] & 1)) {
return func;
}
switch (argCount) {
case 1: return function(value) {
return func.call(thisArg, value);
};
case 2: return function(a, b) {
return func.call(thisArg, a, b);
};
case 3: return function(value, index, collection) {
return func.call(thisArg, value, index, collection);
};
case 4: return function(accumulator, value, index, collection) {
return func.call(thisArg, accumulator, value, index, collection);
};
}
return bind(func, thisArg);
}
/**
* The base implementation of `createWrapper` that creates the wrapper and
* sets its meta data.
*
* @private
* @param {Array} bindData The bind data array.
* @returns {Function} Returns the new function.
*/
function baseCreateWrapper(bindData) {
var func = bindData[0],
bitmask = bindData[1],
partialArgs = bindData[2],
partialRightArgs = bindData[3],
thisArg = bindData[4],
arity = bindData[5];
var isBind = bitmask & 1,
isBindKey = bitmask & 2,
isCurry = bitmask & 4,
isCurryBound = bitmask & 8,
key = func;
function bound() {
var thisBinding = isBind ? thisArg : this;
if (partialArgs) {
var args = slice(partialArgs);
push.apply(args, arguments);
}
if (partialRightArgs || isCurry) {
args || (args = slice(arguments));
if (partialRightArgs) {
push.apply(args, partialRightArgs);
}
if (isCurry && args.length < arity) {
bitmask |= 16 & ~32;
return baseCreateWrapper([func, (isCurryBound ? bitmask : bitmask & ~3), args, null, thisArg, arity]);
}
}
args || (args = arguments);
if (isBindKey) {
func = thisBinding[key];
}
if (this instanceof bound) {
thisBinding = baseCreate(func.prototype);
var result = func.apply(thisBinding, args);
return isObject(result) ? result : thisBinding;
}
return func.apply(thisBinding, args);
}
setBindData(bound, bindData);
return bound;
}
/**
* The base implementation of `_.difference` that accepts a single array
* of values to exclude.
*
* @private
* @param {Array} array The array to process.
* @param {Array} [values] The array of values to exclude.
* @returns {Array} Returns a new array of filtered values.
*/
function baseDifference(array, values) {
var index = -1,
indexOf = getIndexOf(),
length = array ? array.length : 0,
isLarge = length >= largeArraySize && indexOf === baseIndexOf,
result = [];
if (isLarge) {
var cache = createCache(values);
if (cache) {
indexOf = cacheIndexOf;
values = cache;
} else {
isLarge = false;
}
}
while (++index < length) {
var value = array[index];
if (indexOf(values, value) < 0) {
result.push(value);
}
}
if (isLarge) {
releaseObject(values);
}
return result;
}
/**
* The base implementation of `_.flatten` without support for callback
* shorthands or `thisArg` binding.
*
* @private
* @param {Array} array The array to flatten.
* @param {boolean} [isShallow=false] A flag to restrict flattening to a single level.
* @param {boolean} [isStrict=false] A flag to restrict flattening to arrays and `arguments` objects.
* @param {number} [fromIndex=0] The index to start from.
* @returns {Array} Returns a new flattened array.
*/
function baseFlatten(array, isShallow, isStrict, fromIndex) {
var index = (fromIndex || 0) - 1,
length = array ? array.length : 0,
result = [];
while (++index < length) {
var value = array[index];
if (value && typeof value == 'object' && typeof value.length == 'number'
&& (isArray(value) || isArguments(value))) {
// recursively flatten arrays (susceptible to call stack limits)
if (!isShallow) {
value = baseFlatten(value, isShallow, isStrict);
}
var valIndex = -1,
valLength = value.length,
resIndex = result.length;
result.length += valLength;
while (++valIndex < valLength) {
result[resIndex++] = value[valIndex];
}
} else if (!isStrict) {
result.push(value);
}
}
return result;
}
/**
* The base implementation of `_.isEqual`, without support for `thisArg` binding,
* that allows partial "_.where" style comparisons.
*
* @private
* @param {*} a The value to compare.
* @param {*} b The other value to compare.
* @param {Function} [callback] The function to customize comparing values.
* @param {Function} [isWhere=false] A flag to indicate performing partial comparisons.
* @param {Array} [stackA=[]] Tracks traversed `a` objects.
* @param {Array} [stackB=[]] Tracks traversed `b` objects.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
*/
function baseIsEqual(a, b, callback, isWhere, stackA, stackB) {
// used to indicate that when comparing objects, `a` has at least the properties of `b`
if (callback) {
var result = callback(a, b);
if (typeof result != 'undefined') {
return !!result;
}
}
// exit early for identical values
if (a === b) {
// treat `+0` vs. `-0` as not equal
return a !== 0 || (1 / a == 1 / b);
}
var type = typeof a,
otherType = typeof b;
// exit early for unlike primitive values
if (a === a &&
!(a && objectTypes[type]) &&
!(b && objectTypes[otherType])) {
return false;
}
// exit early for `null` and `undefined` avoiding ES3's Function#call behavior
// http://es5.github.io/#x15.3.4.4
if (a == null || b == null) {
return a === b;
}
// compare [[Class]] names
var className = toString.call(a),
otherClass = toString.call(b);
if (className == argsClass) {
className = objectClass;
}
if (otherClass == argsClass) {
otherClass = objectClass;
}
if (className != otherClass) {
return false;
}
switch (className) {
case boolClass:
case dateClass:
// coerce dates and booleans to numbers, dates to milliseconds and booleans
// to `1` or `0` treating invalid dates coerced to `NaN` as not equal
return +a == +b;
case numberClass:
// treat `NaN` vs. `NaN` as equal
return (a != +a)
? b != +b
// but treat `+0` vs. `-0` as not equal
: (a == 0 ? (1 / a == 1 / b) : a == +b);
case regexpClass:
case stringClass:
// coerce regexes to strings (http://es5.github.io/#x15.10.6.4)
// treat string primitives and their corresponding object instances as equal
return a == String(b);
}
var isArr = className == arrayClass;
if (!isArr) {
// unwrap any `lodash` wrapped values
var aWrapped = hasOwnProperty.call(a, '__wrapped__'),
bWrapped = hasOwnProperty.call(b, '__wrapped__');
if (aWrapped || bWrapped) {
return baseIsEqual(aWrapped ? a.__wrapped__ : a, bWrapped ? b.__wrapped__ : b, callback, isWhere, stackA, stackB);
}
// exit for functions and DOM nodes
if (className != objectClass || (!support.nodeClass && (isNode(a) || isNode(b)))) {
return false;
}
// in older versions of Opera, `arguments` objects have `Array` constructors
var ctorA = !support.argsObject && isArguments(a) ? Object : a.constructor,
ctorB = !support.argsObject && isArguments(b) ? Object : b.constructor;
// non `Object` object instances with different constructors are not equal
if (ctorA != ctorB &&
!(isFunction(ctorA) && ctorA instanceof ctorA && isFunction(ctorB) && ctorB instanceof ctorB) &&
('constructor' in a && 'constructor' in b)
) {
return false;
}
}
// assume cyclic structures are equal
// the algorithm for detecting cyclic structures is adapted from ES 5.1
// section 15.12.3, abstract operation `JO` (http://es5.github.io/#x15.12.3)
var initedStack = !stackA;
stackA || (stackA = getArray());
stackB || (stackB = getArray());
var length = stackA.length;
while (length--) {
if (stackA[length] == a) {
return stackB[length] == b;
}
}
var size = 0;
result = true;
// add `a` and `b` to the stack of traversed objects
stackA.push(a);
stackB.push(b);
// recursively compare objects and arrays (susceptible to call stack limits)
if (isArr) {
// compare lengths to determine if a deep comparison is necessary
length = a.length;
size = b.length;
result = size == length;
if (result || isWhere) {
// deep compare the contents, ignoring non-numeric properties
while (size--) {
var index = length,
value = b[size];
if (isWhere) {
while (index--) {
if ((result = baseIsEqual(a[index], value, callback, isWhere, stackA, stackB))) {
break;
}
}
} else if (!(result = baseIsEqual(a[size], value, callback, isWhere, stackA, stackB))) {
break;
}
}
}
}
else {
// deep compare objects using `forIn`, instead of `forOwn`, to avoid `Object.keys`
// which, in this case, is more costly
forIn(b, function(value, key, b) {
if (hasOwnProperty.call(b, key)) {
// count the number of properties.
size++;
// deep compare each property value.
return (result = hasOwnProperty.call(a, key) && baseIsEqual(a[key], value, callback, isWhere, stackA, stackB));
}
});
if (result && !isWhere) {
// ensure both objects have the same number of properties
forIn(a, function(value, key, a) {
if (hasOwnProperty.call(a, key)) {
// `size` will be `-1` if `a` has more properties than `b`
return (result = --size > -1);
}
});
}
}
stackA.pop();
stackB.pop();
if (initedStack) {
releaseArray(stackA);
releaseArray(stackB);
}
return result;
}
/**
* The base implementation of `_.merge` without argument juggling or support
* for `thisArg` binding.
*
* @private
* @param {Object} object The destination object.
* @param {Object} source The source object.
* @param {Function} [callback] The function to customize merging properties.
* @param {Array} [stackA=[]] Tracks traversed source objects.
* @param {Array} [stackB=[]] Associates values with source counterparts.
*/
function baseMerge(object, source, callback, stackA, stackB) {
(isArray(source) ? forEach : forOwn)(source, function(source, key) {
var found,
isArr,
result = source,
value = object[key];
if (source && ((isArr = isArray(source)) || isPlainObject(source))) {
// avoid merging previously merged cyclic sources
var stackLength = stackA.length;
while (stackLength--) {
if ((found = stackA[stackLength] == source)) {
value = stackB[stackLength];
break;
}
}
if (!found) {
var isShallow;
if (callback) {
result = callback(value, source);
if ((isShallow = typeof result != 'undefined')) {
value = result;
}
}
if (!isShallow) {
value = isArr
? (isArray(value) ? value : [])
: (isPlainObject(value) ? value : {});
}
// add `source` and associated `value` to the stack of traversed objects
stackA.push(source);
stackB.push(value);
// recursively merge objects and arrays (susceptible to call stack limits)
if (!isShallow) {
baseMerge(value, source, callback, stackA, stackB);
}
}
}
else {
if (callback) {
result = callback(value, source);
if (typeof result == 'undefined') {
result = source;
}
}
if (typeof result != 'undefined') {
value = result;
}
}
object[key] = value;
});
}
/**
* The base implementation of `_.random` without argument juggling or support
* for returning floating-point numbers.
*
* @private
* @param {number} min The minimum possible value.
* @param {number} max The maximum possible value.
* @returns {number} Returns a random number.
*/
function baseRandom(min, max) {
return min + floor(nativeRandom() * (max - min + 1));
}
/**
* The base implementation of `_.uniq` without support for callback shorthands
* or `thisArg` binding.
*
* @private
* @param {Array} array The array to process.
* @param {boolean} [isSorted=false] A flag to indicate that `array` is sorted.
* @param {Function} [callback] The function called per iteration.
* @returns {Array} Returns a duplicate-value-free array.
*/
function baseUniq(array, isSorted, callback) {
var index = -1,
indexOf = getIndexOf(),
length = array ? array.length : 0,
result = [];
var isLarge = !isSorted && length >= largeArraySize && indexOf === baseIndexOf,
seen = (callback || isLarge) ? getArray() : result;
if (isLarge) {
var cache = createCache(seen);
indexOf = cacheIndexOf;
seen = cache;
}
while (++index < length) {
var value = array[index],
computed = callback ? callback(value, index, array) : value;
if (isSorted
? !index || seen[seen.length - 1] !== computed
: indexOf(seen, computed) < 0
) {
if (callback || isLarge) {
seen.push(computed);
}
result.push(value);
}
}
if (isLarge) {
releaseArray(seen.array);
releaseObject(seen);
} else if (callback) {
releaseArray(seen);
}
return result;
}
/**
* Creates a function that aggregates a collection, creating an object composed
* of keys generated from the results of running each element of the collection
* through a callback. The given `setter` function sets the keys and values
* of the composed object.
*
* @private
* @param {Function} setter The setter function.
* @returns {Function} Returns the new aggregator function.
*/
function createAggregator(setter) {
return function(collection, callback, thisArg) {
var result = {};
callback = lodash.createCallback(callback, thisArg, 3);
if (isArray(collection)) {
var index = -1,
length = collection.length;
while (++index < length) {
var value = collection[index];
setter(result, value, callback(value, index, collection), collection);
}
} else {
baseEach(collection, function(value, key, collection) {
setter(result, value, callback(value, key, collection), collection);
});
}
return result;
};
}
/**
* Creates a function that, when called, either curries or invokes `func`
* with an optional `this` binding and partially applied arguments.
*
* @private
* @param {Function|string} func The function or method name to reference.
* @param {number} bitmask The bitmask of method flags to compose.
* The bitmask may be composed of the following flags:
* 1 - `_.bind`
* 2 - `_.bindKey`
* 4 - `_.curry`
* 8 - `_.curry` (bound)
* 16 - `_.partial`
* 32 - `_.partialRight`
* @param {Array} [partialArgs] An array of arguments to prepend to those
* provided to the new function.
* @param {Array} [partialRightArgs] An array of arguments to append to those
* provided to the new function.
* @param {*} [thisArg] The `this` binding of `func`.
* @param {number} [arity] The arity of `func`.
* @returns {Function} Returns the new function.
*/
function createWrapper(func, bitmask, partialArgs, partialRightArgs, thisArg, arity) {
var isBind = bitmask & 1,
isBindKey = bitmask & 2,
isCurry = bitmask & 4,
isCurryBound = bitmask & 8,
isPartial = bitmask & 16,
isPartialRight = bitmask & 32;
if (!isBindKey && !isFunction(func)) {
throw new TypeError;
}
if (isPartial && !partialArgs.length) {
bitmask &= ~16;
isPartial = partialArgs = false;
}
if (isPartialRight && !partialRightArgs.length) {
bitmask &= ~32;
isPartialRight = partialRightArgs = false;
}
var bindData = func && func.__bindData__;
if (bindData && bindData !== true) {
// clone `bindData`
bindData = slice(bindData);
if (bindData[2]) {
bindData[2] = slice(bindData[2]);
}
if (bindData[3]) {
bindData[3] = slice(bindData[3]);
}
// set `thisBinding` is not previously bound
if (isBind && !(bindData[1] & 1)) {
bindData[4] = thisArg;
}
// set if previously bound but not currently (subsequent curried functions)
if (!isBind && bindData[1] & 1) {
bitmask |= 8;
}
// set curried arity if not yet set
if (isCurry && !(bindData[1] & 4)) {
bindData[5] = arity;
}
// append partial left arguments
if (isPartial) {
push.apply(bindData[2] || (bindData[2] = []), partialArgs);
}
// append partial right arguments
if (isPartialRight) {
unshift.apply(bindData[3] || (bindData[3] = []), partialRightArgs);
}
// merge flags
bindData[1] |= bitmask;
return createWrapper.apply(null, bindData);
}
// fast path for `_.bind`
var creater = (bitmask == 1 || bitmask === 17) ? baseBind : baseCreateWrapper;
return creater([func, bitmask, partialArgs, partialRightArgs, thisArg, arity]);
}
/**
* Creates compiled iteration functions.
*
* @private
* @param {...Object} [options] The compile options object(s).
* @param {string} [options.array] Code to determine if the iterable is an array or array-like.
* @param {boolean} [options.useHas] Specify using `hasOwnProperty` checks in the object loop.
* @param {Function} [options.keys] A reference to `_.keys` for use in own property iteration.
* @param {string} [options.args] A comma separated string of iteration function arguments.
* @param {string} [options.top] Code to execute before the iteration branches.
* @param {string} [options.loop] Code to execute in the object loop.
* @param {string} [options.bottom] Code to execute after the iteration branches.
* @returns {Function} Returns the compiled function.
*/
function createIterator() {
// data properties
iteratorData.shadowedProps = shadowedProps;
iteratorData.support = support;
// iterator options
iteratorData.array = iteratorData.bottom = iteratorData.loop = iteratorData.top = '';
iteratorData.init = 'iterable';
iteratorData.useHas = true;
// merge options into a template data object
for (var object, index = 0; object = arguments[index]; index++) {
for (var key in object) {
iteratorData[key] = object[key];
}
}
var args = iteratorData.args;
iteratorData.firstArg = /^[^,]+/.exec(args)[0];
// create the function factory
var factory = Function(
'baseCreateCallback, errorClass, errorProto, hasOwnProperty, ' +
'indicatorObject, isArguments, isArray, isString, keys, objectProto, ' +
'objectTypes, nonEnumProps, stringClass, stringProto, toString',
'return function(' + args + ') {\n' + iteratorTemplate(iteratorData) + '\n}'
);
// return the compiled function
return factory(
baseCreateCallback, errorClass, errorProto, hasOwnProperty,
indicatorObject, isArguments, isArray, isString, iteratorData.keys, objectProto,
objectTypes, nonEnumProps, stringClass, stringProto, toString
);
}
/**
* Used by `escape` to convert characters to HTML entities.
*
* @private
* @param {string} match The matched character to escape.
* @returns {string} Returns the escaped character.
*/
function escapeHtmlChar(match) {
return htmlEscapes[match];
}
/**
* Gets the appropriate "indexOf" function. If the `_.indexOf` method is
* customized, this method returns the custom method, otherwise it returns
* the `baseIndexOf` function.
*
* @private
* @returns {Function} Returns the "indexOf" function.
*/
function getIndexOf() {
var result = (result = lodash.indexOf) === indexOf ? baseIndexOf : result;
return result;
}
/**
* Checks if `value` is a native function.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if the `value` is a native function, else `false`.
*/
function isNative(value) {
return typeof value == 'function' && reNative.test(value);
}
/**
* Sets `this` binding data on a given function.
*
* @private
* @param {Function} func The function to set data on.
* @param {Array} value The data array to set.
*/
var setBindData = !defineProperty ? noop : function(func, value) {
descriptor.value = value;
defineProperty(func, '__bindData__', descriptor);
descriptor.value = null;
};
/**
* A fallback implementation of `isPlainObject` which checks if a given value
* is an object created by the `Object` constructor, assuming objects created
* by the `Object` constructor have no inherited enumerable properties and that
* there are no `Object.prototype` extensions.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a plain object, else `false`.
*/
function shimIsPlainObject(value) {
var ctor,
result;
// avoid non Object objects, `arguments` objects, and DOM elements
if (!(value && toString.call(value) == objectClass) ||
(ctor = value.constructor, isFunction(ctor) && !(ctor instanceof ctor)) ||
(!support.argsClass && isArguments(value)) ||
(!support.nodeClass && isNode(value))) {
return false;
}
// IE < 9 iterates inherited properties before own properties. If the first
// iterated property is an object's own property then there are no inherited
// enumerable properties.
if (support.ownLast) {
forIn(value, function(value, key, object) {
result = hasOwnProperty.call(object, key);
return false;
});
return result !== false;
}
// In most environments an object's own properties are iterated before
// its inherited properties. If the last iterated property is an object's
// own property then there are no inherited enumerable properties.
forIn(value, function(value, key) {
result = key;
});
return typeof result == 'undefined' || hasOwnProperty.call(value, result);
}
/**
* Used by `unescape` to convert HTML entities to characters.
*
* @private
* @param {string} match The matched character to unescape.
* @returns {string} Returns the unescaped character.
*/
function unescapeHtmlChar(match) {
return htmlUnescapes[match];
}
/*--------------------------------------------------------------------------*/
/**
* Checks if `value` is an `arguments` object.
*
* @static
* @memberOf _
* @category Objects
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if the `value` is an `arguments` object, else `false`.
* @example
*
* (function() { return _.isArguments(arguments); })(1, 2, 3);
* // => true
*
* _.isArguments([1, 2, 3]);
* // => false
*/
function isArguments(value) {
return value && typeof value == 'object' && typeof value.length == 'number' &&
toString.call(value) == argsClass || false;
}
// fallback for browsers that can't detect `arguments` objects by [[Class]]
if (!support.argsClass) {
isArguments = function(value) {
return value && typeof value == 'object' && typeof value.length == 'number' &&
hasOwnProperty.call(value, 'callee') && !propertyIsEnumerable.call(value, 'callee') || false;
};
}
/**
* Checks if `value` is an array.
*
* @static
* @memberOf _
* @type Function
* @category Objects
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if the `value` is an array, else `false`.
* @example
*
* (function() { return _.isArray(arguments); })();
* // => false
*
* _.isArray([1, 2, 3]);
* // => true
*/
var isArray = nativeIsArray || function(value) {
return value && typeof value == 'object' && typeof value.length == 'number' &&
toString.call(value) == arrayClass || false;
};
/**
* A fallback implementation of `Object.keys` which produces an array of the
* given object's own enumerable property names.
*
* @private
* @type Function
* @param {Object} object The object to inspect.
* @returns {Array} Returns an array of property names.
*/
var shimKeys = createIterator({
'args': 'object',
'init': '[]',
'top': 'if (!(objectTypes[typeof object])) return result',
'loop': 'result.push(index)'
});
/**
* Creates an array composed of the own enumerable property names of an object.
*
* @static
* @memberOf _
* @category Objects
* @param {Object} object The object to inspect.
* @returns {Array} Returns an array of property names.
* @example
*
* _.keys({ 'one': 1, 'two': 2, 'three': 3 });
* // => ['one', 'two', 'three'] (property order is not guaranteed across environments)
*/
var keys = !nativeKeys ? shimKeys : function(object) {
if (!isObject(object)) {
return [];
}
if ((support.enumPrototypes && typeof object == 'function') ||
(support.nonEnumArgs && object.length && isArguments(object))) {
return shimKeys(object);
}
return nativeKeys(object);
};
/** Reusable iterator options shared by `each`, `forIn`, and `forOwn` */
var eachIteratorOptions = {
'args': 'collection, callback, thisArg',
'top': "callback = callback && typeof thisArg == 'undefined' ? callback : baseCreateCallback(callback, thisArg, 3)",
'array': "typeof length == 'number'",
'keys': keys,
'loop': 'if (callback(iterable[index], index, collection) === false) return result'
};
/** Reusable iterator options for `assign` and `defaults` */
var defaultsIteratorOptions = {
'args': 'object, source, guard',
'top':
'var args = arguments,\n' +
' argsIndex = 0,\n' +
" argsLength = typeof guard == 'number' ? 2 : args.length;\n" +
'while (++argsIndex < argsLength) {\n' +
' iterable = args[argsIndex];\n' +
' if (iterable && objectTypes[typeof iterable]) {',
'keys': keys,
'loop': "if (typeof result[index] == 'undefined') result[index] = iterable[index]",
'bottom': ' }\n}'
};
/** Reusable iterator options for `forIn` and `forOwn` */
var forOwnIteratorOptions = {
'top': 'if (!objectTypes[typeof iterable]) return result;\n' + eachIteratorOptions.top,
'array': false
};
/**
* Used to convert characters to HTML entities:
*
* Though the `>` character is escaped for symmetry, characters like `>` and `/`
* don't require escaping in HTML and have no special meaning unless they're part
* of a tag or an unquoted attribute value.
* http://mathiasbynens.be/notes/ambiguous-ampersands (under "semi-related fun fact")
*/
var htmlEscapes = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": '''
};
/** Used to convert HTML entities to characters */
var htmlUnescapes = invert(htmlEscapes);
/** Used to match HTML entities and HTML characters */
var reEscapedHtml = RegExp('(' + keys(htmlUnescapes).join('|') + ')', 'g'),
reUnescapedHtml = RegExp('[' + keys(htmlEscapes).join('') + ']', 'g');
/**
* A function compiled to iterate `arguments` objects, arrays, objects, and
* strings consistenly across environments, executing the callback for each
* element in the collection. The callback is bound to `thisArg` and invoked
* with three arguments; (value, index|key, collection). Callbacks may exit
* iteration early by explicitly returning `false`.
*
* @private
* @type Function
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function} [callback=identity] The function called per iteration.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {Array|Object|string} Returns `collection`.
*/
var baseEach = createIterator(eachIteratorOptions);
/*--------------------------------------------------------------------------*/
/**
* Assigns own enumerable properties of source object(s) to the destination
* object. Subsequent sources will overwrite property assignments of previous
* sources. If a callback is provided it will be executed to produce the
* assigned values. The callback is bound to `thisArg` and invoked with two
* arguments; (objectValue, sourceValue).
*
* @static
* @memberOf _
* @type Function
* @alias extend
* @category Objects
* @param {Object} object The destination object.
* @param {...Object} [source] The source objects.
* @param {Function} [callback] The function to customize assigning values.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {Object} Returns the destination object.
* @example
*
* _.assign({ 'name': 'fred' }, { 'employer': 'slate' });
* // => { 'name': 'fred', 'employer': 'slate' }
*
* var defaults = _.partialRight(_.assign, function(a, b) {
* return typeof a == 'undefined' ? b : a;
* });
*
* var object = { 'name': 'barney' };
* defaults(object, { 'name': 'fred', 'employer': 'slate' });
* // => { 'name': 'barney', 'employer': 'slate' }
*/
var assign = createIterator(defaultsIteratorOptions, {
'top':
defaultsIteratorOptions.top.replace(';',
';\n' +
"if (argsLength > 3 && typeof args[argsLength - 2] == 'function') {\n" +
' var callback = baseCreateCallback(args[--argsLength - 1], args[argsLength--], 2);\n' +
"} else if (argsLength > 2 && typeof args[argsLength - 1] == 'function') {\n" +
' callback = args[--argsLength];\n' +
'}'
),
'loop': 'result[index] = callback ? callback(result[index], iterable[index]) : iterable[index]'
});
/**
* Creates a clone of `value`. If `isDeep` is `true` nested objects will also
* be cloned, otherwise they will be assigned by reference. If a callback
* is provided it will be executed to produce the cloned values. If the
* callback returns `undefined` cloning will be handled by the method instead.
* The callback is bound to `thisArg` and invoked with one argument; (value).
*
* @static
* @memberOf _
* @category Objects
* @param {*} value The value to clone.
* @param {boolean} [isDeep=false] Specify a deep clone.
* @param {Function} [callback] The function to customize cloning values.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {*} Returns the cloned value.
* @example
*
* var characters = [
* { 'name': 'barney', 'age': 36 },
* { 'name': 'fred', 'age': 40 }
* ];
*
* var shallow = _.clone(characters);
* shallow[0] === characters[0];
* // => true
*
* var deep = _.clone(characters, true);
* deep[0] === characters[0];
* // => false
*
* _.mixin({
* 'clone': _.partialRight(_.clone, function(value) {
* return _.isElement(value) ? value.cloneNode(false) : undefined;
* })
* });
*
* var clone = _.clone(document.body);
* clone.childNodes.length;
* // => 0
*/
function clone(value, isDeep, callback, thisArg) {
// allows working with "Collections" methods without using their `index`
// and `collection` arguments for `isDeep` and `callback`
if (typeof isDeep != 'boolean' && isDeep != null) {
thisArg = callback;
callback = isDeep;
isDeep = false;
}
return baseClone(value, isDeep, typeof callback == 'function' && baseCreateCallback(callback, thisArg, 1));
}
/**
* Creates a deep clone of `value`. If a callback is provided it will be
* executed to produce the cloned values. If the callback returns `undefined`
* cloning will be handled by the method instead. The callback is bound to
* `thisArg` and invoked with one argument; (value).
*
* Note: This method is loosely based on the structured clone algorithm. Functions
* and DOM nodes are **not** cloned. The enumerable properties of `arguments` objects and
* objects created by constructors other than `Object` are cloned to plain `Object` objects.
* See http://www.w3.org/TR/html5/infrastructure.html#internal-structured-cloning-algorithm.
*
* @static
* @memberOf _
* @category Objects
* @param {*} value The value to deep clone.
* @param {Function} [callback] The function to customize cloning values.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {*} Returns the deep cloned value.
* @example
*
* var characters = [
* { 'name': 'barney', 'age': 36 },
* { 'name': 'fred', 'age': 40 }
* ];
*
* var deep = _.cloneDeep(characters);
* deep[0] === characters[0];
* // => false
*
* var view = {
* 'label': 'docs',
* 'node': element
* };
*
* var clone = _.cloneDeep(view, function(value) {
* return _.isElement(value) ? value.cloneNode(true) : undefined;
* });
*
* clone.node == view.node;
* // => false
*/
function cloneDeep(value, callback, thisArg) {
return baseClone(value, true, typeof callback == 'function' && baseCreateCallback(callback, thisArg, 1));
}
/**
* Creates an object that inherits from the given `prototype` object. If a
* `properties` object is provided its own enumerable properties are assigned
* to the created object.
*
* @static
* @memberOf _
* @category Objects
* @param {Object} prototype The object to inherit from.
* @param {Object} [properties] The properties to assign to the object.
* @returns {Object} Returns the new object.
* @example
*
* function Shape() {
* this.x = 0;
* this.y = 0;
* }
*
* function Circle() {
* Shape.call(this);
* }
*
* Circle.prototype = _.create(Shape.prototype, { 'constructor': Circle });
*
* var circle = new Circle;
* circle instanceof Circle;
* // => true
*
* circle instanceof Shape;
* // => true
*/
function create(prototype, properties) {
var result = baseCreate(prototype);
return properties ? assign(result, properties) : result;
}
/**
* Assigns own enumerable properties of source object(s) to the destination
* object for all destination properties that resolve to `undefined`. Once a
* property is set, additional defaults of the same property will be ignored.
*
* @static
* @memberOf _
* @type Function
* @category Objects
* @param {Object} object The destination object.
* @param {...Object} [source] The source objects.
* @param- {Object} [guard] Allows working with `_.reduce` without using its
* `key` and `object` arguments as sources.
* @returns {Object} Returns the destination object.
* @example
*
* var object = { 'name': 'barney' };
* _.defaults(object, { 'name': 'fred', 'employer': 'slate' });
* // => { 'name': 'barney', 'employer': 'slate' }
*/
var defaults = createIterator(defaultsIteratorOptions);
/**
* This method is like `_.findIndex` except that it returns the key of the
* first element that passes the callback check, instead of the element itself.
*
* If a property name is provided for `callback` the created "_.pluck" style
* callback will return the property value of the given element.
*
* If an object is provided for `callback` the created "_.where" style callback
* will return `true` for elements that have the properties of the given object,
* else `false`.
*
* @static
* @memberOf _
* @category Objects
* @param {Object} object The object to search.
* @param {Function|Object|string} [callback=identity] The function called per
* iteration. If a property name or object is provided it will be used to
* create a "_.pluck" or "_.where" style callback, respectively.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {string|undefined} Returns the key of the found element, else `undefined`.
* @example
*
* var characters = {
* 'barney': { 'age': 36, 'blocked': false },
* 'fred': { 'age': 40, 'blocked': true },
* 'pebbles': { 'age': 1, 'blocked': false }
* };
*
* _.findKey(characters, function(chr) {
* return chr.age < 40;
* });
* // => 'barney' (property order is not guaranteed across environments)
*
* // using "_.where" callback shorthand
* _.findKey(characters, { 'age': 1 });
* // => 'pebbles'
*
* // using "_.pluck" callback shorthand
* _.findKey(characters, 'blocked');
* // => 'fred'
*/
function findKey(object, callback, thisArg) {
var result;
callback = lodash.createCallback(callback, thisArg, 3);
forOwn(object, function(value, key, object) {
if (callback(value, key, object)) {
result = key;
return false;
}
});
return result;
}
/**
* This method is like `_.findKey` except that it iterates over elements
* of a `collection` in the opposite order.
*
* If a property name is provided for `callback` the created "_.pluck" style
* callback will return the property value of the given element.
*
* If an object is provided for `callback` the created "_.where" style callback
* will return `true` for elements that have the properties of the given object,
* else `false`.
*
* @static
* @memberOf _
* @category Objects
* @param {Object} object The object to search.
* @param {Function|Object|string} [callback=identity] The function called per
* iteration. If a property name or object is provided it will be used to
* create a "_.pluck" or "_.where" style callback, respectively.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {string|undefined} Returns the key of the found element, else `undefined`.
* @example
*
* var characters = {
* 'barney': { 'age': 36, 'blocked': true },
* 'fred': { 'age': 40, 'blocked': false },
* 'pebbles': { 'age': 1, 'blocked': true }
* };
*
* _.findLastKey(characters, function(chr) {
* return chr.age < 40;
* });
* // => returns `pebbles`, assuming `_.findKey` returns `barney`
*
* // using "_.where" callback shorthand
* _.findLastKey(characters, { 'age': 40 });
* // => 'fred'
*
* // using "_.pluck" callback shorthand
* _.findLastKey(characters, 'blocked');
* // => 'pebbles'
*/
function findLastKey(object, callback, thisArg) {
var result;
callback = lodash.createCallback(callback, thisArg, 3);
forOwnRight(object, function(value, key, object) {
if (callback(value, key, object)) {
result = key;
return false;
}
});
return result;
}
/**
* Iterates over own and inherited enumerable properties of an object,
* executing the callback for each property. The callback is bound to `thisArg`
* and invoked with three arguments; (value, key, object). Callbacks may exit
* iteration early by explicitly returning `false`.
*
* @static
* @memberOf _
* @type Function
* @category Objects
* @param {Object} object The object to iterate over.
* @param {Function} [callback=identity] The function called per iteration.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {Object} Returns `object`.
* @example
*
* function Shape() {
* this.x = 0;
* this.y = 0;
* }
*
* Shape.prototype.move = function(x, y) {
* this.x += x;
* this.y += y;
* };
*
* _.forIn(new Shape, function(value, key) {
* console.log(key);
* });
* // => logs 'x', 'y', and 'move' (property order is not guaranteed across environments)
*/
var forIn = createIterator(eachIteratorOptions, forOwnIteratorOptions, {
'useHas': false
});
/**
* This method is like `_.forIn` except that it iterates over elements
* of a `collection` in the opposite order.
*
* @static
* @memberOf _
* @category Objects
* @param {Object} object The object to iterate over.
* @param {Function} [callback=identity] The function called per iteration.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {Object} Returns `object`.
* @example
*
* function Shape() {
* this.x = 0;
* this.y = 0;
* }
*
* Shape.prototype.move = function(x, y) {
* this.x += x;
* this.y += y;
* };
*
* _.forInRight(new Shape, function(value, key) {
* console.log(key);
* });
* // => logs 'move', 'y', and 'x' assuming `_.forIn ` logs 'x', 'y', and 'move'
*/
function forInRight(object, callback, thisArg) {
var pairs = [];
forIn(object, function(value, key) {
pairs.push(key, value);
});
var length = pairs.length;
callback = baseCreateCallback(callback, thisArg, 3);
while (length--) {
if (callback(pairs[length--], pairs[length], object) === false) {
break;
}
}
return object;
}
/**
* Iterates over own enumerable properties of an object, executing the callback
* for each property. The callback is bound to `thisArg` and invoked with three
* arguments; (value, key, object). Callbacks may exit iteration early by
* explicitly returning `false`.
*
* @static
* @memberOf _
* @type Function
* @category Objects
* @param {Object} object The object to iterate over.
* @param {Function} [callback=identity] The function called per iteration.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {Object} Returns `object`.
* @example
*
* _.forOwn({ '0': 'zero', '1': 'one', 'length': 2 }, function(num, key) {
* console.log(key);
* });
* // => logs '0', '1', and 'length' (property order is not guaranteed across environments)
*/
var forOwn = createIterator(eachIteratorOptions, forOwnIteratorOptions);
/**
* This method is like `_.forOwn` except that it iterates over elements
* of a `collection` in the opposite order.
*
* @static
* @memberOf _
* @category Objects
* @param {Object} object The object to iterate over.
* @param {Function} [callback=identity] The function called per iteration.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {Object} Returns `object`.
* @example
*
* _.forOwnRight({ '0': 'zero', '1': 'one', 'length': 2 }, function(num, key) {
* console.log(key);
* });
* // => logs 'length', '1', and '0' assuming `_.forOwn` logs '0', '1', and 'length'
*/
function forOwnRight(object, callback, thisArg) {
var props = keys(object),
length = props.length;
callback = baseCreateCallback(callback, thisArg, 3);
while (length--) {
var key = props[length];
if (callback(object[key], key, object) === false) {
break;
}
}
return object;
}
/**
* Creates a sorted array of property names of all enumerable properties,
* own and inherited, of `object` that have function values.
*
* @static
* @memberOf _
* @alias methods
* @category Objects
* @param {Object} object The object to inspect.
* @returns {Array} Returns an array of property names that have function values.
* @example
*
* _.functions(_);
* // => ['all', 'any', 'bind', 'bindAll', 'clone', 'compact', 'compose', ...]
*/
function functions(object) {
var result = [];
forIn(object, function(value, key) {
if (isFunction(value)) {
result.push(key);
}
});
return result.sort();
}
/**
* Checks if the specified property name exists as a direct property of `object`,
* instead of an inherited property.
*
* @static
* @memberOf _
* @category Objects
* @param {Object} object The object to inspect.
* @param {string} key The name of the property to check.
* @returns {boolean} Returns `true` if key is a direct property, else `false`.
* @example
*
* _.has({ 'a': 1, 'b': 2, 'c': 3 }, 'b');
* // => true
*/
function has(object, key) {
return object ? hasOwnProperty.call(object, key) : false;
}
/**
* Creates an object composed of the inverted keys and values of the given object.
*
* @static
* @memberOf _
* @category Objects
* @param {Object} object The object to invert.
* @returns {Object} Returns the created inverted object.
* @example
*
* _.invert({ 'first': 'fred', 'second': 'barney' });
* // => { 'fred': 'first', 'barney': 'second' }
*/
function invert(object) {
var index = -1,
props = keys(object),
length = props.length,
result = {};
while (++index < length) {
var key = props[index];
result[object[key]] = key;
}
return result;
}
/**
* Checks if `value` is a boolean value.
*
* @static
* @memberOf _
* @category Objects
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if the `value` is a boolean value, else `false`.
* @example
*
* _.isBoolean(null);
* // => false
*/
function isBoolean(value) {
return value === true || value === false ||
value && typeof value == 'object' && toString.call(value) == boolClass || false;
}
/**
* Checks if `value` is a date.
*
* @static
* @memberOf _
* @category Objects
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if the `value` is a date, else `false`.
* @example
*
* _.isDate(new Date);
* // => true
*/
function isDate(value) {
return value && typeof value == 'object' && toString.call(value) == dateClass || false;
}
/**
* Checks if `value` is a DOM element.
*
* @static
* @memberOf _
* @category Objects
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if the `value` is a DOM element, else `false`.
* @example
*
* _.isElement(document.body);
* // => true
*/
function isElement(value) {
return value && value.nodeType === 1 || false;
}
/**
* Checks if `value` is empty. Arrays, strings, or `arguments` objects with a
* length of `0` and objects with no own enumerable properties are considered
* "empty".
*
* @static
* @memberOf _
* @category Objects
* @param {Array|Object|string} value The value to inspect.
* @returns {boolean} Returns `true` if the `value` is empty, else `false`.
* @example
*
* _.isEmpty([1, 2, 3]);
* // => false
*
* _.isEmpty({});
* // => true
*
* _.isEmpty('');
* // => true
*/
function isEmpty(value) {
var result = true;
if (!value) {
return result;
}
var className = toString.call(value),
length = value.length;
if ((className == arrayClass || className == stringClass ||
(support.argsClass ? className == argsClass : isArguments(value))) ||
(className == objectClass && typeof length == 'number' && isFunction(value.splice))) {
return !length;
}
forOwn(value, function() {
return (result = false);
});
return result;
}
/**
* Performs a deep comparison between two values to determine if they are
* equivalent to each other. If a callback is provided it will be executed
* to compare values. If the callback returns `undefined` comparisons will
* be handled by the method instead. The callback is bound to `thisArg` and
* invoked with two arguments; (a, b).
*
* @static
* @memberOf _
* @category Objects
* @param {*} a The value to compare.
* @param {*} b The other value to compare.
* @param {Function} [callback] The function to customize comparing values.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
* @example
*
* var object = { 'name': 'fred' };
* var copy = { 'name': 'fred' };
*
* object == copy;
* // => false
*
* _.isEqual(object, copy);
* // => true
*
* var words = ['hello', 'goodbye'];
* var otherWords = ['hi', 'goodbye'];
*
* _.isEqual(words, otherWords, function(a, b) {
* var reGreet = /^(?:hello|hi)$/i,
* aGreet = _.isString(a) && reGreet.test(a),
* bGreet = _.isString(b) && reGreet.test(b);
*
* return (aGreet || bGreet) ? (aGreet == bGreet) : undefined;
* });
* // => true
*/
function isEqual(a, b, callback, thisArg) {
return baseIsEqual(a, b, typeof callback == 'function' && baseCreateCallback(callback, thisArg, 2));
}
/**
* Checks if `value` is, or can be coerced to, a finite number.
*
* Note: This is not the same as native `isFinite` which will return true for
* booleans and empty strings. See http://es5.github.io/#x15.1.2.5.
*
* @static
* @memberOf _
* @category Objects
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if the `value` is finite, else `false`.
* @example
*
* _.isFinite(-101);
* // => true
*
* _.isFinite('10');
* // => true
*
* _.isFinite(true);
* // => false
*
* _.isFinite('');
* // => false
*
* _.isFinite(Infinity);
* // => false
*/
function isFinite(value) {
return nativeIsFinite(value) && !nativeIsNaN(parseFloat(value));
}
/**
* Checks if `value` is a function.
*
* @static
* @memberOf _
* @category Objects
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if the `value` is a function, else `false`.
* @example
*
* _.isFunction(_);
* // => true
*/
function isFunction(value) {
return typeof value == 'function';
}
// fallback for older versions of Chrome and Safari
if (isFunction(/x/)) {
isFunction = function(value) {
return typeof value == 'function' && toString.call(value) == funcClass;
};
}
/**
* Checks if `value` is the language type of Object.
* (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
*
* @static
* @memberOf _
* @category Objects
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if the `value` is an object, else `false`.
* @example
*
* _.isObject({});
* // => true
*
* _.isObject([1, 2, 3]);
* // => true
*
* _.isObject(1);
* // => false
*/
function isObject(value) {
// check if the value is the ECMAScript language type of Object
// http://es5.github.io/#x8
// and avoid a V8 bug
// http://code.google.com/p/v8/issues/detail?id=2291
return !!(value && objectTypes[typeof value]);
}
/**
* Checks if `value` is `NaN`.
*
* Note: This is not the same as native `isNaN` which will return `true` for
* `undefined` and other non-numeric values. See http://es5.github.io/#x15.1.2.4.
*
* @static
* @memberOf _
* @category Objects
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if the `value` is `NaN`, else `false`.
* @example
*
* _.isNaN(NaN);
* // => true
*
* _.isNaN(new Number(NaN));
* // => true
*
* isNaN(undefined);
* // => true
*
* _.isNaN(undefined);
* // => false
*/
function isNaN(value) {
// `NaN` as a primitive is the only value that is not equal to itself
// (perform the [[Class]] check first to avoid errors with some host objects in IE)
return isNumber(value) && value != +value;
}
/**
* Checks if `value` is `null`.
*
* @static
* @memberOf _
* @category Objects
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if the `value` is `null`, else `false`.
* @example
*
* _.isNull(null);
* // => true
*
* _.isNull(undefined);
* // => false
*/
function isNull(value) {
return value === null;
}
/**
* Checks if `value` is a number.
*
* Note: `NaN` is considered a number. See http://es5.github.io/#x8.5.
*
* @static
* @memberOf _
* @category Objects
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if the `value` is a number, else `false`.
* @example
*
* _.isNumber(8.4 * 5);
* // => true
*/
function isNumber(value) {
return typeof value == 'number' ||
value && typeof value == 'object' && toString.call(value) == numberClass || false;
}
/**
* Checks if `value` is an object created by the `Object` constructor.
*
* @static
* @memberOf _
* @category Objects
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a plain object, else `false`.
* @example
*
* function Shape() {
* this.x = 0;
* this.y = 0;
* }
*
* _.isPlainObject(new Shape);
* // => false
*
* _.isPlainObject([1, 2, 3]);
* // => false
*
* _.isPlainObject({ 'x': 0, 'y': 0 });
* // => true
*/
var isPlainObject = !getPrototypeOf ? shimIsPlainObject : function(value) {
if (!(value && toString.call(value) == objectClass) || (!support.argsClass && isArguments(value))) {
return false;
}
var valueOf = value.valueOf,
objProto = isNative(valueOf) && (objProto = getPrototypeOf(valueOf)) && getPrototypeOf(objProto);
return objProto
? (value == objProto || getPrototypeOf(value) == objProto)
: shimIsPlainObject(value);
};
/**
* Checks if `value` is a regular expression.
*
* @static
* @memberOf _
* @category Objects
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if the `value` is a regular expression, else `false`.
* @example
*
* _.isRegExp(/fred/);
* // => true
*/
function isRegExp(value) {
return value && objectTypes[typeof value] && toString.call(value) == regexpClass || false;
}
/**
* Checks if `value` is a string.
*
* @static
* @memberOf _
* @category Objects
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if the `value` is a string, else `false`.
* @example
*
* _.isString('fred');
* // => true
*/
function isString(value) {
return typeof value == 'string' ||
value && typeof value == 'object' && toString.call(value) == stringClass || false;
}
/**
* Checks if `value` is `undefined`.
*
* @static
* @memberOf _
* @category Objects
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if the `value` is `undefined`, else `false`.
* @example
*
* _.isUndefined(void 0);
* // => true
*/
function isUndefined(value) {
return typeof value == 'undefined';
}
/**
* Creates an object with the same keys as `object` and values generated by
* running each own enumerable property of `object` through the callback.
* The callback is bound to `thisArg` and invoked with three arguments;
* (value, key, object).
*
* If a property name is provided for `callback` the created "_.pluck" style
* callback will return the property value of the given element.
*
* If an object is provided for `callback` the created "_.where" style callback
* will return `true` for elements that have the properties of the given object,
* else `false`.
*
* @static
* @memberOf _
* @category Objects
* @param {Object} object The object to iterate over.
* @param {Function|Object|string} [callback=identity] The function called
* per iteration. If a property name or object is provided it will be used
* to create a "_.pluck" or "_.where" style callback, respectively.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {Array} Returns a new object with values of the results of each `callback` execution.
* @example
*
* _.mapValues({ 'a': 1, 'b': 2, 'c': 3} , function(num) { return num * 3; });
* // => { 'a': 3, 'b': 6, 'c': 9 }
*
* var characters = {
* 'fred': { 'name': 'fred', 'age': 40 },
* 'pebbles': { 'name': 'pebbles', 'age': 1 }
* };
*
* // using "_.pluck" callback shorthand
* _.mapValues(characters, 'age');
* // => { 'fred': 40, 'pebbles': 1 }
*/
function mapValues(object, callback, thisArg) {
var result = {};
callback = lodash.createCallback(callback, thisArg, 3);
forOwn(object, function(value, key, object) {
result[key] = callback(value, key, object);
});
return result;
}
/**
* Recursively merges own enumerable properties of the source object(s), that
* don't resolve to `undefined` into the destination object. Subsequent sources
* will overwrite property assignments of previous sources. If a callback is
* provided it will be executed to produce the merged values of the destination
* and source properties. If the callback returns `undefined` merging will
* be handled by the method instead. The callback is bound to `thisArg` and
* invoked with two arguments; (objectValue, sourceValue).
*
* @static
* @memberOf _
* @category Objects
* @param {Object} object The destination object.
* @param {...Object} [source] The source objects.
* @param {Function} [callback] The function to customize merging properties.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {Object} Returns the destination object.
* @example
*
* var names = {
* 'characters': [
* { 'name': 'barney' },
* { 'name': 'fred' }
* ]
* };
*
* var ages = {
* 'characters': [
* { 'age': 36 },
* { 'age': 40 }
* ]
* };
*
* _.merge(names, ages);
* // => { 'characters': [{ 'name': 'barney', 'age': 36 }, { 'name': 'fred', 'age': 40 }] }
*
* var food = {
* 'fruits': ['apple'],
* 'vegetables': ['beet']
* };
*
* var otherFood = {
* 'fruits': ['banana'],
* 'vegetables': ['carrot']
* };
*
* _.merge(food, otherFood, function(a, b) {
* return _.isArray(a) ? a.concat(b) : undefined;
* });
* // => { 'fruits': ['apple', 'banana'], 'vegetables': ['beet', 'carrot] }
*/
function merge(object) {
var args = arguments,
length = 2;
if (!isObject(object)) {
return object;
}
// allows working with `_.reduce` and `_.reduceRight` without using
// their `index` and `collection` arguments
if (typeof args[2] != 'number') {
length = args.length;
}
if (length > 3 && typeof args[length - 2] == 'function') {
var callback = baseCreateCallback(args[--length - 1], args[length--], 2);
} else if (length > 2 && typeof args[length - 1] == 'function') {
callback = args[--length];
}
var sources = slice(arguments, 1, length),
index = -1,
stackA = getArray(),
stackB = getArray();
while (++index < length) {
baseMerge(object, sources[index], callback, stackA, stackB);
}
releaseArray(stackA);
releaseArray(stackB);
return object;
}
/**
* Creates a shallow clone of `object` excluding the specified properties.
* Property names may be specified as individual arguments or as arrays of
* property names. If a callback is provided it will be executed for each
* property of `object` omitting the properties the callback returns truey
* for. The callback is bound to `thisArg` and invoked with three arguments;
* (value, key, object).
*
* @static
* @memberOf _
* @category Objects
* @param {Object} object The source object.
* @param {Function|...string|string[]} [callback] The properties to omit or the
* function called per iteration.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {Object} Returns an object without the omitted properties.
* @example
*
* _.omit({ 'name': 'fred', 'age': 40 }, 'age');
* // => { 'name': 'fred' }
*
* _.omit({ 'name': 'fred', 'age': 40 }, function(value) {
* return typeof value == 'number';
* });
* // => { 'name': 'fred' }
*/
function omit(object, callback, thisArg) {
var result = {};
if (typeof callback != 'function') {
var props = [];
forIn(object, function(value, key) {
props.push(key);
});
props = baseDifference(props, baseFlatten(arguments, true, false, 1));
var index = -1,
length = props.length;
while (++index < length) {
var key = props[index];
result[key] = object[key];
}
} else {
callback = lodash.createCallback(callback, thisArg, 3);
forIn(object, function(value, key, object) {
if (!callback(value, key, object)) {
result[key] = value;
}
});
}
return result;
}
/**
* Creates a two dimensional array of an object's key-value pairs,
* i.e. `[[key1, value1], [key2, value2]]`.
*
* @static
* @memberOf _
* @category Objects
* @param {Object} object The object to inspect.
* @returns {Array} Returns new array of key-value pairs.
* @example
*
* _.pairs({ 'barney': 36, 'fred': 40 });
* // => [['barney', 36], ['fred', 40]] (property order is not guaranteed across environments)
*/
function pairs(object) {
var index = -1,
props = keys(object),
length = props.length,
result = Array(length);
while (++index < length) {
var key = props[index];
result[index] = [key, object[key]];
}
return result;
}
/**
* Creates a shallow clone of `object` composed of the specified properties.
* Property names may be specified as individual arguments or as arrays of
* property names. If a callback is provided it will be executed for each
* property of `object` picking the properties the callback returns truey
* for. The callback is bound to `thisArg` and invoked with three arguments;
* (value, key, object).
*
* @static
* @memberOf _
* @category Objects
* @param {Object} object The source object.
* @param {Function|...string|string[]} [callback] The function called per
* iteration or property names to pick, specified as individual property
* names or arrays of property names.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {Object} Returns an object composed of the picked properties.
* @example
*
* _.pick({ 'name': 'fred', '_userid': 'fred1' }, 'name');
* // => { 'name': 'fred' }
*
* _.pick({ 'name': 'fred', '_userid': 'fred1' }, function(value, key) {
* return key.charAt(0) != '_';
* });
* // => { 'name': 'fred' }
*/
function pick(object, callback, thisArg) {
var result = {};
if (typeof callback != 'function') {
var index = -1,
props = baseFlatten(arguments, true, false, 1),
length = isObject(object) ? props.length : 0;
while (++index < length) {
var key = props[index];
if (key in object) {
result[key] = object[key];
}
}
} else {
callback = lodash.createCallback(callback, thisArg, 3);
forIn(object, function(value, key, object) {
if (callback(value, key, object)) {
result[key] = value;
}
});
}
return result;
}
/**
* An alternative to `_.reduce` this method transforms `object` to a new
* `accumulator` object which is the result of running each of its own
* enumerable properties through a callback, with each callback execution
* potentially mutating the `accumulator` object. The callback is bound to
* `thisArg` and invoked with four arguments; (accumulator, value, key, object).
* Callbacks may exit iteration early by explicitly returning `false`.
*
* @static
* @memberOf _
* @category Objects
* @param {Array|Object} object The object to iterate over.
* @param {Function} [callback=identity] The function called per iteration.
* @param {*} [accumulator] The custom accumulator value.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {*} Returns the accumulated value.
* @example
*
* var squares = _.transform([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], function(result, num) {
* num *= num;
* if (num % 2) {
* return result.push(num) < 3;
* }
* });
* // => [1, 9, 25]
*
* var mapped = _.transform({ 'a': 1, 'b': 2, 'c': 3 }, function(result, num, key) {
* result[key] = num * 3;
* });
* // => { 'a': 3, 'b': 6, 'c': 9 }
*/
function transform(object, callback, accumulator, thisArg) {
var isArr = isArray(object);
if (accumulator == null) {
if (isArr) {
accumulator = [];
} else {
var ctor = object && object.constructor,
proto = ctor && ctor.prototype;
accumulator = baseCreate(proto);
}
}
if (callback) {
callback = lodash.createCallback(callback, thisArg, 4);
(isArr ? baseEach : forOwn)(object, function(value, index, object) {
return callback(accumulator, value, index, object);
});
}
return accumulator;
}
/**
* Creates an array composed of the own enumerable property values of `object`.
*
* @static
* @memberOf _
* @category Objects
* @param {Object} object The object to inspect.
* @returns {Array} Returns an array of property values.
* @example
*
* _.values({ 'one': 1, 'two': 2, 'three': 3 });
* // => [1, 2, 3] (property order is not guaranteed across environments)
*/
function values(object) {
var index = -1,
props = keys(object),
length = props.length,
result = Array(length);
while (++index < length) {
result[index] = object[props[index]];
}
return result;
}
/*--------------------------------------------------------------------------*/
/**
* Creates an array of elements from the specified indexes, or keys, of the
* `collection`. Indexes may be specified as individual arguments or as arrays
* of indexes.
*
* @static
* @memberOf _
* @category Collections
* @param {Array|Object|string} collection The collection to iterate over.
* @param {...(number|number[]|string|string[])} [index] The indexes of `collection`
* to retrieve, specified as individual indexes or arrays of indexes.
* @returns {Array} Returns a new array of elements corresponding to the
* provided indexes.
* @example
*
* _.at(['a', 'b', 'c', 'd', 'e'], [0, 2, 4]);
* // => ['a', 'c', 'e']
*
* _.at(['fred', 'barney', 'pebbles'], 0, 2);
* // => ['fred', 'pebbles']
*/
function at(collection) {
var args = arguments,
index = -1,
props = baseFlatten(args, true, false, 1),
length = (args[2] && args[2][args[1]] === collection) ? 1 : props.length,
result = Array(length);
if (support.unindexedChars && isString(collection)) {
collection = collection.split('');
}
while(++index < length) {
result[index] = collection[props[index]];
}
return result;
}
/**
* Checks if a given value is present in a collection using strict equality
* for comparisons, i.e. `===`. If `fromIndex` is negative, it is used as the
* offset from the end of the collection.
*
* @static
* @memberOf _
* @alias include
* @category Collections
* @param {Array|Object|string} collection The collection to iterate over.
* @param {*} target The value to check for.
* @param {number} [fromIndex=0] The index to search from.
* @returns {boolean} Returns `true` if the `target` element is found, else `false`.
* @example
*
* _.contains([1, 2, 3], 1);
* // => true
*
* _.contains([1, 2, 3], 1, 2);
* // => false
*
* _.contains({ 'name': 'fred', 'age': 40 }, 'fred');
* // => true
*
* _.contains('pebbles', 'eb');
* // => true
*/
function contains(collection, target, fromIndex) {
var index = -1,
indexOf = getIndexOf(),
length = collection ? collection.length : 0,
result = false;
fromIndex = (fromIndex < 0 ? nativeMax(0, length + fromIndex) : fromIndex) || 0;
if (isArray(collection)) {
result = indexOf(collection, target, fromIndex) > -1;
} else if (typeof length == 'number') {
result = (isString(collection) ? collection.indexOf(target, fromIndex) : indexOf(collection, target, fromIndex)) > -1;
} else {
baseEach(collection, function(value) {
if (++index >= fromIndex) {
return !(result = value === target);
}
});
}
return result;
}
/**
* Creates an object composed of keys generated from the results of running
* each element of `collection` through the callback. The corresponding value
* of each key is the number of times the key was returned by the callback.
* The callback is bound to `thisArg` and invoked with three arguments;
* (value, index|key, collection).
*
* If a property name is provided for `callback` the created "_.pluck" style
* callback will return the property value of the given element.
*
* If an object is provided for `callback` the created "_.where" style callback
* will return `true` for elements that have the properties of the given object,
* else `false`.
*
* @static
* @memberOf _
* @category Collections
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function|Object|string} [callback=identity] The function called
* per iteration. If a property name or object is provided it will be used
* to create a "_.pluck" or "_.where" style callback, respectively.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {Object} Returns the composed aggregate object.
* @example
*
* _.countBy([4.3, 6.1, 6.4], function(num) { return Math.floor(num); });
* // => { '4': 1, '6': 2 }
*
* _.countBy([4.3, 6.1, 6.4], function(num) { return this.floor(num); }, Math);
* // => { '4': 1, '6': 2 }
*
* _.countBy(['one', 'two', 'three'], 'length');
* // => { '3': 2, '5': 1 }
*/
var countBy = createAggregator(function(result, value, key) {
(hasOwnProperty.call(result, key) ? result[key]++ : result[key] = 1);
});
/**
* Checks if the given callback returns truey value for **all** elements of
* a collection. The callback is bound to `thisArg` and invoked with three
* arguments; (value, index|key, collection).
*
* If a property name is provided for `callback` the created "_.pluck" style
* callback will return the property value of the given element.
*
* If an object is provided for `callback` the created "_.where" style callback
* will return `true` for elements that have the properties of the given object,
* else `false`.
*
* @static
* @memberOf _
* @alias all
* @category Collections
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function|Object|string} [callback=identity] The function called
* per iteration. If a property name or object is provided it will be used
* to create a "_.pluck" or "_.where" style callback, respectively.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {boolean} Returns `true` if all elements passed the callback check,
* else `false`.
* @example
*
* _.every([true, 1, null, 'yes']);
* // => false
*
* var characters = [
* { 'name': 'barney', 'age': 36 },
* { 'name': 'fred', 'age': 40 }
* ];
*
* // using "_.pluck" callback shorthand
* _.every(characters, 'age');
* // => true
*
* // using "_.where" callback shorthand
* _.every(characters, { 'age': 36 });
* // => false
*/
function every(collection, callback, thisArg) {
var result = true;
callback = lodash.createCallback(callback, thisArg, 3);
if (isArray(collection)) {
var index = -1,
length = collection.length;
while (++index < length) {
if (!(result = !!callback(collection[index], index, collection))) {
break;
}
}
} else {
baseEach(collection, function(value, index, collection) {
return (result = !!callback(value, index, collection));
});
}
return result;
}
/**
* Iterates over elements of a collection, returning an array of all elements
* the callback returns truey for. The callback is bound to `thisArg` and
* invoked with three arguments; (value, index|key, collection).
*
* If a property name is provided for `callback` the created "_.pluck" style
* callback will return the property value of the given element.
*
* If an object is provided for `callback` the created "_.where" style callback
* will return `true` for elements that have the properties of the given object,
* else `false`.
*
* @static
* @memberOf _
* @alias select
* @category Collections
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function|Object|string} [callback=identity] The function called
* per iteration. If a property name or object is provided it will be used
* to create a "_.pluck" or "_.where" style callback, respectively.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {Array} Returns a new array of elements that passed the callback check.
* @example
*
* var evens = _.filter([1, 2, 3, 4, 5, 6], function(num) { return num % 2 == 0; });
* // => [2, 4, 6]
*
* var characters = [
* { 'name': 'barney', 'age': 36, 'blocked': false },
* { 'name': 'fred', 'age': 40, 'blocked': true }
* ];
*
* // using "_.pluck" callback shorthand
* _.filter(characters, 'blocked');
* // => [{ 'name': 'fred', 'age': 40, 'blocked': true }]
*
* // using "_.where" callback shorthand
* _.filter(characters, { 'age': 36 });
* // => [{ 'name': 'barney', 'age': 36, 'blocked': false }]
*/
function filter(collection, callback, thisArg) {
var result = [];
callback = lodash.createCallback(callback, thisArg, 3);
if (isArray(collection)) {
var index = -1,
length = collection.length;
while (++index < length) {
var value = collection[index];
if (callback(value, index, collection)) {
result.push(value);
}
}
} else {
baseEach(collection, function(value, index, collection) {
if (callback(value, index, collection)) {
result.push(value);
}
});
}
return result;
}
/**
* Iterates over elements of a collection, returning the first element that
* the callback returns truey for. The callback is bound to `thisArg` and
* invoked with three arguments; (value, index|key, collection).
*
* If a property name is provided for `callback` the created "_.pluck" style
* callback will return the property value of the given element.
*
* If an object is provided for `callback` the created "_.where" style callback
* will return `true` for elements that have the properties of the given object,
* else `false`.
*
* @static
* @memberOf _
* @alias detect, findWhere
* @category Collections
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function|Object|string} [callback=identity] The function called
* per iteration. If a property name or object is provided it will be used
* to create a "_.pluck" or "_.where" style callback, respectively.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {*} Returns the found element, else `undefined`.
* @example
*
* var characters = [
* { 'name': 'barney', 'age': 36, 'blocked': false },
* { 'name': 'fred', 'age': 40, 'blocked': true },
* { 'name': 'pebbles', 'age': 1, 'blocked': false }
* ];
*
* _.find(characters, function(chr) {
* return chr.age < 40;
* });
* // => { 'name': 'barney', 'age': 36, 'blocked': false }
*
* // using "_.where" callback shorthand
* _.find(characters, { 'age': 1 });
* // => { 'name': 'pebbles', 'age': 1, 'blocked': false }
*
* // using "_.pluck" callback shorthand
* _.find(characters, 'blocked');
* // => { 'name': 'fred', 'age': 40, 'blocked': true }
*/
function find(collection, callback, thisArg) {
callback = lodash.createCallback(callback, thisArg, 3);
if (isArray(collection)) {
var index = -1,
length = collection.length;
while (++index < length) {
var value = collection[index];
if (callback(value, index, collection)) {
return value;
}
}
} else {
var result;
baseEach(collection, function(value, index, collection) {
if (callback(value, index, collection)) {
result = value;
return false;
}
});
return result;
}
}
/**
* This method is like `_.find` except that it iterates over elements
* of a `collection` from right to left.
*
* @static
* @memberOf _
* @category Collections
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function|Object|string} [callback=identity] The function called
* per iteration. If a property name or object is provided it will be used
* to create a "_.pluck" or "_.where" style callback, respectively.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {*} Returns the found element, else `undefined`.
* @example
*
* _.findLast([1, 2, 3, 4], function(num) {
* return num % 2 == 1;
* });
* // => 3
*/
function findLast(collection, callback, thisArg) {
var result;
callback = lodash.createCallback(callback, thisArg, 3);
forEachRight(collection, function(value, index, collection) {
if (callback(value, index, collection)) {
result = value;
return false;
}
});
return result;
}
/**
* Iterates over elements of a collection, executing the callback for each
* element. The callback is bound to `thisArg` and invoked with three arguments;
* (value, index|key, collection). Callbacks may exit iteration early by
* explicitly returning `false`.
*
* Note: As with other "Collections" methods, objects with a `length` property
* are iterated like arrays. To avoid this behavior `_.forIn` or `_.forOwn`
* may be used for object iteration.
*
* @static
* @memberOf _
* @alias each
* @category Collections
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function} [callback=identity] The function called per iteration.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {Array|Object|string} Returns `collection`.
* @example
*
* _([1, 2, 3]).forEach(function(num) { console.log(num); }).join(',');
* // => logs each number and returns '1,2,3'
*
* _.forEach({ 'one': 1, 'two': 2, 'three': 3 }, function(num) { console.log(num); });
* // => logs each number and returns the object (property order is not guaranteed across environments)
*/
function forEach(collection, callback, thisArg) {
if (callback && typeof thisArg == 'undefined' && isArray(collection)) {
var index = -1,
length = collection.length;
while (++index < length) {
if (callback(collection[index], index, collection) === false) {
break;
}
}
} else {
baseEach(collection, callback, thisArg);
}
return collection;
}
/**
* This method is like `_.forEach` except that it iterates over elements
* of a `collection` from right to left.
*
* @static
* @memberOf _
* @alias eachRight
* @category Collections
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function} [callback=identity] The function called per iteration.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {Array|Object|string} Returns `collection`.
* @example
*
* _([1, 2, 3]).forEachRight(function(num) { console.log(num); }).join(',');
* // => logs each number from right to left and returns '3,2,1'
*/
function forEachRight(collection, callback, thisArg) {
var iterable = collection,
length = collection ? collection.length : 0;
callback = callback && typeof thisArg == 'undefined' ? callback : baseCreateCallback(callback, thisArg, 3);
if (isArray(collection)) {
while (length--) {
if (callback(collection[length], length, collection) === false) {
break;
}
}
} else {
if (typeof length != 'number') {
var props = keys(collection);
length = props.length;
} else if (support.unindexedChars && isString(collection)) {
iterable = collection.split('');
}
baseEach(collection, function(value, key, collection) {
key = props ? props[--length] : --length;
return callback(iterable[key], key, collection);
});
}
return collection;
}
/**
* Creates an object composed of keys generated from the results of running
* each element of a collection through the callback. The corresponding value
* of each key is an array of the elements responsible for generating the key.
* The callback is bound to `thisArg` and invoked with three arguments;
* (value, index|key, collection).
*
* If a property name is provided for `callback` the created "_.pluck" style
* callback will return the property value of the given element.
*
* If an object is provided for `callback` the created "_.where" style callback
* will return `true` for elements that have the properties of the given object,
* else `false`
*
* @static
* @memberOf _
* @category Collections
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function|Object|string} [callback=identity] The function called
* per iteration. If a property name or object is provided it will be used
* to create a "_.pluck" or "_.where" style callback, respectively.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {Object} Returns the composed aggregate object.
* @example
*
* _.groupBy([4.2, 6.1, 6.4], function(num) { return Math.floor(num); });
* // => { '4': [4.2], '6': [6.1, 6.4] }
*
* _.groupBy([4.2, 6.1, 6.4], function(num) { return this.floor(num); }, Math);
* // => { '4': [4.2], '6': [6.1, 6.4] }
*
* // using "_.pluck" callback shorthand
* _.groupBy(['one', 'two', 'three'], 'length');
* // => { '3': ['one', 'two'], '5': ['three'] }
*/
var groupBy = createAggregator(function(result, value, key) {
(hasOwnProperty.call(result, key) ? result[key] : result[key] = []).push(value);
});
/**
* Creates an object composed of keys generated from the results of running
* each element of the collection through the given callback. The corresponding
* value of each key is the last element responsible for generating the key.
* The callback is bound to `thisArg` and invoked with three arguments;
* (value, index|key, collection).
*
* If a property name is provided for `callback` the created "_.pluck" style
* callback will return the property value of the given element.
*
* If an object is provided for `callback` the created "_.where" style callback
* will return `true` for elements that have the properties of the given object,
* else `false`.
*
* @static
* @memberOf _
* @category Collections
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function|Object|string} [callback=identity] The function called
* per iteration. If a property name or object is provided it will be used
* to create a "_.pluck" or "_.where" style callback, respectively.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {Object} Returns the composed aggregate object.
* @example
*
* var keys = [
* { 'dir': 'left', 'code': 97 },
* { 'dir': 'right', 'code': 100 }
* ];
*
* _.indexBy(keys, 'dir');
* // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } }
*
* _.indexBy(keys, function(key) { return String.fromCharCode(key.code); });
* // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } }
*
* _.indexBy(characters, function(key) { this.fromCharCode(key.code); }, String);
* // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } }
*/
var indexBy = createAggregator(function(result, value, key) {
result[key] = value;
});
/**
* Invokes the method named by `methodName` on each element in the `collection`
* returning an array of the results of each invoked method. Additional arguments
* will be provided to each invoked method. If `methodName` is a function it
* will be invoked for, and `this` bound to, each element in the `collection`.
*
* @static
* @memberOf _
* @category Collections
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function|string} methodName The name of the method to invoke or
* the function invoked per iteration.
* @param {...*} [arg] Arguments to invoke the method with.
* @returns {Array} Returns a new array of the results of each invoked method.
* @example
*
* _.invoke([[5, 1, 7], [3, 2, 1]], 'sort');
* // => [[1, 5, 7], [1, 2, 3]]
*
* _.invoke([123, 456], String.prototype.split, '');
* // => [['1', '2', '3'], ['4', '5', '6']]
*/
function invoke(collection, methodName) {
var args = slice(arguments, 2),
index = -1,
isFunc = typeof methodName == 'function',
length = collection ? collection.length : 0,
result = Array(typeof length == 'number' ? length : 0);
forEach(collection, function(value) {
result[++index] = (isFunc ? methodName : value[methodName]).apply(value, args);
});
return result;
}
/**
* Creates an array of values by running each element in the collection
* through the callback. The callback is bound to `thisArg` and invoked with
* three arguments; (value, index|key, collection).
*
* If a property name is provided for `callback` the created "_.pluck" style
* callback will return the property value of the given element.
*
* If an object is provided for `callback` the created "_.where" style callback
* will return `true` for elements that have the properties of the given object,
* else `false`.
*
* @static
* @memberOf _
* @alias collect
* @category Collections
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function|Object|string} [callback=identity] The function called
* per iteration. If a property name or object is provided it will be used
* to create a "_.pluck" or "_.where" style callback, respectively.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {Array} Returns a new array of the results of each `callback` execution.
* @example
*
* _.map([1, 2, 3], function(num) { return num * 3; });
* // => [3, 6, 9]
*
* _.map({ 'one': 1, 'two': 2, 'three': 3 }, function(num) { return num * 3; });
* // => [3, 6, 9] (property order is not guaranteed across environments)
*
* var characters = [
* { 'name': 'barney', 'age': 36 },
* { 'name': 'fred', 'age': 40 }
* ];
*
* // using "_.pluck" callback shorthand
* _.map(characters, 'name');
* // => ['barney', 'fred']
*/
function map(collection, callback, thisArg) {
var index = -1,
length = collection ? collection.length : 0,
result = Array(typeof length == 'number' ? length : 0);
callback = lodash.createCallback(callback, thisArg, 3);
if (isArray(collection)) {
while (++index < length) {
result[index] = callback(collection[index], index, collection);
}
} else {
baseEach(collection, function(value, key, collection) {
result[++index] = callback(value, key, collection);
});
}
return result;
}
/**
* Retrieves the maximum value of a collection. If the collection is empty or
* falsey `-Infinity` is returned. If a callback is provided it will be executed
* for each value in the collection to generate the criterion by which the value
* is ranked. The callback is bound to `thisArg` and invoked with three
* arguments; (value, index, collection).
*
* If a property name is provided for `callback` the created "_.pluck" style
* callback will return the property value of the given element.
*
* If an object is provided for `callback` the created "_.where" style callback
* will return `true` for elements that have the properties of the given object,
* else `false`.
*
* @static
* @memberOf _
* @category Collections
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function|Object|string} [callback=identity] The function called
* per iteration. If a property name or object is provided it will be used
* to create a "_.pluck" or "_.where" style callback, respectively.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {*} Returns the maximum value.
* @example
*
* _.max([4, 2, 8, 6]);
* // => 8
*
* var characters = [
* { 'name': 'barney', 'age': 36 },
* { 'name': 'fred', 'age': 40 }
* ];
*
* _.max(characters, function(chr) { return chr.age; });
* // => { 'name': 'fred', 'age': 40 };
*
* // using "_.pluck" callback shorthand
* _.max(characters, 'age');
* // => { 'name': 'fred', 'age': 40 };
*/
function max(collection, callback, thisArg) {
var computed = -Infinity,
result = computed;
// allows working with functions like `_.map` without using
// their `index` argument as a callback
if (typeof callback != 'function' && thisArg && thisArg[callback] === collection) {
callback = null;
}
if (callback == null && isArray(collection)) {
var index = -1,
length = collection.length;
while (++index < length) {
var value = collection[index];
if (value > result) {
result = value;
}
}
} else {
callback = (callback == null && isString(collection))
? charAtCallback
: lodash.createCallback(callback, thisArg, 3);
baseEach(collection, function(value, index, collection) {
var current = callback(value, index, collection);
if (current > computed) {
computed = current;
result = value;
}
});
}
return result;
}
/**
* Retrieves the minimum value of a collection. If the collection is empty or
* falsey `Infinity` is returned. If a callback is provided it will be executed
* for each value in the collection to generate the criterion by which the value
* is ranked. The callback is bound to `thisArg` and invoked with three
* arguments; (value, index, collection).
*
* If a property name is provided for `callback` the created "_.pluck" style
* callback will return the property value of the given element.
*
* If an object is provided for `callback` the created "_.where" style callback
* will return `true` for elements that have the properties of the given object,
* else `false`.
*
* @static
* @memberOf _
* @category Collections
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function|Object|string} [callback=identity] The function called
* per iteration. If a property name or object is provided it will be used
* to create a "_.pluck" or "_.where" style callback, respectively.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {*} Returns the minimum value.
* @example
*
* _.min([4, 2, 8, 6]);
* // => 2
*
* var characters = [
* { 'name': 'barney', 'age': 36 },
* { 'name': 'fred', 'age': 40 }
* ];
*
* _.min(characters, function(chr) { return chr.age; });
* // => { 'name': 'barney', 'age': 36 };
*
* // using "_.pluck" callback shorthand
* _.min(characters, 'age');
* // => { 'name': 'barney', 'age': 36 };
*/
function min(collection, callback, thisArg) {
var computed = Infinity,
result = computed;
// allows working with functions like `_.map` without using
// their `index` argument as a callback
if (typeof callback != 'function' && thisArg && thisArg[callback] === collection) {
callback = null;
}
if (callback == null && isArray(collection)) {
var index = -1,
length = collection.length;
while (++index < length) {
var value = collection[index];
if (value < result) {
result = value;
}
}
} else {
callback = (callback == null && isString(collection))
? charAtCallback
: lodash.createCallback(callback, thisArg, 3);
baseEach(collection, function(value, index, collection) {
var current = callback(value, index, collection);
if (current < computed) {
computed = current;
result = value;
}
});
}
return result;
}
/**
* Retrieves the value of a specified property from all elements in the collection.
*
* @static
* @memberOf _
* @type Function
* @category Collections
* @param {Array|Object|string} collection The collection to iterate over.
* @param {string} property The name of the property to pluck.
* @returns {Array} Returns a new array of property values.
* @example
*
* var characters = [
* { 'name': 'barney', 'age': 36 },
* { 'name': 'fred', 'age': 40 }
* ];
*
* _.pluck(characters, 'name');
* // => ['barney', 'fred']
*/
var pluck = map;
/**
* Reduces a collection to a value which is the accumulated result of running
* each element in the collection through the callback, where each successive
* callback execution consumes the return value of the previous execution. If
* `accumulator` is not provided the first element of the collection will be
* used as the initial `accumulator` value. The callback is bound to `thisArg`
* and invoked with four arguments; (accumulator, value, index|key, collection).
*
* @static
* @memberOf _
* @alias foldl, inject
* @category Collections
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function} [callback=identity] The function called per iteration.
* @param {*} [accumulator] Initial value of the accumulator.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {*} Returns the accumulated value.
* @example
*
* var sum = _.reduce([1, 2, 3], function(sum, num) {
* return sum + num;
* });
* // => 6
*
* var mapped = _.reduce({ 'a': 1, 'b': 2, 'c': 3 }, function(result, num, key) {
* result[key] = num * 3;
* return result;
* }, {});
* // => { 'a': 3, 'b': 6, 'c': 9 }
*/
function reduce(collection, callback, accumulator, thisArg) {
var noaccum = arguments.length < 3;
callback = lodash.createCallback(callback, thisArg, 4);
if (isArray(collection)) {
var index = -1,
length = collection.length;
if (noaccum) {
accumulator = collection[++index];
}
while (++index < length) {
accumulator = callback(accumulator, collection[index], index, collection);
}
} else {
baseEach(collection, function(value, index, collection) {
accumulator = noaccum
? (noaccum = false, value)
: callback(accumulator, value, index, collection)
});
}
return accumulator;
}
/**
* This method is like `_.reduce` except that it iterates over elements
* of a `collection` from right to left.
*
* @static
* @memberOf _
* @alias foldr
* @category Collections
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function} [callback=identity] The function called per iteration.
* @param {*} [accumulator] Initial value of the accumulator.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {*} Returns the accumulated value.
* @example
*
* var list = [[0, 1], [2, 3], [4, 5]];
* var flat = _.reduceRight(list, function(a, b) { return a.concat(b); }, []);
* // => [4, 5, 2, 3, 0, 1]
*/
function reduceRight(collection, callback, accumulator, thisArg) {
var noaccum = arguments.length < 3;
callback = lodash.createCallback(callback, thisArg, 4);
forEachRight(collection, function(value, index, collection) {
accumulator = noaccum
? (noaccum = false, value)
: callback(accumulator, value, index, collection);
});
return accumulator;
}
/**
* The opposite of `_.filter` this method returns the elements of a
* collection that the callback does **not** return truey for.
*
* If a property name is provided for `callback` the created "_.pluck" style
* callback will return the property value of the given element.
*
* If an object is provided for `callback` the created "_.where" style callback
* will return `true` for elements that have the properties of the given object,
* else `false`.
*
* @static
* @memberOf _
* @category Collections
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function|Object|string} [callback=identity] The function called
* per iteration. If a property name or object is provided it will be used
* to create a "_.pluck" or "_.where" style callback, respectively.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {Array} Returns a new array of elements that failed the callback check.
* @example
*
* var odds = _.reject([1, 2, 3, 4, 5, 6], function(num) { return num % 2 == 0; });
* // => [1, 3, 5]
*
* var characters = [
* { 'name': 'barney', 'age': 36, 'blocked': false },
* { 'name': 'fred', 'age': 40, 'blocked': true }
* ];
*
* // using "_.pluck" callback shorthand
* _.reject(characters, 'blocked');
* // => [{ 'name': 'barney', 'age': 36, 'blocked': false }]
*
* // using "_.where" callback shorthand
* _.reject(characters, { 'age': 36 });
* // => [{ 'name': 'fred', 'age': 40, 'blocked': true }]
*/
function reject(collection, callback, thisArg) {
callback = lodash.createCallback(callback, thisArg, 3);
return filter(collection, function(value, index, collection) {
return !callback(value, index, collection);
});
}
/**
* Retrieves a random element or `n` random elements from a collection.
*
* @static
* @memberOf _
* @category Collections
* @param {Array|Object|string} collection The collection to sample.
* @param {number} [n] The number of elements to sample.
* @param- {Object} [guard] Allows working with functions like `_.map`
* without using their `index` arguments as `n`.
* @returns {Array} Returns the random sample(s) of `collection`.
* @example
*
* _.sample([1, 2, 3, 4]);
* // => 2
*
* _.sample([1, 2, 3, 4], 2);
* // => [3, 1]
*/
function sample(collection, n, guard) {
if (collection && typeof collection.length != 'number') {
collection = values(collection);
} else if (support.unindexedChars && isString(collection)) {
collection = collection.split('');
}
if (n == null || guard) {
return collection ? collection[baseRandom(0, collection.length - 1)] : undefined;
}
var result = shuffle(collection);
result.length = nativeMin(nativeMax(0, n), result.length);
return result;
}
/**
* Creates an array of shuffled values, using a version of the Fisher-Yates
* shuffle. See http://en.wikipedia.org/wiki/Fisher-Yates_shuffle.
*
* @static
* @memberOf _
* @category Collections
* @param {Array|Object|string} collection The collection to shuffle.
* @returns {Array} Returns a new shuffled collection.
* @example
*
* _.shuffle([1, 2, 3, 4, 5, 6]);
* // => [4, 1, 6, 3, 5, 2]
*/
function shuffle(collection) {
var index = -1,
length = collection ? collection.length : 0,
result = Array(typeof length == 'number' ? length : 0);
forEach(collection, function(value) {
var rand = baseRandom(0, ++index);
result[index] = result[rand];
result[rand] = value;
});
return result;
}
/**
* Gets the size of the `collection` by returning `collection.length` for arrays
* and array-like objects or the number of own enumerable properties for objects.
*
* @static
* @memberOf _
* @category Collections
* @param {Array|Object|string} collection The collection to inspect.
* @returns {number} Returns `collection.length` or number of own enumerable properties.
* @example
*
* _.size([1, 2]);
* // => 2
*
* _.size({ 'one': 1, 'two': 2, 'three': 3 });
* // => 3
*
* _.size('pebbles');
* // => 7
*/
function size(collection) {
var length = collection ? collection.length : 0;
return typeof length == 'number' ? length : keys(collection).length;
}
/**
* Checks if the callback returns a truey value for **any** element of a
* collection. The function returns as soon as it finds a passing value and
* does not iterate over the entire collection. The callback is bound to
* `thisArg` and invoked with three arguments; (value, index|key, collection).
*
* If a property name is provided for `callback` the created "_.pluck" style
* callback will return the property value of the given element.
*
* If an object is provided for `callback` the created "_.where" style callback
* will return `true` for elements that have the properties of the given object,
* else `false`.
*
* @static
* @memberOf _
* @alias any
* @category Collections
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function|Object|string} [callback=identity] The function called
* per iteration. If a property name or object is provided it will be used
* to create a "_.pluck" or "_.where" style callback, respectively.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {boolean} Returns `true` if any element passed the callback check,
* else `false`.
* @example
*
* _.some([null, 0, 'yes', false], Boolean);
* // => true
*
* var characters = [
* { 'name': 'barney', 'age': 36, 'blocked': false },
* { 'name': 'fred', 'age': 40, 'blocked': true }
* ];
*
* // using "_.pluck" callback shorthand
* _.some(characters, 'blocked');
* // => true
*
* // using "_.where" callback shorthand
* _.some(characters, { 'age': 1 });
* // => false
*/
function some(collection, callback, thisArg) {
var result;
callback = lodash.createCallback(callback, thisArg, 3);
if (isArray(collection)) {
var index = -1,
length = collection.length;
while (++index < length) {
if ((result = callback(collection[index], index, collection))) {
break;
}
}
} else {
baseEach(collection, function(value, index, collection) {
return !(result = callback(value, index, collection));
});
}
return !!result;
}
/**
* Creates an array of elements, sorted in ascending order by the results of
* running each element in a collection through the callback. This method
* performs a stable sort, that is, it will preserve the original sort order
* of equal elements. The callback is bound to `thisArg` and invoked with
* three arguments; (value, index|key, collection).
*
* If a property name is provided for `callback` the created "_.pluck" style
* callback will return the property value of the given element.
*
* If an array of property names is provided for `callback` the collection
* will be sorted by each property value.
*
* If an object is provided for `callback` the created "_.where" style callback
* will return `true` for elements that have the properties of the given object,
* else `false`.
*
* @static
* @memberOf _
* @category Collections
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Array|Function|Object|string} [callback=identity] The function called
* per iteration. If a property name or object is provided it will be used
* to create a "_.pluck" or "_.where" style callback, respectively.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {Array} Returns a new array of sorted elements.
* @example
*
* _.sortBy([1, 2, 3], function(num) { return Math.sin(num); });
* // => [3, 1, 2]
*
* _.sortBy([1, 2, 3], function(num) { return this.sin(num); }, Math);
* // => [3, 1, 2]
*
* var characters = [
* { 'name': 'barney', 'age': 36 },
* { 'name': 'fred', 'age': 40 },
* { 'name': 'barney', 'age': 26 },
* { 'name': 'fred', 'age': 30 }
* ];
*
* // using "_.pluck" callback shorthand
* _.map(_.sortBy(characters, 'age'), _.values);
* // => [['barney', 26], ['fred', 30], ['barney', 36], ['fred', 40]]
*
* // sorting by multiple properties
* _.map(_.sortBy(characters, ['name', 'age']), _.values);
* // = > [['barney', 26], ['barney', 36], ['fred', 30], ['fred', 40]]
*/
function sortBy(collection, callback, thisArg) {
var index = -1,
isArr = isArray(callback),
length = collection ? collection.length : 0,
result = Array(typeof length == 'number' ? length : 0);
if (!isArr) {
callback = lodash.createCallback(callback, thisArg, 3);
}
forEach(collection, function(value, key, collection) {
var object = result[++index] = getObject();
if (isArr) {
object.criteria = map(callback, function(key) { return value[key]; });
} else {
(object.criteria = getArray())[0] = callback(value, key, collection);
}
object.index = index;
object.value = value;
});
length = result.length;
result.sort(compareAscending);
while (length--) {
var object = result[length];
result[length] = object.value;
if (!isArr) {
releaseArray(object.criteria);
}
releaseObject(object);
}
return result;
}
/**
* Converts the `collection` to an array.
*
* @static
* @memberOf _
* @category Collections
* @param {Array|Object|string} collection The collection to convert.
* @returns {Array} Returns the new converted array.
* @example
*
* (function() { return _.toArray(arguments).slice(1); })(1, 2, 3, 4);
* // => [2, 3, 4]
*/
function toArray(collection) {
if (collection && typeof collection.length == 'number') {
return (support.unindexedChars && isString(collection))
? collection.split('')
: slice(collection);
}
return values(collection);
}
/**
* Performs a deep comparison of each element in a `collection` to the given
* `properties` object, returning an array of all elements that have equivalent
* property values.
*
* @static
* @memberOf _
* @type Function
* @category Collections
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Object} props The object of property values to filter by.
* @returns {Array} Returns a new array of elements that have the given properties.
* @example
*
* var characters = [
* { 'name': 'barney', 'age': 36, 'pets': ['hoppy'] },
* { 'name': 'fred', 'age': 40, 'pets': ['baby puss', 'dino'] }
* ];
*
* _.where(characters, { 'age': 36 });
* // => [{ 'name': 'barney', 'age': 36, 'pets': ['hoppy'] }]
*
* _.where(characters, { 'pets': ['dino'] });
* // => [{ 'name': 'fred', 'age': 40, 'pets': ['baby puss', 'dino'] }]
*/
var where = filter;
/*--------------------------------------------------------------------------*/
/**
* Creates an array with all falsey values removed. The values `false`, `null`,
* `0`, `""`, `undefined`, and `NaN` are all falsey.
*
* @static
* @memberOf _
* @category Arrays
* @param {Array} array The array to compact.
* @returns {Array} Returns a new array of filtered values.
* @example
*
* _.compact([0, 1, false, 2, '', 3]);
* // => [1, 2, 3]
*/
function compact(array) {
var index = -1,
length = array ? array.length : 0,
result = [];
while (++index < length) {
var value = array[index];
if (value) {
result.push(value);
}
}
return result;
}
/**
* Creates an array excluding all values of the provided arrays using strict
* equality for comparisons, i.e. `===`.
*
* @static
* @memberOf _
* @category Arrays
* @param {Array} array The array to process.
* @param {...Array} [values] The arrays of values to exclude.
* @returns {Array} Returns a new array of filtered values.
* @example
*
* _.difference([1, 2, 3, 4, 5], [5, 2, 10]);
* // => [1, 3, 4]
*/
function difference(array) {
return baseDifference(array, baseFlatten(arguments, true, true, 1));
}
/**
* This method is like `_.find` except that it returns the index of the first
* element that passes the callback check, instead of the element itself.
*
* If a property name is provided for `callback` the created "_.pluck" style
* callback will return the property value of the given element.
*
* If an object is provided for `callback` the created "_.where" style callback
* will return `true` for elements that have the properties of the given object,
* else `false`.
*
* @static
* @memberOf _
* @category Arrays
* @param {Array} array The array to search.
* @param {Function|Object|string} [callback=identity] The function called
* per iteration. If a property name or object is provided it will be used
* to create a "_.pluck" or "_.where" style callback, respectively.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {number} Returns the index of the found element, else `-1`.
* @example
*
* var characters = [
* { 'name': 'barney', 'age': 36, 'blocked': false },
* { 'name': 'fred', 'age': 40, 'blocked': true },
* { 'name': 'pebbles', 'age': 1, 'blocked': false }
* ];
*
* _.findIndex(characters, function(chr) {
* return chr.age < 20;
* });
* // => 2
*
* // using "_.where" callback shorthand
* _.findIndex(characters, { 'age': 36 });
* // => 0
*
* // using "_.pluck" callback shorthand
* _.findIndex(characters, 'blocked');
* // => 1
*/
function findIndex(array, callback, thisArg) {
var index = -1,
length = array ? array.length : 0;
callback = lodash.createCallback(callback, thisArg, 3);
while (++index < length) {
if (callback(array[index], index, array)) {
return index;
}
}
return -1;
}
/**
* This method is like `_.findIndex` except that it iterates over elements
* of a `collection` from right to left.
*
* If a property name is provided for `callback` the created "_.pluck" style
* callback will return the property value of the given element.
*
* If an object is provided for `callback` the created "_.where" style callback
* will return `true` for elements that have the properties of the given object,
* else `false`.
*
* @static
* @memberOf _
* @category Arrays
* @param {Array} array The array to search.
* @param {Function|Object|string} [callback=identity] The function called
* per iteration. If a property name or object is provided it will be used
* to create a "_.pluck" or "_.where" style callback, respectively.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {number} Returns the index of the found element, else `-1`.
* @example
*
* var characters = [
* { 'name': 'barney', 'age': 36, 'blocked': true },
* { 'name': 'fred', 'age': 40, 'blocked': false },
* { 'name': 'pebbles', 'age': 1, 'blocked': true }
* ];
*
* _.findLastIndex(characters, function(chr) {
* return chr.age > 30;
* });
* // => 1
*
* // using "_.where" callback shorthand
* _.findLastIndex(characters, { 'age': 36 });
* // => 0
*
* // using "_.pluck" callback shorthand
* _.findLastIndex(characters, 'blocked');
* // => 2
*/
function findLastIndex(array, callback, thisArg) {
var length = array ? array.length : 0;
callback = lodash.createCallback(callback, thisArg, 3);
while (length--) {
if (callback(array[length], length, array)) {
return length;
}
}
return -1;
}
/**
* Gets the first element or first `n` elements of an array. If a callback
* is provided elements at the beginning of the array are returned as long
* as the callback returns truey. The callback is bound to `thisArg` and
* invoked with three arguments; (value, index, array).
*
* If a property name is provided for `callback` the created "_.pluck" style
* callback will return the property value of the given element.
*
* If an object is provided for `callback` the created "_.where" style callback
* will return `true` for elements that have the properties of the given object,
* else `false`.
*
* @static
* @memberOf _
* @alias head, take
* @category Arrays
* @param {Array} array The array to query.
* @param {Function|Object|number|string} [callback] The function called
* per element or the number of elements to return. If a property name or
* object is provided it will be used to create a "_.pluck" or "_.where"
* style callback, respectively.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {*} Returns the first element(s) of `array`.
* @example
*
* _.first([1, 2, 3]);
* // => 1
*
* _.first([1, 2, 3], 2);
* // => [1, 2]
*
* _.first([1, 2, 3], function(num) {
* return num < 3;
* });
* // => [1, 2]
*
* var characters = [
* { 'name': 'barney', 'blocked': true, 'employer': 'slate' },
* { 'name': 'fred', 'blocked': false, 'employer': 'slate' },
* { 'name': 'pebbles', 'blocked': true, 'employer': 'na' }
* ];
*
* // using "_.pluck" callback shorthand
* _.first(characters, 'blocked');
* // => [{ 'name': 'barney', 'blocked': true, 'employer': 'slate' }]
*
* // using "_.where" callback shorthand
* _.pluck(_.first(characters, { 'employer': 'slate' }), 'name');
* // => ['barney', 'fred']
*/
function first(array, callback, thisArg) {
var n = 0,
length = array ? array.length : 0;
if (typeof callback != 'number' && callback != null) {
var index = -1;
callback = lodash.createCallback(callback, thisArg, 3);
while (++index < length && callback(array[index], index, array)) {
n++;
}
} else {
n = callback;
if (n == null || thisArg) {
return array ? array[0] : undefined;
}
}
return slice(array, 0, nativeMin(nativeMax(0, n), length));
}
/**
* Flattens a nested array (the nesting can be to any depth). If `isShallow`
* is truey, the array will only be flattened a single level. If a callback
* is provided each element of the array is passed through the callback before
* flattening. The callback is bound to `thisArg` and invoked with three
* arguments; (value, index, array).
*
* If a property name is provided for `callback` the created "_.pluck" style
* callback will return the property value of the given element.
*
* If an object is provided for `callback` the created "_.where" style callback
* will return `true` for elements that have the properties of the given object,
* else `false`.
*
* @static
* @memberOf _
* @category Arrays
* @param {Array} array The array to flatten.
* @param {boolean} [isShallow=false] A flag to restrict flattening to a single level.
* @param {Function|Object|string} [callback=identity] The function called
* per iteration. If a property name or object is provided it will be used
* to create a "_.pluck" or "_.where" style callback, respectively.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {Array} Returns a new flattened array.
* @example
*
* _.flatten([1, [2], [3, [[4]]]]);
* // => [1, 2, 3, 4];
*
* _.flatten([1, [2], [3, [[4]]]], true);
* // => [1, 2, 3, [[4]]];
*
* var characters = [
* { 'name': 'barney', 'age': 30, 'pets': ['hoppy'] },
* { 'name': 'fred', 'age': 40, 'pets': ['baby puss', 'dino'] }
* ];
*
* // using "_.pluck" callback shorthand
* _.flatten(characters, 'pets');
* // => ['hoppy', 'baby puss', 'dino']
*/
function flatten(array, isShallow, callback, thisArg) {
// juggle arguments
if (typeof isShallow != 'boolean' && isShallow != null) {
thisArg = callback;
callback = (typeof isShallow != 'function' && thisArg && thisArg[isShallow] === array) ? null : isShallow;
isShallow = false;
}
if (callback != null) {
array = map(array, callback, thisArg);
}
return baseFlatten(array, isShallow);
}
/**
* Gets the index at which the first occurrence of `value` is found using
* strict equality for comparisons, i.e. `===`. If the array is already sorted
* providing `true` for `fromIndex` will run a faster binary search.
*
* @static
* @memberOf _
* @category Arrays
* @param {Array} array The array to search.
* @param {*} value The value to search for.
* @param {boolean|number} [fromIndex=0] The index to search from or `true`
* to perform a binary search on a sorted array.
* @returns {number} Returns the index of the matched value or `-1`.
* @example
*
* _.indexOf([1, 2, 3, 1, 2, 3], 2);
* // => 1
*
* _.indexOf([1, 2, 3, 1, 2, 3], 2, 3);
* // => 4
*
* _.indexOf([1, 1, 2, 2, 3, 3], 2, true);
* // => 2
*/
function indexOf(array, value, fromIndex) {
if (typeof fromIndex == 'number') {
var length = array ? array.length : 0;
fromIndex = (fromIndex < 0 ? nativeMax(0, length + fromIndex) : fromIndex || 0);
} else if (fromIndex) {
var index = sortedIndex(array, value);
return array[index] === value ? index : -1;
}
return baseIndexOf(array, value, fromIndex);
}
/**
* Gets all but the last element or last `n` elements of an array. If a
* callback is provided elements at the end of the array are excluded from
* the result as long as the callback returns truey. The callback is bound
* to `thisArg` and invoked with three arguments; (value, index, array).
*
* If a property name is provided for `callback` the created "_.pluck" style
* callback will return the property value of the given element.
*
* If an object is provided for `callback` the created "_.where" style callback
* will return `true` for elements that have the properties of the given object,
* else `false`.
*
* @static
* @memberOf _
* @category Arrays
* @param {Array} array The array to query.
* @param {Function|Object|number|string} [callback=1] The function called
* per element or the number of elements to exclude. If a property name or
* object is provided it will be used to create a "_.pluck" or "_.where"
* style callback, respectively.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {Array} Returns a slice of `array`.
* @example
*
* _.initial([1, 2, 3]);
* // => [1, 2]
*
* _.initial([1, 2, 3], 2);
* // => [1]
*
* _.initial([1, 2, 3], function(num) {
* return num > 1;
* });
* // => [1]
*
* var characters = [
* { 'name': 'barney', 'blocked': false, 'employer': 'slate' },
* { 'name': 'fred', 'blocked': true, 'employer': 'slate' },
* { 'name': 'pebbles', 'blocked': true, 'employer': 'na' }
* ];
*
* // using "_.pluck" callback shorthand
* _.initial(characters, 'blocked');
* // => [{ 'name': 'barney', 'blocked': false, 'employer': 'slate' }]
*
* // using "_.where" callback shorthand
* _.pluck(_.initial(characters, { 'employer': 'na' }), 'name');
* // => ['barney', 'fred']
*/
function initial(array, callback, thisArg) {
var n = 0,
length = array ? array.length : 0;
if (typeof callback != 'number' && callback != null) {
var index = length;
callback = lodash.createCallback(callback, thisArg, 3);
while (index-- && callback(array[index], index, array)) {
n++;
}
} else {
n = (callback == null || thisArg) ? 1 : callback || n;
}
return slice(array, 0, nativeMin(nativeMax(0, length - n), length));
}
/**
* Creates an array of unique values present in all provided arrays using
* strict equality for comparisons, i.e. `===`.
*
* @static
* @memberOf _
* @category Arrays
* @param {...Array} [array] The arrays to inspect.
* @returns {Array} Returns an array of shared values.
* @example
*
* _.intersection([1, 2, 3], [5, 2, 1, 4], [2, 1]);
* // => [1, 2]
*/
function intersection() {
var args = [],
argsIndex = -1,
argsLength = arguments.length,
caches = getArray(),
indexOf = getIndexOf(),
trustIndexOf = indexOf === baseIndexOf,
seen = getArray();
while (++argsIndex < argsLength) {
var value = arguments[argsIndex];
if (isArray(value) || isArguments(value)) {
args.push(value);
caches.push(trustIndexOf && value.length >= largeArraySize &&
createCache(argsIndex ? args[argsIndex] : seen));
}
}
var array = args[0],
index = -1,
length = array ? array.length : 0,
result = [];
outer:
while (++index < length) {
var cache = caches[0];
value = array[index];
if ((cache ? cacheIndexOf(cache, value) : indexOf(seen, value)) < 0) {
argsIndex = argsLength;
(cache || seen).push(value);
while (--argsIndex) {
cache = caches[argsIndex];
if ((cache ? cacheIndexOf(cache, value) : indexOf(args[argsIndex], value)) < 0) {
continue outer;
}
}
result.push(value);
}
}
while (argsLength--) {
cache = caches[argsLength];
if (cache) {
releaseObject(cache);
}
}
releaseArray(caches);
releaseArray(seen);
return result;
}
/**
* Gets the last element or last `n` elements of an array. If a callback is
* provided elements at the end of the array are returned as long as the
* callback returns truey. The callback is bound to `thisArg` and invoked
* with three arguments; (value, index, array).
*
* If a property name is provided for `callback` the created "_.pluck" style
* callback will return the property value of the given element.
*
* If an object is provided for `callback` the created "_.where" style callback
* will return `true` for elements that have the properties of the given object,
* else `false`.
*
* @static
* @memberOf _
* @category Arrays
* @param {Array} array The array to query.
* @param {Function|Object|number|string} [callback] The function called
* per element or the number of elements to return. If a property name or
* object is provided it will be used to create a "_.pluck" or "_.where"
* style callback, respectively.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {*} Returns the last element(s) of `array`.
* @example
*
* _.last([1, 2, 3]);
* // => 3
*
* _.last([1, 2, 3], 2);
* // => [2, 3]
*
* _.last([1, 2, 3], function(num) {
* return num > 1;
* });
* // => [2, 3]
*
* var characters = [
* { 'name': 'barney', 'blocked': false, 'employer': 'slate' },
* { 'name': 'fred', 'blocked': true, 'employer': 'slate' },
* { 'name': 'pebbles', 'blocked': true, 'employer': 'na' }
* ];
*
* // using "_.pluck" callback shorthand
* _.pluck(_.last(characters, 'blocked'), 'name');
* // => ['fred', 'pebbles']
*
* // using "_.where" callback shorthand
* _.last(characters, { 'employer': 'na' });
* // => [{ 'name': 'pebbles', 'blocked': true, 'employer': 'na' }]
*/
function last(array, callback, thisArg) {
var n = 0,
length = array ? array.length : 0;
if (typeof callback != 'number' && callback != null) {
var index = length;
callback = lodash.createCallback(callback, thisArg, 3);
while (index-- && callback(array[index], index, array)) {
n++;
}
} else {
n = callback;
if (n == null || thisArg) {
return array ? array[length - 1] : undefined;
}
}
return slice(array, nativeMax(0, length - n));
}
/**
* Gets the index at which the last occurrence of `value` is found using strict
* equality for comparisons, i.e. `===`. If `fromIndex` is negative, it is used
* as the offset from the end of the collection.
*
* If a property name is provided for `callback` the created "_.pluck" style
* callback will return the property value of the given element.
*
* If an object is provided for `callback` the created "_.where" style callback
* will return `true` for elements that have the properties of the given object,
* else `false`.
*
* @static
* @memberOf _
* @category Arrays
* @param {Array} array The array to search.
* @param {*} value The value to search for.
* @param {number} [fromIndex=array.length-1] The index to search from.
* @returns {number} Returns the index of the matched value or `-1`.
* @example
*
* _.lastIndexOf([1, 2, 3, 1, 2, 3], 2);
* // => 4
*
* _.lastIndexOf([1, 2, 3, 1, 2, 3], 2, 3);
* // => 1
*/
function lastIndexOf(array, value, fromIndex) {
var index = array ? array.length : 0;
if (typeof fromIndex == 'number') {
index = (fromIndex < 0 ? nativeMax(0, index + fromIndex) : nativeMin(fromIndex, index - 1)) + 1;
}
while (index--) {
if (array[index] === value) {
return index;
}
}
return -1;
}
/**
* Removes all provided values from the given array using strict equality for
* comparisons, i.e. `===`.
*
* @static
* @memberOf _
* @category Arrays
* @param {Array} array The array to modify.
* @param {...*} [value] The values to remove.
* @returns {Array} Returns `array`.
* @example
*
* var array = [1, 2, 3, 1, 2, 3];
* _.pull(array, 2, 3);
* console.log(array);
* // => [1, 1]
*/
function pull(array) {
var args = arguments,
argsIndex = 0,
argsLength = args.length,
length = array ? array.length : 0;
while (++argsIndex < argsLength) {
var index = -1,
value = args[argsIndex];
while (++index < length) {
if (array[index] === value) {
splice.call(array, index--, 1);
length--;
}
}
}
return array;
}
/**
* Creates an array of numbers (positive and/or negative) progressing from
* `start` up to but not including `end`. If `start` is less than `stop` a
* zero-length range is created unless a negative `step` is specified.
*
* @static
* @memberOf _
* @category Arrays
* @param {number} [start=0] The start of the range.
* @param {number} end The end of the range.
* @param {number} [step=1] The value to increment or decrement by.
* @returns {Array} Returns a new range array.
* @example
*
* _.range(4);
* // => [0, 1, 2, 3]
*
* _.range(1, 5);
* // => [1, 2, 3, 4]
*
* _.range(0, 20, 5);
* // => [0, 5, 10, 15]
*
* _.range(0, -4, -1);
* // => [0, -1, -2, -3]
*
* _.range(1, 4, 0);
* // => [1, 1, 1]
*
* _.range(0);
* // => []
*/
function range(start, end, step) {
start = +start || 0;
step = typeof step == 'number' ? step : (+step || 1);
if (end == null) {
end = start;
start = 0;
}
// use `Array(length)` so engines like Chakra and V8 avoid slower modes
// http://youtu.be/XAqIpGU8ZZk#t=17m25s
var index = -1,
length = nativeMax(0, ceil((end - start) / (step || 1))),
result = Array(length);
while (++index < length) {
result[index] = start;
start += step;
}
return result;
}
/**
* Removes all elements from an array that the callback returns truey for
* and returns an array of removed elements. The callback is bound to `thisArg`
* and invoked with three arguments; (value, index, array).
*
* If a property name is provided for `callback` the created "_.pluck" style
* callback will return the property value of the given element.
*
* If an object is provided for `callback` the created "_.where" style callback
* will return `true` for elements that have the properties of the given object,
* else `false`.
*
* @static
* @memberOf _
* @category Arrays
* @param {Array} array The array to modify.
* @param {Function|Object|string} [callback=identity] The function called
* per iteration. If a property name or object is provided it will be used
* to create a "_.pluck" or "_.where" style callback, respectively.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {Array} Returns a new array of removed elements.
* @example
*
* var array = [1, 2, 3, 4, 5, 6];
* var evens = _.remove(array, function(num) { return num % 2 == 0; });
*
* console.log(array);
* // => [1, 3, 5]
*
* console.log(evens);
* // => [2, 4, 6]
*/
function remove(array, callback, thisArg) {
var index = -1,
length = array ? array.length : 0,
result = [];
callback = lodash.createCallback(callback, thisArg, 3);
while (++index < length) {
var value = array[index];
if (callback(value, index, array)) {
result.push(value);
splice.call(array, index--, 1);
length--;
}
}
return result;
}
/**
* The opposite of `_.initial` this method gets all but the first element or
* first `n` elements of an array. If a callback function is provided elements
* at the beginning of the array are excluded from the result as long as the
* callback returns truey. The callback is bound to `thisArg` and invoked
* with three arguments; (value, index, array).
*
* If a property name is provided for `callback` the created "_.pluck" style
* callback will return the property value of the given element.
*
* If an object is provided for `callback` the created "_.where" style callback
* will return `true` for elements that have the properties of the given object,
* else `false`.
*
* @static
* @memberOf _
* @alias drop, tail
* @category Arrays
* @param {Array} array The array to query.
* @param {Function|Object|number|string} [callback=1] The function called
* per element or the number of elements to exclude. If a property name or
* object is provided it will be used to create a "_.pluck" or "_.where"
* style callback, respectively.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {Array} Returns a slice of `array`.
* @example
*
* _.rest([1, 2, 3]);
* // => [2, 3]
*
* _.rest([1, 2, 3], 2);
* // => [3]
*
* _.rest([1, 2, 3], function(num) {
* return num < 3;
* });
* // => [3]
*
* var characters = [
* { 'name': 'barney', 'blocked': true, 'employer': 'slate' },
* { 'name': 'fred', 'blocked': false, 'employer': 'slate' },
* { 'name': 'pebbles', 'blocked': true, 'employer': 'na' }
* ];
*
* // using "_.pluck" callback shorthand
* _.pluck(_.rest(characters, 'blocked'), 'name');
* // => ['fred', 'pebbles']
*
* // using "_.where" callback shorthand
* _.rest(characters, { 'employer': 'slate' });
* // => [{ 'name': 'pebbles', 'blocked': true, 'employer': 'na' }]
*/
function rest(array, callback, thisArg) {
if (typeof callback != 'number' && callback != null) {
var n = 0,
index = -1,
length = array ? array.length : 0;
callback = lodash.createCallback(callback, thisArg, 3);
while (++index < length && callback(array[index], index, array)) {
n++;
}
} else {
n = (callback == null || thisArg) ? 1 : nativeMax(0, callback);
}
return slice(array, n);
}
/**
* Uses a binary search to determine the smallest index at which a value
* should be inserted into a given sorted array in order to maintain the sort
* order of the array. If a callback is provided it will be executed for
* `value` and each element of `array` to compute their sort ranking. The
* callback is bound to `thisArg` and invoked with one argument; (value).
*
* If a property name is provided for `callback` the created "_.pluck" style
* callback will return the property value of the given element.
*
* If an object is provided for `callback` the created "_.where" style callback
* will return `true` for elements that have the properties of the given object,
* else `false`.
*
* @static
* @memberOf _
* @category Arrays
* @param {Array} array The array to inspect.
* @param {*} value The value to evaluate.
* @param {Function|Object|string} [callback=identity] The function called
* per iteration. If a property name or object is provided it will be used
* to create a "_.pluck" or "_.where" style callback, respectively.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {number} Returns the index at which `value` should be inserted
* into `array`.
* @example
*
* _.sortedIndex([20, 30, 50], 40);
* // => 2
*
* // using "_.pluck" callback shorthand
* _.sortedIndex([{ 'x': 20 }, { 'x': 30 }, { 'x': 50 }], { 'x': 40 }, 'x');
* // => 2
*
* var dict = {
* 'wordToNumber': { 'twenty': 20, 'thirty': 30, 'fourty': 40, 'fifty': 50 }
* };
*
* _.sortedIndex(['twenty', 'thirty', 'fifty'], 'fourty', function(word) {
* return dict.wordToNumber[word];
* });
* // => 2
*
* _.sortedIndex(['twenty', 'thirty', 'fifty'], 'fourty', function(word) {
* return this.wordToNumber[word];
* }, dict);
* // => 2
*/
function sortedIndex(array, value, callback, thisArg) {
var low = 0,
high = array ? array.length : low;
// explicitly reference `identity` for better inlining in Firefox
callback = callback ? lodash.createCallback(callback, thisArg, 1) : identity;
value = callback(value);
while (low < high) {
var mid = (low + high) >>> 1;
(callback(array[mid]) < value)
? low = mid + 1
: high = mid;
}
return low;
}
/**
* Creates an array of unique values, in order, of the provided arrays using
* strict equality for comparisons, i.e. `===`.
*
* @static
* @memberOf _
* @category Arrays
* @param {...Array} [array] The arrays to inspect.
* @returns {Array} Returns an array of combined values.
* @example
*
* _.union([1, 2, 3], [5, 2, 1, 4], [2, 1]);
* // => [1, 2, 3, 5, 4]
*/
function union() {
return baseUniq(baseFlatten(arguments, true, true));
}
/**
* Creates a duplicate-value-free version of an array using strict equality
* for comparisons, i.e. `===`. If the array is sorted, providing
* `true` for `isSorted` will use a faster algorithm. If a callback is provided
* each element of `array` is passed through the callback before uniqueness
* is computed. The callback is bound to `thisArg` and invoked with three
* arguments; (value, index, array).
*
* If a property name is provided for `callback` the created "_.pluck" style
* callback will return the property value of the given element.
*
* If an object is provided for `callback` the created "_.where" style callback
* will return `true` for elements that have the properties of the given object,
* else `false`.
*
* @static
* @memberOf _
* @alias unique
* @category Arrays
* @param {Array} array The array to process.
* @param {boolean} [isSorted=false] A flag to indicate that `array` is sorted.
* @param {Function|Object|string} [callback=identity] The function called
* per iteration. If a property name or object is provided it will be used
* to create a "_.pluck" or "_.where" style callback, respectively.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {Array} Returns a duplicate-value-free array.
* @example
*
* _.uniq([1, 2, 1, 3, 1]);
* // => [1, 2, 3]
*
* _.uniq([1, 1, 2, 2, 3], true);
* // => [1, 2, 3]
*
* _.uniq(['A', 'b', 'C', 'a', 'B', 'c'], function(letter) { return letter.toLowerCase(); });
* // => ['A', 'b', 'C']
*
* _.uniq([1, 2.5, 3, 1.5, 2, 3.5], function(num) { return this.floor(num); }, Math);
* // => [1, 2.5, 3]
*
* // using "_.pluck" callback shorthand
* _.uniq([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x');
* // => [{ 'x': 1 }, { 'x': 2 }]
*/
function uniq(array, isSorted, callback, thisArg) {
// juggle arguments
if (typeof isSorted != 'boolean' && isSorted != null) {
thisArg = callback;
callback = (typeof isSorted != 'function' && thisArg && thisArg[isSorted] === array) ? null : isSorted;
isSorted = false;
}
if (callback != null) {
callback = lodash.createCallback(callback, thisArg, 3);
}
return baseUniq(array, isSorted, callback);
}
/**
* Creates an array excluding all provided values using strict equality for
* comparisons, i.e. `===`.
*
* @static
* @memberOf _
* @category Arrays
* @param {Array} array The array to filter.
* @param {...*} [value] The values to exclude.
* @returns {Array} Returns a new array of filtered values.
* @example
*
* _.without([1, 2, 1, 0, 3, 1, 4], 0, 1);
* // => [2, 3, 4]
*/
function without(array) {
return baseDifference(array, slice(arguments, 1));
}
/**
* Creates an array that is the symmetric difference of the provided arrays.
* See http://en.wikipedia.org/wiki/Symmetric_difference.
*
* @static
* @memberOf _
* @category Arrays
* @param {...Array} [array] The arrays to inspect.
* @returns {Array} Returns an array of values.
* @example
*
* _.xor([1, 2, 3], [5, 2, 1, 4]);
* // => [3, 5, 4]
*
* _.xor([1, 2, 5], [2, 3, 5], [3, 4, 5]);
* // => [1, 4, 5]
*/
function xor() {
var index = -1,
length = arguments.length;
while (++index < length) {
var array = arguments[index];
if (isArray(array) || isArguments(array)) {
var result = result
? baseUniq(baseDifference(result, array).concat(baseDifference(array, result)))
: array;
}
}
return result || [];
}
/**
* Creates an array of grouped elements, the first of which contains the first
* elements of the given arrays, the second of which contains the second
* elements of the given arrays, and so on.
*
* @static
* @memberOf _
* @alias unzip
* @category Arrays
* @param {...Array} [array] Arrays to process.
* @returns {Array} Returns a new array of grouped elements.
* @example
*
* _.zip(['fred', 'barney'], [30, 40], [true, false]);
* // => [['fred', 30, true], ['barney', 40, false]]
*/
function zip() {
var array = arguments.length > 1 ? arguments : arguments[0],
index = -1,
length = array ? max(pluck(array, 'length')) : 0,
result = Array(length < 0 ? 0 : length);
while (++index < length) {
result[index] = pluck(array, index);
}
return result;
}
/**
* Creates an object composed from arrays of `keys` and `values`. Provide
* either a single two dimensional array, i.e. `[[key1, value1], [key2, value2]]`
* or two arrays, one of `keys` and one of corresponding `values`.
*
* @static
* @memberOf _
* @alias object
* @category Arrays
* @param {Array} keys The array of keys.
* @param {Array} [values=[]] The array of values.
* @returns {Object} Returns an object composed of the given keys and
* corresponding values.
* @example
*
* _.zipObject(['fred', 'barney'], [30, 40]);
* // => { 'fred': 30, 'barney': 40 }
*/
function zipObject(keys, values) {
var index = -1,
length = keys ? keys.length : 0,
result = {};
if (!values && length && !isArray(keys[0])) {
values = [];
}
while (++index < length) {
var key = keys[index];
if (values) {
result[key] = values[index];
} else if (key) {
result[key[0]] = key[1];
}
}
return result;
}
/*--------------------------------------------------------------------------*/
/**
* Creates a function that executes `func`, with the `this` binding and
* arguments of the created function, only after being called `n` times.
*
* @static
* @memberOf _
* @category Functions
* @param {number} n The number of times the function must be called before
* `func` is executed.
* @param {Function} func The function to restrict.
* @returns {Function} Returns the new restricted function.
* @example
*
* var saves = ['profile', 'settings'];
*
* var done = _.after(saves.length, function() {
* console.log('Done saving!');
* });
*
* _.forEach(saves, function(type) {
* asyncSave({ 'type': type, 'complete': done });
* });
* // => logs 'Done saving!', after all saves have completed
*/
function after(n, func) {
if (!isFunction(func)) {
throw new TypeError;
}
return function() {
if (--n < 1) {
return func.apply(this, arguments);
}
};
}
/**
* Creates a function that, when called, invokes `func` with the `this`
* binding of `thisArg` and prepends any additional `bind` arguments to those
* provided to the bound function.
*
* @static
* @memberOf _
* @category Functions
* @param {Function} func The function to bind.
* @param {*} [thisArg] The `this` binding of `func`.
* @param {...*} [arg] Arguments to be partially applied.
* @returns {Function} Returns the new bound function.
* @example
*
* var func = function(greeting) {
* return greeting + ' ' + this.name;
* };
*
* func = _.bind(func, { 'name': 'fred' }, 'hi');
* func();
* // => 'hi fred'
*/
function bind(func, thisArg) {
return arguments.length > 2
? createWrapper(func, 17, slice(arguments, 2), null, thisArg)
: createWrapper(func, 1, null, null, thisArg);
}
/**
* Binds methods of an object to the object itself, overwriting the existing
* method. Method names may be specified as individual arguments or as arrays
* of method names. If no method names are provided all the function properties
* of `object` will be bound.
*
* @static
* @memberOf _
* @category Functions
* @param {Object} object The object to bind and assign the bound methods to.
* @param {...string} [methodName] The object method names to
* bind, specified as individual method names or arrays of method names.
* @returns {Object} Returns `object`.
* @example
*
* var view = {
* 'label': 'docs',
* 'onClick': function() { console.log('clicked ' + this.label); }
* };
*
* _.bindAll(view);
* jQuery('#docs').on('click', view.onClick);
* // => logs 'clicked docs', when the button is clicked
*/
function bindAll(object) {
var funcs = arguments.length > 1 ? baseFlatten(arguments, true, false, 1) : functions(object),
index = -1,
length = funcs.length;
while (++index < length) {
var key = funcs[index];
object[key] = createWrapper(object[key], 1, null, null, object);
}
return object;
}
/**
* Creates a function that, when called, invokes the method at `object[key]`
* and prepends any additional `bindKey` arguments to those provided to the bound
* function. This method differs from `_.bind` by allowing bound functions to
* reference methods that will be redefined or don't yet exist.
* See http://michaux.ca/articles/lazy-function-definition-pattern.
*
* @static
* @memberOf _
* @category Functions
* @param {Object} object The object the method belongs to.
* @param {string} key The key of the method.
* @param {...*} [arg] Arguments to be partially applied.
* @returns {Function} Returns the new bound function.
* @example
*
* var object = {
* 'name': 'fred',
* 'greet': function(greeting) {
* return greeting + ' ' + this.name;
* }
* };
*
* var func = _.bindKey(object, 'greet', 'hi');
* func();
* // => 'hi fred'
*
* object.greet = function(greeting) {
* return greeting + 'ya ' + this.name + '!';
* };
*
* func();
* // => 'hiya fred!'
*/
function bindKey(object, key) {
return arguments.length > 2
? createWrapper(key, 19, slice(arguments, 2), null, object)
: createWrapper(key, 3, null, null, object);
}
/**
* Creates a function that is the composition of the provided functions,
* where each function consumes the return value of the function that follows.
* For example, composing the functions `f()`, `g()`, and `h()` produces `f(g(h()))`.
* Each function is executed with the `this` binding of the composed function.
*
* @static
* @memberOf _
* @category Functions
* @param {...Function} [func] Functions to compose.
* @returns {Function} Returns the new composed function.
* @example
*
* var realNameMap = {
* 'pebbles': 'penelope'
* };
*
* var format = function(name) {
* name = realNameMap[name.toLowerCase()] || name;
* return name.charAt(0).toUpperCase() + name.slice(1).toLowerCase();
* };
*
* var greet = function(formatted) {
* return 'Hiya ' + formatted + '!';
* };
*
* var welcome = _.compose(greet, format);
* welcome('pebbles');
* // => 'Hiya Penelope!'
*/
function compose() {
var funcs = arguments,
length = funcs.length;
while (length--) {
if (!isFunction(funcs[length])) {
throw new TypeError;
}
}
return function() {
var args = arguments,
length = funcs.length;
while (length--) {
args = [funcs[length].apply(this, args)];
}
return args[0];
};
}
/**
* Creates a function which accepts one or more arguments of `func` that when
* invoked either executes `func` returning its result, if all `func` arguments
* have been provided, or returns a function that accepts one or more of the
* remaining `func` arguments, and so on. The arity of `func` can be specified
* if `func.length` is not sufficient.
*
* @static
* @memberOf _
* @category Functions
* @param {Function} func The function to curry.
* @param {number} [arity=func.length] The arity of `func`.
* @returns {Function} Returns the new curried function.
* @example
*
* var curried = _.curry(function(a, b, c) {
* console.log(a + b + c);
* });
*
* curried(1)(2)(3);
* // => 6
*
* curried(1, 2)(3);
* // => 6
*
* curried(1, 2, 3);
* // => 6
*/
function curry(func, arity) {
arity = typeof arity == 'number' ? arity : (+arity || func.length);
return createWrapper(func, 4, null, null, null, arity);
}
/**
* Creates a function that will delay the execution of `func` until after
* `wait` milliseconds have elapsed since the last time it was invoked.
* Provide an options object to indicate that `func` should be invoked on
* the leading and/or trailing edge of the `wait` timeout. Subsequent calls
* to the debounced function will return the result of the last `func` call.
*
* Note: If `leading` and `trailing` options are `true` `func` will be called
* on the trailing edge of the timeout only if the the debounced function is
* invoked more than once during the `wait` timeout.
*
* @static
* @memberOf _
* @category Functions
* @param {Function} func The function to debounce.
* @param {number} wait The number of milliseconds to delay.
* @param {Object} [options] The options object.
* @param {boolean} [options.leading=false] Specify execution on the leading edge of the timeout.
* @param {number} [options.maxWait] The maximum time `func` is allowed to be delayed before it's called.
* @param {boolean} [options.trailing=true] Specify execution on the trailing edge of the timeout.
* @returns {Function} Returns the new debounced function.
* @example
*
* // avoid costly calculations while the window size is in flux
* var lazyLayout = _.debounce(calculateLayout, 150);
* jQuery(window).on('resize', lazyLayout);
*
* // execute `sendMail` when the click event is fired, debouncing subsequent calls
* jQuery('#postbox').on('click', _.debounce(sendMail, 300, {
* 'leading': true,
* 'trailing': false
* });
*
* // ensure `batchLog` is executed once after 1 second of debounced calls
* var source = new EventSource('/stream');
* source.addEventListener('message', _.debounce(batchLog, 250, {
* 'maxWait': 1000
* }, false);
*/
function debounce(func, wait, options) {
var args,
maxTimeoutId,
result,
stamp,
thisArg,
timeoutId,
trailingCall,
lastCalled = 0,
maxWait = false,
trailing = true;
if (!isFunction(func)) {
throw new TypeError;
}
wait = nativeMax(0, wait) || 0;
if (options === true) {
var leading = true;
trailing = false;
} else if (isObject(options)) {
leading = options.leading;
maxWait = 'maxWait' in options && (nativeMax(wait, options.maxWait) || 0);
trailing = 'trailing' in options ? options.trailing : trailing;
}
var delayed = function() {
var remaining = wait - (now() - stamp);
if (remaining <= 0) {
if (maxTimeoutId) {
clearTimeout(maxTimeoutId);
}
var isCalled = trailingCall;
maxTimeoutId = timeoutId = trailingCall = undefined;
if (isCalled) {
lastCalled = now();
result = func.apply(thisArg, args);
if (!timeoutId && !maxTimeoutId) {
args = thisArg = null;
}
}
} else {
timeoutId = setTimeout(delayed, remaining);
}
};
var maxDelayed = function() {
if (timeoutId) {
clearTimeout(timeoutId);
}
maxTimeoutId = timeoutId = trailingCall = undefined;
if (trailing || (maxWait !== wait)) {
lastCalled = now();
result = func.apply(thisArg, args);
if (!timeoutId && !maxTimeoutId) {
args = thisArg = null;
}
}
};
return function() {
args = arguments;
stamp = now();
thisArg = this;
trailingCall = trailing && (timeoutId || !leading);
if (maxWait === false) {
var leadingCall = leading && !timeoutId;
} else {
if (!maxTimeoutId && !leading) {
lastCalled = stamp;
}
var remaining = maxWait - (stamp - lastCalled),
isCalled = remaining <= 0;
if (isCalled) {
if (maxTimeoutId) {
maxTimeoutId = clearTimeout(maxTimeoutId);
}
lastCalled = stamp;
result = func.apply(thisArg, args);
}
else if (!maxTimeoutId) {
maxTimeoutId = setTimeout(maxDelayed, remaining);
}
}
if (isCalled && timeoutId) {
timeoutId = clearTimeout(timeoutId);
}
else if (!timeoutId && wait !== maxWait) {
timeoutId = setTimeout(delayed, wait);
}
if (leadingCall) {
isCalled = true;
result = func.apply(thisArg, args);
}
if (isCalled && !timeoutId && !maxTimeoutId) {
args = thisArg = null;
}
return result;
};
}
/**
* Defers executing the `func` function until the current call stack has cleared.
* Additional arguments will be provided to `func` when it is invoked.
*
* @static
* @memberOf _
* @category Functions
* @param {Function} func The function to defer.
* @param {...*} [arg] Arguments to invoke the function with.
* @returns {number} Returns the timer id.
* @example
*
* _.defer(function(text) { console.log(text); }, 'deferred');
* // logs 'deferred' after one or more milliseconds
*/
function defer(func) {
if (!isFunction(func)) {
throw new TypeError;
}
var args = slice(arguments, 1);
return setTimeout(function() { func.apply(undefined, args); }, 1);
}
/**
* Executes the `func` function after `wait` milliseconds. Additional arguments
* will be provided to `func` when it is invoked.
*
* @static
* @memberOf _
* @category Functions
* @param {Function} func The function to delay.
* @param {number} wait The number of milliseconds to delay execution.
* @param {...*} [arg] Arguments to invoke the function with.
* @returns {number} Returns the timer id.
* @example
*
* _.delay(function(text) { console.log(text); }, 1000, 'later');
* // => logs 'later' after one second
*/
function delay(func, wait) {
if (!isFunction(func)) {
throw new TypeError;
}
var args = slice(arguments, 2);
return setTimeout(function() { func.apply(undefined, args); }, wait);
}
/**
* Creates a function that memoizes the result of `func`. If `resolver` is
* provided it will be used to determine the cache key for storing the result
* based on the arguments provided to the memoized function. By default, the
* first argument provided to the memoized function is used as the cache key.
* The `func` is executed with the `this` binding of the memoized function.
* The result cache is exposed as the `cache` property on the memoized function.
*
* @static
* @memberOf _
* @category Functions
* @param {Function} func The function to have its output memoized.
* @param {Function} [resolver] A function used to resolve the cache key.
* @returns {Function} Returns the new memoizing function.
* @example
*
* var fibonacci = _.memoize(function(n) {
* return n < 2 ? n : fibonacci(n - 1) + fibonacci(n - 2);
* });
*
* fibonacci(9)
* // => 34
*
* var data = {
* 'fred': { 'name': 'fred', 'age': 40 },
* 'pebbles': { 'name': 'pebbles', 'age': 1 }
* };
*
* // modifying the result cache
* var get = _.memoize(function(name) { return data[name]; }, _.identity);
* get('pebbles');
* // => { 'name': 'pebbles', 'age': 1 }
*
* get.cache.pebbles.name = 'penelope';
* get('pebbles');
* // => { 'name': 'penelope', 'age': 1 }
*/
function memoize(func, resolver) {
if (!isFunction(func)) {
throw new TypeError;
}
var memoized = function() {
var cache = memoized.cache,
key = resolver ? resolver.apply(this, arguments) : keyPrefix + arguments[0];
return hasOwnProperty.call(cache, key)
? cache[key]
: (cache[key] = func.apply(this, arguments));
}
memoized.cache = {};
return memoized;
}
/**
* Creates a function that is restricted to execute `func` once. Repeat calls to
* the function will return the value of the first call. The `func` is executed
* with the `this` binding of the created function.
*
* @static
* @memberOf _
* @category Functions
* @param {Function} func The function to restrict.
* @returns {Function} Returns the new restricted function.
* @example
*
* var initialize = _.once(createApplication);
* initialize();
* initialize();
* // `initialize` executes `createApplication` once
*/
function once(func) {
var ran,
result;
if (!isFunction(func)) {
throw new TypeError;
}
return function() {
if (ran) {
return result;
}
ran = true;
result = func.apply(this, arguments);
// clear the `func` variable so the function may be garbage collected
func = null;
return result;
};
}
/**
* Creates a function that, when called, invokes `func` with any additional
* `partial` arguments prepended to those provided to the new function. This
* method is similar to `_.bind` except it does **not** alter the `this` binding.
*
* @static
* @memberOf _
* @category Functions
* @param {Function} func The function to partially apply arguments to.
* @param {...*} [arg] Arguments to be partially applied.
* @returns {Function} Returns the new partially applied function.
* @example
*
* var greet = function(greeting, name) { return greeting + ' ' + name; };
* var hi = _.partial(greet, 'hi');
* hi('fred');
* // => 'hi fred'
*/
function partial(func) {
return createWrapper(func, 16, slice(arguments, 1));
}
/**
* This method is like `_.partial` except that `partial` arguments are
* appended to those provided to the new function.
*
* @static
* @memberOf _
* @category Functions
* @param {Function} func The function to partially apply arguments to.
* @param {...*} [arg] Arguments to be partially applied.
* @returns {Function} Returns the new partially applied function.
* @example
*
* var defaultsDeep = _.partialRight(_.merge, _.defaults);
*
* var options = {
* 'variable': 'data',
* 'imports': { 'jq': $ }
* };
*
* defaultsDeep(options, _.templateSettings);
*
* options.variable
* // => 'data'
*
* options.imports
* // => { '_': _, 'jq': $ }
*/
function partialRight(func) {
return createWrapper(func, 32, null, slice(arguments, 1));
}
/**
* Creates a function that, when executed, will only call the `func` function
* at most once per every `wait` milliseconds. Provide an options object to
* indicate that `func` should be invoked on the leading and/or trailing edge
* of the `wait` timeout. Subsequent calls to the throttled function will
* return the result of the last `func` call.
*
* Note: If `leading` and `trailing` options are `true` `func` will be called
* on the trailing edge of the timeout only if the the throttled function is
* invoked more than once during the `wait` timeout.
*
* @static
* @memberOf _
* @category Functions
* @param {Function} func The function to throttle.
* @param {number} wait The number of milliseconds to throttle executions to.
* @param {Object} [options] The options object.
* @param {boolean} [options.leading=true] Specify execution on the leading edge of the timeout.
* @param {boolean} [options.trailing=true] Specify execution on the trailing edge of the timeout.
* @returns {Function} Returns the new throttled function.
* @example
*
* // avoid excessively updating the position while scrolling
* var throttled = _.throttle(updatePosition, 100);
* jQuery(window).on('scroll', throttled);
*
* // execute `renewToken` when the click event is fired, but not more than once every 5 minutes
* jQuery('.interactive').on('click', _.throttle(renewToken, 300000, {
* 'trailing': false
* }));
*/
function throttle(func, wait, options) {
var leading = true,
trailing = true;
if (!isFunction(func)) {
throw new TypeError;
}
if (options === false) {
leading = false;
} else if (isObject(options)) {
leading = 'leading' in options ? options.leading : leading;
trailing = 'trailing' in options ? options.trailing : trailing;
}
debounceOptions.leading = leading;
debounceOptions.maxWait = wait;
debounceOptions.trailing = trailing;
return debounce(func, wait, debounceOptions);
}
/**
* Creates a function that provides `value` to the wrapper function as its
* first argument. Additional arguments provided to the function are appended
* to those provided to the wrapper function. The wrapper is executed with
* the `this` binding of the created function.
*
* @static
* @memberOf _
* @category Functions
* @param {*} value The value to wrap.
* @param {Function} wrapper The wrapper function.
* @returns {Function} Returns the new function.
* @example
*
* var p = _.wrap(_.escape, function(func, text) {
* return '<p>' + func(text) + '</p>';
* });
*
* p('Fred, Wilma, & Pebbles');
* // => '<p>Fred, Wilma, & Pebbles</p>'
*/
function wrap(value, wrapper) {
return createWrapper(wrapper, 16, [value]);
}
/*--------------------------------------------------------------------------*/
/**
* Creates a function that returns `value`.
*
* @static
* @memberOf _
* @category Utilities
* @param {*} value The value to return from the new function.
* @returns {Function} Returns the new function.
* @example
*
* var object = { 'name': 'fred' };
* var getter = _.constant(object);
* getter() === object;
* // => true
*/
function constant(value) {
return function() {
return value;
};
}
/**
* Produces a callback bound to an optional `thisArg`. If `func` is a property
* name the created callback will return the property value for a given element.
* If `func` is an object the created callback will return `true` for elements
* that contain the equivalent object properties, otherwise it will return `false`.
*
* @static
* @memberOf _
* @category Utilities
* @param {*} [func=identity] The value to convert to a callback.
* @param {*} [thisArg] The `this` binding of the created callback.
* @param {number} [argCount] The number of arguments the callback accepts.
* @returns {Function} Returns a callback function.
* @example
*
* var characters = [
* { 'name': 'barney', 'age': 36 },
* { 'name': 'fred', 'age': 40 }
* ];
*
* // wrap to create custom callback shorthands
* _.createCallback = _.wrap(_.createCallback, function(func, callback, thisArg) {
* var match = /^(.+?)__([gl]t)(.+)$/.exec(callback);
* return !match ? func(callback, thisArg) : function(object) {
* return match[2] == 'gt' ? object[match[1]] > match[3] : object[match[1]] < match[3];
* };
* });
*
* _.filter(characters, 'age__gt38');
* // => [{ 'name': 'fred', 'age': 40 }]
*/
function createCallback(func, thisArg, argCount) {
var type = typeof func;
if (func == null || type == 'function') {
return baseCreateCallback(func, thisArg, argCount);
}
// handle "_.pluck" style callback shorthands
if (type != 'object') {
return property(func);
}
var props = keys(func),
key = props[0],
a = func[key];
// handle "_.where" style callback shorthands
if (props.length == 1 && a === a && !isObject(a)) {
// fast path the common case of providing an object with a single
// property containing a primitive value
return function(object) {
var b = object[key];
return a === b && (a !== 0 || (1 / a == 1 / b));
};
}
return function(object) {
var length = props.length,
result = false;
while (length--) {
if (!(result = baseIsEqual(object[props[length]], func[props[length]], null, true))) {
break;
}
}
return result;
};
}
/**
* Converts the characters `&`, `<`, `>`, `"`, and `'` in `string` to their
* corresponding HTML entities.
*
* @static
* @memberOf _
* @category Utilities
* @param {string} string The string to escape.
* @returns {string} Returns the escaped string.
* @example
*
* _.escape('Fred, Wilma, & Pebbles');
* // => 'Fred, Wilma, & Pebbles'
*/
function escape(string) {
return string == null ? '' : String(string).replace(reUnescapedHtml, escapeHtmlChar);
}
/**
* This method returns the first argument provided to it.
*
* @static
* @memberOf _
* @category Utilities
* @param {*} value Any value.
* @returns {*} Returns `value`.
* @example
*
* var object = { 'name': 'fred' };
* _.identity(object) === object;
* // => true
*/
function identity(value) {
return value;
}
/**
* Adds function properties of a source object to the destination object.
* If `object` is a function methods will be added to its prototype as well.
*
* @static
* @memberOf _
* @category Utilities
* @param {Function|Object} [object=lodash] object The destination object.
* @param {Object} source The object of functions to add.
* @param {Object} [options] The options object.
* @param {boolean} [options.chain=true] Specify whether the functions added are chainable.
* @example
*
* function capitalize(string) {
* return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase();
* }
*
* _.mixin({ 'capitalize': capitalize });
* _.capitalize('fred');
* // => 'Fred'
*
* _('fred').capitalize().value();
* // => 'Fred'
*
* _.mixin({ 'capitalize': capitalize }, { 'chain': false });
* _('fred').capitalize();
* // => 'Fred'
*/
function mixin(object, source, options) {
var chain = true,
methodNames = source && functions(source);
if (!source || (!options && !methodNames.length)) {
if (options == null) {
options = source;
}
ctor = lodashWrapper;
source = object;
object = lodash;
methodNames = functions(source);
}
if (options === false) {
chain = false;
} else if (isObject(options) && 'chain' in options) {
chain = options.chain;
}
var ctor = object,
isFunc = isFunction(ctor);
forEach(methodNames, function(methodName) {
var func = object[methodName] = source[methodName];
if (isFunc) {
ctor.prototype[methodName] = function() {
var chainAll = this.__chain__,
value = this.__wrapped__,
args = [value];
push.apply(args, arguments);
var result = func.apply(object, args);
if (chain || chainAll) {
if (value === result && isObject(result)) {
return this;
}
result = new ctor(result);
result.__chain__ = chainAll;
}
return result;
};
}
});
}
/**
* Reverts the '_' variable to its previous value and returns a reference to
* the `lodash` function.
*
* @static
* @memberOf _
* @category Utilities
* @returns {Function} Returns the `lodash` function.
* @example
*
* var lodash = _.noConflict();
*/
function noConflict() {
context._ = oldDash;
return this;
}
/**
* A no-operation function.
*
* @static
* @memberOf _
* @category Utilities
* @example
*
* var object = { 'name': 'fred' };
* _.noop(object) === undefined;
* // => true
*/
function noop() {
// no operation performed
}
/**
* Gets the number of milliseconds that have elapsed since the Unix epoch
* (1 January 1970 00:00:00 UTC).
*
* @static
* @memberOf _
* @category Utilities
* @example
*
* var stamp = _.now();
* _.defer(function() { console.log(_.now() - stamp); });
* // => logs the number of milliseconds it took for the deferred function to be called
*/
var now = isNative(now = Date.now) && now || function() {
return new Date().getTime();
};
/**
* Converts the given value into an integer of the specified radix.
* If `radix` is `undefined` or `0` a `radix` of `10` is used unless the
* `value` is a hexadecimal, in which case a `radix` of `16` is used.
*
* Note: This method avoids differences in native ES3 and ES5 `parseInt`
* implementations. See http://es5.github.io/#E.
*
* @static
* @memberOf _
* @category Utilities
* @param {string} value The value to parse.
* @param {number} [radix] The radix used to interpret the value to parse.
* @returns {number} Returns the new integer value.
* @example
*
* _.parseInt('08');
* // => 8
*/
var parseInt = nativeParseInt(whitespace + '08') == 8 ? nativeParseInt : function(value, radix) {
// Firefox < 21 and Opera < 15 follow the ES3 specified implementation of `parseInt`
return nativeParseInt(isString(value) ? value.replace(reLeadingSpacesAndZeros, '') : value, radix || 0);
};
/**
* Creates a "_.pluck" style function, which returns the `key` value of a
* given object.
*
* @static
* @memberOf _
* @category Utilities
* @param {string} key The name of the property to retrieve.
* @returns {Function} Returns the new function.
* @example
*
* var characters = [
* { 'name': 'fred', 'age': 40 },
* { 'name': 'barney', 'age': 36 }
* ];
*
* var getName = _.property('name');
*
* _.map(characters, getName);
* // => ['barney', 'fred']
*
* _.sortBy(characters, getName);
* // => [{ 'name': 'barney', 'age': 36 }, { 'name': 'fred', 'age': 40 }]
*/
function property(key) {
return function(object) {
return object[key];
};
}
/**
* Produces a random number between `min` and `max` (inclusive). If only one
* argument is provided a number between `0` and the given number will be
* returned. If `floating` is truey or either `min` or `max` are floats a
* floating-point number will be returned instead of an integer.
*
* @static
* @memberOf _
* @category Utilities
* @param {number} [min=0] The minimum possible value.
* @param {number} [max=1] The maximum possible value.
* @param {boolean} [floating=false] Specify returning a floating-point number.
* @returns {number} Returns a random number.
* @example
*
* _.random(0, 5);
* // => an integer between 0 and 5
*
* _.random(5);
* // => also an integer between 0 and 5
*
* _.random(5, true);
* // => a floating-point number between 0 and 5
*
* _.random(1.2, 5.2);
* // => a floating-point number between 1.2 and 5.2
*/
function random(min, max, floating) {
var noMin = min == null,
noMax = max == null;
if (floating == null) {
if (typeof min == 'boolean' && noMax) {
floating = min;
min = 1;
}
else if (!noMax && typeof max == 'boolean') {
floating = max;
noMax = true;
}
}
if (noMin && noMax) {
max = 1;
}
min = +min || 0;
if (noMax) {
max = min;
min = 0;
} else {
max = +max || 0;
}
if (floating || min % 1 || max % 1) {
var rand = nativeRandom();
return nativeMin(min + (rand * (max - min + parseFloat('1e-' + ((rand +'').length - 1)))), max);
}
return baseRandom(min, max);
}
/**
* Resolves the value of property `key` on `object`. If `key` is a function
* it will be invoked with the `this` binding of `object` and its result returned,
* else the property value is returned. If `object` is falsey then `undefined`
* is returned.
*
* @static
* @memberOf _
* @category Utilities
* @param {Object} object The object to inspect.
* @param {string} key The name of the property to resolve.
* @returns {*} Returns the resolved value.
* @example
*
* var object = {
* 'cheese': 'crumpets',
* 'stuff': function() {
* return 'nonsense';
* }
* };
*
* _.result(object, 'cheese');
* // => 'crumpets'
*
* _.result(object, 'stuff');
* // => 'nonsense'
*/
function result(object, key) {
if (object) {
var value = object[key];
return isFunction(value) ? object[key]() : value;
}
}
/**
* A micro-templating method that handles arbitrary delimiters, preserves
* whitespace, and correctly escapes quotes within interpolated code.
*
* Note: In the development build, `_.template` utilizes sourceURLs for easier
* debugging. See http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl
*
* For more information on precompiling templates see:
* https://lodash.com/custom-builds
*
* For more information on Chrome extension sandboxes see:
* http://developer.chrome.com/stable/extensions/sandboxingEval.html
*
* @static
* @memberOf _
* @category Utilities
* @param {string} text The template text.
* @param {Object} data The data object used to populate the text.
* @param {Object} [options] The options object.
* @param {RegExp} [options.escape] The "escape" delimiter.
* @param {RegExp} [options.evaluate] The "evaluate" delimiter.
* @param {Object} [options.imports] An object to import into the template as local variables.
* @param {RegExp} [options.interpolate] The "interpolate" delimiter.
* @param {string} [sourceURL] The sourceURL of the template's compiled source.
* @param {string} [variable] The data object variable name.
* @returns {Function|string} Returns a compiled function when no `data` object
* is given, else it returns the interpolated text.
* @example
*
* // using the "interpolate" delimiter to create a compiled template
* var compiled = _.template('hello <%= name %>');
* compiled({ 'name': 'fred' });
* // => 'hello fred'
*
* // using the "escape" delimiter to escape HTML in data property values
* _.template('<b><%- value %></b>', { 'value': '<script>' });
* // => '<b><script></b>'
*
* // using the "evaluate" delimiter to generate HTML
* var list = '<% _.forEach(people, function(name) { %><li><%- name %></li><% }); %>';
* _.template(list, { 'people': ['fred', 'barney'] });
* // => '<li>fred</li><li>barney</li>'
*
* // using the ES6 delimiter as an alternative to the default "interpolate" delimiter
* _.template('hello ${ name }', { 'name': 'pebbles' });
* // => 'hello pebbles'
*
* // using the internal `print` function in "evaluate" delimiters
* _.template('<% print("hello " + name); %>!', { 'name': 'barney' });
* // => 'hello barney!'
*
* // using a custom template delimiters
* _.templateSettings = {
* 'interpolate': /{{([\s\S]+?)}}/g
* };
*
* _.template('hello {{ name }}!', { 'name': 'mustache' });
* // => 'hello mustache!'
*
* // using the `imports` option to import jQuery
* var list = '<% jq.each(people, function(name) { %><li><%- name %></li><% }); %>';
* _.template(list, { 'people': ['fred', 'barney'] }, { 'imports': { 'jq': jQuery } });
* // => '<li>fred</li><li>barney</li>'
*
* // using the `sourceURL` option to specify a custom sourceURL for the template
* var compiled = _.template('hello <%= name %>', null, { 'sourceURL': '/basic/greeting.jst' });
* compiled(data);
* // => find the source of "greeting.jst" under the Sources tab or Resources panel of the web inspector
*
* // using the `variable` option to ensure a with-statement isn't used in the compiled template
* var compiled = _.template('hi <%= data.name %>!', null, { 'variable': 'data' });
* compiled.source;
* // => function(data) {
* var __t, __p = '', __e = _.escape;
* __p += 'hi ' + ((__t = ( data.name )) == null ? '' : __t) + '!';
* return __p;
* }
*
* // using the `source` property to inline compiled templates for meaningful
* // line numbers in error messages and a stack trace
* fs.writeFileSync(path.join(cwd, 'jst.js'), '\
* var JST = {\
* "main": ' + _.template(mainText).source + '\
* };\
* ');
*/
function template(text, data, options) {
// based on John Resig's `tmpl` implementation
// http://ejohn.org/blog/javascript-micro-templating/
// and Laura Doktorova's doT.js
// https://github.com/olado/doT
var settings = lodash.templateSettings;
text = String(text || '');
// avoid missing dependencies when `iteratorTemplate` is not defined
options = iteratorTemplate ? defaults({}, options, settings) : settings;
var imports = iteratorTemplate && defaults({}, options.imports, settings.imports),
importsKeys = iteratorTemplate ? keys(imports) : ['_'],
importsValues = iteratorTemplate ? values(imports) : [lodash];
var isEvaluating,
index = 0,
interpolate = options.interpolate || reNoMatch,
source = "__p += '";
// compile the regexp to match each delimiter
var reDelimiters = RegExp(
(options.escape || reNoMatch).source + '|' +
interpolate.source + '|' +
(interpolate === reInterpolate ? reEsTemplate : reNoMatch).source + '|' +
(options.evaluate || reNoMatch).source + '|$'
, 'g');
text.replace(reDelimiters, function(match, escapeValue, interpolateValue, esTemplateValue, evaluateValue, offset) {
interpolateValue || (interpolateValue = esTemplateValue);
// escape characters that cannot be included in string literals
source += text.slice(index, offset).replace(reUnescapedString, escapeStringChar);
// replace delimiters with snippets
if (escapeValue) {
source += "' +\n__e(" + escapeValue + ") +\n'";
}
if (evaluateValue) {
isEvaluating = true;
source += "';\n" + evaluateValue + ";\n__p += '";
}
if (interpolateValue) {
source += "' +\n((__t = (" + interpolateValue + ")) == null ? '' : __t) +\n'";
}
index = offset + match.length;
// the JS engine embedded in Adobe products requires returning the `match`
// string in order to produce the correct `offset` value
return match;
});
source += "';\n";
// if `variable` is not specified, wrap a with-statement around the generated
// code to add the data object to the top of the scope chain
var variable = options.variable,
hasVariable = variable;
if (!hasVariable) {
variable = 'obj';
source = 'with (' + variable + ') {\n' + source + '\n}\n';
}
// cleanup code by stripping empty strings
source = (isEvaluating ? source.replace(reEmptyStringLeading, '') : source)
.replace(reEmptyStringMiddle, '$1')
.replace(reEmptyStringTrailing, '$1;');
// frame code as the function body
source = 'function(' + variable + ') {\n' +
(hasVariable ? '' : variable + ' || (' + variable + ' = {});\n') +
"var __t, __p = '', __e = _.escape" +
(isEvaluating
? ', __j = Array.prototype.join;\n' +
"function print() { __p += __j.call(arguments, '') }\n"
: ';\n'
) +
source +
'return __p\n}';
// Use a sourceURL for easier debugging.
// http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl
var sourceURL = '\n/*\n//# sourceURL=' + (options.sourceURL || '/lodash/template/source[' + (templateCounter++) + ']') + '\n*/';
try {
var result = Function(importsKeys, 'return ' + source + sourceURL).apply(undefined, importsValues);
} catch(e) {
e.source = source;
throw e;
}
if (data) {
return result(data);
}
// provide the compiled function's source by its `toString` method, in
// supported environments, or the `source` property as a convenience for
// inlining compiled templates during the build process
result.source = source;
return result;
}
/**
* Executes the callback `n` times, returning an array of the results
* of each callback execution. The callback is bound to `thisArg` and invoked
* with one argument; (index).
*
* @static
* @memberOf _
* @category Utilities
* @param {number} n The number of times to execute the callback.
* @param {Function} callback The function called per iteration.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {Array} Returns an array of the results of each `callback` execution.
* @example
*
* var diceRolls = _.times(3, _.partial(_.random, 1, 6));
* // => [3, 6, 4]
*
* _.times(3, function(n) { mage.castSpell(n); });
* // => calls `mage.castSpell(n)` three times, passing `n` of `0`, `1`, and `2` respectively
*
* _.times(3, function(n) { this.cast(n); }, mage);
* // => also calls `mage.castSpell(n)` three times
*/
function times(n, callback, thisArg) {
n = (n = +n) > -1 ? n : 0;
var index = -1,
result = Array(n);
callback = baseCreateCallback(callback, thisArg, 1);
while (++index < n) {
result[index] = callback(index);
}
return result;
}
/**
* The inverse of `_.escape` this method converts the HTML entities
* `&`, `<`, `>`, `"`, and `'` in `string` to their
* corresponding characters.
*
* @static
* @memberOf _
* @category Utilities
* @param {string} string The string to unescape.
* @returns {string} Returns the unescaped string.
* @example
*
* _.unescape('Fred, Barney & Pebbles');
* // => 'Fred, Barney & Pebbles'
*/
function unescape(string) {
return string == null ? '' : String(string).replace(reEscapedHtml, unescapeHtmlChar);
}
/**
* Generates a unique ID. If `prefix` is provided the ID will be appended to it.
*
* @static
* @memberOf _
* @category Utilities
* @param {string} [prefix] The value to prefix the ID with.
* @returns {string} Returns the unique ID.
* @example
*
* _.uniqueId('contact_');
* // => 'contact_104'
*
* _.uniqueId();
* // => '105'
*/
function uniqueId(prefix) {
var id = ++idCounter;
return String(prefix == null ? '' : prefix) + id;
}
/*--------------------------------------------------------------------------*/
/**
* Creates a `lodash` object that wraps the given value with explicit
* method chaining enabled.
*
* @static
* @memberOf _
* @category Chaining
* @param {*} value The value to wrap.
* @returns {Object} Returns the wrapper object.
* @example
*
* var characters = [
* { 'name': 'barney', 'age': 36 },
* { 'name': 'fred', 'age': 40 },
* { 'name': 'pebbles', 'age': 1 }
* ];
*
* var youngest = _.chain(characters)
* .sortBy('age')
* .map(function(chr) { return chr.name + ' is ' + chr.age; })
* .first()
* .value();
* // => 'pebbles is 1'
*/
function chain(value) {
value = new lodashWrapper(value);
value.__chain__ = true;
return value;
}
/**
* Invokes `interceptor` with the `value` as the first argument and then
* returns `value`. The purpose of this method is to "tap into" a method
* chain in order to perform operations on intermediate results within
* the chain.
*
* @static
* @memberOf _
* @category Chaining
* @param {*} value The value to provide to `interceptor`.
* @param {Function} interceptor The function to invoke.
* @returns {*} Returns `value`.
* @example
*
* _([1, 2, 3, 4])
* .tap(function(array) { array.pop(); })
* .reverse()
* .value();
* // => [3, 2, 1]
*/
function tap(value, interceptor) {
interceptor(value);
return value;
}
/**
* Enables explicit method chaining on the wrapper object.
*
* @name chain
* @memberOf _
* @category Chaining
* @returns {*} Returns the wrapper object.
* @example
*
* var characters = [
* { 'name': 'barney', 'age': 36 },
* { 'name': 'fred', 'age': 40 }
* ];
*
* // without explicit chaining
* _(characters).first();
* // => { 'name': 'barney', 'age': 36 }
*
* // with explicit chaining
* _(characters).chain()
* .first()
* .pick('age')
* .value();
* // => { 'age': 36 }
*/
function wrapperChain() {
this.__chain__ = true;
return this;
}
/**
* Produces the `toString` result of the wrapped value.
*
* @name toString
* @memberOf _
* @category Chaining
* @returns {string} Returns the string result.
* @example
*
* _([1, 2, 3]).toString();
* // => '1,2,3'
*/
function wrapperToString() {
return String(this.__wrapped__);
}
/**
* Extracts the wrapped value.
*
* @name valueOf
* @memberOf _
* @alias value
* @category Chaining
* @returns {*} Returns the wrapped value.
* @example
*
* _([1, 2, 3]).valueOf();
* // => [1, 2, 3]
*/
function wrapperValueOf() {
return this.__wrapped__;
}
/*--------------------------------------------------------------------------*/
// add functions that return wrapped values when chaining
lodash.after = after;
lodash.assign = assign;
lodash.at = at;
lodash.bind = bind;
lodash.bindAll = bindAll;
lodash.bindKey = bindKey;
lodash.chain = chain;
lodash.compact = compact;
lodash.compose = compose;
lodash.constant = constant;
lodash.countBy = countBy;
lodash.create = create;
lodash.createCallback = createCallback;
lodash.curry = curry;
lodash.debounce = debounce;
lodash.defaults = defaults;
lodash.defer = defer;
lodash.delay = delay;
lodash.difference = difference;
lodash.filter = filter;
lodash.flatten = flatten;
lodash.forEach = forEach;
lodash.forEachRight = forEachRight;
lodash.forIn = forIn;
lodash.forInRight = forInRight;
lodash.forOwn = forOwn;
lodash.forOwnRight = forOwnRight;
lodash.functions = functions;
lodash.groupBy = groupBy;
lodash.indexBy = indexBy;
lodash.initial = initial;
lodash.intersection = intersection;
lodash.invert = invert;
lodash.invoke = invoke;
lodash.keys = keys;
lodash.map = map;
lodash.mapValues = mapValues;
lodash.max = max;
lodash.memoize = memoize;
lodash.merge = merge;
lodash.min = min;
lodash.omit = omit;
lodash.once = once;
lodash.pairs = pairs;
lodash.partial = partial;
lodash.partialRight = partialRight;
lodash.pick = pick;
lodash.pluck = pluck;
lodash.property = property;
lodash.pull = pull;
lodash.range = range;
lodash.reject = reject;
lodash.remove = remove;
lodash.rest = rest;
lodash.shuffle = shuffle;
lodash.sortBy = sortBy;
lodash.tap = tap;
lodash.throttle = throttle;
lodash.times = times;
lodash.toArray = toArray;
lodash.transform = transform;
lodash.union = union;
lodash.uniq = uniq;
lodash.values = values;
lodash.where = where;
lodash.without = without;
lodash.wrap = wrap;
lodash.xor = xor;
lodash.zip = zip;
lodash.zipObject = zipObject;
// add aliases
lodash.collect = map;
lodash.drop = rest;
lodash.each = forEach;
lodash.eachRight = forEachRight;
lodash.extend = assign;
lodash.methods = functions;
lodash.object = zipObject;
lodash.select = filter;
lodash.tail = rest;
lodash.unique = uniq;
lodash.unzip = zip;
// add functions to `lodash.prototype`
mixin(lodash);
/*--------------------------------------------------------------------------*/
// add functions that return unwrapped values when chaining
lodash.clone = clone;
lodash.cloneDeep = cloneDeep;
lodash.contains = contains;
lodash.escape = escape;
lodash.every = every;
lodash.find = find;
lodash.findIndex = findIndex;
lodash.findKey = findKey;
lodash.findLast = findLast;
lodash.findLastIndex = findLastIndex;
lodash.findLastKey = findLastKey;
lodash.has = has;
lodash.identity = identity;
lodash.indexOf = indexOf;
lodash.isArguments = isArguments;
lodash.isArray = isArray;
lodash.isBoolean = isBoolean;
lodash.isDate = isDate;
lodash.isElement = isElement;
lodash.isEmpty = isEmpty;
lodash.isEqual = isEqual;
lodash.isFinite = isFinite;
lodash.isFunction = isFunction;
lodash.isNaN = isNaN;
lodash.isNull = isNull;
lodash.isNumber = isNumber;
lodash.isObject = isObject;
lodash.isPlainObject = isPlainObject;
lodash.isRegExp = isRegExp;
lodash.isString = isString;
lodash.isUndefined = isUndefined;
lodash.lastIndexOf = lastIndexOf;
lodash.mixin = mixin;
lodash.noConflict = noConflict;
lodash.noop = noop;
lodash.now = now;
lodash.parseInt = parseInt;
lodash.random = random;
lodash.reduce = reduce;
lodash.reduceRight = reduceRight;
lodash.result = result;
lodash.runInContext = runInContext;
lodash.size = size;
lodash.some = some;
lodash.sortedIndex = sortedIndex;
lodash.template = template;
lodash.unescape = unescape;
lodash.uniqueId = uniqueId;
// add aliases
lodash.all = every;
lodash.any = some;
lodash.detect = find;
lodash.findWhere = find;
lodash.foldl = reduce;
lodash.foldr = reduceRight;
lodash.include = contains;
lodash.inject = reduce;
mixin(function() {
var source = {}
forOwn(lodash, function(func, methodName) {
if (!lodash.prototype[methodName]) {
source[methodName] = func;
}
});
return source;
}(), false);
/*--------------------------------------------------------------------------*/
// add functions capable of returning wrapped and unwrapped values when chaining
lodash.first = first;
lodash.last = last;
lodash.sample = sample;
// add aliases
lodash.take = first;
lodash.head = first;
forOwn(lodash, function(func, methodName) {
var callbackable = methodName !== 'sample';
if (!lodash.prototype[methodName]) {
lodash.prototype[methodName]= function(n, guard) {
var chainAll = this.__chain__,
result = func(this.__wrapped__, n, guard);
return !chainAll && (n == null || (guard && !(callbackable && typeof n == 'function')))
? result
: new lodashWrapper(result, chainAll);
};
}
});
/*--------------------------------------------------------------------------*/
/**
* The semantic version number.
*
* @static
* @memberOf _
* @type string
*/
lodash.VERSION = '2.4.2';
// add "Chaining" functions to the wrapper
lodash.prototype.chain = wrapperChain;
lodash.prototype.toString = wrapperToString;
lodash.prototype.value = wrapperValueOf;
lodash.prototype.valueOf = wrapperValueOf;
// add `Array` functions that return unwrapped values
baseEach(['join', 'pop', 'shift'], function(methodName) {
var func = arrayRef[methodName];
lodash.prototype[methodName] = function() {
var chainAll = this.__chain__,
result = func.apply(this.__wrapped__, arguments);
return chainAll
? new lodashWrapper(result, chainAll)
: result;
};
});
// add `Array` functions that return the existing wrapped value
baseEach(['push', 'reverse', 'sort', 'unshift'], function(methodName) {
var func = arrayRef[methodName];
lodash.prototype[methodName] = function() {
func.apply(this.__wrapped__, arguments);
return this;
};
});
// add `Array` functions that return new wrapped values
baseEach(['concat', 'slice', 'splice'], function(methodName) {
var func = arrayRef[methodName];
lodash.prototype[methodName] = function() {
return new lodashWrapper(func.apply(this.__wrapped__, arguments), this.__chain__);
};
});
// avoid array-like object bugs with `Array#shift` and `Array#splice`
// in IE < 9, Firefox < 10, Narwhal, and RingoJS
if (!support.spliceObjects) {
baseEach(['pop', 'shift', 'splice'], function(methodName) {
var func = arrayRef[methodName],
isSplice = methodName == 'splice';
lodash.prototype[methodName] = function() {
var chainAll = this.__chain__,
value = this.__wrapped__,
result = func.apply(value, arguments);
if (value.length === 0) {
delete value[0];
}
return (chainAll || isSplice)
? new lodashWrapper(result, chainAll)
: result;
};
});
}
// add pseudo private property to be used and removed during the build process
lodash._baseEach = baseEach;
lodash._iteratorTemplate = iteratorTemplate;
lodash._shimKeys = shimKeys;
return lodash;
}
/*--------------------------------------------------------------------------*/
// expose Lo-Dash
var _ = runInContext();
// some AMD build optimizers like r.js check for condition patterns like the following:
if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) {
// Expose Lo-Dash to the global object even when an AMD loader is present in
// case Lo-Dash is loaded with a RequireJS shim config.
// See http://requirejs.org/docs/api.html#config-shim
root._ = _;
// define as an anonymous module so, through path mapping, it can be
// referenced as the "underscore" module
define(function() {
return _;
});
}
// check for `exports` after `define` in case a build optimizer adds an `exports` object
else if (freeExports && freeModule) {
// in Node.js or RingoJS
if (moduleExports) {
(freeModule.exports = _)._ = _;
}
// in Narwhal or Rhino -require
else {
freeExports._ = _;
}
}
else {
// in a browser or Rhino
root._ = _;
}
}.call(this));
| twhetzel/checklist-web | node_modules/browser-sync/node_modules/easy-extender/node_modules/lodash/lodash.js | JavaScript | bsd-3-clause | 245,659 |
.grid-view-loading
{
background:url(loading.gif) no-repeat;
}
.grid-view
{
padding: 15px 0;
}
.grid-view table.items
{
background: white;
border-collapse: collapse;
width: 100%;
border: 1px #D0E3EF solid;
}
.grid-view table.items th, .grid-view table.items td
{
font-size: 0.9em;
border: 1px white solid;
padding: 0.3em;
}
.grid-view table.items th
{
color: white;
background: url("bg.gif") repeat-x scroll left top white;
text-align: center;
}
.grid-view table.items th a
{
color: #EEE;
font-weight: bold;
text-decoration: none;
}
.grid-view table.items th a:hover
{
color: #FFF;
}
.grid-view table.items th a.asc
{
background:url(up.gif) right center no-repeat;
padding-right: 10px;
}
.grid-view table.items th a.desc
{
background:url(down.gif) right center no-repeat;
padding-right: 10px;
}
.grid-view table.items tr.even
{
background: #F8F8F8;
}
.grid-view table.items tr.odd
{
background: #E5F1F4;
}
.grid-view table.items tr.selected
{
background: #BCE774;
}
.grid-view table.items tr:hover
{
background: #ECFBD4;
}
.grid-view .link-column img
{
border: 0;
}
.grid-view .button-column
{
text-align: center;
width: 60px;
}
.grid-view .button-column img
{
border: 0;
}
.grid-view .checkbox-column
{
width: 15px;
}
.grid-view .summary
{
margin: 0 0 5px 0;
text-align: right;
}
.grid-view .pager
{
margin: 5px 0 0 0;
text-align: right;
}
.grid-view .empty
{
font-style: italic;
}
.grid-view .filters input,
.grid-view .filters select
{
width: 100%;
border: 1px solid #ccc;
} | AT-CMS/AT-CMS | atcms/assets/e6bfd44b/gridview/styles.css | CSS | bsd-3-clause | 1,532 |
/***************************************************************************/
/* */
/* ftmac.c */
/* */
/* Mac FOND support. Written by just@letterror.com. */
/* Heavily modified by mpsuzuki, George Williams, and Sean McBride. */
/* */
/* This file is for Mac OS X only; see builds/mac/ftoldmac.c for */
/* classic platforms built by MPW. */
/* */
/* Copyright 1996-2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, */
/* 2009 by */
/* Just van Rossum, David Turner, Robert Wilhelm, and Werner Lemberg. */
/* */
/* This file is part of the FreeType project, and may only be used, */
/* modified, and distributed under the terms of the FreeType project */
/* license, LICENSE.TXT. By continuing to use, modify, or distribute */
/* this file you indicate that you have read the license and */
/* understand and accept it fully. */
/* */
/***************************************************************************/
/*
Notes
Mac suitcase files can (and often do!) contain multiple fonts. To
support this I use the face_index argument of FT_(Open|New)_Face()
functions, and pretend the suitcase file is a collection.
Warning: fbit and NFNT bitmap resources are not supported yet. In old
sfnt fonts, bitmap glyph data for each size is stored in each `NFNT'
resources instead of the `bdat' table in the sfnt resource. Therefore,
face->num_fixed_sizes is set to 0, because bitmap data in `NFNT'
resource is unavailable at present.
The Mac FOND support works roughly like this:
- Check whether the offered stream points to a Mac suitcase file. This
is done by checking the file type: it has to be 'FFIL' or 'tfil'. The
stream that gets passed to our init_face() routine is a stdio stream,
which isn't usable for us, since the FOND resources live in the
resource fork. So we just grab the stream->pathname field.
- Read the FOND resource into memory, then check whether there is a
TrueType font and/or(!) a Type 1 font available.
- If there is a Type 1 font available (as a separate `LWFN' file), read
its data into memory, massage it slightly so it becomes PFB data, wrap
it into a memory stream, load the Type 1 driver and delegate the rest
of the work to it by calling FT_Open_Face(). (XXX TODO: after this
has been done, the kerning data from the FOND resource should be
appended to the face: On the Mac there are usually no AFM files
available. However, this is tricky since we need to map Mac char
codes to ps glyph names to glyph ID's...)
- If there is a TrueType font (an `sfnt' resource), read it into memory,
wrap it into a memory stream, load the TrueType driver and delegate
the rest of the work to it, by calling FT_Open_Face().
- Some suitcase fonts (notably Onyx) might point the `LWFN' file to
itself, even though it doesn't contains `POST' resources. To handle
this special case without opening the file an extra time, we just
ignore errors from the `LWFN' and fallback to the `sfnt' if both are
available.
*/
#include <ft2build.h>
#include FT_FREETYPE_H
#include FT_TRUETYPE_TAGS_H
#include FT_INTERNAL_STREAM_H
#include "ftbase.h"
/* This is for Mac OS X. Without redefinition, OS_INLINE */
/* expands to `static inline' which doesn't survive the */
/* -ansi compilation flag of GCC. */
#if !HAVE_ANSI_OS_INLINE
#undef OS_INLINE
#define OS_INLINE static __inline__
#endif
/* `configure' checks the availability of `ResourceIndex' strictly */
/* and sets HAVE_TYPE_RESOURCE_INDEX 1 or 0 always. If it is */
/* not set (e.g., a build without `configure'), the availability */
/* is guessed from the SDK version. */
#ifndef HAVE_TYPE_RESOURCE_INDEX
#if !defined( MAC_OS_X_VERSION_10_5 ) || \
( MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5 )
#define HAVE_TYPE_RESOURCE_INDEX 0
#else
#define HAVE_TYPE_RESOURCE_INDEX 1
#endif
#endif /* !HAVE_TYPE_RESOURCE_INDEX */
#if ( HAVE_TYPE_RESOURCE_INDEX == 0 )
typedef short ResourceIndex;
#endif
#include <CoreServices/CoreServices.h>
#include <ApplicationServices/ApplicationServices.h>
#include <sys/syslimits.h> /* PATH_MAX */
/* Don't want warnings about our own use of deprecated functions. */
#define FT_DEPRECATED_ATTRIBUTE
#include FT_MAC_H
#ifndef kATSOptionFlagsUnRestrictedScope /* since Mac OS X 10.1 */
#define kATSOptionFlagsUnRestrictedScope kATSOptionFlagsDefault
#endif
/* Set PREFER_LWFN to 1 if LWFN (Type 1) is preferred over
TrueType in case *both* are available (this is not common,
but it *is* possible). */
#ifndef PREFER_LWFN
#define PREFER_LWFN 1
#endif
/* This function is deprecated because FSSpec is deprecated in Mac OS X */
FT_EXPORT_DEF( FT_Error )
FT_GetFile_From_Mac_Name( const char* fontName,
FSSpec* pathSpec,
FT_Long* face_index )
{
FT_UNUSED( fontName );
FT_UNUSED( pathSpec );
FT_UNUSED( face_index );
return FT_Err_Unimplemented_Feature;
}
/* Private function. */
/* The FSSpec type has been discouraged for a long time, */
/* unfortunately an FSRef replacement API for */
/* ATSFontGetFileSpecification() is only available in */
/* Mac OS X 10.5 and later. */
static OSStatus
FT_ATSFontGetFileReference( ATSFontRef ats_font_id,
FSRef* ats_font_ref )
{
#if defined( MAC_OS_X_VERSION_10_5 ) && \
( MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5 )
OSStatus err;
err = ATSFontGetFileReference( ats_font_id, ats_font_ref );
return err;
#elif __LP64__ /* No 64bit Carbon API on legacy platforms */
FT_UNUSED( ats_font_id );
FT_UNUSED( ats_font_ref );
return fnfErr;
#else /* 32bit Carbon API on legacy platforms */
OSStatus err;
FSSpec spec;
err = ATSFontGetFileSpecification( ats_font_id, &spec );
if ( noErr == err )
err = FSpMakeFSRef( &spec, ats_font_ref );
return err;
#endif
}
static FT_Error
FT_GetFileRef_From_Mac_ATS_Name( const char* fontName,
FSRef* ats_font_ref,
FT_Long* face_index )
{
CFStringRef cf_fontName;
ATSFontRef ats_font_id;
*face_index = 0;
cf_fontName = CFStringCreateWithCString( NULL, fontName,
kCFStringEncodingMacRoman );
ats_font_id = ATSFontFindFromName( cf_fontName,
kATSOptionFlagsUnRestrictedScope );
CFRelease( cf_fontName );
if ( ats_font_id == 0 || ats_font_id == 0xFFFFFFFFUL )
return FT_Err_Unknown_File_Format;
if ( noErr != FT_ATSFontGetFileReference( ats_font_id, ats_font_ref ) )
return FT_Err_Unknown_File_Format;
/* face_index calculation by searching preceding fontIDs */
/* with same FSRef */
{
ATSFontRef id2 = ats_font_id - 1;
FSRef ref2;
while ( id2 > 0 )
{
if ( noErr != FT_ATSFontGetFileReference( id2, &ref2 ) )
break;
if ( noErr != FSCompareFSRefs( ats_font_ref, &ref2 ) )
break;
id2 --;
}
*face_index = ats_font_id - ( id2 + 1 );
}
return FT_Err_Ok;
}
FT_EXPORT_DEF( FT_Error )
FT_GetFilePath_From_Mac_ATS_Name( const char* fontName,
UInt8* path,
UInt32 maxPathSize,
FT_Long* face_index )
{
FSRef ref;
FT_Error err;
err = FT_GetFileRef_From_Mac_ATS_Name( fontName, &ref, face_index );
if ( FT_Err_Ok != err )
return err;
if ( noErr != FSRefMakePath( &ref, path, maxPathSize ) )
return FT_Err_Unknown_File_Format;
return FT_Err_Ok;
}
/* This function is deprecated because FSSpec is deprecated in Mac OS X */
FT_EXPORT_DEF( FT_Error )
FT_GetFile_From_Mac_ATS_Name( const char* fontName,
FSSpec* pathSpec,
FT_Long* face_index )
{
#if ( __LP64__ ) || ( defined( MAC_OS_X_VERSION_10_5 ) && \
( MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5 ) )
FT_UNUSED( fontName );
FT_UNUSED( pathSpec );
FT_UNUSED( face_index );
return FT_Err_Unimplemented_Feature;
#else
FSRef ref;
FT_Error err;
err = FT_GetFileRef_From_Mac_ATS_Name( fontName, &ref, face_index );
if ( FT_Err_Ok != err )
return err;
if ( noErr != FSGetCatalogInfo( &ref, kFSCatInfoNone, NULL, NULL,
pathSpec, NULL ) )
return FT_Err_Unknown_File_Format;
return FT_Err_Ok;
#endif
}
static OSErr
FT_FSPathMakeRes( const UInt8* pathname,
ResFileRefNum* res )
{
OSErr err;
FSRef ref;
if ( noErr != FSPathMakeRef( pathname, &ref, FALSE ) )
return FT_Err_Cannot_Open_Resource;
/* at present, no support for dfont format */
err = FSOpenResourceFile( &ref, 0, NULL, fsRdPerm, res );
if ( noErr == err )
return err;
/* fallback to original resource-fork font */
*res = FSOpenResFile( &ref, fsRdPerm );
err = ResError();
return err;
}
/* Return the file type for given pathname */
static OSType
get_file_type_from_path( const UInt8* pathname )
{
FSRef ref;
FSCatalogInfo info;
if ( noErr != FSPathMakeRef( pathname, &ref, FALSE ) )
return ( OSType ) 0;
if ( noErr != FSGetCatalogInfo( &ref, kFSCatInfoFinderInfo, &info,
NULL, NULL, NULL ) )
return ( OSType ) 0;
return ((FInfo *)(info.finderInfo))->fdType;
}
/* Given a PostScript font name, create the Macintosh LWFN file name. */
static void
create_lwfn_name( char* ps_name,
Str255 lwfn_file_name )
{
int max = 5, count = 0;
FT_Byte* p = lwfn_file_name;
FT_Byte* q = (FT_Byte*)ps_name;
lwfn_file_name[0] = 0;
while ( *q )
{
if ( ft_isupper( *q ) )
{
if ( count )
max = 3;
count = 0;
}
if ( count < max && ( ft_isalnum( *q ) || *q == '_' ) )
{
*++p = *q;
lwfn_file_name[0]++;
count++;
}
q++;
}
}
static short
count_faces_sfnt( char* fond_data )
{
/* The count is 1 greater than the value in the FOND. */
/* Isn't that cute? :-) */
return EndianS16_BtoN( *( (short*)( fond_data +
sizeof ( FamRec ) ) ) ) + 1;
}
static short
count_faces_scalable( char* fond_data )
{
AsscEntry* assoc;
FamRec* fond;
short i, face, face_all;
fond = (FamRec*)fond_data;
face_all = EndianS16_BtoN( *( (short *)( fond_data +
sizeof ( FamRec ) ) ) ) + 1;
assoc = (AsscEntry*)( fond_data + sizeof ( FamRec ) + 2 );
face = 0;
for ( i = 0; i < face_all; i++ )
{
if ( 0 == EndianS16_BtoN( assoc[i].fontSize ) )
face++;
}
return face;
}
/* Look inside the FOND data, answer whether there should be an SFNT
resource, and answer the name of a possible LWFN Type 1 file.
Thanks to Paul Miller (paulm@profoundeffects.com) for the fix
to load a face OTHER than the first one in the FOND!
*/
static void
parse_fond( char* fond_data,
short* have_sfnt,
ResID* sfnt_id,
Str255 lwfn_file_name,
short face_index )
{
AsscEntry* assoc;
AsscEntry* base_assoc;
FamRec* fond;
*sfnt_id = 0;
*have_sfnt = 0;
lwfn_file_name[0] = 0;
fond = (FamRec*)fond_data;
assoc = (AsscEntry*)( fond_data + sizeof ( FamRec ) + 2 );
base_assoc = assoc;
/* the maximum faces in a FOND is 48, size of StyleTable.indexes[] */
if ( 47 < face_index )
return;
/* Let's do a little range checking before we get too excited here */
if ( face_index < count_faces_sfnt( fond_data ) )
{
assoc += face_index; /* add on the face_index! */
/* if the face at this index is not scalable,
fall back to the first one (old behavior) */
if ( EndianS16_BtoN( assoc->fontSize ) == 0 )
{
*have_sfnt = 1;
*sfnt_id = EndianS16_BtoN( assoc->fontID );
}
else if ( base_assoc->fontSize == 0 )
{
*have_sfnt = 1;
*sfnt_id = EndianS16_BtoN( base_assoc->fontID );
}
}
if ( EndianS32_BtoN( fond->ffStylOff ) )
{
unsigned char* p = (unsigned char*)fond_data;
StyleTable* style;
unsigned short string_count;
char ps_name[256];
unsigned char* names[64];
int i;
p += EndianS32_BtoN( fond->ffStylOff );
style = (StyleTable*)p;
p += sizeof ( StyleTable );
string_count = EndianS16_BtoN( *(short*)(p) );
p += sizeof ( short );
for ( i = 0; i < string_count && i < 64; i++ )
{
names[i] = p;
p += names[i][0];
p++;
}
{
size_t ps_name_len = (size_t)names[0][0];
if ( ps_name_len != 0 )
{
ft_memcpy(ps_name, names[0] + 1, ps_name_len);
ps_name[ps_name_len] = 0;
}
if ( style->indexes[face_index] > 1 &&
style->indexes[face_index] <= FT_MIN( string_count, 64 ) )
{
unsigned char* suffixes = names[style->indexes[face_index] - 1];
for ( i = 1; i <= suffixes[0]; i++ )
{
unsigned char* s;
size_t j = suffixes[i] - 1;
if ( j < string_count && ( s = names[j] ) != NULL )
{
size_t s_len = (size_t)s[0];
if ( s_len != 0 && ps_name_len + s_len < sizeof ( ps_name ) )
{
ft_memcpy( ps_name + ps_name_len, s + 1, s_len );
ps_name_len += s_len;
ps_name[ps_name_len] = 0;
}
}
}
}
}
create_lwfn_name( ps_name, lwfn_file_name );
}
}
static FT_Error
lookup_lwfn_by_fond( const UInt8* path_fond,
ConstStr255Param base_lwfn,
UInt8* path_lwfn,
size_t path_size )
{
FSRef ref, par_ref;
size_t dirname_len;
/* Pathname for FSRef can be in various formats: HFS, HFS+, and POSIX. */
/* We should not extract parent directory by string manipulation. */
if ( noErr != FSPathMakeRef( path_fond, &ref, FALSE ) )
return FT_Err_Invalid_Argument;
if ( noErr != FSGetCatalogInfo( &ref, kFSCatInfoNone,
NULL, NULL, NULL, &par_ref ) )
return FT_Err_Invalid_Argument;
if ( noErr != FSRefMakePath( &par_ref, path_lwfn, path_size ) )
return FT_Err_Invalid_Argument;
if ( ft_strlen( (char *)path_lwfn ) + 1 + base_lwfn[0] > path_size )
return FT_Err_Invalid_Argument;
/* now we have absolute dirname in path_lwfn */
ft_strcat( (char *)path_lwfn, "/" );
dirname_len = ft_strlen( (char *)path_lwfn );
ft_strcat( (char *)path_lwfn, (char *)base_lwfn + 1 );
path_lwfn[dirname_len + base_lwfn[0]] = '\0';
if ( noErr != FSPathMakeRef( path_lwfn, &ref, FALSE ) )
return FT_Err_Cannot_Open_Resource;
if ( noErr != FSGetCatalogInfo( &ref, kFSCatInfoNone,
NULL, NULL, NULL, NULL ) )
return FT_Err_Cannot_Open_Resource;
return FT_Err_Ok;
}
static short
count_faces( Handle fond,
const UInt8* pathname )
{
ResID sfnt_id;
short have_sfnt, have_lwfn;
Str255 lwfn_file_name;
UInt8 buff[PATH_MAX];
FT_Error err;
short num_faces;
have_sfnt = have_lwfn = 0;
parse_fond( *fond, &have_sfnt, &sfnt_id, lwfn_file_name, 0 );
if ( lwfn_file_name[0] )
{
err = lookup_lwfn_by_fond( pathname, lwfn_file_name,
buff, sizeof ( buff ) );
if ( FT_Err_Ok == err )
have_lwfn = 1;
}
if ( have_lwfn && ( !have_sfnt || PREFER_LWFN ) )
num_faces = 1;
else
num_faces = count_faces_scalable( *fond );
return num_faces;
}
/* Read Type 1 data from the POST resources inside the LWFN file,
return a PFB buffer. This is somewhat convoluted because the FT2
PFB parser wants the ASCII header as one chunk, and the LWFN
chunks are often not organized that way, so we glue chunks
of the same type together. */
static FT_Error
read_lwfn( FT_Memory memory,
ResFileRefNum res,
FT_Byte** pfb_data,
FT_ULong* size )
{
FT_Error error = FT_Err_Ok;
ResID res_id;
unsigned char *buffer, *p, *size_p = NULL;
FT_ULong total_size = 0;
FT_ULong old_total_size = 0;
FT_ULong post_size, pfb_chunk_size;
Handle post_data;
char code, last_code;
UseResFile( res );
/* First pass: load all POST resources, and determine the size of */
/* the output buffer. */
res_id = 501;
last_code = -1;
for (;;)
{
post_data = Get1Resource( TTAG_POST, res_id++ );
if ( post_data == NULL )
break; /* we are done */
code = (*post_data)[0];
if ( code != last_code )
{
if ( code == 5 )
total_size += 2; /* just the end code */
else
total_size += 6; /* code + 4 bytes chunk length */
}
total_size += GetHandleSize( post_data ) - 2;
last_code = code;
/* detect integer overflows */
if ( total_size < old_total_size )
{
error = FT_Err_Array_Too_Large;
goto Error;
}
old_total_size = total_size;
}
if ( FT_ALLOC( buffer, (FT_Long)total_size ) )
goto Error;
/* Second pass: append all POST data to the buffer, add PFB fields. */
/* Glue all consecutive chunks of the same type together. */
p = buffer;
res_id = 501;
last_code = -1;
pfb_chunk_size = 0;
for (;;)
{
post_data = Get1Resource( TTAG_POST, res_id++ );
if ( post_data == NULL )
break; /* we are done */
post_size = (FT_ULong)GetHandleSize( post_data ) - 2;
code = (*post_data)[0];
if ( code != last_code )
{
if ( last_code != -1 )
{
/* we are done adding a chunk, fill in the size field */
if ( size_p != NULL )
{
*size_p++ = (FT_Byte)( pfb_chunk_size & 0xFF );
*size_p++ = (FT_Byte)( ( pfb_chunk_size >> 8 ) & 0xFF );
*size_p++ = (FT_Byte)( ( pfb_chunk_size >> 16 ) & 0xFF );
*size_p++ = (FT_Byte)( ( pfb_chunk_size >> 24 ) & 0xFF );
}
pfb_chunk_size = 0;
}
*p++ = 0x80;
if ( code == 5 )
*p++ = 0x03; /* the end */
else if ( code == 2 )
*p++ = 0x02; /* binary segment */
else
*p++ = 0x01; /* ASCII segment */
if ( code != 5 )
{
size_p = p; /* save for later */
p += 4; /* make space for size field */
}
}
ft_memcpy( p, *post_data + 2, post_size );
pfb_chunk_size += post_size;
p += post_size;
last_code = code;
}
*pfb_data = buffer;
*size = total_size;
Error:
CloseResFile( res );
return error;
}
/* Create a new FT_Face from a file path to an LWFN file. */
static FT_Error
FT_New_Face_From_LWFN( FT_Library library,
const UInt8* pathname,
FT_Long face_index,
FT_Face* aface )
{
FT_Byte* pfb_data;
FT_ULong pfb_size;
FT_Error error;
ResFileRefNum res;
if ( noErr != FT_FSPathMakeRes( pathname, &res ) )
return FT_Err_Cannot_Open_Resource;
pfb_data = NULL;
pfb_size = 0;
error = read_lwfn( library->memory, res, &pfb_data, &pfb_size );
CloseResFile( res ); /* PFB is already loaded, useless anymore */
if ( error )
return error;
return open_face_from_buffer( library,
pfb_data,
pfb_size,
face_index,
"type1",
aface );
}
/* Create a new FT_Face from an SFNT resource, specified by res ID. */
static FT_Error
FT_New_Face_From_SFNT( FT_Library library,
ResID sfnt_id,
FT_Long face_index,
FT_Face* aface )
{
Handle sfnt = NULL;
FT_Byte* sfnt_data;
size_t sfnt_size;
FT_Error error = FT_Err_Ok;
FT_Memory memory = library->memory;
int is_cff, is_sfnt_ps;
sfnt = GetResource( TTAG_sfnt, sfnt_id );
if ( sfnt == NULL )
return FT_Err_Invalid_Handle;
sfnt_size = (FT_ULong)GetHandleSize( sfnt );
if ( FT_ALLOC( sfnt_data, (FT_Long)sfnt_size ) )
{
ReleaseResource( sfnt );
return error;
}
ft_memcpy( sfnt_data, *sfnt, sfnt_size );
ReleaseResource( sfnt );
is_cff = sfnt_size > 4 && !ft_memcmp( sfnt_data, "OTTO", 4 );
is_sfnt_ps = sfnt_size > 4 && !ft_memcmp( sfnt_data, "typ1", 4 );
if ( is_sfnt_ps )
{
FT_Stream stream;
if ( FT_NEW( stream ) )
goto Try_OpenType;
FT_Stream_OpenMemory( stream, sfnt_data, sfnt_size );
if ( !open_face_PS_from_sfnt_stream( library,
stream,
face_index,
0, NULL,
aface ) )
{
FT_Stream_Close( stream );
FT_FREE( stream );
FT_FREE( sfnt_data );
goto Exit;
}
FT_FREE( stream );
}
Try_OpenType:
error = open_face_from_buffer( library,
sfnt_data,
sfnt_size,
face_index,
is_cff ? "cff" : "truetype",
aface );
Exit:
return error;
}
/* Create a new FT_Face from a file path to a suitcase file. */
static FT_Error
FT_New_Face_From_Suitcase( FT_Library library,
const UInt8* pathname,
FT_Long face_index,
FT_Face* aface )
{
FT_Error error = FT_Err_Cannot_Open_Resource;
ResFileRefNum res_ref;
ResourceIndex res_index;
Handle fond;
short num_faces_in_res, num_faces_in_fond;
if ( noErr != FT_FSPathMakeRes( pathname, &res_ref ) )
return FT_Err_Cannot_Open_Resource;
UseResFile( res_ref );
if ( ResError() )
return FT_Err_Cannot_Open_Resource;
num_faces_in_res = 0;
for ( res_index = 1; ; ++res_index )
{
fond = Get1IndResource( TTAG_FOND, res_index );
if ( ResError() )
break;
num_faces_in_fond = count_faces( fond, pathname );
num_faces_in_res += num_faces_in_fond;
if ( 0 <= face_index && face_index < num_faces_in_fond && error )
error = FT_New_Face_From_FOND( library, fond, face_index, aface );
face_index -= num_faces_in_fond;
}
CloseResFile( res_ref );
if ( FT_Err_Ok == error && NULL != aface && NULL != *aface )
(*aface)->num_faces = num_faces_in_res;
return error;
}
/* documentation is in ftmac.h */
FT_EXPORT_DEF( FT_Error )
FT_New_Face_From_FOND( FT_Library library,
Handle fond,
FT_Long face_index,
FT_Face* aface )
{
short have_sfnt, have_lwfn = 0;
ResID sfnt_id, fond_id;
OSType fond_type;
Str255 fond_name;
Str255 lwfn_file_name;
UInt8 path_lwfn[PATH_MAX];
OSErr err;
FT_Error error = FT_Err_Ok;
GetResInfo( fond, &fond_id, &fond_type, fond_name );
if ( ResError() != noErr || fond_type != TTAG_FOND )
return FT_Err_Invalid_File_Format;
parse_fond( *fond, &have_sfnt, &sfnt_id, lwfn_file_name, face_index );
if ( lwfn_file_name[0] )
{
ResFileRefNum res;
res = HomeResFile( fond );
if ( noErr != ResError() )
goto found_no_lwfn_file;
{
UInt8 path_fond[PATH_MAX];
FSRef ref;
err = FSGetForkCBInfo( res, kFSInvalidVolumeRefNum,
NULL, NULL, NULL, &ref, NULL );
if ( noErr != err )
goto found_no_lwfn_file;
err = FSRefMakePath( &ref, path_fond, sizeof ( path_fond ) );
if ( noErr != err )
goto found_no_lwfn_file;
error = lookup_lwfn_by_fond( path_fond, lwfn_file_name,
path_lwfn, sizeof ( path_lwfn ) );
if ( FT_Err_Ok == error )
have_lwfn = 1;
}
}
if ( have_lwfn && ( !have_sfnt || PREFER_LWFN ) )
error = FT_New_Face_From_LWFN( library,
path_lwfn,
face_index,
aface );
else
error = FT_Err_Unknown_File_Format;
found_no_lwfn_file:
if ( have_sfnt && FT_Err_Ok != error )
error = FT_New_Face_From_SFNT( library,
sfnt_id,
face_index,
aface );
return error;
}
/* Common function to load a new FT_Face from a resource file. */
static FT_Error
FT_New_Face_From_Resource( FT_Library library,
const UInt8* pathname,
FT_Long face_index,
FT_Face* aface )
{
OSType file_type;
FT_Error error;
/* LWFN is a (very) specific file format, check for it explicitly */
file_type = get_file_type_from_path( pathname );
if ( file_type == TTAG_LWFN )
return FT_New_Face_From_LWFN( library, pathname, face_index, aface );
/* Otherwise the file type doesn't matter (there are more than */
/* `FFIL' and `tfil'). Just try opening it as a font suitcase; */
/* if it works, fine. */
error = FT_New_Face_From_Suitcase( library, pathname, face_index, aface );
if ( error == 0 )
return error;
/* let it fall through to normal loader (.ttf, .otf, etc.); */
/* we signal this by returning no error and no FT_Face */
*aface = NULL;
return 0;
}
/*************************************************************************/
/* */
/* <Function> */
/* FT_New_Face */
/* */
/* <Description> */
/* This is the Mac-specific implementation of FT_New_Face. In */
/* addition to the standard FT_New_Face() functionality, it also */
/* accepts pathnames to Mac suitcase files. For further */
/* documentation see the original FT_New_Face() in freetype.h. */
/* */
FT_EXPORT_DEF( FT_Error )
FT_New_Face( FT_Library library,
const char* pathname,
FT_Long face_index,
FT_Face* aface )
{
FT_Open_Args args;
FT_Error error;
/* test for valid `library' and `aface' delayed to FT_Open_Face() */
if ( !pathname )
return FT_Err_Invalid_Argument;
error = FT_Err_Ok;
*aface = NULL;
/* try resourcefork based font: LWFN, FFIL */
error = FT_New_Face_From_Resource( library, (UInt8 *)pathname,
face_index, aface );
if ( error != 0 || *aface != NULL )
return error;
/* let it fall through to normal loader (.ttf, .otf, etc.) */
args.flags = FT_OPEN_PATHNAME;
args.pathname = (char*)pathname;
return FT_Open_Face( library, &args, face_index, aface );
}
/*************************************************************************/
/* */
/* <Function> */
/* FT_New_Face_From_FSRef */
/* */
/* <Description> */
/* FT_New_Face_From_FSRef is identical to FT_New_Face except it */
/* accepts an FSRef instead of a path. */
/* */
/* This function is deprecated because Carbon data types (FSRef) */
/* are not cross-platform, and thus not suitable for the freetype API. */
FT_EXPORT_DEF( FT_Error )
FT_New_Face_From_FSRef( FT_Library library,
const FSRef* ref,
FT_Long face_index,
FT_Face* aface )
{
FT_Error error;
FT_Open_Args args;
OSErr err;
UInt8 pathname[PATH_MAX];
if ( !ref )
return FT_Err_Invalid_Argument;
err = FSRefMakePath( ref, pathname, sizeof ( pathname ) );
if ( err )
error = FT_Err_Cannot_Open_Resource;
error = FT_New_Face_From_Resource( library, pathname, face_index, aface );
if ( error != 0 || *aface != NULL )
return error;
/* fallback to datafork font */
args.flags = FT_OPEN_PATHNAME;
args.pathname = (char*)pathname;
return FT_Open_Face( library, &args, face_index, aface );
}
/*************************************************************************/
/* */
/* <Function> */
/* FT_New_Face_From_FSSpec */
/* */
/* <Description> */
/* FT_New_Face_From_FSSpec is identical to FT_New_Face except it */
/* accepts an FSSpec instead of a path. */
/* */
/* This function is deprecated because FSSpec is deprecated in Mac OS X */
FT_EXPORT_DEF( FT_Error )
FT_New_Face_From_FSSpec( FT_Library library,
const FSSpec* spec,
FT_Long face_index,
FT_Face* aface )
{
#if ( __LP64__ ) || ( defined( MAC_OS_X_VERSION_10_5 ) && \
( MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5 ) )
FT_UNUSED( library );
FT_UNUSED( spec );
FT_UNUSED( face_index );
FT_UNUSED( aface );
return FT_Err_Unimplemented_Feature;
#else
FSRef ref;
if ( !spec || FSpMakeFSRef( spec, &ref ) != noErr )
return FT_Err_Invalid_Argument;
else
return FT_New_Face_From_FSRef( library, &ref, face_index, aface );
#endif
}
/* END */
| mattvick/phantomjs | src/qt/qtbase/src/3rdparty/freetype/src/base/ftmac.c | C | bsd-3-clause | 33,023 |
<?php
namespace tests\codeception\common\_support;
use tests\codeception\common\fixtures\UserFixture;
use Codeception\Module;
use yii\test\FixtureTrait;
use yii\test\InitDbFixture;
/**
* This helper is used to populate the database with needed fixtures before any tests are run.
* In this example, the database is populated with the demo login user, which is used in acceptance
* and functional tests. All fixtures will be loaded before the suite is started and unloaded after it
* completes.
*/
class FixtureHelper extends Module
{
/**
* Redeclare visibility because codeception includes all public methods that do not start with "_"
* and are not excluded by module settings, in actor class.
*/
use FixtureTrait {
loadFixtures as public;
fixtures as public;
globalFixtures as public;
createFixtures as public;
unloadFixtures as protected;
getFixtures as protected;
getFixture as protected;
}
/**
* Method called before any suite tests run. Loads User fixture login user
* to use in acceptance and functional tests.
* @param array $settings
*/
public function _beforeSuite($settings = [])
{
$this->loadFixtures();
}
/**
* Method is called after all suite tests run
*/
public function _afterSuite()
{
$this->unloadFixtures();
}
/**
* @inheritdoc
*/
public function globalFixtures()
{
return [
InitDbFixture::className(),
];
}
/**
* @inheritdoc
*/
public function fixtures()
{
return [
'user' => [
'class' => UserFixture::className(),
'dataFile' => '@tests/codeception/common/fixtures/data/init_login.php',
],
];
}
}
| tuananh3988/m5c | tests/codeception/common/_support/FixtureHelper.php | PHP | bsd-3-clause | 1,843 |
// Copyright 2010 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package math
/*
Floating-point error function and complementary error function.
*/
// The original C code and the long comment below are
// from FreeBSD's /usr/src/lib/msun/src/s_erf.c and
// came with this notice. The go code is a simplified
// version of the original C.
//
// ====================================================
// Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
//
// Developed at SunPro, a Sun Microsystems, Inc. business.
// Permission to use, copy, modify, and distribute this
// software is freely granted, provided that this notice
// is preserved.
// ====================================================
//
//
// double erf(double x)
// double erfc(double x)
// x
// 2 |\
// erf(x) = --------- | exp(-t*t)dt
// sqrt(pi) \|
// 0
//
// erfc(x) = 1-erf(x)
// Note that
// erf(-x) = -erf(x)
// erfc(-x) = 2 - erfc(x)
//
// Method:
// 1. For |x| in [0, 0.84375]
// erf(x) = x + x*R(x**2)
// erfc(x) = 1 - erf(x) if x in [-.84375,0.25]
// = 0.5 + ((0.5-x)-x*R) if x in [0.25,0.84375]
// where R = P/Q where P is an odd poly of degree 8 and
// Q is an odd poly of degree 10.
// -57.90
// | R - (erf(x)-x)/x | <= 2
//
//
// Remark. The formula is derived by noting
// erf(x) = (2/sqrt(pi))*(x - x**3/3 + x**5/10 - x**7/42 + ....)
// and that
// 2/sqrt(pi) = 1.128379167095512573896158903121545171688
// is close to one. The interval is chosen because the fix
// point of erf(x) is near 0.6174 (i.e., erf(x)=x when x is
// near 0.6174), and by some experiment, 0.84375 is chosen to
// guarantee the error is less than one ulp for erf.
//
// 2. For |x| in [0.84375,1.25], let s = |x| - 1, and
// c = 0.84506291151 rounded to single (24 bits)
// erf(x) = sign(x) * (c + P1(s)/Q1(s))
// erfc(x) = (1-c) - P1(s)/Q1(s) if x > 0
// 1+(c+P1(s)/Q1(s)) if x < 0
// |P1/Q1 - (erf(|x|)-c)| <= 2**-59.06
// Remark: here we use the taylor series expansion at x=1.
// erf(1+s) = erf(1) + s*Poly(s)
// = 0.845.. + P1(s)/Q1(s)
// That is, we use rational approximation to approximate
// erf(1+s) - (c = (single)0.84506291151)
// Note that |P1/Q1|< 0.078 for x in [0.84375,1.25]
// where
// P1(s) = degree 6 poly in s
// Q1(s) = degree 6 poly in s
//
// 3. For x in [1.25,1/0.35(~2.857143)],
// erfc(x) = (1/x)*exp(-x*x-0.5625+R1/S1)
// erf(x) = 1 - erfc(x)
// where
// R1(z) = degree 7 poly in z, (z=1/x**2)
// S1(z) = degree 8 poly in z
//
// 4. For x in [1/0.35,28]
// erfc(x) = (1/x)*exp(-x*x-0.5625+R2/S2) if x > 0
// = 2.0 - (1/x)*exp(-x*x-0.5625+R2/S2) if -6<x<0
// = 2.0 - tiny (if x <= -6)
// erf(x) = sign(x)*(1.0 - erfc(x)) if x < 6, else
// erf(x) = sign(x)*(1.0 - tiny)
// where
// R2(z) = degree 6 poly in z, (z=1/x**2)
// S2(z) = degree 7 poly in z
//
// Note1:
// To compute exp(-x*x-0.5625+R/S), let s be a single
// precision number and s := x; then
// -x*x = -s*s + (s-x)*(s+x)
// exp(-x*x-0.5626+R/S) =
// exp(-s*s-0.5625)*exp((s-x)*(s+x)+R/S);
// Note2:
// Here 4 and 5 make use of the asymptotic series
// exp(-x*x)
// erfc(x) ~ ---------- * ( 1 + Poly(1/x**2) )
// x*sqrt(pi)
// We use rational approximation to approximate
// g(s)=f(1/x**2) = log(erfc(x)*x) - x*x + 0.5625
// Here is the error bound for R1/S1 and R2/S2
// |R1/S1 - f(x)| < 2**(-62.57)
// |R2/S2 - f(x)| < 2**(-61.52)
//
// 5. For inf > x >= 28
// erf(x) = sign(x) *(1 - tiny) (raise inexact)
// erfc(x) = tiny*tiny (raise underflow) if x > 0
// = 2 - tiny if x<0
//
// 7. Special case:
// erf(0) = 0, erf(inf) = 1, erf(-inf) = -1,
// erfc(0) = 1, erfc(inf) = 0, erfc(-inf) = 2,
// erfc/erf(NaN) is NaN
const (
erx = 8.45062911510467529297e-01 // 0x3FEB0AC160000000
// Coefficients for approximation to erf in [0, 0.84375]
efx = 1.28379167095512586316e-01 // 0x3FC06EBA8214DB69
efx8 = 1.02703333676410069053e+00 // 0x3FF06EBA8214DB69
pp0 = 1.28379167095512558561e-01 // 0x3FC06EBA8214DB68
pp1 = -3.25042107247001499370e-01 // 0xBFD4CD7D691CB913
pp2 = -2.84817495755985104766e-02 // 0xBF9D2A51DBD7194F
pp3 = -5.77027029648944159157e-03 // 0xBF77A291236668E4
pp4 = -2.37630166566501626084e-05 // 0xBEF8EAD6120016AC
qq1 = 3.97917223959155352819e-01 // 0x3FD97779CDDADC09
qq2 = 6.50222499887672944485e-02 // 0x3FB0A54C5536CEBA
qq3 = 5.08130628187576562776e-03 // 0x3F74D022C4D36B0F
qq4 = 1.32494738004321644526e-04 // 0x3F215DC9221C1A10
qq5 = -3.96022827877536812320e-06 // 0xBED09C4342A26120
// Coefficients for approximation to erf in [0.84375, 1.25]
pa0 = -2.36211856075265944077e-03 // 0xBF6359B8BEF77538
pa1 = 4.14856118683748331666e-01 // 0x3FDA8D00AD92B34D
pa2 = -3.72207876035701323847e-01 // 0xBFD7D240FBB8C3F1
pa3 = 3.18346619901161753674e-01 // 0x3FD45FCA805120E4
pa4 = -1.10894694282396677476e-01 // 0xBFBC63983D3E28EC
pa5 = 3.54783043256182359371e-02 // 0x3FA22A36599795EB
pa6 = -2.16637559486879084300e-03 // 0xBF61BF380A96073F
qa1 = 1.06420880400844228286e-01 // 0x3FBB3E6618EEE323
qa2 = 5.40397917702171048937e-01 // 0x3FE14AF092EB6F33
qa3 = 7.18286544141962662868e-02 // 0x3FB2635CD99FE9A7
qa4 = 1.26171219808761642112e-01 // 0x3FC02660E763351F
qa5 = 1.36370839120290507362e-02 // 0x3F8BEDC26B51DD1C
qa6 = 1.19844998467991074170e-02 // 0x3F888B545735151D
// Coefficients for approximation to erfc in [1.25, 1/0.35]
ra0 = -9.86494403484714822705e-03 // 0xBF843412600D6435
ra1 = -6.93858572707181764372e-01 // 0xBFE63416E4BA7360
ra2 = -1.05586262253232909814e+01 // 0xC0251E0441B0E726
ra3 = -6.23753324503260060396e+01 // 0xC04F300AE4CBA38D
ra4 = -1.62396669462573470355e+02 // 0xC0644CB184282266
ra5 = -1.84605092906711035994e+02 // 0xC067135CEBCCABB2
ra6 = -8.12874355063065934246e+01 // 0xC054526557E4D2F2
ra7 = -9.81432934416914548592e+00 // 0xC023A0EFC69AC25C
sa1 = 1.96512716674392571292e+01 // 0x4033A6B9BD707687
sa2 = 1.37657754143519042600e+02 // 0x4061350C526AE721
sa3 = 4.34565877475229228821e+02 // 0x407B290DD58A1A71
sa4 = 6.45387271733267880336e+02 // 0x40842B1921EC2868
sa5 = 4.29008140027567833386e+02 // 0x407AD02157700314
sa6 = 1.08635005541779435134e+02 // 0x405B28A3EE48AE2C
sa7 = 6.57024977031928170135e+00 // 0x401A47EF8E484A93
sa8 = -6.04244152148580987438e-02 // 0xBFAEEFF2EE749A62
// Coefficients for approximation to erfc in [1/.35, 28]
rb0 = -9.86494292470009928597e-03 // 0xBF84341239E86F4A
rb1 = -7.99283237680523006574e-01 // 0xBFE993BA70C285DE
rb2 = -1.77579549177547519889e+01 // 0xC031C209555F995A
rb3 = -1.60636384855821916062e+02 // 0xC064145D43C5ED98
rb4 = -6.37566443368389627722e+02 // 0xC083EC881375F228
rb5 = -1.02509513161107724954e+03 // 0xC09004616A2E5992
rb6 = -4.83519191608651397019e+02 // 0xC07E384E9BDC383F
sb1 = 3.03380607434824582924e+01 // 0x403E568B261D5190
sb2 = 3.25792512996573918826e+02 // 0x40745CAE221B9F0A
sb3 = 1.53672958608443695994e+03 // 0x409802EB189D5118
sb4 = 3.19985821950859553908e+03 // 0x40A8FFB7688C246A
sb5 = 2.55305040643316442583e+03 // 0x40A3F219CEDF3BE6
sb6 = 4.74528541206955367215e+02 // 0x407DA874E79FE763
sb7 = -2.24409524465858183362e+01 // 0xC03670E242712D62
)
// Erf returns the error function of x.
//
// Special cases are:
// Erf(+Inf) = 1
// Erf(-Inf) = -1
// Erf(NaN) = NaN
func Erf(x float64) float64 {
const (
VeryTiny = 2.848094538889218e-306 // 0x0080000000000000
Small = 1.0 / (1 << 28) // 2**-28
)
// special cases
switch {
case IsNaN(x):
return NaN()
case IsInf(x, 1):
return 1
case IsInf(x, -1):
return -1
}
sign := false
if x < 0 {
x = -x
sign = true
}
if x < 0.84375 { // |x| < 0.84375
var temp float64
if x < Small { // |x| < 2**-28
if x < VeryTiny {
temp = 0.125 * (8.0*x + efx8*x) // avoid underflow
} else {
temp = x + efx*x
}
} else {
z := x * x
r := pp0 + z*(pp1+z*(pp2+z*(pp3+z*pp4)))
s := 1 + z*(qq1+z*(qq2+z*(qq3+z*(qq4+z*qq5))))
y := r / s
temp = x + x*y
}
if sign {
return -temp
}
return temp
}
if x < 1.25 { // 0.84375 <= |x| < 1.25
s := x - 1
P := pa0 + s*(pa1+s*(pa2+s*(pa3+s*(pa4+s*(pa5+s*pa6)))))
Q := 1 + s*(qa1+s*(qa2+s*(qa3+s*(qa4+s*(qa5+s*qa6)))))
if sign {
return -erx - P/Q
}
return erx + P/Q
}
if x >= 6 { // inf > |x| >= 6
if sign {
return -1
}
return 1
}
s := 1 / (x * x)
var R, S float64
if x < 1/0.35 { // |x| < 1 / 0.35 ~ 2.857143
R = ra0 + s*(ra1+s*(ra2+s*(ra3+s*(ra4+s*(ra5+s*(ra6+s*ra7))))))
S = 1 + s*(sa1+s*(sa2+s*(sa3+s*(sa4+s*(sa5+s*(sa6+s*(sa7+s*sa8)))))))
} else { // |x| >= 1 / 0.35 ~ 2.857143
R = rb0 + s*(rb1+s*(rb2+s*(rb3+s*(rb4+s*(rb5+s*rb6)))))
S = 1 + s*(sb1+s*(sb2+s*(sb3+s*(sb4+s*(sb5+s*(sb6+s*sb7))))))
}
z := Float64frombits(Float64bits(x) & 0xffffffff00000000) // pseudo-single (20-bit) precision x
r := Exp(-z*z-0.5625) * Exp((z-x)*(z+x)+R/S)
if sign {
return r/x - 1
}
return 1 - r/x
}
// Erfc returns the complementary error function of x.
//
// Special cases are:
// Erfc(+Inf) = 0
// Erfc(-Inf) = 2
// Erfc(NaN) = NaN
func Erfc(x float64) float64 {
const Tiny = 1.0 / (1 << 56) // 2**-56
// special cases
switch {
case IsNaN(x):
return NaN()
case IsInf(x, 1):
return 0
case IsInf(x, -1):
return 2
}
sign := false
if x < 0 {
x = -x
sign = true
}
if x < 0.84375 { // |x| < 0.84375
var temp float64
if x < Tiny { // |x| < 2**-56
temp = x
} else {
z := x * x
r := pp0 + z*(pp1+z*(pp2+z*(pp3+z*pp4)))
s := 1 + z*(qq1+z*(qq2+z*(qq3+z*(qq4+z*qq5))))
y := r / s
if x < 0.25 { // |x| < 1/4
temp = x + x*y
} else {
temp = 0.5 + (x*y + (x - 0.5))
}
}
if sign {
return 1 + temp
}
return 1 - temp
}
if x < 1.25 { // 0.84375 <= |x| < 1.25
s := x - 1
P := pa0 + s*(pa1+s*(pa2+s*(pa3+s*(pa4+s*(pa5+s*pa6)))))
Q := 1 + s*(qa1+s*(qa2+s*(qa3+s*(qa4+s*(qa5+s*qa6)))))
if sign {
return 1 + erx + P/Q
}
return 1 - erx - P/Q
}
if x < 28 { // |x| < 28
s := 1 / (x * x)
var R, S float64
if x < 1/0.35 { // |x| < 1 / 0.35 ~ 2.857143
R = ra0 + s*(ra1+s*(ra2+s*(ra3+s*(ra4+s*(ra5+s*(ra6+s*ra7))))))
S = 1 + s*(sa1+s*(sa2+s*(sa3+s*(sa4+s*(sa5+s*(sa6+s*(sa7+s*sa8)))))))
} else { // |x| >= 1 / 0.35 ~ 2.857143
if sign && x > 6 {
return 2 // x < -6
}
R = rb0 + s*(rb1+s*(rb2+s*(rb3+s*(rb4+s*(rb5+s*rb6)))))
S = 1 + s*(sb1+s*(sb2+s*(sb3+s*(sb4+s*(sb5+s*(sb6+s*sb7))))))
}
z := Float64frombits(Float64bits(x) & 0xffffffff00000000) // pseudo-single (20-bit) precision x
r := Exp(-z*z-0.5625) * Exp((z-x)*(z+x)+R/S)
if sign {
return 2 - r/x
}
return r / x
}
if sign {
return 2
}
return 0
}
| shawnl/go | src/math/erf.go | GO | bsd-3-clause | 11,598 |
from django.core.exceptions import ImproperlyConfigured
from django.template import engines
from django.test import SimpleTestCase, override_settings
class TemplateStringsTests(SimpleTestCase):
@override_settings(TEMPLATES=[{
'BACKEND': 'raise.import.error',
}])
def test_backend_import_error(self):
"""
Failing to import a backend keeps raising the original import error.
Regression test for #24265.
"""
with self.assertRaises(ImportError):
engines.all()
with self.assertRaises(ImportError):
engines.all()
@override_settings(TEMPLATES=[{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
# Incorrect: APP_DIRS and loaders are mutually incompatible.
'APP_DIRS': True,
'OPTIONS': {'loaders': []},
}])
def test_backend_improperly_configured(self):
"""
Failing to initialize a backend keeps raising the original exception.
Regression test for #24265.
"""
with self.assertRaises(ImproperlyConfigured):
engines.all()
with self.assertRaises(ImproperlyConfigured):
engines.all()
@override_settings(TEMPLATES=[{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
}, {
'BACKEND': 'django.template.backends.django.DjangoTemplates',
}])
def test_backend_names_must_be_unique(self):
with self.assertRaises(ImproperlyConfigured):
engines.all()
| himleyb85/django | tests/template_backends/test_utils.py | Python | bsd-3-clause | 1,521 |
# -*- coding: utf-8 -*-
"""
A list of Mexican states for use as `choices` in a formfield.
This exists in this standalone file so that it's only imported into memory
when explicitly needed.
"""
from django.utils.translation import ugettext_lazy as _
STATE_CHOICES = (
('AGU', _(u'Aguascalientes')),
('BCN', _(u'Baja California')),
('BCS', _(u'Baja California Sur')),
('CAM', _(u'Campeche')),
('CHH', _(u'Chihuahua')),
('CHP', _(u'Chiapas')),
('COA', _(u'Coahuila')),
('COL', _(u'Colima')),
('DIF', _(u'Distrito Federal')),
('DUR', _(u'Durango')),
('GRO', _(u'Guerrero')),
('GUA', _(u'Guanajuato')),
('HID', _(u'Hidalgo')),
('JAL', _(u'Jalisco')),
('MEX', _(u'Estado de México')),
('MIC', _(u'Michoacán')),
('MOR', _(u'Morelos')),
('NAY', _(u'Nayarit')),
('NLE', _(u'Nuevo León')),
('OAX', _(u'Oaxaca')),
('PUE', _(u'Puebla')),
('QUE', _(u'Querétaro')),
('ROO', _(u'Quintana Roo')),
('SIN', _(u'Sinaloa')),
('SLP', _(u'San Luis Potosí')),
('SON', _(u'Sonora')),
('TAB', _(u'Tabasco')),
('TAM', _(u'Tamaulipas')),
('TLA', _(u'Tlaxcala')),
('VER', _(u'Veracruz')),
('YUC', _(u'Yucatán')),
('ZAC', _(u'Zacatecas')),
)
| bmander/dancecontraption | django/contrib/localflavor/mx/mx_states.py | Python | bsd-3-clause | 1,251 |
/*
* DateJS Culture String File
* Country Code: ar-MA
* Name: Arabic (Morocco)
* Format: "key" : "value"
* Key is the en-US term, Value is the Key in the current language.
*/
Date.CultureStrings = Date.CultureStrings || {};
Date.CultureStrings["ar-MA"] = {
"name": "ar-MA",
"englishName": "Arabic (Morocco)",
"nativeName": "العربية (المملكة المغربية)",
"Sunday": "الاحد",
"Monday": "الاثنين",
"Tuesday": "الثلاثاء",
"Wednesday": "الاربعاء",
"Thursday": "الخميس",
"Friday": "الجمعة",
"Saturday": "السبت",
"Sun": "الاحد",
"Mon": "الاثنين",
"Tue": "الثلاثاء",
"Wed": "الاربعاء",
"Thu": "الخميس",
"Fri": "الجمعة",
"Sat": "السبت",
"Su": "أ",
"Mo": "ا",
"Tu": "ث",
"We": "أ",
"Th": "خ",
"Fr": "ج",
"Sa": "س",
"S_Sun_Initial": "أ",
"M_Mon_Initial": "ا",
"T_Tue_Initial": "ث",
"W_Wed_Initial": "أ",
"T_Thu_Initial": "خ",
"F_Fri_Initial": "ج",
"S_Sat_Initial": "س",
"January": "يناير",
"February": "فبراير",
"March": "مارس",
"April": "ابريل",
"May": "ماي",
"June": "يونيو",
"July": "يوليوز",
"August": "غشت",
"September": "شتنبر",
"October": "اكتوبر",
"November": "نونبر",
"December": "دجنبر",
"Jan_Abbr": "يناير",
"Feb_Abbr": "فبراير",
"Mar_Abbr": "مارس",
"Apr_Abbr": "ابريل",
"May_Abbr": "ماي",
"Jun_Abbr": "يونيو",
"Jul_Abbr": "يوليوز",
"Aug_Abbr": "غشت",
"Sep_Abbr": "شتنبر",
"Oct_Abbr": "اكتوبر",
"Nov_Abbr": "نونبر",
"Dec_Abbr": "دجنبر",
"AM": "ص",
"PM": "م",
"firstDayOfWeek": 1,
"twoDigitYearMax": 2029,
"mdy": "dmy",
"M/d/yyyy": "dd-MM-yyyy",
"dddd, MMMM dd, yyyy": "dd MMMM, yyyy",
"h:mm tt": "H:mm",
"h:mm:ss tt": "H:mm:ss",
"dddd, MMMM dd, yyyy h:mm:ss tt": "dd MMMM, yyyy H:mm:ss",
"yyyy-MM-ddTHH:mm:ss": "yyyy-MM-ddTHH:mm:ss",
"yyyy-MM-dd HH:mm:ssZ": "yyyy-MM-dd HH:mm:ssZ",
"ddd, dd MMM yyyy HH:mm:ss": "ddd, dd MMM yyyy HH:mm:ss",
"MMMM dd": "dd MMMM",
"MMMM, yyyy": "MMMM, yyyy",
"/jan(uary)?/": "يناير",
"/feb(ruary)?/": "فبراير",
"/mar(ch)?/": "مارس",
"/apr(il)?/": "ابريل",
"/may/": "ماي",
"/jun(e)?/": "يونيو",
"/jul(y)?/": "يوليوز",
"/aug(ust)?/": "غشت",
"/sep(t(ember)?)?/": "شتنبر",
"/oct(ober)?/": "اكتوبر",
"/nov(ember)?/": "نونبر",
"/dec(ember)?/": "دجنبر",
"/^su(n(day)?)?/": "^الاحد",
"/^mo(n(day)?)?/": "^ا(1)?",
"/^tu(e(s(day)?)?)?/": "^الثلاثاء",
"/^we(d(nesday)?)?/": "^الاربعاء",
"/^th(u(r(s(day)?)?)?)?/": "^الخميس",
"/^fr(i(day)?)?/": "^الجمعة",
"/^sa(t(urday)?)?/": "^السبت",
"/^next/": "^next",
"/^last|past|prev(ious)?/": "^last|past|prev(ious)?",
"/^(\\+|aft(er)?|from|hence)/": "^(\\+|aft(er)?|from|hence)",
"/^(\\-|bef(ore)?|ago)/": "^(\\-|bef(ore)?|ago)",
"/^yes(terday)?/": "^yes(terday)?",
"/^t(od(ay)?)?/": "^t(od(ay)?)?",
"/^tom(orrow)?/": "^tom(orrow)?",
"/^n(ow)?/": "^n(ow)?",
"/^ms|milli(second)?s?/": "^ms|milli(second)?s?",
"/^sec(ond)?s?/": "^sec(ond)?s?",
"/^mn|min(ute)?s?/": "^mn|min(ute)?s?",
"/^h(our)?s?/": "^h(our)?s?",
"/^w(eek)?s?/": "^w(eek)?s?",
"/^m(onth)?s?/": "^m(onth)?s?",
"/^d(ay)?s?/": "^d(ay)?s?",
"/^y(ear)?s?/": "^y(ear)?s?",
"/^(a|p)/": "^(a|p)",
"/^(a\\.?m?\\.?|p\\.?m?\\.?)/": "^(a\\.?m?\\.?|p\\.?m?\\.?)",
"/^((e(s|d)t|c(s|d)t|m(s|d)t|p(s|d)t)|((gmt)?\\s*(\\+|\\-)\\s*\\d\\d\\d\\d?)|gmt|utc)/": "^((e(s|d)t|c(s|d)t|m(s|d)t|p(s|d)t)|((gmt)?\\s*(\\+|\\-)\\s*\\d\\d\\d\\d?)|gmt|utc)",
"/^\\s*(st|nd|rd|th)/": "^\\s*(st|nd|rd|th)",
"/^\\s*(\\:|a(?!u|p)|p)/": "^\\s*(\\:|a(?!u|p)|p)",
"LINT": "LINT",
"TOT": "TOT",
"CHAST": "CHAST",
"NZST": "NZST",
"NFT": "NFT",
"SBT": "SBT",
"AEST": "AEST",
"ACST": "ACST",
"JST": "JST",
"CWST": "CWST",
"CT": "CT",
"ICT": "ICT",
"MMT": "MMT",
"BIOT": "BST",
"NPT": "NPT",
"IST": "IST",
"PKT": "PKT",
"AFT": "AFT",
"MSK": "MSK",
"IRST": "IRST",
"FET": "FET",
"EET": "EET",
"CET": "CET",
"UTC": "UTC",
"GMT": "GMT",
"CVT": "CVT",
"GST": "GST",
"BRT": "BRT",
"NST": "NST",
"AST": "AST",
"EST": "EST",
"CST": "CST",
"MST": "MST",
"PST": "PST",
"AKST": "AKST",
"MIT": "MIT",
"HST": "HST",
"SST": "SST",
"BIT": "BIT",
"CHADT": "CHADT",
"NZDT": "NZDT",
"AEDT": "AEDT",
"ACDT": "ACDT",
"AZST": "AZST",
"IRDT": "IRDT",
"EEST": "EEST",
"CEST": "CEST",
"BST": "BST",
"PMDT": "PMDT",
"ADT": "ADT",
"NDT": "NDT",
"EDT": "EDT",
"CDT": "CDT",
"MDT": "MDT",
"PDT": "PDT",
"AKDT": "AKDT",
"HADT": "HADT"
};
Date.CultureStrings.lang = "ar-MA";
| TimSoftDev/RuangKita | vendor/bower/gentelella/vendors/DateJS/build/i18n/ar-MA.js | JavaScript | bsd-3-clause | 5,811 |
""" Information about platform and python version and compilers
This information is manly used to build directory names that
keep the object files and shared libaries straight when
multiple platforms share the same file system.
"""
from __future__ import absolute_import, print_function
import os
import sys
import subprocess
import distutils
from distutils.sysconfig import customize_compiler
from numpy.distutils.ccompiler import new_compiler
from numpy.distutils.core import setup
import distutils.bcppcompiler
#from numpy.distutils import mingw32_support
def dummy_dist():
# create a dummy distribution. It will look at any site configuration files
# and parse the command line to pick up any user configured stuff. The
# resulting Distribution object is returned from setup.
# Setting _setup_stop_after prevents the any commands from actually executing.
distutils.core._setup_stop_after = "commandline"
dist = setup(name="dummy")
distutils.core._setup_stop_after = None
return dist
def create_compiler_instance(dist):
# build_ext is in charge of building C/C++ files.
# We are using it and dist to parse config files, and command line
# configurations. There may be other ways to handle this, but I'm
# worried I may miss one of the steps in distutils if I do it my self.
#ext_builder = build_ext(dist)
#ext_builder.finalize_options ()
# For some reason the build_ext stuff wasn't picking up the compiler
# setting, so we grab it manually from the distribution object instead.
opts = dist.command_options.get('build_ext',None)
compiler_name = ''
if opts:
comp = opts.get('compiler',('',''))
compiler_name = comp[1]
# Create a new compiler, customize it based on the build settings,
# and return it.
if not compiler_name:
compiler_name = None
#print compiler_name
compiler = new_compiler(compiler=compiler_name)
customize_compiler(compiler)
return compiler
def compiler_exe_name(compiler):
exe_name = ''
# this is really ugly... Why aren't the attribute names
# standardized and used in a consistent way?
if hasattr(compiler, "compiler"):
# standard unix format
exe_name = compiler.compiler[0]
elif hasattr(compiler, "cc"):
exe_name = compiler.cc
elif compiler.__class__ is distutils.bcppcompiler.BCPPCompiler:
exe_name = 'brcc32'
return exe_name
def compiler_exe_path(exe_name):
exe_path = None
if os.path.exists(exe_name):
exe_path = exe_name
else:
path_string = os.environ['PATH']
path_string = os.path.expandvars(path_string)
path_string = os.path.expanduser(path_string)
paths = path_string.split(os.pathsep)
for path in paths:
path = os.path.join(path,exe_name)
if os.path.exists(path):
exe_path = path
break
# needed to catch gcc on mingw32 installations.
path = path + '.exe'
if os.path.exists(path):
exe_path = path
break
return exe_path
def check_sum(file):
from hashlib import sha256
try:
f = open(file,'r')
bytes = f.read(-1)
except IOError:
bytes = ''
chk_sum = sha256(bytes)
return chk_sum.hexdigest()[:32] # truncation needed, see gh-3216
def get_compiler_dir(compiler_name):
""" Try to figure out the compiler directory based on the
input compiler name. This is fragile and really should
be done at the distutils level inside the compiler. I
think it is only useful on windows at the moment.
"""
compiler_type = choose_compiler(compiler_name)
#print compiler_type
configure_sys_argv(compiler_type)
#print sys.argv
dist = dummy_dist()
compiler_obj = create_compiler_instance(dist)
#print compiler_obj.__class__
exe_name = compiler_exe_name(compiler_obj)
exe_path = compiler_exe_path(exe_name)
if not exe_path:
raise ValueError("The '%s' compiler was not found." % compiler_name)
chk_sum = check_sum(exe_path)
restore_sys_argv()
return 'compiler_'+chk_sum
#----------------------------------------------------------------------------
# Not needed -- used for testing.
#----------------------------------------------------------------------------
def choose_compiler(compiler_name=''):
""" Try and figure out which compiler is gonna be used on windows.
On other platforms, it just returns whatever value it is given.
converts 'gcc' to 'mingw32' on win32
"""
if not compiler_name:
compiler_name = ''
if sys.platform == 'win32':
if not compiler_name:
# On Windows, default to MSVC and use gcc if it wasn't found
# wasn't found. If neither are found, go with whatever
# the default is for distutils -- and probably fail...
if msvc_exists():
compiler_name = 'msvc'
elif gcc_exists():
compiler_name = 'mingw32'
elif compiler_name == 'gcc':
compiler_name = 'mingw32'
else:
# don't know how to force gcc -- look into this.
if compiler_name == 'gcc':
compiler_name = 'unix'
return compiler_name
old_argv = []
def configure_sys_argv(compiler_name):
# We're gonna play some tricks with argv here to pass info to distutils
# which is really built for command line use. better way??
global old_argv
try:
old_argv = sys.argv[:]
except AttributeError:
pass
sys.argv = ['','build_ext','--compiler='+compiler_name]
def restore_sys_argv():
sys.argv = old_argv
def gcc_exists(name='gcc'):
""" Test to make sure gcc is found
Does this return correct value on win98???
"""
result = 0
cmd = '%s -v' % name
try:
p = subprocess.Popen([str(name), '-v'], shell=True,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
str_result = p.stdout.read()
if 'Reading specs' in str_result:
result = 1
except:
# This was needed because the msvc compiler messes with
# the path variable. and will occasionlly mess things up
# so much that gcc is lost in the path. (Occurs in test
# scripts)
result = not os.system(cmd)
return result
def msvc_exists():
""" Determine whether MSVC is available on the machine.
"""
result = 0
try:
p = subprocess.Popen(['cl'], shell=True,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
str_result = p.stdout.read()
if 'Microsoft' in str_result:
result = 1
except:
#assume we're ok if devstudio exists
import distutils.msvccompiler
# There was a change to 'distutils.msvccompiler' between Python 2.2
# and Python 2.3.
#
# In Python 2.2 the function is 'get_devstudio_versions'
# In Python 2.3 the function is 'get_build_version'
try:
version = distutils.msvccompiler.get_devstudio_versions()
except:
version = distutils.msvccompiler.get_build_version()
if version:
result = 1
return result
if __name__ == "__main__":
"""
import time
t1 = time.time()
dist = dummy_dist()
compiler_obj = create_compiler_instance(dist)
exe_name = compiler_exe_name(compiler_obj)
exe_path = compiler_exe_path(exe_name)
chk_sum = check_sum(exe_path)
t2 = time.time()
print 'compiler exe:', exe_path
print 'check sum:', chk_sum
print 'time (sec):', t2 - t1
print
"""
path = get_compiler_dir('gcc')
print('gcc path:', path)
print()
try:
path = get_compiler_dir('msvc')
print('gcc path:', path)
except ValueError:
pass
| zaxliu/scipy | scipy/weave/platform_info.py | Python | bsd-3-clause | 7,940 |
/*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SampleCode.h"
#include "SkView.h"
#include "SkCanvas.h"
#include "SkGradientShader.h"
static SkShader* setgrad(const SkRect& r, SkColor c0, SkColor c1) {
SkColor colors[] = { c0, c1 };
SkPoint pts[] = { { r.fLeft, r.fTop }, { r.fRight, r.fTop } };
return SkGradientShader::CreateLinear(pts, colors, NULL, 2, SkShader::kClamp_TileMode);
}
static void test_alphagradients(SkCanvas* canvas) {
SkRect r;
r.set(SkIntToScalar(10), SkIntToScalar(10),
SkIntToScalar(410), SkIntToScalar(30));
SkPaint p, p2;
p2.setStyle(SkPaint::kStroke_Style);
p.setShader(setgrad(r, 0xFF00FF00, 0x0000FF00))->unref();
canvas->drawRect(r, p);
canvas->drawRect(r, p2);
r.offset(0, r.height() + SkIntToScalar(4));
p.setShader(setgrad(r, 0xFF00FF00, 0x00000000))->unref();
canvas->drawRect(r, p);
canvas->drawRect(r, p2);
r.offset(0, r.height() + SkIntToScalar(4));
p.setShader(setgrad(r, 0xFF00FF00, 0x00FF0000))->unref();
canvas->drawRect(r, p);
canvas->drawRect(r, p2);
}
///////////////////////////////////////////////////////////////////////////////
struct GradData {
int fCount;
const SkColor* fColors;
const SkScalar* fPos;
};
static const SkColor gColors[] = {
SK_ColorRED, SK_ColorGREEN, SK_ColorBLUE, SK_ColorWHITE, SK_ColorBLACK
};
static const SkScalar gPos0[] = { 0, SK_Scalar1 };
static const SkScalar gPos1[] = { SK_Scalar1/4, SK_Scalar1*3/4 };
static const SkScalar gPos2[] = {
0, SK_Scalar1/8, SK_Scalar1/2, SK_Scalar1*7/8, SK_Scalar1
};
static const GradData gGradData[] = {
{ 2, gColors, NULL },
{ 2, gColors, gPos0 },
{ 2, gColors, gPos1 },
{ 5, gColors, NULL },
{ 5, gColors, gPos2 }
};
static SkShader* MakeLinear(const SkPoint pts[2], const GradData& data, SkShader::TileMode tm) {
return SkGradientShader::CreateLinear(pts, data.fColors, data.fPos, data.fCount, tm);
}
static SkShader* MakeRadial(const SkPoint pts[2], const GradData& data, SkShader::TileMode tm) {
SkPoint center;
center.set(SkScalarAve(pts[0].fX, pts[1].fX),
SkScalarAve(pts[0].fY, pts[1].fY));
return SkGradientShader::CreateRadial(center, center.fX, data.fColors,
data.fPos, data.fCount, tm);
}
static SkShader* MakeSweep(const SkPoint pts[2], const GradData& data, SkShader::TileMode tm) {
SkPoint center;
center.set(SkScalarAve(pts[0].fX, pts[1].fX),
SkScalarAve(pts[0].fY, pts[1].fY));
return SkGradientShader::CreateSweep(center.fX, center.fY, data.fColors, data.fPos, data.fCount);
}
static SkShader* Make2Radial(const SkPoint pts[2], const GradData& data, SkShader::TileMode tm) {
SkPoint center0, center1;
center0.set(SkScalarAve(pts[0].fX, pts[1].fX),
SkScalarAve(pts[0].fY, pts[1].fY));
center1.set(SkScalarInterp(pts[0].fX, pts[1].fX, SkIntToScalar(3)/5),
SkScalarInterp(pts[0].fY, pts[1].fY, SkIntToScalar(1)/4));
return SkGradientShader::CreateTwoPointRadial(
center1, (pts[1].fX - pts[0].fX) / 7,
center0, (pts[1].fX - pts[0].fX) / 2,
data.fColors, data.fPos, data.fCount, tm);
}
static SkShader* Make2RadialConcentric(const SkPoint pts[2], const GradData& data,
SkShader::TileMode tm) {
SkPoint center;
center.set(SkScalarAve(pts[0].fX, pts[1].fX),
SkScalarAve(pts[0].fY, pts[1].fY));
return SkGradientShader::CreateTwoPointRadial(
center, (pts[1].fX - pts[0].fX) / 7,
center, (pts[1].fX - pts[0].fX) / 2,
data.fColors, data.fPos, data.fCount, tm);
}
typedef SkShader* (*GradMaker)(const SkPoint pts[2], const GradData& data, SkShader::TileMode tm);
static const GradMaker gGradMakers[] = {
MakeLinear, MakeRadial, MakeSweep, Make2Radial, Make2RadialConcentric
};
///////////////////////////////////////////////////////////////////////////////
class GradientsView : public SampleView {
public:
GradientsView() {
this->setBGColor(0xFFDDDDDD);
}
protected:
// overrides from SkEventSink
virtual bool onQuery(SkEvent* evt) {
if (SampleCode::TitleQ(*evt)) {
SampleCode::TitleR(evt, "Gradients");
return true;
}
return this->INHERITED::onQuery(evt);
}
virtual void onDrawContent(SkCanvas* canvas) {
SkPoint pts[2] = {
{ 0, 0 },
{ SkIntToScalar(100), SkIntToScalar(100) }
};
SkRect r = { 0, 0, SkIntToScalar(100), SkIntToScalar(100) };
SkPaint paint;
paint.setDither(true);
canvas->save();
canvas->translate(SkIntToScalar(20), SkIntToScalar(10));
for (int tm = 0; tm < SkShader::kTileModeCount; ++tm) {
canvas->save();
for (size_t i = 0; i < SK_ARRAY_COUNT(gGradData); i++) {
canvas->save();
for (size_t j = 0; j < SK_ARRAY_COUNT(gGradMakers); j++) {
SkShader* shader;
shader = gGradMakers[j](pts, gGradData[i], (SkShader::TileMode)tm);
paint.setShader(shader)->unref();
canvas->drawRect(r, paint);
canvas->translate(0, SkIntToScalar(120));
}
canvas->restore();
canvas->translate(SkIntToScalar(120), 0);
}
canvas->restore();
canvas->translate(SK_ARRAY_COUNT(gGradData)*SkIntToScalar(120), 0);
}
canvas->restore();
canvas->translate(0, SkIntToScalar(370));
if (false) { // avoid bit rot, suppress warning
test_alphagradients(canvas);
}
this->inval(NULL);
}
private:
typedef SampleView INHERITED;
};
///////////////////////////////////////////////////////////////////////////////
static SkView* MyFactory() { return new GradientsView; }
static SkViewRegister reg(MyFactory);
| SlimSaber/android_external_skia | samplecode/SampleGradients.cpp | C++ | bsd-3-clause | 6,226 |
/*
Copyright © 2001-2004 World Wide Web Consortium,
(Massachusetts Institute of Technology, European Research Consortium
for Informatics and Mathematics, Keio University). All
Rights Reserved. This work is distributed under the W3C® Software License [1] in the
hope that it will be useful, but WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
[1] http://www.w3.org/Consortium/Legal/2002/copyright-software-20021231
*/
/**
* Gets URI that identifies the test.
* @return uri identifier of test
*/
function getTargetURI() {
return "http://www.w3.org/2001/DOM-Test-Suite/level1/core/hc_domimplementationfeaturexml";
}
var docsLoaded = -1000000;
var builder = null;
//
// This function is called by the testing framework before
// running the test suite.
//
// If there are no configuration exceptions, asynchronous
// document loading is started. Otherwise, the status
// is set to complete and the exception is immediately
// raised when entering the body of the test.
//
function setUpPage() {
setUpPageStatus = 'running';
try {
//
// creates test document builder, may throw exception
//
builder = createConfiguredBuilder();
docsLoaded = 0;
var docRef = null;
if (typeof(this.doc) != 'undefined') {
docRef = this.doc;
}
docsLoaded += preload(docRef, "doc", "hc_staff");
if (docsLoaded == 1) {
setUpPageStatus = 'complete';
}
} catch(ex) {
catchInitializationError(builder, ex);
setUpPageStatus = 'complete';
}
}
//
// This method is called on the completion of
// each asychronous load started in setUpTests.
//
// When every synchronous loaded document has completed,
// the page status is changed which allows the
// body of the test to be executed.
function loadComplete() {
if (++docsLoaded == 1) {
setUpPageStatus = 'complete';
}
}
/**
*
Retrieve the entire DOM document and invoke its
"getImplementation()" method. This should create a
DOMImplementation object whose "hasFeature(feature,
version)" method is invoked with "feature" equal to "html" or "xml".
The method should return a boolean "true".
* @author Curt Arnold
* @see http://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/level-one-core#ID-5CED94D7
* @see http://www.w3.org/Bugs/Public/show_bug.cgi?id=245
*/
function hc_domimplementationfeaturexml() {
var success;
if(checkInitialization(builder, "hc_domimplementationfeaturexml") != null) return;
var doc;
var domImpl;
var state;
var docRef = null;
if (typeof(this.doc) != 'undefined') {
docRef = this.doc;
}
doc = load(docRef, "doc", "hc_staff");
domImpl = doc.implementation;
if(
(builder.contentType == "text/html")
) {
state = domImpl.hasFeature("html","1.0");
assertTrue("supports_html_1.0",state);
}
else {
state = domImpl.hasFeature("xml","1.0");
assertTrue("supports_xml_1.0",state);
}
}
function runTest() {
hc_domimplementationfeaturexml();
}
| hujiajie/chromium-crosswalk | third_party/WebKit/LayoutTests/dom/html/level1/core/hc_domimplementationfeaturexml.js | JavaScript | bsd-3-clause | 3,190 |
/*
Copyright © 2001-2004 World Wide Web Consortium,
(Massachusetts Institute of Technology, European Research Consortium
for Informatics and Mathematics, Keio University). All
Rights Reserved. This work is distributed under the W3C® Software License [1] in the
hope that it will be useful, but WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
[1] http://www.w3.org/Consortium/Legal/2002/copyright-software-20021231
*/
/**
* Gets URI that identifies the test.
* @return uri identifier of test
*/
function getTargetURI() {
return "http://www.w3.org/2001/DOM-Test-Suite/level2/html/HTMLTableColElement05";
}
var docsLoaded = -1000000;
var builder = null;
//
// This function is called by the testing framework before
// running the test suite.
//
// If there are no configuration exceptions, asynchronous
// document loading is started. Otherwise, the status
// is set to complete and the exception is immediately
// raised when entering the body of the test.
//
function setUpPage() {
setUpPageStatus = 'running';
try {
//
// creates test document builder, may throw exception
//
builder = createConfiguredBuilder();
docsLoaded = 0;
var docRef = null;
if (typeof(this.doc) != 'undefined') {
docRef = this.doc;
}
docsLoaded += preload(docRef, "doc", "tablecol");
if (docsLoaded == 1) {
setUpPageStatus = 'complete';
}
} catch(ex) {
catchInitializationError(builder, ex);
setUpPageStatus = 'complete';
}
}
//
// This method is called on the completion of
// each asychronous load started in setUpTests.
//
// When every synchronous loaded document has completed,
// the page status is changed which allows the
// body of the test to be executed.
function loadComplete() {
if (++docsLoaded == 1) {
setUpPageStatus = 'complete';
}
}
/**
*
The charoff attribute specifies offset of alignment character(COL).
Retrieve the charoff attribute from the COL element and examine
its value.
* @author NIST
* @author Mary Brady
* @see http://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/level-one-html#ID-57779225
*/
function HTMLTableColElement05() {
var success;
if(checkInitialization(builder, "HTMLTableColElement05") != null) return;
var nodeList;
var testNode;
var vchoff;
var doc;
var docRef = null;
if (typeof(this.doc) != 'undefined') {
docRef = this.doc;
}
doc = load(docRef, "doc", "tablecol");
nodeList = doc.getElementsByTagName("col");
assertSize("Asize",1,nodeList);
testNode = nodeList.item(0);
vchoff = testNode.chOff;
assertEquals("chLink","20",vchoff);
}
function runTest() {
HTMLTableColElement05();
}
| jtg-gg/blink | LayoutTests/dom/html/level2/html/HTMLTableColElement05.js | JavaScript | bsd-3-clause | 2,895 |
<!--
@license
Copyright (c) 2015 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
Code distributed by Google as part of the polymer project is also
subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
-->
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, minimum-scale=1.0, initial-scale=1.0, user-scalable=yes">
<script src="../../../webcomponentsjs/webcomponents-lite.js"></script>
<script src="../../../web-component-tester/browser.js"></script>
<link rel="import" href="../../platinum-sw-register.html">
<link rel="import" href="../../platinum-sw-import-script.html">
<link rel="import" href="../../platinum-sw-fetch.html">
</head>
<body>
<platinum-sw-register skip-waiting clients-claim auto-register>
<platinum-sw-fetch handler="custom203FetchHandler"
path="/(.*)customFetch"></platinum-sw-fetch>
<platinum-sw-fetch handler="custom410FetchHandler"
path="/(.*)customFetch"
origin="https://matching\.domain"></platinum-sw-fetch>
<platinum-sw-import-script href="custom-fetch-handler.js"></platinum-sw-import-script>
</platinum-sw-register>
<script>
suite('Service Worker Fetch Handlers', function() {
test('the same-origin custom fetch handler is used when the path matches', function() {
return navigator.serviceWorker.ready.then(function() {
return window.fetch('customFetch').then(function(response) {
assert.equal(response.status, 203, 'Custom response status doesn\'t match');
});
});
});
test('the same-origin custom fetch handler isn\'t used when the path doesn\t match', function() {
return navigator.serviceWorker.ready.then(function() {
return window.fetch('dummyUrlThatShould404').then(function(response) {
assert.equal(response.status, 404, 'Expected response status doesn\'t match');
});
});
});
test('the cross-origin fetch handler is used when the path and origin matches', function() {
return navigator.serviceWorker.ready.then(function() {
return window.fetch('https://matching.domain/path/to/customFetch').then(function(response) {
assert.equal(response.status, 410, 'Custom response status doesn\'t match');
});
});
});
});
</script>
</body>
</html>
| beeva-joseangelgomez/dojo-polymer | bower_components/platinum-sw/test/platinum-sw-fetch/index.html | HTML | bsd-3-clause | 2,820 |
"use strict";
exports.__esModule = true;
var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck");
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _binding = require("../binding");
var _binding2 = _interopRequireDefault(_binding);
var _babelTypes = require("babel-types");
var t = _interopRequireWildcard(_babelTypes);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var renameVisitor = {
ReferencedIdentifier: function ReferencedIdentifier(_ref, state) {
var node = _ref.node;
if (node.name === state.oldName) {
node.name = state.newName;
}
},
Scope: function Scope(path, state) {
if (!path.scope.bindingIdentifierEquals(state.oldName, state.binding.identifier)) {
path.skip();
}
},
"AssignmentExpression|Declaration": function AssignmentExpressionDeclaration(path, state) {
var ids = path.getOuterBindingIdentifiers();
for (var name in ids) {
if (name === state.oldName) ids[name].name = state.newName;
}
}
};
var Renamer = function () {
function Renamer(binding, oldName, newName) {
(0, _classCallCheck3.default)(this, Renamer);
this.newName = newName;
this.oldName = oldName;
this.binding = binding;
}
Renamer.prototype.maybeConvertFromExportDeclaration = function maybeConvertFromExportDeclaration(parentDeclar) {
var exportDeclar = parentDeclar.parentPath.isExportDeclaration() && parentDeclar.parentPath;
if (!exportDeclar) return;
var isDefault = exportDeclar.isExportDefaultDeclaration();
if (isDefault && (parentDeclar.isFunctionDeclaration() || parentDeclar.isClassDeclaration()) && !parentDeclar.node.id) {
parentDeclar.node.id = parentDeclar.scope.generateUidIdentifier("default");
}
var bindingIdentifiers = parentDeclar.getOuterBindingIdentifiers();
var specifiers = [];
for (var name in bindingIdentifiers) {
var localName = name === this.oldName ? this.newName : name;
var exportedName = isDefault ? "default" : name;
specifiers.push(t.exportSpecifier(t.identifier(localName), t.identifier(exportedName)));
}
var aliasDeclar = t.exportNamedDeclaration(null, specifiers);
if (parentDeclar.isFunctionDeclaration()) {
aliasDeclar._blockHoist = 3;
}
exportDeclar.insertAfter(aliasDeclar);
exportDeclar.replaceWith(parentDeclar.node);
};
Renamer.prototype.maybeConvertFromClassFunctionDeclaration = function maybeConvertFromClassFunctionDeclaration(path) {
return;
if (!path.isFunctionDeclaration() && !path.isClassDeclaration()) return;
if (this.binding.kind !== "hoisted") return;
path.node.id = t.identifier(this.oldName);
path.node._blockHoist = 3;
path.replaceWith(t.variableDeclaration("let", [t.variableDeclarator(t.identifier(this.newName), t.toExpression(path.node))]));
};
Renamer.prototype.maybeConvertFromClassFunctionExpression = function maybeConvertFromClassFunctionExpression(path) {
return;
if (!path.isFunctionExpression() && !path.isClassExpression()) return;
if (this.binding.kind !== "local") return;
path.node.id = t.identifier(this.oldName);
this.binding.scope.parent.push({
id: t.identifier(this.newName)
});
path.replaceWith(t.assignmentExpression("=", t.identifier(this.newName), path.node));
};
Renamer.prototype.rename = function rename(block) {
var binding = this.binding;
var oldName = this.oldName;
var newName = this.newName;
var scope = binding.scope;
var path = binding.path;
var parentDeclar = path.find(function (path) {
return path.isDeclaration() || path.isFunctionExpression();
});
if (parentDeclar) {
this.maybeConvertFromExportDeclaration(parentDeclar);
}
scope.traverse(block || scope.block, renameVisitor, this);
if (!block) {
scope.removeOwnBinding(oldName);
scope.bindings[newName] = binding;
this.binding.identifier.name = newName;
}
if (binding.type === "hoisted") {}
if (parentDeclar) {
this.maybeConvertFromClassFunctionDeclaration(parentDeclar);
this.maybeConvertFromClassFunctionExpression(parentDeclar);
}
};
return Renamer;
}();
exports.default = Renamer;
module.exports = exports["default"]; | tim-mc/quill | node_modules/babel-traverse/lib/scope/lib/renamer.js | JavaScript | bsd-3-clause | 4,596 |
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2013 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Mail\Storage\Folder;
interface FolderInterface
{
/**
* get root folder or given folder
*
* @param string $rootFolder get folder structure for given folder, else root
* @return FolderInterface root or wanted folder
*/
public function getFolders($rootFolder = null);
/**
* select given folder
*
* folder must be selectable!
*
* @param FolderInterface|string $globalName global name of folder or instance for subfolder
* @throws \Zend\Mail\Storage\Exception\ExceptionInterface
*/
public function selectFolder($globalName);
/**
* get Zend\Mail\Storage\Folder instance for current folder
*
* @return FolderInterface instance of current folder
* @throws \Zend\Mail\Storage\Exception\ExceptionInterface
*/
public function getCurrentFolder();
}
| nguyentanphat/Zend2Learn | vendor/ZF2/library/Zend/Mail/Storage/Folder/FolderInterface.php | PHP | bsd-3-clause | 1,175 |
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
package com.facebook.react.views.scroll;
import javax.annotation.Nullable;
import java.util.Map;
import com.facebook.react.bridge.ReadableArray;
import com.facebook.react.uimanager.PixelUtil;
import com.facebook.infer.annotation.Assertions;
import com.facebook.react.common.MapBuilder;
/**
* Helper for view managers to handle commands like 'scrollTo'.
* Shared by {@link ReactScrollViewManager} and {@link ReactHorizontalScrollViewManager}.
*/
public class ReactScrollViewCommandHelper {
public static final int COMMAND_SCROLL_TO = 1;
public interface ScrollCommandHandler<T> {
void scrollTo(T scrollView, ScrollToCommandData data);
}
public static class ScrollToCommandData {
public final int mDestX, mDestY;
public final boolean mAnimated;
ScrollToCommandData(int destX, int destY, boolean animated) {
mDestX = destX;
mDestY = destY;
mAnimated = animated;
}
}
public static Map<String,Integer> getCommandsMap() {
return MapBuilder.of(
"scrollTo",
COMMAND_SCROLL_TO);
}
public static <T> void receiveCommand(
ScrollCommandHandler<T> viewManager,
T scrollView,
int commandType,
@Nullable ReadableArray args) {
Assertions.assertNotNull(viewManager);
Assertions.assertNotNull(scrollView);
Assertions.assertNotNull(args);
switch (commandType) {
case COMMAND_SCROLL_TO: {
int destX = Math.round(PixelUtil.toPixelFromDIP(args.getDouble(0)));
int destY = Math.round(PixelUtil.toPixelFromDIP(args.getDouble(1)));
boolean animated = args.getBoolean(2);
viewManager.scrollTo(scrollView, new ScrollToCommandData(destX, destY, animated));
return;
}
default:
throw new IllegalArgumentException(String.format(
"Unsupported command %d received by %s.",
commandType,
viewManager.getClass().getSimpleName()));
}
}
}
| jolicloud/exponent | android/ReactAndroid/src/main/java/com/facebook/react/views/scroll/ReactScrollViewCommandHelper.java | Java | bsd-3-clause | 2,247 |
.edui-container{
position: relative;
border: 1px solid #d4d4d4;
box-shadow: 2px 2px 5px #d3d6da;
background-color: #fff;
}
.edui-container .edui-toolbar{
position: relative;
width:auto;
border-bottom: 1px solid #e1e1e1;
box-shadow: 2px 2px 5px #d3d6da;
background-color: #fafafa;
z-index: 99999;
}
.edui-toolbar .edui-btn-toolbar{
position: relative;
padding: 5px;
}
.edui-container .edui-editor-body{
background-color: #fff;
}
.edui-editor-body .edui-body-container{
}
.edui-editor-body .edui-body-container p{margin:5px 0;}
.edui-editor-body .edui-body-container{
border:0;
outline:none;
cursor:text;
padding:0 10px 0;
overflow:auto;
display:block;
word-wrap:break-word;
font-size:16px;
font-family:sans-serif;
}
.edui-editor-body.focus{border:1px solid #5c9dff}
.edui-editor-body table{margin:10px 0 10px;border-collapse:collapse;display:table;}
.edui-editor-body td{padding: 5px 10px;border: 1px solid #DDD;}
.edui-editor-body iframe.mathquill-embedded-latex{
border: 0px;
padding: 0px;
display: inline;
margin: 0px;
background: none;
vertical-align: middle;
width: 0px;
height: 0px;
}
/*普通按钮*/
.edui-btn-toolbar .edui-btn{
position: relative;
display: inline-block;
vertical-align: top;
*display: inline;
*zoom:1;
width:auto;
margin: 0 1px;
padding:1px;
border:none;
background: none;
}
.edui-btn-toolbar .edui-btn .edui-icon{
width: 20px;
height: 20px;
margin: 0;
padding:0;
background-repeat: no-repeat;
background-image: url(../images/icons.png);
background-image: url(../images/icons.gif) \9;
}
/*状态反射*/
.edui-btn-toolbar .edui-btn.edui-hover,
.edui-btn-toolbar .edui-btn.edui-active{
background-color: #d5e1f2;
padding: 0;
border: 1px solid #a3bde3;
_z-index: 1;
}
.edui-btn-toolbar .edui-btn.edui-disabled{
opacity: 0.3;
filter: alpha(opacity = 30);
}
.edui-btn-toolbar .edui-btn .edui-icon-source {
background-position:-260px -0px;
}
.edui-btn-toolbar .edui-btn .edui-icon-undo {
background-position: -160px 0;
}
.edui-btn-toolbar .edui-btn .edui-icon-redo {
background-position: -100px 0;
}
.edui-btn-toolbar .edui-btn .edui-icon-bold{
background-position: 0 0;
}
.edui-btn-toolbar .edui-btn .edui-icon-italic {
background-position: -60px 0;
}
.edui-btn-toolbar .edui-btn .edui-icon-underline {
background-position: -140px 0
}
.edui-btn-toolbar .edui-btn .edui-icon-strikethrough {
background-position: -120px 0;
}
.edui-btn-toolbar .edui-btn .edui-icon-superscript {
background-position: -620px 0;
}
.edui-btn-toolbar .edui-btn .edui-icon-subscript {
background-position: -600px 0;
}
.edui-btn-toolbar .edui-btn .edui-icon-font, .edui-btn-toolbar .edui-btn .edui-icon-forecolor {
background-position: -720px 0;
}
.edui-btn-toolbar .edui-btn .edui-icon-backcolor {
background-position: -760px 0;
}
.edui-btn-toolbar .edui-btn .edui-icon-insertorderedlist {
background-position: -80px 0;
}
.edui-btn-toolbar .edui-btn .edui-icon-insertunorderedlist {
background-position: -20px 0;
}
.edui-btn-toolbar .edui-btn .edui-icon-selectall {
background-position: -400px -20px;
}
.edui-btn-toolbar .edui-btn .edui-icon-cleardoc {
background-position: -520px 0;
}
.edui-btn-toolbar .edui-btn .edui-icon-paragraph {
background-position: -140px 0;
}
.edui-btn-toolbar .edui-btn .edui-icon-fontfamily {
background-position: -140px 0;
}
.edui-btn-toolbar .edui-btn .edui-icon-fontsize {
background-position: -140px 0;
}
.edui-btn-toolbar .edui-btn .edui-icon-justifyleft {
background-position: -460px 0;
}
.edui-btn-toolbar .edui-btn .edui-icon-justifycenter {
background-position: -420px 0;
}
.edui-btn-toolbar .edui-btn .edui-icon-justifyright {
background-position:-480px 0;
}
.edui-btn-toolbar .edui-btn .edui-icon-justifyjustify {
background-position: -440px 0;
}
.edui-btn-toolbar .edui-btn .edui-icon-link {
background-position: -500px 0;
}
.edui-btn-toolbar .edui-btn .edui-icon-unlink {
background-position: -640px 0;
}
.edui-btn-toolbar .edui-btn .edui-icon-image {
background-position: -380px 0;
}
.edui-btn-toolbar .edui-btn .edui-icon-emotion {
background-position: -60px -20px;
}
.edui-btn-toolbar .edui-btn .edui-icon-video {
background-position: -320px -20px;
}
.edui-btn-toolbar .edui-btn .edui-icon-map {
background-position: -40px -40px;
}
.edui-btn-toolbar .edui-btn .edui-icon-gmap {
background-position: -260px -40px;
}
.edui-btn-toolbar .edui-btn .edui-icon-horizontal {
background-position: -360px 0;
}
.edui-btn-toolbar .edui-btn .edui-icon-print {
background-position: -440px -20px;
}
.edui-btn-toolbar .edui-btn .edui-icon-preview {
background-position: -420px -20px;
}
.edui-btn-toolbar .edui-btn-fullscreen{
float:right;
}
.edui-btn-toolbar .edui-btn .edui-icon-fullscreen {
background-position: -100px -20px;
}
.edui-btn-toolbar .edui-btn .edui-icon-removeformat {
background-position: -580px 0;
}
.edui-btn-toolbar .edui-btn .edui-icon-drafts {
background-position: -560px 0;
}
.edui-btn-toolbar .edui-btn .edui-icon-formula {
background-position: -80px -20px;
}
.edui-btn-toolbar .edui-splitbutton{
position: relative;
display: inline-block ;
vertical-align: top;
*display: inline ;
*zoom:1;
margin:0 2px;
}
.edui-splitbutton .edui-btn{
margin: 0;
}
.edui-splitbutton .edui-caret{
position: relative;
display: inline-block ;
vertical-align: top;
*display: inline ;
*zoom:1;
width: 8px;
height: 20px;
background: url(../images/icons.png) -741px 0;
_background: url(../images/icons.gif) -741px 0;
}
.edui-btn-toolbar .edui-splitbutton,
.edui-btn-toolbar .edui-splitbutton{
_border: none;
}
/*状态反射*/
.edui-btn-toolbar .edui-splitbutton.edui-hover .edui-btn{
background-color: #d5e1f2;
}
.edui-btn-toolbar .edui-splitbutton.edui-disabled{
opacity: 0.3;
filter: alpha(opacity = 30);
}
.edui-btn-toolbar .edui-splitbutton.edui-disabled .edui-caret{
opacity: 0.3 \0;
filter: alpha(opacity = 30)\0;
}
.edui-btn-toolbar .edui-combobox{
border: 1px solid #CCC;
padding:0;
margin:0 2px;
line-height: 20px;
}
.edui-combobox .edui-button-label{
position: relative;
display: inline-block;
vertical-align: top;
*display: inline ;
*zoom:1;
width:60px;
height:20px;
line-height: 20px;
padding: 2px;
margin: 0;
font-size: 12px;
text-align: center;
cursor: default;
}
.edui-combobox .edui-button-spacing{
position: relative;
display: inline-block ;
vertical-align: top;
*display: inline ;
*zoom:1;
height:20px;
margin: 0;
padding:0 3px;
}
.edui-combobox .edui-caret{
position: relative;
display: inline-block ;
vertical-align: top;
*display: inline ;
*zoom:1;
height:20px;
width: 12px;
margin: 0;
padding: 0;
background: url(../images/icons.png) -741px 0;
_background: url(../images/icons.gif) -741px 0;
}
.edui-btn-toolbar .edui-combobox.edui-disabled{
opacity: 0.2;
filter: alpha(opacity = 20);
}
.edui-btn-toolbar .edui-combobox.edui-disabled .edui-button-label,
.edui-btn-toolbar .edui-combobox.edui-disabled .edui-caret{
opacity: 0.2 \0;
filter: alpha(opacity = 20)\0;
}
.edui-combobox-menu{
position: absolute;
top: 100%;
left: 0;
display: none;
list-style: none;
text-decoration: none;
margin: 0;
padding:5px;
background-color: #ffffff;
border: 1px solid #ccc;
font-size: 12px;
box-shadow: 2px 2px 5px #d3d6da;
min-width: 160px;
_width: 160px;
}
.edui-combobox-menu .edui-combobox-item {
display: block;
border: 1px solid white;
}
.edui-combobox-menu .edui-combobox-item-label {
height: 25px;
line-height: 25px;
display: inline-block;
_display: inline;
_zoom: 1;
margin-left: 10px;
}
.edui-combobox-menu .edui-combobox-item:hover, .edui-combobox-menu .edui-combobox-stack-item:hover, .edui-combobox-menu .edui-combobox-item-hover {
background-color: #d5e1f2;
padding: 0;
border: 1px solid #a3bde3;
}
.edui-combobox-menu .edui-combobox-item .edui-combobox-icon {
display: inline-block;
*zoom: 1;
*display: inline;
width: 24px;
height: 25px;
background: red;
vertical-align: bottom;
background: url(../images/ok.gif) no-repeat 1000px 1000px;
}
.edui-combobox-menu .edui-combobox-checked .edui-combobox-icon {
background-position: 10px 7px;
}
.edui-combobox-menu .edui-combobox-item-separator {
min-width: 160px;
height: 1px;
line-height: 1px;
overflow: hidden;
background: #d3d3d3;
margin: 5px 0;
*margin-top: -8px;
}
/* 字体样式校正 */
.edui-combobox-fontsize .edui-combobox-item-0.edui-combobox-checked .edui-combobox-icon {
background-position: 10px 7px;
}
.edui-combobox-fontsize .edui-combobox-item-1.edui-combobox-checked .edui-combobox-icon {
background-position: 10px 7px;
}
.edui-combobox-fontsize .edui-combobox-item-2.edui-combobox-checked .edui-combobox-icon {
background-position: 10px 7px;
}
.edui-combobox-fontsize .edui-combobox-item-3.edui-combobox-checked .edui-combobox-icon {
background-position: 10px 7px;
}
/* 24 */
.edui-combobox-fontsize .edui-combobox-item-4 .edui-combobox-item-label {
height: 27px;
line-height: 27px;
}
.edui-combobox-fontsize .edui-combobox-item-4.edui-combobox-checked .edui-combobox-icon {
background-position: 10px 5px;
}
/* 32 */
.edui-combobox-fontsize .edui-combobox-item-5 .edui-combobox-item-label {
height: 31px;
line-height: 31px;
}
.edui-combobox-fontsize .edui-combobox-item-5.edui-combobox-checked .edui-combobox-icon {
background-position: 10px 4px;
}
/* 48 */
.edui-combobox-fontsize .edui-combobox-item-6 .edui-combobox-item-label {
height: 47px;
line-height: 47px;
}
/*.edui-combobox-fontsize .edui-combobox-item-6 .edui-combobox-icon {*/
/*height: 25px;*/
/*margin-bottom: 11px;*/
/*}*/
/*.edui-combobox-fontsize .edui-combobox-item-6.edui-combobox-checked .edui-combobox-icon {*/
/*background-position: 10px 7px;*/
/*}*/
/* 段落样式校正 */
/* h1 */
.edui-combobox-paragraph .edui-combobox-item-1 .edui-combobox-item-label {
font-size: 32px;
height: 36px;
line-height: 36px;
}
.edui-combobox-paragraph .edui-combobox-item-1 .edui-combobox-icon {
height: 25px;
margin-bottom: 5px;
}
.edui-combobox-paragraph .edui-combobox-item-1.edui-combobox-checked .edui-combobox-icon {
background-position: 10px 7px;
}
/* h2 */
.edui-combobox-paragraph .edui-combobox-item-2 .edui-combobox-item-label {
font-size: 28px;
height: 27px;
line-height: 27px;
}
.edui-combobox-paragraph .edui-combobox-item-2 .edui-combobox-icon {
margin-bottom: 5px;
}
.edui-combobox-paragraph .edui-combobox-item-2.edui-combobox-checked .edui-combobox-icon {
background-position: 10px 10px;
}
/* h3 */
.edui-combobox-paragraph .edui-combobox-item-3 .edui-combobox-item-label {
font-size: 24px;
height: 25px;
line-height: 25px;
}
.edui-combobox-paragraph .edui-combobox-item-3 .edui-combobox-icon {
height: 25px;
margin-bottom: 5px;
}
.edui-combobox-paragraph .edui-combobox-item-3.edui-combobox-checked .edui-combobox-icon {
background-position: 10px 11px;
}
/* h4 */
.edui-combobox-paragraph .edui-combobox-item-4 .edui-combobox-item-label {
font-size: 18px;
height: 25px;
line-height: 25px;
}
.edui-combobox-paragraph .edui-combobox-item-4.edui-combobox-checked .edui-combobox-icon {
background-position: 10px 6px;
}
/* h5 */
.edui-combobox-paragraph .edui-combobox-item-5 .edui-combobox-item-label {
font-size: 16px;
}
/* h6 */
.edui-combobox-paragraph .edui-combobox-item-6 .edui-combobox-item-label {
font-size: 12px;
}
.edui-modal {
position: fixed;
_position: absolute;
top: 10%;
left: 50%;
border: 1px solid #acacac;
box-shadow: 2px 2px 5px #d3d6da;
background-color: #ffffff;
outline: 0;
}
.edui-modal-header {
padding: 5px 10px;
border-bottom: 1px solid #eee;
}
.edui-modal-header .edui-close {
float: right;
width:20px;
height:20px;
margin-top: 2px;
padding: 1px;
border: 0;
background: url("../images/close.png") no-repeat center center;
cursor: pointer;
}
.edui-modal-header .edui-close.edui-hover {
background-color: #d5e1f2;
padding:0;
border: 1px solid #a3bde3;
}
.edui-modal-header .edui-title {
margin: 0;
line-height: 25px;
font-size: 20px;
}
.edui-modal-body {
position: relative;
max-height: 400px;
font-size: 12px;
overflow-y: auto;
}
.edui-modal-footer {
float: right;
padding: 5px 15px 15px;
overflow: hidden;
}
.edui-modal-footer .edui-btn {
float: left;
height: 24px;
width: 96px;
margin: 0 10px;
background-color: #ffffff;
padding: 0;
border: 1px solid #ababab;
font-size: 12px;
line-height: 24px;
text-align: center;
cursor: pointer;
}
.edui-modal-footer .edui-btn.edui-hover{
background-color: #d5e1f2;
border: 1px solid #a3bde3;
}
.edui-modal-backdrop{
opacity: 0.5;
filter: alpha(opacity=50);
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
background-color: #c6c6c6;
}
.edui-modal .edui-modal-tip {
color: red;
position: absolute;
bottom: 10px;
left: 10px;
height: 30px;
line-height: 30px;
display: none;
}
/*图片上传*/
.edui-dialog-image-body {
width: 700px;
height: 400px;
}
/*插入视频*/
.edui-dialog-video-body{
width: 600px;
height: 350px;
}
/*谷歌地图*/
.edui-dialog-gmap-body{
width:550px;
height: 400px;
}
/*百度地图*/
.edui-dialog-map-body{
width:580px;
height: 400px;
}
/*链接*/
.edui-dialog-link-body{
width:400px;
height:200px;
}
.edui-popup{
display: none;
background: url('../images/pop-bg.png') repeat #fff;
padding: 2px;
}
.edui-popup .edui-popup-body{
border: 1px solid #bfbfbf;
background-color: #fff;
}
.edui-popup .edui-popup-caret{
width: 21px;
height: 11px;
}
.edui-popup .edui-popup-caret.up{
background:url('../images/caret.png') no-repeat 0 0;
}
.edui-popup .edui-popup-caret.down{
background:url('../images/caret.png') no-repeat 0 0;
}
.edui-tab-nav {
margin: 0;
padding:0;
border-bottom: 1px solid #ddd;
list-style: none;
height:30px;
}
.edui-tab-nav .edui-tab-item {
float:left;
margin-bottom: -1px;
margin-top: 1px;
margin-top: 0\9;
}
.edui-tab-nav .edui-tab-item .edui-tab-text{
display: block;
padding:8px 12px;
border: 1px solid transparent;
color: #0088cc;
text-decoration: none;
outline: 0;
_border:1px solid #fff ;
cursor: pointer;
}
.edui-tab-nav .edui-tab-item .edui-tab-text:FOCUS {
outline: none;
}
.edui-tab-nav .edui-tab-item.edui-active .edui-tab-text{
border: 1px solid #ddd;
border-bottom-color: transparent;
background-color: #fff;
padding:8px 12px;
color: #555555;
cursor: default;
}
.edui-tab-content .edui-tab-pane{
padding: 1px;
position: relative;
display: none;
background-color: #fff;
clear: both;
}
.edui-tab-content .edui-tab-pane.edui-active{
display: block;
}
.edui-btn-toolbar .edui-tooltip{
position: absolute;
padding: 5px 0;
display: none;
/*opacity: 0.8;*/
/*filter: alpha(opacity=80);*/
z-index: 99999;
}
.edui-tooltip .edui-tooltip-arrow{
position: absolute;
top: 0;
_top: -2px;
left: 50%;
width: 0;
height: 0;
padding: 0;
font-size:0;
margin-left: -5px;
border-color: transparent;
border-style: dashed dashed solid dashed;
border-bottom-color: #000000;
border-width: 0 5px 5px;
background: transparent;
}
.edui-tooltip .edui-tooltip-inner{
padding: 6px;
color: #ffffff;
text-align: center;
text-decoration: none;
font-size: 10px;
background-color: #000000;
white-space: nowrap;
line-height: 12px;
}
.edui-splitbutton-color-label {
width: 16px;
height: 3px;
position: absolute;
bottom: 2px;
left: 50%;
margin-left: -8px;
overflow: hidden;
line-height: 3px;
}
.edui-popup .edui-colorpicker {
margin: 10px;
font-size: 12px;
}
.edui-colorpicker .edui-colorpicker-topbar{
height: 27px;
width: 200px;
overflow: hidden;
}
.edui-colorpicker .edui-colorpicker-topbar .edui-colorpicker-preview{
height: 20px;
border: 1px inset black;
margin-left: 1px;
width: 128px;
float: left;
}
.edui-colorpicker .edui-colorpicker-topbar .edui-colorpicker-nocolor{
float: right;
margin-right: 1px;
font-size: 12px;
line-height: 14px;
height: 14px;
border: 1px solid #333;
padding: 3px 5px;
cursor: pointer;
}
.edui-colorpicker table{
border-collapse: collapse;
border-spacing: 2px;
}
.edui-colorpicker tr.edui-colorpicker-firstrow{
height: 30px;
}
.edui-colorpicker table td{
padding: 0 2px;
}
.edui-colorpicker table td .edui-colorpicker-colorcell{
display: block;
text-decoration: none;
color: black;
width: 14px;
height: 14px;
margin: 0;
cursor: pointer;
}
.edui-toolbar .edui-separator{
width: 2px;
height: 20px;
padding: 1px 2px;
background: url(../images/icons.png) -179px 1px;
background: url(../images/icons.gif) -179px 1px \9;
display: inline-block ;
vertical-align: top;
*display: inline ;
*zoom:1;
border:none;
} | XQ-quadrant/gbii | common/widgets/umeditor/assets/themes/default/css/umeditor.css | CSS | bsd-3-clause | 17,733 |
/* Add additional stylesheets below
-------------------------------------------------- */
/*
Bootstrap's documentation styles
Special styles for presenting Bootstrap's documentation and examples
*/
/* Body and structure
-------------------------------------------------- */
body {
position: relative;
padding-top: 90px;
background-color: #fff;
background-image: url(../img/grid-18px-masked.png);
background-repeat: repeat-x;
background-position: 0 40px;
}
/* Tweak navbar brand link to be super sleek
-------------------------------------------------- */
.navbar-fixed-top .brand {
padding-right: 0;
padding-left: 0;
margin-left: 20px;
float: right;
font-weight: bold;
color: #000;
text-shadow: 0 1px 0 rgba(255,255,255,.1), 0 0 30px rgba(255,255,255,.125);
-webkit-transition: all .2s linear;
-moz-transition: all .2s linear;
transition: all .2s linear;
}
.navbar-fixed-top .brand:hover {
text-decoration: none;
}
/* Space out sub-sections more
-------------------------------------------------- */
section {
padding-top: 60px;
}
/* Faded out hr */
hr.soften {
height: 1px;
margin: 54px 0;
background-image: -webkit-linear-gradient(left, rgba(0,0,0,0), rgba(0,0,0,.1), rgba(0,0,0,0));
background-image: -moz-linear-gradient(left, rgba(0,0,0,0), rgba(0,0,0,.1), rgba(0,0,0,0));
background-image: -ms-linear-gradient(left, rgba(0,0,0,0), rgba(0,0,0,.1), rgba(0,0,0,0));
background-image: -o-linear-gradient(left, rgba(0,0,0,0), rgba(0,0,0,.1), rgba(0,0,0,0));
border: 0;
}
/* Jumbotrons
-------------------------------------------------- */
.jumbotron {
position: relative;
}
.jumbotron h1 {
margin-bottom: 9px;
font-size: 81px;
font-weight: bold;
letter-spacing: -1px;
line-height: 1;
}
.jumbotron p {
margin-bottom: 18px;
font-weight: 300;
}
.jumbotron .btn-large {
font-size: 20px;
font-weight: normal;
padding: 14px 24px;
margin-right: 10px;
-webkit-border-radius: 6px;
-moz-border-radius: 6px;
border-radius: 6px;
}
.jumbotron .btn-large small {
font-size: 14px;
}
/* Masthead (docs home) */
.masthead {
padding-top: 36px;
margin-bottom: 72px;
}
.masthead h1,
.masthead p {
text-align: center;
}
.masthead h1 {
margin-bottom: 18px;
}
.masthead p {
margin-left: 5%;
margin-right: 5%;
font-size: 30px;
line-height: 36px;
}
/* Specific jumbotrons
------------------------- */
/* supporting docs pages */
.subhead {
padding-bottom: 0;
margin-bottom: 9px;
}
.subhead h1 {
font-size: 54px;
}
/* Subnav */
.subnav {
width: 100%;
height: 36px;
background-color: #eeeeee; /* Old browsers */
background-repeat: repeat-x; /* Repeat the gradient */
background-image: -moz-linear-gradient(top, #f5f5f5 0%, #eeeeee 100%); /* FF3.6+ */
background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#f5f5f5), color-stop(100%,#eeeeee)); /* Chrome,Safari4+ */
background-image: -webkit-linear-gradient(top, #f5f5f5 0%,#eeeeee 100%); /* Chrome 10+,Safari 5.1+ */
background-image: -ms-linear-gradient(top, #f5f5f5 0%,#eeeeee 100%); /* IE10+ */
background-image: -o-linear-gradient(top, #f5f5f5 0%,#eeeeee 100%); /* Opera 11.10+ */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#f5f5f5', endColorstr='#eeeeee',GradientType=0 ); /* IE6-9 */
background-image: linear-gradient(top, #f5f5f5 0%,#eeeeee 100%); /* W3C */
border: 1px solid #e5e5e5;
-webkit-border-radius: 4px;
-moz-border-radius: 4px;
border-radius: 4px;
}
.subnav .nav {
margin-bottom: 0;
}
.subnav .nav > li > a {
margin: 0;
padding-top: 11px;
padding-bottom: 11px;
border-left: 1px solid #f5f5f5;
border-right: 1px solid #e5e5e5;
-webkit-border-radius: 0;
-moz-border-radius: 0;
border-radius: 0;
}
.subnav .nav > .active > a,
.subnav .nav > .active > a:hover {
padding-left: 13px;
color: #777;
background-color: #e9e9e9;
border-right-color: #ddd;
border-left: 0;
-webkit-box-shadow: inset 0 3px 5px rgba(0,0,0,.05);
-moz-box-shadow: inset 0 3px 5px rgba(0,0,0,.05);
box-shadow: inset 0 3px 5px rgba(0,0,0,.05);
}
.subnav .nav > .active > a .caret,
.subnav .nav > .active > a:hover .caret {
border-top-color: #777;
}
.subnav .nav > li:first-child > a,
.subnav .nav > li:first-child > a:hover {
border-left: 0;
padding-left: 12px;
-webkit-border-radius: 4px 0 0 4px;
-moz-border-radius: 4px 0 0 4px;
border-radius: 4px 0 0 4px;
}
.subnav .nav > li:last-child > a {
border-right: 0;
}
.subnav .dropdown-menu {
-webkit-border-radius: 0 0 4px 4px;
-moz-border-radius: 0 0 4px 4px;
border-radius: 0 0 4px 4px;
}
/* Fixed subnav on scroll, but only for 980px and up (sorry IE!) */
@media (min-width: 980px) {
.subnav-fixed {
position: fixed;
top: 40px;
left: 0;
right: 0;
z-index: 1020; /* 10 less than .navbar-fixed to prevent any overlap */
border-color: #d5d5d5;
border-width: 0 0 1px; /* drop the border on the fixed edges */
-webkit-border-radius: 0;
-moz-border-radius: 0;
border-radius: 0;
-webkit-box-shadow: inset 0 1px 0 #fff, 0 1px 5px rgba(0,0,0,.1);
-moz-box-shadow: inset 0 1px 0 #fff, 0 1px 5px rgba(0,0,0,.1);
box-shadow: inset 0 1px 0 #fff, 0 1px 5px rgba(0,0,0,.1);
filter: progid:DXImageTransform.Microsoft.gradient(enabled=false); /* IE6-9 */
}
.subnav-fixed .nav {
width: 938px;
margin: 0 auto;
padding: 0 1px;
}
.subnav .nav > li:first-child > a,
.subnav .nav > li:first-child > a:hover {
-webkit-border-radius: 0;
-moz-border-radius: 0;
border-radius: 0;
}
}
/* Quick links
-------------------------------------------------- */
.bs-links {
margin: 36px 0;
}
.quick-links {
min-height: 30px;
margin: 0;
padding: 5px 20px;
list-style: none;
text-align: center;
overflow: hidden;
}
.quick-links:first-child {
min-height: 0;
}
.quick-links li {
display: inline;
margin: 0 5px;
color: #999;
}
.quick-links .github-btn,
.quick-links .tweet-btn,
.quick-links .follow-btn {
position: relative;
top: 5px;
}
/* Marketing section of Overview
-------------------------------------------------- */
.marketing .row {
margin-bottom: 9px;
}
.marketing h1 {
margin: 36px 0 27px;
font-size: 40px;
font-weight: 300;
text-align: center;
}
.marketing h2,
.marketing h3 {
font-weight: 300;
}
.marketing h2 {
font-size: 22px;
}
.marketing p {
margin-right: 10px;
}
.marketing .bs-icon {
float: left;
margin: 7px 10px 0 0;
opacity: .8;
}
.marketing .small-bs-icon {
float: left;
margin: 4px 5px 0 0;
}
/* Footer
-------------------------------------------------- */
.footer {
margin-top: 45px;
padding: 35px 0 36px;
border-top: 1px solid #e5e5e5;
}
.footer p {
margin-bottom: 0;
color: #555;
}
/* Special grid styles
-------------------------------------------------- */
.show-grid {
margin-top: 10px;
margin-bottom: 20px;
}
.show-grid [class*="span"] {
background-color: #eee;
text-align: center;
-webkit-border-radius: 3px;
-moz-border-radius: 3px;
border-radius: 3px;
min-height: 30px;
line-height: 30px;
}
.show-grid:hover [class*="span"] {
background: #ddd;
}
.show-grid .show-grid {
margin-top: 0;
margin-bottom: 0;
}
.show-grid .show-grid [class*="span"] {
background-color: #ccc;
}
/* Render mini layout previews
-------------------------------------------------- */
.mini-layout {
border: 1px solid #ddd;
-webkit-border-radius: 6px;
-moz-border-radius: 6px;
border-radius: 6px;
-webkit-box-shadow: 0 1px 2px rgba(0,0,0,.075);
-moz-box-shadow: 0 1px 2px rgba(0,0,0,.075);
box-shadow: 0 1px 2px rgba(0,0,0,.075);
}
.mini-layout {
height: 240px;
margin-bottom: 20px;
padding: 9px;
}
.mini-layout div {
-webkit-border-radius: 3px;
-moz-border-radius: 3px;
border-radius: 3px;
}
.mini-layout .mini-layout-body {
background-color: #dceaf4;
margin: 0 auto;
width: 70%;
height: 240px;
}
.mini-layout.fluid .mini-layout-sidebar,
.mini-layout.fluid .mini-layout-header,
.mini-layout.fluid .mini-layout-body {
float: left;
}
.mini-layout.fluid .mini-layout-sidebar {
background-color: #bbd8e9;
width: 20%;
height: 240px;
}
.mini-layout.fluid .mini-layout-body {
width: 77.5%;
margin-left: 2.5%;
}
/* Popover docs
-------------------------------------------------- */
.popover-well {
min-height: 160px;
}
.popover-well .popover {
display: block;
}
.popover-well .popover-wrapper {
width: 50%;
height: 160px;
float: left;
margin-left: 55px;
position: relative;
}
.popover-well .popover-menu-wrapper {
height: 80px;
}
.large-bird {
margin: 5px 0 0 310px;
opacity: .1;
}
/* Download page
-------------------------------------------------- */
.download .page-header {
margin-top: 36px;
}
.page-header .toggle-all {
margin-top: 5px;
}
/* Space out h3s when following a section */
.download h3 {
margin-bottom: 5px;
}
.download-builder input + h3,
.download-builder .checkbox + h3 {
margin-top: 9px;
}
/* Fields for variables */
.download-builder input[type=text] {
margin-bottom: 9px;
font-family: Menlo, Monaco, "Courier New", monospace;
font-size: 12px;
color: #d14;
}
.download-builder input[type=text]:focus {
background-color: #fff;
}
/* Custom, larger checkbox labels */
.download .checkbox {
padding: 6px 10px 6px 25px;
color: #555;
background-color: #f9f9f9;
-webkit-border-radius: 3px;
-moz-border-radius: 3px;
border-radius: 3px;
cursor: pointer;
}
.download .checkbox:hover {
color: #333;
background-color: #f5f5f5;
}
.download .checkbox small {
font-size: 12px;
color: #777;
}
/* Variables section */
#variables label {
margin-bottom: 0;
}
/* Giant download button */
.download-btn {
margin: 36px 0 108px;
}
#download p,
#download h4 {
max-width: 50%;
margin: 0 auto;
color: #999;
text-align: center;
}
#download h4 {
margin-bottom: 0;
}
#download p {
margin-bottom: 18px;
}
.download-btn .btn {
display: block;
width: auto;
padding: 19px 24px;
margin-bottom: 27px;
font-size: 30px;
line-height: 1;
text-align: center;
-webkit-border-radius: 6px;
-moz-border-radius: 6px;
border-radius: 6px;
}
/* Color swatches on LESS docs page
-------------------------------------------------- */
/* Sets the width of the td */
.swatch-col {
width: 30px;
}
/* Le swatch */
.swatch {
display: inline-block;
width: 30px;
height: 20px;
margin: -6px 0;
-webkit-border-radius: 3px;
-moz-border-radius: 3px;
border-radius: 3px;
}
/* For white swatches, give a border */
.swatch-bordered {
width: 28px;
height: 18px;
border: 1px solid #eee;
}
/* Misc
-------------------------------------------------- */
img {
max-width: 100%;
}
/* Make tables spaced out a bit more */
h2 + table,
h3 + table,
h4 + table,
h2 + .row {
margin-top: 5px;
}
/* Example sites showcase */
.example-sites img {
max-width: 100%;
margin: 0 auto;
}
.marketing-byline {
margin: -18px 0 27px;
font-size: 18px;
font-weight: 300;
line-height: 24px;
color: #999;
text-align: center;
}
.scrollspy-example {
height: 200px;
overflow: auto;
position: relative;
}
/* Remove bottom margin on example forms in wells */
form.well {
padding: 14px;
}
/* Tighten up spacing */
.well hr {
margin: 18px 0;
}
/* Fake the :focus state to demo it */
.focused {
border-color: rgba(82,168,236,.8);
-webkit-box-shadow: inset 0 1px 3px rgba(0,0,0,.1), 0 0 8px rgba(82,168,236,.6);
-moz-box-shadow: inset 0 1px 3px rgba(0,0,0,.1), 0 0 8px rgba(82,168,236,.6);
box-shadow: inset 0 1px 3px rgba(0,0,0,.1), 0 0 8px rgba(82,168,236,.6);
outline: 0;
}
/* For input sizes, make them display block */
.docs-input-sizes select,
.docs-input-sizes input[type=text] {
display: block;
margin-bottom: 9px;
}
/* Icons
------------------------- */
.the-icons {
margin-left: 0;
list-style: none;
}
.the-icons i:hover {
background-color: rgba(255,0,0,.25);
}
/* Eaxmples page
------------------------- */
.bootstrap-examples .thumbnail {
margin-bottom: 9px;
background-color: #fff;
}
/* Responsive table
------------------------- */
.responsive-utilities th small {
display: block;
font-weight: normal;
color: #999;
}
.responsive-utilities tbody th {
font-weight: normal;
}
.responsive-utilities td {
text-align: center;
}
.responsive-utilities td.is-visible {
color: #468847;
background-color: #dff0d8 !important;
}
.responsive-utilities td.is-hidden {
color: #ccc;
background-color: #f9f9f9 !important;
}
/* Responsive tests
------------------------- */
.responsive-utilities-test {
margin-top: 5px;
margin-left: 0;
list-style: none;
overflow: hidden; /* clear floats */
}
.responsive-utilities-test li {
position: relative;
float: left;
width: 25%;
height: 43px;
font-size: 14px;
font-weight: bold;
line-height: 43px;
color: #999;
text-align: center;
border: 1px solid #ddd;
-webkit-border-radius: 4px;
-moz-border-radius: 4px;
border-radius: 4px;
}
.responsive-utilities-test li + li {
margin-left: 10px;
}
.responsive-utilities-test span {
position: absolute;
top: -1px;
left: -1px;
right: -1px;
bottom: -1px;
-webkit-border-radius: 4px;
-moz-border-radius: 4px;
border-radius: 4px;
}
.responsive-utilities-test span {
color: #468847;
background-color: #dff0d8;
border: 1px solid #d6e9c6;
}
/* Responsive Docs
-------------------------------------------------- */
@media (max-width: 480px) {
/* Reduce padding above jumbotron */
body {
padding-top: 70px;
}
/* Change up some type stuff */
h2 {
margin-top: 27px;
}
h2 small {
display: block;
line-height: 18px;
}
h3 {
margin-top: 18px;
}
/* Adjust the jumbotron */
.jumbotron h1,
.jumbotron p {
text-align: center;
margin-right: 0;
}
.jumbotron h1 {
font-size: 45px;
margin-right: 0;
}
.jumbotron p {
margin-right: 0;
margin-left: 0;
font-size: 18px;
line-height: 24px;
}
.jumbotron .btn {
display: block;
font-size: 18px;
padding: 10px 14px;
margin: 0 auto 10px;
}
/* Masthead (home page jumbotron) */
.masthead {
padding-top: 0;
}
/* Don't space out quick links so much */
.quick-links {
margin: 40px 0 0;
}
/* hide the bullets on mobile since our horizontal space is limited */
.quick-links .divider {
display: none;
}
/* center example sites */
.example-sites {
margin-left: 0;
}
.example-sites > li {
float: none;
display: block;
max-width: 280px;
margin: 0 auto 18px;
text-align: center;
}
.example-sites .thumbnail > img {
max-width: 270px;
}
table code {
white-space: normal;
word-wrap: break-word;
word-break: break-all;
}
/* Modal example */
.modal-example .modal {
position: relative;
top: auto;
right: auto;
bottom: auto;
left: auto;
}
}
@media (max-width: 768px) {
/* Remove any padding from the body */
body {
padding-top: 0;
}
/* Jumbotron buttons */
.jumbotron .btn {
margin-bottom: 10px;
}
/* Subnav */
.subnav {
position: static;
top: auto;
z-index: auto;
width: auto;
height: auto;
background: #fff; /* whole background property since we use a background-image for gradient */
-webkit-box-shadow: none;
-moz-box-shadow: none;
box-shadow: none;
}
.subnav .nav > li {
float: none;
}
.subnav .nav > li > a {
border: 0;
}
.subnav .nav > li + li > a {
border-top: 1px solid #e5e5e5;
}
.subnav .nav > li:first-child > a,
.subnav .nav > li:first-child > a:hover {
-webkit-border-radius: 4px 4px 0 0;
-moz-border-radius: 4px 4px 0 0;
border-radius: 4px 4px 0 0;
}
/* Popovers */
.large-bird {
display: none;
}
.popover-well .popover-wrapper {
margin-left: 0;
}
/* Space out the show-grid examples */
.show-grid [class*="span"] {
margin-bottom: 5px;
}
/* Unfloat the back to top link in footer */
.footer .pull-right {
float: none;
}
.footer p {
margin-bottom: 9px;
}
}
@media (min-width: 480px) and (max-width: 768px) {
/* Scale down the jumbotron content */
.jumbotron h1 {
font-size: 54px;
}
.jumbotron p {
margin-right: 0;
margin-left: 0;
}
}
@media (min-width: 768px) and (max-width: 980px) {
/* Remove any padding from the body */
body {
padding-top: 0;
}
/* Scale down the jumbotron content */
.jumbotron h1 {
font-size: 72px;
}
}
@media (max-width: 980px) {
/* Unfloat brand */
.navbar-fixed-top .brand {
float: left;
margin-left: 0;
padding-left: 10px;
padding-right: 10px;
}
/* Inline-block quick links for more spacing */
.quick-links li {
display: inline-block;
margin: 5px;
}
}
/* LARGE DESKTOP SCREENS */
@media (min-width: 1210px) {
/* Update subnav container */
.subnav-fixed .nav {
width: 1168px; /* 2px less to account for left/right borders being removed when in fixed mode */
}
}
| torrange/sipml5 | assets/css/docs.css | CSS | bsd-3-clause | 17,243 |
"""SCons.Tool.pyext
Tool-specific initialization for python extensions builder.
AUTHORS:
- David Cournapeau
- Dag Sverre Seljebotn
"""
#
# __COPYRIGHT__
#
# 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.
#
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
import sys
import SCons
from SCons.Tool import SourceFileScanner, ProgramScanner
# Create common python builders
def createPythonObjectBuilder(env):
"""This is a utility function that creates the PythonObject Builder in an
Environment if it is not there already.
If it is already there, we return the existing one.
"""
try:
pyobj = env['BUILDERS']['PythonObject']
except KeyError:
pyobj = SCons.Builder.Builder(action = {},
emitter = {},
prefix = '$PYEXTOBJPREFIX',
suffix = '$PYEXTOBJSUFFIX',
src_builder = ['CFile', 'CXXFile'],
source_scanner = SourceFileScanner,
single_source = 1)
env['BUILDERS']['PythonObject'] = pyobj
return pyobj
def createPythonExtensionBuilder(env):
"""This is a utility function that creates the PythonExtension Builder in
an Environment if it is not there already.
If it is already there, we return the existing one.
"""
try:
pyext = env['BUILDERS']['PythonExtension']
except KeyError:
import SCons.Action
import SCons.Defaults
action = SCons.Action.Action("$PYEXTLINKCOM", "$PYEXTLINKCOMSTR")
action_list = [ SCons.Defaults.SharedCheck,
action]
pyext = SCons.Builder.Builder(action = action_list,
emitter = "$SHLIBEMITTER",
prefix = '$PYEXTPREFIX',
suffix = '$PYEXTSUFFIX',
target_scanner = ProgramScanner,
src_suffix = '$PYEXTOBJSUFFIX',
src_builder = 'PythonObject')
env['BUILDERS']['PythonExtension'] = pyext
return pyext
def pyext_coms(platform):
"""Return PYEXTCCCOM, PYEXTCXXCOM and PYEXTLINKCOM for the given
platform."""
if platform == 'win32':
pyext_cccom = "$PYEXTCC /Fo$TARGET /c $PYEXTCCSHARED "\
"$PYEXTCFLAGS $PYEXTCCFLAGS $_CCCOMCOM "\
"$_PYEXTCPPINCFLAGS $SOURCES"
pyext_cxxcom = "$PYEXTCXX /Fo$TARGET /c $PYEXTCSHARED "\
"$PYEXTCXXFLAGS $PYEXTCCFLAGS $_CCCOMCOM "\
"$_PYEXTCPPINCFLAGS $SOURCES"
pyext_linkcom = '${TEMPFILE("$PYEXTLINK $PYEXTLINKFLAGS '\
'/OUT:$TARGET.windows $( $_LIBDIRFLAGS $) '\
'$_LIBFLAGS $_PYEXTRUNTIME $SOURCES.windows")}'
else:
pyext_cccom = "$PYEXTCC -o $TARGET -c $PYEXTCCSHARED "\
"$PYEXTCFLAGS $PYEXTCCFLAGS $_CCCOMCOM "\
"$_PYEXTCPPINCFLAGS $SOURCES"
pyext_cxxcom = "$PYEXTCXX -o $TARGET -c $PYEXTCSHARED "\
"$PYEXTCXXFLAGS $PYEXTCCFLAGS $_CCCOMCOM "\
"$_PYEXTCPPINCFLAGS $SOURCES"
pyext_linkcom = "$PYEXTLINK -o $TARGET $PYEXTLINKFLAGS "\
"$SOURCES $_LIBDIRFLAGS $_LIBFLAGS $_PYEXTRUNTIME"
if platform == 'darwin':
pyext_linkcom += ' $_FRAMEWORKPATH $_FRAMEWORKS $FRAMEWORKSFLAGS'
return pyext_cccom, pyext_cxxcom, pyext_linkcom
def set_basic_vars(env):
# Set construction variables which are independant on whether we are using
# distutils or not.
env['PYEXTCPPPATH'] = SCons.Util.CLVar('$PYEXTINCPATH')
env['_PYEXTCPPINCFLAGS'] = '$( ${_concat(INCPREFIX, PYEXTCPPPATH, '\
'INCSUFFIX, __env__, RDirs, TARGET, SOURCE)} $)'
env['PYEXTOBJSUFFIX'] = '$SHOBJSUFFIX'
env['PYEXTOBJPREFIX'] = '$SHOBJPREFIX'
env['PYEXTRUNTIME'] = SCons.Util.CLVar("")
# XXX: this should be handled with different flags
env['_PYEXTRUNTIME'] = '$( ${_concat(LIBLINKPREFIX, PYEXTRUNTIME, '\
'LIBLINKSUFFIX, __env__)} $)'
# XXX: This won't work in all cases (using mingw, for example). To make
# this work, we need to know whether PYEXTCC accepts /c and /Fo or -c -o.
# This is difficult with the current way tools work in scons.
pycc, pycxx, pylink = pyext_coms(sys.platform)
env['PYEXTLINKFLAGSEND'] = SCons.Util.CLVar('$LINKFLAGSEND')
env['PYEXTCCCOM'] = pycc
env['PYEXTCXXCOM'] = pycxx
env['PYEXTLINKCOM'] = pylink
def _set_configuration_nodistutils(env):
# Set env variables to sensible values when not using distutils
def_cfg = {'PYEXTCC' : '$SHCC',
'PYEXTCFLAGS' : '$SHCFLAGS',
'PYEXTCCFLAGS' : '$SHCCFLAGS',
'PYEXTCXX' : '$SHCXX',
'PYEXTCXXFLAGS' : '$SHCXXFLAGS',
'PYEXTLINK' : '$LDMODULE',
'PYEXTSUFFIX' : '$LDMODULESUFFIX',
'PYEXTPREFIX' : ''}
if sys.platform == 'darwin':
def_cfg['PYEXTSUFFIX'] = '.so'
for k, v in def_cfg.items():
ifnotset(env, k, v)
ifnotset(env, 'PYEXT_ALLOW_UNDEFINED',
SCons.Util.CLVar('$ALLOW_UNDEFINED'))
ifnotset(env, 'PYEXTLINKFLAGS', SCons.Util.CLVar('$LDMODULEFLAGS'))
env.AppendUnique(PYEXTLINKFLAGS = env['PYEXT_ALLOW_UNDEFINED'])
def ifnotset(env, name, value):
if not env.has_key(name):
env[name] = value
def set_configuration(env, use_distutils):
"""Set construction variables which are platform dependants.
If use_distutils == True, use distutils configuration. Otherwise, use
'sensible' default.
Any variable already defined is untouched."""
# We define commands as strings so that we can either execute them using
# eval (same python for scons and distutils) or by executing them through
# the shell.
dist_cfg = {'PYEXTCC': ("sysconfig.get_config_var('CC')", False),
'PYEXTCFLAGS': ("sysconfig.get_config_var('CFLAGS')", True),
'PYEXTCCSHARED': ("sysconfig.get_config_var('CCSHARED')", False),
'PYEXTLINKFLAGS': ("sysconfig.get_config_var('LDFLAGS')", True),
'PYEXTLINK': ("sysconfig.get_config_var('LDSHARED')", False),
'PYEXTINCPATH': ("sysconfig.get_python_inc()", False),
'PYEXTSUFFIX': ("sysconfig.get_config_var('SO')", False)}
from distutils import sysconfig
# We set the python path even when not using distutils, because we rarely
# want to change this, even if not using distutils
ifnotset(env, 'PYEXTINCPATH', sysconfig.get_python_inc())
if use_distutils:
for k, (v, should_split) in dist_cfg.items():
val = eval(v)
if should_split:
val = val.split()
ifnotset(env, k, val)
else:
_set_configuration_nodistutils(env)
def generate(env):
"""Add Builders and construction variables for python extensions to an
Environment."""
if not env.has_key('PYEXT_USE_DISTUTILS'):
env['PYEXT_USE_DISTUTILS'] = False
# This sets all constructions variables used for pyext builders.
set_basic_vars(env)
set_configuration(env, env['PYEXT_USE_DISTUTILS'])
# Create the PythonObject builder
pyobj = createPythonObjectBuilder(env)
action = SCons.Action.Action("$PYEXTCCCOM", "$PYEXTCCCOMSTR")
pyobj.add_emitter('.c', SCons.Defaults.SharedObjectEmitter)
pyobj.add_action('.c', action)
action = SCons.Action.Action("$PYEXTCXXCOM", "$PYEXTCXXCOMSTR")
pyobj.add_emitter('$CXXFILESUFFIX', SCons.Defaults.SharedObjectEmitter)
pyobj.add_action('$CXXFILESUFFIX', action)
# Create the PythonExtension builder
createPythonExtensionBuilder(env)
def exists(env):
try:
# This is not quite right: if someone defines all variables by himself,
# it would work without distutils
from distutils import sysconfig
return True
except ImportError:
return False
| bright-sparks/chromium-spacewalk | third_party/cython/src/Tools/site_scons/site_tools/pyext.py | Python | bsd-3-clause | 9,274 |
<?php
/*
* This file is part of PHPUnit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* A TestRunner for the Command Line Interface (CLI)
* PHP SAPI Module.
*
* @since Class available since Release 3.0.0
*/
class PHPUnit_TextUI_Command
{
/**
* @var array
*/
protected $arguments = [
'listGroups' => false,
'listSuites' => false,
'loader' => null,
'useDefaultConfiguration' => true
];
/**
* @var array
*/
protected $options = [];
/**
* @var array
*/
protected $longOptions = [
'atleast-version=' => null,
'bootstrap=' => null,
'colors==' => null,
'columns=' => null,
'configuration=' => null,
'coverage-clover=' => null,
'coverage-crap4j=' => null,
'coverage-html=' => null,
'coverage-php=' => null,
'coverage-text==' => null,
'coverage-xml=' => null,
'debug' => null,
'disallow-test-output' => null,
'disallow-resource-usage' => null,
'disallow-todo-tests' => null,
'enforce-time-limit' => null,
'exclude-group=' => null,
'filter=' => null,
'generate-configuration' => null,
'group=' => null,
'help' => null,
'include-path=' => null,
'list-groups' => null,
'list-suites' => null,
'loader=' => null,
'log-json=' => null,
'log-junit=' => null,
'log-tap=' => null,
'log-teamcity=' => null,
'no-configuration' => null,
'no-coverage' => null,
'no-globals-backup' => null,
'printer=' => null,
'process-isolation' => null,
'repeat=' => null,
'report-useless-tests' => null,
'reverse-list' => null,
'static-backup' => null,
'stderr' => null,
'stop-on-error' => null,
'stop-on-failure' => null,
'stop-on-warning' => null,
'stop-on-incomplete' => null,
'stop-on-risky' => null,
'stop-on-skipped' => null,
'fail-on-warning' => null,
'fail-on-risky' => null,
'strict-coverage' => null,
'disable-coverage-ignore' => null,
'strict-global-state' => null,
'tap' => null,
'teamcity' => null,
'testdox' => null,
'testdox-group=' => null,
'testdox-exclude-group=' => null,
'testdox-html=' => null,
'testdox-text=' => null,
'testdox-xml=' => null,
'test-suffix=' => null,
'testsuite=' => null,
'verbose' => null,
'version' => null,
'whitelist=' => null
];
/**
* @var bool
*/
private $versionStringPrinted = false;
/**
* @param bool $exit
*/
public static function main($exit = true)
{
$command = new static;
return $command->run($_SERVER['argv'], $exit);
}
/**
* @param array $argv
* @param bool $exit
*
* @return int
*/
public function run(array $argv, $exit = true)
{
$this->handleArguments($argv);
$runner = $this->createRunner();
if (is_object($this->arguments['test']) &&
$this->arguments['test'] instanceof PHPUnit_Framework_Test) {
$suite = $this->arguments['test'];
} else {
$suite = $runner->getTest(
$this->arguments['test'],
$this->arguments['testFile'],
$this->arguments['testSuffixes']
);
}
if ($this->arguments['listGroups']) {
$this->printVersionString();
print "Available test group(s):\n";
$groups = $suite->getGroups();
sort($groups);
foreach ($groups as $group) {
print " - $group\n";
}
if ($exit) {
exit(PHPUnit_TextUI_TestRunner::SUCCESS_EXIT);
} else {
return PHPUnit_TextUI_TestRunner::SUCCESS_EXIT;
}
}
if ($this->arguments['listSuites']) {
$this->printVersionString();
print "Available test suite(s):\n";
$configuration = PHPUnit_Util_Configuration::getInstance(
$this->arguments['configuration']
);
$suiteNames = $configuration->getTestSuiteNames();
foreach ($suiteNames as $suiteName) {
print " - $suiteName\n";
}
if ($exit) {
exit(PHPUnit_TextUI_TestRunner::SUCCESS_EXIT);
} else {
return PHPUnit_TextUI_TestRunner::SUCCESS_EXIT;
}
}
unset($this->arguments['test']);
unset($this->arguments['testFile']);
try {
$result = $runner->doRun($suite, $this->arguments, $exit);
} catch (PHPUnit_Framework_Exception $e) {
print $e->getMessage() . "\n";
}
$return = PHPUnit_TextUI_TestRunner::FAILURE_EXIT;
if (isset($result) && $result->wasSuccessful()) {
$return = PHPUnit_TextUI_TestRunner::SUCCESS_EXIT;
} elseif (!isset($result) || $result->errorCount() > 0) {
$return = PHPUnit_TextUI_TestRunner::EXCEPTION_EXIT;
}
return $return;
}
/**
* Create a TestRunner, override in subclasses.
*
* @return PHPUnit_TextUI_TestRunner
*
* @since Method available since Release 3.6.0
*/
protected function createRunner()
{
return new PHPUnit_TextUI_TestRunner($this->arguments['loader']);
}
/**
* Handles the command-line arguments.
*
* A child class of PHPUnit_TextUI_Command can hook into the argument
* parsing by adding the switch(es) to the $longOptions array and point to a
* callback method that handles the switch(es) in the child class like this
*
* <code>
* <?php
* class MyCommand extends PHPUnit_TextUI_Command
* {
* public function __construct()
* {
* // my-switch won't accept a value, it's an on/off
* $this->longOptions['my-switch'] = 'myHandler';
* // my-secondswitch will accept a value - note the equals sign
* $this->longOptions['my-secondswitch='] = 'myOtherHandler';
* }
*
* // --my-switch -> myHandler()
* protected function myHandler()
* {
* }
*
* // --my-secondswitch foo -> myOtherHandler('foo')
* protected function myOtherHandler ($value)
* {
* }
*
* // You will also need this - the static keyword in the
* // PHPUnit_TextUI_Command will mean that it'll be
* // PHPUnit_TextUI_Command that gets instantiated,
* // not MyCommand
* public static function main($exit = true)
* {
* $command = new static;
*
* return $command->run($_SERVER['argv'], $exit);
* }
*
* }
* </code>
*
* @param array $argv
*/
protected function handleArguments(array $argv)
{
if (defined('__PHPUNIT_PHAR__')) {
$this->longOptions['check-version'] = null;
$this->longOptions['selfupdate'] = null;
$this->longOptions['self-update'] = null;
$this->longOptions['selfupgrade'] = null;
$this->longOptions['self-upgrade'] = null;
}
try {
$this->options = PHPUnit_Util_Getopt::getopt(
$argv,
'd:c:hv',
array_keys($this->longOptions)
);
} catch (PHPUnit_Framework_Exception $e) {
$this->showError($e->getMessage());
}
foreach ($this->options[0] as $option) {
switch ($option[0]) {
case '--colors':
$this->arguments['colors'] = $option[1] ?: PHPUnit_TextUI_ResultPrinter::COLOR_AUTO;
break;
case '--bootstrap':
$this->arguments['bootstrap'] = $option[1];
break;
case '--columns':
if (is_numeric($option[1])) {
$this->arguments['columns'] = (int) $option[1];
} elseif ($option[1] == 'max') {
$this->arguments['columns'] = 'max';
}
break;
case 'c':
case '--configuration':
$this->arguments['configuration'] = $option[1];
break;
case '--coverage-clover':
$this->arguments['coverageClover'] = $option[1];
break;
case '--coverage-crap4j':
$this->arguments['coverageCrap4J'] = $option[1];
break;
case '--coverage-html':
$this->arguments['coverageHtml'] = $option[1];
break;
case '--coverage-php':
$this->arguments['coveragePHP'] = $option[1];
break;
case '--coverage-text':
if ($option[1] === null) {
$option[1] = 'php://stdout';
}
$this->arguments['coverageText'] = $option[1];
$this->arguments['coverageTextShowUncoveredFiles'] = false;
$this->arguments['coverageTextShowOnlySummary'] = false;
break;
case '--coverage-xml':
$this->arguments['coverageXml'] = $option[1];
break;
case 'd':
$ini = explode('=', $option[1]);
if (isset($ini[0])) {
if (isset($ini[1])) {
ini_set($ini[0], $ini[1]);
} else {
ini_set($ini[0], true);
}
}
break;
case '--debug':
$this->arguments['debug'] = true;
break;
case 'h':
case '--help':
$this->showHelp();
exit(PHPUnit_TextUI_TestRunner::SUCCESS_EXIT);
break;
case '--filter':
$this->arguments['filter'] = $option[1];
break;
case '--testsuite':
$this->arguments['testsuite'] = $option[1];
break;
case '--generate-configuration':
$this->printVersionString();
printf(
"Generating phpunit.xml in %s\n\n",
getcwd()
);
print 'Bootstrap script (relative to path shown above; default: vendor/autoload.php): ';
$bootstrapScript = trim(fgets(STDIN));
print 'Tests directory (relative to path shown above; default: tests): ';
$testsDirectory = trim(fgets(STDIN));
print 'Source directory (relative to path shown above; default: src): ';
$src = trim(fgets(STDIN));
if ($bootstrapScript == '') {
$bootstrapScript = 'vendor/autoload.php';
}
if ($testsDirectory == '') {
$testsDirectory = 'tests';
}
if ($src == '') {
$src = 'src';
}
$generator = new PHPUnit_Util_ConfigurationGenerator;
file_put_contents(
'phpunit.xml',
$generator->generateDefaultConfiguration(
PHPUnit_Runner_Version::series(),
$bootstrapScript,
$testsDirectory,
$src
)
);
printf(
"\nGenerated phpunit.xml in %s\n",
getcwd()
);
exit(PHPUnit_TextUI_TestRunner::SUCCESS_EXIT);
break;
case '--group':
$this->arguments['groups'] = explode(',', $option[1]);
break;
case '--exclude-group':
$this->arguments['excludeGroups'] = explode(
',',
$option[1]
);
break;
case '--test-suffix':
$this->arguments['testSuffixes'] = explode(
',',
$option[1]
);
break;
case '--include-path':
$includePath = $option[1];
break;
case '--list-groups':
$this->arguments['listGroups'] = true;
break;
case '--list-suites':
$this->arguments['listSuites'] = true;
break;
case '--printer':
$this->arguments['printer'] = $option[1];
break;
case '--loader':
$this->arguments['loader'] = $option[1];
break;
case '--log-json':
$this->arguments['jsonLogfile'] = $option[1];
break;
case '--log-junit':
$this->arguments['junitLogfile'] = $option[1];
break;
case '--log-tap':
$this->arguments['tapLogfile'] = $option[1];
break;
case '--log-teamcity':
$this->arguments['teamcityLogfile'] = $option[1];
break;
case '--process-isolation':
$this->arguments['processIsolation'] = true;
break;
case '--repeat':
$this->arguments['repeat'] = (int) $option[1];
break;
case '--stderr':
$this->arguments['stderr'] = true;
break;
case '--stop-on-error':
$this->arguments['stopOnError'] = true;
break;
case '--stop-on-failure':
$this->arguments['stopOnFailure'] = true;
break;
case '--stop-on-warning':
$this->arguments['stopOnWarning'] = true;
break;
case '--stop-on-incomplete':
$this->arguments['stopOnIncomplete'] = true;
break;
case '--stop-on-risky':
$this->arguments['stopOnRisky'] = true;
break;
case '--stop-on-skipped':
$this->arguments['stopOnSkipped'] = true;
break;
case '--fail-on-warning':
$this->arguments['failOnWarning'] = true;
break;
case '--fail-on-risky':
$this->arguments['failOnRisky'] = true;
break;
case '--tap':
$this->arguments['printer'] = 'PHPUnit_Util_Log_TAP';
break;
case '--teamcity':
$this->arguments['printer'] = 'PHPUnit_Util_Log_TeamCity';
break;
case '--testdox':
$this->arguments['printer'] = 'PHPUnit_Util_TestDox_ResultPrinter_Text';
break;
case '--testdox-group':
$this->arguments['testdoxGroups'] = explode(
',',
$option[1]
);
break;
case '--testdox-exclude-group':
$this->arguments['testdoxExcludeGroups'] = explode(
',',
$option[1]
);
break;
case '--testdox-html':
$this->arguments['testdoxHTMLFile'] = $option[1];
break;
case '--testdox-text':
$this->arguments['testdoxTextFile'] = $option[1];
break;
case '--testdox-xml':
$this->arguments['testdoxXMLFile'] = $option[1];
break;
case '--no-configuration':
$this->arguments['useDefaultConfiguration'] = false;
break;
case '--no-coverage':
$this->arguments['noCoverage'] = true;
break;
case '--no-globals-backup':
$this->arguments['backupGlobals'] = false;
break;
case '--static-backup':
$this->arguments['backupStaticAttributes'] = true;
break;
case 'v':
case '--verbose':
$this->arguments['verbose'] = true;
break;
case '--atleast-version':
exit(version_compare(PHPUnit_Runner_Version::id(), $option[1], '>=')
? PHPUnit_TextUI_TestRunner::SUCCESS_EXIT
: PHPUnit_TextUI_TestRunner::FAILURE_EXIT
);
break;
case '--version':
$this->printVersionString();
exit(PHPUnit_TextUI_TestRunner::SUCCESS_EXIT);
break;
case '--report-useless-tests':
$this->arguments['reportUselessTests'] = true;
break;
case '--strict-coverage':
$this->arguments['strictCoverage'] = true;
break;
case '--disable-coverage-ignore':
$this->arguments['disableCodeCoverageIgnore'] = true;
break;
case '--strict-global-state':
$this->arguments['beStrictAboutChangesToGlobalState'] = true;
break;
case '--disallow-test-output':
$this->arguments['disallowTestOutput'] = true;
break;
case '--disallow-resource-usage':
$this->arguments['beStrictAboutResourceUsageDuringSmallTests'] = true;
break;
case '--enforce-time-limit':
$this->arguments['enforceTimeLimit'] = true;
break;
case '--disallow-todo-tests':
$this->arguments['disallowTodoAnnotatedTests'] = true;
break;
case '--reverse-list':
$this->arguments['reverseList'] = true;
break;
case '--check-version':
$this->handleVersionCheck();
break;
case '--selfupdate':
case '--self-update':
$this->handleSelfUpdate();
break;
case '--selfupgrade':
case '--self-upgrade':
$this->handleSelfUpdate(true);
break;
case '--whitelist':
$this->arguments['whitelist'] = $option[1];
break;
default:
$optionName = str_replace('--', '', $option[0]);
if (isset($this->longOptions[$optionName])) {
$handler = $this->longOptions[$optionName];
} elseif (isset($this->longOptions[$optionName . '='])) {
$handler = $this->longOptions[$optionName . '='];
}
if (isset($handler) && is_callable([$this, $handler])) {
$this->$handler($option[1]);
}
}
}
$this->handleCustomTestSuite();
if (!isset($this->arguments['test'])) {
if (isset($this->options[1][0])) {
$this->arguments['test'] = $this->options[1][0];
}
if (isset($this->options[1][1])) {
$this->arguments['testFile'] = realpath($this->options[1][1]);
} else {
$this->arguments['testFile'] = '';
}
if (isset($this->arguments['test']) &&
is_file($this->arguments['test']) &&
substr($this->arguments['test'], -5, 5) != '.phpt') {
$this->arguments['testFile'] = realpath($this->arguments['test']);
$this->arguments['test'] = substr($this->arguments['test'], 0, strrpos($this->arguments['test'], '.'));
}
}
if (!isset($this->arguments['testSuffixes'])) {
$this->arguments['testSuffixes'] = ['Test.php', '.phpt'];
}
if (isset($includePath)) {
ini_set(
'include_path',
$includePath . PATH_SEPARATOR . ini_get('include_path')
);
}
if ($this->arguments['loader'] !== null) {
$this->arguments['loader'] = $this->handleLoader($this->arguments['loader']);
}
if (isset($this->arguments['configuration']) &&
is_dir($this->arguments['configuration'])) {
$configurationFile = $this->arguments['configuration'] . '/phpunit.xml';
if (file_exists($configurationFile)) {
$this->arguments['configuration'] = realpath(
$configurationFile
);
} elseif (file_exists($configurationFile . '.dist')) {
$this->arguments['configuration'] = realpath(
$configurationFile . '.dist'
);
}
} elseif (!isset($this->arguments['configuration']) &&
$this->arguments['useDefaultConfiguration']) {
if (file_exists('phpunit.xml')) {
$this->arguments['configuration'] = realpath('phpunit.xml');
} elseif (file_exists('phpunit.xml.dist')) {
$this->arguments['configuration'] = realpath(
'phpunit.xml.dist'
);
}
}
if (isset($this->arguments['configuration'])) {
try {
$configuration = PHPUnit_Util_Configuration::getInstance(
$this->arguments['configuration']
);
} catch (Throwable $e) {
print $e->getMessage() . "\n";
exit(PHPUnit_TextUI_TestRunner::FAILURE_EXIT);
} catch (Exception $e) {
print $e->getMessage() . "\n";
exit(PHPUnit_TextUI_TestRunner::FAILURE_EXIT);
}
$phpunitConfiguration = $configuration->getPHPUnitConfiguration();
$configuration->handlePHPConfiguration();
/*
* Issue #1216
*/
if (isset($this->arguments['bootstrap'])) {
$this->handleBootstrap($this->arguments['bootstrap']);
} elseif (isset($phpunitConfiguration['bootstrap'])) {
$this->handleBootstrap($phpunitConfiguration['bootstrap']);
}
/*
* Issue #657
*/
if (isset($phpunitConfiguration['stderr']) && ! isset($this->arguments['stderr'])) {
$this->arguments['stderr'] = $phpunitConfiguration['stderr'];
}
if (isset($phpunitConfiguration['columns']) && ! isset($this->arguments['columns'])) {
$this->arguments['columns'] = $phpunitConfiguration['columns'];
}
if (!isset($this->arguments['printer']) && isset($phpunitConfiguration['printerClass'])) {
if (isset($phpunitConfiguration['printerFile'])) {
$file = $phpunitConfiguration['printerFile'];
} else {
$file = '';
}
$this->arguments['printer'] = $this->handlePrinter(
$phpunitConfiguration['printerClass'],
$file
);
}
if (isset($phpunitConfiguration['testSuiteLoaderClass'])) {
if (isset($phpunitConfiguration['testSuiteLoaderFile'])) {
$file = $phpunitConfiguration['testSuiteLoaderFile'];
} else {
$file = '';
}
$this->arguments['loader'] = $this->handleLoader(
$phpunitConfiguration['testSuiteLoaderClass'],
$file
);
}
if (!isset($this->arguments['test'])) {
$testSuite = $configuration->getTestSuiteConfiguration(isset($this->arguments['testsuite']) ? $this->arguments['testsuite'] : null);
if ($testSuite !== null) {
$this->arguments['test'] = $testSuite;
}
}
} elseif (isset($this->arguments['bootstrap'])) {
$this->handleBootstrap($this->arguments['bootstrap']);
}
if (isset($this->arguments['printer']) &&
is_string($this->arguments['printer'])) {
$this->arguments['printer'] = $this->handlePrinter($this->arguments['printer']);
}
if (isset($this->arguments['test']) && is_string($this->arguments['test']) && substr($this->arguments['test'], -5, 5) == '.phpt') {
$test = new PHPUnit_Extensions_PhptTestCase($this->arguments['test']);
$this->arguments['test'] = new PHPUnit_Framework_TestSuite;
$this->arguments['test']->addTest($test);
}
if (!isset($this->arguments['test']) ||
(isset($this->arguments['testDatabaseLogRevision']) && !isset($this->arguments['testDatabaseDSN']))) {
$this->showHelp();
exit(PHPUnit_TextUI_TestRunner::EXCEPTION_EXIT);
}
}
/**
* Handles the loading of the PHPUnit_Runner_TestSuiteLoader implementation.
*
* @param string $loaderClass
* @param string $loaderFile
*
* @return PHPUnit_Runner_TestSuiteLoader
*/
protected function handleLoader($loaderClass, $loaderFile = '')
{
if (!class_exists($loaderClass, false)) {
if ($loaderFile == '') {
$loaderFile = PHPUnit_Util_Filesystem::classNameToFilename(
$loaderClass
);
}
$loaderFile = stream_resolve_include_path($loaderFile);
if ($loaderFile) {
require $loaderFile;
}
}
if (class_exists($loaderClass, false)) {
$class = new ReflectionClass($loaderClass);
if ($class->implementsInterface('PHPUnit_Runner_TestSuiteLoader') &&
$class->isInstantiable()) {
return $class->newInstance();
}
}
if ($loaderClass == 'PHPUnit_Runner_StandardTestSuiteLoader') {
return;
}
$this->showError(
sprintf(
'Could not use "%s" as loader.',
$loaderClass
)
);
}
/**
* Handles the loading of the PHPUnit_Util_Printer implementation.
*
* @param string $printerClass
* @param string $printerFile
*
* @return PHPUnit_Util_Printer
*/
protected function handlePrinter($printerClass, $printerFile = '')
{
if (!class_exists($printerClass, false)) {
if ($printerFile == '') {
$printerFile = PHPUnit_Util_Filesystem::classNameToFilename(
$printerClass
);
}
$printerFile = stream_resolve_include_path($printerFile);
if ($printerFile) {
require $printerFile;
}
}
if (class_exists($printerClass)) {
$class = new ReflectionClass($printerClass);
if ($class->implementsInterface('PHPUnit_Framework_TestListener') &&
$class->isSubclassOf('PHPUnit_Util_Printer') &&
$class->isInstantiable()) {
if ($class->isSubclassOf('PHPUnit_TextUI_ResultPrinter')) {
return $printerClass;
}
$outputStream = isset($this->arguments['stderr']) ? 'php://stderr' : null;
return $class->newInstance($outputStream);
}
}
$this->showError(
sprintf(
'Could not use "%s" as printer.',
$printerClass
)
);
}
/**
* Loads a bootstrap file.
*
* @param string $filename
*/
protected function handleBootstrap($filename)
{
try {
PHPUnit_Util_Fileloader::checkAndLoad($filename);
} catch (PHPUnit_Framework_Exception $e) {
$this->showError($e->getMessage());
}
}
/**
* @since Method available since Release 4.0.0
*/
protected function handleSelfUpdate($upgrade = false)
{
$this->printVersionString();
$localFilename = realpath($_SERVER['argv'][0]);
if (!is_writable($localFilename)) {
print 'No write permission to update ' . $localFilename . "\n";
exit(PHPUnit_TextUI_TestRunner::EXCEPTION_EXIT);
}
if (!extension_loaded('openssl')) {
print "The OpenSSL extension is not loaded.\n";
exit(PHPUnit_TextUI_TestRunner::EXCEPTION_EXIT);
}
if (!$upgrade) {
$remoteFilename = sprintf(
'https://phar.phpunit.de/phpunit-%s.phar',
file_get_contents(
sprintf(
'https://phar.phpunit.de/latest-version-of/phpunit-%s',
PHPUnit_Runner_Version::series()
)
)
);
} else {
$remoteFilename = sprintf(
'https://phar.phpunit.de/phpunit%s.phar',
PHPUnit_Runner_Version::getReleaseChannel()
);
}
$tempFilename = tempnam(sys_get_temp_dir(), 'phpunit') . '.phar';
// Workaround for https://bugs.php.net/bug.php?id=65538
$caFile = dirname($tempFilename) . '/ca.pem';
copy(__PHPUNIT_PHAR_ROOT__ . '/ca.pem', $caFile);
print 'Updating the PHPUnit PHAR ... ';
$options = [
'ssl' => [
'allow_self_signed' => false,
'cafile' => $caFile,
'verify_peer' => true
]
];
file_put_contents(
$tempFilename,
file_get_contents(
$remoteFilename,
false,
stream_context_create($options)
)
);
chmod($tempFilename, 0777 & ~umask());
try {
$phar = new Phar($tempFilename);
unset($phar);
rename($tempFilename, $localFilename);
unlink($caFile);
} catch (Throwable $_e) {
$e = $_e;
} catch (Exception $_e) {
$e = $_e;
}
if (isset($e)) {
unlink($caFile);
unlink($tempFilename);
print " done\n\n" . $e->getMessage() . "\n";
exit(2);
}
print " done\n";
exit(PHPUnit_TextUI_TestRunner::SUCCESS_EXIT);
}
/**
* @since Method available since Release 4.8.0
*/
protected function handleVersionCheck()
{
$this->printVersionString();
$latestVersion = file_get_contents('https://phar.phpunit.de/latest-version-of/phpunit');
$isOutdated = version_compare($latestVersion, PHPUnit_Runner_Version::id(), '>');
if ($isOutdated) {
print "You are not using the latest version of PHPUnit.\n";
print 'Use "phpunit --self-upgrade" to install PHPUnit ' . $latestVersion . "\n";
} else {
print "You are using the latest version of PHPUnit.\n";
}
exit(PHPUnit_TextUI_TestRunner::SUCCESS_EXIT);
}
/**
* Show the help message.
*/
protected function showHelp()
{
$this->printVersionString();
print <<<EOT
Usage: phpunit [options] UnitTest [UnitTest.php]
phpunit [options] <directory>
Code Coverage Options:
--coverage-clover <file> Generate code coverage report in Clover XML format.
--coverage-crap4j <file> Generate code coverage report in Crap4J XML format.
--coverage-html <dir> Generate code coverage report in HTML format.
--coverage-php <file> Export PHP_CodeCoverage object to file.
--coverage-text=<file> Generate code coverage report in text format.
Default: Standard output.
--coverage-xml <dir> Generate code coverage report in PHPUnit XML format.
--whitelist <dir> Whitelist <dir> for code coverage analysis.
--disable-coverage-ignore Disable annotations for ignoring code coverage.
Logging Options:
--log-junit <file> Log test execution in JUnit XML format to file.
--log-tap <file> Log test execution in TAP format to file.
--log-teamcity <file> Log test execution in TeamCity format to file.
--log-json <file> Log test execution in JSON format.
--testdox-html <file> Write agile documentation in HTML format to file.
--testdox-text <file> Write agile documentation in Text format to file.
--testdox-xml <file> Write agile documentation in XML format to file.
--reverse-list Print defects in reverse order
Test Selection Options:
--filter <pattern> Filter which tests to run.
--testsuite <pattern> Filter which testsuite to run.
--group ... Only runs tests from the specified group(s).
--exclude-group ... Exclude tests from the specified group(s).
--list-groups List available test groups.
--list-suites List available test suites.
--test-suffix ... Only search for test in files with specified
suffix(es). Default: Test.php,.phpt
Test Execution Options:
--report-useless-tests Be strict about tests that do not test anything.
--strict-coverage Be strict about @covers annotation usage.
--strict-global-state Be strict about changes to global state
--disallow-test-output Be strict about output during tests.
--disallow-resource-usage Be strict about resource usage during small tests.
--enforce-time-limit Enforce time limit based on test size.
--disallow-todo-tests Disallow @todo-annotated tests.
--process-isolation Run each test in a separate PHP process.
--no-globals-backup Do not backup and restore \$GLOBALS for each test.
--static-backup Backup and restore static attributes for each test.
--colors=<flag> Use colors in output ("never", "auto" or "always").
--columns <n> Number of columns to use for progress output.
--columns max Use maximum number of columns for progress output.
--stderr Write to STDERR instead of STDOUT.
--stop-on-error Stop execution upon first error.
--stop-on-failure Stop execution upon first error or failure.
--stop-on-warning Stop execution upon first warning.
--stop-on-risky Stop execution upon first risky test.
--stop-on-skipped Stop execution upon first skipped test.
--stop-on-incomplete Stop execution upon first incomplete test.
--fail-on-warning Treat tests with warnings as failures.
--fail-on-risky Treat risky tests as failures.
-v|--verbose Output more verbose information.
--debug Display debugging information during test execution.
--loader <loader> TestSuiteLoader implementation to use.
--repeat <times> Runs the test(s) repeatedly.
--tap Report test execution progress in TAP format.
--teamcity Report test execution progress in TeamCity format.
--testdox Report test execution progress in TestDox format.
--testdox-group Only include tests from the specified group(s).
--testdox-exclude-group Exclude tests from the specified group(s).
--printer <printer> TestListener implementation to use.
Configuration Options:
--bootstrap <file> A "bootstrap" PHP file that is run before the tests.
-c|--configuration <file> Read configuration from XML file.
--no-configuration Ignore default configuration file (phpunit.xml).
--no-coverage Ignore code coverage configuration.
--include-path <path(s)> Prepend PHP's include_path with given path(s).
-d key[=value] Sets a php.ini value.
--generate-configuration Generate configuration file with suggested settings.
Miscellaneous Options:
-h|--help Prints this usage information.
--version Prints the version and exits.
--atleast-version <min> Checks that version is greater than min and exits.
EOT;
if (defined('__PHPUNIT_PHAR__')) {
print "\n --check-version Check whether PHPUnit is the latest version.";
print "\n --self-update Update PHPUnit to the latest version within the same\n release series.\n";
print "\n --self-upgrade Upgrade PHPUnit to the latest version.\n";
}
}
/**
* Custom callback for test suite discovery.
*/
protected function handleCustomTestSuite()
{
}
private function printVersionString()
{
if ($this->versionStringPrinted) {
return;
}
print PHPUnit_Runner_Version::getVersionString() . "\n\n";
$this->versionStringPrinted = true;
}
/**
*/
private function showError($message)
{
$this->printVersionString();
print $message . "\n";
exit(PHPUnit_TextUI_TestRunner::FAILURE_EXIT);
}
}
| dopilzzz/master-topora-yii2 | vendor/phpunit/phpunit/src/TextUI/Command.php | PHP | bsd-3-clause | 39,668 |
/* Malayalam (UTF-8) initialisation for the jQuery UI date picker plugin. */
/* Written by Saji Nediyanchath (saji89@gmail.com). */
(function( factory ) {
if ( typeof define === "function" && define.amd ) {
// AMD. Register as an anonymous module.
define([ "../datepicker" ], factory );
} else {
// Browser globals
factory( jQuery.datepicker );
}
}(function( datepicker ) {
datepicker.regional['ml'] = {
closeText: 'ശരി',
prevText: 'മുന്നത്തെ',
nextText: 'അടുത്തത് ',
currentText: 'ഇന്ന്',
monthNames: ['ജനുവരി','ഫെബ്രുവരി','മാര്ച്ച്','ഏപ്രില്','മേയ്','ജൂണ്',
'ജൂലൈ','ആഗസ്റ്റ്','സെപ്റ്റംബര്','ഒക്ടോബര്','നവംബര്','ഡിസംബര്'],
monthNamesShort: ['ജനു', 'ഫെബ്', 'മാര്', 'ഏപ്രി', 'മേയ്', 'ജൂണ്',
'ജൂലാ', 'ആഗ', 'സെപ്', 'ഒക്ടോ', 'നവം', 'ഡിസ'],
dayNames: ['ഞായര്', 'തിങ്കള്', 'ചൊവ്വ', 'ബുധന്', 'വ്യാഴം', 'വെള്ളി', 'ശനി'],
dayNamesShort: ['ഞായ', 'തിങ്ക', 'ചൊവ്വ', 'ബുധ', 'വ്യാഴം', 'വെള്ളി', 'ശനി'],
dayNamesMin: ['ഞാ','തി','ചൊ','ബു','വ്യാ','വെ','ശ'],
weekHeader: 'ആ',
dateFormat: 'dd/mm/yy',
firstDay: 1,
isRTL: false,
showMonthAfterYear: false,
yearSuffix: ''};
datepicker.setDefaults(datepicker.regional['ml']);
return datepicker.regional['ml'];
}));
| gatoazul2000/yiiadvance2 | frontend/web/assets/bd15c00c/ui/i18n/datepicker-ml.js | JavaScript | bsd-3-clause | 1,684 |
/*
** $Id: lparser.c,v 2.42.1.4 2011/10/21 19:31:42 roberto Exp $
** Lua Parser
** See Copyright Notice in lua.h
*/
#include <string.h>
#define lparser_c
#define LUA_CORE
#include "lua.h"
#include "lcode.h"
#include "ldebug.h"
#include "ldo.h"
#include "lfunc.h"
#include "llex.h"
#include "lmem.h"
#include "lobject.h"
#include "lopcodes.h"
#include "lparser.h"
#include "lstate.h"
#include "lstring.h"
#include "ltable.h"
#define hasmultret(k) ((k) == VCALL || (k) == VVARARG)
#define getlocvar(fs, i) ((fs)->f->locvars[(fs)->actvar[i]])
#define luaY_checklimit(fs,v,l,m) if ((v)>(l)) errorlimit(fs,l,m)
/*
** nodes for block list (list of active blocks)
*/
typedef struct BlockCnt {
struct BlockCnt *previous; /* chain */
int breaklist; /* list of jumps out of this loop */
lu_byte nactvar; /* # active locals outside the breakable structure */
lu_byte upval; /* true if some variable in the block is an upvalue */
lu_byte isbreakable; /* true if `block' is a loop */
} BlockCnt;
/*
** prototypes for recursive non-terminal functions
*/
static void chunk (LexState *ls);
static void expr (LexState *ls, expdesc *v);
static void anchor_token (LexState *ls) {
if (ls->t.token == TK_NAME || ls->t.token == TK_STRING) {
TString *ts = ls->t.seminfo.ts;
luaX_newstring(ls, getstr(ts), ts->tsv.len);
}
}
static void error_expected (LexState *ls, int token) {
luaX_syntaxerror(ls,
luaO_pushfstring(ls->L, LUA_QS " expected", luaX_token2str(ls, token)));
}
static void errorlimit (FuncState *fs, int limit, const char *what) {
const char *msg = (fs->f->linedefined == 0) ?
luaO_pushfstring(fs->L, "main function has more than %d %s", limit, what) :
luaO_pushfstring(fs->L, "function at line %d has more than %d %s",
fs->f->linedefined, limit, what);
luaX_lexerror(fs->ls, msg, 0);
}
static int testnext (LexState *ls, int c) {
if (ls->t.token == c) {
luaX_next(ls);
return 1;
}
else return 0;
}
static void check (LexState *ls, int c) {
if (ls->t.token != c)
error_expected(ls, c);
}
static void checknext (LexState *ls, int c) {
check(ls, c);
luaX_next(ls);
}
#define check_condition(ls,c,msg) { if (!(c)) luaX_syntaxerror(ls, msg); }
static void check_match (LexState *ls, int what, int who, int where) {
if (!testnext(ls, what)) {
if (where == ls->linenumber)
error_expected(ls, what);
else {
luaX_syntaxerror(ls, luaO_pushfstring(ls->L,
LUA_QS " expected (to close " LUA_QS " at line %d)",
luaX_token2str(ls, what), luaX_token2str(ls, who), where));
}
}
}
static TString *str_checkname (LexState *ls) {
TString *ts;
check(ls, TK_NAME);
ts = ls->t.seminfo.ts;
luaX_next(ls);
return ts;
}
static void init_exp (expdesc *e, expkind k, int i) {
e->f = e->t = NO_JUMP;
e->k = k;
e->u.s.info = i;
}
static void codestring (LexState *ls, expdesc *e, TString *s) {
init_exp(e, VK, luaK_stringK(ls->fs, s));
}
static void checkname(LexState *ls, expdesc *e) {
codestring(ls, e, str_checkname(ls));
}
static int registerlocalvar (LexState *ls, TString *varname) {
FuncState *fs = ls->fs;
Proto *f = fs->f;
int oldsize = f->sizelocvars;
luaM_growvector(ls->L, f->locvars, fs->nlocvars, f->sizelocvars,
LocVar, SHRT_MAX, "too many local variables");
while (oldsize < f->sizelocvars) f->locvars[oldsize++].varname = NULL;
f->locvars[fs->nlocvars].varname = varname;
luaC_objbarrier(ls->L, f, varname);
return fs->nlocvars++;
}
#define new_localvarliteral(ls,v,n) \
new_localvar(ls, luaX_newstring(ls, "" v, (sizeof(v)/sizeof(char))-1), n)
static void new_localvar (LexState *ls, TString *name, int n) {
FuncState *fs = ls->fs;
luaY_checklimit(fs, fs->nactvar+n+1, LUAI_MAXVARS, "local variables");
fs->actvar[fs->nactvar+n] = cast(unsigned short, registerlocalvar(ls, name));
}
static void adjustlocalvars (LexState *ls, int nvars) {
FuncState *fs = ls->fs;
fs->nactvar = cast_byte(fs->nactvar + nvars);
for (; nvars; nvars--) {
getlocvar(fs, fs->nactvar - nvars).startpc = fs->pc;
}
}
static void removevars (LexState *ls, int tolevel) {
FuncState *fs = ls->fs;
while (fs->nactvar > tolevel)
getlocvar(fs, --fs->nactvar).endpc = fs->pc;
}
static int indexupvalue (FuncState *fs, TString *name, expdesc *v) {
int i;
Proto *f = fs->f;
int oldsize = f->sizeupvalues;
for (i=0; i<f->nups; i++) {
if (fs->upvalues[i].k == v->k && fs->upvalues[i].info == v->u.s.info) {
lua_assert(f->upvalues[i] == name);
return i;
}
}
/* new one */
luaY_checklimit(fs, f->nups + 1, LUAI_MAXUPVALUES, "upvalues");
luaM_growvector(fs->L, f->upvalues, f->nups, f->sizeupvalues,
TString *, MAX_INT, "");
while (oldsize < f->sizeupvalues) f->upvalues[oldsize++] = NULL;
f->upvalues[f->nups] = name;
luaC_objbarrier(fs->L, f, name);
lua_assert(v->k == VLOCAL || v->k == VUPVAL);
fs->upvalues[f->nups].k = cast_byte(v->k);
fs->upvalues[f->nups].info = cast_byte(v->u.s.info);
return f->nups++;
}
static int searchvar (FuncState *fs, TString *n) {
int i;
for (i=fs->nactvar-1; i >= 0; i--) {
if (n == getlocvar(fs, i).varname)
return i;
}
return -1; /* not found */
}
static void markupval (FuncState *fs, int level) {
BlockCnt *bl = fs->bl;
while (bl && bl->nactvar > level) bl = bl->previous;
if (bl) bl->upval = 1;
}
static int singlevaraux (FuncState *fs, TString *n, expdesc *var, int base) {
if (fs == NULL) { /* no more levels? */
init_exp(var, VGLOBAL, NO_REG); /* default is global variable */
return VGLOBAL;
}
else {
int v = searchvar(fs, n); /* look up at current level */
if (v >= 0) {
init_exp(var, VLOCAL, v);
if (!base)
markupval(fs, v); /* local will be used as an upval */
return VLOCAL;
}
else { /* not found at current level; try upper one */
if (singlevaraux(fs->prev, n, var, 0) == VGLOBAL)
return VGLOBAL;
var->u.s.info = indexupvalue(fs, n, var); /* else was LOCAL or UPVAL */
var->k = VUPVAL; /* upvalue in this level */
return VUPVAL;
}
}
}
static void singlevar (LexState *ls, expdesc *var) {
TString *varname = str_checkname(ls);
FuncState *fs = ls->fs;
if (singlevaraux(fs, varname, var, 1) == VGLOBAL)
var->u.s.info = luaK_stringK(fs, varname); /* info points to global name */
}
static void adjust_assign (LexState *ls, int nvars, int nexps, expdesc *e) {
FuncState *fs = ls->fs;
int extra = nvars - nexps;
if (hasmultret(e->k)) {
extra++; /* includes call itself */
if (extra < 0) extra = 0;
luaK_setreturns(fs, e, extra); /* last exp. provides the difference */
if (extra > 1) luaK_reserveregs(fs, extra-1);
}
else {
if (e->k != VVOID) luaK_exp2nextreg(fs, e); /* close last expression */
if (extra > 0) {
int reg = fs->freereg;
luaK_reserveregs(fs, extra);
luaK_nil(fs, reg, extra);
}
}
}
static void enterlevel (LexState *ls) {
if (++ls->L->nCcalls > LUAI_MAXCCALLS)
luaX_lexerror(ls, "chunk has too many syntax levels", 0);
}
#define leavelevel(ls) ((ls)->L->nCcalls--)
static void enterblock (FuncState *fs, BlockCnt *bl, lu_byte isbreakable) {
bl->breaklist = NO_JUMP;
bl->isbreakable = isbreakable;
bl->nactvar = fs->nactvar;
bl->upval = 0;
bl->previous = fs->bl;
fs->bl = bl;
lua_assert(fs->freereg == fs->nactvar);
}
static void leaveblock (FuncState *fs) {
BlockCnt *bl = fs->bl;
fs->bl = bl->previous;
removevars(fs->ls, bl->nactvar);
if (bl->upval)
luaK_codeABC(fs, OP_CLOSE, bl->nactvar, 0, 0);
/* a block either controls scope or breaks (never both) */
lua_assert(!bl->isbreakable || !bl->upval);
lua_assert(bl->nactvar == fs->nactvar);
fs->freereg = fs->nactvar; /* free registers */
luaK_patchtohere(fs, bl->breaklist);
}
static void pushclosure (LexState *ls, FuncState *func, expdesc *v) {
FuncState *fs = ls->fs;
Proto *f = fs->f;
int oldsize = f->sizep;
int i;
luaM_growvector(ls->L, f->p, fs->np, f->sizep, Proto *,
MAXARG_Bx, "constant table overflow");
while (oldsize < f->sizep) f->p[oldsize++] = NULL;
f->p[fs->np++] = func->f;
luaC_objbarrier(ls->L, f, func->f);
init_exp(v, VRELOCABLE, luaK_codeABx(fs, OP_CLOSURE, 0, fs->np-1));
for (i=0; i<func->f->nups; i++) {
OpCode o = (func->upvalues[i].k == VLOCAL) ? OP_MOVE : OP_GETUPVAL;
luaK_codeABC(fs, o, 0, func->upvalues[i].info, 0);
}
}
static void open_func (LexState *ls, FuncState *fs) {
lua_State *L = ls->L;
Proto *f = luaF_newproto(L);
fs->f = f;
fs->prev = ls->fs; /* linked list of funcstates */
fs->ls = ls;
fs->L = L;
ls->fs = fs;
fs->pc = 0;
fs->lasttarget = -1;
fs->jpc = NO_JUMP;
fs->freereg = 0;
fs->nk = 0;
fs->np = 0;
fs->nlocvars = 0;
fs->nactvar = 0;
fs->bl = NULL;
f->source = ls->source;
f->maxstacksize = 2; /* registers 0/1 are always valid */
fs->h = luaH_new(L, 0, 0);
/* anchor table of constants and prototype (to avoid being collected) */
sethvalue2s(L, L->top, fs->h);
incr_top(L);
setptvalue2s(L, L->top, f);
incr_top(L);
}
static void close_func (LexState *ls) {
lua_State *L = ls->L;
FuncState *fs = ls->fs;
Proto *f = fs->f;
removevars(ls, 0);
luaK_ret(fs, 0, 0); /* final return */
luaM_reallocvector(L, f->code, f->sizecode, fs->pc, Instruction);
f->sizecode = fs->pc;
luaM_reallocvector(L, f->lineinfo, f->sizelineinfo, fs->pc, int);
f->sizelineinfo = fs->pc;
luaM_reallocvector(L, f->k, f->sizek, fs->nk, TValue);
f->sizek = fs->nk;
luaM_reallocvector(L, f->p, f->sizep, fs->np, Proto *);
f->sizep = fs->np;
luaM_reallocvector(L, f->locvars, f->sizelocvars, fs->nlocvars, LocVar);
f->sizelocvars = fs->nlocvars;
luaM_reallocvector(L, f->upvalues, f->sizeupvalues, f->nups, TString *);
f->sizeupvalues = f->nups;
lua_assert(luaG_checkcode(f));
lua_assert(fs->bl == NULL);
ls->fs = fs->prev;
/* last token read was anchored in defunct function; must reanchor it */
if (fs) anchor_token(ls);
L->top -= 2; /* remove table and prototype from the stack */
}
Proto *luaY_parser (lua_State *L, ZIO *z, Mbuffer *buff, const char *name) {
struct LexState lexstate;
struct FuncState funcstate;
lexstate.buff = buff;
luaX_setinput(L, &lexstate, z, luaS_new(L, name));
open_func(&lexstate, &funcstate);
funcstate.f->is_vararg = VARARG_ISVARARG; /* main func. is always vararg */
luaX_next(&lexstate); /* read first token */
chunk(&lexstate);
check(&lexstate, TK_EOS);
close_func(&lexstate);
lua_assert(funcstate.prev == NULL);
lua_assert(funcstate.f->nups == 0);
lua_assert(lexstate.fs == NULL);
return funcstate.f;
}
/*============================================================*/
/* GRAMMAR RULES */
/*============================================================*/
static void field (LexState *ls, expdesc *v) {
/* field -> ['.' | ':'] NAME */
FuncState *fs = ls->fs;
expdesc key;
luaK_exp2anyreg(fs, v);
luaX_next(ls); /* skip the dot or colon */
checkname(ls, &key);
luaK_indexed(fs, v, &key);
}
static void yindex (LexState *ls, expdesc *v) {
/* index -> '[' expr ']' */
luaX_next(ls); /* skip the '[' */
expr(ls, v);
luaK_exp2val(ls->fs, v);
checknext(ls, ']');
}
/*
** {======================================================================
** Rules for Constructors
** =======================================================================
*/
struct ConsControl {
expdesc v; /* last list item read */
expdesc *t; /* table descriptor */
int nh; /* total number of `record' elements */
int na; /* total number of array elements */
int tostore; /* number of array elements pending to be stored */
};
static void recfield (LexState *ls, struct ConsControl *cc) {
/* recfield -> (NAME | `['exp1`]') = exp1 */
FuncState *fs = ls->fs;
int reg = ls->fs->freereg;
expdesc key, val;
int rkkey;
if (ls->t.token == TK_NAME) {
luaY_checklimit(fs, cc->nh, MAX_INT, "items in a constructor");
checkname(ls, &key);
}
else /* ls->t.token == '[' */
yindex(ls, &key);
cc->nh++;
checknext(ls, '=');
rkkey = luaK_exp2RK(fs, &key);
expr(ls, &val);
luaK_codeABC(fs, OP_SETTABLE, cc->t->u.s.info, rkkey, luaK_exp2RK(fs, &val));
fs->freereg = reg; /* free registers */
}
static void closelistfield (FuncState *fs, struct ConsControl *cc) {
if (cc->v.k == VVOID) return; /* there is no list item */
luaK_exp2nextreg(fs, &cc->v);
cc->v.k = VVOID;
if (cc->tostore == LFIELDS_PER_FLUSH) {
luaK_setlist(fs, cc->t->u.s.info, cc->na, cc->tostore); /* flush */
cc->tostore = 0; /* no more items pending */
}
}
static void lastlistfield (FuncState *fs, struct ConsControl *cc) {
if (cc->tostore == 0) return;
if (hasmultret(cc->v.k)) {
luaK_setmultret(fs, &cc->v);
luaK_setlist(fs, cc->t->u.s.info, cc->na, LUA_MULTRET);
cc->na--; /* do not count last expression (unknown number of elements) */
}
else {
if (cc->v.k != VVOID)
luaK_exp2nextreg(fs, &cc->v);
luaK_setlist(fs, cc->t->u.s.info, cc->na, cc->tostore);
}
}
static void listfield (LexState *ls, struct ConsControl *cc) {
expr(ls, &cc->v);
luaY_checklimit(ls->fs, cc->na, MAX_INT, "items in a constructor");
cc->na++;
cc->tostore++;
}
static void constructor (LexState *ls, expdesc *t) {
/* constructor -> ?? */
FuncState *fs = ls->fs;
int line = ls->linenumber;
int pc = luaK_codeABC(fs, OP_NEWTABLE, 0, 0, 0);
struct ConsControl cc;
cc.na = cc.nh = cc.tostore = 0;
cc.t = t;
init_exp(t, VRELOCABLE, pc);
init_exp(&cc.v, VVOID, 0); /* no value (yet) */
luaK_exp2nextreg(ls->fs, t); /* fix it at stack top (for gc) */
checknext(ls, '{');
do {
lua_assert(cc.v.k == VVOID || cc.tostore > 0);
if (ls->t.token == '}') break;
closelistfield(fs, &cc);
switch(ls->t.token) {
case TK_NAME: { /* may be listfields or recfields */
luaX_lookahead(ls);
if (ls->lookahead.token != '=') /* expression? */
listfield(ls, &cc);
else
recfield(ls, &cc);
break;
}
case '[': { /* constructor_item -> recfield */
recfield(ls, &cc);
break;
}
default: { /* constructor_part -> listfield */
listfield(ls, &cc);
break;
}
}
} while (testnext(ls, ',') || testnext(ls, ';'));
check_match(ls, '}', '{', line);
lastlistfield(fs, &cc);
SETARG_B(fs->f->code[pc], luaO_int2fb(cc.na)); /* set initial array size */
SETARG_C(fs->f->code[pc], luaO_int2fb(cc.nh)); /* set initial table size */
}
/* }====================================================================== */
static void parlist (LexState *ls) {
/* parlist -> [ param { `,' param } ] */
FuncState *fs = ls->fs;
Proto *f = fs->f;
int nparams = 0;
f->is_vararg = 0;
if (ls->t.token != ')') { /* is `parlist' not empty? */
do {
switch (ls->t.token) {
case TK_NAME: { /* param -> NAME */
new_localvar(ls, str_checkname(ls), nparams++);
break;
}
case TK_DOTS: { /* param -> `...' */
luaX_next(ls);
#if defined(LUA_COMPAT_VARARG)
/* use `arg' as default name */
new_localvarliteral(ls, "arg", nparams++);
f->is_vararg = VARARG_HASARG | VARARG_NEEDSARG;
#endif
f->is_vararg |= VARARG_ISVARARG;
break;
}
default: luaX_syntaxerror(ls, "<name> or " LUA_QL("...") " expected");
}
} while (!f->is_vararg && testnext(ls, ','));
}
adjustlocalvars(ls, nparams);
f->numparams = cast_byte(fs->nactvar - (f->is_vararg & VARARG_HASARG));
luaK_reserveregs(fs, fs->nactvar); /* reserve register for parameters */
}
static void body (LexState *ls, expdesc *e, int needself, int line) {
/* body -> `(' parlist `)' chunk END */
FuncState new_fs;
open_func(ls, &new_fs);
new_fs.f->linedefined = line;
checknext(ls, '(');
if (needself) {
new_localvarliteral(ls, "self", 0);
adjustlocalvars(ls, 1);
}
parlist(ls);
checknext(ls, ')');
chunk(ls);
new_fs.f->lastlinedefined = ls->linenumber;
check_match(ls, TK_END, TK_FUNCTION, line);
close_func(ls);
pushclosure(ls, &new_fs, e);
}
static int explist1 (LexState *ls, expdesc *v) {
/* explist1 -> expr { `,' expr } */
int n = 1; /* at least one expression */
expr(ls, v);
while (testnext(ls, ',')) {
luaK_exp2nextreg(ls->fs, v);
expr(ls, v);
n++;
}
return n;
}
static void funcargs (LexState *ls, expdesc *f) {
FuncState *fs = ls->fs;
expdesc args;
int base, nparams;
int line = ls->linenumber;
switch (ls->t.token) {
case '(': { /* funcargs -> `(' [ explist1 ] `)' */
if (line != ls->lastline)
luaX_syntaxerror(ls,"ambiguous syntax (function call x new statement)");
luaX_next(ls);
if (ls->t.token == ')') /* arg list is empty? */
args.k = VVOID;
else {
explist1(ls, &args);
luaK_setmultret(fs, &args);
}
check_match(ls, ')', '(', line);
break;
}
case '{': { /* funcargs -> constructor */
constructor(ls, &args);
break;
}
case TK_STRING: { /* funcargs -> STRING */
codestring(ls, &args, ls->t.seminfo.ts);
luaX_next(ls); /* must use `seminfo' before `next' */
break;
}
default: {
luaX_syntaxerror(ls, "function arguments expected");
return;
}
}
lua_assert(f->k == VNONRELOC);
base = f->u.s.info; /* base register for call */
if (hasmultret(args.k))
nparams = LUA_MULTRET; /* open call */
else {
if (args.k != VVOID)
luaK_exp2nextreg(fs, &args); /* close last argument */
nparams = fs->freereg - (base+1);
}
init_exp(f, VCALL, luaK_codeABC(fs, OP_CALL, base, nparams+1, 2));
luaK_fixline(fs, line);
fs->freereg = base+1; /* call remove function and arguments and leaves
(unless changed) one result */
}
/*
** {======================================================================
** Expression parsing
** =======================================================================
*/
static void prefixexp (LexState *ls, expdesc *v) {
/* prefixexp -> NAME | '(' expr ')' */
switch (ls->t.token) {
case '(': {
int line = ls->linenumber;
luaX_next(ls);
expr(ls, v);
check_match(ls, ')', '(', line);
luaK_dischargevars(ls->fs, v);
return;
}
case TK_NAME: {
singlevar(ls, v);
return;
}
default: {
luaX_syntaxerror(ls, "unexpected symbol");
return;
}
}
}
static void primaryexp (LexState *ls, expdesc *v) {
/* primaryexp ->
prefixexp { `.' NAME | `[' exp `]' | `:' NAME funcargs | funcargs } */
FuncState *fs = ls->fs;
prefixexp(ls, v);
for (;;) {
switch (ls->t.token) {
case '.': { /* field */
field(ls, v);
break;
}
case '[': { /* `[' exp1 `]' */
expdesc key;
luaK_exp2anyreg(fs, v);
yindex(ls, &key);
luaK_indexed(fs, v, &key);
break;
}
case ':': { /* `:' NAME funcargs */
expdesc key;
luaX_next(ls);
checkname(ls, &key);
luaK_self(fs, v, &key);
funcargs(ls, v);
break;
}
case '(': case TK_STRING: case '{': { /* funcargs */
luaK_exp2nextreg(fs, v);
funcargs(ls, v);
break;
}
default: return;
}
}
}
static void simpleexp (LexState *ls, expdesc *v) {
/* simpleexp -> NUMBER | STRING | NIL | true | false | ... |
constructor | FUNCTION body | primaryexp */
switch (ls->t.token) {
case TK_NUMBER: {
init_exp(v, VKNUM, 0);
v->u.nval = ls->t.seminfo.r;
break;
}
case TK_STRING: {
codestring(ls, v, ls->t.seminfo.ts);
break;
}
case TK_NIL: {
init_exp(v, VNIL, 0);
break;
}
case TK_TRUE: {
init_exp(v, VTRUE, 0);
break;
}
case TK_FALSE: {
init_exp(v, VFALSE, 0);
break;
}
case TK_DOTS: { /* vararg */
FuncState *fs = ls->fs;
check_condition(ls, fs->f->is_vararg,
"cannot use " LUA_QL("...") " outside a vararg function");
fs->f->is_vararg &= ~VARARG_NEEDSARG; /* don't need 'arg' */
init_exp(v, VVARARG, luaK_codeABC(fs, OP_VARARG, 0, 1, 0));
break;
}
case '{': { /* constructor */
constructor(ls, v);
return;
}
case TK_FUNCTION: {
luaX_next(ls);
body(ls, v, 0, ls->linenumber);
return;
}
default: {
primaryexp(ls, v);
return;
}
}
luaX_next(ls);
}
static UnOpr getunopr (int op) {
switch (op) {
case TK_NOT: return OPR_NOT;
case '-': return OPR_MINUS;
case '#': return OPR_LEN;
default: return OPR_NOUNOPR;
}
}
static BinOpr getbinopr (int op) {
switch (op) {
case '+': return OPR_ADD;
case '-': return OPR_SUB;
case '*': return OPR_MUL;
case '/': return OPR_DIV;
case '%': return OPR_MOD;
case '^': return OPR_POW;
case TK_CONCAT: return OPR_CONCAT;
case TK_NE: return OPR_NE;
case TK_EQ: return OPR_EQ;
case '<': return OPR_LT;
case TK_LE: return OPR_LE;
case '>': return OPR_GT;
case TK_GE: return OPR_GE;
case TK_AND: return OPR_AND;
case TK_OR: return OPR_OR;
default: return OPR_NOBINOPR;
}
}
static const struct {
lu_byte left; /* left priority for each binary operator */
lu_byte right; /* right priority */
} priority[] = { /* ORDER OPR */
{6, 6}, {6, 6}, {7, 7}, {7, 7}, {7, 7}, /* `+' `-' `/' `%' */
{10, 9}, {5, 4}, /* power and concat (right associative) */
{3, 3}, {3, 3}, /* equality and inequality */
{3, 3}, {3, 3}, {3, 3}, {3, 3}, /* order */
{2, 2}, {1, 1} /* logical (and/or) */
};
#define UNARY_PRIORITY 8 /* priority for unary operators */
/*
** subexpr -> (simpleexp | unop subexpr) { binop subexpr }
** where `binop' is any binary operator with a priority higher than `limit'
*/
static BinOpr subexpr (LexState *ls, expdesc *v, unsigned int limit) {
BinOpr op;
UnOpr uop;
enterlevel(ls);
uop = getunopr(ls->t.token);
if (uop != OPR_NOUNOPR) {
luaX_next(ls);
subexpr(ls, v, UNARY_PRIORITY);
luaK_prefix(ls->fs, uop, v);
}
else simpleexp(ls, v);
/* expand while operators have priorities higher than `limit' */
op = getbinopr(ls->t.token);
while (op != OPR_NOBINOPR && priority[op].left > limit) {
expdesc v2;
BinOpr nextop;
luaX_next(ls);
luaK_infix(ls->fs, op, v);
/* read sub-expression with higher priority */
nextop = subexpr(ls, &v2, priority[op].right);
luaK_posfix(ls->fs, op, v, &v2);
op = nextop;
}
leavelevel(ls);
return op; /* return first untreated operator */
}
static void expr (LexState *ls, expdesc *v) {
subexpr(ls, v, 0);
}
/* }==================================================================== */
/*
** {======================================================================
** Rules for Statements
** =======================================================================
*/
static int block_follow (int token) {
switch (token) {
case TK_ELSE: case TK_ELSEIF: case TK_END:
case TK_UNTIL: case TK_EOS:
return 1;
default: return 0;
}
}
static void block (LexState *ls) {
/* block -> chunk */
FuncState *fs = ls->fs;
BlockCnt bl;
enterblock(fs, &bl, 0);
chunk(ls);
lua_assert(bl.breaklist == NO_JUMP);
leaveblock(fs);
}
/*
** structure to chain all variables in the left-hand side of an
** assignment
*/
struct LHS_assign {
struct LHS_assign *prev;
expdesc v; /* variable (global, local, upvalue, or indexed) */
};
/*
** check whether, in an assignment to a local variable, the local variable
** is needed in a previous assignment (to a table). If so, save original
** local value in a safe place and use this safe copy in the previous
** assignment.
*/
static void check_conflict (LexState *ls, struct LHS_assign *lh, expdesc *v) {
FuncState *fs = ls->fs;
int extra = fs->freereg; /* eventual position to save local variable */
int conflict = 0;
for (; lh; lh = lh->prev) {
if (lh->v.k == VINDEXED) {
if (lh->v.u.s.info == v->u.s.info) { /* conflict? */
conflict = 1;
lh->v.u.s.info = extra; /* previous assignment will use safe copy */
}
if (lh->v.u.s.aux == v->u.s.info) { /* conflict? */
conflict = 1;
lh->v.u.s.aux = extra; /* previous assignment will use safe copy */
}
}
}
if (conflict) {
luaK_codeABC(fs, OP_MOVE, fs->freereg, v->u.s.info, 0); /* make copy */
luaK_reserveregs(fs, 1);
}
}
static void assignment (LexState *ls, struct LHS_assign *lh, int nvars) {
expdesc e;
check_condition(ls, VLOCAL <= lh->v.k && lh->v.k <= VINDEXED,
"syntax error");
if (testnext(ls, ',')) { /* assignment -> `,' primaryexp assignment */
struct LHS_assign nv;
nv.prev = lh;
primaryexp(ls, &nv.v);
if (nv.v.k == VLOCAL)
check_conflict(ls, lh, &nv.v);
luaY_checklimit(ls->fs, nvars, LUAI_MAXCCALLS - ls->L->nCcalls,
"variables in assignment");
assignment(ls, &nv, nvars+1);
}
else { /* assignment -> `=' explist1 */
int nexps;
checknext(ls, '=');
nexps = explist1(ls, &e);
if (nexps != nvars) {
adjust_assign(ls, nvars, nexps, &e);
if (nexps > nvars)
ls->fs->freereg -= nexps - nvars; /* remove extra values */
}
else {
luaK_setoneret(ls->fs, &e); /* close last expression */
luaK_storevar(ls->fs, &lh->v, &e);
return; /* avoid default */
}
}
init_exp(&e, VNONRELOC, ls->fs->freereg-1); /* default assignment */
luaK_storevar(ls->fs, &lh->v, &e);
}
static int cond (LexState *ls) {
/* cond -> exp */
expdesc v;
expr(ls, &v); /* read condition */
if (v.k == VNIL) v.k = VFALSE; /* `falses' are all equal here */
luaK_goiftrue(ls->fs, &v);
return v.f;
}
static void breakstat (LexState *ls) {
FuncState *fs = ls->fs;
BlockCnt *bl = fs->bl;
int upval = 0;
while (bl && !bl->isbreakable) {
upval |= bl->upval;
bl = bl->previous;
}
if (!bl)
luaX_syntaxerror(ls, "no loop to break");
if (upval)
luaK_codeABC(fs, OP_CLOSE, bl->nactvar, 0, 0);
luaK_concat(fs, &bl->breaklist, luaK_jump(fs));
}
static void whilestat (LexState *ls, int line) {
/* whilestat -> WHILE cond DO block END */
FuncState *fs = ls->fs;
int whileinit;
int condexit;
BlockCnt bl;
luaX_next(ls); /* skip WHILE */
whileinit = luaK_getlabel(fs);
condexit = cond(ls);
enterblock(fs, &bl, 1);
checknext(ls, TK_DO);
block(ls);
luaK_patchlist(fs, luaK_jump(fs), whileinit);
check_match(ls, TK_END, TK_WHILE, line);
leaveblock(fs);
luaK_patchtohere(fs, condexit); /* false conditions finish the loop */
}
static void repeatstat (LexState *ls, int line) {
/* repeatstat -> REPEAT block UNTIL cond */
int condexit;
FuncState *fs = ls->fs;
int repeat_init = luaK_getlabel(fs);
BlockCnt bl1, bl2;
enterblock(fs, &bl1, 1); /* loop block */
enterblock(fs, &bl2, 0); /* scope block */
luaX_next(ls); /* skip REPEAT */
chunk(ls);
check_match(ls, TK_UNTIL, TK_REPEAT, line);
condexit = cond(ls); /* read condition (inside scope block) */
if (!bl2.upval) { /* no upvalues? */
leaveblock(fs); /* finish scope */
luaK_patchlist(ls->fs, condexit, repeat_init); /* close the loop */
}
else { /* complete semantics when there are upvalues */
breakstat(ls); /* if condition then break */
luaK_patchtohere(ls->fs, condexit); /* else... */
leaveblock(fs); /* finish scope... */
luaK_patchlist(ls->fs, luaK_jump(fs), repeat_init); /* and repeat */
}
leaveblock(fs); /* finish loop */
}
static int exp1 (LexState *ls) {
expdesc e;
int k;
expr(ls, &e);
k = e.k;
luaK_exp2nextreg(ls->fs, &e);
return k;
}
static void forbody (LexState *ls, int base, int line, int nvars, int isnum) {
/* forbody -> DO block */
BlockCnt bl;
FuncState *fs = ls->fs;
int prep, endfor;
adjustlocalvars(ls, 3); /* control variables */
checknext(ls, TK_DO);
prep = isnum ? luaK_codeAsBx(fs, OP_FORPREP, base, NO_JUMP) : luaK_jump(fs);
enterblock(fs, &bl, 0); /* scope for declared variables */
adjustlocalvars(ls, nvars);
luaK_reserveregs(fs, nvars);
block(ls);
leaveblock(fs); /* end of scope for declared variables */
luaK_patchtohere(fs, prep);
endfor = (isnum) ? luaK_codeAsBx(fs, OP_FORLOOP, base, NO_JUMP) :
luaK_codeABC(fs, OP_TFORLOOP, base, 0, nvars);
luaK_fixline(fs, line); /* pretend that `OP_FOR' starts the loop */
luaK_patchlist(fs, (isnum ? endfor : luaK_jump(fs)), prep + 1);
}
static void fornum (LexState *ls, TString *varname, int line) {
/* fornum -> NAME = exp1,exp1[,exp1] forbody */
FuncState *fs = ls->fs;
int base = fs->freereg;
new_localvarliteral(ls, "(for index)", 0);
new_localvarliteral(ls, "(for limit)", 1);
new_localvarliteral(ls, "(for step)", 2);
new_localvar(ls, varname, 3);
checknext(ls, '=');
exp1(ls); /* initial value */
checknext(ls, ',');
exp1(ls); /* limit */
if (testnext(ls, ','))
exp1(ls); /* optional step */
else { /* default step = 1 */
luaK_codeABx(fs, OP_LOADK, fs->freereg, luaK_numberK(fs, 1));
luaK_reserveregs(fs, 1);
}
forbody(ls, base, line, 1, 1);
}
static void forlist (LexState *ls, TString *indexname) {
/* forlist -> NAME {,NAME} IN explist1 forbody */
FuncState *fs = ls->fs;
expdesc e;
int nvars = 0;
int line;
int base = fs->freereg;
/* create control variables */
new_localvarliteral(ls, "(for generator)", nvars++);
new_localvarliteral(ls, "(for state)", nvars++);
new_localvarliteral(ls, "(for control)", nvars++);
/* create declared variables */
new_localvar(ls, indexname, nvars++);
while (testnext(ls, ','))
new_localvar(ls, str_checkname(ls), nvars++);
checknext(ls, TK_IN);
line = ls->linenumber;
adjust_assign(ls, 3, explist1(ls, &e), &e);
luaK_checkstack(fs, 3); /* extra space to call generator */
forbody(ls, base, line, nvars - 3, 0);
}
static void forstat (LexState *ls, int line) {
/* forstat -> FOR (fornum | forlist) END */
FuncState *fs = ls->fs;
TString *varname;
BlockCnt bl;
enterblock(fs, &bl, 1); /* scope for loop and control variables */
luaX_next(ls); /* skip `for' */
varname = str_checkname(ls); /* first variable name */
switch (ls->t.token) {
case '=': fornum(ls, varname, line); break;
case ',': case TK_IN: forlist(ls, varname); break;
default: luaX_syntaxerror(ls, LUA_QL("=") " or " LUA_QL("in") " expected");
}
check_match(ls, TK_END, TK_FOR, line);
leaveblock(fs); /* loop scope (`break' jumps to this point) */
}
static int test_then_block (LexState *ls) {
/* test_then_block -> [IF | ELSEIF] cond THEN block */
int condexit;
luaX_next(ls); /* skip IF or ELSEIF */
condexit = cond(ls);
checknext(ls, TK_THEN);
block(ls); /* `then' part */
return condexit;
}
static void ifstat (LexState *ls, int line) {
/* ifstat -> IF cond THEN block {ELSEIF cond THEN block} [ELSE block] END */
FuncState *fs = ls->fs;
int flist;
int escapelist = NO_JUMP;
flist = test_then_block(ls); /* IF cond THEN block */
while (ls->t.token == TK_ELSEIF) {
luaK_concat(fs, &escapelist, luaK_jump(fs));
luaK_patchtohere(fs, flist);
flist = test_then_block(ls); /* ELSEIF cond THEN block */
}
if (ls->t.token == TK_ELSE) {
luaK_concat(fs, &escapelist, luaK_jump(fs));
luaK_patchtohere(fs, flist);
luaX_next(ls); /* skip ELSE (after patch, for correct line info) */
block(ls); /* `else' part */
}
else
luaK_concat(fs, &escapelist, flist);
luaK_patchtohere(fs, escapelist);
check_match(ls, TK_END, TK_IF, line);
}
static void localfunc (LexState *ls) {
expdesc v, b;
FuncState *fs = ls->fs;
new_localvar(ls, str_checkname(ls), 0);
init_exp(&v, VLOCAL, fs->freereg);
luaK_reserveregs(fs, 1);
adjustlocalvars(ls, 1);
body(ls, &b, 0, ls->linenumber);
luaK_storevar(fs, &v, &b);
/* debug information will only see the variable after this point! */
getlocvar(fs, fs->nactvar - 1).startpc = fs->pc;
}
static void localstat (LexState *ls) {
/* stat -> LOCAL NAME {`,' NAME} [`=' explist1] */
int nvars = 0;
int nexps;
expdesc e;
do {
new_localvar(ls, str_checkname(ls), nvars++);
} while (testnext(ls, ','));
if (testnext(ls, '='))
nexps = explist1(ls, &e);
else {
e.k = VVOID;
nexps = 0;
}
adjust_assign(ls, nvars, nexps, &e);
adjustlocalvars(ls, nvars);
}
static int funcname (LexState *ls, expdesc *v) {
/* funcname -> NAME {field} [`:' NAME] */
int needself = 0;
singlevar(ls, v);
while (ls->t.token == '.')
field(ls, v);
if (ls->t.token == ':') {
needself = 1;
field(ls, v);
}
return needself;
}
static void funcstat (LexState *ls, int line) {
/* funcstat -> FUNCTION funcname body */
int needself;
expdesc v, b;
luaX_next(ls); /* skip FUNCTION */
needself = funcname(ls, &v);
body(ls, &b, needself, line);
luaK_storevar(ls->fs, &v, &b);
luaK_fixline(ls->fs, line); /* definition `happens' in the first line */
}
static void exprstat (LexState *ls) {
/* stat -> func | assignment */
FuncState *fs = ls->fs;
struct LHS_assign v;
primaryexp(ls, &v.v);
if (v.v.k == VCALL) /* stat -> func */
SETARG_C(getcode(fs, &v.v), 1); /* call statement uses no results */
else { /* stat -> assignment */
v.prev = NULL;
assignment(ls, &v, 1);
}
}
static void retstat (LexState *ls) {
/* stat -> RETURN explist */
FuncState *fs = ls->fs;
expdesc e;
int first, nret; /* registers with returned values */
luaX_next(ls); /* skip RETURN */
if (block_follow(ls->t.token) || ls->t.token == ';')
first = nret = 0; /* return no values */
else {
nret = explist1(ls, &e); /* optional return values */
if (hasmultret(e.k)) {
luaK_setmultret(fs, &e);
if (e.k == VCALL && nret == 1) { /* tail call? */
SET_OPCODE(getcode(fs,&e), OP_TAILCALL);
lua_assert(GETARG_A(getcode(fs,&e)) == fs->nactvar);
}
first = fs->nactvar;
nret = LUA_MULTRET; /* return all values */
}
else {
if (nret == 1) /* only one single value? */
first = luaK_exp2anyreg(fs, &e);
else {
luaK_exp2nextreg(fs, &e); /* values must go to the `stack' */
first = fs->nactvar; /* return all `active' values */
lua_assert(nret == fs->freereg - first);
}
}
}
luaK_ret(fs, first, nret);
}
static int statement (LexState *ls) {
int line = ls->linenumber; /* may be needed for error messages */
switch (ls->t.token) {
case TK_IF: { /* stat -> ifstat */
ifstat(ls, line);
return 0;
}
case TK_WHILE: { /* stat -> whilestat */
whilestat(ls, line);
return 0;
}
case TK_DO: { /* stat -> DO block END */
luaX_next(ls); /* skip DO */
block(ls);
check_match(ls, TK_END, TK_DO, line);
return 0;
}
case TK_FOR: { /* stat -> forstat */
forstat(ls, line);
return 0;
}
case TK_REPEAT: { /* stat -> repeatstat */
repeatstat(ls, line);
return 0;
}
case TK_FUNCTION: {
funcstat(ls, line); /* stat -> funcstat */
return 0;
}
case TK_LOCAL: { /* stat -> localstat */
luaX_next(ls); /* skip LOCAL */
if (testnext(ls, TK_FUNCTION)) /* local function? */
localfunc(ls);
else
localstat(ls);
return 0;
}
case TK_RETURN: { /* stat -> retstat */
retstat(ls);
return 1; /* must be last statement */
}
case TK_BREAK: { /* stat -> breakstat */
luaX_next(ls); /* skip BREAK */
breakstat(ls);
return 1; /* must be last statement */
}
default: {
exprstat(ls);
return 0; /* to avoid warnings */
}
}
}
static void chunk (LexState *ls) {
/* chunk -> { stat [`;'] } */
int islast = 0;
enterlevel(ls);
while (!islast && !block_follow(ls->t.token)) {
islast = statement(ls);
testnext(ls, ';');
lua_assert(ls->fs->f->maxstacksize >= ls->fs->freereg &&
ls->fs->freereg >= ls->fs->nactvar);
ls->fs->freereg = ls->fs->nactvar; /* free registers */
}
leavelevel(ls);
}
/* }====================================================================== */
| xlzhan/redis | deps/lua/src/lparser.c | C | bsd-3-clause | 36,696 |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.lang['sr-latn']={"wsc":{"btnIgnore":"Ignoriši","btnIgnoreAll":"Ignoriši sve","btnReplace":"Zameni","btnReplaceAll":"Zameni sve","btnUndo":"Vrati akciju","changeTo":"Izmeni","errorLoading":"Error loading application service host: %s.","ieSpellDownload":"Provera spelovanja nije instalirana. Da li želite da je skinete sa Interneta?","manyChanges":"Provera spelovanja završena: %1 reč(i) je izmenjeno","noChanges":"Provera spelovanja završena: Nije izmenjena nijedna rec","noMispell":"Provera spelovanja završena: greške nisu pronadene","noSuggestions":"- Bez sugestija -","notAvailable":"Sorry, but service is unavailable now.","notInDic":"Nije u rečniku","oneChange":"Provera spelovanja završena: Izmenjena je jedna reč","progress":"Provera spelovanja u toku...","title":"Spell Check","toolbar":"Proveri spelovanje"},"undo":{"redo":"Ponovi akciju","undo":"Poni�ti akciju"},"toolbar":{"toolbarCollapse":"Collapse Toolbar","toolbarExpand":"Expand Toolbar","toolbarGroups":{"document":"Document","clipboard":"Clipboard/Undo","editing":"Editing","forms":"Forms","basicstyles":"Basic Styles","paragraph":"Paragraph","links":"Links","insert":"Insert","styles":"Styles","colors":"Colors","tools":"Tools"},"toolbars":"Editor toolbars"},"templates":{"button":"Obrasci","emptyListMsg":"(Nema definisanih obrazaca)","insertOption":"Replace actual contents","options":"Template Options","selectPromptMsg":"Molimo Vas da odaberete obrazac koji ce biti primenjen na stranicu (trenutni sadržaj ce biti obrisan):","title":"Obrasci za sadržaj"},"table":{"border":"Veličina okvira","caption":"Naslov tabele","cell":{"menu":"Cell","insertBefore":"Insert Cell Before","insertAfter":"Insert Cell After","deleteCell":"Obriši ćelije","merge":"Spoj celije","mergeRight":"Merge Right","mergeDown":"Merge Down","splitHorizontal":"Split Cell Horizontally","splitVertical":"Split Cell Vertically","title":"Cell Properties","cellType":"Cell Type","rowSpan":"Rows Span","colSpan":"Columns Span","wordWrap":"Word Wrap","hAlign":"Horizontal Alignment","vAlign":"Vertical Alignment","alignBaseline":"Baseline","bgColor":"Background Color","borderColor":"Border Color","data":"Data","header":"Header","yes":"Yes","no":"No","invalidWidth":"Cell width must be a number.","invalidHeight":"Cell height must be a number.","invalidRowSpan":"Rows span must be a whole number.","invalidColSpan":"Columns span must be a whole number.","chooseColor":"Choose"},"cellPad":"Razmak ćelija","cellSpace":"Ćelijski prostor","column":{"menu":"Column","insertBefore":"Insert Column Before","insertAfter":"Insert Column After","deleteColumn":"Obriši kolone"},"columns":"Kolona","deleteTable":"Delete Table","headers":"Headers","headersBoth":"Both","headersColumn":"First column","headersNone":"None","headersRow":"First Row","invalidBorder":"Border size must be a number.","invalidCellPadding":"Cell padding must be a positive number.","invalidCellSpacing":"Cell spacing must be a positive number.","invalidCols":"Number of columns must be a number greater than 0.","invalidHeight":"Table height must be a number.","invalidRows":"Number of rows must be a number greater than 0.","invalidWidth":"Table width must be a number.","menu":"Osobine tabele","row":{"menu":"Row","insertBefore":"Insert Row Before","insertAfter":"Insert Row After","deleteRow":"Obriši redove"},"rows":"Redova","summary":"Summary","title":"Osobine tabele","toolbar":"Tabela","widthPc":"procenata","widthPx":"piksela","widthUnit":"width unit"},"stylescombo":{"label":"Stil","panelTitle":"Formatting Styles","panelTitle1":"Block Styles","panelTitle2":"Inline Styles","panelTitle3":"Object Styles"},"specialchar":{"options":"Special Character Options","title":"Odaberite specijalni karakter","toolbar":"Unesi specijalni karakter"},"sourcearea":{"toolbar":"Kôd"},"smiley":{"options":"Smiley Options","title":"Unesi smajlija","toolbar":"Smajli"},"showblocks":{"toolbar":"Show Blocks"},"selectall":{"toolbar":"Označi sve"},"scayt":{"about":"About SCAYT","aboutTab":"About","addWord":"Add Word","allCaps":"Ignore All-Caps Words","dic_create":"Create","dic_delete":"Delete","dic_field_name":"Dictionary name","dic_info":"Initially the User Dictionary is stored in a Cookie. However, Cookies are limited in size. When the User Dictionary grows to a point where it cannot be stored in a Cookie, then the dictionary may be stored on our server. To store your personal dictionary on our server you should specify a name for your dictionary. If you already have a stored dictionary, please type its name and click the Restore button.","dic_rename":"Rename","dic_restore":"Restore","dictionariesTab":"Dictionaries","disable":"Disable SCAYT","emptyDic":"Dictionary name should not be empty.","enable":"Enable SCAYT","ignore":"Ignore","ignoreAll":"Ignore All","ignoreDomainNames":"Ignore Domain Names","langs":"Languages","languagesTab":"Languages","mixedCase":"Ignore Words with Mixed Case","mixedWithDigits":"Ignore Words with Numbers","moreSuggestions":"More suggestions","opera_title":"Not supported by Opera","options":"Options","optionsTab":"Options","title":"Spell Check As You Type","toggle":"Toggle SCAYT"},"save":{"toolbar":"Sačuvaj"},"removeformat":{"toolbar":"Ukloni formatiranje"},"print":{"toolbar":"Štampa"},"preview":{"preview":"Izgled stranice"},"pastetext":{"button":"Zalepi kao čist tekst","title":"Zalepi kao čist tekst"},"pastefromword":{"confirmCleanup":"The text you want to paste seems to be copied from Word. Do you want to clean it before pasting?","error":"It was not possible to clean up the pasted data due to an internal error","title":"Zalepi iz Worda","toolbar":"Zalepi iz Worda"},"pagebreak":{"alt":"Page Break","toolbar":"Insert Page Break for Printing"},"newpage":{"toolbar":"Nova stranica"},"maximize":{"maximize":"Maximize","minimize":"Minimize"},"magicline":{"title":"Insert paragraph here"},"liststyle":{"armenian":"Armenian numbering","bulletedTitle":"Bulleted List Properties","circle":"Circle","decimal":"Decimal (1, 2, 3, etc.)","decimalLeadingZero":"Decimal leading zero (01, 02, 03, etc.)","disc":"Disc","georgian":"Georgian numbering (an, ban, gan, etc.)","lowerAlpha":"Lower Alpha (a, b, c, d, e, etc.)","lowerGreek":"Lower Greek (alpha, beta, gamma, etc.)","lowerRoman":"Lower Roman (i, ii, iii, iv, v, etc.)","none":"None","notset":"<not set>","numberedTitle":"Numbered List Properties","square":"Square","start":"Start","type":"Type","upperAlpha":"Upper Alpha (A, B, C, D, E, etc.)","upperRoman":"Upper Roman (I, II, III, IV, V, etc.)","validateStartNumber":"List start number must be a whole number."},"list":{"bulletedlist":"Nenabrojiva lista","numberedlist":"Nabrojiva lista"},"link":{"acccessKey":"Pristupni taster","advanced":"Napredni tagovi","advisoryContentType":"Advisory vrsta sadržaja","advisoryTitle":"Advisory naslov","anchor":{"toolbar":"Unesi/izmeni sidro","menu":"Osobine sidra","title":"Osobine sidra","name":"Ime sidra","errorName":"Unesite ime sidra","remove":"Remove Anchor"},"anchorId":"Po Id-ju elementa","anchorName":"Po nazivu sidra","charset":"Linked Resource Charset","cssClasses":"Stylesheet klase","emailAddress":"E-Mail adresa","emailBody":"Sadržaj poruke","emailSubject":"Naslov","id":"Id","info":"Link Info","langCode":"Smer jezika","langDir":"Smer jezika","langDirLTR":"S leva na desno (LTR)","langDirRTL":"S desna na levo (RTL)","menu":"Izmeni link","name":"Naziv","noAnchors":"(Nema dostupnih sidra)","noEmail":"Otkucajte adresu elektronske pote","noUrl":"Unesite URL linka","other":"<остало>","popupDependent":"Zavisno (Netscape)","popupFeatures":"Mogućnosti popup prozora","popupFullScreen":"Prikaz preko celog ekrana (IE)","popupLeft":"Od leve ivice ekrana (px)","popupLocationBar":"Lokacija","popupMenuBar":"Kontekstni meni","popupResizable":"Resizable","popupScrollBars":"Scroll bar","popupStatusBar":"Statusna linija","popupToolbar":"Toolbar","popupTop":"Od vrha ekrana (px)","rel":"Relationship","selectAnchor":"Odaberi sidro","styles":"Stil","tabIndex":"Tab indeks","target":"Meta","targetFrame":"<okvir>","targetFrameName":"Naziv odredišnog frejma","targetPopup":"<popup prozor>","targetPopupName":"Naziv popup prozora","title":"Link","toAnchor":"Sidro na ovoj stranici","toEmail":"E-Mail","toUrl":"URL","toolbar":"Unesi/izmeni link","type":"Vrsta linka","unlink":"Ukloni link","upload":"Pošalji"},"justify":{"block":"Obostrano ravnanje","center":"Centriran tekst","left":"Levo ravnanje","right":"Desno ravnanje"},"indent":{"indent":"Uvećaj levu marginu","outdent":"Smanji levu marginu"},"image":{"alertUrl":"Unesite URL slike","alt":"Alternativni tekst","border":"Okvir","btnUpload":"Pošalji na server","button2Img":"Do you want to transform the selected image button on a simple image?","hSpace":"HSpace","img2Button":"Do you want to transform the selected image on a image button?","infoTab":"Info slike","linkTab":"Link","lockRatio":"Zaključaj odnos","menu":"Osobine slika","resetSize":"Resetuj veličinu","title":"Osobine slika","titleButton":"Osobine dugmeta sa slikom","upload":"Pošalji","urlMissing":"Image source URL is missing.","vSpace":"VSpace","validateBorder":"Border must be a whole number.","validateHSpace":"HSpace must be a whole number.","validateVSpace":"VSpace must be a whole number."},"iframe":{"border":"Show frame border","noUrl":"Please type the iframe URL","scrolling":"Enable scrollbars","title":"IFrame Properties","toolbar":"IFrame"},"horizontalrule":{"toolbar":"Unesi horizontalnu liniju"},"forms":{"button":{"title":"Osobine dugmeta","text":"Tekst (vrednost)","type":"Tip","typeBtn":"Button","typeSbm":"Submit","typeRst":"Reset"},"checkboxAndRadio":{"checkboxTitle":"Osobine polja za potvrdu","radioTitle":"Osobine radio-dugmeta","value":"Vrednost","selected":"Označeno"},"form":{"title":"Osobine forme","menu":"Osobine forme","action":"Akcija","method":"Metoda","encoding":"Encoding"},"hidden":{"title":"Osobine skrivenog polja","name":"Naziv","value":"Vrednost"},"select":{"title":"Osobine izbornog polja","selectInfo":"Info","opAvail":"Dostupne opcije","value":"Vrednost","size":"Veličina","lines":"linija","chkMulti":"Dozvoli višestruku selekciju","opText":"Tekst","opValue":"Vrednost","btnAdd":"Dodaj","btnModify":"Izmeni","btnUp":"Gore","btnDown":"Dole","btnSetValue":"Podesi kao označenu vrednost","btnDelete":"Obriši"},"textarea":{"title":"Osobine zone teksta","cols":"Broj kolona","rows":"Broj redova"},"textfield":{"title":"Osobine tekstualnog polja","name":"Naziv","value":"Vrednost","charWidth":"Širina (karaktera)","maxChars":"Maksimalno karaktera","type":"Tip","typeText":"Tekst","typePass":"Lozinka"}},"format":{"label":"Format","panelTitle":"Format","tag_address":"Adresa","tag_div":"Normal (DIV)","tag_h1":"Naslov 1","tag_h2":"Naslov 2","tag_h3":"Naslov 3","tag_h4":"Naslov 4","tag_h5":"Naslov 5","tag_h6":"Naslov 6","tag_p":"Normal","tag_pre":"Formatirano"},"font":{"fontSize":{"label":"Veličina fonta","voiceLabel":"Font Size","panelTitle":"Veličina fonta"},"label":"Font","panelTitle":"Font","voiceLabel":"Font"},"flash":{"access":"Script Access","accessAlways":"Always","accessNever":"Never","accessSameDomain":"Same domain","alignAbsBottom":"Abs dole","alignAbsMiddle":"Abs sredina","alignBaseline":"Bazno","alignTextTop":"Vrh teksta","bgcolor":"Boja pozadine","chkFull":"Allow Fullscreen","chkLoop":"Ponavljaj","chkMenu":"Uključi fleš meni","chkPlay":"Automatski start","flashvars":"Variables for Flash","hSpace":"HSpace","properties":"Osobine fleša","propertiesTab":"Properties","quality":"Quality","qualityAutoHigh":"Auto High","qualityAutoLow":"Auto Low","qualityBest":"Best","qualityHigh":"High","qualityLow":"Low","qualityMedium":"Medium","scale":"Skaliraj","scaleAll":"Prikaži sve","scaleFit":"Popuni površinu","scaleNoBorder":"Bez ivice","title":"Osobine fleša","vSpace":"VSpace","validateHSpace":"HSpace must be a number.","validateSrc":"Unesite URL linka","validateVSpace":"VSpace must be a number.","windowMode":"Window mode","windowModeOpaque":"Opaque","windowModeTransparent":"Transparent","windowModeWindow":"Window"},"find":{"find":"Pretraga","findOptions":"Find Options","findWhat":"Pronadi:","matchCase":"Razlikuj mala i velika slova","matchCyclic":"Match cyclic","matchWord":"Uporedi cele reci","notFoundMsg":"Traženi tekst nije pronađen.","replace":"Zamena","replaceAll":"Zameni sve","replaceSuccessMsg":"%1 occurrence(s) replaced.","replaceWith":"Zameni sa:","title":"Find and Replace"},"fakeobjects":{"anchor":"Anchor","flash":"Flash Animation","hiddenfield":"Hidden Field","iframe":"IFrame","unknown":"Unknown Object"},"elementspath":{"eleLabel":"Elements path","eleTitle":"%1 element"},"div":{"IdInputLabel":"Id","advisoryTitleInputLabel":"Advisory Title","cssClassInputLabel":"Stylesheet Classes","edit":"Edit Div","inlineStyleInputLabel":"Inline Style","langDirLTRLabel":"Left to Right (LTR)","langDirLabel":"Language Direction","langDirRTLLabel":"Right to Left (RTL)","languageCodeInputLabel":" Language Code","remove":"Remove Div","styleSelectLabel":"Style","title":"Create Div Container","toolbar":"Create Div Container"},"contextmenu":{"options":"Context Menu Options"},"colordialog":{"clear":"Clear","highlight":"Highlight","options":"Color Options","selected":"Selected Color","title":"Select color"},"colorbutton":{"auto":"Automatski","bgColorTitle":"Boja pozadine","colors":{"000":"Black","800000":"Maroon","8B4513":"Saddle Brown","2F4F4F":"Dark Slate Gray","008080":"Teal","000080":"Navy","4B0082":"Indigo","696969":"Dark Gray","B22222":"Fire Brick","A52A2A":"Brown","DAA520":"Golden Rod","006400":"Dark Green","40E0D0":"Turquoise","0000CD":"Medium Blue","800080":"Purple","808080":"Gray","F00":"Red","FF8C00":"Dark Orange","FFD700":"Gold","008000":"Green","0FF":"Cyan","00F":"Blue","EE82EE":"Violet","A9A9A9":"Dim Gray","FFA07A":"Light Salmon","FFA500":"Orange","FFFF00":"Yellow","00FF00":"Lime","AFEEEE":"Pale Turquoise","ADD8E6":"Light Blue","DDA0DD":"Plum","D3D3D3":"Light Grey","FFF0F5":"Lavender Blush","FAEBD7":"Antique White","FFFFE0":"Light Yellow","F0FFF0":"Honeydew","F0FFFF":"Azure","F0F8FF":"Alice Blue","E6E6FA":"Lavender","FFF":"White"},"more":"Više boja...","panelTitle":"Colors","textColorTitle":"Boja teksta"},"clipboard":{"copy":"Kopiraj","copyError":"Sigurnosna podešavanja Vašeg pretraživača ne dozvoljavaju operacije automatskog kopiranja teksta. Molimo Vas da koristite prečicu sa tastature (Ctrl/Cmd+C).","cut":"Iseci","cutError":"Sigurnosna podešavanja Vašeg pretraživača ne dozvoljavaju operacije automatskog isecanja teksta. Molimo Vas da koristite prečicu sa tastature (Ctrl/Cmd+X).","paste":"Zalepi","pasteArea":"Paste Area","pasteMsg":"Molimo Vas da zalepite unutar donje povrine koristeći tastaturnu prečicu (<STRONG>Ctrl/Cmd+V</STRONG>) i da pritisnete <STRONG>OK</STRONG>.","securityMsg":"Because of your browser security settings, the editor is not able to access your clipboard data directly. You are required to paste it again in this window.","title":"Zalepi"},"blockquote":{"toolbar":"Block Quote"},"bidi":{"ltr":"Text direction from left to right","rtl":"Text direction from right to left"},"basicstyles":{"bold":"Podebljano","italic":"Kurziv","strike":"Precrtano","subscript":"Indeks","superscript":"Stepen","underline":"Podvučeno"},"about":{"copy":"Copyright © $1. All rights reserved.","dlgTitle":"About CKEditor","help":"Check $1 for help.","moreInfo":"For licensing information please visit our web site:","title":"About CKEditor","userGuide":"CKEditor User's Guide"},"dir":"ltr","editor":"Rich Text Editor","common":{"editorHelp":"Press ALT 0 for help","browseServer":"Pretraži server","url":"URL","protocol":"Protokol","upload":"Pošalji","uploadSubmit":"Pošalji na server","image":"Slika","flash":"Fleš","form":"Forma","checkbox":"Polje za potvrdu","radio":"Radio-dugme","textField":"Tekstualno polje","textarea":"Zona teksta","hiddenField":"Skriveno polje","button":"Dugme","select":"Izborno polje","imageButton":"Dugme sa slikom","notSet":"<nije postavljeno>","id":"Id","name":"Naziv","langDir":"Smer jezika","langDirLtr":"S leva na desno (LTR)","langDirRtl":"S desna na levo (RTL)","langCode":"Kôd jezika","longDescr":"Pun opis URL","cssClass":"Stylesheet klase","advisoryTitle":"Advisory naslov","cssStyle":"Stil","ok":"OK","cancel":"Otkaži","close":"Close","preview":"Preview","resize":"Resize","generalTab":"General","advancedTab":"Napredni tagovi","validateNumberFailed":"This value is not a number.","confirmNewPage":"Any unsaved changes to this content will be lost. Are you sure you want to load new page?","confirmCancel":"Some of the options have been changed. Are you sure to close the dialog?","options":"Options","target":"Target","targetNew":"New Window (_blank)","targetTop":"Topmost Window (_top)","targetSelf":"Same Window (_self)","targetParent":"Parent Window (_parent)","langDirLTR":"Left to Right (LTR)","langDirRTL":"Right to Left (RTL)","styles":"Style","cssClasses":"Stylesheet Classes","width":"Širina","height":"Visina","align":"Ravnanje","alignLeft":"Levo","alignRight":"Desno","alignCenter":"Sredina","alignTop":"Vrh","alignMiddle":"Sredina","alignBottom":"Dole","invalidHeight":"Height must be a number.","invalidWidth":"Width must be a number.","invalidCssLength":"Value specified for the \"%1\" field must be a positive number with or without a valid CSS measurement unit (px, %, in, cm, mm, em, ex, pt, or pc).","invalidHtmlLength":"Value specified for the \"%1\" field must be a positive number with or without a valid HTML measurement unit (px or %).","invalidInlineStyle":"Value specified for the inline style must consist of one or more tuples with the format of \"name : value\", separated by semi-colons.","cssLengthTooltip":"Enter a number for a value in pixels or a number with a valid CSS unit (px, %, in, cm, mm, em, ex, pt, or pc).","unavailable":"%1<span class=\"cke_accessibility\">, unavailable</span>"}} | 1datr/yupe | protected/modules/yupe/extensions/booster/assets/js/ckeditor/lang/sr-latn.js | JavaScript | bsd-3-clause | 18,023 |
<?php
/**
* Slovene PHPMailer language file: refer to English translation for definitive list
* @package PHPMailer
* @author Klemen Tušar <techouse@gmail.com>
*/
$PHPMAILER_LANG['authenticate'] = 'SMTP napaka: Avtentikacija ni uspela.';
$PHPMAILER_LANG['connect_host'] = 'SMTP napaka: Ne morem vzpostaviti povezave s SMTP gostiteljem.';
$PHPMAILER_LANG['data_not_accepted'] = 'SMTP napaka: Strežnik zavrača podatke.';
$PHPMAILER_LANG['empty_message'] = 'E-poštno sporočilo nima vsebine.';
$PHPMAILER_LANG['encoding'] = 'Nepoznan tip kodiranja: ';
$PHPMAILER_LANG['execute'] = 'Operacija ni uspela: ';
$PHPMAILER_LANG['file_access'] = 'Nimam dostopa do datoteke: ';
$PHPMAILER_LANG['file_open'] = 'Ne morem odpreti datoteke: ';
$PHPMAILER_LANG['from_failed'] = 'Neveljaven e-naslov pošiljatelja: ';
$PHPMAILER_LANG['instantiate'] = 'Ne morem inicializirati mail funkcije.';
$PHPMAILER_LANG['invalid_address'] = 'E-poštno sporočilo ni bilo poslano. E-naslov je neveljaven: ';
$PHPMAILER_LANG['mailer_not_supported'] = ' mailer ni podprt.';
$PHPMAILER_LANG['provide_address'] = 'Prosim vnesite vsaj enega naslovnika.';
$PHPMAILER_LANG['recipients_failed'] = 'SMTP napaka: Sledeči naslovniki so neveljavni: ';
$PHPMAILER_LANG['signing'] = 'Napaka pri podpisovanju: ';
$PHPMAILER_LANG['smtp_connect_failed'] = 'Ne morem vzpostaviti povezave s SMTP strežnikom.';
$PHPMAILER_LANG['smtp_error'] = 'Napaka SMTP strežnika: ';
$PHPMAILER_LANG['variable_set'] = 'Ne morem nastaviti oz. ponastaviti spremenljivke: ';
//$PHPMAILER_LANG['extension_missing'] = 'Extension missing: ';
| jarvis0512/aersa | vendor/phpmailer/phpmailer/language/phpmailer.lang-sl.php | PHP | bsd-3-clause | 1,721 |
/*
* Copyright (C) 2011 Apple Inc. All Rights Reserved.
* Copyright (C) 2012 Igalia S.L.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "AccessibilityUIElement.h"
#if HAVE(ACCESSIBILITY)
#include "InjectedBundle.h"
#include "InjectedBundlePage.h"
#include "NotImplemented.h"
#include <JavaScriptCore/JSStringRef.h>
#include <atk/atk.h>
#include <wtf/Assertions.h>
#include <wtf/gobject/GOwnPtr.h>
#include <wtf/gobject/GRefPtr.h>
#include <wtf/text/CString.h>
#include <wtf/text/WTFString.h>
#include <wtf/unicode/CharacterNames.h>
namespace WTR {
static String coreAttributeToAtkAttribute(JSStringRef attribute)
{
size_t bufferSize = JSStringGetMaximumUTF8CStringSize(attribute);
GOwnPtr<gchar> buffer(static_cast<gchar*>(g_malloc(bufferSize)));
JSStringGetUTF8CString(attribute, buffer.get(), bufferSize);
String attributeString = String::fromUTF8(buffer.get());
return attributeString == "AXPlaceholderValue" ? "placeholder-text" : String();
}
static String getAttributeSetValueForId(AtkObject* accessible, const char* id)
{
const char* attributeValue = 0;
AtkAttributeSet* attributeSet = atk_object_get_attributes(accessible);
for (AtkAttributeSet* attributes = attributeSet; attributes; attributes = attributes->next) {
AtkAttribute* atkAttribute = static_cast<AtkAttribute*>(attributes->data);
if (!strcmp(atkAttribute->name, id)) {
attributeValue = atkAttribute->value;
break;
}
}
String atkAttributeValue = String::fromUTF8(attributeValue);
atk_attribute_set_free(attributeSet);
return atkAttributeValue;
}
static char* getAtkAttributeSetAsString(AtkObject* accessible)
{
GString* str = g_string_new(0);
AtkAttributeSet* attributeSet = atk_object_get_attributes(accessible);
for (AtkAttributeSet* attributes = attributeSet; attributes; attributes = attributes->next) {
AtkAttribute* attribute = static_cast<AtkAttribute*>(attributes->data);
GOwnPtr<gchar> attributeData(g_strconcat(attribute->name, ":", attribute->value, NULL));
g_string_append(str, attributeData.get());
if (attributes->next)
g_string_append(str, ", ");
}
atk_attribute_set_free(attributeSet);
return g_string_free(str, FALSE);
}
static bool checkElementState(PlatformUIElement element, AtkStateType stateType)
{
if (!ATK_IS_OBJECT(element.get()))
return false;
GRefPtr<AtkStateSet> stateSet = adoptGRef(atk_object_ref_state_set(ATK_OBJECT(element.get())));
return atk_state_set_contains_state(stateSet.get(), stateType);
}
static JSStringRef indexRangeInTable(PlatformUIElement element, bool isRowRange)
{
GOwnPtr<gchar> rangeString(g_strdup("{0, 0}"));
if (!element || !ATK_IS_OBJECT(element.get()))
return JSStringCreateWithUTF8CString(rangeString.get());
AtkObject* axTable = atk_object_get_parent(ATK_OBJECT(element.get()));
if (!axTable || !ATK_IS_TABLE(axTable))
return JSStringCreateWithUTF8CString(rangeString.get());
// Look for the cell in the table.
gint indexInParent = atk_object_get_index_in_parent(ATK_OBJECT(element.get()));
if (indexInParent == -1)
return JSStringCreateWithUTF8CString(rangeString.get());
int row = -1;
int column = -1;
row = atk_table_get_row_at_index(ATK_TABLE(axTable), indexInParent);
column = atk_table_get_column_at_index(ATK_TABLE(axTable), indexInParent);
// Get the actual values, if row and columns are valid values.
if (row != -1 && column != -1) {
int base = 0;
int length = 0;
if (isRowRange) {
base = row;
length = atk_table_get_row_extent_at(ATK_TABLE(axTable), row, column);
} else {
base = column;
length = atk_table_get_column_extent_at(ATK_TABLE(axTable), row, column);
}
rangeString.set(g_strdup_printf("{%d, %d}", base, length));
}
return JSStringCreateWithUTF8CString(rangeString.get());
}
static void alterCurrentValue(PlatformUIElement element, int factor)
{
if (!element || !ATK_IS_VALUE(element.get()))
return;
GValue currentValue = G_VALUE_INIT;
atk_value_get_current_value(ATK_VALUE(element.get()), ¤tValue);
GValue increment = G_VALUE_INIT;
atk_value_get_minimum_increment(ATK_VALUE(element.get()), &increment);
GValue newValue = G_VALUE_INIT;
g_value_init(&newValue, G_TYPE_DOUBLE);
g_value_set_float(&newValue, g_value_get_float(¤tValue) + factor * g_value_get_float(&increment));
atk_value_set_current_value(ATK_VALUE(element.get()), &newValue);
g_value_unset(&newValue);
g_value_unset(&increment);
g_value_unset(¤tValue);
}
static gchar* replaceCharactersForResults(gchar* str)
{
WTF::String uString = WTF::String::fromUTF8(str);
// The object replacement character is passed along to ATs so we need to be
// able to test for their presence and do so without causing test failures.
uString.replace(objectReplacementCharacter, "<obj>");
// The presence of newline characters in accessible text of a single object
// is appropriate, but it makes test results (especially the accessible tree)
// harder to read.
uString.replace("\n", "<\\n>");
return g_strdup(uString.utf8().data());
}
static const gchar* roleToString(AtkRole role)
{
switch (role) {
case ATK_ROLE_ALERT:
return "AXRole: AXAlert";
case ATK_ROLE_CANVAS:
return "AXRole: AXCanvas";
case ATK_ROLE_CHECK_BOX:
return "AXRole: AXCheckBox";
case ATK_ROLE_COLUMN_HEADER:
return "AXRole: AXColumnHeader";
case ATK_ROLE_COMBO_BOX:
return "AXRole: AXComboBox";
case ATK_ROLE_DOCUMENT_FRAME:
return "AXRole: AXWebArea";
case ATK_ROLE_ENTRY:
return "AXRole: AXTextField";
case ATK_ROLE_FOOTER:
return "AXRole: AXFooter";
case ATK_ROLE_FORM:
return "AXRole: AXForm";
case ATK_ROLE_GROUPING:
return "AXRole: AXGroup";
case ATK_ROLE_HEADING:
return "AXRole: AXHeading";
case ATK_ROLE_IMAGE:
return "AXRole: AXImage";
case ATK_ROLE_IMAGE_MAP:
return "AXRole: AXImageMap";
case ATK_ROLE_LABEL:
return "AXRole: AXLabel";
case ATK_ROLE_LINK:
return "AXRole: AXLink";
case ATK_ROLE_LIST:
return "AXRole: AXList";
case ATK_ROLE_LIST_BOX:
return "AXRole: AXListBox";
case ATK_ROLE_LIST_ITEM:
return "AXRole: AXListItem";
case ATK_ROLE_MENU:
return "AXRole: AXMenu";
case ATK_ROLE_MENU_BAR:
return "AXRole: AXMenuBar";
case ATK_ROLE_MENU_ITEM:
return "AXRole: AXMenuItem";
case ATK_ROLE_PAGE_TAB:
return "AXRole: AXTab";
case ATK_ROLE_PAGE_TAB_LIST:
return "AXRole: AXTabGroup";
case ATK_ROLE_PANEL:
return "AXRole: AXGroup";
case ATK_ROLE_PARAGRAPH:
return "AXRole: AXParagraph";
case ATK_ROLE_PASSWORD_TEXT:
return "AXRole: AXPasswordField";
case ATK_ROLE_PUSH_BUTTON:
return "AXRole: AXButton";
case ATK_ROLE_RADIO_BUTTON:
return "AXRole: AXRadioButton";
case ATK_ROLE_ROW_HEADER:
return "AXRole: AXRowHeader";
case ATK_ROLE_RULER:
return "AXRole: AXRuler";
case ATK_ROLE_SCROLL_BAR:
return "AXRole: AXScrollBar";
case ATK_ROLE_SCROLL_PANE:
return "AXRole: AXScrollArea";
case ATK_ROLE_SECTION:
return "AXRole: AXDiv";
case ATK_ROLE_SEPARATOR:
return "AXRole: AXHorizontalRule";
case ATK_ROLE_SLIDER:
return "AXRole: AXSlider";
case ATK_ROLE_SPIN_BUTTON:
return "AXRole: AXSpinButton";
case ATK_ROLE_TABLE:
return "AXRole: AXTable";
case ATK_ROLE_TABLE_CELL:
return "AXRole: AXCell";
case ATK_ROLE_TABLE_COLUMN_HEADER:
return "AXRole: AXColumnHeader";
case ATK_ROLE_TABLE_ROW:
return "AXRole: AXRow";
case ATK_ROLE_TABLE_ROW_HEADER:
return "AXRole: AXRowHeader";
case ATK_ROLE_TOGGLE_BUTTON:
return "AXRole: AXToggleButton";
case ATK_ROLE_TOOL_BAR:
return "AXRole: AXToolbar";
case ATK_ROLE_TOOL_TIP:
return "AXRole: AXUserInterfaceTooltip";
case ATK_ROLE_TREE:
return "AXRole: AXTree";
case ATK_ROLE_TREE_TABLE:
return "AXRole: AXTreeGrid";
case ATK_ROLE_TREE_ITEM:
return "AXRole: AXTreeItem";
case ATK_ROLE_WINDOW:
return "AXRole: AXWindow";
case ATK_ROLE_UNKNOWN:
return "AXRole: AXUnknown";
default:
// We want to distinguish ATK_ROLE_UNKNOWN from a known AtkRole which
// our DRT isn't properly handling.
return "AXRole: FIXME not identified";
}
}
AccessibilityUIElement::AccessibilityUIElement(PlatformUIElement element)
: m_element(element)
{
}
AccessibilityUIElement::AccessibilityUIElement(const AccessibilityUIElement& other)
: JSWrappable()
, m_element(other.m_element)
{
}
AccessibilityUIElement::~AccessibilityUIElement()
{
}
bool AccessibilityUIElement::isEqual(AccessibilityUIElement* otherElement)
{
return m_element == otherElement->platformUIElement();
}
void AccessibilityUIElement::getChildren(Vector<RefPtr<AccessibilityUIElement> >& children)
{
if (!m_element || !ATK_IS_OBJECT(m_element.get()))
return;
int count = childrenCount();
for (int i = 0; i < count; i++) {
GRefPtr<AtkObject> child = adoptGRef(atk_object_ref_accessible_child(ATK_OBJECT(m_element.get()), i));
children.append(AccessibilityUIElement::create(child.get()));
}
}
void AccessibilityUIElement::getChildrenWithRange(Vector<RefPtr<AccessibilityUIElement> >& children, unsigned location, unsigned length)
{
if (!m_element || !ATK_IS_OBJECT(m_element.get()))
return;
unsigned end = location + length;
for (unsigned i = location; i < end; i++) {
GRefPtr<AtkObject> child = adoptGRef(atk_object_ref_accessible_child(ATK_OBJECT(m_element.get()), i));
children.append(AccessibilityUIElement::create(child.get()));
}
}
int AccessibilityUIElement::childrenCount()
{
if (!m_element)
return 0;
return atk_object_get_n_accessible_children(ATK_OBJECT(m_element.get()));
}
PassRefPtr<AccessibilityUIElement> AccessibilityUIElement::elementAtPoint(int x, int y)
{
if (!m_element || !ATK_IS_OBJECT(m_element.get()))
return 0;
GRefPtr<AtkObject> objectAtPoint = adoptGRef(atk_component_ref_accessible_at_point(ATK_COMPONENT(m_element.get()), x, y, ATK_XY_WINDOW));
return objectAtPoint ? AccessibilityUIElement::create(objectAtPoint.get()) : 0;
}
unsigned AccessibilityUIElement::indexOfChild(AccessibilityUIElement* element)
{
if (!m_element || !ATK_IS_OBJECT(m_element.get()))
return 0;
Vector<RefPtr<AccessibilityUIElement> > children;
getChildren(children);
unsigned count = children.size();
for (unsigned i = 0; i < count; i++)
if (children[i]->isEqual(element))
return i;
return 0;
}
PassRefPtr<AccessibilityUIElement> AccessibilityUIElement::childAtIndex(unsigned index)
{
Vector<RefPtr<AccessibilityUIElement> > children;
getChildrenWithRange(children, index, 1);
if (children.size() == 1)
return children[0];
return 0;
}
PassRefPtr<AccessibilityUIElement> AccessibilityUIElement::linkedUIElementAtIndex(unsigned index)
{
// FIXME: implement
return 0;
}
PassRefPtr<AccessibilityUIElement> AccessibilityUIElement::ariaOwnsElementAtIndex(unsigned index)
{
// FIXME: implement
return 0;
}
PassRefPtr<AccessibilityUIElement> AccessibilityUIElement::ariaFlowToElementAtIndex(unsigned index)
{
// FIXME: implement
return 0;
}
PassRefPtr<AccessibilityUIElement> AccessibilityUIElement::disclosedRowAtIndex(unsigned index)
{
// FIXME: implement
return 0;
}
PassRefPtr<AccessibilityUIElement> AccessibilityUIElement::rowAtIndex(unsigned index)
{
// FIXME: implement
return 0;
}
PassRefPtr<AccessibilityUIElement> AccessibilityUIElement::selectedChildAtIndex(unsigned index) const
{
// FIXME: implement
return 0;
}
unsigned AccessibilityUIElement::selectedChildrenCount() const
{
// FIXME: implement
return 0;
}
PassRefPtr<AccessibilityUIElement> AccessibilityUIElement::selectedRowAtIndex(unsigned index)
{
// FIXME: implement
return 0;
}
PassRefPtr<AccessibilityUIElement> AccessibilityUIElement::titleUIElement()
{
if (!m_element)
return 0;
AtkRelationSet* set = atk_object_ref_relation_set(ATK_OBJECT(m_element.get()));
if (!set)
return 0;
AtkObject* target = 0;
int count = atk_relation_set_get_n_relations(set);
for (int i = 0; i < count; i++) {
AtkRelation* relation = atk_relation_set_get_relation(set, i);
if (atk_relation_get_relation_type(relation) == ATK_RELATION_LABELLED_BY) {
GPtrArray* targetList = atk_relation_get_target(relation);
if (targetList->len)
target = static_cast<AtkObject*>(g_ptr_array_index(targetList, 0));
}
}
g_object_unref(set);
return target ? AccessibilityUIElement::create(target) : 0;
}
PassRefPtr<AccessibilityUIElement> AccessibilityUIElement::parentElement()
{
if (!m_element || !ATK_IS_OBJECT(m_element.get()))
return 0;
AtkObject* parent = atk_object_get_parent(ATK_OBJECT(m_element.get()));
return parent ? AccessibilityUIElement::create(parent) : 0;
}
PassRefPtr<AccessibilityUIElement> AccessibilityUIElement::disclosedByRow()
{
// FIXME: implement
return 0;
}
JSRetainPtr<JSStringRef> AccessibilityUIElement::attributesOfLinkedUIElements()
{
// FIXME: implement
return JSStringCreateWithCharacters(0, 0);
}
JSRetainPtr<JSStringRef> AccessibilityUIElement::attributesOfDocumentLinks()
{
// FIXME: implement
return JSStringCreateWithCharacters(0, 0);
}
JSRetainPtr<JSStringRef> AccessibilityUIElement::attributesOfChildren()
{
// FIXME: implement
return JSStringCreateWithCharacters(0, 0);
}
JSRetainPtr<JSStringRef> AccessibilityUIElement::allAttributes()
{
if (!m_element || !ATK_IS_OBJECT(m_element.get()))
return JSStringCreateWithCharacters(0, 0);
GOwnPtr<char> attributeData(getAtkAttributeSetAsString(ATK_OBJECT(m_element.get())));
return JSStringCreateWithUTF8CString(attributeData.get());
}
JSRetainPtr<JSStringRef> AccessibilityUIElement::stringAttributeValue(JSStringRef attribute)
{
if (!m_element)
return JSStringCreateWithCharacters(0, 0);
String atkAttributeName = coreAttributeToAtkAttribute(attribute);
if (atkAttributeName.isNull())
return JSStringCreateWithCharacters(0, 0);
String attributeValue = getAttributeSetValueForId(ATK_OBJECT(m_element.get()), atkAttributeName.utf8().data());
return JSStringCreateWithUTF8CString(attributeValue.utf8().data());
}
double AccessibilityUIElement::numberAttributeValue(JSStringRef attribute)
{
// FIXME: implement
return 0.0f;
}
PassRefPtr<AccessibilityUIElement> AccessibilityUIElement::uiElementAttributeValue(JSStringRef attribute) const
{
// FIXME: implement
return 0;
}
bool AccessibilityUIElement::boolAttributeValue(JSStringRef attribute)
{
// FIXME: implement
return false;
}
bool AccessibilityUIElement::isAttributeSettable(JSStringRef attribute)
{
// FIXME: implement
return false;
}
bool AccessibilityUIElement::isAttributeSupported(JSStringRef attribute)
{
// FIXME: implement
return false;
}
JSRetainPtr<JSStringRef> AccessibilityUIElement::parameterizedAttributeNames()
{
// FIXME: implement
return JSStringCreateWithCharacters(0, 0);
}
JSRetainPtr<JSStringRef> AccessibilityUIElement::role()
{
if (!m_element || !ATK_IS_OBJECT(m_element.get()))
return JSStringCreateWithCharacters(0, 0);
AtkRole role = atk_object_get_role(ATK_OBJECT(m_element.get()));
if (!role)
return JSStringCreateWithCharacters(0, 0);
GOwnPtr<gchar> axRole(g_strdup(roleToString(role)));
return JSStringCreateWithUTF8CString(axRole.get());
}
JSRetainPtr<JSStringRef> AccessibilityUIElement::subrole()
{
// FIXME: implement
return JSStringCreateWithCharacters(0, 0);
}
JSRetainPtr<JSStringRef> AccessibilityUIElement::roleDescription()
{
// FIXME: implement
return JSStringCreateWithCharacters(0, 0);
}
JSRetainPtr<JSStringRef> AccessibilityUIElement::title()
{
if (!m_element || !ATK_IS_OBJECT(m_element.get()))
return JSStringCreateWithCharacters(0, 0);
const gchar* name = atk_object_get_name(ATK_OBJECT(m_element.get()));
GOwnPtr<gchar> axTitle(g_strdup_printf("AXTitle: %s", name ? name : ""));
return JSStringCreateWithUTF8CString(axTitle.get());
}
JSRetainPtr<JSStringRef> AccessibilityUIElement::description()
{
if (!m_element || !ATK_IS_OBJECT(m_element.get()))
return JSStringCreateWithCharacters(0, 0);
const gchar* description = atk_object_get_description(ATK_OBJECT(m_element.get()));
if (!description)
return JSStringCreateWithCharacters(0, 0);
GOwnPtr<gchar> axDesc(g_strdup_printf("AXDescription: %s", description));
return JSStringCreateWithUTF8CString(axDesc.get());
}
JSRetainPtr<JSStringRef> AccessibilityUIElement::orientation() const
{
if (!m_element || !ATK_IS_OBJECT(m_element.get()))
return JSStringCreateWithCharacters(0, 0);
const gchar* axOrientation = 0;
if (checkElementState(m_element.get(), ATK_STATE_HORIZONTAL))
axOrientation = "AXOrientation: AXHorizontalOrientation";
else if (checkElementState(m_element.get(), ATK_STATE_VERTICAL))
axOrientation = "AXOrientation: AXVerticalOrientation";
if (!axOrientation)
return JSStringCreateWithCharacters(0, 0);
return JSStringCreateWithUTF8CString(axOrientation);
}
JSRetainPtr<JSStringRef> AccessibilityUIElement::stringValue()
{
if (!m_element || !ATK_IS_TEXT(m_element.get()))
return JSStringCreateWithCharacters(0, 0);
GOwnPtr<gchar> text(atk_text_get_text(ATK_TEXT(m_element.get()), 0, -1));
GOwnPtr<gchar> textWithReplacedCharacters(replaceCharactersForResults(text.get()));
GOwnPtr<gchar> axValue(g_strdup_printf("AXValue: %s", textWithReplacedCharacters.get()));
return JSStringCreateWithUTF8CString(axValue.get());
}
JSRetainPtr<JSStringRef> AccessibilityUIElement::language()
{
if (!m_element || !ATK_IS_OBJECT(m_element.get()))
return JSStringCreateWithCharacters(0, 0);
const gchar* locale = atk_object_get_object_locale(ATK_OBJECT(m_element.get()));
if (!locale)
return JSStringCreateWithCharacters(0, 0);
GOwnPtr<char> axValue(g_strdup_printf("AXLanguage: %s", locale));
return JSStringCreateWithUTF8CString(axValue.get());
}
JSRetainPtr<JSStringRef> AccessibilityUIElement::helpText() const
{
// FIXME: implement
// We need a way to call WebCore::AccessibilityObject::helpText()
// from here, probably a new helper class in WebProcess/WebCoreSupport.
return JSStringCreateWithCharacters(0, 0);
}
double AccessibilityUIElement::x()
{
if (!m_element || !ATK_IS_OBJECT(m_element.get()))
return 0.0f;
int x, y;
atk_component_get_position(ATK_COMPONENT(m_element.get()), &x, &y, ATK_XY_SCREEN);
return x;
}
double AccessibilityUIElement::y()
{
if (!m_element || !ATK_IS_OBJECT(m_element.get()))
return 0.0f;
int x, y;
atk_component_get_position(ATK_COMPONENT(m_element.get()), &x, &y, ATK_XY_SCREEN);
return y;
}
double AccessibilityUIElement::width()
{
if (!m_element || !ATK_IS_OBJECT(m_element.get()))
return 0.0f;
int width, height;
atk_component_get_size(ATK_COMPONENT(m_element.get()), &width, &height);
return width;
}
double AccessibilityUIElement::height()
{
if (!m_element || !ATK_IS_OBJECT(m_element.get()))
return 0.0f;
int width, height;
atk_component_get_size(ATK_COMPONENT(m_element.get()), &width, &height);
return height;
}
double AccessibilityUIElement::clickPointX()
{
// FIXME: implement
return 0.0f;
}
double AccessibilityUIElement::clickPointY()
{
// FIXME: implement
return 0.0f;
}
double AccessibilityUIElement::intValue() const
{
if (!m_element || !ATK_IS_OBJECT(m_element.get()))
return 0.0f;
GValue value = G_VALUE_INIT;
atk_value_get_current_value(ATK_VALUE(m_element.get()), &value);
if (!G_VALUE_HOLDS_FLOAT(&value))
return 0.0f;
return g_value_get_float(&value);
}
double AccessibilityUIElement::minValue()
{
if (!m_element || !ATK_IS_OBJECT(m_element.get()))
return 0.0f;
GValue value = G_VALUE_INIT;
atk_value_get_minimum_value(ATK_VALUE(m_element.get()), &value);
if (!G_VALUE_HOLDS_FLOAT(&value))
return 0.0f;
return g_value_get_float(&value);
}
double AccessibilityUIElement::maxValue()
{
if (!m_element || !ATK_IS_OBJECT(m_element.get()))
return 0.0f;
GValue value = G_VALUE_INIT;
atk_value_get_maximum_value(ATK_VALUE(m_element.get()), &value);
if (!G_VALUE_HOLDS_FLOAT(&value))
return 0.0f;
return g_value_get_float(&value);
}
JSRetainPtr<JSStringRef> AccessibilityUIElement::valueDescription()
{
// FIXME: implement
return JSStringCreateWithCharacters(0, 0);
}
int AccessibilityUIElement::insertionPointLineNumber()
{
// FIXME: implement
return -1;
}
bool AccessibilityUIElement::isPressActionSupported()
{
// FIXME: implement
return false;
}
bool AccessibilityUIElement::isIncrementActionSupported()
{
// FIXME: implement
return false;
}
bool AccessibilityUIElement::isDecrementActionSupported()
{
// FIXME: implement
return false;
}
bool AccessibilityUIElement::isEnabled()
{
return checkElementState(m_element.get(), ATK_STATE_ENABLED);
}
bool AccessibilityUIElement::isRequired() const
{
return checkElementState(m_element.get(), ATK_STATE_REQUIRED);
}
bool AccessibilityUIElement::isFocused() const
{
return checkElementState(m_element.get(), ATK_STATE_FOCUSED);
}
bool AccessibilityUIElement::isSelected() const
{
return checkElementState(m_element.get(), ATK_STATE_SELECTED);
}
bool AccessibilityUIElement::isExpanded() const
{
return checkElementState(m_element.get(), ATK_STATE_EXPANDED);
}
bool AccessibilityUIElement::isChecked() const
{
return checkElementState(m_element.get(), ATK_STATE_CHECKED);
}
int AccessibilityUIElement::hierarchicalLevel() const
{
// FIXME: implement
return 0;
}
JSRetainPtr<JSStringRef> AccessibilityUIElement::speak()
{
// FIXME: implement
return JSStringCreateWithCharacters(0, 0);
}
bool AccessibilityUIElement::ariaIsGrabbed() const
{
// FIXME: implement
return false;
}
JSRetainPtr<JSStringRef> AccessibilityUIElement::ariaDropEffects() const
{
// FIXME: implement
return JSStringCreateWithCharacters(0, 0);
}
// parameterized attributes
int AccessibilityUIElement::lineForIndex(int index)
{
// FIXME: implement
return 0;
}
JSRetainPtr<JSStringRef> AccessibilityUIElement::rangeForLine(int line)
{
// FIXME: implement
return JSStringCreateWithCharacters(0, 0);
}
JSRetainPtr<JSStringRef> AccessibilityUIElement::rangeForPosition(int x, int y)
{
// FIXME: implement
return JSStringCreateWithCharacters(0, 0);
}
JSRetainPtr<JSStringRef> AccessibilityUIElement::boundsForRange(unsigned location, unsigned length)
{
// FIXME: implement
return JSStringCreateWithCharacters(0, 0);
}
JSRetainPtr<JSStringRef> AccessibilityUIElement::stringForRange(unsigned location, unsigned length)
{
// FIXME: implement
return JSStringCreateWithCharacters(0, 0);
}
JSRetainPtr<JSStringRef> AccessibilityUIElement::attributedStringForRange(unsigned location, unsigned length)
{
// FIXME: implement
return JSStringCreateWithCharacters(0, 0);
}
bool AccessibilityUIElement::attributedStringRangeIsMisspelled(unsigned location, unsigned length)
{
// FIXME: implement
return false;
}
PassRefPtr<AccessibilityUIElement> AccessibilityUIElement::uiElementForSearchPredicate(JSContextRef context, AccessibilityUIElement* startElement, bool isDirectionNext, JSValueRef searchKey, JSStringRef searchText, bool visibleOnly)
{
// FIXME: implement
return 0;
}
JSRetainPtr<JSStringRef> AccessibilityUIElement::attributesOfColumnHeaders()
{
// FIXME: implement
return JSStringCreateWithCharacters(0, 0);
}
JSRetainPtr<JSStringRef> AccessibilityUIElement::attributesOfRowHeaders()
{
// FIXME: implement
return JSStringCreateWithCharacters(0, 0);
}
JSRetainPtr<JSStringRef> AccessibilityUIElement::attributesOfColumns()
{
// FIXME: implement
return JSStringCreateWithCharacters(0, 0);
}
JSRetainPtr<JSStringRef> AccessibilityUIElement::attributesOfRows()
{
// FIXME: implement
return JSStringCreateWithCharacters(0, 0);
}
JSRetainPtr<JSStringRef> AccessibilityUIElement::attributesOfVisibleCells()
{
// FIXME: implement
return JSStringCreateWithCharacters(0, 0);
}
JSRetainPtr<JSStringRef> AccessibilityUIElement::attributesOfHeader()
{
// FIXME: implement
return JSStringCreateWithCharacters(0, 0);
}
int AccessibilityUIElement::rowCount()
{
if (!m_element || !ATK_IS_TABLE(m_element.get()))
return 0;
return atk_table_get_n_rows(ATK_TABLE(m_element.get()));
}
int AccessibilityUIElement::columnCount()
{
if (!m_element || !ATK_IS_TABLE(m_element.get()))
return 0;
return atk_table_get_n_columns(ATK_TABLE(m_element.get()));
}
int AccessibilityUIElement::indexInTable()
{
// FIXME: implement
return -1;
}
JSRetainPtr<JSStringRef> AccessibilityUIElement::rowIndexRange()
{
// Range in table for rows.
return indexRangeInTable(m_element.get(), true);
}
JSRetainPtr<JSStringRef> AccessibilityUIElement::columnIndexRange()
{
// Range in table for columns.
return indexRangeInTable(m_element.get(), false);
}
PassRefPtr<AccessibilityUIElement> AccessibilityUIElement::cellForColumnAndRow(unsigned col, unsigned row)
{
if (!m_element || !ATK_IS_TABLE(m_element.get()))
return 0;
// Adopt the AtkObject representing the cell because
// at_table_ref_at() transfers full ownership.
GRefPtr<AtkObject> foundCell = adoptGRef(atk_table_ref_at(ATK_TABLE(m_element.get()), row, col));
return foundCell ? AccessibilityUIElement::create(foundCell.get()) : 0;
}
PassRefPtr<AccessibilityUIElement> AccessibilityUIElement::horizontalScrollbar() const
{
// FIXME: implement
return 0;
}
PassRefPtr<AccessibilityUIElement> AccessibilityUIElement::verticalScrollbar() const
{
// FIXME: implement
return 0;
}
JSRetainPtr<JSStringRef> AccessibilityUIElement::selectedTextRange()
{
// FIXME: implement
return JSStringCreateWithCharacters(0, 0);
}
void AccessibilityUIElement::setSelectedTextRange(unsigned location, unsigned length)
{
// FIXME: implement
}
void AccessibilityUIElement::increment()
{
alterCurrentValue(m_element.get(), 1);
}
void AccessibilityUIElement::decrement()
{
alterCurrentValue(m_element.get(), -1);
}
void AccessibilityUIElement::showMenu()
{
// FIXME: implement
}
void AccessibilityUIElement::press()
{
if (!m_element || !ATK_IS_OBJECT(m_element.get()))
return;
if (!ATK_IS_ACTION(m_element.get()))
return;
// Only one action per object is supported so far.
atk_action_do_action(ATK_ACTION(m_element.get()), 0);
}
void AccessibilityUIElement::setSelectedChild(AccessibilityUIElement* element) const
{
// FIXME: implement
}
JSRetainPtr<JSStringRef> AccessibilityUIElement::accessibilityValue() const
{
// FIXME: implement
return JSStringCreateWithCharacters(0, 0);
}
JSRetainPtr<JSStringRef> AccessibilityUIElement::documentEncoding()
{
if (!m_element || !ATK_IS_OBJECT(m_element.get()))
return JSStringCreateWithCharacters(0, 0);
AtkRole role = atk_object_get_role(ATK_OBJECT(m_element.get()));
if (role != ATK_ROLE_DOCUMENT_FRAME)
return JSStringCreateWithCharacters(0, 0);
return JSStringCreateWithUTF8CString(atk_document_get_attribute_value(ATK_DOCUMENT(m_element.get()), "Encoding"));
}
JSRetainPtr<JSStringRef> AccessibilityUIElement::documentURI()
{
if (!m_element || !ATK_IS_OBJECT(m_element.get()))
return JSStringCreateWithCharacters(0, 0);
AtkRole role = atk_object_get_role(ATK_OBJECT(m_element.get()));
if (role != ATK_ROLE_DOCUMENT_FRAME)
return JSStringCreateWithCharacters(0, 0);
return JSStringCreateWithUTF8CString(atk_document_get_attribute_value(ATK_DOCUMENT(m_element.get()), "URI"));
}
JSRetainPtr<JSStringRef> AccessibilityUIElement::url()
{
// FIXME: implement
return JSStringCreateWithCharacters(0, 0);
}
bool AccessibilityUIElement::addNotificationListener(JSValueRef functionCallback)
{
// FIXME: implement
return true;
}
bool AccessibilityUIElement::removeNotificationListener()
{
// FIXME: implement
return true;
}
bool AccessibilityUIElement::isFocusable() const
{
return checkElementState(m_element.get(), ATK_STATE_FOCUSABLE);
}
bool AccessibilityUIElement::isSelectable() const
{
return checkElementState(m_element.get(), ATK_STATE_SELECTABLE);
}
bool AccessibilityUIElement::isMultiSelectable() const
{
return checkElementState(m_element.get(), ATK_STATE_MULTISELECTABLE);
}
bool AccessibilityUIElement::isVisible() const
{
return checkElementState(m_element.get(), ATK_STATE_VISIBLE);
}
bool AccessibilityUIElement::isOffScreen() const
{
// FIXME: implement
return false;
}
bool AccessibilityUIElement::isCollapsed() const
{
// FIXME: implement
return false;
}
bool AccessibilityUIElement::isIgnored() const
{
// FIXME: implement
return false;
}
bool AccessibilityUIElement::hasPopup() const
{
if (!m_element || !ATK_IS_OBJECT(m_element.get()))
return false;
return equalIgnoringCase(getAttributeSetValueForId(ATK_OBJECT(m_element.get()), "aria-haspopup"), "true");
}
void AccessibilityUIElement::takeFocus()
{
// FIXME: implement
}
void AccessibilityUIElement::takeSelection()
{
// FIXME: implement
}
void AccessibilityUIElement::addSelection()
{
// FIXME: implement
}
void AccessibilityUIElement::removeSelection()
{
// FIXME: implement
}
// Text markers
PassRefPtr<AccessibilityTextMarkerRange> AccessibilityUIElement::textMarkerRangeForElement(AccessibilityUIElement* element)
{
// FIXME: implement
return 0;
}
int AccessibilityUIElement::textMarkerRangeLength(AccessibilityTextMarkerRange* range)
{
// FIXME: implement
return 0;
}
PassRefPtr<AccessibilityTextMarker> AccessibilityUIElement::previousTextMarker(AccessibilityTextMarker* textMarker)
{
// FIXME: implement
return 0;
}
PassRefPtr<AccessibilityTextMarker> AccessibilityUIElement::nextTextMarker(AccessibilityTextMarker* textMarker)
{
// FIXME: implement
return 0;
}
JSRetainPtr<JSStringRef> AccessibilityUIElement::stringForTextMarkerRange(AccessibilityTextMarkerRange* markerRange)
{
// FIXME: implement
return JSStringCreateWithCharacters(0, 0);
}
PassRefPtr<AccessibilityTextMarkerRange> AccessibilityUIElement::textMarkerRangeForMarkers(AccessibilityTextMarker* startMarker, AccessibilityTextMarker* endMarker)
{
// FIXME: implement
return 0;
}
PassRefPtr<AccessibilityTextMarker> AccessibilityUIElement::startTextMarkerForTextMarkerRange(AccessibilityTextMarkerRange* range)
{
// FIXME: implement
return 0;
}
PassRefPtr<AccessibilityTextMarker> AccessibilityUIElement::endTextMarkerForTextMarkerRange(AccessibilityTextMarkerRange* range)
{
// FIXME: implement
return 0;
}
PassRefPtr<AccessibilityTextMarker> AccessibilityUIElement::textMarkerForPoint(int x, int y)
{
// FIXME: implement
return 0;
}
PassRefPtr<AccessibilityUIElement> AccessibilityUIElement::accessibilityElementForTextMarker(AccessibilityTextMarker* marker)
{
// FIXME: implement
return 0;
}
bool AccessibilityUIElement::attributedStringForTextMarkerRangeContainsAttribute(JSStringRef attribute, AccessibilityTextMarkerRange* range)
{
// FIXME: implement
return false;
}
int AccessibilityUIElement::indexForTextMarker(AccessibilityTextMarker* marker)
{
// FIXME: implement
return -1;
}
bool AccessibilityUIElement::isTextMarkerValid(AccessibilityTextMarker* textMarker)
{
// FIXME: implement
return false;
}
PassRefPtr<AccessibilityTextMarker> AccessibilityUIElement::textMarkerForIndex(int textIndex)
{
// FIXME: implement
return 0;
}
void AccessibilityUIElement::scrollToMakeVisible()
{
// FIXME: implement
}
JSRetainPtr<JSStringRef> AccessibilityUIElement::supportedActions() const
{
// FIXME: implement
return 0;
}
JSRetainPtr<JSStringRef> AccessibilityUIElement::pathDescription() const
{
notImplemented();
return 0;
}
JSRetainPtr<JSStringRef> AccessibilityUIElement::mathPostscriptsDescription() const
{
notImplemented();
return 0;
}
JSRetainPtr<JSStringRef> AccessibilityUIElement::mathPrescriptsDescription() const
{
notImplemented();
return 0;
}
} // namespace WTR
#endif
| sxhao/phantomjs | src/qt/qtwebkit/Tools/WebKitTestRunner/InjectedBundle/atk/AccessibilityUIElementAtk.cpp | C++ | bsd-3-clause | 34,506 |
/*
* Copyright (C) 2011 Brian Grinstead All rights reserved.
* Copyright (C) 2013 Matt Holden <jftholden@yahoo.com>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
WebInspector.CSSColorPicker = function()
{
WebInspector.Object.call(this);
this._element = document.createElement("div");
this._element.className = "colorpicker-container";
var topElement = this._element.createChild("div", "colorpicker-top");
topElement.createChild("div", "colorpicker-fill");
var topInnerElement = topElement.createChild("div", "colorpicker-top-inner colorpicker-fill-parent");
this._draggerElement = topInnerElement.createChild("div", "colorpicker-color");
this._dragHelperElement = this._draggerElement
.createChild("div", "colorpicker-saturation colorpicker-fill-parent")
.createChild("div", "colorpicker-value colorpicker-fill-parent")
.createChild("div", "colorpicker-dragger");
this._sliderElement = topInnerElement.createChild("div", "colorpicker-hue");
this._slideHelper = this._sliderElement.createChild("div", "colorpicker-slider");
var rangeContainer = this._element.createChild("div", "colorpicker-range-container");
var alphaLabel = rangeContainer.createChild("label", "colorpicker-text");
alphaLabel.textContent = WebInspector.UIString("Opacity:");
this._alphaElement = rangeContainer.createChild("input", "colorpicker-range");
this._alphaElement.setAttribute("type", "range");
this._alphaElement.setAttribute("min", "0");
this._alphaElement.setAttribute("max", "100");
this._alphaElement.addEventListener("change", alphaDrag.bind(this), false);
var displayContainer = this._element.createChild("div", "colorpicker-bottom");
var swatchElement = displayContainer.createChild("span", "swatch");
this._swatchInnerElement = swatchElement.createChild("span", "swatch-inner");
swatchElement.addEventListener("click", colorSwatchClicked.bind(this), false);
this._displayElement = displayContainer.createChild("span", "colorpicker-text colorpicker-color-text-value");
makeDraggable(this._sliderElement, hueDrag.bind(this));
makeDraggable(this._draggerElement, colorDrag.bind(this), colorDragStart.bind(this));
function makeDraggable(element, onmove, onstart, onstop)
{
var doc = document;
var dragging;
var offset;
var scrollOffset;
var maxHeight;
var maxWidth;
function consume(e)
{
event.preventDefault();
}
function move(e)
{
if (!dragging || !onmove)
return;
var dragX = Math.max(0, Math.min(e.pageX - offset.left + scrollOffset.left, maxWidth));
var dragY = Math.max(0, Math.min(e.pageY - offset.top + scrollOffset.top, maxHeight));
onmove(element, dragX, dragY, e);
}
function start(e)
{
if (e.button !== 0 || e.ctrlKey)
return;
if (dragging)
return;
if (onstart)
onstart(element, e)
dragging = true;
maxHeight = element.clientHeight;
maxWidth = element.clientWidth;
scrollOffset = {left: 0, top: 0};
var boundingRect = element.getBoundingClientRect();
offset = {left: boundingRect.left, top: boundingRect.top};
doc.addEventListener("selectstart", consume, false);
doc.addEventListener("dragstart", consume, false);
doc.addEventListener("mousemove", move, false);
doc.addEventListener("mouseup", stop, false);
move(e);
consume(e);
}
function stop(e)
{
if (!dragging)
return;
doc.removeEventListener("selectstart", consume, false);
doc.removeEventListener("dragstart", consume, false);
doc.removeEventListener("mousemove", move, false);
doc.removeEventListener("mouseup", stop, false);
if (onstop)
onstop(element, e);
dragging = false;
}
element.addEventListener("mousedown", start, false);
}
function hueDrag(element, dragX, dragY)
{
this.hsv[0] = dragY / this.slideHeight;
this._updateDisplay(true);
}
var initialHelperOffset;
function colorDragStart(element, dragX, dragY)
{
initialHelperOffset = {x: this._dragHelperElement.offsetLeft, y: this._dragHelperElement.offsetTop};
}
function colorDrag(element, dragX, dragY, event)
{
if (event.shiftKey) {
if (Math.abs(dragX - initialHelperOffset.x) >= Math.abs(dragY - initialHelperOffset.y))
dragY = initialHelperOffset.y;
else
dragX = initialHelperOffset.x;
}
this.hsv[1] = dragX / this.dragWidth;
this.hsv[2] = (this.dragHeight - dragY) / this.dragHeight;
this._updateDisplay(true);
}
function alphaDrag()
{
this.hsv[3] = this._alphaElement.value / 100;
this._updateDisplay(true);
}
function colorSwatchClicked()
{
// By changing this value, the new color format
// will be propagated down to any listeners after the UI is updated.
this._originalFormat = this.color.nextFormat();
this._updateDisplay(true);
}
};
WebInspector.Object.addConstructorFunctions(WebInspector.CSSColorPicker);
WebInspector.CSSColorPicker.Event = {
ColorChanged: "css-color-picker-color-changed"
};
WebInspector.CSSColorPicker.prototype = {
contructor: WebInspector.CSSColorPicker,
get element()
{
return this._element;
},
set color(color)
{
if (!this._originalFormat) {
this._originalFormat = color.format;
if (color.format === WebInspector.Color.Format.ShortHEX)
this._originalFormat = WebInspector.Color.Format.HEX;
}
var rgba = (color.rgba || color.rgb).slice(0);
if (rgba.length === 3)
rgba[3] = 1;
this.hsv = WebInspector.CSSColorPicker.rgbaToHSVA(rgba[0], rgba[1], rgba[2], rgba[3]);
},
get color()
{
var rgba = WebInspector.CSSColorPicker.hsvaToRGBA(this.hsv[0], this.hsv[1], this.hsv[2], this.hsv[3]);
var color;
if (rgba[3] === 1)
color = WebInspector.Color.fromRGB(rgba[0], rgba[1], rgba[2]);
else
color = WebInspector.Color.fromRGBA(rgba[0], rgba[1], rgba[2], rgba[3]);
var colorValue = color.toString(this.outputColorFormat);
if (!colorValue)
colorValue = color.toString(); // this.outputColorFormat can be invalid for current color (e.g. "nickname").
return new WebInspector.Color(colorValue);
},
get outputColorFormat()
{
var format = this._originalFormat;
if (this.hsv[3] === 1) {
// Simplify transparent formats, and don't allow ShortHex.
if (format === WebInspector.Color.Format.RGBA)
format = WebInspector.Color.Format.RGB;
else if (format === WebInspector.Color.Format.HSLA)
format = WebInspector.Color.Format.HSL;
else if (format === WebInspector.Color.Format.ShortHEX)
format = WebInspector.Color.Format.HEX;
} else {
// Everything except HSL(A) should be returned as RGBA if transparency is involved.
var printableTransparentFormats = [
WebInspector.Color.Format.HSLA,
WebInspector.Color.Format.RGBA
];
if (printableTransparentFormats.indexOf(format) === -1)
format = WebInspector.Color.Format.RGBA;
}
return format;
},
get colorHueOnly()
{
var rgba = WebInspector.CSSColorPicker.hsvaToRGBA(this.hsv[0], 1, 1, 1);
return WebInspector.Color.fromRGBA(rgba[0], rgba[1], rgba[2], rgba[3]);
},
set displayText(text)
{
this._displayElement.textContent = text;
},
shown: function()
{
this.slideHeight = this._sliderElement.offsetHeight;
this.dragWidth = this._draggerElement.offsetWidth;
this.dragHeight = this._draggerElement.offsetHeight;
this._dragHelperElementHeight = this._dragHelperElement.offsetHeight / 2;
this.slideHelperHeight = this._slideHelper.offsetHeight / 2;
this._updateDisplay();
},
// Private
_updateHelperLocations: function()
{
var h = this.hsv[0];
var s = this.hsv[1];
var v = this.hsv[2];
// Where to show the little circle that displays your current selected color.
var dragX = s * this.dragWidth;
var dragY = this.dragHeight - (v * this.dragHeight);
dragX = Math.max(-this._dragHelperElementHeight,
Math.min(this.dragWidth - this._dragHelperElementHeight, dragX - this._dragHelperElementHeight));
dragY = Math.max(-this._dragHelperElementHeight,
Math.min(this.dragHeight - this._dragHelperElementHeight, dragY - this._dragHelperElementHeight));
this._dragHelperElement.positionAt(dragX, dragY);
// Where to show the bar that displays your current selected hue.
var slideY = (h * this.slideHeight) - this.slideHelperHeight;
this._slideHelper.style.top = slideY + "px";
this._alphaElement.value = this.hsv[3] * 100;
},
_updateDisplay: function(colorWasChanged)
{
this._updateHelperLocations();
var rgb = (this.color.rgba || this.color.rgb).slice(0);
if (rgb.length === 3)
rgb[3] = 1;
var rgbHueOnly = this.colorHueOnly.rgb;
var flatColor = "rgb(" + rgbHueOnly[0] + ", " + rgbHueOnly[1] + ", " + rgbHueOnly[2] + ")";
var fullColor = "rgba(" + rgb[0] + ", " + rgb[1] + ", " + rgb[2] + ", " + rgb[3] + ")";
this._draggerElement.style.backgroundColor = flatColor;
this._swatchInnerElement.style.backgroundColor = fullColor;
this._alphaElement.value = this.hsv[3] * 100;
var colorValue = this.color.toString(this.outputColorFormat);
if (!colorValue)
colorValue = this.color.toString(); // this.outputColorFormat can be invalid for current color (e.g. "nickname").
this.displayText = colorValue;
if (colorWasChanged)
this.dispatchEventToListeners(WebInspector.CSSColorPicker.Event.ColorChanged, {color: this.color});
}
};
WebInspector.CSSColorPicker.hsvaToRGBA = function(h, s, v, a)
{
var r, g, b;
var i = Math.floor(h * 6);
var f = h * 6 - i;
var p = v * (1 - s);
var q = v * (1 - f * s);
var t = v * (1 - (1 - f) * s);
switch(i % 6) {
case 0:
r = v, g = t, b = p;
break;
case 1:
r = q, g = v, b = p;
break;
case 2:
r = p, g = v, b = t;
break;
case 3:
r = p, g = q, b = v;
break;
case 4:
r = t, g = p, b = v;
break;
case 5:
r = v, g = p, b = q;
break;
}
return [Math.round(r * 255), Math.round(g * 255), Math.round(b * 255), a];
};
WebInspector.CSSColorPicker.rgbaToHSVA = function(r, g, b, a)
{
r = r / 255;
g = g / 255;
b = b / 255;
var max = Math.max(r, g, b);
var min = Math.min(r, g, b);
var h;
var s;
var v = max;
var d = max - min;
s = max ? d / max : 0;
if(max === min) {
// Achromatic.
h = 0;
} else {
switch(max) {
case r:
h = (g - b) / d + (g < b ? 6 : 0);
break;
case g:
h = (b - r) / d + 2;
break;
case b:
h = (r - g) / d + 4;
break;
}
h /= 6;
}
return [h, s, v, a];
};
WebInspector.CSSColorPicker.prototype.__proto__ = WebInspector.Object.prototype;
| bprodoehl/phantomjs | src/qt/qtwebkit/Source/WebInspectorUI/UserInterface/CSSColorPicker.js | JavaScript | bsd-3-clause | 13,431 |
/*
* Copyright (C) 2012 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// This all-in-one cpp file cuts down on template bloat to allow us to build our Windows release build.
#include "ConsoleMessage.cpp"
#include "ContentSearchUtils.cpp"
#include "DOMEditor.cpp"
#include "DOMPatchSupport.cpp"
#include "IdentifiersFactory.cpp"
#include "InjectedScript.cpp"
#include "InjectedScriptBase.cpp"
#include "InjectedScriptCanvasModule.cpp"
#include "InjectedScriptHost.cpp"
#include "InjectedScriptManager.cpp"
#include "InjectedScriptModule.cpp"
#include "InspectorAgent.cpp"
#include "InspectorApplicationCacheAgent.cpp"
#include "InspectorBaseAgent.cpp"
#include "InspectorCSSAgent.cpp"
#include "InspectorCanvasAgent.cpp"
#include "InspectorClient.cpp"
#include "InspectorConsoleAgent.cpp"
#include "InspectorController.cpp"
#include "InspectorCounters.cpp"
#include "InspectorDOMAgent.cpp"
#include "InspectorDOMDebuggerAgent.cpp"
#include "InspectorDOMStorageAgent.cpp"
#include "InspectorDatabaseAgent.cpp"
#include "InspectorDatabaseResource.cpp"
#include "InspectorDebuggerAgent.cpp"
#include "InspectorFileSystemAgent.cpp"
#include "InspectorFrontendClientLocal.cpp"
#include "InspectorFrontendHost.cpp"
#include "InspectorHeapProfilerAgent.cpp"
#include "InspectorHistory.cpp"
#include "InspectorIndexedDBAgent.cpp"
#include "InspectorInputAgent.cpp"
#include "InspectorInstrumentation.cpp"
#include "InspectorLayerTreeAgent.cpp"
#include "InspectorMemoryAgent.cpp"
#include "InspectorOverlay.cpp"
#include "InspectorPageAgent.cpp"
#include "InspectorProfilerAgent.cpp"
#include "InspectorResourceAgent.cpp"
#include "InspectorRuntimeAgent.cpp"
#include "InspectorState.cpp"
#include "InspectorStyleSheet.cpp"
#include "InspectorStyleTextEditor.cpp"
#include "InspectorTimelineAgent.cpp"
#include "InspectorValues.cpp"
#include "InspectorWorkerAgent.cpp"
#include "InstrumentingAgents.cpp"
#include "NetworkResourcesData.cpp"
#include "PageConsoleAgent.cpp"
#include "PageDebuggerAgent.cpp"
#include "PageRuntimeAgent.cpp"
#include "ScriptArguments.cpp"
#include "ScriptCallFrame.cpp"
#include "ScriptCallStack.cpp"
#include "TimelineRecordFactory.cpp"
#include "TimelineTraceEventProcessor.cpp"
#include "WorkerConsoleAgent.cpp"
#include "WorkerDebuggerAgent.cpp"
#include "WorkerInspectorController.cpp"
#include "WorkerRuntimeAgent.cpp"
| Observer-Wu/phantomjs | src/qt/qtwebkit/Source/WebCore/inspector/InspectorAllInOne.cpp | C++ | bsd-3-clause | 3,628 |
/*
* Copyright (C) 2012 Igalia S.L.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2,1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "config.h"
#include "WebKitTestBus.h"
#include "WebViewTest.h"
#include <wtf/gobject/GRefPtr.h>
static WebKitTestBus* bus;
static void testWebExtensionGetTitle(WebViewTest* test, gconstpointer)
{
test->loadHtml("<html><head><title>WebKitGTK+ Web Extensions Test</title></head><body></body></html>", 0);
test->waitUntilLoadFinished();
GRefPtr<GDBusProxy> proxy = adoptGRef(bus->createProxy("org.webkit.gtk.WebExtensionTest",
"/org/webkit/gtk/WebExtensionTest" , "org.webkit.gtk.WebExtensionTest", test->m_mainLoop));
GRefPtr<GVariant> result = adoptGRef(g_dbus_proxy_call_sync(
proxy.get(),
"GetTitle",
g_variant_new("(t)", webkit_web_view_get_page_id(test->m_webView)),
G_DBUS_CALL_FLAGS_NONE,
-1, 0, 0));
g_assert(result);
const char* title;
g_variant_get(result.get(), "(&s)", &title);
g_assert_cmpstr(title, ==, "WebKitGTK+ Web Extensions Test");
}
static void documentLoadedCallback(GDBusConnection*, const char*, const char*, const char*, const char*, GVariant*, WebViewTest* test)
{
g_main_loop_quit(test->m_mainLoop);
}
static void testDocumentLoadedSignal(WebViewTest* test, gconstpointer)
{
GRefPtr<GDBusProxy> proxy = adoptGRef(bus->createProxy("org.webkit.gtk.WebExtensionTest",
"/org/webkit/gtk/WebExtensionTest", "org.webkit.gtk.WebExtensionTest", test->m_mainLoop));
GDBusConnection* connection = g_dbus_proxy_get_connection(proxy.get());
guint id = g_dbus_connection_signal_subscribe(connection,
0,
"org.webkit.gtk.WebExtensionTest",
"DocumentLoaded",
"/org/webkit/gtk/WebExtensionTest",
0,
G_DBUS_SIGNAL_FLAGS_NONE,
reinterpret_cast<GDBusSignalCallback>(documentLoadedCallback),
test,
0);
g_assert(id);
test->loadHtml("<html><head><title>WebKitGTK+ Web Extensions Test</title></head><body></body></html>", 0);
g_main_loop_run(test->m_mainLoop);
g_dbus_connection_signal_unsubscribe(connection, id);
}
static gboolean webProcessCrashedCallback(WebKitWebView*, WebViewTest* test)
{
test->quitMainLoop();
return FALSE;
}
static void testWebKitWebViewProcessCrashed(WebViewTest* test, gconstpointer)
{
test->loadHtml("<html></html>", 0);
test->waitUntilLoadFinished();
g_signal_connect(test->m_webView, "web-process-crashed",
G_CALLBACK(webProcessCrashedCallback), test);
GRefPtr<GDBusProxy> proxy = adoptGRef(bus->createProxy("org.webkit.gtk.WebExtensionTest",
"/org/webkit/gtk/WebExtensionTest", "org.webkit.gtk.WebExtensionTest", test->m_mainLoop));
GRefPtr<GVariant> result = adoptGRef(g_dbus_proxy_call_sync(
proxy.get(),
"AbortProcess",
0,
G_DBUS_CALL_FLAGS_NONE,
-1, 0, 0));
g_assert(!result);
g_main_loop_run(test->m_mainLoop);
}
void beforeAll()
{
webkit_web_context_set_web_extensions_directory(webkit_web_context_get_default(), WEBKIT_TEST_WEB_EXTENSIONS_DIR);
bus = new WebKitTestBus();
if (!bus->run())
return;
WebViewTest::add("WebKitWebExtension", "dom-document-title", testWebExtensionGetTitle);
WebViewTest::add("WebKitWebExtension", "document-loaded-signal", testDocumentLoadedSignal);
WebViewTest::add("WebKitWebView", "web-process-crashed", testWebKitWebViewProcessCrashed);
}
void afterAll()
{
delete bus;
}
| webmull/phantomjs | src/qt/qtwebkit/Source/WebKit2/UIProcess/API/gtk/tests/TestWebExtensions.cpp | C++ | bsd-3-clause | 4,205 |
/*
Copyright (C) 2012 Samsung Electronics
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "config.h"
#include "ewk_file_chooser.h"
#include "FileChooser.h"
#include "ewk_file_chooser_private.h"
#include <wtf/text/CString.h>
struct _Ewk_File_Chooser {
RefPtr<WebCore::FileChooser> fileChooser;
};
Eina_Bool ewk_file_chooser_allows_multiple_files_get(const Ewk_File_Chooser* chooser)
{
EINA_SAFETY_ON_NULL_RETURN_VAL(chooser, false);
return chooser->fileChooser->settings().allowsMultipleFiles;
}
Eina_Bool ewk_file_chooser_allows_directory_upload_get(const Ewk_File_Chooser* chooser)
{
#if ENABLE(DIRECTORY_UPLOAD)
EINA_SAFETY_ON_NULL_RETURN_VAL(chooser, false);
return chooser->fileChooser->settings().allowsDirectoryUpload;
#else
UNUSED_PARAM(chooser);
return false;
#endif
}
Eina_List* ewk_file_chooser_accept_mimetypes_get(const Ewk_File_Chooser* chooser)
{
EINA_SAFETY_ON_NULL_RETURN_VAL(chooser, 0);
Eina_List* mimetypes = 0;
size_t count = chooser->fileChooser->settings().acceptMIMETypes.size();
for (size_t i = 0; i < count; ++i)
mimetypes = eina_list_append(mimetypes, eina_stringshare_add(chooser->fileChooser->settings().acceptMIMETypes[i].utf8().data()));
return mimetypes;
}
Eina_List* ewk_file_chooser_accept_file_extentions_get(const Ewk_File_Chooser* chooser)
{
EINA_SAFETY_ON_NULL_RETURN_VAL(chooser, 0);
Eina_List* fileExtentions = 0;
size_t count = chooser->fileChooser->settings().acceptFileExtensions.size();
for (size_t i = 0; i < count; ++i)
fileExtentions = eina_list_append(fileExtentions, eina_stringshare_add(chooser->fileChooser->settings().acceptFileExtensions[i].utf8().data()));
return fileExtentions;
}
Eina_List* ewk_file_chooser_selected_files_get(const Ewk_File_Chooser* chooser)
{
EINA_SAFETY_ON_NULL_RETURN_VAL(chooser, 0);
Eina_List* files = 0;
size_t count = chooser->fileChooser->settings().selectedFiles.size();
for (size_t i = 0; i < count; ++i)
files = eina_list_append(files, eina_stringshare_add(chooser->fileChooser->settings().selectedFiles[i].utf8().data()));
return files;
}
Ewk_File_Chooser_Capture_Type ewk_file_chooser_capture_get(const Ewk_File_Chooser* chooser)
{
#if ENABLE(MEDIA_CAPTURE)
EINA_SAFETY_ON_NULL_RETURN_VAL(chooser, EWK_FILE_CHOOSER_CAPTURE_TYPE_INVALID);
String capture = chooser->fileChooser->settings().capture;
if (capture == "camera")
return EWK_FILE_CHOOSER_CAPTURE_TYPE_CAMERA;
if (capture == "camcorder")
return EWK_FILE_CHOOSER_CAPTURE_TYPE_CAMCORDER;
if (capture == "microphone")
return EWK_FILE_CHOOSER_CAPTURE_TYPE_MICROPHONE;
return EWK_FILE_CHOOSER_CAPTURE_TYPE_FILESYSTEM;
#else
UNUSED_PARAM(chooser);
return EWK_FILE_CHOOSER_CAPTURE_TYPE_INVALID;
#endif
}
Ewk_File_Chooser* ewk_file_chooser_new(WebCore::FileChooser* fileChooser)
{
Ewk_File_Chooser* ewkFileChooser = new Ewk_File_Chooser;
ewkFileChooser->fileChooser = fileChooser;
return ewkFileChooser;
}
void ewk_file_chooser_free(Ewk_File_Chooser* chooser)
{
chooser->fileChooser = 0;
delete chooser;
}
| martonw/phantomjs | src/qt/qtwebkit/Source/WebKit/efl/ewk/ewk_file_chooser.cpp | C++ | bsd-3-clause | 3,901 |
from django.contrib.postgres.signals import register_hstore_handler
from django.db.migrations.operations.base import Operation
class CreateExtension(Operation):
reversible = True
def __init__(self, name):
self.name = name
def state_forwards(self, app_label, state):
pass
def database_forwards(self, app_label, schema_editor, from_state, to_state):
if schema_editor.connection.vendor != 'postgresql':
return
schema_editor.execute("CREATE EXTENSION IF NOT EXISTS %s" % self.name)
def database_backwards(self, app_label, schema_editor, from_state, to_state):
schema_editor.execute("DROP EXTENSION %s" % self.name)
def describe(self):
return "Creates extension %s" % self.name
class HStoreExtension(CreateExtension):
def __init__(self):
self.name = 'hstore'
def database_forwards(self, app_label, schema_editor, from_state, to_state):
super(HStoreExtension, self).database_forwards(app_label, schema_editor, from_state, to_state)
# Register hstore straight away as it cannot be done before the
# extension is installed, a subsequent data migration would use the
# same connection
register_hstore_handler(schema_editor.connection)
class UnaccentExtension(CreateExtension):
def __init__(self):
self.name = 'unaccent'
| jsoref/django | django/contrib/postgres/operations.py | Python | bsd-3-clause | 1,377 |
/*
* Copyright 2010 The Android Open Source Project
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkPDFCatalog.h"
#include "SkPDFDevice.h"
#include "SkPDFPage.h"
#include "SkPDFResourceDict.h"
#include "SkStream.h"
SkPDFPage::SkPDFPage(SkPDFDevice* content)
: SkPDFDict("Page"),
fDevice(content) {
SkSafeRef(content);
}
SkPDFPage::~SkPDFPage() {}
void SkPDFPage::finalizePage(SkPDFCatalog* catalog, bool firstPage,
const SkTSet<SkPDFObject*>& knownResourceObjects,
SkTSet<SkPDFObject*>* newResourceObjects) {
SkPDFResourceDict* resourceDict = fDevice->getResourceDict();
if (fContentStream.get() == NULL) {
insert("Resources", resourceDict);
SkSafeUnref(this->insert("MediaBox", fDevice->copyMediaBox()));
if (!SkToBool(catalog->getDocumentFlags() &
SkPDFDocument::kNoLinks_Flags)) {
SkPDFArray* annots = fDevice->getAnnotations();
if (annots && annots->size() > 0) {
insert("Annots", annots);
}
}
SkAutoTUnref<SkStream> content(fDevice->content());
fContentStream.reset(new SkPDFStream(content.get()));
insert("Contents", new SkPDFObjRef(fContentStream.get()))->unref();
}
catalog->addObject(fContentStream.get(), firstPage);
resourceDict->getReferencedResources(knownResourceObjects,
newResourceObjects,
true);
}
off_t SkPDFPage::getPageSize(SkPDFCatalog* catalog, off_t fileOffset) {
SkASSERT(fContentStream.get() != NULL);
catalog->setFileOffset(fContentStream.get(), fileOffset);
return fContentStream->getOutputSize(catalog, true);
}
void SkPDFPage::emitPage(SkWStream* stream, SkPDFCatalog* catalog) {
SkASSERT(fContentStream.get() != NULL);
fContentStream->emitObject(stream, catalog, true);
}
// static
void SkPDFPage::GeneratePageTree(const SkTDArray<SkPDFPage*>& pages,
SkPDFCatalog* catalog,
SkTDArray<SkPDFDict*>* pageTree,
SkPDFDict** rootNode) {
// PDF wants a tree describing all the pages in the document. We arbitrary
// choose 8 (kNodeSize) as the number of allowed children. The internal
// nodes have type "Pages" with an array of children, a parent pointer, and
// the number of leaves below the node as "Count." The leaves are passed
// into the method, have type "Page" and need a parent pointer. This method
// builds the tree bottom up, skipping internal nodes that would have only
// one child.
static const int kNodeSize = 8;
SkAutoTUnref<SkPDFName> kidsName(new SkPDFName("Kids"));
SkAutoTUnref<SkPDFName> countName(new SkPDFName("Count"));
SkAutoTUnref<SkPDFName> parentName(new SkPDFName("Parent"));
// curNodes takes a reference to its items, which it passes to pageTree.
SkTDArray<SkPDFDict*> curNodes;
curNodes.setReserve(pages.count());
for (int i = 0; i < pages.count(); i++) {
SkSafeRef(pages[i]);
curNodes.push(pages[i]);
}
// nextRoundNodes passes its references to nodes on to curNodes.
SkTDArray<SkPDFDict*> nextRoundNodes;
nextRoundNodes.setReserve((pages.count() + kNodeSize - 1)/kNodeSize);
int treeCapacity = kNodeSize;
do {
for (int i = 0; i < curNodes.count(); ) {
if (i > 0 && i + 1 == curNodes.count()) {
nextRoundNodes.push(curNodes[i]);
break;
}
SkPDFDict* newNode = new SkPDFDict("Pages");
SkAutoTUnref<SkPDFObjRef> newNodeRef(new SkPDFObjRef(newNode));
SkAutoTUnref<SkPDFArray> kids(new SkPDFArray);
kids->reserve(kNodeSize);
int count = 0;
for (; i < curNodes.count() && count < kNodeSize; i++, count++) {
curNodes[i]->insert(parentName.get(), newNodeRef.get());
kids->append(new SkPDFObjRef(curNodes[i]))->unref();
// TODO(vandebo): put the objects in strict access order.
// Probably doesn't matter because they are so small.
if (curNodes[i] != pages[0]) {
pageTree->push(curNodes[i]); // Transfer reference.
catalog->addObject(curNodes[i], false);
} else {
SkSafeUnref(curNodes[i]);
catalog->addObject(curNodes[i], true);
}
}
// treeCapacity is the number of leaf nodes possible for the
// current set of subtrees being generated. (i.e. 8, 64, 512, ...).
// It is hard to count the number of leaf nodes in the current
// subtree. However, by construction, we know that unless it's the
// last subtree for the current depth, the leaf count will be
// treeCapacity, otherwise it's what ever is left over after
// consuming treeCapacity chunks.
int pageCount = treeCapacity;
if (i == curNodes.count()) {
pageCount = ((pages.count() - 1) % treeCapacity) + 1;
}
newNode->insert(countName.get(), new SkPDFInt(pageCount))->unref();
newNode->insert(kidsName.get(), kids.get());
nextRoundNodes.push(newNode); // Transfer reference.
}
curNodes = nextRoundNodes;
nextRoundNodes.rewind();
treeCapacity *= kNodeSize;
} while (curNodes.count() > 1);
pageTree->push(curNodes[0]); // Transfer reference.
catalog->addObject(curNodes[0], false);
if (rootNode) {
*rootNode = curNodes[0];
}
}
const SkTDArray<SkPDFFont*>& SkPDFPage::getFontResources() const {
return fDevice->getFontResources();
}
const SkPDFGlyphSetMap& SkPDFPage::getFontGlyphUsage() const {
return fDevice->getFontGlyphUsage();
}
void SkPDFPage::appendDestinations(SkPDFDict* dict) {
fDevice->appendDestinations(dict, this);
}
| ModdedPA/android_external_skia | src/pdf/SkPDFPage.cpp | C++ | bsd-3-clause | 6,145 |
define(function (require) {
var Gradient = require('zrender/graphic/Gradient');
return function (seriesType, styleType, ecModel) {
function encodeColor(seriesModel) {
var colorAccessPath = [styleType, 'normal', 'color'];
var colorList = ecModel.get('color');
var data = seriesModel.getData();
var color = seriesModel.get(colorAccessPath) // Set in itemStyle
|| colorList[seriesModel.seriesIndex % colorList.length]; // Default color
// FIXME Set color function or use the platte color
data.setVisual('color', color);
// Only visible series has each data be visual encoded
if (!ecModel.isSeriesFiltered(seriesModel)) {
if (typeof color === 'function' && !(color instanceof Gradient)) {
data.each(function (idx) {
data.setItemVisual(
idx, 'color', color(seriesModel.getDataParams(idx))
);
});
}
data.each(function (idx) {
var itemModel = data.getItemModel(idx);
var color = itemModel.get(colorAccessPath, true);
if (color != null) {
data.setItemVisual(idx, 'color', color);
}
});
}
}
seriesType ? ecModel.eachSeriesByType(seriesType, encodeColor)
: ecModel.eachSeries(encodeColor);
};
}); | tuananh3988/m5c | backend/web/vendors/echarts/src/visual/seriesColor.js | JavaScript | bsd-3-clause | 1,546 |
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Tool
* @subpackage Framework
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
/**
* @see Zend_Tool_Project_Context_Filesystem_Directory
*/
require_once 'Zend/Tool/Project/Context/Filesystem/Directory.php';
/**
* This class is the front most class for utilizing Zend_Tool_Project
*
* A profile is a hierarchical set of resources that keep track of
* items within a specific project.
*
* @category Zend
* @package Zend_Tool
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Tool_Project_Context_Zf_TestApplicationDirectory extends Zend_Tool_Project_Context_Filesystem_Directory
{
/**
* @var string
*/
protected $_filesystemName = 'application';
/**
* getName()
*
* @return string
*/
public function getName()
{
return 'TestApplicationDirectory';
}
}
| kipnos/ZF1-Ticket | library/Zend/Tool/Project/Context/Zf/TestApplicationDirectory.php | PHP | bsd-3-clause | 1,603 |
package etcd
import (
"errors"
)
// Errors introduced by the Watch command.
var (
ErrWatchStoppedByUser = errors.New("Watch stopped by the user via stop channel")
)
// If recursive is set to true the watch returns the first change under the given
// prefix since the given index.
//
// If recursive is set to false the watch returns the first change to the given key
// since the given index.
//
// To watch for the latest change, set waitIndex = 0.
//
// If a receiver channel is given, it will be a long-term watch. Watch will block at the
//channel. After someone receives the channel, it will go on to watch that
// prefix. If a stop channel is given, the client can close long-term watch using
// the stop channel.
func (c *Client) Watch(prefix string, waitIndex uint64, recursive bool,
receiver chan *Response, stop chan bool) (*Response, error) {
logger.Debugf("watch %s [%s]", prefix, c.cluster.Leader)
if receiver == nil {
raw, err := c.watchOnce(prefix, waitIndex, recursive, stop)
if err != nil {
return nil, err
}
return raw.Unmarshal()
}
defer close(receiver)
for {
raw, err := c.watchOnce(prefix, waitIndex, recursive, stop)
if err != nil {
return nil, err
}
resp, err := raw.Unmarshal()
if err != nil {
return nil, err
}
waitIndex = resp.Node.ModifiedIndex + 1
receiver <- resp
}
}
func (c *Client) RawWatch(prefix string, waitIndex uint64, recursive bool,
receiver chan *RawResponse, stop chan bool) (*RawResponse, error) {
logger.Debugf("rawWatch %s [%s]", prefix, c.cluster.Leader)
if receiver == nil {
return c.watchOnce(prefix, waitIndex, recursive, stop)
}
for {
raw, err := c.watchOnce(prefix, waitIndex, recursive, stop)
if err != nil {
return nil, err
}
resp, err := raw.Unmarshal()
if err != nil {
return nil, err
}
waitIndex = resp.Node.ModifiedIndex + 1
receiver <- raw
}
}
// helper func
// return when there is change under the given prefix
func (c *Client) watchOnce(key string, waitIndex uint64, recursive bool, stop chan bool) (*RawResponse, error) {
options := Options{
"wait": true,
}
if waitIndex > 0 {
options["waitIndex"] = waitIndex
}
if recursive {
options["recursive"] = true
}
resp, err := c.getCancelable(key, options, stop)
if err == ErrRequestCancelled {
return nil, ErrWatchStoppedByUser
}
return resp, err
}
| cgvarela/vitess | Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/watch.go | GO | bsd-3-clause | 2,367 |
/*
* Copyright (C) 2012 Samsung Electronics
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "config.h"
#include "NavigatorBattery.h"
#if ENABLE(BATTERY_STATUS)
#include "BatteryController.h"
#include "BatteryManager.h"
#include "Navigator.h"
#include "ScriptExecutionContext.h"
namespace WebCore {
NavigatorBattery::NavigatorBattery()
{
}
NavigatorBattery::~NavigatorBattery()
{
}
BatteryManager* NavigatorBattery::webkitBattery(Navigator* navigator)
{
if (!navigator->frame())
return 0;
NavigatorBattery* navigatorBattery = NavigatorBattery::from(navigator);
if (!navigatorBattery->m_batteryManager)
navigatorBattery->m_batteryManager = BatteryManager::create(navigator);
return navigatorBattery->m_batteryManager.get();
}
const char* NavigatorBattery::supplementName()
{
return "NavigatorBattery";
}
NavigatorBattery* NavigatorBattery::from(Navigator* navigator)
{
NavigatorBattery* supplement = static_cast<NavigatorBattery*>(Supplement<Navigator>::from(navigator, supplementName()));
if (!supplement) {
supplement = new NavigatorBattery();
provideTo(navigator, supplementName(), adoptPtr(supplement));
}
return supplement;
}
BatteryManager* NavigatorBattery::batteryManager()
{
return m_batteryManager.get();
}
} // namespace WebCore
#endif // ENABLE(BATTERY_STATUS)
| thomasrogers03/phantomjs | src/qt/qtwebkit/Source/WebCore/Modules/battery/NavigatorBattery.cpp | C++ | bsd-3-clause | 2,112 |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.component.restlet;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.util.EntityUtils;
import org.junit.Test;
/**
*
* @version
*/
public class RestletExceptionResponseTest extends RestletTestSupport {
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() throws Exception {
from("restlet:http://localhost:" + portNum + "/users/{username}?restletMethod=POST").process(new Processor() {
public void process(Exchange exchange) throws Exception {
exchange.setException(new IllegalArgumentException("Damn something went wrong"));
}
});
from("direct:start").to("restlet:http://localhost:" + portNum + "/users/tester?restletMethod=POST");
}
};
}
@Test
public void testExceptionResponse() throws Exception {
HttpResponse response = doExecute(new HttpPost("http://localhost:" + portNum + "/users/homer"));
String body = EntityUtils.toString(response.getEntity());
assertHttpResponse(response, 500, "text/plain");
assertTrue(body.contains("IllegalArgumentException"));
assertTrue(body.contains("Damn something went wrong"));
}
@Test
public void testRestletProducerGetExceptionResponse() throws Exception {
sendRequest("restlet:http://localhost:" + portNum + "/users/tester?restletMethod=POST");
}
@Test
public void testSendRequestDirectEndpoint() throws Exception {
sendRequest("direct:start");
}
protected void sendRequest(String endpointUri) throws Exception {
Exchange exchange = template.request(endpointUri, new Processor() {
@Override
public void process(Exchange exchange) throws Exception {
exchange.getIn().setBody("<order foo='1'/>");
}
});
RestletOperationException exception = (RestletOperationException) exchange.getException();
String body = exception.getResponseBody();
assertEquals("http://localhost:" + portNum + "/users/tester", exception.getUri());
assertTrue(body.contains("IllegalArgumentException"));
assertTrue(body.contains("Damn something went wrong"));
}
}
| salikjan/camel | components/camel-restlet/src/test/java/org/apache/camel/component/restlet/RestletExceptionResponseTest.java | Java | bsd-3-clause | 3,356 |
"""A simple Python template renderer, for a nano-subset of Django syntax."""
# Coincidentally named the same as http://code.activestate.com/recipes/496702/
import re, sys
class Templite(object):
"""A simple template renderer, for a nano-subset of Django syntax.
Supported constructs are extended variable access::
{{var.modifer.modifier|filter|filter}}
loops::
{% for var in list %}...{% endfor %}
and ifs::
{% if var %}...{% endif %}
Comments are within curly-hash markers::
{# This will be ignored #}
Construct a Templite with the template text, then use `render` against a
dictionary context to create a finished string.
"""
def __init__(self, text, *contexts):
"""Construct a Templite with the given `text`.
`contexts` are dictionaries of values to use for future renderings.
These are good for filters and global values.
"""
self.text = text
self.context = {}
for context in contexts:
self.context.update(context)
# Split the text to form a list of tokens.
toks = re.split(r"(?s)({{.*?}}|{%.*?%}|{#.*?#})", text)
# Parse the tokens into a nested list of operations. Each item in the
# list is a tuple with an opcode, and arguments. They'll be
# interpreted by TempliteEngine.
#
# When parsing an action tag with nested content (if, for), the current
# ops list is pushed onto ops_stack, and the parsing continues in a new
# ops list that is part of the arguments to the if or for op.
ops = []
ops_stack = []
for tok in toks:
if tok.startswith('{{'):
# Expression: ('exp', expr)
ops.append(('exp', tok[2:-2].strip()))
elif tok.startswith('{#'):
# Comment: ignore it and move on.
continue
elif tok.startswith('{%'):
# Action tag: split into words and parse further.
words = tok[2:-2].strip().split()
if words[0] == 'if':
# If: ('if', (expr, body_ops))
if_ops = []
assert len(words) == 2
ops.append(('if', (words[1], if_ops)))
ops_stack.append(ops)
ops = if_ops
elif words[0] == 'for':
# For: ('for', (varname, listexpr, body_ops))
assert len(words) == 4 and words[2] == 'in'
for_ops = []
ops.append(('for', (words[1], words[3], for_ops)))
ops_stack.append(ops)
ops = for_ops
elif words[0].startswith('end'):
# Endsomething. Pop the ops stack
ops = ops_stack.pop()
assert ops[-1][0] == words[0][3:]
else:
raise SyntaxError("Don't understand tag %r" % words)
else:
ops.append(('lit', tok))
assert not ops_stack, "Unmatched action tag: %r" % ops_stack[-1][0]
self.ops = ops
def render(self, context=None):
"""Render this template by applying it to `context`.
`context` is a dictionary of values to use in this rendering.
"""
# Make the complete context we'll use.
ctx = dict(self.context)
if context:
ctx.update(context)
# Run it through an engine, and return the result.
engine = _TempliteEngine(ctx)
engine.execute(self.ops)
return "".join(engine.result)
class _TempliteEngine(object):
"""Executes Templite objects to produce strings."""
def __init__(self, context):
self.context = context
self.result = []
def execute(self, ops):
"""Execute `ops` in the engine.
Called recursively for the bodies of if's and loops.
"""
for op, args in ops:
if op == 'lit':
self.result.append(args)
elif op == 'exp':
try:
self.result.append(str(self.evaluate(args)))
except:
exc_class, exc, _ = sys.exc_info()
new_exc = exc_class("Couldn't evaluate {{ %s }}: %s"
% (args, exc))
raise new_exc
elif op == 'if':
expr, body = args
if self.evaluate(expr):
self.execute(body)
elif op == 'for':
var, lis, body = args
vals = self.evaluate(lis)
for val in vals:
self.context[var] = val
self.execute(body)
else:
raise AssertionError("TempliteEngine doesn't grok op %r" % op)
def evaluate(self, expr):
"""Evaluate an expression.
`expr` can have pipes and dots to indicate data access and filtering.
"""
if "|" in expr:
pipes = expr.split("|")
value = self.evaluate(pipes[0])
for func in pipes[1:]:
value = self.evaluate(func)(value)
elif "." in expr:
dots = expr.split('.')
value = self.evaluate(dots[0])
for dot in dots[1:]:
try:
value = getattr(value, dot)
except AttributeError:
value = value[dot]
if hasattr(value, '__call__'):
value = value()
else:
value = self.context[expr]
return value
| axinging/chromium-crosswalk | third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/coverage/templite.py | Python | bsd-3-clause | 5,701 |
define("ace/theme/vibrant_ink",["require","exports","module"],function(a,b,c){var d=a("pilot/dom"),e=".ace-vibrant-ink .ace_editor {\n border: 2px solid rgb(159, 159, 159);\n}\n\n.ace-vibrant-ink .ace_editor.ace_focus {\n border: 2px solid #327fbd;\n}\n\n.ace-vibrant-ink .ace_gutter {\n width: 50px;\n background: #e8e8e8;\n color: #333;\n overflow : hidden;\n}\n\n.ace-vibrant-ink .ace_gutter-layer {\n width: 100%;\n text-align: right;\n}\n\n.ace-vibrant-ink .ace_gutter-layer .ace_gutter-cell {\n padding-right: 6px;\n}\n\n.ace-vibrant-ink .ace_print_margin {\n width: 1px;\n background: #e8e8e8;\n}\n\n.ace-vibrant-ink .ace_scroller {\n background-color: #0F0F0F;\n}\n\n.ace-vibrant-ink .ace_text-layer {\n cursor: text;\n color: #FFFFFF;\n}\n\n.ace-vibrant-ink .ace_cursor {\n border-left: 2px solid #FFFFFF;\n}\n\n.ace-vibrant-ink .ace_cursor.ace_overwrite {\n border-left: 0px;\n border-bottom: 1px solid #FFFFFF;\n}\n \n.ace-vibrant-ink .ace_marker-layer .ace_selection {\n background: #6699CC;\n}\n\n.ace-vibrant-ink .ace_marker-layer .ace_step {\n background: rgb(198, 219, 174);\n}\n\n.ace-vibrant-ink .ace_marker-layer .ace_bracket {\n margin: -1px 0 0 -1px;\n border: 1px solid #99CC99;\n}\n\n.ace-vibrant-ink .ace_marker-layer .ace_active_line {\n background: #333333;\n}\n\n \n.ace-vibrant-ink .ace_invisible {\n color: #404040;\n}\n\n.ace-vibrant-ink .ace_keyword {\n color:#FF6600;\n}\n\n.ace-vibrant-ink .ace_keyword.ace_operator {\n \n}\n\n.ace-vibrant-ink .ace_constant {\n \n}\n\n.ace-vibrant-ink .ace_constant.ace_language {\n color:#339999;\n}\n\n.ace-vibrant-ink .ace_constant.ace_library {\n \n}\n\n.ace-vibrant-ink .ace_constant.ace_numeric {\n color:#99CC99;\n}\n\n.ace-vibrant-ink .ace_invalid {\n color:#CCFF33;\n background-color:#000000;\n}\n\n.ace-vibrant-ink .ace_invalid.ace_illegal {\n \n}\n\n.ace-vibrant-ink .ace_invalid.ace_deprecated {\n color:#CCFF33;\n background-color:#000000;\n}\n\n.ace-vibrant-ink .ace_support {\n \n}\n\n.ace-vibrant-ink .ace_support.ace_function {\n color:#FFCC00;\n}\n\n.ace-vibrant-ink .ace_function.ace_buildin {\n \n}\n\n.ace-vibrant-ink .ace_string {\n color:#66FF00;\n}\n\n.ace-vibrant-ink .ace_string.ace_regexp {\n \n}\n\n.ace-vibrant-ink .ace_comment {\n color:#9933CC;\n}\n\n.ace-vibrant-ink .ace_comment.ace_doc {\n \n}\n\n.ace-vibrant-ink .ace_comment.ace_doc.ace_tag {\n \n}\n\n.ace-vibrant-ink .ace_variable {\n \n}\n\n.ace-vibrant-ink .ace_variable.ace_language {\n \n}\n\n.ace-vibrant-ink .ace_xml_pe {\n \n}";d.importCssString(e),b.cssClass="ace-vibrant-ink"}) | emailbox/convomail_server | public/app/js/libs/ace/theme-vibrant_ink.js | JavaScript | bsd-3-clause | 2,593 |
"""
HttpError Spider Middleware
See documentation in docs/topics/spider-middleware.rst
"""
import logging
from scrapy.exceptions import IgnoreRequest
logger = logging.getLogger(__name__)
class HttpError(IgnoreRequest):
"""A non-200 response was filtered"""
def __init__(self, response, *args, **kwargs):
self.response = response
super(HttpError, self).__init__(*args, **kwargs)
class HttpErrorMiddleware(object):
@classmethod
def from_crawler(cls, crawler):
return cls(crawler.settings)
def __init__(self, settings):
self.handle_httpstatus_all = settings.getbool('HTTPERROR_ALLOW_ALL')
self.handle_httpstatus_list = settings.getlist('HTTPERROR_ALLOWED_CODES')
def process_spider_input(self, response, spider):
if 200 <= response.status < 300: # common case
return
meta = response.meta
if 'handle_httpstatus_all' in meta:
return
if 'handle_httpstatus_list' in meta:
allowed_statuses = meta['handle_httpstatus_list']
elif self.handle_httpstatus_all:
return
else:
allowed_statuses = getattr(spider, 'handle_httpstatus_list', self.handle_httpstatus_list)
if response.status in allowed_statuses:
return
raise HttpError(response, 'Ignoring non-200 response')
def process_spider_exception(self, response, exception, spider):
if isinstance(exception, HttpError):
logger.debug(
"Ignoring response %(response)r: HTTP status code is not handled or not allowed",
{'response': response}, extra={'spider': spider},
)
return []
| cyberplant/scrapy | scrapy/spidermiddlewares/httperror.py | Python | bsd-3-clause | 1,706 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.