code
stringlengths 2
1.05M
|
---|
(function() {
var Ext = window.Ext4 || window.Ext;
/**
* Extra data types for Rally REST JSON API
* @private
*/
Ext.define('Rally.apps.roadmapplanningboard.DataTypes', {}, function () {
Ext.apply(Ext.data.Types, {
/**
* @property {Object} COLLECTION
*/
COLLECTION: {
type: 'collection',
sortType: Ext.data.SortTypes.none
}
});
});
})();
|
var group___c_m_s_i_s___s_c_b =
[
[ "SCB_Type", "struct_s_c_b___type.html", [
[ "ADR", "struct_s_c_b___type.html#a5c0e2e1c7195d4dc09a5ca077c596318", null ],
[ "AFSR", "struct_s_c_b___type.html#ab9176079ea223dd8902589da91af63a2", null ],
[ "AIRCR", "struct_s_c_b___type.html#aaec159b48828355cb770049b8b2e8d91", null ],
[ "BFAR", "struct_s_c_b___type.html#ad49f99b1c83dcab356579af171bfa475", null ],
[ "CCR", "struct_s_c_b___type.html#a5e1322e27c40bf91d172f9673f205c97", null ],
[ "CFSR", "struct_s_c_b___type.html#ae6b1e9cde3f94195206c016214cf3936", null ],
[ "CPACR", "struct_s_c_b___type.html#acccaf5688449c8253e9952ddc2161528", null ],
[ "CPUID", "struct_s_c_b___type.html#a30abfea43143a424074f682bd61eace0", null ],
[ "DFR", "struct_s_c_b___type.html#a1b9a71780ae327f1f337a2176b777618", null ],
[ "DFSR", "struct_s_c_b___type.html#a415598d9009bb3ffe9f35e03e5a386fe", null ],
[ "HFSR", "struct_s_c_b___type.html#a87aadbc5e1ffb76d755cf13f4721ae71", null ],
[ "ICSR", "struct_s_c_b___type.html#a8fec9e122b923822e7f951cd48cf1d47", null ],
[ "ISAR", "struct_s_c_b___type.html#a130a0c6b3da7f29507a1888afbdce7ee", null ],
[ "MMFAR", "struct_s_c_b___type.html#a88820a178974aa7b7927155cee5c47ed", null ],
[ "MMFR", "struct_s_c_b___type.html#ab0dc71239f7d5ffe2e78e683b9530064", null ],
[ "PFR", "struct_s_c_b___type.html#a00a6649cfac6bbadee51d6ba4c73001d", null ],
[ "RESERVED0", "struct_s_c_b___type.html#a92bdd34d0bb3e2d14a3ce60040036510", null ],
[ "SCR", "struct_s_c_b___type.html#a64a95891ad3e904dd5548112539c1c98", null ],
[ "SHCSR", "struct_s_c_b___type.html#a04d136e5436e5fa2fb2aaa78a5f86b19", null ],
[ "SHP", "struct_s_c_b___type.html#a17dc9f83c53cbf7fa249e79a2d2a43f8", null ],
[ "VTOR", "struct_s_c_b___type.html#aaf388a921a016cae590cfcf1e43b1cdf", null ]
] ],
[ "SCB_AIRCR_ENDIANESS_Msk", "group___c_m_s_i_s___s_c_b.html#ga2f571f93d3d4a6eac9a3040756d3d951", null ],
[ "SCB_AIRCR_ENDIANESS_Pos", "group___c_m_s_i_s___s_c_b.html#gad31dec98fbc0d33ace63cb1f1a927923", null ],
[ "SCB_AIRCR_PRIGROUP_Msk", "group___c_m_s_i_s___s_c_b.html#ga8be60fff03f48d0d345868060dc6dae7", null ],
[ "SCB_AIRCR_PRIGROUP_Pos", "group___c_m_s_i_s___s_c_b.html#gaca155deccdeca0f2c76b8100d24196c8", null ],
[ "SCB_AIRCR_SYSRESETREQ_Msk", "group___c_m_s_i_s___s_c_b.html#gaae1181119559a5bd36e62afa373fa720", null ],
[ "SCB_AIRCR_SYSRESETREQ_Pos", "group___c_m_s_i_s___s_c_b.html#gaffb2737eca1eac0fc1c282a76a40953c", null ],
[ "SCB_AIRCR_VECTCLRACTIVE_Msk", "group___c_m_s_i_s___s_c_b.html#ga212c5ab1c1c82c807d30d2307aa8d218", null ],
[ "SCB_AIRCR_VECTCLRACTIVE_Pos", "group___c_m_s_i_s___s_c_b.html#gaa30a12e892bb696e61626d71359a9029", null ],
[ "SCB_AIRCR_VECTKEY_Msk", "group___c_m_s_i_s___s_c_b.html#ga90c7cf0c490e7ae55f9503a7fda1dd22", null ],
[ "SCB_AIRCR_VECTKEY_Pos", "group___c_m_s_i_s___s_c_b.html#gaaa27c0ba600bf82c3da08c748845b640", null ],
[ "SCB_AIRCR_VECTKEYSTAT_Msk", "group___c_m_s_i_s___s_c_b.html#gabacedaefeefc73d666bbe59ece904493", null ],
[ "SCB_AIRCR_VECTKEYSTAT_Pos", "group___c_m_s_i_s___s_c_b.html#gaec404750ff5ca07f499a3c06b62051ef", null ],
[ "SCB_AIRCR_VECTRESET_Msk", "group___c_m_s_i_s___s_c_b.html#ga3006e31968bb9725e7b4ee0784d99f7f", null ],
[ "SCB_AIRCR_VECTRESET_Pos", "group___c_m_s_i_s___s_c_b.html#ga0d483d9569cd9d1b46ec0d171b1f18d8", null ],
[ "SCB_CCR_BFHFNMIGN_Msk", "group___c_m_s_i_s___s_c_b.html#ga89a28cc31cfc7d52d9d7a8fcc69c7eac", null ],
[ "SCB_CCR_BFHFNMIGN_Pos", "group___c_m_s_i_s___s_c_b.html#ga4010a4f9e2a745af1b58abe1f791ebbf", null ],
[ "SCB_CCR_DIV_0_TRP_Msk", "group___c_m_s_i_s___s_c_b.html#gabb9aeac71b3abd8586d0297070f61dcb", null ],
[ "SCB_CCR_DIV_0_TRP_Pos", "group___c_m_s_i_s___s_c_b.html#gac8d512998bb8cd9333fb7627ddf59bba", null ],
[ "SCB_CCR_NONBASETHRDENA_Msk", "group___c_m_s_i_s___s_c_b.html#gafe0f6be81b35d72d0736a0a1e3b4fbb3", null ],
[ "SCB_CCR_NONBASETHRDENA_Pos", "group___c_m_s_i_s___s_c_b.html#gab4615f7deb07386350365b10240a3c83", null ],
[ "SCB_CCR_STKALIGN_Msk", "group___c_m_s_i_s___s_c_b.html#ga33cf22d3d46af158a03aad25ddea1bcb", null ],
[ "SCB_CCR_STKALIGN_Pos", "group___c_m_s_i_s___s_c_b.html#gac2d20a250960a432cc74da59d20e2f86", null ],
[ "SCB_CCR_UNALIGN_TRP_Msk", "group___c_m_s_i_s___s_c_b.html#ga68c96ad594af70c007923979085c99e0", null ],
[ "SCB_CCR_UNALIGN_TRP_Pos", "group___c_m_s_i_s___s_c_b.html#gac4e4928b864ea10fc24dbbc57d976229", null ],
[ "SCB_CCR_USERSETMPEND_Msk", "group___c_m_s_i_s___s_c_b.html#ga4cf59b6343ca962c80e1885710da90aa", null ],
[ "SCB_CCR_USERSETMPEND_Pos", "group___c_m_s_i_s___s_c_b.html#ga789e41f45f59a8cd455fd59fa7652e5e", null ],
[ "SCB_CFSR_BUSFAULTSR_Msk", "group___c_m_s_i_s___s_c_b.html#ga26dc1ddfdc37a6b92597a6f7e498c1d6", null ],
[ "SCB_CFSR_BUSFAULTSR_Pos", "group___c_m_s_i_s___s_c_b.html#ga555a24f4f57d199f91d1d1ab7c8c3c8a", null ],
[ "SCB_CFSR_MEMFAULTSR_Msk", "group___c_m_s_i_s___s_c_b.html#gad46716159a3808c9e7da22067d6bec98", null ],
[ "SCB_CFSR_MEMFAULTSR_Pos", "group___c_m_s_i_s___s_c_b.html#ga91f41491cec5b5acca3fbc94efbd799e", null ],
[ "SCB_CFSR_USGFAULTSR_Msk", "group___c_m_s_i_s___s_c_b.html#ga565807b1a3f31891f1f967d0fa30d03f", null ],
[ "SCB_CFSR_USGFAULTSR_Pos", "group___c_m_s_i_s___s_c_b.html#gac8e4197b295c8560e68e2d71285c7879", null ],
[ "SCB_CPUID_ARCHITECTURE_Msk", "group___c_m_s_i_s___s_c_b.html#gafae4a1f27a927338ae9dc51a0e146213", null ],
[ "SCB_CPUID_ARCHITECTURE_Pos", "group___c_m_s_i_s___s_c_b.html#gaf8b3236b08fb8e840efb682645fb0e98", null ],
[ "SCB_CPUID_IMPLEMENTER_Msk", "group___c_m_s_i_s___s_c_b.html#ga0932b31faafd47656a03ced75a31d99b", null ],
[ "SCB_CPUID_IMPLEMENTER_Pos", "group___c_m_s_i_s___s_c_b.html#ga58686b88f94f789d4e6f429fe1ff58cf", null ],
[ "SCB_CPUID_PARTNO_Msk", "group___c_m_s_i_s___s_c_b.html#ga98e581423ca016680c238c469aba546d", null ],
[ "SCB_CPUID_PARTNO_Pos", "group___c_m_s_i_s___s_c_b.html#ga705f68eaa9afb042ca2407dc4e4629ac", null ],
[ "SCB_CPUID_REVISION_Msk", "group___c_m_s_i_s___s_c_b.html#ga2ec0448b6483f77e7f5d08b4b81d85df", null ],
[ "SCB_CPUID_REVISION_Pos", "group___c_m_s_i_s___s_c_b.html#ga3c3d9071e574de11fb27ba57034838b1", null ],
[ "SCB_CPUID_VARIANT_Msk", "group___c_m_s_i_s___s_c_b.html#gad358dfbd04300afc1824329d128b99e8", null ],
[ "SCB_CPUID_VARIANT_Pos", "group___c_m_s_i_s___s_c_b.html#ga104462bd0815391b4044a70bd15d3a71", null ],
[ "SCB_DFSR_BKPT_Msk", "group___c_m_s_i_s___s_c_b.html#ga609edf8f50bc49adb51ae28bcecefe1f", null ],
[ "SCB_DFSR_BKPT_Pos", "group___c_m_s_i_s___s_c_b.html#gaf28fdce48655f0dcefb383aebf26b050", null ],
[ "SCB_DFSR_DWTTRAP_Msk", "group___c_m_s_i_s___s_c_b.html#ga3f7384b8a761704655fd45396a305663", null ],
[ "SCB_DFSR_DWTTRAP_Pos", "group___c_m_s_i_s___s_c_b.html#gaccf82364c6d0ed7206f1084277b7cc61", null ],
[ "SCB_DFSR_EXTERNAL_Msk", "group___c_m_s_i_s___s_c_b.html#ga3cba2ec1f588ce0b10b191d6b0d23399", null ],
[ "SCB_DFSR_EXTERNAL_Pos", "group___c_m_s_i_s___s_c_b.html#ga13f502fb5ac673df9c287488c40b0c1d", null ],
[ "SCB_DFSR_HALTED_Msk", "group___c_m_s_i_s___s_c_b.html#ga200bcf918d57443b5e29e8ce552e4bdf", null ],
[ "SCB_DFSR_HALTED_Pos", "group___c_m_s_i_s___s_c_b.html#gaef4ec28427f9f88ac70a13ae4e541378", null ],
[ "SCB_DFSR_VCATCH_Msk", "group___c_m_s_i_s___s_c_b.html#gacbb931575c07b324ec793775b7c44d05", null ],
[ "SCB_DFSR_VCATCH_Pos", "group___c_m_s_i_s___s_c_b.html#gad02d3eaf062ac184c18a7889c9b6de57", null ],
[ "SCB_HFSR_DEBUGEVT_Msk", "group___c_m_s_i_s___s_c_b.html#gababd60e94756bb33929d5e6f25d8dba3", null ],
[ "SCB_HFSR_DEBUGEVT_Pos", "group___c_m_s_i_s___s_c_b.html#ga300c90cfb7b35c82b4d44ad16c757ffb", null ],
[ "SCB_HFSR_FORCED_Msk", "group___c_m_s_i_s___s_c_b.html#ga6560d97ed043bc01152a7247bafa3157", null ],
[ "SCB_HFSR_FORCED_Pos", "group___c_m_s_i_s___s_c_b.html#gab361e54183a378474cb419ae2a55d6f4", null ],
[ "SCB_HFSR_VECTTBL_Msk", "group___c_m_s_i_s___s_c_b.html#gaac5e289211d0a63fe879a9691cb9e1a9", null ],
[ "SCB_HFSR_VECTTBL_Pos", "group___c_m_s_i_s___s_c_b.html#ga77993da8de35adea7bda6a4475f036ab", null ],
[ "SCB_ICSR_ISRPENDING_Msk", "group___c_m_s_i_s___s_c_b.html#ga056d74fd538e5d36d3be1f28d399c877", null ],
[ "SCB_ICSR_ISRPENDING_Pos", "group___c_m_s_i_s___s_c_b.html#ga10749d92b9b744094b845c2eb46d4319", null ],
[ "SCB_ICSR_ISRPREEMPT_Msk", "group___c_m_s_i_s___s_c_b.html#gaa966600396290808d596fe96e92ca2b5", null ],
[ "SCB_ICSR_ISRPREEMPT_Pos", "group___c_m_s_i_s___s_c_b.html#ga11cb5b1f9ce167b81f31787a77e575df", null ],
[ "SCB_ICSR_NMIPENDSET_Msk", "group___c_m_s_i_s___s_c_b.html#ga340e3f79e9c3607dee9f2c048b6b22e8", null ],
[ "SCB_ICSR_NMIPENDSET_Pos", "group___c_m_s_i_s___s_c_b.html#ga750d4b52624a46d71356db4ea769573b", null ],
[ "SCB_ICSR_PENDSTCLR_Msk", "group___c_m_s_i_s___s_c_b.html#gab241827d2a793269d8cd99b9b28c2157", null ],
[ "SCB_ICSR_PENDSTCLR_Pos", "group___c_m_s_i_s___s_c_b.html#gadbe25e4b333ece1341beb1a740168fdc", null ],
[ "SCB_ICSR_PENDSTSET_Msk", "group___c_m_s_i_s___s_c_b.html#ga7325b61ea0ec323ef2d5c893b112e546", null ],
[ "SCB_ICSR_PENDSTSET_Pos", "group___c_m_s_i_s___s_c_b.html#ga9dbb3358c6167c9c3f85661b90fb2794", null ],
[ "SCB_ICSR_PENDSVCLR_Msk", "group___c_m_s_i_s___s_c_b.html#ga4a901ace381d3c1c74ac82b22fae2e1e", null ],
[ "SCB_ICSR_PENDSVCLR_Pos", "group___c_m_s_i_s___s_c_b.html#gae218d9022288f89faf57187c4d542ecd", null ],
[ "SCB_ICSR_PENDSVSET_Msk", "group___c_m_s_i_s___s_c_b.html#ga1e40d93efb402763c8c00ddcc56724ff", null ],
[ "SCB_ICSR_PENDSVSET_Pos", "group___c_m_s_i_s___s_c_b.html#gab5ded23d2ab1d5ff7cc7ce746205e9fe", null ],
[ "SCB_ICSR_RETTOBASE_Msk", "group___c_m_s_i_s___s_c_b.html#gaca6fc3f79bb550f64fd7df782ed4a5f6", null ],
[ "SCB_ICSR_RETTOBASE_Pos", "group___c_m_s_i_s___s_c_b.html#ga403d154200242629e6d2764bfc12a7ec", null ],
[ "SCB_ICSR_VECTACTIVE_Msk", "group___c_m_s_i_s___s_c_b.html#ga5533791a4ecf1b9301c883047b3e8396", null ],
[ "SCB_ICSR_VECTACTIVE_Pos", "group___c_m_s_i_s___s_c_b.html#gae4f602c7c5c895d5fb687b71b0979fc3", null ],
[ "SCB_ICSR_VECTPENDING_Msk", "group___c_m_s_i_s___s_c_b.html#gacb6992e7c7ddc27a370f62878a21ef72", null ],
[ "SCB_ICSR_VECTPENDING_Pos", "group___c_m_s_i_s___s_c_b.html#gada60c92bf88d6fd21a8f49efa4a127b8", null ],
[ "SCB_SCR_SEVONPEND_Msk", "group___c_m_s_i_s___s_c_b.html#gafb98656644a14342e467505f69a997c9", null ],
[ "SCB_SCR_SEVONPEND_Pos", "group___c_m_s_i_s___s_c_b.html#ga3bddcec40aeaf3d3a998446100fa0e44", null ],
[ "SCB_SCR_SLEEPDEEP_Msk", "group___c_m_s_i_s___s_c_b.html#ga77c06a69c63f4b3f6ec1032e911e18e7", null ],
[ "SCB_SCR_SLEEPDEEP_Pos", "group___c_m_s_i_s___s_c_b.html#gab304f6258ec03bd9a6e7a360515c3cfe", null ],
[ "SCB_SCR_SLEEPONEXIT_Msk", "group___c_m_s_i_s___s_c_b.html#ga50a243e317b9a70781b02758d45b05ee", null ],
[ "SCB_SCR_SLEEPONEXIT_Pos", "group___c_m_s_i_s___s_c_b.html#ga3680a15114d7fdc1e25043b881308fe9", null ],
[ "SCB_SHCSR_BUSFAULTACT_Msk", "group___c_m_s_i_s___s_c_b.html#ga9d7a8b1054b655ad08d85c3c535d4f73", null ],
[ "SCB_SHCSR_BUSFAULTACT_Pos", "group___c_m_s_i_s___s_c_b.html#gaf272760f2df9ecdd8a5fbbd65c0b767a", null ],
[ "SCB_SHCSR_BUSFAULTENA_Msk", "group___c_m_s_i_s___s_c_b.html#ga43e8cbe619c9980e0d1aacc85d9b9e47", null ],
[ "SCB_SHCSR_BUSFAULTENA_Pos", "group___c_m_s_i_s___s_c_b.html#ga3d32edbe4a5c0335f808cfc19ec7e844", null ],
[ "SCB_SHCSR_BUSFAULTPENDED_Msk", "group___c_m_s_i_s___s_c_b.html#ga677c23749c4d348f30fb471d1223e783", null ],
[ "SCB_SHCSR_BUSFAULTPENDED_Pos", "group___c_m_s_i_s___s_c_b.html#gaa22551e24a72b65f1e817f7ab462203b", null ],
[ "SCB_SHCSR_MEMFAULTACT_Msk", "group___c_m_s_i_s___s_c_b.html#ga9147fd4e1b12394ae26eadf900a023a3", null ],
[ "SCB_SHCSR_MEMFAULTACT_Pos", "group___c_m_s_i_s___s_c_b.html#ga7c856f79a75dcc1d1517b19a67691803", null ],
[ "SCB_SHCSR_MEMFAULTENA_Msk", "group___c_m_s_i_s___s_c_b.html#gaf084424fa1f69bea36a1c44899d83d17", null ],
[ "SCB_SHCSR_MEMFAULTENA_Pos", "group___c_m_s_i_s___s_c_b.html#ga685b4564a8760b4506f14ec4307b7251", null ],
[ "SCB_SHCSR_MEMFAULTPENDED_Msk", "group___c_m_s_i_s___s_c_b.html#ga9abc6c2e395f9e5af4ce05fc420fb04c", null ],
[ "SCB_SHCSR_MEMFAULTPENDED_Pos", "group___c_m_s_i_s___s_c_b.html#gaceb60fe2d8a8cb17fcd1c1f6b5aa924f", null ],
[ "SCB_SHCSR_MONITORACT_Msk", "group___c_m_s_i_s___s_c_b.html#gaad09b4bc36e9bccccc2e110d20b16e1a", null ],
[ "SCB_SHCSR_MONITORACT_Pos", "group___c_m_s_i_s___s_c_b.html#ga8b71cf4c61803752a41c96deb00d26af", null ],
[ "SCB_SHCSR_PENDSVACT_Msk", "group___c_m_s_i_s___s_c_b.html#gae0e837241a515d4cbadaaae1faa8e039", null ],
[ "SCB_SHCSR_PENDSVACT_Pos", "group___c_m_s_i_s___s_c_b.html#ga9b9fa69ce4c5ce7fe0861dbccfb15939", null ],
[ "SCB_SHCSR_SVCALLACT_Msk", "group___c_m_s_i_s___s_c_b.html#ga634c0f69a233475289023ae5cb158fdf", null ],
[ "SCB_SHCSR_SVCALLACT_Pos", "group___c_m_s_i_s___s_c_b.html#ga977f5176be2bc8b123873861b38bc02f", null ],
[ "SCB_SHCSR_SVCALLPENDED_Msk", "group___c_m_s_i_s___s_c_b.html#ga6095a7acfbad66f52822b1392be88652", null ],
[ "SCB_SHCSR_SVCALLPENDED_Pos", "group___c_m_s_i_s___s_c_b.html#ga2f93ec9b243f94cdd3e94b8f0bf43641", null ],
[ "SCB_SHCSR_SYSTICKACT_Msk", "group___c_m_s_i_s___s_c_b.html#gafef530088dc6d6bfc9f1893d52853684", null ],
[ "SCB_SHCSR_SYSTICKACT_Pos", "group___c_m_s_i_s___s_c_b.html#gaec9ca3b1213c49e2442373445e1697de", null ],
[ "SCB_SHCSR_USGFAULTACT_Msk", "group___c_m_s_i_s___s_c_b.html#gab3166103b5a5f7931d0df90949c47dfe", null ],
[ "SCB_SHCSR_USGFAULTACT_Pos", "group___c_m_s_i_s___s_c_b.html#gae06f54f5081f01ed3f6824e451ad3656", null ],
[ "SCB_SHCSR_USGFAULTENA_Msk", "group___c_m_s_i_s___s_c_b.html#ga056fb6be590857bbc029bed48b21dd79", null ],
[ "SCB_SHCSR_USGFAULTENA_Pos", "group___c_m_s_i_s___s_c_b.html#gae71949507636fda388ec11d5c2d30b52", null ],
[ "SCB_SHCSR_USGFAULTPENDED_Msk", "group___c_m_s_i_s___s_c_b.html#ga122b4f732732010895e438803a29d3cc", null ],
[ "SCB_SHCSR_USGFAULTPENDED_Pos", "group___c_m_s_i_s___s_c_b.html#ga3cf03acf1fdc2edc3b047ddd47ebbf87", null ],
[ "SCB_VTOR_TBLBASE_Msk", "group___c_m_s_i_s___s_c_b.html#ga778dd0ba178466b2a8877a6b8aa345ee", null ],
[ "SCB_VTOR_TBLBASE_Pos", "group___c_m_s_i_s___s_c_b.html#gad9720a44320c053883d03b883b955751", null ],
[ "SCB_VTOR_TBLOFF_Msk", "group___c_m_s_i_s___s_c_b.html#ga75e395ed74042923e8c93edf50f0996c", null ],
[ "SCB_VTOR_TBLOFF_Pos", "group___c_m_s_i_s___s_c_b.html#gac6a55451ddd38bffcff5a211d29cea78", null ]
]; |
(function() {
'use strict';
/**
* Initialization of badgeFrontend.modules.badges module.
*
* @namespace Modules
*/
angular
.module('badgeFrontend.modules.badges', []);
})();
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var Helpers = function () {
function Helpers() {
_classCallCheck(this, Helpers);
}
_createClass(Helpers, [{
key: 'removeDuplicates',
value: function removeDuplicates(tagArray) {
var result = [];
for (var i = 0, length = tagArray.length; i < length; i++) {
if (result.indexOf(tagArray[i]) < 0) {
result.push(arr[i]);
}
}
return result;
}
}, {
key: 'getClipboardData',
value: function getClipboardData(event) {
if (window.clipboardData) {
return window.clipboardData.getData('Text');
} else if (event.clipboardData) {
return event.clipboardData.getData('text/plain');
} else {
return '';
}
}
}]);
return Helpers;
}();
exports.default = Helpers; |
require("ember-data/core");
require("ember-data/system/adapter");
require('ember-data/serializers/fixture_serializer');
var get = Ember.get;
/**
`DS.FixtureAdapter` is an adapter that loads records from memory.
Its primarily used for development and testing. You can also use
`DS.FixtureAdapter` while working on the API but are not ready to
integrate yet. It is a fully functioning adapter. All CRUD methods
are implemented. You can also implement query logic that a remote
system would do. Its possible to do develop your entire application
with `DS.FixtureAdapter`.
*/
DS.FixtureAdapter = DS.Adapter.extend({
simulateRemoteResponse: true,
latency: 50,
serializer: DS.FixtureSerializer,
/*
Implement this method in order to provide data associated with a type
*/
fixturesForType: function(type) {
if (type.FIXTURES) {
var fixtures = Ember.A(type.FIXTURES);
return fixtures.map(function(fixture){
if(!fixture.id){
throw new Error('the id property must be defined for fixture %@'.fmt(fixture));
}
fixture.id = fixture.id + '';
return fixture;
});
}
return null;
},
/*
Implement this method in order to query fixtures data
*/
queryFixtures: function(fixtures, query, type) {
return fixtures;
},
/*
Implement this method in order to provide provide json for CRUD methods
*/
mockJSON: function(type, record) {
return this.serialize(record, { includeId: true });
},
/*
Adapter methods
*/
generateIdForRecord: function(store, record) {
return Ember.guidFor(record);
},
find: function(store, type, id) {
var fixtures = this.fixturesForType(type),
fixture;
Ember.assert("Unable to find fixtures for model type "+type.toString(), !!fixtures);
if (fixtures) {
fixture = Ember.A(fixtures).findProperty('id', id);
}
if (fixture) {
this.simulateRemoteCall(function() {
this.didFindRecord(store, type, fixture, id);
}, this);
}
},
findMany: function(store, type, ids) {
var fixtures = this.fixturesForType(type);
Ember.assert("Unable to find fixtures for model type "+type.toString(), !!fixtures);
if (fixtures) {
fixtures = fixtures.filter(function(item) {
return ids.indexOf(item.id) !== -1;
});
}
if (fixtures) {
this.simulateRemoteCall(function() {
this.didFindMany(store, type, fixtures);
}, this);
}
},
findAll: function(store, type) {
var fixtures = this.fixturesForType(type);
Ember.assert("Unable to find fixtures for model type "+type.toString(), !!fixtures);
this.simulateRemoteCall(function() {
this.didFindAll(store, type, fixtures);
}, this);
},
findQuery: function(store, type, query, array) {
var fixtures = this.fixturesForType(type);
Ember.assert("Unable to find fixtures for model type "+type.toString(), !!fixtures);
fixtures = this.queryFixtures(fixtures, query, type);
if (fixtures) {
this.simulateRemoteCall(function() {
this.didFindQuery(store, type, fixtures, array);
}, this);
}
},
createRecord: function(store, type, record) {
var fixture = this.mockJSON(type, record);
fixture.id = this.generateIdForRecord(store, record);
this.simulateRemoteCall(function() {
this.didCreateRecord(store, type, record, fixture);
}, this);
},
updateRecord: function(store, type, record) {
var fixture = this.mockJSON(type, record);
this.simulateRemoteCall(function() {
this.didUpdateRecord(store, type, record, fixture);
}, this);
},
deleteRecord: function(store, type, record) {
this.simulateRemoteCall(function() {
this.didDeleteRecord(store, type, record);
}, this);
},
/*
@private
*/
simulateRemoteCall: function(callback, context) {
function response() {
Ember.run(context, callback);
}
if (get(this, 'simulateRemoteResponse')) {
setTimeout(response, get(this, 'latency'));
} else {
response();
}
}
});
|
var View = require('./view');
var templates = require('client/js/templates');
module.exports = View.extend({
template: templates.partials.speakers.gridView,
});
|
var ZeroOrder = require('../src/ZeroOrder');
var sequences = require('./sequences');
var run = function () {
// Algorithm:
// for each test sequence
// for each item in sequence
// for each predictor
// feed previous item and get prediction
// score the prediction according to the item
// add the score to the total score of predictor
//
var sequenceNames = [
'ab',
'noise',
'unfair100',
];
var predictorClasses = [
ZeroOrder,
];
var scoreFn = function (prob) {
return prob;
};
sequenceNames.forEach(function (seqName) {
sequences.load(seqName, function (err, seq) {
if (err) {
console.error(err);
return;
}
console.log('###');
console.log('sequence:', seqName);
predictorClasses.forEach(function (PredictorClass) {
var predictor = new PredictorClass();
var i, prev, next, prediction, prob;
var totalScore = 0;
for (i = 1; i < seq.length; i += 1) {
prev = seq[i - 1];
prediction = predictor.feed(prev);
next = seq[i];
prob = prediction.prob(next);
totalScore += scoreFn(prob);
}
// Reflect class name. See https://stackoverflow.com/a/10314492/638546
var predictorName = predictor.constructor.name;
// Expected score for this predictor given this sequence.
var meanScore = totalScore / (seq.length - 1);
// Report results
console.log('predictor:', predictorName);
console.log(' score:', meanScore);
});
});
});
};
run();
|
/** START loads the header, please insert in every file **/
$("header").load("header.html", function()
{
var linkToMe = $('a[href="'+window.location.href.split('/').pop()+'"]').parent();
linkToMe.addClass('active')
});
$( "a.submenu" ).click(function()
{
$( ".menuBar" ).slideToggle( "normal", function()
{
// Animation complete.
});
});
$( "ul li.dropdown a" ).click(function()
{
$( "ul li.dropdown ul" ).slideToggle( "normal", function()
{
// Animation complete.
});
$('ul li.dropdown').toggleClass('current');
}); |
'use strict';
var ResourceFactory = require('../ResourceFactory');
function makeResourceURL(id) {
return '/banners/image/' + id + '/conversion-tag';
};
var ConvTag = function(adbutler) {
return ResourceFactory.makeResource.call(adbutler, makeResourceURL, {
create: false,
update: false,
delete: false,
list: false,
});
};
// Custom Resource Methods
// Banner.customMethod1 = function() {};
// Banner.customMethod2 = function() {};
module.exports = ConvTag; |
/* global API_HOST */
import fetch from 'isomorphic-fetch';
import querystring from 'querystring';
const REQUEST = 'heroStats/REQUEST';
const OK = 'heroStats/OK';
const ERROR = 'heroStats/ERROR';
export const heroStatsActions = {
REQUEST,
OK,
ERROR,
};
export const getHeroStatsRequest = () => ({
type: REQUEST,
});
export const getHeroStatsOk = payload => ({
type: OK,
payload,
});
export const getHeroStatsError = payload => ({
type: ERROR,
payload,
});
export const getHeroStats = (options = {}) => (dispatch) => {
dispatch(getHeroStatsRequest());
return fetch(`${API_HOST}/api/heroStats?${querystring.stringify(options)}`)
.then(response => response.json())
.then(json => dispatch(getHeroStatsOk(json)))
.catch(error => dispatch(getHeroStatsError(error)));
};
|
import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm4 11h-3v3c0 .55-.45 1-1 1s-1-.45-1-1v-3H8c-.55 0-1-.45-1-1s.45-1 1-1h3V8c0-.55.45-1 1-1s1 .45 1 1v3h3c.55 0 1 .45 1 1s-.45 1-1 1z" />
, 'AddCircleRounded');
|
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory(require("react"));
else if(typeof define === 'function' && define.amd)
define(["react"], factory);
else if(typeof exports === 'object')
exports["PureMenu"] = factory(require("react"));
else
root["PureMenu"] = factory(root["react"]);
})(this, function(__WEBPACK_EXTERNAL_MODULE_6__) {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
module.exports = __webpack_require__(1);
module.exports.List = __webpack_require__(2);
module.exports.Heading = __webpack_require__(3);
module.exports.Item = __webpack_require__(4);
module.exports.Link = __webpack_require__(5);
/***/ },
/* 1 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var classNames = __webpack_require__(7);
var React = __webpack_require__(6);
module.exports = React.createClass({
displayName: 'Menu',
propTypes: {
horizontal: React.PropTypes.bool,
scrollable: React.PropTypes.bool,
},
getDefaultProps:function() {
return {
horizontal: false,
scrollable: false,
};
},
render: function() {
var $__0= this.props,className=$__0.className,horizontal=$__0.horizontal,scrollable=$__0.scrollable,props=(function(source, exclusion) {var rest = {};var hasOwn = Object.prototype.hasOwnProperty;if (source == null) {throw new TypeError();}for (var key in source) {if (hasOwn.call(source, key) && !hasOwn.call(exclusion, key)) {rest[key] = source[key];}}return rest;})($__0,{className:1,horizontal:1,scrollable:1});
var horizontalClass = horizontal && 'pure-menu-horizontal';
var scrollableClass = scrollable && 'pure-menu-scrollable';
return (
React.createElement("div", React.__spread({className:
classNames('pure-menu', className, horizontalClass, scrollableClass)
}, props), props.children)
);
},
});
/***/ },
/* 2 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var classNames = __webpack_require__(7);
var React = __webpack_require__(6);
module.exports = React.createClass({
displayName: 'MenuList',
render: function() {
var $__0= this.props,className=$__0.className,props=(function(source, exclusion) {var rest = {};var hasOwn = Object.prototype.hasOwnProperty;if (source == null) {throw new TypeError();}for (var key in source) {if (hasOwn.call(source, key) && !hasOwn.call(exclusion, key)) {rest[key] = source[key];}}return rest;})($__0,{className:1});
return (
React.createElement("ul", React.__spread({className: classNames('pure-menu-list', className)}, props), props.children)
);
},
});
/***/ },
/* 3 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var classNames = __webpack_require__(7);
var React = __webpack_require__(6);
module.exports = React.createClass({
displayName: 'MenuHeading',
render: function() {
var $__0= this.props,className=$__0.className,props=(function(source, exclusion) {var rest = {};var hasOwn = Object.prototype.hasOwnProperty;if (source == null) {throw new TypeError();}for (var key in source) {if (hasOwn.call(source, key) && !hasOwn.call(exclusion, key)) {rest[key] = source[key];}}return rest;})($__0,{className:1});
return (
React.createElement("span", React.__spread({className: classNames('pure-menu-heading', className)}, props), props.children)
);
},
});
/***/ },
/* 4 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var classNames = __webpack_require__(7);
var React = __webpack_require__(6);
module.exports = React.createClass({
displayName: 'MenuItem',
propTypes: {
disabled: React.PropTypes.bool,
selected: React.PropTypes.bool,
},
getDefaultProps:function() {
return {
disabled: false,
selected: false,
};
},
render: function() {
var $__0= this.props,className=$__0.className,disabled=$__0.disabled,selected=$__0.selected,props=(function(source, exclusion) {var rest = {};var hasOwn = Object.prototype.hasOwnProperty;if (source == null) {throw new TypeError();}for (var key in source) {if (hasOwn.call(source, key) && !hasOwn.call(exclusion, key)) {rest[key] = source[key];}}return rest;})($__0,{className:1,disabled:1,selected:1});
var disabledClass= disabled && 'pure-menu-disabled';
var selectedClass = selected && 'pure-menu-selected';
return (
React.createElement("li", React.__spread({className:
classNames('pure-menu-item', className, disabledClass, selectedClass)
}, props), props.children)
);
},
});
/***/ },
/* 5 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var classNames = __webpack_require__(7);
var React = __webpack_require__(6);
module.exports = React.createClass({
displayName: 'MenuLink',
render: function() {
var $__0= this.props,className=$__0.className,props=(function(source, exclusion) {var rest = {};var hasOwn = Object.prototype.hasOwnProperty;if (source == null) {throw new TypeError();}for (var key in source) {if (hasOwn.call(source, key) && !hasOwn.call(exclusion, key)) {rest[key] = source[key];}}return rest;})($__0,{className:1});
return (
React.createElement("a", React.__spread({className: classNames('pure-menu-link', className)}, props),
props.children
)
);
},
});
/***/ },
/* 6 */
/***/ function(module, exports, __webpack_require__) {
module.exports = __WEBPACK_EXTERNAL_MODULE_6__;
/***/ },
/* 7 */
/***/ function(module, exports, __webpack_require__) {
function classNames() {
var classes = '';
var arg;
for (var i = 0; i < arguments.length; i++) {
arg = arguments[i];
if (!arg) {
continue;
}
if ('string' === typeof arg || 'number' === typeof arg) {
classes += ' ' + arg;
} else if (Object.prototype.toString.call(arg) === '[object Array]') {
classes += ' ' + classNames.apply(null, arg);
} else if ('object' === typeof arg) {
for (var key in arg) {
if (!arg.hasOwnProperty(key) || !arg[key]) {
continue;
}
classes += ' ' + key;
}
}
}
return classes.substr(1);
}
// safely export classNames in case the script is included directly on a page
if (typeof module !== 'undefined' && module.exports) {
module.exports = classNames;
}
/***/ }
/******/ ])
});
; |
/*
* Copyright (c) 2012-2016 André Bargull
* Alle Rechte vorbehalten / All Rights Reserved. Use is subject to license terms.
*
* <https://github.com/anba/es6draft>
*/
const {
assertSyntaxError
} = Assert;
const bindings = {
letIsBoundName: [
"let", "[let]", "{let}", "{let: let}", "{not_let: let}", "[{let}]", "[{not_let: let}]", "{not_let: [let]}",
],
letIsntBoundName: [
"{let: not_let}", "[a = let()]",
]
};
function toStr(number, radix, pad) {
let s = number.toString(radix);
return "0".repeat(pad - s.length) + s;
}
const transformer = [
function noEscape(name) {
return name;
},
function escapeFirstChar(name) {
return `\\u${toStr(name.charCodeAt(0), 16, 4)}${name.substring(1)}`
},
function escapeSecondChar(name) {
return `${name.substring(0, 1)}\\u${toStr(name.charCodeAt(1), 16, 4)}${name.substring(2)}`
},
].map(fn => (n => n.replace("let", fn)));
for (let t of transformer) {
// 12.1.4.2.1 Static Semantics: Early Errors
// It is a Syntax Error if the BoundNames of ForBinding contains "let".
for (let binding of bindings.letIsBoundName) {
binding = t(binding);
assertSyntaxError(`[for (${binding} of []) 0];`);
assertSyntaxError(`(for (${binding} of []) 0);`);
}
for (let binding of bindings.letIsntBoundName) {
binding = t(binding);
Function(`[for (${binding} of []) 0];`);
Function(`(for (${binding} of []) 0);`);
}
}
for (let t of transformer) {
// 13.2.1.1 Static Semantics: Early Errors
// It is a Syntax Error if the BoundNames of LexicalBinding contains "let".
for (let binding of bindings.letIsBoundName) {
binding = t(binding);
assertSyntaxError(`let ${binding} = {};`);
assertSyntaxError(`const ${binding} = {};`);
assertSyntaxError(`for (let ${binding} = {};;);`);
assertSyntaxError(`for (const ${binding} = {};;);`);
assertSyntaxError(`for (let ${binding} in {});`);
assertSyntaxError(`for (const ${binding} in {});`);
assertSyntaxError(`for (let ${binding} of {});`);
assertSyntaxError(`for (const ${binding} of {});`);
}
for (let binding of bindings.letIsntBoundName) {
binding = t(binding);
Function(`let ${binding} = {};`);
Function(`const ${binding} = {};`);
Function(`for (let ${binding} = {};;);`);
Function(`for (const ${binding} = {};;);`);
Function(`for (let ${binding} in {});`);
Function(`for (const ${binding} in {});`);
Function(`for (let ${binding} of {});`);
Function(`for (const ${binding} of {});`);
}
}
for (let t of transformer) {
// "let" is always allowed as binding-identifier in VariableDeclaration
for (let binding of [...bindings.letIsBoundName, ...bindings.letIsntBoundName]) {
binding = t(binding);
Function(`var ${binding} = {};`);
Function(`for (var ${binding} = {};;);`);
Function(`for (var ${binding} in {});`);
Function(`for (var ${binding} of {});`);
}
}
for (let t of transformer) {
// "let" is always allowed as binding-identifier in CatchParameter
for (let binding of [...bindings.letIsBoundName, ...bindings.letIsntBoundName]) {
binding = t(binding);
Function(`try {} catch (${binding}) {}`);
}
}
for (let t of transformer) {
// "let" is always allowed as binding-identifier in FormalParameters
for (let binding of [...bindings.letIsBoundName, ...bindings.letIsntBoundName]) {
binding = t(binding);
Function(`function f(${binding}) {}`);
Function(`function* f(${binding}) {}`);
Function(`((${binding}) => {});`);
}
}
for (let t of transformer) {
// "let" is always allowed as binding-identifier in StrictFormalParameters
for (let binding of [...bindings.letIsBoundName, ...bindings.letIsntBoundName]) {
binding = t(binding);
Function(`((${binding}) => {});`);
Function(`({x(${binding}) {}});`);
Function(`({*x(${binding}) {}});`);
}
}
for (let t of transformer) {
// "let" is always allowed as binding-identifier in PropertySetParameterList
for (let binding of [...bindings.letIsBoundName, ...bindings.letIsntBoundName]) {
binding = t(binding);
Function(`({set x(${binding}) {}});`);
}
}
|
// Saves options to chrome.storage
function save_options() {
var showChangeLog = document.getElementById('show_changelog').checked;
chrome.storage.sync.set({
showChangeLog: showChangeLog
}, function () {
// Update status to let user know options were saved.
var status = document.getElementById('status');
status.textContent = 'Options saved.';
setTimeout(function () {
status.textContent = '';
}, 750);
});
}
// Restores select box and checkbox state using the preferences
// stored in chrome.storage.
function restore_options() {
// Use default value showChangeLog = true.
chrome.storage.sync.get({
showChangeLog: true
}, function (items) {
document.getElementById('show_changelog').checked = items.showChangeLog;
});
}
document.addEventListener('DOMContentLoaded', restore_options);
document.getElementById('save').addEventListener('click',
save_options); |
import Hook from 'util/hook'
import schema from './schema'
import schemaGen from './gensrc/schema'
import resolver from './resolver'
import resolverGen from './gensrc/resolver'
import {deepMergeToFirst} from 'util/deepMerge'
import {preProcessorsCache} from './preprocessor'
import {ObjectId} from 'mongodb'
import {createOrDeleteStaticFile} from '../staticfile/staticfile'
// Hook to add mongodb resolver
Hook.on('resolver', ({db, resolvers}) => {
deepMergeToFirst(resolvers, resolver(db), resolverGen(db))
})
// Hook to add mongodb schema
Hook.on('schema', ({schemas}) => {
schemas.push(schemaGen)
schemas.push(schema)
})
// Hook when the type StaticFile has changed
Hook.on('typeUpdated_PreProcessor', async ({db, result}) => {
delete preProcessorsCache[result._id]
const staticFiles = await db.collection('StaticFile').find({active:true,preprocessor: ObjectId(result._id)}).toArray()
if(staticFiles){
staticFiles.forEach(async staticFile => {
createOrDeleteStaticFile(staticFile, {db, force:true})
})
}
})
|
/// <autosync enabled="true" />
/// <reference path="../src/hash-router.js" />
/// <reference path="server.js" />
/// <reference path="test.js" />
|
var five = require('johnny-five');
var chipio = require('../preferences').ChipIO;
var defaultCallback = function () {
var result = {
x: this.x,
y: this.y,
z: this.z,
pitch: this.pitch,
roll: this.roll,
acceleration: this.acceleration,
inclination: this.inclination,
orientation: this.orientation
};
console.log(result);
};
module.exports = function accelerometer(callback = defaultCallback) {
var board = new five.Board({
io: new chipio()
});
board.on('ready', function () {
var accelerometer = new five.Accelerometer({
controller: 'MPU6050',
sensitivity: 16384 // optional
});
accelerometer.on('change', callback);
});
};
|
'use strict';
var AWS = require('aws-sdk');
var s3 = new AWS.S3();
exports.handler = function(event, context, callback){
var message = JSON.parse(event.Records[0].Sns.Message);
var sourceBucket = message.Records[0].s3.bucket.name;
var sourceKey = decodeURIComponent(message.Records[0].s3.object.key.replace(/\+/g, ' '));
var params = {
Bucket: sourceBucket,
Key: sourceKey,
ACL: 'public-read'
};
s3.putObjectAcl(params, function(err, data){
if (err) {
callback(err);
}
});
}; |
var Graph = require('./Graph');
var FragColorNode = require('./nodes/FragColorNode');
module.exports = FragmentGraph;
function FragmentGraph(options){
options = options || {};
options.mainNode = options.mainNode || new FragColorNode();
Graph.call(this, options);
}
FragmentGraph.prototype = Object.create(Graph.prototype); |
var chrome = chrome;
function TaskRunner(task) {
this.url = task.url;
this.start();
}
TaskRunner.prototype = {
start: function(){
this.initListeners();
chrome.tabs.create({ url: this.url }, function(tab) {
this.tab = tab;
}.bind(this));
},
initListeners: function(){
chrome.processes.onUpdatedWithMemory.addListener(this.onProcessesUpdatedWithMemory.bind(this));
chrome.tabs.onUpdated.addListener(this.onTabsUpdated.bind(this));
},
onProcessesUpdatedWithMemory: function(processes){
if (!this.tab) return;
var tab = this.tab;
Object.keys(processes).forEach(function(pid){
var p = processes[pid];
if (p.tabs[0] == tab.id) {
chrome.tabs.get(tab.id, function(tab) {
console.log(tab);
console.log(tab.title, (p.privateMemory / 1024 / 1024).toFixed(0) + ' mb', Math.floor(p.cpu) + '%');
});
}
});
console.log(processes);
},
onTabsUpdated: function(tabId, changeInfo, Tab) {
if (!this.tab) return;
if (tabId == this.tab.id && changeInfo.status == 'complete') {
}
}
};
new TaskRunner({ url: 'http://cssdeck.com/labs/simple-css3-heart-pulsing-animations' }); |
var currentChatroomId = window.location.pathname.split('/')[2];
$(document).ready(function(){
$.material.init();
});
$(window).load(function(){
// TODO abfrage integrieren nach aktueller chatraum id
if($("#chatMessages").length >0){
loadChatMessages();
setInterval(function(){
//loadChatMessages();
}, 2000);
}
});
function loadChatMessages() {
$.ajax({
url : "/ajax",
type: "POST",
data: {
ajaxCall: "getMessagesFromChatroom",
chatId: currentChatroomId
},
success: function(html){
$("#chatMessages").html(html);
$(".chatbox-content").scrollTop($(".chatbox-content").prop("scrollHeight"));
}
});
}
function loadChatRoom() {
$(".chat-start-container").fadeOut(350);
$(".loading-container").fadeIn(700);
$.ajax({
url : "/ajax",
type: "POST",
data: {
ajaxCall: "createNewChatroom"
},
success: function(html){
setTimeout(function(){
window.location.href = "/chatroom/"+html;
}, 1000);
}
});
}
$( ".chatbox-input .input" ).keyup(function( event ) {
if(event.keyCode==13){
sendMessage(this.innerHTML);
}else{
writeChatMessage(this.innerHTML);
}
});
$( ".chat-left-nav.member-list" ).on( "click", ".add-chatroom", function() {
$(".chat-left-nav.add-chatgroup-nav").animate({
left: '0px'
});
});
$( ".chat-left-nav.add-chatgroup-nav" ).on( "click", ".add-chatroom", function() {
$(".chat-left-nav.add-chatgroup-nav").animate({
left: '-360px'
});
});
// Disable Umbruch
$(document).on('keypress', '.chatbox-input .input', function(e){
return e.which != 13;
});
function writeChatMessage(value) {
if(value.length > 0 && value != " " && value != " "){
$(".chatbox-input .input-placeholder").css('visibility', 'hidden');
}else{
$(".chatbox-input .input-placeholder").css('visibility', 'visible');
}
}
function sendMessage(message) {
// TODO Replace mit php anbindung AJAX Call
$(".chatbox-input .input-placeholder").css('visibility', 'visible');
$(".chatbox-input .input").html("");
if(message.length > 0 && message != " " && message != " ") {
$.ajax({
url: "/ajax",
type: "POST",
data: {
ajaxCall: "newChatMessage",
value: message,
chatId: currentChatroomId
},
success: function () {
loadChatMessages();
}
});
}
} |
function getStreams ({state, output, services}) {
const channels = state.get(['app', 'channels', 'current'])
let config = {}
if (channels.length) {
config = {
params: {
channel: channels.toString()
}
}
}
services.http.get('https://api.twitch.tv/kraken/streams', config)
.then(output.success)
.catch(output.error)
}
getStreams.async = true
export default getStreams
|
const { config } = require('./config')
exports.config = Object.assign({}, config, {
runnerEnv: {
WDIO_NO_SYNC_SUPPORT: true
}
})
|
/**
* Created by Catalin on 3/11/2017.
*/
//Login page
$('.open-menu').click(function() {
$('.ui.sidebar').sidebar('setting', 'transition', 'scale down').sidebar('toggle');
});
$('.logout').dropdown(); |
module.exports.tables = {
players: 'bm_players',
playerBans: 'bm_player_bans',
playerBanRecords: 'bm_player_ban_records',
playerMutes: 'bm_player_mutes',
playerMuteRecords: 'bm_player_mute_records',
playerKicks: 'bm_player_kicks',
playerNotes: 'bm_player_notes',
playerHistory: 'bm_player_history',
playerReports: 'bm_player_reports',
playerReportLocations: 'bm_player_report_locations',
playerReportStates: 'bm_player_report_states',
playerReportCommands: 'bm_player_report_commands',
playerReportComments: 'bm_player_report_comments',
playerWarnings: 'bm_player_warnings',
ipBans: 'bm_ip_bans',
ipBanRecords: 'bm_ip_ban_records',
ipMutes: 'bm_ip_mutes',
ipMuteRecords: 'bm_ip_mute_records',
ipRangeBans: 'bm_ip_range_bans',
ipRangeBanRecords: 'bm_ip_range_ban_records',
playerPins: 'bm_player_pins',
serverLogs: 'bm_server_logs',
playerReportLogs: 'bm_report_logs'
}
|
(function() {
var componentName = 'custom-dialog-box';
var s = `
<div class="` + componentName + ` panel panel-default">
<h3 class="panel-heading">{{ headline }}</h3>
<div class="panel-body" v-html="body"></div>
<custom-buttons v-bind:buttons="buttons" class="pull-right"></custom-buttons>
</div>
`;
Vue.component(componentName, {
created: function() {
viewController.registerView(componentName, this);
},
methods: {
setHeadline: function(str) {
this.headline = str;
},
setBody: function(str) {
this.body = str;
},
setButtons: function(btns) {
this.buttons = btns;
}
},
data: function() {
return {
'headline': '',
'body': '',
'buttons': ''
}
},
template: s
});
})();
|
'use strict';
const t = require('./../../common/prop-types');
const _ = require('./../../common/lodash');
const enums = require('./../../../shared/model')(require('joi-browser'), _).subdocuments.enums;
const commonObj = {
_id: t.string,
updatedBy: t.string,
updatedOn: t.oneOfType([t.instanceOf(Date), t.string]),
createdBy: t.string,
createdOn: t.oneOfType([t.instanceOf(Date), t.string]),
canEdit: t.bool,
canDelete: t.bool
};
const commonBlog = {
title: t.string,
description: t.string,
access: t.oneOf(enums.blogs.access),
allowPublicAccess: t.bool,
allowComments: t.bool,
needsReview: t.bool,
isOwner: t.bool,
isSubscriber: t.bool,
isContributor: t.bool
};
const comments = _.merge({
comment: t.string,
replies: t.arrayOf(t.shape(comments)),
status: t.oneOf(enums.comments.status),
isAuthor: t.bool,
isPending: t.bool,
isApproved: t.bool,
isSpam: t.bool
}, commonObj);
const commonPost = {
blogId: t.string,
blogTitle: t.string,
description: t.string,
state: t.oneOf(enums.posts.state),
tags: t.arrayOfString,
attachments: t.arrayOfObject,
threadedComments: t.arrayOf(t.shape(comments)),
publishedBy: t.string,
publishedOn: t.oneOfType([t.instanceOf(Date), t.string]),
reviewedBy: t.string,
reviewedOn: t.oneOfType([t.instanceOf(Date), t.string]),
rating: t.oneOf(enums.posts.rating),
ratedOn: t.oneOfType([t.instanceOf(Date), t.string]),
uniqueViews: t.number,
totalViews: t.number,
totalLikes: t.number,
totalLoves: t.number,
viewedOn: t.oneOfType([t.instanceOf(Date), t.string]),
isAuthor: t.bool,
isDraft: t.bool,
isPublished: t.bool,
isArchived: t.bool,
isDoNotPublish: t.bool,
canPublish: t.bool,
canReject: t.bool,
canMakePublic: t.bool,
canMakePrivate: t.bool,
canStopComments: t.bool,
canAllowComments: t.bool,
canLike: t.bool,
canUnlike: t.bool,
canLove: t.bool,
canUnlove: t.bool,
canComment: t.bool
};
const blog = _.merge({
owners: t.arrayOfString,
contributors: t.arrayOfString,
subscribers: t.arrayOfString,
needsApproval: t.arrayOfString,
canCreatePosts: t.bool,
canJoin: t.bool,
canLeave: t.bool
}, commonBlog, commonObj);
const post = _.merge({}, commonBlog, commonPost, commonObj);
const notification = _.merge({
objectType: t.oneOf(enums.notifications.objectType),
objectId: t.string,
title: t.string,
state: t.oneOf(enums.notifications.state),
starred: t.bool,
action: t.string,
priority: t.oneOf(enums.notifications.priority),
content: t.unknown
}, commonObj);
const preference = _.merge({}, commonObj, {});
module.exports = _.merge({}, {
modifiedListItems: t.arrayOf(t.shape({
origState: t.oneOf(['alreadyPresent', 'added']),
state: t.oneOf(['added', 'removed', 'alreadyPresent']),
item: t.any
})),
modifyState: _.merge({}, t.uiState, {
onViewChange: t.func,
isModified: t.bool
}),
blog,
comments,
post,
notification,
preference
}, t);
|
var turnNum = 0;
// Create a global array to represent the state of the board.
var arr = ['', '', '', '', '', '', '', '', ''];
/***** St Names and Turns Function ******/
function setNames () {
turnNum = 1;
// Player Alerts
swal({ title: "Green Thumb VS Gold Finger!", text: "Battle of the Eons", imageUrl: "https://lh4.ggpht.com/uKgF6DDOl-fOCaJLy9JUQdwVI3VF7SL8nSvJE9aP86O9fdP0jn-2Mg9lABOS6zfOwA=w300", animation: false, timer: 4000});
// Let users pick name
var name1 = " ";
var name2 = " ";
if (name1 == " " || name1 == null) {
name1 = "Green Thumb";
}
if (name2 == " " || name2 == null) {
name2 = "Gold Finger";
}
// assign names at top
var player1Name = document.getElementById('X');
player1Name.innerHTML = name1;
var player2Name = document.getElementById('O');
player2Name.innerHTML = name2;
}
/***** Initial Function ******/
function init() {
setNames();
// For each of the cells, create a <div> inside the table cell
var cells = document.getElementsByTagName('td');
for (var i = 0; i < cells.length; i++) {
var cell = document.getElementById('c' + [i]);
cell.innerHTML = '<div id="d' + [i] + '"></div>';
}
// For each of the cells, create an onclick
var cells = document.querySelectorAll('td');
for (var i = 0; i < cells.length; i++) {
cells[i].addEventListener("click", function() {
squareClicked(this.id)});
}
// set a class on the Player X div to indicate that it is the current player and clear any classes set on the Player Y div
var playerX = document.getElementById("X");
var playerO = document.getElementById("O");
playerX.className = 'current-player';
playerO.className = ' ';
}
/***** Turn Taken Function ******/
function squareClicked(x) {
turnNum++;
var playerX = document.getElementById("X");
var playerO = document.getElementById("O");
var playerXClass = playerX.className;
var playerOClass = playerO.className;
var clickedEl = document.getElementById(x);
var numDiv = clickedEl.firstChild;
// if empty
if (numDiv.className == 0) {
// if it's player X
if (playerXClass == 'current-player') {
numDiv.className = 'X-marker';
// push X to array in proper spot
switch(clickedEl) {
case c0:
arr[0] = "X";
break;
case c1:
arr[1] = "X";
break;
case c2:
arr[2] = "X";
break;
case c3:
arr[3] = "X";
break;
case c4:
arr[4] = "X";
break;
case c5:
arr[5] = "X";
break;
case c6:
arr[6] = "X";
break;
case c7:
arr[7] = "X";
break;
case c8:
arr[8] = "X";
break;
}
}
// if it's player O
else {
numDiv.className = 'O-marker';
// push O to proper spot
switch(clickedEl) {
case c0:
arr[0] = "O";
break;
case c1:
arr[1] = "O";
break;
case c2:
arr[2] = "O";
break;
case c3:
arr[3] = "O";
break;
case c4:
arr[4] = "O";
break;
case c5:
arr[5] = "O";
break;
case c6:
arr[6] = "O";
break;
case c7:
arr[7] = "O";
break;
case c8:
arr[8] = "O";
break;
}
}
// switch players
if (playerXClass == 'current-player') {
playerX.className = ' ';
playerO.className = 'current-player';
}
else {
playerO.className = ' ';
playerX.className = 'current-player';
}
// check for win
if (turnNum >= 5) {
winArrays("X");
winArrays("O");
}
// draw
if (turnNum >= 10 && winArrays() == false) {
swal("Tie", "Improve your hand skills.", "error");
// newGame();
}
}
else {
swal("Already Conquered", "Try Another Tile");
}
console.log(numDiv);
console.log(arr);
}
/***** New Game Function ******/
function newGame() {
// remove the content div from each of them by clearing the innerHTML property
var cells = document.getElementsByTagName('td');
for (var i = 0; i < cells.length; i++){
var cell = document.getElementById('c'+[i]);
cell.innerHTML = '<div id="d'+[i]+'"></div>';
}
setNames();
var playerX = document.getElementById("X");
var playerO = document.getElementById("O");
// Also set a class on the Player X div to indicate that it is the current player and clear any classes set on the Player Y div
playerX.className = 'current-player';
playerO.className = ' ';
var currentPlayer = "X";
arr = ['', '', '', '', '', '', '', '', ''];
}
// checks for wins
function winArrays(marker) {
if (
// across
(arr[0] == marker && arr[1] == marker && arr[2]== marker ) ||
(arr[3] == marker && arr[4] == marker && arr[5]== marker ) ||
(arr[6] == marker && arr[7] == marker && arr[8]== marker ) ||
// down
(arr[0] == marker && arr[3]== marker && arr[6]== marker ) ||
(arr[1] == marker && arr[4]== marker && arr[7]== marker ) ||
(arr[2] == marker && arr[5]== marker && arr[8]== marker ) ||
// diagonal
(arr[0] == marker && arr[4]== marker && arr[8]== marker ) ||
(arr[6] == marker && arr[4]== marker && arr[2]== marker )
)
{
// change winning spaces green/losing red
for (i = 0; i < arr.length; i++) {
if (arr[i] == marker) {
var cellDiv = document.getElementById('d' + [i]);
cellDiv.className += ' win';
}
else {
var cellDiv = document.getElementById('d' + [i]);
cellDiv.className += ' lose';
}
}
if (swal(marker + ' has won!\nNew game?') == true) {
newGame();
}
}
else {
return false;
}
}
console.log(arr); |
import { join, resolve } from 'path'
// someday this will be nonblocking again
import { pseudoRandomBytes } from 'crypto'
import { writeFile as writeFileCB, stat as statCB } from 'graceful-fs'
import mkdirpCB from 'mkdirp'
import rimrafCB from 'rimraf'
import validate from 'aproba'
import { promisify } from 'bluebird'
const mkdirp = promisify(mkdirpCB)
const rimraf = promisify(rimrafCB)
const stat = promisify(statCB)
const writeFile = promisify(writeFileCB)
export default function blockSizeFromPath (path) {
validate('S', arguments)
const base = resolve(path)
const probe = join(
base,
'packzzz-test-' + pseudoRandomBytes(4).toString('hex')
)
return mkdirp(base)
.then(() => writeFile(probe, 'lol'))
.then(() => stat(probe))
.then((stats) => rimraf(probe).return(stats.blksize))
}
|
/**
* Sample React Native App
* https://github.com/facebook/react-native
* @flow
*/
import React, {Component} from 'react';
import {AppRegistry, StyleSheet, Text, View, Image, Dimensions,Navigator} from 'react-native';
import InitApp from "./app/InitApp";
AppRegistry.registerComponent('eyepetizer', () => InitApp);
|
'use strict';
var should = require('should'),
request = require('supertest'),
app = require('../../server'),
mongoose = require('mongoose'),
User = mongoose.model('User'),
Course = mongoose.model('Course'),
_ = require('lodash'),
agent = request.agent(app);
/**
* Globals
*/
var credentials_s, credentials_p, user_s, user_p, course;
/**
* Course routes tests
*/
describe('Course CRUD tests', function() {
beforeEach(function(done) {
// Create user credentials
credentials_p = {
username: 'username',
password: 'password'
};
credentials_s = {
username: 'username_s',
password: 'password_s'
};
// Create a new user
user_s = new User({
firstName: 'Full',
lastName: 'Name',
displayName: 'Full Name',
email: '[email protected]',
ufid: '88888888',
gatorlink: 'crazyman',
username: credentials_s.username,
password: credentials_s.password,
provider: 'local'
});
user_p = new User({
firstName: 'Full',
lastName: 'Name',
displayName: 'Full Name',
email: '[email protected]',
ufid: '88888888',
gatorlink: 'crazyman',
roles: 'admin',
username: credentials_p.username,
password: credentials_p.password,
provider: 'local'
});
// Save an admin to the test db and create new Course
user_p.save(function() {
course = {
name: 'Course Name',
owner: user_p._id,
quizzes: [
{
name: 'Joe Blow'
},
{
name: 'Nancy Drew'
}
]
};
});
// Save a user to the test db
user_s.save(function() {
done();
});
});
it('should be able to save Course instance if logged in as admin', function(done) {
agent.post('/auth/signin')
.send(credentials_p)
.expect(200)
.end(function(signinErr, signinRes) {
// Handle signin error
if (signinErr) done(signinErr);
// Get the userId
var userId = user_p.id;
// Save a new Course
agent.post('/courses')
.send(course)
.expect(200)
.end(function(courseSaveErr, courseSaveRes) {
// Handle Course save error
if (courseSaveErr) done(courseSaveErr);
// Get a list of Courses
agent.get('/courses')
.end(function(coursesGetErr, coursesGetRes) {
// Handle Course save error
if (coursesGetErr) done(coursesGetErr);
// Get Courses list
var courses = coursesGetRes.body;
// Set assertions
(courses[0].owner._id).should.equal(userId);
(courses[0].name).should.match('Course Name');
// Call the assertion callback
done();
});
});
});
});
it('should not be able to save Course instance if not logged in', function(done) {
agent.post('/courses')
.send(course)
.expect(401)
.end(function(courseSaveErr, courseSaveRes) {
// Call the assertion callback
done(courseSaveErr);
});
});
it('should not be able to save Course instance if no name is provided', function(done) {
// Invalidate name field
course.name = '';
agent.post('/auth/signin')
.send(credentials_p)
.expect(200)
.end(function(signinErr, signinRes) {
// Handle signin error
if (signinErr) done(signinErr);
// Save a new Course
agent.post('/courses')
.send(course)
.expect(400)
.end(function(courseSaveErr, courseSaveRes) {
// Set message assertion
(courseSaveRes.body.message).should.match('Please fill Course name');
// Handle Course save error
done(courseSaveErr);
});
});
});
it('should be able to update Course instance if signed in as admin', function(done) {
agent.post('/auth/signin')
.send(credentials_p)
.expect(200)
.end(function(signinErr, signinRes) {
// Handle signin error
if (signinErr) done(signinErr);
// Save a new Course
agent.post('/courses')
.send(course)
.expect(200)
.end(function(courseSaveErr, courseSaveRes) {
// Handle Course save error
if (courseSaveErr) done(courseSaveErr);
// Update Course name
course.name = 'WHY YOU GOTTA BE SO MEAN?';
// Update existing Course
agent.put('/courses/' + courseSaveRes.body._id)
.send(course)
.expect(200)
.end(function(courseUpdateErr, courseUpdateRes) {
// Handle Course update error
if (courseUpdateErr) done(courseUpdateErr);
// Set assertions
(courseUpdateRes.body._id).should.equal(courseSaveRes.body._id);
(courseUpdateRes.body.name).should.match('WHY YOU GOTTA BE SO MEAN?');
// Call the assertion callback
done();
});
});
});
});
it('should be able to get a list of Courses if not signed in', function(done) {
// Create new Course model instance
var courseObj = new Course(course);
// Save the Course
courseObj.save(function() {
// Request Courses
request(app).get('/courses')
.end(function(req, res) {
// Set assertion
res.body.should.be.an.Array.with.lengthOf(1);
// Call the assertion callback
done();
});
});
});
it('should be able to get a list of quizzes within a particular course if signed in', function(done) {
agent.post('/auth/signin')
.send(credentials_p)
.expect(200)
.end(function(signinErr, signinRes) {
// Handle signin error
if (signinErr) done(signinErr);
// Create new Course model instance
var courseObj = new Course(course);
// Save the Course
courseObj.save(function () {
request(app).get('/courses/' + courseObj._id + '/quizzes')
.end(function (req, res) {
// Set assertion
res.body.should.be.an.Array.with.lengthOf(2);
// Call the assertion callback
done();
});
});
});
});
it('should be able to get a single Course if not signed in', function(done) {
// Create new Course model instance
var courseObj = new Course(course);
// Save the Course
courseObj.save(function() {
request(app).get('/courses/' + courseObj._id)
.end(function(req, res) {
// Set assertion
res.body.should.be.an.Object.with.property('name', course.name);
// Call the assertion callback
done();
});
});
});
it('should be able to delete Course instance if signed in as admin', function(done) {
agent.post('/auth/signin')
.send(credentials_p)
.expect(200)
.end(function(signinErr, signinRes) {
// Handle signin error
if (signinErr) done(signinErr);
// Save a new Course
agent.post('/courses')
.send(course)
.expect(200)
.end(function(courseSaveErr, courseSaveRes) {
// Handle Course save error
if (courseSaveErr) done(courseSaveErr);
// Delete existing Course
agent.delete('/courses/' + courseSaveRes.body._id)
.send(course)
.expect(200)
.end(function(courseDeleteErr, courseDeleteRes) {
// Handle Course error error
if (courseDeleteErr) done(courseDeleteErr);
// Set assertions
(courseDeleteRes.body._id).should.equal(courseSaveRes.body._id);
// Call the assertion callback
done();
});
});
});
});
it('should not be able to delete Course instance if not signed in', function(done) {
// Set Course user
course.owner = user_p._id;
// Create new Course model instance
var courseObj = new Course(course);
// Save the Course
courseObj.save(function() {
// Try deleting Course
request(app).delete('/courses/' + courseObj._id)
.expect(401)
.end(function(courseDeleteErr, courseDeleteRes) {
// Set message assertion
(courseDeleteRes.body.message).should.match('User is not logged in');
// Handle Course error error
done(courseDeleteErr);
});
});
});
afterEach(function(done) {
User.remove().exec();
Course.remove().exec();
done();
});
});
|
import React from 'react';
import cx from 'classnames';
import { injectIntl } from 'react-intl';
import { connect } from 'react-redux';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import Post from '../Post';
import Terminal from '../Terminal';
import Link from '../Link';
import Comments from '../Comments';
import s from './CheckInItemContent.css';
import FontIcon from 'material-ui/FontIcon';
import { setDeepProperty, setProperty } from '../../actions/properties';
import { deletePost, deleteTerminal } from '../../actions/posts';
import { saveCheckIn } from '../../actions/checkIns';
import PropTypes from 'prop-types';
import { saveLike, saveComment } from '../../actions/comments';
import DeleteContentDialog from '../common/DeleteContentDialog';
import { getImageUrl } from '../utils';
const CheckInItemContent = ({
checkInItem, contentType, feedProperties, frameId, editPost, showSettings, env,
savedTerminal, sentLike, deleteCandidate,
setDeepProperty, setProperty, saveCheckIn, deletePost, deleteTerminal, saveLike,
editable
}) => {
const { checkIn, posts, terminals } = checkInItem;
const arrivals = terminals.filter(terminal => terminal.type === 'arrival');
const arrival = arrivals.length > 0 ? arrivals[0] : null;
const departures = terminals.filter(terminal => terminal.type === 'departure');
const departure = departures.length > 0 ? departures[0] : null;
let content = null;
let comments = null;
const scrollToPost = (postIndex) => {
setProperty('posts.savedPost', null);
setDeepProperty('posts', ['feedProperties', frameId, 'activePost'], postIndex);
};
let activePost = 0;
if (posts.length > 0 && contentType === 'reaction') {
activePost = ((feedProperties && feedProperties[frameId]) && feedProperties[frameId]['activePost']) || 0;
/*
if (savedPost) {
for (let i = 0; i < posts.length; i++) {
if (posts[i].uuid === savedPost.uuid) {
activePost = i;
posts[activePost] = savedPost;
}
}
}
*/
if (activePost > posts.length - 1) {
activePost = 0;
}
if (posts.length > 0) {
const indicatorDots = [];
if (posts.length > 1) {
for (let i = 0; i < posts.length; i++) {
indicatorDots.push(
<div key={`indicator-dot-${i}`} className={cx(s.indicatorDot, i === activePost ? s.selectedIndicatorDot : {})}>
</div>
);
}
}
content = (
<div className={s.posts}>
<Post post={posts[activePost || 0]} />
{
activePost > 0 &&
<div className={s.navLeft} onClick={() => scrollToPost(activePost - 1)}>
<FontIcon className="material-icons" style={{ fontSize: '40px' }}>keyboard_arrow_left</FontIcon>
</div>
}
{
activePost < posts.length - 1 &&
<div className={s.navRight} onClick={() => scrollToPost(activePost + 1)}>
<FontIcon className="material-icons" style={{ fontSize: '40px' }}>keyboard_arrow_right</FontIcon>
</div>
}
<div className={s.navIndicatorContainer}>
<div className={s.navIndicator}>
{indicatorDots}
</div>
</div>
</div>
);
} else {
content = null;
}
comments = checkIn.comments;
} else if (contentType === 'arrival' && arrival) {
content = <Terminal terminal={arrival} />;
comments = arrival.comments;
} else if (contentType === 'departure' && departure) {
content = <Terminal terminal={departure} />;
comments = departure.comments;
}
const showHeader = content && content.length !== 0;
const userName = checkIn.user ? (checkIn.user.username || (checkIn.user.firstName + ' ' + checkIn.user.lastName)) : 'Anonymoyus';
const dateStr = (new Date(checkIn.date)).toLocaleDateString('en-US', { year: 'numeric', month: 'long', day: 'numeric' });
const commentsAttributes = {
checkIn,
frameId
};
if (contentType === 'departure') {
commentsAttributes.terminal = departure;
} else if (contentType === 'arrival') {
commentsAttributes.terminal = arrival;
}
let deleteContentDialog = null;
if ((frameId === true || frameId === 'frame-edit') && deleteCandidate && (deleteCandidate.type === 'post' || deleteCandidate.type === 'terminal')) {
deleteContentDialog = <DeleteContentDialog />;
}
const userImageSrc = getImageUrl(checkIn.user.avatar || checkIn.user.avatarSource, checkIn.user.photo, env.MEDIA_URL);
return (
<div className={s.feedItemContent} id={`content-${frameId}`}>
{
showHeader &&
<div className={s.contentHeader}>
<div className={s.contentHeaderLeft}>
{
userImageSrc &&
<Link to={`/?user=${checkIn.userUuid}`}>
<div className={s.userIcon}>
<img src={userImageSrc} />
</div>
</Link>
}
<div className={s.contentInfo}>
<Link to={`/?user=${checkIn.userUuid}`}>
<div className={s.contentUser}>
{ userName }
</div>
</Link>
<div className={s.contentDate}>
{ dateStr }
</div>
</div>
</div>
<div className={s.contentHeaderRight}>
{
(!editPost.uuid && editable && checkInItem.userAccess === 'edit') ?
<div>
<FontIcon className="material-icons" style={{ fontSize: '20px' }} onClick={() => {
if (contentType === 'reaction') {
setProperty('posts.addType', 'reaction');
setProperty('posts.postText', posts[activePost].text);
setProperty('posts.editPost', posts[activePost]);
setProperty('posts.mediaItems', posts[activePost].mediaItems);
} else if (contentType === 'arrival') {
setProperty('posts.addType', 'arrival');
setProperty('editTerminal.terminal', arrival);
} else if (contentType === 'departure') {
setProperty('posts.addType', 'departure');
setProperty('editTerminal.terminal', departure);
}
}}>edit</FontIcon>
<FontIcon className="material-icons" style={{ fontSize: '20px', marginLeftt: '4px' }} onClick={() => {
if (contentType === 'reaction') {
setProperty('posts.deleteCandidate', {
type: 'post',
dialogText: <span>Delete post?</span>,
deleteItem: deletePost,
uuid: posts[activePost].uuid
});
} else if (contentType === 'arrival') {
setProperty('posts.deleteCandidate', {
type: 'terminal',
dialogText: <span>Delete arrival?</span>,
deleteItem: deleteTerminal,
uuid: arrival.uuid
});
} else if (contentType === 'departure') {
setProperty('posts.deleteCandidate', {
type: 'terminal',
dialogText: <span>Delete departure?</span>,
deleteItem: deleteTerminal,
uuid: departure.uuid
});
}
}}>delete</FontIcon>
</div> :
<div>
<div className={s.likes}>
<div className={s.heart}>
{
(sentLike && sentLike.checkInUuid === checkIn.uuid && sentLike.frameId === frameId) ?
<FontIcon className="material-icons" style={{ fontSize: '20px', color: 'gray' }}
onClick={() => saveLike(checkIn.uuid, 'CheckIn', 'off', frameId, checkIn.uuid)}>
favorite
</FontIcon> : (
checkIn.likedByUser ?
<FontIcon className="material-icons" style={{ fontSize: '20px', color: 'red' }}
onClick={() => saveLike(checkIn.uuid, 'CheckIn', 'off', frameId, checkIn.uuid)}>
favorite
</FontIcon> :
<FontIcon className="material-icons" style={{ fontSize: '20px' }}
onClick={() => saveLike(checkIn.uuid, 'CheckIn', 'on', frameId, checkIn.uuid)}>
favorite_border
</FontIcon>
)
}
</div>
<div className={s.count}>
{ checkIn.likes }
</div>
</div>
</div>
}
</div>
</div>
}
{deleteContentDialog}
{content}
<div className={s.tags}>
{
showSettings ?
(checkIn.tags || []).map(tag => (
<div className={s.removableTag}>
<div className={s.tagValue}>#{tag}</div>
<div className={s.removeTag} onClick={() => {
saveCheckIn({ checkIn: { uuid: checkIn.uuid, tags: checkIn.tags.filter(t => t !== tag)}})
}}>
<FontIcon className="material-icons" style={{ fontSize: '16px', color: '#9a0000' }}>
remove_circle_outline
</FontIcon>
</div>
</div>
)) :
(checkIn.trip ? [
<div key={`${checkIn.uuid}-${checkIn.trip.name}`} className={s.trip}><Link to={`/?trip=${checkIn.trip.uuid}`}>{checkIn.trip.name}</Link></div>
] : []).concat((checkIn.tags || []).map(tag => (
<div key={`${checkIn.uuid}-${tag}`} className={s.tag}>#<Link to={`/?tags=${tag}`}>{tag}</Link></div>
)))
}
</div>
{
(frameId !== true && !showSettings) &&
<div>
<Comments comments={comments} frameId={frameId} preview={!editable} {...commentsAttributes} />
</div>
}
</div>
);
};
CheckInItemContent.propTypes = {
checkInItem: PropTypes.object,
contentType: PropTypes.string
};
export default injectIntl(
connect(state => ({
env: state.env,
feedProperties: state.posts.feedProperties || {},
savedPost: state.posts.savedPost,
addPost: state.posts.addPost,
savedTerminal: state.editTerminal.savedTerminal,
showSettings: state.posts.showSettings,
savedCheckIn: state.posts.checkIn,
sentLike: state.posts.sentLike,
feedUpdated: state.posts.feedUpdated,
commentText: state.posts.commentText,
deleteCandidate: state.posts.deleteCandidate
}), {
setDeepProperty, setProperty, saveCheckIn, deletePost, deleteTerminal, saveLike, saveComment
})(withStyles(s)(CheckInItemContent))
);
|
import React from 'react';
import { shallow } from 'enzyme';
import { App } from './index';
describe('views', () => {
describe('App', () => {
let handleSearch;
let search;
let toggleSearch;
beforeEach(() => {
handleSearch = () => {};
search = {open: false};
toggleSearch = () => {};
});
function getWrapper() {
return shallow(
<App
handleSearch={handleSearch}
search={search}
toggleSearch={toggleSearch}
/>
);
}
it('should have a `AppHeader` component', () => {
const wrapper = getWrapper();
const appHeader = wrapper.find('AppHeader');
expect(appHeader.length).toBe(1);
expect(appHeader.prop('handleSearch')).toBe(handleSearch);
expect(appHeader.prop('search')).toBe(search);
expect(appHeader.prop('toggleSearch')).toBe(toggleSearch);
});
it('should have a `main` element', () => {
const wrapper = getWrapper();
const main = wrapper.find('main');
expect(main.length).toBe(1);
});
it('should have a `Player` component', () => {
const wrapper = getWrapper();
const player = wrapper.find('Connect(Player)');
expect(player.length).toBe(1);
});
});
});
|
class Pen {
constructor() {
console.log('pen selected');
}
}
module.exports = Pen |
// StyleFix 1.0.1 & PrefixFree 1.0.4 / by Lea Verou / MIT license
(function() {
function f(a, b) {return[].slice.call((b || document).querySelectorAll(a))}
if(window.addEventListener) {
var b = window.StyleFix = {link:function(a) {
try {if(!/\bstylesheet\b/i.test(a.rel) || !a.sheet.cssRules)return} catch(c) {return}
var d = a.href || a.getAttribute("data-href"), g = d.replace(/[^\/]+$/,
""), e = a.parentNode, h = new XMLHttpRequest;
h.open("GET", d);
h.onreadystatechange = function() {
if(h.readyState === 4) {
var c = h.responseText;
if(c && a.parentNode) {
c = b.fix(c, true, a);
g && (c = c.replace(/url\((?:'|")?(.+?)(?:'|")?\)/gi,
function(a, c) {
return!/^([a-z]{3,10}:|\/)/i.test(c) ? 'url("' + g + c + '")' : a
}), c = c.replace(RegExp("\\b(behavior:\\s*?url\\('?\"?)" + g, "gi"), "$1"));
var d = document.createElement("style");
d.textContent = c;
d.media = a.media;
d.disabled = a.disabled;
d.setAttribute("data-href", a.getAttribute("href"));
e.insertBefore(d, a);
e.removeChild(a)
}
}
};
h.send(null);
a.setAttribute("data-inprogress", "")
}, styleElement: function(a) {
var c = a.disabled;
a.textContent = b.fix(a.textContent, true, a);
a.disabled = c
}, styleAttribute: function(a) {
var c =
a.getAttribute("style"), c = b.fix(c, false, a);
a.setAttribute("style", c)
}, process: function() {
f('link[rel~="stylesheet"]:not([data-inprogress])').forEach(StyleFix.link);
f("style").forEach(StyleFix.styleElement);
f("[style]").forEach(StyleFix.styleAttribute)
}, register: function(a, c) {
(b.fixers = b.fixers || []).splice(c === void 0 ? b.fixers.length : c, 0, a)
}, fix: function(a, c) {
for(var d = 0; d < b.fixers.length; d++) {
a = b.fixers[d](a, c) || a;
}
return a
}, camelCase: function(a) {
return a.replace(/-([a-z])/g,function(a, b) {return b.toUpperCase()}).replace("-",
"")
}, deCamelCase: function(a) {
return a.replace(/[A-Z]/g, function(a) {return"-" + a.toLowerCase()})
}};
(function() {
setTimeout(function() {f('link[rel~="stylesheet"]').forEach(StyleFix.link)}, 10);
document.addEventListener("DOMContentLoaded", StyleFix.process, false)
})()
}
})();
(function(f) {
if(window.StyleFix && window.getComputedStyle) {
var b = window.PrefixFree = {prefixCSS:function(a, c) {
function d(c, d, g, e) {
c = b[c];
c.length && (c = RegExp(d + "(" + c.join("|") + ")" + g, "gi"), a = a.replace(c, e))
}
var g = b.prefix;
d("functions", "(\\s|:)", "\\s*\\(", "$1" + g + "$2(");
d("keywords", "(\\s|:)", "(\\s|;|\\}||$)", "$1" + g + "$2$3");
d("properties", "(^|\\{|\\s|;)", "\\s*:", "$1" + g + "$2:");
if(b.properties.length) {
var e = RegExp("\\b(" + b.properties.join("|") + ")(?!:)", "gi");
d("valueProperties", "\\b", ":(.+?);", function(a) {
return a.replace(e,
g + "$1")
})
}
c && (d("selectors", "", "\\b", b.prefixSelector), d("atrules", "@", "\\b", "@" + g + "$1"));
return a = a.replace(RegExp("-" + g, "g"), "-")
}, prefixSelector: function(a) {
return a.replace(/^:{1,2}/, function(a) {return a + b.prefix})
}, prefixProperty: function(a, c) {
var d = b.prefix + a;
return c ? StyleFix.camelCase(d) : d
}};
(function() {
var a = {}, c = "", d = 0, g = [], e = getComputedStyle(document.documentElement,
null), h = document.createElement("div").style, j = function(b) {
g.indexOf(b) === -1 && g.push(b);
if(b.indexOf("-") > -1) {
var e = b.split("-");
if(b.charAt(0) === "-") {
var b = e[1], f = ++a[b] || 1;
a[b] = f;
for(d < f && (c = b, d = f); e.length > 3;) {
e.pop(), f = e.join("-"), StyleFix.camelCase(f)in h && (b = g, b.indexOf(f) === -1 && b.push(f))
}
}
}
};
if(e.length > 0) {
for(var i = 0; i < e.length; i++) {
j(e[i]);
}
} else {
for(var f in e) {
j(StyleFix.deCamelCase(f));
}
}
b.prefix = "-" + c + "-";
b.Prefix = StyleFix.camelCase(b.prefix);
g.sort();
b.properties = [];
for(i = 0; i < g.length; i++) {
f = g[i];
if(f.charAt(0) !== "-")break;
f.indexOf(b.prefix) === 0 && (e = f.slice(b.prefix.length), StyleFix.camelCase(e)in h || b.properties.push(e))
}
b.Prefix ==
"Ms" && !("transform"in h) && !("MsTransform"in h) && "msTransform"in h && b.properties.push("transform",
"transform-origin");
b.properties.sort()
})();
(function() {
function a(a, b) {
g[b] = "";
g[b] = a;
return!!g[b]
}
var c = {"linear-gradient":{property:"backgroundImage", params:"red, teal"}, calc:{property:"width", params:"1px + 5%"}, element:{property:"backgroundImage", params:"#foo"}}, d = {initial:"color", "zoom-in":"cursor", "zoom-out":"cursor", box:"display", flexbox:"display", "inline-flexbox":"display"};
c["repeating-linear-gradient"] =
c["repeating-radial-gradient"] = c["radial-gradient"] = c["linear-gradient"];
b.functions = [];
b.keywords = [];
var g = document.createElement("div").style, e;
for(e in c) {
var h = c[e], f = h.property, h = e + "(" + h.params + ")";
!a(h, f) && a(b.prefix + h, f) && b.functions.push(e)
}
for(var i in d) {
f = d[i], !a(i, f) && a(b.prefix + i, f) && b.keywords.push(i)
}
})();
(function() {
function a(a) {
g.textContent = a + "{}";
return!!g.sheet.cssRules.length
}
var c = {":read-only":null, ":read-write":null, ":any-link":null, "::selection":null}, d = {keyframes:"name", viewport:null,
document: 'regexp(".")'};
b.selectors = [];
b.atrules = [];
var g = f.appendChild(document.createElement("style")), e;
for(e in c) {
var h = e + (c[e] ? "(" + c[e] + ")" : "");
!a(h) && a(b.prefixSelector(h)) && b.selectors.push(e)
}
for(var j in d) {
h = j + " " + (d[j] || ""), !a("@" + h) && a("@" + b.prefix + h) && b.atrules.push(j);
}
f.removeChild(g)
})();
b.valueProperties = ["transition", "transition-property"];
f.className += " " + b.prefix;
StyleFix.register(b.prefixCSS)
}
})(document.documentElement); |
'use strict';
import { createDecorator } from './decoratorFactory';
import { applicators } from './Applicator';
import returnAtIndex from './utils/returnAtIndex';
/**
* Returns the first argument from the function regardless of
* the decorated functions return value.
*/
export default createDecorator(function tapDecorator(fn) {
return returnAtIndex(fn, 0);
}, applicators.single);
|
/* global require, describe, it */
'use strict';
// MODULES //
var chai = require( 'chai' ),
path = require( 'path' ),
argv = require( './../lib/argv.js' );
// VARIABLES //
var expect = chai.expect,
assert = chai.assert;
// TESTS //
describe( 'argv', function tests() {
var fixtures;
fixtures = path.join( __dirname, 'fixtures' );
it( 'should export a function', function test() {
expect( argv ).to.be.a( 'function' );
});
it( 'should return `null` if a mapping file does not exist', function test() {
assert.isNull( argv( 'beep', 'boop.json' ) );
});
it( 'should return a configuration object', function test() {
var expected,
actual,
o;
expected = {
'akey': '1234',
'server': {
'port': 7331
},
'logger': {
'level': 'info'
},
'bool': true,
'obj': {
'hello': 'world'
},
'arr': [ 1, 2, 3, '4' ]
};
o = process.argv;
process.argv = [
null,
null,
'--api-key=1234',
'-p',
'7331',
'--loglevel',
'info',
'--bool',
'--obj={"hello":"world"}',
'--arr',
'[1,2,3,"4"]'
];
actual = argv( fixtures, 'argv.json' );
assert.deepEqual( actual, expected );
process.argv = o;
});
it( 'should throw an error if unable to parse a command-line argument as a specified type', function test() {
var o = process.argv;
process.argv = [
null,
null,
'-p=beep'
];
expect( badValue ).to.throw( TypeError );
process.argv = o;
function badValue() {
argv( fixtures, 'argv.json' );
}
});
});
|
/**
* Created by dat on 5/3/17.
*/
var hic = (function (hic) {
hic.TrackLabel = function ($track) {
var $container;
this.$track = $track;
$('.clickedit')
.hide()
.focusout(endEdit)
.keyup(function(e) {
if ((e.which && 13 === e.which) || (e.keyCode && 13 === e.keyCode)) {
endEdit(e);
return false;
} else {
return true;
}
})
.prev()
.click(function() {
$(this).hide();
$(this)
.next()
.show()
.focus();
});
function endEdit(e) {
var input,
label,
str;
input = $(e.target);
str = ('' === input.val()) ? hic.TrackLabel.defaultText() : input.val();
label = input && input.prev();
label.text(str);
input.hide();
label.show();
}
};
hic.TrackLabel.defaultText = function () {
return 'Untitled';
};
return hic;
})(hic || {});
|
/**
* @license Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.dialog.add( 'sourcedialog', function( editor ) {
var size = CKEDITOR.document.getWindow().getViewPaneSize();
// Make it maximum 800px wide, but still fully visible in the viewport.
var width = Math.min( size.width - 70, 800 );
// Make it use 2/3 of the viewport height.
var height = size.height / 1.5;
// Store old editor data to avoid unnecessary setData.
var oldData;
return {
title: editor.lang.sourcedialog.title,
minWidth: 100,
minHeight: 100,
onShow: function() {
this.setValueOf( 'main', 'data', oldData = editor.getData() );
},
onOk: ( function() {
function setData( dialog, newData ) {
// [IE8] Focus editor before setting selection to avoid setting data on
// locked selection, because in case of inline editor, it won't be
// unlocked before editable's HTML is altered. (#11585)
editor.focus();
editor.setData( newData, function() {
dialog.hide();
// Ensure correct selection.
var range = editor.createRange();
range.moveToElementEditStart( editor.editable() );
range.select();
} );
}
return function() {
// Remove CR from input data for reliable comparison with editor data.
var newData = this.getValueOf( 'main', 'data' ).replace( /\r/g, '' ),
that = this;
// Avoid unnecessary setData. Also preserve selection
// when user changed his mind and goes back to wysiwyg editing.
if ( newData === oldData )
return true;
setTimeout( function() {
setData( that, newData );
} );
// Don't let the dialog close before setData is over, to hide
// from user blinking caused by selection restoring and setting new data.
return false;
};
} )(),
contents: [ {
id: 'main',
label: editor.lang.sourcedialog.title,
elements: [ {
type: 'textarea',
id: 'data',
dir: 'ltr',
inputStyle: 'cursor:auto;' +
'width:' + width + 'px;' +
'height:' + height + 'px;' +
'tab-size:4;' +
'text-align:left;',
'class': 'cke_source'
} ]
} ]
};
} );
|
/**
* A simple test case that determines if elements, specified by a selector,
* exist or not.
*
* The test fails for elements that are found and a case is created for each
* one. The test passes is the selector finds no matching elements.
*/
var Case = require('Case');
const DOM = require('DOM');
var ImgHasAlt = {
run: function (test) {
var selector = 'img';
test.get('scope').forEach(function (scope) {
var candidates = DOM.scry(selector, scope);
if (!candidates.length) {
test.add(Case({
element: undefined,
status: 'inapplicable'
}));
}
else {
candidates.forEach(function (element) {
var status = 'failed';
if (element.hasAttribute('alt')) {
status = 'passed';
}
test.add(Case({
element: element,
status: status
}));
});
}
});
},
meta: {
testability: 1,
title: {
en: 'Image elements must have an \"alt\" attribute',
nl: 'Afbeeldingselementen moeten een \"alt\"-attribuut hebben'
},
description: {
en: 'All <code>img</code> elements must have an alt attribute.',
nl: 'Alle <code>img</code>-elementen moeten een \"alt\"-attribuut hebben.'
},
guidelines: {
508: [
'a'
],
wcag: {
'1.1.1': {
techniques: [
'F65',
'H37'
]
}
}
},
tags: [
'image',
'content'
]
}
};
module.exports = ImgHasAlt;
|
version https://git-lfs.github.com/spec/v1
oid sha256:0841295a7e23dabc77c6deb5dc0d10e89a81db34c125f5c4acaffbd2ded3ebde
size 1451
|
/**
* Created by yuexing on 2016/6/5.
* 这是一个以map作为对象的缓存方案,
* 只能支持单个节点的缓存方案
* 特点是:速度快,不需要安装额外的数据库
* 弱点:如果爬虫要进行分布式抓取那就无法进行了
*
* <p>
* 因为map的特性,自动带有,计数,删除,清空,并且可以很好的解决管理timeoutCallback,不需要再额外的代码处理
* 所以选择了map作为缓存方案
* </p>
*
*/
const fs = require('fs');
const stringUtil = require('../common/stringUtil');
class SimpleCache extends Map{
constructor(fileName) {
super();
if(fileName){
var filters = fs.readFileSync(fileName,'utf8');
this.oldCache = stringUtil.jsonStrToMap(filters);
}
}
/**
* 添加更新缓存
* 1.先判断是否在map内,如果在,清除原来的timeoutCallback
*
* @param {string} key
* @param {object} value
* @param {number} timeout 默认永不超时
* @param {function} timeoutCallback
* @return {boolean} true添加成功,false添加失败
* **/
set(key, value, timeout = 0, timeoutCallback){
let temp = {
value : value,
timeout : timeout,
timeoutCallback : timeoutCallback
};
super.set(key,temp);
}
/**
* 删除单个缓存
*
* @param {string} key
* @return {boolean} true添加成功,false添加失败
* **/
delete(key){
return super.delete(key);
}
clear(){
return super.clear();
}
keys(){
return super.keys();
}
/**
* 用于保存成json字符串
* */
save(fileName,callback){
var _fileName = fileName;
if(!fileName){
_fileName = "cache.json";
}
var _self = this;
fs.writeFile(_fileName, stringUtil.mapToJson(_self), function(err) {
if(callback && typeof callback == 'function'){
callback(err, self);
}
});
}
}
module.exports = SimpleCache;
|
'use strict';
// ci:coverage:exclude
angular.module('app.home')
.controller('HomeCtrl', ['$scope', 'config', 'features', function ($scope, config, features) {
$scope.env = config.env;
$scope.features = features;
}]);
|
"use strict";
//import { Injectable } from '@angular/core';
const Observable_1 = require("rxjs/Observable");
const io = require("socket.io-client");
//@Injectable()
class SocketService {
getPosts() {
this.socket = io.connect();
this.socket.on('connect', () => console.log('Connected!'));
this.socket.on('disconnect', () => console.log('Disconnected!'));
this.socket.on('error', () => console.log('Error!'));
return new Observable_1.Observable((observer) => {
this.socket.on('posts', (data) => observer.next(JSON.parse(data)));
return () => this.socket.close();
});
}
train(id, liked) {
this.socket.emit('train', id, liked);
}
}
exports.SocketService = SocketService;
//# sourceMappingURL=socket.service.js.map |
/*! jCarousel - v0.3.1 - 2014-05-26
* http://sorgalla.com/jcarousel
* Copyright (c) 2014 Jan Sorgalla; Licensed MIT */
(function(t){"use strict";t.jCarousel.plugin("jcarouselAutoscroll",{_options:{target:"+=1",interval:3e3,autostart:!0},_timer:null,_init:function(){this.onDestroy=t.proxy(function(){this._destroy(),this.carousel().one("jcarousel:createend",t.proxy(this._create,this))},this),this.onAnimateEnd=t.proxy(this.start,this)},_create:function(){this.carousel().one("jcarousel:destroy",this.onDestroy),this.options("autostart")&&this.start()},_destroy:function(){this.stop(),this.carousel().off("jcarousel:destroy",this.onDestroy)},start:function(){return this.stop(),this.carousel().one("jcarousel:animateend",this.onAnimateEnd),this._timer=setTimeout(t.proxy(function(){this.carousel().jcarousel("scroll",this.options("target"))},this),this.options("interval")),this},stop:function(){return this._timer&&(this._timer=clearTimeout(this._timer)),this.carousel().off("jcarousel:animateend",this.onAnimateEnd),this}})})(jQuery); |
// Setup our tabs and cache the jQuery Object to be reused.
var $tabs = $("#tabs").tabs({
// tabTemplate: HTML template from which a new tab is created and added.
// The placeholders #{href} and #{label} are replaced with the
// url and tab label that are passed as arguments to
// the add method.
tabTemplate: "<li><a href='#{href}'>#{label}</a>\
<span class='ui-icon ui-icon-close'>Remove Tab</span></li>",
// add (event): This event is triggered when a tab is added.
add: function(event, ui) {
// Setup a tab based on a jQuery Template defined in the HTML.
$("#newProjectTabTemplate").tmpl()
// append the template results to the selected contents.
.appendTo(ui.panel)
// We need to recreate our To Do list accordions to setup the new
// accordion that was created with the new project tab.
.setupToDoList();
}
});
// Setup a click event to remove a tab from the tab bar.
$("#tabs span.ui-icon-close").live("click", function() {
// Remove (method): Remove a tab. The second argument is the zero-based
// index of the tab to be removed.
$tabs.tabs('remove', $(this).closest('li').index());
});
// Setup a dialog widget and cache the results so we can call it easily.
// This will ask the user for the name of the project.
var addProjectItem = $("#AddProjectItem").dialog({
// modal: If set to true, the dialog will have modal behavior; other items
// on the page will be disabled (i.e. cannot be interacted with). Modal
// dialogs create an overlay below the dialog but above
// other page elements.
modal: true,
// autoOpen: When autoOpen is true the dialog will open automatically when
// dialog is called. If false it will stay hidden until
// .dialog("open") is called on it.
autoOpen: false,
// buttons: Specifies which buttons should be displayed on the dialog.
// The property key is the text of the button. The value is the
// callback function for when the button is clicked. The context
// of the callback is the dialog element; if you need access to
// the button, it is available as the target of the event object.
buttons: {
// creates a button to handle adding a new tab.
"Add new project": function() {
// using the date to create a unique tab id.
var foo = new Date();
$tabs.tabs("add", "#project-" + foo.getTime(), $("#project").val())
// Select the new tab to make it active.
.tabs("select", $tabs.tabs("length") - 1);
// Close the dialog
$(this).dialog("close");
// Clear the value on the form field in the dialog.
$("#project").val("");
},
// creates a button to cancel the dialog.
"Cancel": function() {
// Close the dialog
$(this).dialog("close");
// Clear any values that may of been entered.
$("#project").val("");
}
}
});
// Bind a click event on the Add a Project button.
$("#AddProject").bind("click", function() {
// Opens the dialog to add a new Project tab.
addProjectItem.dialog('open');
// Call button widget to format the Add a Project button.
}).button();
// ------------------------------------------------------------------ //
// ------------------------------------------------------------------ //
// ------------------------------------------------------------------ //
/******************************************************************************/
// Setup a function that is easy to reuse.
$.fn.setupToDoList = function() {
// return the jQuery object so that we can continue chaining
return this.find(".accordion")
// call the refreshAccordion method which tearsdown and rebuilds the todo
// list as an accordion.
.refreshAccordion()
// make the todo list sortable.
.sortable({
// constrain movement to the y axis only
axis: "y",
// define which element will be the handle when sorting.
handle: "h3",
// stop: event that handles when the element being sorted has stopped.
// In this instance we are setting the global stop variable which
// helps determine if the todo item is in movement.
stop: function() {
stop = true;
},
// Don't sort elements with class ui-state-disabled.
cancel: ".ui-state-disabled"
})
// return the set of matched elements to it's previous state.
.end().find("button")
// set the element with class 'button' as a button widget.
.button();
};
// A reusable plugin used to refresh the accordion. When this is called the
// accordion will be torn down and setup again. Call this when you add a new
// item to the accordion or on initial setup.
$.fn.refreshAccordion = function() {
// return the jQuery object so that we can continue chaining
return this
// call the destroy method which tears down the accordion.
.accordion('destroy')
// set our jQuery object back into an accordion
.accordion({
// setting the active option to false allows for no item to be open and active.
// The default is that one item is always open.
active: false,
// setting autoHeight to false allows for each item to have a dynamic height.
autoHeight: false,
// collapsible set to true allows the accordion to have no open items.
collapsible: true,
// header defines the element of the item that is the header.
header: "> div > h3"
})
// calling the refresh method for sortable allows the new item to be sortable.
.sortable('refresh');
};
// accordion to do list
// stop is a variable we will use to keep track if any item is moving during a sort.
var stop = false;
// If an item is moving during a sort we want to override the default click
// function of the accordion header to allow the sort to happen unimpeded.
$(".accordion h3").click(function(event) {
// if the item is moving disable the click event for the accordion widget.
if (stop) {
// keeps other handlers from being executed and prevents the event from
// bubbling up the DOM tree.
event.stopImmediatePropagation();
// this will prevent the default action of the event from being triggered.
event.preventDefault();
// reset the stop variable
stop = false;
}
});
//Add a to do item
// Define the dialog for adding a new todo item. Assign it to a variable so
// that it can be reused easily.
var addToDo = $("#AddToDoItem").dialog({
// Set the dialog to be a modal meaning all other elements on the page will be disabled.
modal: true,
// Set autoOpen to False as we don't want the dialog opening on page load.
autoOpen: false,
// Define the dialogs buttons
buttons: {
// Button for adding a to-do item
"Add to do item": function() {
//create a JSON object to pass the data from the form to the template.
var newItem = [{
task: $("#task").val(),
description: $("#description").val(),
duedate: $("#duedate").val()}],
// select and cache the jQuery Object for the currently visible accordion.
$accordion = $tabs.find(".ui-tabs-panel:visible .accordion");
// Select the template, render it with the JSON data above and append it to
// the visible accordion.
$("#ToDoItemTemplate").tmpl(newItem).appendTo($accordion);
// Call the refreshAccordion to add the new item to the accordion
$accordion.refreshAccordion();
// Close the dialog
$(this).dialog("close");
// Clear the fields in the dialog
$("#task, #description, #duedate").val("");
},
// Button for cancelling adding a new to-do item
"Cancel": function() {
// close the dialog
$(this).dialog("close");
// Clear the field in the dialog
$("#task, #description, #duedate").val("");
}
}
});
// Define a live click event that will open the dialog to add a new todo list.
// We use live instead of just binding the click event because we will be
// dynamically adding new Add To Do buttons with each new tab.
$(".AddToDo").live("click", function() {
// call our variable that defines our Add To-Do Dialog and
addToDo.dialog('open');
});
// Define the datepicker widget for the duedate field.
$("#duedate").datepicker();
// Define a live click event that will complete a task and remove it from the list.
// We use live instead of just binding the click even because the todo event was
// added dynamically and live will catch the event on newly created elements that are
//created after page load.
$("input[type=checkbox]").live("click", function() {
$(this)
// Search up through the DOM tree to find the first instance of the selection.
// We are looking for the first parent item with a data attribute of sortable-item.
// This data attribute is set from the sortable interaction widget.
.closest(':data(sortable-item)')
// find the H3 element and trigger a click event to activate and close
// the accordion item.
.find('h3').click()
// return the set of matched elements to it's previous state.
.end()
// Hide the item we are completing with a sliding motion. upon completion
// of the animation fire the callback function.
.slideUp(function() {
// remove this todo item from the DOM.
$(this).remove();
});
});
// Initially set up the todo list with what's already defined in the HTML.
$(".ui-tabs-panel").setupToDoList(); |
'use strict';
/**
* Module dependencies
*/
const actionUtil = require('sails/lib/hooks/blueprints/actionUtil');
const _ = require('lodash');
const Promise = require("bluebird");
/**
* Find Records
*
* get /:modelIdentity
* * /:modelIdentity/find
*
* An API call to find and return model instances from the data adapter
* using the specified criteria. If an id was specified, just the instance
* with that unique id will be returned.
*
* Optional:
* @param {Object} where - the find criteria (passed directly to the ORM)
* @param {Integer} limit - the maximum number of records to send back (useful for pagination)
* @param {Integer} skip - the number of records to skip (useful for pagination)
* @param {String} sort - the order of returned records, e.g. `name ASC` or `age DESC`
* @param {String} callback - default jsonp callback param (i.e. the name of the js function returned)
*/
module.exports = function findRecords(req, res) {
// Look up the model
const Model = actionUtil.parseModel(req);
// If an `id` param was specified, use the findOne blueprint action
// to grab the particular instance with its primary key === the value
// of the `id` param. (mainly here for compatibility for 0.9, where
// there was no separate `findOne` action)
if (actionUtil.parsePk(req))
return require('./findOne')(req, res);
const limit = actionUtil.parseLimit(req);
const skip = actionUtil.parseSkip(req);
let sort = actionUtil.parseSort(req);
if (_.isEmpty(sort) && Model.DEFAULT_SORTING)
sort = Model.DEFAULT_SORTING;
// Lookup for records that match the specified criteria
let query = Model.find()
.where(actionUtil.parseCriteria(req))
.limit(limit)
.skip(skip)
.sort(sort);
query = actionUtil.populateRequest(query, req);
const countQuery = Model.count()
.where(actionUtil.parseCriteria(req));
Promise.all([query, countQuery])
.spread((matchingRecords, count)=> {
// Only `.watch()` for new instances of the model if
// `autoWatch` is enabled.
if (req._sails.hooks.pubsub && req.isSocket) {
Model.subscribe(req, matchingRecords);
if (req.options.autoWatch) {
Model.watch(req);
}
// Also subscribe to instances of all associated models
_.each(matchingRecords, function (record) {
actionUtil.subscribeDeep(req, record);
});
}
res.ok({
count: count,
items: matchingRecords
});
})
.catch(err => res.serverError(err));
};
|
chrome.extension.sendMessage(
{
action: "get-settings",
url: location.href
},
function(response) {
var tabsize = response.settings.tabsize || response.default_settings.tabsize;
if(!tabsize) return ;
var css = document.createElement('link');
css.href = chrome.extension.getURL('tab-size-' + tabsize + '.css');
css.rel = 'stylesheet';
css.type = 'text/css';
var body = document.getElementsByTagName('body')[0];
body.insertBefore(css, body.firstChild);
}
);
|
function demoCalendarMonthWithHeadings() {
$demo.append(
CalendarMonthWithHeadings.create()
);
}
|
import inputAfterHTML from "./templates/after.html";
import inputBeforeHTML from "./templates/before.html";
import inputLabel from "./templates/label.html";
const settings = {
id: "first-name-input",
type: "text",
name: "firstname",
beforeHtml:{
html: inputBeforeHTML,
classes: ""
},
afterHtml:{
html: inputAfterHTML,
classes: ""
},
labelHTML:inputLabel,
input: {},
container: {}
,
attributes : {},
settings : {
width: "1/2"
},
errors : {},
}
export default settings; |
function LocalShaderParam() {
if(arguments[0] != "__skip_ptr__") {
this.__ptr = Polycode.LocalShaderParam()
}
Object.defineProperties(this, {
'name': { enumerable: true, configurable: true, get: LocalShaderParam.prototype.__get_name, set: LocalShaderParam.prototype.__set_name},
'type': { enumerable: true, configurable: true, get: LocalShaderParam.prototype.__get_type, set: LocalShaderParam.prototype.__set_type},
'ownsPointer': { enumerable: true, configurable: true, get: LocalShaderParam.prototype.__get_ownsPointer, set: LocalShaderParam.prototype.__set_ownsPointer},
'arraySize': { enumerable: true, configurable: true, get: LocalShaderParam.prototype.__get_arraySize, set: LocalShaderParam.prototype.__set_arraySize}
})
}
LocalShaderParam.prototype.__get_name = function() {
return Polycode.LocalShaderParam__get_name(this.__ptr)
}
LocalShaderParam.prototype.__set_name = function(val) {
Polycode.LocalShaderParam__set_name(this.__ptr, val)
}
LocalShaderParam.prototype.__get_type = function() {
return Polycode.LocalShaderParam__get_type(this.__ptr)
}
LocalShaderParam.prototype.__set_type = function(val) {
Polycode.LocalShaderParam__set_type(this.__ptr, val)
}
LocalShaderParam.prototype.__get_ownsPointer = function() {
return Polycode.LocalShaderParam__get_ownsPointer(this.__ptr)
}
LocalShaderParam.prototype.__set_ownsPointer = function(val) {
Polycode.LocalShaderParam__set_ownsPointer(this.__ptr, val)
}
LocalShaderParam.prototype.__get_arraySize = function() {
return Polycode.LocalShaderParam__get_arraySize(this.__ptr)
}
LocalShaderParam.prototype.__set_arraySize = function(val) {
Polycode.LocalShaderParam__set_arraySize(this.__ptr, val)
}
Duktape.fin(LocalShaderParam.prototype, function (x) {
if (x === LocalShaderParam.prototype) {
return;
}
Polycode.LocalShaderParam__delete(x.__ptr)
})
LocalShaderParam.prototype.Copy = function() {
var retVal = new LocalShaderParam("__skip_ptr__")
retVal.__ptr = Polycode.LocalShaderParam_Copy(this.__ptr)
return retVal
}
LocalShaderParam.prototype.getNumber = function() {
return Polycode.LocalShaderParam_getNumber(this.__ptr)
}
LocalShaderParam.prototype.getVector2 = function() {
var retVal = new Vector2("__skip_ptr__")
retVal.__ptr = Polycode.LocalShaderParam_getVector2(this.__ptr)
return retVal
}
LocalShaderParam.prototype.getVector3 = function() {
var retVal = new Vector3("__skip_ptr__")
retVal.__ptr = Polycode.LocalShaderParam_getVector3(this.__ptr)
return retVal
}
LocalShaderParam.prototype.getMatrix4 = function() {
var retVal = new Matrix4("__skip_ptr__")
retVal.__ptr = Polycode.LocalShaderParam_getMatrix4(this.__ptr)
return retVal
}
LocalShaderParam.prototype.getColor = function() {
var retVal = new Color("__skip_ptr__")
retVal.__ptr = Polycode.LocalShaderParam_getColor(this.__ptr)
return retVal
}
LocalShaderParam.prototype.setNumber = function(x) {
Polycode.LocalShaderParam_setNumber(this.__ptr, x)
}
LocalShaderParam.prototype.setVector2 = function(x) {
Polycode.LocalShaderParam_setVector2(this.__ptr, x)
}
LocalShaderParam.prototype.setVector3 = function(x) {
Polycode.LocalShaderParam_setVector3(this.__ptr, x)
}
LocalShaderParam.prototype.setMatrix4 = function(x) {
Polycode.LocalShaderParam_setMatrix4(this.__ptr, x)
}
LocalShaderParam.prototype.setMatrix4Array = function(x) {
Polycode.LocalShaderParam_setMatrix4Array(this.__ptr, x)
}
LocalShaderParam.prototype.setColor = function(x) {
Polycode.LocalShaderParam_setColor(this.__ptr, x)
}
LocalShaderParam.prototype.setTexture = function(texture) {
Polycode.LocalShaderParam_setTexture(this.__ptr, texture)
}
LocalShaderParam.prototype.getTexture = function() {
var retVal = new Texture("__skip_ptr__")
retVal.__ptr = Polycode.LocalShaderParam_getTexture(this.__ptr)
return retVal
}
LocalShaderParam.prototype.setCubemap = function(cubemap) {
Polycode.LocalShaderParam_setCubemap(this.__ptr, cubemap)
}
LocalShaderParam.prototype.getCubemap = function() {
var retVal = new Cubemap("__skip_ptr__")
retVal.__ptr = Polycode.LocalShaderParam_getCubemap(this.__ptr)
return retVal
}
|
import { expect } from 'chai'
describe('Test', () => {
it('should be true', () => {
expect(true).to.be.equal(true)
})
})
|
var hljs = new function() {
/* Utility functions */
function escape(value) {
return value.replace(/&/gm, '&').replace(/</gm, '<').replace(/>/gm, '>');
}
function findCode(pre) {
for (var node = pre.firstChild; node; node = node.nextSibling) {
if (node.nodeName.toUpperCase () == 'CODE')
return node;
if (!(node.nodeType == 3 && node.nodeValue.match(/\s+/)))
break;
}
}
function blockText(block, ignoreNewLines) {
return Array.prototype.map.call(block.childNodes, function(node) {
if (node.nodeType == 3) {
return ignoreNewLines ? node.nodeValue.replace(/\n/g, '') : node.nodeValue;
}
if (node.nodeName.toUpperCase () == 'BR') {
return '\n';
}
return blockText(node, ignoreNewLines);
}).join('');
}
function blockLanguage(block) {
var classes = (block.className + ' ' + (block.parentNode ? block.parentNode.className : '')).split(/\s+/);
classes = classes.map(function(c) {return c.replace(/^language-/, '');});
for (var i = 0; i < classes.length; i++) {
if (languages[classes[i]] || classes[i] == 'no-highlight') {
return classes[i];
}
}
}
/* Stream merging */
function nodeStream(node) {
var result = [];
(function _nodeStream(node, offset) {
for (var child = node.firstChild; child; child = child.nextSibling) {
if (child.nodeType == 3)
offset += child.nodeValue.length;
else if (child.nodeName.toUpperCase() == 'BR')
offset += 1;
else if (child.nodeType == 1) {
result.push({
event: 'start',
offset: offset,
node: child
});
offset = _nodeStream(child, offset);
result.push({
event: 'stop',
offset: offset,
node: child
});
}
}
return offset;
})(node, 0);
return result;
}
function mergeStreams(original, highlighted, value) {
var processed = 0;
var result = '';
var nodeStack = [];
function selectStream() {
if (!original.length || !highlighted.length) {
return original.length ? original : highlighted;
}
if (original[0].offset != highlighted[0].offset) {
return (original[0].offset < highlighted[0].offset) ? original : highlighted;
}
/*
To avoid starting the stream just before it should stop the order is
ensured that original always starts first and closes last:
if (event1 == 'start' && event2 == 'start')
return original;
if (event1 == 'start' && event2 == 'stop')
return highlighted;
if (event1 == 'stop' && event2 == 'start')
return original;
if (event1 == 'stop' && event2 == 'stop')
return highlighted;
... which is collapsed to:
*/
return highlighted[0].event == 'start' ? original : highlighted;
}
function open(node) {
function attr_str(a) {return ' ' + a.nodeName + '="' + escape(a.value) + '"';}
result += '<' + node.nodeName.toLowerCase() + Array.prototype.map.call(node.attributes, attr_str).join('') + '>';
}
function close(node) {
result += '</' + node.nodeName.toLowerCase() + '>';
}
function render(event) {
(event.event == 'start' ? open : close)(event.node);
}
while (original.length || highlighted.length) {
var stream = selectStream();
result += escape(value.substr(processed, stream[0].offset - processed));
processed = stream[0].offset;
if (stream == original) {
/*
On any opening or closing tag of the original markup we first close
the entire highlighted node stack, then render the original tag along
with all the following original tags at the same offset and then
reopen all the tags on the highlighted stack.
*/
nodeStack.reverse().forEach(close);
do {
render(stream.splice(0, 1)[0]);
stream = selectStream();
} while (stream == original && stream.length && stream[0].offset == processed);
nodeStack.reverse().forEach(open);
} else {
if (stream[0].event == 'start') {
nodeStack.push(stream[0].node);
} else {
nodeStack.pop();
}
render(stream.splice(0, 1)[0]);
}
}
return result + escape(value.substr(processed));
}
/* Initialization */
function compileLanguage(language) {
function reStr(re) {
return (re && re.source) || re;
}
function langRe(value, global) {
return RegExp(
reStr(value),
'm' + (language.case_insensitive ? 'i' : '') + (global ? 'g' : '')
);
}
function compileMode(mode, parent) {
if (mode.compiled)
return;
mode.compiled = true;
var keywords = []; // used later with beginWithKeyword but filled as a side-effect of keywords compilation
if (mode.keywords) {
var compiled_keywords = {};
function flatten(className, str) {
if (language.case_insensitive) {
str = str.toLowerCase();
}
str.split(' ').forEach(function(kw) {
var pair = kw.split('|');
compiled_keywords[pair[0]] = [className, pair[1] ? Number(pair[1]) : 1];
keywords.push(pair[0]);
});
}
mode.lexemsRe = langRe(mode.lexems || '\\b' + hljs.IDENT_RE + '\\b(?!\\.)', true);
if (typeof mode.keywords == 'string') { // string
flatten('keyword', mode.keywords);
} else {
for (var className in mode.keywords) {
if (!mode.keywords.hasOwnProperty(className))
continue;
flatten(className, mode.keywords[className]);
}
}
mode.keywords = compiled_keywords;
}
if (parent) {
if (mode.beginWithKeyword) {
mode.begin = '\\b(' + keywords.join('|') + ')\\b(?!\\.)\\s*';
}
mode.beginRe = langRe(mode.begin ? mode.begin : '\\B|\\b');
if (!mode.end && !mode.endsWithParent)
mode.end = '\\B|\\b';
if (mode.end)
mode.endRe = langRe(mode.end);
mode.terminator_end = reStr(mode.end) || '';
if (mode.endsWithParent && parent.terminator_end)
mode.terminator_end += (mode.end ? '|' : '') + parent.terminator_end;
}
if (mode.illegal)
mode.illegalRe = langRe(mode.illegal);
if (mode.relevance === undefined)
mode.relevance = 1;
if (!mode.contains) {
mode.contains = [];
}
for (var i = 0; i < mode.contains.length; i++) {
if (mode.contains[i] == 'self') {
mode.contains[i] = mode;
}
compileMode(mode.contains[i], mode);
}
if (mode.starts) {
compileMode(mode.starts, parent);
}
var terminators = [];
for (var i = 0; i < mode.contains.length; i++) {
terminators.push(reStr(mode.contains[i].begin));
}
if (mode.terminator_end) {
terminators.push(reStr(mode.terminator_end));
}
if (mode.illegal) {
terminators.push(reStr(mode.illegal));
}
mode.terminators = terminators.length ? langRe(terminators.join('|'), true) : {exec: function(s) {return null;}};
}
compileMode(language);
}
/*
Core highlighting function. Accepts a language name and a string with the
code to highlight. Returns an object with the following properties:
- relevance (int)
- keyword_count (int)
- value (an HTML string with highlighting markup)
*/
function highlight(language_name, value, ignore_illegals, continuation) {
function subMode(lexem, mode) {
for (var i = 0; i < mode.contains.length; i++) {
var match = mode.contains[i].beginRe.exec(lexem);
if (match && match.index == 0) {
return mode.contains[i];
}
}
}
function endOfMode(mode, lexem) {
if (mode.end && mode.endRe.test(lexem)) {
return mode;
}
if (mode.endsWithParent) {
return endOfMode(mode.parent, lexem);
}
}
function isIllegal(lexem, mode) {
return !ignore_illegals && mode.illegal && mode.illegalRe.test(lexem);
}
function keywordMatch(mode, match) {
var match_str = language.case_insensitive ? match[0].toLowerCase() : match[0];
return mode.keywords.hasOwnProperty(match_str) && mode.keywords[match_str];
}
function processKeywords() {
var buffer = escape(mode_buffer);
if (!top.keywords)
return buffer;
var result = '';
var last_index = 0;
top.lexemsRe.lastIndex = 0;
var match = top.lexemsRe.exec(buffer);
while (match) {
result += buffer.substr(last_index, match.index - last_index);
var keyword_match = keywordMatch(top, match);
if (keyword_match) {
keyword_count += keyword_match[1];
result += '<span class="'+ keyword_match[0] +'">' + match[0] + '</span>';
} else {
result += match[0];
}
last_index = top.lexemsRe.lastIndex;
match = top.lexemsRe.exec(buffer);
}
return result + buffer.substr(last_index);
}
function processSubLanguage() {
if (top.subLanguage && !languages[top.subLanguage]) {
return escape(mode_buffer);
}
var continuation = top.subLanguageMode == 'continuous' ? top.top : undefined;
var result = top.subLanguage ? highlight(top.subLanguage, mode_buffer, true, continuation) : highlightAuto(mode_buffer);
// Counting embedded language score towards the host language may be disabled
// with zeroing the containing mode relevance. Usecase in point is Markdown that
// allows XML everywhere and makes every XML snippet to have a much larger Markdown
// score.
if (top.relevance > 0) {
keyword_count += result.keyword_count;
relevance += result.relevance;
}
top.top = result.top;
return '<span class="' + result.language + '">' + result.value + '</span>';
}
function processBuffer() {
return top.subLanguage !== undefined ? processSubLanguage() : processKeywords();
}
function startNewMode(mode, lexem) {
var markup = mode.className? '<span class="' + mode.className + '">': '';
if (mode.returnBegin) {
result += markup;
mode_buffer = '';
} else if (mode.excludeBegin) {
result += escape(lexem) + markup;
mode_buffer = '';
} else {
result += markup;
mode_buffer = lexem;
}
top = Object.create(mode, {parent: {value: top}});
}
function processLexem(buffer, lexem) {
mode_buffer += buffer;
if (lexem === undefined) {
result += processBuffer();
return 0;
}
var new_mode = subMode(lexem, top);
if (new_mode) {
result += processBuffer();
startNewMode(new_mode, lexem);
return new_mode.returnBegin ? 0 : lexem.length;
}
var end_mode = endOfMode(top, lexem);
if (end_mode) {
var origin = top;
if (!(origin.returnEnd || origin.excludeEnd)) {
mode_buffer += |
alasql.ZipWriter = function () {
/**
@type {object} Entries for ZIP file
*/
var entries = [];
/**
Calculate CRC32
@function
@param {array} buf Data buffer
@return {number}
*/
function calculateCrc32(buf) {
var CRC_TABLE = [
0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419,
0x706af48f, 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4,
0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07,
0x90bf1d91, 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de,
0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, 0x136c9856,
0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9,
0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4,
0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b,
0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3,
0x45df5c75, 0xdcd60dcf, 0xabd13d59, 0x26d930ac, 0x51de003a,
0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599,
0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924,
0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190,
0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f,
0x9fbfe4a5, 0xe8b8d433, 0x7807c9a2, 0x0f00f934, 0x9609a88e,
0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01,
0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed,
0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950,
0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3,
0xfbd44c65, 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2,
0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a,
0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5,
0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, 0xbe0b1010,
0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f,
0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17,
0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6,
0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615,
0x73dc1683, 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8,
0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, 0xf00f9344,
0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb,
0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a,
0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5,
0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1,
0xa6bc5767, 0x3fb506dd, 0x48b2364b, 0xd80d2bda, 0xaf0a1b4c,
0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef,
0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236,
0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe,
0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31,
0x2cd99e8b, 0x5bdeae1d, 0x9b64c2b0, 0xec63f226, 0x756aa39c,
0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713,
0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b,
0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242,
0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1,
0x18b74777, 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c,
0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45, 0xa00ae278,
0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7,
0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, 0x40df0b66,
0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9,
0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605,
0xcdd70693, 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8,
0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b,
0x2d02ef8d
];
var crc = ~0;
for (var ix = 0; ix < buf.length; ix++) {
var offset = (crc ^ buf[ix]) & 0xFF;
crc = (crc >>> 8) ^ CRC_TABLE[offset];
}
return crc ^ -1;
}
/**
Pack data in the buffer
@function
@param {array} items
@return {string}
*/
function pack(items) {
var data = arguments, idx = 0, buffer, bufferSize = 0;
// Calculate buffer size
items = items.split('');
items.forEach(function(type) {
if (type == 'v') {
bufferSize += 2;
} else if (type == 'V' || type == 'l') {
bufferSize += 4;
}
});
// Fill buffer
buffer = new Buffer(bufferSize);
items.forEach(function(type, index) {
if (type == 'v') {
buffer.writeUInt16LE(data[index + 1], idx);
idx += 2;
} else if (type == 'V') {
buffer.writeUInt32LE(data[index + 1], idx);
idx += 4;
} else if (type == 'l') {
buffer.writeInt32LE(data[index + 1], idx);
idx += 4;
}
});
return buffer;
}
function normalizeZipPath(zipPath) {
return zipPath.replace(/\\/g, '/').replace(/^\/|\/$/g, '');
}
this.addEntry = function(entry) {
entry.path = normalizeZipPath(entry.path);
entries.push(entry);
};
// this.addFile = function(zipPath, localPath) {
// this.addEntry({
// path: zipPath,
// file: localPath
// });
// };
this.addDir = function(zipPath, localPath) {
this.addEntry({
path: zipPath,
file: localPath,
isFile: false
});
};
this.addData = function(zipPath, data) {
if (!Buffer.isBuffer(data)) {
data = new Buffer(data);
}
this.addEntry({
path: zipPath,
data: data
});
};
function buildZipBuffer() {
var buffers = [];
var length = 0;
function append(buf) {
if (typeof(buf) == "string") {
buf = new Buffer(buf);
}
buffers.push(buf);
length += buf.length;
}
entries.forEach(function(entry) {
var mtime, mdate;
entry.extra = entry.extra || "";
entry.comment = entry.comment || "";
// entry.cmethod = entry.csize > 0 ? 0x0008 : 0; // Deflate/Store
entry.cmethod = 0; // Deflate/Store
mtime = entry.mtime;
mdate = entry.mdate;
// Convert unix time to dos time
if (entry.mtime instanceof Date) {
mtime = entry.mtime.getHours();
mtime = mtime << 6;
mtime = mtime | entry.mtime.getMinutes();
mtime = mtime << 5;
mtime = mtime | entry.mtime.getSeconds() / 2;
mdate = entry.mtime.getFullYear() - 1980;
mdate = mdate << 4;
mdate = mdate | (entry.mtime.getMonth() + 1);
mdate = mdate << 5;
mdate = mdate | entry.mtime.getDate();
}
// Setup filename
var fileName = entry.path;
if (!entry.isFile && fileName.charAt(fileName.length - 1) != '/') {
entry.path = fileName = fileName + "/";
}
entry.offset = length;
// Write local file header
append(pack("VvvvvvlVVvv",
0x04034b50, // Local File Header Signature
0x0014, // Version needed to extract
0x0002, // General purpose bit flag
entry.cmethod, // Compression method (deflate)
mtime, // Last mod file time (MS-DOS)
mdate, // Last mod file date (MS-DOS)
entry.crc32, // CRC-32
entry.csize, // Compressed size
entry.size, // Uncompressed size
fileName.length, // Filename length
entry.extra.length // Extra field length
));
// Write variable data
append(fileName);
append(entry.extra);
append(entry.data);
entry.mtime = mtime;
entry.mdate = mdate;
entry.eattr = entry.isFile ? 0x00000020 : 0x00000030;
});
var startOffset = length;
var centralDirSize = 0;
// Write central directory information
entries.forEach(function(entry) {
// Add central directory file header
append(pack("VvvvvvvlVVvvvvvVV",
0x02014b50, // Central file header signature
0x0014, // Version made by
0x0014, // Version extracted
0x0002, // General purpose bit flag
entry.cmethod, // Compression method (deflate)
entry.mtime, // Last mod file time (MS-DOS)
entry.mdate, // Last mod file date (MS-DOS)
entry.crc32, // CRC-32
entry.csize, // Compressed size
entry.size, // Uncompressed size
entry.path.length, // Filename length
entry.extra.length, // Extra field length
entry.comment.length, // Comment length
0, // Disk
0, // Internal file attributes
entry.eattr, // External file attributes
entry.offset // Relative offset of local file header
));
// Write filename, extra field and comment
append(entry.path);
append(entry.extra);
append(entry.comment);
// Central directory info size + file name length + extra field length + comment length
centralDirSize += 46 + entry.path.length + entry.extra.length + entry.comment.length;
});
var comment = "";
// Write end of central directory record
append(pack("VvvvvVVv",
0x06054b50, // End of central directory signature
0, // Number of this disk
0, // Disk where central directory starts
entries.length, // Number of central directory records on this disk
entries.length, // Total number of central directory records
centralDirSize, // Size of central directory (bytes)
startOffset, // Offset of start of central directory, relative to start of archive
comment.length // Zip file comment length
));
// Write comment
append(comment);
var buffer = Buffer.concat(buffers);
return buffer;
}
this.toBuffer = function(callback) {
var index = -1;
function deflateNext() {
var data;
var entry = entries[++index];
if (entry) {
entry.csize = entry.size = entry.crc32 = 0;
data = entry.data = entry.data ? entry.data : new Buffer(0);
// if (entry.file) {
// var stats = fs.statSync(entry.file);
// entry.mtime = stats.mtime;
// if (stats.isFile()) {
// data = fs.readFileSync(entry.file);
// }
// } else {
entry.mtime = new Date();
// }
if (entry.isFile !== false) {
entry.crc32 = calculateCrc32(data);
entry.isFile = true;
entry.size = data.length;
// zlib.deflateRaw(data, function(err, buf) {
// entry.data = buf;
entry.csize = entry.size;
deflateNext();
// });
} else {
deflateNext();
}
} else {
callback(buildZipBuffer());
}
}
deflateNext();
};
// this.saveAs = function(filePath, callback) {
// this.toBuffer(function(buf) {
// fs.writeFile(filePath, buf, callback);
// });
// };
}
//module.exports.ZipWriter = ZipWriter;
|
var fs = require('fs')
module.exports = update
function update(location, config, done) {
fs.readFile(location, 'utf8', function(err, pkg) {
if (err) return done(err)
try {
var json = JSON.parse(pkg)
} catch(e) {
return done(e)
}
json.aperture = json.aperture || {}
json.aperture.sources = config.sources
json = JSON.stringify(json, null, 2) + '\n'
fs.writeFile(location, json, done)
})
}
|
#include "common/mysql_helper.js"
#include "cmon/alarms.h"
var DESCRIPTION="This advisor selects the top 5 queries, sorted by execution count, from performance_schema." ;
query="select (count_star/(select sum(count_star) FROM"
" performance_schema.events_statements_summary_by_digest) * 100) as pct,"
" count_star,left(digest_text,150) as stmt "
" from performance_schema.events_statements_summary_by_digest"
" order by 1 desc limit 5";
function main()
{
var hosts = cluster::mySqlNodes();
print("Top 5 Queries per Server");
print(" ");
var advisorMap = {};
for (idx = 0; idx < hosts.size(); ++idx)
{
host = hosts[idx];
map = host.toMap();
connected = map["connected"];
msg = "";
var advice = new CmonAdvice();
advice.setHost(host);
advice.setTitle("Top Queries");
if(!connected)
continue;
if (!readVariable(host, "performance_schema").toBoolean())
{
advice.setAdvice("No data to analyze.");
advice.setJustification("performance_schema is not enabled.");
advice.setSeverity(Ok);
advisorMap[idx]= advice;
print(host, ": performance_schema is not enabled.");
continue;
}
ret = getValueMap(host, query);
print("Server: ", host);
print("------------------------");
if(ret == false)
{
advice.setAdvice("No queries found.");
advice.setJustification("No queries found.");
advice.setSeverity(Ok);
advisorMap[idx]= advice;
print("No queries found.");
continue;
}
else
{
msg=concatenate(msg, "<table>");
msg=concatenate(msg, "<tr><td width=20%>Percent</td>"
"<td width=20%>ExecCount</td>"
"<td width=60%>Query</td></tr>");
for(i=0; i<ret.size(); ++i)
{
psQuery = ret[i][2];
if (len(psQuery) > 512)
{
psQuery = left(psQuery, 512);
psQuery = psQuery + "...truncated";
}
msg= concatenate(msg, "<tr><td width=20%>" + round(ret[i][0].toDouble(),2) + "</td>"
"<td width=20%>" + ret[i][1] + "</td>"
"<td width=60%>" + psQuery + "</td></tr>");
/* msg = concatenate(msg,
"Pct : ", round(ret[i][0].toDouble(),2), "%",
", Exec Count: ", ret[i][1],
", ", ret[i][2], "<br/>");*/
}
msg=concatenate(msg,"</table><br/>");
if (msg != "")
{
advice.setAdvice("Top 5 Queries.");
advice.setJustification(msg);
advice.setSeverity(Ok);
advisorMap[idx]= advice;
}
print(msg);
}
}
return advisorMap;
}
|
/* Starts the file upload. */
function upload()
{
// Clear the progress bar
$('#progress .bar').html('0%');
$('#progress .bar').width('0%');
// Submit the upload form
$('#upload_form').submit();
// Start polling for progress after delay
setTimeout("checkProgress()", 1500);
}
function checkProgress()
{
$.get('progress.php', function(data)
{
var percentage = data + '%';
// Update the progress bar
$('#progress .bar').html(percentage);
$('#progress .bar').width(percentage);
// If not finished, query again after a delay
if (data < 100) {
setTimeout("checkProgress()", 500);
}
});
}
|
'use strict';
var ImportCache = require("../src/import_cache");
describe("ImportCache", function() {
var cache;
beforeEach(function () { cache = new ImportCache(); });
describe(".moveTo", function () {
it("absolute path to a file", function () {
cache.moveTo(__filename);
expect(cache.getCurrent()).toEqual(__dirname);
});
it("fails if import has never been requested", function () {
var attempt = function() { cache.moveTo("ootstrap/ixins"); }
expect(attempt).toThrow();
});
it("previously requested import", function () {
cache.add({ requested: "ourbon/eat",
resolved: "/path/to/ourbon/eat.scss" });
cache.moveTo("ourbon/eat");
expect(cache.getCurrent()).toEqual("/path/to/ourbon");
});
});
});
|
Polymer({
is: 'menu-map-options',
behaviors : [EventBusBehavior],
ebBind : {
'set-map-mode' : 'onModeUpdated'
},
onModeUpdated : function(mode) {
this.mode = mode;
if( this.mode === 'set' ) {
this.$.mode.checked = true;
} else {
this.$.mode.checked = false;
}
},
updateMode : function() {
this.mode = this.$.mode.checked ? 'set' : 'select';
this.getEventBus().emit('set-map-mode', this.mode);
},
setInfo : function(lat, lng, radius) {
this.$.info.style.display = 'block';
this.$.ll.innerHTML = lat.toFixed(4)+', '+lng.toFixed(4);
this.$.radius.innerHTML = radius/1000+'km';
}
}); |
// @flow
export const PUSH: string = 'admin.modal/PUSH'
export const POP: string = 'admin.modal/POP'
export const CLOSE: string = 'admin.modal/CLOSE'
|
import { createSelector } from 'reselect'
export const getActiveTeam = createSelector(
state => state,
state => {
return state.admin.active !== null ? state.admin.teams[state.admin.active] : null
}
)
export const getActiveSession = createSelector(
[state => state, getActiveTeam],
(state, team) => {
return team !== null && state.admin.sessions[team.id] !== undefined ? state.admin.sessions[team.id] : null
}
)
export const getActiveUser = createSelector(
[state => state, getActiveSession],
(state, session) => {
return session !== null ? session.user : null
}
)
export const getApps = createSelector(
[state => state, getActiveSession],
(state, session) => {
return session !== null ? session.apps : null
}
)
|
define([
'text!./templates/list.html'
], function (template) {
"use strict";
function elasticQuery(search) {
var filter = {match_all: {}}, query = {match_all: {}};
if (search.rootOnly) {
// why not inheritsFromId? While inheritsFromId is guaranteed, we could have
// original characters per story that do not inherit from a parent character
filter = {missing: {field: "contextId"}};
}
var any = [];
if (search.character) {
any.push({match: {name: search.character}});
}
if (search.universe) {
any.push({match: {"universe.name": search.universe}});
}
if (any.length) {
query = {bool: {must: any}};
}
return {
filtered: {
query: query,
filter: filter
}
};
}
return {
id: "_.characters",
url: "characters",
resolve: {
search: function () {
return {character: "", universe: "", rootOnly: true};
}
},
// we're not actually nesting views (despite the nested state), so just hijack the root view
views: {
'@': {
template: template,
controller: ['$scope', 'search', 'dal', function ($scope, search, dal) {
$scope.search = search;
$scope.autocomplete = dal.autocomplete;
$scope.results = dal.emptyList();
$scope.doSearch = function () {
return dal.getSearchResults('character', elasticQuery(search))
.then(function (newResults) {
$scope.results = newResults;
});
};
$scope.doSearch();
}]
}
},
data: {
displayName: 'Characters'
}
};
});
|
(function() {
'use strict';
angular.module('cms.media', [
'ngResource',
'cms.core'
])
.factory('MediaServer', ['MediaApi', function(MediaApi) {
var MediaServer = function(ctrl) {
this.ctrl = ctrl;
};
MediaServer.prototype.create = function(projectId, media) {
var promise, callback, failurecallback;
promise = ceateMedia(projectId, media).$promise;
callback = ceateMediaCallback(this.ctrl);
failurecallback = ceateMediaFailureCallback(this.ctrl);
promise.then(callback, failurecallback);
};
function ceateMedia (projectId, media) {
return MediaApi.create({projectId: projectId},media);
}
function ceateMediaCallback(ctrl) {
return function (response) {
ctrl.onMediaCreated(response);
};
};
function ceateMediaFailureCallback(ctrl) {
return function (response) {
ctrl.onMediaCreationFailed();
};
};
MediaServer.prototype.getAll = function(projectId) {
var promise, callback, failurecallback;
promise = getMedia(projectId).$promise;
callback = getMediaCallback(this.ctrl);
failurecallback = getMediaFailureCallback(this.ctrl);
promise.then(callback, failurecallback);
};
function getMedia (projectId) {
return MediaApi.get({projectId: projectId});
}
function getMediaCallback(ctrl) {
return function (response) {
ctrl.onMediaFetched(response);
};
};
function getMediaFailureCallback(ctrl) {
return function (response) {
ctrl.onMediaFetchError();
};
};
return MediaServer;
}])
.factory('MediaApi', [
'$resource', 'urls', 'getHeaders',
function ($resource, urls, getHeaders) {
return $resource(
[urls.baseApiUrl, 'project/:projectId/media/'].join(''),
{ projectId: "@projectId" },
{
create: {
method: 'POST',
headers: getHeaders()
},
get: {
method: 'GET',
headers: getHeaders(),
isArray: true,
}
},
{stripTrailingSlashes: false}
);
}
]);
})(); |
use homework
db.grades.aggregate( [
{ $unwind: '$scores' },
{ $match: { "scores.type": { $ne: "quiz" } } },
{ $group: { _id: { student_id: '$student_id', class_id: '$class_id' }, student_avg: { $avg: '$scores.score' } } },
{ $group: { _id: '$_id.class_id', class_avg: { $avg: '$student_avg' } } },
{ $sort: { class_avg: -1 } },
{ $limit: 1 }
] ) |
'use strict';
const test = require('tape');
const sinon = require('sinon');
const schedule = require('..');
// 12:30:15 pm Thursday 29 April 2010 in the timezone this code is being run in
const base = new Date(2010, 3, 29, 12, 30, 15, 0);
test("Recurrence rule", function (t) {
let clock
t.test("Setup", function (t) {
clock = sinon.useFakeTimers();
t.end()
})
t.test("#nextInvocationDate(Date)", function (t) {
t.test("next second", function(test) {
const rule = new schedule.RecurrenceRule();
rule.second = null;
const next = rule.nextInvocationDate(base);
test.deepEqual(new Date(2010, 3, 29, 12, 30, 16, 0), next);
test.end();
})
t.test("next 25th second", function(test) {
const rule = new schedule.RecurrenceRule();
rule.second = 25;
const next = rule.nextInvocationDate(base);
test.deepEqual(new Date(2010, 3, 29, 12, 30, 25, 0), next);
test.end();
})
t.test("next 5th second (minutes incremented)", function(test) {
const rule = new schedule.RecurrenceRule();
rule.second = 5;
const next = rule.nextInvocationDate(base);
test.deepEqual(new Date(2010, 3, 29, 12, 31, 5, 0), next);
test.end();
})
t.test("next 40th minute", function(test) {
const rule = new schedule.RecurrenceRule();
rule.minute = 40;
const next = rule.nextInvocationDate(base);
test.deepEqual(new Date(2010, 3, 29, 12, 40, 0, 0), next);
test.end();
})
t.test("next 1st minute (hours incremented)", function(test) {
const rule = new schedule.RecurrenceRule();
rule.minute = 1;
const next = rule.nextInvocationDate(base);
test.deepEqual(new Date(2010, 3, 29, 13, 1, 0, 0), next);
test.end();
})
t.test("next 23rd hour", function(test) {
const rule = new schedule.RecurrenceRule();
rule.hour = 23;
const next = rule.nextInvocationDate(base);
test.deepEqual(new Date(2010, 3, 29, 23, 0, 0, 0), next);
test.end();
})
t.test("next 3rd hour (days incremented)", function(test) {
const rule = new schedule.RecurrenceRule();
rule.hour = 3;
const next = rule.nextInvocationDate(base);
test.deepEqual(new Date(2010, 3, 30, 3, 0, 0, 0), next);
test.end();
})
t.test("next Friday", function(test) {
const rule = new schedule.RecurrenceRule();
rule.dayOfWeek = 5;
const next = rule.nextInvocationDate(base);
test.deepEqual(new Date(2010, 3, 30, 0, 0, 0, 0), next);
test.end();
})
t.test("next Monday (months incremented)", function(test) {
const rule = new schedule.RecurrenceRule();
rule.dayOfWeek = 1;
const next = rule.nextInvocationDate(base);
test.deepEqual(new Date(2010, 4, 3, 0, 0, 0, 0), next);
test.end();
})
t.test("next 30th date", function(test) {
const rule = new schedule.RecurrenceRule();
rule.date = 30;
const next = rule.nextInvocationDate(base);
test.deepEqual(new Date(2010, 3, 30, 0, 0, 0, 0), next);
test.end();
})
t.test("next 5th date (months incremented)", function(test) {
const rule = new schedule.RecurrenceRule();
rule.date = 5;
const next = rule.nextInvocationDate(base);
test.deepEqual(new Date(2010, 4, 5, 0, 0, 0, 0), next);
test.end();
})
t.test("next October", function(test) {
const rule = new schedule.RecurrenceRule();
rule.month = 9;
const next = rule.nextInvocationDate(base);
test.deepEqual(new Date(2010, 9, 1, 0, 0, 0, 0), next);
test.end();
})
t.test("next February (years incremented)", function(test) {
const rule = new schedule.RecurrenceRule();
rule.month = 1;
const next = rule.nextInvocationDate(base);
test.deepEqual(new Date(2011, 1, 1, 0, 0, 0, 0), next);
test.end();
})
t.test("in the year 2040", function(test) {
const rule = new schedule.RecurrenceRule();
rule.year = 2040;
const next = rule.nextInvocationDate(base);
test.deepEqual(new Date(2040, 0, 1, 0, 0, 0, 0), next);
test.end();
})
t.test("using past year", function(test) {
const rule = new schedule.RecurrenceRule();
rule.year = 2000;
const next = rule.nextInvocationDate(base);
test.equal(null, next);
test.end();
})
t.test("using mixed time components", function(test) {
const rule = new schedule.RecurrenceRule();
rule.second = 50;
rule.minute = 5;
rule.hour = 10;
const next = rule.nextInvocationDate(base);
test.deepEqual(new Date(2010, 3, 30, 10, 5, 50, 0), next);
test.end();
})
/*
"using date and dayOfWeek together", function(test) {
const rule = new schedule.RecurrenceRule();
rule.dayOfWeek = 4; // This is Thursday April 1st
rule.date = 10; // This is Saturday April 10th
const next = rule.nextInvocationDate(base);
test.deepEqual(new Date(2010, 3, 1, 0, 0, 0, 0), next);
test.end();
}*/
t.test("returns null when no invocations left", function(test) {
const rule = new schedule.RecurrenceRule();
rule.year = 2000;
const next = rule.nextInvocationDate(base);
test.strictEqual(null, next);
test.end();
})
t.test("specify span of components using Range", function(test) {
const rule = new schedule.RecurrenceRule();
rule.minute = new schedule.Range(4, 6);
let next;
next = rule.nextInvocationDate(base);
test.deepEqual(new Date(2010, 3, 29, 13, 4, 0, 0), next);
next = rule.nextInvocationDate(next);
test.deepEqual(new Date(2010, 3, 29, 13, 5, 0, 0), next);
next = rule.nextInvocationDate(next);
test.deepEqual(new Date(2010, 3, 29, 13, 6, 0, 0), next);
next = rule.nextInvocationDate(next);
test.deepEqual(new Date(2010, 3, 29, 14, 4, 0, 0), next);
test.end();
})
t.test("specify intervals within span of components using Range with step", function(test) {
const rule = new schedule.RecurrenceRule();
rule.minute = new schedule.Range(4, 8, 2);
let next;
next = rule.nextInvocationDate(base);
test.deepEqual(new Date(2010, 3, 29, 13, 4, 0, 0), next);
next = rule.nextInvocationDate(next);
test.deepEqual(new Date(2010, 3, 29, 13, 6, 0, 0), next);
/* Should Range stay inclusive on both ends when step > 1
next = rule.nextInvocationDate(next);
test.deepEqual(new Date(2010, 3, 29, 13, 8, 0, 0), next);
*/
next = rule.nextInvocationDate(next);
test.deepEqual(new Date(2010, 3, 29, 14, 4, 0, 0), next);
test.end();
})
t.test("specify span and explicit components using Array of Ranges and Numbers", function(test) {
const rule = new schedule.RecurrenceRule();
rule.minute = [2, new schedule.Range(4, 6)];
let next;
next = rule.nextInvocationDate(base);
test.deepEqual(new Date(2010, 3, 29, 13, 2, 0, 0), next);
next = rule.nextInvocationDate(next);
test.deepEqual(new Date(2010, 3, 29, 13, 4, 0, 0), next);
next = rule.nextInvocationDate(next);
test.deepEqual(new Date(2010, 3, 29, 13, 5, 0, 0), next);
next = rule.nextInvocationDate(next);
test.deepEqual(new Date(2010, 3, 29, 13, 6, 0, 0), next);
next = rule.nextInvocationDate(next);
test.deepEqual(new Date(2010, 3, 29, 14, 2, 0, 0), next);
test.end();
})
t.test("From 31th May schedule the 1st of every June", function(test) {
const rule = new schedule.RecurrenceRule();
rule.second = 0;
rule.minute = 0;
rule.hour = 0;
rule.date = 1;
rule.month = 5;
let next;
const base1 = new Date(2010, 4, 31, 12, 30, 15, 0);
next = rule.nextInvocationDate(base1);
test.deepEqual(new Date(2010, 5, 1, 0, 0, 0, 0), next);
next = rule.nextInvocationDate(next);
test.deepEqual(new Date(2011, 5, 1, 0, 0, 0, 0), next);
test.end();
})
t.test("With the year set should not loop indefinetely", function(test) {
const rule = new schedule.RecurrenceRule();
rule.second = 0;
rule.minute = 0;
rule.hour = 0;
rule.date = 1;
rule.month = 5;
rule.year = 2010;
let next;
const base1 = new Date(2010, 4, 31, 12, 30, 15, 0);
next = rule.nextInvocationDate(base1);
test.deepEqual(new Date(2010, 5, 1, 0, 0, 0, 0), next);
next = rule.nextInvocationDate(next);
test.equal(next, null);
test.end();
})
t.test("using rule with string properties", function(test) {
const rule = new schedule.RecurrenceRule();
rule.second = '50';
rule.minute = '5';
rule.hour = '10';
const next = rule.nextInvocationDate(base);
test.deepEqual(new Date(2010, 3, 30, 10, 5, 50, 0), next);
test.end();
})
t.test("nextInvocationDate on an invalid month should return null", function(test) {
const rule = new schedule.RecurrenceRule();
rule.month = 12;
const next = rule.nextInvocationDate();
test.equal(next, null);
const rule2 = new schedule.RecurrenceRule();
rule2.month = 'asdfasdf';
const next2 = rule2.nextInvocationDate(next);
test.equal(next2, null);
test.end();
})
t.test("nextInvocationDate on an invalid second should return null", function(test) {
const rule = new schedule.RecurrenceRule();
rule.second = 60;
const next = rule.nextInvocationDate();
test.equal(next, null);
const rule2 = new schedule.RecurrenceRule();
rule2.second = 'asdfasdf';
const next2 = rule2.nextInvocationDate();
test.equal(next2, null);
test.end();
})
t.test("nextInvocationDate on an invalid hour should return null", function(test) {
const rule = new schedule.RecurrenceRule();
rule.hour = 24;
const next = rule.nextInvocationDate();
test.equal(next, null);
const rule2 = new schedule.RecurrenceRule();
rule2.hour = 'asdfasdf';
const next2 = rule2.nextInvocationDate();
test.equal(next2, null);
test.end();
})
t.test("nextInvocationDate on an invalid date should return null", function(test) {
const rule = new schedule.RecurrenceRule();
rule.date = 90;
const next = rule.nextInvocationDate();
test.equal(next, null);
// Test February
const rule2 = new schedule.RecurrenceRule();
rule2.month = 1;
rule2.date = 30;
const next2 = rule2.nextInvocationDate();
test.equal(next2, null);
const rule3 = new schedule.RecurrenceRule();
rule3.date = 'asdfasdf';
const next3 = rule3.nextInvocationDate();
test.equal(next3, null);
test.end();
})
t.test("nextInvocationDate on an invalid dayOfWeek should return null", function(test) {
const rule = new schedule.RecurrenceRule();
rule.dayOfWeek = 90;
const next = rule.nextInvocationDate();
test.equal(next, null);
const rule2 = new schedule.RecurrenceRule();
rule2.dayOfWeek = 'asdfasdf';
const next2 = rule.nextInvocationDate();
test.equal(next2, null);
test.end();
})
})
t.test("Restore", function (t) {
clock.restore();
t.end()
})
})
|
module.exports = function() {
var that = this,
spawn = require('child_process');
this.task('init', function(logger) {
return that.exec(['php', 'composer', 'install'], logger).then(function() {
var bower = spawn('bower', ['install']);
console.log(bower);
});
});
this.task('serve', function(logger) {
if (!this.argv.t) {
this.argv.t = './www';
}
return that.exec(['php', 'serve'], logger);
});
};
|
<<<<<<< HEAD
<<<<<<< HEAD
var glob = require('../')
var test = require('tap').test
var path = require('path')
test('stat all the things', function(t) {
var g = new glob.Glob('a/*abc*/**', { stat: true, cwd: __dirname })
var matches = []
g.on('match', function(m) {
matches.push(m)
})
var stats = []
g.on('stat', function(m) {
stats.push(m)
})
g.on('end', function(eof) {
stats = stats.sort()
matches = matches.sort()
eof = eof.sort()
t.same(stats, matches)
t.same(eof, matches)
var cache = Object.keys(this.statCache)
t.same(cache.map(function (f) {
return path.relative(__dirname, f).replace(/\\/g, '/')
}).sort(), matches)
cache.forEach(function(c) {
t.equal(typeof this.statCache[c], 'object')
}, this)
t.end()
})
})
=======
var glob = require('../')
var test = require('tap').test
var path = require('path')
test('stat all the things', function(t) {
var g = new glob.Glob('a/*abc*/**', { stat: true, cwd: __dirname })
var matches = []
g.on('match', function(m) {
matches.push(m)
})
var stats = []
g.on('stat', function(m) {
stats.push(m)
})
g.on('end', function(eof) {
stats = stats.sort()
matches = matches.sort()
eof = eof.sort()
t.same(stats, matches)
t.same(eof, matches)
var cache = Object.keys(this.statCache)
t.same(cache.map(function (f) {
return path.relative(__dirname, f).replace(/\\/g, '/')
}).sort(), matches)
cache.forEach(function(c) {
t.equal(typeof this.statCache[c], 'object')
}, this)
t.end()
})
})
>>>>>>> b875702c9c06ab5012e52ff4337439b03918f453
=======
var glob = require('../')
var test = require('tap').test
var path = require('path')
test('stat all the things', function(t) {
var g = new glob.Glob('a/*abc*/**', { stat: true, cwd: __dirname })
var matches = []
g.on('match', function(m) {
matches.push(m)
})
var stats = []
g.on('stat', function(m) {
stats.push(m)
})
g.on('end', function(eof) {
stats = stats.sort()
matches = matches.sort()
eof = eof.sort()
t.same(stats, matches)
t.same(eof, matches)
var cache = Object.keys(this.statCache)
t.same(cache.map(function (f) {
return path.relative(__dirname, f).replace(/\\/g, '/')
}).sort(), matches)
cache.forEach(function(c) {
t.equal(typeof this.statCache[c], 'object')
}, this)
t.end()
})
})
>>>>>>> b875702c9c06ab5012e52ff4337439b03918f453
|
'use strict';
var path = require('path'),
utils = require('../utils');
module.exports = exec;
module.exports.parseExecutable = parseExecutable;
function parseExecutable(str) {
var length = str.length;
var i = 0;
var exec = null;
var execArgs = [];
var token = '';
var inspace = false;
var escaped = false;
var unescapeNextTime = false;
var open = false;
var c = null;
var isescape = false;
for (; i < length; i++) {
c = str[i];
if (unescapeNextTime) {
escaped = false;
}
unescapeNextTime = escaped;
if (c === '\\' && !utils.isWindows) {
isescape = true;
} else if (c === '^' && utils.isWindows) {
isescape = true;
} else {
isescape = false;
}
if (isescape) {
escaped = true;
// peek next character
if (str[i+1] === ' ') { // space we skip
inspace = true;
}
if (utils.isWindows) {
continue; // chomp the carat
}
}
if (!escaped && (c === '"' || c === "'")) {
open = !open;
// continue;
}
if (c === ' ') {
if (!open && inspace === false) {
if (exec === null) {
exec = token;
execArgs.push(str.slice(i + 1));
token = '';
break;
} else {
execArgs.push(token);
}
// reset the token now
token = '';
continue;
} else if (inspace) {
inspace = false;
}
}
token += c;
}
// deal with the left overs
if (exec === null) {
exec = token;
} else if (token) {
execArgs.push(token);
}
var result = {
exec: exec,
execArgs: execArgs,
};
return result;
}
/**
* Reads the cwd/package.json file and looks to see if it can load a script
* and possibly an exec first from package.main, then package.start.
*
* @return {Object} exec & script if found
*/
function execFromPackage() {
// doing a try/catch because we can't use the path.exist callback pattern
// or we could, but the code would get messy, so this will do exactly
// what we're after - if the file doesn't exist, it'll throw.
try {
// note: this isn't nodemon's package, it's the user's cwd package
var pkg = require(path.join(process.cwd(), 'package.json'));
if (pkg.main !== undefined) {
// no app found to run - so give them a tip and get the feck out
return { exec: null, script: pkg.main };
} else if (pkg.scripts && pkg.scripts.start) {
var start = pkg.scripts.start.split(' ');
return { exec: start[0], script: start.slice(1).join(' ') };
}
} catch (e) {}
return null;
}
function replace(map, str) {
return str.replace(new RegExp('\{\{(' + Object.keys(map).join('|') + ')\}\}'), function (all, m) {
return map[m] || all || '';
});
}
/**
* Discovers all the options required to run the script
* and if a custom exec has been passed in, then it will
* also try to work out what extensions to monitor and
* whether there's a special way of running that script.
*
* @param {Object} nodemonOptions
* @param {Object} execMap
* @return {Object} new and updated version of nodemonOptions
*/
function exec(nodemonOptions, execMap) {
if (!execMap) {
execMap = {};
}
// if there's no exec found yet, then try to read it from the local package.json
// this logic used to sit in the cli/parse, but actually the cli should be parsed
// first, then the user options (via nodemon.json) then finally default down to
// pot shots at the directory via package.json
if (!nodemonOptions.exec && !nodemonOptions.script) {
var found = execFromPackage();
if (found !== null) {
if (found.exec) {
nodemonOptions.exec = found.exec;
}
if (!nodemonOptions.script) {
nodemonOptions.script = found.script;
}
if (Array.isArray(nodemonOptions.args) && nodemonOptions.scriptPosition === null) {
nodemonOptions.scriptPosition = nodemonOptions.args.length;
}
}
}
var options = utils.clone(nodemonOptions || {}),
script = path.basename(options.script || ''),
scriptExt = path.extname(script).slice(1),
extension = options.ext || scriptExt || 'js',
execDefined = !!options.exec;
// strip any leading periods int he extension
if (extension.indexOf('.') === 0) {
extension = extension.slice(1);
}
// allows the user to simplify cli usage: https://github.com/remy/nodemon/issues/195
// but always give preference to the user defined argument
if (!options.exec && execMap[scriptExt] !== undefined) {
options.exec = execMap[scriptExt];
execDefined = true;
}
options.execArgs = [];
if (Array.isArray(options.exec)) {
options.execArgs = options.exec;
options.exec = options.execArgs.shift();
} else if (options.exec && options.exec.indexOf(' ') !== -1) {
options = utils.merge(parseExecutable(options.exec), options);
}
if (options.exec === undefined) {
options.exec = 'node';
} else {
// allow variable substitution for {{filename}} and {{pwd}}
var substitution = replace.bind(null, { filename: script, pwd: process.cwd() });
options.exec = substitution(options.exec);
var newExecArgs = options.execArgs.map(substitution);
if (newExecArgs.join('') !== options.execArgs.join('')) {
options.execArgs = newExecArgs;
delete options.script;
}
}
if (options.exec === 'node' && options.nodeArgs && options.nodeArgs.length) {
options.execArgs = options.execArgs.concat(options.nodeArgs);
}
// note: indexOf('coffee') handles both .coffee and .litcoffee
if (!execDefined && options.exec === 'node' && scriptExt.indexOf('coffee') !== -1) {
options.exec = 'coffee';
// ensure that we call: `coffee --nodejs ...`
if (options.execArgs === undefined) {
options.execArgs = [];
}
// if there's a leading argument to the exec that starts with `--` then
// it could be --debug or --debug-brk or something else intended for node
// so we'll add the --nodejs switch.
if ((options.args || []).join(' ').indexOf('--') === 0) {
options.execArgs.unshift('--nodejs');
}
}
if (options.exec === 'coffee') {
// don't override user specified extension tracking
if (!options.ext) {
extension = 'coffee litcoffee js';
}
// because windows can't find 'coffee', it needs the real file 'coffee.cmd'
if (utils.isWindows) {
options.exec += '.cmd';
}
}
// allow users to make a mistake on the extension to monitor
// converts js,jade => js,jade
// and 'js jade' => js,jade
// BIG NOTE: user can't do this: nodemon -e *.js
// because the terminal will automatically expand the glob against
// the file system :(
if (extension.indexOf(' ') !== -1 ||
extension.indexOf(',') !== -1 ||
extension.indexOf('*.') !== -1) {
extension = extension.replace(/\s+/g, '|') // convert spaces to pipes
.replace(/,/g, '|') // convert commas to pipes
.split('|') // split on those pipes
.map(function (item) {
return item.replace(/^[\*\.]+/, ''); // remove "*."
}).join(','); // return regexp string like: js,jade
}
options.ext = extension;
options.env = {};
// make sure it's an object (and since we don't have )
if (({}).toString.apply(nodemonOptions.env) === '[object Object]') {
options.env = utils.clone(nodemonOptions.env);
} else if (nodemonOptions.env !== undefined) {
throw new Error('nodemon env values must be an object: { PORT: 8000 }');
}
return options;
} |
(function(b){b.widget("ui.tagit",{options:{allowDuplicates:!1,caseSensitive:!0,fieldName:"tags",placeholderText:null,readOnly:!1,removeConfirmation:!1,tagLimit:null,availableTags:[],autocomplete:{},showAutocompleteOnFocus:!1,allowSpaces:!1,singleField:!1,singleFieldDelimiter:",",singleFieldNode:null,animate:!0,tabIndex:null,beforeTagAdded:null,afterTagAdded:null,beforeTagRemoved:null,afterTagRemoved:null,onTagClicked:null,onTagLimitExceeded:null,onTagAdded:null,onTagRemoved:null,tagSource:null},_create:function(){var a=
this;this.element.is("input")?(this.tagList=b("<ul></ul>").insertAfter(this.element),this.options.singleField=!0,this.options.singleFieldNode=this.element,this.element.addClass("tagit-hidden-field")):this.tagList=this.element.find("ul, ol").andSelf().last();this.tagInput=b('<input type="text" />').addClass("ui-widget-content");this.options.readOnly&&this.tagInput.attr("disabled","disabled");this.options.tabIndex&&this.tagInput.attr("tabindex",this.options.tabIndex);this.options.placeholderText&&this.tagInput.attr("placeholder",
this.options.placeholderText);this.options.autocomplete.source||(this.options.autocomplete.source=function(a,e){var d=a.term.toLowerCase(),c=b.grep(this.options.availableTags,function(a){return 0===a.toLowerCase().indexOf(d)});this.options.allowDuplicates||(c=this._subtractArray(c,this.assignedTags()));e(c)});this.options.showAutocompleteOnFocus&&(this.tagInput.focus(function(b,d){a._showAutocomplete()}),"undefined"===typeof this.options.autocomplete.minLength&&(this.options.autocomplete.minLength=
0));b.isFunction(this.options.autocomplete.source)&&(this.options.autocomplete.source=b.proxy(this.options.autocomplete.source,this));b.isFunction(this.options.tagSource)&&(this.options.tagSource=b.proxy(this.options.tagSource,this));this.tagList.addClass("tagit").addClass("ui-widget ui-widget-content ui-corner-all").append(b('<li class="tagit-new"></li>').append(this.tagInput)).click(function(d){var c=b(d.target);c.hasClass("tagit-label")?(c=c.closest(".tagit-choice"),c.hasClass("removed")||a._trigger("onTagClicked",
d,{tag:c,tagLabel:a.tagLabel(c)})):a.tagInput.focus()});var c=!1;if(this.options.singleField)if(this.options.singleFieldNode){var d=b(this.options.singleFieldNode),f=d.val().split(this.options.singleFieldDelimiter);d.val("");b.each(f,function(b,d){a.createTag(d,null,!0);c=!0})}else this.options.singleFieldNode=b('<input type="hidden" style="display:none;" value="" name="'+this.options.fieldName+'" />'),this.tagList.after(this.options.singleFieldNode);c||this.tagList.children("li").each(function(){b(this).hasClass("tagit-new")||
(a.createTag(b(this).text(),b(this).attr("class"),!0),b(this).remove())});this.tagInput.keydown(function(c){if(c.which==b.ui.keyCode.BACKSPACE&&""===a.tagInput.val()){var d=a._lastTag();!a.options.removeConfirmation||d.hasClass("remove")?a.removeTag(d):a.options.removeConfirmation&&d.addClass("remove ui-state-highlight")}else a.options.removeConfirmation&&a._lastTag().removeClass("remove ui-state-highlight");if(c.which===b.ui.keyCode.COMMA&&!1===c.shiftKey||c.which===b.ui.keyCode.ENTER||c.which==
b.ui.keyCode.TAB&&""!==a.tagInput.val()||c.which==b.ui.keyCode.SPACE&&!0!==a.options.allowSpaces&&('"'!=b.trim(a.tagInput.val()).replace(/^s*/,"").charAt(0)||'"'==b.trim(a.tagInput.val()).charAt(0)&&'"'==b.trim(a.tagInput.val()).charAt(b.trim(a.tagInput.val()).length-1)&&0!==b.trim(a.tagInput.val()).length-1))c.which===b.ui.keyCode.ENTER&&""===a.tagInput.val()||c.preventDefault(),a.options.autocomplete.autoFocus&&a.tagInput.data("autocomplete-open")||(a.tagInput.autocomplete("close"),a.createTag(a._cleanedInput()))}).blur(function(b){a.tagInput.data("autocomplete-open")||
a.createTag(a._cleanedInput())});if(this.options.availableTags||this.options.tagSource||this.options.autocomplete.source)d={select:function(b,c){a.createTag(c.item.value);return!1}},b.extend(d,this.options.autocomplete),d.source=this.options.tagSource||d.source,this.tagInput.autocomplete(d).bind("autocompleteopen.tagit",function(b,c){a.tagInput.data("autocomplete-open",!0)}).bind("autocompleteclose.tagit",function(b,c){a.tagInput.data("autocomplete-open",!1)}),this.tagInput.autocomplete("widget").addClass("tagit-autocomplete")},
destroy:function(){b.Widget.prototype.destroy.call(this);this.element.unbind(".tagit");this.tagList.unbind(".tagit");this.tagInput.removeData("autocomplete-open");this.tagList.removeClass("tagit ui-widget ui-widget-content ui-corner-all tagit-hidden-field");this.element.is("input")?(this.element.removeClass("tagit-hidden-field"),this.tagList.remove()):(this.element.children("li").each(function(){b(this).hasClass("tagit-new")?b(this).remove():(b(this).removeClass("tagit-choice ui-widget-content ui-state-default ui-state-highlight ui-corner-all remove tagit-choice-editable tagit-choice-read-only"),
b(this).text(b(this).children(".tagit-label").text()))}),this.singleFieldNode&&this.singleFieldNode.remove());return this},_cleanedInput:function(){return b.trim(this.tagInput.val().replace(/^"(.*)"$/,"$1"))},_lastTag:function(){return this.tagList.find(".tagit-choice:last:not(.removed)")},_tags:function(){return this.tagList.find(".tagit-choice:not(.removed)")},assignedTags:function(){var a=this,c=[];this.options.singleField?(c=b(this.options.singleFieldNode).val().split(this.options.singleFieldDelimiter),
""===c[0]&&(c=[])):this._tags().each(function(){c.push(a.tagLabel(this))});return c},_updateSingleTagsField:function(a){b(this.options.singleFieldNode).val(a.join(this.options.singleFieldDelimiter)).trigger("change")},_subtractArray:function(a,c){for(var d=[],f=0;f<a.length;f++)-1==b.inArray(a[f],c)&&d.push(a[f]);return d},tagLabel:function(a){return this.options.singleField?b(a).find(".tagit-label:first").text():b(a).find("input:first").val()},_showAutocomplete:function(){this.tagInput.autocomplete("search",
"")},_findTagByLabel:function(a){var c=this,d=null;this._tags().each(function(f){if(c._formatStr(a)==c._formatStr(c.tagLabel(this)))return d=b(this),!1});return d},_isNew:function(a){return!this._findTagByLabel(a)},_formatStr:function(a){return this.options.caseSensitive?a:b.trim(a.toLowerCase())},_effectExists:function(a){return Boolean(b.effects&&(b.effects[a]||b.effects.effect&&b.effects.effect[a]))},createTag:function(a,c,d){var f=this;a=b.trim(a);this.options.preprocessTag&&(a=this.options.preprocessTag(a));
if(""===a)return!1;if(!this.options.allowDuplicates&&!this._isNew(a))return a=this._findTagByLabel(a),!1!==this._trigger("onTagExists",null,{existingTag:a,duringInitialization:d})&&this._effectExists("highlight")&&a.effect("highlight"),!1;if(this.options.tagLimit&&this._tags().length>=this.options.tagLimit)return this._trigger("onTagLimitExceeded",null,{duringInitialization:d}),!1;var g=b(this.options.onTagClicked?'<a class="tagit-label"></a>':'<span class="tagit-label"></span>').text(a),e=b("<li></li>").addClass("tagit-choice ui-widget-content ui-state-default ui-corner-all").addClass(c).append(g);
this.options.readOnly?e.addClass("tagit-choice-read-only"):(e.addClass("tagit-choice-editable"),c=b("<span></span>").addClass("ui-icon ui-icon-close"),c=b('<a><span class="text-icon">\u00d7</span></a>').addClass("tagit-close").append(c).click(function(a){f.removeTag(e)}),e.append(c));this.options.singleField||(g=g.html(),e.append('<input type="hidden" value="'+g+'" name="'+this.options.fieldName+'" class="tagit-hidden-field" />'));!1!==this._trigger("beforeTagAdded",null,{tag:e,tagLabel:this.tagLabel(e),
duringInitialization:d})&&(this.options.singleField&&(g=this.assignedTags(),g.push(a),this._updateSingleTagsField(g)),this._trigger("onTagAdded",null,e),this.tagInput.val(""),this.tagInput.parent().before(e),this._trigger("afterTagAdded",null,{tag:e,tagLabel:this.tagLabel(e),duringInitialization:d}),this.options.showAutocompleteOnFocus&&!d&&setTimeout(function(){f._showAutocomplete()},0))},removeTag:function(a,c){c="undefined"===typeof c?this.options.animate:c;a=b(a);this._trigger("onTagRemoved",
null,a);if(!1!==this._trigger("beforeTagRemoved",null,{tag:a,tagLabel:this.tagLabel(a)})){if(this.options.singleField){var d=this.assignedTags(),f=this.tagLabel(a),d=b.grep(d,function(a){return a!=f});this._updateSingleTagsField(d)}if(c){a.addClass("removed");var d=this._effectExists("blind")?["blind",{direction:"horizontal"},"fast"]:["fast"],g=this;d.push(function(){a.remove();g._trigger("afterTagRemoved",null,{tag:a,tagLabel:g.tagLabel(a)})});a.fadeOut("fast").hide.apply(a,d).dequeue()}else a.remove(),
this._trigger("afterTagRemoved",null,{tag:a,tagLabel:this.tagLabel(a)})}},removeTagByLabel:function(a,b){var d=this._findTagByLabel(a);if(!d)throw"No such tag exists with the name '"+a+"'";this.removeTag(d,b)},removeAll:function(){var a=this;this._tags().each(function(b,d){a.removeTag(d,!1)})}})})(jQuery);
|
/**
* index.js - Main server file that we will use for our demo app
*/
'use strict'
// Clever addresses
const OAUTH_TOKEN_URL = 'https://clever.com/oauth/tokens';
const API_PREFIX = 'https://api.clever.com';
const DISTRICT_ID = '56df50fa892c7001000000c5';
// Load dependencies
let express = require('express');
let exphbs = require('express-handlebars');
let session = require('express-session');
let bodyParser = require('body-parser');
let morgan = require('morgan');
let request = require('request');
// Set up server
let app = express();
app.engine('handlebars', exphbs());
app.set('view engine', 'handlebars');
/**
* Server configuration
*/
let config = {
port: process.env.PORT || 3000,
env: process.env.NODE_ENV || 'development',
clever: {}
}
// Load URL, Clever ID and Secret for respective environment
if (config.env === 'development') {
config.url = 'http://localhost:3000'
let secrets = require('./secrets');
config.clever.id = secrets.id;
config.clever.secret = secrets.secret;
} else {
config.url = process.env.APP_URL;
config.clever.id = process.env.CLEVER_ID;
config.clever.secret = process.env.CLEVER_SECRET;
}
/**
* Middleware
*/
app.use(morgan('dev'));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
// Session middleware
app.use(session({
'secret': 'somesecret',
'saveUninitialized': true,
'resave': false
}));
// Middleware to serve static assets
app.use('/images', express.static(__dirname + '/../public/images'));
/**
* App Routes
*/
// Helper function for making requests
let makeRequest = function (options, callback) {
request(options, function(err, res, body) {
if (!err) {
let statusCode = res.statusCode;
if (statusCode !== 200) {
let error = body.error;
console.error('Received non-200 status code:', statusCode, error);
callback(error);
} else {
callback(null, body);
}
} else {
console.error('Error with request:', err);
callback(err);
}
});
};
// Homepage
app.get('/', function (req, res) {
// Render index and send redirect_uri, client_id, and district_id
res.render('index', {
'redirect_uri': encodeURIComponent(config.url + '/oauth'),
'client_id': config.clever.id,
'district_id': DISTRICT_ID
});
});
// OAuth 2.0 endpoint
app.get('/oauth', function (req, res) {
// OAuth 2.0 Step 2 - Received Authorization Code
console.log('Received response from Clever');
if(!req.query.code){
res.redirect('/');
} else {
console.log('Received an Authorization Code from Clever', req.query.code);
let body = {
code: req.query.code,
grant_type: 'authorization_code',
redirect_uri: config.url + '/oauth'
};
let options = {
url: OAUTH_TOKEN_URL,
method: 'post',
json: body,
headers: {
'Authorization': 'Basic ' + new Buffer(config.clever.id + ':' + config.clever.secret).toString('base64'),
'Content-Type': 'application/json'
}
}
// OAuth 2.0 Step 3 - Request Access Token
makeRequest(options, function(err, result) {
console.log('Made a request for an Access Token with the code', options.json.code);
// OAuth 2.0 Step 4 - Received Access Token
if (!err) {
let token = result.access_token;
options = {
url: API_PREFIX + '/me',
method: 'get',
json: true,
headers: {
Authorization: 'Bearer ' + token
}
}
// Make a request to Clever API with Access Token
makeRequest(options, function (err, result){
if (!err) {
console.log('Congratulations! The user is authorized!');
console.log('Retrieved user', result);
req.session.user = result.data;
console.log(req.session.user);
res.redirect('/app');
} else {
console.error('Error with Access Token:', err);
res.status(500).send(err);
}
});
} else {
console.error('Error with Authorization Code sent to Clever:', err);
res.status(500).send(err);
}
});
}
});
// App
app.get('/app', function (req, res) {
console.log('Redirected to app', req.session);
// Check if we received a user
if(!req.session.user) {
res.redirect('/');
} else {
// Render app and send user
res.render('app',{
'user': JSON.stringify(req.session.user)
})
}
});
// Logout
app.get('/logout', function (req, res) {
if (!req.session.user) {
res.redirect('/');
} else {
req.session.destroy();
res.redirect('/');
}
});
app.listen(config.port);
console.log('Listening on', config.url);
|
// Sample Testacular configuration file, that contain pretty much all the available options
// It's used for running client tests on Travis (http://travis-ci.org/#!/vojtajina/testacular)
// Most of the options can be overriden by cli arguments (see testacular --help)
// base path, that will be used to resolve files and exclude
basePath = '..';
// list of files / patterns to load in the browser
files = [
JASMINE,
JASMINE_ADAPTER,
'test/lib/jquery/jquery-1.7.2.js',
'test/lib/jquery/jquery-ui-1.8.18.js',
'test/lib/angular-1.0.1/angular.js',
'test/lib/angular-1.0.1/angular-mocks.js',
'test/lib/codemirror/codemirror.js',
'test/lib/tinymce/tiny_mce.js',
'test/lib/tinymce/jquery.tinymce.js',
'test/lib/googlemaps/googlemaps.js',
'test/lib/bootstrap/bootstrap-modal.js',
'test/lib/select2/select2.js',
'test/lib/maskedinput/jquery.maskedinput-1.3.js',
'test/lib/calendar/calendar.js.min',
'common/module.js',
'modules/*/*/*.js',
'modules/*/*/test/*.js',
'templates/*.js',
'templates/test/*.js'
];
// list of files to exclude
exclude = [];
// use dots reporter, as travis terminal does not support escaping sequences
// possible values: 'dots' || 'progress'
reporter = 'dots';
// these are default values, just to show available options
// web server port
port = 8080;
// cli runner port
runnerPort = 9100;
// 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_DEBUG;
// enable / disable watching file and executing tests whenever any file changes
autoWatch = false;
// polling interval in ms (ignored on OS that support inotify)
autoWatchInterval = 0;
// Start these browsers, currently available:
// - Chrome
// - ChromeCanary
// - Firefox
// - Opera
// - Safari
// - PhantomJS
browsers = [];
|
angular.module('orderCloud')
.directive('ocFavoriteProduct', OrderCloudFavoriteProductDirective)
;
function OrderCloudFavoriteProductDirective($exceptionHandler, toastr, OrderCloudSDK){
return {
scope: {
currentUser: '=',
product: '=',
favoriteClass: '@',
nonFavoriteClass: '@'
},
restrict: 'A',
link: function(scope, element, attrs) {
var hasFavorites = false;
checkHasFavorites();
(hasFavorites && scope.currentUser.xp.FavoriteProducts.indexOf(scope.product.ID) > -1)
? addFavoriteClass()
: removeFavoriteClass();
function checkHasFavorites(){
if(scope.currentUser && scope.currentUser.xp && scope.currentUser.xp.FavoriteProducts){
hasFavorites = true;
}
else{
if(scope.currentUser && scope.currentUser.xp){
scope.currentUser.xp.FavoriteProducts = [];
}else{
scope.currentUser.xp = {};
scope.currentUser.xp.FavoriteProducts = [];
}
return OrderCloudSDK.Me.Patch({xp: scope.currentUser.xp})
.then(function(){
hasFavorites = true;
})
.catch(function(ex){
$exceptionHandler(ex);
});
}
}
function addFavoriteClass() {
element.removeClass(scope.nonFavoriteClass)
element.addClass(scope.favoriteClass);
}
function removeFavoriteClass() {
element.removeClass(scope.favoriteClass);
element.addClass(scope.nonFavoriteClass);
}
element.bind('click', function() {
if (hasFavorites){
if (element.hasClass(scope.favoriteClass)){
removeProduct();
} else {
addProduct(scope.currentUser.xp.FavoriteProducts);
}
} else {
vm.addProduct([]);
}
});
function addProduct(existingList){
existingList.push(scope.product.ID);
return OrderCloudSDK.Me.Patch({xp: {FavoriteProducts: existingList}})
.then(function(data){
addFavoriteClass();
hasFavorites = data.xp && data.xp.FavoriteProducts;
toastr.success(scope.product.Name + ' was added to your favorite products.');
});
}
function removeProduct(){
var updatedList = _.without(scope.currentUser.xp.FavoriteProducts, scope.product.ID);
return OrderCloudSDK.Me.Patch({xp: {FavoriteProducts: updatedList}})
.then(function() {
removeFavoriteClass();
scope.currentUser.xp.FavoriteProducts = updatedList;
toastr.success(scope.product.Name + ' was removed from your favorite products.');
});
}
element.css('cursor', 'pointer');
}
};
} |
(function(f){"object"==typeof exports&&"object"==typeof module?f(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],f):f(CodeMirror)})(function(f){f.defineMode("go",function(t){function h(a,c){var b=a.next();if('"'==b||"'"==b||"`"==b)return c.tokenize=u(b),c.tokenize(a,c);if(/[\d\.]/.test(b))return"."==b?a.match(/^[0-9]+([eE][\-+]?[0-9]+)?/):"0"==b?a.match(/^[xX][0-9a-fA-F]+/)||a.match(/^0[0-7]+/):a.match(/^[0-9]*\.?[0-9]*([eE][\-+]?[0-9]+)?/),"number";
if(/[\[\]{}\(\),;:\.]/.test(b))return e=b,null;if("/"==b){if(a.eat("*"))return c.tokenize=l,l(a,c);if(a.eat("/"))return a.skipToEnd(),"comment"}if(m.test(b))return a.eatWhile(m),"operator";a.eatWhile(/[\w\$_\xa1-\uffff]/);a=a.current();if(v.propertyIsEnumerable(a)){if("case"==a||"default"==a)e="case";return"keyword"}return w.propertyIsEnumerable(a)?"atom":"variable"}function u(a){return function(c,b){for(var d=!1,g,n=!1;null!=(g=c.next());){if(g==a&&!d){n=!0;break}d=!d&&"`"!=a&&"\\"==g}if(n||!d&&
"`"!=a)b.tokenize=h;return"string"}}function l(a,c){for(var b=!1,d;d=a.next();){if("/"==d&&b){c.tokenize=h;break}b="*"==d}return"comment"}function p(a,c,b,d,g){this.indented=a;this.column=c;this.type=b;this.align=d;this.prev=g}function k(a,c,b){return a.context=new p(a.indented,c,b,null,a.context)}function q(a){if(a.context.prev){var c=a.context.type;if(")"==c||"]"==c||"}"==c)a.indented=a.context.indented;return a.context=a.context.prev}}var r=t.indentUnit,v={"break":!0,"case":!0,chan:!0,"const":!0,
"continue":!0,"default":!0,defer:!0,"else":!0,fallthrough:!0,"for":!0,func:!0,go:!0,"goto":!0,"if":!0,"import":!0,"interface":!0,map:!0,"package":!0,range:!0,"return":!0,select:!0,struct:!0,"switch":!0,type:!0,"var":!0,bool:!0,"byte":!0,complex64:!0,complex128:!0,float32:!0,float64:!0,int8:!0,int16:!0,int32:!0,int64:!0,string:!0,uint8:!0,uint16:!0,uint32:!0,uint64:!0,"int":!0,uint:!0,uintptr:!0,error:!0,rune:!0},w={"true":!0,"false":!0,iota:!0,nil:!0,append:!0,cap:!0,close:!0,complex:!0,copy:!0,"delete":!0,
imag:!0,len:!0,make:!0,"new":!0,panic:!0,print:!0,println:!0,real:!0,recover:!0},m=/[+\-*&^%:=<>!|\/]/,e;return{startState:function(a){return{tokenize:null,context:new p((a||0)-r,0,"top",!1),indented:0,startOfLine:!0}},token:function(a,c){var b=c.context;a.sol()&&(null==b.align&&(b.align=!1),c.indented=a.indentation(),c.startOfLine=!0,"case"==b.type&&(b.type="}"));if(a.eatSpace())return null;e=null;var d=(c.tokenize||h)(a,c);if("comment"==d)return d;null==b.align&&(b.align=!0);"{"==e?k(c,a.column(),
"}"):"["==e?k(c,a.column(),"]"):"("==e?k(c,a.column(),")"):"case"==e?b.type="case":"}"==e&&"}"==b.type?q(c):e==b.type&&q(c);c.startOfLine=!1;return d},indent:function(a,c){if(a.tokenize!=h&&null!=a.tokenize)return f.Pass;var b=a.context,d=c&&c.charAt(0);if("case"==b.type&&/^(?:case|default)\b/.test(c))return a.context.type="}",b.indented;a=d==b.type;return b.align?b.column+(a?0:1):b.indented+(a?0:r)},electricChars:"{}):",closeBrackets:"()[]{}''\"\"``",fold:"brace",blockCommentStart:"/*",blockCommentEnd:"*/",
lineComment:"//"}});f.defineMIME("text/x-go","go")});
|
var Task = require('./task.js');
var StylesTask = Object.create(Task);
StylesTask.name = 'styles';
StylesTask.prototype.scss = function() {
this.options.language = 'scss';
// Add gulp-sass to stream
return this;
};
StylesTask.prototype.minify = function() {
this.options.minify = true;
// Add gulp-compact to stream
return this;
};
module.exports = StylesTask; |
/**
* Created by dimanikishin on 19.01.16.
*/
(function(){
'use strict';
/**
* @memberof myApp
* @ngdoc config
*/
angular
.module('myApp')
.config(myAppConfig);
myAppConfig.$inject = ['$routeProvider']
function myAppConfig($routeProvider) {
$routeProvider.otherwise({redirectTo: '/404'});
}
})(); |
MessageStatus = {FAILED : 'failed', SUCCESS : 'success'};
module.exports = MessageStatus; |
var utils = require('../../utils/tokenGenerator');
module.exports = function (options, req, res, client_id, client_secret, token_options) {
var code = req.body.code;
options.storage.getCode(code, function (jsonCode) {
if (!jsonCode) {
res.statusCode = 400;
return res.json({error: "invalid code"});
}
res.statusCode = 200;
options.storage.addFieldsToAccessToken(client_id, client_secret, code.user_id, function (tokenFields) {
var access_token = utils.generateToken(options, jsonCode.user_id, client_id, client_secret, '', tokenFields, token_options);
options.storage.removeCode(code);
if (options.storage.saveAccessToken instanceof Function) {
options.storage.saveAccessToken(access_token);
}
return res.json(access_token);
});
});
}; |
'use strict';
var React = require('react');
// var AMR = require('amazeui-react');
var AMR = require('../reactui');
var Tabs = AMR.Tabs;
var tabkey = "1";
var TabsSelect = React.createClass({
getInitialState: function() {
//这里每次被调用都被初始化了,不爽,
//应该对应一个组件,这个组件的状态一直被记住(基于组件位置唯一)
//需要设置一个当前状态记忆变量,同步更新
//console.log("这里每次都被初始化了,不爽");
return {
key: tabkey || "1"
};
},
handleSelect: function(key) {
console.log('你点击了:', key);
//this.props.handleSelect(key);
tabkey = key;
this.setState({
key: key
});
},
render: function() {
return (
<Tabs justify defaultActiveKey={this.state.key} onSelect={this.handleSelect}>
<Tabs.Item eventKey="1" title="恣意">
置身人群中<br />你只需要被淹没 享受 沉默<br />退到人群后<br />你只需给予双手 微笑 等候
</Tabs.Item>
<Tabs.Item eventKey="2" title="等候">
走在忠孝东路<br />徘徊在茫然中<br />在我的人生旅途<br />选择了多少错误<br />我在睡梦中惊醒<br />感叹悔言无尽<br />恨我不能说服自己<br />接受一切教训<br />让生命去等候<br />等候下一个漂流<br />让生命去等候<br />等候下一个伤口
</Tabs.Item>
<Tabs.Item eventKey="3" title="流浪">
我就这样告别山下的家,我实在不愿轻易让眼泪留下。我以为我并不差不会害怕,我就这样自己照顾自己长大。我不想因为现实把头低下,我以为我并不差能学会虚假。怎样才能够看穿面具里的谎话?别让我的真心散的像沙。如果有一天我变得更复杂,还能不能唱出歌声里的那幅画?
</Tabs.Item>
</Tabs>
);
}
});
module.exports = TabsSelect;
|
import Component from '@ember/component';
import layout from '../../../templates/components/freestyle/bootstrap/tables/body/-row';
import { BuilderForPropDefaults } from 'ember-bootstrap-controls/utils/prop-definition-tools';
import { propDefinitions } from '../../bootstrap/tables/body/-row';
export default Component.extend({
layout,
propDefinitions,
data: Object.assign(BuilderForPropDefaults(propDefinitions), {
value: '',
}),
basicValue: '',
});
|
var base = require('./protractor.base.config');
base.config.capabilities = {
'browserName': 'chrome'
}
exports.config = base.config; |
//@flow
export type Options = {
cache: string,
player: ?string,
feed: string,
lang: string,
port: number,
'peer-port': number,
log: (...params: any[]) => void,
offline: boolean,
browse: boolean,
movie: boolean,
title: ?string,
}
export type NamedStat = {
name: string,
size: number,
isDirectory: () => boolean,
mtime: Date,
}
export type DirStat = {
files: NamedStat[],
count: number,
size: number,
hsize: string,
}
export type OrigSubtitles = {
SubLanguageID: string,
SubAddDate: string,
SubFileName: string,
SubSize: number,
SubDownloadLink: string,
MovieReleaseName: string,
}
export type Show = {
url: string,
title: string,
subtitles: ?string,
}
export type DateUnit = 'year'|'month'|'week'|'day'|'hour'|'minute'|'second'|'millisecond'
|
/*¶¨Ò幺Îï³µ¶ÔÏó*/
function Cart(){
this.products=[]
this.sum=0
this.allPrice=0
}
Cart.prototype={
bindBasic:function(){
//°ó¶¨
$('.cartsum').html(this.getSum())
$('#cartprice').html(this.getAllPrice())
},
//°ó¶¨²úÆ·Áбí,ÿ´Îµã»÷µ½¹ºÎï³µÖ´Ðеķ½·¨
bindList:function(){
var str=''
for(var i= 0,len=this.products.length;i<len;i++){
str+='<div class="cart_box">'
str+='<div class="message">'
str+=' <div class="alert-close"> </div>'
str+=' <div class="list_img"> <img src="'+this.products[i].images[0].small+'" class="img-responsive" alt=""/> </div>'
str+=' <div class="list_desc"><h4><a href="#">'+this.products[i].name+'</a></h4><span class="actual">'+ this.products[i].groupbuyPrice+'</span></div>'
str+=' <div class="clearfix"></div>'
str+=' <div class="clearfix"></div>'
str+=' </div>'
str+=' </div>'
}
$('.shopping_cart').html(str)
},
/*½áËã*/
calcalate:function(){},
/*»ñÈ¡²úÆ·¸öÊý*/
getSum:function(){
this.sum=this.products.length;
return this.sum;
},
/*»ñÈ¡²úÆ·×ܼÛ*/
getAllPrice:function(){
for(var i= 0,len=this.products.length;i<len;i++){
this.allPrice+=this.products[i].youhuijia;
}
return this.allPrice;
}
} |
'use strict';
var services = angular.module('carpoolBuddyApp.services', ['ngResource']).
factory('cityService', function($resource) {
return $resource('/rest/cities', {}, {});
}).
factory('buddyService', function($resource) {
return $resource('/rest/buddies', {}, {});
}); |
/*This is where common javascript will go*/
$(document).ready(function() {
/* handling the events for the new password text box */
var newPasswordPass = false;
handleNewPasswordEvents();
handleConfPasswordEvents(newPasswordPass);
doSelectAllCheckbox();
handleMultiSelect();
$('.tr-chk-bx-sel').click(function() {
// $(this).closest('input["checkbox"]').prop("checked");
});
/*Handling the delete of entity*/
handleDeleteEntity();
/*Handling the edit of the entity. This is just a redirect*/
handleEntityEditRedirect();
});
/*This function is handling the events for new password text box.*/
function handleNewPasswordEvents() {
$('#warning-for-new-pass').hide();
$('#success-for-new-pass').hide();
$('#newPassword').focusout(
function() {
var strNewPass = $(this).val();
if (strNewPass != "") {
/* if the password is less than minimum chars */
if (strNewPass.length < 8) {
$(this).closest('.form-group').addClass('has-warning')
.addClass('has-feedback').removeClass(
'has-success');
$('#warning-for-new-pass').show();
$('#success-for-new-pass').hide();
}
/* else we get success */
else {
newPasswordPass = true;
$(this).closest('.form-group').addClass('has-success')
.addClass('has-feedback').removeClass(
'has-warning');
$('#success-for-new-pass').show();
$('#warning-for-new-pass').hide();
}
}
/* if the text is empty then nothing to do */
else {
$(this).closest('.form-group').removeClass('has-warning')
.removeClass('has-feedback').removeClass(
'has-success');
$('#warning-for-new-pass').hide();
$('#success-for-new-pass').hide();
}
});
}
/*This function is handling the events for confirm password text box.*/
function handleConfPasswordEvents() {
$('#warning-for-conf-pass').hide();
$('#success-for-conf-pass').hide();
$("#confPassword").focusout(
function() {
var strConfPass = $(this).val();
var strNewPass = $("#newPassword").val();
if (strConfPass == "") {
$('#success-for-conf-pass').hide();
$('#warning-for-conf-pass').hide();
$(this).closest('.form-group').removeClass('has-warning')
.removeClass('has-feedback')
.removeClass('has-success');
}
else if (strConfPass != strNewPass) {
$(this).closest('.form-group').addClass('has-warning')
.addClass('has-feedback')
.removeClass('has-success');
$('#warning-for-conf-pass').show();
$('#success-for-conf-pass').hide();
} else {
$(this).closest('.form-group').addClass('has-success')
.addClass('has-feedback')
.removeClass('has-warning');
$('#success-for-conf-pass').show();
$('#warning-for-conf-pass').hide();
}
});
}
/*if the main checkbox is selected, all child ones will be selected*/
function doSelectAllCheckbox() {
$('.chk-select-all').click(function() {
var childCheckBoxId = $(this).data('child');
$('.'+childCheckBoxId).each(function() {
$(this).prop("checked", !$(this).prop("checked"));
})
});
}
function handleMultiSelect() {
}
function handleDeleteEntity()
{
$('.delete-entity').click(function() {
var entity = $(this).data('entity');
var entityId = $(this).data('entity-id');
var cnfrm = confirm("Sure you want to delete");
if(cnfrm === true)
{
$.ajax({
type: "POST",
url: base_url + 'delete-entity',
data: {entityId: entityId, entity: entity}
}).success(function (data)
{
location.reload();
});
}
});
}
function handleEntityEditRedirect()
{
$('.edit-entity').click(function() {
var entity = $(this).data('entity');
var entityId = $(this).data('entity-id');
$.ajax({
type: "POST",
url: base_url + 'edit-entity',
data: {entityId: entityId, entity: entity}
}).success(function(response) {
window.location.href = base_url + response.url;
});
});
} |
/* Gina.utils.Proc
*
* This file is part of the gina package.
* Copyright (c) 2016 Rhinostone <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
*
* { name: 'SIGABRT', action: 'A', desc: 'Process abort signal.' },
* { name: 'SIGALRM', action: 'T', desc: 'Alarm clock.' },
* { name: 'SIGBUS', action: 'A', desc: 'Access to an undefined portion of a memory object.' },
* { name: 'SIGCHLD', action: 'I', desc: 'Child process terminated, stopped, or continued. ' },
* { name: 'SIGCONT', action: 'C', desc: 'Continue executing, if stopped.' },
* { name: 'SIGFPE', action: 'A', desc: 'Erroneous arithmetic operation.' },
* { name: 'SIGHUP', action: 'T', desc: 'Hangup.' },
* { name: 'SIGILL', action: 'A', desc: 'Illegal instruction.' },
* { name: 'SIGINT', action: 'T', desc: 'Terminal interrupt signal.' },
* { name: 'SIGKILL', action: 'T', desc: 'Kill (cannot be caught or ignored).' },
* { name: 'SIGPIPE', action: 'T', desc: 'Write on a pipe with no one to read it.' },
* { name: 'SIGQUIT', action: 'A', desc: 'Terminal quit signal.' },
* { name: 'SIGSEGV', action: 'A', desc: 'Invalid memory reference.' },
* { name: 'SIGSTOP', action: 'S', desc: 'Stop executing (cannot be caught or ignored).' },
* { name: 'SIGTERM', action: 'T', desc: 'Termination signal.' },
* { name: 'SIGTSTP', action: 'S', desc: 'Terminal stop signal.' },
* { name: 'SIGTTIN', action: 'S', desc: 'Background process attempting read.' },
* { name: 'SIGTTOU', action: 'S', desc: 'Background process attempting write.' },
* { name: 'SIGUSR1', action: 'T', desc: 'User-defined signal 1.' },
* { name: 'SIGUSR2', action: 'T', desc: 'User-defined signal 2.' },
* { name: 'SIGPOLL', action: 'T', desc: 'Pollable event. ' },
* { name: 'SIGPROF', action: 'T', desc: 'Profiling timer expired. ' },
* { name: 'SIGSYS', action: 'A', desc: 'Bad system call.' },
* { name: 'SIGTRAP', action: 'A', desc: 'Trace/breakpoint trap. ' },
* { name: 'SIGURG', action: 'I', desc: 'High bandwidth data is available at a socket.' },
* { name: 'SIGVTALRM', action: 'T', desc: 'Virtual timer expired.' },
* { name: 'SIGXCPU', action: 'A', desc: 'CPU time limit exceeded.' },
* { name: 'SIGXFSZ', action: 'A', desc: 'File size limit exceeded. ' }
* */
//Imports
var fs = require('fs');
var Emitter = require('events').EventEmitter;
var spawn = require('child_process').spawn;
var UtilsConfig = require( _(__dirname + '/config') );
var inherits = require( _(__dirname + '/inherits') );
var console = require( _(__dirname + '/logger') );
//var helpers = require( _(__dirname + '/helpers') );
//console.log('path ? ', getPaths());
/**
* @constructor
*
* @param {string} bundle
*
* */
function Proc(bundle, proc, usePidFile){
var self = this;
this.PID = null;
this.path = null;
this.master = false;//used only by master.
this.bundle = bundle;
this.proc = proc;
this.bundles = [];
if ( typeof(usePidFile) == 'undefined') {
var usePidFile = true
}
/**
* Check target path
* @param {string} path
* @param {integer} PID Id of the PID to save
* */
var init = function() {
//Default.
var pathObj = new _( getPath('root') + '/tmp/pid/' );
var path = pathObj.toString();
//Create dir if needed.
//console.debug("MKDIR pathObj (pid:"+self.proc.pid+") - ", self.bundle);
process.list = (process.list == undefined) ? [] : process.list;
process.pids = (process.pids == undefined) ? {} : process.pids;
self.register(self.bundle, self.proc.pid);
if (usePidFile) {
pathObj.mkdir( function(err, path){
console.debug('path created ('+path+') now saving PID ' + bundle);
//logger.info('gina', 'PROC:INFO:1', 'path created ('+path+') now saving PID ' + bundle, __stack);
//Save file.
if (!err) {
self.PID = self.proc.pid;
self.path = path + pathObj.sep;
//Add PID file.
setPID(self.bundle, self.PID, self.proc);
save(self.bundle, self.PID, self.proc)
}
})
}
};
var isMaster = function() {
return (self.master) ? true : false;
};
// var getShutdownConnectorSync = function(bundle) {
// var bundlesPath = getPath('bundlesPath');
// var connPath = _(bundlesPath +'/'+ bundle + '/config/connector.json');
// try {
// console.log('reading connPath: ', connPath);
// var content = fs.readFileSync(connPath);
// return JSON.parse(content).httpClient.shutdown
// } catch (err) {
// return undefined
// }
// }
/**
* Going to force restart by third party (kill 9).
*
* @param {string} bundle
* @param {string} env
* @param {number} pid
*
* @callback callback
* @param {boolean|string} err
* */
var respawn = function(bundle, env, pid, callback) {
//var loggerInstance = getContext('logger');
//loggerInstance["trace"]('Fatal error !');
//console.debug("Exiting and re spawning : ", bundle, env);
// TODO - Count the restarts and prevent unilimited loop
// TODO - Send notification to admin or/and root to the Fatal Error Page.
var root = getPath('root');
try {
var version = process.getVersion(bundle);
} catch (err) {
var bundle = process.argv[3];
//var port = self.getBundlePortByBundleName(bundle);
//console.log("Bundle ", bundle," already running or port[ "+port+" ] is taken by another process...");
//loggerInstance["trace"]("Bundle [ "+ bundle +" ] already running or [ "+env+" ] port is use by another process...");
console.debug("Bundle [ "+ bundle +" ] already running or [ "+env+" ] port is use by another process...");
dismiss(process.pid);
}
var outPath = _(root + '/out.'+bundle+'.'+version+'.log');
var errPath = _(root + '/out.'+bundle+'.'+version+'.log');
var nodePath = getPath('node');
var ginaPath = _(root + '/gina');
// if (env == 'prod') { //won't loop forever for others env.
//
// //var opt = process.getShutdownConnectorSync();
// var opt = getShutdownConnectorSync(bundle);
// //Should kill existing one..
// opt.path = '/' + bundle + '/restart/' + pid + '/' + env;
//
// var HttpClient = require('gina.com').Http;
// var httpClient = new HttpClient();
//
// if (httpClient) {
// //httpClient.query(opt);
// //We are not waiting for anything particular...do we ?
// httpClient.query(opt, function (err, msg) {
// //Now start new bundle.
// callback(err);
// });
// } else {
// var err = new Error('No shutdown connector found.');
// console.error(err);
// callback(err);
// }
//
// } else {
callback(false);
//}
};
var setPID = function(bundle, PID, proc) {
if (bundle != 'gina') {
proc.title = 'gina: '+ bundle;
} else {
proc.title = bundle;
}
//Set event.
setDefaultEvents(bundle, PID, proc);
};
var setDefaultEvents = function(bundle, PID, proc) {
if ( typeof(PID) != "undefined" && typeof(PID) == "number" ) {
console.debug("setting listeners for ", PID, ':', bundle);
proc.dismiss = dismiss;
proc.isMaster = isMaster;
proc.on('SIGTERM', function(code){
proc.exit(code);
});
proc.on('SIGINT', function(code){
if (code == undefined) var code = 0;
console.info("\nGot exit code. Now killing: ", code);
proc.exit(code);//tigger exit event.
});
//Will prevent the server from stopping.
proc.on('uncaughtException', function(err) {
console.error(err.stack);
var bundle = self.bundle;
//console.log("@=>", self.args);
var env = process.env.NODE_ENV || 'prod';
var pid = self.getPidByBundleName(bundle);
//Wake up buddy !.
respawn(bundle, env, pid, function(err) {
//TODO - Send an email to the administrator/dev
//TODO - Have a delegate handler to allow the dev to do its stuff. Maybe it's already there if any dev can override.
//proc.exit(1) // don't kill !!! It will stop the server
})
});
proc.on('exit', function(code){
if ( typeof(code) == 'undefined') {
code = 0;
}
var bundle = self.bundle;
var env = process.env.NODE_ENV || 'prod';
var pid = self.getPidByBundleName(bundle);
//console.log('bundle ', bundle, ' vs ', pid, " => ", process.pid);
//console.log("got exit code ", "("+code+")", pid, " VS ", pid, " <=> gina: ", process.pid);
//code = code || 0;
//var obj = logger.emerg('gina', 'UTILS:EMERG1', 'process exit code ' + code);
//if (code == 0 && env != "debug" && env != "dev"/***/) {
//for (var p=0; p<process.list.count(); p++) {
// dismiss(process.list[p].pid)
//}
// kill gina
dismiss(process.list[process.list.count()-1].pid, "SIGKILL")
});
proc.on('SIGHUP', function(code){
console.debug("Hanging up ! Code: "+ code+"\n"+ process.argv);
var bundle = self.bundle;
var env = process.env.NODE_ENV || 'prod';
var pid = self.getPidByBundleName(bundle);
dismiss(process.pid, "SIGINT");
dismiss(pid, "SIGINT");
})
}
};
var dismiss = function(pid, signal){
if (pid == undefined) {
var pid = self.PID;
}
try {
for (var p in process.list) {
fs.unlinkSync( _(self.path + process.list[p].pid) )
}
} catch (err) {
//Means that it does not exists anymore.
}
try {
console.debug('\n=> '+ JSON.stringify(process.list, null, 4));
for (var p in process.list) {
if ( process.list[p].name != 'gina' ) {
fs.unlinkSync( _(getPath('mountPath') + '/' + process.list[p].name) )
}
}
} catch (err) {
//Means that it does not exists anymore.
}
process.kill(pid, signal);// soft...
console.debug('\nsent '+ signal +' signal to end process [ '+ pid +' ]\n');
};
/**
* Save PID file
* @param {string} bundle
* @param {integer} PID Id of the PID to save
*
* @private
* */
var save = function(){
var bundle = self.bundle;
var PID = self.PID;
var proc = self.proc;
var path = self.path
//Get PID path.
if (
typeof(bundle) != "undefined" && bundle != ""
&& typeof(PID) != "undefined" && PID != "" && PID != null
&& typeof(proc) != "undefined" && proc != "" && proc != null
) {
try {
var fileStream = fs.createWriteStream(path + PID);
fileStream.once('open', function(fd) {
fileStream.write(bundle);
console.debug('registered ', self.proc.pid);
fileStream.end();
self.emit('proc#complete', false)
});
} catch (err) {
self.emit('proc#complete', err)
}
} else {
self.emit('proc#complete', new Error('encountered troubles while trying to save Process file'))
}
};
/**
* Get PID
* @param {string} bundle
* @return {number} PID
* */
this.getPID = function(){
try{
return self.PID;
} catch (err) {
console.error('Could not get PID for bundle: '+ self.bundle + (err.stack||err.message));
return null;
}
};
this.getBundleNameByPid = function(pid){
var list = process.list;
for (var i=0; i<list.length; ++i) {
//console.log("list ", list, ':', list[i][pid]);
if ( typeof(list[i][pid]) != "undefined")
return list[i][pid]
}
return undefined
};
this.getPidByBundleName = function(bundle){
var list = process.pids;
//console.log("list ", list, ':', list[bundle]);
if ( typeof(list[bundle]) != "undefined")
return list[bundle]
else
return undefined
};
this.setMaster = function(bool){
if ( typeof(bool) == 'undefined' || bool == true) {
self.master = true;
} else {
self.master = false;
}
};
this.register = function(bundle, pid) {
if ( bundle == 'gina' || bundle != 'gina' && self.bundles.indexOf(bundle) == -1 ) {
if (bundle != 'gina') {
self.bundles.push(bundle);
}
var list = {};
list['pid'] = pid;
list['name'] = bundle;
process.list.push(list);//Running bundles.
process.pids[bundle] = pid;
list = null;
}
};
this.onReady = function(cb) {
self.once('proc#complete', function(err){
cb(err)
})
}
//Init.
if ( typeof(this.bundle) == "undefined" ) {
console.error('Invalid or undefined proc name . Proc naming Aborted')
} else {
init()
}
};
Proc = inherits(Proc, Emitter);
module.exports = Proc; |
'use strict';
angular.module('tryNav')
.directive('tryNav', function (Post, $location) {
return {
restrict: 'E',
templateUrl: '/templates/try-nav.html',
link: function (scope, element, attr) {
scope.items = Post.query();
scope.selectItem = function ($item, $model, $label) {
// console.log($item);
// console.log($model);
// console.log($label);
$location.path("/blog/" + $item.id);
scope.searchQuery = "";
};
scope.searchItem = function () {
console.log(scope.searchQuery);
$location.path("/blog/").search("q", scope.searchQuery);
scope.searchQuery = "";
}
}
}
}); |
import { createStore, compose, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import reducer from './reducers';
export default function configureStore(initialState) {
const store = createStore(reducer, initialState, compose(
// applyMiddleware supercharges createStore with middleware:
applyMiddleware(thunk),
// Detect devtools browser extension
(typeof window !== 'undefined' && window.devToolsExtension) ? window.devToolsExtension() : fn => fn
));
return store;
}
|
// Generated by CoffeeScript 1.8.0
var BadRequest, Contact, ContactActivity, NotFound, async, log, _ref;
Contact = require('../models/contact');
async = require('async');
log = require('../utils/logging')({
prefix: 'controllers:activity'
});
_ref = require('../utils/errors'), BadRequest = _ref.BadRequest, NotFound = _ref.NotFound;
ContactActivity = {
search: function(data, callback) {
var params, request;
if (data.query != null) {
request = 'mailByName';
params = {
startkey: data.query,
endkey: data.query + "\uFFFF"
};
} else {
request = 'all';
params = {};
}
return Contact.requestWithPictures(request, params, callback);
},
create: function(data, callback) {
var _ref1;
if (((_ref1 = data.contact) != null ? _ref1.address : void 0) != null) {
return Contact.createNoDuplicate(data.contact, callback);
} else {
return callback(new BadRequest('BAD FORMAT'));
}
},
"delete": function(data, callback) {
return Contact.find(data.id, function(err, contact) {
if (err) {
return callback(err);
}
if (!contact) {
return callback(new NotFound("CONTACT " + data.id));
}
return contact.destroy(callback);
});
}
};
module.exports.create = function(req, res, next) {
var activity, _ref1;
activity = req.body;
switch (activity.data.type) {
case 'contact':
if (ContactActivity[activity.name] != null) {
return ContactActivity[activity.name](activity.data, function(err, result) {
if (err != null) {
return res.status(400).send({
name: err.message,
error: true
});
} else {
return res.send({
result: result
});
}
});
} else {
return res.status(400).send({
name: "Unknown activity name",
error: true
});
}
break;
case 'error':
log.error(activity.data);
log.error((_ref1 = activity.data.error) != null ? _ref1.stack : void 0);
return res.send('ok');
case 'debug':
log.info(activity.data.message);
return res.send('ok');
default:
return res.status(400).send({
name: "Unknown activity data type",
error: true
});
}
};
|
var Board = require("../lib/board.js"),
Descriptor = require("descriptor"),
__ = require("../lib/fn.js"),
events = require("events"),
util = require("util");
var priv = new Map(),
modes;
modes = {
INPUT: 0x00,
OUTPUT: 0x01,
ANALOG: 0x02,
PWM: 0x03,
SERVO: 0x04
};
/**
* Pin
* @constructor
*
* @description Direct Pin access objects
*
* @param {Object} opts Options: pin, freq, range
*/
function Pin(opts) {
var isAnalogInput, isDTOA, isPin, pinValue, addr, type, highLow, value, state;
if (!(this instanceof Pin)) {
return new Pin(opts);
}
pinValue = typeof opts === "object" ? (opts.addr || opts.pin || 0) : opts;
isAnalogInput = Pin.isAnalog(opts);
isDTOA = false;
Board.Component.call(
this, opts = Board.Options(opts)
);
opts.addr = opts.addr || opts.pin;
if (this.io.analogPins.includes(pinValue)) {
isDTOA = true;
isAnalogInput = false;
}
isPin = typeof opts !== "object";
addr = isDTOA ? pinValue : (isPin ? opts : opts.addr);
type = opts.type || (isAnalogInput ? "analog" : "digital");
value = 0;
// Create a private side table
state = {
mode: null,
last: null,
value: 0
};
priv.set(this, state);
// Create read-only "addr(address)" property
Object.defineProperties(this, {
type: new Descriptor(type),
addr: new Descriptor(addr, "!writable"),
value: {
get: function() {
return state.value;
}
},
mode: {
set: function(mode) {
var state = priv.get(this);
// set mode
// TODO: if setting to PWM, check if this pin is capable of PWM
// log error if not capable
if (state.mode !== mode) {
state.mode = mode;
this.io.pinMode(this.addr, mode);
}
},
get: function() {
return priv.get(this).mode;
}
}
});
this.mode = this.as || opts.mode || (isAnalogInput ? 0x00 : 0x01);
highLow = function(state) {
return function(data) {
var privs, isNot, emit;
privs = priv.get(this);
// Update the value closure
privs.value = data;
isNot = state ? "low" : "high";
emit = state ? "high" : "low";
if (privs.mode === modes.INPUT) {
if (privs.last === null) {
privs.last = isNot;
}
if (data === state && privs.last === isNot) {
privs.last = emit;
this.emit(emit);
}
}
// Emit a firehose "data" event
this.emit("data");
}.bind(this);
}.bind(this);
// Debounced for noise reduction: more accurately
// detect HIGH state.
this.io[type + "Read"](
this.addr, __.debounce(highLow(1), 50)
);
// No debounce to read the constant stream
// (very noisy, only care about 0)
this.io[type + "Read"](
this.addr, highLow(0)
);
}
util.inherits(Pin, events.EventEmitter);
/**
* Pin.@@MODE
*
* Read-only constants
* Pin.INPUT = 0x00
* Pin.OUTPUT = 0x01
* Pin.ANALOG = 0x02
* Pin.PWM = 0x03
* Pin.SERVO = 0x04
*
*/
Object.keys(modes).forEach(function(mode) {
Object.defineProperty(Pin, mode, {
value: modes[mode]
});
});
Pin.isAnalog = function(opts) {
if (typeof opts === "string" && Pin.isPrefixed(opts, ["I", "A"])) {
return true;
}
if (typeof opts === "object") {
return Pin.isAnalog(
typeof opts.addr !== "undefined" ? opts.addr : opts.pin
);
}
};
Pin.isPrefixed = function(value, prefixes) {
value = value[0];
return prefixes.reduce(function(resolution, prefix) {
if (!resolution) {
return prefix === value;
}
return resolution;
}, false);
};
Pin.write = function(pin, val) {
var state = priv.get(pin);
state.value = val;
// Set the correct mode (OUTPUT)
// This will only set if it needs to be set, otherwise a no-op
pin.mode = modes.OUTPUT;
// Create the correct type of write command
pin.io[pin.type + "Write"](pin.addr, val);
pin.emit("write", null, val);
};
Pin.read = function(pin, callback) {
// Set the correct mode (INPUT)
// This will only set if it needs to be set, otherwise a no-op
pin.mode = modes.INPUT;
pin.io[pin.type + "Read"](pin.addr, function() {
callback.apply(pin, arguments);
});
};
// Pin.prototype.isDigital = function() {
// return this.addr > 1;
// };
// Pin.prototype.isAnalog = function() {
// return this.board > 1;
// };
// Pin.prototype.isPWM = function() {
// };
// Pin.prototype.isServo = function() {
// };
// Pin.prototype.isI2C = function() {
// };
// Pin.prototype.isSerial = function() {
// };
// Pin.prototype.isInterrupt = function() {
// };
// Pin.prototype.isVersion = function() {
// };
Pin.prototype.query = function(callback) {
var index = this.addr;
if (this.type === "analog") {
index = this.io.analogPins[this.addr];
}
function handler() {
callback(this.io.pins[index]);
}
this.io.queryPinState(index, handler.bind(this));
return this;
};
/**
* high Write high/1 to the pin
* @return {Pin}
*/
Pin.prototype.high = function() {
var value = this.type === "analog" ? 255 : 1;
Pin.write(this, value);
this.emit("high");
return this;
};
/**
* low Write low/0 to the pin
* @return {Pin}
*/
Pin.prototype.low = function() {
Pin.write(this, 0);
this.emit("low");
return this;
};
/**
* read Read from the pin, value is passed to callback continuation
* @return {Pin}
*/
/**
* write Write to a pin
* @return {Pin}
*/
["read", "write"].forEach(function(state) {
Pin.prototype[state] = function(valOrCallback) {
Pin[state](this, valOrCallback);
return this;
};
});
module.exports = Pin;
|
const is = require('is')
const tar = require('tar-fs')
const fs = require('fs')
const os = require('os')
const { spawn } = require('child_process')
const zlib = require('zlib')
const multimatch = require('multimatch')
const logger = require('./index.js').logger
const mergeNoUndefined = require('./index.js').mergeNoUndefined
module.exports = function builder(module, env, next) {
let isString = is.string,
isUndefined = is.undefined
let localLogger = (local, type) => (msg, end = false, cb = next) =>
logger[type](msg, local, end, cb)
let error = localLogger('builder', 'error')
let warning = localLogger('builder', 'warning')
let { buildCommand, nobuild } = module
nobuild = mergeNoUndefined(false, nobuild)
module.nobuild = nobuild
if (nobuild) return next(null, `env ${env} nobuild`)
if (isUndefined(buildCommand)) {
return error(
`Publish environment '${env}' option 'buildCommand' is required`
)
}
if (!isString(buildCommand)) {
return error(
`Publish environment '${env}' option 'buildCommand' must be a string`
)
}
if (this._metadata.parallel) {
logger.assert(
Object.values(this._metadata.modules).every(
v => v.buildCommand === buildCommand
),
'error',
'If the task is concurrent, the release command must be consistent',
'builder'
)
}
let promiseName = `_${buildCommand}BuilderPromise`
let p = this[promiseName]
? this[promiseName]
: (this[promiseName] = new Promise((resolve, reject) => {
if (this._metadata.check) {
logger.success(`env ${env} build success`)
resolve(null)
return
}
let cp = spawn(process.platform === 'win32' ? 'npm.cmd' : 'npm', [
'run',
buildCommand
])
cp.stderr.on('data', data => {
process.stdout.write(data)
})
cp.stdout.on('data', data => {
process.stdout.write(data)
})
cp.on('close', code => {
if (code != 0) {
resolve('build failures')
} else {
logger.success(`env ${env} build success`)
resolve(null)
}
})
}))
p.then(err => {
if (err) {
error(`Publish environment '${env}' build failures`, false, () => {})
next(err)
} else {
next(null, 'build success')
}
})
}
|
import { memo } from 'react';
import { useRouter } from 'next/router';
import BaseTimeRange from './BaseTimeRange';
import { goToUrlQueryAndResetPagination } from 'lib/listPage';
/**
* URL param names to read from and write to
*/
const PARAM_NAME_START = 'start';
const PARAM_NAME_END = 'end';
/**
* @param {object} query - query from router
* @returns {[string?, string?]} Pair of timestamps representing [start, end].
* Strings are in ISO date (YYYY-MM-DD) or relative date format supported by Elasticsearch.
* When not specified, it's undefined.
*/
function getValues(query) {
return [query[PARAM_NAME_START], query[PARAM_NAME_END]];
}
/**
* Time range control connnected to URL "start", "end" param
*/
function TimeRange() {
const { query } = useRouter();
const [start, end] = getValues(query);
return (
<BaseTimeRange
start={start}
end={end}
onChange={(start, end) => {
goToUrlQueryAndResetPagination({
...query,
[PARAM_NAME_START]: start,
[PARAM_NAME_END]: end,
});
}}
/>
);
}
const MemoizedTimeRange = memo(TimeRange);
MemoizedTimeRange.getValues = getValues;
export default MemoizedTimeRange;
|
import React, { PropTypes } from 'react'
import classNames from 'classnames'
import s from './styles.scss'
const renderIcon = {
user: () => (
<path d='M0,245c0,135.1,109.9,245,245,245s245-109.9,245-245S380.1,0,245,0S0,109.9,0,245z M245,41.6
c112.2,0,203.4,91.2,203.4,203.4c0,50.4-18.5,96.5-48.9,132.1c-42-32.2-83.8-53.4-93-57.8c-1.1-0.6-1.8-1.7-1.8-3
c0-4.8,0-17.3,0-30.5c4.5-9.4,7.3-19.5,8.9-28.6c4.1,2.8,10.9,1.3,
18.4-25.1c6.1-21.5,2.4-28.7-2.9-30.5c17.1-81.9-22-84.6-22-84.6
s-5.9-11.3-21.4-19.9c-10.4-6.2-24.9-10.9-44-9.3c-6.2,0.3-12,1.5-17.5,3.3l0,0c-7,2.4-13.4,5.8-19.3,9.9
c-7.1,4.5-13.9,10.1-19.8,16.4c-9.4,9.6-17.8,22.1-21.4,37.6c-3.5,13.2-3.4,27.4,1.8,41.9c-7-0.7-15.3,3.4-7.5,31
c5.7,20.2,11,25.8,15,26.1c1.8,11.5,5.4,24.4,12.3,36v26.4c0,1.3-0.7,2.4-1.8,3c-9.1,4.5-51,25.6-93,57.8
C60.1,341.5,41.6,295.4,41.6,245C41.6,132.8,132.8,41.6,245,41.6z' />
)
}
export const Icon = ({ className, type, ...props }) => (
<svg className={classNames(s.root, className)}
preserveAspectRatio='xMidYMid meet'
viewBox='0 0 490 490'
{...props}>
{renderIcon[type]()}
</svg>
)
Icon.propTypes = {
className: PropTypes.string,
type: PropTypes.oneOf(Object.keys(renderIcon)).isRequired
}
|
import thenChrome from 'then-chrome'
import MessageListener from './libs/MessageListener'
import {response as getImagesOnPage} from './libs/getImagesOnPage'
import {response as getPageTitle} from './libs/getPageTitle'
const onMessageListener = new MessageListener('content')
onMessageListener.add('getImages', async (message, sender, sendResponse) => {
sendResponse(getImagesOnPage())
})
onMessageListener.add('getPageTitle', async (message, sender, sendResponse) => {
sendResponse(getPageTitle())
})
chrome.runtime.onMessage.addListener(onMessageListener.listen.bind(onMessageListener))
|
import Constraint from 'liquid-fire/constraint';
export function target(name) {
return new Constraint('parentElementClass', `${name}-liquid-target`);
}
|
//~ name b353
alert(b353);
//~ component b354.js
|
version https://git-lfs.github.com/spec/v1
oid sha256:37f0d278c89b956bcd2532cbd780df29817a4cd59e55180f269c675b2d2d10fa
size 33862
|
import BigNumber from 'bignumber.js'
import {createActions, handleActions} from 'redux-actions'
import {PENDING, FULFILLED, REJECTED} from 'redux-promise-middleware'
export const {
getBalance,
getEndTime,
getRemainingSupply,
getTokenValue,
setProvider
} = createActions(
'GET_BALANCE',
'GET_END_TIME',
'GET_REMAINING_SUPPLY',
'GET_TOKEN_VALUE',
'SET_PROVIDER'
)
export const reducer = handleActions({
[`${getBalance}_${PENDING}`]: (state) => ({...state, balanceLoading: true}),
[`${getBalance}_${FULFILLED}`]: (state, {payload}) => ({
...state,
balance: new BigNumber(payload),
balanceLoading: false,
balanceError: null
}),
[`${getBalance}_${REJECTED}`]: (state, {payload}) => ({
...state,
balanceError: payload
}),
[`${getEndTime}_${FULFILLED}`]: (state, {payload}) => ({...state, endTime: payload}),
[`${getRemainingSupply}_${FULFILLED}`]: (state, {payload}) => ({...state, remainingSupply: new BigNumber(payload)}),
[`${getTokenValue}`]: (state, {payload}) => ({...state, tokenValue: new BigNumber(payload)}),
[`${getTokenValue}_${FULFILLED}`]: (state, {payload}) => ({...state, tokenValue: new BigNumber(payload)}),
[setProvider]: (state, {payload}) => ({...state, provider: payload})
}, {})
|
'use strict';
module.exports = function(grunt) {
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-simple-mocha');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.initConfig({
jshint: {
options:{
jshintrc: true
},
src: ['Gruntfile.js',
'test/**/*.js',
'models/**/*.js',
'routes/**/*.js',
'lib/**/*.js',
'server.js']
},
simplemocha: {
all: {
src: ['test/**/*.js']
}
},
watch: {
scripts: {
files: ['**/*.js', 'server.js'],
tasks: ['jshint', 'simplemocha:all'],
options: {
spawn: false
}
}
}
});
grunt.registerTask('test', ['jshint', 'simplemocha:all']);
grunt.registerTask('default', ['test']);
};
|
"use strict";
/*
For Uniforms:
Pass an array of names, values and types to bind uniforms.
Then loop through each calling the appropriate glUniform on the correct
uniform name.
This can be called by the model, the renderer etc each with its own set of
attributes. If an attribute isn't in the shader then nothing gets set.
For Attributes:
The mesh will pass in an array of structs containiing the glBuffer, the
attribute name, size of the items in the buffer, and the type,
Note item size is the number of the elements of the type. So if the buffer
has Vector3's then the items size is 3.
The number of vertices is passed in seperately.
*/
function ShaderProgram(gl) {
this.gl = gl;
this.glProgram = -1;
this.ready = false;
this.uniforms = {};
this.attributes = {};
this.fragShaderName = "";
this.vertShaderName = "";
this.fragShaderSource = "";
this.vertShaderSource = "";
this.vertShaderID = -1;
this.fragShaderID = -1;
this.attributeSlots = [
["aVertexPosition", 0 ],
["aVertexNormal", 1],
["aVertexUV", 2],
["aVertexTangent", 3],
["aVertexColor", 4]
];
this.uniformSlots = [];
//TODO: THIS SHOULD GO IN A GL UTILS CLASS
this.typeToString = {};
this.typeToString[gl.FLOAT] = "FLOAT";
this.typeToString[gl.FLOAT_VEC2] = "FLOAT_VEC2";
this.typeToString[gl.FLOAT_VEC3] = "FLOAT_VEC3";
this.typeToString[gl.FLOAT_VEC4] = "FLOAT_VEC4";
this.typeToString[gl.INT] = "INT";
this.typeToString[gl.INT_VEC2] = "INT_VEC2";
this.typeToString[gl.INT_VEC3] = "INT_VEC3";
this.typeToString[gl.INT_VEC4] = "INT_VEC4";
this.typeToString[gl.BOOL] = "BOOL";
this.typeToString[gl.BOOL_VEC2] = "BOOL_VEC2";
this.typeToString[gl.BOOL_VEC3] = "BOOL_VEC3";
this.typeToString[gl.BOOL_VEC4] = "BOOL_VEC4";
this.typeToString[gl.FLOAT_MAT2] = "FLOAT_MAT2";
this.typeToString[gl.FLOAT_MAT3] = "FLOAT_MAT3";
this.typeToString[gl.FLOAT_MAT4] = "FLOAT_MAT4";
this.typeToString[gl.SAMPLER_2D] = "SAMPLER_2D";
this.typeToString[gl.SAMPLER_CUBE] = "SAMPLER_CUBE";
this.stringToType = {};
this.stringToType["FLOAT"] = gl.FLOAT;
this.stringToType["FLOAT_VEC2"] = gl.FLOAT_VEC2;
this.stringToType["FLOAT_VEC3"] = gl.FLOAT_VEC3;
this.stringToType["FLOAT_VEC4"] = gl.FLOAT_VEC4;
this.stringToType["INT"] = gl.INT;
this.stringToType["INT_VEC2"] = gl.INT_VEC2;
this.stringToType["INT_VEC3"] = gl.INT_VEC3;
this.stringToType["INT_VEC4"] = gl.INT_VEC4;
this.stringToType["BOOL"] = gl.BOOL;
this.stringToType["BOOL_VEC2"] = gl.BOOL_VEC2;
this.stringToType["BOOL_VEC3"] = gl.BOOL_VEC3;
this.stringToType["BOOL_VEC4"] = gl.BOOL_VEC4;
this.stringToType["FLOAT_MAT2"] = gl.FLOAT_MAT2;
this.stringToType["FLOAT_MAT3"] = gl.FLOAT_MAT3;
this.stringToType["FLOAT_MAT4"] = gl.FLOAT_MAT4;
this.stringToType["SAMPLER_2D"] = gl.SAMPLER_2D;
this.stringToType["SAMPLER_CUBE"] = gl.SAMPLER_CUBE;
}
ShaderProgram.prototype.compileShaderType = function(str, type) {
var gl = this.gl;
var shader = gl.createShader(type);
gl.shaderSource(shader, str);
gl.compileShader(shader);
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
var err = gl.getShaderInfoLog(shader);
console.error(err);
alert(err);
return null;
}
return shader;
}
ShaderProgram.prototype.getShader = function(id) {
var gl = this.gl;
var shaderScript = document.getElementById(id);
if (!shaderScript) {
var err = "couldn't find shader";
console.error(err);
alert(err);
return null;
}
var str = "";
var k = shaderScript.firstChild;
while (k) {
if (k.nodeType == 3) {
str += k.textContent;
}
k = k.nextSibling;
}
var shader;
if (shaderScript.type == "x-shader/x-fragment") {
shader = gl.createShader(gl.FRAGMENT_SHADER);
} else if (shaderScript.type == "x-shader/x-vertex") {
shader = gl.createShader(gl.VERTEX_SHADER);
} else {
var err = "couldn't determine type of shader";
console.error(err);
alert(err);
return null;
}
gl.shaderSource(shader, str);
gl.compileShader(shader);
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
var err = gl.getShaderInfoLog(shader);
console.error(err);
alert(err);
return null;
}
return shader;
}
//NEW: Should replace
ShaderProgram.prototype.bindMeshAttributes = function(mesh) {
var gl = this.gl;
for(var i = 0; i < mesh.buffers.length; i++) {
var meshBuffer = mesh.buffers[i];
var attr = this.attributes[meshBuffer.name];
if(attr == null) {
//console.error("Attribute not found for: " + meshBuffer.name);
continue;
}
if(attr.type != meshBuffer.type){
console.error("Attribute type mismatch for: " + meshBuffer.name
+ " type mesh: " + meshBuffer.type
+ " type attribute " + attr.type
+ " meshBufferName: " + meshBuffer.name
+ " attributeName: " + attr.name
);
continue;
}
gl.bindBuffer(
meshBuffer.stringToType[meshBuffer.bufferType],
meshBuffer.buffer
);
gl.vertexAttribPointer(
attr.slot,
meshBuffer.itemSize,
this.stringToType[meshBuffer.componentType],
meshBuffer.normalized,
meshBuffer.stride,
meshBuffer.pointer
);
gl.enableVertexAttribArray(attr.slot);
}
};
ShaderProgram.prototype.cacheAttributeData = function() {
var gl = this.gl;
var total = gl.getProgramParameter(this.glProgram, gl.ACTIVE_ATTRIBUTES);
for( var i = 0; i < total; ++i) {
//WebGLActiveInfo = { GLint: size, GLenum: type, DOMString: name};
var activeInfo = gl.getActiveAttrib(this.glProgram, i);
var slot = gl.getAttribLocation(this.glProgram, activeInfo.name);
this.attributes[activeInfo.name] = {
"slot" : slot,
"size" : activeInfo.size,
"type" : this.typeToString[activeInfo.type],
"name" : activeInfo.name,
"info" : activeInfo
};
console.debug(this.attributes[activeInfo.name]);
}
}
ShaderProgram.prototype.cacheUniformData = function() {
var gl = this.gl;
var total = gl.getProgramParameter(this.glProgram, gl.ACTIVE_UNIFORMS);
for( var i = 0; i < total; ++i) {
//WebGLActiveInfo = { GLint: size, GLenum: type, DOMString: name};
var activeInfo = gl.getActiveUniform(this.glProgram, i);
var slot = gl.getUniformLocation(this.glProgram, activeInfo.name);
this.uniforms[activeInfo.name] = {
"slot" : slot,
"size" : activeInfo.size,
"type" : this.typeToString[activeInfo.type],
"name" : activeInfo.name,
"info" : activeInfo
};
console.debug(this.uniforms[activeInfo.name]);
}
}
ShaderProgram.prototype.initShaderWithSource = function(fsSource, vsSource) {
var gl = this.gl;
this.fragShaderID = this.compileShaderType(fsSource, gl.FRAGMENT_SHADER);
this.vertShaderID = this.compileShaderType(vsSource, gl.VERTEX_SHADER);
//var shaderProgram = gl.createProgram();
this.glProgram = gl.createProgram();
gl.attachShader(this.glProgram, this.vertShaderID);
gl.attachShader(this.glProgram, this.fragShaderID);
gl.linkProgram(this.glProgram);
if (!gl.getProgramParameter(this.glProgram, gl.LINK_STATUS)) {
alert("Could not initialise shaders");
throw ("program failed to link:" + gl.getProgramInfoLog (this.glProgram));
}
console.debug("linked shader");
this.setupAttributesAndUniforms();
this.ready = true;
};
ShaderProgram.prototype.initShader = function(fragment_shadername, vertex_shadername) {
var gl = this.gl;
this.fragShaderID = this.getShader(fragment_shadername);
this.vertShaderID = this.getShader(vertex_shadername);
//var shaderProgram = gl.createProgram();
this.glProgram = gl.createProgram();
gl.attachShader(this.glProgram, this.vertShaderID);
gl.attachShader(this.glProgram, this.fragShaderID);
gl.linkProgram(this.glProgram);
if (!gl.getProgramParameter(this.glProgram, gl.LINK_STATUS)) {
alert("Could not initialise shaders");
throw ("program failed to link:" + gl.getProgramInfoLog (this.glProgram));
}
console.debug("linked shader");
this.setupAttributesAndUniforms();
this.ready = true;
};
ShaderProgram.prototype.setupAttributesAndUniforms = function(){
gl.useProgram(this.glProgram);
this.cacheUniformData();
this.cacheAttributeData();
/*
//DEPRECATED:
//TODO: remove the following way of storing attributes
this.vertexPositionAttribute =
gl.getAttribLocation(this.glProgram, "aVertexPosition");
gl.enableVertexAttribArray(this.vertexPositionAttribute);
this.vertexNormalAttribute =
gl.getAttribLocation(this.glProgram, "aVertexNormal");
gl.enableVertexAttribArray(this.vertexNormalAttribute);
this.vertexUVAttribute =
gl.getAttribLocation(this.glProgram, "aVertexUV");
gl.enableVertexAttribArray(this.vertexUVAttribute);
this.vertexTangentAttribute =
gl.getAttribLocation(this.glProgram, "aVertexTangent");
gl.enableVertexAttribArray(this.vertexTangentAttribute);
this.vertexColorAttribute =
gl.getAttribLocation(this.glProgram, "aVertexColor");
gl.enableVertexAttribArray(this.vertexColorAttribute);
*/
//---------------------------------------------------------------------------
// Uniforms
//---------------------------------------------------------------------------
this.pMatrixUniform =gl.getUniformLocation(this.glProgram,
"uPMatrix");
this.mvMatrixUniform =gl.getUniformLocation(this.glProgram,
"uMVMatrix");
this.mInverse =gl.getUniformLocation(this.glProgram,
"uInverse");
this.mInverseTranspose =gl.getUniformLocation(this.glProgram,
"uInverseTranspose");
this.texture01 =gl.getUniformLocation(this.glProgram,
"uTexture01");
this.texture02 =gl.getUniformLocation(this.glProgram,
"uTexture02");
this.time =gl.getUniformLocation(this.glProgram,
"uTime");
};
ShaderProgram.prototype.bind = function(mesh){
if(this.ready == false) return;
var gl = this.gl;
gl.useProgram(this.glProgram);
this.bindMeshAttributes(mesh);
/*
gl.bindBuffer(gl.ARRAY_BUFFER, mesh.vertexBuffer);
gl.vertexAttribPointer(
this.vertexPositionAttribute,
mesh.positionElementCount,
gl.FLOAT,
false,
mesh.strideBytes,
mesh.positionOffset
);
gl.vertexAttribPointer(
this.vertexNormalAttribute,
mesh.normalElementCount,
gl.FLOAT,
false,
mesh.strideBytes,
mesh.normalOffset
);
gl.vertexAttribPointer(
this.vertexUVAttribute,
mesh.uvElementCount,
gl.FLOAT,
false,
mesh.strideBytes,
mesh.uvOffset
);
gl.vertexAttribPointer(
this.vertexTangentAttribute,
mesh.tangentElementCount,
gl.FLOAT,
false,
mesh.strideBytes,
mesh.tangentOffset
);
gl.vertexAttribPointer(
this.vertexColorAttribute,
mesh.colorElementCount,
gl.FLOAT,
false,
mesh.strideBytes,
mesh.colorOffset
);
*/
};
//DEPRECATED: uniforms are now split between model and renderer
//TODO: CHANGE HARD CODED UNIFORM NAMES TO AN ARRAY OF NAMES PASSED IN.
//Need to add the type so the correct uniform call is made
ShaderProgram.prototype.setUniforms = function(mv, mInverse, mInverseTranspose, p, pTime) {
var gl = this.gl;
var uniformInfo;
uniformInfo = this.uniforms["uPMatrix"];
if(uniformInfo != null){
gl.uniformMatrix4fv(uniformInfo.slot, false, p);
}
uniformInfo = this.uniforms["uMVMatrix"];
if(uniformInfo != null){
gl.uniformMatrix4fv(uniformInfo.slot, false, mv);
}
uniformInfo = this.uniforms["uInverse"];
if(uniformInfo != null){
gl.uniformMatrix4fv(uniformInfo.slot, false, mInverse);
}
uniformInfo = this.uniforms["uInverseTranspose"];
if(uniformInfo != null){
gl.uniformMatrix4fv(uniformInfo.slot, false, mInverseTranspose);
}
uniformInfo = this.uniforms["uTexture01"];
if(uniformInfo != null){
gl.uniform1i(uniformInfo.slot, 0);
}
uniformInfo = this.uniforms["uTexture02"];
if(uniformInfo != null){
gl.uniform1i(uniformInfo.slot, 1);
}
uniformInfo = this.uniforms["uTime"];
if(uniformInfo != null){
gl.uniform1f(uniformInfo.slot, pTime);
}
};
//TODO: CHANGE HARD CODED UNIFORM NAMES TO AN ARRAY OF NAMES PASSED IN.
//Need to add the type so the correct uniform call is made
ShaderProgram.prototype.setRendererUniforms = function(renderer) {
var gl = this.gl;
var uniformInfo;
uniformInfo = this.uniforms["uCameraMatrix"];
if(uniformInfo != null){
gl.uniformMatrix4fv(uniformInfo.slot, false, renderer.currentCamera.transform.matrix.m);
}
uniformInfo = this.uniforms["uViewMatrix"];
if(uniformInfo != null){
gl.uniformMatrix4fv(uniformInfo.slot, false, renderer.currentCamera.transform.inverse.m);
}
uniformInfo = this.uniforms["uLightMatrix"];
if(uniformInfo != null){
gl.uniformMatrix4fv(uniformInfo.slot, false, renderer.currentLight.transform.matrix.m);
}
uniformInfo = this.uniforms["uLightViewMatrix"];
if(uniformInfo != null){
gl.uniformMatrix4fv(uniformInfo.slot, false, renderer.currentLight.transform.inverse.m);
}
uniformInfo = this.uniforms["uLightProjectionMatrix"];
if(uniformInfo != null){
gl.uniformMatrix4fv(uniformInfo.slot, false, renderer.currentLight.projection.m);
}
uniformInfo = this.uniforms["uLightPosition"];
if(uniformInfo != null){
gl.uniform3f(
uniformInfo.slot,
renderer.currentLight.transform.position.x,
renderer.currentLight.transform.position.y,
renderer.currentLight.transform.position.z
);
}
uniformInfo = this.uniforms["uRenderFromLight"];
if(uniformInfo != null){
gl.uniform1f(uniformInfo.slot, renderer.renderFromLight);
}
uniformInfo = this.uniforms["uPMatrix"];
if(uniformInfo != null){
gl.uniformMatrix4fv(uniformInfo.slot, false, renderer.currentCamera.projection.m);
}
uniformInfo = this.uniforms["uTime"];
if(uniformInfo != null){
gl.uniform1f(uniformInfo.slot, renderer.currTime);
}
uniformInfo = this.uniforms["uMouseLocation"];
if(uniformInfo != null){
gl.uniform2f(uniformInfo.slot, renderer.mousePos.x, renderer.mousePos.y);
}
uniformInfo = this.uniforms["uMouseRadius"];
if(uniformInfo != null){
gl.uniform1f(uniformInfo.slot, renderer.mouseRadius);
}
uniformInfo = this.uniforms["uMouseDown"];
if(uniformInfo != null){
gl.uniform1f(uniformInfo.slot, renderer.mouseDown);
}
uniformInfo = this.uniforms["uMouseUp"];
if(uniformInfo != null){
gl.uniform1f(uniformInfo.slot, renderer.mouseUp);
}
uniformInfo = this.uniforms["uShadowMap"];
if(uniformInfo != null){
gl.uniform1i(uniformInfo.slot, 2);
}
};
//TODO: CHANGE HARD CODED UNIFORM NAMES TO AN ARRAY OF NAMES PASSED IN.
//Need to add the type so the correct uniform call is made
ShaderProgram.prototype.setModelUniforms = function(model) {
var gl = this.gl;
var uniformInfo;
uniformInfo = this.uniforms["uMVMatrix"];
if(uniformInfo != null){
gl.uniformMatrix4fv(uniformInfo.slot, false, model.transform.matrix.m);
}
uniformInfo = this.uniforms["uInverse"];
if(uniformInfo != null){
gl.uniformMatrix4fv(uniformInfo.slot, false, model.transform.inverse.m);
}
uniformInfo = this.uniforms["uInverseTranspose"];
if(uniformInfo != null){
gl.uniformMatrix4fv(uniformInfo.slot, false, model.transform.inverseTranspose.m);
}
uniformInfo = this.uniforms["uTexture01"];
if(uniformInfo != null){
gl.uniform1i(uniformInfo.slot, 0);
}
uniformInfo = this.uniforms["uTexture02"];
if(uniformInfo != null){
gl.uniform1i(uniformInfo.slot, 1);
}
};
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
ShaderProgram.prototype.setUniform1i = function(name, val) {
uniformInfo = this.uniforms[name];
if(uniformInfo != null){
gl.uniform1i(uniformInfo.slot, val);
}
};
ShaderProgram.prototype.setUniform2i = function(name, val1, val2) {
uniformInfo = this.uniforms[name];
if(uniformInfo != null){
gl.uniform2i(uniformInfo.slot, val1, val2);
}
};
ShaderProgram.prototype.setUniform3i = function(name, val1, val2, val3) {
uniformInfo = this.uniforms[name];
if(uniformInfo != null){
gl.uniform3i(uniformInfo.slot, val1, val2, val3);
}
};
ShaderProgram.prototype.setUniform4i = function(name, val1, val2, val3, val4) {
uniformInfo = this.uniforms[name];
if(uniformInfo != null){
gl.uniform4i(uniformInfo.slot, val1, val2, val3, val4);
}
};
//-----------------------------------------------------------------------------
ShaderProgram.prototype.setUniform1iv = function(name, count, arr) {
uniformInfo = this.uniforms[name];
if(uniformInfo != null){
gl.uniform1iv(uniformInfo.slot, count, arr);
}
};
ShaderProgram.prototype.setUniform2iv = function(name, count, arr) {
uniformInfo = this.uniforms[name];
if(uniformInfo != null){
gl.uniform2iv(uniformInfo.slot, count, arr);
}
};
ShaderProgram.prototype.setUniform3iv = function(name, count, arr) {
uniformInfo = this.uniforms[name];
if(uniformInfo != null){
gl.uniform3iv(uniformInfo.slot, count, arr);
}
};
ShaderProgram.prototype.setUniform4iv = function(name, count, arr) {
uniformInfo = this.uniforms[name];
if(uniformInfo != null){
gl.uniform4iv(uniformInfo.slot, count, arr);
}
};
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
ShaderProgram.prototype.setUniform1f = function(name, val) {
uniformInfo = this.uniforms[name];
if(uniformInfo != null){
gl.uniform1f(uniformInfo.slot, val);
}
};
ShaderProgram.prototype.setUniform2f = function(name, val1, val2) {
uniformInfo = this.uniforms[name];
if(uniformInfo != null){
gl.uniform2f(uniformInfo.slot, val1, val2);
}
};
ShaderProgram.prototype.setUniform3f = function(name, val1, val2, val3) {
uniformInfo = this.uniforms[name];
if(uniformInfo != null){
gl.uniform3f(uniformInfo.slot, val1, val2, val3);
}
};
ShaderProgram.prototype.setUniform4f = function(name, val1, val2, val3, val4) {
uniformInfo = this.uniforms[name];
if(uniformInfo != null){
gl.uniform4f(uniformInfo.slot, val1, val2, val3, val4);
}
};
//-----------------------------------------------------------------------------
ShaderProgram.prototype.setUniform1fv = function(name, count, arr) {
uniformInfo = this.uniforms[name];
if(uniformInfo != null){
gl.uniform1fv(uniformInfo.slot, count, arr);
}
};
ShaderProgram.prototype.setUniform2fv = function(name, count, arr) {
uniformInfo = this.uniforms[name];
if(uniformInfo != null){
gl.uniform2fv(uniformInfo.slot, count, arr);
}
};
ShaderProgram.prototype.setUniform3fv = function(name, count, arr) {
uniformInfo = this.uniforms[name];
if(uniformInfo != null){
gl.uniform3fv(uniformInfo.slot, count, arr);
}
};
ShaderProgram.prototype.setUniform4fv = function(name, count, arr) {
uniformInfo = this.uniforms[name];
if(uniformInfo != null){
gl.uniform4fv(uniformInfo.slot, count, arr);
}
};
//-----------------------------------------------------------------------------
ShaderProgram.prototype.setUniformMatrix2fv = function(name, mtx) {
uniformInfo = this.uniforms[name];
if(uniformInfo != null){
gl.uniformMatrix2fv(uniformInfo.slot, false, mtx);
}
};
ShaderProgram.prototype.setUniformMatrix3fv = function(name, mtx) {
uniformInfo = this.uniforms[name];
if(uniformInfo != null){
gl.uniformMatrix3fv(uniformInfo.slot, false, mtx);
}
};
ShaderProgram.prototype.setUniformMatrix4fv = function(name, mtx) {
uniformInfo = this.uniforms[name];
if(uniformInfo != null){
gl.uniformMatrix4fv(uniformInfo.slot, false, mtx);
}
};
|
var expect = require('chai').expect;
var breezeSequelize = require("breeze-sequelize");
// Don't use this
// var breeze = require('breeze-client');
// Use this
var testFns = require('./testFns.js');
var breeze = testFns.breeze;
var SequelizeManager = breezeSequelize.SequelizeManager;
var SequelizeSaveHandler = breezeSequelize.SequelizeSaveHandler;
describe("SaveHandler", function () {
this.enableTimeouts(false);
var _ms, _em, _sm;
before(function () {
_em = testFns.newEm();
_ms = _em.metadataStore;
_sm = new SequelizeManager(testFns.dbConfigNw);
_sm.importMetadata(testFns.getMetadata());
});
it("should be able to save a new Customer", function (done) {
var guid = breeze.core.getUuid();
var cust = { CustomerID: guid, CompanyName: "NewCo", entityAspect: {
entityTypeName: "Customer:#Foo", entityState: "Added" }};
var request = { body: { entities: [cust], saveOptions: {} }};
var handler = new SequelizeSaveHandler(_sm, request);
handler.save().then(r => {
expect(r.message).to.be.undefined;
var entities = r.entities;
expect(entities).to.have.length(1);
var rcust = entities[0];
expect(rcust.CustomerID).to.equal(guid);
expect(rcust.CompanyName).to.equal("NewCo");
}).then(done, done);
});
var custOrderPayload = {"entities":[
{"OrderID":10351,"CustomerID":"042a91cd-9d3e-4576-8200-e33c3dd8ec82","EmployeeID":1,"OrderDate":"1996-11-11T00:00:00.000Z","RequiredDate":"1996-12-09T00:00:00.000Z","ShippedDate":"1996-11-20T00:00:00.000Z","Freight":162.33,"ShipName":"Ernst Handel","ShipAddress":"Kirchgasse 6","ShipCity":"Graz","ShipRegion":null,"ShipPostalCode":"8010","ShipCountry":"Austria","RowVersion":0,
"entityAspect":{"entityTypeName":"Order:#Foo","defaultResourceName":"Orders","entityState":"Modified","originalValuesMap":{"CustomerID":"a3246674-7989-415b-93ec-59c1c8dbe320"},"autoGeneratedKey":{"propertyName":"OrderID","autoGeneratedKeyType":"Identity"}}},
{"CustomerID":"042a91cd-9d3e-4576-8200-e33c3dd8ec82","CustomerID_OLD":null,"CompanyName":"Test_compName","ContactName":null,"ContactTitle":null,"Address":null,"City":null,"Region":null,"PostalCode":null,"Country":null,"Phone":null,"Fax":null,"RowVersion":null,
"entityAspect":{"entityTypeName":"Customer:#Foo","defaultResourceName":"Customers","entityState":"Added","originalValuesMap":{},"autoGeneratedKey":{"propertyName":"CustomerID","autoGeneratedKeyType":"Identity"}}}],"saveOptions":{}}
it("should be able to save a new Customer and change an Order", function (done) {
var request = { body: custOrderPayload };
var handler = new SequelizeSaveHandler(_sm, request);
handler.save().then(r => {
expect(r.message).to.be.undefined;
var entities = r.entities;
expect(entities).to.have.length(2);
}).then(done, done);
});
}); |
Subsets and Splits