code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
const TYPE_NUMBER = 'number'; export function isNumber(value: unknown): value is number { return typeof value === TYPE_NUMBER || value instanceof Number; }
rumble-charts/rumble-charts
src/helpers/isNumber.ts
TypeScript
mit
161
// module of common directives, filters, etc namespace common { 'use strict'; angular .module('common', []); }
yellownoggin/dkindred
src/client/app/common/common.module.ts
TypeScript
mit
128
/** * Description : This is a test suite that tests an LRS endpoint based on the testing requirements document * found at https://github.com/adlnet/xAPI_LRS_Test/blob/master/TestingRequirements.md * * https://github.com/adlnet/xAPI_LRS_Test/blob/master/TestingRequirements.md * */ (function (module) { "use strict"; // defines overwriting data var INVALID_DATE = '01/011/2015'; var INVALID_NUMERIC = 12345; var INVALID_OBJECT = {key: 'should fail'}; var INVALID_STRING = 'should fail'; var INVALID_UUID_TOO_MANY_DIGITS = 'AA97B177-9383-4934-8543-0F91A7A028368'; var INVALID_UUID_INVALID_LETTER = 'MA97B177-9383-4934-8543-0F91A7A02836'; var INVALID_VERSION_0_9_9 = '0.9.9'; var INVALID_VERSION_1_1_0 = '1.1.0'; var VALID_EXTENSION = {extensions: {'http://example.com/null': null}}; var VALID_VERSION_1_0 = '1.0'; var VALID_VERSION_1_0_9 = '1.0.9'; // configures tests module.exports.config = function () { return [ { name: 'Statements Verify Templates', config: [ { name: 'should pass statement template', templates: [ {statement: '{{statements.default}}'}, {timestamp: '2013-05-18T05:32:34.804Z'} ], expect: [200] } ] }, { name: 'A Statement contains an "actor" property (Multiplicity, 4.1.b)', config: [ { name: 'statement "actor" missing', templates: [ {statement: '{{statements.no_actor}}'} ], expect: [400] } ] }, { name: 'A Statement contains a "verb" property (Multiplicity, 4.1.b)', config: [ { name: 'statement "verb" missing', templates: [ {statement: '{{statements.no_verb}}'} ], expect: [400] } ] }, { name: 'A Statement contains an "object" property (Multiplicity, 4.1.b)', config: [ { name: 'statement "object" missing', templates: [ {statement: '{{statements.no_object}}'} ], expect: [400] } ] }, { name: 'A Statement\'s "id" property is a String (Type, 4.1.1.description.a)', config: [ { name: 'statement "id" invalid numeric', templates: [ {statement: '{{statements.default}}'}, {id: INVALID_NUMERIC} ], expect: [400] }, { name: 'statement "id" invalid object', templates: [ {statement: '{{statements.default}}'}, {id: INVALID_OBJECT} ], expect: [400] } ] }, { name: 'A Statement\'s "id" property is a UUID following RFC 4122 (Syntax, RFC 4122)', config: [ { name: 'statement "id" invalid UUID with too many digits', templates: [ {statement: '{{statements.default}}'}, {id: INVALID_UUID_TOO_MANY_DIGITS} ], expect: [400] }, { name: 'statement "id" invalid UUID with non A-F', templates: [ {statement: '{{statements.default}}'}, {id: INVALID_UUID_INVALID_LETTER} ], expect: [400] } ] }, { name: 'A TimeStamp is defined as a Date/Time formatted according to ISO 8601 (Format, ISO8601)', config: [ { name: 'statement "template" invalid string', templates: [ {statement: '{{statements.default}}'}, {timestamp: INVALID_STRING} ], expect: [400] }, { name: 'statement "template" invalid date', templates: [ {statement: '{{statements.default}}'}, {timestamp: INVALID_DATE} ], expect: [400] } ] }, { name: 'A "timestamp" property is a TimeStamp (Type, 4.1.2.1.table1.row7.a, 4.1.2.1.table1.row7.b)', config: [ { name: 'statement "template" invalid string', templates: [ {statement: '{{statements.default}}'}, {timestamp: INVALID_STRING} ], expect: [400] }, { name: 'statement "template" invalid date', templates: [ {statement: '{{statements.default}}'}, {timestamp: INVALID_DATE} ], expect: [400] } ] }, { name: 'A "stored" property is a TimeStamp (Type, 4.1.2.1.table1.row8.a, 4.1.2.1.table1.row8.b)', config: [ { name: 'statement "stored" invalid string', templates: [ {statement: '{{statements.default}}'}, {stored: INVALID_STRING} ], expect: [400] }, { name: 'statement "stored" invalid date', templates: [ {statement: '{{statements.default}}'}, {stored: INVALID_DATE} ], expect: [400] } ] }, { name: 'A "version" property enters the LRS with the value of "1.0.0" or is not used (Vocabulary, 4.1.10.e, 4.1.10.f)', config: [ { name: 'statement "version" invalid string', templates: [ {statement: '{{statements.default}}'}, {version: INVALID_STRING} ], expect: [400] }, { name: 'statement "version" invalid', templates: [ {statement: '{{statements.default}}'}, {version: INVALID_VERSION_0_9_9} ], expect: [400] } ] }, { name: 'An LRS rejects with error code 400 Bad Request any Statement having a property whose value is set to "null", except in an "extensions" property (4.1.12.d.a)', config: [ { name: 'statement actor should fail on "null"', templates: [ {statement: '{{statements.actor}}'}, {actor: '{{agents.mbox}}'}, {name: null} ], expect: [400] }, { name: 'statement verb should fail on "null"', templates: [ {statement: '{{statements.verb}}'}, {verb: '{{verbs.default}}'}, {display: {'en-US': null}} ], expect: [400] }, { name: 'statement context should fail on "null"', templates: [ {statement: '{{statements.context}}'}, {context: '{{contexts.default}}'}, {registration: null} ], expect: [400] }, { name: 'statement object should fail on "null"', templates: [ {statement: '{{statements.object_activity}}'}, {object: '{{activities.default}}'}, {definition: {moreInfo: null}} ], expect: [400] }, { name: 'statement activity extensions can be empty', templates: [ {statement: '{{statements.object_activity}}'}, {object: '{{activities.no_extensions}}'}, {definition: VALID_EXTENSION} ], expect: [200] }, { name: 'statement result extensions can be empty', templates: [ {statement: '{{statements.result}}'}, {result: '{{results.no_extensions}}'}, VALID_EXTENSION ], expect: [200] }, { name: 'statement context extensions can be empty', templates: [ {statement: '{{statements.context}}'}, {context: '{{contexts.no_extensions}}'}, VALID_EXTENSION ], expect: [200] }, { name: 'statement substatement activity extensions can be empty', templates: [ {statement: '{{statements.object_substatement}}'}, {object: '{{substatements.activity}}'}, {object: '{{activities.no_extensions}}'}, {definition: VALID_EXTENSION} ], expect: [200] }, { name: 'statement substatement result extensions can be empty', templates: [ {statement: '{{statements.object_substatement}}'}, {object: '{{substatements.result}}'}, {result: '{{results.no_extensions}}'}, VALID_EXTENSION ], expect: [200] }, { name: 'statement substatement context extensions can be empty', templates: [ {statement: '{{statements.object_substatement}}'}, {object: '{{substatements.context}}'}, {context: '{{contexts.no_extensions}}'}, VALID_EXTENSION ], expect: [200] } ] }, { name: 'An LRS rejects with error code 400 Bad Request, a Request which uses "version" and has the value set to anything but "1.0" or "1.0.x", where x is the semantic versioning number (Format, 4.1.10.b, 6.2.c, 6.2.f)', config: [ { name: 'statement "version" valid 1.0', templates: [ {statement: '{{statements.default}}'}, {version: VALID_VERSION_1_0} ], expect: [200] }, { name: 'statement "version" valid 1.0.9', templates: [ {statement: '{{statements.default}}'}, {version: VALID_VERSION_1_0_9} ], expect: [200] }, { name: 'statement "version" invalid 0.9.9', templates: [ {statement: '{{statements.default}}'}, {version: INVALID_VERSION_0_9_9} ], expect: [400] }, { name: 'statement "version" invalid 1.1.0', templates: [ {statement: '{{statements.default}}'}, {version: INVALID_VERSION_1_1_0} ], expect: [400] } ] }, { name: 'An LRS rejects with error code 400 Bad Request, a Request which the "X-Experience-API-Version" header\'s value is anything but "1.0" or "1.0.x", where x is the semantic versioning number to any API except the About API (Format, 6.2.d, 6.2.e, 6.2.f, 7.7.f)', config: [ { name: 'statement "version" valid 1.0', templates: [ {statement: '{{statements.default}}'}, {version: VALID_VERSION_1_0} ], expect: [200] }, { name: 'statement "version" valid 1.0.9', templates: [ {statement: '{{statements.default}}'}, {version: VALID_VERSION_1_0_9} ], expect: [200] }, { name: 'statement "version" invalid 0.9.9', templates: [ {statement: '{{statements.default}}'}, {version: INVALID_VERSION_0_9_9} ], expect: [400] }, { name: 'statement "version" invalid 1.1.0', templates: [ {statement: '{{statements.default}}'}, {version: INVALID_VERSION_1_1_0} ], expect: [400] } ] }, { name: 'An LRS rejects with error code 400 Bad Request any Statement violating a Statement Requirement. (4.1.12, Varies)', config: [ { name: 'statement "actor" missing reply 400', templates: [ {statement: '{{statements.no_actor}}'} ], expect: [400] }, { name: 'statement "verb" missing reply 400', templates: [ {statement: '{{statements.no_verb}}'} ], expect: [400] }, { name: 'statement "object" missing reply 400', templates: [ {statement: '{{statements.no_object}}'} ], expect: [400] } ] } ]; }; }(module));
cr8onski/lrs-conformance-test-suite
test/v1_0_2/configs/statements.js
JavaScript
mit
16,935
package creditnote import ( "testing" assert "github.com/stretchr/testify/require" stripe "github.com/stripe/stripe-go/v72" _ "github.com/stripe/stripe-go/v72/testing" ) func TestCreditNoteGet(t *testing.T) { cn, err := Get("cn_123", nil) assert.Nil(t, err) assert.NotNil(t, cn) } func TestCreditNoteList(t *testing.T) { params := &stripe.CreditNoteListParams{ Invoice: stripe.String("in_123"), } i := List(params) // Verify that we can get at least one credit note assert.True(t, i.Next()) assert.Nil(t, i.Err()) assert.NotNil(t, i.CreditNote()) assert.NotNil(t, i.CreditNoteList()) } func TestCreditNoteListLines(t *testing.T) { i := ListLines(&stripe.CreditNoteLineItemListParams{ ID: stripe.String("cn_123"), }) // Verify that we can get at least one invoice assert.True(t, i.Next()) assert.Nil(t, i.Err()) assert.NotNil(t, i.CreditNoteLineItem()) assert.NotNil(t, i.CreditNoteLineItemList()) } func TestCreditNoteListPreviewLines(t *testing.T) { params := &stripe.CreditNoteLineItemListPreviewParams{ Invoice: stripe.String("in_123"), Lines: []*stripe.CreditNoteLineParams{ { Type: stripe.String(string(stripe.CreditNoteLineItemTypeInvoiceLineItem)), Amount: stripe.Int64(100), InvoiceLineItem: stripe.String("ili_123"), TaxRates: stripe.StringSlice([]string{ "txr_123", }), }, }, } i := ListPreviewLines(params) // Verify that we can get at least one invoice assert.True(t, i.Next()) assert.Nil(t, i.Err()) assert.NotNil(t, i.CreditNoteLineItem()) } func TestCreditNoteNew(t *testing.T) { params := &stripe.CreditNoteParams{ Amount: stripe.Int64(100), Invoice: stripe.String("in_123"), Reason: stripe.String(string(stripe.CreditNoteReasonDuplicate)), Lines: []*stripe.CreditNoteLineParams{ { Type: stripe.String(string(stripe.CreditNoteLineItemTypeInvoiceLineItem)), Amount: stripe.Int64(100), InvoiceLineItem: stripe.String("ili_123"), TaxRates: stripe.StringSlice([]string{ "txr_123", }), }, }, } cn, err := New(params) assert.Nil(t, err) assert.NotNil(t, cn) } func TestCreditNoteUpdate(t *testing.T) { params := &stripe.CreditNoteParams{ Params: stripe.Params{ Metadata: map[string]string{ "foo": "bar", }, }, } cn, err := Update("cn_123", params) assert.Nil(t, err) assert.NotNil(t, cn) } func TestCreditNotePreview(t *testing.T) { params := &stripe.CreditNotePreviewParams{ Amount: stripe.Int64(100), Invoice: stripe.String("in_123"), Lines: []*stripe.CreditNoteLineParams{ { Type: stripe.String(string(stripe.CreditNoteLineItemTypeInvoiceLineItem)), Amount: stripe.Int64(100), InvoiceLineItem: stripe.String("ili_123"), TaxRates: stripe.StringSlice([]string{ "txr_123", }), }, }, } cn, err := Preview(params) assert.Nil(t, err) assert.NotNil(t, cn) } func TestCreditNoteVoidCreditNote(t *testing.T) { params := &stripe.CreditNoteVoidParams{} cn, err := VoidCreditNote("cn_123", params) assert.Nil(t, err) assert.NotNil(t, cn) }
stripe/stripe-go
creditnote/client_test.go
GO
mit
3,100
<?php namespace BackOffice\RO\ReservationBundle\DependencyInjection; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; /** * This is the class that validates and merges configuration from your app/config files * * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class} */ class Configuration implements ConfigurationInterface { /** * {@inheritdoc} */ public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $rootNode = $treeBuilder->root('reservation'); // Here you should define the parameters that are allowed to // configure your bundle. See the documentation linked above for // more information on that topic. return $treeBuilder; } }
ramisg85/oueslatirami
src/BackOffice/RO/ReservationBundle/DependencyInjection/Configuration.php
PHP
mit
891
CatarsePaypalExpress::Engine.routes.draw do resources :paypal_express, only: [], path: 'payment/paypal_express' do collection do post :ipn end member do get :review match :pay match :success match :cancel end end end
MHBA/catarse_paypal_express
config/routes.rb
Ruby
mit
271
package com.symbolplay.tria.game; public final class CollisionEffects { public static final int JUMP_BOOST = 0; public static final int REPOSITION_PLATFORMS = 1; public static final int VISIBLE_ON_JUMP = 2; public static final int IMPALE_ATTACHED_SPIKES = 3; public static final int REVEAL_ON_JUMP = 4; public static final int IMPALE_SPIKES = 5; public static final int TOGGLE_SPIKES = 6; private static final int NUM_EFFECTS = 7; private final boolean effects[]; private final Object effectData[]; private final JumpBoostCollisionEffectData jumpBoostCollisionEffectData; private final RevealOnJumpCollisionEffectData revealOnJumpCollisionEffectData; public CollisionEffects() { effects = new boolean[NUM_EFFECTS]; effectData = new Object[NUM_EFFECTS]; jumpBoostCollisionEffectData = new JumpBoostCollisionEffectData(); revealOnJumpCollisionEffectData = new RevealOnJumpCollisionEffectData(); } public void clear() { for (int i = 0; i < NUM_EFFECTS; i++) { effects[i] = false; } } public void set(int effect) { set(effect, 0.0f); } public void set(int effect, Object data) { effects[effect] = true; effectData[effect] = data; } public void setJumpBoostEffect(float speed, float soundVolume) { effects[JUMP_BOOST] = true; jumpBoostCollisionEffectData.jumpBoostSpeed = speed; jumpBoostCollisionEffectData.soundVolume = soundVolume; effectData[JUMP_BOOST] = jumpBoostCollisionEffectData; } public void setRevealOnJumpEffect(int[] revealOnJumpIds) { effects[REVEAL_ON_JUMP] = true; revealOnJumpCollisionEffectData.revealOnJumpIds = revealOnJumpIds; effectData[REVEAL_ON_JUMP] = revealOnJumpCollisionEffectData; } public boolean isEffectActive(int effect) { return effects[effect]; } public Object getEffectData(int effect) { return effectData[effect]; } }
mrzli/tria
core/src/com/symbolplay/tria/game/CollisionEffects.java
Java
mit
2,103
<?php /* SVN FILE: $Id: cake_test_case.php 7945 2008-12-19 02:16:01Z gwoo $ */ /** * Short description for file. * * Long description for file * * PHP versions 4 and 5 * * CakePHP(tm) Tests <https://trac.cakephp.org/wiki/Developement/TestSuite> * Copyright 2005-2008, Cake Software Foundation, Inc. (http://www.cakefoundation.org) * * Licensed under The Open Group Test Suite License * Redistributions of files must retain the above copyright notice. * * @filesource * @copyright Copyright 2005-2008, Cake Software Foundation, Inc. (http://www.cakefoundation.org) * @link https://trac.cakephp.org/wiki/Developement/TestSuite CakePHP(tm) Tests * @package cake * @subpackage cake.cake.tests.libs * @since CakePHP(tm) v 1.2.0.4667 * @version $Revision: 7945 $ * @modifiedby $LastChangedBy: gwoo $ * @lastmodified $Date: 2008-12-18 21:16:01 -0500 (Thu, 18 Dec 2008) $ * @license http://www.opensource.org/licenses/opengroup.php The Open Group Test Suite License */ if (!class_exists('dispatcher')) { require CAKE . 'dispatcher.php'; } require_once CAKE_TESTS_LIB . 'cake_test_model.php'; require_once CAKE_TESTS_LIB . 'cake_test_fixture.php'; App::import('Vendor', 'simpletest' . DS . 'unit_tester'); /** * Short description for class. * * @package cake * @subpackage cake.cake.tests.lib */ class CakeTestDispatcher extends Dispatcher { var $controller; var $testCase; function testCase(&$testCase) { $this->testCase =& $testCase; } function _invoke (&$controller, $params, $missingAction = false) { $this->controller =& $controller; if (isset($this->testCase) && method_exists($this->testCase, 'startController')) { $this->testCase->startController($this->controller, $params); } $result = parent::_invoke($this->controller, $params, $missingAction); if (isset($this->testCase) && method_exists($this->testCase, 'endController')) { $this->testCase->endController($this->controller, $params); } return $result; } } /** * Short description for class. * * @package cake * @subpackage cake.cake.tests.lib */ class CakeTestCase extends UnitTestCase { /** * Methods used internally. * * @var array * @access private */ var $methods = array('start', 'end', 'startcase', 'endcase', 'starttest', 'endtest'); var $__truncated = true; var $__savedGetData = array(); /** * By default, all fixtures attached to this class will be truncated and reloaded after each test. * Set this to false to handle manually * * @var array * @access public */ var $autoFixtures = true; /** * Set this to false to avoid tables to be dropped if they already exist * * @var boolean * @access public */ var $dropTables = true; /** * Maps fixture class names to fixture identifiers as included in CakeTestCase::$fixtures * * @var array * @access protected */ var $_fixtureClassMap = array(); /** * Called when a test case (group of methods) is about to start (to be overriden when needed.) * * @param string $method Test method about to get executed. * * @access protected */ function startCase() { } /** * Called when a test case (group of methods) has been executed (to be overriden when needed.) * * @param string $method Test method about that was executed. * * @access protected */ function endCase() { } /** * Called when a test case method is about to start (to be overriden when needed.) * * @param string $method Test method about to get executed. * * @access protected */ function startTest($method) { } /** * Called when a test case method has been executed (to be overriden when needed.) * * @param string $method Test method about that was executed. * * @access protected */ function endTest($method) { } /** * Overrides SimpleTestCase::assert to enable calling of skipIf() from within tests */ function assert(&$expectation, $compare, $message = '%s') { if ($this->_should_skip) { return; } return parent::assert($expectation, $compare, $message); } /** * Overrides SimpleTestCase::skipIf to provide a boolean return value */ function skipIf($shouldSkip, $message = '%s') { parent::skipIf($shouldSkip, $message); return $shouldSkip; } /** * Callback issued when a controller's action is about to be invoked through testAction(). * * @param Controller $controller Controller that's about to be invoked. * @param array $params Additional parameters as sent by testAction(). */ function startController(&$controller, $params = array()) { if (isset($params['fixturize']) && ((is_array($params['fixturize']) && !empty($params['fixturize'])) || $params['fixturize'] === true)) { if (!isset($this->db)) { $this->_initDb(); } if ($controller->uses === false) { $list = array($controller->modelClass); } else { $list = is_array($controller->uses) ? $controller->uses : array($controller->uses); } $models = array(); ClassRegistry::config(array('ds' => $params['connection'])); foreach ($list as $name) { if ((is_array($params['fixturize']) && in_array($name, $params['fixturize'])) || $params['fixturize'] === true) { if (class_exists($name) || App::import('Model', $name)) { $object =& ClassRegistry::init($name); //switch back to specified datasource. $object->setDataSource($params['connection']); $db =& ConnectionManager::getDataSource($object->useDbConfig); $db->cacheSources = false; $models[$object->alias] = array( 'table' => $object->table, 'model' => $object->alias, 'key' => strtolower($name), ); } } } ClassRegistry::config(array('ds' => 'test_suite')); if (!empty($models) && isset($this->db)) { $this->_actionFixtures = array(); foreach ($models as $model) { $fixture =& new CakeTestFixture($this->db); $fixture->name = $model['model'] . 'Test'; $fixture->table = $model['table']; $fixture->import = array('model' => $model['model'], 'records' => true); $fixture->init(); $fixture->create($this->db); $fixture->insert($this->db); $this->_actionFixtures[] =& $fixture; } foreach ($models as $model) { $object =& ClassRegistry::getObject($model['key']); if ($object !== false) { $object->setDataSource('test_suite'); $object->cacheSources = false; } } } } } /** * Callback issued when a controller's action has been invoked through testAction(). * * @param Controller $controller Controller that has been invoked. * * @param array $params Additional parameters as sent by testAction(). */ function endController(&$controller, $params = array()) { if (isset($this->db) && isset($this->_actionFixtures) && !empty($this->_actionFixtures)) { foreach ($this->_actionFixtures as $fixture) { $fixture->drop($this->db); } } } /** * Executes a Cake URL, and can get (depending on the $params['return'] value): * * 1. 'result': Whatever the action returns (and also specifies $this->params['requested'] for controller) * 2. 'view': The rendered view, without the layout * 3. 'contents': The rendered view, within the layout. * 4. 'vars': the view vars * * @param string $url Cake URL to execute (e.g: /articles/view/455) * @param array $params Parameters, or simply a string of what to return * @return mixed Whatever is returned depending of requested result * @access public */ function testAction($url, $params = array()) { $default = array( 'return' => 'result', 'fixturize' => false, 'data' => array(), 'method' => 'post', 'connection' => 'default' ); if (is_string($params)) { $params = array('return' => $params); } $params = array_merge($default, $params); $toSave = array( 'case' => null, 'group' => null, 'app' => null, 'output' => null, 'show' => null, 'plugin' => null ); $this->__savedGetData = (empty($this->__savedGetData)) ? array_intersect_key($_GET, $toSave) : $this->__savedGetData; $data = (!empty($params['data'])) ? $params['data'] : array(); if (strtolower($params['method']) == 'get') { $_GET = array_merge($this->__savedGetData, $data); $_POST = array(); } else { $_POST = array('data' => $data); $_GET = $this->__savedGetData; } $return = $params['return']; $params = array_diff_key($params, array('data' => null, 'method' => null, 'return' => null)); $dispatcher =& new CakeTestDispatcher(); $dispatcher->testCase($this); if ($return != 'result') { if ($return != 'contents') { $params['layout'] = false; } ob_start(); @$dispatcher->dispatch($url, $params); $result = ob_get_clean(); if ($return == 'vars') { $view =& ClassRegistry::getObject('view'); $viewVars = $view->getVars(); $result = array(); foreach ($viewVars as $var) { $result[$var] = $view->getVar($var); } if (!empty($view->pageTitle)) { $result = array_merge($result, array('title' => $view->pageTitle)); } } } else { $params['return'] = 1; $params['bare'] = 1; $params['requested'] = 1; $result = @$dispatcher->dispatch($url, $params); } if (isset($this->_actionFixtures)) { unset($this->_actionFixtures); } ClassRegistry::flush(); return $result; } /** * Announces the start of a test. * * @param string $method Test method just started. * * @access public */ function before($method) { parent::before($method); if (isset($this->fixtures) && (!is_array($this->fixtures) || empty($this->fixtures))) { unset($this->fixtures); } // Set up DB connection if (isset($this->fixtures) && strtolower($method) == 'start') { $this->_initDb(); $this->_loadFixtures(); } // Create records if (isset($this->_fixtures) && isset($this->db) && !in_array(strtolower($method), array('start', 'end')) && $this->__truncated && $this->autoFixtures == true) { foreach ($this->_fixtures as $fixture) { $inserts = $fixture->insert($this->db); } } if (!in_array(strtolower($method), $this->methods)) { $this->startTest($method); } } /** * Runs as first test to create tables. * * @access public */ function start() { if (isset($this->_fixtures) && isset($this->db)) { Configure::write('Cache.disable', true); $cacheSources = $this->db->cacheSources; $this->db->cacheSources = false; $sources = $this->db->listSources(); $this->db->cacheSources = $cacheSources; if (!$this->dropTables) { return; } foreach ($this->_fixtures as $fixture) { if (in_array($fixture->table, $sources)) { $fixture->drop($this->db); $fixture->create($this->db); } elseif (!in_array($fixture->table, $sources)) { $fixture->create($this->db); } } } } /** * Runs as last test to drop tables. * * @access public */ function end() { if (isset($this->_fixtures) && isset($this->db)) { if ($this->dropTables) { foreach (array_reverse($this->_fixtures) as $fixture) { $fixture->drop($this->db); } } $this->db->sources(true); Configure::write('Cache.disable', false); } if (class_exists('ClassRegistry')) { ClassRegistry::flush(); } } /** * Announces the end of a test. * * @param string $method Test method just finished. * * @access public */ function after($method) { if (isset($this->_fixtures) && isset($this->db) && !in_array(strtolower($method), array('start', 'end'))) { foreach ($this->_fixtures as $fixture) { $fixture->truncate($this->db); } $this->__truncated = true; } else { $this->__truncated = false; } if (!in_array(strtolower($method), $this->methods)) { $this->endTest($method); } $this->_should_skip = false; parent::after($method); } /** * Gets a list of test names. Normally that will be all internal methods that start with the * name "test". This method should be overridden if you want a different rule. * * @return array List of test names. * * @access public */ function getTests() { $methods = array_diff(parent::getTests(), array('testAction', 'testaction')); $methods = array_merge(array_merge(array('start', 'startCase'), $methods), array('endCase', 'end')); return $methods; } /** * Chooses which fixtures to load for a given test * * @param string $fixture Each parameter is a model name that corresponds to a fixture, i.e. 'Post', 'Author', etc. * @access public * @see CakeTestCase::$autoFixtures */ function loadFixtures() { $args = func_get_args(); foreach ($args as $class) { if (isset($this->_fixtureClassMap[$class])) { $fixture = $this->_fixtures[$this->_fixtureClassMap[$class]]; $fixture->truncate($this->db); $fixture->insert($this->db); } else { trigger_error("Non-existent fixture class {$class} referenced in test", E_USER_WARNING); } } } /** * Takes an array $expected and generates a regex from it to match the provided $string. Samples for $expected: * * Checks for an input tag with a name attribute (contains any value) and an id attribute that contains 'my-input': * array('input' => array('name', 'id' => 'my-input')) * * Checks for two p elements with some text in them: * array( * array('p' => true), * 'textA', * '/p', * array('p' => true), * 'textB', * '/p' * ) * * You can also specify a pattern expression as part of the attribute values, or the tag being defined, * if you prepend the value with preg: and enclose it with slashes, like so: * array( * array('input' => array('name', 'id' => 'preg:/FieldName\d+/')), * 'preg:/My\s+field/' * ) * * Important: This function is very forgiving about whitespace and also accepts any permutation of attribute order. * It will also allow whitespaces between specified tags. * * @param string $string An HTML/XHTML/XML string * @param array $expected An array, see above * @param string $message SimpleTest failure output string * @access public */ function assertTags($string, $expected, $fullDebug = false) { $regex = array(); $normalized = array(); foreach ((array) $expected as $key => $val) { if (!is_numeric($key)) { $normalized[] = array($key => $val); } else { $normalized[] = $val; } } $i = 0; foreach ($normalized as $tags) { $i++; if (is_string($tags) && $tags{0} == '<') { $tags = array(substr($tags, 1) => array()); } elseif (is_string($tags)) { if (preg_match('/^\*?\//', $tags, $match)) { $prefix = array(null, null); if ($match[0] == '*/') { $prefix = array('Anything, ', '.*?'); } $regex[] = array( sprintf('%sClose %s tag', $prefix[0], substr($tags, strlen($match[0]))), sprintf('%s<[\s]*\/[\s]*%s[\s]*>[\n\r]*', $prefix[1], substr($tags, strlen($match[0]))), $i, ); continue; } if (!empty($tags) && preg_match('/^preg\:\/(.+)\/$/i', $tags, $matches)) { $tags = $matches[1]; $type = 'Regex matches'; } else { $tags = preg_quote($tags, '/'); $type = 'Text equals'; } $regex[] = array( sprintf('%s "%s"', $type, $tags), $tags, $i, ); continue; } foreach ($tags as $tag => $attributes) { $regex[] = array( sprintf('Open %s tag', $tag), sprintf('[\s]*<%s', preg_quote($tag, '/')), $i, ); if ($attributes === true) { $attributes = array(); } $attrs = array(); $explanations = array(); foreach ($attributes as $attr => $val) { if (is_numeric($attr) && preg_match('/^preg\:\/(.+)\/$/i', $val, $matches)) { $attrs[] = $matches[1]; $explanations[] = sprintf('Regex "%s" matches', $matches[1]); continue; } else { $quotes = '"'; if (is_numeric($attr)) { $attr = $val; $val = '.+?'; $explanations[] = sprintf('Attribute "%s" present', $attr); } else if (!empty($val) && preg_match('/^preg\:\/(.+)\/$/i', $val, $matches)) { $quotes = '"?'; $val = $matches[1]; $explanations[] = sprintf('Attribute "%s" matches "%s"', $attr, $val); } else { $explanations[] = sprintf('Attribute "%s" == "%s"', $attr, $val); $val = preg_quote($val, '/'); } $attrs[] = '[\s]+'.preg_quote($attr, '/').'='.$quotes.$val.$quotes; } } if ($attrs) { $permutations = $this->__array_permute($attrs); $permutationTokens = array(); foreach ($permutations as $permutation) { $permutationTokens[] = join('', $permutation); } $regex[] = array( sprintf('%s', join(', ', $explanations)), $permutationTokens, $i, ); } $regex[] = array( sprintf('End %s tag', $tag), '[\s]*\/?[\s]*>[\n\r]*', $i, ); } } foreach ($regex as $i => $assertation) { list($description, $expressions, $itemNum) = $assertation; $matches = false; foreach ((array)$expressions as $expression) { if (preg_match(sprintf('/^%s/s', $expression), $string, $match)) { $matches = true; $string = substr($string, strlen($match[0])); break; } } if (!$matches) { $this->assert(new TrueExpectation(), false, sprintf('Item #%d / regex #%d failed: %s', $itemNum, $i, $description)); if ($fullDebug) { debug($string, true); debug($regex, true); } return false; } } return $this->assert(new TrueExpectation(), true, '%s'); } /** * Generates all permutation of an array $items and returns them in a new array. * * @param array $items An array of items * @return array * @access public */ function __array_permute($items, $perms = array()) { static $permuted; if (empty($perms)) { $permuted = array(); } if (empty($items)) { $permuted[] = $perms; } else { $numItems = count($items) - 1; for ($i = $numItems; $i >= 0; --$i) { $newItems = $items; $newPerms = $perms; list($tmp) = array_splice($newItems, $i, 1); array_unshift($newPerms, $tmp); $this->__array_permute($newItems, $newPerms); } return $permuted; } } /** * Initialize DB connection. * * @access protected */ function _initDb() { $testDbAvailable = in_array('test', array_keys(ConnectionManager::enumConnectionObjects())); $_prefix = null; if ($testDbAvailable) { // Try for test DB restore_error_handler(); @$db =& ConnectionManager::getDataSource('test'); set_error_handler('simpleTestErrorHandler'); $testDbAvailable = $db->isConnected(); } // Try for default DB if (!$testDbAvailable) { $db =& ConnectionManager::getDataSource('default'); $_prefix = $db->config['prefix']; $db->config['prefix'] = 'test_suite_'; } ConnectionManager::create('test_suite', $db->config); $db->config['prefix'] = $_prefix; // Get db connection $this->db =& ConnectionManager::getDataSource('test_suite'); $this->db->cacheSources = false; ClassRegistry::config(array('ds' => 'test_suite')); } /** * Load fixtures specified in var $fixtures. * * @access private */ function _loadFixtures() { if (!isset($this->fixtures) || empty($this->fixtures)) { return; } if (!is_array($this->fixtures)) { $this->fixtures = array_map('trim', explode(',', $this->fixtures)); } $this->_fixtures = array(); foreach ($this->fixtures as $index => $fixture) { $fixtureFile = null; if (strpos($fixture, 'core.') === 0) { $fixture = substr($fixture, strlen('core.')); foreach (Configure::corePaths('cake') as $key => $path) { $fixturePaths[] = $path . DS . 'tests' . DS . 'fixtures'; } } elseif (strpos($fixture, 'app.') === 0) { $fixture = substr($fixture, strlen('app.')); $fixturePaths = array( TESTS . 'fixtures', VENDORS . 'tests' . DS . 'fixtures' ); } elseif (strpos($fixture, 'plugin.') === 0) { $parts = explode('.', $fixture, 3); $pluginName = $parts[1]; $fixture = $parts[2]; $fixturePaths = array( APP . 'plugins' . DS . $pluginName . DS . 'tests' . DS . 'fixtures', TESTS . 'fixtures', VENDORS . 'tests' . DS . 'fixtures' ); $pluginPaths = Configure::read('pluginPaths'); foreach ($pluginPaths as $path) { if (file_exists($path . $pluginName . DS . 'tests' . DS. 'fixtures')) { $fixturePaths[0] = $path . $pluginName . DS . 'tests' . DS. 'fixtures'; break; } } } else { $fixturePaths = array( TESTS . 'fixtures', VENDORS . 'tests' . DS . 'fixtures', TEST_CAKE_CORE_INCLUDE_PATH . DS . 'cake' . DS . 'tests' . DS . 'fixtures' ); } foreach ($fixturePaths as $path) { if (is_readable($path . DS . $fixture . '_fixture.php')) { $fixtureFile = $path . DS . $fixture . '_fixture.php'; break; } } if (isset($fixtureFile)) { require_once($fixtureFile); $fixtureClass = Inflector::camelize($fixture) . 'Fixture'; $this->_fixtures[$this->fixtures[$index]] =& new $fixtureClass($this->db); $this->_fixtureClassMap[Inflector::camelize($fixture)] = $this->fixtures[$index]; } } if (empty($this->_fixtures)) { unset($this->_fixtures); } } } ?>
tectronics/fambom
cake/tests/lib/cake_test_case.php
PHP
mit
21,057
#include "ofApp.h" #include "SharedUtils.h" void updatePuppet(Skeleton* skeleton, ofxPuppet& puppet) { for(int i = 0; i < skeleton->size(); i++) { puppet.setControlPoint(skeleton->getControlIndex(i), skeleton->getPositionAbsolute(i)); } } //-------------------------------------------------------------- void ofApp::setup(){ scenes.push_back(new NoneScene(&puppet, &handSkeleton, &immutableHandSkeleton)); scenes.push_back(new WaveScene(&puppet, &handSkeleton, &immutableHandSkeleton)); scenes.push_back(new WiggleScene(&puppet, &handSkeleton, &immutableHandSkeleton)); scenes.push_back(new WobbleScene(&puppet, &handSkeleton, &immutableHandSkeleton)); scenes.push_back(new EqualizeScene(&puppet, &handSkeleton, &immutableHandSkeleton)); scenes.push_back(new NorthScene(&puppet, &handSkeleton, &immutableHandSkeleton)); scenes.push_back(new MeanderScene(&puppet, &handSkeleton, &immutableHandSkeleton)); scenes.push_back(new SinusoidalLengthScene(&puppet, &handSkeleton, &immutableHandSkeleton)); scenes.push_back(new MiddleDifferentLengthScene(&puppet, &handSkeleton, &immutableHandSkeleton)); scenes.push_back(new StartrekScene(&puppet, &handSkeleton, &immutableHandSkeleton)); scenes.push_back(new PropogatingWiggleScene(&puppet, &handWithFingertipsSkeleton, &immutableHandWithFingertipsSkeleton)); scenes.push_back(new PulsatingPalmScene(&puppet, &palmSkeleton, &immutablePalmSkeleton)); scenes.push_back(new RetractingFingersScene(&puppet, &handWithFingertipsSkeleton, &immutableHandWithFingertipsSkeleton)); scenes.push_back(new StraightenFingersScene(&puppet, &handWithFingertipsSkeleton, &immutableHandWithFingertipsSkeleton)); scenes.push_back(new SplayFingersScene(&puppet, &handWithFingertipsSkeleton, &immutableHandWithFingertipsSkeleton)); scenes.push_back(new PropogatingWiggleScene(&puppet, &handWithFingertipsSkeleton, &immutableHandWithFingertipsSkeleton)); scenes.push_back(new SinusoidalWiggleScene(&puppet, &handWithFingertipsSkeleton, &immutableHandWithFingertipsSkeleton)); scenes.push_back(new GrowingMiddleFingerScene(&puppet, &handWithFingertipsSkeleton, &immutableHandWithFingertipsSkeleton)); scenes.push_back(new PinkyPuppeteerScene(&puppet, &handWithFingertipsSkeleton, &immutableHandWithFingertipsSkeleton)); scenes.push_back(new FingerLengthPuppeteerScene(&puppet, &handWithFingertipsSkeleton, &immutableHandWithFingertipsSkeleton)); scenes.push_back(new LissajousScene(&puppet, &threePointSkeleton, &immutableThreePointSkeleton)); sharedSetup(); string basePath = ofToDataPath("", true); ofSetDataPathRoot("../../../../../SharedData2013/"); // for Golan's machine. Don't delete, please! setupGui(); hand.loadImage("hand/genericHandCenteredNew.jpg"); mesh.load("hand/handmarksNew.ply"); for (int i = 0; i < mesh.getNumVertices(); i++) { mesh.addTexCoord(mesh.getVertex(i)); } //---------------------------- // Set up the puppet. puppet.setup(mesh); //---------------------------- // Set up all of the skeletons. previousSkeleton = NULL; currentSkeleton = NULL; handSkeleton.setup(mesh); immutableHandSkeleton.setup(mesh); handWithFingertipsSkeleton.setup(mesh); immutableHandWithFingertipsSkeleton.setup(mesh); palmSkeleton.setup(mesh); immutablePalmSkeleton.setup(mesh); wristSpineSkeleton.setup(mesh); immutableWristSpineSkeleton.setup(mesh); threePointSkeleton.setup(mesh); immutableThreePointSkeleton.setup(mesh); // Initialize gui features mouseControl = false; showImage = true; showWireframe = true; showSkeleton = true; frameBasedAnimation = false; showGuis = true; sceneRadio = 0; } void ofApp::setupGui() { // set up the guis for each scene for (int i=0; i < scenes.size(); i++) { sceneNames.push_back(scenes[i]->getName()); sceneWithSkeletonNames.push_back(scenes[i]->getNameWithSkeleton()); scenes[i]->setupGui(); scenes[i]->setupMouseGui(); } } //-------------------------------------------------------------- void ofApp::update(){ handSkeleton.setup(mesh); immutableHandSkeleton.setup(mesh); // get the current scene int scene = sceneRadio;//getSelection(0); scenes[scene]->update(); setSkeleton(scenes[scene]->getSkeleton()); // update the puppet using the current scene's skeleton updatePuppet(currentSkeleton, puppet); puppet.update(); } //-------------------------------------------------------------- void ofApp::draw(){ ofBackground(0); ofSetColor(255); if (showImage) { hand.bind(); puppet.drawFaces(); hand.unbind(); } if(showWireframe) { puppet.drawWireframe(); puppet.drawControlPoints(); } if(showSkeleton) { currentSkeleton->draw(); } int scene = sceneRadio; scenes[scene]->draw(); } void ofApp::setSkeleton(Skeleton* skeleton) { if(skeleton != currentSkeleton) { previousSkeleton = currentSkeleton; currentSkeleton = skeleton; if(previousSkeleton != NULL) { vector<int>& previousControlIndices = previousSkeleton->getControlIndices(); for(int i = 0; i < previousControlIndices.size(); i++) { puppet.removeControlPoint(previousControlIndices[i]); } } vector<int>& currentControlIndices = currentSkeleton->getControlIndices(); for(int i = 0; i < currentControlIndices.size(); i++) { puppet.setControlPoint(currentControlIndices[i]); } } } //-------------------------------------------------------------- void ofApp::keyPressed(int key){ switch(key){ case OF_KEY_RIGHT : sceneRadio = (sceneRadio+1) % scenes.size(); cout << "scene " << sceneRadio << endl; break; case OF_KEY_LEFT : sceneRadio -=1; if(sceneRadio<0)sceneRadio = scenes.size()-1; cout << "scene " << sceneRadio << endl; break; } } //-------------------------------------------------------------- void ofApp::keyReleased(int key){ } //-------------------------------------------------------------- void ofApp::mouseMoved(int x, int y ){ } //-------------------------------------------------------------- void ofApp::mouseDragged(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mousePressed(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseReleased(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::windowResized(int w, int h){ } //-------------------------------------------------------------- void ofApp::gotMessage(ofMessage msg){ } //-------------------------------------------------------------- void ofApp::dragEvent(ofDragInfo dragInfo){ }
CreativeInquiry/digital_art_2014
MeshTester/src/ofApp.cpp
C++
mit
6,809
<?php namespace Home\Controller; use Think\Controller; class AddressController extends Controller { protected function _initialize () { if (!session('user')) { if (IS_AJAX) { $this->ajaxReturn(['status'=>2, 'info'=>'请登陆之后在执行此操作!']); } else { $this->error('您还没有登陆,没有权限进行此操作!正在跳转到首页...', '/Index/index', 2); } } } public function del () { $address_id = I('post.address_id'); if (D('Address')->where(['address_id' => $address_id])->delete()) { $this->ajaxReturn(['status'=>1, 'info'=>'删除成功!']); } else { $this->ajaxReturn(['status'=>2, 'info'=>'删除失败!']); } } public function add () { $address = D('Address'); $_POST['user_id'] = session('user.user_id'); if($address->create(null, 1)){ $address_id = $address->add(); if ($address_id) { $this->ajaxReturn(['status'=>1, 'info'=>'添加成功!']); } else { $this->ajaxReturn(['status'=>2, 'info'=>'添加失败!']); } } else { $this->ajaxReturn(['status'=>2, 'info'=>$address->getError()]); } } public function edit () { $address = D('Address'); if($address->create(null, 2)){ $address_id = $address->where(['address_id' => I('post.address_id')])->save(); if ($address_id) { $this->ajaxReturn(['status'=>1, 'info'=>'保存成功!']); } else { $this->ajaxReturn(['status'=>2, 'info'=>'保存失败!']); } } else { $this->ajaxReturn(['status'=>2, 'info'=>$address->getError()]); } } public function getForm () { $content = $this->fetch('form'); $this->ajaxReturn(['status'=>1, 'content'=>$content]); } public function setAddress () { $address = D('Address'); $address->where(['user_id' => session('user.user_id'), 'is_default' => 1])->setField('is_default', 0); if ($address->where(['address_id' => I('post.address_id')])->setField('is_default', 1) >= 0) { $this->ajaxReturn(['status'=>1, 'info'=>'设置成功!']); } else { $this->ajaxReturn(['status'=>2, 'info'=>'设置失败!']); } } public function getAddress () { return D('Address')->where(['user_id' => session('user.user_id')])->order('is_default desc')->select(); } }
hookidea/yiwukongjian
Application/Home/Controller/AddressController.class.php
PHP
mit
2,650
public class ENG { }
zacswolf/CompSciProjects
Java (AP CompSci)/Eclipse/RankedGPA/src/ENG.java
Java
mit
23
require "rails_helper" RSpec.describe FormsController do describe "#index" do context "when an application has been started" do it "renders the index page" do current_app = create(:common_application) session[:current_application_id] = current_app.id get :index expect(response).to render_template(:index) end end end describe ".skip?" do it "defaults to false" do expect(FormsController.skip?(double("foo"))).to eq(false) end end describe "#application_title" do context "when no application present yet" do it "returns a string for all programs" do expect(controller.application_title).to eq("Food Assistance + Healthcare Coverage") end end context "when only applying for food assistance" do it "returns Food Assistance" do current_app = create(:common_application, navigator: build(:application_navigator, applying_for_food: true)) session[:current_application_id] = current_app.id expect(controller.application_title).to eq("Food Assistance") end end context "when only applying for healthcare coverage" do it "returns Healthcare Coverage" do current_app = create(:common_application, navigator: build(:application_navigator, applying_for_healthcare: true)) session[:current_application_id] = current_app.id expect(controller.application_title).to eq("Healthcare Coverage") end end context "when only applying for all programs" do it "returns Food Assistance + Healthcare Coverage" do current_app = create(:common_application, navigator: build(:application_navigator, applying_for_healthcare: true, applying_for_food: true)) session[:current_application_id] = current_app.id expect(controller.application_title).to eq("Food Assistance + Healthcare Coverage") end end end end
codeforamerica/michigan-benefits
spec/controllers/forms_controller_spec.rb
Ruby
mit
2,108
import { MutableRefObject, useEffect, useMemo, useState } from 'react'; import { useApi } from '@proton/components'; import { addMilliseconds } from '@proton/shared/lib/date-fns-utc'; import { Calendar as tsCalendar } from '@proton/shared/lib/interfaces/calendar'; import { noop } from '@proton/shared/lib/helpers/function'; import { DAY, MINUTE } from '@proton/shared/lib/constants'; import getCalendarsAlarmsCached from './getCalendarsAlarmsCached'; import { CalendarsAlarmsCache } from './CacheInterface'; const PADDING = 2 * MINUTE; export const getCalendarsAlarmsCache = ({ start = new Date(2000, 1, 1), end = new Date(2000, 1, 1), } = {}): CalendarsAlarmsCache => ({ calendarsCache: {}, start, end, }); const useCalendarsAlarms = ( calendars: tsCalendar[], cacheRef: MutableRefObject<CalendarsAlarmsCache>, lookAhead = 2 * DAY ) => { const api = useApi(); const [forceRefresh, setForceRefresh] = useState<any>(); const calendarIDs = useMemo(() => calendars.map(({ ID }) => ID), [calendars]); useEffect(() => { let timeoutHandle = 0; let unmounted = false; const update = async () => { const now = new Date(); // Cache is invalid if (+cacheRef.current.end - PADDING <= +now) { cacheRef.current = getCalendarsAlarmsCache({ start: now, end: addMilliseconds(now, lookAhead), }); cacheRef.current.rerender = () => setForceRefresh({}); } const promise = getCalendarsAlarmsCached(api, cacheRef.current.calendarsCache, calendarIDs, [ cacheRef.current.start, cacheRef.current.end, ]); cacheRef.current.promise = promise; if (timeoutHandle) { clearTimeout(timeoutHandle); } await promise; // If it's not the latest, ignore if (unmounted || promise !== cacheRef.current.promise) { return; } const delay = Math.max(0, +cacheRef.current.end - PADDING - Date.now()); timeoutHandle = window.setTimeout(() => { update().catch(noop); }, delay); setForceRefresh({}); }; update().catch(noop); cacheRef.current.rerender = () => setForceRefresh({}); return () => { cacheRef.current.rerender = undefined; unmounted = true; clearTimeout(timeoutHandle); }; }, [calendarIDs]); return useMemo(() => { const { calendarsCache } = cacheRef.current; return calendarIDs .map((calendarID) => { return calendarsCache[calendarID]?.result ?? []; }) .flat() .sort((a, b) => { return a.Occurrence - b.Occurrence; }); }, [forceRefresh, calendarIDs]); }; export default useCalendarsAlarms;
ProtonMail/WebClient
applications/calendar/src/app/containers/alarms/useCalendarsAlarms.ts
TypeScript
mit
3,017
class ArrowSprite extends Phaser.Sprite { constructor(game, x, y) { super(game, x, y, 'arrow'); this.game.stage.addChild(this); this.scale.set(0.2); this.alpha = 0.2; this.anchor.setTo(0.5, 1.3); this.animations.add('rotate', [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13], 30, true); this.animations.play('rotate', 30, true); this.currentlyControlling = 'player'; } updatePosition(playerObject, wormObject) { this.x = this.currentlyControlling === 'player' ? playerObject.x : wormObject.x; this.x -= this.game.camera.x; // Shift with camera position this.y = this.currentlyControlling === 'player' ? playerObject.y : wormObject.y; let playerHoldsOn = this.currentlyControlling === 'player' && playerObject.body.velocity.x === 0; let wormHoldsOn = this.currentlyControlling === 'worm' && wormObject.body.velocity.x === 0 && wormObject.body.velocity.y === 0; if (playerHoldsOn || wormHoldsOn) { this.scale.set(0.8); this.anchor.setTo(0.5, 1); } else { this.anchor.setTo(0.5, 1.3); this.scale.set(0.2); } } // Note: 'this' here is context from Main! static switchPlayer () { if (this.tabButton.arrow.currentlyControlling === 'player') { this.tabButton.arrow.currentlyControlling = 'worm'; this.game.camera.follow(this.wormObject); } else { this.tabButton.arrow.currentlyControlling = 'player'; this.game.camera.follow(this.playerObject); } } } export default ArrowSprite;
babruix/alien_worm_game
src/objects/Arrow.js
JavaScript
mit
1,556
import { Injectable } from '@angular/core'; @Injectable() export class DummyService { // eslint-disable-next-line no-useless-constructor constructor() {} getItems() { return new Promise(resolve => { setTimeout(() => { resolve(['Joe', 'Jane']); }, 2000); }); } }
storybooks/react-storybook
examples/angular-cli/src/stories/moduleMetadata/dummy.service.ts
TypeScript
mit
300
require "danger/commands/local_helpers/pry_setup" RSpec.describe Danger::PrySetup do before { cleanup } after { cleanup } describe "#setup_pry" do it "copies the Dangerfile and appends bindings.pry" do Dir.mktmpdir do |dir| dangerfile_path = "#{dir}/Dangerfile" File.write(dangerfile_path, "") dangerfile_copy = described_class .new(testing_ui) .setup_pry(dangerfile_path) expect(File).to exist(dangerfile_copy) expect(File.read(dangerfile_copy)).to include("binding.pry; File.delete(\"_Dangerfile.tmp\")") end end it "doesn't copy a nonexistant Dangerfile" do described_class.new(testing_ui).setup_pry("") expect(File).not_to exist("_Dangerfile.tmp") end it "warns when the pry gem is not installed" do ui = testing_ui expect(Kernel).to receive(:require).with("pry").and_raise(LoadError) expect do described_class.new(ui).setup_pry("Dangerfile") end.to raise_error(SystemExit) expect(ui.err_string).to include("Pry was not found") end def cleanup File.delete "_Dangerfile.tmp" if File.exist? "_Dangerfile.tmp" end end end
KrauseFx/danger
spec/lib/danger/commands/local_helpers/pry_setup_spec.rb
Ruby
mit
1,200
class HomeController < ApplicationController skip_authorization_check def index @project_promotions = ProjectPromotion.includes(:project => :brand).order("projects.title") @tags_by_category = Tag.includes(:tag_category, :projects).order(:name).group_by(&:tag_category) end end
nbudin/larp_library
app/controllers/home_controller.rb
Ruby
mit
292
package router import "testing" func TestColon(t *testing.T) { for k, v := range tCases["Colon"] { r := Colon(k) testingRouter(t, r, v) } } func BenchmarkColon(b *testing.B) { for k, v := range tCases["Colon"] { r := Colon(k) benchmarkingRouter(b, r, v) } }
mikespook/possum
router/colon_test.go
GO
mit
273
module Overcast class Color def self.darken(hex, amount=0.5) hex = remove_pound(hex) rgb = convert_to_rgb(hex).map{|element| element * amount } convert_to_hex(rgb) end def self.lighten(hex, amount=0.5) hex = remove_pound(hex) rgb = convert_to_rgb(hex).map{ |element| [(element + 255 * amount).round, 255].min } convert_to_hex(rgb) end private def self.remove_pound(hex) hex.gsub('#', '') end def self.convert_to_rgb(hex) hex.scan(/../).map {|color| color.hex} end def self.convert_to_hex(rgb) "#%02x%02x%02x" % rgb end end end
jespr/overcast
lib/overcast/color.rb
Ruby
mit
633
#include "Receiver.h" #include "ofGraphics.h" #include "Utils.h" namespace ofxSpout { //---------- Receiver::Receiver() : defaultFormat(GL_RGBA) { this->spoutReceiver = nullptr; } //---------- Receiver::~Receiver() { this->release(); } //---------- bool Receiver::init(std::string channelName) { this->release(); try { this->spoutReceiver = new SpoutReceiver(); //name provided, so let's use it if (!channelName.empty()) { this->spoutReceiver->SetReceiverName(channelName.c_str()); } return true; } catch (const char * e) { ofLogError(__FUNCTION__) << "Channel : " << channelName << " : " << e; return false; } } //---------- void Receiver::release() { if (this->isInitialized()) { this->spoutReceiver->ReleaseReceiver(); delete this->spoutReceiver; this->spoutReceiver = nullptr; } } //---------- bool Receiver::isInitialized() const { if (this->spoutReceiver) { return true; } else { return false; } } //---------- bool Receiver::receive(ofTexture & texture) { try { //check if we're initialised if (!this->isInitialized()) { throw("Not initialized"); } //check if the texture is allocated correctly, if not, allocate it if (this->spoutReceiver->IsUpdated()) { texture.allocate(this->spoutReceiver->GetSenderWidth(), this->spoutReceiver->GetSenderHeight(), GL_RGBA); } //pull data into the texture (keep any existing fbo attachments) GLint drawFboId = 0; glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &drawFboId); if (!this->spoutReceiver->ReceiveTextureData(texture.getTextureData().textureID, texture.getTextureData().textureTarget, drawFboId)) { throw("Can't receive texture"); } return true; } catch (const char * e) { ofLogError(__FUNCTION__) << e; return false; } } //---------- bool Receiver::selectSenderPanel() { try { if (!this->isInitialized()) { throw("Not initialized"); } this->spoutReceiver->SelectSender(); return true; } catch (const char * e) { ofLogError(__FUNCTION__) << e; return false; } } //----------- std::string Receiver::getChannelName() const { if (this->isInitialized()) { return this->spoutReceiver->GetSenderName(); } return ""; } //---------- float Receiver::getWidth() const { if (this->isInitialized()) { return this->spoutReceiver->GetSenderWidth(); } return 0; } //---------- float Receiver::getHeight() const { if (this->isInitialized()) { return this->spoutReceiver->GetSenderHeight(); } return 0; } }
elliotwoods/ofxSpout
src/ofxSpout/Receiver.cpp
C++
mit
2,691
class RenameUserIdInContacts < ActiveRecord::Migration def self.up rename_column "contacts", "user_id", "az_user_id" end def self.down rename_column "contacts", "az_user_id", "user_id" end end
stg34/azalo
db/migrate/20100709182724_rename_user_id_in_contacts.rb
Ruby
mit
210
<header class="banner" role="banner"> <nav role="navigation" class="navbar navbar-inverse"> <div class="container"> <!-- Brand and toggle get grouped for better mobile display --> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="brand navbar-brand" href="<?= esc_url(home_url('/')); ?>"><?php bloginfo('name'); ?></a> </div> <!-- Collect the nav links, forms, and other content for toggling --> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <?php if (has_nav_menu('primary_navigation')) : wp_nav_menu(['theme_location' => 'primary_navigation', 'menu_class' => 'nav navbar-nav']); endif; ?> </div><!-- /.navbar-collapse --> </div><!-- /.container-fluid --> </nav> </header> <div class="feature-box" style="background-image: url('/app/uploads/2015/08/Spartan_Race_-_Muddy_Hit-web.jpg'); background-size: cover;"> <img class="logo center-block" src="/app/uploads/2015/08/average-ocr_web.png" alt="average-ocr_web" width="150" height="150" /> </div>
obelis/AverageOCR
web/app/themes/averageocr/templates/header.php
PHP
mit
1,410
import random color_names=[ 'aliceblue', 'antiquewhite', 'aqua', 'aquamarine', 'azure', 'beige', 'bisque', 'blanchedalmond', 'blue', 'blueviolet', 'brown', 'burlywood', 'cadetblue', 'chartreuse', 'chocolate', 'coral', 'cornflowerblue', 'cornsilk', 'crimson', 'cyan', 'darkblue', 'darkcyan', 'darkgoldenrod', 'darkgray', 'darkgreen', 'darkkhaki', 'darkmagenta', 'darkolivegreen', 'darkorange', 'darkorchid', 'darkred', 'darksalmon', 'darkseagreen', 'darkslateblue', 'darkturquoise', 'darkviolet', 'deeppink', 'deepskyblue', 'dimgray', 'dodgerblue', 'firebrick', 'floralwhite', 'forestgreen', 'fuchsia', 'gainsboro', 'ghostwhite', 'gold', 'goldenrod', 'gray', 'green', 'greenyellow', 'honeydew', 'hotpink', 'indianred', 'indigo', 'ivory', 'khaki', 'lavender', 'lavenderblush', 'lawngreen', 'lemonchiffon', 'lightblue', 'lightcoral', 'lightcyan', 'lightgoldenrodyellow', 'lightgreen', 'lightgray', 'lightpink', 'lightsalmon', 'lightseagreen', 'lightskyblue', 'lightslategray', 'lightsteelblue', 'lightyellow', 'lime', 'limegreen', 'linen', 'magenta', 'maroon', 'mediumaquamarine', 'mediumblue', 'mediumorchid', 'mediumpurple', 'mediumseagreen', 'mediumslateblue', 'mediumspringgreen', 'mediumturquoise', 'mediumvioletred', 'mintcream', 'mistyrose', 'moccasin', 'navajowhite', 'navy', 'oldlace', 'olive', 'olivedrab', 'orange', 'orangered', 'orchid', 'palegoldenrod', 'palegreen', 'paleturquoise', 'palevioletred', 'papayawhip', 'peachpuff', 'peru', 'pink', 'plum', 'powderblue', 'purple', 'red', 'rosybrown', 'royalblue', 'saddlebrown', 'salmon', 'sandybrown', 'seagreen', 'seashell', 'sienna', 'silver', 'skyblue', 'slateblue', 'slategray', 'snow', 'springgreen', 'steelblue', 'tan', 'teal', 'thistle', 'tomato', 'turquoise', 'violet', 'wheat', 'white', 'whitesmoke', 'yellow', 'yellowgreen', ] def getRandomColors(num): if num > len(color_names): return color_names ns = set() while num > len(ns): ns.add(random.choice(color_names)) return list(ns)
largetalk/tenbagger
draw/colors.py
Python
mit
2,176
using System.Collections.Generic; using System.Text; namespace SourceGenerators { internal static class Templates { public static string AppRoutes(IEnumerable<string> allRoutes) { // hard code the namespace for now var sb = new StringBuilder(@" using System.Collections.Generic; using System.Collections.ObjectModel; namespace BlazorApp1 { public static class AppRoutes { public static ReadOnlyCollection<string> Routes { get; } = new ReadOnlyCollection<string>( new List<string> { "); foreach (var route in allRoutes) { sb.AppendLine($"\"{route}\","); } sb.Append(@" } ); } }"); return sb.ToString(); } public static string PageDetail() { return @" namespace BlazorApp1 { public record PageDetail(string Route, string Title, string Icon); } "; } public static string MenuItemAttribute() { return @" namespace BlazorApp1 { public class MenuItemAttribute : System.Attribute { public string Icon { get; } public string Description { get; } public int Order { get; } public MenuItemAttribute( string icon, string description, int order = 0 ) { Icon = icon; Description = description; Order = order; } } } "; } public static string MenuPages(IEnumerable<RouteableComponent> pages) { // hard code the namespace for now var sb = new StringBuilder(@" using System.Collections.Generic; using System.Collections.ObjectModel; namespace BlazorApp1 { public static class PageDetails { public static ReadOnlyCollection<PageDetail> MenuPages { get; } = new ReadOnlyCollection<PageDetail>( new List<PageDetail> { "); foreach (var page in pages) { sb.AppendLine($"new PageDetail(\"{page.Route}\", \"{page.Title}\", \"{page.Icon}\"),"); } sb.Append(@" } ); } }"); return sb.ToString(); } } }
andrewlock/blog-examples
BlazorPreRender/BlazorApp1/SourceGenerators/Templates.cs
C#
mit
2,345
#region Copyright //-------------------------------------------------------------------------------------------------------- // <copyright file="RecentChanges.ascx.cs" company="DNN Corp®"> // DNN Corp® - http://www.dnnsoftware.com Copyright (c) 2002-2013 by DNN Corp® // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and // associated documentation files (the "Software"), to deal in the Software without restriction, // including without limitation the rights to use, copy, modify, merge, publish, distribute, // sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT // NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // </copyright> ////-------------------------------------------------------------------------------------------------------- #endregion Copyright using DotNetNuke.Services.Localization; using DotNetNuke.Wiki.Utilities; namespace DotNetNuke.Wiki.Views { /// <summary> /// Recent changes class based on WikiModuleBase /// </summary> public partial class RecentChanges : WikiModuleBase { #region Constructor /// <summary> /// Initializes a new instance of the <see cref="RecentChanges"/> class. /// </summary> public RecentChanges() { this.Load += this.Page_Load; } #endregion Constructor #region Events /// <summary> /// Handles the Click event of the Last 7 Days control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event /// data.</param> protected void CmdLast7Days_Click(object sender, System.EventArgs e) { this.HitTable.Text = this.CreateRecentChangeTable(7); } /// <summary> /// Handles the Click event of the Last 24 hours control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event /// data.</param> protected void CmdLast24Hrs_Click(object sender, System.EventArgs e) { this.HitTable.Text = this.CreateRecentChangeTable(1); } /// <summary> /// Handles the Click event of the Last Month control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event /// data.</param> protected void CmdLastMonth_Click(object sender, System.EventArgs e) { this.HitTable.Text = this.CreateRecentChangeTable(31); } /// <summary> /// Handles the Load event of the Page control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs" /> instance containing the event /// data.</param> public new void Page_Load(object sender, System.EventArgs e) { this.LoadLocalization(); if (!this.IsPostBack) { this.HitTable.Text = this.CreateRecentChangeTable(1); } } #endregion Events #region Methods /// <summary> /// Loads the localization. /// </summary> private void LoadLocalization() { this.TitleLbl.Text = Localization.GetString("RCTitle", this.RouterResourceFile); this.cmdLast24Hrs.Text = Localization.GetString("RCLast24h", this.RouterResourceFile); this.cmdLast7Days.Text = Localization.GetString("RCLast7d", this.RouterResourceFile); this.cmdLastMonth.Text = Localization.GetString("RCLastMonth", this.RouterResourceFile); } #endregion Methods } }
DNNCommunity/DNN.Wiki
Views/RecentChanges.ascx.cs
C#
mit
4,659
package ku_TR import ( "testing" "time" "github.com/go-playground/locales" "github.com/go-playground/locales/currency" ) func TestLocale(t *testing.T) { trans := New() expected := "ku_TR" if trans.Locale() != expected { t.Errorf("Expected '%s' Got '%s'", expected, trans.Locale()) } } func TestPluralsRange(t *testing.T) { trans := New() tests := []struct { expected locales.PluralRule }{ // { // expected: locales.PluralRuleOther, // }, } rules := trans.PluralsRange() // expected := 1 // if len(rules) != expected { // t.Errorf("Expected '%d' Got '%d'", expected, len(rules)) // } for _, tt := range tests { r := locales.PluralRuleUnknown for i := 0; i < len(rules); i++ { if rules[i] == tt.expected { r = rules[i] break } } if r == locales.PluralRuleUnknown { t.Errorf("Expected '%s' Got '%s'", tt.expected, r) } } } func TestPluralsOrdinal(t *testing.T) { trans := New() tests := []struct { expected locales.PluralRule }{ // { // expected: locales.PluralRuleOne, // }, // { // expected: locales.PluralRuleTwo, // }, // { // expected: locales.PluralRuleFew, // }, // { // expected: locales.PluralRuleOther, // }, } rules := trans.PluralsOrdinal() // expected := 4 // if len(rules) != expected { // t.Errorf("Expected '%d' Got '%d'", expected, len(rules)) // } for _, tt := range tests { r := locales.PluralRuleUnknown for i := 0; i < len(rules); i++ { if rules[i] == tt.expected { r = rules[i] break } } if r == locales.PluralRuleUnknown { t.Errorf("Expected '%s' Got '%s'", tt.expected, r) } } } func TestPluralsCardinal(t *testing.T) { trans := New() tests := []struct { expected locales.PluralRule }{ // { // expected: locales.PluralRuleOne, // }, // { // expected: locales.PluralRuleOther, // }, } rules := trans.PluralsCardinal() // expected := 2 // if len(rules) != expected { // t.Errorf("Expected '%d' Got '%d'", expected, len(rules)) // } for _, tt := range tests { r := locales.PluralRuleUnknown for i := 0; i < len(rules); i++ { if rules[i] == tt.expected { r = rules[i] break } } if r == locales.PluralRuleUnknown { t.Errorf("Expected '%s' Got '%s'", tt.expected, r) } } } func TestRangePlurals(t *testing.T) { trans := New() tests := []struct { num1 float64 v1 uint64 num2 float64 v2 uint64 expected locales.PluralRule }{ // { // num1: 1, // v1: 1, // num2: 2, // v2: 2, // expected: locales.PluralRuleOther, // }, } for _, tt := range tests { rule := trans.RangePluralRule(tt.num1, tt.v1, tt.num2, tt.v2) if rule != tt.expected { t.Errorf("Expected '%s' Got '%s'", tt.expected, rule) } } } func TestOrdinalPlurals(t *testing.T) { trans := New() tests := []struct { num float64 v uint64 expected locales.PluralRule }{ // { // num: 1, // v: 0, // expected: locales.PluralRuleOne, // }, // { // num: 2, // v: 0, // expected: locales.PluralRuleTwo, // }, // { // num: 3, // v: 0, // expected: locales.PluralRuleFew, // }, // { // num: 4, // v: 0, // expected: locales.PluralRuleOther, // }, } for _, tt := range tests { rule := trans.OrdinalPluralRule(tt.num, tt.v) if rule != tt.expected { t.Errorf("Expected '%s' Got '%s'", tt.expected, rule) } } } func TestCardinalPlurals(t *testing.T) { trans := New() tests := []struct { num float64 v uint64 expected locales.PluralRule }{ // { // num: 1, // v: 0, // expected: locales.PluralRuleOne, // }, // { // num: 4, // v: 0, // expected: locales.PluralRuleOther, // }, } for _, tt := range tests { rule := trans.CardinalPluralRule(tt.num, tt.v) if rule != tt.expected { t.Errorf("Expected '%s' Got '%s'", tt.expected, rule) } } } func TestDaysAbbreviated(t *testing.T) { trans := New() days := trans.WeekdaysAbbreviated() for i, day := range days { s := trans.WeekdayAbbreviated(time.Weekday(i)) if s != day { t.Errorf("Expected '%s' Got '%s'", day, s) } } tests := []struct { idx int expected string }{ // { // idx: 0, // expected: "Sun", // }, // { // idx: 1, // expected: "Mon", // }, // { // idx: 2, // expected: "Tue", // }, // { // idx: 3, // expected: "Wed", // }, // { // idx: 4, // expected: "Thu", // }, // { // idx: 5, // expected: "Fri", // }, // { // idx: 6, // expected: "Sat", // }, } for _, tt := range tests { s := trans.WeekdayAbbreviated(time.Weekday(tt.idx)) if s != tt.expected { t.Errorf("Expected '%s' Got '%s'", tt.expected, s) } } } func TestDaysNarrow(t *testing.T) { trans := New() days := trans.WeekdaysNarrow() for i, day := range days { s := trans.WeekdayNarrow(time.Weekday(i)) if s != day { t.Errorf("Expected '%s' Got '%s'", string(day), s) } } tests := []struct { idx int expected string }{ // { // idx: 0, // expected: "S", // }, // { // idx: 1, // expected: "M", // }, // { // idx: 2, // expected: "T", // }, // { // idx: 3, // expected: "W", // }, // { // idx: 4, // expected: "T", // }, // { // idx: 5, // expected: "F", // }, // { // idx: 6, // expected: "S", // }, } for _, tt := range tests { s := trans.WeekdayNarrow(time.Weekday(tt.idx)) if s != tt.expected { t.Errorf("Expected '%s' Got '%s'", tt.expected, s) } } } func TestDaysShort(t *testing.T) { trans := New() days := trans.WeekdaysShort() for i, day := range days { s := trans.WeekdayShort(time.Weekday(i)) if s != day { t.Errorf("Expected '%s' Got '%s'", day, s) } } tests := []struct { idx int expected string }{ // { // idx: 0, // expected: "Su", // }, // { // idx: 1, // expected: "Mo", // }, // { // idx: 2, // expected: "Tu", // }, // { // idx: 3, // expected: "We", // }, // { // idx: 4, // expected: "Th", // }, // { // idx: 5, // expected: "Fr", // }, // { // idx: 6, // expected: "Sa", // }, } for _, tt := range tests { s := trans.WeekdayShort(time.Weekday(tt.idx)) if s != tt.expected { t.Errorf("Expected '%s' Got '%s'", tt.expected, s) } } } func TestDaysWide(t *testing.T) { trans := New() days := trans.WeekdaysWide() for i, day := range days { s := trans.WeekdayWide(time.Weekday(i)) if s != day { t.Errorf("Expected '%s' Got '%s'", day, s) } } tests := []struct { idx int expected string }{ // { // idx: 0, // expected: "Sunday", // }, // { // idx: 1, // expected: "Monday", // }, // { // idx: 2, // expected: "Tuesday", // }, // { // idx: 3, // expected: "Wednesday", // }, // { // idx: 4, // expected: "Thursday", // }, // { // idx: 5, // expected: "Friday", // }, // { // idx: 6, // expected: "Saturday", // }, } for _, tt := range tests { s := trans.WeekdayWide(time.Weekday(tt.idx)) if s != tt.expected { t.Errorf("Expected '%s' Got '%s'", tt.expected, s) } } } func TestMonthsAbbreviated(t *testing.T) { trans := New() months := trans.MonthsAbbreviated() for i, month := range months { s := trans.MonthAbbreviated(time.Month(i + 1)) if s != month { t.Errorf("Expected '%s' Got '%s'", month, s) } } tests := []struct { idx int expected string }{ // { // idx: 1, // expected: "Jan", // }, // { // idx: 2, // expected: "Feb", // }, // { // idx: 3, // expected: "Mar", // }, // { // idx: 4, // expected: "Apr", // }, // { // idx: 5, // expected: "May", // }, // { // idx: 6, // expected: "Jun", // }, // { // idx: 7, // expected: "Jul", // }, // { // idx: 8, // expected: "Aug", // }, // { // idx: 9, // expected: "Sep", // }, // { // idx: 10, // expected: "Oct", // }, // { // idx: 11, // expected: "Nov", // }, // { // idx: 12, // expected: "Dec", // }, } for _, tt := range tests { s := trans.MonthAbbreviated(time.Month(tt.idx)) if s != tt.expected { t.Errorf("Expected '%s' Got '%s'", tt.expected, s) } } } func TestMonthsNarrow(t *testing.T) { trans := New() months := trans.MonthsNarrow() for i, month := range months { s := trans.MonthNarrow(time.Month(i + 1)) if s != month { t.Errorf("Expected '%s' Got '%s'", month, s) } } tests := []struct { idx int expected string }{ // { // idx: 1, // expected: "J", // }, // { // idx: 2, // expected: "F", // }, // { // idx: 3, // expected: "M", // }, // { // idx: 4, // expected: "A", // }, // { // idx: 5, // expected: "M", // }, // { // idx: 6, // expected: "J", // }, // { // idx: 7, // expected: "J", // }, // { // idx: 8, // expected: "A", // }, // { // idx: 9, // expected: "S", // }, // { // idx: 10, // expected: "O", // }, // { // idx: 11, // expected: "N", // }, // { // idx: 12, // expected: "D", // }, } for _, tt := range tests { s := trans.MonthNarrow(time.Month(tt.idx)) if s != tt.expected { t.Errorf("Expected '%s' Got '%s'", tt.expected, s) } } } func TestMonthsWide(t *testing.T) { trans := New() months := trans.MonthsWide() for i, month := range months { s := trans.MonthWide(time.Month(i + 1)) if s != month { t.Errorf("Expected '%s' Got '%s'", month, s) } } tests := []struct { idx int expected string }{ // { // idx: 1, // expected: "January", // }, // { // idx: 2, // expected: "February", // }, // { // idx: 3, // expected: "March", // }, // { // idx: 4, // expected: "April", // }, // { // idx: 5, // expected: "May", // }, // { // idx: 6, // expected: "June", // }, // { // idx: 7, // expected: "July", // }, // { // idx: 8, // expected: "August", // }, // { // idx: 9, // expected: "September", // }, // { // idx: 10, // expected: "October", // }, // { // idx: 11, // expected: "November", // }, // { // idx: 12, // expected: "December", // }, } for _, tt := range tests { s := string(trans.MonthWide(time.Month(tt.idx))) if s != tt.expected { t.Errorf("Expected '%s' Got '%s'", tt.expected, s) } } } func TestFmtTimeFull(t *testing.T) { // loc, err := time.LoadLocation("America/Toronto") // if err != nil { // t.Errorf("Expected '<nil>' Got '%s'", err) // } // fixed := time.FixedZone("OTHER", -4) tests := []struct { t time.Time expected string }{ // { // t: time.Date(2016, 02, 03, 9, 5, 1, 0, loc), // expected: "9:05:01 am Eastern Standard Time", // }, // { // t: time.Date(2016, 02, 03, 20, 5, 1, 0, fixed), // expected: "8:05:01 pm OTHER", // }, } trans := New() for _, tt := range tests { s := trans.FmtTimeFull(tt.t) if s != tt.expected { t.Errorf("Expected '%s' Got '%s'", tt.expected, s) } } } func TestFmtTimeLong(t *testing.T) { // loc, err := time.LoadLocation("America/Toronto") // if err != nil { // t.Errorf("Expected '<nil>' Got '%s'", err) // } tests := []struct { t time.Time expected string }{ // { // t: time.Date(2016, 02, 03, 9, 5, 1, 0, loc), // expected: "9:05:01 am EST", // }, // { // t: time.Date(2016, 02, 03, 20, 5, 1, 0, loc), // expected: "8:05:01 pm EST", // }, } trans := New() for _, tt := range tests { s := trans.FmtTimeLong(tt.t) if s != tt.expected { t.Errorf("Expected '%s' Got '%s'", tt.expected, s) } } } func TestFmtTimeMedium(t *testing.T) { tests := []struct { t time.Time expected string }{ // { // t: time.Date(2016, 02, 03, 9, 5, 1, 0, time.UTC), // expected: "9:05:01 am", // }, // { // t: time.Date(2016, 02, 03, 20, 5, 1, 0, time.UTC), // expected: "8:05:01 pm", // }, } trans := New() for _, tt := range tests { s := trans.FmtTimeMedium(tt.t) if s != tt.expected { t.Errorf("Expected '%s' Got '%s'", tt.expected, s) } } } func TestFmtTimeShort(t *testing.T) { tests := []struct { t time.Time expected string }{ // { // t: time.Date(2016, 02, 03, 9, 5, 1, 0, time.UTC), // expected: "9:05 am", // }, // { // t: time.Date(2016, 02, 03, 20, 5, 1, 0, time.UTC), // expected: "8:05 pm", // }, } trans := New() for _, tt := range tests { s := trans.FmtTimeShort(tt.t) if s != tt.expected { t.Errorf("Expected '%s' Got '%s'", tt.expected, s) } } } func TestFmtDateFull(t *testing.T) { tests := []struct { t time.Time expected string }{ // { // t: time.Date(2016, 02, 03, 9, 0, 1, 0, time.UTC), // expected: "Wednesday, February 3, 2016", // }, } trans := New() for _, tt := range tests { s := trans.FmtDateFull(tt.t) if s != tt.expected { t.Errorf("Expected '%s' Got '%s'", tt.expected, s) } } } func TestFmtDateLong(t *testing.T) { tests := []struct { t time.Time expected string }{ // { // t: time.Date(2016, 02, 03, 9, 0, 1, 0, time.UTC), // expected: "February 3, 2016", // }, } trans := New() for _, tt := range tests { s := trans.FmtDateLong(tt.t) if s != tt.expected { t.Errorf("Expected '%s' Got '%s'", tt.expected, s) } } } func TestFmtDateMedium(t *testing.T) { tests := []struct { t time.Time expected string }{ // { // t: time.Date(2016, 02, 03, 9, 0, 1, 0, time.UTC), // expected: "Feb 3, 2016", // }, } trans := New() for _, tt := range tests { s := trans.FmtDateMedium(tt.t) if s != tt.expected { t.Errorf("Expected '%s' Got '%s'", tt.expected, s) } } } func TestFmtDateShort(t *testing.T) { tests := []struct { t time.Time expected string }{ // { // t: time.Date(2016, 02, 03, 9, 0, 1, 0, time.UTC), // expected: "2/3/16", // }, // { // t: time.Date(-500, 02, 03, 9, 0, 1, 0, time.UTC), // expected: "2/3/500", // }, } trans := New() for _, tt := range tests { s := trans.FmtDateShort(tt.t) if s != tt.expected { t.Errorf("Expected '%s' Got '%s'", tt.expected, s) } } } func TestFmtNumber(t *testing.T) { tests := []struct { num float64 v uint64 expected string }{ // { // num: 1123456.5643, // v: 2, // expected: "1,123,456.56", // }, // { // num: 1123456.5643, // v: 1, // expected: "1,123,456.6", // }, // { // num: 221123456.5643, // v: 3, // expected: "221,123,456.564", // }, // { // num: -221123456.5643, // v: 3, // expected: "-221,123,456.564", // }, // { // num: -221123456.5643, // v: 3, // expected: "-221,123,456.564", // }, // { // num: 0, // v: 2, // expected: "0.00", // }, // { // num: -0, // v: 2, // expected: "0.00", // }, // { // num: -0, // v: 2, // expected: "0.00", // }, } trans := New() for _, tt := range tests { s := trans.FmtNumber(tt.num, tt.v) if s != tt.expected { t.Errorf("Expected '%s' Got '%s'", tt.expected, s) } } } func TestFmtCurrency(t *testing.T) { tests := []struct { num float64 v uint64 currency currency.Type expected string }{ // { // num: 1123456.5643, // v: 2, // currency: currency.USD, // expected: "$1,123,456.56", // }, // { // num: 1123456.5643, // v: 1, // currency: currency.USD, // expected: "$1,123,456.60", // }, // { // num: 221123456.5643, // v: 3, // currency: currency.USD, // expected: "$221,123,456.564", // }, // { // num: -221123456.5643, // v: 3, // currency: currency.USD, // expected: "-$221,123,456.564", // }, // { // num: -221123456.5643, // v: 3, // currency: currency.CAD, // expected: "-CAD 221,123,456.564", // }, // { // num: 0, // v: 2, // currency: currency.USD, // expected: "$0.00", // }, // { // num: -0, // v: 2, // currency: currency.USD, // expected: "$0.00", // }, // { // num: -0, // v: 2, // currency: currency.CAD, // expected: "CAD 0.00", // }, // { // num: 1.23, // v: 0, // currency: currency.USD, // expected: "$1.00", // }, } trans := New() for _, tt := range tests { s := trans.FmtCurrency(tt.num, tt.v, tt.currency) if s != tt.expected { t.Errorf("Expected '%s' Got '%s'", tt.expected, s) } } } func TestFmtAccounting(t *testing.T) { tests := []struct { num float64 v uint64 currency currency.Type expected string }{ // { // num: 1123456.5643, // v: 2, // currency: currency.USD, // expected: "$1,123,456.56", // }, // { // num: 1123456.5643, // v: 1, // currency: currency.USD, // expected: "$1,123,456.60", // }, // { // num: 221123456.5643, // v: 3, // currency: currency.USD, // expected: "$221,123,456.564", // }, // { // num: -221123456.5643, // v: 3, // currency: currency.USD, // expected: "($221,123,456.564)", // }, // { // num: -221123456.5643, // v: 3, // currency: currency.CAD, // expected: "(CAD 221,123,456.564)", // }, // { // num: -0, // v: 2, // currency: currency.USD, // expected: "$0.00", // }, // { // num: -0, // v: 2, // currency: currency.CAD, // expected: "CAD 0.00", // }, // { // num: 1.23, // v: 0, // currency: currency.USD, // expected: "$1.00", // }, } trans := New() for _, tt := range tests { s := trans.FmtAccounting(tt.num, tt.v, tt.currency) if s != tt.expected { t.Errorf("Expected '%s' Got '%s'", tt.expected, s) } } } func TestFmtPercent(t *testing.T) { tests := []struct { num float64 v uint64 expected string }{ // { // num: 15, // v: 0, // expected: "15%", // }, // { // num: 15, // v: 2, // expected: "15.00%", // }, // { // num: 434.45, // v: 0, // expected: "434%", // }, // { // num: 34.4, // v: 2, // expected: "34.40%", // }, // { // num: -34, // v: 0, // expected: "-34%", // }, } trans := New() for _, tt := range tests { s := trans.FmtPercent(tt.num, tt.v) if s != tt.expected { t.Errorf("Expected '%s' Got '%s'", tt.expected, s) } } }
go-playground/locales
ku_TR/ku_TR_test.go
GO
mit
19,303
var _for = require ('../index'); var should = require ('should'); describe ('passing data', function () { it ('should call the loop with the passed data', function (done) { var results = ''; var loop = _for ( 0, function (i) { return i < 2; }, function (i) { return i + 1; }, function (i, _break, _continue, data) { results = results + i + data; _continue (); }); loop ('a', function () { loop ('b', function () { loop ('c', function (data) { should.not.exist (data); results.should.eql('0a1a0b1b0c1c'); done (); }); }); }); }); it ('should work when making a loop with two arguments', function (done) { var results = ''; var loop = _for (2, function (i, _break, _continue, data) { results = results + i + data; _continue (); }); loop ('a', function () { loop ('b', function () { loop ('c', function (data) { should.not.exist (data); results.should.eql('0a1a0b1b0c1c'); done (); }); }); }); }); });
JosephJNK/async-for
tests/data.tests.js
JavaScript
mit
1,126
#region License // Copyright (c) 2013 Chandramouleswaran Ravichandran // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Windows; using System.Windows.Data; using VEF.Interfaces.Controls; namespace VEF.Interfaces.Converters { public class MenuVisibilityConverter : IValueConverter { #region IValueConverter Members public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { AbstractMenuItem menu = value as AbstractMenuItem; if (menu == null) return Visibility.Hidden; if (menu.Command != null && menu.Command.CanExecute(null) == false && menu.HideDisabled == true) return Visibility.Collapsed; if (menu.Children.Count > 0 || menu.Command != null || menu.IsCheckable == true) return Visibility.Visible; return Visibility.Collapsed; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } #endregion } }
devxkh/FrankE
Editor/VEF/VEF.Core.Shared/Interfaces/Converters/MenuVisibilityConverter.cs
C#
mit
2,235
using System; namespace Paramore.Darker.Builder { internal sealed class RegistryActionWrapper : IQueryHandlerDecoratorRegistry { private readonly Action<Type> _action; public RegistryActionWrapper(Action<Type> action) { _action = action; } public void Register(Type decoratorType) { _action(decoratorType); } } }
BrighterCommand/Darker
src/Paramore.Darker/Builder/RegistryActionWrapper.cs
C#
mit
407
# encoding: utf-8 class LogoPhotoUploader < CarrierWave::Uploader::Base # Include RMagick or MiniMagick support: # include CarrierWave::RMagick include CarrierWave::MiniMagick # Choose what kind of storage to use for this uploader: storage :file # storage :fog # Override the directory where uploaded files will be stored. # This is a sensible default for uploaders that are meant to be mounted: def store_dir "uploads/logo/" end # Provide a default URL as a default if there hasn't been a file uploaded: # def default_url # # For Rails 3.1+ asset pipeline compatibility: # # ActionController::Base.helpers.asset_path("fallback/" + [version_name, "default.png"].compact.join('_')) # # "/images/fallback/" + [version_name, "default.png"].compact.join('_') # end # Process files as they are uploaded: # process :scale => [200, 300] # # def scale(width, height) # # do something # end # Create different versions of your uploaded files: process :resize_to_fit => [50, 50] # Add a white list of extensions which are allowed to be uploaded. # For images you might use something like this: def extension_white_list %w(jpg jpeg gif png) end # Override the filename of the uploaded files: # Avoid using model.id or version_name here, see uploader/store.rb for details. # def filename # "something.jpg" if original_filename # end def filename "logo." + original_filename.split(".").last if original_filename end end
zhaoguobin/company_website
app/uploaders/logo_photo_uploader.rb
Ruby
mit
1,512
/** * @fileoverview A rule to suggest using of const declaration for variables that are never reassigned after declared. * @author Toru Nagashima */ "use strict"; const astUtils = require("../util/ast-utils"); //------------------------------------------------------------------------------ // Helpers //------------------------------------------------------------------------------ const PATTERN_TYPE = /^(?:.+?Pattern|RestElement|SpreadProperty|ExperimentalRestProperty|Property)$/; const DECLARATION_HOST_TYPE = /^(?:Program|BlockStatement|SwitchCase)$/; const DESTRUCTURING_HOST_TYPE = /^(?:VariableDeclarator|AssignmentExpression)$/; /** * Checks whether a given node is located at `ForStatement.init` or not. * * @param {ASTNode} node - A node to check. * @returns {boolean} `true` if the node is located at `ForStatement.init`. */ function isInitOfForStatement(node) { return node.parent.type === "ForStatement" && node.parent.init === node; } /** * Checks whether a given Identifier node becomes a VariableDeclaration or not. * * @param {ASTNode} identifier - An Identifier node to check. * @returns {boolean} `true` if the node can become a VariableDeclaration. */ function canBecomeVariableDeclaration(identifier) { let node = identifier.parent; while (PATTERN_TYPE.test(node.type)) { node = node.parent; } return ( node.type === "VariableDeclarator" || ( node.type === "AssignmentExpression" && node.parent.type === "ExpressionStatement" && DECLARATION_HOST_TYPE.test(node.parent.parent.type) ) ); } /** * Checks if an property or element is from outer scope or function parameters * in destructing pattern. * * @param {string} name - A variable name to be checked. * @param {eslint-scope.Scope} initScope - A scope to start find. * @returns {boolean} Indicates if the variable is from outer scope or function parameters. */ function isOuterVariableInDestructing(name, initScope) { if (initScope.through.find(ref => ref.resolved && ref.resolved.name === name)) { return true; } const variable = astUtils.getVariableByName(initScope, name); if (variable !== null) { return variable.defs.some(def => def.type === "Parameter"); } return false; } /** * Gets the VariableDeclarator/AssignmentExpression node that a given reference * belongs to. * This is used to detect a mix of reassigned and never reassigned in a * destructuring. * * @param {eslint-scope.Reference} reference - A reference to get. * @returns {ASTNode|null} A VariableDeclarator/AssignmentExpression node or * null. */ function getDestructuringHost(reference) { if (!reference.isWrite()) { return null; } let node = reference.identifier.parent; while (PATTERN_TYPE.test(node.type)) { node = node.parent; } if (!DESTRUCTURING_HOST_TYPE.test(node.type)) { return null; } return node; } /** * Determines if a destructuring assignment node contains * any MemberExpression nodes. This is used to determine if a * variable that is only written once using destructuring can be * safely converted into a const declaration. * @param {ASTNode} node The ObjectPattern or ArrayPattern node to check. * @returns {boolean} True if the destructuring pattern contains * a MemberExpression, false if not. */ function hasMemberExpressionAssignment(node) { switch (node.type) { case "ObjectPattern": return node.properties.some(prop => { if (prop) { /* * Spread elements have an argument property while * others have a value property. Because different * parsers use different node types for spread elements, * we just check if there is an argument property. */ return hasMemberExpressionAssignment(prop.argument || prop.value); } return false; }); case "ArrayPattern": return node.elements.some(element => { if (element) { return hasMemberExpressionAssignment(element); } return false; }); case "AssignmentPattern": return hasMemberExpressionAssignment(node.left); case "MemberExpression": return true; // no default } return false; } /** * Gets an identifier node of a given variable. * * If the initialization exists or one or more reading references exist before * the first assignment, the identifier node is the node of the declaration. * Otherwise, the identifier node is the node of the first assignment. * * If the variable should not change to const, this function returns null. * - If the variable is reassigned. * - If the variable is never initialized nor assigned. * - If the variable is initialized in a different scope from the declaration. * - If the unique assignment of the variable cannot change to a declaration. * e.g. `if (a) b = 1` / `return (b = 1)` * - If the variable is declared in the global scope and `eslintUsed` is `true`. * `/*exported foo` directive comment makes such variables. This rule does not * warn such variables because this rule cannot distinguish whether the * exported variables are reassigned or not. * * @param {eslint-scope.Variable} variable - A variable to get. * @param {boolean} ignoreReadBeforeAssign - * The value of `ignoreReadBeforeAssign` option. * @returns {ASTNode|null} * An Identifier node if the variable should change to const. * Otherwise, null. */ function getIdentifierIfShouldBeConst(variable, ignoreReadBeforeAssign) { if (variable.eslintUsed && variable.scope.type === "global") { return null; } // Finds the unique WriteReference. let writer = null; let isReadBeforeInit = false; const references = variable.references; for (let i = 0; i < references.length; ++i) { const reference = references[i]; if (reference.isWrite()) { const isReassigned = ( writer !== null && writer.identifier !== reference.identifier ); if (isReassigned) { return null; } const destructuringHost = getDestructuringHost(reference); if (destructuringHost !== null && destructuringHost.left !== void 0) { const leftNode = destructuringHost.left; let hasOuterVariables = false, hasNonIdentifiers = false; if (leftNode.type === "ObjectPattern") { const properties = leftNode.properties; hasOuterVariables = properties .filter(prop => prop.value) .map(prop => prop.value.name) .some(name => isOuterVariableInDestructing(name, variable.scope)); hasNonIdentifiers = hasMemberExpressionAssignment(leftNode); } else if (leftNode.type === "ArrayPattern") { const elements = leftNode.elements; hasOuterVariables = elements .map(element => element && element.name) .some(name => isOuterVariableInDestructing(name, variable.scope)); hasNonIdentifiers = hasMemberExpressionAssignment(leftNode); } if (hasOuterVariables || hasNonIdentifiers) { return null; } } writer = reference; } else if (reference.isRead() && writer === null) { if (ignoreReadBeforeAssign) { return null; } isReadBeforeInit = true; } } /* * If the assignment is from a different scope, ignore it. * If the assignment cannot change to a declaration, ignore it. */ const shouldBeConst = ( writer !== null && writer.from === variable.scope && canBecomeVariableDeclaration(writer.identifier) ); if (!shouldBeConst) { return null; } if (isReadBeforeInit) { return variable.defs[0].name; } return writer.identifier; } /** * Groups by the VariableDeclarator/AssignmentExpression node that each * reference of given variables belongs to. * This is used to detect a mix of reassigned and never reassigned in a * destructuring. * * @param {eslint-scope.Variable[]} variables - Variables to group by destructuring. * @param {boolean} ignoreReadBeforeAssign - * The value of `ignoreReadBeforeAssign` option. * @returns {Map<ASTNode, ASTNode[]>} Grouped identifier nodes. */ function groupByDestructuring(variables, ignoreReadBeforeAssign) { const identifierMap = new Map(); for (let i = 0; i < variables.length; ++i) { const variable = variables[i]; const references = variable.references; const identifier = getIdentifierIfShouldBeConst(variable, ignoreReadBeforeAssign); let prevId = null; for (let j = 0; j < references.length; ++j) { const reference = references[j]; const id = reference.identifier; /* * Avoid counting a reference twice or more for default values of * destructuring. */ if (id === prevId) { continue; } prevId = id; // Add the identifier node into the destructuring group. const group = getDestructuringHost(reference); if (group) { if (identifierMap.has(group)) { identifierMap.get(group).push(identifier); } else { identifierMap.set(group, [identifier]); } } } } return identifierMap; } /** * Finds the nearest parent of node with a given type. * * @param {ASTNode} node – The node to search from. * @param {string} type – The type field of the parent node. * @param {Function} shouldStop – a predicate that returns true if the traversal should stop, and false otherwise. * @returns {ASTNode} The closest ancestor with the specified type; null if no such ancestor exists. */ function findUp(node, type, shouldStop) { if (!node || shouldStop(node)) { return null; } if (node.type === type) { return node; } return findUp(node.parent, type, shouldStop); } //------------------------------------------------------------------------------ // Rule Definition //------------------------------------------------------------------------------ module.exports = { meta: { type: "suggestion", docs: { description: "require `const` declarations for variables that are never reassigned after declared", category: "ECMAScript 6", recommended: false, url: "https://eslint.org/docs/rules/prefer-const" }, fixable: "code", schema: [ { type: "object", properties: { destructuring: { enum: ["any", "all"] }, ignoreReadBeforeAssign: { type: "boolean" } }, additionalProperties: false } ] }, create(context) { const options = context.options[0] || {}; const sourceCode = context.getSourceCode(); const shouldMatchAnyDestructuredVariable = options.destructuring !== "all"; const ignoreReadBeforeAssign = options.ignoreReadBeforeAssign === true; const variables = []; let reportCount = 0; let name = ""; /** * Reports given identifier nodes if all of the nodes should be declared * as const. * * The argument 'nodes' is an array of Identifier nodes. * This node is the result of 'getIdentifierIfShouldBeConst()', so it's * nullable. In simple declaration or assignment cases, the length of * the array is 1. In destructuring cases, the length of the array can * be 2 or more. * * @param {(eslint-scope.Reference|null)[]} nodes - * References which are grouped by destructuring to report. * @returns {void} */ function checkGroup(nodes) { const nodesToReport = nodes.filter(Boolean); if (nodes.length && (shouldMatchAnyDestructuredVariable || nodesToReport.length === nodes.length)) { const varDeclParent = findUp(nodes[0], "VariableDeclaration", parentNode => parentNode.type.endsWith("Statement")); const isVarDecParentNull = varDeclParent === null; if (!isVarDecParentNull && varDeclParent.declarations.length > 0) { const firstDeclaration = varDeclParent.declarations[0]; if (firstDeclaration.init) { const firstDecParent = firstDeclaration.init.parent; /* * First we check the declaration type and then depending on * if the type is a "VariableDeclarator" or its an "ObjectPattern" * we compare the name from the first identifier, if the names are different * we assign the new name and reset the count of reportCount and nodeCount in * order to check each block for the number of reported errors and base our fix * based on comparing nodes.length and nodesToReport.length. */ if (firstDecParent.type === "VariableDeclarator") { if (firstDecParent.id.name !== name) { name = firstDecParent.id.name; reportCount = 0; } if (firstDecParent.id.type === "ObjectPattern") { if (firstDecParent.init.name !== name) { name = firstDecParent.init.name; reportCount = 0; } } } } } let shouldFix = varDeclParent && // Don't do a fix unless the variable is initialized (or it's in a for-in or for-of loop) (varDeclParent.parent.type === "ForInStatement" || varDeclParent.parent.type === "ForOfStatement" || varDeclParent.declarations[0].init) && /* * If options.destructuring is "all", then this warning will not occur unless * every assignment in the destructuring should be const. In that case, it's safe * to apply the fix. */ nodesToReport.length === nodes.length; if (!isVarDecParentNull && varDeclParent.declarations && varDeclParent.declarations.length !== 1) { if (varDeclParent && varDeclParent.declarations && varDeclParent.declarations.length >= 1) { /* * Add nodesToReport.length to a count, then comparing the count to the length * of the declarations in the current block. */ reportCount += nodesToReport.length; shouldFix = shouldFix && (reportCount === varDeclParent.declarations.length); } } nodesToReport.forEach(node => { context.report({ node, message: "'{{name}}' is never reassigned. Use 'const' instead.", data: node, fix: shouldFix ? fixer => fixer.replaceText(sourceCode.getFirstToken(varDeclParent), "const") : null }); }); } } return { "Program:exit"() { groupByDestructuring(variables, ignoreReadBeforeAssign).forEach(checkGroup); }, VariableDeclaration(node) { if (node.kind === "let" && !isInitOfForStatement(node)) { variables.push(...context.getDeclaredVariables(node)); } } }; } };
Aladdin-ADD/eslint
lib/rules/prefer-const.js
JavaScript
mit
16,721
""" Compare the regions predicted to be prophages to the regions that are marked as prophages in our testing set Probably the hardest part of this is the identifiers! """ import os import sys import argparse import gzip from Bio import SeqIO, BiopythonWarning from PhiSpyModules import message, is_gzip_file __author__ = 'Rob Edwards' __copyright__ = 'Copyright 2020, Rob Edwards' __credits__ = ['Rob Edwards'] __license__ = 'MIT' __maintainer__ = 'Rob Edwards' __email__ = 'raedwards@gmail.com' def genbank_seqio(gbkf): if is_gzip_file(gbkf): handle = gzip.open(gbkf, 'rt') else: handle = open(gbkf, 'r') return SeqIO.parse(handle, "genbank") def actual_phage_cds(gbkf, verbose=False): """ Read the genbank file and return a list of features that are actually phage regions :param gbkf: the test genbank file with CDS marked with is_phage :param verbose: more output :return: a set of phage features """ if verbose: message(f"Reading {gbkf}", "GREEN", "stderr") phage = {} nonphage = {} for seq in genbank_seqio(gbkf): for feat in seq.features: if feat.type == 'CDS': if 'product' not in feat.qualifiers: feat.qualifiers['product'] = [f"Hypothetical protein (not annotated in {gbkf})"] if 'is_phage' in feat.qualifiers: phage[str(feat.translate(seq, cds=False).seq).upper()] = feat.qualifiers['product'][0] else: nonphage[str(feat.translate(seq, cds=False).seq).upper()] = feat.qualifiers['product'][0] return phage, nonphage def predicted_genbank(predf, verbose=False): """ Read the predictions from the genbank file and return a set of features :param predf: the predictions file :param verbose: more output :return: a set of predicted phage genes """ if verbose: message(f"Reading {predf}", "GREEN", "stderr") predicted = {} for seq in genbank_seqio(predf): for feat in seq.features: if feat.type == 'CDS': if 'product' in feat.qualifiers: predicted[str(feat.translate(seq, cds=False).seq).upper()] = feat.qualifiers['product'][0] else: predicted[str(feat.translate(seq, cds=False).seq).upper()] = f"Hypothetical protein (not annotated in {predf})" if verbose: message(f"Found {len(predicted)} predicted prophage features", "BLUE", "stderr") return predicted def predicted_regions(regf, gbkf, verbose): """ Pull the phage genes from the regions :param regf: the regions file with contigs/start/stop :param gbkf: the genbank file used to make those predictions :param verbose: more output :return: a set of predicted phage genes """ regions = {} if verbose: message(f"Reading {regf}", "GREEN", "stderr") with open(regf, 'r') as f: for l in f: p = l.strip().split("\t") assert(len(p) == 3), f"Expected a tple of [contig, start, stop] in {regf}" p[1] = int(p[1]) p[2] = int(p[2]) if p[0] not in regions: regions[p[0]] = [] if p[2] < p[1]: regions[p[0]].append([p[2], p[1]]) else: regions[p[0]].append([p[1], p[2]]) if verbose: message(f"Reading {gbkf} again to get the phage regions", "GREEN", "stderr") predicted = {} for seq in genbank_seqio(gbkf): if seq.id in regions: for loc in regions[seq.id]: if verbose: message(f"Getting from {loc[0]} to {loc[1]}", "PINK", "stderr") for feat in seq[loc[0]:loc[1]].features: if feat.type == 'CDS': if 'product' in feat.qualifiers: predicted[str(feat.translate(seq[loc[0]:loc[1]], cds=False).seq).upper()] = feat.qualifiers['product'][0] else: predicted[str(feat.translate(seq[loc[0]:loc[1]], cds=False).seq).upper()] = f"Hypothetical protein (not annotated in {gbkf})" if verbose: message(f"Found {len(predicted)} predicted prophage features", "BLUE", "stderr") return predicted def compare_real_predicted(phage: dict, nonphage: dict, predicted: dict, print_fp: bool, print_fn: bool, verbose: bool): """ Compare the features that are real and predicted :param print_fn: print out the false negative matches :param print_fp: print out the false positive matches :param phage: actual phage features :param nonphage: actual non phage features :param predicted: predicted phage features :param verbose: more output :return: """ if verbose: message(f"Comparing real and predicted", "GREEN", "stderr") # TP = phage intersection predicted # TN = nonphage intersection [not in predicted] # FP = nonphage intersection predicted # FN = phage intersection [not in predicted] # convert the keys to sets phage_set = set(phage.keys()) nonphage_set = set(nonphage.keys()) predicted_set = set(predicted.keys()) # calculate not in predicted not_predicted = set() for s in phage_set.union(nonphage): if s not in predicted: not_predicted.add(s) print(f"Found:\nTest set:\n\tPhage: {len(phage)} Not phage: {len(nonphage)}") print(f"Predictions:\n\tPhage: {len(predicted)} Not phage: {len(not_predicted)}") tp = len(phage_set.intersection(predicted_set)) tn = len(nonphage_set.intersection(not_predicted)) fp = len(nonphage_set.intersection(predicted_set)) fn = len(phage_set.intersection(not_predicted)) print(f"TP: {tp} FP: {fp} TN: {tn} FN: {fn}") try: accuracy = (tp+tn)/(tp + tn + fp + fn) except ZeroDivisionError: accuracy = "NaN" try: precision = tp/(tp+fp) except ZeroDivisionError: precision = "NaN" try: recall = tp/(tp+fn) except ZeroDivisionError: recall = "NaN" try: specificity = tn/(tn+fp) except ZeroDivisionError: specificity = "NaN" f1_score = "NaN" if accuracy != "NaN" and precision != "NaN" and recall != "NaN" and specificity != "NaN": try: f1_score = 2*(recall * precision) / (recall + precision) except ZeroDivisionError: f1_score = "NaN" if accuracy != "NaN": print(f"Accuracy: {accuracy:.3f}\t(this is the ratio of the correctly labeled phage genes to the whole pool of genes") else: print("Accuracy: NaN") if precision != "NaN": print(f"Precision: {precision:.3f}\t(This is the ratio of correctly labeled phage genes to all predictions)") else: print("Precision: NaN") if recall != "NaN": print(f"Recall: {recall:.3f}\t(This is the fraction of actual phage genes we got right)") else: print("Recall: NaN") if specificity != "NaN": print(f"Specificity: {specificity:.3f}\t(This is the fraction of non phage genes we got right)") else: print("Specificity: NaN") if f1_score != "NaN": print(f"f1 score: {f1_score:.3f}\t(this is the harmonic mean of precision and recall, and is the best measure when, as in this case, there is a big difference between the number of phage and non-phage genes)") else: print("f1 score: NaN") if print_fp: for i in nonphage_set.intersection(predicted_set): print(f"FP\t{i}\t{nonphage[i]}") if print_fn: for i in phage_set.intersection(not_predicted): print(f"FN\t{i}\t{[phage[i]]}") if __name__ == '__main__': parser = argparse.ArgumentParser(description="Compare predictions to reality") parser.add_argument('-t', '--testfile', help='test file that has phage proteins marked with the is_phage qualifier', required=True) parser.add_argument('-p', '--predictfile', help='predictions genbank file that has each prophage as a sequence entry') parser.add_argument('-r', '--regionsfile', help='predictions regions file that has tuple of [contig, start, end]') parser.add_argument('--fp', help='print out the false positives', action='store_true') parser.add_argument('--fn', help='print out the false negatives', action='store_true') parser.add_argument('-v', help='verbose output', action='store_true') args = parser.parse_args() pred = None if args.predictfile: pred = predicted_genbank(args.predictfile, args.v) elif args.regionsfile: pred = predicted_regions(args.regionsfile, args.testfile, args.v) else: message("FATAL: Please provide either a predictions genbank or tsv file", "RED", "stderr") phage, nonphage = actual_phage_cds(args.testfile, args.v) compare_real_predicted(phage, nonphage, pred, args.fp, args.fn, args.v)
linsalrob/PhiSpy
scripts/compare_predictions_to_phages.py
Python
mit
8,988
from pymarkdownlint.tests.base import BaseTestCase from pymarkdownlint.config import LintConfig, LintConfigError from pymarkdownlint import rules class LintConfigTests(BaseTestCase): def test_get_rule_by_name_or_id(self): config = LintConfig() # get by id expected = rules.MaxLineLengthRule() rule = config.get_rule_by_name_or_id('R1') self.assertEqual(rule, expected) # get by name expected = rules.TrailingWhiteSpace() rule = config.get_rule_by_name_or_id('trailing-whitespace') self.assertEqual(rule, expected) # get non-existing rule = config.get_rule_by_name_or_id('foo') self.assertIsNone(rule) def test_default_rules(self): config = LintConfig() expected_rule_classes = [rules.MaxLineLengthRule, rules.TrailingWhiteSpace, rules.HardTab] expected_rules = [rule_cls() for rule_cls in expected_rule_classes] self.assertEqual(config.default_rule_classes, expected_rule_classes) self.assertEqual(config.rules, expected_rules) def test_load_config_from_file(self): # regular config file load, no problems LintConfig.load_from_file(self.get_sample_path("markdownlint")) # bad config file load foo_path = self.get_sample_path("foo") with self.assertRaisesRegexp(LintConfigError, "Invalid file path: {0}".format(foo_path)): LintConfig.load_from_file(foo_path) # error during file parsing bad_markdowlint_path = self.get_sample_path("badmarkdownlint") expected_error_msg = "Error during config file parsing: File contains no section headers." with self.assertRaisesRegexp(LintConfigError, expected_error_msg): LintConfig.load_from_file(bad_markdowlint_path)
jorisroovers/pymarkdownlint
pymarkdownlint/tests/test_config.py
Python
mit
1,809
Template.SightingsEdit.helpers({ onDelete: function () { return function (result) { //when record is deleted, go back to record listing Router.go('SightingsList'); }; }, }); Template.SightingsEdit.events({ }); Template.SightingsEdit.rendered = function () { }; AutoForm.hooks({ updateSightingsForm: { onSuccess: function (operation, result, template) { Router.go('SightingsView', { _id: template.data.doc._id }); }, } });
bdunnette/meleagris
client/views/sightings/sightingsEdit.js
JavaScript
mit
482
/** * Copyright (c) 2013 Egor Pushkin. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.scientificsoft.iremote.platform.net; import java.io.InputStream; import java.io.OutputStream; import java.io.IOException; import java.net.InetSocketAddress; import java.net.SocketTimeoutException; import com.scientificsoft.iremote.server.tools.TimeoutException; public class Socket { private java.net.Socket _socket = null; public Socket(String host, String port, long timeout) throws IOException, TimeoutException { try { _socket = new java.net.Socket(); _socket.connect(new InetSocketAddress(host, new Integer(port)), (int)timeout); } catch ( SocketTimeoutException e ) { throw new TimeoutException(); } catch ( Exception e ) { throw new IOException("Failed to establish connection."); } } public InputStream getInputStream() throws IOException { return _socket.getInputStream(); } public OutputStream getOutputStream() throws IOException { return _socket.getOutputStream(); } public void close() throws IOException { try { _socket.shutdownInput(); } catch ( Exception e ) { } try { _socket.shutdownOutput(); } catch ( Exception e ) { } _socket.close(); } }
egorpushkin/iremote
dev/iRemote.Android/src/com/scientificsoft/iremote/platform/net/Socket.java
Java
mit
2,463
package org.zenframework.easyservices.update; import java.util.Collection; @SuppressWarnings("rawtypes") public class CollectionUpdateAdapter implements UpdateAdapter<Collection> { @Override public Class<Collection> getValueClass() { return Collection.class; } @SuppressWarnings("unchecked") @Override public void update(Collection oldValue, Collection newValue, ValueUpdater updater) { if (oldValue == newValue || newValue == null) return; if (oldValue == null) throw new UpdateException("Old value is null"); oldValue.clear(); oldValue.addAll(newValue); } }
zenframework/easy-services
easy-services-core/src/main/java/org/zenframework/easyservices/update/CollectionUpdateAdapter.java
Java
mit
657
""" homeassistant.components.binary_sensor ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Component to interface with binary sensors (sensors which only know two states) that can be monitored. For more details about this component, please refer to the documentation at https://home-assistant.io/components/binary_sensor/ """ import logging from homeassistant.helpers.entity_component import EntityComponent from homeassistant.helpers.entity import Entity from homeassistant.const import (STATE_ON, STATE_OFF) DOMAIN = 'binary_sensor' DEPENDENCIES = [] SCAN_INTERVAL = 30 ENTITY_ID_FORMAT = DOMAIN + '.{}' def setup(hass, config): """ Track states and offer events for binary sensors. """ component = EntityComponent( logging.getLogger(__name__), DOMAIN, hass, SCAN_INTERVAL) component.setup(config) return True # pylint: disable=no-self-use class BinarySensorDevice(Entity): """ Represents a binary sensor. """ @property def is_on(self): """ True if the binary sensor is on. """ return None @property def state(self): """ Returns the state of the binary sensor. """ return STATE_ON if self.is_on else STATE_OFF @property def friendly_state(self): """ Returns the friendly state of the binary sensor. """ return None
badele/home-assistant
homeassistant/components/binary_sensor/__init__.py
Python
mit
1,321
<?php $eZTranslationCacheCodeDate = 1058863428; $CacheInfo = array ( 'charset' => 'utf-8', ); $TranslationInfo = array ( 'context' => 'design/admin/content/edit', ); $TranslationRoot = array ( 'd5c6e07de8b9dccaac1d0452dee0b581' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Edit <%object_name> [%class_name]', 'comment' => NULL, 'translation' => 'Modifica <%object_name> [%class_name]', 'key' => 'd5c6e07de8b9dccaac1d0452dee0b581', ), 'e811c8a9685fbfaf39c964a635600fd5' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Translating content from %from_lang to %to_lang', 'comment' => NULL, 'translation' => 'Esecuzione traduzione del contenuto da %from_lang a %to_lang', 'key' => 'e811c8a9685fbfaf39c964a635600fd5', ), '11fb129ce59c549f147420ee3451ac24' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Send for publishing', 'comment' => NULL, 'translation' => 'Pubblica', 'key' => '11fb129ce59c549f147420ee3451ac24', ), '8c5749194e3baf11dddd5c34b1811596' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Store draft', 'comment' => NULL, 'translation' => 'Registra bozza', 'key' => '8c5749194e3baf11dddd5c34b1811596', ), 'd506eed04b8a1daa90d9dbe145445605' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Store the contents of the draft that is being edited and continue editing. Use this button to periodically save your work while editing.', 'comment' => NULL, 'translation' => 'Registra i contenuti della bozza in fase di modifica e continua a modificare. Usa questo pulsante per salvare periodicamente il tuo lavoro mentre modifichi.', 'key' => 'd506eed04b8a1daa90d9dbe145445605', ), 'd7ebb04b02e47d0bd52637484b18f14e' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Discard draft', 'comment' => NULL, 'translation' => 'Annulla bozza', 'key' => 'd7ebb04b02e47d0bd52637484b18f14e', ), '8ff4bdf4365cea79d60c64729aa5a3d7' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Published', 'comment' => NULL, 'translation' => 'Pubblicato', 'key' => '8ff4bdf4365cea79d60c64729aa5a3d7', ), 'd57eeb192509b0a21c9fb559e0875ee4' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Modified', 'comment' => NULL, 'translation' => 'Modificato il', 'key' => 'd57eeb192509b0a21c9fb559e0875ee4', ), 'b5f9dcbfc8129dbad5a5a46430976cab' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Section', 'comment' => NULL, 'translation' => 'Sezione', 'key' => 'b5f9dcbfc8129dbad5a5a46430976cab', ), 'a8122643230a05433801fbfdc325b0ac' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Depth', 'comment' => NULL, 'translation' => 'Profondità', 'key' => 'a8122643230a05433801fbfdc325b0ac', ), 'de3a2815973e43df00aee9ea89c2e9ee' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Name', 'comment' => NULL, 'translation' => 'Nome', 'key' => 'de3a2815973e43df00aee9ea89c2e9ee', ), '0c449515a963c751510ea4a1c5ad5a16' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Priority', 'comment' => NULL, 'translation' => 'Priorità', 'key' => '0c449515a963c751510ea4a1c5ad5a16', ), '67bc86a3e97a3a3d92ea3beb65dd6e87' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Locations [%locations]', 'comment' => NULL, 'translation' => 'Collocazioni [%locations]', 'key' => '67bc86a3e97a3a3d92ea3beb65dd6e87', ), 'ab439be2c1960ef2864aba2706f3da54' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Invert selection.', 'comment' => NULL, 'translation' => 'Inverti selezione.', 'key' => 'ab439be2c1960ef2864aba2706f3da54', ), '49e8f0ddafe626663288d81e2fb49ca0' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Location', 'comment' => NULL, 'translation' => 'Collocazione', 'key' => '49e8f0ddafe626663288d81e2fb49ca0', ), 'eef9b86d0bc32e55d39032df03d414f7' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Sub items', 'comment' => NULL, 'translation' => 'Sotto-elementi', 'key' => 'eef9b86d0bc32e55d39032df03d414f7', ), 'cc6dc33d8904d3c3b934998b16c5f64b' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Sorting of sub items', 'comment' => NULL, 'translation' => 'Ordinamento sotto-elementi', 'key' => 'cc6dc33d8904d3c3b934998b16c5f64b', ), '2f0a11483a590a1f6268a02200198343' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Current visibility', 'comment' => NULL, 'translation' => 'Visibilità corrente', 'key' => '2f0a11483a590a1f6268a02200198343', ), '14d015346e3dcd669f6b7289e556c379' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Visibility after publishing', 'comment' => NULL, 'translation' => 'Visibilità dopo la pubblicazione', 'key' => '14d015346e3dcd669f6b7289e556c379', ), 'f2d0aed249fd63a9ad7750f5e3b05826' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Main', 'comment' => NULL, 'translation' => 'Principale', 'key' => 'f2d0aed249fd63a9ad7750f5e3b05826', ), 'f0f5443a120379e97eaf90b672707d60' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Select location for removal.', 'comment' => NULL, 'translation' => 'Seleziona la collocazione da eliminare.', 'key' => 'f0f5443a120379e97eaf90b672707d60', ), '0de946921daa4f766d6cb8b899f50c1f' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Desc.', 'comment' => NULL, 'translation' => 'Disc.', 'key' => '0de946921daa4f766d6cb8b899f50c1f', ), '876544ffd52dfaa722d262e22b1ccb50' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Asc.', 'comment' => NULL, 'translation' => 'Asc.', 'key' => '876544ffd52dfaa722d262e22b1ccb50', ), '783d1958da4861ba7dc9f1d396513661' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Hidden by parent', 'comment' => NULL, 'translation' => 'Nascosto dal genitore', 'key' => '783d1958da4861ba7dc9f1d396513661', ), 'a7e239075d454945331613656140d9e4' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Visible', 'comment' => NULL, 'translation' => 'Visibile', 'key' => 'a7e239075d454945331613656140d9e4', ), '275526eb7c8f1a68977c1239e1905d67' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Unchanged', 'comment' => NULL, 'translation' => 'Non modificato', 'key' => '275526eb7c8f1a68977c1239e1905d67', ), '856d33ca67120cf3e125b3e674792f2d' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Hidden', 'comment' => NULL, 'translation' => 'Nascosto', 'key' => '856d33ca67120cf3e125b3e674792f2d', ), '9b78cdb793ba06dd24c1cb659fd8f18e' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Use these radio buttons to specify the main location (main node) for the object being edited.', 'comment' => NULL, 'translation' => 'Usa questi pulsanti radio per specificare la collocazione principale (nodo principale) dell\'oggetto in fase di modifica.', 'key' => '9b78cdb793ba06dd24c1cb659fd8f18e', ), '026f2a715a276e9d8d737446b9da0018' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Move to another location.', 'comment' => NULL, 'translation' => 'Sposta in un\'altra collocazione.', 'key' => '026f2a715a276e9d8d737446b9da0018', ), '30e0f7f35119baaa4d4454fbe2913660' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Remove selected', 'comment' => NULL, 'translation' => 'Elimina selezionati', 'key' => '30e0f7f35119baaa4d4454fbe2913660', ), '3bd76c0ad50229499785fd214b38a423' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Remove selected locations.', 'comment' => NULL, 'translation' => 'Elimina le collocazioni selezionate.', 'key' => '3bd76c0ad50229499785fd214b38a423', ), '91f558d19141ff4355d842ee41371638' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Add locations', 'comment' => NULL, 'translation' => 'Aggiungi collocazioni', 'key' => '91f558d19141ff4355d842ee41371638', ), 'd1348b630823ba147fee6a3080b93e6a' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Add one or more locations for the object being edited.', 'comment' => NULL, 'translation' => 'Aggiungi una o più collocazioni per l\'oggetto in fase di modifica.', 'key' => 'd1348b630823ba147fee6a3080b93e6a', ), '24684de48a0e5f5cd59453cfaecf3fe2' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Object information', 'comment' => NULL, 'translation' => 'Informazioni sull\'oggetto', 'key' => '24684de48a0e5f5cd59453cfaecf3fe2', ), '7ef3f2da93bc270f92af697bf09d2478' => array ( 'context' => 'design/admin/content/edit', 'source' => 'ID', 'comment' => NULL, 'translation' => 'ID', 'key' => '7ef3f2da93bc270f92af697bf09d2478', ), 'db6996ee096133dd3bf27a66d6c6a245' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Created', 'comment' => NULL, 'translation' => 'Creato il', 'key' => 'db6996ee096133dd3bf27a66d6c6a245', ), '3504c716aee9e860aea283ab634315f5' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Not yet published', 'comment' => NULL, 'translation' => 'Non ancora pubblicato', 'key' => '3504c716aee9e860aea283ab634315f5', ), '8a20002c7443ef8d46e8fd516830827a' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Published version', 'comment' => NULL, 'translation' => 'Versione pubblicata', 'key' => '8a20002c7443ef8d46e8fd516830827a', ), '3b445a4b6127869d991f6b9f21540def' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Manage versions', 'comment' => NULL, 'translation' => 'Gestisci versioni', 'key' => '3b445a4b6127869d991f6b9f21540def', ), '459828e3bbf9aca1b85a34598762c68f' => array ( 'context' => 'design/admin/content/edit', 'source' => 'View and manage (copy, delete, etc.) the versions of this object.', 'comment' => NULL, 'translation' => 'Guarda ed amministra (copia, cancella, ecc.) le versioni di quest\'oggetto.', 'key' => '459828e3bbf9aca1b85a34598762c68f', ), '337ce19fed6e1043de7d521d5f20a58c' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Current draft', 'comment' => NULL, 'translation' => 'Bozza corrente', 'key' => '337ce19fed6e1043de7d521d5f20a58c', ), '3bc586e5f657cf80e47166d0049f6c75' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Version', 'comment' => NULL, 'translation' => 'Versione', 'key' => '3bc586e5f657cf80e47166d0049f6c75', ), '34ea08d6e0326ca7a804a034afd76eba' => array ( 'context' => 'design/admin/content/edit', 'source' => 'View', 'comment' => NULL, 'translation' => 'Visualizza', 'key' => '34ea08d6e0326ca7a804a034afd76eba', ), 'e1668f1e0ee902c1ec6ce6b87fca974e' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Preview the draft that is being edited.', 'comment' => NULL, 'translation' => 'Visualizza la bozza in fase di modifica.', 'key' => 'e1668f1e0ee902c1ec6ce6b87fca974e', ), '9cfee90b36ba6a94a051395e41071d64' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Store and exit', 'comment' => NULL, 'translation' => 'Registra ed esci', 'key' => '9cfee90b36ba6a94a051395e41071d64', ), '1b7dc1e4c2c6fb9afa6ba1d0d2cfe22e' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Store the draft that is being edited and exit from edit mode.', 'comment' => NULL, 'translation' => 'Registra la bozza in fase di modifica ed esci dalla modalità di modifica.', 'key' => '1b7dc1e4c2c6fb9afa6ba1d0d2cfe22e', ), 'deff3631a2a6a7aefe62c90e6f531393' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Translate', 'comment' => NULL, 'translation' => 'Traduci', 'key' => 'deff3631a2a6a7aefe62c90e6f531393', ), '15261022404c70f9d80d19670046617c' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Related objects [%related_objects]', 'comment' => NULL, 'translation' => 'Oggetti correlati [%related_objects]', 'key' => '15261022404c70f9d80d19670046617c', ), 'bdc9407d88adf5b51f71300747bc65b4' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Related images [%related_images]', 'comment' => NULL, 'translation' => 'Immagini correlate [%related_images]', 'key' => 'bdc9407d88adf5b51f71300747bc65b4', ), '49e4893c354086bd227f26833da6fae3' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Related files [%related_files]', 'comment' => NULL, 'translation' => 'File correlati [%related_files]', 'key' => '49e4893c354086bd227f26833da6fae3', ), 'fb0e2e8db005e5abbfc19f74d4d2ff59' => array ( 'context' => 'design/admin/content/edit', 'source' => 'File type', 'comment' => NULL, 'translation' => 'Tipo file', 'key' => 'fb0e2e8db005e5abbfc19f74d4d2ff59', ), 'cbe610719066288bb0f8f16e66eb60bf' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Size', 'comment' => NULL, 'translation' => 'Dimensione', 'key' => 'cbe610719066288bb0f8f16e66eb60bf', ), '7629938cdf31fb430956705c4f25915c' => array ( 'context' => 'design/admin/content/edit', 'source' => 'XML code', 'comment' => NULL, 'translation' => 'Codice XML', 'key' => '7629938cdf31fb430956705c4f25915c', ), '2e759ee05aa1ad12add670edbc15d2c2' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Related content [%related_objects]', 'comment' => NULL, 'translation' => 'Oggetti correlati [%related_objects]', 'key' => '2e759ee05aa1ad12add670edbc15d2c2', ), '42720949af15fd05c21a1220ce7dcaed' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Type', 'comment' => NULL, 'translation' => 'Tipo', 'key' => '42720949af15fd05c21a1220ce7dcaed', ), 'a71c6cd033f06f84a746efa15bec425f' => array ( 'context' => 'design/admin/content/edit', 'source' => 'There are no objects related to the one that is currently being edited.', 'comment' => NULL, 'translation' => 'Non vi sono oggetti correlati a quello attualmente in fase di modifica.', 'key' => 'a71c6cd033f06f84a746efa15bec425f', ), '7c9c383b8a6efc73a57865ea173956f4' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Remove the selected items from the list(s) above. It is only the relations that will be removed. The items will not be deleted.', 'comment' => NULL, 'translation' => 'Elimina gli elementi selezionati dalla lista(e) in alto. Verranno eliminate solo le relazioni. Gli elementi non saranno eliminati.', 'key' => '7c9c383b8a6efc73a57865ea173956f4', ), 'e4bc8d93d24d7f58fcd273d10a85a787' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Add existing', 'comment' => NULL, 'translation' => 'Aggiungi esistente', 'key' => 'e4bc8d93d24d7f58fcd273d10a85a787', ), '42bfc9071828350c26ed3c83b752a191' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Add an existing item as a related object.', 'comment' => NULL, 'translation' => 'Aggiungi un elemento esistente come oggetto correlato.', 'key' => '42bfc9071828350c26ed3c83b752a191', ), 'ba94e70cabd1cb7edd98f029ed9e6219' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Upload new', 'comment' => NULL, 'translation' => 'Upload nuovo', 'key' => 'ba94e70cabd1cb7edd98f029ed9e6219', ), '5c9aa913f95d407fbb752e4cb03c31d5' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Upload a file and add it as a related object.', 'comment' => NULL, 'translation' => 'Carica un file e aggiungilo come oggetto correlato.', 'key' => '5c9aa913f95d407fbb752e4cb03c31d5', ), 'c32705fc7ed02108c0cc8637bfb014a3' => array ( 'context' => 'design/admin/content/edit', 'source' => 'The draft could not be stored.', 'comment' => NULL, 'translation' => 'La bozza non può essere registrata.', 'key' => 'c32705fc7ed02108c0cc8637bfb014a3', ), '0107a013d1906cdccde3185dac816952' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Required data is either missing or is invalid', 'comment' => NULL, 'translation' => 'I dati richiesti sono mancanti o non corretti', 'key' => '0107a013d1906cdccde3185dac816952', ), '4636bf4dbd364e83747d95d2e5291f09' => array ( 'context' => 'design/admin/content/edit', 'source' => 'The following locations are invalid', 'comment' => NULL, 'translation' => 'Le seguenti collocazioni non sono valide', 'key' => '4636bf4dbd364e83747d95d2e5291f09', ), 'a4e029b88453feb1b89b03e5f94d7417' => array ( 'context' => 'design/admin/content/edit', 'source' => 'The draft was only partially stored.', 'comment' => NULL, 'translation' => 'Bozza registrata solo parzialmente.', 'key' => 'a4e029b88453feb1b89b03e5f94d7417', ), '5547c5c42894c60e4f4e423b62a29ea1' => array ( 'context' => 'design/admin/content/edit', 'source' => 'The draft was successfully stored.', 'comment' => NULL, 'translation' => 'Registrazione bozza riuscita.', 'key' => '5547c5c42894c60e4f4e423b62a29ea1', ), '978390e9e54157ef85305dbab13222b8' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Are you sure you want to discard the draft?', 'comment' => NULL, 'translation' => 'Sei sicuro di voler annullare la bozza?', 'key' => '978390e9e54157ef85305dbab13222b8', ), 'b2151a3ff3097b7918ffb0bf77ddd3d9' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Discard the draft that is being edited. This will also remove the translations that belong to the draft (if any).', 'comment' => NULL, 'translation' => 'Annulla la bozza in fase di modifica. Rimuoverai anche le traduzioni appartenenti alla bozza (se ve ne sono).', 'key' => 'b2151a3ff3097b7918ffb0bf77ddd3d9', ), '64b2382b215c4fa9830f9a21fb2c4ca8' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Translate from', 'comment' => NULL, 'translation' => 'Traduci da', 'key' => '64b2382b215c4fa9830f9a21fb2c4ca8', ), '7410909128e3c35ccf9d14cceb80820e' => array ( 'context' => 'design/admin/content/edit', 'source' => 'No translation', 'comment' => NULL, 'translation' => 'Nessuna traduzione', 'key' => '7410909128e3c35ccf9d14cceb80820e', ), 'a535d0e0c96877445a89aef4ee173dc4' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Edit the current object showing the selected language as a reference.', 'comment' => NULL, 'translation' => 'Modifica i seguenti oggetti mostrando la lingua selezionata come riferimento.', 'key' => 'a535d0e0c96877445a89aef4ee173dc4', ), 'd692cfde1a62954707c8672718099413' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Publish data', 'comment' => NULL, 'translation' => 'Pubblica i dati', 'key' => 'd692cfde1a62954707c8672718099413', ), 'eb0ae2aa2dc3d1e21c38bb5c4216db5d' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Back to edit', 'comment' => NULL, 'translation' => 'Torna alla modifica', 'key' => 'eb0ae2aa2dc3d1e21c38bb5c4216db5d', ), 'ec3eb846d3b45c2b95ac208645003f88' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Relation type', 'comment' => NULL, 'translation' => 'Tipo di relazione', 'key' => 'ec3eb846d3b45c2b95ac208645003f88', ), '54a0d205353a46d3d3a0e72dcb9de665' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Common', 'comment' => NULL, 'translation' => 'Comune', 'key' => '54a0d205353a46d3d3a0e72dcb9de665', ), '58e308c58d795fe23ce95b39e31631b0' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Embedded', 'comment' => NULL, 'translation' => 'Incluso', 'key' => '58e308c58d795fe23ce95b39e31631b0', ), '3e931f75750447a56ff75badd13e66d5' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Linked', 'comment' => NULL, 'translation' => 'Collegato', 'key' => '3e931f75750447a56ff75badd13e66d5', ), '6f1be5a3016b77c751f014cba5abf62b' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Attribute', 'comment' => NULL, 'translation' => 'Attributo', 'key' => '6f1be5a3016b77c751f014cba5abf62b', ), '630cf7951abe12d79a7d8e68e4e59b8c' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Copy this code and paste it into an XML field to embed the object.', 'comment' => NULL, 'translation' => 'Copia questo codice ed incollalo in un campo XML per includere l\'oggetto.', 'key' => '630cf7951abe12d79a7d8e68e4e59b8c', ), '88fc57c68a451c3ae68461cd1be0ac09' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Copy this code and paste it into an XML field to link the object.', 'comment' => NULL, 'translation' => 'Copia questo codice ed incollalo in un campo XML per collegare l\'oggetto.', 'key' => '88fc57c68a451c3ae68461cd1be0ac09', ), '2e6bc1eade5bc87d907d552c1f2850c2' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Top node', 'comment' => NULL, 'translation' => 'Nodo superiore', 'key' => '2e6bc1eade5bc87d907d552c1f2850c2', ), 'e21865e61399551e932cfa56e2f037c3' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Publish the contents of the draft that is being edited. The draft will become the published version of the object.', 'comment' => NULL, 'translation' => 'Pubblica i contenuti della bozza in fase di modifica. La bozza diverrà la versione pubblicata dell\'oggetto.', 'key' => 'e21865e61399551e932cfa56e2f037c3', ), 'a0ff5452f01b802f02e9589528383468' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Class identifier', 'comment' => NULL, 'translation' => 'Identificatore della classe', 'key' => 'a0ff5452f01b802f02e9589528383468', ), 'a03bc27f29960a05a2082afa54bd767f' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Class name', 'comment' => NULL, 'translation' => 'Nome della classe', 'key' => 'a03bc27f29960a05a2082afa54bd767f', ), '548d9e60b02ca3fea8f9eca6e5ea270b' => array ( 'context' => 'design/admin/content/edit', 'source' => 'This location will remain unchanged when the object is published.', 'comment' => NULL, 'translation' => 'Questa collocazione non verrà modificata quando l\'oggetto verrà pubblicato.', 'key' => '548d9e60b02ca3fea8f9eca6e5ea270b', ), 'b84aa5ba3b4a29912b256550b85372d2' => array ( 'context' => 'design/admin/content/edit', 'source' => 'This location will be created when the object is published.', 'comment' => NULL, 'translation' => 'Questa collocazione verrà creata quando l\'oggetto verrà pubblicato.', 'key' => 'b84aa5ba3b4a29912b256550b85372d2', ), '8dfc007c6f91ff521eb15a6ae1cfda44' => array ( 'context' => 'design/admin/content/edit', 'source' => 'This location will be moved when the object is published.', 'comment' => NULL, 'translation' => 'Questa collocazione verrà spostata quando l\'oggetto verrà pubblicato.', 'key' => '8dfc007c6f91ff521eb15a6ae1cfda44', ), '99deb2fe1a6237dcc341c6a0f3dc7980' => array ( 'context' => 'design/admin/content/edit', 'source' => 'This location will be removed when the object is published.', 'comment' => NULL, 'translation' => 'Questa collocazione verrà eliminata quando l\'oggetto verrà pubblicato.', 'key' => '99deb2fe1a6237dcc341c6a0f3dc7980', ), '1559f1473d1db10faf6251edb2bda77e' => array ( 'context' => 'design/admin/content/edit', 'source' => 'You do not have permission to remove this location.', 'comment' => NULL, 'translation' => 'Non hai i permessi per eliminare questa collocazione.', 'key' => '1559f1473d1db10faf6251edb2bda77e', ), 'fdd63332e502d8369d3cf5e937afc089' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Use this menu to set the sorting method for the sub items in this location.', 'comment' => NULL, 'translation' => 'Usa questo menù per impostare il metodo di ordinamento dei sotto-elementi di questa collocazione.', 'key' => 'fdd63332e502d8369d3cf5e937afc089', ), '6deedda369647ff46f481b752d545896' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Use this menu to set the sorting direction for the sub items in this location.', 'comment' => NULL, 'translation' => 'Usa questo menù per impostare la direzione di ordinamento dei sotto-elementi di questa collocazione.', 'key' => '6deedda369647ff46f481b752d545896', ), '657e97cded3ee381946c164372ca6986' => array ( 'context' => 'design/admin/content/edit', 'source' => 'You cannot add or remove locations because the object being edited belongs to a top node.', 'comment' => NULL, 'translation' => 'Non puoi aggiungere o eliminare collocazioni perché l\'oggetto in fase di modifica appartiene ad un nodo principale.', 'key' => '657e97cded3ee381946c164372ca6986', ), 'cc637428ff7420fa16299a1534569ba3' => array ( 'context' => 'design/admin/content/edit', 'source' => 'You do not have permission to view this object', 'comment' => NULL, 'translation' => 'Non sei abilitato a vedere quest\'oggetto', 'key' => 'cc637428ff7420fa16299a1534569ba3', ), 'e18abee452b4714bda51c8f4e41135ea' => array ( 'context' => 'design/admin/content/edit', 'source' => 'You cannot manage the versions of this object because there is only one version available (the one that is being edited).', 'comment' => NULL, 'translation' => 'Non puoi gestire le versioni di quest\'oggetto perché c\'è solo una versione disponibile (quella che viene modificata).', 'key' => 'e18abee452b4714bda51c8f4e41135ea', ), 'eb8bc6ee1e297b27503af0207afddca1' => array ( 'context' => 'design/admin/content/edit', 'source' => 'States', 'comment' => NULL, 'translation' => 'Stati', 'key' => 'eb8bc6ee1e297b27503af0207afddca1', ), '6cd07f3dd6f612f4a629660e3f17f225' => array ( 'context' => 'design/admin/content/edit', 'source' => 'The following data is invalid according to the custom validation rules', 'comment' => NULL, 'translation' => 'I seguenti dati non sono validi sulla base delle regole di validazione impostate', 'key' => '6cd07f3dd6f612f4a629660e3f17f225', ), 'c134eae4296615056100774aba5c737c' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Toggle fullscreen editing!', 'comment' => NULL, 'translation' => 'Tasto per la modifica a schermo intero!', 'key' => 'c134eae4296615056100774aba5c737c', ), '2b21fdd22aac1dc9d52badd4daa84cc8' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Store draft and exit', 'comment' => NULL, 'translation' => 'Registra bozza ed esci', 'key' => '2b21fdd22aac1dc9d52badd4daa84cc8', ), 'c19fe6950ef73d4a5aac038c6c2f3e1b' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Store the draft that is being edited and exit from edit mode. Use when you need to exit your work and return later to continue.', 'comment' => NULL, 'translation' => 'Registra la bozza in fase di modifica ed esci dalla modifica. Usa questo pulsante per uscire dal tuo lavoro e tornare successivamente per continuare.', 'key' => 'c19fe6950ef73d4a5aac038c6c2f3e1b', ), '820c3bacd630fd295899e660ba22918c' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Edit <%object_name> (%class_name)', 'comment' => NULL, 'translation' => 'Modifica <%object_name> (%class_name)', 'key' => '820c3bacd630fd295899e660ba22918c', ), '8950a2381757b6dd0db5091483661bb0' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Locations (%locations)', 'comment' => NULL, 'translation' => 'Collocazioni (%locations)', 'key' => '8950a2381757b6dd0db5091483661bb0', ), '3965117f5e3158b59fe549e6cdba2c9a' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Preview', 'comment' => NULL, 'translation' => 'Anteprima', 'key' => '3965117f5e3158b59fe549e6cdba2c9a', ), '6042d6c6f7e4f2e7e22e7c65162514ae' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Existing translations', 'comment' => NULL, 'translation' => 'Traduzioni esistenti', 'key' => '6042d6c6f7e4f2e7e22e7c65162514ae', ), '6763edccdd45769450ffd1434299bf10' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Base translation on', 'comment' => NULL, 'translation' => 'Traduzione di base su', 'key' => '6763edccdd45769450ffd1434299bf10', ), '21d0fdacb0a7736484e419ed81e22956' => array ( 'context' => 'design/admin/content/edit', 'source' => 'None', 'comment' => NULL, 'translation' => 'Nessuna', 'key' => '21d0fdacb0a7736484e419ed81e22956', ), '06304ec517378373e9de1c95fb429df1' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Related objects (%related_objects)', 'comment' => NULL, 'translation' => 'Oggetti correlati (%related_objects)', 'key' => '06304ec517378373e9de1c95fb429df1', ), 'b104c545ae07332644ae2d20a9f1384b' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Related images (%related_images)', 'comment' => NULL, 'translation' => 'Immagini correlate (%related_images)', 'key' => 'b104c545ae07332644ae2d20a9f1384b', ), '3d94b5daec0e506ade7e107b6b73d978' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Related files (%related_files)', 'comment' => NULL, 'translation' => 'File correlati (%related_files)', 'key' => '3d94b5daec0e506ade7e107b6b73d978', ), '8adb2a84570bcb0cc99ec5ae9d73bf95' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Related content (%related_objects)', 'comment' => NULL, 'translation' => 'Oggetti correlati (%related_objects)', 'key' => '8adb2a84570bcb0cc99ec5ae9d73bf95', ), '58607b576d3d0e5e08333fccc24d840c' => array ( 'context' => 'design/admin/content/edit', 'source' => 'View the draft that is being edited.', 'comment' => NULL, 'translation' => 'Visualizza la bozza in fase di modifica.', 'key' => '58607b576d3d0e5e08333fccc24d840c', ), '21cf1f883c2e361d5810fa6bc0eac58e' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Path String', 'comment' => NULL, 'translation' => 'Stringa percorso', 'key' => '21cf1f883c2e361d5810fa6bc0eac58e', ), '03fb656941a080471b673d39a3d6d0fb' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Go to the top', 'comment' => NULL, 'translation' => 'Vai all\'inizio', 'key' => '03fb656941a080471b673d39a3d6d0fb', ), ); ?>
SnceGroup/snce-website
web/var/cache/translation/f1fa2db4683ed697d014961bf03dd47c/ita-IT/e1865bb9511c2e58519696970e878347.php
PHP
mit
32,257
// Copyright (c) 2012-2013 The PPCoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <boost/assign/list_of.hpp> #include "kernel.h" #include "txdb.h" using namespace std; extern int nStakeMaxAge; extern int nStakeTargetSpacing; typedef std::map<int, unsigned int> MapModifierCheckpoints; // Hard checkpoints of stake modifiers to ensure they are deterministic static std::map<int, unsigned int> mapStakeModifierCheckpoints = boost::assign::map_list_of ( 0, 0xfd11f4e7 ) ( 1, 0x2dcbe358 ) ; // Hard checkpoints of stake modifiers to ensure they are deterministic (testNet) static std::map<int, unsigned int> mapStakeModifierCheckpointsTestNet = boost::assign::map_list_of ( 0, 0x0e00670bu ) ; // Get time weight int64 GetWeight(int64 nIntervalBeginning, int64 nIntervalEnd) { // Kernel hash weight starts from 0 at the 30-day min age // this change increases active coins participating the hash and helps // to secure the network when proof-of-stake difficulty is low // // Maximum TimeWeight is 90 days. return min(nIntervalEnd - nIntervalBeginning - nStakeMinAge, (int64)nStakeMaxAge); } // Get the last stake modifier and its generation time from a given block static bool GetLastStakeModifier(const CBlockIndex* pindex, uint64& nStakeModifier, int64& nModifierTime) { if (!pindex) return error("GetLastStakeModifier: null pindex"); while (pindex && pindex->pprev && !pindex->GeneratedStakeModifier()) pindex = pindex->pprev; if (!pindex->GeneratedStakeModifier()) return error("GetLastStakeModifier: no generation at genesis block"); nStakeModifier = pindex->nStakeModifier; nModifierTime = pindex->GetBlockTime(); return true; } // Get selection interval section (in seconds) static int64 GetStakeModifierSelectionIntervalSection(int nSection) { assert (nSection >= 0 && nSection < 64); return (nModifierInterval * 63 / (63 + ((63 - nSection) * (MODIFIER_INTERVAL_RATIO - 1)))); } // Get stake modifier selection interval (in seconds) static int64 GetStakeModifierSelectionInterval() { int64 nSelectionInterval = 0; for (int nSection=0; nSection<64; nSection++) nSelectionInterval += GetStakeModifierSelectionIntervalSection(nSection); return nSelectionInterval; } // select a block from the candidate blocks in vSortedByTimestamp, excluding // already selected blocks in vSelectedBlocks, and with timestamp up to // nSelectionIntervalStop. static bool SelectBlockFromCandidates(vector<pair<int64, uint256> >& vSortedByTimestamp, map<uint256, const CBlockIndex*>& mapSelectedBlocks, int64 nSelectionIntervalStop, uint64 nStakeModifierPrev, const CBlockIndex** pindexSelected) { bool fSelected = false; uint256 hashBest = 0; *pindexSelected = (const CBlockIndex*) 0; BOOST_FOREACH(const PAIRTYPE(int64, uint256)& item, vSortedByTimestamp) { if (!mapBlockIndex.count(item.second)) return error("SelectBlockFromCandidates: failed to find block index for candidate block %s", item.second.ToString().c_str()); const CBlockIndex* pindex = mapBlockIndex[item.second]; if (fSelected && pindex->GetBlockTime() > nSelectionIntervalStop) break; if (mapSelectedBlocks.count(pindex->GetBlockHash()) > 0) continue; // compute the selection hash by hashing its proof-hash and the // previous proof-of-stake modifier uint256 hashProof = pindex->IsProofOfStake()? pindex->hashProofOfStake : pindex->GetBlockHash(); CDataStream ss(SER_GETHASH, 0); ss << hashProof << nStakeModifierPrev; uint256 hashSelection = Hash(ss.begin(), ss.end()); // the selection hash is divided by 2**32 so that proof-of-stake block // is always favored over proof-of-work block. this is to preserve // the energy efficiency property if (pindex->IsProofOfStake()) hashSelection >>= 32; if (fSelected && hashSelection < hashBest) { hashBest = hashSelection; *pindexSelected = (const CBlockIndex*) pindex; } else if (!fSelected) { fSelected = true; hashBest = hashSelection; *pindexSelected = (const CBlockIndex*) pindex; } } if (fDebug && GetBoolArg("-printstakemodifier")) printf("SelectBlockFromCandidates: selection hash=%s\n", hashBest.ToString().c_str()); return fSelected; } // Stake Modifier (hash modifier of proof-of-stake): // The purpose of stake modifier is to prevent a txout (coin) owner from // computing future proof-of-stake generated by this txout at the time // of transaction confirmation. To meet kernel protocol, the txout // must hash with a future stake modifier to generate the proof. // Stake modifier consists of bits each of which is contributed from a // selected block of a given block group in the past. // The selection of a block is based on a hash of the block's proof-hash and // the previous stake modifier. // Stake modifier is recomputed at a fixed time interval instead of every // block. This is to make it difficult for an attacker to gain control of // additional bits in the stake modifier, even after generating a chain of // blocks. bool ComputeNextStakeModifier(const CBlockIndex* pindexPrev, uint64& nStakeModifier, bool& fGeneratedStakeModifier) { nStakeModifier = 0; fGeneratedStakeModifier = false; if (!pindexPrev) { fGeneratedStakeModifier = true; return true; // genesis block's modifier is 0 } // First find current stake modifier and its generation block time // if it's not old enough, return the same stake modifier int64 nModifierTime = 0; if (!GetLastStakeModifier(pindexPrev, nStakeModifier, nModifierTime)) return error("ComputeNextStakeModifier: unable to get last modifier"); if (fDebug) { printf("ComputeNextStakeModifier: prev modifier=0x%016"PRI64x" time=%s\n", nStakeModifier, DateTimeStrFormat(nModifierTime).c_str()); } if (nModifierTime / nModifierInterval >= pindexPrev->GetBlockTime() / nModifierInterval) return true; // Sort candidate blocks by timestamp vector<pair<int64, uint256> > vSortedByTimestamp; vSortedByTimestamp.reserve(64 * nModifierInterval / nStakeTargetSpacing); int64 nSelectionInterval = GetStakeModifierSelectionInterval(); int64 nSelectionIntervalStart = (pindexPrev->GetBlockTime() / nModifierInterval) * nModifierInterval - nSelectionInterval; const CBlockIndex* pindex = pindexPrev; while (pindex && pindex->GetBlockTime() >= nSelectionIntervalStart) { vSortedByTimestamp.push_back(make_pair(pindex->GetBlockTime(), pindex->GetBlockHash())); pindex = pindex->pprev; } int nHeightFirstCandidate = pindex ? (pindex->nHeight + 1) : 0; reverse(vSortedByTimestamp.begin(), vSortedByTimestamp.end()); sort(vSortedByTimestamp.begin(), vSortedByTimestamp.end()); // Select 64 blocks from candidate blocks to generate stake modifier uint64 nStakeModifierNew = 0; int64 nSelectionIntervalStop = nSelectionIntervalStart; map<uint256, const CBlockIndex*> mapSelectedBlocks; for (int nRound=0; nRound<min(64, (int)vSortedByTimestamp.size()); nRound++) { // add an interval section to the current selection round nSelectionIntervalStop += GetStakeModifierSelectionIntervalSection(nRound); // select a block from the candidates of current round if (!SelectBlockFromCandidates(vSortedByTimestamp, mapSelectedBlocks, nSelectionIntervalStop, nStakeModifier, &pindex)) return error("ComputeNextStakeModifier: unable to select block at round %d", nRound); // write the entropy bit of the selected block nStakeModifierNew |= (((uint64)pindex->GetStakeEntropyBit()) << nRound); // add the selected block from candidates to selected list mapSelectedBlocks.insert(make_pair(pindex->GetBlockHash(), pindex)); if (fDebug && GetBoolArg("-printstakemodifier")) printf("ComputeNextStakeModifier: selected round %d stop=%s height=%d bit=%d\n", nRound, DateTimeStrFormat(nSelectionIntervalStop).c_str(), pindex->nHeight, pindex->GetStakeEntropyBit()); } // Print selection map for visualization of the selected blocks if (fDebug && GetBoolArg("-printstakemodifier")) { string strSelectionMap = ""; // '-' indicates proof-of-work blocks not selected strSelectionMap.insert(0, pindexPrev->nHeight - nHeightFirstCandidate + 1, '-'); pindex = pindexPrev; while (pindex && pindex->nHeight >= nHeightFirstCandidate) { // '=' indicates proof-of-stake blocks not selected if (pindex->IsProofOfStake()) strSelectionMap.replace(pindex->nHeight - nHeightFirstCandidate, 1, "="); pindex = pindex->pprev; } BOOST_FOREACH(const PAIRTYPE(uint256, const CBlockIndex*)& item, mapSelectedBlocks) { // 'S' indicates selected proof-of-stake blocks // 'W' indicates selected proof-of-work blocks strSelectionMap.replace(item.second->nHeight - nHeightFirstCandidate, 1, item.second->IsProofOfStake()? "S" : "W"); } printf("ComputeNextStakeModifier: selection height [%d, %d] map %s\n", nHeightFirstCandidate, pindexPrev->nHeight, strSelectionMap.c_str()); } if (fDebug) { printf("ComputeNextStakeModifier: new modifier=0x%016"PRI64x" time=%s\n", nStakeModifierNew, DateTimeStrFormat(pindexPrev->GetBlockTime()).c_str()); } nStakeModifier = nStakeModifierNew; fGeneratedStakeModifier = true; return true; } // The stake modifier used to hash for a stake kernel is chosen as the stake // modifier about a selection interval later than the coin generating the kernel static bool GetKernelStakeModifier(uint256 hashBlockFrom, uint64& nStakeModifier, int& nStakeModifierHeight, int64& nStakeModifierTime, bool fPrintProofOfStake) { nStakeModifier = 0; if (!mapBlockIndex.count(hashBlockFrom)) return error("GetKernelStakeModifier() : block not indexed"); const CBlockIndex* pindexFrom = mapBlockIndex[hashBlockFrom]; nStakeModifierHeight = pindexFrom->nHeight; nStakeModifierTime = pindexFrom->GetBlockTime(); int64 nStakeModifierSelectionInterval = GetStakeModifierSelectionInterval(); const CBlockIndex* pindex = pindexFrom; // loop to find the stake modifier later by a selection interval while (nStakeModifierTime < pindexFrom->GetBlockTime() + nStakeModifierSelectionInterval) { if (!pindex->pnext) { // reached best block; may happen if node is behind on block chain if (fPrintProofOfStake || (pindex->GetBlockTime() + nStakeMinAge - nStakeModifierSelectionInterval > GetAdjustedTime())) return error("GetKernelStakeModifier() : reached best block %s at height %d from block %s", pindex->GetBlockHash().ToString().c_str(), pindex->nHeight, hashBlockFrom.ToString().c_str()); else return false; } pindex = pindex->pnext; if (pindex->GeneratedStakeModifier()) { nStakeModifierHeight = pindex->nHeight; nStakeModifierTime = pindex->GetBlockTime(); } } nStakeModifier = pindex->nStakeModifier; return true; } // ppcoin kernel protocol // coinstake must meet hash target according to the protocol: // kernel (input 0) must meet the formula // hash(nStakeModifier + txPrev.block.nTime + txPrev.offset + txPrev.nTime + txPrev.vout.n + nTime) < bnTarget * nCoinDayWeight // this ensures that the chance of getting a coinstake is proportional to the // amount of coin age one owns. // The reason this hash is chosen is the following: // nStakeModifier: scrambles computation to make it very difficult to precompute // future proof-of-stake at the time of the coin's confirmation // txPrev.block.nTime: prevent nodes from guessing a good timestamp to // generate transaction for future advantage // txPrev.offset: offset of txPrev inside block, to reduce the chance of // nodes generating coinstake at the same time // txPrev.nTime: reduce the chance of nodes generating coinstake at the same // time // txPrev.vout.n: output number of txPrev, to reduce the chance of nodes // generating coinstake at the same time // block/tx hash should not be used here as they can be generated in vast // quantities so as to generate blocks faster, degrading the system back into // a proof-of-work situation. // bool CheckStakeKernelHash(unsigned int nBits, const CBlock& blockFrom, unsigned int nTxPrevOffset, const CTransaction& txPrev, const COutPoint& prevout, unsigned int nTimeTx, uint256& hashProofOfStake, uint256& targetProofOfStake, bool fPrintProofOfStake) { if (nTimeTx < txPrev.nTime) // Transaction timestamp violation return error("CheckStakeKernelHash() : nTime violation"); unsigned int nTimeBlockFrom = blockFrom.GetBlockTime(); if (nTimeBlockFrom + nStakeMinAge > nTimeTx) // Min age requirement return error("CheckStakeKernelHash() : min age violation"); CBigNum bnTargetPerCoinDay; bnTargetPerCoinDay.SetCompact(nBits); int64 nValueIn = txPrev.vout[prevout.n].nValue; uint256 hashBlockFrom = blockFrom.GetHash(); CBigNum bnCoinDayWeight = CBigNum(nValueIn) * GetWeight((int64)txPrev.nTime, (int64)nTimeTx) / COIN / (24 * 60 * 60); targetProofOfStake = (bnCoinDayWeight * bnTargetPerCoinDay).getuint256(); // Calculate hash CDataStream ss(SER_GETHASH, 0); uint64 nStakeModifier = 0; int nStakeModifierHeight = 0; int64 nStakeModifierTime = 0; if (!GetKernelStakeModifier(hashBlockFrom, nStakeModifier, nStakeModifierHeight, nStakeModifierTime, fPrintProofOfStake)) return false; ss << nStakeModifier; ss << nTimeBlockFrom << nTxPrevOffset << txPrev.nTime << prevout.n << nTimeTx; hashProofOfStake = Hash(ss.begin(), ss.end()); if (fPrintProofOfStake) { printf("CheckStakeKernelHash() : using modifier 0x%016"PRI64x" at height=%d timestamp=%s for block from height=%d timestamp=%s\n", nStakeModifier, nStakeModifierHeight, DateTimeStrFormat(nStakeModifierTime).c_str(), mapBlockIndex[hashBlockFrom]->nHeight, DateTimeStrFormat(blockFrom.GetBlockTime()).c_str()); printf("CheckStakeKernelHash() : check modifier=0x%016"PRI64x" nTimeBlockFrom=%u nTxPrevOffset=%u nTimeTxPrev=%u nPrevout=%u nTimeTx=%u hashProof=%s\n", nStakeModifier, nTimeBlockFrom, nTxPrevOffset, txPrev.nTime, prevout.n, nTimeTx, hashProofOfStake.ToString().c_str()); } // Now check if proof-of-stake hash meets target protocol if (CBigNum(hashProofOfStake) > bnCoinDayWeight * bnTargetPerCoinDay) return false; if (fDebug && !fPrintProofOfStake) { printf("CheckStakeKernelHash() : using modifier 0x%016"PRI64x" at height=%d timestamp=%s for block from height=%d timestamp=%s\n", nStakeModifier, nStakeModifierHeight, DateTimeStrFormat(nStakeModifierTime).c_str(), mapBlockIndex[hashBlockFrom]->nHeight, DateTimeStrFormat(blockFrom.GetBlockTime()).c_str()); printf("CheckStakeKernelHash() : pass modifier=0x%016"PRI64x" nTimeBlockFrom=%u nTxPrevOffset=%u nTimeTxPrev=%u nPrevout=%u nTimeTx=%u hashProof=%s\n", nStakeModifier, nTimeBlockFrom, nTxPrevOffset, txPrev.nTime, prevout.n, nTimeTx, hashProofOfStake.ToString().c_str()); } return true; } // Check kernel hash target and coinstake signature bool CheckProofOfStake(const CTransaction& tx, unsigned int nBits, uint256& hashProofOfStake, uint256& targetProofOfStake) { if (!tx.IsCoinStake()) return error("CheckProofOfStake() : called on non-coinstake %s", tx.GetHash().ToString().c_str()); // Kernel (input 0) must match the stake hash target per coin age (nBits) const CTxIn& txin = tx.vin[0]; // First try finding the previous transaction in database CTxDB txdb("r"); CTransaction txPrev; CTxIndex txindex; if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex)) return tx.DoS(1, error("CheckProofOfStake() : INFO: read txPrev failed")); // previous transaction not in main chain, may occur during initial download // Verify signature if (!VerifySignature(txPrev, tx, 0, true, 0)) return tx.DoS(100, error("CheckProofOfStake() : VerifySignature failed on coinstake %s", tx.GetHash().ToString().c_str())); // Read block header CBlock block; if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false)) return fDebug? error("CheckProofOfStake() : read block failed") : false; // unable to read block of previous transaction if (!CheckStakeKernelHash(nBits, block, txindex.pos.nTxPos - txindex.pos.nBlockPos, txPrev, txin.prevout, tx.nTime, hashProofOfStake, targetProofOfStake, fDebug)) return tx.DoS(1, error("CheckProofOfStake() : INFO: check kernel failed on coinstake %s, hashProof=%s", tx.GetHash().ToString().c_str(), hashProofOfStake.ToString().c_str())); // may occur during initial download or if behind on block chain sync return true; } // Check whether the coinstake timestamp meets protocol bool CheckCoinStakeTimestamp(int64 nTimeBlock, int64 nTimeTx) { // v0.3 protocol return (nTimeBlock == nTimeTx); } // Get stake modifier checksum unsigned int GetStakeModifierChecksum(const CBlockIndex* pindex) { assert (pindex->pprev || pindex->GetBlockHash() == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet)); // Hash previous checksum with flags, hashProofOfStake and nStakeModifier CDataStream ss(SER_GETHASH, 0); if (pindex->pprev) ss << pindex->pprev->nStakeModifierChecksum; ss << pindex->nFlags << pindex->hashProofOfStake << pindex->nStakeModifier; uint256 hashChecksum = Hash(ss.begin(), ss.end()); hashChecksum >>= (256 - 32); return hashChecksum.Get64(); } // Check stake modifier hard checkpoints bool CheckStakeModifierCheckpoints(int nHeight, unsigned int nStakeModifierChecksum) { MapModifierCheckpoints& checkpoints = (fTestNet ? mapStakeModifierCheckpointsTestNet : mapStakeModifierCheckpoints); if (checkpoints.count(nHeight)) return nStakeModifierChecksum == checkpoints[nHeight]; return true; }
Rimbit/Wallets
src/kernel.cpp
C++
mit
18,814
<?php class Html { public static function LinkCSS($filename) { $link = Configuration::$base_dir."/Ressources/css/".$filename; return($link); } public static function LinkImage($filename) { $link = Configuration::$base_dir."/Ressources/images/".$filename; return($link); } public static function LinkJS($filename) { $link = Configuration::$base_dir."/Ressources/js/".$filename; return($link); } public static function Link($bundle, $action, array $params = null) { if (!isset($params)) return(Configuration::$base_dir."/".$bundle."/".$action); else { $link = Configuration::$base_dir."/".$bundle."/".$action; foreach ($params as $p) $link = $link."/".$p; return ($link); } } }
abclive/Lightning
Core/Html.php
PHP
mit
729
require 'cnpj' module Presenter class CNPJ < Each def output ::CNPJ.new(value).formatted end end end
thiagoa/super_form
lib/presenter/cnpj.rb
Ruby
mit
120
package main import ( "net/http" "github.com/freehaha/token-auth" "github.com/freehaha/token-auth/memory" "github.com/gorilla/mux" ) // Route type is used to define a route of the API type Route struct { Name string Method string Pattern string HandlerFunc http.HandlerFunc } // Routes type is an array of Route type Routes []Route // NewRouter is the constructeur of the Router // It will create every routes from the routes variable just above func NewRouter() *mux.Router { tokenAuth := tauth.NewTokenAuth(nil, nil, memStore, nil) router := mux.NewRouter().StrictSlash(true) for _, route := range publicRoutes { router. Methods(route.Method). Path(route.Pattern). Name(route.Name). Handler(route.HandlerFunc) } for _, route := range routes { router. Methods(route.Method). Path(route.Pattern). Name(route.Name). Handler(tokenAuth.HandleFunc(route.HandlerFunc)) } return router } var memStore = memstore.New("salty") var publicRoutes = Routes{ Route{"LogUser", "GET", "/user/{id}/login/{token}", LogUserController}, } var routes = Routes{ //Debt Route{"GetDebt", "GET", "/debt/{id}", GetDebtController}, Route{"DeleteDebt", "DELETE", "/debt/{id}", DeleteDebtController}, Route{"AddImageDebt", "POST", "/debt/{id}/image", AddImageDebtController}, Route{"ReimburseDebt", "PUT", "/debt/{id}", ReimburseDebtController}, //User + Debt Route{"GetMyDebts", "GET", "/user/{userID}/mydebt", GetMyDebtsController}, Route{"GetTheirDebts", "GET", "/user/{userID}/debt", GetTheirDebtsController}, Route{"CreateDebt", "POST", "/user/{userID}/debt", CreateDebtController}, //User Route{"GetUser", "GET", "/user/{id}", GetUserController}, Route{"CreateUser", "POST", "/user", CreateUserController}, Route{"DeleteUser", "DELETE", "/user/{id}", DeleteUserController}, Route{"AddPayee", "POST", "/user/{id}/payee/{payeeID}", AddPayeeController}, Route{"RemovePayee", "DELETE", "/user/{id}/payee/{payeeID}", RemovePayeeController}, //Notification Route{"GetNotification", "GET", "/user/{id}/notification", GetNotificationController}, }
fthomasmorel/reimburse-me-golang
routes.go
GO
mit
2,108
#include "smd3d.h" #define SMSFACE_MAX 1000 //Àӽà ÆäÀ̽º ¸ñ·Ï ÀúÀå Àå¼Ò smSTAGE_FACE *smFaceList[ SMSFACE_MAX ]; int smFaceListCnt; //°É¾î ´Ù´Ò¼ö ÀÖ´Â ÃÖ´ë °íÀúÂ÷ int Stage_StepHeight = 10*fONE; int smStage_WaterChk; //¹° ýũ¿ë Ç÷¢ smSTAGE_FACE *CheckFace=0; //Æò¸é°ú 1Á¡ÀÇ À§Ä¡ÀÇ °ªÀ» ±¸ÇÔ ( Æò¸é ¹æÁ¤½Ä ) int smGetPlaneProduct( POINT3D *p1 , POINT3D *p2 , POINT3D *p3 , POINT3D *p ) { int ux , uy , uz; int vx , vy , vz; int nx , ny , nz; int result; //º¤ÅÍ °è»ê ux = (p2->x - p1->x)>>6 ; uy = (p2->y - p1->y)>>6 ; uz = (p2->z - p1->z)>>6 ; vx = (p3->x - p1->x)>>6 ; vy = (p3->y - p1->y)>>6 ; vz = (p3->z - p1->z)>>6 ; //³ë¸» °è»ê nx = (uy*vz - uz*vy)>>2 ; ny = (uz*vx - ux*vz)>>2 ; nz = (ux*vy - uy*vx)>>2 ; //Æò¸é ¹æÁ¤½Ä¿¡ ´ëÀÔ result = ( nx*((p->x-p1->x)>>6) + ny*((p->y-p1->y)>>6) + nz*((p->z-p1->z)>>6) ); return result; }; //Æò¸é°ú 1Á¡ÀÇ À§Ä¡ÀÇ °ªÀ» ±¸ÇÔ ( Æò¸é ¹æÁ¤½Ä ) int smGetThroughPlane( POINT3D *p1 , POINT3D *p2 , POINT3D *p3 , POINT3D *sp , POINT3D *ep , POINT3D *cp ) { int ux , uy , uz; int vx , vy , vz; int nx , ny , nz; int denominator , t; int lx,ly,lz; //º¤ÅÍ °è»ê ux = (p2->x - p1->x) ; uy = (p2->y - p1->y) ; uz = (p2->z - p1->z) ; vx = (p3->x - p1->x) ; vy = (p3->y - p1->y) ; vz = (p3->z - p1->z) ; //³ë¸» °è»ê nx = (uy*vz - uz*vy)>>3; ny = (uz*vx - ux*vz)>>3; nz = (ux*vy - uy*vx)>>3; lx = ep->x - sp->x; ly = ep->y - sp->y; lz = ep->z - sp->z; denominator = ( nx * lx + ny * ly + nz * lz )>>3; if ( denominator!=0 ) { t = (( ( -nx * sp->x + nx * p1->x ) + ( -ny * sp->y + ny * p1->y ) + ( -nz * sp->z + nz * p1->z ) )<<3)/ denominator; // if ( t>=0 && t<=fONE ) { if ( t>=0 && t<=8 ) { cp->x = sp->x + ((lx * t)>>3); cp->y = sp->y + ((ly * t)>>3); cp->z = sp->z + ((lz * t)>>3); return TRUE; } } return FALSE; }; /* BOOL CollisionLineVSPolygon( LPD3DVECTOR lpCollisionPoint, LPD3DVECTOR lpLineBegin, LPD3DVECTOR lpLineEnd, LPD3DVECTOR lpPolygonVtx1, LPD3DVECTOR lpPolygonVtx2, LPD3DVECTOR lpPolygonVtx3 ) { // 1) get Polygon normal vector(CrossProduct) D3DVECTOR PolygonNormal, u, v; u.x = lpPolygonVtx2->x - lpPolygonVtx1->x; u.y = lpPolygonVtx2->y - lpPolygonVtx1->y; u.z = lpPolygonVtx2->z - lpPolygonVtx1->z; v.x = lpPolygonVtx3->x - lpPolygonVtx1->x; v.y = lpPolygonVtx3->y - lpPolygonVtx1->y; v.z = lpPolygonVtx3->z - lpPolygonVtx1->z; PolygonNormal.x = u.y*v.z - u.z*v.y; PolygonNormal.y = u.z*v.x - u.x*v.z; PolygonNormal.z = u.x*v.y - u.y*v.x; // 2) get t of Line equation( 0 <= t <= 1 ) D3DVALUE denominator = ((PolygonNormal.x * ( lpLineEnd->x - lpLineBegin->x) ) + (PolygonNormal.y * ( lpLineEnd->y - lpLineBegin->y) ) + (PolygonNormal.z * ( lpLineEnd->z - lpLineBegin->z) ) ); D3DVALUE t; if( denominator != 0 ) { t = (( -PolygonNormal.x * lpLineBegin->x + PolygonNormal.x * lpPolygonVtx1->x) + ( -PolygonNormal.y * lpLineBegin->y + PolygonNormal.y * lpPolygonVtx1->y) + ( -PolygonNormal.z * lpLineBegin->z + PolygonNormal.z * lpPolygonVtx1->z) ) / denominator; if( ( t >= 0.0f ) && ( t <= 1.0f ) ) { lpCollisionPoint->x = lpLineBegin.x + (lpLineEnd->x - lpLineBegin->x) * t; lpCollisionPoint->y = lpLineBegin.y + (lpLineEnd->y - lpLineBegin->y) * t; lpCollisionPoint->z = lpLineBegin.z + (lpLineEnd->z - lpLineBegin->z) * t; return TRUE; } else return FALSE; } else return FALSE; } */ int smGetTriangleImact( POINT3D *p1 , POINT3D *p2 , POINT3D *p3 , POINT3D *sp , POINT3D *ep ) { int vx,vy,vz; POINT3D cp1, cp2, cp3; int c1,c2; c1 = smGetPlaneProduct( p1 , p2 , p3 , sp ); c2 = smGetPlaneProduct( p1 , p2 , p3 , ep ); if ( (c1<=0 && c2<=0) || ( c1>0 && c2>0 ) ) return FALSE; vx = (ep->x - sp->x)<<4; vy = (ep->y - sp->y)<<4; vz = (ep->z - sp->z)<<4; cp1.x = p1->x + vx; cp1.y = p1->y + vy; cp1.z = p1->z + vz; cp2.x = p2->x + vx; cp2.y = p2->y + vy; cp2.z = p2->z + vz; cp3.x = p3->x + vx; cp3.y = p3->y + vy; cp3.z = p3->z + vz; c1 = smGetPlaneProduct( p1 , p2 , &cp1 , sp ); if ( c1>=0 ) return FALSE; c1 = smGetPlaneProduct( p2 , p3 , &cp2 , sp ); if ( c1>=0 ) return FALSE; c1 = smGetPlaneProduct( p3 , p1 , &cp3 , sp ); if ( c1>=0 ) return FALSE; return TRUE; }; int smGetTriangleOnArea( smSTAGE_VERTEX *sp1 , smSTAGE_VERTEX *sp2 , smSTAGE_VERTEX *sp3 , POINT3D *sp ) { // int vx,vy,vz; POINT3D cp1, cp2, cp3; int c1;//,c2; POINT3D p1,p2,p3; p1.x = sp1->x; p1.y = sp1->y; p1.z = sp1->z; p2.x = sp2->x; p2.y = sp2->y; p2.z = sp2->z; p3.x = sp3->x; p3.y = sp3->y; p3.z = sp3->z; cp1.x = p1.x; cp1.y = p1.y - 32*fONE; cp1.z = p1.z; cp2.x = p2.x; cp2.y = p2.y - 32*fONE; cp2.z = p2.z; cp3.x = p3.x; cp3.y = p3.y - 32*fONE; cp3.z = p3.z; c1 = smGetPlaneProduct( &p1 , &p2 , &cp1 , sp ); if ( c1>=0 ) return FALSE; c1 = smGetPlaneProduct( &p2 , &p3 , &cp2 , sp ); if ( c1>=0 ) return FALSE; c1 = smGetPlaneProduct( &p3 , &p1 , &cp3 , sp ); if ( c1>=0 ) return FALSE; return TRUE; }; //Æò¸é°ú 1Á¡ÀÇ À§Ä¡ÀÇ °ªÀ» ±¸ÇÔ ( Æò¸é ¹æÁ¤½Ä ) int smSTAGE3D::GetPlaneProduct( smSTAGE_FACE *face , POINT3D *p ) { int result; smSTAGE_VERTEX *vp; vp = &Vertex[ face->Vertex[0] ]; //Æò¸é ¹æÁ¤½Ä¿¡ ´ëÀÔ result = ( (face->VectNormal[0]>>4) * ((p->x - vp->x)>>4) + (face->VectNormal[1]>>4) * ((p->y - vp->y)>>4) + (face->VectNormal[2]>>4) * ((p->z - vp->z)>>4) ); return result; }; //Æò¸é°ú 1Á¡ÀÇ À§Ä¡ÀÇ °ªÀ» ±¸ÇÔ ( Æò¸é ¹æÁ¤½Ä ) int smSTAGE3D::GetThroughPlane( smSTAGE_FACE *face , POINT3D *sp , POINT3D *ep ) { // int result; POINT3D p1,p2,p3,cp,ssp,eep; smSTAGE_VERTEX *vp; vp = &Vertex[ face->Vertex[0] ]; p1.x = vp->x>>5; p1.y = vp->y>>5; p1.z = vp->z>>5; vp = &Vertex[ face->Vertex[1] ]; p2.x = vp->x>>5; p2.y = vp->y>>5; p2.z = vp->z>>5; vp = &Vertex[ face->Vertex[2] ]; p3.x = vp->x>>5; p3.y = vp->y>>5; p3.z = vp->z>>5; ssp.x = sp->x>>5; ssp.y = sp->y>>5; ssp.z = sp->z>>5; eep.x = ep->x>>5; eep.y = ep->y>>5; eep.z = ep->z>>5; return smGetThroughPlane( &p1,&p2,&p3,&ssp,&eep,&cp ); }; //smGetThroughPlane smSTAGE_FACE *DebugFace = 0; WORD DebugFaceMat = 0; //°¢ ¶óÀÎÀÌ ÆäÀ̽º¸¦ °üÅëÇÏ´ÂÁö °Ë»çÇÑ´Ù ( ¸ðµç ¼±ºÐÀÌ °üÅëÇÏÁö ¾ÊÀ» °æ¿ì TRUE ±×¿ÜÀÇ °æ¿ì FALSE ) int smSTAGE3D::GetTriangleImact( smSTAGE_FACE *face, smLINE3D *pLines , int LineCnt ) { int vx,vy,vz; POINT3D p1,p2,p3; POINT3D cp; POINT3D *sp,*ep; int c1,c2; smSTAGE_VERTEX *vp; int cnt; int flag , TrueCnt; //ÆäÀ̽ºÀÇ ÁÂÇ¥3°³¸¦ Æ÷ÀÎÅÍ·Î ¸¸µë vp = &Vertex[ face->Vertex[0] ]; p1.x = vp->x; p1.y = vp->y; p1.z = vp->z; vp = &Vertex[ face->Vertex[1] ]; p2.x = vp->x; p2.y = vp->y; p2.z = vp->z; vp = &Vertex[ face->Vertex[2] ]; p3.x = vp->x; p3.y = vp->y; p3.z = vp->z; TrueCnt = 0; for(int cnt=0;cnt<LineCnt;cnt++ ) { sp = &pLines[cnt].sp; ep = &pLines[cnt].ep; flag = TRUE; if ( ((sp->y<p1.y && sp->y<p2.y && sp->y<p3.y) || (sp->y>p1.y && sp->y>p2.y && sp->y>p3.y) ) && ((ep->y<p1.y && ep->y<p2.y && ep->y<p3.y) || (ep->y>p1.y && ep->y>p2.y && ep->y>p3.y) ) ) flag = FALSE; if ( flag ) { //Æò¸éÀ» °üÅëÇÏ´ÂÁö È®ÀÎ c1 = GetPlaneProduct( face , sp ); c2 = GetPlaneProduct( face , ep ); if ( (c1<=0 && c2<=0) || ( c1>0 && c2>0 ) ) flag = FALSE; // if ( GetThroughPlane( face , sp , ep )==FALSE ) // flag = FALSE; //###################################################################################### //ÀÛ ¼º ÀÚ : ¿À ¿µ ¼® //if( flag == TRUE ) //{ // vx = (ep->x - sp->x)<<8; // vy = (ep->y - sp->y)<<8; // vz = (ep->z - sp->z)<<8; //} //»ï°¢Çü°ú ¿¬Àå¼± ÁÂÇ¥ Æò¸é Á¦ÀÛ if ( c1<=0 ) { vx = (ep->x - sp->x)<<8; vy = (ep->y - sp->y)<<8; vz = (ep->z - sp->z)<<8; } else { vx = (sp->x - ep->x)<<8; vy = (ep->y - ep->y)<<8; vz = (ep->z - ep->z)<<8; } //###################################################################################### // Åë°úÇÏ´Â ¼±ÀÌ »ï°¢Çü ¿µ¿ª ¾È¿¡ ÀÖ´ÂÁö Á¶»ç // 3°³ÀÇ °¡»óÀÇ Æò¸éÀ» ¸¸µé¾î Æò¸éÀ§Ä¡¸¦ È®ÀÎÇÏ´Â ¹æ¹ý if ( flag==TRUE ) { cp.x = p1.x + vx; cp.y = p1.y + vy; cp.z = p1.z + vz; c1 = smGetPlaneProduct( &p1 , &p2 , &cp , sp ); //###################################################################################### //ÀÛ ¼º ÀÚ : ¿À ¿µ ¼® //if( c2 >= 0 && c1 >= 0 ) // flag = FALSE; //else if( c2 < 0 && c1 < 0 ) // flag = FALSE; if ( c1>0 ) flag=FALSE; //###################################################################################### } if (flag==TRUE) { cp.x = p2.x + vx; cp.y = p2.y + vy; cp.z = p2.z + vz; c1 = smGetPlaneProduct( &p2 , &p3 , &cp , sp ); //###################################################################################### //ÀÛ ¼º ÀÚ : ¿À ¿µ ¼® //if( c2 >= 0 && c1 >= 0 ) // flag = FALSE; //else if( c2 < 0 && c1 < 0 ) // flag = FALSE; if ( c1>0 ) flag=FALSE; //###################################################################################### } if (flag==TRUE) { cp.x = p3.x + vx; cp.y = p3.y + vy; cp.z = p3.z + vz; c1 = smGetPlaneProduct( &p3 , &p1 , &cp , sp ); //###################################################################################### //ÀÛ ¼º ÀÚ : ¿À ¿µ ¼® //if( c2 >= 0 && c1 >= 0 ) // flag = FALSE; //else if( c2 < 0 && c1 < 0 ) // flag = FALSE; if ( c1>0 ) flag=FALSE; //###################################################################################### } if ( flag==TRUE ) { return TRUE; } } } return FALSE; } //TÀ̵¿ÇÒ À§Ä¡¸¦ TÀÚ ¶óÀÎÀ¸·Î ã´Â´Ù static int smMakeTLine( POINT3D *Posi , POINT3D *Angle , int dist , int ObjWidth , int ObjHeight, smLINE3D *Lines , POINT3D *ep ) { int width; int dist2 = dist+fONE*12; int PosiMinY = fONE*12; int PosiMaxY = ObjHeight-(ObjHeight>>2); width = ObjWidth>>2; GetMoveLocation( 0, 0, dist, Angle->x, Angle->y, Angle->z ); ep->x = Posi->x+GeoResult_X; ep->y = Posi->y+GeoResult_Y; ep->z = Posi->z+GeoResult_Z; GetMoveLocation( 0, PosiMinY, 0, Angle->x, Angle->y, Angle->z ); Lines[0].sp.x=Posi->x+GeoResult_X; Lines[0].sp.y=Posi->y+GeoResult_Y; Lines[0].sp.z=Posi->z+GeoResult_Z; GetMoveLocation( 0, PosiMinY, dist2, Angle->x, Angle->y, Angle->z ); Lines[0].ep.x=Posi->x+GeoResult_X; Lines[0].ep.y=Posi->y+GeoResult_Y; Lines[0].ep.z=Posi->z+GeoResult_Z; GetMoveLocation( 0, PosiMaxY, 0, Angle->x, Angle->y, Angle->z ); Lines[1].sp.x=Posi->x+GeoResult_X; Lines[1].sp.y=Posi->y+GeoResult_Y; Lines[1].sp.z=Posi->z+GeoResult_Z; GetMoveLocation( 0, PosiMaxY, dist2, Angle->x, Angle->y, Angle->z ); Lines[1].ep.x=Posi->x+GeoResult_X; Lines[1].ep.y=Posi->y+GeoResult_Y; Lines[1].ep.z=Posi->z+GeoResult_Z; GetMoveLocation( -width, PosiMinY, dist2, Angle->x, Angle->y, Angle->z ); Lines[2].sp.x=Posi->x+GeoResult_X; Lines[2].sp.y=Posi->y+GeoResult_Y; Lines[2].sp.z=Posi->z+GeoResult_Z; GetMoveLocation( width, PosiMinY, dist2, Angle->x, Angle->y, Angle->z ); Lines[2].ep.x=Posi->x+GeoResult_X; Lines[2].ep.y=Posi->y+GeoResult_Y; Lines[2].ep.z=Posi->z+GeoResult_Z; GetMoveLocation( -width, PosiMaxY, dist2, Angle->x, Angle->y, Angle->z ); Lines[3].sp.x=Posi->x+GeoResult_X; Lines[3].sp.y=Posi->y+GeoResult_Y; Lines[3].sp.z=Posi->z+GeoResult_Z; GetMoveLocation( width, PosiMaxY, dist2, Angle->x, Angle->y, Angle->z ); Lines[3].ep.x=Posi->x+GeoResult_X; Lines[3].ep.y=Posi->y+GeoResult_Y; Lines[3].ep.z=Posi->z+GeoResult_Z; return 4; } //XÀ̵¿ÇÒ À§Ä¡¸¦ X ¶óÀÎÀ¸·Î ã´Â´Ù static int smMakeXLine( POINT3D *Posi , POINT3D *Angle , int dist , int ObjWidth , int ObjHeight, smLINE3D *Lines , POINT3D *ep ) { int width; int dist2 = dist+fONE*12; int PosiMinY = fONE*15; int PosiMaxY = ObjHeight-(ObjHeight>>2); int left,right,top,bottom; width = ObjWidth>>2; GetMoveLocation( 0, 0, dist, Angle->x, Angle->y, Angle->z ); ep->x = Posi->x+GeoResult_X; ep->y = Posi->y+GeoResult_Y; ep->z = Posi->z+GeoResult_Z; left = -width; right = width; top = -width; bottom = width; GetMoveLocation( 0, PosiMinY, 0, Angle->x, Angle->y, Angle->z ); Lines[0].sp.x=Posi->x+GeoResult_X; Lines[0].sp.y=Posi->y+GeoResult_Y; Lines[0].sp.z=Posi->z+GeoResult_Z; GetMoveLocation( 0, PosiMinY, dist2, Angle->x, Angle->y, Angle->z ); Lines[0].ep.x=Posi->x+GeoResult_X; Lines[0].ep.y=Posi->y+GeoResult_Y; Lines[0].ep.z=Posi->z+GeoResult_Z; GetMoveLocation( 0, PosiMaxY, 0, Angle->x, Angle->y, Angle->z ); Lines[1].sp.x=Posi->x+GeoResult_X; Lines[1].sp.y=Posi->y+GeoResult_Y; Lines[1].sp.z=Posi->z+GeoResult_Z; GetMoveLocation( 0, PosiMaxY, dist2, Angle->x, Angle->y, Angle->z ); Lines[1].ep.x=Posi->x+GeoResult_X; Lines[1].ep.y=Posi->y+GeoResult_Y; Lines[1].ep.z=Posi->z+GeoResult_Z; GetMoveLocation( -width, PosiMinY, -width, Angle->x, Angle->y, Angle->z ); Lines[2].sp.x=ep->x+GeoResult_X; Lines[2].sp.y=ep->y+GeoResult_Y; Lines[2].sp.z=ep->z+GeoResult_Z; GetMoveLocation( width, PosiMinY, width, Angle->x, Angle->y, Angle->z ); Lines[2].ep.x=ep->x+GeoResult_X; Lines[2].ep.y=ep->y+GeoResult_Y; Lines[2].ep.z=ep->z+GeoResult_Z; GetMoveLocation( -width, PosiMaxY, width, Angle->x, Angle->y, Angle->z ); Lines[3].sp.x=ep->x+GeoResult_X; Lines[3].sp.y=ep->y+GeoResult_Y; Lines[3].sp.z=ep->z+GeoResult_Z; GetMoveLocation( width, PosiMaxY, -width, Angle->x, Angle->y, Angle->z ); Lines[3].ep.x=ep->x+GeoResult_X; Lines[3].ep.y=ep->y+GeoResult_Y; Lines[3].ep.z=ep->z+GeoResult_Z; return 6; } class smCHAR; //´Ù¸¥ ij¸¯ÅÍ¿ÍÀÇ À§Ä¡ °ãÄ¡´ÂÁö È®ÀÎ extern smCHAR *CheckOtherPlayPosi( int x, int y, int z ); //À̵¿ÇÒ ¹æÇâ°ú À§Ä¡¸¦ °Ë»çÇÏ¿© ÁÂÇ¥¸¦ µ¹·ÁÁØ´Ù int smSTAGE3D::CheckNextMove( POINT3D *Posi, POINT3D *Angle , POINT3D *MovePosi, int dist , int ObjWidth , int ObjHeight , int CheckOverLap ) { int he,height; // int num, fnum; int cnt; smSTAGE_FACE *face; // int CalcSum; POINT3D ep; POINT3D zAngle[3]; smLINE3D Lines[8]; //int left,right,top,bottom; if ( !Head ) return NULL; CheckFace = 0; smStage_WaterChk = CLIP_OUT; height = CLIP_OUT; zAngle[0].x = Angle->x; zAngle[0].y = Angle->y; zAngle[0].z = Angle->z; zAngle[1].x = Angle->x; zAngle[1].y = (Angle->y- 768) & ANGCLIP; zAngle[1].z = Angle->z; zAngle[2].x = Angle->x; zAngle[2].y = (Angle->y+ 768) & ANGCLIP; zAngle[2].z = Angle->z; int hy; int heFace; int acnt; int cnt2; int Sucess = 0; int Oly = Posi->y; int WaterHeight; int whe; hy = (ObjHeight+fONE*16384); acnt = MakeAreaFaceList( Posi->x-fONE*64*1 , Posi->z-fONE*64*1 , fONE*64*2 , fONE*64*2 , Posi->y+hy , Posi->y-hy ); if ( !acnt ) return NULL; int ccnt; int LineCnt; WaterHeight = CLIP_OUT; for( ccnt=0;ccnt<3;ccnt++ ) { LineCnt = smMakeTLine( Posi , &zAngle[ccnt] , dist , ObjWidth , ObjHeight, Lines , &ep ); // LineCnt = smMakeXLine( Posi , &zAngle[ccnt] , dist , ObjWidth , ObjHeight, Lines , &ep ); for(int cnt=0;cnt<acnt;cnt++ ) { face = smFaceList[cnt]; if ( smMaterial[ face->Vertex[3] ].MeshState & SMMAT_STAT_CHECK_FACE ) { he = GetPolyHeight( face , ep.x, ep.z ); if ( he!=CLIP_OUT ) { hy = he-ep.y; if ( hy< Stage_StepHeight ) {//10*fONE ) { if ( height<he ) { height = he; heFace = cnt; } } CheckFace = face; } } else { //if (smMaterial[ face->Vertex[3] ].Transparency!=0.1) { // //±âÁ¸¿¡ ¿øº». if (smMaterial[ face->Vertex[3] ].Transparency>0.1) { //###################################################################################### //ÀÛ ¼º ÀÚ : ¿À ¿µ ¼® if( smMaterial[face->Vertex[3]].Transparency > 0.1 || smMaterial[face->Vertex[3]].MeshState & sMATS_SCRIPT_ORG_WATER ) //###################################################################################### { //¹° ³ôÀÌ °è»ê he = GetPolyHeight( face , ep.x, ep.z ); if ( WaterHeight<he ) WaterHeight = he; } } } if ( height!=CLIP_OUT ) { smStage_WaterChk = WaterHeight; whe = (height+(ObjHeight>>1))+10*fONE; if ( WaterHeight!=CLIP_OUT && WaterHeight>whe && WaterHeight<whe+5*fONE ) { //¹°¼Ó¿¡ Àá±è //return FALSE; cnt2 = 0; } else { for( cnt2=0;cnt2<acnt;cnt2++ ) { if ( smMaterial[ smFaceList[cnt2]->Vertex[3] ].MeshState & SMMAT_STAT_CHECK_FACE ) { if ( GetTriangleImact( smFaceList[cnt2], Lines ,LineCnt )==TRUE ) { cnt2=-1; break; } } } } if ( cnt2>0 ) { if ( CheckOverLap ) { if ( ccnt>0 && CheckOtherPlayPosi( ep.x , height, ep.z )==NULL ) { MovePosi->x = ep.x; MovePosi->z = ep.z; MovePosi->y = height; Sucess = TRUE; return ccnt+1; } } else { MovePosi->x = ep.x; MovePosi->z = ep.z; MovePosi->y = height; Sucess = TRUE; return ccnt+1; } } } if ( ccnt==0 ) dist>>=1; } CheckFace = 0; return NULL; } //ÇöÀç À§Ä¡¿¡¼­ÀÇ ¹Ù´Ú ³ôÀ̸¦ ±¸ÇÑ´Ù int smSTAGE3D::GetFloorHeight( int x, int y, int z , int ObjHeight ) { int he,height; int cnt; smSTAGE_FACE *face; int hy; int acnt; hy = (ObjHeight+fONE*16384); acnt = MakeAreaFaceList( x-fONE*64*1 , z-fONE*64*1 , fONE*64*2 , fONE*64*2 , y+hy , y-hy ); if ( !acnt ) return CLIP_OUT; height = CLIP_OUT; for(int cnt=0;cnt<acnt;cnt++ ) { face = smFaceList[cnt]; if ( smMaterial[ face->Vertex[3] ].MeshState & SMMAT_STAT_CHECK_FACE ) { he = GetPolyHeight( face , x, z ); if ( he!=CLIP_OUT ) { hy = he-y; if ( hy<10*fONE ) { if ( height<he ) { height = he; } } } } } return height; } //ÇöÀç À§Ä¡¿¡¼­ÀÇ ¹Ù´Ú ³ôÀ̸¦ ±¸ÇÑ´Ù int smSTAGE3D::GetFloorHeight2( int x, int y, int z , int ObjHeight ) { int he,height; int cnt; smSTAGE_FACE *face; int hy; int acnt; hy = (ObjHeight+fONE*16384); acnt = MakeAreaFaceList( x-fONE*64*1 , z-fONE*64*1 , fONE*64*2 , fONE*64*2 , y+hy , y-hy ); if ( !acnt ) return CLIP_OUT; height = CLIP_OUT; for(int cnt=0;cnt<acnt;cnt++ ) { face = smFaceList[cnt]; if ( smMaterial[ face->Vertex[3] ].MeshState & SMMAT_STAT_CHECK_FACE ) { he = GetPolyHeight( face , x, z ); if ( he!=CLIP_OUT ) { hy = he-y; if ( hy>10*fONE ) { if ( height>he ) { height = he; } } } } } return height; } //ÇöÀç ³ôÀÌ¿¡ °ãÄ¡´Â Æú¸®°ïÀÌ ÀÖ´Â Áö È®ÀÎÈÄ ÀÖÀ¸¸é Àüü ³ôÀ̸¦ ±¸ÇÑ´Ù int smSTAGE3D::GetEmptyHeight( int x, int y, int z , int ObjHeight ) { int he,height; int cnt; smSTAGE_FACE *face; int hy; int acnt; int fchk; fchk = 0; hy = (ObjHeight+fONE*16384); acnt = MakeAreaFaceList( x-fONE*64*1 , z-fONE*64*1 , fONE*64*2 , fONE*64*2 , y+hy , y-hy ); if ( !acnt ) return CLIP_OUT; height = CLIP_OUT; for(int cnt=0;cnt<acnt;cnt++ ) { face = smFaceList[cnt]; if ( smMaterial[ face->Vertex[3] ].MeshState & SMMAT_STAT_CHECK_FACE ) { he = GetPolyHeight( face , x, z ); if ( he!=CLIP_OUT ) { if ( height<he ) { height = he; } if ( he<y+ObjHeight && he>y ) fchk++; } } } if ( fchk==0 ) return NULL; return height; } //¹Ù´Ú Æú¸®°ï ¸é¿¡ y==height ¿Í ÀÏÄ¡ÇÏ´ÂÁö È®ÀÎ int smSTAGE3D::CheckFloorFaceHeight( int x, int y, int z , int hSize ) { int cnt; smSTAGE_FACE *face; int height = 1000000; int acnt; int he; int hy = fONE*16384; acnt = MakeAreaFaceList( x-fONE*64*1 , z-fONE*64*1 , fONE*64*2 , fONE*64*2 , y+hy , y-hy ); if ( !acnt ) return CLIP_OUT; for(int cnt=0;cnt<acnt;cnt++ ) { face = smFaceList[cnt]; if ( smMaterial[ face->Vertex[3] ].MeshState & SMMAT_STAT_CHECK_FACE ) { he = abs(GetPolyHeight( face , x, z )-y); if ( he<height ) height = he; if ( he<=hSize ) return 0; } } if ( height==1000000 ) height = CLIP_OUT; return height; } //ÁöÁ¤µÈ ¹æÇâÀÇ °Å¸®¸¦ ÀÕ´Â ¼±ºÐ¿¡ Æú¸®°ÇÀÌ Ãæµ¹ÇÏ´ÂÁö È®ÀÎ int smSTAGE3D::CheckVecImpact( POINT3D *Posi, POINT3D *Angle , int dist ) { smLINE3D sLine[1]; if ( !Head ) return 0; int hy; int acnt; int cnt2; hy = (fONE*64); acnt = MakeAreaFaceList( Posi->x-fONE*64*1 , Posi->z-fONE*64*1 , fONE*64*2 , fONE*64*2 , Posi->y+hy , Posi->y-hy ); if ( !acnt ) return TRUE; memcpy( &sLine[0].sp , Posi , sizeof( POINT3D ) ); GetMoveLocation( 0, 0, dist, Angle->x, Angle->y, Angle->z ); sLine[0].ep.x = Posi->x+GeoResult_X; sLine[0].ep.y = Posi->y+GeoResult_Y; sLine[0].ep.z = Posi->z+GeoResult_Z; for( cnt2=0;cnt2<acnt;cnt2++ ) { if ( smMaterial[ smFaceList[cnt2]->Vertex[3] ].MeshState & SMMAT_STAT_CHECK_FACE ) { if ( GetTriangleImact( smFaceList[cnt2], sLine ,1 )==TRUE ) { Posi->x = sLine[0].ep.x; Posi->y = sLine[0].ep.y; Posi->z = sLine[0].ep.z; return FALSE; } } } Posi->x = sLine[0].ep.x; Posi->y = sLine[0].ep.y; Posi->z = sLine[0].ep.z; return TRUE; } //ÁöÁ¤µÈ ¹æÇâÀÇ °Å¸®¸¦ ÀÕ´Â ¼±ºÐ¿¡ Æú¸®°ÇÀÌ Ãæµ¹ÇÏ´ÂÁö È®ÀÎ int smSTAGE3D::CheckVecImpact2( int sx,int sy,int sz, int ex,int ey,int ez ) { smLINE3D sLine[1]; if ( !Head ) return 0; int hy; int acnt; int cnt2; hy = (fONE*128); acnt = MakeAreaFaceList( sx-fONE*64*1 , sz-fONE*64*1 , fONE*64*2 , fONE*64*2 , sy+hy , sy-hy ); if ( !acnt ) return TRUE; sLine[0].sp.x = sx; sLine[0].sp.y = sy; sLine[0].sp.z = sz; sLine[0].ep.x = ex; sLine[0].ep.y = ey; sLine[0].ep.z = ez; for( cnt2=0;cnt2<acnt;cnt2++ ) { if ( smMaterial[ smFaceList[cnt2]->Vertex[3] ].MeshState & SMMAT_STAT_CHECK_FACE ) { if ( GetTriangleImact( smFaceList[cnt2], sLine ,1 )==TRUE ) { return FALSE; } } } return TRUE; } smSTAGE3D::smSTAGE3D() { // ¶óÀÌÆ® º¤ÅÍ VectLight.x = fONE; VectLight.y = -fONE; VectLight.z = fONE/2; Bright = DEFAULT_BRIGHT; Contrast = DEFAULT_CONTRAST; Head = FALSE; smLight = 0; nLight = 0; MemMode = 0; } smSTAGE3D::~smSTAGE3D() { Close(); } smSTAGE3D::smSTAGE3D( int nv , int nf ) { // ¶óÀÌÆ® º¤ÅÍ VectLight.x = fONE; VectLight.y = -fONE; VectLight.z = fONE/2; Bright = DEFAULT_BRIGHT; Contrast = DEFAULT_CONTRAST; Head = FALSE; smLight = 0; nLight = 0; MemMode = 0; Init( nv, nf ); } //###################################################################################### //ÀÛ ¼º ÀÚ : ¿À ¿µ ¼® void smSTAGE3D::Init(void) { nLight = 0; nTexLink = 0; nFace = 0; nVertex = 0; ::ZeroMemory( StageArea, sizeof(StageArea) ); AreaList = NULL; Vertex = NULL; Face = NULL; TexLink = NULL; smLight = NULL; smMaterialGroup = NULL; StageObject = NULL; smMaterial = NULL; lpwAreaBuff = NULL; } //###################################################################################### int smSTAGE3D::Init( int nv , int nf ) { Vertex = new smSTAGE_VERTEX[ nv ]; Face = new smSTAGE_FACE[ nf ]; TexLink = new smTEXLINK[ nf * 4 ]; StageObject = new smSTAGE_OBJECT; nVertex = 0; nFace = 0; nTexLink = 0; nVertColor = 0; SumCount = 0; CalcSumCount = 0; smMaterialGroup = 0; lpwAreaBuff = 0; StageMapRect.top = 0; StageMapRect.bottom = 0; StageMapRect.left = 0; StageMapRect.right = 0; clearStageArea(); return TRUE; } int smSTAGE3D::Close() { Head = 0; /* int cnt,cnt2; int num; for( cnt2=MAP_SIZE-1;cnt2>=0;cnt2--) { for( cnt=MAP_SIZE-1;cnt>=0;cnt-- ) { num = (int)StageArea[ cnt ][ cnt2 ]; if ( num>0 ) { delete StageArea[cnt][cnt2]; } } } */ /* MemMode smLIGHT3D *smLight; //Á¶¸í ¼³Á¤ int nLight; //Á¶¸í ¼ö */ if ( nLight ) delete smLight; if ( lpwAreaBuff ) delete lpwAreaBuff; if ( nTexLink ) delete TexLink; if ( nFace ) delete Face; if ( nVertex ) delete Vertex; if ( StageObject ) delete StageObject; if ( smMaterialGroup ) delete smMaterialGroup; return TRUE; } //¹öÅØ½º ÁÂÇ¥ Ãß°¡ int smSTAGE3D::AddVertex ( int x, int y, int z ) { Vertex[nVertex].sum = 0; Vertex[nVertex].x = x; Vertex[nVertex].y = y; Vertex[nVertex].z = z; Vertex[nVertex].sDef_Color[ SMC_R ] = 255; Vertex[nVertex].sDef_Color[ SMC_G ] = 255; Vertex[nVertex].sDef_Color[ SMC_B ] = 255; Vertex[nVertex].sDef_Color[ SMC_A ] = 255; if ( nVertex==0 ) { //¸ÇóÀ½ °ªÀ¸·Î ÃʱâÈ­ StageMapRect.top = z; StageMapRect.bottom = z; StageMapRect.left = x; StageMapRect.right = x; } else { //Á¸Àç ÇÏ´Â ±¸¿ªÅ©±â ¼³Á¤ if ( StageMapRect.top>z ) StageMapRect.top = z; if ( StageMapRect.bottom<z ) StageMapRect.bottom = z; if ( StageMapRect.left>x ) StageMapRect.left = x; if ( StageMapRect.right<x ) StageMapRect.right = x; } nVertex++; return (nVertex-1); } //ÆäÀ̽º Ãß°¡ int smSTAGE3D::AddFace ( int a, int b, int c , int matrial ) { Face[nFace].sum = 0; Face[nFace].Vertex[0] = a; Face[nFace].Vertex[1] = b; Face[nFace].Vertex[2] = c; Face[nFace].Vertex[3] = matrial; Face[nFace].lpTexLink = 0; // ÅØ½ºÃÄ ¿¬°á ÁÂÇ¥ nFace++; /* //µð¹ö±ë¿ë int x,z,sx,sz; x = abs( Vertex[a].x - Vertex[b].x ); if ( x>64*30*fONE ) { x = x; } x = abs( Vertex[b].x - Vertex[c].x ); if ( x>64*30*fONE ) { x = x; } x = abs( Vertex[c].x - Vertex[a].x ); if ( x>64*30*fONE ) { x = x; } x = abs( Vertex[a].z - Vertex[b].z ); if ( x>64*30*fONE ) { x = x; } x = abs( Vertex[b].z - Vertex[c].z ); if ( x>64*30*fONE ) { x = x; } x = abs( Vertex[c].z - Vertex[a].z ); if ( x>64*30*fONE ) { x = x; } */ return nFace-1; } //ÆäÀ̽º¿¡ ¸ÞÆ®¸®¾ó ÀÔ·Â int smSTAGE3D::SetFaceMaterial( int FaceNum , int MatNum ) { Face[ FaceNum ].Vertex[3] = MatNum; return TRUE; } //¹öÅØ½º¿¡ »ö ¼³Á¤ int smSTAGE3D::SetVertexColor ( DWORD NumVertex , BYTE r , BYTE g, BYTE b , BYTE a ) { Vertex[ NumVertex ].sDef_Color[ SMC_R ] = r; Vertex[ NumVertex ].sDef_Color[ SMC_G ] = g; Vertex[ NumVertex ].sDef_Color[ SMC_B ] = b; Vertex[ NumVertex ].sDef_Color[ SMC_A ] = a; return TRUE; } //ÅØ½ºÃÄ ÁÂÇ¥¿¬°áÀ» Ãß°¡ÇÑ´Ù int smSTAGE3D::AddTexLink( int FaceNum , DWORD *hTex , smFTPOINT *t1 , smFTPOINT *t2 , smFTPOINT *t3 ) { int cnt; smTEXLINK *tl; //ÁÂÇ¥¼³Á¤ TexLink[ nTexLink ].u[0] = t1->u; TexLink[ nTexLink ].v[0] = t1->v; TexLink[ nTexLink ].u[1] = t2->u; TexLink[ nTexLink ].v[1] = t2->v; TexLink[ nTexLink ].u[2] = t3->u; TexLink[ nTexLink ].v[2] = t3->v; TexLink[ nTexLink ].hTexture = hTex; TexLink[ nTexLink ].NextTex = 0; //ÁöÁ¤µÈ ÆäÀ̽º¿Í ¿¬°á½ÃŲ´Ù if ( !Face[FaceNum].lpTexLink ) { //ÃÖÃÊÀÇ ÅØ½ºÃÄÁÂÇ¥ÀÏ °æ¿ì Face[FaceNum].lpTexLink = &TexLink[ nTexLink ]; } else { //ÀÌ¹Ì ¿¬°áµÇÀÖ´Â ÁÂÇ¥°¡ Àִ°æ¿ì tl = Face[FaceNum].lpTexLink; for(int cnt=0;cnt<8;cnt++ ) { if ( !tl->NextTex ) { //¸¶Áö¸·À¸·Î ¿¬°áµÈ ÁÂÇ¥¸¦ ã¾Æ ¿¬°á tl->NextTex = &TexLink[ nTexLink ]; break; } else { //´ÙÀ½ ÁÂÇ¥·Î ³Ñ±è tl = tl->NextTex; } } } nTexLink++; return nTexLink-1; } //³ë¸» °ªÀ» ±¸ÇÏ¿© ¹öÅØ½º¿¡ ½¦À̵ù ¸í¾ÏÀ» Ãß°¡ÇÑ´Ù //###################################################################################### //ÀÛ ¼º ÀÚ : ¿À ¿µ ¼® int smSTAGE3D::SetVertexShade( int isSetLight ) //###################################################################################### { int cnt; int cnt2; POINT3D p[3]; POINT3D pn; POINT3D *normal; POINT3D pLight; int *NormalCnt; int gShade; int r,g,b; memcpy( &pLight , &VectLight , sizeof( POINT3D ) ); normal = new POINT3D[nVertex]; NormalCnt = new int [nVertex]; // Normal°ª ÃʱâÈ­ for(int cnt=0; cnt<nVertex ;cnt++) { normal[cnt].x = 0; normal[cnt].y = 0; normal[cnt].z = 0; NormalCnt[cnt] = 0; } // NormalÁÂÇ¥ ±¸ÇÔ for(int cnt=0; cnt<nFace; cnt++ ) { for(cnt2=0;cnt2<3;cnt2++) { p[cnt2].x = Vertex[ Face[cnt].Vertex[cnt2] ].x>>FLOATNS; p[cnt2].y = Vertex[ Face[cnt].Vertex[cnt2] ].y>>FLOATNS; p[cnt2].z = Vertex[ Face[cnt].Vertex[cnt2] ].z>>FLOATNS; } SetNormal( &p[0], &p[1], &p[2] , &pn ); //Face ³ë¸»º¤ÅÍ ¼³Á¤ Face[cnt].VectNormal[0] = (short)pn.x; Face[cnt].VectNormal[1] = (short)pn.y; Face[cnt].VectNormal[2] = (short)pn.z; for(cnt2=0;cnt2<3;cnt2++) { normal[ Face[cnt].Vertex[cnt2] ].x += pn.x; normal[ Face[cnt].Vertex[cnt2] ].y += pn.y; normal[ Face[cnt].Vertex[cnt2] ].z += pn.z; NormalCnt[ Face[cnt].Vertex[cnt2] ] ++; } } // gShade ³ë¸» ±¸ÇÑµÚ RGBA·Î ¹öÅØ½º¿¡ ÀúÀå for(int cnt=0; cnt<nVertex; cnt++ ) { if ( NormalCnt[ cnt ]>0 ) { normal[ cnt ].x /= NormalCnt[cnt]; normal[ cnt ].y /= NormalCnt[cnt]; normal[ cnt ].z /= NormalCnt[cnt]; } pn.x = normal[ cnt ].x; pn.y = normal[ cnt ].y; pn.z = normal[ cnt ].z; //###################################################################################### //ÀÛ ¼º ÀÚ : ¿À ¿µ ¼® if( isSetLight ) { gShade = ((pn.x * pLight.x) + (pn.y * pLight.y) + (pn.z * pLight.z)) >> FLOATNS; gShade /= Contrast; //CONTRAST gShade += Bright; //BRIGHT r = Vertex[ cnt ].sDef_Color[ SMC_R ]; g = Vertex[ cnt ].sDef_Color[ SMC_G ]; b = Vertex[ cnt ].sDef_Color[ SMC_B ]; r = ( r*gShade )>>8; // %1ºñÀ² x 0 ~ 2 ±îÁö g = ( g*gShade )>>8; b = ( b*gShade )>>8; Vertex[ cnt ].sDef_Color[SMC_R] = r; Vertex[ cnt ].sDef_Color[SMC_G] = g; Vertex[ cnt ].sDef_Color[SMC_B] = b; Vertex[ cnt ].sDef_Color[SMC_A] = 255; //Alpha } //###################################################################################### } float transp; for(int cnt=0;cnt<nFace;cnt++) { transp = smMaterial[ Face[cnt].Vertex[3] ].Transparency; if ( transp>0 ) { for( cnt2=0;cnt2<3;cnt2++ ) { Vertex[ Face[cnt].Vertex[cnt2] ].sDef_Color[ SMC_A ] = 255-((BYTE)(transp * 255)); } } } delete NormalCnt; delete normal; return TRUE; } //¸ðµç ¹öÅØ½º¿¡ Á¶¸í°ªÀ» Ãß°¡ ÇÑ´Ù int smSTAGE3D::AddVertexLightRound( POINT3D *LightPos , int r, int g, int b, int Range ) { int cnt; double ddist; int dist; int dr,dg,db; int lx,ly,lz; int dRange; int x,y,z; int eLight; dRange = ((Range/256)*72) >>FLOATNS; dRange *= dRange; lx = LightPos->x; ly = LightPos->y; lz = LightPos->z; /* r/=8; g/=8; b/=8; */ for(int cnt=0; cnt<nVertex; cnt++ ) { x = (lx - Vertex[ cnt ].x)>>FLOATNS; y = (ly - Vertex[ cnt ].y)>>FLOATNS; z = (lz - Vertex[ cnt ].z)>>FLOATNS; /* if ( abs(x)>Range || abs(y)>Range || abs(z)>Range ) ddist = dRange; else ddist = x*x+y*y+z*z; */ ddist = x*x+y*y+z*z; if ( ddist<dRange ) { //Á¶¸í ¹üÀ§ ¾È¿¡ ÀÖÀ½ dist = (int)sqrt( ddist ); eLight = (Range>>FLOATNS)-dist; //eLight = dRange-ddist; eLight = fONE - ((eLight<<FLOATNS)/dRange); dr = (r * eLight)>>FLOATNS; dg = (g * eLight)>>FLOATNS; db = (b * eLight)>>FLOATNS; Vertex[cnt].sDef_Color[SMC_R] += dr; Vertex[cnt].sDef_Color[SMC_G] += dg; Vertex[cnt].sDef_Color[SMC_B] += db; if ( Vertex[cnt].sDef_Color[SMC_R]>360 ) Vertex[cnt].sDef_Color[SMC_R] = 360; if ( Vertex[cnt].sDef_Color[SMC_G]>360 ) Vertex[cnt].sDef_Color[SMC_G] = 360; if ( Vertex[cnt].sDef_Color[SMC_B]>360 ) Vertex[cnt].sDef_Color[SMC_B] = 360; /* Vertex[cnt].sDef_Color[0] += db; Vertex[cnt].sDef_Color[1] += dg; Vertex[cnt].sDef_Color[2] += dr; */ /* if ( Vertex[cnt].sDef_Color[0]>420 ) Vertex[cnt].sDef_Color[0]=420; if ( Vertex[cnt].sDef_Color[1]>420 ) Vertex[cnt].sDef_Color[1]=420; if ( Vertex[cnt].sDef_Color[2]>420 ) Vertex[cnt].sDef_Color[2]=420; */ } } return TRUE; } //µ¿Àû Á¶¸í ÃʱâÈ­ ( ¼³Á¤ °¹¼ö ) int smSTAGE3D::InitDynLight( int nl ) { nLight = 0; smLight = new smLIGHT3D[ nl ]; return TRUE; } //¸ðµç ¹öÅØ½º¿¡ Á¶¸í°ªÀ» Ãß°¡ ÇÑ´Ù int smSTAGE3D::AddDynLight( int type , POINT3D *LightPos , int r, int g, int b, int Range ) { smLight[nLight].type = type; smLight[nLight].x = LightPos->x; smLight[nLight].y = LightPos->y; smLight[nLight].z = LightPos->z; smLight[nLight].r = r; smLight[nLight].g = g; smLight[nLight].b = b; smLight[nLight].Range = Range; nLight++; return TRUE; } //###################################################################################### //ÀÛ ¼º ÀÚ : ¿À ¿µ ¼® int smSTAGE3D::CheckFaceIceFoot( POINT3D *Pos, POINT3D *Angle, int CheckHeight ) { int num = CheckHeight + (fONE*16384); int acnt = MakeAreaFaceList( Pos->x - (fONE*64*1), Pos->z - (fONE*64*1), fONE*64*2, fONE*64*2, Pos->y+num, Pos->y-num ); if( ! acnt ) return 0; smSTAGE_FACE *face; int faceNum = 0, faceheight = CLIP_OUT; for( int cnt=0; cnt < acnt; cnt++ ) { face = smFaceList[ cnt ]; num = smMaterial[ face->Vertex[3] ].MeshState; if( (num & SMMAT_STAT_CHECK_FACE) && (num & sMATS_SCRIPT_CHECK_ICE) ) { num = GetPolyHeight( face, Pos->x, Pos->z ); if( num != CLIP_OUT ) { if( (num - Pos->y) < 10 * fONE ) { if( faceheight < num ) { faceheight = num; faceNum = cnt; } } } } } if( faceNum == 0 ) return 0; face = smFaceList[ faceNum ]; Angle->x = GetRadian2D( 0, -1024, face->VectNormal[2], face->VectNormal[1] ); Angle->z = GetRadian2D( 0, -1024, face->VectNormal[0], face->VectNormal[1] ); Pos->y = faceheight + (1*fONE); return 1; } //###################################################################################### /* MemMode smLIGHT3D *smLight; //Á¶¸í ¼³Á¤ int nLight; //Á¶¸í ¼ö struct smLIGHT3D { int type; int x,y,z; int Range; BYTE r,g,b; }; */ /* // ¹öÅØ½º struct smSTAGE_VERTEX { DWORD sum; // ÃÖ±Ù ¿¬»ê ¹øÈ£ smRENDVERTEX *lpRendVertex; // ·»´õ¸µÀ» À§ÇÑ ¹öÅØ½º Æ÷ÀÎÅÍ // ¼Ò½º ¹öÅØ½º int x,y,z; // ¿ùµå ÁÂÇ¥ //BYTE bDef_Color[4]; // ±âº» »ö»ó (RGBA)(Color ) //BYTE bDef_Specular[4]; // ±âº» »ö»ó (RGBA)(Specular ) short sDef_Color[4]; // ±âº» »ö»ó ( RGBA ) }; // ÇöÀç Å©±â 28 ¹ÙÀÌÆ® */ //Àӽà ÆäÀ̽º ¸ñ·ÏÀ» ÀÛ¼ºÇÑ´Ù int smSTAGE3D::MakeAreaFaceList( int x,int z, int width, int height , int top , int bottom ) { int cnt; smSTAGE_FACE *face; int CalcSum; int wx,wz; int lx,lz; int num,fnum; int cntX , cntZ; int sx,sz; int y1,y2,y3; smFaceListCnt = 0; CalcSumCount++; CalcSum = CalcSumCount; sx = (x>>(FLOATNS+6))&0xFF; sz = (z>>(FLOATNS+6))&0xFF; wx = sx+(width>>(FLOATNS+6)); wz = sz+(height>>(FLOATNS+6)); //###################################################################################### //ÀÛ ¼º ÀÚ : ¿À ¿µ ¼® //for( cntX=sx; cntX <= wx; cntX++ ) //{ // for( cntZ=sz; cntZ <= wz; cntZ++ ) for( cntX=sx; cntX < wx; cntX++ ) { for( cntZ=sz; cntZ < wz; cntZ++ ) { //###################################################################################### lx=cntX&0xFF; lz=cntZ&0xFF; if ( StageArea[lx][lz] ) { //¿µ¿ª num = StageArea[lx][lz][0]; //¿µ¿ª¿¡ Æ÷ÇÔµÈ ÆäÀ̽º ¼ö for( cnt=1;cnt<num+1;cnt++ ) { fnum = StageArea[lx][lz][cnt]; face = &Face[ fnum ]; if ( face->CalcSum!=CalcSum ) { face->CalcSum = CalcSum; y1 = Vertex[face->Vertex[0]].y; y2 = Vertex[face->Vertex[1]].y; y3 = Vertex[face->Vertex[2]].y; if ( (y1<top && y1>bottom) || (y2<top && y2>bottom) || (y3<top && y3>bottom) ) smFaceList[ smFaceListCnt ++] = face; } } } } } CalcSumCount++; return smFaceListCnt; } //ÆäÀ̽º¿¡ ÇØ´çÇÏ´Â ³ôÀ̸¦ ±¸ÇÑ´Ù int smSTAGE3D::GetPolyHeight( smSTAGE_FACE *face , int x, int z ) { smSTAGE_VERTEX *p[3]; smSTAGE_VERTEX *ptop, *pmid , *pbot; int cnt; int lx , tx , bx; int ly , ty , by; int lz , tz , bz; int x1 , x2; int y1 , y2; int ye,xe; int yl; p[0] = &Vertex[ face->Vertex[0] ]; p[1] = &Vertex[ face->Vertex[1] ]; p[2] = &Vertex[ face->Vertex[2] ]; ptop = p[0]; pbot = p[1]; pmid = p[2]; //ÃÖ»óÀ§ Æ÷ÀÎÆ® for(cnt=0;cnt<3;cnt++) { if ( p[cnt]->z<ptop->z ) ptop = p[cnt]; } if ( ptop==pbot ) pbot = pmid; //ÃÖÇÏÀ§ Æ÷ÀÎÆ® for(cnt=0;cnt<3;cnt++) { if ( p[cnt]->z>pbot->z && ptop!=p[cnt] ) pbot = p[cnt]; } //Áß°£ Æ÷ÀÎÆ® for(cnt=0;cnt<3;cnt++) { if ( ptop!=p[cnt] && pbot!=p[cnt] ) { pmid = p[cnt]; break; } } if ( z<ptop->z || z>pbot->z ) return CLIP_OUT; lz = pbot->z - ptop->z; tz = pmid->z - ptop->z; bz = pbot->z - pmid->z; if ( lz!=0 ) lx = ((pbot->x - ptop->x)<<FLOATNS) / lz ; else lx = 0; if ( tz!=0 ) tx = ((pmid->x - ptop->x)<<FLOATNS) / tz ; else tx = 0; if ( bz!=0 ) bx = ((pbot->x - pmid->x)<<FLOATNS) / bz ; else bx = 0; x1 = (( lx * ( z - ptop->z ) )>>FLOATNS) + ptop->x; if( z<pmid->z ) { x2 = (( tx * ( z - ptop->z ) )>>FLOATNS) + ptop->x; } else { x2 = (( bx * ( z - pmid->z ) )>>FLOATNS) + pmid->x; } if ( lz!=0 ) ly = ((pbot->y - ptop->y)<<FLOATNS) / lz ; else ly = 0; if ( tz!=0 ) ty = ((pmid->y - ptop->y)<<FLOATNS) / tz ; else ty = 0; if ( bz!=0 ) by = ((pbot->y - pmid->y)<<FLOATNS) / bz ; else by = 0; y1 = (( ly * ( z - ptop->z ) ) >>FLOATNS) + ptop->y; if( z<pmid->z ) { y2 = (( ty * ( z - ptop->z ) )>>FLOATNS) + ptop->y; } else { y2 = (( by * ( z - pmid->z ) )>>FLOATNS) + pmid->y; } if ( x1>x2 ) { cnt=x1; x1=x2; x2=cnt; cnt=y1; y1=y2; y2=cnt; } if ( x<x1 || x>x2 ) return CLIP_OUT; xe = x2-x1; ye = y2-y1; if ( xe!=0 ) yl = (ye<<FLOATNS) / xe; else yl = y1; return (( yl * (x - x1 ))>>FLOATNS)+y1; } //¿µ¿ª¿¡ ÇØ´çÇÏ´Â ÆäÀ̽º¸¦ °Ë»çÇÏ¿© ³ôÀ̸¦ ±¸ÇÑ´Ù int smSTAGE3D::GetAreaHeight( int ax, int az , int x, int z ) { int he,height; int num, fnum; int cnt; smSTAGE_FACE *face; int CalcSum; int lx,lz; lx = ax&0xFF; lz = az&0xFF; CalcSum = CalcSumCount; height = -200*fONE; if ( StageArea[lx][lz] ) { //¿µ¿ª num = StageArea[lx][lz][0]; //¿µ¿ª¿¡ Æ÷ÇÔµÈ ÆäÀ̽º ¼ö for( cnt=1;cnt<num+1;cnt++ ) { fnum = StageArea[lx][lz][cnt]; face = &Face[ fnum ]; if ( face->CalcSum!=CalcSum && smMaterial[ face->Vertex[3] ].MeshState & SMMAT_STAT_CHECK_FACE ) { face->CalcSum = CalcSum; he = GetPolyHeight( face , x, z ); if ( he!=CLIP_OUT && he>height ) height = he; } } } return height; } //¿µ¿ª¿¡ ÇØ´çÇÏ´Â ÆäÀ̽º¸¦ °Ë»çÇÏ¿© ³ôÀ̸¦ ±¸ÇÑ´Ù ( ¹ÝÅõ¸í °ªµµ À¯È¿ ó¸® ) int smSTAGE3D::GetAreaHeight2( int ax, int az , int x, int z ) { int he,height; int num, fnum; int cnt; smSTAGE_FACE *face; int CalcSum; int lx,lz; lx = ax&0xFF; lz = az&0xFF; CalcSum = CalcSumCount; height = -200*fONE; if ( StageArea[lx][lz] ) { //¿µ¿ª num = StageArea[lx][lz][0]; //¿µ¿ª¿¡ Æ÷ÇÔµÈ ÆäÀ̽º ¼ö for( cnt=1;cnt<num+1;cnt++ ) { fnum = StageArea[lx][lz][cnt]; face = &Face[ fnum ]; //if ( face->CalcSum!=CalcSum && // ( smMaterial[ face->Vertex[3] ].MeshState & SMMAT_STAT_CHECK_FACE || smMaterial[ face->Vertex[3] ].Transparency!=0 ) ) { if ( face->CalcSum!=CalcSum ) { face->CalcSum = CalcSum; he = GetPolyHeight( face , x, z ); if ( he!=CLIP_OUT && he>height ) height = he; } } } return height; } //ÆäÀ̽º¿¡ ÇØ´çÇÏ´Â ³ôÀ̸¦ ±¸ÇÑ´Ù int smSTAGE3D::GetHeight( int x, int z ) { int lx,lz; int height = 0; if ( !Head ) return 0; lx = x >> (6+FLOATNS); lz = z >> (6+FLOATNS); height = GetAreaHeight( lx,lz , x, z ); CalcSumCount ++; return height; } //ÆäÀ̽º¿¡ ÇØ´çÇÏ´Â ³ôÀ̸¦ ±¸ÇÑ´Ù int smSTAGE3D::GetHeight2( int x, int z ) { int lx,lz; int height = 0; if ( !Head ) return 0; lx = x >> (6+FLOATNS); lz = z >> (6+FLOATNS); height = GetAreaHeight2( lx,lz , x, z ); CalcSumCount ++; return height; } //À̵¿ÇÒ À§Ä¡ÀÇ Àå¾Ö¹°À» °Ë»çÇÑ´Ù int smSTAGE3D::CheckSolid( int sx, int sy, int sz , int dx, int dy, int dz ) { int num, fnum; int cnt; smSTAGE_FACE *face; int CalcSum; int lx,lz; POINT3D p1,p2,p3,sp,dp; sp.x=sx; sp.y=sy; sp.z=sz; dp.x=dx; dp.y=dy; dp.z=dz; CalcSum = CalcSumCount; lx = dx >> (6+FLOATNS); lz = dz >> (6+FLOATNS); lx &= 0xFF; lz &= 0xFF; if ( StageArea[lx][lz] ) { //¿µ¿ª num = StageArea[lx][lz][0]; //¿µ¿ª¿¡ Æ÷ÇÔµÈ ÆäÀ̽º ¼ö for( cnt=1;cnt<num+1;cnt++ ) { fnum = StageArea[lx][lz][cnt]; face = &Face[ fnum ]; if ( face->CalcSum!=CalcSum && smMaterial[ face->Vertex[3] ].MeshState & SMMAT_STAT_CHECK_FACE ) { face->CalcSum = CalcSum; p1.x = Vertex[ face->Vertex[0] ].x; p1.y = Vertex[ face->Vertex[0] ].y; p1.z = Vertex[ face->Vertex[0] ].z; p2.x = Vertex[ face->Vertex[1] ].x; p2.y = Vertex[ face->Vertex[1] ].y; p2.z = Vertex[ face->Vertex[1] ].z; p3.x = Vertex[ face->Vertex[2] ].x; p3.y = Vertex[ face->Vertex[2] ].y; p3.z = Vertex[ face->Vertex[2] ].z; if ( smGetTriangleImact( &p1,&p2,&p3,&sp,&dp )==TRUE ) { CalcSumCount ++; return TRUE; } } } } lx = sx >> (6+FLOATNS); lz = sz >> (6+FLOATNS); lx &= 0xFF; lz &= 0xFF; if ( StageArea[lx][lz] ) { //¿µ¿ª num = StageArea[lx][lz][0]; //¿µ¿ª¿¡ Æ÷ÇÔµÈ ÆäÀ̽º ¼ö for( cnt=1;cnt<num+1;cnt++ ) { fnum = StageArea[lx][lz][cnt]; face = &Face[ fnum ]; if ( face->CalcSum!=CalcSum && smMaterial[ face->Vertex[3] ].MeshState & SMMAT_STAT_CHECK_FACE ) { face->CalcSum = CalcSum; p1.x = Vertex[ face->Vertex[0] ].x; p1.y = Vertex[ face->Vertex[0] ].y; p1.z = Vertex[ face->Vertex[0] ].z; p2.x = Vertex[ face->Vertex[1] ].x; p2.y = Vertex[ face->Vertex[1] ].y; p2.z = Vertex[ face->Vertex[1] ].z; p3.x = Vertex[ face->Vertex[2] ].x; p3.y = Vertex[ face->Vertex[2] ].y; p3.z = Vertex[ face->Vertex[2] ].z; if ( smGetTriangleImact( &p1,&p2,&p3,&sp,&dp )==TRUE ) { CalcSumCount ++; return TRUE; } } } } CalcSumCount ++; return FALSE; } // StageArea¸¦ 0 À¸·Î ÃʱâÈ­ void smSTAGE3D::clearStageArea() { int x,y; for(y=0;y<MAP_SIZE;y++) { for(x=0;x<MAP_SIZE;x++) { StageArea[x][y] = 0; } } } // »ï°¢ÆäÀ̽º°¡ À§Ä¡ÇÑ ±¸¿ª(64x64) À» ±¸ÇÏ¿© AreaList ¿¡ ¼³Á¤ int smSTAGE3D::getPolyAreas( POINT3D *ip1 , POINT3D *ip2, POINT3D *ip3 ) { POINT3D p1, p2 , p3; POINT3D *p[3]; int cnt; int left , right , top , bottom; int cntX,cntY; memcpy( &p1, ip1 , sizeof( POINT3D ) ); memcpy( &p2, ip2 , sizeof( POINT3D ) ); memcpy( &p3, ip3 , sizeof( POINT3D ) ); p[0] = &p1; p[1] = &p2; p[2] = &p3; left = p[0]->x; right = p[0]->x; top = p[0]->z; bottom = p[0]->z; for( cnt=1; cnt<3; cnt++ ) { if ( p[cnt]->x < left ) left = p[cnt]->x; if ( p[cnt]->x > right ) right = p[cnt]->x; if ( p[cnt]->z < top ) top = p[cnt]->z; if ( p[cnt]->z > bottom ) bottom = p[cnt]->z; } left >>=6; right >>=6; top >>=6; bottom>>=6; right++; bottom++; AreaListCnt = 0; for( cntX=left; cntX<right; cntX++ ) { for( cntY=top; cntY<bottom; cntY++ ) { AreaList[ AreaListCnt ].x = cntX & 0xFF ; // AreaList[ AreaListCnt ].y = cntY & 0xFF ; // AreaListCnt ++; } } return TRUE; } //°¢ Æú¸®°ïÀÌ À§Ä¡ÇÑ ¿µ¿ª Á¤º¸¸¦ ¸¸µé¾î ÀúÀåÇÑ´Ù int smSTAGE3D::SetupPolyAreas() { POINT3D p[3]; int cnt,cnt2; int num; // ±¸¿ª ¹è¿­ ¿µ¿ªÀÇ ¸ðµç °ªÀ» 0 À¸·Î ÃʱâÈ­ clearStageArea(); AreaList = new POINT [ 4096 ]; // ¸ðµç Face¸¦ °Ë»çÇÏ¿© Â÷ÁöÇÏ´Â °ø°£ ±¸¿ªÀ» È®ÀÎÇÏ¿© ±¸¿ª ¹è¿­ ¿µ¿ª¿¡ ÇÒ´çµÉ °ø°£À» ±¸ÇÑ´Ù for(int cnt=0;cnt<nFace;cnt++ ) { for(cnt2=0;cnt2<3;cnt2++) { p[cnt2].x = Vertex[ Face[cnt].Vertex[cnt2] ].x>>FLOATNS; p[cnt2].y = Vertex[ Face[cnt].Vertex[cnt2] ].y>>FLOATNS; p[cnt2].z = Vertex[ Face[cnt].Vertex[cnt2] ].z>>FLOATNS; } getPolyAreas( &p[0] , &p[1], &p[2] ); //ÀÏ´Ü StageArea¿¡ ÀúÀåµÉ ÆäÀ̽º ¼ö¸¦ ÀúÀå if ( AreaListCnt>0 ) { for( cnt2=0;cnt2<AreaListCnt;cnt2++ ) { StageArea[ AreaList[cnt2].x ][ AreaList[cnt2].y]++; } } } delete AreaList; // lpwAreaBuff = 0; int wbCnt; wbCnt = 0; // ±¸¿ª ¿µ¿ª¿¡ ÇÊ¿äÇÑ °ø°£ È®º¸ for( cnt2=0;cnt2<MAP_SIZE;cnt2++) { for(int cnt=0;cnt<MAP_SIZE;cnt++ ) { num = (int)StageArea[ cnt ][ cnt2 ]; //°è»êµÈ ÆäÀ̽º ¼öÆÇÅ­ ¹öÆÛ¸¦ ÀâÀ½ if ( num>0 ) { wbCnt += num+1; } } } wAreaSize = wbCnt; lpwAreaBuff = new WORD[ wbCnt ]; wbCnt = 0; // ±¸¿ª ¿µ¿ª¿¡ ÇÊ¿äÇÑ °ø°£ È®º¸ for( cnt2=0;cnt2<MAP_SIZE;cnt2++) { for(int cnt=0;cnt<MAP_SIZE;cnt++ ) { num = (int)StageArea[ cnt ][ cnt2 ]; //°è»êµÈ ÆäÀ̽º ¼öÆÇÅ­ ¹öÆÛ¸¦ ÀâÀ½ if ( num>0 ) { StageArea[cnt][cnt2] = &lpwAreaBuff[wbCnt]; StageArea[cnt][cnt2][0] = 0; wbCnt += num+1; } } } /* // ±¸¿ª ¿µ¿ª¿¡ ÇÊ¿äÇÑ °ø°£ È®º¸ for( cnt2=0;cnt2<MAP_SIZE;cnt2++) { for(int cnt=0;cnt<MAP_SIZE;cnt++ ) { num = (int)StageArea[ cnt ][ cnt2 ]; //°è»êµÈ ÆäÀ̽º ¼öÆÇÅ­ ¹öÆÛ¸¦ ÀâÀ½ if ( num>0 ) { num/=sizeof( WORD ); StageArea[cnt][cnt2] = new WORD[ num+1 ]; if ( StageArea[cnt][cnt2] ) StageArea[cnt][cnt2][0] = 0; // ¹è¿­ÀÇ[0]Àº Æ÷ÇÔÇÏ´Â Æú¸®°ï °¹¼ö else StageArea[cnt][cnt2] = 0; // ¹è¿­ÀÇ[0]Àº Æ÷ÇÔÇÏ´Â Æú¸®°ï °¹¼ö } } } */ AreaList = new POINT [ 4096 ]; // ´Ù½Ã Face¸¦ °Ë»çÇϰí È®º¸µÈ ¿µ¿ª¿¡ °ªÀ» ¼³Á¤ for(int cnt=0;cnt<nFace;cnt++ ) { for(cnt2=0;cnt2<3;cnt2++) { p[cnt2].x = Vertex[ Face[cnt].Vertex[cnt2] ].x>>FLOATNS; p[cnt2].y = Vertex[ Face[cnt].Vertex[cnt2] ].y>>FLOATNS; p[cnt2].z = Vertex[ Face[cnt].Vertex[cnt2] ].z>>FLOATNS; } getPolyAreas( &p[0] , &p[1], &p[2] ); if ( AreaListCnt>0 ) { for( cnt2=0;cnt2<AreaListCnt;cnt2++ ) { StageArea[ AreaList[cnt2].x ][ AreaList[cnt2].y ][0]++; num = StageArea[ AreaList[cnt2].x ][ AreaList[cnt2].y ][0]; StageArea[ AreaList[cnt2].x ][ AreaList[cnt2].y ][ num ] = cnt; } } } delete AreaList; return TRUE; } // ·»´õ¸µÀ» À§ÇÑ ¿¬»ê°ú Á¤·Ä int smSTAGE3D::RenderGeom() { int cnt; int x1,x2; int t; int h,w; int num; int fnum; smSTAGE_FACE *face; int clipW,clipH; smRENDFACE *rendface; int k=0; if ( smMaterialGroup ) smRender.SetMaterialGroup( smMaterialGroup ); //·»´õ¸µ¿ë Àӽà ¹öÆÛ ÃʱâÈ­ ( ¹öÅØ½º Æ÷ÀÎÅÍ ¾Ë·ÁÁÜ ) smRender.InitStageMesh ( Vertex , SumCount ); for( h=MapPosiTop; h<MapPosiBot ; h++ ) { x1 = MapPosiLeft[ h&0xFF ]; x2 = MapPosiRight[ h&0xFF ]; if ( x1>x2 ) { t=x1; x1=x2 ; x2=t; } // x1<->x2 ¹Ù²Þ clipH = h&0xFF; for( w=x1; w<x2 ; w++ ) { clipW = w&0xFF; if ( StageArea[clipW][clipH] ) { //·»´õ¸µ µÉ ¿µ¿ª num = StageArea[clipW][clipH][0]; //¿µ¿ª¿¡ Æ÷ÇÔµÈ ÆäÀ̽º ¼ö for( cnt=1;cnt<num+1;cnt++ ) { fnum = StageArea[clipW][clipH][cnt]; face = &Face[ fnum ]; // if ( face->sum != SumCount && CheckFace!=face ) { if ( face->sum != SumCount ) { //&& (smMaterial[Face[ fnum ].Vertex[3]].UseState&Display sMATS_SCRIPT_NOTVIEW) ) { rendface = smRender.AddStageFace( face ); // ·»´õ¸µ ÆäÀ̽º·Î Ãß°¡ } k++; } } } } smRender.ClipRendFace(); // Àüü ·»´õ¸µ ÆäÀ̽º¸¦ Ŭ¸®ÇÎ smRender.GeomVertex2D(); // ¹öÅØ½º¸¦ 2DÁÂÇ¥·Î º¯È¯ return TRUE; } #define STAGE_RECT_LIMIT (30*64*fONE) #define STAGE_RECT_LIMIT2 (240*64*fONE) int smSTAGE3D::DrawStage(int x , int y, int z, int angX, int angY, int angZ , smEMATRIX *eRotMatrix ) { if ( !Head ) return 0; SumCount++; //±×¸±¼ö ÀÖ´Â Áö¿ªÀ» ¹þ¾î³­ °æ¿ì Ãâ·Â ÇÏÁö ¾ÊÀ½ if ( z<(StageMapRect.top-STAGE_RECT_LIMIT) ) return FALSE; if ( z>(StageMapRect.bottom+STAGE_RECT_LIMIT) ) return FALSE; if ( x<(StageMapRect.left-STAGE_RECT_LIMIT) ) return FALSE; if ( x>(StageMapRect.right+STAGE_RECT_LIMIT) ) return FALSE; CameraX = x>>FLOATNS; CameraY = y>>FLOATNS; CameraZ = z>>FLOATNS; CameraY -= 1500; if (CameraY<400) CameraY=400; CameraAngX = GetRadian( angX ); CameraAngY = GetRadian( angY ); CameraAngZ = GetRadian( angZ ); //###################################################################################### //ÀÛ ¼º ÀÚ : ¿À ¿µ ¼® if( CameraAngX > ANGLE_90 ) CameraAngX = ANGLE_360-CameraAngX; //###################################################################################### SetViewLength(); SetViewRadian(); if ( MakeMapTable() ) { if ( eRotMatrix ) smRender.SetCameraPosi( x, y, z, eRotMatrix ); else smRender.SetCameraPosi( x, y, z, angX, angY, angZ ); CameraAngX = GetRadian( angX ); CameraAngY = GetRadian( angY ); CameraAngZ = GetRadian( angZ ); /* int cnt,dx,dy,dz,dist; for(cnt=0;cnt<nLight;cnt++) { dx = (x-smLight[cnt].x)>>FLOATNS; dy = (y-smLight[cnt].y)>>FLOATNS; dz = (z-smLight[cnt].z)>>FLOATNS; dist = dx*dx+dy*dy+dz*dz; if ( dist<0x300000 ) { smRender.AddDynamicLight( smLight[cnt].x,smLight[cnt].y,smLight[cnt].z, smLight[cnt].r,smLight[cnt].g,smLight[cnt].b, 0 , smLight[cnt].Range ); } } */ RenderGeom(); // smRender D3D·»´õ¸µ smRender.RenderD3D(); StageObject->Draw( x, y, z, angX, angY, angZ ); } return FALSE; } int smSTAGE3D::DrawStage2(int x , int y, int z, int angX, int angY, int angZ , smEMATRIX *eRotMatrix ) { if ( !Head ) return 0; SumCount++; //±×¸±¼ö ÀÖ´Â Áö¿ªÀ» ¹þ¾î³­ °æ¿ì Ãâ·Â ÇÏÁö ¾ÊÀ½ if ( z<(StageMapRect.top-STAGE_RECT_LIMIT) ) return FALSE; if ( z>(StageMapRect.bottom+STAGE_RECT_LIMIT) ) return FALSE; if ( x<(StageMapRect.left-STAGE_RECT_LIMIT) ) return FALSE; if ( x>(StageMapRect.right+STAGE_RECT_LIMIT) ) return FALSE; if ( z<(StageMapRect.bottom-STAGE_RECT_LIMIT2) ) return FALSE; if ( z>(StageMapRect.top+STAGE_RECT_LIMIT2) ) return FALSE; if ( x<(StageMapRect.right-STAGE_RECT_LIMIT2) ) return FALSE; if ( x>(StageMapRect.left+STAGE_RECT_LIMIT2) ) return FALSE; CameraX = x>>FLOATNS; CameraY = y>>FLOATNS; CameraZ = z>>FLOATNS; CameraY -= 1500; if (CameraY<400) CameraY=400; CameraAngX = GetRadian( angX ); CameraAngY = GetRadian( angY ); CameraAngZ = GetRadian( angZ ); //###################################################################################### //ÀÛ ¼º ÀÚ : ¿À ¿µ ¼® if( CameraAngX > ANGLE_90 ) CameraAngX = ANGLE_360-CameraAngX; //###################################################################################### SetViewLength(); SetViewRadian(); if ( MakeMapTable() ) { if ( eRotMatrix ) smRender.SetCameraPosi( x, y, z, eRotMatrix ); else smRender.SetCameraPosi( x, y, z, angX, angY, angZ ); CameraAngX = GetRadian( angX ); CameraAngY = GetRadian( angY ); CameraAngZ = GetRadian( angZ ); RenderGeom(); // smRender D3D·»´õ¸µ smRender.RenderD3D(); return TRUE; } return FALSE; } //###################################################################################### //ÀÛ ¼º ÀÚ : ¿À ¿µ ¼® int smSTAGE3D::DrawOpeningStage(int x, int y, int z, int angX, int angY, int angZ, int FrameStep ) { if ( !Head ) return 0; SumCount++; //±×¸±¼ö ÀÖ´Â Áö¿ªÀ» ¹þ¾î³­ °æ¿ì Ãâ·Â ÇÏÁö ¾ÊÀ½ if ( z<(StageMapRect.top-STAGE_RECT_LIMIT) ) return FALSE; if ( z>(StageMapRect.bottom+STAGE_RECT_LIMIT) ) return FALSE; if ( x<(StageMapRect.left-STAGE_RECT_LIMIT) ) return FALSE; if ( x>(StageMapRect.right+STAGE_RECT_LIMIT) ) return FALSE; CameraX = x>>FLOATNS; CameraY = y>>FLOATNS; CameraZ = z>>FLOATNS; CameraY -= 1500; if (CameraY<400) CameraY=400; CameraAngX = GetRadian( angX ); CameraAngY = GetRadian( angY ); CameraAngZ = GetRadian( angZ ); if( CameraAngX > ANGLE_90 ) CameraAngX = ANGLE_360-CameraAngX; SetViewLength(); SetViewRadian(); if ( MakeMapTable() ) { smRender.SetCameraPosi( x, y, z, angX, angY, angZ ); CameraAngX = GetRadian( angX ); CameraAngY = GetRadian( angY ); CameraAngZ = GetRadian( angZ ); RenderGeom(); // smRender D3D·»´õ¸µ smRender.RenderD3D(); StageObject->DrawOpening( x, y, z, angX, angY, angZ, FrameStep ); } return FALSE; } //###################################################################################### static char *szSMDFileHeader = "SMD Stage data Ver 0.72"; //µ¥ÀÌŸ¸¦ ÆÄÀÏ·Î ÀúÀå int smSTAGE3D::SaveFile( char *szFile ) { HANDLE hFile; DWORD dwAcess; int cnt,cnt2,slen; int pFile; // int size; smDFILE_HEADER FileHeader; lstrcpy( FileHeader.szHeader , szSMDFileHeader ); Head = FALSE; //Çì´õ Á¦ÀÛ if ( smMaterialGroup ) FileHeader.MatCounter = smMaterialGroup->MaterialCount; else FileHeader.MatCounter = 0; //ÆÄÀÏ Æ÷ÀÎÅÍ pFile = sizeof( smDFILE_HEADER );// + sizeof( smPAT3D ); FileHeader.MatFilePoint = pFile; //¸ÞÆ®¸®¾ó µ¥ÀÌŸ ÀúÀå Å©±â if ( smMaterialGroup ) pFile+= smMaterialGroup->GetSaveSize(); FileHeader.First_ObjInfoPoint = pFile; //ÆÄÀÏ·Î ÀúÀå hFile = CreateFile( szFile , GENERIC_WRITE , FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS , FILE_ATTRIBUTE_NORMAL , NULL ); if ( hFile == INVALID_HANDLE_VALUE ) return FALSE; //Çì´õ ÀúÀå WriteFile( hFile , &FileHeader , sizeof( smDFILE_HEADER ) , &dwAcess , NULL ); //ÇöÀç Ŭ·¡½ºÀÇ µ¥ÀÌŸ ÀúÀå WriteFile( hFile , &Head , sizeof( smSTAGE3D ) , &dwAcess , NULL ); //¸ÞÆ®¸®¾ó µ¥ÀÌŸ ÀúÀå if ( smMaterialGroup ) smMaterialGroup->SaveFile( hFile ); // °¢ ¸Þ½Ã µ¥ÀÌŸ¸¦ ÀúÀå WriteFile( hFile , Vertex , sizeof( smSTAGE_VERTEX )* nVertex , &dwAcess , NULL ); WriteFile( hFile , Face , sizeof( smSTAGE_FACE )* nFace , &dwAcess , NULL ); WriteFile( hFile , TexLink , sizeof( smTEXLINK ) * nTexLink , &dwAcess , NULL ); if ( nLight>0 ) WriteFile( hFile , smLight , sizeof( smLIGHT3D ) * nLight , &dwAcess , NULL ); // ±¸¿ª ¿µ¿ªÀÇ µ¥ÀÌŸ¸¦ ÀúÀå for( cnt2=0;cnt2<MAP_SIZE;cnt2++) { for(int cnt=0;cnt<MAP_SIZE;cnt++ ) { if (StageArea[ cnt ][ cnt2 ]) { slen = (StageArea[cnt][cnt2][0]+1) ; WriteFile( hFile , &slen , sizeof(int) , &dwAcess , NULL ); WriteFile( hFile , StageArea[cnt][cnt2] , slen * sizeof( WORD ), &dwAcess , NULL ); } } } //ÇÚµé ´Ý±¸ Á¾·á CloseHandle( hFile ); return TRUE; } //ÆÄÀÏ¿¡¼­ µ¥ÀÌŸ¸¦ ·Îµå int smSTAGE3D::LoadFile( char *szFile ) { HANDLE hFile; DWORD dwAcess; int cnt,cnt2; int size; int slen; int wbCnt; smTEXLINK *lpOldTexLink; int SubTexLink; smDFILE_HEADER FileHeader; hFile = CreateFile( szFile , GENERIC_READ , FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_EXISTING , FILE_ATTRIBUTE_NORMAL , NULL ); //Çì´õÀÇ ³»¿ëÀ» Àоî¿È size=ReadFile( hFile , &FileHeader , sizeof( smDFILE_HEADER ) , &dwAcess , NULL ); //Çì´õ°¡ Ʋ¸² ( ¹öÀüÀÌ Æ²¸®°Å³ª.. ) if ( lstrcmp( FileHeader.szHeader , szSMDFileHeader )!=0 ) { //ÇÚµé ´Ý±¸ Á¾·á CloseHandle( hFile ); return FALSE; } //Ŭ·¡½ºÀÇ ³»¿ëÀ» ÀÐÀ½ ReadFile( hFile , &Head , sizeof( smSTAGE3D ) , &dwAcess , NULL ); lpOldTexLink = TexLink; //¸ÞÆ®¸®¾ó Àоî¿È if ( FileHeader.MatCounter ) { smMaterialGroup = new smMATERIAL_GROUP; smMaterialGroup->LoadFile( hFile ); smMaterial = smMaterialGroup->smMaterial; } //»õ·Î¿î ¸Þ¸ð¸® ºí·° ÇÒ´ç Vertex = new smSTAGE_VERTEX[ nVertex ]; ReadFile( hFile , Vertex , sizeof( smSTAGE_VERTEX ) * nVertex , &dwAcess , NULL ); Face = new smSTAGE_FACE[ nFace ]; ReadFile( hFile , Face , sizeof( smSTAGE_FACE ) * nFace , &dwAcess , NULL ); TexLink = new smTEXLINK[ nTexLink ]; ReadFile( hFile , TexLink , sizeof( smTEXLINK ) * nTexLink , &dwAcess , NULL ); if ( nLight>0 ) { smLight = new smLIGHT3D[nLight]; ReadFile( hFile , smLight , sizeof( smLIGHT3D ) * nLight , &dwAcess , NULL ); } //ÅØ½ºÃÄ ÁÂÇ¥°¡ ¾îµå·¹½º Æ÷ÀÎÅÍ·Î µÇ ÀÖÀ¸¹Ç·Î »õ·Î º¸Á¤ÇÔ SubTexLink = TexLink-lpOldTexLink; for(int cnt=0;cnt<nTexLink;cnt++) { if ( TexLink[cnt].NextTex ) { SubTexLink = TexLink[cnt].NextTex-lpOldTexLink; TexLink[cnt].NextTex = TexLink + SubTexLink; } } for(int cnt=0;cnt<nFace;cnt++) { if ( Face[cnt].lpTexLink ) { SubTexLink = Face[cnt].lpTexLink-lpOldTexLink; Face[cnt].lpTexLink = TexLink + SubTexLink; } } StageObject = new smSTAGE_OBJECT; lpwAreaBuff = new WORD[ wAreaSize ]; wbCnt = 0; // ±¸¿ª ¿µ¿ªÀÇ µ¥ÀÌŸ¸¦ ÀÐÀ½ for( cnt2=0;cnt2<MAP_SIZE;cnt2++) { for(int cnt=0;cnt<MAP_SIZE;cnt++ ) { if (StageArea[ cnt ][ cnt2 ]) { ReadFile( hFile , &slen , sizeof(int) , &dwAcess , NULL ); StageArea[cnt][cnt2] = &lpwAreaBuff[ wbCnt ]; ReadFile( hFile , StageArea[cnt][cnt2] , slen*sizeof(WORD) , &dwAcess , NULL ); wbCnt += slen; } } } //ÇÚµé ´Ý±¸ Á¾·á CloseHandle( hFile ); CalcSumCount++; return TRUE; }
rafaellincoln/Source-Priston-Tale
J_Server/smLib3d/smStage3d.cpp
C++
mit
55,585
#! /usr/bin/env python import sys sys.setrecursionlimit(150000) import time count = 0 def my_yield(): global count count = count + 1 yield def run_co(c): global count count = 0 t0 = time.clock() for r in c: () t = time.clock() dt = t-t0 print(dt,count,count / dt) return r def parallel_(p1,p2): r1 = None r2 = None while(r1 == None or r2 == None): if(r1 == None): r1 = next(p1) if(r2 == None): r2 = next(p2) for x in my_yield() : yield for x in my_yield() : yield r1,r2 def parallel_many_aux(ps,l,u): if(l < u): for x in parallel_(ps[l],parallel_many_aux(ps,l+1,u)): for y in my_yield(): yield x yield 0 def parallel_many_(ps): return parallel_many_aux(ps,0,len(ps)) def parallel_first_(p1,p2): r1 = None r2 = None while(r1 == None and r2 == None): if(r1 == None): r1 = next(p1) if(r2 == None): r2 = next(p2) for x in my_yield() : yield for x in my_yield() : yield r1,r2 def wait(max_dt): t0 = time.clock() t = time.clock() while(t - t0 < max_dt): for x in my_yield() : yield #print(t - t0) t = time.clock() for x in my_yield() : yield 0 def fibo_co(n): if(n==0): for x in my_yield() : yield 0 else: if(n==1): for x in my_yield() : yield 1 else: for x in my_yield() : yield for n1 in fibo_co(n-1): for x in my_yield() : yield for n2 in fibo_co(n-2): for x in my_yield() : yield for x in my_yield() : yield n1+n2 def log(i): #print("log ", i) for x in wait(2.0): for x in my_yield() : yield for x in log(i+1): for x in my_yield() : yield def fibo_test(): run_co(parallel_first_(fibo_co(25),log(0))) def many_fibs(n): #yield return log(0); for i in range(0,n+1): yield fibo_co(i + 5) def many_fibs_test(): run_co(parallel_many_(list(many_fibs(15)))) #fibo_test() #many_fibs_test() class Entity: pass class State: pass def simple_mk_ship(n): s = Entity() s.Position = 100.0 - n return s def add_ship(new_ship, run_ship, state): state.Entities.append(new_ship) for result in run_ship(new_ship): for x in my_yield(): yield state.Entities.remove(new_ship) for x in my_yield(): yield result def simple_run_ship(self): while(self.Position > 0.0): self.Position = self.Position - 0.1 for x in my_yield(): yield yield 0 def many_ships(n,state): if(n > 0): for x in parallel_(add_ship(simple_mk_ship(n), simple_run_ship, state), many_ships(n-1,state)): for x in my_yield(): yield yield 0 def log_ships(state): while(True): print("there are ", len(state.Entities), " ships") for x in wait(2.0): for x in my_yield(): yield def state_access_test(): state = State() state.Entities = [] #test = parallel_(many_ships(200,state),log_ships(state)) test = many_ships(200,state) run_co(test) state_access_test()
vs-team/Papers
0. MonadicCoroutines/Src/MonadicCoroutines/CSharp/main.py
Python
mit
3,063
package io.reactivesw.order.order.infrastructure.enums; /** * Created by Davis on 16/11/17. */ public enum OrderState { /** * Open order state. */ Open, /** * Confirmed order state. */ Confirmed, /** * Complete order state. */ Complete, /** * Cancelled order state. */ Cancelled; }
reactivesw/customer_server
src/main/java/io/reactivesw/order/order/infrastructure/enums/OrderState.java
Java
mit
327
<?php namespace Ibw\MagSoftBundle\Entity; use Doctrine\ORM\EntityRepository; /** * ProiecteRepository * * This class was generated by the Doctrine ORM. Add your own custom * repository methods below. */ class ProiecteRepository extends EntityRepository { public function getLastProiectGeneratId() { $qb = $this->createQueryBuilder('j') ->select('max(j.nrProiectGenerat)'); return $qb->getQuery()->getSingleScalarResult(); } public function getLastDosarDefinitivId() { $qb = $this->createQueryBuilder('j') ->select('max(j.nrDosarDefinitiv)'); return $qb->getQuery()->getSingleScalarResult(); } public function getLastProiectId() { $qb = $this->createQueryBuilder('j') ->select('max(j.id)'); return $qb->getQuery()->getResult(); } public function getRaportLucrari($partener = 0, $dateFrom = null, $dateTo = null) { $qb = $this->getEntityManager()->createQueryBuilder(); $qb->select('p, c, pt') ->from('IbwMagSoftBundle:Proiecte', 'p') ->innerJoin('p.clienti', 'c') ->innerJoin('c.parteneri', 'pt'); if ($partener != 0) { $qb->andwhere('pt.id= :partener') ->setParameter('partener', $partener); } if ($dateFrom != new \DateTime() && $dateTo != new \DateTime()) { $qb->andwhere('p.dataCerereAcordAcces BETWEEN :fromDate and :toDate') ->setParameter('fromDate', $dateFrom) ->setParameter('toDate', $dateTo); } return $qb->getQuery()->getResult(); } public function getRaportProiecte($partener = 0, $dateFrom = null, $dateTo = null) { $qb = $this->getEntityManager()->createQueryBuilder(); $qb->select('p, c, pt, pr') ->from('IbwMagSoftBundle:Proiecte', 'p') ->innerJoin('p.clienti', 'c') ->innerJoin('c.parteneri', 'pt') ->innerJoin('p.pret', 'pr'); if ($partener != 0) { $qb->andwhere('pt.id= :partener') ->setParameter('partener', $partener); } if ($dateFrom != new \DateTime() && $dateTo != new \DateTime()) { $qb->andwhere('p.dataCerereAcordAcces BETWEEN :fromDate and :toDate') ->setParameter('fromDate', $dateFrom) ->setParameter('toDate', $dateTo); } return $qb->getQuery()->getResult(); } public function getSumPret() { $qb = $this->getEntityManager()->createQueryBuilder(); $qb->select('sum(p.pret)') ->from('IbwMagSoftBundle:Proiecte', 'p'); return $qb->getQuery()->getSingleScalarResult(); } public function getProiectPriceByPartener() { $qb = $this->getEntityManager()->createQueryBuilder(); $qb->select('p.valoarePret') ->from('IbwMagSoftBundle:Pret', 'p') ->where('p.parteneri = :partener') ->setParameter('partener', 'numePartener1'); return $qb->getQuery()->getArrayResult(); } }
annonnim/magsoft
src/Ibw/MagSoftBundle/Entity/ProiecteRepository.php
PHP
mit
3,167
package org.adaptlab.chpir.android.survey.utils; import org.adaptlab.chpir.android.survey.models.DeviceUser; public class AuthUtils { private static DeviceUser sCurrentUser = null; public static boolean isSignedIn() { return sCurrentUser != null; } public static void signOut() { sCurrentUser = null; } public static void signIn(DeviceUser deviceUser) { sCurrentUser = deviceUser; } public static DeviceUser getCurrentUser() { return sCurrentUser; } }
DukeMobileTech/AndroidSurvey
app/src/main/java/org/adaptlab/chpir/android/survey/utils/AuthUtils.java
Java
mit
543
using System; namespace SDNUMobile.SDK.Entity.Bathroom { /// <summary> /// 浴室使用用量实体 /// </summary> public class BathroomUsageAmount { #region 字段 private DateTime _logTime; private Int32[] _amount; #endregion #region 属性 /// <summary> /// 获取或设置记录时间 /// </summary> public DateTime LogTime { get { return this._logTime; } set { this._logTime = value; } } /// <summary> /// 获取或设置使用数量 /// </summary> public Int32[] Amount { get { return this._amount; } set { this._amount = value; } } #endregion } }
isdnu/DotNetSDK
SDNUMobile.SDK/Entity/Bathroom/BathroomUsageAmount.cs
C#
mit
809
;(function() { 'use strict'; const nodemailer = require('nodemailer'); const htmlToText = require('nodemailer-html-to-text').htmlToText; module.exports = Extension => class Mailer extends Extension { _constructor() { this.send.context = Extension.ROUTER; } send(ctx) { let subject = ctx.arg('subject'); let formKeys = Object.keys(ctx.body) .filter(key => key.startsWith(ctx.arg('prefix'))) .reduce((map, key) => map.set(key.slice(ctx.arg('prefix').length), ctx.body[key]), new Map()); formKeys.forEach((key, value) => subject = subject.replace(`{${key}}`, value)); let content = ctx.render(formKeys); let transporter = nodemailer.createTransport(); transporter.use('compile', htmlToText()); ctx.logger.log(ctx.logger.debug, 'sending mail...'); transporter.sendMail({ from: ctx.arg('from'), to: ctx.arg('to'), subject: subject, html: content }, function(err, info) { if (err) { ctx.logger.log(ctx.logger.error, 'can\'t send mail: {0}', err); } else { ctx.logger.log(ctx.logger.info, 'mail sent: {0}', info.response); } ctx.set('status', err); return ctx.success(); }); } } })();
xabinapal/verlag
extensions/mailer.js
JavaScript
mit
1,288
<?php include('dbconnect.php'); include('_admin_session.php'); if(isset($_POST['form1'])){ $acc_date = $_POST['acc_date']; $acc_desc = $_POST['acc_desc']; $acc_amo = $_POST['acc_amo']; $acc_dr_cr = $_POST['acc_dr_cr']; $acc_total = $_POST['acc_total']; $result = mysql_query("insert into accounts (acc_date, acc_desc, acc_amo, acc_dr_cr, acc_total) values('$acc_date','$acc_desc','$acc_amo','$acc_dr_cr','$acc_total')")or die(mysql_error()); if ($result) { echo ("<p style='font-size:20px;'>Accounts Data input successfully</p>"); } else { echo ("<p style='font-size:20px;'>Accounts Data input Failed</p>"); } } //header("location: index.php?action=_accounts_view"); ?> <!DOCTYPE HTML> <html lang="en-US"> <head> <meta charset="UTF-8"> <title>প্রতিষ্ঠানের একাউন্টস</title> <script type="text/javascript"> function confirm_del() { return confirm('Do you want to delete this data ?'); } </script> </head> <body> <h2>প্রতিষ্ঠানের একাউন্টস</h2> <form action="" method="post" enctype="multipart/form-data"> <table> <tr> <td>তারিখ: </td> <td><input type="text" name="acc_date" placeholder="ex: ১২/০৯।২০১৫ " required /></td> </tr> <tr> <td>টাকার বিবরণ: </td> <td><input type="text" name="acc_desc" placeholder="ex: টাকার বিবরণ লিখুন " required /></td> </tr> <tr> <td>পরিমান: </td> <td><input type="text" name="acc_amo" placeholder="ex: ৪,০০০ /=" required /></td> </tr> <tr> <td>জমা/ খরচ: </td> <td> <select name="acc_dr_cr" id=""> <option value="--Select--">--Select A Option--</option> <option value="জমা">জমা</option> <option value="খরচ">খরচ</option> </select> </td> </tr> <tr> <td>মোট পরিমাণ: </td> <td><input type="text" name="acc_total" placeholder="ex: ১২,০০০ /=" required /></td> </tr> <tr> <td></td> <td><input type="submit" value="সেভ করুন" name="form1"/></td> </tr> </table> </form> <br /> <table border="1" id="mytable"> <tr> <th>ক্রমিক নং</th> <th>তারিখ</th> <th>টাকার বিবরণ</th> <th>পরিমান</th> <th>জমা/ খরচ</th> <th>মোট পরিমাণ</th> <th>নিয়ন্ত্রণ করুন</th> </tr> <?php $i = 0; $result= mysql_query("select * from accounts" ) or die (mysql_error()); while ($row = mysql_fetch_array ($result)){ $i++; ?> <tr> <td><?php echo $i;?></td> <td><?php echo $row['acc_date'];?></td> <td><?php echo $row['acc_desc'];?></td> <td><?php echo $row['acc_amo'];?>/=</td> <td><?php echo $row['acc_dr_cr'];?></td> <td><?php echo $row['acc_total'];?>/=</td> <td> <a href="_accounts_edit.php?id=<?php echo $row['acc_id'];?>">এডিট </a> | <a onClick="return confirm_del();" href="_accounts_del.php?id=<?php echo $row['acc_id'];?>">ডিলিট </a> </td> </tr> <?php } ?> </table> </body> </html>
saidurwd/muradschool
backend/_accounts_view.php
PHP
mit
3,202
require 'spec_helper' require_relative '../../lib/concerns/linkable' describe Linkable do context 'link' do class Example include Linkable def initialize(response) @response = response end end it 'removes all \ from strings' do e = Example.new("\"https:\\/\\/ead.local.co\\/videos\\/aulas\\/cooolllllller\\/asdfasdf.pdf?secure=asdfasdf\"") expect(e.link).to eq('https://ead.local.co/videos/aulas/cooolllllller/asdfasdf.pdf?secure=asdfasdf') end end end
fortesinformatica/iesde
spec/concerns/linkable_spec.rb
Ruby
mit
514
export class VendorTest { private expe: string = 'z100123'; constructor(props:any){ //console.log(props); //this.expe = props; } }
ferrugemjs/library
src/example/ui-vendor-example/vendor-test.ts
TypeScript
mit
144
from django import forms class SearchForm(forms.Form): criteria = forms.CharField(label='Criteria', max_length=100, required=True)
chaocodes/playlist-manager-django
manager/search/forms.py
Python
mit
135
# frozen_string_literal: true module DropletKit class DomainMapping include Kartograph::DSL kartograph do mapping Domain root_key plural: 'domains', singular: 'domain', scopes: [:read] property :name, scopes: [:read, :create] property :ttl, scopes: [:read] property :zone_file, scopes: [:read] property :ip_address, scopes: [:create] end end end
digitalocean/droplet_kit
lib/droplet_kit/mappings/domain_mapping.rb
Ruby
mit
400
package com.example.author.boundary; import com.example.author.entity.Author; import com.example.author.repository.AuthorRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.IdGenerator; import java.util.Collection; import java.util.UUID; /** * Implementation for {@link AuthorService}. */ @Service @Transactional(readOnly = true) public class AuthorServiceImpl implements AuthorService { private final AuthorRepository authorRepository; private final IdGenerator idGenerator; /** * Constructor. * * @param authorRepository the {@link AuthorRepository} * @param idGenerator the {@link IdGenerator} */ @Autowired public AuthorServiceImpl(AuthorRepository authorRepository, IdGenerator idGenerator) { this.authorRepository = authorRepository; this.idGenerator = idGenerator; } @Transactional @Override public Author createAuthor(Author author) { if (author.getIdentifier() == null) { author.setIdentifier(idGenerator.generateId()); } return this.authorRepository.save(author); } @Override public Author findByIdentifier(UUID identifier) { return this.authorRepository.findByIdentifier(identifier); } @Override public Collection<Author> findAllAuthors() { return this.authorRepository.findAll(); } @Override public Collection<Author> findByLastname(String lastName) { return this.authorRepository.findByLastname(lastName); } @Transactional @Override public boolean deleteAuthor(UUID identifier) { return this.authorRepository.deleteByIdentifier(identifier); } }
andifalk/spring-rest-docs-demo
src/main/java/com/example/author/boundary/AuthorServiceImpl.java
Java
mit
1,838
using System.Collections.Generic; using BizHawk.Emulation.Common; namespace BizHawk.Emulation.Cores.Computers.AmstradCPC { /// <summary> /// CPCHawk: Core Class /// * Controllers * /// </summary> public partial class AmstradCPC { /// <summary> /// The one CPCHawk ControllerDefinition /// </summary> public ControllerDefinition AmstradCPCControllerDefinition { get { ControllerDefinition definition = new ControllerDefinition(); definition.Name = "AmstradCPC Controller"; // joysticks List<string> joys1 = new List<string> { // P1 Joystick "P1 Up", "P1 Down", "P1 Left", "P1 Right", "P1 Fire1", "P1 Fire2", "P1 Fire3" }; foreach (var s in joys1) { definition.BoolButtons.Add(s); definition.CategoryLabels[s] = "J1"; } List<string> joys2 = new List<string> { // P2 Joystick "P2 Up", "P2 Down", "P2 Left", "P2 Right", "P2 Fire", }; foreach (var s in joys2) { definition.BoolButtons.Add(s); definition.CategoryLabels[s] = "J2"; } // keyboard List<string> keys = new List<string> { // http://www.cpcwiki.eu/index.php/Programming:Keyboard_scanning // http://www.cpcwiki.eu/index.php/File:Grimware_cpc464_version3_case_top.jpg // Keyboard - row 1 "Key ESC", "Key 1", "Key 2", "Key 3", "Key 4", "Key 5", "Key 6", "Key 7", "Key 8", "Key 9", "Key 0", "Key Dash", "Key Hat", "Key CLR", "Key DEL", // Keyboard - row 2 "Key TAB", "Key Q", "Key W", "Key E", "Key R", "Key T", "Key Y", "Key U", "Key I", "Key O", "Key P", "Key @", "Key LeftBracket", "Key RETURN", // Keyboard - row 3 "Key CAPSLOCK", "Key A", "Key S", "Key D", "Key F", "Key G", "Key H", "Key J", "Key K", "Key L", "Key Colon", "Key SemiColon", "Key RightBracket", // Keyboard - row 4 "Key SHIFT", "Key Z", "Key X", "Key C", "Key V", "Key B", "Key N", "Key M", "Key Comma", "Key Period", "Key ForwardSlash", "Key BackSlash", // Keyboard - row 5 "Key SPACE", "Key CONTROL", // Keyboard - Cursor "Key CURUP", "Key CURDOWN", "Key CURLEFT", "Key CURRIGHT", "Key COPY", // Keyboard - Numpad "Key NUM0", "Key NUM1", "Key NUM2", "Key NUM3", "Key NUM4", "Key NUM5", "Key NUM6", "Key NUM7", "Key NUM8", "Key NUM9", "Key NUMPERIOD", "KEY ENTER" }; foreach (var s in keys) { definition.BoolButtons.Add(s); definition.CategoryLabels[s] = "Keyboard"; } // Power functions List<string> power = new List<string> { // Power functions "Reset", "Power" }; foreach (var s in power) { definition.BoolButtons.Add(s); definition.CategoryLabels[s] = "Power"; } // Datacorder (tape device) List<string> tape = new List<string> { // Tape functions "Play Tape", "Stop Tape", "RTZ Tape", "Record Tape", "Insert Next Tape", "Insert Previous Tape", "Next Tape Block", "Prev Tape Block", "Get Tape Status" }; foreach (var s in tape) { definition.BoolButtons.Add(s); definition.CategoryLabels[s] = "Datacorder"; } // Datacorder (tape device) List<string> disk = new List<string> { // Tape functions "Insert Next Disk", "Insert Previous Disk", /*"Eject Current Disk",*/ "Get Disk Status" }; foreach (var s in disk) { definition.BoolButtons.Add(s); definition.CategoryLabels[s] = "Amstrad Disk Drive"; } return definition; } } } /// <summary> /// The possible joystick types /// </summary> public enum JoystickType { NULL, Joystick1, Joystick2 } }
ircluzar/RTC3
Real-Time Corruptor/BizHawk_RTC/BizHawk.Emulation.Cores/Computers/AmstradCPC/AmstradCPC.Controllers.cs
C#
mit
4,843
#include <iostream> #include <cstdlib> #include <stdio.h> #include <math.h> #include<cstdio> #include<string.h> using namespace std; int main(){ int in=0,x,o=0,n; cin>>n; for (int i = 0; i < n; i++) { cin>>x; if(x>=10&&x<=20) in++; else o++; } printf("%d in\n%d out\n",in,o); return 0; }
ahmedengu/URI-solutions
Beginner/1072 - Interval 2.cpp
C++
mit
354
namespace p03_WildFarm.Models.Foods { public class Vegetable : Food { public Vegetable(int quantity) : base(quantity) { } } }
DimitarIvanov8/software-university
C#_OOP_Basics/Polymorphism/p03_WildFarm/Models/Foods/Vegetable.cs
C#
mit
164
<?php /** * PHPExcel * * Copyright (c) 2006 - 2013 PHPExcel * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * @category PHPExcel * @package PHPExcel_Reader * @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel) * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL * @version 1.7.9, 2013-06-02 */ /** PHPExcel root directory */ if (!defined('PHPEXCEL_ROOT')) { /** * @ignore */ define('PHPEXCEL_ROOT', dirname(__FILE__) . '/../../'); require(PHPEXCEL_ROOT . 'PHPExcel/Autoloader.php'); } /** * PHPExcel_Reader_SYLK * * @category PHPExcel * @package PHPExcel_Reader * @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel) */ class PHPExcel_Reader_SYLK extends PHPExcel_Reader_Abstract implements PHPExcel_Reader_IReader { /** * Input encoding * * @var string */ private $_inputEncoding = 'ANSI'; /** * Sheet index to read * * @var int */ private $_sheetIndex = 0; /** * Formats * * @var array */ private $_formats = array(); /** * Format Count * * @var int */ private $_format = 0; /** * Create a new PHPExcel_Reader_SYLK */ public function __construct() { $this->_readFilter = new PHPExcel_Reader_DefaultReadFilter(); } /** * Validate that the current file is a SYLK file * * @return boolean */ protected function _isValidFormat() { // Read sample data (first 2 KB will do) $data = fread($this->_fileHandle, 2048); // Count delimiters in file $delimiterCount = substr_count($data, ';'); if ($delimiterCount < 1) { return FALSE; } // Analyze first line looking for ID; signature $lines = explode("\n", $data); if (substr($lines[0],0,4) != 'ID;P') { return FALSE; } return TRUE; } /** * Set input encoding * * @param string $pValue Input encoding */ public function setInputEncoding($pValue = 'ANSI') { $this->_inputEncoding = $pValue; return $this; } /** * Get input encoding * * @return string */ public function getInputEncoding() { return $this->_inputEncoding; } /** * Return worksheet info (Name, Last Column Letter, Last Column Index, Total Rows, Total Columns) * * @param string $pFilename * @throws PHPExcel_Reader_Exception */ public function listWorksheetInfo($pFilename) { // Open file $this->_openFile($pFilename); if (!$this->_isValidFormat()) { fclose ($this->_fileHandle); throw new PHPExcel_Reader_Exception($pFilename . " is an Invalid Spreadsheet file."); } $fileHandle = $this->_fileHandle; rewind($fileHandle); $worksheetInfo = array(); $worksheetInfo[0]['worksheetName'] = 'Worksheet'; $worksheetInfo[0]['lastColumnLetter'] = 'A'; $worksheetInfo[0]['lastColumnIndex'] = 0; $worksheetInfo[0]['totalRows'] = 0; $worksheetInfo[0]['totalColumns'] = 0; // Loop through file $rowData = array(); // loop through one row (line) at a time in the file $rowIndex = 0; while (($rowData = fgets($fileHandle)) !== FALSE) { $columnIndex = 0; // convert SYLK encoded $rowData to UTF-8 $rowData = PHPExcel_Shared_String::SYLKtoUTF8($rowData); // explode each row at semicolons while taking into account that literal semicolon (;) // is escaped like this (;;) $rowData = explode("\t",str_replace('짚',';',str_replace(';',"\t",str_replace(';;','짚',rtrim($rowData))))); $dataType = array_shift($rowData); if ($dataType == 'C') { // Read cell value data foreach($rowData as $rowDatum) { switch($rowDatum{0}) { case 'C' : case 'X' : $columnIndex = substr($rowDatum,1) - 1; break; case 'R' : case 'Y' : $rowIndex = substr($rowDatum,1); break; } $worksheetInfo[0]['totalRows'] = max($worksheetInfo[0]['totalRows'], $rowIndex); $worksheetInfo[0]['lastColumnIndex'] = max($worksheetInfo[0]['lastColumnIndex'], $columnIndex); } } } $worksheetInfo[0]['lastColumnLetter'] = PHPExcel_Cell::stringFromColumnIndex($worksheetInfo[0]['lastColumnIndex']); $worksheetInfo[0]['totalColumns'] = $worksheetInfo[0]['lastColumnIndex'] + 1; // Close file fclose($fileHandle); return $worksheetInfo; } /** * Loads PHPExcel from file * * @param string $pFilename * @return PHPExcel * @throws PHPExcel_Reader_Exception */ public function load($pFilename) { // Create new PHPExcel $objPHPExcel = new PHPExcel(); // Load into this instance return $this->loadIntoExisting($pFilename, $objPHPExcel); } /** * Loads PHPExcel from file into PHPExcel instance * * @param string $pFilename * @param PHPExcel $objPHPExcel * @return PHPExcel * @throws PHPExcel_Reader_Exception */ public function loadIntoExisting($pFilename, PHPExcel $objPHPExcel) { // Open file $this->_openFile($pFilename); if (!$this->_isValidFormat()) { fclose ($this->_fileHandle); throw new PHPExcel_Reader_Exception($pFilename . " is an Invalid Spreadsheet file."); } $fileHandle = $this->_fileHandle; rewind($fileHandle); // Create new PHPExcel while ($objPHPExcel->getSheetCount() <= $this->_sheetIndex) { $objPHPExcel->createSheet(); } $objPHPExcel->setActiveSheetIndex( $this->_sheetIndex ); $fromFormats = array('\-', '\ '); $toFormats = array('-', ' '); // Loop through file $rowData = array(); $column = $row = ''; // loop through one row (line) at a time in the file while (($rowData = fgets($fileHandle)) !== FALSE) { // convert SYLK encoded $rowData to UTF-8 $rowData = PHPExcel_Shared_String::SYLKtoUTF8($rowData); // explode each row at semicolons while taking into account that literal semicolon (;) // is escaped like this (;;) $rowData = explode("\t",str_replace('짚',';',str_replace(';',"\t",str_replace(';;','짚',rtrim($rowData))))); $dataType = array_shift($rowData); // Read shared styles if ($dataType == 'P') { $formatArray = array(); foreach($rowData as $rowDatum) { switch($rowDatum{0}) { case 'P' : $formatArray['numberformat']['code'] = str_replace($fromFormats,$toFormats,substr($rowDatum,1)); break; case 'E' : case 'F' : $formatArray['font']['name'] = substr($rowDatum,1); break; case 'L' : $formatArray['font']['size'] = substr($rowDatum,1); break; case 'S' : $styleSettings = substr($rowDatum,1); for ($i=0;$i<strlen($styleSettings);++$i) { switch ($styleSettings{$i}) { case 'I' : $formatArray['font']['italic'] = true; break; case 'D' : $formatArray['font']['bold'] = true; break; case 'T' : $formatArray['borders']['top']['style'] = PHPExcel_Style_Border::BORDER_THIN; break; case 'B' : $formatArray['borders']['bottom']['style'] = PHPExcel_Style_Border::BORDER_THIN; break; case 'L' : $formatArray['borders']['left']['style'] = PHPExcel_Style_Border::BORDER_THIN; break; case 'R' : $formatArray['borders']['right']['style'] = PHPExcel_Style_Border::BORDER_THIN; break; } } break; } } $this->_formats['P'.$this->_format++] = $formatArray; // Read cell value data } elseif ($dataType == 'C') { $hasCalculatedValue = false; $cellData = $cellDataFormula = ''; foreach($rowData as $rowDatum) { switch($rowDatum{0}) { case 'C' : case 'X' : $column = substr($rowDatum,1); break; case 'R' : case 'Y' : $row = substr($rowDatum,1); break; case 'K' : $cellData = substr($rowDatum,1); break; case 'E' : $cellDataFormula = '='.substr($rowDatum,1); // Convert R1C1 style references to A1 style references (but only when not quoted) $temp = explode('"',$cellDataFormula); $key = false; foreach($temp as &$value) { // Only count/replace in alternate array entries if ($key = !$key) { preg_match_all('/(R(\[?-?\d*\]?))(C(\[?-?\d*\]?))/',$value, $cellReferences,PREG_SET_ORDER+PREG_OFFSET_CAPTURE); // Reverse the matches array, otherwise all our offsets will become incorrect if we modify our way // through the formula from left to right. Reversing means that we work right to left.through // the formula $cellReferences = array_reverse($cellReferences); // Loop through each R1C1 style reference in turn, converting it to its A1 style equivalent, // then modify the formula to use that new reference foreach($cellReferences as $cellReference) { $rowReference = $cellReference[2][0]; // Empty R reference is the current row if ($rowReference == '') $rowReference = $row; // Bracketed R references are relative to the current row if ($rowReference{0} == '[') $rowReference = $row + trim($rowReference,'[]'); $columnReference = $cellReference[4][0]; // Empty C reference is the current column if ($columnReference == '') $columnReference = $column; // Bracketed C references are relative to the current column if ($columnReference{0} == '[') $columnReference = $column + trim($columnReference,'[]'); $A1CellReference = PHPExcel_Cell::stringFromColumnIndex($columnReference-1).$rowReference; $value = substr_replace($value,$A1CellReference,$cellReference[0][1],strlen($cellReference[0][0])); } } } unset($value); // Then rebuild the formula string $cellDataFormula = implode('"',$temp); $hasCalculatedValue = true; break; } } $columnLetter = PHPExcel_Cell::stringFromColumnIndex($column-1); $cellData = PHPExcel_Calculation::_unwrapResult($cellData); // Set cell value $objPHPExcel->getActiveSheet()->getCell($columnLetter.$row)->setValue(($hasCalculatedValue) ? $cellDataFormula : $cellData); if ($hasCalculatedValue) { $cellData = PHPExcel_Calculation::_unwrapResult($cellData); $objPHPExcel->getActiveSheet()->getCell($columnLetter.$row)->setCalculatedValue($cellData); } // Read cell formatting } elseif ($dataType == 'F') { $formatStyle = $columnWidth = $styleSettings = ''; $styleData = array(); foreach($rowData as $rowDatum) { switch($rowDatum{0}) { case 'C' : case 'X' : $column = substr($rowDatum,1); break; case 'R' : case 'Y' : $row = substr($rowDatum,1); break; case 'P' : $formatStyle = $rowDatum; break; case 'W' : list($startCol,$endCol,$columnWidth) = explode(' ',substr($rowDatum,1)); break; case 'S' : $styleSettings = substr($rowDatum,1); for ($i=0;$i<strlen($styleSettings);++$i) { switch ($styleSettings{$i}) { case 'I' : $styleData['font']['italic'] = true; break; case 'D' : $styleData['font']['bold'] = true; break; case 'T' : $styleData['borders']['top']['style'] = PHPExcel_Style_Border::BORDER_THIN; break; case 'B' : $styleData['borders']['bottom']['style'] = PHPExcel_Style_Border::BORDER_THIN; break; case 'L' : $styleData['borders']['left']['style'] = PHPExcel_Style_Border::BORDER_THIN; break; case 'R' : $styleData['borders']['right']['style'] = PHPExcel_Style_Border::BORDER_THIN; break; } } break; } } if (($formatStyle > '') && ($column > '') && ($row > '')) { $columnLetter = PHPExcel_Cell::stringFromColumnIndex($column-1); if (isset($this->_formats[$formatStyle])) { $objPHPExcel->getActiveSheet()->getStyle($columnLetter.$row)->applyFromArray($this->_formats[$formatStyle]); } } if ((!empty($styleData)) && ($column > '') && ($row > '')) { $columnLetter = PHPExcel_Cell::stringFromColumnIndex($column-1); $objPHPExcel->getActiveSheet()->getStyle($columnLetter.$row)->applyFromArray($styleData); } if ($columnWidth > '') { if ($startCol == $endCol) { $startCol = PHPExcel_Cell::stringFromColumnIndex($startCol-1); $objPHPExcel->getActiveSheet()->getColumnDimension($startCol)->setWidth($columnWidth); } else { $startCol = PHPExcel_Cell::stringFromColumnIndex($startCol-1); $endCol = PHPExcel_Cell::stringFromColumnIndex($endCol-1); $objPHPExcel->getActiveSheet()->getColumnDimension($startCol)->setWidth($columnWidth); do { $objPHPExcel->getActiveSheet()->getColumnDimension(++$startCol)->setWidth($columnWidth); } while ($startCol != $endCol); } } } else { foreach($rowData as $rowDatum) { switch($rowDatum{0}) { case 'C' : case 'X' : $column = substr($rowDatum,1); break; case 'R' : case 'Y' : $row = substr($rowDatum,1); break; } } } } // Close file fclose($fileHandle); // Return return $objPHPExcel; } /** * Get sheet index * * @return int */ public function getSheetIndex() { return $this->_sheetIndex; } /** * Set sheet index * * @param int $pValue Sheet index * @return PHPExcel_Reader_SYLK */ public function setSheetIndex($pValue = 0) { $this->_sheetIndex = $pValue; return $this; } }
cigiko/brdnc.cafe24.com
os/PHPExcel/Classes/PHPExcel/Reader/SYLK.php
PHP
mit
14,181
package com.polydes.common.comp.utils; import java.awt.AWTEvent; import java.awt.Component; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.awt.event.MouseEvent; public class HierarchyLeaveListener extends TemporaryAWTListener implements FocusListener { private boolean inHierarchy; //was the last click in the component's hierarchy private final Component component; private final Runnable callback; public HierarchyLeaveListener(Component component, final Runnable callback) { super(AWTEvent.MOUSE_EVENT_MASK); this.component = component; this.callback = callback; component.addFocusListener(this); } @Override public void eventDispatched(AWTEvent e) { if(e instanceof MouseEvent) { MouseEvent me = (MouseEvent) e; if(me.getClickCount() > 0 && e.toString().contains("PRESSED")) { Component c = (Component) me.getSource(); if(inHierarchy != SwingUtils.isDescendingFrom(c, component)) { inHierarchy = !inHierarchy; if(!inHierarchy) callback.run(); } } } } @Override public void dispose() { super.dispose(); component.removeFocusListener(this); } @Override public void focusGained(FocusEvent e) { inHierarchy = true; start(); } @Override public void focusLost(FocusEvent e) { if(!inHierarchy) stop(); } }
justin-espedal/polydes
Common/src/com/polydes/common/comp/utils/HierarchyLeaveListener.java
Java
mit
1,420
import {bindable} from 'aurelia-framework'; export class SideBarLeft { @bindable router; @bindable layoutCnf = {}; }
hoalongntc/aurelia-material
src/components/layout/sidebar-left.js
JavaScript
mit
122
/** * @depends nothing * @name core.array * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} */ /** * Remove a element, or a set of elements from an array * @version 1.0.0 * @date June 30, 2010 * @copyright John Resig * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ Array.prototype.remove = function(from, to) { var rest = this.slice((to || from) + 1 || this.length); this.length = from < 0 ? this.length + from : from; return this.push.apply(this, rest); }; /** * Get a element from an array at [index] * if [current] is set, then set this index as the current index (we don't care if it doesn't exist) * @version 1.0.1 * @date July 09, 2010 * @since 1.0.0 June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ Array.prototype.get = function(index, current) { // Determine if ( index === 'first' ) { index = 0; } else if ( index === 'last' ) { index = this.length-1; } else if ( index === 'prev' ) { index = this.index-1; } else if ( index === 'next' ) { index = this.index+1; } else if ( !index && index !== 0 ) { index = this.index; } // Set current? if ( current||false !== false ) { this.setIndex(index); } // Return return this.exists(index) ? this[index] : undefined; }; /** * Apply the function {handler} to each element in the array * Return false in the {handler} to break the cycle. * @param {Function} handler * @version 1.0.1 * @date August 20, 2010 * @since June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ Array.prototype.each = function(handler){ for (var i = 0; i < this.length; ++i) { var value = this[i]; if ( handler.apply(value,[i,value]) === false ) { break; } } return this; } /** * Checks whether the index is a valid index * @version 1.0.0 * @date July 09, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ Array.prototype.validIndex = function(index){ return index >= 0 && index < this.length; }; /** * Set the current index of the array * @version 1.0.0 * @date June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ Array.prototype.setIndex = function(index){ if ( this.validIndex(index) ) { this.index = index; } else { this.index = null; } return this; }; /** * Get the current index of the array * If [index] is passed then set that as the current, and return it's value * @version 1.0.0 * @date June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ Array.prototype.current = function(index){ return this.get(index, true); }; /** * Get whether or not the array is empty * @version 1.0.0 * @date June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ Array.prototype.isEmpty = function(){ return this.length === 0; }; /** * Get whether or not the array has only one item * @version 1.0.0 * @date June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ Array.prototype.isSingle = function(){ return this.length === 1; }; /** * Get whether or not the array is not empty * @version 1.0.0 * @date June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ Array.prototype.isNotEmpty = function(){ return this.length !== 0; }; /** * Get whether or not the array has more than one item * @version 1.0.0 * @date June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ Array.prototype.isNotEmpty = function(){ return this.length > 1; }; /** * Get whether or not the current index is the last one * @version 1.0.0 * @date June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ Array.prototype.isLast = function(index){ index = typeof index === 'undefined' ? this.index : index; return !this.isEmpty() && index === this.length-1; } /** * Get whether or not the current index is the first one * @version 1.0.0 * @date June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ Array.prototype.isFirst = function(index){ index = typeof index === 'undefined' ? this.index : index; return !this.isEmpty() && index === 0; } /** * Clear the array * @version 1.0.0 * @date June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ Array.prototype.clear = function(){ this.length = 0; }; /** * Set the index as the next one, and get the item * @version 1.0.0 * @date June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ Array.prototype.next = function(update){ return this.get(this.index+1, update); }; /** * Set the index as the previous one, and get the item * @version 1.0.0 * @date June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ Array.prototype.prev = function(update){ return this.get(this.index-1, update); }; /** * Reset the index * @version 1.0.0 * @date June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ Array.prototype.reset = function(){ this.index = null; return this; }; /** * Set the [index] to the [item] * @version 1.0.0 * @date June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ Array.prototype.set = function(index, item){ // We want to set the item if ( index < this.length && index >= 0 ) { this[index] = item; } else { throw new Error('Array.prototype.set: [index] above this.length'); // return false; } return this; }; /** * Set the index as the next item, and return it. * If we reach the end, then start back at the beginning. * @version 1.0.0 * @date June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ Array.prototype.loop = function(){ if ( !this.index && this.index !== 0 ) { // index is not a valid value return this.current(0); } return this.next(); }; /** * Add the [arguments] to the array * @version 1.0.0 * @date June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ Array.prototype.add = function(){ this.push.apply(this,arguments); return this; }; /** * Insert the [item] at the [index] or at the end of the array * @version 1.0.0 * @date June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ Array.prototype.insert = function(index, item){ if ( typeof index !== 'number' ) { index = this.length; } index = index<=this.length ? index : this.length; var rest = this.slice(index); this.length = index; this.push(item); this.push.apply(this, rest); return this; }; /** * Get whether or not the index exists in the array * @version 1.0.0 * @date July 09, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ Array.prototype.exists = Array.prototype.exists || function(index){ return typeof this[index] !== 'undefined'; }; /** * Get whether or not the value exists in the array * @version 1.0.0 * @date June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ Array.prototype.has = Array.prototype.has || function(value){ var has = false; for ( var i=0, n=this.length; i<n; ++i ) { if ( value == this[i] ) { has = true; break; } } return has; }; /** * @depends nothing * @name core.console * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} */ /** * Console Emulator * We have to convert arguments into arrays, and do this explicitly as webkit (chrome) hates function references, and arguments cannot be passed as is * @version 1.0.3 * @date August 31, 2010 * @since 0.1.0-dev, December 01, 2009 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ // Check to see if console exists, if not define it if ( typeof window.console === 'undefined' ) { window.console = {}; } // Check to see if we have emulated the console yet if ( typeof window.console.emulated === 'undefined' ) { // Emulate Log if ( typeof window.console.log === 'function' ) { window.console.hasLog = true; } else { if ( typeof window.console.log === 'undefined' ) { window.console.log = function(){}; } window.console.hasLog = false; } // Emulate Debug if ( typeof window.console.debug === 'function' ) { window.console.hasDebug = true; } else { if ( typeof window.console.debug === 'undefined' ) { window.console.debug = !window.console.hasLog ? function(){} : function(){ var arr = ['console.debug:']; for(var i = 0; i < arguments.length; i++) { arr.push(arguments[i]); }; window.console.log.apply(window.console, arr); }; } window.console.hasDebug = false; } // Emulate Warn if ( typeof window.console.warn === 'function' ) { window.console.hasWarn = true; } else { if ( typeof window.console.warn === 'undefined' ) { window.console.warn = !window.console.hasLog ? function(){} : function(){ var arr = ['console.warn:']; for(var i = 0; i < arguments.length; i++) { arr.push(arguments[i]); }; window.console.log.apply(window.console, arr); }; } window.console.hasWarn = false; } // Emulate Error if ( typeof window.console.error === 'function' ) { window.console.hasError = true; } else { if ( typeof window.console.error === 'undefined' ) { window.console.error = function(){ var msg = "An error has occured."; // Log if ( window.console.hasLog ) { var arr = ['console.error:']; for(var i = 0; i < arguments.length; i++) { arr.push(arguments[i]); }; window.console.log.apply(window.console, arr); // Adjust Message msg = 'An error has occured. More information is available in your browser\'s javascript console.' } // Prepare Arguments for ( var i = 0; i < arguments.length; ++i ) { if ( typeof arguments[i] !== 'string' ) { break; } msg += "\n"+arguments[i]; } // Throw Error if ( typeof Error !== 'undefined' ) { throw new Error(msg); } else { throw(msg); } }; } window.console.hasError = false; } // Emulate Trace if ( typeof window.console.trace === 'function' ) { window.console.hasTrace = true; } else { if ( typeof window.console.trace === 'undefined' ) { window.console.trace = function(){ window.console.error('console.trace does not exist'); }; } window.console.hasTrace = false; } // Done window.console.emulated = true; } /** * @depends nothing * @name core.date * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} */ /** * Apply the Datetime string to the current Date object * Datetime string in the format of "year month day hour min sec". "hour min sec" all optional. * @version 1.0.0 * @date June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ Date.prototype.setDatetimestr = Date.prototype.setDatetimestr || function(timestamp){ // Set the datetime from a string var pieces = timestamp.split(/[\-\s\:]/g); var year = pieces[0]; var month = pieces[1]; var day = pieces[2]; var hour = pieces[3]||0; var min = pieces[4]||0; var sec = pieces[5]||0; this.setUTCFullYear(year,month-1,day); this.setUTCHours(hour); this.setUTCMinutes(min); this.setUTCSeconds(sec); return this; }; /** * Apply the Date string to the current Date object * Date string in the format of "year month day". "year month day" all optional. * @version 1.0.0 * @date June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ Date.prototype.setDatestr = Date.prototype.setDatestr || function(timestamp){ // Set the date from a string var pieces = timestamp.split(/[\-\s\:]/g); var year = pieces[0]||1978; var month = pieces[1]||0; var day = pieces[2]||1; this.setUTCFullYear(year,month-1,day); return this; }; /** * Apply the Time string to the current Date object * Time string in the format of "hour min sec". "hour min sec" all optional. * @version 1.0.0 * @date June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ Date.prototype.setTimestr = Date.prototype.setTimestr || function(timestamp){ // Set the time from a string var pieces = timestamp.split(/[\-\s\:]/g); var hour = pieces[0]||0; var min = pieces[1]||0; var sec = pieces[2]||0; this.setUTCHours(hour); this.setUTCMinutes(min); this.setUTCSeconds(sec); return this; }; /** * Return the Date as a Datetime string * Datetime string in the format of "year-month-date hours:minutes:seconds". * @version 1.0.0 * @date June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ Date.prototype.getDatetimestr = Date.prototype.getDatetimestr || function() { // Get the datetime as a string var date = this; return date.getDatestr()+' '+date.getTimestr(); }; /** * Return the Date as a Datetime string * Datetime string in the format of "year-month-date". * @version 1.0.0 * @date June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ Date.prototype.getDatestr = Date.prototype.getDatestr || function() { // Get the date as a string var date = this; var year = date.getUTCFullYear(); var month = (this.getUTCMonth() + 1).padLeft(0,2); var date = this.getUTCDate().padLeft(0,2); return year+'-'+month+'-'+date; }; /** * Return the Date as a Datetime string * Datetime string in the format of "hours:minutes:seconds". * @version 1.0.0 * @date June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ Date.prototype.getTimestr = Date.prototype.getTimestr || function(){ // Get the time as a string var date = this; var hours = date.getUTCHours().padLeft(0,2); var minutes = date.getUTCMinutes().padLeft(0,2); var seconds = date.getUTCSeconds().padLeft(0,2); return hours+':'+minutes+':'+seconds; }; /** * Return the Date as a ISO 8601 date string * @version 1.0.0 * @date June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ Date.prototype.getDatetime = String.prototype.getDatetime || function(){ // Get a ISO 8601 date var now = this; var datetime = now.getUTCFullYear() + '-' + (now.getUTCMonth()+1).zeroise(2) + '-' + now.getUTCDate().zeroise(2) + 'T' + now.getUTCHours().zeroise(2) + ':' + now.getUTCMinutes().zeroise(2) + ':' + now.getUTCSeconds().zeroise(2) + '+00:00'; return datetime; }; /** * @depends nothing * @name core.number * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} */ /** * Return a new string with zeroes added correctly to the front of the number, given the threshold * @version 1.0.0 * @date June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ Number.prototype.zeroise = String.prototype.zeroise = String.prototype.zeroise ||function(threshold){ var number = this, str = number.toString(); if (number < 0) { str = str.substr(1, str.length) } while (str.length < threshold) { str = '0' + str } if (number < 0) { str = '-' + str } return str; }; /** * Return a new string with the string/number padded left using [ch] of [num] length * @version 1.0.0 * @date June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ Number.prototype.padLeft = String.prototype.padLeft = String.prototype.padLeft ||function(ch, num){ var val = String(this); var re = new RegExp('.{' + num + '}$'); var pad = ''; if ( !ch && ch !== 0 ) ch = ' '; do { pad += ch; } while(pad.length < num); return re.exec(pad + val)[0]; }; /** * Return a new string with the string/number padded right using [ch] of [num] length * @version 1.0.0 * @date June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ Number.prototype.padRight = String.prototype.padRight = String.prototype.padRight ||function(ch, num){ var val = String(this); var re = new RegExp('^.{' + num + '}'); var pad = ''; if ( !ch && ch !== 0 ) ch = ' '; do { pad += ch; } while (pad.length < num); return re.exec(val + pad)[0]; }; /** * Return a new number with the current number rounded to [to] * @version 1.0.0 * @date June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ Number.prototype.roundTo = String.prototype.roundTo = String.prototype.roundTo || function(to){ var val = String(parseInt(this,10)); val = parseInt(val.replace(/[1,2]$/, 0).replace(/[3,4]$/, 5),10); return val; }; /** * @depends nothing * @name core.string * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} */ /** * Return a new string with any spaces trimmed the left and right of the string * @version 1.0.0 * @date June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ String.prototype.trim = String.prototype.trim || function() { // Trim off any whitespace from the front and back return this.replace(/^\s+|\s+$/g, ''); }; /** * Return a new string with the value stripped from the left and right of the string * @version 1.1.1 * @date July 22, 2010 * @since 1.0.0, June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ String.prototype.strip = String.prototype.strip || function(value,regex){ // Strip a value from left and right, with optional regex support (defaults to false) value = String(value); var str = this; if ( value.length ) { if ( !(regex||false) ) { // We must escape value as we do not want regex support value = value.replace(/([\[\]\(\)\^\$\.\?\|\/\\])/g, '\\$1'); } str = str.replace(eval('/^'+value+'+|'+value+'+$/g'), ''); } return String(str); } /** * Return a new string with the value stripped from the left of the string * @version 1.1.1 * @date July 22, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ String.prototype.stripLeft = String.prototype.stripLeft || function(value,regex){ // Strip a value from the left, with optional regex support (defaults to false) value = String(value); var str = this; if ( value.length ) { if ( !(regex||false) ) { // We must escape value as we do not want regex support value = value.replace(/([\[\]\(\)\^\$\.\?\|\/\\])/g, '\\$1'); } str = str.replace(eval('/^'+value+'+/g'), ''); } return String(str); } /** * Return a new string with the value stripped from the right of the string * @version 1.1.1 * @date July 22, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ String.prototype.stripRight = String.prototype.stripRight || function(value,regex){ // Strip a value from the right, with optional regex support (defaults to false) value = String(value); var str = this; if ( value.length ) { if ( !(regex||false) ) { // We must escape value as we do not want regex support value = value.replace(/([\[\]\(\)\^\$\.\?\|\/\\])/g, '\\$1'); } str = str.replace(eval('/'+value+'+$/g'), ''); } return String(str); } /** * Return a int of the string * @version 1.0.0 * @date June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ String.prototype.toInt = String.prototype.toInt || function(){ // Convert to a Integer return parseInt(this,10); }; /** * Return a new string of the old string wrapped with the start and end values * @version 1.0.0 * @date June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ String.prototype.wrap = String.prototype.wrap || function(start,end){ // Wrap the string return start+this+end; }; /** * Return a new string of a selection of the old string wrapped with the start and end values * @version 1.0.0 * @date June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ String.prototype.wrapSelection = String.prototype.wrapSelection || function(start,end,a,z){ // Wrap the selection if ( typeof a === 'undefined' || a === null ) a = this.length; if ( typeof z === 'undefined' || z === null ) z = this.length; return this.substring(0,a)+start+this.substring(a,z)+end+this.substring(z); }; /** * Return a new string of the slug of the old string * @version 1.1.0 * @date July 16, 2010 * @since 1.0.0, June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ String.prototype.toSlug = String.prototype.toSlug || function(){ // Convert a string to a slug return this.toLowerCase().replace(/[\s_]/g, '-').replace(/[^-a-z0-9]/g, '').replace(/--+/g, '-').replace(/^-+|-+$/g,''); } /** * Return a new JSON object of the old string. * Turns: * file.js?a=1&amp;b.c=3.0&b.d=four&a_false_value=false&a_null_value=null * Into: * {"a":1,"b":{"c":3,"d":"four"},"a_false_value":false,"a_null_value":null} * @version 1.1.0 * @date July 16, 2010 * @since 1.0.0, June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ String.prototype.queryStringToJSON = String.prototype.queryStringToJSON || function ( ) { // Turns a params string or url into an array of params // Prepare var params = String(this); // Remove url if need be params = params.substring(params.indexOf('?')+1); // params = params.substring(params.indexOf('#')+1); // Change + to %20, the %20 is fixed up later with the decode params = params.replace(/\+/g, '%20'); // Do we have JSON string if ( params.substring(0,1) === '{' && params.substring(params.length-1) === '}' ) { // We have a JSON string return eval(decodeURIComponent(params)); } // We have a params string params = params.split(/\&(amp\;)?/); var json = {}; // We have params for ( var i = 0, n = params.length; i < n; ++i ) { // Adjust var param = params[i] || null; if ( param === null ) { continue; } param = param.split('='); if ( param === null ) { continue; } // ^ We now have "var=blah" into ["var","blah"] // Get var key = param[0] || null; if ( key === null ) { continue; } if ( typeof param[1] === 'undefined' ) { continue; } var value = param[1]; // ^ We now have the parts // Fix key = decodeURIComponent(key); value = decodeURIComponent(value); try { // value can be converted value = eval(value); } catch ( e ) { // value is a normal string } // Set // window.console.log({'key':key,'value':value}, split); var keys = key.split('.'); if ( keys.length === 1 ) { // Simple json[key] = value; } else { // Advanced (Recreating an object) var path = '', cmd = ''; // Ensure Path Exists $.each(keys,function(ii,key){ path += '["'+key.replace(/"/g,'\\"')+'"]'; jsonCLOSUREGLOBAL = json; // we have made this a global as closure compiler struggles with evals cmd = 'if ( typeof jsonCLOSUREGLOBAL'+path+' === "undefined" ) jsonCLOSUREGLOBAL'+path+' = {}'; eval(cmd); json = jsonCLOSUREGLOBAL; delete jsonCLOSUREGLOBAL; }); // Apply Value jsonCLOSUREGLOBAL = json; // we have made this a global as closure compiler struggles with evals valueCLOSUREGLOBAL = value; // we have made this a global as closure compiler struggles with evals cmd = 'jsonCLOSUREGLOBAL'+path+' = valueCLOSUREGLOBAL'; eval(cmd); json = jsonCLOSUREGLOBAL; delete jsonCLOSUREGLOBAL; delete valueCLOSUREGLOBAL; } // ^ We now have the parts added to your JSON object } return json; }; /** * @depends jquery * @name jquery.appendscriptstyle * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} */ /** * jQuery Aliaser */ (function($){ /** * Append a Stylesheet to the DOM * @version 1.1.0 * @date July 23, 2010 * @since 1.0.0, June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ $.appendStylesheet = $.appendStylesheet || function(url, overwrite){ // Check if ( !(document.body||false) ) { setTimeout(function(){ $.appendStylesheet.apply($,[url,overwrite]); },500); // Chain return $; } // Prepare var id = 'stylesheet-'+url.replace(/[^a-zA-Z0-9]/g, '');; var $old = $('#'+id); if ( typeof overwrite === 'undefined' ) { overwrite = false; } // Check if ( $old.length === 1 ) { if ( overwrite ) { $old.remove(); } else { // Chain return $; } } // Create var bodyEl = document.getElementsByTagName($.browser.safari ? 'head' : 'body')[0]; var linkEl = document.createElement('link'); linkEl.type = 'text/css'; linkEl.rel = 'stylesheet'; linkEl.media = 'screen'; linkEl.href = url; linkEl.id = id; bodyEl.appendChild(linkEl); // Chain return $; }; /** * Append a Script to the DOM * @version 1.1.0 * @date July 23, 2010 * @since 1.0.0, June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ $.appendScript = $.appendScript || function(url, overwrite){ // Check if ( !(document.body||false) ) { setTimeout(function(){ $.appendScript.apply($,[url,overwrite]); },500); // Chain return $; } // Prepare var id = 'script-'+url.replace(/[^a-zA-Z0-9]/g, '');; var $old = $('#'+id); if ( typeof overwrite === 'undefined' ) { overwrite = false; } // Check if ( $old.length === 1 ) { if ( overwrite ) { $old.remove(); } else { // Chain return $; } } // Create var bodyEl = document.getElementsByTagName($.browser.safari ? 'head' : 'body')[0]; var scriptEl = document.createElement('script'); scriptEl.type = 'text/javascript'; scriptEl.src = url; scriptEl.id = id; bodyEl.appendChild(scriptEl); // Chain return $; }; })(jQuery); /** * @depends jquery * @name jquery.extra * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} */ /** * jQuery Aliaser */ (function($){ /** * Opacity Fix for Text without Backgrounds * Fixes the text corrosion during opacity effects by forcing a background-color value on the element. * The background-color value is the the same value as the first parent div which has a background-color. * @version 1.0.0 * @date June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ $.fn.opacityFix = $.fn.opacityFix || function(){ var $this = $(this); // Check if this fix applies var color = $this.css('background-color'); if ( color && color !== 'rgba(0, 0, 0, 0)' ) { return this; } // Apply the background colour of the first parent which has a background colour var $parent = $this; while ( $parent.inDOM() ) { $parent = $parent.parent(); color = $parent.css('background-color'); if ( color && color !== 'rgba(0, 0, 0, 0)' ) { $this.css('background-color',color); break; } } // Chain return this; }; /** * Get all elements above ourself which match the selector, and include ourself in the search * @version 1.0.0 * @date June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ $.fn.parentsAndSelf = $.fn.parentsAndSelf || function(selector){ var $this = $(this); return $this.parents(selector).andSelf().filter(selector); }; /** * Get all elements within ourself which match the selector, and include ourself in the search * @version 1.0.0 * @date June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ $.fn.findAndSelf = $.fn.findAndSelf || function(selector){ var $this = $(this); return $this.find(selector).andSelf().filter(selector); }; /** * Find the first input, and include ourself in the search * @version 1.0.0 * @date June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ $.fn.firstInput = $.fn.firstInput || function(){ var $this = $(this); return $this.findAndSelf(':input').filter(':first'); }; /** * Select a option within options, checkboxes, radios and selects. * Rather than setting the actual value of a element which $el.val does. * @version 1.0.0 * @date June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ $.fn.choose = $.fn.choose||function(value){ var $this = $(this); if ( typeof value === 'undefined' ) { value = $this.val(); } else if ( $this.val() !== value ) { // Return early, don't match return this; } switch ( true ) { case this.is('option'): $this.parents('select:first').choose(value); break; case $this.is(':checkbox'): $this.attr('checked', true); break; case $this.is(':radio'): $this.attr('checked', true); break; case $this.is('select'): $this.val(value); break; default: break; } return this; }; /** * Deselect a option within options, checkboxes, radios and selects. * @version 1.0.0 * @date June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ $.fn.unchoose = $.fn.unchoose||function(){ var $this = $(this); switch ( true ) { case $this.is('option'): $this.parents(':select:first').unchoose(); break; case $this.is(':checkbox'): $this.attr('checked', false); break; case $this.is(':radio'): $this.attr('checked', false); break; case $this.is('select'): $this.val($this.find('option:first').val()); break; default: break; } return this; }; /** * Checks if the element would be passed with the form if the form was submitted. * @version 1.0.0 * @date June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ $.fn.wouldSubmit = $.fn.wouldSubmit || function(){ var $input = $(this).findAndSelf(':input'); var result = true; if ( !$input.length || !($input.attr('name')||false) || ($input.is(':radio,:checkbox') && !$input.is(':selected,:checked')) ) { result = false; } return result; }; /** * Grab all the values of a form in JSON format if the form would be submitted. * @version 1.0.0 * @date June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ $.fn.values = $.fn.values || function(){ var $inputs = $(this).findAndSelf(':input'); var values = {}; $inputs.each(function(){ var $input = $(this); var name = $input.attr('name') || null; var value = $input.val(); // Skip if wouldn't submit if ( !$input.wouldSubmit() ) { return true; } // Set value if (name.indexOf('[]') !== -1) { // We want an array if (typeof values[name] === 'undefined') { values[name] = []; } values[name].push(value); } else { values[name] = value; } }); return values; }; /** * Submit the form which the element is associated with. * @version 1.0.0 * @date June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ $.fn.submitForm = $.fn.submitForm || function(){ // Submit the parent form or our form var $this = $(this); // Handle var $form = $this.parentsAndSelf('form:first').trigger('submit'); // Chain return $this; }; /** * Checks if the element is attached within the DOM * @version 1.0.0 * @date June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ $.fn.inDOM = $.fn.inDOM || function(){ var $ancestor = $(this).parent().parent(); return $ancestor.size() && ($ancestor.height()||$ancestor.width()); }; /** * Wrap the element's value with the passed start and end text * @version 1.0.0 * @date June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ $.fn.valWrap = $.fn.valWrap || function(start,end){ // Wrap a value var $field = $(this); return $field.val($field.val().wrap(start,end)); }; /** * Wrap a selection of the element's value with the passed start and end text * @version 1.0.0 * @date June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ $.fn.valWrapSelection = $.fn.valWrapSelection || function(start,end,a,z){ // Wrap the selected text var $field = $(this); var field = $field.get(0); start = start||''; end = end||''; if ( a || z ) { $field.val($field.val().wrapSelection(start,end,a,z)); } else { var a = field.selectionStart, z = field.selectionEnd; if ( document.selection) { field.focus(); var sel = document.selection.createRange(); sel.text = start + sel.text + end; } else { var scrollTop = field.scrollTop; $field.val($field.val().wrapSelection(start,end,a,z)); field.focus(); field.selectionStart = a+start.length; field.selectionEnd = z+start.length; field.scrollTop = scrollTop; } } return $field; }; /** * Find (with regards to the element) the first visible input element, and give focus to it * @version 1.0.0 * @date June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ $.fn.giveFocus = $.fn.giveFocus || function(){ // Give focus to the current element var $this = $(this); var selector = ':input:visible:first'; $this.findAndSelf(selector).focus(); return this; }; /** * Gives target to the element, and removes target from everything else * @version 1.0.0 * @date August 23, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ $.fn.giveTarget = $.fn.giveTarget || function(){ // Give focus to the current element var $this = $(this); $('.target').removeClass('target'); $this.addClass('target'); return this; }; /** * Perform the highlight effect * @version 1.0.0 * @date June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ $.fn.highlight = $.fn.highlight || function(duration){ // Perform the Highlight Effect return $(this).effect('highlight', {}, duration||3000); }; /** * Get a elements html including it's own tag * @version 1.0.1 * @date August 07, 2010 * @since 1.0.0, August 07, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ $.fn.htmlAndSelf = $.fn.htmlAndSelf || function(){ // Get a elements html including it's own tag return $(this).attr('outerHTML'); }; /** * Prevent the default action when a click is performed * @version 1.0.1 * @date August 31, 2010 * @since 1.0.0, August 19, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ $.fn.preventDefaultOnClick = $.fn.preventDefaultOnClick || function(){ return $(this).click(function(event){ event.preventDefault(); return false; }); }; /** * Attempts to change the element type to {$type} * @version 1.0.1 * @date August 07, 2010 * @since 1.0.0, August 07, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ $.fn.attemptTypeChangeTo = $.fn.attemptTypeChangeTo || function(type){ // Prepare var $input = $(this), result = false, el = $input.get(0), oldType = el.type; // Handle if ( type === oldType ) { // Setting to the same result = true; } else if ( $input.is('input') ) { // We are in fact an input if ( !$.browser.msie ) { // We are not IE, this is due to bug mentioned here: http://stackoverflow.com/questions/1544317/jquery-change-type-of-input-field el.type = type; if ( el.type !== oldType ) { // It stuck, so we successfully applied the type result = true; } } } // Return result return result; }; })(jQuery); /** * @depends jquery * @name jquery.events * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} */ /** * jQuery Aliaser */ (function($){ /** * Bind a event, with or without data * Benefit over $.bind, is that $.binder(event, callback, false|{}|''|false) works. * @version 1.0.0 * @date June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ $.fn.binder = $.fn.binder || function(event, data, callback){ // Help us bind events properly var $this = $(this); // Handle if ( (callback||false) ) { $this.bind(event, data, callback); } else { callback = data; $this.bind(event, callback); } // Chain return $this; }; /** * Bind a event only once * @version 1.0.0 * @date June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ $.fn.once = $.fn.once || function(event, data, callback){ // Only apply a event handler once var $this = $(this); // Handle if ( (callback||false) ) { $this.unbind(event, callback); $this.bind(event, data, callback); } else { callback = data; $this.unbind(event, callback); $this.bind(event, callback); } // Chain return $this; }; /** * Event for pressing the enter key * @version 1.0.0 * @date June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ $.fn.enter = $.fn.enter || function(data,callback){ return $(this).binder('enter',data,callback); }; $.event.special.enter = $.event.special.enter || { setup: function( data, namespaces ) { $(this).bind('keypress', $.event.special.enter.handler); }, teardown: function( namespaces ) { $(this).unbind('keypress', $.event.special.enter.handler); }, handler: function( event ) { // Prepare var $el = $(this); // Setup var enterKey = event.keyCode === 13; if ( enterKey ) { // Our event event.type = 'enter'; $.event.handle.apply(this, [event]); return true; } // Not our event return; } }; /** * Event for pressing the escape key * @version 1.0.0 * @date June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ $.fn.cancel = $.fn.cancel || function(data,callback){ return $(this).binder('cancel',data,callback); }; $.event.special.cancel = $.event.special.cancel || { setup: function( data, namespaces ) { $(this).bind('keyup', $.event.special.cancel.handler); }, teardown: function( namespaces ) { $(this).unbind('keyup', $.event.special.cancel.handler); }, handler: function( event ) { // Prepare var $el = $(this); // Setup var moz = typeof event.DOM_VK_ESCAPE === 'undefined' ? false : event.DOM_VK_ESCAPE; var escapeKey = event.keyCode === 27; if ( moz || escapeKey ) { // Our event event.type = 'cancel'; $.event.handle.apply(this, [event]); return true; } // Not our event return; } }; /** * Event for the last click for a series of one or more clicks * @version 1.0.0 * @date July 16, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ $.fn.lastclick = $.fn.lastclick || function(data,callback){ return $(this).binder('lastclick',data,callback); }; $.event.special.lastclick = $.event.special.lastclick || { setup: function( data, namespaces ) { $(this).bind('click', $.event.special.lastclick.handler); }, teardown: function( namespaces ) { $(this).unbind('click', $.event.special.lastclick.handler); }, handler: function( event ) { // Setup var clear = function(){ // Fetch var Me = this; var $el = $(Me); // Fetch Timeout var timeout = $el.data('lastclick-timeout')||false; // Clear Timeout if ( timeout ) { clearTimeout(timeout); } timeout = false; // Store Timeout $el.data('lastclick-timeout',timeout); }; var check = function(event){ // Fetch var Me = this; clear.call(Me); var $el = $(Me); // Store the amount of times we have been clicked $el.data('lastclick-clicks', ($el.data('lastclick-clicks')||0)+1); // Handle Timeout for when All Clicks are Completed var timeout = setTimeout(function(){ // Fetch Clicks Count var clicks = $el.data('lastclick-clicks'); // Clear Timeout clear.apply(Me,[event]); // Reset Click Count $el.data('lastclick-clicks',0); // Fire Event event.type = 'lastclick'; $.event.handle.apply(Me, [event,clicks]) },500); // Store Timeout $el.data('lastclick-timeout',timeout); }; // Fire check.apply(this,[event]); } }; /** * Event for the first click for a series of one or more clicks * @version 1.0.0 * @date July 16, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ $.fn.firstclick = $.fn.firstclick || function(data,callback){ return $(this).binder('firstclick',data,callback); }; $.event.special.firstclick = $.event.special.firstclick || { setup: function( data, namespaces ) { $(this).bind('click', $.event.special.firstclick.handler); }, teardown: function( namespaces ) { $(this).unbind('click', $.event.special.firstclick.handler); }, handler: function( event ) { // Setup var clear = function(event){ // Fetch var Me = this; var $el = $(Me); // Fetch Timeout var timeout = $el.data('firstclick-timeout')||false; // Clear Timeout if ( timeout ) { clearTimeout(timeout); } timeout = false; // Store Timeout $el.data('firstclick-timeout',timeout); }; var check = function(event){ // Fetch var Me = this; clear.call(Me); var $el = $(Me); // Update the amount of times we have been clicked $el.data('firstclick-clicks', ($el.data('firstclick-clicks')||0)+1); // Check we are the First of the series of many if ( $el.data('firstclick-clicks') === 1 ) { // Fire Event event.type = 'firstclick'; $.event.handle.apply(Me, [event]) } // Handle Timeout for when All Clicks are Completed var timeout = setTimeout(function(){ // Clear Timeout clear.apply(Me,[event]); // Reset Click Count $el.data('firstclick-clicks',0); },500); // Store Timeout $el.data('firstclick-timeout',timeout); }; // Fire check.apply(this,[event]); } }; /** * Event for performing a singleclick * @version 1.1.0 * @date July 16, 2010 * @since 1.0.0, June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ $.fn.singleclick = $.fn.singleclick || function(data,callback){ return $(this).binder('singleclick',data,callback); }; $.event.special.singleclick = $.event.special.singleclick || { setup: function( data, namespaces ) { $(this).bind('click', $.event.special.singleclick.handler); }, teardown: function( namespaces ) { $(this).unbind('click', $.event.special.singleclick.handler); }, handler: function( event ) { // Setup var clear = function(event){ // Fetch var Me = this; var $el = $(Me); // Fetch Timeout var timeout = $el.data('singleclick-timeout')||false; // Clear Timeout if ( timeout ) { clearTimeout(timeout); } timeout = false; // Store Timeout $el.data('singleclick-timeout',timeout); }; var check = function(event){ // Fetch var Me = this; clear.call(Me); var $el = $(Me); // Update the amount of times we have been clicked $el.data('singleclick-clicks', ($el.data('singleclick-clicks')||0)+1); // Handle Timeout for when All Clicks are Completed var timeout = setTimeout(function(){ // Fetch Clicks Count var clicks = $el.data('singleclick-clicks'); // Clear Timeout clear.apply(Me,[event]); // Reset Click Count $el.data('singleclick-clicks',0); // Check Click Status if ( clicks === 1 ) { // There was only a single click performed // Fire Event event.type = 'singleclick'; $.event.handle.apply(Me, [event]) } },500); // Store Timeout $el.data('singleclick-timeout',timeout); }; // Fire check.apply(this,[event]); } }; })(jQuery); /** * @depends jquery * @name jquery.utilities * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} */ /** * jQuery Aliaser */ (function($){ /** * Creates a new object, which uses baseObject's structure, and userObject's values when applicable * @params {Object} baseObject * @params {Object} userObject * @params {Object} ... * @return {Object} newObject * @version 1.0.0 * @date August 01, 2010 * @since 1.0.0 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ $.prepareObject = $.prepareObject || function(baseObject,userObject) { var newObject = {}; var skipValue = '$.prepareObject.skipValue'; // Extend newObject $.extend(newObject,baseObject||{}); // Intercept with the userObject $.intercept(true,newObject,userObject); // Handle additional params var objects = arguments; objects[0] = objects[1] = skipValue; // Cycle through additional objects $.each(objects,function(i,object){ // Check if we want to skip if ( object === skipValue ) return true; // continue // Intercept with the object $.intercept(true,newObject,object); }); // Return the newObject return newObject; }; /** * Intercept two objects * @params [deep], &object1, object2, ... * @version 1.0.0 * @date August 01, 2010 * @since 1.0.0 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ $.intercept = $.intercept || function() { // Prepare var objects = arguments, object, deep = false, copy = false; var skipValue = '$.intercept.skipValue'; // Check Deep if ( typeof objects[0] === 'boolean' ) { deep = objects[0]; objects[0] = skipValue; // Check Copy if ( typeof objects[1] === 'boolean' ) { copy = objects[1]; objects[1] = skipValue; // Handle Copy if ( copy ) { object = {}; } else { object = objects[2]; objects[2] = skipValue; } } else { object = objects[1]; objects[1] = skipValue; } } else { object = objects[0]; objects[0] = skipValue; } // Grab Keys var keys = {}; $.each(object,function(key){ keys[key] = true; }); // Intercept Objects if ( deep ) { // Cycle through objects $.each(objects, function(i,v){ // Check if we want to skip if ( v === skipValue ) return true; // continue // Cycle through arguments $.each(v, function(key,value){ // Check if the key exists so we can intercept if ( typeof keys[key] === 'undefined' ) return true; // continue // It exists, check value type if ( typeof value === 'object' && !(value.test||false && value.exec||false) ) { // Extend this object $.extend(object[key],value||{}); } else { // Copy value over object[key] = value; } }); }) } else { // Cycle through objects $.each(objects, function(i,v){ // Cycle through arguments $.each(v, function(key,value){ // Check if the key exists so we can intercept if ( typeof keys[key] === 'undefined' ) return true; // continue // It exists, check value type if ( typeof value === 'object' && !(value.test||false && value.exec||false) ) { // Intercept this object $.intercept(true,object[key],value); } else { // Copy value over object[key] = value; } }); }) } // Return object return object; }; /** * Handle a Promise * @param {Object} options.object * @param {String} options.handlers * @param {String} options.flag * @param {Funtion} options.handler * @return {Boolean} Whether or not the promise is ready * @version 1.0.0 * @date August 31, 2010 * @since 1.0.0 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ $.promise = $.promise || function(options){ // Extract var object = options.object||this; // Check if ( typeof object[options.handlers] === 'undefined' ) { object[options.handlers] = []; } if ( typeof object[options.flag] === 'undefined' ) { object[options.flag] = false; } // Extract var handlers = object[options.handlers], flag = object[options.flag], handler = options.arguments[0]; // Handle switch ( typeof handler ) { case 'boolean': // We want to set the flag as true or false, then continue on flag = object[options.flag] = handler; // no break, as we want to continue on case 'undefined': // We want to fire the handlers, so check if the flag is true if ( flag && handlers.length ) { // Fire the handlers $.each(handlers, function(i,handler){ handler.call(object); }); // Clear the handlers object[options.handlers] = []; } break; case 'function': // We want to add or fire a handler, so check the flag if ( flag ) { // Fire the event handler handler.call(object); } else { // Add to the handlers object[options.handlers].push(handler); } break; default: window.console.error('Unknown arguments for $.promise', [this, arguments]); break; } // Return flag return flag; } })(jQuery); /** * @depends jquery * @name jquery.passwordstrength * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} */ /** * jQuery Aliaser */ (function($){ /** * String.prototype.passwordStrength * @version 1.0.0 * @date June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ String.prototype.passwordstrength = String.prototype.passwordstrength || function(confirm,username){ var password = this.toString(), symbolSize = 0, natLog, score; confirm = confirm||''; username = username||''; // Short if ( password.length < 4 ) { return "short"; }; // Username if ( username.length && password.toLowerCase() == username.toLowerCase()) { return "username"; } // Confirm if ( confirm.length && password != confirm ) { return "mismatch"; } // Strength if ( password.match(/[0-9]/) ) symbolSize +=10; if ( password.match(/[a-z]/) ) symbolSize +=26; if ( password.match(/[A-Z]/) ) symbolSize +=26; if ( password.match(/[^a-zA-Z0-9]/) ) symbolSize +=31; // Score natLog = Math.log( Math.pow(symbolSize,password.length) ); score = natLog / Math.LN2; // Check if (score < 40 ) { return "low"; } else if (score < 56 ) { return "medium"; } // Strong return "high"; }; /** * jQuery Password Strength * @version 1.0.0 * @date June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ if ( !($.fn.passwordstrength||false) ) { $.fn.passwordstrength = function(options) { // Prepare var passwordstrength = $.fn.passwordstrength; passwordstrength.config = passwordstrength.config || { content: '<div class="sparkle-passwordstrength-result"></div><div class="sparkle-passwordstrength-description"></div>', contentSelectors: { result: '.sparkle-passwordstrength-result', description: '.sparkle-passwordstrength-description' }, strengthCss: { "short": "invalid", mismatch: "invalid", username: "invalid", low: "low", medium: "medium", high: "high", empty: "" }, il8n: { description: "Hint: The password should be have a strength of at least medium. To make it stronger, use upper and lower case letters, numbers and symbols like ! \" ? $ % ^ &amp; ).", empty: "Strength indicator", username: "Password should not match username", mismatch: "Confirm password does not match", "short": "Password is too short", low: "Weak", medium: "Medium", high: "Strongest" } }; var config = $.extend({}, passwordstrength.config); // Options $.extend(true, config, options); // Fetch var $this = $(this); var $container = $this.html(config.content).hide(); // Implode var $result = $container.find(config.contentSelectors.result); var $description = $container.find(config.contentSelectors.description).html(config.il8n.description); if ( !config.il8n.description ) { $description.remove(); } // Prepare var classes = [ config.strengthCss["short"], config.strengthCss.mismatch, config.strengthCss.username, config.strengthCss.low, config.strengthCss.medium, config.strengthCss.high, config.strengthCss.empty ].join(' '); // Fetch var $password = $(config.password), $confirm = $(config.confirm||null), $username = $(config.username||null); // Apply var check = function(){ // Fetch var password = $password.val(), confirm = $confirm.val(), username = $username.val(); // Strength var strength = password ? password.passwordstrength(confirm,username) : "empty"; var strength_css = config.strengthCss[strength]; var strength_text = config.il8n[strength]; // Apply $result.removeClass(classes).addClass(strength_css).html(strength_text); }; $password .keyup(function(){ var $password = $(this); $confirm.val(''); if ( $password.val() !== '' && !$container.data('shown') ) { $container.animate({'height':'show','opacity':'show'},'slow').data('shown',true); } }); $password.add($confirm).add($username).keyup(check); check(); // Chain return $this; } } else { window.console.warn("$.fn.passwordstrength has already been defined..."); } })(jQuery);/** * @depends jquery, core.console * @name jquery.balclass * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} */ /** * jQuery Aliaser */ (function($){ /** * BalClass * @version 1.5.0 * @date August 28, 2010 * @since 1.0.0, June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ if ( !($.BalClass||false) ) { // Constructor $.BalClass = function(extend){ this.construct(extend); }; // Prototype $.extend($.BalClass.prototype, { config: { }, construct: function(){ var Me = this, extend = {}; // Handle if ( typeof arguments[0] === 'object' && typeof arguments[1] === 'object' ) { // config, extend extend = arguments[1]; extend.config = arguments[0]||{}; } else if ( typeof arguments[0] === 'object' ) { // extend extend = arguments[0]; extend.config = extend.config||{}; } else if ( typeof arguments[0] === 'undefined' ) { // No arguments were passed extend = false; } else { window.console.error('BalClass.construct: Invalid Input'); } // Check if ( extend !== false ) { // Configure Me.configure(extend.config); delete extend.config; // Extend $.extend(Me,extend); } // Build if ( typeof Me.built === 'function' ) { return Me.built(); } // Return true return true; }, configure: function(config){ var Me = this; Me.config = Me.config||{}; Me.config = $.extend({},Me.config,config||{}); // we want to clone return Me; }, clone: function(extend){ // Clone a BalClass (Creates a new BalClass type) var Me = this; var clone = function(extend){ this.construct(extend); }; $.extend(clone.prototype, Me.prototype, extend||{}); clone.clone = clone.prototype.clone; clone.create = clone.prototype.create; return clone; }, create: function(Extension){ // Create a BalClass (Creates a new instance of a BalClass) var Me = this; var Obj = new Me(Extension); return Obj; }, addConfig: function(name, config){ var Me = this; if ( typeof config === 'undefined' ) { if ( typeof name === 'object' ) { // Series $.each(name,function(key,value){ Me.applyConfig(key, value); }); } return false; } else if ( typeof config === 'object' ) { // Single Me.applyConfig(name, config); } return Me; }, applyConfig: function(name,config){ var Me = this; Me.config[name] = Me.config[name]||{}; $.extend(true,Me.config[name],config||{}); return Me; }, setConfig: function(name,config){ var Me = this; Me.config[name] = config||{}; return Me; }, hasConfig: function(name){ var Me = this; return typeof Me.config[name] !== 'undefined'; }, getConfig: function(name){ var Me = this; if ( typeof name !== 'string' ) { return this.config; } return this.getConfigWith(name); }, getConfigWith: function(name,config){ var Me = this; if ( typeof name !== 'string' ) { if ( typeof config === 'undefined' ) { config = name; } name = 'default'; } if ( typeof config !== 'object' ) { config = {}; } var result = {}; $.extend(true, result, Me.config[name]||{}, config||{}); return result; }, getConfigWithDefault: function(name,config){ var Me = this; return Me.getConfigWith('default',Me.getConfigWith(name,config)); }, setDefaults: function(config){ var Me = this; return Me.applyConfig('default',config); } }); // Instance $.BalClass.clone = $.BalClass.prototype.clone; $.BalClass.create = $.BalClass.prototype.create; // ^ we alias these as they should be both in prototype and instance // however we do not want to create a full instance yet... } else { window.console.warn("$.BalClass has already been defined..."); } })(jQuery);/** * @depends jquery, core.console, jquery.balclass, bespin * @name jquery.balclass.bespin * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} */ /** * jQuery Aliaser */ (function($){ /** * jQuery Bespin Extender * @version 1.2.1 * @date August 20, 2010 * @since 1.0.0, June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ if ( !($.Bespin||false) ) { $.Bespin = $.BalClass.create({ // Configuration config: { "default": { "content": null, "bespin": { "settings": { "tabstop": 4 } }, "toolbar": { "fullscreen": true } }, "rich": { "bespin": { "syntax": "html" } }, "html": { "bespin": { "syntax": "html" } }, "plain": { "toolbar": false } }, // Functions fn: function(mode, options) { // Prepare var Me = $.Bespin; var config = Me.getConfigWithDefault(mode,options); // Elements var element = this; // Bespin var onBespinLoad = function(){ // Use Bespin Me.useBespin(element, config); }; $(window).bind('onBespinLoad', onBespinLoad); // Events var events = { onBespinLoad: function(){ $(window).trigger('onBespinLoad'); } }; // Check Loaded if ( bespin.bootLoaded ) { // Fire Event setTimeout(function(){ events.onBespinLoad(); },500); } else { // Add Event window.onBespinLoad = events.onBespinLoad; } // ^ we have this check as if bespin has already loaded, then the onBespinLoad will never fire! // Chain return this; }, useBespin: function(element, config) { // Prepare var Me = $.Bespin; // Elements var $element = $(element), $bespin, bespin_id; // Check if ( $element.is('textarea') ) { // Editor is a textarea // So we have to create a div to use as our bespin editor // Update id bespin_id = $element.attr('id')+'-bespin'; // Create div $bespin = $('<div id="'+bespin_id+'"/>').html($element.val()).css({ height: $element.css('height'), width: $element.css('width') }); // Insert div $bespin.insertAfter($element); // Hide textarea $element.hide(); } else { // Editor is likely a div // So we can use that as our bespin editor $bespin = $element; bespin_id = $bespin.attr('id'); } // Use Bespin bespin.useBespin(bespin_id,config.bespin).then( function(env){ // Success Me.postBespin(bespin_id, env, config); }, function(error){ // Error window.console.error("Bespin Launch Failed: " + error); } ); // Chain return this; }, postBespin: function(bespin_id, env, config) { // Prepare var Me = $.Bespin; // Elements var $bespin = $('#'+bespin_id); var $textarea = $bespin.siblings('textarea'); var editor = env.editor; // Ensure overflow is set to hidden // stops bespin from having text outside it's box in rare circumstances $bespin.css('overflow','hidden'); // Wrap our div $bespin.wrap('<div class="bespin-wrap" />'); var $bespin_wrap = $bespin.parent(); // Update Textarea on submit if ( $textarea.length ) { var updateFunction = function(){ var val = editor.value; $textarea.val(val); }; $textarea.parents('form:first').submit(updateFunction); } // Change the value if ( config.content || config.content === '' ) { editor.value = config.content; } // Toolbar if ( config.toolbar||false ) { var $toolbar = $('<div class="bespin-toolbar" />'); $toolbar.insertBefore($bespin); // Fullscreen if (config.toolbar.fullscreen||false ) { var $fullscreen = $('<span class="bespin-toolbar-fullscreen" title="Toggle Fullscreen"></span>'); $fullscreen.appendTo($toolbar); $fullscreen.click(function(){ if ( $bespin_wrap.hasClass('bespin-fullscreen') ) { // Destroy fullscreen $('body').add($bespin_wrap).removeClass('bespin-fullscreen'); } else { // Make fullscreen $('body').add($bespin_wrap).addClass('bespin-fullscreen'); } env.dimensionsChanged(); }); } } // Chain return this; }, built: function(){ // Prepare var Me = this; // Attach $.fn.Bespin = function(mode,options) { // Alias return Me.fn.apply(this,[mode,options]); }; // Return true return true; } }); } else { window.console.warn("$.Bespin has already been defined..."); } })(jQuery);/** * @depends jquery, core.console, jquery.balclass * @name jquery.balclass.datepicker * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} */ /** * jQuery Aliaser */ (function($){ /** * jQuery Date Picker * @version 1.0.1 * @date August 20, 2010 * @since 1.0.0, August 18, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ if ( !($.Datepicker||false) ) { $.Datepicker = $.BalClass.create({ // Configuration config: { 'default': { useHtml5: false } }, // Functions fn: function(mode,options){ // Prepare var Me = $.Datepicker; var config = Me.getConfigWithDefault(mode,options); // Handle return $(this).each(function(){ var $input = $(this); // Prepare if ( $input.hasClass('sparkle-date-has') ) { // Already done return this; } $input.addClass('sparkle-date').addClass('sparkle-date-has'); // HTML5 if ( config.useHtml5 && Modernizr && Modernizr.inputtypes.date && $input.attemptTypeChangeTo('date') ) { // Chain return this; } // Instantiate $input.datepicker(config); // Chain return this; }); }, built: function(){ // Prepare var Me = this; // Attach $.fn.Datepicker = function(mode,options) { // Alias return Me.fn.apply(this,[mode,options]); }; // Return true return true; } }); } else { window.console.warn("$.Datepicker has already been defined..."); } })(jQuery);/** * @depends jquery, core.console, jquery.balclass * @name jquery.balclass.datetimepicker * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} */ /** * jQuery Aliaser */ (function($){ /** * jQuery Date Time Picker * @version 1.3.1 * @date August 20, 2010 * @since 1.0.0, June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ if ( !($.Datetimepicker||false) ) { $.Datetimepicker = $.BalClass.create({ // Configuration config: { 'default': { useHtml5: false, datepickerOptions: { }, timepickerOptions: { } }, '12hr': { timepickerOptions: { timeConvention: 12 } }, '24hr': { timepickerOptions: { timeConvention: 24 } } }, // Functions fn: function(mode,options){ // Prepare var Me = $.Datetimepicker; var config = Me.getConfigWithDefault(mode,options); // Handle return $(this).each(function(){ var $input = $(this); // Prepare if ( $input.hasClass('sparkle-datetime-has') ) { // Already done return this; } $input.addClass('sparkle-datetime').addClass('sparkle-datetime-has'); // HTML5 if ( config.useHtml5 && Modernizr && Modernizr.inputtypes.datetime && $input.attemptTypeChangeTo('datetime') ) { // Chain return this; } // -------------------------- // Defaults var value = $input.val(); var date = new Date(); var datestr = '', timestr = ''; if ( value ) { date.setDatetimestr(value); datestr = date.getDatestr(); timestr = date.getTimestr(); } // -------------------------- // DOM Manipulation // Hide $input.hide(); // Create date part var $date = $('<input type="text" class="sparkle-date"/>'); var $sep = $('<span class="sparkle-datetime-sep"> @ </span>'); var $time = $('<input type="text" class="sparkle-time"/>'); // Append $time.insertAfter($input); $sep.insertAfter($input); $date.insertAfter($input); // Apply $date.val(datestr); $time.val(timestr); // -------------------------- // Bind var updateFunction = function(){ var value = $date.val()+' '+$time.val(); $input.val(value).trigger('change'); }; $date.add($time).change(updateFunction); // Instantiate $date.Datepicker(config.datepickerOptions); $time.Timepicker(config.timepickerOptions); // Chain return $input; }); }, built: function(){ // Prepare var Me = this; // Attach $.fn.datetimepicker = $.fn.Datetimepicker = function(mode,options) { // Alias return Me.fn.apply(this,[mode,options]); }; // Return true return true; } }); } else { window.console.warn("$.Datetimepicker has already been defined..."); } })(jQuery);/** * @depends jquery, core.console, jquery.balclass * @name jquery.balclass.eventcalendar * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} */ /** * jQuery Aliaser */ (function($){ /** * Event Calendar * @version 1.2.1 * @date August 20, 2010 * @since 1.0.0, June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ if ( !($.EventCalendar||false) ) { $.EventCalendar = $.BalClass.create({ // Configuration config: { // Default Mode "default": { // Ajax Variables /** The JSON variable that will be return on the AJAX request which will contain our entries */ ajaxEntriesVariable: 'entries', /** The AJAX url to request for our entries */ ajaxEntriesUrl: '', /** The JSON Object to send via POST to our AJAX request */ ajaxPostData: {}, /** Whether or not to Cache the AJAX data */ ajaxCache: true, // Data Variables /* If you are not using AJAX, you can define your entries here */ calendarEntries: [], // Customisation Variables /** The CSS class which will be assigned to the Event Calendar */ calendarClass: 'hasEventCalendar', /** The CSS class which will be assigned to day when the day contains a entry */ dayEventClass: 'ui-state-active hasEvent', /** The standard options to send to the datepicker */ datepickerOptions: {}, /** Whether or not to disable the datepicker date selection click */ disableClick: true, /** * Whatever events you would like to assign to a $day * You will recieve the arguments: domEvent, day, dayEntries, entries */ domEvents: {} } }, // Functions /** * jQuery Object Function */ fn: function(mode,options){ var EventCalendar = $.EventCalendar; // Group? var $calendar = $(this); if ( $calendar.length > 1 ) { $calendar.each(function(){ $(this).EventCalendar(mode,options); }); return this; } // Prepare var Me = $.EventCalendar; var config = Me.getConfigWithDefault(mode,options); // Initialise var Entries = { /** * Calendar Entries Stored by {entryId:entry} */ entriesById: {}, /** * Calendar Entries Stored by {"year-month":[entry,entry]} */ entriesByYearMonth: {}, /** * Whether or not the "year-month" is cacheable */ cacheableByYearMonth: {}, /** * Get whether or not a "year-month" is cacheable */ isCacheable: function(year,month,value){ return (this.cacheableByYearMonth[year+'-'+month]||false) ? true : false; }, /** * Set whether or not a "year-month" is cacheable */ setCacheable: function(year,month,value){ if ( typeof value === 'undefined' ) value = this.cacheableByYearMonth[year+'-'+month] = value; return this; }, /** * Calendar Entries Undefined */ isYearMonthSet: function(year,month) { return typeof this.entriesByYearMonth[year+'-'+month] !== 'undefined'; }, /** * Calendar Entries Empty */ isYearMonthEmpty: function(year,month) { var notempty = (typeof this.entriesByYearMonth[year+'-'+month] === 'array' && this.entriesByYearMonth[year+'-'+month].length !== 0) || (typeof this.entriesByYearMonth[year+'-'+month] === 'object' && !$.isEmptyObject(this.entriesByYearMonth[year+'-'+month])) ; return !notempty; }, /** * Calendar Entries Getter */ getEntriesByYearMonth: function(year,month) { return this.entriesByYearMonth[year+'-'+month]||[]; }, /** * Calendar Entries Getter */ getEntryById: function(id) { return this.entriesById[id]||undefined; }, /** * Get Days in a Month by passing a date */ getDaysInMonth: function(date){ // http://snippets.dzone.com/posts/show/2099 return 32 - new Date(date.getFullYear(), date.getMonth(), 32).getDate(); }, /** * Get Date */ getDate: function(timestamp){ // Convert var date; if ( typeof timestamp === 'string' ) { date = new Date(timestamp); } else if ( typeof timestamp === 'number' ) { date = new Date(); date.setTime(timestamp); } else if ( typeof timestamp === 'object' ) { date = new Date(); date.setTime(timestamp.getTime()); } else { throw Error("Unknown date format."); } // Fix for Firefox if ( isNaN(date) || date.toString() === "Invalid Date" ) { date = new Date(); date.setDatetimestr(timestamp); } // Return date return date; }, /** * Calendar Entries Setter */ addEntries: function(entries) { // Prepare var Me = this; // Add $.each(entries,function(index,entry){ // Prepare entry.id = entry.id||index; // Add Entry Me.addEntry(entry); }); // Chain return true; }, /** * Calendar Entries Setter */ addEntry: function(entry) { // Prepare entry entry.start = this.getDate(entry.start); entry.finish = this.getDate(entry.finish); // Cycle through years and months var currentDate = this.getDate(entry.start); currentDate.setDate(1); currentDate.setHours(0); currentDate.setMinutes(0); currentDate.setSeconds(0); currentDate.setMilliseconds(0); var finishDate = this.getDate(entry.finish); finishDate.setDate(2); finishDate.setHours(0); finishDate.setMinutes(0); finishDate.setSeconds(0); finishDate.setMilliseconds(0); while ( currentDate < finishDate ) { // Fetch var year = currentDate.getFullYear(), month = currentDate.getMonth()+1; /* // Add entry.span = entry.span||{}; entry.span[year] = entry.span[year]||{}; entry.span[year][month] = entry.span[year][month]||{}; // Cycle through days // Determine span var firstMonth = (year === entry.start.getFullYear() && month === entry.start.getMonth()+1), lastMonth = (year === entry.finish.getFullYear() && month === entry.finish.getMonth()+1), daysInMonth = this.getDaysInMonth(currentDate); // Ifs if ( firstMonth && lastMonth ) { // First + Last // Get days between (inclusive) var startDay = entry.start.getDate(), finishDay = entry.finish.getDate(); else if ( ) { // First // Get days from (inclusive) var startDay = entry.start.getDate(), finishDay = daysInMonth; } else if ( ) { // Last // Get days to (inclusive) var startDay = 1, finishDay = entry.finish.getDate(); } else { // Intermediate // Get all days var startDay = 1, finishDay = daysInMonth; } // Apply for ( var day = startDay; day<=finishDay; ++day ) { entry.span[year][month][day] = true; } */ // Add to Year-Month Indexed if ( typeof this.entriesByYearMonth[year+'-'+month] === 'undefined' ) { this.entriesByYearMonth[year+'-'+month] = {}; } this.entriesByYearMonth[year+'-'+month][entry.id] = entry; // Increment date by one month if ( month === 11 ) { currentDate.setMonth(0); currentDate.setYear(year+1); } else { currentDate.setMonth(month+1); } } // Add to ID Indexed this.entriesById[entry.id] = entry; // Return entry return entry; } }; // Add the passed entries (if any) Entries.addEntries(config.calendarEntries); // Our Extender Event var calendarEntriesRender = function(datepicker, year, month) { // Fetch the Entries var monthEntries = Entries.getEntriesByYearMonth(year,month), $datepicker = $(datepicker); // Reset the Render var $days_tds = $datepicker.find('tbody td'), $days = $days_tds.find('a'); // Disable Click if ( config.disableClick ) { $days_tds.unbind('click').removeAttr('onclick'); $days.removeAttr('href').css('cursor','default'); } // Cycle Through Entries $.each(monthEntries, function(entryIndex,entry){ // Fetch stat and finish days var startMonth = entry.start.getMonth()+1, finishMonth = entry.finish.getMonth()+1, startDay = entry.start.getDate(), finishDay = entry.finish.getDate(); // Determine start and finish days in the rendered calendar var $startDay = startMonth == month ? $days.filter(':contains('+startDay+'):first') : $days.filter(':first'), $finishDay = finishMonth == month ? $days.filter(':contains('+finishDay+'):first') : $days.filter(':last'); // Determine the indexes var start = startMonth == month ? $days.index($startDay) : 0, finish = finishMonth == month ? $days.index($finishDay) : $days.length-1, duration = finish-start+1; // +1 to be inclusive // Betweens var $entryDays = []; if ( start == finish ) { $entryDays = $startDay; } else if ( start == finish-1 ) { $entryDays = $startDay.add($finishDay); } else { $entryDays = $startDay.add($days.filter(':lt('+(finish)+')').filter(':gt('+(start)+')')).add($finishDay); } // Add the Entry to These Days $entryDays.addClass(config.dayEventClass).each(function(dayIndex,dayElement){ // Fetch var $day = $(dayElement), day = $day.text().trim(), dayEntriesIds = $day.data('dayEntriesIds'); // Handle if ( typeof dayEntriesIds === 'undefined' ) { dayEntriesIds = entry.id; } else { dayEntriesIds = String(dayEntriesIds).split(/,/g); dayEntriesIds.push(entry.id); dayEntriesIds = dayEntriesIds.join(','); } // Apply $day.data('dayEntriesIds',dayEntriesIds); // Bind Entries $.each(config.domEvents,function(domEventName,domEventHandler){ $day.unbind(domEventName).bind(domEventName,function(domEvent){ // Prepare var $day = $(this), day = $day.text().trim(), dayEntriesIds = String($day.data('dayEntriesIds')).split(/,/g), date = new Date(); date.setDatestr(year+'-'+month+'-'+day); // Entries var dayEntries = [] $.each(dayEntriesIds,function(i,entryId){ var dayEntry = Entries.getEntryById(entryId); dayEntries.push(dayEntry); }); // Fire domEventHandler.apply(this, [domEvent, { "year":year, "month":month, "day":day, "date":date, "dayEntries":dayEntries, "monthEntries":monthEntries, "datepicker":datepicker }]); // Done return true; }); }); // Done }); }); // Done return true; }; // Change Month Year var calendarChangeMonthYear = function(year, month, inst) { // Prepare var datepicker = inst.dpDiv||inst; // Check if ( typeof config.ajaxEntriesUrl === 'string' && config.ajaxEntriesUrl.length ) { // Ajax Enabled if ( config.ajaxCache && Entries.isCacheable(year,month) && !Entries.isYearMonthEmpty(year,month) ) { // We can use the cache // And we have entries setTimeout(function(){ calendarEntriesRender(datepicker, year, month) },50); } else { // Prepare var data = $.extend({},{ year: year, month: month }, config.ajaxPostData ); // Fetch into the cache $.ajax({ "url": config.ajaxEntriesUrl, "method": 'post', "dataType": 'json', "data": data, success: function(data, status){ // Cycle var entries = data[config.ajaxEntriesVariable]||[]; // Enable caching for this year month Entries.setCacheable(year,month,true) // Check if we have entries if ( entries.length === 0 ) { return true; } // Store the Entries in the Calendar Data Entries.addEntries(entries); // Render the year and month, as we have new data setTimeout(function(){ calendarEntriesRender(datepicker, year, month) },50); // Done return true; }, error: function(XMLHttpRequest, textStatus, errorThrown, response_data){ // Error window.console.warn('$.EventCalendar.calendarChangeMonthYear.ajax.error:', [this, arguments]); } }); } } else if ( !Entries.isYearMonthEmpty(year,month) ) { // We are not using cache // And we have entries setTimeout(function(){ calendarEntriesRender(datepicker, year, month) },50); } // Done return true; }; // Prepare initial render var calendarInitialised = false; var calendarInit = function(year,month,inst){ // Prepare if ( calendarInitialised ) return; calendarInitialised = true; // Apply $(inst).addClass(config.calendarClass); calendarChangeMonthYear(year, month, inst); }; // Calendar Options var datepickerOptions = $.extend({}, config.datepickerOptions, { onChangeMonthYear: function(year, month, inst) { // Our Event calendarChangeMonthYear(year,month,inst); // Users' Event if ( typeof config.datepickerOptions.onChangeMonthYear === 'function' ) { calendarInit(year,month,inst); } }, beforeShow: function(input, inst) { datepickerShowed = true; // Users' Event if ( typeof config.datepickerOptions.beforeShow === 'function' ) { config.datepickerOptions.beforeShow.apply(this,[input,inst]); } // Our Event setTimeout(function(){ calendarInit(inst.drawYear, inst.drawMonth+1, inst); },1000); } }); // Apply Options so we can hook into the events $calendar.datepicker(datepickerOptions); // Fallback in case beforeShow fails us setTimeout(function(){ var date = $calendar.datepicker("getDate"); calendarInit(date.getFullYear(), date.getMonth()+1, $calendar); },2000); // Chain return $calendar; }, built: function(){ // Prepare var Me = this; // Attach $.fn.EventCalendar = function(mode,options) { // Alias return Me.fn.apply(this,[mode,options]); }; // Return true return true; } }); } else { window.console.warn("$.EventCalendar has already been defined..."); } })(jQuery);/** * @depends jquery, core.console, jquery.balclass * @name jquery.balclass.help * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} */ /** * jQuery Aliaser */ (function($){ /** * jQuery Help * @version 1.2.1 * @date August 20, 2010 * @since 1.0.0, June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ if ( !($.Help||false) ) { $.Help = $.BalClass.create({ // Configuration config: { 'default': { // Elements wrap: '<span class="sparkle-help-wrap"/>', icon: '<span class="sparkle-help-icon"/>', text: '<span class="sparkle-help-text"/>', parentClass: '', title: '' } }, // Functions fn: function(options){ var Me = $.Help; if ( typeof options === 'string' ) { options = { title: options }; } var config = Me.getConfigWithDefault('default',options); // Fetch var $this = $(this); var $wrap = $(config.wrap); var $icon = $(config.icon); var $text = $(config.text); var $parent = $this.parent().addClass(config.parentClass); // Build var $contents = $this.contents(); $this.append($wrap.append($text).append($icon)); $contents.appendTo($text); $this.attr('title', config.title); // Done return $this; }, built: function(){ // Prepare var Me = this; // Attach $.fn.help = function(mode,options) { // Alias return Me.fn.apply(this,[mode,options]); }; // Return true return true; } }); } else { window.console.warn("$.Help has already been defined..."); } })(jQuery);/** * @depends jquery, core.console, jquery.balclass * @name jquery.balclass.timepicker * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} */ /** * jQuery Aliaser */ (function($){ /** * jQuery Time Picker * @version 1.3.1 * @date August 20, 2010 * @since 1.0.0, June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ if ( !($.Timepicker||false) ) { /** * $.timepicker */ $.Timepicker = $.BalClass.create({ // Configuration config: { 'default': { useHtml5: false, timeConvention: 12 }, '12hr': { timeConvention: 12 }, '24hr': { timeConvention: 24 } }, // Functions fn: function(mode,options){ // Prepare var Me = $.Timepicker; var config = Me.getConfigWithDefault(mode,options); // Handle return $(this).each(function(){ var $input = $(this); // Prepare if ( $input.hasClass('sparkle-time-has') ) { // Already done return this; } $input.addClass('sparkle-time').addClass('sparkle-time-has'); // HTML5 if ( config.useHtml5 && Modernizr && Modernizr.inputtypes.date && $input.attemptTypeChangeTo('time') ) { // Chain return this; } // -------------------------- // Defaults var value = $input.val(), date = new Date(), timeConvention = config.timeConvention, hours = 12, minutes = 0, meridian = 'am'; // Assign if ( value ) { date.setTimestr(value); hours = date.getUTCHours(); minutes = date.getUTCMinutes(); } // Adjust if ( timeConvention === 12 && hours > 12 ) { meridian = 'pm'; hours -= 12; } minutes = minutes.roundTo(5); // Check if ( timeConvention === 12 ) { if ( hours > 12 || hours < 1 ) { hours = 1; window.console.warn('timepicker.fn: Invalid Hours.', [this,arguments]); } } else { if ( hours > 23 || hours < 0 ) { hours = 1; window.console.warn('timepicker.fn: Invalid Hours.', [this,arguments]); } } if ( minutes > 60 || minutes < 0 ) { minutes = 0; window.console.warn('timepicker.fn: Invalid Minutes.', [this,arguments]); } // -------------------------- // DOM Manipulation // Hide $input.hide(); // Meridian if ( timeConvention === 12 ) { var $meridian = $('<select class="sparkle-time-meridian" />'); $meridian.append('<option>am</option>'); $meridian.append('<option>pm</option>'); $meridian.val(meridian).insertAfter($input); } // Minutes var $minutes = $('<select class="sparkle-time-minutes" />'); for ( var mins=55,min=0; min<=mins; min+=5) { $minutes.append('<option value="'+min+'">'+min.padLeft('0',2)+'</option>'); } $minutes.val(minutes).insertAfter($input); // Hours var $hours = $('<select class="sparkle-time-hours" />'); if ( timeConvention === 12 ) { for ( var hours=timeConvention,hour=1; hour<=hours; ++hour ) { $hours.append('<option value="'+hour+'">'+hour.padLeft('0',2)+'</option>'); } $hours.val(hours-1).insertAfter($input); } else { for ( var hours=timeConvention,hour=0; hour<hours; ++hour ) { $hours.append('<option value="'+hour+'">'+hour.padLeft('0',2)+'</option>'); } $hours.val(hours).insertAfter($input); } // -------------------------- // Bind var updateFunction = function(){ var hours = parseInt($hours.val(),10); var minutes = $minutes.val(); if ( timeConvention === 12 ) { var meridian = $meridian.val(); // PM Adjustment if ( hours !== 12 && meridian === 'pm' ) { hours += 12; } // AM Adjustment if ( hours === 12 && meridian === 'am' ) { hours = 0; } } // Apply var value = hours.padLeft(0,2)+':'+minutes.padLeft(0,2)+':00'; $input.val(value).trigger('change'); }; $hours.add($minutes).add($meridian).change(updateFunction); $input.parent('form:first').submit(updateFunction); // Done return $input; }); }, built: function(){ // Prepare var Me = this; // Attach $.fn.timepicker = $.fn.Timepicker = function(mode,options) { // Alias return Me.fn.apply(this,[mode,options]); }; // Return true return true; } }); } else { window.console.warn("$.Timepicker has already been defined..."); } })(jQuery);/** * @depends jquery, core.console, jquery.balclass, tinymce * @name jquery.balclass.tinymce * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} */ /** * jQuery Aliaser */ (function($){ /** * jQuery TinyMCE Extender * @version 1.2.1 * @date August 20, 2010 * @since 1.0.0, June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ if ( !($.Tinymce||false) ) { $.Tinymce = $.BalClass.create({ // Configuration config: { 'default': { // Location of TinyMCE script script_url: '/scripts/tiny_mce/tiny_mce.js', // General options theme: "advanced", plugins: "autoresize,safari,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template", // Theme options theme_advanced_buttons1: "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,styleselect,formatselect,fontselect,fontsizeselect,|,code,", theme_advanced_buttons2: "cut,copy,paste,pastetext,pasteword,|,undo,redo,|,link,unlink,image,|,preview,|,forecolor,backcolor,|,bullist,numlist,|,outdent,indent,blockquote,|,fullscreen", theme_advanced_buttons3: "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup", theme_advanced_toolbar_location: "top", theme_advanced_toolbar_align: "left", theme_advanced_statusbar_location: "bottom", theme_advanced_path: false, theme_advanced_resizing: false, width: "100%", // Compat //add_form_submit_trigger: false, //submit_patch: false, // Example content CSS (should be your site CSS) // content_css : "css/content.css", // Replace values for the template plugin template_replace_values: { } }, 'rich': { }, 'simple': { theme_advanced_buttons2: "", theme_advanced_buttons3: "" } }, // Functions fn: function(mode,options) { var Me = $.Tinymce; var config = Me.getConfigWithDefault(mode,options); var $this = $(this); // Apply + Return return $this.tinymce(config); }, built: function(){ // Prepare var Me = this; // Attach $.fn.Tinymce = function(mode,options) { // Alias return Me.fn.apply(this,[mode,options]); }; // Return true return true; } }); } else { window.console.warn("$.Tinymce has already been defined..."); } })(jQuery);/** * @depends jquery, core.console, jquery.extra, jquery.balclass * @name jquery.balclass.bespin.sparkle * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} */ /** * jQuery Aliaser */ (function($){ /** * Prepare Body */ $(document.body).addClass('js'); /** * jQuery Sparkle - jQuery's DRY Effect Library * @version 1.5.0 * @date August 28, 2010 * @since 1.0.0, June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ if ( !($.Sparkle||false) ) { /** * $.SparkleClass */ $.SparkleClass = $.BalClass.clone({ /** * Alias for Sparkle.addExtension */ addExtensions: function() { // Prepare var Sparkle = this; // Handle var result = Sparkle.addExtension.apply(Sparkle,arguments); // Fire the Configured Promise Sparkle.onConfigured(true); // Return result return result; }, /** * Add an Extension */ addExtension: function() { // Prepare var Sparkle = this, Extension = {}; // Determine switch ( true ) { case Boolean(arguments[2]||false): // name, config, extension // name, extension, config if ( typeof arguments[0] === 'string' && typeof arguments[2] === 'function' && typeof arguments[1] === 'object' ) { Extension.extension = arguments[2]; Extension.config = arguments[1]; Extension.name = arguments[0]; } if ( typeof arguments[0] === 'string' && typeof arguments[1] === 'function' && typeof arguments[2] === 'object' ) { Extension.extension = arguments[1]; Extension.config = arguments[2]; Extension.name = arguments[0]; } else { window.console.error('Sparkle.addExtension: Invalid Input'); } break; case Boolean(arguments[1]||false): // name, Extension // name, extension if ( typeof arguments[0] === 'string' && typeof arguments[1] === 'function' ) { Extension.extension = arguments[1]; Extension.name = arguments[0]; } else if ( typeof arguments[0] === 'string' && Sparkle.isExtension(arguments[1]) ){ Extension = arguments[1]; Extension.name = arguments[0]; } else { window.console.error('Sparkle.addExtension: Invalid Input'); } break; case Boolean(arguments[0]||false): // Extension // Series if ( Sparkle.isExtension(arguments[0]) ) { Extension = arguments[0]; } else if ( typeof arguments[0] === 'object' || typeof arguments[0] === 'array' ) { // Series $.each(arguments[0],function(key,value){ Sparkle.addExtension(key,value); }); // Chain return this; } else { window.console.error('Sparkle.addExtension: Invalid Input'); } break; } // Ensure Extension.config = Extension.config||{}; Extension.extension = Extension.extension||{}; // Add Extension Sparkle.addConfig(Extension.name, Extension); // Bind Ready Handler Sparkle.onReady(function(){ // Fire Extension Sparkle.triggerExtension($('body'),Extension); }); // Chain return this; }, /** * Do we have that Extension */ hasExtension: function (extension) { // Prepare var Sparkle = this, Extension = Sparkle.getExtension(extension); // Return return Extension !== 'undefined'; }, /** * Is the passed Extension an Extension */ isExtension: function (extension) { // Return return Boolean(extension && (extension.extension||false)); }, /** * Get the Extensions */ getExtensions: function ( ) { // Prepare var Sparkle = this, Config = Sparkle.getConfig(), Extensions = {}; // Handle $.each(Config,function(key,value){ if ( Sparkle.isExtension(value) ) { Extensions[key] = value; } }); // Return Extensions return Extensions; }, /** * Get an Extension */ getExtension: function(extension) { // Prepare var Sparkle = this, Extension = undefined; // HAndle if ( Sparkle.isExtension(extension) ) { Extension = extension; } else { var fetched = Sparkle.getConfigWithDefault(extension); if ( Sparkle.isExtension(fetched) ) { Extension = fetched; } } // Return Extension return Extension; }, /** * Get Config from an Extension */ getExtensionConfig: function(extension) { // Prepare var Sparkle = this Extension = Sparkle.getExtension(extension); // Return return Extension.config||{}; }, /** * Apply Config to an Extension */ applyExtensionConfig: function(extension, config) { // Prepare var Sparkle = this; // Handle Sparkle.applyConfig(extension, {'config':config}); // Chain return this; }, /** * Trigger all the Extensions */ triggerExtensions: function(element){ // Prepare var Sparkle = this, Extensions = Sparkle.getExtensions(); // Handle $.each(Extensions,function(extension,Extension){ Sparkle.triggerExtension(element,Extension); }); // Chain return this; }, /** * Trigger Extension */ triggerExtension: function(element,extension){ // Prepare var Sparkle = this, Extension = Sparkle.getExtension(extension), element = element instanceof jQuery ? element : $('body'); // Handle if ( Extension ) { return Extension.extension.apply(element, [Sparkle, Extension.config, Extension]); } else { window.console.error('Sparkle.triggerExtension: Could not find the extension.', [this,arguments], [extension,Extension]); } // Chain return this; }, /** * Sparkle jQuery Function */ fn: function(Sparkle,extension){ // Prepare var $el = $(this); // HAndle if ( extension ) { // Individual Sparkle.triggerExtension.apply(Sparkle, [$el,extension]); } else { // Series Sparkle.triggerExtensions.apply(Sparkle, [$el]); } // Chain return this; }, /** * Sparkle Constructor */ built: function(){ // Prepare var Sparkle = this; // -------------------------- // Attach $.fn.sparkle = function(extension) { // Alias return Sparkle.fn.apply(this,[Sparkle,extension]); }; // -------------------------- // Setup Promises // Bind DomReady Handler $(function(){ // Fire DocumentReady Promise Sparkle.onDocumentReady(true); }); // Bind Configured Handler Sparkle.onConfigured(function(){ // Bind DocumentReady Handler Sparkle.onDocumentReady(function(){ // Fire Ready Promise Sparkle.onReady(true); }); }); // -------------------------- // Return true return true; }, /** * Handle the Configured Promise * We use promise as the function will fire if the event was already fired as it is still true * @param {mixed} arguments */ onConfigured: function(){ var Sparkle = this; // Handle Promise return $.promise({ 'object': Sparkle, 'handlers': 'onConfiguredHandlers', 'flag': 'isConfigured', 'arguments': arguments }); }, /** * Handle the DocumentReady Promise * We use promise as the function will fire if the event was already fired as it is still true * @param {mixed} arguments */ onDocumentReady: function(handler){ // Prepare var Sparkle = this; // Handle Promise return $.promise({ 'object': Sparkle, 'handlers': 'onDocumentReadyHandlers', 'flag': 'isDocumentReady', 'arguments': arguments }); }, /** * Handle the Ready Promise * We use promise as the function will fire if the event was already fired as it is still true * @param {mixed} arguments */ onReady: function(handler){ // Prepare var Sparkle = this; // Handle Promise return $.promise({ 'object': Sparkle, 'handlers': 'onReadyHandlers', 'flag': 'isReady', 'arguments': arguments }); } }); /** * $.Sparkle */ $.Sparkle = $.SparkleClass.create().addExtensions({ 'date': { config: { selector: '.sparkle-date', datepickerOptions: { }, demoText: 'Date format must use the international standard: [year-month-day]. This due to other formats being ambigious eg. day/month/year or month/day/year.', demo: '<input type="text" class="sparkle-date" value="2010-08-05" />' }, extension: function(Sparkle, config){ var $this = $(this); // Fetch var $elements = $this.findAndSelf(config.selector); if ( !$elements.length ) { return true; } // Check if ( typeof $elements.Datepicker === 'undefined' ) { window.console.warn('Datepicker not loaded. Did you forget to include it?'); return false; } // Apply $elements.Datepicker(config.datepickerOptions); // Done return true; } }, 'time': { config: { selector: '.sparkle-time', timepickerOptions: { }, demoText: 'Time format must be either [hour:minute:second] or [hour:minute], with hours being between 0-23.', demo: '<input type="text" class="sparkle-time" value="23:11" />' }, extension: function(Sparkle, config){ var $this = $(this); // Fetch var $elements = $this.findAndSelf(config.selector); if ( !$elements.length ) { return true; } // Check if ( typeof $elements.Timepicker === 'undefined' ) { window.console.warn('Timepicker not loaded. Did you forget to include it?'); return false; } // Apply $elements.Timepicker(config.timepickerOptions); // Done return true; } }, 'datetime': { config: { selector: '.sparkle-datetime', datepickerOptions: { }, timepickerOptions: { }, demoText: 'Date format must use the international standard: [year-month-day]. This due to other formats being ambigious eg. day/month/year or month/day/year.<br/>\ Time format must be either [hour:minute:second] or [hour:minute], with hours being between 0-23.', demo: '<input type="text" class="sparkle-datetime" value="2010-08-05 23:10:09" />' }, extension: function(Sparkle, config){ var $this = $(this); // Fetch var $elements = $this.findAndSelf(config.selector); if ( !$elements.length ) { return true; } // Check if ( typeof $elements.Datetimepicker === 'undefined' ) { window.console.warn('Datetimepicker not loaded. Did you forget to include it?'); return false; } // Apply $elements.Datetimepicker({ datepickerOptions: Sparkle.getExtensionConfig('date').datepickerOptions, timepickerOptions: Sparkle.getExtensionConfig('time').timepickerOptions }); // Done return true; } }, 'hide-if-empty': { config: { selector: '.sparkle-hide-if-empty:empty', demo: '<div class="sparkle-hide-if-empty" style="border:1px solid black"></div>'+"\n"+ '<div class="sparkle-hide-if-empty" style="border:1px solid black">Hello World</div>' }, extension: function(Sparkle, config) { var $this = $(this); // Fetch var $elements = $this.findAndSelf(config.selector); if ( !$elements.length ) { return true; } // Apply $elements.hide(); // Done return true; } }, 'hide': { config: { selector: '.sparkle-hide', demo: '<div class="sparkle-hide">Something to Hide when Sparkle has Loaded</div>' }, extension: function(Sparkle, config) { var $this = $(this); // Fetch var $elements = $this.findAndSelf(config.selector); if ( !$elements.length ) { return true; } // Apply $elements.removeClass(config.selector.replace('.','')).hide(); // Done return true; } }, 'show': { config: { selector: '.sparkle-show', demo: '<div class="sparkle-show" style="display:none;">Something to Show when Sparkle has Loaded</div>' }, extension: function(Sparkle, config) { var $this = $(this); // Fetch var $elements = $this.findAndSelf(config.selector); if ( !$elements.length ) { return true; } // Apply $elements.removeClass(config.selector.replace('.','')).show(); // Done return true; } }, 'subtle': { config: { selector: '.sparkle-subtle', css: { }, inSpeed: 200, inCss: { 'opacity': 1 }, outSpeed: 400, outCss: { 'opacity': 0.5 }, demo: '<div class="sparkle-subtle">This is some subtle text. (mouseover)</div>' }, extension: function(Sparkle, config) { var $this = $(this); // Fetch var $elements = $this.findAndSelf(config.selector); if ( !$elements.length ) { return true; } // Apply var css = {}; $.extend(css, config.outCss, config.css); $elements.css(css).opacityFix().hover(function() { // Over $(this).stop(true, false).animate(config.inCss, config.inSpeed); }, function() { // Out $(this).stop(true, false).animate(config.outCss, config.outSpeed); }); // Done return true; } }, 'panelshower': { config: { selectorSwitch: '.sparkle-panelshower-switch', selectorPanel: '.sparkle-panelshower-panel', inSpeed: 200, outSpeed: 200, demo: '' }, extension: function(Sparkle, config) { var $this = $(this); // Fetch var $switches = $this.findAndSelf(config.selectorSwitch); var $panels = $this.findAndSelf(config.selectorPanel); if ( !$switches.length && !$panels.length ) { return true; } // Events var events = { clickEvent: function(event) { var $switch = $(this); var $panel = $switch.siblings(config.selectorPanel).filter(':first'); var value = $switch.val(); var show = $switch.is(':checked,:selected') && !(!value || value === 0 || value === '0' || value === 'false' || value === false || value === 'no' || value === 'off'); if (show) { $panel.fadeIn(config.inSpeed); } else { $panel.fadeOut(config.outSpeed); } } }; // Apply $switches.once('click',events.clickEvent); $panels.hide(); // Done return true; } }, 'autogrow': { config: { selector: 'textarea.autogrow,textarea.autosize', demo: '<textarea class="autogrow">This textarea will autogrow with your input. - Only if jQuery Autogrow has been loaded.</textarea>' }, extension: function(Sparkle, config){ var $this = $(this); // Fetch var $elements = $this.findAndSelf(config.selector); if ( !$elements.length ) { return true; } // Check if (typeof $.fn.autogrow === 'undefined') { window.console.warn('autogrow not loaded. Did you forget to include it?'); return false; } // Apply $elements.autogrow(); // Done return true; } }, 'gsfnwidget': { config: { selector: '.gsfnwidget', demo: '<a class="gsfnwidget" href="#">This link will show a GetSatisfaction Widget onclick. - Only if GetSatisfaction has been loaded.</a>' }, extension: function(Sparkle, config) { var $this = $(this); // Events var events = { clickEvent: function(event) { if ( typeof GSFN_feedback_widget === 'undefined' ) { window.console.warn('GSFN not loaded. Did you forget to include it?'); return true; // continue with click event } GSFN_feedback_widget.show(); //event.stopPropagation(); event.preventDefault(); return false; } }; // Fetch var $elements = $this.findAndSelf(config.selector); if ( !$elements.length ) { return true; } // Apply $elements.once('click',events.clickEvent); // Done return true; } }, 'hint': { config: { selector: '.form-input-tip,.sparkle-hint,.sparkle-hint-has,:text[placeholder]', hasClass: 'sparkle-hint-has', hintedClass: 'sparkle-hint-hinted', demoText: 'Simulates HTML5\'s <code>placeholder</code> attribute for non HTML5 browsers. Placeholder can be the <code>title</code> or <code>placeholder</code> attribute. Placeholder will not be sent with the form (unlike most other solutions). The <code>sparkle-hint</code> class is optional if you are using the <code>placeholder</code> attribute.', demo: '<input type="text" class="sparkle-hint" placeholder="This is some hint text." title="This is a title." /><br/>'+"\n"+ '<input type="text" class="sparkle-hint" title="This is some hint text." />' }, extension: function(Sparkle, config) { var $this = $(this); // Fetch var $inputs = $this.findAndSelf(config.selector).addClass(config.hasClass); if ( !$inputs.length ) { return true; } // Events var events = { focusEvent: function(){ var $input = $(this); var tip = $input.attr('placeholder')||$input.attr('title'); var val = $input.val(); // Handle if (tip === val) { $input.val('').removeClass(config.hintedClass); } // Done return true; }, blurEvent: function(){ var $input = $(this); var tip = $input.attr('placeholder')||$input.attr('title'); var val = $input.val(); // Handle if (tip === val || !val) { $input.val('').addClass(config.hintedClass).val(tip); } // Done return true; }, submitEvent: function(){ $inputs.trigger('focus'); } }; // Apply if ( typeof Modernizr !== 'undefined' && Modernizr.input.placeholder ) { // We Support HTML5 Hinting $inputs.each(function(){ var $input = $(this); // Set the placeholder as the title if the placeholder does not exist // We could use a filter selector, however we believe this should be faster - not benchmarked though var title = $input.attr('title'); if ( title && !$input.attr('placeholder') ) { $input.attr('placeholder',title); } }); } else { // We Support Javascript Hinting $inputs.each(function(){ var $input = $(this); $input.once('focus',events.focusEvent).once('blur',events.blurEvent).trigger('blur'); }); $this.find('form').once('submit',events.submitEvent); } // Done return $this; } }, 'debug': { config: { selector: '.sparkle-debug', hasClass: 'sparkle-debug-has', hintedClass: 'sparkle-debug-hinted', showVar: 'sparkle-debug-show', demo: '' }, extension: function(Sparkle, config) { var $this = $(this); // Fetch var $debug = $this.findAndSelf(config.selector); if ( !$debug.length ) { return true; } // Apply $debug.addClass(config.hasClass).find('.value:has(.var)').hide().siblings('.name,.type').addClass('link').once('singleclick',events.clickEvent).once('dblclick',events.dblclickEvent); // Events var events = { clickEvent: function(event){ var $this = $(this); var $parent = $this.parent(); var show = !$parent.data(config.showVar); $parent.data(config.showVar, show); $this.siblings('.value').toggle(show); }, dblclickEvent: function(event){ var $this = $(this); var $parent = $this.parent(); var show = $parent.data(config.showVar); // first click will set this off $parent.data(config.showVar, show); $parent.find('.value').toggle(show); } }; // Done return $this; } }, 'submit': { config: { selector: '.sparkle-submit', demoText: 'Adding the <code>sparkle-submit</code> class to an element within a <code>form</code> will submit the form when that element is clicked.' }, extension: function(Sparkle, config) { var $this = $(this); // Fetch var $submit = $this.findAndSelf(config.selector); if ( !$submit.length ) { return true; } // Events var events = { clickEvent: function(event){ var $this = $(this).submitForm(); return true; } }; // Apply $submit.once('singleclick',events.clickEvent); // Done return $this; } }, 'submitswap': { config: { selector: '.sparkle-submitswap', demoText: 'Adding the <code>sparkle-submitswap</code> class to a submit button, will swap it\'s value with it\'s title when it has been clicked. Making it possible for a submit value which isn\'t the submit button\'s text.' }, extension: function(Sparkle, config) { var $this = $(this); // Fetch var $submit = $this.findAndSelf(config.selector); if ( !$submit.length ) { return true; } // Events var events = { clickEvent: function(event){ // Fetch var $submit = $(this); // Put correct value back $submit.val($submit.data('sparkle-submitswap-value')); // Continue with Form Submission return true; } }; // Apply $submit.once('singleclick',events.clickEvent); $submit.each(function(){ var $submit = $(this); $submit.data('sparkle-submitswap-value', $submit.val()); $submit.val($submit.attr('title')); $submit.removeAttr('title'); }); // Done return $this; } }, 'highlight-values': { config: { selector: '.sparkle-highlight-values', innerSelector: 'td,.column', empty: ['',false,null,'false','null',0,'-'], emptyClass: 'sparkle-highlight-values-empty', notemptyClass: 'sparkle-highlight-values-notempty', demoText: 'Adding the <code>sparkle-highlight-values</code> class to a table will highlight all <code>td</code> elements with non empty values. By adding <code>sparkle-highlight-values-notempty</code> or <code>sparkle-highlight-values-empty</code> to the corresponding <code>td</code> element - which can by styled by yourself. Benefit over css\'s <code>:empty</code> as 0, false, null and - are counted as empty values (not just "").' }, extension: function(Sparkle, config) { var $this = $(this); // Fetch var $container = $this.findAndSelf(config.selector); if ( !$container.length ) { return true; } // Apply var $inner = $container.findAndSelf(config.innerSelector); $inner.each(function(){ var $this = $(this); var value = $this.text().trim(); var empty = config.empty.has(value); if ( empty ) { $this.addClass(config.emptyClass); } else { $this.addClass(config.notemptyClass); } }); // Done return $this; } }, 'demo': { config: { selector: '.sparkle-demo', hasClass: 'sparkle-debug-has', demoText: 'Adding the <code>sparkle-demo</code> will display all these demo examples used on this page.' }, extension: function(Sparkle, config){ var $this = $(this); var $container = $this.findAndSelf(config.selector); // Prepare if ( $container.hasClass(config.hasClass) || !$container.length ) { // Only run once return true; } $container.addClass(config.hasClass); // Fetch var Extensions = Sparkle.getExtensions(); // Cycle $.each(Extensions,function(extension,Extension){ var demo = Extension.config.demo||''; var demoText = Extension.config.demoText||''; if ( !demo && !demoText ) { return true; // continue } var $demo = $( '<div class="sparkle-demo-section" id="sparkle-demo-'+extension+'">\ <h3>'+extension+'</h3>\ </div>' ); if ( demoText ) { $demo.append('<div class="sparkle-demo-text">'+demoText+'</div>'); } if ( demo ) { var demoCode = demo.replace(/</g,'&lt;').replace(/>/g,'&gt;'); $demo.append( '<h4>Example Code:</h4>\ <pre class="code language-html sparkle-demo-code">'+demoCode+'</pre>\ <h4>Example Result:</h4>\ <div class="sparkle-demo-result">'+demo+'</div>' ); } $demo.appendTo($container); }); // Sparkle $container.sparkle(); // Done return $this; } } }); } else { window.console.warn('$.Sparkle has already been defined...'); } })(jQuery);
balupton/jquery-sparkle
scripts/jquery.sparkle.js
JavaScript
mit
134,797
/* globals document, ajaxurl, tinymce, window */ define([ 'jquery', 'modal', 'jquery-ui.sortable' ], function ($, modal) { return function(areas, callback) { var $areas = $(areas).filter(':not(.initialized)'); $areas.addClass('initialized'); var updateData = function() { if(typeof tinymce !== 'undefined' && tinymce.get('content')) { //use WordPress native beforeunload warning if content is modified tinymce.get('content').isNotDirty = false; } var data = {}; $areas.each(function () { var col = []; $(this).find('> ul, > div > ul').find('> li[data-widget]:not(.removed)').each(function () { col.push({ "widgetId": $(this).data('widget'), "instance": $(this).data('instance') }); }); data[$(this).data('id')] = col; }); callback(data); }; $areas.find('> ul, > div > ul').sortable({ connectWith: $areas.find('> ul, > div > ul'), placeholder: "neochic-woodlets-placeholder", delay: 250, update: updateData, receive: function (e, ui) { var $area = $(this).closest('.woodlets-content-area'); var widgetId = ui.item.data('widget'); var allowed = $area.data('allowed'); if ($.inArray(widgetId, allowed) < 0) { ui.sender.sortable("cancel"); } } }); $areas.on('click', '.add-element', function (e) { var $button = $(this); if ($button.hasClass('blocked')) { return; } $button.addClass('blocked'); e.preventDefault(); var $area = $(this).closest('.woodlets-content-area'); $.ajax({ method: "post", url: ajaxurl, data: { action: "neochic_woodlets_get_widget_list", allowed: $area.data('allowed') } }).done(function (data) { var $content = $(data); var selectWidget = function($widget, preventClose) { var widget = $widget.closest('.widget').data('widget'); $button.removeClass('blocked'); $.ajax({ method: "post", url: ajaxurl, data: { "action": "neochic_woodlets_get_widget_preview", "widget": widget, "instance": null } }).done(function (result) { var item = $(result); $area.find('> ul, > div > ul').append(item); updateData(); if (!preventClose) { modal.close(); } item.trigger('click'); }); }; var $widgets = $content.find('.widget-top'); if ($widgets.length === 1) { selectWidget($widgets, true); return; } $content.on('click', '.widget-top', function () { selectWidget($(this)); }); $content.on('click', '.cancel', function() { modal.close(); }); modal.open($content, 'Add item'); }); }); $areas.on('click', '.delete', function () { var removed = $(this).closest('.neochic-woodlets-widget'); removed.addClass('removed'); updateData(); }); $areas.on('click', '.revert-removal a', function() { var reverted = $(this).closest('.neochic-woodlets-widget'); //we wan't the click event to bubble first window.setTimeout(function() { reverted.removeClass('removed'); updateData(); }, 4); }); $areas.on('click', '> ul > li.neochic-woodlets-widget, > div > ul > li.neochic-woodlets-widget', function (e) { var el = $(this); if (el.hasClass('blocked') || el.hasClass('removed')) { return; } el.addClass('blocked'); /* * stop propagation to prevent widget getting collapsed by WordPress */ e.stopPropagation(); /* * do not open widget form if an action (like "delete") is clicked */ if (!$(e.target).is('.edit') && $(e.target).closest('.row-actions').length > 0) { return; } var widget = $(this).data('widget'); //this should be done more elegant! var name = $(this).find(".widget-title h4").text(); var data = { action: "neochic_woodlets_get_widget_form", widget: widget, instance: JSON.stringify(el.data('instance')) }; var pageIdEle = $("#post_ID"); if (pageIdEle.length) { data.woodletsPageId = pageIdEle.val(); } $.ajax({ method: "post", url: ajaxurl, data: data }).done(function (data) { var form = $('<form>' + data + '<span class="button cancel">Cancel</span> <button type="submit" class="button button-primary">Save</button></form>'); form.on('submit', function (e) { $(document).trigger('neochic-woodlets-form-end', form); $.ajax({ method: "post", url: ajaxurl, data: $(this).serialize() + '&widget=' + widget + '&action=neochic_woodlets_get_widget_update' + (pageIdEle.length ? '&woodletsPageId=' + pageIdEle.val() : "") }).done(function (result) { var instance = $.parseJSON(result); el.data('instance', instance); var previewData = { "action": "neochic_woodlets_get_widget_preview", "widget": widget, "instance": JSON.stringify(instance) }; if (pageIdEle.length) { previewData.woodletsPageId = pageIdEle.val(); } $.ajax({ method: "post", url: ajaxurl, data: previewData }).done(function (result) { el.replaceWith($(result)); }); modal.close(); updateData(); }); e.preventDefault(); }); form.on('click', '.cancel', function() { modal.close(); }); modal.open(form, name); $(document).trigger('neochic-woodlets-form-init', form); el.removeClass('blocked'); }); }); }; });
Neochic/Woodlets
js/content-area-manager.js
JavaScript
mit
7,553
Factory.define :content_element_text do |p| p.content_element { |c| c.association(:content_element, :element_type => "ContentElementText") } end
dkd/palani
spec/factories/content_element_text_factory.rb
Ruby
mit
146
$(document).ready(function() { var $sandbox = $('#sandbox'); module('typographer_punctuation', { teardown: function() { teardownSandbox($sandbox); } }); var bdquo = '\u201E'; // &bdquo; var rdquo = '\u201D'; // &rdquo; var laquo = '\u00AB'; // &laquo; var raquo = '\u00BB'; // &raquo; var nbsp = '\u00A0'; // &nbsp; var ellip = '\u2026'; // &hellip; var apos = '\u2019'; // &rsquo; var ndash = '\u2013'; // '&ndash; półpauza var mdash = '\u2014'; // '&ndash; pauza test('Initialization', function() { $sandbox.typographer_punctuation(); ok($.fn.typographer_punctuation.defaults, '$.fn.typographer_punctuation.defaults present'); ok($sandbox.hasClass($.fn.typographer_punctuation.defaults.contextClass), 'Context has valid class'); }); test('Quotes correction', function() { var testSpec = [ { init: 'Lorem "ipsum" dolor sit amet.', expected: 'Lorem \u201Eipsum\u201D dolor sit amet.' }, { init: 'Oto "źdźbło" trawy.', expected: 'Oto \u201Eźdźbło\u201D trawy.' }, { init: 'kolegom, że "...moja to trzyma buty".', expected: 'kolegom, że \u201E...moja to trzyma buty\u201D.' }, { init: 'Taką "długą grę" lubię.', expected: 'Taką \u201Edługą grę\u201D lubię.' }, { init: '"jakimi butami jesteś", mój wynik ', expected: '\u201Ejakimi butami jesteś\u201D, mój wynik ' }, { init: 'Lorem "ipsum »dolor« sit" amet.', expected: 'Lorem \u201Eipsum \u00ABdolor\u00BB sit\u201D amet.' } ]; $.each(testSpec, function(i, data) { $sandbox.get(0).innerHTML = data.init; $sandbox.typographer_punctuation({'correction': ['quotes']}); equal($sandbox.get(0).innerHTML, data.expected, data.init); teardownSandbox($sandbox); }); }); test('Ellipsis correction', function() { var testSpec = [ { init: 'Dawno, dawno temu...', expected: 'Dawno, dawno temu' + ellip }, { init: 'Wprost do... domu.', expected: 'Wprost do' + ellip + ' domu.' } ]; $.each(testSpec, function(i, data) { $sandbox.get(0).innerHTML = data.init; $sandbox.typographer_punctuation({'correction': ['ellipsis']}); equal($sandbox.get(0).innerHTML, data.expected, data.init); teardownSandbox($sandbox); }); }); test('Apostrophe correction', function() { var testSpec = [ { init: 'Alfabet Morse\'a', expected: 'Alfabet Morse' + apos + 'a' }, { init: 'prawo Murphy\'ego', expected: 'prawo Murphy' + apos + 'ego' } ]; $.each(testSpec, function(i, data) { $sandbox.get(0).innerHTML = data.init; $sandbox.typographer_punctuation({'correction': ['apostrophe']}); equal($sandbox.get(0).innerHTML, data.expected, data.init); teardownSandbox($sandbox); }); }); test('Dash correction', function() { var testSpec = [ { init: 'A to jest - rzecz oczywista - najlepsze wyjście.', expected: 'A to jest ' + ndash + ' rzecz oczywista ' + ndash + ' najlepsze wyjście.' }, { init: 'Wiedza - to potęga.', expected: 'Wiedza ' + ndash + ' to potęga.' }, { init: 'Działalność PAN-u', expected: 'Działalność PAN-u' }, { init: 'Działalność PAN' + ndash + 'u', expected: 'Działalność PAN-u' }, { init: 'Elżbieta Nowak-Kowalska', expected: 'Elżbieta Nowak-Kowalska' }, { init: 'W latach 1999-2001', expected: 'W latach 1999' + ndash + '2001' }, { init: 'W latach 1999 - 2001', expected: 'W latach 1999' + ndash + '2001' }, { init: 'W latach 1999 ' + ndash + ' 2001', expected: 'W latach 1999' + ndash + '2001' } ]; $.each(testSpec, function(i, data) { $sandbox.get(0).innerHTML = data.init; $sandbox.typographer_punctuation({'dash': ['dash']}); equal($sandbox.get(0).innerHTML, data.expected, data.init); teardownSandbox($sandbox); }); }); });
mir3z/jquery.typographer
test/jquery.typographer.punctuation.test.js
JavaScript
mit
4,996
<?php include('head.php'); global $TPL; ?> <div class="page-header"> <h1>Dateiliste</h1> </div> <?php if($_SESSION['login_msg']) { $_SESSION['login_msg']=false; ?> <div class="alert alert-info"> <button type="button" class="close" data-dismiss="alert">&times;</button> <h4>Erfolgreich eingeloggt.</h4> Willkommen <?php echo $_SESSION['whoami']; ?> </div> <?php } ?> <p>Folgende Dateien wurden gefunden:</p> <?php include('foot.php'); ?> <script type="text/javascript"> var filelist = <?php echo json_encode($TPL['files']) . ';'; ?> </script> <script src="tpl/default/js/filelist.js"></script>
jnugh/php-miniupload
tpl/default/list.php
PHP
mit
603
module.exports = { general: { lenguage (){ temp['locale'] = event.target.value }, close (){ temp['exit_without_ask'] = event.target.checked }, minimize (){ temp['exit_forced'] = event.target.checked }, hide (){ temp['start_hide'] = event.target.checked }, delete (){ temp['ask_on_delete'] = event.target.checked }, theme (){ temp['theme'] = event.target.value } }, network: { conections (){ temp['conections_max'] = event.target.value }, directory (){ temp['dir_downloads'] = event.target.value }, announces (){ temp['announces'] = event.target.value } }, advance: { table (){ temp_interval['table'] = event.target.value }, tray (){ temp_interval['tray'] = event.target.value }, footer (){ temp_interval['footer'] = event.target.value }, reset() { dialog.showMessageBox({ type: "question", title: locale.dialog.reset.title, message: locale.dialog.reset.ask, defaultId: 0, cancelId: 0, buttons: [locale.cancel, locale.dialog.reset.accept] }, select => { if(select === 0) return false gui.send('reset-settings') $('#modal_configs').modal('hide') }) } }, gui: { open() { temp = [] temp_interval = [] modal = $('#modal_configs') modal.modal('toggle') configs.gui.set(modal); }, save() { for (config in temp) settings[config] = temp[config] for (config in temp_interval) settings.interval[config] = temp_interval[config] ipcRenderer.send('save-settings', settings) }, set(modal) { let checkboxs = ['exit_without_ask', 'start_hide', 'exit_forced', 'ask_on_delete'] for (var i = checkboxs.length - 1; i >= 0; i--) { modal.find('#opt-'+checkboxs[i]).prop("checked", settings[checkboxs[i]]) } let textboxs = ['announces', 'conections_max', 'dir_downloads'] for (var i = textboxs.length - 1; i >= 0; i--) { modal.find('#opt-'+textboxs[i]).val(settings[textboxs[i]]) } let intervals = ["table", "tray", "footer"] for (var i = intervals.length - 1; i >= 0; i--) { modal.find('#opt-interval_'+intervals[i]).val(settings.interval[intervals[i]]) } modal.find('#opt-locale-'+ settings.locale).prop("selected", true) } } }
FaCuZ/torrentmedia
app/js/configs.js
JavaScript
mit
2,228
/* This file has been generated by yabbler.js */ require.define({ "program": function(require, exports, module) { var test = require('test'); var a = require('submodule/a'); var b = require('submodule/b'); test.assert(a.foo == b.foo, 'a and b share foo through a relative require'); test.print('DONE', 'info'); }}, ["test", "submodule/a", "submodule/b"]);
jbrantly/yabble
test/modules1.0/wrappedTests/relative/program.js
JavaScript
mit
356
(function() { 'use strict'; angular .module('material') .controller('MainController', MainController); /** @ngInject */ function MainController($timeout, webDevTec, toastr) { var vm = this; vm.awesomeThings = []; vm.classAnimation = ''; vm.creationDate = 1437577753474; vm.showToastr = showToastr; activate(); function activate() { getWebDevTec(); $timeout(function() { vm.classAnimation = 'rubberBand'; }, 4000); } function showToastr() { toastr.info('Fork <a href="https://github.com/Swiip/generator-gulp-angular" target="_blank"><b>generator-gulp-angular</b></a>'); vm.classAnimation = ''; } function getWebDevTec() { vm.awesomeThings = webDevTec.getTec(); angular.forEach(vm.awesomeThings, function(awesomeThing) { awesomeThing.rank = Math.random(); }); } } })();
LuukMoret/gulp-angular-examples
es5/material/src/app/main/main.controller.js
JavaScript
mit
906
package io.github.intrainos.samsungltool; import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.content.Intent; import android.view.View; import android.widget.Button; public class Main extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button gotoAppops = (Button) findViewById(R.id.gotoAppops); gotoAppops.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Intent AppopsIntent = new Intent(); AppopsIntent.setClassName("com.android.settings", "com.android.settings.Settings"); AppopsIntent.setAction("android.intent.action.MAIN"); AppopsIntent.addCategory("android.intent.category.DEFAULT"); AppopsIntent.setFlags(268468224); AppopsIntent.putExtra(":android:show_fragment", "com.android.settings.applications.AppOpsSummary"); startActivity(AppopsIntent); } }); Button TouchLightSetting = (Button) findViewById(R.id.gotoTouchlightSetting); TouchLightSetting.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Intent TouchLightSetting = new Intent(getApplicationContext(), TouchLight.class); startActivity(TouchLightSetting); } }); Button gotoSViewWPSetting = (Button) findViewById(R.id.gotoSViewWPSetting); gotoSViewWPSetting.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Intent gotoSViewWPSetting = new Intent(); gotoSViewWPSetting.setClassName("com.android.settings", "com.android.settings.SViewColor2014"); gotoSViewWPSetting.setAction("android.intent.action.MAIN"); gotoSViewWPSetting.addCategory("android.intent.category.DEFAULT"); gotoSViewWPSetting.setFlags(268468224); startActivity(gotoSViewWPSetting); } }); Button gotoToolBoxSetting = (Button) findViewById(R.id.gotoToolBoxSetting); gotoToolBoxSetting.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Intent gotoToolBoxSetting = new Intent(); gotoToolBoxSetting.setClassName("com.android.settings", "com.android.settings.Settings$ToolboxMenuActivity"); gotoToolBoxSetting.setAction("android.intent.action.MAIN"); gotoToolBoxSetting.addCategory("android.intent.category.DEFAULT"); gotoToolBoxSetting.setFlags(268468224); startActivity(gotoToolBoxSetting); } }); Button gotoToolBoxList = (Button) findViewById(R.id.gotoToolBoxList); gotoToolBoxList.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Intent gotoToolBoxList = new Intent(); gotoToolBoxList.setClassName("com.android.settings", "com.android.settings.Settings$ToolboxListActivity"); gotoToolBoxList.setAction("android.intent.action.MAIN"); gotoToolBoxList.addCategory("android.intent.category.DEFAULT"); gotoToolBoxList.setFlags(268468224); startActivity(gotoToolBoxList); } }); Button gotoDownloadBoosterSetting = (Button) findViewById(R.id.gotoDownloadBoosterSetting); gotoDownloadBoosterSetting.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Intent gotoDownloadBoosterSetting = new Intent(); gotoDownloadBoosterSetting.setClassName("com.android.settings", "com.android.settings.Settings$SmartBondingSettingsActivity"); gotoDownloadBoosterSetting.setAction("android.intent.action.MAIN"); gotoDownloadBoosterSetting.addCategory("android.intent.category.DEFAULT"); gotoDownloadBoosterSetting.setFlags(268468224); startActivity(gotoDownloadBoosterSetting); } }); Button goto2014PowerSavingModeSetting = (Button) findViewById(R.id.goto2014PowerSavingModeSetting); goto2014PowerSavingModeSetting.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Intent goto2014PowerSavingModeSetting = new Intent(); goto2014PowerSavingModeSetting.setClassName("com.android.settings", "com.android.settings.Settings$PowerSavingModeSettings2014Activity"); goto2014PowerSavingModeSetting.setAction("android.intent.action.MAIN"); goto2014PowerSavingModeSetting.addCategory("android.intent.category.DEFAULT"); goto2014PowerSavingModeSetting.setFlags(268468224); startActivity(goto2014PowerSavingModeSetting); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); /* //Not Use //noinspection SimplifiableIfStatement if (id == R.id.action_about) { return true; } return super.onOptionsItemSelected(item); */ return false; } }
Intrainos/SamsungLTool
src/main/java/io/github/intrainos/samsungltool/Main.java
Java
mit
5,768
import { makeStyles } from '@material-ui/core/styles'; const drawerWidth = 240; export const useStyles = makeStyles((theme) => ({ root: { display: 'flex', height: '100vh', }, appBar: { width: `calc(100% - ${drawerWidth}px)`, marginLeft: drawerWidth, }, drawer: { width: drawerWidth, flexShrink: 0, }, drawerPaper: { width: drawerWidth, }, toolbar: { display: 'flex', 'justify-content': 'space-between', background: '#5700FA', }, toolbarSpacer: theme.mixins.toolbar, content: { flexGrow: 1, backgroundColor: theme.palette.background.default, position: 'relative', height: 'calc(100% - 64px)', }, headerButtonText: { marginLeft: '0.5rem', }, headerButton: { paddingLeft: '0.5rem', paddingRight: '0.5rem', height: '34px', }, iframe: { border: 'none', }, }));
diegodoumecq/joymap
examples/Main/styles.ts
TypeScript
mit
872
import getValue from './getValue.js'; import getNumberValue from './getNumberValue.js'; export default function getOverlayPlaneModule(metaData) { const overlays = []; for (let overlayGroup = 0x00; overlayGroup <= 0x1e; overlayGroup += 0x02) { let groupStr = `x60${overlayGroup.toString(16)}`; if (groupStr.length === 4) { groupStr = `x600${overlayGroup.toString(16)}`; } const data = getValue(metaData[`${groupStr}3000`]); if (!data) { continue; } const pixelData = []; for (let i = 0; i < data.length; i++) { for (let k = 0; k < 8; k++) { const byte_as_int = metaData.Value[data.dataOffset + i]; pixelData[i * 8 + k] = (byte_as_int >> k) & 0b1; // eslint-disable-line no-bitwise } } overlays.push({ rows: getNumberValue(metaData[`${groupStr}0010`]), columns: getNumberValue(metaData[`${groupStr}0011`]), type: getValue(metaData[`${groupStr}0040`]), x: getNumberValue(metaData[`${groupStr}0050`], 1) - 1, y: getNumberValue(metaData[`${groupStr}0050`], 0) - 1, pixelData, description: getValue(metaData[`${groupStr}0022`]), label: getValue(metaData[`${groupStr}1500`]), roiArea: getValue(metaData[`${groupStr}1301`]), roiMean: getValue(metaData[`${groupStr}1302`]), roiStandardDeviation: getValue(metaData[`${groupStr}1303`]), }); } return { overlays, }; }
chafey/cornerstoneWADOImageLoader
src/imageLoader/wadors/metaData/getOverlayPlaneModule.js
JavaScript
mit
1,430
class Solution: def combine(self, n, k): return [list(elem) for elem in itertools.combinations(xrange(1, n + 1), k)]
rahul-ramadas/leetcode
combinations/Solution.6808610.py
Python
mit
132
'use strict'; /********************************************************************** * Angular Application (client side) **********************************************************************/ angular.module('SwagApp', ['ngRoute', 'appRoutes', 'ui.bootstrap', 'ui.bootstrap.tpls' , 'MainCtrl', 'LoginCtrl', 'MySwagCtrl', 'MySwagService', 'GeekCtrl', 'GeekService']) .config(function($routeProvider, $locationProvider, $httpProvider) { //================================================ // Add an interceptor for AJAX errors //================================================ $httpProvider.responseInterceptors.push(function($q, $location) { return function(promise) { return promise.then( // Success: just return the response function(response){ return response; }, // Error: check the error status to get only the 401 function(response) { if (response.status === 401) $location.url('/login'); return $q.reject(response); } ); } }); //================================================ }) //end of config .run(function($rootScope, $http){ $rootScope.message = ''; // Logout function is available in any pages $rootScope.logout = function(){ $rootScope.message = 'Logged out.'; $http.post('/logout'); }; });
e2themillions/swaggatar
public/js/app.js
JavaScript
mit
1,462
import os import unittest from erettsegit import argparse, yearify, monthify, levelify from erettsegit import MessageType, message_for class TestErettsegit(unittest.TestCase): def test_yearify_raises_out_of_bounds_years(self): with self.assertRaises(argparse.ArgumentTypeError): yearify(2003) yearify(1999) yearify(2) yearify(2999) def test_yearify_pads_short_year(self): self.assertEqual(yearify(12), 2012) def test_monthify_handles_textual_dates(self): self.assertEqual(monthify('Feb'), 2) self.assertEqual(monthify('majus'), 5) self.assertEqual(monthify('ősz'), 10) def test_levelify_handles_multi_lang(self): self.assertEqual(levelify('mid-level'), 'k') self.assertEqual(levelify('advanced'), 'e') def test_messages_get_interpolated_with_extra(self): os.environ['ERETTSEGIT_LANG'] = 'EN' self.assertEqual(message_for(MessageType.e_input, MessageType.c_year), 'incorrect year') def test_messages_ignore_unnecessary_extra(self): self.assertNotIn('None', message_for(MessageType.i_quit, extra=None))
z2s8/erettsegit
test_erettsegit.py
Python
mit
1,186
module Boxy class HomesickHandler def install(url, options) url = URI.parse(url) name = File.basename(url.path) unless castle_cloned?(name) system "homesick clone #{url.to_s}" system "homesick symlink #{name}" else puts "skipping #{name}, already installed" end end private def castle_cloned?(name) `homesick status #{name} > /dev/null 2>&1` $? == 0 end end Boxy.register(:homesick, HomesickHandler.new) end
fooheads/boxy
lib/boxy/homesick.rb
Ruby
mit
505
from django.core.exceptions import PermissionDenied, ObjectDoesNotExist from django.core.paginator import InvalidPage, Paginator from django.db import models from django.http import HttpResponseRedirect from django.template.response import SimpleTemplateResponse, TemplateResponse from django.utils.datastructures import SortedDict from django.utils.encoding import force_unicode, smart_unicode from django.utils.html import escape, conditional_escape from django.utils.safestring import mark_safe from django.utils.text import capfirst from django.utils.translation import ugettext as _ from nadmin.util import lookup_field, display_for_field, label_for_field, boolean_icon from base import ModelAdminView, filter_hook, inclusion_tag, csrf_protect_m # List settings ALL_VAR = 'all' ORDER_VAR = 'o' PAGE_VAR = 'p' TO_FIELD_VAR = 't' COL_LIST_VAR = '_cols' ERROR_FLAG = 'e' DOT = '.' # Text to display within change-list table cells if the value is blank. EMPTY_CHANGELIST_VALUE = _('Null') class FakeMethodField(object): """ This class used when a column is an model function, wrap function as a fake field to display in select columns. """ def __init__(self, name, verbose_name): # Initial comm field attrs self.name = name self.verbose_name = verbose_name self.primary_key = False class ResultRow(dict): pass class ResultItem(object): def __init__(self, field_name, row): self.classes = [] self.text = '&nbsp;' self.wraps = [] self.tag = 'td' self.tag_attrs = [] self.allow_tags = False self.btns = [] self.menus = [] self.is_display_link = False self.row = row self.field_name = field_name self.field = None self.attr = None self.value = None @property def label(self): text = mark_safe( self.text) if self.allow_tags else conditional_escape(self.text) if force_unicode(text) == '': text = mark_safe('&nbsp;') for wrap in self.wraps: text = mark_safe(wrap % text) return text @property def tagattrs(self): return mark_safe( '%s%s' % ((self.tag_attrs and ' '.join(self.tag_attrs) or ''), (self.classes and (' class="%s"' % ' '.join(self.classes)) or ''))) class ResultHeader(ResultItem): def __init__(self, field_name, row): super(ResultHeader, self).__init__(field_name, row) self.tag = 'th' self.tag_attrs = ['scope="col"'] self.sortable = False self.allow_tags = True self.sorted = False self.ascending = None self.sort_priority = None self.url_primary = None self.url_remove = None self.url_toggle = None class ListAdminView(ModelAdminView): """ Display models objects view. this class has ordering and simple filter features. """ list_display = ('__str__',) list_display_links = () list_display_links_details = False list_select_related = None list_per_page = 50 list_max_show_all = 200 list_exclude = () search_fields = () paginator_class = Paginator ordering = None # Change list templates object_list_template = None def init_request(self, *args, **kwargs): if not self.has_view_permission(): raise PermissionDenied request = self.request request.session['LIST_QUERY'] = (self.model_info, self.request.META['QUERY_STRING']) self.pk_attname = self.opts.pk.attname self.lookup_opts = self.opts self.list_display = self.get_list_display() self.list_display_links = self.get_list_display_links() # Get page number parameters from the query string. try: self.page_num = int(request.GET.get(PAGE_VAR, 0)) except ValueError: self.page_num = 0 # Get params from request self.show_all = ALL_VAR in request.GET self.to_field = request.GET.get(TO_FIELD_VAR) self.params = dict(request.GET.items()) if PAGE_VAR in self.params: del self.params[PAGE_VAR] if ERROR_FLAG in self.params: del self.params[ERROR_FLAG] @filter_hook def get_list_display(self): """ Return a sequence containing the fields to be displayed on the list. """ self.base_list_display = (COL_LIST_VAR in self.request.GET and self.request.GET[COL_LIST_VAR] != "" and \ self.request.GET[COL_LIST_VAR].split('.')) or self.list_display return list(self.base_list_display) @filter_hook def get_list_display_links(self): """ Return a sequence containing the fields to be displayed as links on the changelist. The list_display parameter is the list of fields returned by get_list_display(). """ if self.list_display_links or not self.list_display: return self.list_display_links else: # Use only the first item in list_display as link return list(self.list_display)[:1] def make_result_list(self): # Get search parameters from the query string. self.base_queryset = self.queryset() self.list_queryset = self.get_list_queryset() self.ordering_field_columns = self.get_ordering_field_columns() self.paginator = self.get_paginator() # Get the number of objects, with admin filters applied. self.result_count = self.paginator.count # Get the total number of objects, with no admin filters applied. # Perform a slight optimization: Check to see whether any filters were # given. If not, use paginator.hits to calculate the number of objects, # because we've already done paginator.hits and the value is cached. if not self.list_queryset.query.where: self.full_result_count = self.result_count else: self.full_result_count = self.base_queryset.count() self.can_show_all = self.result_count <= self.list_max_show_all self.multi_page = self.result_count > self.list_per_page # Get the list of objects to display on this page. if (self.show_all and self.can_show_all) or not self.multi_page: self.result_list = self.list_queryset._clone() else: try: self.result_list = self.paginator.page( self.page_num + 1).object_list except InvalidPage: if ERROR_FLAG in self.request.GET.keys(): return SimpleTemplateResponse('nadmin/views/invalid_setup.html', { 'title': _('Database error'), }) return HttpResponseRedirect(self.request.path + '?' + ERROR_FLAG + '=1') self.has_more = self.result_count > ( self.list_per_page * self.page_num + len(self.result_list)) @filter_hook def get_result_list(self): return self.make_result_list() @filter_hook def post_result_list(self): return self.make_result_list() @filter_hook def get_list_queryset(self): """ Get model queryset. The query has been filted and ordered. """ # First, get queryset from base class. queryset = self.queryset() # Use select_related() if one of the list_display options is a field # with a relationship and the provided queryset doesn't already have # select_related defined. if not queryset.query.select_related: if self.list_select_related: queryset = queryset.select_related() elif self.list_select_related is None: related_fields = [] for field_name in self.list_display: try: field = self.opts.get_field(field_name) except models.FieldDoesNotExist: pass else: if isinstance(field.rel, models.ManyToOneRel): related_fields.append(field_name) if related_fields: queryset = queryset.select_related(*related_fields) else: pass # Then, set queryset ordering. queryset = queryset.order_by(*self.get_ordering()) # Return the queryset. return queryset # List ordering def _get_default_ordering(self): ordering = [] if self.ordering: ordering = self.ordering elif self.opts.ordering: ordering = self.opts.ordering return ordering @filter_hook def get_ordering_field(self, field_name): """ Returns the proper model field name corresponding to the given field_name to use for ordering. field_name may either be the name of a proper model field or the name of a method (on the admin or model) or a callable with the 'admin_order_field' attribute. Returns None if no proper model field name can be matched. """ try: field = self.opts.get_field(field_name) return field.name except models.FieldDoesNotExist: # See whether field_name is a name of a non-field # that allows sorting. if callable(field_name): attr = field_name elif hasattr(self, field_name): attr = getattr(self, field_name) else: attr = getattr(self.model, field_name) return getattr(attr, 'admin_order_field', None) @filter_hook def get_ordering(self): """ Returns the list of ordering fields for the change list. First we check the get_ordering() method in model admin, then we check the object's default ordering. Then, any manually-specified ordering from the query string overrides anything. Finally, a deterministic order is guaranteed by ensuring the primary key is used as the last ordering field. """ ordering = list(super(ListAdminView, self).get_ordering() or self._get_default_ordering()) if ORDER_VAR in self.params and self.params[ORDER_VAR]: # Clear ordering and used params ordering = [pfx + self.get_ordering_field(field_name) for n, pfx, field_name in map( lambda p: p.rpartition('-'), self.params[ORDER_VAR].split('.')) if self.get_ordering_field(field_name)] # Ensure that the primary key is systematically present in the list of # ordering fields so we can guarantee a deterministic order across all # database backends. pk_name = self.opts.pk.name if not (set(ordering) & set(['pk', '-pk', pk_name, '-' + pk_name])): # The two sets do not intersect, meaning the pk isn't present. So # we add it. ordering.append('-pk') return ordering @filter_hook def get_ordering_field_columns(self): """ Returns a SortedDict of ordering field column numbers and asc/desc """ # We must cope with more than one column having the same underlying sort # field, so we base things on column numbers. ordering = self._get_default_ordering() ordering_fields = SortedDict() if ORDER_VAR not in self.params or not self.params[ORDER_VAR]: # for ordering specified on ModelAdmin or model Meta, we don't know # the right column numbers absolutely, because there might be more # than one column associated with that ordering, so we guess. for field in ordering: if field.startswith('-'): field = field[1:] order_type = 'desc' else: order_type = 'asc' for attr in self.list_display: if self.get_ordering_field(attr) == field: ordering_fields[field] = order_type break else: for p in self.params[ORDER_VAR].split('.'): none, pfx, field_name = p.rpartition('-') ordering_fields[field_name] = 'desc' if pfx == '-' else 'asc' return ordering_fields def get_check_field_url(self, f): """ Return the select column menu items link. We must use base_list_display, because list_display maybe changed by plugins. """ fields = [fd for fd in self.base_list_display if fd != f.name] if len(self.base_list_display) == len(fields): if f.primary_key: fields.insert(0, f.name) else: fields.append(f.name) return self.get_query_string({COL_LIST_VAR: '.'.join(fields)}) def get_model_method_fields(self): """ Return the fields info defined in model. use FakeMethodField class wrap method as a db field. """ methods = [] for name in dir(self): try: if getattr(getattr(self, name), 'is_column', False): methods.append((name, getattr(self, name))) except: pass return [FakeMethodField(name, getattr(method, 'short_description', capfirst(name.replace('_', ' ')))) for name, method in methods] @filter_hook def get_context(self): """ Prepare the context for templates. """ self.title = _('%s List') % force_unicode(self.opts.verbose_name) model_fields = [(f, f.name in self.list_display, self.get_check_field_url(f)) for f in (self.opts.fields + tuple(self.get_model_method_fields())) if f.name not in self.list_exclude] new_context = { 'model_name': force_unicode(self.opts.verbose_name_plural), 'title': self.title, 'cl': self, 'model_fields': model_fields, 'clean_select_field_url': self.get_query_string(remove=[COL_LIST_VAR]), 'has_add_permission': self.has_add_permission(), 'app_label': self.app_label, 'brand_name': self.opts.verbose_name_plural, 'brand_icon': self.get_model_icon(self.model), 'add_url': self.model_admin_url('add'), 'result_headers': self.result_headers(), 'results': self.results() } context = super(ListAdminView, self).get_context() context.update(new_context) return context @filter_hook def get_response(self, context, *args, **kwargs): pass @csrf_protect_m @filter_hook def get(self, request, *args, **kwargs): """ The 'change list' admin view for this model. """ response = self.get_result_list() if response: return response context = self.get_context() context.update(kwargs or {}) response = self.get_response(context, *args, **kwargs) return response or TemplateResponse(request, self.object_list_template or self.get_template_list('views/model_list.html'), context, current_app=self.admin_site.name) @filter_hook def post_response(self, *args, **kwargs): pass @csrf_protect_m @filter_hook def post(self, request, *args, **kwargs): return self.post_result_list() or self.post_response(*args, **kwargs) or self.get(request, *args, **kwargs) @filter_hook def get_paginator(self): return self.paginator_class(self.list_queryset, self.list_per_page, 0, True) @filter_hook def get_page_number(self, i): if i == DOT: return mark_safe(u'<span class="dot-page">...</span> ') elif i == self.page_num: return mark_safe(u'<span class="this-page">%d</span> ' % (i + 1)) else: return mark_safe(u'<a href="%s"%s>%d</a> ' % (escape(self.get_query_string({PAGE_VAR: i})), (i == self.paginator.num_pages - 1 and ' class="end"' or ''), i + 1)) # Result List methods @filter_hook def result_header(self, field_name, row): ordering_field_columns = self.ordering_field_columns item = ResultHeader(field_name, row) text, attr = label_for_field(field_name, self.model, model_admin=self, return_attr=True ) item.text = text item.attr = attr if attr and not getattr(attr, "admin_order_field", None): return item # OK, it is sortable if we got this far th_classes = ['sortable'] order_type = '' new_order_type = 'desc' sort_priority = 0 sorted = False # Is it currently being sorted on? if field_name in ordering_field_columns: sorted = True order_type = ordering_field_columns.get(field_name).lower() sort_priority = ordering_field_columns.keys().index(field_name) + 1 th_classes.append('sorted %sending' % order_type) new_order_type = {'asc': 'desc', 'desc': 'asc'}[order_type] # build new ordering param o_list_asc = [] # URL for making this field the primary sort o_list_desc = [] # URL for making this field the primary sort o_list_remove = [] # URL for removing this field from sort o_list_toggle = [] # URL for toggling order type for this field make_qs_param = lambda t, n: ('-' if t == 'desc' else '') + str(n) for j, ot in ordering_field_columns.items(): if j == field_name: # Same column param = make_qs_param(new_order_type, j) # We want clicking on this header to bring the ordering to the # front o_list_asc.insert(0, j) o_list_desc.insert(0, '-' + j) o_list_toggle.append(param) # o_list_remove - omit else: param = make_qs_param(ot, j) o_list_asc.append(param) o_list_desc.append(param) o_list_toggle.append(param) o_list_remove.append(param) if field_name not in ordering_field_columns: o_list_asc.insert(0, field_name) o_list_desc.insert(0, '-' + field_name) item.sorted = sorted item.sortable = True item.ascending = (order_type == "asc") item.sort_priority = sort_priority menus = [ ('asc', o_list_asc, 'caret-up', _(u'Sort ASC')), ('desc', o_list_desc, 'caret-down', _(u'Sort DESC')), ] if sorted: row['num_sorted_fields'] = row['num_sorted_fields'] + 1 menus.append((None, o_list_remove, 'times', _(u'Cancel Sort'))) item.btns.append('<a class="toggle" href="%s"><i class="fa fa-%s"></i></a>' % ( self.get_query_string({ORDER_VAR: '.'.join(o_list_toggle)}), 'sort-up' if order_type == "asc" else 'sort-down')) item.menus.extend(['<li%s><a href="%s" class="active"><i class="fa fa-%s"></i> %s</a></li>' % ( (' class="active"' if sorted and order_type == i[ 0] else ''), self.get_query_string({ORDER_VAR: '.'.join(i[1])}), i[2], i[3]) for i in menus]) item.classes.extend(th_classes) return item @filter_hook def result_headers(self): """ Generates the list column headers. """ row = ResultRow() row['num_sorted_fields'] = 0 row.cells = [self.result_header( field_name, row) for field_name in self.list_display] return row @filter_hook def result_item(self, obj, field_name, row): """ Generates the actual list of data. """ item = ResultItem(field_name, row) try: f, attr, value = lookup_field(field_name, obj, self) except (AttributeError, ObjectDoesNotExist): item.text = mark_safe("<span class='text-muted'>%s</span>" % EMPTY_CHANGELIST_VALUE) else: if f is None: item.allow_tags = getattr(attr, 'allow_tags', False) boolean = getattr(attr, 'boolean', False) if boolean: item.allow_tags = True item.text = boolean_icon(value) else: item.text = smart_unicode(value) else: if isinstance(f.rel, models.ManyToOneRel): field_val = getattr(obj, f.name) if field_val is None: item.text = mark_safe("<span class='text-muted'>%s</span>" % EMPTY_CHANGELIST_VALUE) else: item.text = field_val else: item.text = display_for_field(value, f) if isinstance(f, models.DateField)\ or isinstance(f, models.TimeField)\ or isinstance(f, models.ForeignKey): item.classes.append('nowrap') item.field = f item.attr = attr item.value = value # If list_display_links not defined, add the link tag to the first field if (item.row['is_display_first'] and not self.list_display_links) \ or field_name in self.list_display_links: item.row['is_display_first'] = False item.is_display_link = True if self.list_display_links_details: item_res_uri = self.model_admin_url("detail", getattr(obj, self.pk_attname)) if item_res_uri: if self.has_change_permission(obj): edit_url = self.model_admin_url("change", getattr(obj, self.pk_attname)) else: edit_url = "" item.wraps.append('<a data-res-uri="%s" data-edit-uri="%s" class="details-handler" rel="tooltip" title="%s">%%s</a>' % (item_res_uri, edit_url, _(u'Details of %s') % str(obj))) else: url = self.url_for_result(obj) item.wraps.append(u'<a href="%s">%%s</a>' % url) return item @filter_hook def result_row(self, obj): row = ResultRow() row['is_display_first'] = True row['object'] = obj row.cells = [self.result_item( obj, field_name, row) for field_name in self.list_display] return row @filter_hook def results(self): results = [] for obj in self.result_list: results.append(self.result_row(obj)) return results @filter_hook def url_for_result(self, result): return self.get_object_url(result) # Media @filter_hook def get_media(self): media = super(ListAdminView, self).get_media() + self.vendor('nadmin.page.list.js', 'nadmin.page.form.js') if self.list_display_links_details: media += self.vendor('nadmin.plugin.details.js', 'nadmin.form.css') return media # Blocks @inclusion_tag('nadmin/includes/pagination.html') def block_pagination(self, context, nodes, page_type='normal'): """ Generates the series of links to the pages in a paginated list. """ paginator, page_num = self.paginator, self.page_num pagination_required = ( not self.show_all or not self.can_show_all) and self.multi_page if not pagination_required: page_range = [] else: ON_EACH_SIDE = {'normal': 5, 'small': 3}.get(page_type, 3) ON_ENDS = 2 # If there are 10 or fewer pages, display links to every page. # Otherwise, do some fancy if paginator.num_pages <= 10: page_range = range(paginator.num_pages) else: # Insert "smart" pagination links, so that there are always ON_ENDS # links at either end of the list of pages, and there are always # ON_EACH_SIDE links at either end of the "current page" link. page_range = [] if page_num > (ON_EACH_SIDE + ON_ENDS): page_range.extend(range(0, ON_EACH_SIDE - 1)) page_range.append(DOT) page_range.extend( range(page_num - ON_EACH_SIDE, page_num + 1)) else: page_range.extend(range(0, page_num + 1)) if page_num < (paginator.num_pages - ON_EACH_SIDE - ON_ENDS - 1): page_range.extend( range(page_num + 1, page_num + ON_EACH_SIDE + 1)) page_range.append(DOT) page_range.extend(range( paginator.num_pages - ON_ENDS, paginator.num_pages)) else: page_range.extend(range(page_num + 1, paginator.num_pages)) need_show_all_link = self.can_show_all and not self.show_all and self.multi_page return { 'cl': self, 'pagination_required': pagination_required, 'show_all_url': need_show_all_link and self.get_query_string({ALL_VAR: ''}), 'page_range': map(self.get_page_number, page_range), 'ALL_VAR': ALL_VAR, '1': 1, }
A425/django-nadmin
nadmin/views/list.py
Python
mit
25,811
<?php namespace Dragoon\MoviesBundle; use Symfony\Component\HttpKernel\Bundle\Bundle; class DragoonMoviesBundle extends Bundle { }
lboulay/sonata
src/Dragoon/MoviesBundle/DragoonMoviesBundle.php
PHP
mit
134
import { bindable, customAttribute, inject } from 'aurelia-framework'; import { AttributeManager } from '../common/attributeManager'; @customAttribute('b-button') @inject(Element) export class BButton { @bindable bStyle = 'default'; @bindable bSize = null; @bindable bBlock = null; @bindable bDisabled = false; @bindable bActive = false; constructor(element) { this.element = element; this.fixedAttributeManager = new AttributeManager(this.element); } attached() { this.fixedAttributeManager.addClasses('btn'); this.fixedAttributeManager.addClasses(`btn-${this.bStyle}`); if (this.bSize) { this.fixedAttributeManager.addClasses(`btn-${this.bSize}`); } if (this.bBlock) { this.fixedAttributeManager.addClasses('btn-block'); } if (this.bDisabled === true) { this.fixedAttributeManager.addClasses('disabled'); } if (this.bActive === true) { this.fixedAttributeManager.addClasses('active'); } } }
aurelia-ui-toolkits/aurelia-bootstrap-bridge
src/button/button.js
JavaScript
mit
1,041
<?php namespace ZPB\AdminBundle\Entity; use Doctrine\ORM\EntityRepository; /** * AnimationProgramRepository * * This class was generated by the Doctrine ORM. Add your own custom * repository methods below. */ class AnimationProgramRepository extends EntityRepository { public function animationsInMonth($month, $year = 2014) { $m = \DateTime::createFromFormat('j/n/Y', '1/'.$month.'/'.$year); $daysInMonth = (int)$m->format('t') + 1; $result = []; for($i = 1; $i < $daysInMonth; $i++){ $d = \DateTime::createFromFormat('Y/n/j',$year.'/'.$month.'/'.$i); $qb = $this->createQueryBuilder('p')->where('p.daytime = :theDate') ->setParameter('theDate', $d, \Doctrine\DBAL\Types\Type::DATE); $result[] = $qb->getQuery()->getOneOrNullResult(); } return $result; } public function getAnimationsInMonth($month, $year = 2014) { $programs = $this->animationsInMonth($month, $year); $result = ['error'=>false, 'message'=>'NO ERROR','year'=>$year, 'month'=>$month, 'days'=>[]]; foreach($programs as $prog){ if($prog != null){ /** @var \ZPB\AdminBundle\Entity\AnimationProgram $prog */ $days = $prog->getAnimationDays(); $tmp = []; foreach($days as $day){ /** @var \ZPB\AdminBundle\Entity\AnimationDay $day */ $tmp[] = $day->toArray(); } $result['days'][] = $tmp; } else { $result['days'][] = []; } } return $result; } }
Grosloup/multisite3
src/ZPB/AdminBundle/Entity/AnimationProgramRepository.php
PHP
mit
1,680
<?php /** * Lithium: the most rad php framework * * @copyright Copyright 2011, Union of RAD (http://union-of-rad.org) * @license http://opensource.org/licenses/bsd-license.php The BSD License */ namespace lithium\tests\cases\net\http; use lithium\action\Request; use lithium\net\http\Route; use lithium\net\http\Router; use lithium\action\Response; class RouterTest extends \lithium\test\Unit { public $request = null; protected $_routes = array(); public function setUp() { $this->request = new Request(); $this->_routes = Router::get(); Router::reset(); } public function tearDown() { Router::reset(); foreach ($this->_routes as $route) { Router::connect($route); } } public function testBasicRouteConnection() { $result = Router::connect('/hello', array('controller' => 'posts', 'action' => 'index')); $expected = array( 'template' => '/hello', 'pattern' => '@^/hello$@', 'params' => array('controller' => 'posts', 'action' => 'index'), 'match' => array('controller' => 'posts', 'action' => 'index'), 'meta' => array(), 'persist' => array('controller'), 'defaults' => array(), 'keys' => array(), 'subPatterns' => array(), 'handler' => null ); $this->assertEqual($expected, $result->export()); $result = Router::connect('/{:controller}/{:action}', array('action' => 'view')); $this->assertTrue($result instanceof Route); $expected = array( 'template' => '/{:controller}/{:action}', 'pattern' => '@^(?:/(?P<controller>[^\\/]+))(?:/(?P<action>[^\\/]+)?)?$@', 'params' => array('action' => 'view'), 'defaults' => array('action' => 'view'), 'match' => array(), 'meta' => array(), 'persist' => array('controller'), 'keys' => array('controller' => 'controller', 'action' => 'action'), 'subPatterns' => array(), 'handler' => null ); $this->assertEqual($expected, $result->export()); } /** * Tests generating routes with required parameters which are not present in the URL. * * @return void */ public function testConnectingWithRequiredParams() { $result = Router::connect('/{:controller}/{:action}', array( 'action' => 'view', 'required' => true )); $expected = array( 'template' => '/{:controller}/{:action}', 'pattern' => '@^(?:/(?P<controller>[^\\/]+))(?:/(?P<action>[^\\/]+)?)?$@', 'keys' => array('controller' => 'controller', 'action' => 'action'), 'params' => array('action' => 'view', 'required' => true), 'defaults' => array('action' => 'view'), 'match' => array('required' => true), 'meta' => array(), 'persist' => array('controller'), 'subPatterns' => array(), 'handler' => null ); $this->assertEqual($expected, $result->export()); } public function testConnectingWithDefaultParams() { $result = Router::connect('/{:controller}/{:action}', array('action' => 'archive')); $expected = array( 'template' => '/{:controller}/{:action}', 'pattern' => '@^(?:/(?P<controller>[^\/]+))(?:/(?P<action>[^\/]+)?)?$@', 'keys' => array('controller' => 'controller', 'action' => 'action'), 'params' => array('action' => 'archive'), 'match' => array(), 'meta' => array(), 'persist' => array('controller'), 'defaults' => array('action' => 'archive'), 'subPatterns' => array(), 'handler' => null ); $this->assertEqual($expected, $result->export()); } /** * Tests basic options for connecting routes. * * @return void */ public function testBasicRouteMatching() { Router::connect('/hello', array('controller' => 'posts', 'action' => 'index')); $expected = array('controller' => 'posts', 'action' => 'index'); foreach (array('/hello/', '/hello', 'hello/', 'hello') as $url) { $this->request->url = $url; $result = Router::parse($this->request); $this->assertEqual($expected, $result->params); $this->assertEqual(array('controller'), $result->persist); } } public function testRouteMatchingWithDefaultParameters() { Router::connect('/{:controller}/{:action}', array('action' => 'view')); $expected = array('controller' => 'posts', 'action' => 'view'); foreach (array('/posts/view', '/posts', 'posts', 'posts/view', 'posts/view/') as $url) { $this->request->url = $url; $result = Router::parse($this->request); $this->assertEqual($expected, $result->params); $this->assertEqual(array('controller'), $result->persist); } $expected['action'] = 'index'; foreach (array('/posts/index', 'posts/index', 'posts/index/') as $url) { $this->request->url = $url; $result = Router::parse($this->request); $this->assertEqual($expected, $result->params); } $this->request->url = '/posts/view/1'; $result = Router::parse($this->request); $this->assertNull($result); } /** * Tests that URLs specified as "Controller::action" are interpreted properly. * * @return void */ public function testStringActions() { Router::connect('/login', array('controller' => 'sessions', 'action' => 'create')); Router::connect('/{:controller}/{:action}'); $result = Router::match("Sessions::create"); $this->assertEqual('/login', $result); $result = Router::match("Posts::index"); $this->assertEqual('/posts', $result); $result = Router::match("ListItems::archive"); $this->assertEqual('/list_items/archive', $result); } public function testNamedAnchor() { Router::connect('/{:controller}/{:action}'); Router::connect('/{:controller}/{:action}/{:id:[0-9]+}', array('id' => null)); $result = Router::match(array('Posts::edit', '#' => 'foo')); $this->assertEqual('/posts/edit#foo', $result); $result = Router::match(array('Posts::edit', 'id' => 42, '#' => 'foo')); $this->assertEqual('/posts/edit/42#foo', $result); $result = Router::match(array('controller' => 'users', 'action' => 'view', '#' => 'blah')); $this->assertEqual('/users/view#blah', $result); $result = Router::match(array( 'controller' => 'users', 'action' => 'view', 'id' => 47, '#' => 'blargh' )); $this->assertEqual('/users/view/47#blargh', $result); } public function testQueryString() { Router::connect('/{:controller}/{:action}'); Router::connect('/{:controller}/{:action}/{:id:[0-9]+}', array('id' => null)); $result = Router::match(array('Posts::edit', '?' => array('key' => 'value'))); $this->assertEqual('/posts/edit?key=value', $result); $result = Router::match(array( 'Posts::edit', 'id' => 42, '?' => array('key' => 'value', 'test' => 'foo') )); $this->assertEqual('/posts/edit/42?key=value&test=foo', $result); } /** * Tests that URLs specified as "Controller::action" and including additional parameters are * interpreted properly. * * @return void */ public function testEmbeddedStringActions() { Router::connect('/logout/{:id:[0-9]{5,6}}', array( 'controller' => 'sessions', 'action' => 'destroy', 'id' => null )); Router::connect('/{:controller}/{:action}'); Router::connect('/{:controller}/{:action}/{:id:[0-9]+}', array('id' => null)); $result = Router::match("Sessions::create"); $this->assertEqual('/sessions/create', $result); $result = Router::match(array("Sessions::create")); $this->assertEqual('/sessions/create', $result); $result = Router::match(array("Sessions::destroy", 'id' => '03815')); $this->assertEqual('/logout/03815', $result); $result = Router::match("Posts::index"); $this->assertEqual('/posts', $result); $ex = "No parameter match found for URL "; $ex .= "`('controller' => 'sessions', 'action' => 'create', 'id' => 'foo')`."; $this->expectException($ex); $result = Router::match(array("Sessions::create", 'id' => 'foo')); } /** * Tests that routes can be created with shorthand strings, i.e. `'Controller::action'` and * `array('Controller::action', 'id' => '...')`. * * @return void */ public function testStringParameterConnect() { Router::connect('/posts/{:id:[0-9a-f]{24}}', 'Posts::edit'); $result = Router::match(array( 'controller' => 'posts', 'action' => 'edit', 'id' => '4bbf25bd8ead0e5180130000' )); $expected = '/posts/4bbf25bd8ead0e5180130000'; $this->assertEqual($expected, $result); $ex = "No parameter match found for URL `("; $ex .= "'controller' => 'posts', 'action' => 'view', 'id' => '4bbf25bd8ead0e5180130000')`."; $this->expectException($ex); $result = Router::match(array( 'controller' => 'posts', 'action' => 'view', 'id' => '4bbf25bd8ead0e5180130000' )); } public function testShorthandParameterMatching() { Router::reset(); Router::connect('/posts/{:page:[0-9]+}', array('Posts::index', 'page' => '1')); $result = Router::match(array('controller' => 'posts', 'page' => '5')); $expected = '/posts/5'; $this->assertEqual($expected, $result); $result = Router::match(array('Posts::index', 'page' => '10')); $expected = '/posts/10'; $this->assertEqual($expected, $result); $request = new Request(array('url' => '/posts/13')); $result = Router::process($request); $expected = array('controller' => 'posts', 'action' => 'index', 'page' => '13'); $this->assertEqual($expected, $result->params); } /** * Tests that routing is fully reset when calling `Router::reset()`. * * @return void */ public function testResettingRoutes() { Router::connect('/{:controller}', array('controller' => 'posts')); $this->request->url = '/hello'; $expected = array('controller' => 'hello', 'action' => 'index'); $result = Router::parse($this->request); $this->assertEqual($expected, $result->params); Router::reset(); $this->assertNull(Router::parse($this->request)); } /** * Tests matching routes where the route template is a static string with no insert parameters. */ public function testRouteMatchingWithNoInserts() { Router::connect('/login', array('controller' => 'sessions', 'action' => 'add')); $result = Router::match(array('controller' => 'sessions', 'action' => 'add')); $this->assertEqual('/login', $result); $this->expectException( "No parameter match found for URL `('controller' => 'sessions', 'action' => 'index')`." ); Router::match(array('controller' => 'sessions', 'action' => 'index')); } /** * Test matching routes with only insert parameters and no default values. */ public function testRouteMatchingWithOnlyInserts() { Router::connect('/{:controller}'); $this->assertEqual('/posts', Router::match(array('controller' => 'posts'))); $this->expectException( "No parameter match found for URL `('controller' => 'posts', 'action' => 'view')`." ); Router::match(array('controller' => 'posts', 'action' => 'view')); } /** * Test matching routes with insert parameters which have default values. */ public function testRouteMatchingWithInsertsAndDefaults() { Router::connect('/{:controller}/{:action}', array('action' => 'archive')); $this->assertEqual('/posts', Router::match(array('controller' => 'posts'))); $result = Router::match(array('controller' => 'posts', 'action' => 'archive')); $this->assertEqual('/posts/archive', $result); Router::reset(); Router::connect('/{:controller}/{:action}', array('controller' => 'users')); $result = Router::match(array('action' => 'view')); $this->assertEqual('/users/view', $result); $result = Router::match(array('controller' => 'posts', 'action' => 'view')); $this->assertEqual('/posts/view', $result); $ex = "No parameter match found for URL "; $ex .= "`('controller' => 'posts', 'action' => 'view', 'id' => '2')`."; $this->expectException($ex); Router::match(array('controller' => 'posts', 'action' => 'view', 'id' => '2')); } /** * Tests matching routes and returning an absolute (protocol + hostname) URL. */ public function testRouteMatchAbsoluteUrl() { Router::connect('/login', array('controller' => 'sessions', 'action' => 'add')); $result = Router::match('Sessions::add', $this->request); $base = $this->request->env('base'); $this->assertEqual($base . '/login', $result); $result = Router::match('Sessions::add', $this->request, array('absolute' => true)); $base = $this->request->env('HTTPS') ? 'https://' : 'http://'; $base .= $this->request->env('HTTP_HOST'); $base .= $this->request->env('base'); $this->assertEqual($base . '/login', $result); $result = Router::match('Sessions::add', $this->request, array('host' => 'test.local', 'absolute' => true) ); $base = $this->request->env('HTTPS') ? 'https://' : 'http://'; $base .= 'test.local'; $base .= $this->request->env('base'); $this->assertEqual($base . '/login', $result); $result = Router::match('Sessions::add', $this->request, array('scheme' => 'https://', 'absolute' => true) ); $base = 'https://' . $this->request->env('HTTP_HOST'); $base .= $this->request->env('base'); $this->assertEqual($base . '/login', $result); $result = Router::match('Sessions::add', $this->request, array('scheme' => 'https://', 'absolute' => true) ); $base = 'https://' . $this->request->env('HTTP_HOST'); $base .= $this->request->env('base'); $this->assertEqual($base . '/login', $result); } /** * Tests getting routes using `Router::get()`, and checking to see if the routes returned match * the routes connected. */ public function testRouteRetrieval() { $expected = Router::connect('/hello', array('controller' => 'posts', 'action' => 'index')); $result = Router::get(0); $this->assertIdentical($expected, $result); list($result) = Router::get(); $this->assertIdentical($expected, $result); } public function testStringUrlGeneration() { $result = Router::match('/posts'); $expected = '/posts'; $this->assertEqual($expected, $result); $result = Router::match('/posts'); $this->assertEqual($expected, $result); $result = Router::match('/posts/view/5'); $expected = '/posts/view/5'; $this->assertEqual($expected, $result); $request = new Request(array('base' => '/my/web/path')); $result = Router::match('/posts', $request); $expected = '/my/web/path/posts'; $this->assertEqual($expected, $result); $request = new Request(array('base' => '/my/web/path')); $result = Router::match('/some/where', $request, array('absolute' => true)); $prefix = $this->request->env('HTTPS') ? 'https://' : 'http://'; $prefix .= $this->request->env('HTTP_HOST'); $this->assertEqual($prefix . '/my/web/path/some/where', $result); $result = Router::match('mailto:foo@localhost'); $expected = 'mailto:foo@localhost'; $this->assertEqual($expected, $result); $result = Router::match('#top'); $expected = '#top'; $this->assertEqual($expected, $result); } public function testWithWildcardString() { Router::connect('/add/{:args}', array('controller' => 'tests', 'action' => 'add')); $expected = '/add'; $result = Router::match('/add'); $this->assertEqual($expected, $result); $expected = '/add/alke'; $result = Router::match('/add/alke'); $this->assertEqual($expected, $result); } public function testWithWildcardArray() { Router::connect('/add/{:args}', array('controller' => 'tests', 'action' => 'add')); $expected = '/add'; $result = Router::match(array('controller' => 'tests', 'action' => 'add')); $this->assertEqual($expected, $result); $expected = '/add/alke'; $result = Router::match(array( 'controller' => 'tests', 'action' => 'add', 'args' => array('alke') )); $this->assertEqual($expected, $result); $expected = '/add/alke/php'; $result = Router::match(array( 'controller' => 'tests', 'action' => 'add', 'args' => array('alke', 'php') )); $this->assertEqual($expected, $result); } public function testProcess() { Router::connect('/add/{:args}', array('controller' => 'tests', 'action' => 'add')); $request = Router::process(new Request(array('url' => '/add/foo/bar'))); $params = array('controller' => 'tests', 'action' => 'add', 'args' => array('foo', 'bar')); $this->assertEqual($params, $request->params); $this->assertEqual(array('controller'), $request->persist); $request = Router::process(new Request(array('url' => '/remove/foo/bar'))); $this->assertFalse($request->params); } /** * Tests that the order of the parameters is respected so it can trim * the URL correctly. */ public function testParameterOrderIsRespected() { Router::connect('/{:locale}/{:controller}/{:action}/{:args}'); Router::connect('/{:controller}/{:action}/{:args}'); $request = Router::process(new Request(array('url' => 'posts'))); $url = Router::match('Posts::index', $request); $this->assertEqual($this->request->env('base') . '/posts', $url); $request = Router::process(new Request(array('url' => 'fr/posts'))); $params = array('Posts::index', 'locale' => 'fr'); $url = Router::match($params, $request); $this->assertEqual($this->request->env('base') . '/fr/posts', $url); } /** * Tests that a request context with persistent parameters generates URLs where those parameters * are properly taken into account. */ public function testParameterPersistence() { Router::connect('/{:controller}/{:action}/{:id:[0-9]+}', array(), array( 'persist' => array('controller', 'id') )); // URLs generated with $request will now have the 'controller' and 'id' // parameters copied to new URLs. $request = Router::process(new Request(array('url' => 'posts/view/1138'))); $params = array('action' => 'edit'); $url = Router::match($params, $request); // Returns: '/posts/edit/1138' $this->assertEqual($this->request->env('base') . '/posts/edit/1138', $url); Router::connect( '/add/{:args}', array('controller' => 'tests', 'action' => 'add'), array('persist' => array('controller', 'action')) ); $request = Router::process(new Request(array('url' => '/add/foo/bar', 'base' => ''))); $path = Router::match(array('args' => array('baz', 'dib')), $request); $this->assertEqual('/add/baz/dib', $path); } /** * Tests that persistent parameters can be overridden with nulled-out values. */ public function testOverridingPersistentParameters() { Router::connect( '/admin/{:controller}/{:action}', array('admin' => true), array('persist' => array('admin', 'controller')) ); Router::connect('/{:controller}/{:action}'); $request = Router::process(new Request(array('url' => '/admin/posts/add', 'base' => ''))); $expected = array('controller' => 'posts', 'action' => 'add', 'admin' => true); $this->assertEqual($expected, $request->params); $this->assertEqual(array('admin', 'controller'), $request->persist); $url = Router::match(array('action' => 'archive'), $request); $this->assertEqual('/admin/posts/archive', $url); $url = Router::match(array('action' => 'archive', 'admin' => null), $request); $this->assertEqual('/posts/archive', $url); } /** * Tests passing a closure handler to `Router::connect()` to bypass or augment default * dispatching. * * @return void */ public function testRouteHandler() { Router::connect('/login', 'Users::login'); Router::connect('/users/login', array(), function($request) { return new Response(array( 'location' => array('controller' => 'users', 'action' => 'login') )); }); $result = Router::process(new Request(array('url' => '/users/login'))); $this->assertTrue($result instanceof Response); $headers = array('location' => '/login'); $this->assertEqual($headers, $result->headers); } /** * Tests that a successful match against a route with template `'/'` operating at the root of * a domain never returns an empty string. * * @return void */ public function testMatchingEmptyRoute() { Router::connect('/', 'Users::view'); $request = new Request(array('base' => '/')); $url = Router::match(array('controller' => 'users', 'action' => 'view'), $request); $this->assertEqual('/', $url); $request = new Request(array('base' => '')); $url = Router::match(array('controller' => 'users', 'action' => 'view'), $request); $this->assertEqual('/', $url); } /** * Tests routing based on content type extensions, with HTML being the default when types are * not defined. * * @return void */ public function testTypeBasedRouting() { Router::connect('/{:controller}/{:id:[0-9]+}', array( 'action' => 'index', 'type' => 'html', 'id' => null )); Router::connect('/{:controller}/{:id:[0-9]+}.{:type}', array( 'action' => 'index', 'id' => null )); Router::connect('/{:controller}/{:action}/{:id:[0-9]+}', array( 'type' => 'html', 'id' => null )); Router::connect('/{:controller}/{:action}/{:id:[0-9]+}.{:type}', array('id' => null)); $url = Router::match(array('controller' => 'posts', 'type' => 'html')); $this->assertEqual('/posts', $url); $url = Router::match(array('controller' => 'posts', 'type' => 'json')); $this->assertEqual('/posts.json', $url); } /** * Tests that routes can be connected and correctly match based on HTTP headers or method verbs. * * @return void */ public function testHttpMethodBasedRouting() { Router::connect('/{:controller}/{:id:[0-9]+}', array( 'http:method' => 'GET', 'action' => 'view' )); Router::connect('/{:controller}/{:id:[0-9]+}', array( 'http:method' => 'PUT', 'action' => 'edit' )); $request = new Request(array('url' => '/posts/13', 'env' => array( 'REQUEST_METHOD' => 'GET' ))); $params = Router::process($request)->params; $expected = array('controller' => 'posts', 'action' => 'view', 'id' => '13'); $this->assertEqual($expected, $params); $this->assertEqual('/posts/13', Router::match($params)); $request = new Request(array('url' => '/posts/13', 'env' => array( 'REQUEST_METHOD' => 'PUT' ))); $params = Router::process($request)->params; $expected = array('controller' => 'posts', 'action' => 'edit', 'id' => '13'); $this->assertEqual($expected, $params); $request = new Request(array('url' => '/posts/13', 'env' => array( 'REQUEST_METHOD' => 'POST' ))); $params = Router::process($request)->params; $this->assertFalse($params); } /** * Tests that the class dependency configuration can be modified. * * @return void */ public function testCustomConfiguration() { $old = Router::config(); $config = array('classes' => array('route' => 'my\custom\Route')); Router::config($config); $this->assertEqual($config, Router::config()); Router::config($old); $this->assertEqual($old, Router::config()); } } ?>
WarToaster/HangOn
libraries/lithium/tests/cases/net/http/RouterTest.php
PHP
mit
22,379
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the MIT License (MIT). // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //********************************************************* #include "stdafx.h" #include "CullDataVisualizer.h" #include "DXSampleHelper.h" using namespace DirectX; namespace { const wchar_t* s_boundingSphereMsFilename = L"BoundingSphereMS.cso"; const wchar_t* s_normalConeMsFilename = L"NormalConeMS.cso"; const wchar_t* s_debugDrawPsFilename = L"DebugDrawPS.cso"; std::wstring GetAssetFullPath(const wchar_t* path) { WCHAR assetsPath[512]; GetAssetsPath(assetsPath, _countof(assetsPath)); return std::wstring(assetsPath) + path; } } CullDataVisualizer::CullDataVisualizer() : m_constantData(nullptr) , m_frameIndex(0) { } void CullDataVisualizer::CreateDeviceResources(ID3D12Device2* device, DXGI_FORMAT rtFormat, DXGI_FORMAT dsFormat) { // Load shader bytecode and extract root signature struct { byte* data; uint32_t size; } normalConeMs, boundingSphereMs, pixelShader; ReadDataFromFile(GetAssetFullPath(s_normalConeMsFilename).c_str(), &normalConeMs.data, &normalConeMs.size); ReadDataFromFile(GetAssetFullPath(s_boundingSphereMsFilename).c_str(), &boundingSphereMs.data, &boundingSphereMs.size); ReadDataFromFile(GetAssetFullPath(s_debugDrawPsFilename).c_str(), &pixelShader.data, &pixelShader.size); ThrowIfFailed(device->CreateRootSignature(0, normalConeMs.data, normalConeMs.size, IID_PPV_ARGS(&m_rootSignature))); // Disable culling CD3DX12_RASTERIZER_DESC rasterDesc = CD3DX12_RASTERIZER_DESC(D3D12_DEFAULT); rasterDesc.CullMode = D3D12_CULL_MODE_NONE; // Disable depth test & writes CD3DX12_DEPTH_STENCIL_DESC dsDesc = CD3DX12_DEPTH_STENCIL_DESC(D3D12_DEFAULT); dsDesc.DepthEnable = false; dsDesc.StencilEnable = false; dsDesc.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ZERO; // Populate the Mesh Shader PSO descriptor D3DX12_MESH_SHADER_PIPELINE_STATE_DESC psoDesc = {}; psoDesc.pRootSignature = m_rootSignature.Get(); psoDesc.PS = { pixelShader.data, pixelShader.size }; psoDesc.NumRenderTargets = 1; psoDesc.RTVFormats[0] = rtFormat; psoDesc.DSVFormat = dsFormat; psoDesc.RasterizerState = rasterDesc; psoDesc.DepthStencilState = dsDesc; psoDesc.SampleMask = UINT_MAX; psoDesc.SampleDesc = DefaultSampleDesc(); // Create normal cone pipeline { // Cone lines are drawn opaquely psoDesc.MS = { normalConeMs.data, normalConeMs.size }; psoDesc.BlendState = CD3DX12_BLEND_DESC(D3D12_DEFAULT); // Opaque auto meshStreamDesc = CD3DX12_PIPELINE_MESH_STATE_STREAM(psoDesc); // Populate the stream desc with our defined PSO descriptor D3D12_PIPELINE_STATE_STREAM_DESC streamDesc = {}; streamDesc.SizeInBytes = sizeof(meshStreamDesc); streamDesc.pPipelineStateSubobjectStream = &meshStreamDesc; ThrowIfFailed(device->CreatePipelineState(&streamDesc, IID_PPV_ARGS(&m_normalConePso))); } // Create bounding sphere pipeline { // bounding sphere pipeline requires additive blending D3D12_BLEND_DESC blendDesc = {}; blendDesc.RenderTarget[0].BlendEnable = true; blendDesc.RenderTarget[0].BlendOp = D3D12_BLEND_OP_ADD; blendDesc.RenderTarget[0].SrcBlend = D3D12_BLEND_SRC_ALPHA; blendDesc.RenderTarget[0].DestBlend = D3D12_BLEND_INV_SRC_ALPHA; blendDesc.RenderTarget[0].BlendOpAlpha = D3D12_BLEND_OP_MAX; blendDesc.RenderTarget[0].SrcBlendAlpha = D3D12_BLEND_ZERO; blendDesc.RenderTarget[0].DestBlendAlpha = D3D12_BLEND_ONE; blendDesc.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL; psoDesc.MS = { boundingSphereMs.data, boundingSphereMs.size }; psoDesc.BlendState = blendDesc; auto meshStreamDesc = CD3DX12_PIPELINE_MESH_STATE_STREAM(psoDesc); // Populate the stream desc with our defined PSO descriptor D3D12_PIPELINE_STATE_STREAM_DESC streamDesc = {}; streamDesc.SizeInBytes = sizeof(meshStreamDesc); streamDesc.pPipelineStateSubobjectStream = &meshStreamDesc; ThrowIfFailed(device->CreatePipelineState(&streamDesc, IID_PPV_ARGS(&m_boundingSpherePso))); } const CD3DX12_HEAP_PROPERTIES constantBufferHeapProps(D3D12_HEAP_TYPE_UPLOAD); const CD3DX12_RESOURCE_DESC constantBufferDesc = CD3DX12_RESOURCE_DESC::Buffer(sizeof(Constants) * 2); // Create shared constant buffer ThrowIfFailed(device->CreateCommittedResource( &constantBufferHeapProps, D3D12_HEAP_FLAG_NONE, &constantBufferDesc, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&m_constantResource) )); ThrowIfFailed(m_constantResource->Map(0, nullptr, &m_constantData)); } void CullDataVisualizer::ReleaseResources() { m_rootSignature.Reset(); m_boundingSpherePso.Reset(); m_normalConePso.Reset(); m_constantResource.Reset(); } void CullDataVisualizer::SetConstants(FXMMATRIX world, CXMMATRIX view, CXMMATRIX proj, CXMVECTOR color) { m_frameIndex = (m_frameIndex + 1) % 2; XMVECTOR scl, rot, pos; XMMatrixDecompose(&scl, &rot, &pos, world); XMMATRIX viewToWorld = XMMatrixTranspose(view); XMVECTOR camUp = XMVector3TransformNormal(g_XMIdentityR1, viewToWorld); // Y-axis is up direction XMVECTOR camForward = XMVector3TransformNormal(g_XMNegIdentityR2, viewToWorld); // -Z-axis is forward direction auto& constants = *(reinterpret_cast<Constants*>(m_constantData) + m_frameIndex); XMStoreFloat4x4(&constants.ViewProj, XMMatrixTranspose(view * proj)); XMStoreFloat4x4(&constants.World, XMMatrixTranspose(world)); XMStoreFloat4(&constants.Color, color); XMStoreFloat4(&constants.ViewUp, camUp); XMStoreFloat3(&constants.ViewForward, camForward); constants.Scale = XMVectorGetX(scl); constants.Color.w = 0.3f; } void CullDataVisualizer::Draw(ID3D12GraphicsCommandList6* commandList, const Mesh& mesh, uint32_t offset, uint32_t count) { // Push constant data to GPU for our shader invocations assert(offset + count <= static_cast<uint32_t>(mesh.Meshlets.size())); // Shared root signature between two shaders commandList->SetGraphicsRootSignature(m_rootSignature.Get()); commandList->SetGraphicsRootConstantBufferView(0, m_constantResource->GetGPUVirtualAddress() + sizeof(Constants) * m_frameIndex); commandList->SetGraphicsRoot32BitConstant(1, offset, 0); commandList->SetGraphicsRoot32BitConstant(1, count, 1); commandList->SetGraphicsRootShaderResourceView(2, mesh.CullDataResource->GetGPUVirtualAddress()); // Dispatch bounding sphere draw commandList->SetPipelineState(m_boundingSpherePso.Get()); commandList->DispatchMesh(count, 1, 1); // Dispatch normal cone draw commandList->SetPipelineState(m_normalConePso.Get()); commandList->DispatchMesh(count, 1, 1); }
SuperWangKai/DirectX-Graphics-Samples
Samples/Desktop/D3D12MeshShaders/src/MeshletCull/CullDataVisualizer.cpp
C++
mit
7,493
package com.wrapper.spotify.requests.data.player; import com.wrapper.spotify.TestUtil; import com.wrapper.spotify.enums.CurrentlyPlayingType; import com.wrapper.spotify.enums.ModelObjectType; import com.wrapper.spotify.exceptions.SpotifyWebApiException; import com.wrapper.spotify.model_objects.miscellaneous.CurrentlyPlaying; import com.wrapper.spotify.model_objects.specification.Episode; import com.wrapper.spotify.model_objects.specification.Track; import com.wrapper.spotify.requests.data.AbstractDataTest; import org.apache.hc.core5.http.ParseException; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.runners.MockitoJUnitRunner; import java.io.IOException; import java.util.concurrent.ExecutionException; import static org.junit.Assert.*; @RunWith(MockitoJUnitRunner.class) public class GetUsersCurrentlyPlayingTrackRequestTest extends AbstractDataTest<CurrentlyPlaying> { private final GetUsersCurrentlyPlayingTrackRequest defaultRequest = SPOTIFY_API .getUsersCurrentlyPlayingTrack() .setHttpManager( TestUtil.MockedHttpManager.returningJson( "requests/data/player/GetUsersCurrentlyPlayingTrackRequest.json")) .market(MARKET) .additionalTypes(ADDITIONAL_TYPES) .build(); private final GetUsersCurrentlyPlayingTrackRequest defaultEpisodeRequest = SPOTIFY_API .getUsersCurrentlyPlayingTrack() .setHttpManager( TestUtil.MockedHttpManager.returningJson( "requests/data/player/GetUsersCurrentlyPlayingTrackRequest_Episode.json")) .market(MARKET) .additionalTypes(ADDITIONAL_TYPES) .build(); private final GetUsersCurrentlyPlayingTrackRequest emptyRequest = SPOTIFY_API .getUsersCurrentlyPlayingTrack() .setHttpManager( TestUtil.MockedHttpManager.returningJson(null)) .market(MARKET) .additionalTypes(ADDITIONAL_TYPES) .build(); public GetUsersCurrentlyPlayingTrackRequestTest() throws Exception { } @Test public void shouldComplyWithReference() { assertHasAuthorizationHeader(defaultRequest); assertEquals( "https://api.spotify.com:443/v1/me/player/currently-playing?market=SE&additional_types=track%2Cepisode", defaultRequest.getUri().toString()); } @Test public void shouldReturnDefault_sync() throws IOException, SpotifyWebApiException, ParseException { shouldReturnDefault(defaultRequest.execute()); } @Test public void shouldReturnDefault_async() throws ExecutionException, InterruptedException { shouldReturnDefault(defaultRequest.executeAsync().get()); } public void shouldReturnDefault(final CurrentlyPlaying currentlyPlaying) { assertNull( currentlyPlaying.getContext()); assertEquals( 1516669900630L, (long) currentlyPlaying.getTimestamp()); assertEquals( 78810, (int) currentlyPlaying.getProgress_ms()); assertFalse( currentlyPlaying.getIs_playing()); assertNotNull( currentlyPlaying.getItem()); assertTrue( currentlyPlaying.getItem() instanceof Track); assertNotNull( currentlyPlaying.getActions()); assertEquals( 4, currentlyPlaying.getActions().getDisallows().getDisallowedActions().size()); assertEquals( CurrentlyPlayingType.TRACK, currentlyPlaying.getCurrentlyPlayingType()); } @Test public void shouldReturnDefaultEpisode_sync() throws IOException, SpotifyWebApiException, ParseException { shouldReturnDefaultEpisode(defaultEpisodeRequest.execute()); } @Test public void shouldReturnDefaultEpisode_async() throws ExecutionException, InterruptedException { shouldReturnDefaultEpisode(defaultEpisodeRequest.executeAsync().get()); } public void shouldReturnDefaultEpisode(final CurrentlyPlaying currentlyPlaying) { assertEquals( 1516669848357L, (long) currentlyPlaying.getTimestamp()); assertNotNull( currentlyPlaying.getContext()); assertEquals( currentlyPlaying.getContext().getType(), ModelObjectType.SHOW); assertEquals( 3636145, (int) currentlyPlaying.getProgress_ms()); assertNotNull( currentlyPlaying.getItem()); assertTrue( currentlyPlaying.getItem() instanceof Episode); assertEquals( CurrentlyPlayingType.EPISODE, currentlyPlaying.getCurrentlyPlayingType()); assertNotNull( currentlyPlaying.getActions()); assertEquals( 4, currentlyPlaying.getActions().getDisallows().getDisallowedActions().size()); assertTrue( currentlyPlaying.getIs_playing()); } @Test public void shouldReturnEmpty_sync() throws IOException, SpotifyWebApiException, ParseException { shouldReturnEmpty(emptyRequest.execute()); } @Test public void shouldReturnEmpty_async() throws ExecutionException, InterruptedException { shouldReturnEmpty(emptyRequest.executeAsync().get()); } public void shouldReturnEmpty(final CurrentlyPlaying currentlyPlaying) { assertNull( currentlyPlaying); } }
thelinmichael/spotify-web-api-java
src/test/java/com/wrapper/spotify/requests/data/player/GetUsersCurrentlyPlayingTrackRequestTest.java
Java
mit
4,985
package org.javacs.rewrite; /** JavaType represents a potentially parameterized named type. */ public class JavaType { final String name; final JavaType[] parameters; public JavaType(String name, JavaType[] parameters) { this.name = name; this.parameters = parameters; } }
georgewfraser/vscode-javac
src/main/java/org/javacs/rewrite/JavaType.java
Java
mit
307
/* * Copyright (c) 2018 Rain Agency <contact@rain.agency> * Author: Rain Agency <contact@rain.agency> * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ export function toSSML(statement?: string): string | undefined { if (!statement) { return undefined; } if (statement.startsWith("<speak>")) { return statement; } // Hack. Full xml escaping would be better, but the & is currently the only special character used. statement = statement.replace(/&/g, "&amp;"); return `<speak>${statement}</speak>`; }
armonge/voxa
src/ssml.ts
TypeScript
mit
1,552
MRuby::Build.new do |conf| toolchain :gcc conf.gembox 'default' conf.gem '../m-activerecord' conf.enable_test end
yasuyuki/m-activerecord
.travis_build_config.rb
Ruby
mit
122
$(document).ready(function(){ var nav = navigator.userAgent.toLowerCase(); //La variable nav almacenará la información del navegador del usuario if(nav.indexOf("firefox") != -1){ //En caso de que el usuario este usando el navegador MozillaFirefox $("#fecha_inicio").mask("9999-99-99",{placeholder:"AAAA-MM-DD"}); //Se inicializa el campo fecha con el plugIn de maskedInput $("#fecha_fin").mask("9999-99-99",{placeholder:"AAAA-MM-DD"}); //Se inicializa el campo fecha con el plugIn de maskedInput } $("#accordion").on("show.bs.collapse", ".collapse", function(e){ $(this).parent(".panel").find(".panel-heading .panel-title a span").removeClass("glyphicon-plus").addClass("glyphicon-minus"); }); $("#accordion").on("hide.bs.collapse", ".collapse", function(e){ $(this).parent(".panel").find(".panel-heading .panel-title a span").addClass("glyphicon-plus").removeClass("glyphicon-minus"); }); $("#hora_inicio").mask("99:99",{placeholder:"00:00"}); $("#hora_fin").mask("99:99",{placeholder:"00:00"}); $('#registro-evento').validator(); $("#registro-evento").on("submit", function(){ $(this).attr("disabled","disabled"); $('#seccion2').animate({scrollTop : 0}, 500); }); $("#imagen").fileinput({ language: "es", fileType: "image", showUpload: false, browseLabel: 'Examinar &hellip;', removeLabel: 'Remover' }); $("#img-change").on("click", function(){ if ($("#img-change").is(":checked")) { $("#imagen-content figure").hide(); $("#imagen-content h4").hide(); $("#imagen-content .form-group").removeClass("hidden"); }else{ $("#imagen-content figure").show(); $("#imagen-content h4").show(); $("#imagen-content .form-group").addClass("hidden"); } }); });
JoseSoto33/proyecto-sismed
assets/js/funciones-formulario-evento.js
JavaScript
mit
1,944
(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["shared-components"] = factory(require("react")); else root["shared-components"] = factory(root["react"]); })(this, function(__WEBPACK_EXTERNAL_MODULE_1__) { 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"; 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; }; }(); var _react = __webpack_require__(1); var _react2 = _interopRequireDefault(_react); __webpack_require__(2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var NumberPicker = function (_React$Component) { _inherits(NumberPicker, _React$Component); function NumberPicker(props) { _classCallCheck(this, NumberPicker); var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(NumberPicker).call(this, props)); _this.MAX_VALUE = _this.maxValue(); return _this; } _createClass(NumberPicker, [{ key: "maxValue", value: function maxValue() { var str_max = ""; for (var i = 0; i < this.props.digits; i++) { str_max += "9"; }if (this.props.showDecimal) str_max += ".99"; return parseFloat(str_max); } }, { key: "digitInteger", value: function digitInteger(ltr_digit) { var sValue = this.props.value.toString(); var a_sValue = sValue.split("."); var integer = a_sValue[0]; var rtl_digit = this.props.digits - (ltr_digit - 1); if (rtl_digit > integer.length) return "0"; return integer[integer.length - rtl_digit]; } }, { key: "digitDecimal", value: function digitDecimal(ltr_digit) { var sValue = this.props.value.toString(); var a_sValue = sValue.split("."); var decimal = a_sValue.length > 1 && a_sValue[1].length > 0 ? a_sValue[1] : "00"; if (decimal.length > 2) decimal = decimal.substr(0, 2); if (decimal.length < 2) decimal = decimal + "0"; return decimal[ltr_digit - 1]; } }, { key: "modifyValue", value: function modifyValue(type, value, event) { event.preventDefault(); if (!this.props.onChange) return; var value_to_add = type === "down" ? value * -1 : value; var new_value = this.props.value + value_to_add; /* adjust float operations */ var str_new_value = this.props.showDecimal ? new_value.toFixed(2) : new_value.toFixed(0); var adjusted_new_value = parseFloat(str_new_value); /* dont work with negative values, YET */ if (adjusted_new_value < 0) adjusted_new_value = 0; /* prevent from exceed maximum possible values */ if (adjusted_new_value > this.MAX_VALUE) adjusted_new_value = this.MAX_VALUE; this.props.onChange(adjusted_new_value); } }, { key: "renderButtons", value: function renderButtons(type) { var elements = []; /* display an invisible cell */ if (this.props.currency) { elements.push(_react2.default.createElement("div", { key: "currency", className: "NumberPicker__cell button" })); } /* display tob/bottom buttons */ for (var i = 0; i < this.props.digits; i++) { var value_to_add = Math.pow(10, this.props.digits - i - 1); elements.push(_react2.default.createElement( "div", { key: "integer-" + i, className: "NumberPicker__cell button " + type }, _react2.default.createElement("span", { className: type, onClick: this.modifyValue.bind(this, type, value_to_add) }) )); } /* display invisible cell to decimal separator and tob/bottom buttons for decimals */ if (this.props.showDecimal) { elements.push(_react2.default.createElement("div", { key: "decimal-separator", className: "NumberPicker__cell decimal-separator" })); elements.push(_react2.default.createElement( "div", { key: "decimal-1", className: "NumberPicker__cell button " + type }, _react2.default.createElement("span", { className: type, onClick: this.modifyValue.bind(this, type, 0.1) }) )); elements.push(_react2.default.createElement( "div", { key: "decimal-2", className: "NumberPicker__cell button " + type }, _react2.default.createElement("span", { className: type, onClick: this.modifyValue.bind(this, type, 0.01) }) )); } return elements; } }, { key: "renderDigits", value: function renderDigits() { var elements = []; if (this.props.currency) { elements.push(_react2.default.createElement( "div", { key: "currency", className: "NumberPicker__cell currency" }, _react2.default.createElement( "span", { className: "currency" }, this.props.currency ) )); } for (var i = 0; i < this.props.digits; i++) { var digit = i + 1; elements.push(_react2.default.createElement( "div", { key: digit, className: "NumberPicker__cell digit" }, _react2.default.createElement( "span", { className: "digit" }, this.digitInteger(digit) ) )); } if (this.props.showDecimal) { elements.push(_react2.default.createElement( "div", { key: "decimal-separator", className: "NumberPicker__cell decimal-separator" }, _react2.default.createElement( "span", { className: "decimal-separator" }, this.props.decimalSeparator ) )); elements.push(_react2.default.createElement( "div", { key: "decimal-1", className: "NumberPicker__cell digit" }, _react2.default.createElement( "span", { className: "digit" }, this.digitDecimal(1) ) )); elements.push(_react2.default.createElement( "div", { key: "decimal-2", className: "NumberPicker__cell digit" }, _react2.default.createElement( "span", { className: "digit" }, this.digitDecimal(2) ) )); } return elements; } }, { key: "render", value: function render() { return _react2.default.createElement( "div", { className: "NumberPicker__wrapper" }, _react2.default.createElement( "div", { className: "NumberPicker__table" }, _react2.default.createElement( "div", { className: "NumberPicker__row" }, this.renderButtons("up") ), _react2.default.createElement( "div", { className: "NumberPicker__row" }, this.renderDigits() ), _react2.default.createElement( "div", { className: "NumberPicker__row" }, this.renderButtons("down") ) ) ); } }]); return NumberPicker; }(_react2.default.Component); NumberPicker.propTypes = { onChange: _react2.default.PropTypes.func, digits: _react2.default.PropTypes.number.isRequired, currency: _react2.default.PropTypes.string, value: _react2.default.PropTypes.number.isRequired, showDecimal: _react2.default.PropTypes.bool.isRequired, decimalSeparator: _react2.default.PropTypes.string.isRequired }; NumberPicker.defaultProps = { digits: 1, currency: null, value: 0.00, decimalSeparator: ".", showDecimal: false }; exports.default = NumberPicker; /***/ }, /* 1 */ /***/ function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE_1__; /***/ }, /* 2 */ /***/ function(module, exports) { // removed by extract-text-webpack-plugin /***/ } /******/ ]) }); ;
mrlew/react-number-picker
dist/react-number-picker.js
JavaScript
mit
10,328
<?php defined('BASEPATH') OR exit('No direct script access allowed'); /* |-------------------------------------------------------------------------- | Base Site URL |-------------------------------------------------------------------------- | | URL to your CodeIgniter root. Typically this will be your base URL, | WITH a trailing slash: | | http://example.com/ | | WARNING: You MUST set this value! | | If it is not set, then CodeIgniter will try guess the protocol and path | your installation, but due to security concerns the hostname will be set | to $_SERVER['SERVER_ADDR'] if available, or localhost otherwise. | The auto-detection mechanism exists only for convenience during | development and MUST NOT be used in production! | | If you need to allow multiple domains, remember that this file is still | a PHP script and you can easily do that on your own. | */ $config['base_url'] = 'http://training_ci.happy.cba/'; //$config['base_url'] = 'http://localhost:81/Training_CI-master/'; /* |-------------------------------------------------------------------------- | Index File |-------------------------------------------------------------------------- | | Typically this will be your index.php file, unless you've renamed it to | something else. If you are using mod_rewrite to remove the page set this | variable so that it is blank. | */ $config['index_page'] = ''; /* |-------------------------------------------------------------------------- | URI PROTOCOL |-------------------------------------------------------------------------- | | This item determines which server global should be used to retrieve the | URI string. The default setting of 'REQUEST_URI' works for most servers. | If your links do not seem to work, try one of the other delicious flavors: | | 'REQUEST_URI' Uses $_SERVER['REQUEST_URI'] | 'QUERY_STRING' Uses $_SERVER['QUERY_STRING'] | 'PATH_INFO' Uses $_SERVER['PATH_INFO'] | | WARNING: If you set this to 'PATH_INFO', URIs will always be URL-decoded! */ $config['uri_protocol'] = 'REQUEST_URI'; /* |-------------------------------------------------------------------------- | URL suffix |-------------------------------------------------------------------------- | | This option allows you to add a suffix to all URLs generated by CodeIgniter. | For more information please see the user guide: | | http://codeigniter.com/user_guide/general/urls.html */ $config['url_suffix'] = ''; /* |-------------------------------------------------------------------------- | Default Language |-------------------------------------------------------------------------- | | This determines which set of language files should be used. Make sure | there is an available translation if you intend to use something other | than english. | */ $config['language'] = 'english'; /* |-------------------------------------------------------------------------- | Default Character Set |-------------------------------------------------------------------------- | | This determines which character set is used by default in various methods | that require a character set to be provided. | | See http://php.net/htmlspecialchars for a list of supported charsets. | */ $config['charset'] = 'UTF-8'; /* |-------------------------------------------------------------------------- | Enable/Disable System Hooks |-------------------------------------------------------------------------- | | If you would like to use the 'hooks' feature you must enable it by | setting this variable to TRUE (boolean). See the user guide for details. | */ $config['enable_hooks'] = FALSE; /* |-------------------------------------------------------------------------- | Class Extension Prefix |-------------------------------------------------------------------------- | | This item allows you to set the filename/classname prefix when extending | native libraries. For more information please see the user guide: | | http://codeigniter.com/user_guide/general/core_classes.html | http://codeigniter.com/user_guide/general/creating_libraries.html | */ $config['subclass_prefix'] = 'MY_'; /* |-------------------------------------------------------------------------- | Composer auto-loading |-------------------------------------------------------------------------- | | Enabling this setting will tell CodeIgniter to look for a Composer | package auto-loader script in application/vendor/autoload.php. | | $config['composer_autoload'] = TRUE; | | Or if you have your vendor/ directory located somewhere else, you | can opt to set a specific path as well: | | $config['composer_autoload'] = '/path/to/vendor/autoload.php'; | | For more information about Composer, please visit http://getcomposer.org/ | | Note: This will NOT disable or override the CodeIgniter-specific | autoloading (application/config/autoload.php) */ $config['composer_autoload'] = FALSE; /* |-------------------------------------------------------------------------- | Allowed URL Characters |-------------------------------------------------------------------------- | | This lets you specify which characters are permitted within your URLs. | When someone tries to submit a URL with disallowed characters they will | get a warning message. | | As a security measure you are STRONGLY encouraged to restrict URLs to | as few characters as possible. By default only these are allowed: a-z 0-9~%.:_- | | Leave blank to allow all characters -- but only if you are insane. | | The configured value is actually a regular expression character group | and it will be executed as: ! preg_match('/^[<permitted_uri_chars>]+$/i | | DO NOT CHANGE THIS UNLESS YOU FULLY UNDERSTAND THE REPERCUSSIONS!! | */ $config['permitted_uri_chars'] = 'a-z 0-9~%.:_\-'; /* |-------------------------------------------------------------------------- | Enable Query Strings |-------------------------------------------------------------------------- | | By default CodeIgniter uses search-engine friendly segment based URLs: | example.com/who/what/where/ | | By default CodeIgniter enables access to the $_GET array. If for some | reason you would like to disable it, set 'allow_get_array' to FALSE. | | You can optionally enable standard query string based URLs: | example.com?who=me&what=something&where=here | | Options are: TRUE or FALSE (boolean) | | The other items let you set the query string 'words' that will | invoke your controllers and its functions: | example.com/index.php?c=controller&m=function | | Please note that some of the helpers won't work as expected when | this feature is enabled, since CodeIgniter is designed primarily to | use segment based URLs. | */ $config['allow_get_array'] = TRUE; $config['enable_query_strings'] = FALSE; $config['controller_trigger'] = 'c'; $config['function_trigger'] = 'm'; $config['directory_trigger'] = 'd'; /* |-------------------------------------------------------------------------- | Error Logging Threshold |-------------------------------------------------------------------------- | | You can enable error logging by setting a threshold over zero. The | threshold determines what gets logged. Threshold options are: | | 0 = Disables logging, Error logging TURNED OFF | 1 = Error Messages (including PHP errors) | 2 = Debug Messages | 3 = Informational Messages | 4 = All Messages | | You can also pass an array with threshold levels to show individual error types | | array(2) = Debug Messages, without Error Messages | | For a live site you'll usually only enable Errors (1) to be logged otherwise | your log files will fill up very fast. | */ $config['log_threshold'] = 0; /* |-------------------------------------------------------------------------- | Error Logging Directory Path |-------------------------------------------------------------------------- | | Leave this BLANK unless you would like to set something other than the default | application/logs/ directory. Use a full server path with trailing slash. | */ $config['log_path'] = ''; /* |-------------------------------------------------------------------------- | Log File Extension |-------------------------------------------------------------------------- | | The default filename extension for log files. The default 'php' allows for | protecting the log files via basic scripting, when they are to be stored | under a publicly accessible directory. | | Note: Leaving it blank will default to 'php'. | */ $config['log_file_extension'] = ''; /* |-------------------------------------------------------------------------- | Log File Permissions |-------------------------------------------------------------------------- | | The file system permissions to be applied on newly created log files. | | IMPORTANT: This MUST be an integer (no quotes) and you MUST use octal | integer notation (i.e. 0700, 0644, etc.) */ $config['log_file_permissions'] = 0644; /* |-------------------------------------------------------------------------- | Date Format for Logs |-------------------------------------------------------------------------- | | Each item that is logged has an associated date. You can use PHP date | codes to set your own date formatting | */ $config['log_date_format'] = 'Y-m-d H:i:s'; /* |-------------------------------------------------------------------------- | Error Views Directory Path |-------------------------------------------------------------------------- | | Leave this BLANK unless you would like to set something other than the default | application/views/errors/ directory. Use a full server path with trailing slash. | */ $config['error_views_path'] = ''; /* |-------------------------------------------------------------------------- | Cache Directory Path |-------------------------------------------------------------------------- | | Leave this BLANK unless you would like to set something other than the default | application/cache/ directory. Use a full server path with trailing slash. | */ $config['cache_path'] = ''; /* |-------------------------------------------------------------------------- | Cache Include Query String |-------------------------------------------------------------------------- | | Whether to take the URL query string into consideration when generating | output cache files. Valid options are: | | FALSE = Disabled | TRUE = Enabled, take all query parameters into account. | Please be aware that this may result in numerous cache | files generated for the same page over and over again. | array('q') = Enabled, but only take into account the specified list | of query parameters. | */ $config['cache_query_string'] = FALSE; /* |-------------------------------------------------------------------------- | Encryption Key |-------------------------------------------------------------------------- | | If you use the Encryption class, you must set an encryption key. | See the user guide for more info. | | http://codeigniter.com/user_guide/libraries/encryption.html | */ $config['encryption_key'] = ''; /* |-------------------------------------------------------------------------- | Session Variables |-------------------------------------------------------------------------- | | 'sess_driver' | | The storage driver to use: files, database, redis, memcached | | 'sess_cookie_name' | | The session cookie name, must contain only [0-9a-z_-] characters | | 'sess_expiration' | | The number of SECONDS you want the session to last. | Setting to 0 (zero) means expire when the browser is closed. | | 'sess_save_path' | | The location to save sessions to, driver dependent. | | For the 'files' driver, it's a path to a writable directory. | WARNING: Only absolute paths are supported! | | For the 'database' driver, it's a table name. | Please read up the manual for the format with other session drivers. | | IMPORTANT: You are REQUIRED to set a valid save path! | | 'sess_match_ip' | | Whether to match the user's IP address when reading the session data. | | WARNING: If you're using the database driver, don't forget to update | your session table's PRIMARY KEY when changing this setting. | | 'sess_time_to_update' | | How many seconds between CI regenerating the session ID. | | 'sess_regenerate_destroy' | | Whether to destroy session data associated with the old session ID | when auto-regenerating the session ID. When set to FALSE, the data | will be later deleted by the garbage collector. | | Other session cookie settings are shared with the rest of the application, | except for 'cookie_prefix' and 'cookie_httponly', which are ignored here. | */ $config['sess_driver'] = 'files'; $config['sess_cookie_name'] = 'ci_session'; $config['sess_expiration'] = 7200; $config['sess_save_path'] = NULL; $config['sess_match_ip'] = FALSE; $config['sess_time_to_update'] = 300; $config['sess_regenerate_destroy'] = FALSE; /* |-------------------------------------------------------------------------- | Cookie Related Variables |-------------------------------------------------------------------------- | | 'cookie_prefix' = Set a cookie name prefix if you need to avoid collisions | 'cookie_domain' = Set to .your-domain.com for site-wide cookies | 'cookie_path' = Typically will be a forward slash | 'cookie_secure' = Cookie will only be set if a secure HTTPS connection exists. | 'cookie_httponly' = Cookie will only be accessible via HTTP(S) (no javascript) | | Note: These settings (with the exception of 'cookie_prefix' and | 'cookie_httponly') will also affect sessions. | */ $config['cookie_prefix'] = ''; $config['cookie_domain'] = ''; $config['cookie_path'] = '/'; $config['cookie_secure'] = FALSE; $config['cookie_httponly'] = FALSE; /* |-------------------------------------------------------------------------- | Standardize newlines |-------------------------------------------------------------------------- | | Determines whether to standardize newline characters in input data, | meaning to replace \r\n, \r, \n occurrences with the PHP_EOL value. | | This is particularly useful for portability between UNIX-based OSes, | (usually \n) and Windows (\r\n). | */ $config['standardize_newlines'] = FALSE; /* |-------------------------------------------------------------------------- | Global XSS Filtering |-------------------------------------------------------------------------- | | Determines whether the XSS filter is always active when GET, POST or | COOKIE data is encountered | | WARNING: This feature is DEPRECATED and currently available only | for backwards compatibility purposes! | */ $config['global_xss_filtering'] = FALSE; /* |-------------------------------------------------------------------------- | Cross Site Request Forgery |-------------------------------------------------------------------------- | Enables a CSRF cookie token to be set. When set to TRUE, token will be | checked on a submitted form. If you are accepting user data, it is strongly | recommended CSRF protection be enabled. | | 'csrf_token_name' = The token name | 'csrf_cookie_name' = The cookie name | 'csrf_expire' = The number in seconds the token should expire. | 'csrf_regenerate' = Regenerate token on every submission | 'csrf_exclude_uris' = Array of URIs which ignore CSRF checks */ $config['csrf_protection'] = FALSE; $config['csrf_token_name'] = 'csrf_test_name'; $config['csrf_cookie_name'] = 'csrf_cookie_name'; $config['csrf_expire'] = 7200; $config['csrf_regenerate'] = TRUE; $config['csrf_exclude_uris'] = array(); /* |-------------------------------------------------------------------------- | Output Compression |-------------------------------------------------------------------------- | | Enables Gzip output compression for faster page loads. When enabled, | the output class will test whether your server supports Gzip. | Even if it does, however, not all browsers support compression | so enable only if you are reasonably sure your visitors can handle it. | | Only used if zlib.output_compression is turned off in your php.ini. | Please do not use it together with httpd-level output compression. | | VERY IMPORTANT: If you are getting a blank page when compression is enabled it | means you are prematurely outputting something to your browser. It could | even be a line of whitespace at the end of one of your scripts. For | compression to work, nothing can be sent before the output buffer is called | by the output class. Do not 'echo' any values with compression enabled. | */ $config['compress_output'] = FALSE; /* |-------------------------------------------------------------------------- | Master Time Reference |-------------------------------------------------------------------------- | | Options are 'local' or any PHP supported timezone. This preference tells | the system whether to use your server's local time as the master 'now' | reference, or convert it to the configured one timezone. See the 'date | helper' page of the user guide for information regarding date handling. | */ $config['time_reference'] = 'local'; /* |-------------------------------------------------------------------------- | Rewrite PHP Short Tags |-------------------------------------------------------------------------- | | If your PHP installation does not have short tag support enabled CI | can rewrite the tags on-the-fly, enabling you to utilize that syntax | in your view files. Options are TRUE or FALSE (boolean) | | Note: You need to have eval() enabled for this to work. | */ $config['rewrite_short_tags'] = FALSE; /* |-------------------------------------------------------------------------- | Reverse Proxy IPs |-------------------------------------------------------------------------- | | If your server is behind a reverse proxy, you must whitelist the proxy | IP addresses from which CodeIgniter should trust headers such as | HTTP_X_FORWARDED_FOR and HTTP_CLIENT_IP in order to properly identify | the visitor's IP address. | | You can use both an array or a comma-separated list of proxy addresses, | as well as specifying whole subnets. Here are a few examples: | | Comma-separated: '10.0.1.200,192.168.5.0/24' | Array: array('10.0.1.200', '192.168.5.0/24') */ $config['proxy_ips'] = '';
DeRossi/Training_CI
application/config/config.php
PHP
mit
18,210
import json import re from pygeocoder import Geocoder from pygeolib import GeocoderError import requests # from picasso.index.models import Tag from picasso.index.models import Address, Listing, Tag __author__ = 'tmehta' url = 'http://www.yellowpages.ca/ajax/search/music+teachers/Toronto%2C+ON?sType=si&sort=rel&pg=1&' + \ 'skipNonPaids=56&trGeo=43.797452066539165,-79.15031040820315&blGeo=43.55112164714018,-79.6419485917969' base_url = 'http://www.yellowpages.ca/bus/' city = 'Toronto' def extract_cats(p): try: p_s = p.split('Products and Services</h3>')[1].split('</span>')[0].replace('<span>', '') except IndexError: return [] p_s = p_s.split("'>")[1:] cats = [] for line in p_s: cats.append(line.split('</li>')[0]) return cats def extract_phone(p): try: phone = p.split('class="phone"')[1].split('<span >')[1].split('</span>')[0] except IndexError: phone = '' return phone r = requests.get(url) listings = json.loads(r.text)['features'] for l in listings: name = l['properties']['name'] scraped_url = base_url + str(l['properties']['id']) + '.html' try: lst = Listing.objects.get(scraped_url=scraped_url) page = requests.get(scraped_url).text try: location = page.split('itemprop="streetAddress">')[1].split('</span>')[0] except IndexError: location = '' try: postalCode = page.split('itemprop="postalCode">')[1].split('</span>')[0] except IndexError: postalCode = '' lat = l["geometry"]["coordinates"][0] lon = l["geometry"]["coordinates"][1] point = "POINT(%s %s)" % (lon, lat) lst.address.point = point lst.save() except Listing.DoesNotExist: active = True place = 'Sch' email = '' page = requests.get(scraped_url).text categories = extract_cats(page) tags = [] for cat in categories: t = Tag.objects.get_or_create(tag_name=cat) phone_number = extract_phone(page) try: location = page.split('itemprop="streetAddress">')[1].split('</span>')[0] except IndexError: location = '' try: postalCode = page.split('itemprop="postalCode">')[1].split('</span>')[0] except IndexError: postalCode = '' try: description = page.split('itemprop="description">')[1].split('</article>')[0].split('<a href')[0].replace( '<span', '').replace('</span>', '') except IndexError: description = '' lat = l["geometry"]["coordinates"][0] lon = l["geometry"]["coordinates"][1] point = "POINT(%s %s)" % (lon, lat) add = Address.objects.create(location=location, postal_code=postalCode, city=city, point=point) lst = Listing.objects.create(address=add, listing_name=name, scraped_url=scraped_url, description=description, phone=phone_number) for t in tags: lst.tags.add(t) lst.save()
TejasM/picasso
picasso/yellow_pages.py
Python
mit
3,125
require 'timeout' require 'spec_helper' shared_examples 'using a mysql database' do before :all do within 'form#jira-setup-database' do # select using external database choose 'jira-setup-database-field-database-external' # allow some time for the DOM to change sleep 1 # fill in database configuration select "MySQL", from: 'jira-setup-database-field-database-type' fill_in 'jdbcHostname', with: @container_db.host fill_in 'jdbcPort', with: '3306' fill_in 'jdbcDatabase', with: 'jiradb' fill_in 'jdbcUsername', with: 'root' fill_in 'jdbcPassword', with: 'mysecretpassword' # continue database setup click_button 'Next' end end end
wpxgit/docker-atlassian-jira
spec/support/shared_examples/using_a_mysql_database_shared_example.rb
Ruby
mit
678
package com.sincsmart.attendance.util; import com.activeandroid.util.Log; import android.content.Context; import android.util.TypedValue; //常用单位转换的辅助类 public class DensityUtils { private DensityUtils() { /* cannot be instantiated */ throw new UnsupportedOperationException("cannot be instantiated"); } /** * dp转px * * @param context * @param val * @return */ public static int dp2px(Context context, float dpVal) { final float scale = context.getResources().getDisplayMetrics().density; Log.i("ldb", "分辨率" + scale); return (int) (dpVal * scale + 0.5f); } /** * sp转px * * @param context * @param val * @return */ public static int sp2px(Context context, float spVal) { return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, spVal, context.getResources().getDisplayMetrics()); } /** * px转dp * * @param context * @param pxVal * @return */ public static float px2dp(Context context, float pxVal) { final float scale = context.getResources().getDisplayMetrics().density; return (pxVal / scale); } /** * px转sp * * @param fontScale * @param pxVal * @return */ public static float px2sp(Context context, float pxVal) { return (pxVal / context.getResources().getDisplayMetrics().scaledDensity); } }
zhilianxinke/attendance
src/com/sincsmart/attendance/util/DensityUtils.java
Java
mit
1,335
// Copyright (c) 2012 Ecma International. All rights reserved. // Ecma International makes this code available under the terms and conditions set // forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the // "Use Terms"). Any redistribution of this code must retain the above // copyright and this notice and otherwise comply with the Use Terms. /*--- es5id: 15.2.3.7-6-a-78 description: > Object.defineProperties will not throw TypeError when P.configurable is false, P.writalbe is false, properties.value and P.value are two numbers with the same value (8.12.9 step 10.a.ii.1) includes: [propertyHelper.js] ---*/ var obj = {}; Object.defineProperty(obj, "foo", { value: 100, writable: false, configurable: false }); Object.defineProperties(obj, { foo: { value: 100 } }); verifyEqualTo(obj, "foo", 100); verifyNotWritable(obj, "foo"); verifyNotEnumerable(obj, "foo"); verifyNotConfigurable(obj, "foo");
PiotrDabkowski/Js2Py
tests/test_cases/built-ins/Object/defineProperties/15.2.3.7-6-a-78.js
JavaScript
mit
975
import './clean-rich-text-editor.css'; import select from 'select-dom'; import onetime from 'onetime'; import * as pageDetect from 'github-url-detection'; import features from '.'; function hideButtons(): void { document.body.classList.add('rgh-clean-rich-text-editor'); } function hideTextareaTooltip(): void { for (const textarea of select.all('.comment-form-textarea')) { textarea.title = ''; } } void features.add(__filebasename, { include: [ pageDetect.hasRichTextEditor, ], deduplicate: 'has-rgh-inner', init: hideTextareaTooltip, }, { include: [ pageDetect.isRepo, ], awaitDomReady: false, init: onetime(hideButtons), });
sindresorhus/refined-github
source/features/clean-rich-text-editor.tsx
TypeScript
mit
650
import subprocess with open('names.txt') as f: names = f.read().splitlines() with open('portraits.txt') as f: portraits = f.read().splitlines() for i, name in enumerate(names): portrait = portraits[i] if portrait.endswith('.png'): subprocess.call(['cp', 'minor/{}'.format(portrait), '{}.png'.format(name.lower())])
dcripplinger/rotj
data/images/portraits/copy_portraits.py
Python
mit
341
<h2>New Group</h2> <br> <?php echo render('admin/group/_form'); ?> <p><?php echo Html::anchor('admin/group', 'Back'); ?></p>
hrabbit/newzearch
fuel/app/views/admin/group/create.php
PHP
mit
128
import React from "react"; export default class TransactionSentModal extends React.Component { constructor(props) { super(props); this.state = { }; } render() { return ( <div className={this.props.transactionSent ? "transaction-sent-wrap active" : "transaction-sent-wrap"}> { this.props.transactionSent ? <form className="container transactionSent" onSubmit={this.props.closeSuccessModal}> <div className="head"> <h3>Sent </h3> <span className="close" onClick={this.props.closeSuccessModal}>X</span> </div> <div className="currency"> <span>Currency:</span> <img className={this.props.sendCoin === 'safex' ? 'coin' : 'coin hidden-xs hidden-sm hidden-md hidden-lg'} onClick={this.props.sendCoinSafex} src="images/coin-white.png" alt="Safex Coin"/> <img className={this.props.sendCoin === 'btc' ? 'coin' : 'coin hidden-xs hidden-sm hidden-md hidden-lg'} onClick={this.props.sendCoinBtc} src="images/btc-coin.png" alt="Bitcoin Coin"/> </div> <div className="input-group"> <label htmlFor="from">From:</label> <textarea name="from" className="form-control" readOnly value={this.props.publicKey} placeholder="Address" aria-describedby="basic-addon1"> </textarea> </div> <div className="input-group"> <label htmlFor="destination">To:</label> <textarea name="destination" className="form-control" readOnly value={this.props.receiveAddress} placeholder="Address" aria-describedby="basic-addon1"> </textarea> </div> <div className="input-group"> <label htmlFor="txid">TX ID:</label> <textarea name="txid" className="form-control" readOnly value={this.props.txid} placeholder="Address" aria-describedby="basic-addon1" rows="3"> </textarea> </div> <input type="hidden" readOnly name="private_key" value={this.props.privateKey} /> <input type="hidden" readOnly name="public_key" value={this.props.publicKey} /> <div className="form-group"> <label htmlFor="amount">Amount:</label> <input readOnly name="amount" value={this.props.sendAmount} /> </div> <div className="form-group"> <label htmlFor="fee">Fee(BTC):</label> <input readOnly name="fee" value={this.props.sendFee} /> </div> <div className="form-group"> <label htmlFor="total">Total:</label> <input readOnly name="total" value={this.props.sendTotal} /> </div> <button type="submit" className="sent-close button-shine"> Close </button> </form> : <div></div> } </div> ); } }
safex/safex_wallet
src/components/partials/TransactionSentModal.js
JavaScript
mit
4,367
#pragma once #include <vector> #include <memory> #ifndef ARBITER_IS_AMALGAMATION #include <arbiter/driver.hpp> #include <arbiter/util/http.hpp> #endif #ifdef ARBITER_CUSTOM_NAMESPACE namespace ARBITER_CUSTOM_NAMESPACE { #endif namespace arbiter { namespace drivers { /** @brief HTTP driver. Intended as both a standalone driver as well as a base * for derived drivers build atop HTTP. * * Derivers should overload the HTTP-specific put/get methods that accept * headers and query parameters rather than Driver::put and Driver::get. * * Internal methods for derivers are provided as protected methods. */ class ARBITER_DLL Http : public Driver { public: Http(http::Pool& pool); static std::unique_ptr<Http> create(http::Pool& pool); // Inherited from Driver. virtual std::string type() const override { return "http"; } /** By default, performs a HEAD request and returns the contents of the * Content-Length header. */ virtual std::unique_ptr<std::size_t> tryGetSize( std::string path) const override; virtual void put( std::string path, const std::vector<char>& data) const final override { put(path, data, http::Headers(), http::Query()); } /* HTTP-specific driver methods follow. Since many drivers (S3, Dropbox, * etc.) are built atop HTTP, we'll provide HTTP-specific methods for * derived classes to use in addition to the generic PUT/GET combinations. * * Specifically, we'll add POST/HEAD calls, and allow headers and query * parameters to be passed as well. */ /** Perform an HTTP GET request. */ std::string get( std::string path, http::Headers headers = http::Headers(), http::Query query = http::Query()) const; /** Perform an HTTP GET request. */ std::unique_ptr<std::string> tryGet( std::string path, http::Headers headers = http::Headers(), http::Query query = http::Query()) const; /* Perform an HTTP HEAD request. */ std::size_t getSize( std::string path, http::Headers headers, http::Query query = http::Query()) const; /* Perform an HTTP HEAD request. */ std::unique_ptr<std::size_t> tryGetSize( std::string path, http::Headers headers, http::Query query = http::Query()) const; /** Perform an HTTP GET request. */ std::vector<char> getBinary( std::string path, http::Headers headers, http::Query query) const; /** Perform an HTTP GET request. */ std::unique_ptr<std::vector<char>> tryGetBinary( std::string path, http::Headers headers, http::Query query) const; /** Perform an HTTP PUT request. */ void put( std::string path, const std::string& data, http::Headers headers, http::Query query) const; /** HTTP-derived Drivers should override this version of PUT to allow for * custom headers and query parameters. */ /** Perform an HTTP PUT request. */ virtual void put( std::string path, const std::vector<char>& data, http::Headers headers, http::Query query) const; void post( std::string path, const std::string& data, http::Headers headers, http::Query query) const; void post( std::string path, const std::vector<char>& data, http::Headers headers, http::Query query) const; /* These operations are other HTTP-specific calls that derived drivers may * need for their underlying API use. */ http::Response internalGet( std::string path, http::Headers headers = http::Headers(), http::Query query = http::Query(), std::size_t reserve = 0) const; http::Response internalPut( std::string path, const std::vector<char>& data, http::Headers headers = http::Headers(), http::Query query = http::Query()) const; http::Response internalHead( std::string path, http::Headers headers = http::Headers(), http::Query query = http::Query()) const; http::Response internalPost( std::string path, const std::vector<char>& data, http::Headers headers = http::Headers(), http::Query query = http::Query()) const; protected: /** HTTP-derived Drivers should override this version of GET to allow for * custom headers and query parameters. */ virtual bool get( std::string path, std::vector<char>& data, http::Headers headers, http::Query query) const; http::Pool& m_pool; private: virtual bool get( std::string path, std::vector<char>& data) const final override { return get(path, data, http::Headers(), http::Query()); } std::string typedPath(const std::string& p) const; }; /** @brief HTTPS driver. Identical to the HTTP driver except for its type * string. */ class Https : public Http { public: Https(http::Pool& pool) : Http(pool) { } static std::unique_ptr<Https> create(http::Pool& pool) { return std::unique_ptr<Https>(new Https(pool)); } virtual std::string type() const override { return "https"; } }; } // namespace drivers } // namespace arbiter #ifdef ARBITER_CUSTOM_NAMESPACE } #endif
connormanning/arbiter
arbiter/drivers/http.hpp
C++
mit
5,624
Chance = require('chance'); chance = new Chance(); function generateStudent() { var numberOfStudent = chance.integer({ min: 0, max: 10 }) console.log(numberOfStudent); var students = []; for (var i = 0; i < numberOfStudent; i++) { var birthYear = chance.year({ min: 1990, max: 2000 }); var gender = chance.gender(); students.push({ firstname: chance.first({ gender: gender }), lastname: chance.last(), gender: gender, birthday: chance.birthday({ year: birthYear }) }); } console.log(students); return students; } function genPlaName() { var planetsName = ["Sun", "Kepler", "Earth", "Dagoba", "Coruscant", "Venus", "Jupiter", "Hoth"]; var idName = chance.integer({ min: 0, max: planetsName.length-1 }); var rndNumber = chance.integer({ min: 1, max: 9999 }); return planetsName[idName] + "-" + rndNumber; } function generatePlanet() { var nbrOfPlanet = chance.integer({ min: 1, max: 10 }); var planets = []; for (var i = 0; i < nbrOfPlanet; i++) { var minTemperature = chance.integer({ min: -270, max: 1000 }); var maxTemperature = chance.integer({ min: minTemperature, max: 1000 }); planets.push({ name: genPlaName(), minTemperature: minTemperature, maxTemperature: maxTemperature }); } console.log(planets); return planets; } function generatePayload() { return generatePlanet(); } exports.generatePayload = generatePayload;
verdonarthur/Teaching-HEIGVD-RES-2016-Labo-HTTPInfra
docker-images/node-image/src/jsonPayloadGen.js
JavaScript
mit
1,797
#!/usr/bin/env python3 # -*- encoding: utf-8 -*- from distutils.core import setup, Extension setup(name='sample', ext_modules=[ Extension('sample', ['pysample.c'], include_dirs=['/some/dir'], define_macros=[('FOO', '1')], undef_macros=['BAR'], library_dirs=['/usr/local/lib'], libraries=['sample'] ) ] )
xu6148152/Binea_Python_Project
PythonCookbook/interaction_c/setup.py
Python
mit
474