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
import logging from copy import copy from six import iteritems, reraise import sys from .base import Singleton from .utils import APP_DIR, rel, merge class BaseConfigMixin(dict): def __setitem__(self, key, value): self.__dict__[key.lower()] = value def __getitem__(self, key): return self.__dict__[key.lower()] def __delitem__(self, key): del self.__dict__[key] def __contains__(self, key): return key in self.__dict__ def __len__(self): return len(self.__dict__) def get(self, key, default=None): return self.__dict__.get(key.lower(), default) def init_config(self): def is_builtin(k, v): return k.startswith('__') or k.endswith('__') def is_callable(k, v): return callable(v) for k, v in iteritems(Config.__dict__): if is_builtin(k, v) or is_callable(k, v): continue self[k] = v def override_config(self, **kwargs): for k, v in iteritems(kwargs): orig_v = getattr(self, k, getattr(Config, k)) if orig_v is not None: if isinstance(orig_v, dict): v = merge(copy(orig_v), v) self[k] = v class Config(BaseConfigMixin, Singleton): def __init__(self, *a, **kw): Singleton.__init__(self, *a, **kw) def init(self, **kwargs): self.init_config() self.override_config(**kwargs) app_dir = APP_DIR environment = 'dev' verbose = False application = { #'key': #'token' #"path": 'https://staging-api.translationexchange.com' #"cdn_path": "http://trex-snapshots.s3-us-west-1.amazonaws.com" "path": "https://api.translationexchange.com", "cdn_path": "http://cdn.translationexchange.com" } logger = { 'enabled': True, 'path': rel(APP_DIR, 'tml.log'), 'level': logging.DEBUG } api_client = 'tml.api.client.Client' locale = { 'default': 'en', 'method': 'current_locale', 'subdomain': False, 'extension': False, 'query_param': 'locale' } locale_mapping = { 'pt-br': 'pt-BR', 'zh-hans-cn': 'zh-Hans-CN' } agent = { 'enabled': True, 'type': 'agent', 'cache': 86400, # timeout every 24 hours 'host': "https://tools.translationexchange.com/agent/stable/agent.min.js", 'force_injection': False # force inject js agent as soon as tml is configured #'host': "https://tools.translationexchange.com/agent/staging/agent.min.js" } data_preprocessors = () env_generators = ('tml.tools.viewing_user.get_viewing_user',) cache = { 'enabled': False, #'adapter': 'file', #'path': 'a/b/c/snapshot.tar.gz' } default_source = "index" context_class = None # just for testing purpose context_rules = { 'number': {'variables': {}}, 'gender': { 'variables': { '@gender': 'gender', '@size': lambda lst: len(lst) } }, 'genders': { 'variables': { '@genders': lambda lst: [u['gender'] if hasattr(u, 'items') else getattr(u, 'gender') for u in lst] } }, 'date': {'variables': {}}, 'time': {'variables': {}}, 'list': { 'variables': { '@count': lambda lst: len(lst) } } } localization = { 'default_day_names' : ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"], 'default_abbr_day_names' : ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"], 'default_month_names' : ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"], 'default_abbr_month_names': ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], 'custom_date_formats' : { 'default' : '%m/%d/%Y', # 07/4/2008 'short_numeric' : '%m/%d', # 07/4 'short_numeric_year' : '%m/%d/%y', # 07/4/08 'long_numeric' : '%m/%d/%Y', # 07/4/2008 'verbose' : '%A, %B %d, %Y', # Friday, July 4, 2008 'monthname' : '%B %d', # July 4 'monthname_year' : '%B %d, %Y', # July 4, 2008 'monthname_abbr' : '%b %d', # Jul 4 'monthname_abbr_year' : '%b %d, %Y', # Jul 4, 2008 'date_time' : '%m/%d/%Y at %H:%M', # 01/03/1010 at 5:30 }, 'token_mapping': { '%a': '{short_week_day_name}', '%A': '{week_day_name}', '%b': '{short_month_name}', '%B': '{month_name}', '%p': '{am_pm}', '%d': '{days}', '%e': '{day_of_month}', '%j': '{year_days}', '%m': '{months}', '%W': '{week_num}', '%w': '{week_days}', '%y': '{short_years}', '%Y': '{years}', '%l': '{trimed_hour}', '%H': '{full_hours}', '%I': '{short_hours}', '%M': '{minutes}', '%S': '{seconds}', '%s': '{since_epoch}' } } translator_options = { 'debug': False, 'debug_format_html': "<span style='font-size:20px;color:red;'>{</span> {$0} <span style='font-size:20px;color:red;'>}</span>", 'debug_format': '{{{{$0}}}}', 'split_sentences': False, 'nodes': { 'ignored': [], 'scripts': ["style", "script", "code", "pre"], 'inline': ["a", "span", "i", "b", "img", "strong", "s", "em", "u", "sub", "sup"], 'short': ["i", "b"], 'splitters': ["br", "hr"] }, 'attributes': { 'labels': ["title", "alt"] }, 'name_mapping': { 'b': 'bold', 'i': 'italic', 'a': 'link', 'img': 'picture' }, 'data_tokens': { 'special': { 'enabled': True, 'regex': '(&[^;]*;)' }, 'date': { 'enabled': True, 'formats': [ ['((Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s+\d+,\s+\d+)', "{month} {day}, {year}"], ['((January|February|March|April|May|June|July|August|September|October|November|December)\s+\d+,\s+\d+)', "{month} {day}, {year}"], ['(\d+\s+(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec),\s+\d+)', "{day} {month}, {year}"], ['(\d+\s+(January|February|March|April|May|June|July|August|September|October|November|December),\s+\d+)', "{day} {month}, {year}"] ], 'name': 'date' }, 'rules': [ {'enabled': True, 'name': 'time', 'regex': '(\d{1,2}:\d{1,2}\s+([A-Z]{2,3}|am|pm|AM|PM)?)'}, {'enabled': True, 'name': 'phone', 'regex': '((\d{1}-)?\d{3}-\d{3}-\d{4}|\d?\(\d{3}\)\s*\d{3}-\d{4}|(\d.)?\d{3}.\d{3}.\d{4})'}, {'enabled': True, 'name': 'email', 'regex': '([-a-z0-9~!$%^&*_=+}{\'?]+(\.[-a-z0-9~!$%^&*_=+}{\'?]+)*@([a-z0-9_][-a-z0-9_]*(\.[-a-z0-9_]+)*\.(aero|arpa|biz|com|coop|edu|gov|info|int|mil|museum|name|net|org|pro|travel|io|mobi|[a-z][a-z])|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(:[0-9]{1,5})?)'}, {'enabled': True, 'name': 'price', 'regex': '(\$\d*(,\d*)*(\.\d*)?)'}, {'enabled': True, 'name': 'fraction', 'regex': '(\d+\/\d+)'}, {'enabled': True, 'name': 'num', 'regex': '\\b(\d+(,\d*)*(\.\d*)?%?)\\b'} ] } } # memcached #'cache': { #'enabled': True, #'adapter': 'memcached', #'backend': 'default', # 'namespace': 'foody' #}, version_check_interval = 3600 source_separator = '@:@' strict_mode = False supported_tr_opts = ('source', 'target_locale',) tml_cookie = 'trex_%s' decorator_class = "html" @property def default_locale(self): return self.locale['default'] def get_locale(self, locale): if not locale: return self.default_locale return self.locale_mapping.get(locale, locale) def cache_enabled(self): return self['cache'].get('enabled', False) def application_key(self): return self['application'].get('key', 'current') def access_token(self, default=None): return self['application'].get('access_token', default) def api_host(self): return self.application['path'] if self.environment == 'prod': return 'https://api.translationexchange.com' else: return def cdn_host(self): return self.application['cdn_path'] def agent_host(self): return self.agent['host'] def is_interactive_mode(self): return False def get_custom_date_format(self, format): return self.localization['custom_date_formats'][format] def strftime_symbol_to_token(self, symbol): return self.localization['token_mapping'].get(symbol, None) def get_abbr_day_name(self, index): return self.localization['default_abbr_day_names'][index] def get_day_name(self, index): return self.localization['default_day_names'][index] def get_abbr_month_name(self, index): return self.localization['default_abbr_month_names'][index] def get_month_name(self, index): return self.localization['default_month_names'][index] def handle_exception(self, exc): if self.strict_mode: reraise(exc.__class__, exc, sys.exc_info()[2]) else: pass # silent (logged in tml.py) def nested_value(self, hash_value, key, default_value=None): parts = key.split('.') for part in parts: if not hash_value.get(part, None): return default_value hash_value = hash_value.get(part) return hash_value def translator_option(self, key): return self.nested_value(self.translator_options, key) CONFIG = Config.instance() def configure(**kwargs): global CONFIG if kwargs: CONFIG.override_config(**kwargs) return CONFIG
translationexchange/tml-python
tml/config.py
Python
mit
10,511
<?php namespace Mleczek\CBuilder\Tests\Package; use DI\Container; use DI\ContainerBuilder; use Mleczek\CBuilder\Constraint\Parser; use Mleczek\CBuilder\Environment\Config; use Mleczek\CBuilder\Package\Exceptions\InvalidTypeException; use Mleczek\CBuilder\Package\Exceptions\UnrecognizedArchitectureException; use Mleczek\CBuilder\Package\Exceptions\UnrecognizedLinkingException; use Mleczek\CBuilder\Package\Exceptions\UnrecognizedPlatformException; use Mleczek\CBuilder\Package\Exceptions\UnrecognizedTypeException; use Mleczek\CBuilder\Package\Package; use Mleczek\CBuilder\Repository\Exceptions\UnknownRepositoryTypeException; use Mleczek\CBuilder\Repository\Repository; use Mleczek\CBuilder\Tests\TestCase; class PackageTest extends TestCase { /** * @var Parser|\PHPUnit_Framework_MockObject_MockObject */ private $parser; /** * @var Config|\PHPUnit_Framework_MockObject_MockObject */ private $config; /** * Called before each test is executed. */ protected function setUp() { $di = ContainerBuilder::buildDevContainer(); $this->parser = new Parser($di); $this->config = $this->createMock(Config::class); } public function testGetJson() { $json = (object)[ 'x' => 3, 'y' => true, 'z' => 'lorem', ]; $package = new Package($this->parser, $this->config, $json); $this->assertEquals($json, $package->getJson()); } public function testGetIncludeDir() { $json = json_decode('{"include": "temp/dir"}'); $package = new Package($this->parser, $this->config, $json); $this->assertEquals($json->include, $package->getIncludeDir()); } public function testGetIncludeDirDefaultValue() { $json = json_decode('{}'); $package = new Package($this->parser, $this->config, $json); $this->assertEquals('include', $package->getIncludeDir()); } public function testGetSourceDir() { $json = json_decode('{"source": "temp/dir"}'); $package = new Package($this->parser, $this->config, $json); $this->assertEquals($json->source, $package->getSourceDir()); } public function testGetSourceDirDefaultValue() { $json = json_decode('{}'); $package = new Package($this->parser, $this->config, $json); $this->assertEquals('src', $package->getSourceDir()); } public function testGetCompilers() { $json = json_decode('{"compiler": {"gcc": "^5.3", "clang": "*"}}'); $package = new Package($this->parser, $this->config, $json); $this->assertEquals($json->compiler, $package->getCompilers()); } public function testGetCompilersDefaultValue() { $json = json_decode('{}'); $package = new Package($this->parser, $this->config, $json); $this->assertEquals([], $package->getCompilers()); } public function testGetPlatforms() { $json = json_decode('{"platform": "windows"}'); $package = new Package($this->parser, $this->config, $json); $this->assertEquals([$json->platform], $package->getPlatforms()); } public function testGetPlatformsArray() { $json = json_decode('{"platform": ["windows", "linux", "mac"]}'); $package = new Package($this->parser, $this->config, $json); $this->assertEquals($json->platform, $package->getPlatforms()); } public function testGetPlatformsDefaultValue() { $json = json_decode('{}'); $package = new Package($this->parser, $this->config, $json); $this->assertEquals(Package::AVAILABLE_PLATFORMS, $package->getPlatforms()); } public function testGetPlatformsUnsupportedValues() { $json = json_decode('{"platform": "lorem"}'); $package = new Package($this->parser, $this->config, $json); $this->expectException(UnrecognizedPlatformException::class); $package->getPlatforms(); } public function testGetArchitectures() { $json = json_decode('{"arch": "x86"}'); $package = new Package($this->parser, $this->config, $json); $this->assertEquals([$json->arch], $package->getArchitectures()); } public function testGetArchitecturesArray() { $json = json_decode('{"arch": ["x86", "x64"]}'); $package = new Package($this->parser, $this->config, $json); $this->assertEquals($json->arch, $package->getArchitectures()); } public function testGetArchitecturesDefaultValue() { $json = json_decode('{}'); $package = new Package($this->parser, $this->config, $json); $this->assertEquals(Package::AVAILABLE_ARCHITECTURES, $package->getArchitectures()); } public function testGetArchitecturesUnsupportedValues() { $json = json_decode('{"arch": "lorem"}'); $package = new Package($this->parser, $this->config, $json); $this->expectException(UnrecognizedArchitectureException::class); $package->getArchitectures(); } public function testGetLinkingType() { $json = json_decode('{"linking": "static"}'); $package = new Package($this->parser, $this->config, $json); $this->assertEquals([$json->linking], $package->getLinkingType()); } public function testGetLinkingTypeForProject() { $json = json_decode('{"type": "project"}'); $package = new Package($this->parser, $this->config, $json); $this->expectException(InvalidTypeException::class); $package->getLinkingType(); } public function testGetLinkingTypeDefaultValue() { $json = json_decode('{}'); $package = new Package($this->parser, $this->config, $json); $this->assertEquals(Package::AVAILABLE_LINKING, $package->getLinkingType()); } public function testGetLinkingTypeUnsupportedValues() { $json = json_decode('{"linking": "lorem"}'); $package = new Package($this->parser, $this->config, $json); $this->expectException(UnrecognizedLinkingException::class); $package->getLinkingType(); } public function testIsLibrary() { $json = json_decode('{"type": "library"}'); $package = new Package($this->parser, $this->config, $json); $this->assertTrue($package->isLibrary()); } public function testIsNotLibrary() { $json = json_decode('{"type": "project"}'); $package = new Package($this->parser, $this->config, $json); $this->assertFalse($package->isLibrary()); } public function testGetName() { $json = json_decode('{"name": "org/package"}'); $package = new Package($this->parser, $this->config, $json); $this->assertEquals($json->name, $package->getName()); } public function testGetType() { $json = json_decode('{"type": "project"}'); $package = new Package($this->parser, $this->config, $json); $this->assertEquals($json->type, $package->getType()); } public function testGetTypeDefaultValue() { $json = json_decode('{}'); $package = new Package($this->parser, $this->config, $json); $this->assertEquals('library', $package->getType()); } public function testGetTypeUnsupportedValue() { $json = json_decode('{"type": "lorem"}'); $package = new Package($this->parser, $this->config, $json); $this->expectException(UnrecognizedTypeException::class); $package->getType(); } public function testGetDependencies() { $json = json_decode('{"dependencies": {"org/console": "^2.3:static", "org/hello": "*"}}'); $expected = [ (object)[ 'name' => 'org/console', 'version' => '^2.3', 'linking' => ['static'], ], (object)[ 'name' => 'org/hello', 'version' => '*', 'linking' => Package::AVAILABLE_LINKING, ], ]; $package = new Package($this->parser, $this->config, $json); $this->assertEquals($expected, $package->getDependencies()); $this->assertEquals([], $package->getDevDependencies()); } public function testGetDependenciesDefaultValue() { $json = json_decode('{}'); $package = new Package($this->parser, $this->config, $json); $this->assertEquals([], $package->getDependencies()); } public function testGetDevDependencies() { $json = json_decode('{"dev-dependencies": {"org/console": "^2.3:static", "org/hello": "*"}}'); $expected = [ (object)[ 'name' => 'org/console', 'version' => '^2.3', 'linking' => ['static'], ], (object)[ 'name' => 'org/hello', 'version' => '*', 'linking' => Package::AVAILABLE_LINKING, ], ]; $package = new Package($this->parser, $this->config, $json); $this->assertEquals($expected, $package->getDevDependencies()); $this->assertEquals([], $package->getDependencies()); } public function testGetDevDependenciesDefaultValue() { $json = json_decode('{}'); $package = new Package($this->parser, $this->config, $json); $this->assertEquals([], $package->getDevDependencies()); } public function testGetDebugDefines() { $json = json_decode('{"define": {"debug": {"DEBUG": true, "_DEBUG": true}}}'); $expected = (object)[ 'DEBUG' => true, '_DEBUG' => true, ]; $package = new Package($this->parser, $this->config, $json); $this->assertEquals($expected, $package->getDefines('debug')); } public function testGetReleaseDefines() { $json = json_decode('{"define": {"release": {"NDEBUG": true}}}'); $expected = (object)['NDEBUG' => true]; $package = new Package($this->parser, $this->config, $json); $this->assertEquals($expected, $package->getDefines('release')); } public function testGetDefinesDefaultValue() { $json = json_decode('{"define": {"release": {"NDEBUG": true}}}'); $package = new Package($this->parser, $this->config, $json); // Empty result because we get debug (not release) macros. $this->assertEquals((object)[], $package->getDefines('debug')); } public function testGetSystemScripts() { $json = json_decode('{"scripts": {"before-build": ["cmd1", "cmd2"], "after-build:windows": "rm -r cache"}}'); $expected = [ 'before-build' => ['cmd1', 'cmd2'], 'after-build' => ['rm -r cache'], ]; $package = new Package($this->parser, $this->config, $json); $this->assertEquals($expected, $package->getSystemScripts()); } public function testGetSystemScriptsDefaultValue() { $json = json_decode('{}'); $package = new Package($this->parser, $this->config, $json); $this->assertEquals([], $package->getSystemScripts()); } public function testGetScripts() { $json = json_decode('{"scripts": {"before-build": "...", "custom:x86": "..."}}'); $expected = [ 'before-build' => ['...'], 'custom' => ['...'], ]; $package = new Package($this->parser, $this->config, $json); $this->assertEquals($expected, $package->getScripts()); } public function testGetScriptsArchFilter() { $json = json_decode('{"scripts": {"s1": "...", "s2:x86": "...", "s3:x64" : "..."}}'); $expected = [ 's1' => ['...'], 's2' => ['...'], ]; $package = new Package($this->parser, $this->config, $json); $this->assertEquals($expected, $package->getScripts(['arch' => 'x86'])); } public function testGetScriptsPlatformFilter() { $json = json_decode('{"scripts": {"s1": "...", "s2:windows": "...", "s3:linux" : "..."}}'); $expected = [ 's1' => ['...'], 's2' => ['...'], ]; $package = new Package($this->parser, $this->config, $json); $this->assertEquals($expected, $package->getScripts(['platform' => 'windows'])); } public function testGetScriptsLibraryTypeFilter() { $json = json_decode('{"scripts": {"s1": "...", "s2:static": "...", "s3:dynamic" : "..."}}'); $expected = [ 's1' => ['...'], 's2' => ['...'], ]; $package = new Package($this->parser, $this->config, $json); $this->assertEquals($expected, $package->getScripts(['library' => 'static'])); } public function testGetScriptsAllFilters() { $json = json_decode('{"scripts": {"s1:x86": "...", "s2:x86,windows,static": "...", "s3:x64" : "..."}}'); $expected = [ 's1' => ['...'], 's2' => ['...'], ]; $package = new Package($this->parser, $this->config, $json); $this->assertEquals($expected, $package->getScripts([ 'arch' => 'x86', 'platform' => 'windows', 'library' => 'static', ])); } public function testGetScriptsDefaultValue() { $json = json_decode('{}'); $package = new Package($this->parser, $this->config, $json); $this->assertEquals([], $package->getScripts()); } public function testGetRepositories() { $this->config->method('get')->willReturn([]); $json = json_decode('{"repositories": [{"type": "local", "src": "temp/dir"}]}'); $package = new Package($this->parser, $this->config, $json); $this->assertEquals($json->repositories, $package->getRepositories()); } public function testGetRepositoriesValidOrder() { $defaultRepo = (object)[ "type" => "official", "src" => "https://repository.cbuilder.pl/", ]; $this->config->method('get') ->with('repositories.defaults') ->willReturn([$defaultRepo]); $json = json_decode('{"repositories": [{"type": "lorem", "src": "temp/dir"}, {"type": "lorem", "src": "temp/dir2"}]}'); $package = new Package($this->parser, $this->config, $json); $this->assertEquals($json->repositories[0], $package->getRepositories()[0]); $this->assertEquals($json->repositories[1], $package->getRepositories()[1]); $this->assertEquals($defaultRepo, $package->getRepositories()[2]); } }
mleczek/cbuilder
tests/Package/PackageTest.php
PHP
mit
14,684
package securbank.authentication; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler; import org.springframework.stereotype.Component; import securbank.services.AuthenticationService; @Component public class CustomAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler { @Autowired private AuthenticationService authService; @Override protected String determineTargetUrl(HttpServletRequest request, HttpServletResponse response) { // Get the role of logged in user Authentication auth = SecurityContextHolder.getContext().getAuthentication(); String role = auth.getAuthorities().toString(); if(role==null){ return "/"; } return authService.getRedirectUrlFromRole(role); } }
Nikh13/securbank
src/main/java/securbank/authentication/CustomAuthenticationSuccessHandler.java
Java
mit
1,123
from ..osid import records as osid_records class HierarchyRecord(osid_records.OsidRecord): """A record for a ``Hierarchy``. The methods specified by the record type are available through the underlying object. """ class HierarchyQueryRecord(osid_records.OsidRecord): """A record for a ``HierarchyQuery``. The methods specified by the record type are available through the underlying object. """ class HierarchyFormRecord(osid_records.OsidRecord): """A record for a ``HierarchyForm``. The methods specified by the record type are available through the underlying object. """ class HierarchySearchRecord(osid_records.OsidRecord): """A record for a ``HierarchySearch``. The methods specified by the record type are available through the underlying object. """
birdland/dlkit-doc
dlkit/hierarchy/records.py
Python
mit
848
/** * @ignore * Add indent and outdent command identifier for KISSY Editor. * @author yiminghe@gmail.com */ /* Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ KISSY.add(function (S, require) { var Editor = require('editor'); var ListUtils = require('./list-utils'); var listNodeNames = {ol: 1, ul: 1}, Walker = Editor.Walker, Dom = S.DOM, Node = S.Node, UA = S.UA, isNotWhitespaces = Walker.whitespaces(true), INDENT_CSS_PROPERTY = 'margin-left', INDENT_OFFSET = 40, INDENT_UNIT = 'px', isNotBookmark = Walker.bookmark(false, true); function isListItem(node) { return node.nodeType === Dom.NodeType.ELEMENT_NODE && Dom.nodeName(node) === 'li'; } function indentList(range, listNode, type) { // Our starting and ending points of the range might be inside some blocks under a list item... // So before playing with the iterator, we need to expand the block to include the list items. var startContainer = range.startContainer, endContainer = range.endContainer; while (startContainer && !startContainer.parent().equals(listNode)) { startContainer = startContainer.parent(); } while (endContainer && !endContainer.parent().equals(listNode)) { endContainer = endContainer.parent(); } if (!startContainer || !endContainer) { return; } // Now we can iterate over the individual items on the same tree depth. var block = startContainer, itemsToMove = [], stopFlag = false; while (!stopFlag) { if (block.equals(endContainer)) { stopFlag = true; } itemsToMove.push(block); block = block.next(); } if (itemsToMove.length < 1) { return; } // Do indent or outdent operations on the array model of the list, not the // list's Dom tree itself. The array model demands that it knows as much as // possible about the surrounding lists, we need to feed it the further // ancestor node that is still a list. var listParents = listNode._4eParents(true, undefined); listParents.each(function (n, i) { listParents[i] = n; }); for (var i = 0; i < listParents.length; i++) { if (listNodeNames[ listParents[i].nodeName() ]) { listNode = listParents[i]; break; } } var indentOffset = type === 'indent' ? 1 : -1, startItem = itemsToMove[0], lastItem = itemsToMove[ itemsToMove.length - 1 ], database = {}; // Convert the list Dom tree into a one dimensional array. var listArray = ListUtils.listToArray(listNode, database); // Apply indenting or outdenting on the array. // listarray_index 为 item 在数组中的下标,方便计算 var baseIndent = listArray[ lastItem.data('listarray_index') ].indent; for (i = startItem.data('listarray_index'); i <= lastItem.data('listarray_index'); i++) { listArray[ i ].indent += indentOffset; // Make sure the newly created sublist get a brand-new element of the same type. (#5372) var listRoot = listArray[ i ].parent; listArray[ i ].parent = new Node(listRoot[0].ownerDocument.createElement(listRoot.nodeName())); } /* 嵌到下层的li <li>鼠标所在开始</li> <li>ss鼠标所在结束ss <ul> <li></li> <li></li> </ul> </li> baseIndent 为鼠标所在结束的嵌套层次, 如果下面的比结束li的indent大,那么证明是嵌在结束li里面的,也要缩进 一直处理到大于或等于,跳出了当前嵌套 */ for (i = lastItem.data('listarray_index') + 1; i < listArray.length && listArray[i].indent > baseIndent; i++) { listArray[i].indent += indentOffset; } // Convert the array back to a Dom forest (yes we might have a few subtrees now). // And replace the old list with the new forest. var newList = ListUtils.arrayToList(listArray, database, null, 'p'); // Avoid nested <li> after outdent even they're visually same, // recording them for later refactoring.(#3982) var pendingList = []; var parentLiElement; if (type === 'outdent') { if (( parentLiElement = listNode.parent() ) && parentLiElement.nodeName() === 'li') { var children = newList.listNode.childNodes, count = children.length, child; for (i = count - 1; i >= 0; i--) { if (( child = new Node(children[i]) ) && child.nodeName() === 'li') { pendingList.push(child); } } } } if (newList) { Dom.insertBefore(newList.listNode[0] || newList.listNode, listNode[0] || listNode); listNode.remove(); } // Move the nested <li> to be appeared after the parent. if (pendingList && pendingList.length) { for (i = 0; i < pendingList.length; i++) { var li = pendingList[ i ], followingList = li; // Nest preceding <ul>/<ol> inside current <li> if any. while (( followingList = followingList.next() ) && followingList.nodeName() in listNodeNames) { // IE requires a filler NBSP for nested list inside empty list item, // otherwise the list item will be inaccessiable. (#4476) /*jshint loopfunc:true*/ if (UA.ie && !li.first(function (node) { return isNotWhitespaces(node) && isNotBookmark(node); }, 1)) { li[0].appendChild(range.document.createTextNode('\u00a0')); } li[0].appendChild(followingList[0]); } Dom.insertAfter(li[0], parentLiElement[0]); } } // Clean up the markers. Editor.Utils.clearAllMarkers(database); } function indentBlock(range, type) { var iterator = range.createIterator(), block; // enterMode = 'p'; iterator.enforceRealBlocks = true; iterator.enlargeBr = true; while ((block = iterator.getNextParagraph())) { indentElement(block, type); } } function indentElement(element, type) { var currentOffset = parseInt(element.style(INDENT_CSS_PROPERTY), 10); if (isNaN(currentOffset)) { currentOffset = 0; } currentOffset += ( type === 'indent' ? 1 : -1 ) * INDENT_OFFSET; if (currentOffset < 0) { return false; } currentOffset = Math.max(currentOffset, 0); currentOffset = Math.ceil(currentOffset / INDENT_OFFSET) * INDENT_OFFSET; element.css(INDENT_CSS_PROPERTY, currentOffset ? currentOffset + INDENT_UNIT : ''); if (element[0].style.cssText === '') { element.removeAttr('style'); } return true; } function indentEditor(editor, type) { var selection = editor.getSelection(), range = selection && selection.getRanges()[0]; if (!range) { return; } var startContainer = range.startContainer, endContainer = range.endContainer, rangeRoot = range.getCommonAncestor(), nearestListBlock = rangeRoot; while (nearestListBlock && !( nearestListBlock[0].nodeType === Dom.NodeType.ELEMENT_NODE && listNodeNames[ nearestListBlock.nodeName() ] )) { nearestListBlock = nearestListBlock.parent(); } var walker; // Avoid selection anchors under list root. // <ul>[<li>...</li>]</ul> => <ul><li>[...]</li></ul> //注:firefox 永远不会出现 //注2:哪种情况会出现? if (nearestListBlock && startContainer[0].nodeType === Dom.NodeType.ELEMENT_NODE && startContainer.nodeName() in listNodeNames) { walker = new Walker(range); walker.evaluator = isListItem; range.startContainer = walker.next(); } if (nearestListBlock && endContainer[0].nodeType === Dom.NodeType.ELEMENT_NODE && endContainer.nodeName() in listNodeNames) { walker = new Walker(range); walker.evaluator = isListItem; range.endContainer = walker.previous(); } var bookmarks = selection.createBookmarks(true); if (nearestListBlock) { var firstListItem = nearestListBlock.first(); while (firstListItem && firstListItem.nodeName() !== 'li') { firstListItem = firstListItem.next(); } var rangeStart = range.startContainer, indentWholeList = firstListItem[0] === rangeStart[0] || firstListItem.contains(rangeStart); // Indent the entire list if cursor is inside the first list item. (#3893) if (!( indentWholeList && indentElement(nearestListBlock, type) )) { indentList(range, nearestListBlock, type); } } else { indentBlock(range, type); } selection.selectBookmarks(bookmarks); } function addCommand(editor, cmdType) { if (!editor.hasCommand(cmdType)) { editor.addCommand(cmdType, { exec: function (editor) { editor.execCommand('save'); indentEditor(editor, cmdType); editor.execCommand('save'); editor.notifySelectionChange(); } }); } } return { checkOutdentActive: function (elementPath) { var blockLimit = elementPath.blockLimit; if (elementPath.contains(listNodeNames)) { return true; } else { var block = elementPath.block || blockLimit; return block && block.style(INDENT_CSS_PROPERTY); } }, addCommand: addCommand }; });
tedyhy/SCI
kissy-1.4.9/src/editor/sub-modules/plugin/dent-cmd/src/dent-cmd.js
JavaScript
mit
10,700
package main import ( "database/sql" "fmt" "github.com/jrallison/go-workers" "github.com/lib/pq" "log" "time" ) func WorkerExtractPgerror(err error) (*string, error) { pgerr, ok := err.(pq.PGError) if ok { msg := pgerr.Get('M') return &msg, nil } if err.Error() == "driver: bad connection" { msg := "could not connect to database" return &msg, nil } return nil, err } // WorkerCoerceType returns a coerced version of the raw // database value in, which we get from scanning into // interface{}s. We expect queries from the following // Postgres types to result in the following return values: // [Postgres] -> [Go: in] -> [Go: WorkerCoerceType'd] // text []byte string // ??? func WorkerCoerceType(in interface{}) interface{} { switch in := in.(type) { case []byte: return string(in) default: return in } } // WorkerQuery queries the pin db at pinDbUrl and updates the // passed pin according to the results/errors. System errors // are returned. func WorkerQuery(p *Pin, pinDbUrl string) error { log.Printf("worker.query.start pin_id=%s", p.Id) applicationName := fmt.Sprintf("pgpin.pin.%s", p.Id) pinDbConn := fmt.Sprintf("%s?application_name=%s&statement_timeout=%d&connect_timeout=%d", pinDbUrl, applicationName, ConfigPinStatementTimeout/time.Millisecond, ConfigDatabaseConnectTimeout/time.Millisecond) pinDb, err := sql.Open("postgres", pinDbConn) if err != nil { p.ResultsError, err = WorkerExtractPgerror(err) return err } resultsRows, err := pinDb.Query(p.Query) if err != nil { p.ResultsError, err = WorkerExtractPgerror(err) return err } defer func() { Must(resultsRows.Close()) }() resultsFieldsData, err := resultsRows.Columns() if err != nil { p.ResultsError, err = WorkerExtractPgerror(err) return err } resultsRowsData := make([][]interface{}, 0) resultsRowsSeen := 0 for resultsRows.Next() { resultsRowsSeen += 1 if resultsRowsSeen > ConfigPinResultsRowsMax { message := "too many rows in query results" p.ResultsError = &message return nil } resultsRowData := make([]interface{}, len(resultsFieldsData)) resultsRowPointers := make([]interface{}, len(resultsFieldsData)) for i, _ := range resultsRowData { resultsRowPointers[i] = &resultsRowData[i] } err := resultsRows.Scan(resultsRowPointers...) if err != nil { p.ResultsError, err = WorkerExtractPgerror(err) return err } for i, _ := range resultsRowData { resultsRowData[i] = WorkerCoerceType(resultsRowData[i]) } resultsRowsData = append(resultsRowsData, resultsRowData) } err = resultsRows.Err() if err != nil { p.ResultsError, err = WorkerExtractPgerror(err) return err } p.ResultsFields = MustNewPgJson(resultsFieldsData) p.ResultsRows = MustNewPgJson(resultsRowsData) log.Printf("worker.query.finish pin_id=%s", p.Id) return nil } func WorkerProcess(jobId string, pinId string) error { log.Printf("worker.job.start job_id=%s pin_id=%s", jobId, pinId) pin, err := PinGet(pinId) if err != nil { return err } pinDbUrl, err := PinDbUrl(pin) if err != nil { return err } startedAt := time.Now() pin.QueryStartedAt = &startedAt err = WorkerQuery(pin, pinDbUrl) if err != nil { return err } finishedAt := time.Now() pin.QueryFinishedAt = &finishedAt err = PinUpdate(pin) if err != nil { return err } log.Printf("worker.job.finish job_id=%s pin_id=%s", jobId, pinId) return nil } func WorkerProcessWrapper(msg *workers.Msg) { jobId := msg.Jid() pinId, err := msg.Args().String() Must(err) err = WorkerProcess(jobId, pinId) if err != nil { log.Printf("worker.job.error job_id=%s pin_id=%s %s", jobId, pinId, err) } } func WorkerStart() { log.Printf("worker.start") PgStart() RedisStart() workers.Process("pins", WorkerProcessWrapper, ConfigWorkerPoolSize) workers.Run() }
mmcgrana/pgpin
worker.go
GO
mit
3,817
require 'test_helper' class GiftRegistryTest < ActiveSupport::TestCase # test "the truth" do # assert true # end end
robertleelittleiii/silverweb_bridereg
test/models/gift_registry_test.rb
Ruby
mit
126
/************************************************************************************ Copyright : Copyright 2014 Oculus VR, LLC. All Rights reserved. Licensed under the Oculus VR Rift SDK License Version 3.3 (the "License"); you may not use the Oculus VR Rift SDK except in compliance with the License, which is provided at the time of installation or download, or which otherwise accompanies this software in either electronic or hard copy form. You may obtain a copy of the License at http://www.oculus.com/licenses/LICENSE-3.3 Unless required by applicable law or agreed to in writing, the Oculus VR SDK distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ************************************************************************************/ #if !UNITY_5 || UNITY_5_0 #error Oculus Utilities require Unity 5.1 or higher. #endif using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using UnityEngine; using VR = UnityEngine.VR; /// <summary> /// Configuration data for Oculus virtual reality. /// </summary> public class OVRManager : MonoBehaviour { public enum TrackingOrigin { EyeLevel = OVRPlugin.TrackingOrigin.EyeLevel, FloorLevel = OVRPlugin.TrackingOrigin.FloorLevel, } /// <summary> /// Gets the singleton instance. /// </summary> public static OVRManager instance { get; private set; } /// <summary> /// Gets a reference to the active display. /// </summary> public static OVRDisplay display { get; private set; } /// <summary> /// Gets a reference to the active sensor. /// </summary> public static OVRTracker tracker { get; private set; } private static bool _profileIsCached = false; private static OVRProfile _profile; /// <summary> /// Gets the current profile, which contains information about the user's settings and body dimensions. /// </summary> public static OVRProfile profile { get { if (!_profileIsCached) { _profile = new OVRProfile(); _profile.TriggerLoad(); while (_profile.state == OVRProfile.State.LOADING) System.Threading.Thread.Sleep(1); if (_profile.state != OVRProfile.State.READY) Debug.LogWarning("Failed to load profile."); _profileIsCached = true; } return _profile; } } private bool _isPaused; private IEnumerable<Camera> disabledCameras; float prevTimeScale; private bool paused { get { return _isPaused; } set { if (value == _isPaused) return; // Sample code to handle VR Focus // if (value) // { // prevTimeScale = Time.timeScale; // Time.timeScale = 0.01f; // disabledCameras = GameObject.FindObjectsOfType<Camera>().Where(c => c.isActiveAndEnabled); // foreach (var cam in disabledCameras) // cam.enabled = false; // } // else // { // Time.timeScale = prevTimeScale; // if (disabledCameras != null) { // foreach (var cam in disabledCameras) // cam.enabled = true; // } // disabledCameras = null; // } _isPaused = value; } } /// <summary> /// Occurs when an HMD attached. /// </summary> public static event Action HMDAcquired; /// <summary> /// Occurs when an HMD detached. /// </summary> public static event Action HMDLost; /// <summary> /// Occurs when an HMD is put on the user's head. /// </summary> public static event Action HMDMounted; /// <summary> /// Occurs when an HMD is taken off the user's head. /// </summary> public static event Action HMDUnmounted; /// <summary> /// Occurs when VR Focus is acquired. /// </summary> public static event Action VrFocusAcquired; /// <summary> /// Occurs when VR Focus is lost. /// </summary> public static event Action VrFocusLost; /// <summary> /// Occurs when the active Audio Out device has changed and a restart is needed. /// </summary> public static event Action AudioOutChanged; /// <summary> /// Occurs when the active Audio In device has changed and a restart is needed. /// </summary> public static event Action AudioInChanged; /// <summary> /// Occurs when the sensor gained tracking. /// </summary> public static event Action TrackingAcquired; /// <summary> /// Occurs when the sensor lost tracking. /// </summary> public static event Action TrackingLost; /// <summary> /// Occurs when HSW dismissed. /// </summary> public static event Action HSWDismissed; private static bool _isHmdPresentCached = false; private static bool _isHmdPresent = false; private static bool _wasHmdPresent = false; /// <summary> /// If true, a head-mounted display is connected and present. /// </summary> public static bool isHmdPresent { get { if (!_isHmdPresentCached) { _isHmdPresentCached = true; _isHmdPresent = OVRPlugin.hmdPresent; } return _isHmdPresent; } private set { _isHmdPresentCached = true; _isHmdPresent = value; } } /// <summary> /// Gets the audio output device identifier. /// </summary> /// <description> /// On Windows, this is a string containing the GUID of the IMMDevice for the Windows audio endpoint to use. /// </description> public static string audioOutId { get { return OVRPlugin.audioOutId; } } /// <summary> /// Gets the audio input device identifier. /// </summary> /// <description> /// On Windows, this is a string containing the GUID of the IMMDevice for the Windows audio endpoint to use. /// </description> public static string audioInId { get { return OVRPlugin.audioInId; } } private static bool _hasVrFocusCached = false; private static bool _hasVrFocus = false; private static bool _hadVrFocus = false; /// <summary> /// If true, the app has VR Focus. /// </summary> public static bool hasVrFocus { get { if (!_hasVrFocusCached) { _hasVrFocusCached = true; _hasVrFocus = OVRPlugin.hasVrFocus; } return _hasVrFocus; } private set { _hasVrFocusCached = true; _hasVrFocus = value; } } private static bool _isHSWDisplayedCached = false; private static bool _isHSWDisplayed = false; private static bool _wasHSWDisplayed; /// <summary> /// If true, then the Oculus health and safety warning (HSW) is currently visible. /// </summary> public static bool isHSWDisplayed { get { if (!isHmdPresent) return false; if (!_isHSWDisplayedCached) { _isHSWDisplayedCached = true; _isHSWDisplayed = OVRPlugin.hswVisible; } return _isHSWDisplayed; } private set { _isHSWDisplayedCached = true; _isHSWDisplayed = value; } } /// <summary> /// If the HSW has been visible for the necessary amount of time, this will make it disappear. /// </summary> public static void DismissHSWDisplay() { if (!isHmdPresent) return; OVRPlugin.DismissHSW(); } /// <summary> /// If true, chromatic de-aberration will be applied, improving the image at the cost of texture bandwidth. /// </summary> public bool chromatic { get { if (!isHmdPresent) return false; return OVRPlugin.chromatic; } set { if (!isHmdPresent) return; OVRPlugin.chromatic = value; } } /// <summary> /// If true, both eyes will see the same image, rendered from the center eye pose, saving performance. /// </summary> public bool monoscopic { get { if (!isHmdPresent) return true; return OVRPlugin.monoscopic; } set { if (!isHmdPresent) return; OVRPlugin.monoscopic = value; } } /// <summary> /// If true, distortion rendering work is submitted a quarter-frame early to avoid pipeline stalls and increase CPU-GPU parallelism. /// </summary> public bool queueAhead = true; /// <summary> /// If true, Unity will use the optimal antialiasing level for quality/performance on the current hardware. /// </summary> public bool useRecommendedMSAALevel = true; /// <summary> /// If true, dynamic resolution will be enabled /// </summary> public bool enableAdaptiveResolution = false; /// <summary> /// Max RenderScale the app can reach under adaptive resolution mode ( enableAdaptiveResolution = ture ); /// </summary> [RangeAttribute(0.5f, 2.0f)] public float maxRenderScale = 1.0f; /// <summary> /// Min RenderScale the app can reach under adaptive resolution mode ( enableAdaptiveResolution = ture ); /// </summary> [RangeAttribute(0.5f, 2.0f)] public float minRenderScale = 0.7f; /// <summary> /// The number of expected display frames per rendered frame. /// </summary> public int vsyncCount { get { if (!isHmdPresent) return 1; return OVRPlugin.vsyncCount; } set { if (!isHmdPresent) return; OVRPlugin.vsyncCount = value; } } /// <summary> /// Gets the current battery level. /// </summary> /// <returns><c>battery level in the range [0.0,1.0]</c> /// <param name="batteryLevel">Battery level.</param> public static float batteryLevel { get { if (!isHmdPresent) return 1f; return OVRPlugin.batteryLevel; } } /// <summary> /// Gets the current battery temperature. /// </summary> /// <returns><c>battery temperature in Celsius</c> /// <param name="batteryTemperature">Battery temperature.</param> public static float batteryTemperature { get { if (!isHmdPresent) return 0f; return OVRPlugin.batteryTemperature; } } /// <summary> /// Gets the current battery status. /// </summary> /// <returns><c>battery status</c> /// <param name="batteryStatus">Battery status.</param> public static int batteryStatus { get { if (!isHmdPresent) return -1; return (int)OVRPlugin.batteryStatus; } } /// <summary> /// Gets the current volume level. /// </summary> /// <returns><c>volume level in the range [0,1].</c> public static float volumeLevel { get { if (!isHmdPresent) return 0f; return OVRPlugin.systemVolume; } } /// <summary> /// Gets or sets the current CPU performance level (0-2). Lower performance levels save more power. /// </summary> public static int cpuLevel { get { if (!isHmdPresent) return 2; return OVRPlugin.cpuLevel; } set { if (!isHmdPresent) return; OVRPlugin.cpuLevel = value; } } /// <summary> /// Gets or sets the current GPU performance level (0-2). Lower performance levels save more power. /// </summary> public static int gpuLevel { get { if (!isHmdPresent) return 2; return OVRPlugin.gpuLevel; } set { if (!isHmdPresent) return; OVRPlugin.gpuLevel = value; } } /// <summary> /// If true, the CPU and GPU are currently throttled to save power and/or reduce the temperature. /// </summary> public static bool isPowerSavingActive { get { if (!isHmdPresent) return false; return OVRPlugin.powerSaving; } } [SerializeField] private OVRManager.TrackingOrigin _trackingOriginType = OVRManager.TrackingOrigin.EyeLevel; /// <summary> /// Defines the current tracking origin type. /// </summary> public OVRManager.TrackingOrigin trackingOriginType { get { if (!isHmdPresent) return _trackingOriginType; return (OVRManager.TrackingOrigin)OVRPlugin.GetTrackingOriginType(); } set { if (!isHmdPresent) return; if (OVRPlugin.SetTrackingOriginType((OVRPlugin.TrackingOrigin)value)) { // Keep the field exposed in the Unity Editor synchronized with any changes. _trackingOriginType = value; } } } /// <summary> /// If true, head tracking will affect the position of each OVRCameraRig's cameras. /// </summary> public bool usePositionTracking = true; /// <summary> /// If true, the distance between the user's eyes will affect the position of each OVRCameraRig's cameras. /// </summary> public bool useIPDInPositionTracking = true; /// <summary> /// If true, each scene load will cause the head pose to reset. /// </summary> public bool resetTrackerOnLoad = false; /// <summary> /// True if the current platform supports virtual reality. /// </summary> public bool isSupportedPlatform { get; private set; } private static bool _isUserPresentCached = false; private static bool _isUserPresent = false; private static bool _wasUserPresent = false; /// <summary> /// True if the user is currently wearing the display. /// </summary> public bool isUserPresent { get { if (!_isUserPresentCached) { _isUserPresentCached = true; _isUserPresent = OVRPlugin.userPresent; } return _isUserPresent; } private set { _isUserPresentCached = true; _isUserPresent = value; } } private static bool prevAudioOutIdIsCached = false; private static bool prevAudioInIdIsCached = false; private static string prevAudioOutId = string.Empty; private static string prevAudioInId = string.Empty; private static bool wasPositionTracked = false; [SerializeField] [HideInInspector] internal static bool runInBackground = false; #region Unity Messages private void Awake() { // Only allow one instance at runtime. if (instance != null) { enabled = false; DestroyImmediate(this); return; } instance = this; Debug.Log("Unity v" + Application.unityVersion + ", " + "Oculus Utilities v" + OVRPlugin.wrapperVersion + ", " + "OVRPlugin v" + OVRPlugin.version + ", " + "SDK v" + OVRPlugin.nativeSDKVersion + "."); #if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN if (SystemInfo.graphicsDeviceType != UnityEngine.Rendering.GraphicsDeviceType.Direct3D11) Debug.LogWarning("VR rendering requires Direct3D11. Your graphics device: " + SystemInfo.graphicsDeviceType); #endif // Detect whether this platform is a supported platform RuntimePlatform currPlatform = Application.platform; isSupportedPlatform |= currPlatform == RuntimePlatform.Android; //isSupportedPlatform |= currPlatform == RuntimePlatform.LinuxPlayer; isSupportedPlatform |= currPlatform == RuntimePlatform.OSXEditor; isSupportedPlatform |= currPlatform == RuntimePlatform.OSXPlayer; isSupportedPlatform |= currPlatform == RuntimePlatform.WindowsEditor; isSupportedPlatform |= currPlatform == RuntimePlatform.WindowsPlayer; if (!isSupportedPlatform) { Debug.LogWarning("This platform is unsupported"); return; } #if UNITY_ANDROID && !UNITY_EDITOR // We want to set up our touchpad messaging system OVRTouchpad.Create(); // Turn off chromatic aberration by default to save texture bandwidth. chromatic = false; #endif if (display == null) display = new OVRDisplay(); if (tracker == null) tracker = new OVRTracker(); if (resetTrackerOnLoad) display.RecenterPose(); // Disable the occlusion mesh by default until open issues with the preview window are resolved. OVRPlugin.occlusionMesh = false; OVRPlugin.ignoreVrFocus = runInBackground; } private void Update() { #if !UNITY_EDITOR paused = !OVRPlugin.hasVrFocus; #endif if (OVRPlugin.shouldQuit) Application.Quit(); if (OVRPlugin.shouldRecenter) OVRManager.display.RecenterPose(); if (trackingOriginType != _trackingOriginType) trackingOriginType = _trackingOriginType; tracker.isEnabled = usePositionTracking; OVRPlugin.useIPDInPositionTracking = useIPDInPositionTracking; // Dispatch HMD events. isHmdPresent = OVRPlugin.hmdPresent; if (isHmdPresent) { OVRPlugin.queueAheadFraction = (queueAhead) ? 0.25f : 0f; } if (useRecommendedMSAALevel && QualitySettings.antiAliasing != display.recommendedMSAALevel) { QualitySettings.antiAliasing = display.recommendedMSAALevel; Debug.Log ("MSAA level: " + QualitySettings.antiAliasing); } if (_wasHmdPresent && !isHmdPresent) { try { if (HMDLost != null) HMDLost(); } catch (Exception e) { Debug.LogError("Caught Exception: " + e); } } if (!_wasHmdPresent && isHmdPresent) { try { if (HMDAcquired != null) HMDAcquired(); } catch (Exception e) { Debug.LogError("Caught Exception: " + e); } } _wasHmdPresent = isHmdPresent; // Dispatch HMD mounted events. isUserPresent = OVRPlugin.userPresent; if (_wasUserPresent && !isUserPresent) { try { if (HMDUnmounted != null) HMDUnmounted(); } catch (Exception e) { Debug.LogError("Caught Exception: " + e); } } if (!_wasUserPresent && isUserPresent) { try { if (HMDMounted != null) HMDMounted(); } catch (Exception e) { Debug.LogError("Caught Exception: " + e); } } _wasUserPresent = isUserPresent; // Dispatch VR Focus events. hasVrFocus = OVRPlugin.hasVrFocus; if (_hadVrFocus && !hasVrFocus) { try { if (VrFocusLost != null) VrFocusLost(); } catch (Exception e) { Debug.LogError("Caught Exception: " + e); } } if (!_hadVrFocus && hasVrFocus) { try { if (VrFocusAcquired != null) VrFocusAcquired(); } catch (Exception e) { Debug.LogError("Caught Exception: " + e); } } _hadVrFocus = hasVrFocus; // Changing effective rendering resolution dynamically according performance #if (UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN) && UNITY_5 && !(UNITY_5_0 || UNITY_5_1 || UNITY_5_2 || UNITY_5_3) if (enableAdaptiveResolution) { if (VR.VRSettings.renderScale < maxRenderScale) { // Allocate renderScale to max to avoid re-allocation VR.VRSettings.renderScale = maxRenderScale; } else { // Adjusting maxRenderScale in case app started with a larger renderScale value maxRenderScale = Mathf.Max(maxRenderScale, VR.VRSettings.renderScale); } float minViewportScale = minRenderScale / VR.VRSettings.renderScale; float recommendedViewportScale = OVRPlugin.GetEyeRecommendedResolutionScale() / VR.VRSettings.renderScale; recommendedViewportScale = Mathf.Clamp(recommendedViewportScale, minViewportScale, 1.0f); VR.VRSettings.renderViewportScale = recommendedViewportScale; } #endif // Dispatch Audio Device events. string audioOutId = OVRPlugin.audioOutId; if (!prevAudioOutIdIsCached) { prevAudioOutId = audioOutId; prevAudioOutIdIsCached = true; } else if (audioOutId != prevAudioOutId) { try { if (AudioOutChanged != null) AudioOutChanged(); } catch (Exception e) { Debug.LogError("Caught Exception: " + e); } prevAudioOutId = audioOutId; } string audioInId = OVRPlugin.audioInId; if (!prevAudioInIdIsCached) { prevAudioInId = audioInId; prevAudioInIdIsCached = true; } else if (audioInId != prevAudioInId) { try { if (AudioInChanged != null) AudioInChanged(); } catch (Exception e) { Debug.LogError("Caught Exception: " + e); } prevAudioInId = audioInId; } // Dispatch tracking events. if (wasPositionTracked && !tracker.isPositionTracked) { try { if (TrackingLost != null) TrackingLost(); } catch (Exception e) { Debug.LogError("Caught Exception: " + e); } } if (!wasPositionTracked && tracker.isPositionTracked) { try { if (TrackingAcquired != null) TrackingAcquired(); } catch (Exception e) { Debug.LogError("Caught Exception: " + e); } } wasPositionTracked = tracker.isPositionTracked; // Dispatch HSW events. isHSWDisplayed = OVRPlugin.hswVisible; if (isHSWDisplayed && Input.anyKeyDown) DismissHSWDisplay(); if (!isHSWDisplayed && _wasHSWDisplayed) { try { if (HSWDismissed != null) HSWDismissed(); } catch (Exception e) { Debug.LogError("Caught Exception: " + e); } } _wasHSWDisplayed = isHSWDisplayed; display.Update(); OVRInput.Update(); } private void LateUpdate() { OVRHaptics.Process(); } /// <summary> /// Leaves the application/game and returns to the launcher/dashboard /// </summary> public void ReturnToLauncher() { // show the platform UI quit prompt OVRManager.PlatformUIConfirmQuit(); } #endregion public static void PlatformUIConfirmQuit() { if (!isHmdPresent) return; OVRPlugin.ShowUI(OVRPlugin.PlatformUI.ConfirmQuit); } public static void PlatformUIGlobalMenu() { if (!isHmdPresent) return; OVRPlugin.ShowUI(OVRPlugin.PlatformUI.GlobalMenu); } }
michel-zimmer/smartpad-hoverboard
Assets/OVR/Scripts/OVRManager.cs
C#
mit
20,634
""" homeassistant.components.device_tracker.tplink ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Device tracker platform that supports scanning a TP-Link router for device presence. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/device_tracker.tplink.html """ import base64 import logging from datetime import timedelta import re import threading import requests from homeassistant.const import CONF_HOST, CONF_USERNAME, CONF_PASSWORD from homeassistant.helpers import validate_config from homeassistant.util import Throttle from homeassistant.components.device_tracker import DOMAIN # Return cached results if last scan was less then this time ago MIN_TIME_BETWEEN_SCANS = timedelta(seconds=5) _LOGGER = logging.getLogger(__name__) def get_scanner(hass, config): """ Validates config and returns a TP-Link scanner. """ if not validate_config(config, {DOMAIN: [CONF_HOST, CONF_USERNAME, CONF_PASSWORD]}, _LOGGER): return None scanner = Tplink3DeviceScanner(config[DOMAIN]) if not scanner.success_init: scanner = Tplink2DeviceScanner(config[DOMAIN]) if not scanner.success_init: scanner = TplinkDeviceScanner(config[DOMAIN]) return scanner if scanner.success_init else None class TplinkDeviceScanner(object): """ This class queries a wireless router running TP-Link firmware for connected devices. """ def __init__(self, config): host = config[CONF_HOST] username, password = config[CONF_USERNAME], config[CONF_PASSWORD] self.parse_macs = re.compile('[0-9A-F]{2}-[0-9A-F]{2}-[0-9A-F]{2}-' + '[0-9A-F]{2}-[0-9A-F]{2}-[0-9A-F]{2}') self.host = host self.username = username self.password = password self.last_results = {} self.lock = threading.Lock() self.success_init = self._update_info() def scan_devices(self): """ Scans for new devices and return a list containing found device ids. """ self._update_info() return self.last_results # pylint: disable=no-self-use def get_device_name(self, device): """ The TP-Link firmware doesn't save the name of the wireless device. """ return None @Throttle(MIN_TIME_BETWEEN_SCANS) def _update_info(self): """ Ensures the information from the TP-Link router is up to date. Returns boolean if scanning successful. """ with self.lock: _LOGGER.info("Loading wireless clients...") url = 'http://{}/userRpm/WlanStationRpm.htm'.format(self.host) referer = 'http://{}'.format(self.host) page = requests.get(url, auth=(self.username, self.password), headers={'referer': referer}) result = self.parse_macs.findall(page.text) if result: self.last_results = [mac.replace("-", ":") for mac in result] return True return False class Tplink2DeviceScanner(TplinkDeviceScanner): """ This class queries a wireless router running newer version of TP-Link firmware for connected devices. """ def scan_devices(self): """ Scans for new devices and return a list containing found device ids. """ self._update_info() return self.last_results.keys() # pylint: disable=no-self-use def get_device_name(self, device): """ The TP-Link firmware doesn't save the name of the wireless device. """ return self.last_results.get(device) @Throttle(MIN_TIME_BETWEEN_SCANS) def _update_info(self): """ Ensures the information from the TP-Link router is up to date. Returns boolean if scanning successful. """ with self.lock: _LOGGER.info("Loading wireless clients...") url = 'http://{}/data/map_access_wireless_client_grid.json' \ .format(self.host) referer = 'http://{}'.format(self.host) # Router uses Authorization cookie instead of header # Let's create the cookie username_password = '{}:{}'.format(self.username, self.password) b64_encoded_username_password = base64.b64encode( username_password.encode('ascii') ).decode('ascii') cookie = 'Authorization=Basic {}' \ .format(b64_encoded_username_password) response = requests.post(url, headers={'referer': referer, 'cookie': cookie}) try: result = response.json().get('data') except ValueError: _LOGGER.error("Router didn't respond with JSON. " "Check if credentials are correct.") return False if result: self.last_results = { device['mac_addr'].replace('-', ':'): device['name'] for device in result } return True return False class Tplink3DeviceScanner(TplinkDeviceScanner): """ This class queries the Archer C9 router running version 150811 or higher of TP-Link firmware for connected devices. """ def __init__(self, config): self.stok = '' self.sysauth = '' super(Tplink3DeviceScanner, self).__init__(config) def scan_devices(self): """ Scans for new devices and return a list containing found device ids. """ self._update_info() return self.last_results.keys() # pylint: disable=no-self-use def get_device_name(self, device): """ The TP-Link firmware doesn't save the name of the wireless device. We are forced to use the MAC address as name here. """ return self.last_results.get(device) def _get_auth_tokens(self): """ Retrieves auth tokens from the router. """ _LOGGER.info("Retrieving auth tokens...") url = 'http://{}/cgi-bin/luci/;stok=/login?form=login' \ .format(self.host) referer = 'http://{}/webpages/login.html'.format(self.host) # if possible implement rsa encryption of password here response = requests.post(url, params={'operation': 'login', 'username': self.username, 'password': self.password}, headers={'referer': referer}) try: self.stok = response.json().get('data').get('stok') _LOGGER.info(self.stok) regex_result = re.search('sysauth=(.*);', response.headers['set-cookie']) self.sysauth = regex_result.group(1) _LOGGER.info(self.sysauth) return True except ValueError: _LOGGER.error("Couldn't fetch auth tokens!") return False @Throttle(MIN_TIME_BETWEEN_SCANS) def _update_info(self): """ Ensures the information from the TP-Link router is up to date. Returns boolean if scanning successful. """ with self.lock: if (self.stok == '') or (self.sysauth == ''): self._get_auth_tokens() _LOGGER.info("Loading wireless clients...") url = 'http://{}/cgi-bin/luci/;stok={}/admin/wireless?form=statistics' \ .format(self.host, self.stok) referer = 'http://{}/webpages/index.html'.format(self.host) response = requests.post(url, params={'operation': 'load'}, headers={'referer': referer}, cookies={'sysauth': self.sysauth}) try: json_response = response.json() if json_response.get('success'): result = response.json().get('data') else: if json_response.get('errorcode') == 'timeout': _LOGGER.info("Token timed out. " "Relogging on next scan.") self.stok = '' self.sysauth = '' return False else: _LOGGER.error("An unknown error happened " "while fetching data.") return False except ValueError: _LOGGER.error("Router didn't respond with JSON. " "Check if credentials are correct.") return False if result: self.last_results = { device['mac'].replace('-', ':'): device['mac'] for device in result } return True return False
pottzer/home-assistant
homeassistant/components/device_tracker/tplink.py
Python
mit
9,226
require 'rails_helper' feature 'User can visit the home page' do scenario 'and see upcoming events on the home page' do events = create_list(:event_with_registrations, 2) visit root_path expect(page).to have_content('Upcoming events') expect(page).to have_content(events.first.title) expect(page).to have_content(events.second.title) end scenario 'Can access sign in / sign up page' do visit root_path expect(page).to have_content('Sign in') end scenario 'can view sign in form' do visit new_user_session_path expect(page).to have_content('Enter your e-mail') expect(page).to have_content('Login') expect(page).to have_content('Sign up') expect(page).to have_content('Forgot your password?') expect(page).to have_content("Didn't receive confirmation instructions?") end scenario 'can view sign up form with all appropriate fields' do visit new_user_registration_path expect(page).to have_content('Sign up') expect(find_by_id('user_name').native.attributes['placeholder'].value).to eq 'Enter name' expect(find_by_id('user_gender').native.children[0].children.text).to eq 'Select gender' expect(find_by_id('user_age').native.children[0].children.text).to eq 'Select your age' expect(find_by_id('user_grade').native.children[0].children.text).to eq 'Select your grade' expect(find_by_id('user_locality_id').native.children[0].children.text).to eq 'Select locality' expect(find_by_id('user_email').native.attributes['placeholder'].value).to eq 'Enter email' expect(find_by_id('user_password').native.attributes['placeholder'].value).to eq 'Enter password' expect(find_by_id('user_password_confirmation').native.attributes['placeholder'].value).to eq 'Enter password confirmation' end end
stephen144/ypreg
spec/features/user_visits_site_spec.rb
Ruby
mit
1,800
// # Settings Test // Test the various tabs on the settings page /*globals CasperTest, casper */ // These classes relate to elements which only appear when a given tab is loaded. // These are used to check that a switch to a tab is complete, or that we are on the right tab. var generalTabDetector = '.settings-content form#settings-general', userTabDetector = '.settings-content form.user-profile'; // CasperTest.emberBegin('Settings screen is correct', 17, function suite(test) { casper.thenOpenAndWaitForPageLoad('settings', function testTitleAndUrl() { test.assertTitle('Ghost Admin', 'Ghost admin has no title'); test.assertUrlMatch(/ghost\/ember\/settings\/general\/$/, 'Landed on the correct URL'); }); casper.then(function testViews() { test.assertExists('.wrapper', 'Settings main view is present'); test.assertExists('.settings-sidebar', 'Settings sidebar view is present'); test.assertExists('.settings-menu', 'Settings menu is present'); test.assertExists('.settings-menu .general', 'General tab is present'); test.assertExists('.settings-menu .users', 'Users tab is present'); test.assertNotExists('.settings-menu .apps', 'Apps is present'); test.assertExists('.wrapper', 'Settings main view is present'); test.assertExists('.settings-content', 'Settings content view is present'); test.assertExists('.settings-menu .general.active', 'General tab is marked active'); test.assertExists(generalTabDetector, 'Form is present'); test.assertSelectorHasText('.settings-content.active h2.title', 'General', 'Title is general'); }); casper.then(function testSwitchingTabs() { casper.thenClick('.settings-menu .users a'); casper.waitForSelector(userTabDetector, function then () { // assert that the right menu item is active test.assertExists('.settings-menu .users.active', 'User tab is active'); test.assertDoesntExist('.settings-menu .general.active', 'General tab is not active'); }, casper.failOnTimeout(test, 'waitForSelector `userTabDetector` timed out')); casper.thenClick('.settings-menu .general a'); casper.waitForSelector(generalTabDetector, function then () { // assert that the right menu item is active test.assertExists('.settings-menu .general.active', 'General tab is active'); test.assertDoesntExist('.settings-menu .users.active', 'User tab is not active'); }, casper.failOnTimeout(test, 'waitForSelector `generalTabDetector` timed out')); }); }); // ## General settings tests CasperTest.emberBegin('General settings pane is correct', 8, function suite(test) { casper.thenOpenAndWaitForPageLoad('settings.general', function testTitleAndUrl() { test.assertTitle('Ghost Admin', 'Ghost admin has no title'); test.assertUrlMatch(/ghost\/ember\/settings\/general\/$/, 'Landed on the correct URL'); }); function assertImageUploaderModalThenClose() { test.assertSelectorHasText('.description', 'Add image'); casper.click('#modal-container .js-button-accept'); casper.waitForSelector('.notification-success', function onSuccess() { test.assert(true, 'Got success notification'); }, casper.failOnTimeout(test, 'No success notification')); } // Ensure image upload modals display correctly // Test Blog Logo Upload Button casper.waitForSelector('.js-modal-logo', function () { casper.click('.js-modal-logo'); }); casper.waitForSelector('#modal-container .modal-content .js-drop-zone .description', assertImageUploaderModalThenClose, casper.failOnTimeout(test, 'No upload logo modal container appeared')); // Test Blog Cover Upload Button casper.waitForSelector('.js-modal-cover', function () { casper.click('.js-modal-cover'); }); casper.waitForSelector('#modal-container .modal-content .js-drop-zone .description', assertImageUploaderModalThenClose, casper.failOnTimeout(test, 'No upload cover modal container appeared')); function handleSettingsRequest(requestData) { // make sure we only get requests from the user pane if (requestData.url.indexOf('users/') !== -1) { test.fail('Saving a settings pane triggered the user pane to save'); } } casper.then(function listenForRequests() { casper.on('resource.requested', handleSettingsRequest); }); // Ensure can save casper.waitForSelector('header .button-save').then(function () { casper.thenClick('header .button-save').waitFor(function successNotification() { return this.evaluate(function () { return document.querySelectorAll('.js-bb-notification section').length > 0; }); }, function doneWaiting() { test.pass('Waited for notification'); }, casper.failOnTimeout(test, 'Saving the general pane did not result in a notification')); }); casper.then(function checkSettingsWereSaved() { casper.removeListener('resource.requested', handleSettingsRequest); }); casper.waitForSelector('.notification-success', function onSuccess() { test.assert(true, 'Got success notification'); }, casper.failOnTimeout(test, 'No success notification :(')); }); //// ## General settings validations tests CasperTest.emberBegin('General settings validation is correct', 7, function suite(test) { casper.thenOpenAndWaitForPageLoad('settings.general', function testTitleAndUrl() { test.assertTitle('Ghost Admin', 'Ghost admin has no title'); test.assertUrlMatch(/ghost\/ember\/settings\/general\/$/, 'Landed on the correct URL'); }); // Ensure general blog title field length validation casper.fillAndSave('form#settings-general', { 'general[title]': new Array(152).join('a') }); casper.waitForSelectorTextChange('.notification-error', function onSuccess() { test.assertSelectorHasText('.notification-error', 'too long'); }, casper.failOnTimeout(test, 'Blog title length error did not appear'), 2000); casper.thenClick('.js-bb-notification .close'); // Ensure general blog description field length validation casper.fillAndSave('form#settings-general', { 'general[description]': new Array(202).join('a') }); casper.waitForSelectorTextChange('.notification-error', function onSuccess() { test.assertSelectorHasText('.notification-error', 'too long'); }, casper.failOnTimeout(test, 'Blog description length error did not appear')); casper.thenClick('.js-bb-notification .close'); // Ensure postsPerPage number field form validation casper.fillAndSave('form#settings-general', { 'general[postsPerPage]': 'notaninteger' }); casper.waitForSelectorTextChange('.notification-error', function onSuccess() { test.assertSelectorHasText('.notification-error', 'use a number'); }, casper.failOnTimeout(test, 'postsPerPage error did not appear'), 2000); casper.thenClick('.js-bb-notification .close'); // Ensure postsPerPage max of 1000 casper.fillAndSave('form#settings-general', { 'general[postsPerPage]': '1001' }); casper.waitForSelectorTextChange('.notification-error', function onSuccess() { test.assertSelectorHasText('.notification-error', 'use a number less than 1000'); }, casper.failOnTimeout(test, 'postsPerPage max error did not appear', 2000)); casper.thenClick('.js-bb-notification .close'); // Ensure postsPerPage min of 0 casper.fillAndSave('form#settings-general', { 'general[postsPerPage]': '-1' }); casper.waitForSelectorTextChange('.notification-error', function onSuccess() { test.assertSelectorHasText('.notification-error', 'use a number greater than 0'); }, casper.failOnTimeout(test, 'postsPerPage min error did not appear', 2000)); }); // ### User settings tests // Please uncomment and fix these as the functionality is implemented //CasperTest.emberBegin('Can save settings', 6, function suite(test) { // casper.thenOpenAndWaitForPageLoad('settings.user', function testTitleAndUrl() { // test.assertTitle('Ghost Admin', 'Ghost admin has no title'); // test.assertUrlMatch(/ghost\/ember\/settings\/user\/$/, 'Landed on the correct URL'); // }); // // function handleUserRequest(requestData) { // // make sure we only get requests from the user pane // if (requestData.url.indexOf('settings/') !== -1) { // test.fail('Saving the user pane triggered another settings pane to save'); // } // } // // function handleSettingsRequest(requestData) { // // make sure we only get requests from the user pane // if (requestData.url.indexOf('users/') !== -1) { // test.fail('Saving a settings pane triggered the user pane to save'); // } // } // // casper.then(function listenForRequests() { // casper.on('resource.requested', handleUserRequest); // }); // // casper.thenClick('#user .button-save'); // casper.waitFor(function successNotification() { // return this.evaluate(function () { // return document.querySelectorAll('.js-bb-notification section').length > 0; // }); // }, function doneWaiting() { // test.pass('Waited for notification'); // }, casper.failOnTimeout(test, 'Saving the user pane did not result in a notification')); // // casper.then(function checkUserWasSaved() { // casper.removeListener('resource.requested', handleUserRequest); // }); // // casper.waitForSelector('.notification-success', function onSuccess() { // test.assert(true, 'Got success notification'); // }, casper.failOnTimeout(test, 'No success notification :(')); // // casper.thenClick('#main-menu .settings a').then(function testOpeningSettingsTwice() { // casper.on('resource.requested', handleSettingsRequest); // test.assertEval(function testUserIsActive() { // return document.querySelector('.settings-menu .general').classList.contains('active'); // }, 'general tab is marked active'); // }); // // casper.thenClick('#general .button-save').waitFor(function successNotification() { // return this.evaluate(function () { // return document.querySelectorAll('.js-bb-notification section').length > 0; // }); // }, function doneWaiting() { // test.pass('Waited for notification'); // }, casper.failOnTimeout(test, 'Saving the general pane did not result in a notification')); // // casper.then(function checkSettingsWereSaved() { // casper.removeListener('resource.requested', handleSettingsRequest); // }); // // casper.waitForSelector('.notification-success', function onSuccess() { // test.assert(true, 'Got success notification'); // }, casper.failOnTimeout(test, 'No success notification :(')); // // CasperTest.beforeDone(function () { // casper.removeListener('resource.requested', handleUserRequest); // casper.removeListener('resource.requested', handleSettingsRequest); // }); // //CasperTest.emberBegin('User settings screen validates email', 6, function suite(test) { // var email, brokenEmail; // // casper.thenOpenAndWaitForPageLoad('settings.user', function testTitleAndUrl() { // test.assertTitle('Ghost Admin', 'Ghost admin has no title'); // test.assertUrlMatch(/ghost\/settings\/user\/$/, 'Ghost doesn\'t require login this time'); // }); // // casper.then(function setEmailToInvalid() { // email = casper.getElementInfo('#user-email').attributes.value; // brokenEmail = email.replace('.', '-'); // // casper.fillSelectors('.user-profile', { // '#user-email': brokenEmail // }, false); // }); // // casper.thenClick('#user .button-save'); // // casper.waitForResource('/users/'); // // casper.waitForSelector('.notification-error', function onSuccess() { // test.assert(true, 'Got error notification'); // test.assertSelectorDoesntHaveText('.notification-error', '[object Object]'); // }, casper.failOnTimeout(test, 'No error notification :(')); // // casper.then(function resetEmailToValid() { // casper.fillSelectors('.user-profile', { // '#user-email': email // }, false); // }); // // casper.thenClick('#user .button-save'); // // casper.waitForResource(/users/); // // casper.waitForSelector('.notification-success', function onSuccess() { // test.assert(true, 'Got success notification'); // test.assertSelectorDoesntHaveText('.notification-success', '[object Object]'); // }, casper.failOnTimeout(test, 'No success notification :(')); //}); // // CasperTest.emberBegin('User settings screen shows remaining characters for Bio properly', 4, function suite(test) { casper.thenOpenAndWaitForPageLoad('settings.user', function testTitleAndUrl() { test.assertTitle('Ghost Admin', 'Ghost admin has no title'); test.assertUrlMatch(/ghost\/ember\/settings\/user\/$/, 'Ghost doesn\'t require login this time'); }); function getRemainingBioCharacterCount() { return casper.getHTML('.word-count'); } casper.then(function checkCharacterCount() { test.assert(getRemainingBioCharacterCount() === '200', 'Bio remaining characters is 200'); }); casper.then(function setBioToValid() { casper.fillSelectors('.user-profile', { '#user-bio': 'asdf\n' // 5 characters }, false); }); casper.then(function checkCharacterCount() { test.assert(getRemainingBioCharacterCount() === '195', 'Bio remaining characters is 195'); }); }); //CasperTest.emberBegin('Ensure user bio field length validation', 3, function suite(test) { // casper.thenOpenAndWaitForPageLoad('settings.user', function testTitleAndUrl() { // test.assertTitle('Ghost Admin', 'Ghost admin has no title'); // test.assertUrlMatch(/ghost\/settings\/user\/$/, 'Ghost doesn\'t require login this time'); // }); // // casper.waitForSelector('#user', function then() { // this.fillSelectors('form.user-profile', { // '#user-bio': new Array(202).join('a') // }); // }, casper.failOnTimeout(test, 'waitForSelector #user timed out')); // // casper.thenClick('#user .button-save'); // // casper.waitForSelectorTextChange('.notification-error', function onSuccess() { // test.assertSelectorHasText('.notification-error', 'is too long'); // }, casper.failOnTimeout(test, 'Bio field length error did not appear', 2000)); //}); // //CasperTest.emberBegin('Ensure user url field validation', 3, function suite(test) { // casper.thenOpenAndWaitForPageLoad('settings.user', function testTitleAndUrl() { // test.assertTitle('Ghost Admin', 'Ghost admin has no title'); // test.assertUrlMatch(/ghost\/settings\/user\/$/, 'Ghost doesn\'t require login this time'); // }); // // casper.waitForSelector('#user', function then() { // this.fillSelectors('form.user-profile', { // '#user-website': 'notaurl' // }); // }, casper.failOnTimeout(test, 'waitForSelector #user timed out')); // // casper.thenClick('#user .button-save'); // // casper.waitForSelectorTextChange('.notification-error', function onSuccess() { // test.assertSelectorHasText('.notification-error', 'use a valid url'); // }, casper.failOnTimeout(test, 'Url validation error did not appear', 2000)); //}); // //CasperTest.emberBegin('Ensure user location field length validation', 3, function suite(test) { // casper.thenOpenAndWaitForPageLoad('settings.user', function testTitleAndUrl() { // test.assertTitle('Ghost Admin', 'Ghost admin has no title'); // test.assertUrlMatch(/ghost\/settings\/user\/$/, 'Ghost doesn\'t require login this time'); // }); // // casper.waitForSelector('#user', function then() { // this.fillSelectors('form.user-profile', { // '#user-location': new Array(1002).join('a') // }); // }, casper.failOnTimeout(test, 'waitForSelector #user timed out')); // // casper.thenClick('#user .button-save'); // // casper.waitForSelectorTextChange('.notification-error', function onSuccess() { // test.assertSelectorHasText('.notification-error', 'is too long'); // }, casper.failOnTimeout(test, 'Location field length error did not appear', 2000)); //});
Unitech/Ghost
core/test/functional/client/settings_test.js
JavaScript
mit
16,580
// Modify the previous program to skip duplicates: // n=4, k=2 → (1 2), (1 3), (1 4), (2 3), (2 4), (3 4) namespace CombinationsWithouthDuplicates { using System; public class CombinationsWithouthDuplicates { public static void Main() { Console.WriteLine("Enter n:"); int endNum = int.Parse(Console.ReadLine()); Console.WriteLine("Enter k:"); int k = int.Parse(Console.ReadLine()); int startNum = 1; int index = 1; int[] arr = new int[k]; GenerateCombinations(arr, index, startNum, endNum); } private static void GenerateCombinations(int[] arr, int index, int startNum, int endNum) { if (index >= arr.Length) { Console.WriteLine("({0})", string.Join(", ", arr)); } else { for (int i = startNum; i <= endNum; i++) { arr[index] = i; GenerateCombinations(arr, index + 1, i + 1, endNum); } } } } }
marianamn/Telerik-Academy-Activities
Homeworks/15. DSA/02. Recursion/CombinationsWithouthDuplicates/CombinationsWithouthDuplicates.cs
C#
mit
1,140
using System; using System.Text; using System.Collections; using System.Collections.Generic; using System.Runtime.Serialization; using Newtonsoft.Json; namespace Org.OpenAPITools.Model { /// <summary> /// /// </summary> [DataContract] public class ResponseTimeMonitorData { /// <summary> /// Gets or Sets Class /// </summary> [DataMember(Name="_class", EmitDefaultValue=false)] [JsonProperty(PropertyName = "_class")] public string Class { get; set; } /// <summary> /// Gets or Sets Timestamp /// </summary> [DataMember(Name="timestamp", EmitDefaultValue=false)] [JsonProperty(PropertyName = "timestamp")] public int? Timestamp { get; set; } /// <summary> /// Gets or Sets Average /// </summary> [DataMember(Name="average", EmitDefaultValue=false)] [JsonProperty(PropertyName = "average")] public int? Average { get; set; } /// <summary> /// Get the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class ResponseTimeMonitorData {\n"); sb.Append(" Class: ").Append(Class).Append("\n"); sb.Append(" Timestamp: ").Append(Timestamp).Append("\n"); sb.Append(" Average: ").Append(Average).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Get the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); } } }
cliffano/swaggy-jenkins
clients/csharp-dotnet2/generated/src/main/CsharpDotNet2/Org/OpenAPITools/Model/ResponseTimeMonitorData.cs
C#
mit
1,733
#!/usr/bin/env python3 # Copyright 2014 BitPay Inc. # Copyright 2016-2019 The Bitcoin Core developers # Copyright 2015-2019 The Auroracoin developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test framework for auroracoin utils. Runs automatically during `make check`. Can also be run manually.""" import argparse import binascii import configparser import difflib import json import logging import os import pprint import subprocess import sys def main(): config = configparser.ConfigParser() config.optionxform = str config.read_file(open(os.path.join(os.path.dirname(__file__), "../config.ini"), encoding="utf8")) env_conf = dict(config.items('environment')) parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('-v', '--verbose', action='store_true') args = parser.parse_args() verbose = args.verbose if verbose: level = logging.DEBUG else: level = logging.ERROR formatter = '%(asctime)s - %(levelname)s - %(message)s' # Add the format/level to the logger logging.basicConfig(format=formatter, level=level) bctester(os.path.join(env_conf["SRCDIR"], "test", "util", "data"), "auroracoin-util-test.json", env_conf) def bctester(testDir, input_basename, buildenv): """ Loads and parses the input file, runs all tests and reports results""" input_filename = os.path.join(testDir, input_basename) raw_data = open(input_filename, encoding="utf8").read() input_data = json.loads(raw_data) failed_testcases = [] for testObj in input_data: try: bctest(testDir, testObj, buildenv) logging.info("PASSED: " + testObj["description"]) except: logging.info("FAILED: " + testObj["description"]) failed_testcases.append(testObj["description"]) if failed_testcases: error_message = "FAILED_TESTCASES:\n" error_message += pprint.pformat(failed_testcases, width=400) logging.error(error_message) sys.exit(1) else: sys.exit(0) def bctest(testDir, testObj, buildenv): """Runs a single test, comparing output and RC to expected output and RC. Raises an error if input can't be read, executable fails, or output/RC are not as expected. Error is caught by bctester() and reported. """ # Get the exec names and arguments execprog = os.path.join(buildenv["BUILDDIR"], "src", testObj["exec"] + buildenv["EXEEXT"]) execargs = testObj['args'] execrun = [execprog] + execargs # Read the input data (if there is any) stdinCfg = None inputData = None if "input" in testObj: filename = os.path.join(testDir, testObj["input"]) inputData = open(filename, encoding="utf8").read() stdinCfg = subprocess.PIPE # Read the expected output data (if there is any) outputFn = None outputData = None outputType = None if "output_cmp" in testObj: outputFn = testObj['output_cmp'] outputType = os.path.splitext(outputFn)[1][1:] # output type from file extension (determines how to compare) try: outputData = open(os.path.join(testDir, outputFn), encoding="utf8").read() except: logging.error("Output file " + outputFn + " can not be opened") raise if not outputData: logging.error("Output data missing for " + outputFn) raise Exception if not outputType: logging.error("Output file %s does not have a file extension" % outputFn) raise Exception # Run the test proc = subprocess.Popen(execrun, stdin=stdinCfg, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) try: outs = proc.communicate(input=inputData) except OSError: logging.error("OSError, Failed to execute " + execprog) raise if outputData: data_mismatch, formatting_mismatch = False, False # Parse command output and expected output try: a_parsed = parse_output(outs[0], outputType) except Exception as e: logging.error('Error parsing command output as %s: %s' % (outputType, e)) raise try: b_parsed = parse_output(outputData, outputType) except Exception as e: logging.error('Error parsing expected output %s as %s: %s' % (outputFn, outputType, e)) raise # Compare data if a_parsed != b_parsed: logging.error("Output data mismatch for " + outputFn + " (format " + outputType + ")") data_mismatch = True # Compare formatting if outs[0] != outputData: error_message = "Output formatting mismatch for " + outputFn + ":\n" error_message += "".join(difflib.context_diff(outputData.splitlines(True), outs[0].splitlines(True), fromfile=outputFn, tofile="returned")) logging.error(error_message) formatting_mismatch = True assert not data_mismatch and not formatting_mismatch # Compare the return code to the expected return code wantRC = 0 if "return_code" in testObj: wantRC = testObj['return_code'] if proc.returncode != wantRC: logging.error("Return code mismatch for " + outputFn) raise Exception if "error_txt" in testObj: want_error = testObj["error_txt"] # Compare error text # TODO: ideally, we'd compare the strings exactly and also assert # That stderr is empty if no errors are expected. However, auroracoin-tx # emits DISPLAY errors when running as a windows application on # linux through wine. Just assert that the expected error text appears # somewhere in stderr. if want_error not in outs[1]: logging.error("Error mismatch:\n" + "Expected: " + want_error + "\nReceived: " + outs[1].rstrip()) raise Exception def parse_output(a, fmt): """Parse the output according to specified format. Raise an error if the output can't be parsed.""" if fmt == 'json': # json: compare parsed data return json.loads(a) elif fmt == 'hex': # hex: parse and compare binary data return binascii.a2b_hex(a.strip()) else: raise NotImplementedError("Don't know how to compare %s" % fmt) if __name__ == '__main__': main()
aurarad/auroracoin
test/util/auroracoin-util-test.py
Python
mit
6,651
/* * Copyright (C) 2009-2013 Typesafe Inc. <http://www.typesafe.com> */ package play; import play.core.j.JavaModeConverter$; /** * High-level API to access Play global features. */ public class Play { /** * Returns the currently running application. */ public static Application application() { return play.api.Play.current().injector().instanceOf(Application.class); } /** * Returns the current mode of the application. */ public static Mode mode() { return JavaModeConverter$.MODULE$.asJavaMode(play.api.Play.mode(play.api.Play.current())); } /** * Returns `true` if the current application is `DEV` mode. */ public static boolean isDev() { return play.api.Play.isDev(play.api.Play.current()); } /** * Returns `true` if the current application is `PROD` mode. */ public static boolean isProd() { return play.api.Play.isProd(play.api.Play.current()); } /** * Returns `true` if the current application is `TEST` mode. */ public static boolean isTest() { return play.api.Play.isTest(play.api.Play.current()); } public static String langCookieName() { return play.api.Play.langCookieName(play.api.Play.current()); } }
jyotikamboj/container
pf-framework/src/play/src/main/java/play/Play.java
Java
mit
1,294
/** * Copyright (c) LambdaCraft Modding Team, 2013 * 版权许可:LambdaCraft 制作小组, 2013. * http://lambdacraft.half-life.cn/ * * LambdaCraft is open-source. It is distributed under the terms of the * LambdaCraft Open Source License. It grants rights to read, modify, compile * or run the code. It does *NOT* grant the right to redistribute this software * or its modifications in any form, binary or source, except if expressively * granted by the copyright holder. * * LambdaCraft是完全开源的。它的发布遵从《LambdaCraft开源协议》你允许阅读,修改以及调试运行 * 源代码, 然而你不允许将源代码以另外任何的方式发布,除非你得到了版权所有者的许可。 */ package cn.lambdacraft.crafting.block.generator; import ic2.api.energy.tile.IEnergySource; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; import net.minecraftforge.common.util.ForgeDirection; import cn.lambdacraft.core.block.TileElectrical; /** * @author WeAthFolD, Rikka * */ public abstract class TileGeneratorBase extends TileElectrical implements IEnergySource { public final int maxStorage, tier; public int currentEnergy; /** * The generator production in this tick */ public int production; public TileGeneratorBase(int tier, int store) { this.maxStorage = store; this.tier = tier; } @Override public void updateEntity() { super.updateEntity(); } /** * Reads a tile entity from NBT. */ @Override public void readFromNBT(NBTTagCompound nbt) { super.readFromNBT(nbt); this.currentEnergy = nbt.getInteger("energy"); } /** * Writes a tile entity to NBT. */ @Override public void writeToNBT(NBTTagCompound nbt) { super.writeToNBT(nbt); nbt.setInteger("energy", currentEnergy); } @Override public boolean emitsEnergyTo(TileEntity paramTileEntity, ForgeDirection paramDirection) { return true; } }
LambdaInnovation/LambdaCraft-Legacy
src/main/java/cn/lambdacraft/crafting/block/generator/TileGeneratorBase.java
Java
mit
2,075
<?php // NOTE for template develoepers: SQL and most other databases are either latin characters only, or Unicode for their // identifiers, so you don't need to worry about encoding issues for identifiers. ?> // this function is required for objects that implement the // IteratorAggregate interface public function getIterator() { $iArray = array(); <?php foreach ($objTable->ColumnArray as $objColumn) { ?> if (isset($this->__blnValid[self::<?= strtoupper($objColumn->Name) ?>_FIELD])) { $iArray['<?= $objColumn->PropertyName ?>'] = $this-><?= $objColumn->VariableName ?>; } <?php } ?> return new ArrayIterator($iArray); } /** * @deprecated. Just call json_encode on the object. See the jsonSerialize function for the result. /*/ public function getJson() { return json_encode($this->getIterator()); } /** * Default "toJsObject" handler * Specifies how the object should be displayed in JQuery UI lists and menus. Note that these lists use * value and label differently. * * value = The short form of what to display in the list and selection. * label = [optional] If defined, is what is displayed in the menu * id = Primary key of object. * * @return string */ public function toJsObject () { return JavaScriptHelper::toJsObject(array('value' => $this->__toString(), 'id' => <?php if ( count($objTable->PrimaryKeyColumnArray) == 1 ) { ?> $this-><?= $objTable->PrimaryKeyColumnArray[0]->VariableName ?> <?php } ?><?php if ( count($objTable->PrimaryKeyColumnArray) > 1 ) { ?> array(<?php foreach ($objTable->PrimaryKeyColumnArray as $objColumn) { ?> $this-><?= $objColumn->VariableName ?>, <?php } ?><?php GO_BACK(2); ?>) <?php } ?>)); } /** * Default "jsonSerialize" handler * Specifies how the object should be serialized using json_encode. * Control the values that are output by using QQ::Select to control which * fields are valid, and QQ::Expand to control embedded objects. * WARNING: If an object is found in short-term cache, it will be used instead of the queried object and may * contain data fields that were fetched earlier. To really control what fields exist in this object, preceed * any query calls (like Load or QueryArray), with a call to <?= $objTable->ClassName ?>::ClearCache() * * @return array An array that is json serializable */ public function jsonSerialize () { $a = []; <?php foreach ($objTable->ColumnArray as $objColumn) { ?> <?php if (($objColumn->Reference) && (!$objColumn->Reference->IsType)) { ?> if (isset($this-><?= $objColumn->Reference->VariableName ?>)) { $a['<?= $objColumn->Reference->Name ?>'] = $this-><?= $objColumn->Reference->VariableName ?>; } elseif (isset($this->__blnValid[self::<?= strtoupper($objColumn->Name) ?>_FIELD])) { $a['<?= $objColumn->Name ?>'] = $this-><?= $objColumn->VariableName ?>; } <?php } else { ?> if (isset($this->__blnValid[self::<?= strtoupper($objColumn->Name) ?>_FIELD])) { <?php if ($objColumn->DbType == \QCubed\Database\FieldType::BLOB) { // binary value ?> $a['<?= $objColumn->Name ?>'] = base64_encode($this-><?= $objColumn->VariableName ?>); <?php } elseif ($objColumn->VariableType == \QCubed\Type::STRING && __APPLICATION_ENCODING_TYPE__ != 'UTF-8') { ?> $a['<?= $objColumn->Name ?>'] = JavsScriptHelper::MakeJsonEncodable($this-><?= $objColumn->VariableName ?>); <?php } else {?> $a['<?= $objColumn->Name ?>'] = $this-><?= $objColumn->VariableName ?>; <?php } ?> } <?php } ?> <?php } ?> <?php foreach ($objTable->ReverseReferenceArray as $objReverseReference) { ?> <?php if ($objReverseReference->Unique) { ?> if (isset($this-><?= $objReverseReference->ObjectMemberVariable ?>)) { $a['<?= \QCubed\QString::UnderscoreFromCamelCase($objReverseReference->ObjectDescription) ?>'] = $this-><?= $objReverseReference->ObjectMemberVariable ?>; } <?php } else { ?> if (isset($this->_obj<?= $objReverseReference->ObjectDescription ?>)) { $a['<?= \QCubed\QString::UnderscoreFromCamelCase($objReverseReference->ObjectDescription) ?>'] = $this->_obj<?= $objReverseReference->ObjectDescription ?>; } elseif (isset($this->_obj<?= $objReverseReference->ObjectDescription ?>Array)) { $a['<?= \QCubed\QString::UnderscoreFromCamelCase($objReverseReference->ObjectDescription) ?>'] = $this->_obj<?= $objReverseReference->ObjectDescription ?>Array; } <?php } ?> <?php } ?> <?php foreach ($objTable->ManyToManyReferenceArray as $objReference) { ?> <?php $objAssociatedTable = $objCodeGen->GetTable($objReference->AssociatedTable); $varPrefix = (is_a($objAssociatedTable, '\QCubed\Codegen\TypeTable') ? '_int' : '_obj'); ?> if (isset($this-><?= $varPrefix . $objReference->ObjectDescription ?>)) { $a['<?= \QCubed\QString::UnderscoreFromCamelCase($objReference->ObjectDescription) ?>'] = $this-><?= $varPrefix . $objReference->ObjectDescription ?>; } elseif (isset($this-><?= $varPrefix . $objReference->ObjectDescription ?>Array)) { $a['<?= \QCubed\QString::UnderscoreFromCamelCase($objReference->ObjectDescription) ?>'] = $this-><?= $varPrefix . $objReference->ObjectDescription ?>Array; } <?php } ?> return $a; }
spekary/qcubed-orm
codegen/templates/db_orm/class_gen/json_methods.tpl.php
PHP
mit
5,513
// Utility namespace for InPhO JavaScript. Contains dynamic URL builder. var inpho = inpho || {}; inpho.util = inpho.util || {}; /* inpho.util.url * Takes a path for the inpho rest API and builds an absolute URL based on the * current host and protocol. * * // running on http://inphodev.cogs.indiana.edu:8080 * > inpho.util.url('/entity.json') * http://inphodev.cogs.indiana.edu:8080/entity.json * */ inpho.util.base_url = null; inpho.util.url = function(api_call) { if (inpho.util.base_url == null) return window.location.protocol + "//" + window.location.host + api_call; else return inpho.util.base_url + api_call; } inpho.util.getCookieValueForName = function(cookieName) { console.log("Getting list of cookies..."); var cookies = document.cookie.split(";"); for(var i = 0; i < cookies.length; i++) { var pair = cookies[i].split("="); console.log("Cookie " + i + ": name(" + pair[0] + "), value(" + pair[1] + ")"); if($.trim(pair[0]) === $.trim(cookieName)) { console.log("Success! Cookie found: " + cookieName); return pair[1]; } } console.log("Error! Cookie not found: " + cookieName); return null; } inpho.util.getURLParamsAndValues = function() { var paramsAndValues = []; var queryString = window.location.href.slice(window.location.href.indexOf('?') + 1); var keyValPairs = queryString.split('&'); console.log("Parsing query string: " + queryString); for(var i = 0; i < keyValPairs.length; i++) { var pair = keyValPairs[i].split('='); if(pair.length == 2) { paramsAndValues.push(pair[0]); paramsAndValues[pair[0]] = pair[1]; } else { console.log("Error: invalid URL query string"); } } return paramsAndValues; } inpho.util.getValueForURLParam = function(param) { var paramsAndValues = inpho.util.getURLParamsAndValues(); if(paramsAndValues.length == 0) return null; return paramsAndValues[param]; }
iSumitG/topic-explorer
www/lib/inpho/util.js
JavaScript
mit
1,940
namespace TestingPerformance { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.Spatial; public partial class Address { public Address() { Employees = new HashSet<Employee>(); } public int AddressID { get; set; } [Required] [StringLength(100)] public string AddressText { get; set; } public int? TownID { get; set; } public virtual Town Town { get; set; } public virtual ICollection<Employee> Employees { get; set; } } }
TsvetanKT/TelerikHomeworks
Databases/09.EntityFrameworkPerformance/TestingPerformance/TelerikAcademyEntities/Address.cs
C#
mit
672
'use strict'; var EMBED_WIDTH = 600; var EMBED_HEIGHT = 300; var mustache = require('mustache'), url = require('url'); var cache = require('./cache'); exports.getEmbedCode = function getEmbedCode(_, request, response) { var params = url.parse(request.url, true).query; if (!params.url) { respond('', 400, response); return; } //Check for format issues if (params.format && params.format !== 'json') { respond('Not implemented. Please use JSON', 501, response); return; } var data = cache.summary; data.height = EMBED_HEIGHT; data.width = EMBED_WIDTH; cache.summary.host = request.headers.host; /*eslint-disable camelcase */ //For now, respond to any url request the same way var embedCode = { //As per the spec at http://oembed.com/ /* type (required) The resource type. Valid values, along with value-specific parameters, are described below. */ type: 'rich', /*version (required) The oEmbed version number. This must be 1.0.*/ version: 1.0, /*author_name (optional) The name of the author/owner of the resource. */ author_name: 'Sock Drawer', /*author_url (optional) A URL for the author/owner of the resource.*/ author_url: 'https://github.com/SockDrawer', /*html (required) The HTML required to display the resource. The HTML should have no padding or margins. Consumers may wish to load the HTML in an off-domain iframe to avoid XSS vulnerabilities. The markup should be valid XHTML 1.0 Basic. */ html: mustache.render(cache.templates.embedTemplate, data, cache.templates), /*width (required) The width in pixels required to display the HTML.*/ width: EMBED_WIDTH, /*height (required) The height in pixels required to display the HTML.*/ height: EMBED_HEIGHT }; /*eslint-enable camelcase */ respond(JSON.stringify(embedCode), 200, response); }; function respond(data, code, response) { response.writeHead(code); response.write(data, 'utf8'); response.end(); }
SockDrawer/SockSite
oembed.js
JavaScript
mit
1,976
module SnakeCase VERSION = "0.0.1" end
FluffyJack/snake_case
lib/snake_case/version.rb
Ruby
mit
41
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "init.h" #include "util.h" #include "sync.h" #include "ui_interface.h" #include "base58.h" #include "bitcoinrpc.h" #include "db.h" #include <boost/asio.hpp> #include <boost/asio/ip/v6_only.hpp> #include <boost/bind.hpp> #include <boost/filesystem.hpp> #include <boost/foreach.hpp> #include <boost/iostreams/concepts.hpp> #include <boost/iostreams/stream.hpp> #include <boost/algorithm/string.hpp> #include <boost/lexical_cast.hpp> #include <boost/asio/ssl.hpp> #include <boost/filesystem/fstream.hpp> #include <boost/shared_ptr.hpp> #include <list> using namespace std; using namespace boost; using namespace boost::asio; using namespace json_spirit; static std::string strRPCUserColonPass; // These are created by StartRPCThreads, destroyed in StopRPCThreads static asio::io_service* rpc_io_service = NULL; static ssl::context* rpc_ssl_context = NULL; static boost::thread_group* rpc_worker_group = NULL; static inline unsigned short GetDefaultRPCPort() { return GetBoolArg("-testnet", false) ? 7612030 : 8511566; } Object JSONRPCError(int code, const string& message) { Object error; error.push_back(Pair("code", code)); error.push_back(Pair("message", message)); return error; } void RPCTypeCheck(const Array& params, const list<Value_type>& typesExpected, bool fAllowNull) { unsigned int i = 0; BOOST_FOREACH(Value_type t, typesExpected) { if (params.size() <= i) break; const Value& v = params[i]; if (!((v.type() == t) || (fAllowNull && (v.type() == null_type)))) { string err = strprintf("Expected type %s, got %s", Value_type_name[t], Value_type_name[v.type()]); throw JSONRPCError(RPC_TYPE_ERROR, err); } i++; } } void RPCTypeCheck(const Object& o, const map<string, Value_type>& typesExpected, bool fAllowNull) { BOOST_FOREACH(const PAIRTYPE(string, Value_type)& t, typesExpected) { const Value& v = find_value(o, t.first); if (!fAllowNull && v.type() == null_type) throw JSONRPCError(RPC_TYPE_ERROR, strprintf("Missing %s", t.first.c_str())); if (!((v.type() == t.second) || (fAllowNull && (v.type() == null_type)))) { string err = strprintf("Expected type %s for %s, got %s", Value_type_name[t.second], t.first.c_str(), Value_type_name[v.type()]); throw JSONRPCError(RPC_TYPE_ERROR, err); } } } int64 AmountFromValue(const Value& value) { double dAmount = value.get_real(); if (dAmount <= 0.0 || dAmount > 84000000.0) throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount"); int64 nAmount = roundint64(dAmount * COIN); if (!MoneyRange(nAmount)) throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount"); return nAmount; } Value ValueFromAmount(int64 amount) { return (double)amount / (double)COIN; } std::string HexBits(unsigned int nBits) { union { int32_t nBits; char cBits[4]; } uBits; uBits.nBits = htonl((int32_t)nBits); return HexStr(BEGIN(uBits.cBits), END(uBits.cBits)); } /// /// Note: This interface may still be subject to change. /// string CRPCTable::help(string strCommand) const { string strRet; set<rpcfn_type> setDone; for (map<string, const CRPCCommand*>::const_iterator mi = mapCommands.begin(); mi != mapCommands.end(); ++mi) { const CRPCCommand *pcmd = mi->second; string strMethod = mi->first; // We already filter duplicates, but these deprecated screw up the sort order if (strMethod.find("label") != string::npos) continue; if (strCommand != "" && strMethod != strCommand) continue; if (pcmd->reqWallet && !pwalletMain) continue; try { Array params; rpcfn_type pfn = pcmd->actor; if (setDone.insert(pfn).second) (*pfn)(params, true); } catch (std::exception& e) { // Help text is returned in an exception string strHelp = string(e.what()); if (strCommand == "") if (strHelp.find('\n') != string::npos) strHelp = strHelp.substr(0, strHelp.find('\n')); strRet += strHelp + "\n"; } } if (strRet == "") strRet = strprintf("help: unknown command: %s\n", strCommand.c_str()); strRet = strRet.substr(0,strRet.size()-1); return strRet; } Value help(const Array& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "help [command]\n" "List commands, or get help for a command."); string strCommand; if (params.size() > 0) strCommand = params[0].get_str(); return tableRPC.help(strCommand); } Value stop(const Array& params, bool fHelp) { // Accept the deprecated and ignored 'detach' boolean argument if (fHelp || params.size() > 1) throw runtime_error( "stop\n" "Stop christcoin server."); // Shutdown will take long enough that the response should get back StartShutdown(); return "christcoin server stopping"; } // // Call Table // static const CRPCCommand vRPCCommands[] = { // name actor (function) okSafeMode threadSafe reqWallet // ------------------------ ----------------------- ---------- ---------- --------- { "help", &help, true, true, false }, { "stop", &stop, true, true, false }, { "getblockcount", &getblockcount, true, false, false }, { "getbestblockhash", &getbestblockhash, true, false, false }, { "getconnectioncount", &getconnectioncount, true, false, false }, { "getpeerinfo", &getpeerinfo, true, false, false }, { "addnode", &addnode, true, true, false }, { "getaddednodeinfo", &getaddednodeinfo, true, true, false }, { "getdifficulty", &getdifficulty, true, false, false }, { "getnetworkhashps", &getnetworkhashps, true, false, false }, { "getgenerate", &getgenerate, true, false, false }, { "setgenerate", &setgenerate, true, false, true }, { "gethashespersec", &gethashespersec, true, false, false }, { "getinfo", &getinfo, true, false, false }, { "getmininginfo", &getmininginfo, true, false, false }, { "getnewaddress", &getnewaddress, true, false, true }, { "getaccountaddress", &getaccountaddress, true, false, true }, { "setaccount", &setaccount, true, false, true }, { "getaccount", &getaccount, false, false, true }, { "getaddressesbyaccount", &getaddressesbyaccount, true, false, true }, { "sendtoaddress", &sendtoaddress, false, false, true }, { "getreceivedbyaddress", &getreceivedbyaddress, false, false, true }, { "getreceivedbyaccount", &getreceivedbyaccount, false, false, true }, { "listreceivedbyaddress", &listreceivedbyaddress, false, false, true }, { "listreceivedbyaccount", &listreceivedbyaccount, false, false, true }, { "backupwallet", &backupwallet, true, false, true }, { "keypoolrefill", &keypoolrefill, true, false, true }, { "walletpassphrase", &walletpassphrase, true, false, true }, { "walletpassphrasechange", &walletpassphrasechange, false, false, true }, { "walletlock", &walletlock, true, false, true }, { "encryptwallet", &encryptwallet, false, false, true }, { "validateaddress", &validateaddress, true, false, false }, { "getbalance", &getbalance, false, false, true }, { "move", &movecmd, false, false, true }, { "sendfrom", &sendfrom, false, false, true }, { "sendmany", &sendmany, false, false, true }, { "addmultisigaddress", &addmultisigaddress, false, false, true }, { "createmultisig", &createmultisig, true, true , false }, { "getrawmempool", &getrawmempool, true, false, false }, { "getblock", &getblock, false, false, false }, { "getblockhash", &getblockhash, false, false, false }, { "gettransaction", &gettransaction, false, false, true }, { "listtransactions", &listtransactions, false, false, true }, { "listaddressgroupings", &listaddressgroupings, false, false, true }, { "signmessage", &signmessage, false, false, true }, { "verifymessage", &verifymessage, false, false, false }, { "getwork", &getwork, true, false, true }, { "getworkex", &getworkex, true, false, true }, { "listaccounts", &listaccounts, false, false, true }, { "settxfee", &settxfee, false, false, true }, { "getblocktemplate", &getblocktemplate, true, false, false }, { "submitblock", &submitblock, false, false, false }, { "setmininput", &setmininput, false, false, false }, { "listsinceblock", &listsinceblock, false, false, true }, { "dumpprivkey", &dumpprivkey, true, false, true }, { "importprivkey", &importprivkey, false, false, true }, { "listunspent", &listunspent, false, false, true }, { "getrawtransaction", &getrawtransaction, false, false, false }, { "createrawtransaction", &createrawtransaction, false, false, false }, { "decoderawtransaction", &decoderawtransaction, false, false, false }, { "signrawtransaction", &signrawtransaction, false, false, false }, { "sendrawtransaction", &sendrawtransaction, false, false, false }, { "gettxoutsetinfo", &gettxoutsetinfo, true, false, false }, { "gettxout", &gettxout, true, false, false }, { "lockunspent", &lockunspent, false, false, true }, { "listlockunspent", &listlockunspent, false, false, true }, { "verifychain", &verifychain, true, false, false }, }; CRPCTable::CRPCTable() { unsigned int vcidx; for (vcidx = 0; vcidx < (sizeof(vRPCCommands) / sizeof(vRPCCommands[0])); vcidx++) { const CRPCCommand *pcmd; pcmd = &vRPCCommands[vcidx]; mapCommands[pcmd->name] = pcmd; } } const CRPCCommand *CRPCTable::operator[](string name) const { map<string, const CRPCCommand*>::const_iterator it = mapCommands.find(name); if (it == mapCommands.end()) return NULL; return (*it).second; } // // HTTP protocol // // This ain't Apache. We're just using HTTP header for the length field // and to be compatible with other JSON-RPC implementations. // string HTTPPost(const string& strMsg, const map<string,string>& mapRequestHeaders) { ostringstream s; s << "POST / HTTP/1.1\r\n" << "User-Agent: christcoin-json-rpc/" << FormatFullVersion() << "\r\n" << "Host: 127.0.0.1\r\n" << "Content-Type: application/json\r\n" << "Content-Length: " << strMsg.size() << "\r\n" << "Connection: close\r\n" << "Accept: application/json\r\n"; BOOST_FOREACH(const PAIRTYPE(string, string)& item, mapRequestHeaders) s << item.first << ": " << item.second << "\r\n"; s << "\r\n" << strMsg; return s.str(); } string rfc1123Time() { char buffer[64]; time_t now; time(&now); struct tm* now_gmt = gmtime(&now); string locale(setlocale(LC_TIME, NULL)); setlocale(LC_TIME, "C"); // we want POSIX (aka "C") weekday/month strings strftime(buffer, sizeof(buffer), "%a, %d %b %Y %H:%M:%S +0000", now_gmt); setlocale(LC_TIME, locale.c_str()); return string(buffer); } static string HTTPReply(int nStatus, const string& strMsg, bool keepalive) { if (nStatus == HTTP_UNAUTHORIZED) return strprintf("HTTP/1.0 401 Authorization Required\r\n" "Date: %s\r\n" "Server: christcoin-json-rpc/%s\r\n" "WWW-Authenticate: Basic realm=\"jsonrpc\"\r\n" "Content-Type: text/html\r\n" "Content-Length: 296\r\n" "\r\n" "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"\r\n" "\"http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd\">\r\n" "<HTML>\r\n" "<HEAD>\r\n" "<TITLE>Error</TITLE>\r\n" "<META HTTP-EQUIV='Content-Type' CONTENT='text/html; charset=ISO-8859-1'>\r\n" "</HEAD>\r\n" "<BODY><H1>401 Unauthorized.</H1></BODY>\r\n" "</HTML>\r\n", rfc1123Time().c_str(), FormatFullVersion().c_str()); const char *cStatus; if (nStatus == HTTP_OK) cStatus = "OK"; else if (nStatus == HTTP_BAD_REQUEST) cStatus = "Bad Request"; else if (nStatus == HTTP_FORBIDDEN) cStatus = "Forbidden"; else if (nStatus == HTTP_NOT_FOUND) cStatus = "Not Found"; else if (nStatus == HTTP_INTERNAL_SERVER_ERROR) cStatus = "Internal Server Error"; else cStatus = ""; return strprintf( "HTTP/1.1 %d %s\r\n" "Date: %s\r\n" "Connection: %s\r\n" "Content-Length: %"PRIszu"\r\n" "Content-Type: application/json\r\n" "Server: christcoin-json-rpc/%s\r\n" "\r\n" "%s", nStatus, cStatus, rfc1123Time().c_str(), keepalive ? "keep-alive" : "close", strMsg.size(), FormatFullVersion().c_str(), strMsg.c_str()); } bool ReadHTTPRequestLine(std::basic_istream<char>& stream, int &proto, string& http_method, string& http_uri) { string str; getline(stream, str); // HTTP request line is space-delimited vector<string> vWords; boost::split(vWords, str, boost::is_any_of(" ")); if (vWords.size() < 2) return false; // HTTP methods permitted: GET, POST http_method = vWords[0]; if (http_method != "GET" && http_method != "POST") return false; // HTTP URI must be an absolute path, relative to current host http_uri = vWords[1]; if (http_uri.size() == 0 || http_uri[0] != '/') return false; // parse proto, if present string strProto = ""; if (vWords.size() > 2) strProto = vWords[2]; proto = 0; const char *ver = strstr(strProto.c_str(), "HTTP/1."); if (ver != NULL) proto = atoi(ver+7); return true; } int ReadHTTPStatus(std::basic_istream<char>& stream, int &proto) { string str; getline(stream, str); vector<string> vWords; boost::split(vWords, str, boost::is_any_of(" ")); if (vWords.size() < 2) return HTTP_INTERNAL_SERVER_ERROR; proto = 0; const char *ver = strstr(str.c_str(), "HTTP/1."); if (ver != NULL) proto = atoi(ver+7); return atoi(vWords[1].c_str()); } int ReadHTTPHeaders(std::basic_istream<char>& stream, map<string, string>& mapHeadersRet) { int nLen = 0; loop { string str; std::getline(stream, str); if (str.empty() || str == "\r") break; string::size_type nColon = str.find(":"); if (nColon != string::npos) { string strHeader = str.substr(0, nColon); boost::trim(strHeader); boost::to_lower(strHeader); string strValue = str.substr(nColon+1); boost::trim(strValue); mapHeadersRet[strHeader] = strValue; if (strHeader == "content-length") nLen = atoi(strValue.c_str()); } } return nLen; } int ReadHTTPMessage(std::basic_istream<char>& stream, map<string, string>& mapHeadersRet, string& strMessageRet, int nProto) { mapHeadersRet.clear(); strMessageRet = ""; // Read header int nLen = ReadHTTPHeaders(stream, mapHeadersRet); if (nLen < 0 || nLen > (int)MAX_SIZE) return HTTP_INTERNAL_SERVER_ERROR; // Read message if (nLen > 0) { vector<char> vch(nLen); stream.read(&vch[0], nLen); strMessageRet = string(vch.begin(), vch.end()); } string sConHdr = mapHeadersRet["connection"]; if ((sConHdr != "close") && (sConHdr != "keep-alive")) { if (nProto >= 1) mapHeadersRet["connection"] = "keep-alive"; else mapHeadersRet["connection"] = "close"; } return HTTP_OK; } bool HTTPAuthorized(map<string, string>& mapHeaders) { string strAuth = mapHeaders["authorization"]; if (strAuth.substr(0,6) != "Basic ") return false; string strUserPass64 = strAuth.substr(6); boost::trim(strUserPass64); string strUserPass = DecodeBase64(strUserPass64); return TimingResistantEqual(strUserPass, strRPCUserColonPass); } // // JSON-RPC protocol. Bitcoin speaks version 1.0 for maximum compatibility, // but uses JSON-RPC 1.1/2.0 standards for parts of the 1.0 standard that were // unspecified (HTTP errors and contents of 'error'). // // 1.0 spec: http://json-rpc.org/wiki/specification // 1.2 spec: http://groups.google.com/group/json-rpc/web/json-rpc-over-http // http://www.codeproject.com/KB/recipes/JSON_Spirit.aspx // string JSONRPCRequest(const string& strMethod, const Array& params, const Value& id) { Object request; request.push_back(Pair("method", strMethod)); request.push_back(Pair("params", params)); request.push_back(Pair("id", id)); return write_string(Value(request), false) + "\n"; } Object JSONRPCReplyObj(const Value& result, const Value& error, const Value& id) { Object reply; if (error.type() != null_type) reply.push_back(Pair("result", Value::null)); else reply.push_back(Pair("result", result)); reply.push_back(Pair("error", error)); reply.push_back(Pair("id", id)); return reply; } string JSONRPCReply(const Value& result, const Value& error, const Value& id) { Object reply = JSONRPCReplyObj(result, error, id); return write_string(Value(reply), false) + "\n"; } void ErrorReply(std::ostream& stream, const Object& objError, const Value& id) { // Send error reply from json-rpc error object int nStatus = HTTP_INTERNAL_SERVER_ERROR; int code = find_value(objError, "code").get_int(); if (code == RPC_INVALID_REQUEST) nStatus = HTTP_BAD_REQUEST; else if (code == RPC_METHOD_NOT_FOUND) nStatus = HTTP_NOT_FOUND; string strReply = JSONRPCReply(Value::null, objError, id); stream << HTTPReply(nStatus, strReply, false) << std::flush; } bool ClientAllowed(const boost::asio::ip::address& address) { // Make sure that IPv4-compatible and IPv4-mapped IPv6 addresses are treated as IPv4 addresses if (address.is_v6() && (address.to_v6().is_v4_compatible() || address.to_v6().is_v4_mapped())) return ClientAllowed(address.to_v6().to_v4()); if (address == asio::ip::address_v4::loopback() || address == asio::ip::address_v6::loopback() || (address.is_v4() // Check whether IPv4 addresses match 127.0.0.0/8 (loopback subnet) && (address.to_v4().to_ulong() & 0xff000000) == 0x7f000000)) return true; const string strAddress = address.to_string(); const vector<string>& vAllow = mapMultiArgs["-rpcallowip"]; BOOST_FOREACH(string strAllow, vAllow) if (WildcardMatch(strAddress, strAllow)) return true; return false; } // // IOStream device that speaks SSL but can also speak non-SSL // template <typename Protocol> class SSLIOStreamDevice : public iostreams::device<iostreams::bidirectional> { public: SSLIOStreamDevice(asio::ssl::stream<typename Protocol::socket> &streamIn, bool fUseSSLIn) : stream(streamIn) { fUseSSL = fUseSSLIn; fNeedHandshake = fUseSSLIn; } void handshake(ssl::stream_base::handshake_type role) { if (!fNeedHandshake) return; fNeedHandshake = false; stream.handshake(role); } std::streamsize read(char* s, std::streamsize n) { handshake(ssl::stream_base::server); // HTTPS servers read first if (fUseSSL) return stream.read_some(asio::buffer(s, n)); return stream.next_layer().read_some(asio::buffer(s, n)); } std::streamsize write(const char* s, std::streamsize n) { handshake(ssl::stream_base::client); // HTTPS clients write first if (fUseSSL) return asio::write(stream, asio::buffer(s, n)); return asio::write(stream.next_layer(), asio::buffer(s, n)); } bool connect(const std::string& server, const std::string& port) { ip::tcp::resolver resolver(stream.get_io_service()); ip::tcp::resolver::query query(server.c_str(), port.c_str()); ip::tcp::resolver::iterator endpoint_iterator = resolver.resolve(query); ip::tcp::resolver::iterator end; boost::system::error_code error = asio::error::host_not_found; while (error && endpoint_iterator != end) { stream.lowest_layer().close(); stream.lowest_layer().connect(*endpoint_iterator++, error); } if (error) return false; return true; } private: bool fNeedHandshake; bool fUseSSL; asio::ssl::stream<typename Protocol::socket>& stream; }; class AcceptedConnection { public: virtual ~AcceptedConnection() {} virtual std::iostream& stream() = 0; virtual std::string peer_address_to_string() const = 0; virtual void close() = 0; }; template <typename Protocol> class AcceptedConnectionImpl : public AcceptedConnection { public: AcceptedConnectionImpl( asio::io_service& io_service, ssl::context &context, bool fUseSSL) : sslStream(io_service, context), _d(sslStream, fUseSSL), _stream(_d) { } virtual std::iostream& stream() { return _stream; } virtual std::string peer_address_to_string() const { return peer.address().to_string(); } virtual void close() { _stream.close(); } typename Protocol::endpoint peer; asio::ssl::stream<typename Protocol::socket> sslStream; private: SSLIOStreamDevice<Protocol> _d; iostreams::stream< SSLIOStreamDevice<Protocol> > _stream; }; void ServiceConnection(AcceptedConnection *conn); // Forward declaration required for RPCListen template <typename Protocol, typename SocketAcceptorService> static void RPCAcceptHandler(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor, ssl::context& context, bool fUseSSL, AcceptedConnection* conn, const boost::system::error_code& error); /** * Sets up I/O resources to accept and handle a new connection. */ template <typename Protocol, typename SocketAcceptorService> static void RPCListen(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor, ssl::context& context, const bool fUseSSL) { // Accept connection AcceptedConnectionImpl<Protocol>* conn = new AcceptedConnectionImpl<Protocol>(acceptor->get_io_service(), context, fUseSSL); acceptor->async_accept( conn->sslStream.lowest_layer(), conn->peer, boost::bind(&RPCAcceptHandler<Protocol, SocketAcceptorService>, acceptor, boost::ref(context), fUseSSL, conn, boost::asio::placeholders::error)); } /** * Accept and handle incoming connection. */ template <typename Protocol, typename SocketAcceptorService> static void RPCAcceptHandler(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor, ssl::context& context, const bool fUseSSL, AcceptedConnection* conn, const boost::system::error_code& error) { // Immediately start accepting new connections, except when we're cancelled or our socket is closed. if (error != asio::error::operation_aborted && acceptor->is_open()) RPCListen(acceptor, context, fUseSSL); AcceptedConnectionImpl<ip::tcp>* tcp_conn = dynamic_cast< AcceptedConnectionImpl<ip::tcp>* >(conn); // TODO: Actually handle errors if (error) { delete conn; } // Restrict callers by IP. It is important to // do this before starting client thread, to filter out // certain DoS and misbehaving clients. else if (tcp_conn && !ClientAllowed(tcp_conn->peer.address())) { // Only send a 403 if we're not using SSL to prevent a DoS during the SSL handshake. if (!fUseSSL) conn->stream() << HTTPReply(HTTP_FORBIDDEN, "", false) << std::flush; delete conn; } else { ServiceConnection(conn); conn->close(); delete conn; } } void StartRPCThreads() { strRPCUserColonPass = mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"]; if ((mapArgs["-rpcpassword"] == "") || (mapArgs["-rpcuser"] == mapArgs["-rpcpassword"])) { unsigned char rand_pwd[32]; RAND_bytes(rand_pwd, 32); string strWhatAmI = "To use christcoind"; if (mapArgs.count("-server")) strWhatAmI = strprintf(_("To use the %s option"), "\"-server\""); else if (mapArgs.count("-daemon")) strWhatAmI = strprintf(_("To use the %s option"), "\"-daemon\""); uiInterface.ThreadSafeMessageBox(strprintf( _("%s, you must set a rpcpassword in the configuration file:\n" "%s\n" "It is recommended you use the following random password:\n" "rpcuser=christcoinrpc\n" "rpcpassword=%s\n" "(you do not need to remember this password)\n" "The username and password MUST NOT be the same.\n" "If the file does not exist, create it with owner-readable-only file permissions.\n" "It is also recommended to set alertnotify so you are notified of problems;\n" "for example: alertnotify=echo %%s | mail -s \"christcoin Alert\" admin@foo.com\n"), strWhatAmI.c_str(), GetConfigFile().string().c_str(), EncodeBase58(&rand_pwd[0],&rand_pwd[0]+32).c_str()), "", CClientUIInterface::MSG_ERROR); StartShutdown(); return; } assert(rpc_io_service == NULL); rpc_io_service = new asio::io_service(); rpc_ssl_context = new ssl::context(*rpc_io_service, ssl::context::sslv23); const bool fUseSSL = GetBoolArg("-rpcssl"); if (fUseSSL) { rpc_ssl_context->set_options(ssl::context::no_sslv2); filesystem::path pathCertFile(GetArg("-rpcsslcertificatechainfile", "server.cert")); if (!pathCertFile.is_complete()) pathCertFile = filesystem::path(GetDataDir()) / pathCertFile; if (filesystem::exists(pathCertFile)) rpc_ssl_context->use_certificate_chain_file(pathCertFile.string()); else printf("ThreadRPCServer ERROR: missing server certificate file %s\n", pathCertFile.string().c_str()); filesystem::path pathPKFile(GetArg("-rpcsslprivatekeyfile", "server.pem")); if (!pathPKFile.is_complete()) pathPKFile = filesystem::path(GetDataDir()) / pathPKFile; if (filesystem::exists(pathPKFile)) rpc_ssl_context->use_private_key_file(pathPKFile.string(), ssl::context::pem); else printf("ThreadRPCServer ERROR: missing server private key file %s\n", pathPKFile.string().c_str()); string strCiphers = GetArg("-rpcsslciphers", "TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH"); SSL_CTX_set_cipher_list(rpc_ssl_context->impl(), strCiphers.c_str()); } // Try a dual IPv6/IPv4 socket, falling back to separate IPv4 and IPv6 sockets const bool loopback = !mapArgs.count("-rpcallowip"); asio::ip::address bindAddress = loopback ? asio::ip::address_v6::loopback() : asio::ip::address_v6::any(); ip::tcp::endpoint endpoint(bindAddress, GetArg("-rpcport", GetDefaultRPCPort())); boost::system::error_code v6_only_error; boost::shared_ptr<ip::tcp::acceptor> acceptor(new ip::tcp::acceptor(*rpc_io_service)); bool fListening = false; std::string strerr; try { acceptor->open(endpoint.protocol()); acceptor->set_option(boost::asio::ip::tcp::acceptor::reuse_address(true)); // Try making the socket dual IPv6/IPv4 (if listening on the "any" address) acceptor->set_option(boost::asio::ip::v6_only(loopback), v6_only_error); acceptor->bind(endpoint); acceptor->listen(socket_base::max_connections); RPCListen(acceptor, *rpc_ssl_context, fUseSSL); fListening = true; } catch(boost::system::system_error &e) { strerr = strprintf(_("An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s"), endpoint.port(), e.what()); } try { // If dual IPv6/IPv4 failed (or we're opening loopback interfaces only), open IPv4 separately if (!fListening || loopback || v6_only_error) { bindAddress = loopback ? asio::ip::address_v4::loopback() : asio::ip::address_v4::any(); endpoint.address(bindAddress); acceptor.reset(new ip::tcp::acceptor(*rpc_io_service)); acceptor->open(endpoint.protocol()); acceptor->set_option(boost::asio::ip::tcp::acceptor::reuse_address(true)); acceptor->bind(endpoint); acceptor->listen(socket_base::max_connections); RPCListen(acceptor, *rpc_ssl_context, fUseSSL); fListening = true; } } catch(boost::system::system_error &e) { strerr = strprintf(_("An error occurred while setting up the RPC port %u for listening on IPv4: %s"), endpoint.port(), e.what()); } if (!fListening) { uiInterface.ThreadSafeMessageBox(strerr, "", CClientUIInterface::MSG_ERROR); StartShutdown(); return; } rpc_worker_group = new boost::thread_group(); for (int i = 0; i < GetArg("-rpcthreads", 4); i++) rpc_worker_group->create_thread(boost::bind(&asio::io_service::run, rpc_io_service)); } void StopRPCThreads() { if (rpc_io_service == NULL) return; rpc_io_service->stop(); rpc_worker_group->join_all(); delete rpc_worker_group; rpc_worker_group = NULL; delete rpc_ssl_context; rpc_ssl_context = NULL; delete rpc_io_service; rpc_io_service = NULL; } class JSONRequest { public: Value id; string strMethod; Array params; JSONRequest() { id = Value::null; } void parse(const Value& valRequest); }; void JSONRequest::parse(const Value& valRequest) { // Parse request if (valRequest.type() != obj_type) throw JSONRPCError(RPC_INVALID_REQUEST, "Invalid Request object"); const Object& request = valRequest.get_obj(); // Parse id now so errors from here on will have the id id = find_value(request, "id"); // Parse method Value valMethod = find_value(request, "method"); if (valMethod.type() == null_type) throw JSONRPCError(RPC_INVALID_REQUEST, "Missing method"); if (valMethod.type() != str_type) throw JSONRPCError(RPC_INVALID_REQUEST, "Method must be a string"); strMethod = valMethod.get_str(); if (strMethod != "getwork" && strMethod != "getworkex" && strMethod != "getblocktemplate") printf("ThreadRPCServer method=%s\n", strMethod.c_str()); // Parse params Value valParams = find_value(request, "params"); if (valParams.type() == array_type) params = valParams.get_array(); else if (valParams.type() == null_type) params = Array(); else throw JSONRPCError(RPC_INVALID_REQUEST, "Params must be an array"); } static Object JSONRPCExecOne(const Value& req) { Object rpc_result; JSONRequest jreq; try { jreq.parse(req); Value result = tableRPC.execute(jreq.strMethod, jreq.params); rpc_result = JSONRPCReplyObj(result, Value::null, jreq.id); } catch (Object& objError) { rpc_result = JSONRPCReplyObj(Value::null, objError, jreq.id); } catch (std::exception& e) { rpc_result = JSONRPCReplyObj(Value::null, JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id); } return rpc_result; } static string JSONRPCExecBatch(const Array& vReq) { Array ret; for (unsigned int reqIdx = 0; reqIdx < vReq.size(); reqIdx++) ret.push_back(JSONRPCExecOne(vReq[reqIdx])); return write_string(Value(ret), false) + "\n"; } void ServiceConnection(AcceptedConnection *conn) { bool fRun = true; while (fRun) { int nProto = 0; map<string, string> mapHeaders; string strRequest, strMethod, strURI; // Read HTTP request line if (!ReadHTTPRequestLine(conn->stream(), nProto, strMethod, strURI)) break; // Read HTTP message headers and body ReadHTTPMessage(conn->stream(), mapHeaders, strRequest, nProto); if (strURI != "/") { conn->stream() << HTTPReply(HTTP_NOT_FOUND, "", false) << std::flush; break; } // Check authorization if (mapHeaders.count("authorization") == 0) { conn->stream() << HTTPReply(HTTP_UNAUTHORIZED, "", false) << std::flush; break; } if (!HTTPAuthorized(mapHeaders)) { printf("ThreadRPCServer incorrect password attempt from %s\n", conn->peer_address_to_string().c_str()); /* Deter brute-forcing short passwords. If this results in a DOS the user really shouldn't have their RPC port exposed.*/ if (mapArgs["-rpcpassword"].size() < 20) MilliSleep(250); conn->stream() << HTTPReply(HTTP_UNAUTHORIZED, "", false) << std::flush; break; } if (mapHeaders["connection"] == "close") fRun = false; JSONRequest jreq; try { // Parse request Value valRequest; if (!read_string(strRequest, valRequest)) throw JSONRPCError(RPC_PARSE_ERROR, "Parse error"); string strReply; // singleton request if (valRequest.type() == obj_type) { jreq.parse(valRequest); Value result = tableRPC.execute(jreq.strMethod, jreq.params); // Send reply strReply = JSONRPCReply(result, Value::null, jreq.id); // array of requests } else if (valRequest.type() == array_type) strReply = JSONRPCExecBatch(valRequest.get_array()); else throw JSONRPCError(RPC_PARSE_ERROR, "Top-level object parse error"); conn->stream() << HTTPReply(HTTP_OK, strReply, fRun) << std::flush; } catch (Object& objError) { ErrorReply(conn->stream(), objError, jreq.id); break; } catch (std::exception& e) { ErrorReply(conn->stream(), JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id); break; } } } json_spirit::Value CRPCTable::execute(const std::string &strMethod, const json_spirit::Array &params) const { // Find method const CRPCCommand *pcmd = tableRPC[strMethod]; if (!pcmd) throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found"); if (pcmd->reqWallet && !pwalletMain) throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found (disabled)"); // Observe safe mode string strWarning = GetWarnings("rpc"); if (strWarning != "" && !GetBoolArg("-disablesafemode") && !pcmd->okSafeMode) throw JSONRPCError(RPC_FORBIDDEN_BY_SAFE_MODE, string("Safe mode: ") + strWarning); try { // Execute Value result; { if (pcmd->threadSafe) result = pcmd->actor(params, false); else if (!pwalletMain) { LOCK(cs_main); result = pcmd->actor(params, false); } else { LOCK2(cs_main, pwalletMain->cs_wallet); result = pcmd->actor(params, false); } } return result; } catch (std::exception& e) { throw JSONRPCError(RPC_MISC_ERROR, e.what()); } } Object CallRPC(const string& strMethod, const Array& params) { if (mapArgs["-rpcuser"] == "" && mapArgs["-rpcpassword"] == "") throw runtime_error(strprintf( _("You must set rpcpassword=<password> in the configuration file:\n%s\n" "If the file does not exist, create it with owner-readable-only file permissions."), GetConfigFile().string().c_str())); // Connect to localhost bool fUseSSL = GetBoolArg("-rpcssl"); asio::io_service io_service; ssl::context context(io_service, ssl::context::sslv23); context.set_options(ssl::context::no_sslv2); asio::ssl::stream<asio::ip::tcp::socket> sslStream(io_service, context); SSLIOStreamDevice<asio::ip::tcp> d(sslStream, fUseSSL); iostreams::stream< SSLIOStreamDevice<asio::ip::tcp> > stream(d); if (!d.connect(GetArg("-rpcconnect", "127.0.0.1"), GetArg("-rpcport", itostr(GetDefaultRPCPort())))) throw runtime_error("couldn't connect to server"); // HTTP basic authentication string strUserPass64 = EncodeBase64(mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"]); map<string, string> mapRequestHeaders; mapRequestHeaders["Authorization"] = string("Basic ") + strUserPass64; // Send request string strRequest = JSONRPCRequest(strMethod, params, 1); string strPost = HTTPPost(strRequest, mapRequestHeaders); stream << strPost << std::flush; // Receive HTTP reply status int nProto = 0; int nStatus = ReadHTTPStatus(stream, nProto); // Receive HTTP reply message headers and body map<string, string> mapHeaders; string strReply; ReadHTTPMessage(stream, mapHeaders, strReply, nProto); if (nStatus == HTTP_UNAUTHORIZED) throw runtime_error("incorrect rpcuser or rpcpassword (authorization failed)"); else if (nStatus >= 400 && nStatus != HTTP_BAD_REQUEST && nStatus != HTTP_NOT_FOUND && nStatus != HTTP_INTERNAL_SERVER_ERROR) throw runtime_error(strprintf("server returned HTTP error %d", nStatus)); else if (strReply.empty()) throw runtime_error("no response from server"); // Parse reply Value valReply; if (!read_string(strReply, valReply)) throw runtime_error("couldn't parse reply from server"); const Object& reply = valReply.get_obj(); if (reply.empty()) throw runtime_error("expected reply to have result, error and id properties"); return reply; } template<typename T> void ConvertTo(Value& value, bool fAllowNull=false) { if (fAllowNull && value.type() == null_type) return; if (value.type() == str_type) { // reinterpret string as unquoted json value Value value2; string strJSON = value.get_str(); if (!read_string(strJSON, value2)) throw runtime_error(string("Error parsing JSON:")+strJSON); ConvertTo<T>(value2, fAllowNull); value = value2; } else { value = value.get_value<T>(); } } // Convert strings to command-specific RPC representation Array RPCConvertValues(const std::string &strMethod, const std::vector<std::string> &strParams) { Array params; BOOST_FOREACH(const std::string &param, strParams) params.push_back(param); int n = params.size(); // // Special case non-string parameter types // if (strMethod == "stop" && n > 0) ConvertTo<bool>(params[0]); if (strMethod == "getaddednodeinfo" && n > 0) ConvertTo<bool>(params[0]); if (strMethod == "setgenerate" && n > 0) ConvertTo<bool>(params[0]); if (strMethod == "setgenerate" && n > 1) ConvertTo<boost::int64_t>(params[1]); if (strMethod == "getnetworkhashps" && n > 0) ConvertTo<boost::int64_t>(params[0]); if (strMethod == "getnetworkhashps" && n > 1) ConvertTo<boost::int64_t>(params[1]); if (strMethod == "sendtoaddress" && n > 1) ConvertTo<double>(params[1]); if (strMethod == "settxfee" && n > 0) ConvertTo<double>(params[0]); if (strMethod == "setmininput" && n > 0) ConvertTo<double>(params[0]); if (strMethod == "getreceivedbyaddress" && n > 1) ConvertTo<boost::int64_t>(params[1]); if (strMethod == "getreceivedbyaccount" && n > 1) ConvertTo<boost::int64_t>(params[1]); if (strMethod == "listreceivedbyaddress" && n > 0) ConvertTo<boost::int64_t>(params[0]); if (strMethod == "listreceivedbyaddress" && n > 1) ConvertTo<bool>(params[1]); if (strMethod == "listreceivedbyaccount" && n > 0) ConvertTo<boost::int64_t>(params[0]); if (strMethod == "listreceivedbyaccount" && n > 1) ConvertTo<bool>(params[1]); if (strMethod == "getbalance" && n > 1) ConvertTo<boost::int64_t>(params[1]); if (strMethod == "getblockhash" && n > 0) ConvertTo<boost::int64_t>(params[0]); if (strMethod == "move" && n > 2) ConvertTo<double>(params[2]); if (strMethod == "move" && n > 3) ConvertTo<boost::int64_t>(params[3]); if (strMethod == "sendfrom" && n > 2) ConvertTo<double>(params[2]); if (strMethod == "sendfrom" && n > 3) ConvertTo<boost::int64_t>(params[3]); if (strMethod == "listtransactions" && n > 1) ConvertTo<boost::int64_t>(params[1]); if (strMethod == "listtransactions" && n > 2) ConvertTo<boost::int64_t>(params[2]); if (strMethod == "listaccounts" && n > 0) ConvertTo<boost::int64_t>(params[0]); if (strMethod == "walletpassphrase" && n > 1) ConvertTo<boost::int64_t>(params[1]); if (strMethod == "getblocktemplate" && n > 0) ConvertTo<Object>(params[0]); if (strMethod == "listsinceblock" && n > 1) ConvertTo<boost::int64_t>(params[1]); if (strMethod == "sendmany" && n > 1) ConvertTo<Object>(params[1]); if (strMethod == "sendmany" && n > 2) ConvertTo<boost::int64_t>(params[2]); if (strMethod == "addmultisigaddress" && n > 0) ConvertTo<boost::int64_t>(params[0]); if (strMethod == "addmultisigaddress" && n > 1) ConvertTo<Array>(params[1]); if (strMethod == "createmultisig" && n > 0) ConvertTo<boost::int64_t>(params[0]); if (strMethod == "createmultisig" && n > 1) ConvertTo<Array>(params[1]); if (strMethod == "listunspent" && n > 0) ConvertTo<boost::int64_t>(params[0]); if (strMethod == "listunspent" && n > 1) ConvertTo<boost::int64_t>(params[1]); if (strMethod == "listunspent" && n > 2) ConvertTo<Array>(params[2]); if (strMethod == "getblock" && n > 1) ConvertTo<bool>(params[1]); if (strMethod == "getrawtransaction" && n > 1) ConvertTo<boost::int64_t>(params[1]); if (strMethod == "createrawtransaction" && n > 0) ConvertTo<Array>(params[0]); if (strMethod == "createrawtransaction" && n > 1) ConvertTo<Object>(params[1]); if (strMethod == "signrawtransaction" && n > 1) ConvertTo<Array>(params[1], true); if (strMethod == "signrawtransaction" && n > 2) ConvertTo<Array>(params[2], true); if (strMethod == "gettxout" && n > 1) ConvertTo<boost::int64_t>(params[1]); if (strMethod == "gettxout" && n > 2) ConvertTo<bool>(params[2]); if (strMethod == "lockunspent" && n > 0) ConvertTo<bool>(params[0]); if (strMethod == "lockunspent" && n > 1) ConvertTo<Array>(params[1]); if (strMethod == "importprivkey" && n > 2) ConvertTo<bool>(params[2]); if (strMethod == "verifychain" && n > 0) ConvertTo<boost::int64_t>(params[0]); if (strMethod == "verifychain" && n > 1) ConvertTo<boost::int64_t>(params[1]); return params; } int CommandLineRPC(int argc, char *argv[]) { string strPrint; int nRet = 0; try { // Skip switches while (argc > 1 && IsSwitchChar(argv[1][0])) { argc--; argv++; } // Method if (argc < 2) throw runtime_error("too few parameters"); string strMethod = argv[1]; // Parameters default to strings std::vector<std::string> strParams(&argv[2], &argv[argc]); Array params = RPCConvertValues(strMethod, strParams); // Execute Object reply = CallRPC(strMethod, params); // Parse reply const Value& result = find_value(reply, "result"); const Value& error = find_value(reply, "error"); if (error.type() != null_type) { // Error strPrint = "error: " + write_string(error, false); int code = find_value(error.get_obj(), "code").get_int(); nRet = abs(code); } else { // Result if (result.type() == null_type) strPrint = ""; else if (result.type() == str_type) strPrint = result.get_str(); else strPrint = write_string(result, true); } } catch (boost::thread_interrupted) { throw; } catch (std::exception& e) { strPrint = string("error: ") + e.what(); nRet = 87; } catch (...) { PrintException(NULL, "CommandLineRPC()"); } if (strPrint != "") { fprintf((nRet == 0 ? stdout : stderr), "%s\n", strPrint.c_str()); } return nRet; } #ifdef TEST int main(int argc, char *argv[]) { #ifdef _MSC_VER // Turn off Microsoft heap dump noise _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE); _CrtSetReportFile(_CRT_WARN, CreateFile("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0)); #endif setbuf(stdin, NULL); setbuf(stdout, NULL); setbuf(stderr, NULL); try { if (argc >= 2 && string(argv[1]) == "-server") { printf("server ready\n"); ThreadRPCServer(NULL); } else { return CommandLineRPC(argc, argv); } } catch (boost::thread_interrupted) { throw; } catch (std::exception& e) { PrintException(&e, "main()"); } catch (...) { PrintException(NULL, "main()"); } return 0; } #endif const CRPCTable tableRPC;
ChristCoin7/christcoin
src/bitcoinrpc.cpp
C++
mit
48,589
//https://gist.github.com/Ninputer/2227226 https://gist.github.com/chenshuo/2232954 //ÇëʵÏÖÏÂÃæµÄº¯Êý£¬ÊäÈë²ÎÊýbaseStrÊÇÒ»¸ö£¨¿ÉÒÔ¸ü¸ÄµÄ£©×Ö·û´®£¬Ç뽫ÆäÖÐËùÓÐÁ¬Ðø³öÏֵĶà¸ö¿Õ¸ñ¶¼Ìæ»»³ÉÒ»¸ö¿Õ¸ñ£¬µ¥Ò»¿Õ¸ñÐè±£Áô¡£ //ÇëÖ±½ÓʹÓÃbaseStrµÄ¿Õ¼ä£¬ÈçÐ迪±ÙеĴ洢¿Õ¼ä£¬²»Äܳ¬¹ýo(N)£¨×¢ÒâÊÇСo£¬NÊÇ×Ö·û´®µÄ³¤¶È£©¡£·µ»ØÖµÊÇÌæ»»ºóµÄ×Ö·û´®µÄ³¤¶È¡£ //ÑùÀý´úÂëΪC#£¬µ«¿ÉÒÔʹÓÃÈκÎÓïÑÔ¡£ÈçÐèʹÓÃÈκο⺯Êý£¬±ØÐëͬʱ¸ø³ö¿âº¯ÊýµÄʵÏÖ¡£ #include <algorithm> #include <string.h> #include <cassert> struct AreBothSpaces { bool operator()(char x, char y) const { return x == ' ' && y == ' '; } }; //impl by chenshuo int removeContinuousSpaces(char* const str) { size_t len = strlen(str); // or use std::string char* end = str+len; assert(*end == '\0'); char* last = std::unique(str, end, AreBothSpaces()); *last = '\0'; return last - str; } int main() { char inout[256] = ""; strcpy(inout, ""); removeContinuousSpaces(inout); assert(strcmp(inout, "") == 0); strcpy(inout, "a"); removeContinuousSpaces(inout); assert(strcmp(inout, "a") == 0); strcpy(inout, " a"); removeContinuousSpaces(inout); assert(strcmp(inout, " a") == 0); strcpy(inout, " a"); removeContinuousSpaces(inout); assert(strcmp(inout, " a") == 0); strcpy(inout, "a "); removeContinuousSpaces(inout); assert(strcmp(inout, "a ") == 0); strcpy(inout, "a "); removeContinuousSpaces(inout); assert(strcmp(inout, "a ") == 0); strcpy(inout, "abc def"); removeContinuousSpaces(inout); assert(strcmp(inout, "abc def") == 0); strcpy(inout, "abc def ghi"); removeContinuousSpaces(inout); assert(strcmp(inout, "abc def ghi") == 0); strcpy(inout, " a b d e "); removeContinuousSpaces(inout); assert(strcmp(inout, " a b d e ") == 0); strcpy(inout, " "); removeContinuousSpaces(inout); assert(strcmp(inout, " ") == 0); system("pause"); return 0; }
lizhenghn123/myAlgorithmStudy
trim_continuous_space/trim_continuous_space.cpp
C++
mit
1,862
'use strict'; angular.module('myContacts.contacts', ['ngRoute', 'firebase']) .config(['$routeProvider', function($routeProvider) { $routeProvider.when('/contacts', { templateUrl: 'contacts/contacts.html', controller: 'ContactsController' }); }]) .controller('ContactsController', ['$scope', '$firebaseArray', function($scope, $firebaseArray) { var ref = new Firebase('https://mycontactsforangjsprojects.firebaseio.com/contacts') $scope.contacts = $firebaseArray(ref); // console.log($scope.contacts); $scope.showAddForm = function(){ clearFields(); $scope.addFormShow = true; } $scope.showEditForm = function(contact) { $scope.editFormShow = true; $scope.id = contact.$id; $scope.name = contact.name; $scope.email = contact.email; $scope.company = contact.company; $scope.work_phone = contact.phones[0].work; $scope.home_phone = contact.phones[0].home; $scope.mobile_phone = contact.phones[0].mobile; $scope.street_address = contact.address[0].street_address; $scope.city = contact.address[0].city; $scope.state = contact.address[0].state; $scope.zipcode = contact.address[0].zipcode; } $scope.hide= function(){ $scope.addFormShow = false; $scope.contactShow = false; $scope.editFormShow = false; } $scope.addFormSubmit = function(){ //assign values if($scope.name){var name = $scope.name;} else {var name = null;} if($scope.email){var email = $scope.email;} else {var email = null;} if($scope.company){var company = $scope.company;} else {var company = null;} if($scope.mobile_phone){var mobile_phone = $scope.mobile_phone;} else {var mobile_phone = null;} if($scope.home_phone){var home_phone = $scope.home_phone;} else {var home_phone = null;} if($scope.work_phone){var work_phone = $scope.work_phone;} else {var work_phone = null;} if($scope.street_address){var street_address = $scope.street_address;} else {var street_address = null;} if($scope.city){var city = $scope.city;} else {var city = null;} if($scope.state){var state = $scope.state;} else {var state = null;} if($scope.zipcode){var zipcode = $scope.zipcode;} else {var zipcode = null;} //build object $scope.contacts.$add({ name: name, email: email, company: company, phones: [ { mobile: mobile_phone, home: home_phone, work: work_phone } ], address: [ { street_address: street_address, city: city, state: state, zipcode: zipcode } ] }).then(function(ref){ var id = ref.key(); console.log('Added contact with ID: ' + id); //clear the form clearFields(); $scope.addFormShow = false; $scope.msg = "Contact added!"; }); } $scope.editFormSubmit = function() { console.log('update contact...'); //obtain contact id var id = $scope.id; //get record var record = $scope.contacts.$getRecord(id); //assign values record.name = $scope.name; record.email = $scope.email; record.company = $scope.company; record.phones[0].work = $scope.work_phone; record.phones[0].home = $scope.home_phone; record.phones[0].mobile = $scope.mobile_phone; record.address[0].street_address = $scope.street_address; record.address[0].city = $scope.city; record.address[0].state = $scope.state; record.address[0].zipcode = $scope.zipcode; // Save Contact $scope.contacts.$save(record).then(function(ref){ console.log(ref.key); }); clearFields(); $scope.editFormShow = false; $scope.msg = "Contact Updated!"; } $scope.showContact = function(contact) { console.log(contact); $scope.name = contact.name; $scope.email = contact.email; $scope.company = contact.company; $scope.work_phone = contact.phones[0].work; $scope.home_phone = contact.phones[0].home; $scope.mobile_phone = contact.phones[0].mobile; $scope.street_address = contact.address[0].street_address; $scope.city = contact.address[0].city; $scope.state = contact.address[0].state; $scope.zipcode = contact.address[0].zipcode; $scope.contactShow = true; } //Delete contact $scope.deleteContact = function(contact){ $scope.contacts.$remove(contact); $scope.msg = "Contact Removed."; } function clearFields() { console.log('Clearing all fields...'); $scope.name = ''; $scope.email = ''; $scope.company = ''; $scope.mobile_phone = ''; $scope.home_phone = ''; $scope.work_phone = ''; $scope.street_address = ''; $scope.city = ''; $scope.state = ''; $scope.zipcode = ''; } }]);
joryschmidt/angular-contacts-app
app/contacts/contacts.js
JavaScript
mit
4,767
import { omit, parse } from 'search-params' import { MatchOptions, MatchResponse, RouteNode } from './RouteNode' import { TestMatch } from 'path-parser' const getPath = (path: string): string => path.split('?')[0] const getSearch = (path: string): string => path.split('?')[1] || '' const matchChildren = ( nodes: RouteNode[], pathSegment: string, currentMatch: MatchResponse, options: MatchOptions = {}, consumedBefore?: string ): MatchResponse | null => { const { queryParamsMode = 'default', strictTrailingSlash = false, strongMatching = true, caseSensitive = false } = options const isRoot = nodes.length === 1 && nodes[0].name === '' // for (child of node.children) { for (const child of nodes) { // Partially match path let match: TestMatch | null = null let remainingPath let segment = pathSegment if (consumedBefore === '/' && child.path === '/') { // when we encounter repeating slashes we add the slash // back to the URL to make it de facto pathless segment = '/' + pathSegment } if (!child.children.length) { match = child.parser!.test(segment, { caseSensitive, strictTrailingSlash, queryParams: options.queryParams, urlParamsEncoding: options.urlParamsEncoding }) } if (!match) { match = child.parser!.partialTest(segment, { delimited: strongMatching, caseSensitive, queryParams: options.queryParams, urlParamsEncoding: options.urlParamsEncoding }) } if (match) { // Remove consumed segment from path let consumedPath = child.parser!.build(match, { ignoreSearch: true, urlParamsEncoding: options.urlParamsEncoding }) if (!strictTrailingSlash && !child.children.length) { consumedPath = consumedPath.replace(/\/$/, '') } // Can't create a regexp from the path because it might contain a // regexp character. if (segment.toLowerCase().indexOf(consumedPath.toLowerCase()) === 0) { remainingPath = segment.slice(consumedPath.length) } else { remainingPath = segment } if (!strictTrailingSlash && !child.children.length) { remainingPath = remainingPath.replace(/^\/\?/, '?') } const { querystring } = omit( getSearch(segment.replace(consumedPath, '')), child.parser!.queryParams, options.queryParams ) remainingPath = getPath(remainingPath) + (querystring ? `?${querystring}` : '') if ( !strictTrailingSlash && !isRoot && remainingPath === '/' && !/\/$/.test(consumedPath) ) { remainingPath = '' } currentMatch.segments.push(child) Object.keys(match).forEach( param => (currentMatch.params[param] = match![param]) ) if (!isRoot && !remainingPath.length) { // fully matched return currentMatch } if ( !isRoot && queryParamsMode !== 'strict' && remainingPath.indexOf('?') === 0 ) { // unmatched queryParams in non strict mode const remainingQueryParams = parse( remainingPath.slice(1), options.queryParams ) as any Object.keys(remainingQueryParams).forEach( name => (currentMatch.params[name] = remainingQueryParams[name]) ) return currentMatch } // Continue matching on non absolute children const children = child.getNonAbsoluteChildren() // If no children to match against but unmatched path left if (!children.length) { return null } // Else: remaining path and children return matchChildren( children, remainingPath, currentMatch, options, consumedPath ) } } return null } export default matchChildren
troch/route-node
src/matchChildren.ts
TypeScript
mit
3,921
from ..models import Job import datetime class JobContainer(): def __init__(self): self.organization = None self.title = None self.division = None self.date_posted = None self.date_closing = None self.date_collected = None self.url_detail = None self.salary_waged = None self.salary_amount = None self.region = None def is_unique(self): """ Checks whether job (denoted by URL) already exists in DB. Remember to use this function before doing any intense parsing operations. """ if not self.url_detail: raise KeyError( "Queried record uniqueness before detail URL set: {}".format(self)) else: if len(Job.objects.filter(url_detail=self.url_detail)) == 0: return True else: # print("Job already exists in DB: {}".format(self.url_detail)) return False def cleanup(self): self.title = self.title.title() if self.title.isupper() else self.title self.salary_amount = 0 if self.salary_amount == None else self.salary_amount # totally arbitray amount self.salary_waged = True if self.salary_amount < 5000 else False self.date_collected = datetime.date.today() def validate(self): field_dict = self.__dict__ attributes = { k: v for k, v in field_dict.items() if not k.startswith("_")} for k, v in attributes.items(): if v == None: raise KeyError( "Job {} was missing {}".format(self.url_detail, k)) def save(self): """ Save job to DB, after final checks. """ if not self.is_unique(): # failsafe in case we forgot to check this earlier. print( "{} tried to save a job hat is not unique!".format(self.organization)) return self.cleanup() try: self.validate() except KeyError as err: print("|| EXCEPTION ", err) return print("Saved job to DB: {}".format(self)) j = Job(organization=self.organization, title=self.title, division=self.division, date_posted=self.date_posted, date_closing=self.date_closing, url_detail=self.url_detail, salary_waged=self.salary_waged, salary_amount=self.salary_amount, region=self.region, date_collected=self.date_collected ) try: j.save() except Exception as err: print("|| Exception ", err) def __str__(self): return "{} at {}".format(self.title, self.organization)
rgscherf/gainful2
parsing/parsinglib/jobcontainer.py
Python
mit
2,667
var expect = require('chai').expect; // NOTE: we run tests in chrome only, because we mainly test server API functionality. describe('[Raw API] beforeEach/afterEach hooks', function () { it('Should run hooks for all tests', function () { var test1Err = null; return runTests('./testcafe-fixtures/run-all.testcafe', 'Test1', { shouldFail: true, only: 'chrome' }) .catch(function (errs) { test1Err = errs[0]; return runTests('./testcafe-fixtures/run-all.testcafe', 'Test2', { shouldFail: true, only: 'chrome' }); }) .catch(function (errs) { expect(errs[0]).eql(test1Err); expect(errs[0]).contains( '- Error in afterEach hook - ' + 'Error on page "http://localhost:3000/fixtures/api/raw/before-after-each-hooks/pages/index.html": ' + 'Uncaught Error: [beforeEach][test][afterEach]' ); }); }); it('Should not run test and afterEach if fails in beforeEach', function () { return runTests('./testcafe-fixtures/fail-in-before-each.testcafe', 'Test', { shouldFail: true, only: 'chrome' }) .catch(function (errs) { expect(errs[0]).contains( '- Error in beforeEach hook - ' + 'Error on page "http://localhost:3000/fixtures/api/raw/before-after-each-hooks/pages/index.html": ' + 'Uncaught Error: [beforeEach]' ); }); }); it('Should run test and afterEach and beforeEach if test fails', function () { return runTests('./testcafe-fixtures/fail-in-test.testcafe', 'Test', { shouldFail: true, only: 'chrome' }) .catch(function (errs) { expect(errs[0]).to.contains('Error on page "http://localhost:3000/fixtures/api/raw/before-after-each-hooks/pages/index.html": ' + 'Uncaught Error: [beforeEach]'); expect(errs[1]).to.contains('- Error in afterEach hook - ' + 'Error on page "http://localhost:3000/fixtures/api/raw/before-after-each-hooks/pages/index.html": ' + 'Uncaught Error: [beforeEach][afterEach]'); }); }); });
helen-dikareva/testcafe-phoenix
test/functional/fixtures/api/raw/before-after-each-hooks/test.js
JavaScript
mit
2,401
import { computed, reactive, toRefs } from '@vue/composition-api' import { Frame as GameSetting } from '@xmcl/gamesetting' import { useBusy, useSemaphore } from './useSemaphore' import { useService, useServiceOnly } from './useService' import { useStore } from './useStore' import { useCurrentUser } from './useUser' import { useMinecraftVersions } from './useVersion' import { InstanceSchema as InstanceConfig, RuntimeVersions } from '/@shared/entities/instance.schema' import { CurseforgeModpackResource, ModpackResource } from '/@shared/entities/resource' import { ResourceType } from '/@shared/entities/resource.schema' import { getExpectVersion } from '/@shared/entities/version' import { InstanceGameSettingServiceKey } from '/@shared/services/InstanceGameSettingService' import { InstanceIOServiceKey } from '/@shared/services/InstanceIOService' import { InstanceLogServiceKey } from '/@shared/services/InstanceLogService' import { CloneSaveOptions, DeleteSaveOptions, ImportSaveOptions, InstanceSavesServiceKey } from '/@shared/services/InstanceSavesService' import { CreateOption, InstanceServiceKey } from '/@shared/services/InstanceService' export function useInstanceBase() { const { state } = useStore() const path = computed(() => state.instance.path) return { path } } /** * Use the general info of the instance */ export function useInstance() { const { getters, state } = useStore() const path = computed(() => state.instance.path) const name = computed(() => getters.instance.name) const author = computed(() => getters.instance.author || '') const description = computed(() => getters.instance.description) const showLog = computed(() => getters.instance.showLog) const hideLauncher = computed(() => getters.instance.hideLauncher) const runtime = computed(() => getters.instance.runtime) const java = computed(() => getters.instance.java) const resolution = computed(() => getters.instance.resolution) const minMemory = computed(() => getters.instance.minMemory) const maxMemory = computed(() => getters.instance.maxMemory) const vmOptions = computed(() => getters.instance.vmOptions) const mcOptions = computed(() => getters.instance.mcOptions) const url = computed(() => getters.instance.url) const icon = computed(() => getters.instance.icon) const lastAccessDate = computed(() => getters.instance.lastAccessDate) const creationDate = computed(() => getters.instance.creationDate) const server = computed(() => getters.instance.server) const version = computed(() => getters.instance.version) return { path, name, author, description, showLog, hideLauncher, runtime, version, java, resolution, minMemory, maxMemory, vmOptions, mcOptions, url, icon, lastAccessDate, creationDate, server, isServer: computed(() => getters.instance.server !== null), refreshing: computed(() => useSemaphore('instance').value !== 0), ...useServiceOnly(InstanceServiceKey, 'editInstance', 'refreshServerStatus'), ...useServiceOnly(InstanceIOServiceKey, 'exportInstance'), } } /** * Hook of a view of all instances & some deletion/selection functions */ export function useInstances() { const { getters } = useStore() return { instances: computed(() => getters.instances), ...useServiceOnly(InstanceServiceKey, 'mountInstance', 'deleteInstance', 'refreshServerStatusAll'), ...useServiceOnly(InstanceIOServiceKey, 'importInstance', 'linkInstance'), } } /** * Hook to create a general instance */ export function useInstanceCreation() { const { gameProfile } = useCurrentUser() const { createAndMount: createAndSelect } = useService(InstanceServiceKey) const { release } = useMinecraftVersions() const data = reactive({ name: '', runtime: { forge: '', minecraft: release.value?.id || '', liteloader: '', fabricLoader: '', yarn: '' } as RuntimeVersions, java: '', showLog: false, hideLauncher: true, vmOptions: [] as string[], mcOptions: [] as string[], maxMemory: undefined as undefined | number, minMemory: undefined as undefined | number, author: gameProfile.value.name, description: '', resolution: undefined as undefined | CreateOption['resolution'], url: '', icon: '', image: '', blur: 4, server: null as undefined | CreateOption['server'], }) const refs = toRefs(data) const required: Required<typeof refs> = toRefs(data) as any return { ...required, /** * Commit this creation. It will create and select the instance. */ create() { return createAndSelect(data) }, /** * Reset the change */ reset() { data.name = '' data.runtime = { minecraft: release.value?.id || '', forge: '', liteloader: '', fabricLoader: '', yarn: '', } data.java = '' data.showLog = false data.hideLauncher = true data.vmOptions = [] data.mcOptions = [] data.maxMemory = undefined data.minMemory = undefined data.author = gameProfile.value.name data.description = '' data.resolution = undefined data.url = '' data.icon = '' data.image = '' data.blur = 4 data.server = null }, /** * Use the same configuration as the input instance * @param instance The instance will be copied */ use(instance: InstanceConfig) { data.name = instance.name data.runtime = { ...instance.runtime } data.java = instance.java data.showLog = instance.showLog data.hideLauncher = instance.hideLauncher data.vmOptions = [...instance.vmOptions] data.mcOptions = [...instance.mcOptions] data.maxMemory = instance.maxMemory data.minMemory = instance.minMemory data.author = instance.author data.description = instance.description data.url = instance.url data.icon = instance.icon data.server = instance.server ? { ...instance.server } : undefined }, useModpack(resource: CurseforgeModpackResource | ModpackResource) { if (resource.type === ResourceType.CurseforgeModpack) { const metadata = resource.metadata data.name = `${metadata.name} - ${metadata.version}` data.runtime.minecraft = metadata.minecraft.version if (metadata.minecraft.modLoaders.length > 0) { for (const loader of metadata.minecraft.modLoaders) { if (loader.id.startsWith('forge-')) { data.runtime.forge = loader.id.substring('forge-'.length) } } } data.author = metadata.author } else { const metadata = resource.metadata data.name = resource.name data.runtime.minecraft = metadata.runtime.minecraft data.runtime.forge = metadata.runtime.forge data.runtime.fabricLoader = metadata.runtime.fabricLoader } }, } } export function useInstanceVersionBase() { const { getters } = useStore() const minecraft = computed(() => getters.instance.runtime.minecraft) const forge = computed(() => getters.instance.runtime.forge) const fabricLoader = computed(() => getters.instance.runtime.fabricLoader) const yarn = computed(() => getters.instance.runtime.yarn) return { minecraft, forge, fabricLoader, yarn, } } export function useInstanceTemplates() { const { getters, state } = useStore() return { instances: computed(() => getters.instances), modpacks: computed(() => state.resource.modpacks), } } export function useInstanceGameSetting() { const { state } = useStore() const { refresh: _refresh, edit, showInFolder } = useService(InstanceGameSettingServiceKey) const refresh = () => _refresh() const fancyGraphics = computed(() => state.instanceGameSetting.fancyGraphics) const renderClouds = computed(() => state.instanceGameSetting.renderClouds) const ao = computed(() => state.instanceGameSetting.ao) const entityShadows = computed(() => state.instanceGameSetting.entityShadows) const particles = computed(() => state.instanceGameSetting.particles) const mipmapLevels = computed(() => state.instanceGameSetting.mipmapLevels) const useVbo = computed(() => state.instanceGameSetting.useVbo) const fboEnable = computed(() => state.instanceGameSetting.fboEnable) const enableVsync = computed(() => state.instanceGameSetting.enableVsync) const anaglyph3d = computed(() => state.instanceGameSetting.anaglyph3d) return { fancyGraphics, renderClouds, ao, entityShadows, particles, mipmapLevels, useVbo, fboEnable, enableVsync, anaglyph3d, showInFolder, refreshing: useBusy('loadInstanceGameSettings'), refresh, commit(settings: GameSetting) { edit(settings) }, } } export function useInstanceSaves() { const { state } = useStore() const { cloneSave, deleteSave, exportSave, readAllInstancesSaves, importSave, mountInstanceSaves } = useService(InstanceSavesServiceKey) const refresh = () => mountInstanceSaves(state.instance.path) return { refresh, cloneSave: (options: CloneSaveOptions) => cloneSave(options).finally(refresh), deleteSave: (options: DeleteSaveOptions) => deleteSave(options).finally(refresh), exportSave, readAllInstancesSaves, importSave: (options: ImportSaveOptions) => importSave(options).finally(refresh), path: computed(() => state.instance.path), saves: computed(() => state.instanceSave.saves), } } /** * Use references of all the version info of this instance */ export function useInstanceVersion() { const { getters } = useStore() const folder = computed(() => getters.instanceVersion.id || 'unknown') const id = computed(() => getExpectVersion(getters.instance.runtime)) return { ...useInstanceVersionBase(), id, folder, } } export function useInstanceLogs() { const { state } = useStore() return { path: computed(() => state.instance.path), ...useServiceOnly(InstanceLogServiceKey, 'getCrashReportContent', 'getLogContent', 'listCrashReports', 'listLogs', 'removeCrashReport', 'removeLog', 'showCrash', 'showLog'), } }
InfinityStudio/ILauncher
src/renderer/hooks/useInstance.ts
TypeScript
mit
10,224
require 'spec_helper' describe Urmum do it 'should have a version number' do Urmum::VERSION.should_not be_nil end end
dgmstuart/urmum
spec/urmum_spec.rb
Ruby
mit
127
<?php namespace App\Http\Controllers; class PageController extends Controller { public function index($request, $response) { return $this->twigView->render($response, "auth/index.twig"); } }
Rodz3rd2/my-framework
app/Http/Controllers/PageController.php
PHP
mit
198
# encoding: utf-8 require 'spec_helper' RSpec.describe Github::Client::Gists, '#get' do let(:gist_id) { 1 } before { stub_get(request_path).to_return(body: body, status: status, headers: {content_type: "application/json; charset=utf-8"}) } after { reset_authentication_for(subject) } context "resource found" do let(:request_path) { "/gists/#{gist_id}" } let(:body) { fixture('gists/gist.json') } let(:status) { 200 } it { should respond_to :find } it "fails to get resource without gist id" do expect { subject.get }.to raise_error(ArgumentError) end it "gets the resource" do subject.get gist_id expect(a_get(request_path)).to have_been_made end it "gets gist information" do gist = subject.get gist_id expect(gist.id.to_i).to eq gist_id expect(gist.user.login).to eq('octocat') end it "returns response wrapper" do gist = subject.get(gist_id) expect(gist).to be_a(Github::ResponseWrapper) end it_should_behave_like 'request failure' do let(:requestable) { subject.get gist_id } end end context 'resource found with sha' do let(:sha) { 'aa5a315d61ae9438b18d' } let(:request_path) { "/gists/#{gist_id}/#{sha}" } let(:body) { fixture('gists/gist.json') } let(:status) { 200 } it "gets the resource" do subject.get(gist_id, sha: sha) expect(a_get(request_path)).to have_been_made end end end # get
samphilipd/github
spec/github/client/gists/get_spec.rb
Ruby
mit
1,482
/** * @title Check last password reset * @overview Check the last time that a user changed his or her account password. * @gallery true * @category access control * * This rule will check the last time that a user changed his or her account password. * */ function checkLastPasswordReset(user, context, callback) { function daydiff(first, second) { return (second - first) / (1000 * 60 * 60 * 24); } const last_password_change = user.last_password_reset || user.created_at; if (daydiff(new Date(last_password_change), new Date()) > 30) { return callback(new UnauthorizedError('please change your password')); } callback(null, user, context); }
auth0/rules
src/rules/check-last-password-reset.js
JavaScript
mit
675
import { router } from 'router'; $('body').ready(function() { router.start(); });
fasttakerbg/Final-Project
public/scripts/main.js
JavaScript
mit
87
using System; using A4CoreBlog.Data.Services.Contracts; using A4CoreBlog.Data.UnitOfWork; using AutoMapper; using A4CoreBlog.Data.Models; using System.Linq; using AutoMapper.QueryableExtensions; namespace A4CoreBlog.Data.Services.Implementations { public class SystemImageService : ISystemImageService { private readonly IBlogSystemData _data; public SystemImageService(IBlogSystemData data) { _data = data; } public T AddOrUpdate<T>(T model) { try { var dbModel = Mapper.Map<SystemImage>(model); dbModel.CreatedOn = DateTime.Now; _data.Images.Add(dbModel); _data.SaveChanges(); model = Mapper.Map<T>(dbModel); return model; } catch (Exception ex) { // TODO: return default T or null return model; } } public T Get<T>(int id) { var dbModel = _data.Images.GetById(id); var resultModel = Mapper.Map<T>(dbModel); return resultModel; } public IQueryable<T> GetCollection<T>() { var result = _data.Images.All() .OrderByDescending(i => i.CreatedOn) .ProjectTo<T>(); return result; } } }
yasenm/a4-netcore
A4CoreBlog/A4CoreBlog.Data.Services/Implementations/SystemImageService.cs
C#
mit
1,409
/** * Simple script to detect misc CSS @support's. * If not... Redirect to: /upgrade * * To minify (example): * uglifyjs detect_support.js -o detect_support.min.js -c -m */ (function detectSupport() { var upradeURL = '/upgrade', /** * List your CSS @support tests. * On the upgrade page, it will add to console.log(): * Your browser doesn't support “Foo Bar Variables”: @supports ($foo, Bar) */ cssObj = { 'CSS Variables': ['--var', 0], //'Foo Bar Variables': ['$foo', 'bar'], }; var redirect = (function() { window.location = upradeURL; }); for (var t in cssObj) { if (window.CSS && window.CSS.supports && !window.CSS.supports(cssObj[t][0], cssObj[t][1])) { sessionStorage.setItem('detect_support.js', 'Your browser doesn\'t support “' + t + '”: @supports (' + cssObj[t][0] + ', ' + cssObj[t][1] + ')'); redirect(); } } })(); /** * In your upgrade page add: * * <script type="text/javascript"> * if (sessionStorage.getItem('detect_support.js')) { * console.log(sessionStorage.getItem('detect_support.js')); * sessionStorage.removeItem('detect_support.js'); * } * </script> */
iEFdev/browser-upgrade-page
upgrade/js/detect_support.js
JavaScript
mit
1,304
package net.airvantage.sched.app; import java.util.Properties; import java.util.concurrent.TimeUnit; import javax.sql.DataSource; import org.apache.commons.dbcp2.ConnectionFactory; import org.apache.commons.dbcp2.DriverManagerConnectionFactory; import org.apache.commons.dbcp2.PoolableConnection; import org.apache.commons.dbcp2.PoolableConnectionFactory; import org.apache.commons.dbcp2.PoolingDataSource; import org.apache.commons.pool2.impl.GenericObjectPool; import org.apache.commons.pool2.impl.GenericObjectPoolConfig; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.eclipse.jetty.webapp.WebAppContext; import org.quartz.JobListener; import org.quartz.Scheduler; import org.quartz.SchedulerException; import org.quartz.TriggerListener; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.codahale.metrics.MetricRegistry; import com.codahale.metrics.Slf4jReporter; import net.airvantage.sched.app.exceptions.ServiceRuntimeException; import net.airvantage.sched.app.mapper.JsonMapper; import net.airvantage.sched.conf.ConfigurationManager; import net.airvantage.sched.conf.Keys; import net.airvantage.sched.dao.JobConfigDao; import net.airvantage.sched.dao.JobLockDao; import net.airvantage.sched.dao.JobSchedulingDao; import net.airvantage.sched.dao.JobWakeupDao; import net.airvantage.sched.db.SchemaMigrator; import net.airvantage.sched.event.YakEventsManagerImpl; import net.airvantage.sched.quartz.DefaultJobListener; import net.airvantage.sched.quartz.DefaultTriggerListener; import net.airvantage.sched.quartz.QuartzClusteredSchedulerFactory; import net.airvantage.sched.services.JobSchedulingService; import net.airvantage.sched.services.JobStateService; import net.airvantage.sched.services.impl.JobSchedulingServiceImpl; import net.airvantage.sched.services.impl.JobStateServiceImpl; import net.airvantage.sched.services.tech.JobExecutionHelper; import net.airvantage.sched.services.tech.RemoteServiceConnector; import net.airvantage.sched.services.tech.RetryPolicyHelper; import net.airvantage.yak.client.YakClient; import net.airvantage.yak.client.YakClientConfig; public class ServiceLocator { private static final Logger LOG = LoggerFactory.getLogger(ServiceLocator.class); // Do not use everywhere, only in things like quartz jobs & servlets private static ServiceLocator instance; private MetricRegistry metrics; private ConfigurationManager configManager; private Scheduler scheduler; private SchemaMigrator schemaMigrator; private DataSource dataSource; private JsonMapper jsonMapper; private CloseableHttpClient httpClient; private YakClient yakClient; private YakEventsManagerImpl yakEventsManager; private JobStateService jobStateService; private JobSchedulingService jobService; private RetryPolicyHelper retryPolicyHelper; private JobExecutionHelper jobExecutionHelper; private JobSchedulingDao jobSchedulingDao; private JobConfigDao jobConfigDao; private JobWakeupDao jobWakeupDao; private JobLockDao jobLockDao; // ----------------------------------------------- Initialization ------------------------------------------------- public static ServiceLocator getInstance() { if (instance == null) { instance = new ServiceLocator(); } return instance; } public void init() { instance = this; configManager = new ConfigurationManager(); } public void servicesPreload(WebAppContext context) { try { // Load internal jobs ((JobSchedulingServiceImpl) getJobSchedulingService()).loadInternalJobs(); // Load YAK client and register handlers getYakEventsManager().configure(context); } catch (Exception ex) { LOG.error("Failed to initialize services.", ex); } } // -------------------------------------------------- Services ---------------------------------------------------- public JobSchedulingService getJobSchedulingService() { if (jobService == null) { jobService = new JobSchedulingServiceImpl(getScheduler(), getJobStateService(), getJobConfigDao(), getJobLockDao(), getJobSchedulingDao(), getJobWakeupDao(), getWakeupJobCron(), getWakeupStatsJobCron()); } return jobService; } public RetryPolicyHelper getRetryPolicyHelper() { if (retryPolicyHelper == null) { retryPolicyHelper = new RetryPolicyHelper(getJobStateService(), getJobSchedulingService(), getJobWakeupDao()); } return retryPolicyHelper; } public JobStateService getJobStateService() { if (jobStateService == null) { jobStateService = new JobStateServiceImpl(getJobConfigDao(), getJobLockDao(), getJobSchedulingDao()); } return jobStateService; } public JobSchedulingDao getJobSchedulingDao() { if (jobSchedulingDao == null) { jobSchedulingDao = new JobSchedulingDao(getScheduler()); } return jobSchedulingDao; } public JobLockDao getJobLockDao() { if (jobLockDao == null) { jobLockDao = new JobLockDao(getDataSource()); } return jobLockDao; } public JobConfigDao getJobConfigDao() { if (jobConfigDao == null) { jobConfigDao = new JobConfigDao(getDataSource()); } return jobConfigDao; } public JobWakeupDao getJobWakeupDao() { if (jobWakeupDao == null) { jobWakeupDao = new JobWakeupDao(getDataSource()); } return jobWakeupDao; } public JobExecutionHelper geJobExecutionHelper() { if (jobExecutionHelper == null) { RemoteServiceConnector connector = new RemoteServiceConnector(this.getHttpClient(), 3); jobExecutionHelper = new JobExecutionHelper(getJobStateService(), connector, getSchedSecret(), getJsonMapper(), getJobConfigDao(), getRetryPolicyHelper()); } return jobExecutionHelper; } public CloseableHttpClient getHttpClient() { if (httpClient == null) { int poolSize = this.getOutputCnxPoolSize(); httpClient = HttpClientBuilder.create().disableContentCompression().setMaxConnPerRoute(poolSize) .setMaxConnTotal(poolSize * 2).evictExpiredConnections().build(); } return httpClient; } public ConfigurationManager getConfigManager() { return configManager; } public JsonMapper getJsonMapper() { if (jsonMapper == null) { jsonMapper = new JsonMapper(); } return jsonMapper; } public SchemaMigrator getSchemaMigrator() { if (schemaMigrator == null) { schemaMigrator = new SchemaMigrator(getDataSource()); } return schemaMigrator; } public Scheduler getScheduler() { if (scheduler == null) { try { scheduler = QuartzClusteredSchedulerFactory.buildScheduler(getConfigManager().get()); scheduler.start(); scheduler.getListenerManager().addTriggerListener(getLockTriggerListener()); scheduler.getListenerManager().addJobListener(getRetryJobListener()); } catch (SchedulerException ex) { LOG.error("Unable to load scheduler", ex); throw new ServiceRuntimeException("Unable to load scheduler", ex); } } return scheduler; } public YakClient getYakClient() { if (yakClient == null) { YakClientConfig config = new YakClientConfig().setPollOrderTimeoutMs(3000).setAckOrderTimeoutMs(3000); String yakUrl = getConfigManager().get().getString("av-sched.yak.url", "none"); return new YakClient(getEnvName(), "av-sched", yakUrl, config); } return yakClient; } public YakEventsManagerImpl getYakEventsManager() { if (yakEventsManager == null) { yakEventsManager = new YakEventsManagerImpl(getYakClient(), getJobSchedulingService()); } return yakEventsManager; } public MetricRegistry getMetrics() { if (metrics == null) { metrics = new MetricRegistry(); Slf4jReporter.forRegistry(metrics).outputTo(LOG).convertRatesTo(TimeUnit.SECONDS) .convertDurationsTo(TimeUnit.MILLISECONDS).build().start(5, TimeUnit.MINUTES); } return metrics; } // ------------------------------------------------- Deploy Configuration ----------------------------------------- public String getEnvName() { return getConfigManager().get().getString(Keys.ENV_NAME, "dev"); } public String getSchedSecret() { return getConfigManager().get().getString(Keys.SECRET); } public int getPort() { return getConfigManager().get().getInt(Keys.PORT); } public int getOutputCnxPoolSize() { return getConfigManager().get().getInt(Keys.Io.OUT_CNX_POOL_SIZE, 100); } public int getWakeupJobThreadPoolSize() { return getConfigManager().get().getInt(Keys.Io.OUT_THREAD_POOL_SIZE, 100); } public int getServletCnxPoolSize() { return getConfigManager().get().getInt(Keys.Io.IN_CNX_POOL_SIZE, 100); } public int getDbCnxPoolMin() { return getConfigManager().get().getInt(Keys.Db.POOL_MIN, 50); } public int getDbCnxPoolMax() { // RDS default max connections allowed = {DBInstanceClassMemory/12582880} // db.t2.medium : 4000000000/12582880 =~ 312 // SQL QUERY : SHOW VARIABLES where VARIABLE_NAME = 'max_connections' return getConfigManager().get().getInt(Keys.Db.POOL_MAX, 130); } public String getWakeupJobCron() { return getConfigManager().get().getString(Keys.Cron.WAKEUP_JOB, "0 0/2 * * * ?"); } public String getWakeupStatsJobCron() { return getConfigManager().get().getString(Keys.Cron.WAKEUP_STATS_JOB, "0/30 * * * * ?"); } // ---------------------------------------------------- Private Methods ------------------------------------------- private DataSource getDataSource() { if (dataSource == null) { String host = getConfigManager().get().getString(Keys.Db.SERVER); int port = getConfigManager().get().getInt(Keys.Db.PORT); String dbname = getConfigManager().get().getString(Keys.Db.DB_NAME); String user = getConfigManager().get().getString(Keys.Db.USER); String password = getConfigManager().get().getString(Keys.Db.PASSWORD); Properties props = new Properties(); props.setProperty("user", user); props.setProperty("password", password); props.setProperty("defaultTransactionIsolation", "NONE"); // props.setProperty("validationQuery", "SELECT 1"); // props.setProperty("testOnBorrow", "true"); String url = "jdbc:mysql://" + host + ":" + port + "/" + dbname + "?tcpKeepAlive=true"; GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig(); poolConfig.setMinIdle(getDbCnxPoolMin()); poolConfig.setMaxTotal(getDbCnxPoolMax()); ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(url, props); PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory, null); GenericObjectPool<PoolableConnection> connectionPool = new GenericObjectPool<>(poolableConnectionFactory, poolConfig); poolableConnectionFactory.setPool(connectionPool); dataSource = new PoolingDataSource<>(connectionPool); LOG.info("MYSQL[default] connection to {}", url); } return dataSource; } private TriggerListener getLockTriggerListener() { return new DefaultTriggerListener(getJobStateService()); } private JobListener getRetryJobListener() { return new DefaultJobListener(getRetryPolicyHelper()); } }
AirVantage/av-sched
src/main/java/net/airvantage/sched/app/ServiceLocator.java
Java
mit
12,317
module foo { exports foo; }
opengl-8080/Samples
java/java9/jigsaw/src/main/java/module-info.java
Java
mit
33
package org.knowm.xchange.btcchina.dto.trade.response; import static org.junit.Assert.assertEquals; import java.io.IOException; import java.math.BigDecimal; import org.junit.Test; import com.fasterxml.jackson.databind.ObjectMapper; import org.knowm.xchange.btcchina.dto.trade.BTCChinaMarketDepthOrder; public class BTCChinaGetMarketDepthResponseTest { private final ObjectMapper mapper = new ObjectMapper(); @Test public void testBTCChinaGetMarketDepthResponse() throws IOException { BTCChinaGetMarketDepthResponse response = mapper.readValue(getClass().getResourceAsStream("getMarketDepth2.json"), BTCChinaGetMarketDepthResponse.class); assertEquals("1", response.getId()); BTCChinaMarketDepthOrder[] bids = response.getResult().getMarketDepth().getBids(); BTCChinaMarketDepthOrder[] asks = response.getResult().getMarketDepth().getAsks(); assertEquals(2, bids.length); assertEquals(2, asks.length); assertEquals(new BigDecimal("99"), bids[0].getPrice()); assertEquals(new BigDecimal("1"), bids[0].getAmount()); assertEquals(new BigDecimal("98"), bids[1].getPrice()); assertEquals(new BigDecimal("2"), bids[1].getAmount()); assertEquals(new BigDecimal("100"), asks[0].getPrice()); assertEquals(new BigDecimal("0.997"), asks[0].getAmount()); assertEquals(new BigDecimal("101"), asks[1].getPrice()); assertEquals(new BigDecimal("2"), asks[1].getAmount()); } }
mmithril/XChange
xchange-btcchina/src/test/java/org/knowm/xchange/btcchina/dto/trade/response/BTCChinaGetMarketDepthResponseTest.java
Java
mit
1,445
package com.cezarykluczynski.stapi.auth.common.factory; import com.cezarykluczynski.stapi.model.common.dto.RequestSortClauseDTO; import com.cezarykluczynski.stapi.model.common.dto.RequestSortDTO; import com.cezarykluczynski.stapi.model.common.dto.enums.RequestSortDirectionDTO; import com.google.common.collect.Lists; import org.springframework.stereotype.Service; @Service public class RequestSortDTOFactory { public RequestSortDTO create() { RequestSortDTO requestSortDTO = new RequestSortDTO(); RequestSortClauseDTO requestSortClauseDTO = new RequestSortClauseDTO(); requestSortClauseDTO.setDirection(RequestSortDirectionDTO.ASC); requestSortClauseDTO.setName("id"); requestSortDTO.setClauses(Lists.newArrayList(requestSortClauseDTO)); return requestSortDTO; } }
cezarykluczynski/stapi
auth/src/main/java/com/cezarykluczynski/stapi/auth/common/factory/RequestSortDTOFactory.java
Java
mit
784
package com.bah.app; import com.bah.ml.classifiers.Perceptron; import org.apache.commons.cli.*; import org.apache.log4j.BasicConfigurator; import java.util.Arrays; import java.util.logging.Level; import java.util.logging.Logger; public class perceptron { private static final Logger log = Logger.getLogger(perceptron.class.getName()); public static void main(String[] args) { // Configure log4j BasicConfigurator.configure(); final Options options = new Options(); options.addOption("h", "help", false, "show help"); options.addOption("m", "mode", true, "Sets the mode <test|train>"); options.addOption("d", "data", true, "Sets the data source (file or URL)"); options.addOption("k", "k-folds", true, "Sets the k-folds"); options.addOption("l", "learn-rate", true, "Sets the learning rate"); options.addOption("r", "learn-random", false, "Will use random value for learning rate after each iteration"); Option targetsOption = new Option("t", "target", true, "Specify which target to train/test, if not set all targets found will be trained/tested (max 256)"); targetsOption.setArgs(256); options.addOption(targetsOption); options.addOption("i", "iterations", false, "Specify Max iterations to run for training, defaults to 1000"); options.addOption("i", "min-error", false, "Specify minimum error while training, defaults to 0.05"); CommandLineParser parser = new BasicParser(); CommandLine cmd = null; try { cmd = parser.parse(options, args); if (cmd.hasOption("h")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("perceptron", options); System.exit(0); } if (cmd.hasOption("m")) { log.log(Level.INFO, "Using cli argument -m=" + cmd.getOptionValue("m")); Perceptron perceptron = new Perceptron(); if (cmd.getOptionValue("m").toLowerCase().equals("train")) { perceptron.setMode(Perceptron.Mode.TRAIN); perceptron.setDataSource(cmd.getOptionValue("d")); perceptron.setTargets(Arrays.asList(cmd.getOptionValues("t"))); perceptron.setkFolds(Integer.valueOf(cmd.getOptionValue("k", "10"))); if (cmd.hasOption("r")) { perceptron.setRandomLearning(true); } else { perceptron.setRandomLearning(false); perceptron.setLearningRate(Double.valueOf(cmd.getOptionValue("l", "0.5"))); } perceptron.setMaxIterations(Integer.valueOf(cmd.getOptionValue("i", "1000"))); perceptron.setMinError(Double.valueOf(cmd.getOptionValue("e", "0.05"))); perceptron.run(); } else { perceptron.setMode(Perceptron.Mode.TEST); } } else { log.log(Level.SEVERE, "Missing m option"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("Main", options); System.exit(0); } } catch (ParseException e) { log.log(Level.SEVERE, "Failed to parse command line properties", e); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("Main", options); System.exit(0); } } }
jaybkun/machine-learning-library
src/main/java/com/bah/app/perceptron.java
Java
mit
3,562
using System; using System.Collections.Generic; using System.Linq; using System.Windows.Forms; namespace ParcelTracker { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new MainForm()); } } }
Vyacheslav-1991/parceltracker
ParcelTracker/Program.cs
C#
mit
487
using System.Collections.Generic; namespace TemplateApp.Data.Models { public class Subsidiary : EntityBase { // // Constructor public Subsidiary() { Locations = new HashSet<Location>(); Subsidiaries = new HashSet<Subsidiary>(); Divisions = new HashSet<Division>(); } // // Currency public Currency Currency { get; set; } // // Divisions public virtual ICollection<Division> Divisions { get; set; } // // Identification (Primary Key) public int Id { get; set; } // // Locations public virtual ICollection<Location> Locations { get; set; } // // Subsidiaries public virtual ICollection<Subsidiary> Subsidiaries { get; set; } } }
panchaldineshb/Sarabi
TemplateApp/TemplateApp.Data/Models/Subsidiary.cs
C#
mit
843
'use strict'; describe('Controller: SitenewCtrl', function () { // load the controller's module beforeEach(module('uiApp')); var SitenewCtrl, scope; // Initialize the controller and a mock scope beforeEach(inject(function ($controller, $rootScope) { scope = $rootScope.$new(); SitenewCtrl = $controller('SitenewCtrl', { $scope: scope }); })); it('should attach a list of awesomeThings to the scope', function () { expect(scope.awesomeThings.length).toBe(3); }); });
Ecotrust/floodplain-restoration
ui/test/spec/controllers/sitenew.js
JavaScript
mit
513
import React, {Component} from 'react'; import LanguageSwitcher from './LanguageSwitcher'; import Navigation from './Navigation'; import $ from 'jquery'; const Translate = require('react-i18nify').Translate; export default class Menu extends Component{ constructor(){ super(); let self = this; this.state = {currentPage: '#home', isOpen: 0}; this.bindSidebarCallback(); $("body").on("click", (event) => { let countElementClicks = (counter, element) => counter + event.target.className.indexOf(element); let elements = ['nav-item', 'menu-toggler', 'language-switcher', "lang", "toggler"]; let isClicked = elements.reduce(countElementClicks, elements.length); if(isClicked == 0) this.setState({isOpen: 0}); }); } handleClick(e){ e.preventDefault(); var section = e.target.getAttribute('href') || e.target.parentNode.getAttribute('href'); Navigation.goTo(section); } toggleMenu(e){ e.preventDefault(); this.setState(prevState => ({ isOpen: !prevState.isOpen })); } bindSidebarCallback(){ let self = this; function setStateOnResizeWindow(){ if($(this).width() <= 768) self.setState((previousState) => ({isOpen: 0})); } $(window).resize(setStateOnResizeWindow); setStateOnResizeWindow(); } render(){ return ( <div className="menu"> <div className="container "> <nav className={this.state.isOpen > 0 ? "nav-item is-open" : "nav-item"}> <a href="#home" className="manguezal-logo-small" onClick={this.handleClick.bind(this)}> Manguez.al</a> <a href="#" className={this.state.isOpen > 0 ? "menu-toggler menu-toggler__is-open" : "menu-toggler"} onClick={this.toggleMenu.bind(this)}>&nbsp;</a> <div className="menu-group"> <a href="#welcome" onClick={this.handleClick.bind(this)}><Translate value="nav_about"/></a> <a href="#startups" onClick={this.handleClick.bind(this)}><Translate value="nav_startups"/></a> <a href="#events" onClick={this.handleClick.bind(this)}><Translate value="nav_events"/></a> <a href="#newsletter" onClick={this.handleClick.bind(this)}><Translate value="nav_newsletter"/></a> <a href="https://medium.com/comunidade-empreendedora-manguezal" target="_blank"><Translate value="nav_blog"/></a> </div> <LanguageSwitcher /> </nav> </div> </div> ) } }
lhew/manguezal-test
src/components/Menu.js
JavaScript
mit
2,593
<?php if (!defined('PRETZEL_EXCEPTION_SERVER')) exit('No Pretzel No (Server) Exception'); class Pretzel_Exception_Server_IllegalValueForType extends Pretzel_Exception_Server { }
smotyn/Pretzel
src/Pretzel/Exception/Server/IllegalValueForType.php
PHP
mit
180
define( ['polygonjs/math/Color'], function (Color) { "use strict"; var Surface = function (opts) { opts = opts || {}; this.width = opts.width || 640; this.height = opts.height || 480; this.cx = this.width / 2; this.cy = this.height / 2; var canvas = this.createEl('canvas', { style: 'background: black', width: this.width, height: this.height }); var container = typeof opts.container === 'string' ? document.getElementById(opts.container) : opts.container; container.appendChild(canvas); this.container = container; this.canvas = canvas; this.context = canvas.getContext('2d'); return this; }; Surface.create = function (opts) { return new Surface(opts); }; Surface.prototype = { createEl: function (name, attrs) { var el = document.createElement(name); attrs = attrs || {}; for (var attr in attrs) this.setAttr(el, attr, attrs[attr]); return el; }, setAttr: function (el, name, value) { el.setAttribute(name, value); }, setAttrNS: function (el, namespace, name, value) { el.setAttributeNS(namespace, name, value); }, clear: function () { this.context.clearRect(0, 0, this.width, this.height); }, polygon: function (points, color) { var len = points.length; if (len > 1) { var ctx = this.context; var a = points[0]; // var b = points[1]; // var tint = Color.create({r: 0.0, g: 0.05, b: 0.0}); // var gradient = ctx.createLinearGradient( // a.x + this.cx, -a.y + this.cy, // b.x + this.cx, -b.y + this.cy); // // gradient.addColorStop(0, color.clone().subtract(tint).clamp().getHexStyle()); // gradient.addColorStop(1, color.clone().add(tint).clamp().getHexStyle()); ctx.fillStyle = color.getHexStyle(); // ctx.strokeStyle = color; ctx.beginPath(); ctx.moveTo(a.x + this.cx, -a.y + this.cy); for (var i = 1; i < len; i++) { a = points[i]; ctx.lineTo(a.x + this.cx, -a.y + this.cy); } ctx.closePath(); ctx.fill(); // ctx.stroke(); // Gets rid of seams but performance hit } }, line: function (from, to, color) { var ctx = this.context; ctx.strokeStyle = color.getHexStyle(); ctx.beginPath(); ctx.moveTo(from.x + this.cx, -from.x + this.cy); ctx.lineTo(to.x + this.cx, -to.y + this.cy); ctx.stroke(); }, render: function () {} }; return Surface; } );
WebSeed/PolygonJS
polygonjs/surfaces/CanvasSurface.js
JavaScript
mit
3,361
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("05. BooleanVariable")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("05. BooleanVariable")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("d66ea66d-c61a-4b5a-bc31-47890c5e80db")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
g-yonchev/TelerikAcademy
Homeworks/C# 1/02.PrimitiveDataTypesHW/05. BooleanVariable/Properties/AssemblyInfo.cs
C#
mit
1,414
import java.util.*; public class PowerSet { public static Set<Set<Integer>> powerset(Set<Integer> set) { Set<Set<Integer>> ps = new HashSet<Set<Integer>>(); if(set.isEmpty()) { Set<Integer> emptySet = new HashSet<Integer>(); ps.add(emptySet); return ps; } List<Integer> list = new ArrayList<Integer>(set); Integer head = list.get(0); Set<Integer> rest = new HashSet<Integer>(list.subList(1, list.size())); for(Set<Integer> s: powerset(rest)) { Set<Integer> newSet = new HashSet<Integer>(); newSet.add(head); newSet.addAll(s); ps.add(newSet); ps.add(s); } return ps; } public static void main(String[] args) { Set<Integer> sampleSet = new HashSet<Integer>(); sampleSet.add(new Integer(5)); sampleSet.add(new Integer(4)); sampleSet.add(new Integer(3)); sampleSet.add(new Integer(2)); sampleSet.add(new Integer(1)); System.out.println(sampleSet.toString()); System.out.println(powerset(sampleSet).toString()); } }
leejay-schmidt/java-libs
FunJavaPrograms/PowerSet.java
Java
mit
1,040
// © 2015 skwas using System; using System.IO; using System.Linq; using System.Reflection; using ColossalFramework.Plugins; using ColossalFramework.Steamworks; using ICities; namespace skwas.CitiesSkylines { /// <summary> /// Base class for mod implementations. Takes mod info from the type and assembly (AssemblyInfo), and resolves into the actual plugin info. /// </summary> /// <remarks> /// Use of this base class is only working for compiled DLL projects. It is also absolutely important you version your DLL using [assembly: AssemblyVersion("1.0.*")], otherwise the plugin resolving code won't work properly and might return the wrong mod location. /// </remarks> public abstract class ModBase : IUserMod { private readonly Assembly _assembly; private PluginManager.PluginInfo _pluginInfo; protected ModBase() { _assembly = GetType().Assembly; } #region Implementation of IUserMod /// <summary> /// Gets the mod name. /// </summary> /// <remarks>Uses the class name if AssemblyTitleAttribute is missing.</remarks> public virtual string Name { get { var attr = GetAssemblyAttribute<AssemblyTitleAttribute>(); return string.Format("{0} v{1}", attr == null ? GetType().Name : attr.Title, Version ); } } /// <summary> /// Gets the in-game mod description (includes author name if available). /// </summary> /// <remarks>Explicitly implemented, the author name is only added to the game description.</remarks> string IUserMod.Description { get { return string.IsNullOrEmpty(Author) ? Description : string.Format("{0}\nby {1}", Description, Author); } } #endregion /// <summary> /// Gets the mod description. /// </summary> public virtual string Description { get { var attr = GetAssemblyAttribute<AssemblyDescriptionAttribute>(); return attr == null ? null : attr.Description; } } /// <summary> /// Gets the mod author. /// </summary> public virtual string Author { get { var attr = GetAssemblyAttribute<AssemblyCompanyAttribute>(); return attr == null ? null : attr.Company; } } /// <summary> /// Gets the mod version. /// </summary> public virtual Version Version { get { return _assembly.GetName().Version; } } /// <summary> /// Gets the mod path. /// </summary> public virtual string ModPath { get { return PluginInfo == null ? null : PluginInfo.modPath; } } private string _modDllPath; /// <summary> /// Gets the mod dll path. /// </summary> public virtual string ModDllPath { get { var modPath = ModPath; // Prefetch, forces load of plugin info. return _modDllPath ?? modPath; } } /// <summary> /// Gets the steam workshop id of the mod/plugin. In local installations, returns PublishedFileId.invalid. /// </summary> public virtual PublishedFileId SteamWorkshopId { get { return PluginInfo == null ? PublishedFileId.invalid : PluginInfo.publishedFileID; } } /// <summary> /// Gets the plugin info for this mod (and caches it in local variable). /// </summary> protected virtual PluginManager.PluginInfo PluginInfo { get { return _pluginInfo ?? (_pluginInfo = GetPluginInfo()); } } /// <summary> /// Helper to read assembly info. /// </summary> /// <typeparam name="T">The custom attribute to read from the assembly.</typeparam> /// <returns></returns> protected T GetAssemblyAttribute<T>() { var attributes = _assembly.GetCustomAttributes(typeof (T), false); if (attributes.Length == 0) return default(T); return (T)attributes[0]; } /// <summary> /// Enumerates plugins to find our plugin definition. This can be used to also determine save location when using Steam workshop (in which case path is different). /// </summary> /// <returns></returns> private PluginManager.PluginInfo GetPluginInfo() { try { var currentAssemblyName = _assembly.GetName().FullName; foreach (var p in PluginManager.instance.GetPluginsInfo()) { if (!p.isBuiltin) { // Enumerate all assemblies in modPath, until we find the one matching the current assembly. foreach (var assemblyName in Directory.GetFiles(p.modPath, "*.dll", SearchOption.TopDirectoryOnly) .Select(AssemblyName.GetAssemblyName) .Where(assemblyName => assemblyName.FullName.Equals(currentAssemblyName, StringComparison.OrdinalIgnoreCase))) { // This is our assembly! _modDllPath = new Uri(assemblyName.CodeBase).LocalPath; return p; } } } throw new FileNotFoundException(string.Format("The plugin assembly '{0}' could not be resolved.", currentAssemblyName)); } catch (Exception ex) { Log.Error(ex.ToString()); throw; // Note: the plugin will fail if it can't find the assembly. } } } }
skwasjer/CSModBase
ModBase.cs
C#
mit
4,864
package nona.gameengine2d.maths; public class Vector4f extends Vector { public Vector4f() { super(4); } public Vector4f(float x, float y, float z, float w) { super(x, y, z, w); } public Vector4f(float[] v) { super(v); } public Vector4f(Vector4f r) { super(r); } @Override public Vector normalized() { Vector4f result = new Vector4f(this); result.div(length()); return result; } }
LeonardVollmann/GameEngine2D
src/nona/gameengine2d/maths/Vector4f.java
Java
mit
421
<?php namespace Acme\MenusBundle\Tests\Controller; use Symfony\Bundle\FrameworkBundle\Test\WebTestCase; class DefaultControllerTest extends WebTestCase { public function testIndex() { $client = static::createClient(); $crawler = $client->request('GET', '/hello/Fabien'); $this->assertTrue($crawler->filter('html:contains("Hello Fabien")')->count() > 0); } }
oshanrube/iva
src/Acme/MenusBundle/Tests/Controller/DefaultControllerTest.php
PHP
mit
399
'use strict'; var handler = { fragments: null, tab: null, tabId: 0, windowId: 0, captureCmd: '', initContextMenu: function () {}, queryActiveTab: function (callback) { chrome.tabs.query({ active: true, lastFocusedWindow: true }, function (tabs) { var tab = tabs && tabs[0] || {}; handler.tab = tab; handler.tabId = tab.id; handler.windowId = tab.windowId; callback && callback(tab); }); }, checkContentScript: function () { handler.queryActiveTab(function () { handler.executeScript({ file: "js/isLoaded.js" }); }); }, injectContentScript: function () { handler.executeScript({ file: "js/content.js" }, function () { handler.onContentReady(); }); }, executeScript: function (details, callback) { if (handler.tabId) { chrome.tabs.executeScript(handler.tabId, details, callback); } }, onContentReady: function () { if (handler.captureCmd) { handler.sendCaptureCmd(handler.captureCmd); handler.captureCmd = ''; } }, sendCaptureCmd: function (cmd) { handler.queryActiveTab(function (tab) { chrome.tabs.sendMessage(tab.id, { action: cmd }); }); }, captureElement: function () { // capture the selected html element handler.captureCmd = 'captureElement'; handler.checkContentScript(); }, captureRegion: function () { // capture the crop region handler.captureCmd = 'captureRegion'; handler.checkContentScript(); }, captureEntire: function () { // capture entire page handler.captureCmd = 'captureEntire'; handler.checkContentScript(); }, captureVisible: function () { // capture the visible part of page handler.captureCmd = 'captureVisible'; handler.checkContentScript(); }, captureWindow: function () { // capture desktop window }, editContent: function () { // TODO: 更好的编辑模式提示,可离开编辑模式 handler.queryActiveTab(function () { handler.executeScript({ allFrames: true, code: 'document.designMode="on"' }, function () { alert('Now you can edit this page'); }); }); }, clearFragments: function () { handler.fragments = null; }, onFragment: function (message, sender) { chrome.tabs.captureVisibleTab(sender.tab.windowId, { format: 'png' }, function (dataURI) { var fragments = handler.fragments; var fragment = message.fragment; fragment.dataURI = dataURI; if (!fragments) { fragments = handler.fragments = []; } fragments.push(fragment); chrome.tabs.sendMessage(sender.tab.id, { action: 'nextFragment' }); }); }, onCaptureEnd: function (message, sender) { var fragments = handler.fragments; if (fragments && fragments.length) { var fragment = fragments[0]; var totalWidth = fragment.totalWidth; var totalHeight = fragment.totalHeight; if (fragment.ratio !== 1) { totalWidth *= fragment.ratio; totalHeight *= fragment.ratio; } var canvas = document.createElement('canvas'); var context = canvas.getContext('2d'); canvas.width = Math.round(totalWidth); canvas.height = Math.round(totalHeight); var totalCount = fragments.length; var loadedCount = 0; fragments.forEach(function (data) { var image = new Image(); var ratio = data.ratio; var sx = Math.round(data.sx * ratio); var sy = Math.round(data.sy * ratio); var dx = Math.round(data.dx * ratio); var dy = Math.round(data.dy * ratio); var width = Math.round(data.width * ratio); var height = Math.round(data.height * ratio); image.onload = function () { context.drawImage(image, sx, sy, width, height, dx, dy, width, height ); loadedCount++; if (loadedCount === totalCount) { handler.clearFragments(); var croppedDataUrl = canvas.toDataURL('image/png'); chrome.tabs.create({ url: croppedDataUrl, windowId: sender.tab.windowId }); } }; image.src = data.dataURI; }); } console.log(fragments); }, }; // handle message from tabs chrome.runtime.onMessage.addListener(function (message, sender, callback) { console.log(message); if (!sender || sender.id !== chrome.runtime.id || !sender.tab) { return; } var action = message.action; if (action && handler[action]) { return handler[action](message, sender, callback); } });
bubkoo/crx-element-capture
src/js/background.js
JavaScript
mit
4,787
<?php return array( 'plugin.connectedSite.ConnectedServices'=>'Services connectés', );
christophehurpeau/Springbok-Framework-Plugins
connectedSite/config/lang.fr.php
PHP
mit
89
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ASPPatterns.Chap5.DependencyInjection.Model { public class Product { public void AdjustPriceWith(IProductDiscountStrategy discount) { } } }
liqipeng/helloGithub
Book-Code/ASP.NET Design Pattern/ASPPatternsc05/ASPPatterns.Chap5.DependencyInjection/ASPPatterns.Chap5.DependencyInjection.Model/Product.cs
C#
mit
289
class Tagging include DataMapper::Resource property :id, Serial property :tag_id, Integer, :nullable => false property :taggable_id, Integer, :nullable => false property :taggable_type, String, :nullable => false property :tag_context, String, :nullable => false belongs_to :tag def taggable eval("#{taggable_type}.get!(#{taggable_id})") if taggable_type and taggable_id end end
bterlson/dm-more
dm-tags/lib/dm-tags/tagging.rb
Ruby
mit
428
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("_01.Odd_lines")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("_01.Odd_lines")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("f38f3389-37f3-493e-b2ba-8642c2d400b6")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
todorm85/TelerikAcademy
Courses/Programming/C# Part 2/08. Text Files/01. Odd lines/Properties/AssemblyInfo.cs
C#
mit
1,402
package com.vk.api.sdk.objects.users; import com.google.gson.annotations.SerializedName; import java.util.Objects; /** * UserXtrCounters object */ public class UserXtrCounters extends UserFull { @SerializedName("counters") private UserCounters counters; public UserCounters getCounters() { return counters; } @Override public int hashCode() { return Objects.hash(super.hashCode(), counters); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (!super.equals(o)) return false; UserXtrCounters userXtrCounters = (UserXtrCounters) o; return Objects.equals(counters, userXtrCounters.counters); } @Override public String toString() { final StringBuilder sb = new StringBuilder("UserXtrCounters{"); sb.append("counters=").append(counters); sb.append('}'); return sb.toString(); } }
kokorin/vk-java-sdk
sdk/src/main/java/com/vk/api/sdk/objects/users/UserXtrCounters.java
Java
mit
1,010
declare module "electron-builder-http/out/CancellationToken" { /// <reference types="node" /> import { EventEmitter } from "events" export class CancellationToken extends EventEmitter { private parentCancelHandler private _cancelled readonly cancelled: boolean private _parent parent: CancellationToken constructor(parent?: CancellationToken) cancel(): void private onCancel(handler) createPromise<R>(callback: (resolve: (thenableOrResult?: R) => void, reject: (error?: Error) => void, onCancel: (callback: () => void) => void) => void): Promise<R> private removeParentCancelHandler() dispose(): void } export class CancellationError extends Error { constructor() } } declare module "electron-builder-http/out/ProgressCallbackTransform" { /// <reference types="node" /> import { Transform } from "stream" import { CancellationToken } from "electron-builder-http/out/CancellationToken" export interface ProgressInfo { total: number delta: number transferred: number percent: number bytesPerSecond: number } export class ProgressCallbackTransform extends Transform { private readonly total private readonly cancellationToken private readonly onProgress private start private transferred private delta private nextUpdate constructor(total: number, cancellationToken: CancellationToken, onProgress: (info: ProgressInfo) => any) _transform(chunk: any, encoding: string, callback: Function): void _flush(callback: Function): void } } declare module "electron-builder-http/out/publishOptions" { export type PublishProvider = "github" | "bintray" | "s3" | "generic" export type AllPublishOptions = string | GithubOptions | S3Options | GenericServerOptions | BintrayOptions export type Publish = AllPublishOptions | Array<AllPublishOptions> | null /** * Can be specified in the [config](https://github.com/electron-userland/electron-builder/wiki/Options#Config) or any platform- or target- specific options. * * If `GH_TOKEN` is set — defaults to `[{provider: "github"}]`. * * If `BT_TOKEN` is set and `GH_TOKEN` is not set — defaults to `[{provider: "bintray"}]`. */ export interface PublishConfiguration { /** * The provider. */ readonly provider: PublishProvider /** * The owner. */ readonly owner?: string | null readonly token?: string | null } /** * GitHub options. * * GitHub [personal access token](https://help.github.com/articles/creating-an-access-token-for-command-line-use/) is required. You can generate by going to [https://github.com/settings/tokens/new](https://github.com/settings/tokens/new). The access token should have the repo scope/permission. * Define `GH_TOKEN` environment variable. */ export interface GithubOptions extends PublishConfiguration { /** * The repository name. [Detected automatically](#github-repository-and-bintray-package). */ readonly repo?: string | null /** * Whether to use `v`-prefixed tag name. * @default true */ readonly vPrefixedTagName?: boolean /** * The host (including the port if need). * @default github.com */ readonly host?: string | null /** * The protocol. GitHub Publisher supports only `https`. * @default https */ readonly protocol?: "https" | "http" | null /** * The access token to support auto-update from private github repositories. Never specify it in the configuration files. Only for [setFeedURL](module:electron-updater/out/AppUpdater.AppUpdater+setFeedURL). */ readonly token?: string | null /** * Whether to use private github auto-update provider if `GH_TOKEN` environment variable is set. * @see https://github.com/electron-userland/electron-builder/wiki/Auto-Update#private-github-update-repo */ readonly private?: boolean | null } export function githubUrl(options: GithubOptions): string /** * Generic (any HTTP(S) server) options. */ export interface GenericServerOptions extends PublishConfiguration { /** * The base url. e.g. `https://bucket_name.s3.amazonaws.com`. You can use `${os}` (expanded to `mac`, `linux` or `win` according to target platform) and `${arch}` macros. */ readonly url: string /** * The channel. * @default latest */ readonly channel?: string | null } /** * Amazon S3 options. `https` must be used, so, if you use direct Amazon S3 endpoints, format `https://s3.amazonaws.com/bucket_name` [must be used](http://stackoverflow.com/a/11203685/1910191). And do not forget to make files/directories public. * * AWS credentials are required, please see [getting your credentials](http://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/getting-your-credentials.html). * Define `AWS_SECRET_ACCESS_KEY` and `AWS_ACCESS_KEY_ID` [environment variables](http://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/loading-node-credentials-environment.html). Or in the [~/.aws/credentials](http://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/loading-node-credentials-shared.html). */ export interface S3Options extends PublishConfiguration { /** * The bucket name. */ readonly bucket: string /** * The directory path. * @default / */ readonly path?: string | null /** * The region. Is determined and set automatically when publishing. */ readonly region?: string | null /** * The channel. * @default latest */ readonly channel?: string | null /** * The ACL. * @default public-read */ readonly acl?: "private" | "public-read" | null /** * The type of storage to use for the object. * @default STANDARD */ readonly storageClass?: "STANDARD" | "REDUCED_REDUNDANCY" | "STANDARD_IA" | null } export function s3Url(options: S3Options): string /** * Bintray options. */ export interface BintrayOptions extends PublishConfiguration { /** * The Bintray package name. */ readonly package?: string | null /** * The Bintray repository name. * @default generic */ readonly repo?: string | null /** * The Bintray user account. Used in cases where the owner is an organization. */ readonly user?: string | null } export interface VersionInfo { /** * The version. */ readonly version: string } export interface UpdateInfo extends VersionInfo { readonly path: string readonly githubArtifactName?: string | null readonly sha2: string /** * The release name. */ readonly releaseName?: string | null /** * The release notes. */ readonly releaseNotes?: string | null /** * The release date. */ readonly releaseDate: string } } declare module "electron-builder-http" { /// <reference types="node" /> import { EventEmitter } from "events" import { RequestOptions } from "http" import { CancellationToken } from "electron-builder-http/out/CancellationToken" import { ProgressInfo } from "electron-builder-http/out/ProgressCallbackTransform" export interface RequestHeaders { [key: string]: any } export interface Response extends EventEmitter { statusCode?: number statusMessage?: string headers: any setEncoding(encoding: string): void } export interface DownloadOptions { readonly headers?: RequestHeaders | null readonly skipDirCreation?: boolean readonly sha2?: string | null readonly cancellationToken: CancellationToken onProgress?(progress: ProgressInfo): void } export class HttpExecutorHolder { private _httpExecutor httpExecutor: HttpExecutor<any, any> } export const executorHolder: HttpExecutorHolder export function download(url: string, destination: string, options?: DownloadOptions | null): Promise<string> export class HttpError extends Error { readonly response: { statusMessage?: string | undefined statusCode?: number | undefined headers?: { [key: string]: string[] } | undefined } description: any | null constructor(response: { statusMessage?: string | undefined statusCode?: number | undefined headers?: { [key: string]: string[] } | undefined }, description?: any | null) } export abstract class HttpExecutor<REQUEST_OPTS, REQUEST> { protected readonly maxRedirects: number request<T>(options: RequestOptions, cancellationToken: CancellationToken, data?: { [name: string]: any } | null): Promise<T> protected abstract doApiRequest<T>(options: REQUEST_OPTS, cancellationToken: CancellationToken, requestProcessor: (request: REQUEST, reject: (error: Error) => void) => void, redirectCount: number): Promise<T> abstract download(url: string, destination: string, options: DownloadOptions): Promise<string> protected handleResponse(response: Response, options: RequestOptions, cancellationToken: CancellationToken, resolve: (data?: any) => void, reject: (error: Error) => void, redirectCount: number, requestProcessor: (request: REQUEST, reject: (error: Error) => void) => void): void protected abstract doRequest(options: any, callback: (response: any) => void): any protected doDownload(requestOptions: any, destination: string, redirectCount: number, options: DownloadOptions, callback: (error: Error | null) => void, onCancel: (callback: () => void) => void): void protected addTimeOutHandler(request: any, callback: (error: Error) => void): void } export function request<T>(options: RequestOptions, cancellationToken: CancellationToken, data?: { [name: string]: any } | null): Promise<T> export function configureRequestOptions(options: RequestOptions, token?: string | null, method?: "GET" | "DELETE" | "PUT"): RequestOptions export function dumpRequestOptions(options: RequestOptions): string } declare module "electron-builder-http/out/bintray" { import { BintrayOptions } from "electron-builder-http/out/publishOptions" import { CancellationToken } from "electron-builder-http/out/CancellationToken" export function bintrayRequest<T>(path: string, auth: string | null, data: { [name: string]: any } | null | undefined, cancellationToken: CancellationToken, method?: "GET" | "DELETE" | "PUT"): Promise<T> export interface Version { readonly name: string readonly package: string } export interface File { name: string path: string sha1: string sha256: string } export class BintrayClient { private readonly cancellationToken private readonly basePath readonly auth: string | null readonly repo: string readonly owner: string readonly user: string readonly packageName: string constructor(options: BintrayOptions, cancellationToken: CancellationToken, apiKey?: string | null) getVersion(version: string): Promise<Version> getVersionFiles(version: string): Promise<Array<File>> createVersion(version: string): Promise<any> deleteVersion(version: string): Promise<any> } }
eyang414/superFriend
electronApp/node_modules/electron-builder-http/out/electron-builder-http.d.ts
TypeScript
mit
11,265
<?php /* :menu:show.html.twig */ class __TwigTemplate_c6c87740e1e23e28cd7ec08186f946f29f7e280dd27072f88536dcc022e66357 extends Twig_Template { public function __construct(Twig_Environment $env) { parent::__construct($env); // line 1 $this->parent = $this->loadTemplate("base.html.twig", ":menu:show.html.twig", 1); $this->blocks = array( 'body' => array($this, 'block_body'), ); } protected function doGetParent(array $context) { return "base.html.twig"; } protected function doDisplay(array $context, array $blocks = array()) { $this->parent->display($context, array_merge($this->blocks, $blocks)); } // line 3 public function block_body($context, array $blocks = array()) { // line 4 echo " <h1>Menu</h1> <div align=\"right\"> <a href=\""; // line 9 echo twig_escape_filter($this->env, $this->env->getExtension('routing')->getPath("menu_index", array("id" => $this->getAttribute((isset($context["menu"]) ? $context["menu"] : null), "id", array()))), "html", null, true); echo "\">Volver <span class=\"glyphicon glyphicon-arrow-left\"></span> </a> </div> <div class=\"page-container\"> <div class=\"row\"> <div class=\"col-md-12\"> <!-- BEGIN EXAMPLE TABLE PORTLET--> <div class=\"portlet light bordered\"> <div class=\"portlet-title\"> <div class=\"caption font-green\"> <i class=\"icon-settings font-green\"></i> <span class=\"caption-subject bold uppercase\"></span> </div> </div> <div class=\"portlet-body\"> <table class=\"table table-striped table-bordered table-hover dt-responsive\" width=\"100%\" id=\"sample_2\"> <tr> <th>Descripcion</th> <td>"; // line 29 echo $this->getAttribute((isset($context["menu"]) ? $context["menu"] : null), "descripcion", array()); echo "</td> </tr> <tr> <th>Visible</th> <td>"; // line 34 if ($this->getAttribute((isset($context["menu"]) ? $context["menu"] : null), "visible", array())) { echo "Sí"; } else { echo "No"; } echo "</td> </tr> <tr> <th>Posicion</th> <td>"; // line 38 if ($this->getAttribute((isset($context["menu"]) ? $context["menu"] : null), "posicion", array())) { echo "Sí"; } else { echo "No"; } echo "</td> </tr> <tr> <th>Enlace</th> <td>"; // line 42 if ($this->getAttribute((isset($context["menu"]) ? $context["menu"] : null), "enlace", array())) { echo "Sí"; } else { echo "No"; } echo "</td> </tr> <tr> <th>Id</th> <td>"; // line 47 echo twig_escape_filter($this->env, $this->getAttribute((isset($context["menu"]) ? $context["menu"] : null), "id", array()), "html", null, true); echo "</td> </tr> </table> </div> </div> <!-- END EXAMPLE TABLE PORTLET--> </div> </div> <!-- END CONTENT BODY --> </div> <div align=\"right\"> "; // line 63 echo $this->env->getExtension('form')->renderer->renderBlock((isset($context["delete_form"]) ? $context["delete_form"] : null), 'form_start'); echo " <a href=\""; // line 64 echo twig_escape_filter($this->env, $this->env->getExtension('routing')->getPath("menu_edit", array("id" => $this->getAttribute((isset($context["menu"]) ? $context["menu"] : null), "id", array()))), "html", null, true); echo "\" class=\"btn btn-info\" role=\"button\">Editar</a> <input type=\"submit\" class=\"btn btn-danger\" value=\"Eliminar\"> <!--input type=\"submit\" value=\"Eliminar\"--> </button> "; // line 69 echo $this->env->getExtension('form')->renderer->renderBlock((isset($context["delete_form"]) ? $context["delete_form"] : null), 'form_end'); echo " </div> "; } public function getTemplateName() { return ":menu:show.html.twig"; } public function isTraitable() { return false; } public function getDebugInfo() { return array ( 134 => 69, 126 => 64, 122 => 63, 103 => 47, 91 => 42, 80 => 38, 69 => 34, 61 => 29, 38 => 9, 31 => 4, 28 => 3, 11 => 1,); } } /* {% extends 'base.html.twig' %}*/ /* */ /* {% block body %}*/ /* <h1>Menu</h1>*/ /* */ /* */ /* */ /* <div align="right">*/ /* <a href="{{ path('menu_index', { 'id': menu.id }) }}">Volver*/ /* <span class="glyphicon glyphicon-arrow-left"></span>*/ /* </a> */ /* </div>*/ /* <div class="page-container">*/ /* */ /* <div class="row">*/ /* <div class="col-md-12">*/ /* <!-- BEGIN EXAMPLE TABLE PORTLET-->*/ /* <div class="portlet light bordered">*/ /* <div class="portlet-title">*/ /* <div class="caption font-green">*/ /* <i class="icon-settings font-green"></i>*/ /* <span class="caption-subject bold uppercase"></span>*/ /* </div> */ /* </div> */ /* <div class="portlet-body">*/ /* <table class="table table-striped table-bordered table-hover dt-responsive" width="100%" id="sample_2">*/ /* <tr>*/ /* <th>Descripcion</th>*/ /* <td>{{ menu.descripcion | raw}}</td>*/ /* </tr>*/ /* */ /* <tr>*/ /* <th>Visible</th>*/ /* <td>{% if menu.visible %}Sí{% else %}No{% endif %}</td>*/ /* </tr>*/ /* <tr>*/ /* <th>Posicion</th>*/ /* <td>{% if menu.posicion %}Sí{% else %}No{% endif %}</td>*/ /* </tr>*/ /* <tr>*/ /* <th>Enlace</th>*/ /* <td>{% if menu.enlace %}Sí{% else %}No{% endif %}</td>*/ /* </tr>*/ /* */ /* <tr>*/ /* <th>Id</th>*/ /* <td>{{ menu.id }}</td>*/ /* </tr>*/ /* </table>*/ /* */ /* </div>*/ /* </div> */ /* <!-- END EXAMPLE TABLE PORTLET-->*/ /* </div>*/ /* */ /* </div>*/ /* <!-- END CONTENT BODY -->*/ /* </div> */ /* */ /* */ /* <div align="right">*/ /* */ /* {{ form_start(delete_form) }}*/ /* <a href="{{ path('menu_edit', { 'id': menu.id }) }}" class="btn btn-info" role="button">Editar</a>*/ /* */ /* <input type="submit" class="btn btn-danger" value="Eliminar">*/ /* <!--input type="submit" value="Eliminar"-->*/ /* </button>*/ /* {{ form_end(delete_form) }} */ /* */ /* </div>*/ /* */ /* */ /* */ /* */ /* */ /* {% endblock %}*/ /* */
mwveliz/sitio
app/prod/cache/twig/b4/b462afc70965e9a17df2a81b97874458452b1f180b2dd42f516196f0e7c44238.php
PHP
mit
9,504
<?php declare(strict_types=1); /** * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) * * Licensed under The MIT License * For full copyright and license information, please see the LICENSE.txt * Redistributions of files must retain the above copyright notice. * * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) * @link https://cakephp.org CakePHP(tm) Project * @since 3.0.0 * @license https://opensource.org/licenses/mit-license.php MIT License */ namespace Cake\View\Widget; use Cake\View\Form\ContextInterface; use Cake\View\Helper\IdGeneratorTrait; use Cake\View\StringTemplate; /** * Input widget class for generating multiple checkboxes. */ class MultiCheckboxWidget implements WidgetInterface { use IdGeneratorTrait; /** * Template instance to use. * * @var \Cake\View\StringTemplate */ protected $_templates; /** * Label widget instance. * * @var \Cake\View\Widget\LabelWidget */ protected $_label; /** * Render multi-checkbox widget. * * This class uses the following templates: * * - `checkbox` Renders checkbox input controls. Accepts * the `name`, `value` and `attrs` variables. * - `checkboxWrapper` Renders the containing div/element for * a checkbox and its label. Accepts the `input`, and `label` * variables. * - `multicheckboxWrapper` Renders a wrapper around grouped inputs. * - `multicheckboxTitle` Renders the title element for grouped inputs. * * @param \Cake\View\StringTemplate $templates Templates list. * @param \Cake\View\Widget\LabelWidget $label Label widget instance. */ public function __construct(StringTemplate $templates, LabelWidget $label) { $this->_templates = $templates; $this->_label = $label; } /** * Render multi-checkbox widget. * * Data supports the following options. * * - `name` The name attribute of the inputs to create. * `[]` will be appended to the name. * - `options` An array of options to create checkboxes out of. * - `val` Either a string/integer or array of values that should be * checked. Can also be a complex options set. * - `disabled` Either a boolean or an array of checkboxes to disable. * - `escape` Set to false to disable HTML escaping. * - `options` An associative array of value=>labels to generate options for. * - `idPrefix` Prefix for generated ID attributes. * * ### Options format * * The options option can take a variety of data format depending on * the complexity of HTML you want generated. * * You can generate simple options using a basic associative array: * * ``` * 'options' => ['elk' => 'Elk', 'beaver' => 'Beaver'] * ``` * * If you need to define additional attributes on your option elements * you can use the complex form for options: * * ``` * 'options' => [ * ['value' => 'elk', 'text' => 'Elk', 'data-foo' => 'bar'], * ] * ``` * * This form **requires** that both the `value` and `text` keys be defined. * If either is not set options will not be generated correctly. * * @param array $data The data to generate a checkbox set with. * @param \Cake\View\Form\ContextInterface $context The current form context. * @return string */ public function render(array $data, ContextInterface $context): string { $data += [ 'name' => '', 'escape' => true, 'options' => [], 'disabled' => null, 'val' => null, 'idPrefix' => null, 'templateVars' => [], 'label' => true, ]; $this->_idPrefix = $data['idPrefix']; $this->_clearIds(); return implode('', $this->_renderInputs($data, $context)); } /** * Render the checkbox inputs. * * @param array $data The data array defining the checkboxes. * @param \Cake\View\Form\ContextInterface $context The current form context. * @return array An array of rendered inputs. */ protected function _renderInputs(array $data, ContextInterface $context): array { $out = []; foreach ($data['options'] as $key => $val) { // Grouped inputs in a fieldset. if (is_string($key) && is_array($val) && !isset($val['text'], $val['value'])) { $inputs = $this->_renderInputs(['options' => $val] + $data, $context); $title = $this->_templates->format('multicheckboxTitle', ['text' => $key]); $out[] = $this->_templates->format('multicheckboxWrapper', [ 'content' => $title . implode('', $inputs), ]); continue; } // Standard inputs. $checkbox = [ 'value' => $key, 'text' => $val, ]; if (is_array($val) && isset($val['text'], $val['value'])) { $checkbox = $val; } if (!isset($checkbox['templateVars'])) { $checkbox['templateVars'] = $data['templateVars']; } if (!isset($checkbox['label'])) { $checkbox['label'] = $data['label']; } if (!empty($data['templateVars'])) { $checkbox['templateVars'] = array_merge($data['templateVars'], $checkbox['templateVars']); } $checkbox['name'] = $data['name']; $checkbox['escape'] = $data['escape']; $checkbox['checked'] = $this->_isSelected((string)$checkbox['value'], $data['val']); $checkbox['disabled'] = $this->_isDisabled((string)$checkbox['value'], $data['disabled']); if (empty($checkbox['id'])) { if (isset($data['id'])) { $checkbox['id'] = $data['id'] . '-' . trim( $this->_idSuffix((string)$checkbox['value']), '-' ); } else { $checkbox['id'] = $this->_id($checkbox['name'], (string)$checkbox['value']); } } $out[] = $this->_renderInput($checkbox + $data, $context); } return $out; } /** * Render a single checkbox & wrapper. * * @param array $checkbox An array containing checkbox key/value option pairs * @param \Cake\View\Form\ContextInterface $context Context object. * @return string */ protected function _renderInput(array $checkbox, ContextInterface $context): string { $input = $this->_templates->format('checkbox', [ 'name' => $checkbox['name'] . '[]', 'value' => $checkbox['escape'] ? h($checkbox['value']) : $checkbox['value'], 'templateVars' => $checkbox['templateVars'], 'attrs' => $this->_templates->formatAttributes( $checkbox, ['name', 'value', 'text', 'options', 'label', 'val', 'type'] ), ]); if ($checkbox['label'] === false && strpos($this->_templates->get('checkboxWrapper'), '{{input}}') === false) { $label = $input; } else { $labelAttrs = is_array($checkbox['label']) ? $checkbox['label'] : []; $labelAttrs += [ 'for' => $checkbox['id'], 'escape' => $checkbox['escape'], 'text' => $checkbox['text'], 'templateVars' => $checkbox['templateVars'], 'input' => $input, ]; if ($checkbox['checked']) { $labelAttrs = (array)$this->_templates->addClass($labelAttrs, 'selected'); } $label = $this->_label->render($labelAttrs, $context); } return $this->_templates->format('checkboxWrapper', [ 'templateVars' => $checkbox['templateVars'], 'label' => $label, 'input' => $input, ]); } /** * Helper method for deciding what options are selected. * * @param string $key The key to test. * @param array|string|null $selected The selected values. * @return bool */ protected function _isSelected(string $key, $selected): bool { if ($selected === null) { return false; } if (!is_array($selected)) { return $key === (string)$selected; } $strict = !is_numeric($key); return in_array($key, $selected, $strict); } /** * Helper method for deciding what options are disabled. * * @param string $key The key to test. * @param mixed $disabled The disabled values. * @return bool */ protected function _isDisabled(string $key, $disabled): bool { if ($disabled === null || $disabled === false) { return false; } if ($disabled === true || is_string($disabled)) { return true; } $strict = !is_numeric($key); return in_array($key, $disabled, $strict); } /** * @inheritDoc */ public function secureFields(array $data): array { return [$data['name']]; } }
dakota/cakephp
src/View/Widget/MultiCheckboxWidget.php
PHP
mit
9,482
package de.henningBrinkmann.mybatisSample.mapper; import org.apache.ibatis.annotations.Select; import de.henningBrinkmann.mybatisSample.xmltv.Description; public interface DescriptionMapper { void insertDescription(Description description); @Select("SELECT * FROM mybatissample.description WHERE `value` = #{value};") Description findDescriptionByValue(String value); }
hebrinkmann/mybatis
src/main/java/de/henningBrinkmann/mybatisSample/mapper/DescriptionMapper.java
Java
mit
378
package com.chernowii.hero4; import android.app.Activity; import android.content.Intent; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.widget.Toast; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; public class OCVideo extends Activity { public static String getFileContents(final File file) throws IOException { final InputStream inputStream = new FileInputStream(file); final BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); final StringBuilder stringBuilder = new StringBuilder(); boolean done = false; while (!done) { final String line = reader.readLine(); done = (line == null); if (line != null) { stringBuilder.append(line); } } reader.close(); inputStream.close(); return stringBuilder.toString(); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_ocvideo); String yourFilePath = this.getFilesDir() + "/" + "camconfig.txt"; File yourFile = new File( yourFilePath ); try { String password = getFileContents(yourFile); new HttpAsyncTask().execute("http://10.5.5.9/camera/CM?t=" + password + "&p=%00"); } catch (IOException e) { e.printStackTrace(); } Intent intentTwo = new Intent(this, MainActivity.class); startActivity(intentTwo); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_ocvideo, 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(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } public static String GET(String url){ InputStream inputStream = null; String result = ""; try { // create HttpClient HttpClient httpclient = new DefaultHttpClient(); // make GET request to the given URL HttpResponse httpResponse = httpclient.execute(new HttpGet(url)); // receive response as inputStream inputStream = httpResponse.getEntity().getContent(); // convert inputstream to string if(inputStream != null) result = convertInputStreamToString(inputStream); else result = "Did not work!"; } catch (Exception e) { Log.d("InputStream", e.getLocalizedMessage()); } return result; } private static String convertInputStreamToString(InputStream inputStream) throws IOException{ BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream)); String line = ""; String result = ""; while((line = bufferedReader.readLine()) != null) result += line; inputStream.close(); return result; } public boolean isConnected(){ ConnectivityManager connMgr = (ConnectivityManager) getSystemService(this.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); if (networkInfo != null && networkInfo.isConnected()) return true; else return false; } private class HttpAsyncTask extends AsyncTask<String, Void, String> { @Override protected String doInBackground(String... urls) { return GET(urls[0]); } // onPostExecute displays the results of the AsyncTask. @Override protected void onPostExecute(String result) { Toast.makeText(getBaseContext(), "Done!", Toast.LENGTH_SHORT).show(); ; } } }
KonradIT/goprohero
GoProHERO4Controller/app/src/main/java/com/chernowii/hero4/OCVideo.java
Java
mit
4,726
const isAsync = (caller) => caller && caller.ASYNC; module.exports = api => { const ASYNC = api.caller(isAsync); return { babelrc: false, plugins: [ ['./babel-plugin-$-identifiers-and-imports', { ASYNC }], ['macros', { async: { ASYNC } }], // use dead code elimination to clean up if(false) {} and if(true) {} ['minify-dead-code-elimination', { keepFnName: true, keepFnArgs: true, keepClassName: true }], ], } }
sithmel/iter-tools
generate/babel-generate.config.js
JavaScript
mit
456
import unittest from tweet_dns.sources.source_base import SourceBase class SourceBaseTest(unittest.TestCase): def test_regex(self): text = """ 1.1.1.1 192.168.0.1 127.0.0.1 255.255.255.255 256. 1.1..1 1.200.3.4 """ correct_ips = ['1.1.1.1', '192.168.0.1', '127.0.0.1', '255.255.255.255', '1.200.3.4'] self.assert_(list(SourceBase._search_for_ips(text)) == correct_ips) with self.assertRaises(RuntimeError): SourceBase().get()
AstromechZA/TweetDNS
tests/sources/source_base_test.py
Python
mit
579
#!/usr/bin/env python3 # Copyright (c) 2017-2019 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test that the wallet resends transactions periodically.""" from collections import defaultdict import time from test_framework.blocktools import create_block, create_coinbase from test_framework.messages import ToHex from test_framework.mininode import P2PInterface, mininode_lock from test_framework.test_framework import BitcoinTestFramework from test_framework.util import assert_equal, wait_until class P2PStoreTxInvs(P2PInterface): def __init__(self): super().__init__() self.tx_invs_received = defaultdict(int) def on_inv(self, message): # Store how many times invs have been received for each tx. for i in message.inv: if i.type == 1: # save txid self.tx_invs_received[i.hash] += 1 class ResendWalletTransactionsTest(BitcoinTestFramework): def set_test_params(self): self.num_nodes = 1 def skip_test_if_missing_module(self): self.skip_if_no_wallet() def run_test(self): node = self.nodes[0] # alias node.add_p2p_connection(P2PStoreTxInvs()) self.log.info("Create a new transaction and wait until it's broadcast") txid = int(node.sendtoaddress(node.getnewaddress(), 1), 16) # Wallet rebroadcast is first scheduled 1 sec after startup (see # nNextResend in ResendWalletTransactions()). Sleep for just over a # second to be certain that it has been called before the first # setmocktime call below. time.sleep(1.1) # Can take a few seconds due to transaction trickling wait_until(lambda: node.p2p.tx_invs_received[txid] >= 1, lock=mininode_lock) # Add a second peer since txs aren't rebroadcast to the same peer (see filterInventoryKnown) node.add_p2p_connection(P2PStoreTxInvs()) self.log.info("Create a block") # Create and submit a block without the transaction. # Transactions are only rebroadcast if there has been a block at least five minutes # after the last time we tried to broadcast. Use mocktime and give an extra minute to be sure. block_time = int(time.time()) + 6 * 60 node.setmocktime(block_time) block = create_block(int(node.getbestblockhash(), 16), create_coinbase(node.getblockchaininfo()['blocks']), block_time) block.nVersion = 3 block.rehash() block.solve() node.submitblock(ToHex(block)) # Transaction should not be rebroadcast node.p2ps[1].sync_with_ping() assert_equal(node.p2ps[1].tx_invs_received[txid], 0) self.log.info("Transaction should be rebroadcast after 30 minutes") # Use mocktime and give an extra 5 minutes to be sure. rebroadcast_time = int(time.time()) + 41 * 60 node.setmocktime(rebroadcast_time) wait_until(lambda: node.p2ps[1].tx_invs_received[txid] >= 1, lock=mininode_lock) if __name__ == '__main__': ResendWalletTransactionsTest().main()
afk11/bitcoin
test/functional/wallet_resendwallettransactions.py
Python
mit
3,194
using System; using System.Linq; using System.Threading.Tasks; using Baseline; using Marten.Testing.Events; using Marten.Testing.Events.Projections; using Marten.Testing.Harness; using Shouldly; namespace Marten.Testing.Examples { public class event_store_quickstart { public void capture_events() { #region sample_event-store-quickstart var store = DocumentStore.For(_ => { _.Connection(ConnectionSource.ConnectionString); _.Events.Projections.SelfAggregate<QuestParty>(); }); var questId = Guid.NewGuid(); using (var session = store.OpenSession()) { var started = new QuestStarted { Name = "Destroy the One Ring" }; var joined1 = new MembersJoined(1, "Hobbiton", "Frodo", "Sam"); // Start a brand new stream and commit the new events as // part of a transaction session.Events.StartStream<Quest>(questId, started, joined1); session.SaveChanges(); // Append more events to the same stream var joined2 = new MembersJoined(3, "Buckland", "Merry", "Pippen"); var joined3 = new MembersJoined(10, "Bree", "Aragorn"); var arrived = new ArrivedAtLocation { Day = 15, Location = "Rivendell" }; session.Events.Append(questId, joined2, joined3, arrived); session.SaveChanges(); } #endregion sample_event-store-quickstart #region sample_event-store-start-stream-with-explicit-type using (var session = store.OpenSession()) { var started = new QuestStarted { Name = "Destroy the One Ring" }; var joined1 = new MembersJoined(1, "Hobbiton", "Frodo", "Sam"); // Start a brand new stream and commit the new events as // part of a transaction session.Events.StartStream(typeof(Quest), questId, started, joined1); } #endregion sample_event-store-start-stream-with-explicit-type #region sample_event-store-start-stream-with-no-type using (var session = store.OpenSession()) { var started = new QuestStarted { Name = "Destroy the One Ring" }; var joined1 = new MembersJoined(1, "Hobbiton", "Frodo", "Sam"); // Start a brand new stream and commit the new events as // part of a transaction // no stream type will be stored in database session.Events.StartStream(questId, started, joined1); } #endregion sample_event-store-start-stream-with-no-type #region sample_events-fetching-stream using (var session = store.OpenSession()) { var events = session.Events.FetchStream(questId); events.Each(evt => { Console.WriteLine($"{evt.Version}.) {evt.Data}"); }); } #endregion sample_events-fetching-stream #region sample_events-aggregate-on-the-fly using (var session = store.OpenSession()) { // questId is the id of the stream var party = session.Events.AggregateStream<QuestParty>(questId); Console.WriteLine(party); var party_at_version_3 = session.Events .AggregateStream<QuestParty>(questId, 3); var party_yesterday = session.Events .AggregateStream<QuestParty>(questId, timestamp: DateTime.UtcNow.AddDays(-1)); } #endregion sample_events-aggregate-on-the-fly using (var session = store.OpenSession()) { var party = session.Load<QuestParty>(questId); Console.WriteLine(party); } } #region sample_using-fetch-stream public void load_event_stream(IDocumentSession session, Guid streamId) { // Fetch *all* of the events for this stream var events1 = session.Events.FetchStream(streamId); // Fetch the events for this stream up to and including version 5 var events2 = session.Events.FetchStream(streamId, 5); // Fetch the events for this stream at this time yesterday var events3 = session.Events .FetchStream(streamId, timestamp: DateTime.UtcNow.AddDays(-1)); } public async Task load_event_stream_async(IDocumentSession session, Guid streamId) { // Fetch *all* of the events for this stream var events1 = await session.Events.FetchStreamAsync(streamId); // Fetch the events for this stream up to and including version 5 var events2 = await session.Events.FetchStreamAsync(streamId, 5); // Fetch the events for this stream at this time yesterday var events3 = await session.Events .FetchStreamAsync(streamId, timestamp: DateTime.UtcNow.AddDays(-1)); } #endregion sample_using-fetch-stream #region sample_load-a-single-event public void load_a_single_event_synchronously(IDocumentSession session, Guid eventId) { // If you know what the event type is already var event1 = session.Events.Load<MembersJoined>(eventId); // If you do not know what the event type is var event2 = session.Events.Load(eventId); } public async Task load_a_single_event_asynchronously(IDocumentSession session, Guid eventId) { // If you know what the event type is already var event1 = await session.Events.LoadAsync<MembersJoined>(eventId); // If you do not know what the event type is var event2 = await session.Events.LoadAsync(eventId); } #endregion sample_load-a-single-event #region sample_using_live_transformed_events public void using_live_transformed_events(IDocumentSession session) { var started = new QuestStarted { Name = "Find the Orb" }; var joined = new MembersJoined { Day = 2, Location = "Faldor's Farm", Members = new string[] { "Garion", "Polgara", "Belgarath" } }; var slayed1 = new MonsterSlayed { Name = "Troll" }; var slayed2 = new MonsterSlayed { Name = "Dragon" }; MembersJoined joined2 = new MembersJoined { Day = 5, Location = "Sendaria", Members = new string[] { "Silk", "Barak" } }; session.Events.StartStream<Quest>(started, joined, slayed1, slayed2); session.SaveChanges(); // Our MonsterDefeated documents are created inline // with the SaveChanges() call above and are available // for querying session.Query<MonsterDefeated>().Count() .ShouldBe(2); } #endregion sample_using_live_transformed_events } }
JasperFx/Marten
src/Marten.Testing/Examples/event_store_quickstart.cs
C#
mit
7,180
import React from 'react'; import PropTypes from 'prop-types'; import Post from './Post'; const Posts = ({ posts }) => ( <div> {posts .filter(post => post.frontmatter.title.length > 0) .map((post, index) => <Post key={index} post={post} />)} </div> ); Posts.propTypes = { posts: PropTypes.arrayOf(PropTypes.object), }; export default Posts;
kbariotis/kostasbariotis.com
src/components/blog/Posts.js
JavaScript
mit
367
require 'bio-ucsc' describe "Bio::Ucsc::Hg18::BurgeRnaSeqGemMapperAlignBreastAllRawSignal" do describe "#find_by_interval" do context "given range chr1:1-10,000" do it 'returns a record (r.chrom == "chr1")' do Bio::Ucsc::Hg18::DBConnection.default Bio::Ucsc::Hg18::DBConnection.connect i = Bio::GenomicInterval.parse("chr1:1-10,000") r = Bio::Ucsc::Hg18::BurgeRnaSeqGemMapperAlignBreastAllRawSignal.find_by_interval(i) r.chrom.should == "chr1" end end end end
misshie/bioruby-ucsc-api
spec/hg18/burgernaseqgemmapperalignbreastallrawsignal_spec.rb
Ruby
mit
527
/** The MIT License (MIT) * Copyright (c) 2016 铭飞科技 * 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.mingsoft.people.dao; import org.apache.ibatis.annotations.Param; import com.mingsoft.base.dao.IBaseDao; /** * * * <p> * <b>铭飞MS平台</b> * </p> * * <p> * Copyright: Copyright (c) 2014 - 2015 * </p> * * <p> * Company:景德镇铭飞科技有限公司 * </p> * * @author 刘继平 * * @version 300-001-001 * * <p> * 版权所有 铭飞科技 * </p> * * <p> * Comments:用户信息持久化层接口,继承IBaseDao * </p> * * <p> * Create Date:2014-9-4 * </p> * * <p> * Modification history: * </p> */ public interface IPeopleUserDao extends IBaseDao { /** * 根据用户id集合批量删除用户 * @param peopleIds 用户id集合 */ public void deletePeopleUsers(@Param("peopleIds") int[] peopleIds); }
shentt3214/mcms
src/main/java/com/mingsoft/people/dao/IPeopleUserDao.java
Java
mit
1,907
from BeautifulSoup import BeautifulSoup as b from collections import Counter import urllib2, numpy import matplotlib.pyplot as plt response = urllib2.urlopen('http://en.wikipedia.org/wiki/List_of_Question_Time_episodes') html = response.read() soup = b(html) people = [] tables = soup.findAll('table','wikitable')[2:] #First two tables are other content year_headers = soup.findAll('h2')[2:-4] # Likewise with headers years = [] for year in year_headers: spans = year.findAll('span') years.append(int(spans[0].text)) for i, table in enumerate(tables[-10:]): print i for row in table.findAll('tr'): cols = row.findAll('td') if len(cols) >= 3: names = cols[2] nstring = names.getText().split(',') for name in nstring: people.append(name) else: continue counts = Counter(people) order = numpy.argsort(counts.values()) names = numpy.array(counts.keys())[order][::-1] appearances = numpy.array(counts.values())[order][::-1] N = 20 app_percentage = (appearances[:N] / float(numpy.sum(appearances[:N]))) * 100 index = numpy.arange(N)+0.25 bar_width = 0.5 """ PLOT THAT SHIT """ Fig = plt.figure(figsize=(10,6)) Ax = Fig.add_subplot(111) Apps = Ax.bar(index,app_percentage,bar_width, color='dodgerblue',alpha=0.8,linewidth=0) Ax.set_xticks(index+ 0.5*bar_width) Ax.set_xticklabels(names[:N],rotation=90) Ax.set_ylabel('Appearance Percentage') amin,amax = numpy.min(app_percentage), numpy.max(app_percentage) def autolabel(Bars): # attach some text labels for Bar in Bars: height = Bar.get_height() Ax.text(Bar.get_x()+Bar.get_width()/2., 1.03*height, '%.1f'%float(height), ha='center', va='bottom',fontsize=9) autolabel(Apps) Ax.set_ylim([amin-1,amax+1]) Ax.set_title('Top '+str(N)+' QT guests') Fig.subplots_adjust(bottom=0.26,right=0.95,left=0.07) Fig.savefig('QTappearances.png',fmt='png') plt.show()
dunkenj/DimbleData
QTstats.py
Python
mit
1,981
'use strict'; const Promise = require('bluebird'); const { Transform } = require('readable-stream'); const vfs = require('vinyl-fs'); module.exports = function assets(src, dest, options = {}) { const { parser, env } = options; Reflect.deleteProperty(options, 'parser'); Reflect.deleteProperty(options, 'env'); const opts = Object.assign({ allowEmpty: true }, options); return new Promise((resolve, reject) => { let stream = vfs.src(src, opts); if (parser) { const transform = new Transform({ objectMode: true, transform: (file, enc, cb) => { parser(file, enc, env); return cb(null, file); }, }); stream = stream.pipe(transform); } stream.pipe(vfs.dest(dest)).on('error', reject).on('finish', resolve); }); };
oddbird/sassdoc-theme-herman
lib/utils/assets.js
JavaScript
mit
801
// Copyright (c) 2009-2012 The Bitcoin 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> // for 'map_list_of()' #include <boost/foreach.hpp> #include "checkpoints.h" #include "db.h" #include "main.h" #include "uint256.h" namespace Checkpoints { typedef std::map<int, uint256> MapCheckpoints; // // What makes a good checkpoint block? // + Is surrounded by blocks with reasonable timestamps // (no blocks before with a timestamp after, none after with // timestamp before) // + Contains no strange transactions // static MapCheckpoints mapCheckpoints = boost::assign::map_list_of ( 0, hashGenesisBlockOfficial ) ; static MapCheckpoints mapCheckpointsTestnet = boost::assign::map_list_of ( 0, hashGenesisBlockTestNet ) ; bool CheckHardened(int nHeight, const uint256& hash) { MapCheckpoints& checkpoints = (fTestNet ? mapCheckpointsTestnet : mapCheckpoints); MapCheckpoints::const_iterator i = checkpoints.find(nHeight); if (i == checkpoints.end()) return true; return hash == i->second; } int GetTotalBlocksEstimate() { MapCheckpoints& checkpoints = (fTestNet ? mapCheckpointsTestnet : mapCheckpoints); return checkpoints.rbegin()->first; } CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex) { MapCheckpoints& checkpoints = (fTestNet ? mapCheckpointsTestnet : mapCheckpoints); BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints) { const uint256& hash = i.second; std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash); if (t != mapBlockIndex.end()) return t->second; } return NULL; } // nexus: synchronized checkpoint (centrally broadcasted) uint256 hashSyncCheckpoint = 0; uint256 hashPendingCheckpoint = 0; CSyncCheckpoint checkpointMessage; CSyncCheckpoint checkpointMessagePending; uint256 hashInvalidCheckpoint = 0; CCriticalSection cs_hashSyncCheckpoint; // nexus: get last synchronized checkpoint CBlockIndex* GetLastSyncCheckpoint() { LOCK(cs_hashSyncCheckpoint); if (!mapBlockIndex.count(hashSyncCheckpoint)) error("GetSyncCheckpoint: block index missing for current sync-checkpoint %s", hashSyncCheckpoint.ToString().c_str()); else return mapBlockIndex[hashSyncCheckpoint]; return NULL; } // nexus: only descendant of current sync-checkpoint is allowed bool ValidateSyncCheckpoint(uint256 hashCheckpoint) { if (!mapBlockIndex.count(hashSyncCheckpoint)) return error("ValidateSyncCheckpoint: block index missing for current sync-checkpoint %s", hashSyncCheckpoint.ToString().c_str()); if (!mapBlockIndex.count(hashCheckpoint)) return error("ValidateSyncCheckpoint: block index missing for received sync-checkpoint %s", hashCheckpoint.ToString().c_str()); CBlockIndex* pindexSyncCheckpoint = mapBlockIndex[hashSyncCheckpoint]; CBlockIndex* pindexCheckpointRecv = mapBlockIndex[hashCheckpoint]; if (pindexCheckpointRecv->nHeight <= pindexSyncCheckpoint->nHeight) { // Received an older checkpoint, trace back from current checkpoint // to the same height of the received checkpoint to verify // that current checkpoint should be a descendant block CBlockIndex* pindex = pindexSyncCheckpoint; while (pindex->nHeight > pindexCheckpointRecv->nHeight) if (!(pindex = pindex->pprev)) return error("ValidateSyncCheckpoint: pprev1 null - block index structure failure"); if (pindex->GetBlockHash() != hashCheckpoint) { hashInvalidCheckpoint = hashCheckpoint; return error("ValidateSyncCheckpoint: new sync-checkpoint %s is conflicting with current sync-checkpoint %s", hashCheckpoint.ToString().c_str(), hashSyncCheckpoint.ToString().c_str()); } return false; // ignore older checkpoint } // Received checkpoint should be a descendant block of the current // checkpoint. Trace back to the same height of current checkpoint // to verify. CBlockIndex* pindex = pindexCheckpointRecv; while (pindex->nHeight > pindexSyncCheckpoint->nHeight) if (!(pindex = pindex->pprev)) return error("ValidateSyncCheckpoint: pprev2 null - block index structure failure"); if (pindex->GetBlockHash() != hashSyncCheckpoint) { hashInvalidCheckpoint = hashCheckpoint; return error("ValidateSyncCheckpoint: new sync-checkpoint %s is not a descendant of current sync-checkpoint %s", hashCheckpoint.ToString().c_str(), hashSyncCheckpoint.ToString().c_str()); } return true; } bool WriteSyncCheckpoint(const uint256& hashCheckpoint) { CTxDB txdb; txdb.TxnBegin(); if (!txdb.WriteSyncCheckpoint(hashCheckpoint)) { txdb.TxnAbort(); return error("WriteSyncCheckpoint(): failed to write to db sync checkpoint %s", hashCheckpoint.ToString().c_str()); } if (!txdb.TxnCommit()) return error("WriteSyncCheckpoint(): failed to commit to db sync checkpoint %s", hashCheckpoint.ToString().c_str()); txdb.Close(); Checkpoints::hashSyncCheckpoint = hashCheckpoint; return true; } bool AcceptPendingSyncCheckpoint() { LOCK(cs_hashSyncCheckpoint); if (hashPendingCheckpoint != 0 && mapBlockIndex.count(hashPendingCheckpoint)) { if (!ValidateSyncCheckpoint(hashPendingCheckpoint)) { hashPendingCheckpoint = 0; checkpointMessagePending.SetNull(); return false; } CTxDB txdb; CBlockIndex* pindexCheckpoint = mapBlockIndex[hashPendingCheckpoint]; if (!pindexCheckpoint->IsInMainChain()) { CBlock block; if (!block.ReadFromDisk(pindexCheckpoint)) return error("AcceptPendingSyncCheckpoint: ReadFromDisk failed for sync checkpoint %s", hashPendingCheckpoint.ToString().c_str()); if (!block.SetBestChain(txdb, pindexCheckpoint)) { hashInvalidCheckpoint = hashPendingCheckpoint; return error("AcceptPendingSyncCheckpoint: SetBestChain failed for sync checkpoint %s", hashPendingCheckpoint.ToString().c_str()); } } txdb.Close(); if (!WriteSyncCheckpoint(hashPendingCheckpoint)) return error("AcceptPendingSyncCheckpoint(): failed to write sync checkpoint %s", hashPendingCheckpoint.ToString().c_str()); hashPendingCheckpoint = 0; checkpointMessage = checkpointMessagePending; checkpointMessagePending.SetNull(); printf("AcceptPendingSyncCheckpoint : sync-checkpoint at %s\n", hashSyncCheckpoint.ToString().c_str()); // relay the checkpoint if (!checkpointMessage.IsNull()) { BOOST_FOREACH(CNode* pnode, vNodes) checkpointMessage.RelayTo(pnode); } return true; } return false; } // Automatically select a suitable sync-checkpoint uint256 AutoSelectSyncCheckpoint() { // Proof-of-work blocks are immediately checkpointed // to defend against 51% attack which rejects other miners block // Select the last proof-of-work block const CBlockIndex *pindex = GetLastBlockIndex(pindexBest, false); // Search forward for a block within max span and maturity window while (pindex->pnext && (pindex->GetBlockTime() + CHECKPOINT_MAX_SPAN <= pindexBest->GetBlockTime() || pindex->nHeight + std::min(6, nCoinbaseMaturity - 20) <= pindexBest->nHeight)) pindex = pindex->pnext; return pindex->GetBlockHash(); } // Check against synchronized checkpoint bool CheckSync(const uint256& hashBlock, const CBlockIndex* pindexPrev) { if (fTestNet) return true; // Testnet has no checkpoints int nHeight = pindexPrev->nHeight + 1; LOCK(cs_hashSyncCheckpoint); // sync-checkpoint should always be accepted block assert(mapBlockIndex.count(hashSyncCheckpoint)); const CBlockIndex* pindexSync = mapBlockIndex[hashSyncCheckpoint]; if (nHeight > pindexSync->nHeight) { // trace back to same height as sync-checkpoint const CBlockIndex* pindex = pindexPrev; while (pindex->nHeight > pindexSync->nHeight) if (!(pindex = pindex->pprev)) return error("CheckSync: pprev null - block index structure failure"); if (pindex->nHeight < pindexSync->nHeight || pindex->GetBlockHash() != hashSyncCheckpoint) return false; // only descendant of sync-checkpoint can pass check } if (nHeight == pindexSync->nHeight && hashBlock != hashSyncCheckpoint) return false; // same height with sync-checkpoint if (nHeight < pindexSync->nHeight && !mapBlockIndex.count(hashBlock)) return false; // lower height than sync-checkpoint return true; } bool WantedByPendingSyncCheckpoint(uint256 hashBlock) { LOCK(cs_hashSyncCheckpoint); if (hashPendingCheckpoint == 0) return false; if (hashBlock == hashPendingCheckpoint) return true; if (mapOrphanBlocks.count(hashPendingCheckpoint) && hashBlock == WantedByOrphan(mapOrphanBlocks[hashPendingCheckpoint])) return true; return false; } // nexus: reset synchronized checkpoint to last hardened checkpoint bool ResetSyncCheckpoint() { LOCK(cs_hashSyncCheckpoint); const uint256& hash = mapCheckpoints.rbegin()->second; if (mapBlockIndex.count(hash) && !mapBlockIndex[hash]->IsInMainChain()) { // checkpoint block accepted but not yet in main chain printf("ResetSyncCheckpoint: SetBestChain to hardened checkpoint %s\n", hash.ToString().c_str()); CTxDB txdb; CBlock block; if (!block.ReadFromDisk(mapBlockIndex[hash])) return error("ResetSyncCheckpoint: ReadFromDisk failed for hardened checkpoint %s", hash.ToString().c_str()); if (!block.SetBestChain(txdb, mapBlockIndex[hash])) { return error("ResetSyncCheckpoint: SetBestChain failed for hardened checkpoint %s", hash.ToString().c_str()); } txdb.Close(); } else if(!mapBlockIndex.count(hash)) { // checkpoint block not yet accepted hashPendingCheckpoint = hash; checkpointMessagePending.SetNull(); printf("ResetSyncCheckpoint: pending for sync-checkpoint %s\n", hashPendingCheckpoint.ToString().c_str()); } BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, mapCheckpoints) { const uint256& hash = i.second; if (mapBlockIndex.count(hash) && mapBlockIndex[hash]->IsInMainChain()) { if (!WriteSyncCheckpoint(hash)) return error("ResetSyncCheckpoint: failed to write sync checkpoint %s", hash.ToString().c_str()); printf("ResetSyncCheckpoint: sync-checkpoint reset to %s\n", hashSyncCheckpoint.ToString().c_str()); return true; } } return false; } void AskForPendingSyncCheckpoint(CNode* pfrom) { LOCK(cs_hashSyncCheckpoint); if (pfrom && hashPendingCheckpoint != 0 && (!mapBlockIndex.count(hashPendingCheckpoint)) && (!mapOrphanBlocks.count(hashPendingCheckpoint))) pfrom->AskFor(CInv(MSG_BLOCK, hashPendingCheckpoint)); } bool SetCheckpointPrivKey(std::string strPrivKey) { // Test signing a sync-checkpoint with genesis block CSyncCheckpoint checkpoint; checkpoint.hashCheckpoint = !fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet; CDataStream sMsg(SER_NETWORK, PROTOCOL_VERSION); sMsg << (CUnsignedSyncCheckpoint)checkpoint; checkpoint.vchMsg = std::vector<unsigned char>(sMsg.begin(), sMsg.end()); std::vector<unsigned char> vchPrivKey = ParseHex(strPrivKey); CKey key; key.SetPrivKey(CPrivKey(vchPrivKey.begin(), vchPrivKey.end())); // if key is not correct openssl may crash if (!key.Sign(Hash(checkpoint.vchMsg.begin(), checkpoint.vchMsg.end()), checkpoint.vchSig)) return false; // Test signing successful, proceed CSyncCheckpoint::strMasterPrivKey = strPrivKey; return true; } bool SendSyncCheckpoint(uint256 hashCheckpoint) { CSyncCheckpoint checkpoint; checkpoint.hashCheckpoint = hashCheckpoint; CDataStream sMsg(SER_NETWORK, PROTOCOL_VERSION); sMsg << (CUnsignedSyncCheckpoint)checkpoint; checkpoint.vchMsg = std::vector<unsigned char>(sMsg.begin(), sMsg.end()); if (CSyncCheckpoint::strMasterPrivKey.empty()) return error("SendSyncCheckpoint: Checkpoint master key unavailable."); std::vector<unsigned char> vchPrivKey = ParseHex(CSyncCheckpoint::strMasterPrivKey); CKey key; key.SetPrivKey(CPrivKey(vchPrivKey.begin(), vchPrivKey.end())); // if key is not correct openssl may crash if (!key.Sign(Hash(checkpoint.vchMsg.begin(), checkpoint.vchMsg.end()), checkpoint.vchSig)) return error("SendSyncCheckpoint: Unable to sign checkpoint, check private key?"); if(!checkpoint.ProcessSyncCheckpoint(NULL)) { printf("WARNING: SendSyncCheckpoint: Failed to process checkpoint.\n"); return false; } // Relay checkpoint { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) checkpoint.RelayTo(pnode); } return true; } // Is the sync-checkpoint outside maturity window? bool IsMatureSyncCheckpoint() { LOCK(cs_hashSyncCheckpoint); // sync-checkpoint should always be accepted block assert(mapBlockIndex.count(hashSyncCheckpoint)); const CBlockIndex* pindexSync = mapBlockIndex[hashSyncCheckpoint]; return (nBestHeight >= pindexSync->nHeight + nCoinbaseMaturity || pindexSync->GetBlockTime() + nStakeMinAge < GetAdjustedTime()); } // Is the sync-checkpoint too old? bool IsSyncCheckpointTooOld(unsigned int nSeconds) { LOCK(cs_hashSyncCheckpoint); // sync-checkpoint should always be accepted block assert(mapBlockIndex.count(hashSyncCheckpoint)); const CBlockIndex* pindexSync = mapBlockIndex[hashSyncCheckpoint]; return (pindexSync->GetBlockTime() + nSeconds < GetAdjustedTime()); } } // nexus: sync-checkpoint master key const std::string CSyncCheckpoint::strMasterPubKey = "0489cab128b9f39a3e514a12c07a7644fa1808662195edcf2d4671b1cce76868b7f2f588a9dfad5753be3cd6b8e9518be439c936e2bad93a25bb6d32300fab41c3"; std::string CSyncCheckpoint::strMasterPrivKey = ""; // nexus: verify signature of sync-checkpoint message bool CSyncCheckpoint::CheckSignature() { CKey key; if (!key.SetPubKey(ParseHex(CSyncCheckpoint::strMasterPubKey))) return error("CSyncCheckpoint::CheckSignature() : SetPubKey failed"); if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig)) return error("CSyncCheckpoint::CheckSignature() : verify signature failed"); // Now unserialize the data CDataStream sMsg(vchMsg, SER_NETWORK, PROTOCOL_VERSION); sMsg >> *(CUnsignedSyncCheckpoint*)this; return true; } // nexus: process synchronized checkpoint bool CSyncCheckpoint::ProcessSyncCheckpoint(CNode* pfrom) { if (!CheckSignature()) return false; LOCK(Checkpoints::cs_hashSyncCheckpoint); if (!mapBlockIndex.count(hashCheckpoint)) { // We haven't received the checkpoint chain, keep the checkpoint as pending Checkpoints::hashPendingCheckpoint = hashCheckpoint; Checkpoints::checkpointMessagePending = *this; printf("ProcessSyncCheckpoint: pending for sync-checkpoint %s\n", hashCheckpoint.ToString().c_str()); // Ask this guy to fill in what we're missing if (pfrom) { pfrom->PushGetBlocks(pindexBest, hashCheckpoint); // ask directly as well in case rejected earlier by duplicate // proof-of-stake because getblocks may not get it this time pfrom->AskFor(CInv(MSG_BLOCK, mapOrphanBlocks.count(hashCheckpoint)? WantedByOrphan(mapOrphanBlocks[hashCheckpoint]) : hashCheckpoint)); } return false; } if (!Checkpoints::ValidateSyncCheckpoint(hashCheckpoint)) return false; CTxDB txdb; CBlockIndex* pindexCheckpoint = mapBlockIndex[hashCheckpoint]; if (!pindexCheckpoint->IsInMainChain()) { // checkpoint chain received but not yet main chain CBlock block; if (!block.ReadFromDisk(pindexCheckpoint)) return error("ProcessSyncCheckpoint: ReadFromDisk failed for sync checkpoint %s", hashCheckpoint.ToString().c_str()); if (!block.SetBestChain(txdb, pindexCheckpoint)) { Checkpoints::hashInvalidCheckpoint = hashCheckpoint; return error("ProcessSyncCheckpoint: SetBestChain failed for sync checkpoint %s", hashCheckpoint.ToString().c_str()); } } txdb.Close(); if (!Checkpoints::WriteSyncCheckpoint(hashCheckpoint)) return error("ProcessSyncCheckpoint(): failed to write sync checkpoint %s", hashCheckpoint.ToString().c_str()); Checkpoints::checkpointMessage = *this; Checkpoints::hashPendingCheckpoint = 0; Checkpoints::checkpointMessagePending.SetNull(); printf("ProcessSyncCheckpoint: sync-checkpoint at %s\n", hashCheckpoint.ToString().c_str()); return true; }
Skryptex/Nexus-Proof-of-Stake-Coin
src/checkpoints.cpp
C++
mit
18,523
package berkeleydb /* #cgo LDFLAGS: -ldb #include <db.h> #include "bdb.h" */ import "C" type Environment struct { environ *C.DB_ENV } func NewEnvironment() (*Environment, error) { var env *C.DB_ENV err := C.db_env_create(&env, 0) if err > 0 { return nil, createError(err) } return &Environment{env}, nil } func (env *Environment) Open(path string, flags C.u_int32_t, fileMode int) error { mode := C.u_int32_t(fileMode) err := C.go_env_open(env.environ, C.CString(path), flags, mode) return createError(err) } func (env *Environment) Close() error { err := C.go_env_close(env.environ, 0) return createError(err) }
technosophos/perkdb
berkeleydb/environment.go
GO
mit
633
<div class="form-group has-warning"> {!! Form::label( App\Import\Flap\POS_Member\Import::OPTIONS_CATEGORY, '*任務名稱', ['class' => 'control-label']) !!} {!! Form::text( 'name', $task->name, ['id'=> 'name', 'class' => 'form-control', 'required' => true, 'placeholder' => '請輸入任務名稱']) !!} <p class="help-block">{{'任務名稱必須唯一,不可重複'}}</p> </div> @if (NULL === $task->id) <div class="form-group has-warning"> {!! Form::label('file', '*選擇匯入檔案', ['class' => 'control-label']) !!} <input type="text" readonly class="form-control" placeholder="Browse..."> {!! Form::file( 'file', ['id'=>'excel', 'class' => 'form-control', 'accept' => 'application/vnd.ms-excel']) !!} <p class="help-block">{{'請選擇沒有密碼鎖定的 .xls 檔案,並且只留下一個工作表'}}</p> </div> @endif <div class="form-group has-warning"> {!! Form::label( App\Import\Flap\POS_Member\Import::OPTIONS_CATEGORY, '*會員類別', ['class' => 'control-label']) !!} {!! Form::text( App\Import\Flap\POS_Member\Import::OPTIONS_CATEGORY, $task->category, ['id'=>App\Import\Flap\POS_Member\Import::OPTIONS_CATEGORY, 'class' => 'form-control', 'required' => true, 'placeholder' => '請輸入會員類別代號']) !!} <p class="help-block">{{'Example: 126'}}</p> </div> <div class="form-group has-warning"> {!! Form::label( App\Import\Flap\POS_Member\Import::OPTIONS_DISTINCTION, '*會員區別', ['class' => 'control-label']) !!} {!! Form::text( App\Import\Flap\POS_Member\Import::OPTIONS_DISTINCTION, $task->distinction, ['id'=>App\Import\Flap\POS_Member\Import::OPTIONS_DISTINCTION, 'class' => 'form-control', 'required' => true, 'placeholder' => '請輸入會員區別代號']) !!} <p class="help-block">{{'Example: 126-75'}}</p> </div> <div class="form-group"> {!! Form::label( App\Import\Flap\POS_Member\Import::OPTIONS_INSERTFLAG, '請參考提示輸入旗標', ['class' => 'control-label']) !!} {!! Form::text( App\Import\Flap\POS_Member\Import::OPTIONS_INSERTFLAG, $task->getInsertFlagString(), ['id'=>App\Import\Flap\POS_Member\Import::OPTIONS_INSERTFLAG, 'class' => 'form-control']) !!} <p class="help-block"><b>11:A 5:B</b> (旗標 11 設定為A, 旗標 5 設定為 B,使用空白區隔)</p> </div> <div class="form-group"> {!! Form::label( App\Import\Flap\POS_Member\Import::OPTIONS_UPDATEFLAG, '請參考提示輸入重覆比對旗標', ['class' => 'control-label']) !!} {!! Form::text( App\Import\Flap\POS_Member\Import::OPTIONS_UPDATEFLAG, $task->getUpdateFlagString(), ['id'=> App\Import\Flap\POS_Member\Import::OPTIONS_UPDATEFLAG, 'class' => 'form-control']) !!} <p class="help-block"><b>12:A 5:B</b> (旗標 12 設定為 A, 旗標 5 設定為 B,使用空白區隔)</p> </div> <div class="form-group"> {!! Form::label( App\Import\Flap\POS_Member\Import::OPTIONS_OBMEMO, '請輸入客經二備註', ['class' => 'control-label']) !!} {!! Form::text( App\Import\Flap\POS_Member\Import::OPTIONS_OBMEMO, $task->memo, ['id'=> App\Import\Flap\POS_Member\Import::OPTIONS_OBMEMO, 'class' => 'form-control']) !!} </div> <div class="form-group"> {!! Form::submit(NULL === $task->id ? '匯入' : '確認', ['class' => 'btn btn-raised btn-primary btn-sm']) !!} </div>
jocoonopa/lubri
resources/views/flap/posmember/import_task/_formAct.blade.php
PHP
mit
3,704
<?php namespace Vibs\EvesymBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * Industryactivityproducts * * @ORM\Table(name="industryActivityProducts", indexes={@ORM\Index(name="ix_industryActivityProducts_typeID", columns={"typeID"}), @ORM\Index(name="ix_industryActivityProducts_productTypeID", columns={"productTypeID"}), @ORM\Index(name="activityID", columns={"activityID"})}) * @ORM\Entity */ class Industryactivityproducts { /** * @var integer * * @ORM\Column(name="id", type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="IDENTITY") */ private $id; /** * @var integer * * @ORM\Column(name="quantity", type="integer", nullable=true) */ private $quantity; /** * @var \Vibs\EvesymBundle\Entity\Ramactivities * * @ORM\ManyToOne(targetEntity="Vibs\EvesymBundle\Entity\Ramactivities") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="activityID", referencedColumnName="activityID") * }) */ private $activityid; /** * @var \Vibs\EvesymBundle\Entity\Invtypes * * @ORM\ManyToOne(targetEntity="Vibs\EvesymBundle\Entity\Invtypes") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="typeID", referencedColumnName="typeID") * }) */ private $typeid; /** * @var \Vibs\EvesymBundle\Entity\Invtypes * * @ORM\ManyToOne(targetEntity="Vibs\EvesymBundle\Entity\Invtypes") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="productTypeID", referencedColumnName="typeID") * }) */ private $producttypeid; /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set quantity * * @param integer $quantity * * @return Industryactivityproducts */ public function setQuantity($quantity) { $this->quantity = $quantity; return $this; } /** * Get quantity * * @return integer */ public function getQuantity() { return $this->quantity; } /** * Set activityid * * @param \Vibs\EvesymBundle\Entity\Ramactivities $activityid * * @return Industryactivityproducts */ public function setActivityid(\Vibs\EvesymBundle\Entity\Ramactivities $activityid = null) { $this->activityid = $activityid; return $this; } /** * Get activityid * * @return \Vibs\EvesymBundle\Entity\Ramactivities */ public function getActivityid() { return $this->activityid; } /** * Set typeid * * @param \Vibs\EvesymBundle\Entity\Invtypes $typeid * * @return Industryactivityproducts */ public function setTypeid(\Vibs\EvesymBundle\Entity\Invtypes $typeid = null) { $this->typeid = $typeid; return $this; } /** * Get typeid * * @return \Vibs\EvesymBundle\Entity\Invtypes */ public function getTypeid() { return $this->typeid; } /** * Set producttypeid * * @param \Vibs\EvesymBundle\Entity\Invtypes $producttypeid * * @return Industryactivityproducts */ public function setProducttypeid(\Vibs\EvesymBundle\Entity\Invtypes $producttypeid = null) { $this->producttypeid = $producttypeid; return $this; } /** * Get producttypeid * * @return \Vibs\EvesymBundle\Entity\Invtypes */ public function getProducttypeid() { return $this->producttypeid; } }
vladibalan/evesym
Entity/Industryactivityproducts.php
PHP
mit
3,604
class Admin::ToursController < Admin::ApplicationController before_action :set_tour, only: [:show, :edit, :update, :destroy] def index @tours = Tour.includes(:city).newest.page(params[:page]) end def show;end def new @tour = Tour.new end def edit end def create @tour = Tour.new(tour_params) if @tour.save redirect_to admin_tours_path, notice: 'Tour succefully added' else redirect_to admin_tours_path, alert: 'Something wrong in add procedure' end end def update if @tour.update(tour_params) redirect_to admin_tours_path, notice: 'Tour succefully updated' else redirect_to admin_tours_path, alert: 'Something wrong in update procedure' end end def destroy if @tour.destroy redirect_to admin_tours_path, notice: 'Tour deleted' else redirect_to admin_tours_path, alert: 'Something wrong in delete procedure' end end private def set_tour @tour = Tour.find(params[:id]) end def tour_params params.require(:tour).permit(:name, :description, :city_id) end end
mpakus/excurso
app/controllers/admin/tours_controller.rb
Ruby
mit
1,106
<?php /** * This file is part of Laravel Desktop Notifier. * * (c) Nuno Maduro <enunomaduro@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace NunoMaduro\LaravelDesktopNotifier; use Joli\JoliNotif\Notification as BaseNotification; use NunoMaduro\LaravelDesktopNotifier\Contracts\Notification as NotificationContract; /** * The concrete implementation of the notification. * * @author Nuno Maduro <enunomaduro@gmail.com> */ class Notification extends BaseNotification implements NotificationContract { }
nunomaduro/laravel-desktop-notifier
src/Notification.php
PHP
mit
620
'use strict'; function injectJS(src, cb) { var script = document.createElement('script'); script.setAttribute('type', 'text/javascript'); script.onreadystatechange = script.onload = function () { var readyState = script.readyState; if (!readyState || readyState == 'loaded' || readyState == 'complete' || readyState == 'uninitialized') { cb && cb(); script.onload = script.onreadystatechange = script.onerror = null; } }; script.src = src; document.body.appendChild(script); }
elpadi/js-library
dist/utils.js
JavaScript
mit
496
/** * Created by desen on 2017/7/24. */ function isArray(value) { if (typeof Array.isArray === "function") { return Array.isArray(value); } else { return Object.prototype.toString.call(value) === "[object Array]"; } } // 进行虚拟DOm的类型的判断 function isVtext(vNode) { return true; }
enmeen/2017studyPlan
someDemo/虚拟DOM实现/util.js
JavaScript
mit
307
package mankind; public class Worker extends Human { Double weekSalary; Double workHoursPerDay; public Worker(String firstName, String lastName, Double weekSalary, Double workHoursPerDay) { super(firstName, lastName); this.weekSalary = weekSalary; this.workHoursPerDay = workHoursPerDay; } public Double getWeekSalary() { return this.weekSalary; } public Double getWorkHoursPerDay() { return this.workHoursPerDay; } public Double getSalaryPerHour() { return this.weekSalary / (this.workHoursPerDay * 7); } }
akkirilov/SoftUniProject
04_DB Frameworks_Hibernate+Spring Data/03_OOP Principles EX/src/mankind/Worker.java
Java
mit
539
# -*- coding: utf-8 -*- """ Utils has nothing to do with models and views. """ from datetime import datetime from flask import current_app def get_current_time(): return datetime.utcnow() def format_date(value, format='%Y-%m-%d %H:%M:%S'): return value.strftime(format) def get_resource_as_string(name, charset='utf-8'): with current_app.open_resource(name) as f: return f.read().decode(charset)
vovantics/flask-bluebone
app/utils.py
Python
mit
427
# Copyright (c) 2016 kamyu. All rights reserved. # # Google Code Jam 2016 Round 1A - Problem B. Rank and File # https://code.google.com/codejam/contest/4304486/dashboard#s=p1 # # Time: O(N^2) # Space: O(N^2), at most N^2 numbers in the Counter # from collections import Counter def rank_and_file(): N = input() cnt = Counter() for _ in xrange(2 * N - 1): cnt += Counter(list(raw_input().strip().split())) file = [] for k, v in cnt.iteritems(): # The count of the missing number must be odd. if v % 2 == 1: file.append(k) # The order of the missing numbers must be sorted. file.sort(key=int) return " ".join(file) for case in xrange(input()): print 'Case #%d: %s' % (case+1, rank_and_file())
kamyu104/GoogleCodeJam-2016
Round 1A/rank-and-file.py
Python
mit
774
package workspace; import java.util.Collection; import javax.swing.JComponent; import renderable.RenderableBlock; /** WorkspaceWidgets are components within the workspace other than blocks that * include bars, buttons, factory drawers, and single instance widgets such as * the MiniMap and the TrashCan. */ public interface WorkspaceWidget { /** * Called by RenderableBlocks that get "dropped" onto this Widget * @param block the RenderableBlock that is "dropped" onto this Widget */ public void blockDropped(RenderableBlock block); /** * Called by RenderableBlocks as they are dragged over this Widget. * @param block the RenderableBlock being dragged */ public void blockDragged(RenderableBlock block); /** * Called when a RenderableBlock is being dragged and goes from being * outside this Widget to being inside the Widget. * @param block the RenderableBlock being dragged */ public void blockEntered(RenderableBlock block); /** * Called when a RenderableBlock that was being dragged over this Widget * goes from being inside this Widget to being outside the Widget. * @param block the RenderableBlock being dragged */ public void blockExited(RenderableBlock block); /** * Used by RenderableBlocks to tell their originating Widgets that * they're moving somewhere else and so should be removed. * @param block the RenderableBlock */ public void removeBlock(RenderableBlock block); /** * Adds the specified block to this widget interally and graphically. The * difference between this method and blockDropped is that blockDropped is * activated by user actions, such as mouse drag and drop or typeblocking. * Use this method only for single blocks, as it may cause repainting! For * adding several blocks at once use addBlocks, which delays graphical updates * until after the blocks have all been added. * @param block the desired RenderableBlock to add to this */ public void addBlock(RenderableBlock block); //TODO ria maybe rename this to putBlock? /** * Adds a collection of blocks to this widget internally and graphically. * This method adds blocks internally first, and only updates graphically * once all of the blocks have been added. It is therefore preferable to * use this method rather than addBlock whenever multiple blocks will be added. * @param blocks the Collection of RenderableBlocks to add */ public void addBlocks(Collection<RenderableBlock> blocks); /** * Widgets must be able to report whether a given point is inside them * @param x * @param y */ public boolean contains(int x, int y); /** * Very Java Swing dependent method * @return the JComponent-ized cast of this widget. */ public JComponent getJComponent(); /** * Returns the set of blocks that abstract "lives" inside this widget. * Does not return all the blocks that exists in thsi component, * or return all the blocks that are handled by this widget. Rather, * the set of blocks returned all the blocks that "lives" in this widget. */ public Iterable<RenderableBlock> getBlocks(); }
boubre/BayouBot
Workspace/src/workspace/WorkspaceWidget.java
Java
mit
3,255
package com.knesek.springmockedtests.service.impl; import com.knesek.springmockedtests.TestAppConfig; import com.knesek.springmockedtests.com.knesek.springmockedtests.util.MockedBeans; import com.knesek.springmockedtests.model.User; import com.knesek.springmockedtests.repository.UserRepository; import com.knesek.springmockedtests.service.EmailService; import com.knesek.springmockedtests.service.PasswordEncoder; import com.knesek.springmockedtests.service.StatisticsService; import com.knesek.springmockedtests.service.UserService; import com.lambdaworks.crypto.SCryptUtil; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.AnnotationConfigContextLoader; import javax.transaction.Transactional; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; /** * Demo of an integration test that uses both, mocked objects and actual spring objects. * Mocked objects are specified concisely using custom @MockedBeans annotation. * * @author knesek * Created on: 17/08/14 */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(loader=AnnotationConfigContextLoader.class) public class UserServiceImplIntegrationTest { @Autowired UserService userService; @Autowired UserRepository userRepository; /** * Note that we can autowire mocked beans and then use them in Mockito's verify assertions. */ @Autowired StatisticsService statisticsService; /** * Integration test that stores User into the database, then reads it from the database * and verifies if password was correctly hashed. */ @Transactional @Test public void testRegisterNewUser() { final String userName = "someone"; final String password = "somepass"; userService.registerNewUser(new User("someone@example.com", userName, password)); User user = userRepository.findByUserName(userName); Assert.assertNotNull(user); Assert.assertTrue(SCryptUtil.check(password, user.getPassword())); //Verifying interaction with a mocked bean verify(statisticsService, times(1)).recalculateStatisticReports(); } /** * Inner class configuration object. Spring will read it thanks to * @ContextConfiguration(loader=AnnotationConfigContextLoader.class) * annotation on the test class. */ @Configuration @Import(TestAppConfig.class) //TestAppConfig contains common integration testing configuration @MockedBeans({EmailService.class, StatisticsService.class}) //Beans to be mocked static class ContextConfiguration { @Bean public UserService userService() { return new UserServiceImpl(); } @Bean public PasswordEncoder passwordEncoder() { return new SCryptPasswordEncoder(); } } }
knes1/springmockedtests
src/test/java/com/knesek/springmockedtests/service/impl/UserServiceImplIntegrationTest.java
Java
mit
3,082
import babel from 'rollup-plugin-babel'; export default { plugins: [babel()] };
alexeyraspopov/message-script
rollup.config.js
JavaScript
mit
83
import * as _ from 'lodash'; import * as vscode from 'vscode'; import {Mode, ModeName} from './mode'; import NormalMode from './modeNormal'; import InsertMode from './modeInsert'; import VisualMode from './modeVisual'; import Configuration from '../configuration'; type ModeChangedHandler = (mode: Mode) => void; export default class ModeHandler { private modes : Mode[]; private modeChangedHandlers: ModeChangedHandler[] = []; private statusBarItem : vscode.StatusBarItem; configuration : Configuration; constructor() { this.configuration = Configuration.fromUserFile(); this.modes = [ new NormalMode(), new InsertMode(), new VisualMode(), ]; this.setCurrentModeByName(ModeName.Normal); } get currentMode() : Mode { var currentMode = this.modes.find((mode, index) => { return mode.IsActive; }); return currentMode; } setCurrentModeByName(modeName : ModeName) { this.modes.forEach(mode => { mode.IsActive = (mode.Name === modeName); }); var statusBarText = (this.currentMode.Name === ModeName.Normal) ? '' : ModeName[modeName]; this.setupStatusBarItem(statusBarText.toUpperCase()); for (let handler of this.modeChangedHandlers) { handler(this.currentMode); } } handleKeyEvent(key : string) : void { // Due to a limitation in Electron, en-US QWERTY char codes are used in international keyboards. // We'll try to mitigate this problem until it's fixed upstream. // https://github.com/Microsoft/vscode/issues/713 key = this.configuration.keyboardLayout.translate(key); var currentModeName = this.currentMode.Name; var nextMode : Mode; var inactiveModes = _.filter(this.modes, (m) => !m.IsActive); _.forEach(inactiveModes, (m, i) => { if (m.ShouldBeActivated(key, currentModeName)) { nextMode = m; } }); if (nextMode) { this.currentMode.HandleDeactivation(); nextMode.HandleActivation(key); this.setCurrentModeByName(nextMode.Name); return; } this.currentMode.HandleKeyEvent(key); } onModeChanged(handler: (newMode: Mode) => void) : void { this.modeChangedHandlers.push(handler); } private setupStatusBarItem(text : string) : void { if (!this.statusBarItem) { this.statusBarItem = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Left); } this.statusBarItem.text = (text) ? '-- ' + text + ' --' : ''; this.statusBarItem.show(); } dispose() { this.statusBarItem.dispose(); } }
AndersenJ/Vim
src/mode/modeHandler.ts
TypeScript
mit
2,801
<? /** */ require_once(dirname(__FILE__).'/DbManager_MySQL.php'); /** * @package SmartDatabase * @ignore */ class DbManager_Tests extends DbManager_MySQL{ public function TestAll(){ $passed = 0; $failed = 0; $result = $this->TestWhereClause1(); if($result['passed']) $passed++; else $failed++; $result = $this->TestWhereClause2(); if($result['passed']) $passed++; else $failed++; $result = $this->TestWhereClause3(); if($result['passed']) $passed++; else $failed++; $result = $this->TestWhereClause4(); if($result['passed']) $passed++; else $failed++; $result = $this->TestWhereClause5(); if($result['passed']) $passed++; else $failed++; $result = $this->TestWhereClause6(); if($result['passed']) $passed++; else $failed++; $result = $this->TestWhereClause7(); if($result['passed']) $passed++; else $failed++; $result = $this->TestWhereClause8(); if($result['passed']) $passed++; else $failed++; $result = $this->TestWhereClause9(); if($result['passed']) $passed++; else $failed++; $result = $this->TestWhereClause10(); if($result['passed']) $passed++; else $failed++; $result = $this->TestWhereClause11(); if($result['passed']) $passed++; else $failed++; $result = $this->TestWhereClause12(); if($result['passed']) $passed++; else $failed++; $result = $this->TestWhereClause13(); if($result['passed']) $passed++; else $failed++; $result = $this->TestWhereClause14(); if($result['passed']) $passed++; else $failed++; $result = $this->TestWhereClause15(); if($result['passed']) $passed++; else $failed++; $result = $this->TestWhereClause16(); if($result['passed']) $passed++; else $failed++; $result = $this->TestWhereClause17(); if($result['passed']) $passed++; else $failed++; $result = $this->TestWhereClause18(); if($result['passed']) $passed++; else $failed++; $result = $this->TestWhereClause19(); if($result['passed']) $passed++; else $failed++; $result = $this->TestWhereClause20(); if($result['passed']) $passed++; else $failed++; $result = $this->TestWhereClause21(); if($result['passed']) $passed++; else $failed++; $result = $this->TestWhereClause22(); if($result['passed']) $passed++; else $failed++; $result = $this->TestMultiQuery(); if($result['passed']) $passed++; else $failed++; // test database copy. connected user should have permissions to drop/create tables and databases //this also tests creating and dropping databases and tables $success = $this->CopyDatabase('smartdb_test', 'smartdb_test_copy', array( 'create-tables' => true, 'create-database' => true, 'copy-data' => true, 'drop-existing-tables' => true, 'drop-existing-database' => true, )); if($success){ $passed++; echo 'Copy database passed (create/drop tables and databases)'; } else {$failed++; echo "Error: could not copy database 'smartdb_test' to 'smartdb_test_copy'<br>";} echo "<br><br> -- RESULTS -- "; echo "<br>Tests passed: $passed"; echo "<br>Tests failed: $failed"; } private function TestMultiQuery(){ try{ $sql = 'insert into `FastSetting` (`Id`,`Name`,`ShortName`) values (444, "4@44.44", "444!");'; $sql .= 'select * from `FastSetting` where `Id`=444;'; $sql .= 'delete from `FastSetting` where `Id`=444;'; $bool = $this->Query($sql, array( 'multi-query' => true )); if(!$bool){ throw new Exception("multi-query 1 failed"); } $bool = $this->NextResult(); if(!$bool){ throw new Exception("multi-query 2 failed"); } //get rows from query 2 $rows = $this->FetchAssocList(); //print_r($rows); if(count($rows)!=1) throw new Exception("1 row was expected for query: 'select * from `FastSetting` where `Id`=444;'"); $bool = $this->NextResult(); if(!$bool){ throw new Exception("multi-query 3 failed"); } $bool = $this->NextResult(); if($bool !== false){ throw new Exception('Next result did not return FALSE as expected. Returned: '.$bool); } } catch(Exception $e){ if($this->_driver == self::MYSQL_DRIVER){ //not supported, so an exception here is a PASS $failed = false; } else{ $failed = true; $failMsg = $e->getMessage(); } } if($failed) echo ($msg = __FUNCTION__." <strong>FAILED</strong>:<br>".$failMsg); else echo ($msg = __FUNCTION__." passed."); echo "<br><br>"; return array('passed'=>!$failMsg, 'message'=>$msg); } private function TestWhereClause($array_where, $expectedResult, $testFuncName=null, $options=array()){ try{ $actualResult = trim($this->GenerateWhereClause("TEST_TABLE", $array_where, false, false, $options)); if(strcmp($actualResult,$expectedResult) != 0){ throw new Exception("Expected Result: <strong>$expectedResult</strong><br>Actual Result: <strong>$actualResult</strong>"); } } catch(Exception $e){ $failed = true; $failMsg = $e->getMessage(); } if($failed) echo ($msg = "$testFuncName <strong>FAILED</strong>:<br>".$failMsg); else echo ($msg = "$testFuncName passed."); echo "<br><br>"; return array('passed'=>!$failMsg, 'message'=>$msg); } private function TestWhereClause1(){ $array_where = array( "col1"=>"5" ); $expectedResult = "WHERE col1 = 5"; return $this->TestWhereClause($array_where, $expectedResult, __FUNCTION__); } private function TestWhereClause2(){ $expectedResult = "WHERE col1 = 5 AND col2 = 10 AND col3 = 15"; $array_where = array( // (nested arrays default to "AND") "col1"=>5, //col1=5 //AND "col2"=>10, //col2=10 //AND "col3"=>15 //col3=15 ); return $this->TestWhereClause($array_where, $expectedResult, __FUNCTION__); } private function TestWhereClause3(){ $expectedResult = "WHERE (col1 = 5 OR col2 = 10 OR col3 = 15)"; $array_where = array( // (outer array defaults to "AND") "OR" => array( //override with "OR" "col1"=>5, //col1=5 //OR "col2"=>10, //col2=10 //OR "col3"=>15 //col3=15 ) ); return $this->TestWhereClause($array_where, $expectedResult, __FUNCTION__); } private function TestWhereClause4(){ $expectedResult = "WHERE foo2 = 'bar2' AND (foo3 = 'bar3' AND foo4 = 'bar4') AND foo5 = 'bar5'"; $array_where = array( // (outer array defaults to "AND") "foo2" => "bar2", //foo2='bar2' //AND array( // (nested arrays default to "AND") "foo3" => "bar3", //foo3='bar3' //AND "foo4" => "bar4" //foo4='bar4' ), //AND "foo5" => "bar5" //foo5='bar5' ); return $this->TestWhereClause($array_where, $expectedResult, __FUNCTION__); } private function TestWhereClause5(){ $expectedResult = "WHERE (foo1 = 'bar1' AND foo2 = 'bar2') AND (foo3 = 'bar3' AND foo4 = 'bar4')"; $array_where = array( // (outer array defaults to "AND") array( "foo1" => "bar1", //foo1='bar1' //AND "foo2" => "bar2" //foo2='bar2' ), //AND array( "foo3" => "bar3", //foo3='bar3' //AND "foo4" => "bar4" //foo4='bar4' ) ); return $this->TestWhereClause($array_where, $expectedResult, __FUNCTION__); } private function TestWhereClause6(){ $expectedResult = 'WHERE (col1 = 4 AND col3 = 5) AND (col1 = 6 OR col2 = 7)'; $array_where = array( // (outer array defaults to "AND") "AND"=>array( "col1"=>4, //col1=4 //AND "col3"=>5 //col3=5 ), //AND (from outer array) "OR"=>array( "col1"=>6, //col1=6 //OR "col2"=>7 //col2=7 ) ); return $this->TestWhereClause($array_where, $expectedResult, __FUNCTION__); } private function TestWhereClause7(){ $expectedResult = 'WHERE (col1 > 40) AND (col2 < 100)'; $array_where = array( // (outer array defaults to "AND") "col1" => array( ">" => 40 ), //col1 > 40 //AND "col2" => array( "<" => 100 ) //col1 > 100 ); return $this->TestWhereClause($array_where, $expectedResult, __FUNCTION__); } private function TestWhereClause8(){ $expectedResult = 'WHERE (col1 > 4) AND col3 = 5 AND (col1 = 6 OR col2 = 7)'; $array_where = array( "col1"=>array( ">" => 4 ), //col1 > 4 //AND "col3"=>5, //col3 = 5 //AND "OR"=>array( "col1"=>6, //col1 = 6 //OR "col2"=>7 //col2 = 7 ) // (anything else added here is AND'ed) ); return $this->TestWhereClause($array_where, $expectedResult, __FUNCTION__); } private function TestWhereClause9(){ $expectedResult = 'WHERE (col1 = 3 AND col1 = 5 AND col1 = 7)'; $array_where = array( "col1" => array("3","5","7") ); return $this->TestWhereClause($array_where, $expectedResult, __FUNCTION__); } private function TestWhereClause10(){ $expectedResult = 'WHERE ((col1 = 3 OR col1 = 5 OR col1 = 7))'; $array_where = array( "col1" => array( "OR" => array("3","5","7") ) ); return $this->TestWhereClause($array_where, $expectedResult, __FUNCTION__); } private function TestWhereClause11(){ $expectedResult = 'WHERE ((col1 = 3 OR col1 = 5 OR col1 = 7))'; $array_where = array( "col1" => array( "OR" => array( 3,5,7 ) ) ); return $this->TestWhereClause($array_where, $expectedResult, __FUNCTION__); } private function TestWhereClause12(){ $expectedResult = 'WHERE (col1 < 10 AND (col1 = 3 OR col1 = 5 OR col1 = 7)) AND col2 = 11'; $array_where = array( // (outer array defaults to "AND") "col1" => array( "<" => 10, //col1<10 //AND "OR" => array("3","5","7") //col1=3 OR col1=5 OR col1=7 ), //AND "col2" => 11 //col2=11 ); return $this->TestWhereClause($array_where, $expectedResult, __FUNCTION__); } private function TestWhereClause13(){ $expectedResult = 'WHERE (col1 > 40 AND col1 <= 50)'; $array_where = array( // (outer array defaults to "AND") "col1" => array( ">" => 40, //col1 > 40 //AND "<=" => 50 //col1 <= 50 ), ); return $this->TestWhereClause($array_where, $expectedResult, __FUNCTION__); } private function TestWhereClause14(){ $expectedResult = 'WHERE ((col1 <= 40 OR col1 > 50))'; $array_where = array( // (outer array defaults to "AND") "col1" => array( "OR" => array( // (override the outer "AND") "<=" => 40, //col1 <= 40 //OR ">" => 50 //col1 > 50 ) ) ); return $this->TestWhereClause($array_where, $expectedResult, __FUNCTION__); } private function TestWhereClause15(){ $expectedResult = 'WHERE ((col1 <= 40 OR col1 > 50) AND (col1 != 44 OR col1 is null))'; $array_where = array(// (outer array defaults to "AND") "col1" => array( "OR" => array( // (override the outer "AND" with "OR") "<=" => 40, //col1 <= 40 //OR ">" => 50 //col1 > 50 ), //AND "!=" => "44" //col1 != 44 OR col1 is null ("is null" case is special for MySQL) ), ); return $this->TestWhereClause($array_where, $expectedResult, __FUNCTION__); } private function TestWhereClause16(){ $expectedResult = 'WHERE (((col1 > 4 OR col1 = 1) AND ((col1 != 9 OR col1 is null) AND col1 = 2)))'; $array_where = array( // (outer array defaults to "AND") "col1" => array( "AND" => array ( "OR" => array( ">" => 4, //col1 > 4 //OR 1, //col1 = 1 ), "AND" => array( "!=" => 9, //col1 != 9 OR col1 is null ("is null" case is special for MySQL) //OR "=" => 2 //col1 = 2 ) ) ) ); return $this->TestWhereClause($array_where, $expectedResult, __FUNCTION__); } private function TestWhereClause17(){ $expectedResult = 'WHERE ((col1 < 0 OR (col1 > 3 AND ((col1 != 10 OR col1 is null) AND (col1 != 12 OR col1 is null))))) AND col2 = 5'; $array_where = array( // (outer array defaults to "AND") "col1" => array( "OR" => array( "<" => 0, //col1 < 0 //OR "AND" => array( // override outer "OR" with "AND" for the following ">" => 3, //col1 > 3 //AND "!=" => array(10,12) //(col1 != 10 OR col1 is null) AND (col1 != 12 OR col1 is null) ("is null" cases are special for MySQL) ) ) ), //AND "col2" => 5 //col2 = 5 ); return $this->TestWhereClause($array_where, $expectedResult, __FUNCTION__); } private function TestWhereClause18() { $expectedResult = "WHERE ((col1 = 5 OR (col2 = -1 AND col3 = 'yo')) AND (col4 LIKE 'yo again') AND ((col5 != 5 OR col5 is null)))"; $array_where = array( "AND" => array( "OR" => array( "col1" => 5, "AND" => array( "col2"=>-1, "col3"=>"yo" ) ), "col4" => array( "LIKE"=>"yo again" ), "col5" => array( "<>" => 5 ) ) ); return $this->TestWhereClause($array_where, $expectedResult, __FUNCTION__); } private function TestWhereClause19() { $expectedResult = "WHERE ((col1 < 'z') AND col2 is null AND (col3 IS NOT 5))"; $array_where = array( "AND" => array( "col1" => array("<" => "z"), "col2" => NULL, "col3" => array("IS NOT"=>5) ) ); return $this->TestWhereClause($array_where, $expectedResult, __FUNCTION__); } private function TestWhereClause20() { $expectedResult = "WHERE (col1 = 5 AND col2 = 6 AND col3 = '99999999999999999999999999999999999999999999999' AND col4 = '-99999999999999999999999999999999999999999999999')"; $array_where = array( "AND" => array( "col1" => 5, "col2" => 6, "col3" => '99999999999999999999999999999999999999999999999', "col4" => '-99999999999999999999999999999999999999999999999', ) ); return $this->TestWhereClause($array_where, $expectedResult, __FUNCTION__, array( 'quote-numerics'=>false )); } private function TestWhereClause21() { $expectedResult = "WHERE (col1 = '5' AND col2 = '6' AND col3 = '99999999999999999999999999999999999999999999999' AND col4 = '-99999999999999999999999999999999999999999999999')"; $array_where = array( "AND" => array( "col1" => 5, "col2" => 6, "col3" => '99999999999999999999999999999999999999999999999', "col4" => '-99999999999999999999999999999999999999999999999', ) ); return $this->TestWhereClause($array_where, $expectedResult, __FUNCTION__, array( 'quote-numerics'=>true )); } private function TestWhereClause22() { $expectedResult = "WHERE (((col1 != 0 OR col1 is null)) AND (col2 is null) AND (col3 is not null) AND (col4 is not null))"; $array_where = array( "AND" => array( "col1" => array("!=" => "0"), "col2" => array("=" => NULL), "col3" => array("IS NOT"=>null), "col4" => array("!="=>null), ) ); return $this->TestWhereClause($array_where, $expectedResult, __FUNCTION__); } } //$tests = new DbManager_Tests('SERVER','USERNAME','PASSWORD','DATABASE_NAME'); $tests = new DbManager_Tests('localhost','smartdb','smartdb123','smartdb_test', array( 'driver'=>'mysql' )); $tests->TestAll(); $tests = new DbManager_Tests('localhost','smartdb','smartdb123','smartdb_test', array( 'driver'=>'mysqli' )); $tests->TestAll();
cirkuitnet/PHP-SmartDB
DbManagers/DbManager_Tests.php
PHP
mit
16,042
package ru.VirtaMarketAnalyzer.parser; import org.junit.jupiter.api.Test; import ru.VirtaMarketAnalyzer.data.Country; import ru.VirtaMarketAnalyzer.data.Region; import ru.VirtaMarketAnalyzer.main.Wizard; import java.io.IOException; import java.util.List; import static org.junit.jupiter.api.Assertions.*; class CityInitParserTest { @Test void getRegionsTest() throws IOException { final List<Region> list = CityInitParser.getRegions(Wizard.host, "olga"); assertFalse(list.isEmpty()); } @Test void getCountriesTest() throws IOException { final List<Country> list = CityInitParser.getCountries(Wizard.host, "olga"); assertFalse(list.isEmpty()); } }
cobr123/VirtaMarketAnalyzer
src/test/java/ru/VirtaMarketAnalyzer/parser/CityInitParserTest.java
Java
mit
708
var lang = navigator.language; exports.set_lang=function(_lang,msgs){ lang = _lang || navigator.language; if(lang.indexOf('en')===0){ lang = 'en'; }else if(lang.indexOf('es')===0){ lang = 'es'; }else{ lang = 'en'; } var nodes = document.querySelectorAll('[msg]'); for(var i = 0; i < nodes.length; i++){ var node = nodes.item(i); if(node.getAttribute("placeholder")){ node.setAttribute("placeholder",property(msgs,lang+"."+node.getAttribute("msg"))); }else{ node.innerText = property(msgs,lang+"."+node.getAttribute("msg")); node.textContent = node.innerText; } } window.userLang = lang; }; exports.get=function(msg,msgs){ return property(msgs,lang+"."+msg); }; function property(o,s){ if(typeof s === 'undefined'){ return ''; } if(typeof o === 'undefined'){ return s; } s = s.replace(/\[(\w+)\]/g, '.$1'); // convert indexes to properties s = s.replace(/^\./, ''); // strip a leading dot var a = s.split('.'); while (a.length) { var n = a.shift(); if (n in o) { o = o[n]; } else { return s; } } return o; }
Technogi/website
src/scripts/msg.js
JavaScript
mit
1,145
<?php include("session.php"); $debug=$_GET['d']; ?> <!DOCTYPE html> <!-------------------------------------------- LICENSE (MIT) ------------------------------------------------- Copyright (c) 2015 Conor Walsh Website: http://www.conorwalsh.net GitHub: https://github.com/conorwalsh Project: Smart Environment Monitoring system (S.E.M.) 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. __ __ ____ __ __ _ _ ____ ___ _ ____ / /__\ \ / ___|___ _ __ ___ _ __ \ \ / /_ _| |___| |__ |___ \ / _ \/ | ___| | |/ __| | | / _ \| '_ \ / _ \| '__| \ \ /\ / / _` | / __| '_ \ __) | | | | |___ \ | | (__| | |__| (_) | | | | (_) | | \ V V / (_| | \__ \ | | | / __/| |_| | |___) | | |\___| |\____\___/|_| |_|\___/|_| \_/\_/ \__,_|_|___/_| |_| |_____|\___/|_|____/ \_\ /_/ ----------------------------------------------- LICENSE END ------------------------------------------------> <!---------------------------------------------- PAGE INFO -------------------------------------------------- This page is where a standard user is redirected when they try to access a restricted admin only page. ---------------------------------------------- PAGE INFO END -----------------------------------------------> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content=""> <title><?php echo $pagetitle;?></title> <link rel="SHORTCUT ICON" href="<?php echo $favicon;?>"> <!-- Bootstrap core CSS --> <link href="css/bootstrap.css" rel="stylesheet"> <!-- Add custom CSS here --> <link href="css/sb-admin.css" rel="stylesheet"> <link href="css/lightbox.css" rel="stylesheet"> <link rel="stylesheet" href="font-awesome/css/font-awesome.min.css"> <!-- Page Specific CSS --> <link rel="stylesheet" href="css/bootstrap-datetimepicker.css"> <!-- JavaScript --> <script src="js/jquery-1.10.2.js"></script> <script src="js/bootstrap.js"></script> <script src="js/moment.js"></script> </head> <body> <div id="wrapper"> <!-- Sidebar --> <nav class="navbar navbar-inverse navbar-fixed-top" role="navigation"> <!-- Brand and toggle get grouped for better mobile display --> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse"> <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="navbar-brand" href="home.php"><img src="<?php echo $brandheaderimage;?>" border="0" style="margin-top: -3px;" /> <?php echo $brandname;?></a> </div> <!-- Collect the nav links, forms, and other content for toggling --> <div class="collapse navbar-collapse navbar-ex1-collapse"> <ul class="nav navbar-nav side-nav"> <li><a href="home.php"><i class="fa fa-dashboard"></i> Dashboard</a></li> <li><a href="graphs.php"><i class="fa fa-area-chart"></i> Graphs</a></li> <li><a href="logs.php"><i class="fa fa-list"></i> Logs</a></li> <li><a href="webusers.php"><i class="fa fa-users"></i> Website users</a></li> </ul> <ul class="nav navbar-nav navbar-right navbar-user"> <li style="padding: 15px 15px 14.5px;" class="userbtn" class="alerts-dropdown"> <div id="clockbox"></div> </li> <li class="dropdown user-dropdown"> <a href="#" class= "userbtn" class="dropdown-toggle" data-toggle="dropdown"><i class="fa fa-user"></i> <?php echo $login_session; ?> <b class="caret"></b></a> <ul class="dropdown-menu"> <li><a href="settings.php"><i class="fa fa-gear"></i> Settings</a></li> <li class="divider"></li> <li><a href="logout.php"><i class="fa fa-power-off"></i> Log Out</a></li> </ul> </li> </ul> </div><!-- /.navbar-collapse --> </nav> <div id="page-wrapper"> <div class="row"> <div class="col-lg-12"> <h1>Non Admin</h1> <ol class="breadcrumb"> <li><a href="home.php"><i class="fa fa-dashboard"></i> Dashboard</a></li> <li class="active"><i class="fa fa-ban"></i> Non Admin</li> </ol> </div> </div><!-- /.row --> <div class="row"> <div style="text-align: center; font-size: 18px;" class="col-lg-12"> <img src="img/ban.png" /><div> The page that you tried to access is only availible to administrators, if you require access we would suggest contacting your administrator.</div> </div><!-- /#page-wrapper --> </div><!-- /#wrapper --> <!-- Page Specific Plugins --> <script src="js/clock.js"></script> </body> </html>
conorwalsh/SEM
Web/nonadmin.php
PHP
mit
6,313
'use strict'; const postcodeApi = require('../index.js'); const sinon = require('sinon'); const chai = require('chai'); const expect = chai.expect; const sinonChai = require('sinon-chai'); const requestApi = require('../lib/requestApi.js'); before(() => { chai.use(sinonChai); }); var sandbox; beforeEach(() => { sandbox = sinon.createSandbox(); }); afterEach(() => { sandbox.restore(); }); // Loading assets const response1 = require('./assets/followNext/response1.json'); const response2 = require('./assets/followNext/response2.json'); const response3 = require('./assets/followNext/response3.json'); const expectedResult = require('./assets/followNext/expected.json'); const rateLimit = { limit: 123, remaining: 123 }; const rateLimitLast = { limit: 123, remaining: 0 }; describe('helpers/followNext()', () => { it('should be able to follow next-href of the _links object in a response', () => { // Preparing requestApi const requestApiStub = sandbox.stub(requestApi, 'get').callsFake((options, callback) => { switch (options.url) { // Respond with the correct json case 'https://www.test.nl/page1': return callback(null, response1, rateLimit); case 'https://www.test.nl/page2': return callback(null, response2, rateLimit); case 'https://www.test.nl/page3': return callback(null, response3, rateLimitLast); } }); // Preparing options let options = { url: 'https://www.test.nl/page1' }; // Run the function return postcodeApi.helpers.followNext(options, (error, body, rateLimit) => { expect(error).to.eql(null); expect(body).to.eql(expectedResult); expect(rateLimit).to.eql(undefined); expect(requestApiStub).to.be.calledWith(options); expect(requestApiStub).to.be.calledThrice; }); }); it('should be to return the correct rateLimits after performing several requests', () => { // Preparing requestApi const requestApiStub = sandbox.stub(requestApi, 'get').callsFake((options, callback) => { switch (options.url) { // Respond with the correct json case 'https://www.test.nl/page1': return callback(null, response1, rateLimit); case 'https://www.test.nl/page2': return callback(null, response2, rateLimit); case 'https://www.test.nl/page3': return callback(null, response3, rateLimitLast); } }); // Setting options let options = { url: 'https://www.test.nl/page1', returnRateLimit: true }; // Run the function return postcodeApi.helpers.followNext(options, (error, body, rateLimit) => { expect(error).to.eql(null); expect(body).to.eql(expectedResult); expect(rateLimit).to.eql(rateLimitLast); expect(requestApiStub).to.be.calledWith(options); expect(requestApiStub).to.be.calledThrice; }); }); it('should be able to handle a single response without next-href', () => { // Preparing requestApi const requestApiStub = sandbox.stub(requestApi, 'get').callsFake((options, callback) => { return callback(null, response3); }); postcodeApi.helpers.followNext({}, (error, body, rateLimit) => { expect(error).to.eql(null); expect(body).to.eql(response3); expect(rateLimit).to.eql(undefined); expect(requestApiStub).to.be.calledOnce; }); }); it('should be able to handle a single response without next-href and return the right rateLimit', () => { // Preparing requestApi const requestApiStub = sandbox.stub(requestApi, 'get').callsFake((options, callback) => { return callback(null, response3, rateLimitLast); }); // Setting options let options = { returnRateLimit: true }; return postcodeApi.helpers.followNext(options, (error, body, rateLimit) => { expect(error).to.eql(null); expect(body).to.eql(response3); expect(rateLimit).to.eql(rateLimitLast); expect(requestApiStub).to.be.calledWith(options); expect(requestApiStub).to.be.calledOnce; }); }); it('should be able to handle errors from requestApi.get()', () => { // Preparing requestApi const requestApiStub = sandbox.stub(requestApi, 'get').callsFake((options, callback) => { return callback(new Error('Error'), null); }); return postcodeApi.helpers.followNext({}, (error, body, rateLimit) => { expect(error).to.be.instanceof(Error); expect(body).to.eql(null); expect(rateLimit).to.eql(undefined); expect(requestApiStub).to.be.calledOnce; }); }); it('should be able to handle no results from the external API', () => { // Preparing requestApi const requestApiStub = sandbox.stub(requestApi, 'get').callsFake((options, callback) => { return callback(null, null); }); return postcodeApi.helpers.followNext({}, (error, body, rateLimit) => { expect(error).to.eql(null); expect(body).to.eql(null); expect(rateLimit).to.eql(undefined); expect(requestApiStub).to.be.calledOnce; }); }); it('should be able to handle errors from mergeResults() when performing there is a next-href', () => { // Preparing requestApi const requestApiStub = sandbox.stub(requestApi, 'get').callsFake((options, callback) => { return callback(null, response1); }); const mergeResults = sandbox.stub(postcodeApi.helpers, 'mergeResults') .callsFake((source, destination, callback) => { return callback(new Error('Error'), null); }); return postcodeApi.helpers.followNext({}, (error, body, rateLimit) => { expect(error).to.be.instanceof(Error); expect(body).to.eql(null); expect(rateLimit).to.eql(undefined); expect(requestApiStub).to.be.calledTwice; expect(mergeResults).to.be.calledOnce; }); }); it('should be able to handle errors from mergeResults() when performing there is no next-href', () => { // Preparing requestApi const requestApiStub = sandbox.stub(requestApi, 'get').callsFake((options, callback) => { return callback(null, response3); }); const mergeResults = sandbox.stub(postcodeApi.helpers, 'mergeResults') .callsFake((source, destination, callback) => { return callback(new Error('Error'), null); }); return postcodeApi.helpers.followNext({}, response2, (error, body, rateLimit) => { expect(error).to.be.instanceof(Error); expect(body).to.eql(null); expect(rateLimit).to.eql(undefined); expect(requestApiStub).to.be.calledOnce; expect(mergeResults).to.be.calledOnce; }); }); });
joostdebruijn/node-postcode-nl
test/helpers.followNext.js
JavaScript
mit
6,658
<?php /** * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) * * Licensed under The MIT License * For full copyright and license information, please see the LICENSE.txt * Redistributions of files must retain the above copyright notice. * * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) * @link https://cakephp.org CakePHP(tm) Project * @since 3.0.0 * @license https://opensource.org/licenses/mit-license.php MIT License */ namespace Cake\ORM\Behavior; use Cake\Datasource\EntityInterface; use Cake\Event\Event; use Cake\ORM\Association; use Cake\ORM\Behavior; use Cake\ORM\Entity; /** * CounterCache behavior * * Enables models to cache the amount of connections in a given relation. * * Examples with Post model belonging to User model * * Regular counter cache * ``` * [ * 'Users' => [ * 'post_count' * ] * ] * ``` * * Counter cache with scope * ``` * [ * 'Users' => [ * 'posts_published' => [ * 'conditions' => [ * 'published' => true * ] * ] * ] * ] * ``` * * Counter cache using custom find * ``` * [ * 'Users' => [ * 'posts_published' => [ * 'finder' => 'published' // Will be using findPublished() * ] * ] * ] * ``` * * Counter cache using lambda function returning the count * This is equivalent to example #2 * ``` * [ * 'Users' => [ * 'posts_published' => function (Event $event, EntityInterface $entity, Table $table) { * $query = $table->find('all')->where([ * 'published' => true, * 'user_id' => $entity->get('user_id') * ]); * return $query->count(); * } * ] * ] * ``` * * Ignore updating the field if it is dirty * ``` * [ * 'Users' => [ * 'posts_published' => [ * 'ignoreDirty' => true * ] * ] * ] * ``` * * You can disable counter updates entirely by sending the `ignoreCounterCache` option * to your save operation: * * ``` * $this->Articles->save($article, ['ignoreCounterCache' => true]); * ``` */ class CounterCacheBehavior extends Behavior { /** * Store the fields which should be ignored * * @var array */ protected $_ignoreDirty = []; /** * beforeSave callback. * * Check if a field, which should be ignored, is dirty * * @param \Cake\Event\Event $event The beforeSave event that was fired * @param \Cake\Datasource\EntityInterface $entity The entity that is going to be saved * @param \ArrayObject $options The options for the query * @return void */ public function beforeSave(Event $event, EntityInterface $entity, $options) { if (isset($options['ignoreCounterCache']) && $options['ignoreCounterCache'] === true) { return; } foreach ($this->_config as $assoc => $settings) { $assoc = $this->_table->association($assoc); foreach ($settings as $field => $config) { if (is_int($field)) { continue; } $registryAlias = $assoc->getTarget()->getRegistryAlias(); $entityAlias = $assoc->getProperty(); if (!is_callable($config) && isset($config['ignoreDirty']) && $config['ignoreDirty'] === true && $entity->$entityAlias->isDirty($field) ) { $this->_ignoreDirty[$registryAlias][$field] = true; } } } } /** * afterSave callback. * * Makes sure to update counter cache when a new record is created or updated. * * @param \Cake\Event\Event $event The afterSave event that was fired. * @param \Cake\Datasource\EntityInterface $entity The entity that was saved. * @param \ArrayObject $options The options for the query * @return void */ public function afterSave(Event $event, EntityInterface $entity, $options) { if (isset($options['ignoreCounterCache']) && $options['ignoreCounterCache'] === true) { return; } $this->_processAssociations($event, $entity); $this->_ignoreDirty = []; } /** * afterDelete callback. * * Makes sure to update counter cache when a record is deleted. * * @param \Cake\Event\Event $event The afterDelete event that was fired. * @param \Cake\Datasource\EntityInterface $entity The entity that was deleted. * @param \ArrayObject $options The options for the query * @return void */ public function afterDelete(Event $event, EntityInterface $entity, $options) { if (isset($options['ignoreCounterCache']) && $options['ignoreCounterCache'] === true) { return; } $this->_processAssociations($event, $entity); } /** * Iterate all associations and update counter caches. * * @param \Cake\Event\Event $event Event instance. * @param \Cake\Datasource\EntityInterface $entity Entity. * @return void */ protected function _processAssociations(Event $event, EntityInterface $entity) { foreach ($this->_config as $assoc => $settings) { $assoc = $this->_table->association($assoc); $this->_processAssociation($event, $entity, $assoc, $settings); } } /** * Updates counter cache for a single association * * @param \Cake\Event\Event $event Event instance. * @param \Cake\ORM\Entity $entity Entity * @param \Cake\ORM\Association $assoc The association object * @param array $settings The settings for for counter cache for this association * @return void */ protected function _processAssociation(Event $event, Entity $entity, Association $assoc, array $settings) { $foreignKeys = (array)$assoc->getForeignKey(); $primaryKeys = (array)$assoc->getBindingKey(); $countConditions = $entity->extract($foreignKeys); $updateConditions = array_combine($primaryKeys, $countConditions); $countOriginalConditions = $entity->extractOriginalChanged($foreignKeys); if ($countOriginalConditions !== []) { $updateOriginalConditions = array_combine($primaryKeys, $countOriginalConditions); } foreach ($settings as $field => $config) { if (is_int($field)) { $field = $config; $config = []; } if (isset($this->_ignoreDirty[$assoc->getTarget()->getRegistryAlias()][$field]) && $this->_ignoreDirty[$assoc->getTarget()->getRegistryAlias()][$field] === true ) { continue; } if (!is_string($config) && is_callable($config)) { $count = $config($event, $entity, $this->_table, false); } else { $count = $this->_getCount($config, $countConditions); } $assoc->getTarget()->updateAll([$field => $count], $updateConditions); if (isset($updateOriginalConditions)) { if (!is_string($config) && is_callable($config)) { $count = $config($event, $entity, $this->_table, true); } else { $count = $this->_getCount($config, $countOriginalConditions); } $assoc->getTarget()->updateAll([$field => $count], $updateOriginalConditions); } } } /** * Fetches and returns the count for a single field in an association * * @param array $config The counter cache configuration for a single field * @param array $conditions Additional conditions given to the query * @return int The number of relations matching the given config and conditions */ protected function _getCount(array $config, array $conditions) { $finder = 'all'; if (!empty($config['finder'])) { $finder = $config['finder']; unset($config['finder']); } if (!isset($config['conditions'])) { $config['conditions'] = []; } $config['conditions'] = array_merge($conditions, $config['conditions']); $query = $this->_table->find($finder, $config); return $query->count(); } }
LCabreroG/opensource
vendor/cakephp/cakephp/src/ORM/Behavior/CounterCacheBehavior.php
PHP
mit
8,607
import test from 'ava'; import { actionTest } from 'redux-ava'; import { ADD_POST_REQUEST, DELETE_POST_REQUEST, } from '../constants'; import { addPostRequest, deletePostRequest, } from '../PostActions'; const post = { name: 'Prashant', title: 'Hello Mern', cuid: 'f34gb2bh24b24b2', content: "All cats meow 'mern!'", slug: 'hello-mern', _id: 1 }; test('should return the correct type for addPostRequest', actionTest( addPostRequest, post, { type: ADD_POST_REQUEST, post }, )); test('should return the correct type for deletePostRequest', actionTest( deletePostRequest, post.cuid, { type: DELETE_POST_REQUEST, cuid: post.cuid }, ));
Skrpk/mern-sagas
client/modules/Post/__tests__/PostActions.spec.js
JavaScript
mit
657
<?php class User_Form_Validate_PasswordMatch extends Zend_Validate_Abstract { const NOT_MATCH = 'notMatch'; protected $_messageTemplates = array( self::NOT_MATCH => 'Geslo in ponovi geslo se ne ujemata' ); public function isValid($value, $context = null) { $value = (string) $value; $this->_setValue($value); if (is_array($context)) { if ( isset($context['password']) && ($value == $context['password'])) { return true; } } elseif (is_string($context) && ($value == $context)) { return true; } $this->_error(self::NOT_MATCH); return false; } }
freshcrm/fresh-crm
plugins/User/lib/User/Form/Validate/PasswordMatch.php
PHP
mit
590
version https://git-lfs.github.com/spec/v1 oid sha256:ba1edb37cd9663c92048dc14cd2f7e9e81d2ce7364194e973ba9e1238f9198a2 size 878
yogeshsaroya/new-cdnjs
ajax/libs/extjs/4.2.1/src/lang/Number.min.js
JavaScript
mit
128
package xyz.hotchpotch.jutaime.throwable.matchers; import java.util.Objects; import org.hamcrest.Matcher; import xyz.hotchpotch.jutaime.throwable.Testee; /** * スローされた例外を検査する {@code Matcher} です。<br> * この {@code Matcher} は、スローされた例外そのものの型やメッセージが期待されたものかを検査します。<br> * 検査対象のオペレーションが正常終了した場合は、不合格と判定します。<br> * <br> * この {@code Matcher} は、スローされた例外の型が期待された型と完全に同一の場合に一致と判定します。<br> * <br> * このクラスはスレッドセーフではありません。<br> * ひとつの {@code Matcher} オブジェクトが複数のスレッドから操作されることは想定されていません。<br> * * @since 1.0.0 * @author nmby */ public class RaiseExact extends RaiseBase { // [static members] ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ /** * スローされた例外の型を検査する {@code Matcher} オブジェクトを返します。<br> * このメソッドにより返される {@code Matcher} オブジェクトは、スローされた例外の型が期待された型と完全に同一の場合に一致と判定します。<br> * * @param expectedType 期待される例外の型 * @return スローされた例外を検査する {@code Matcher} * @throws NullPointerException {@code expectedType} が {@code null} の場合 */ public static Matcher<Testee<?>> raiseExact(Class<? extends Throwable> expectedType) { Objects.requireNonNull(expectedType); return new RaiseExact(expectedType); } /** * スローされた例外の型とメッセージを検査する {@code Matcher} オブジェクトを返します。<br> * このメソッドにより返される {@code Matcher} オブジェクトは、スローされた例外の型が期待された型と完全に同一の場合に一致と判定します。<br> * * @param expectedType 期待される例外の型 * @param expectedMessage 期待されるメッセージ({@code null} が許容されます) * @return スローされた例外を検査する {@code Matcher} * @throws NullPointerException {@code expectedType} が {@code null} の場合 */ public static Matcher<Testee<?>> raiseExact(Class<? extends Throwable> expectedType, String expectedMessage) { Objects.requireNonNull(expectedType); return new RaiseExact(expectedType, expectedMessage); } // [instance members] ++++++++++++++++++++++++++++++++++++++++++++++++++++++ private RaiseExact(Class<? extends Throwable> expectedType) { super(true, expectedType); } private RaiseExact(Class<? extends Throwable> expectedType, String expectedMessage) { super(true, expectedType, expectedMessage); } }
nmby/jUtaime
project/src/main/java/xyz/hotchpotch/jutaime/throwable/matchers/RaiseExact.java
Java
mit
3,077
/** * Module dependencies */ var uuid = require('uuid'); var utils = require('../utils'); var safeRequire = utils.safeRequire; var helpers = utils.helpers; var couchbase = safeRequire('couchbase'); var CouchBase; exports.initialize = function (schema, callback) { var db, opts; opts = schema.settings || {}; if (!opts.url) { var host = opts.host || 'localhost'; var port = opts.port || '8091'; var database = opts.database || 'test'; var proto = opts.ssl ? 'couchbases' : 'couchbase'; opts.url = proto + '://' + host + ':' + port; } schema.client = new couchbase.Cluster(opts.url); db = schema.client.openBucket(database); schema.adapter = new CouchBase(schema.client, db); process.nextTick(function () { schema.adapter.db = schema.client.openBucket(database); return callback && callback(); }.bind(this)); }; function CouchBase(client, db, callback) { this.name = 'couchbase'; this.client = client; this.db = db; this._models = {}; } CouchBase.prototype.define = function (descr) { var m, self = this; m = descr.model.modelName; descr.properties._rev = { type: String }; var design = { views: { all: { map: 'function (doc, meta) { if (doc._type === "' + m.toLowerCase() + '") { return emit(doc._type, doc); } }', reduce: '_count' } } }; return self.db.manager().insertDesignDocument('caminte_' + m.toLowerCase(), design, function (err, doc) { return self.db.get('caminte_' + m.toLowerCase() + '_counter', function (err, doc) { if (!doc) { self.db.insert('caminte_' + m.toLowerCase() + '_counter', 0, function () { return self._models[m] = descr; }); } else { return self._models[m] = descr; } }); }); }; CouchBase.prototype.create = function (model, data, callback) { var self = this; data._type = model.toLowerCase(); helpers.savePrep(data); return self.db.counter('caminte_' + data._type + '_counter', +1, function (err, res) { if (err) { console.log('create counter for ' + data._type + ' failed', err); } var uid = res && res.value ? (data._type + '_' + res.value) : uuid.v1(); var key = data.id || uid; data.id = key; return self.db.upsert(key, self.forDB(model, data), function (err, doc) { return callback(err, key); }); }); }; CouchBase.prototype.save = function (model, data, callback) { var self = this; data._type = model.toLowerCase(); helpers.savePrep(data); var uid = uuid.v1(); var key = data.id || data._id || uid; if (data.id) { delete data.id; } if (data._id) { delete data._id; } return self.db.replace(key, self.forDB(model, data), function (err, doc) { return callback(err, key); }); }; CouchBase.prototype.updateOrCreate = function (model, data, callback) { var self = this; return self.exists(model, data.id, function (err, exists) { if (exists) { return self.save(model, data, callback); } else { return self.create(model, data, function (err, id) { data.id = id; return callback(err, data); }); } }); }; CouchBase.prototype.exists = function (model, id, callback) { return this.db.get(id, function (err, doc) { if (err) { return callback(null, false); } return callback(null, doc); }); }; CouchBase.prototype.findById = function (model, id, callback) { var self = this; return self.db.get(id, function (err, data) { var doc = data && (data.doc || data.value) ? (data.doc || data.value) : null; if (doc) { if (doc._type) { delete doc._type; } doc = self.fromDB(model, doc); if (doc._id) { doc.id = doc._id; delete doc._id; } } return callback(err, doc); }); }; CouchBase.prototype.destroy = function (model, id, callback) { var self = this; return self.db.remove(id, function (err, doc) { if (err) { return callback(err); } callback.removed = true; return callback(); }); }; CouchBase.prototype.updateAttributes = function (model, id, data, callback) { var self = this; return self.findById(model, id, function (err, base) { if (err) { return callback(err); } if (base) { data = helpers.merge(base, data); data.id = id; } return self.save(model, data, callback); }); }; CouchBase.prototype.count = function (model, callback, where) { var self = this; var query = new couchbase.ViewQuery() .from('caminte_' + model, 'all') .reduce(true) .stale(1) .include_docs(true); return self.db.query(query, function (err, body) { return callback(err, docs.length); }); }; CouchBase.prototype.destroyAll = function (model, callback) { var self = this; return self.all(model, {}, function (err, docs) { return callback(err, docs); }); }; CouchBase.prototype.forDB = function (model, data) { var k, props, v; if (data === null) { data = {}; } props = this._models[model].properties; for (k in props) { v = props[k]; if (data[k] && props[k].type.name === 'Date' && (data[k].getTime !== null) && (typeof data[k].getTime === 'function')) { data[k] = data[k].getTime(); } } return data; }; CouchBase.prototype.fromDB = function (model, data) { var date, k, props, v; if (!data) { return data; } props = this._models[model].properties; for (k in props) { v = props[k]; if ((data[k] !== null) && props[k].type.name === 'Date') { date = new Date(data[k]); date.setTime(data[k]); data[k] = date; } } return data; }; CouchBase.prototype.remove = function (model, filter, callback) { var self = this; return self.all(model, filter, function (err, docs) { var doc; console.log(docs) // return _this.db.bulk({ // docs: docs // }, function (err, body) { return callback(err, docs); // }); }); }; /* CouchBase.prototype.destroyById = function destroyById(model, id, callback) { var self = this; return self.db.remove(id, function (err, doc) { console.log(err, doc) return callback(err, doc); }); }; */ CouchBase.prototype.all = function (model, filter, callback) { if ('function' === typeof filter) { callback = filter; filter = {}; } if (!filter) { filter = {}; } var self = this; var query = new couchbase.ViewQuery() .from('caminte_' + model, 'all') .reduce(false) .include_docs(true); if (filter.order) { if (/desc/gi.test()) { query.order(couchbase.ViewQuery.Order.DESCENDING); } // query.order(filter.order); } if (filter.skip) { query.skip(filter.skip); } if (filter.limit) { query.limit(filter.limit); } if (filter.where) { query.custom(filter.where); } return self.db.query(query, function (err, body) { var doc, docs, i, k, key, orders, row, sorting, v, where, _i, _len; if (err) { if (err.statusCode == 404) { return err; } else { return err; } } docs = body.map(function (row) { var item = row.value; item.id = row.id; return item; }); // console.log('docs:', docs) where = filter !== null ? filter.where : void 0; if (where) { docs = docs ? docs.filter(helpers.applyFilter(filter)) : docs; } orders = filter !== null ? filter.order : void 0; if (orders) { if (typeof orders === 'string') { orders = [orders]; } sorting = function (a, b) { var ak, bk, i, item, rev, _i, _len; for (i = _i = 0, _len = this.length; _i < _len; i = ++_i) { item = this[i]; ak = a[this[i].key]; bk = b[this[i].key]; rev = this[i].reverse; if (ak > bk) { return 1 * rev; } if (ak < bk) { return -1 * rev; } } return 0; }; for (i = _i = 0, _len = orders.length; _i < _len; i = ++_i) { key = orders[i]; orders[i] = { reverse: helpers.reverse(key), key: helpers.stripOrder(key) }; } docs.sort(sorting.bind(orders)); } return callback(err, (function () { var _j, _len1, _results; _results = []; for (_j = 0, _len1 = docs.length; _j < _len1; _j++) { doc = docs[_j]; _results.push(this.fromDB(model, doc)); } return _results; }).call(self)); }); }; CouchBase.prototype.autoupdate = function (callback) { this.client.manager().createBucket(database, {}, function (err) { if (err) console.log('createBucket', err) return callback && callback(); }); };
biggora/caminte
lib/adapters/couchbase.js
JavaScript
mit
9,831
var ObjectExplorer = require('../') var explorer = document.getElementById('explorer') var add = document.getElementById('add') var obj = { a: 10, b: true, reg: /foo/g, dat: new Date('2013-08-29'), str: "fooo, bar" } obj.self = obj obj.arr = [obj, obj, obj] obj.longArr = [] for (i = 0; i < 500; i++) obj.longArr.push(i) var state = null function next() { var e = new ObjectExplorer(obj, state) e.appendTo(explorer) state = e.state } next() add.addEventListener('click', next, false)
ForbesLindesay/object-explorer
demo/client.js
JavaScript
mit
503
package service import ( "fmt" "jarvis/log" "os/exec" "strings" "time" ) type CommandResult struct { Text string Error error } type Docker struct{} func (d Docker) RunShInContainer(command string, timeout time.Duration) (string, error) { log.Info("Executing command '%v' in container 'ubuntu'", command) resultCh := make(chan CommandResult) args := []string{"run", "--rm", "ubuntu"} for _, userArg := range strings.Split(command, " ") { args = append(args, userArg) } cmd := exec.Command("docker", args...) go func() { out, err := cmd.Output() log.Trace("Result: %v", string(out)) if err != nil { log.Trace("Error: %v", err.Error()) } else { log.Trace("No error") } resultCh <- CommandResult{ Text: string(out), Error: err, } }() select { case res := <-resultCh: return res.Text, res.Error case <-time.After(timeout): cmd.Process.Kill() return "", fmt.Errorf("Your command took longer than %v to run and has thus been killed.", Time{}.DurationToString(timeout)) } } func (d Docker) RunPythonInContainer(command string, timeout time.Duration) (string, error) { log.Info("Executing command '%v' in container 'python'", command) resultCh := make(chan CommandResult) cmd := exec.Command("docker", "run", "--rm", "python", "python", "-c", command) go func() { out, err := cmd.Output() log.Trace("Result: %v", string(out)) if err != nil { log.Trace("Error: %v", err.Error()) } else { log.Trace("No error") } resultCh <- CommandResult{ Text: string(out), Error: err, } }() select { case res := <-resultCh: return res.Text, res.Error case <-time.After(timeout): cmd.Process.Kill() return "", fmt.Errorf("Your command took longer than %v to run and has thus been killed.", Time{}.DurationToString(timeout)) } }
mhoc/jarvis
src/jarvis/service/docker_service.go
GO
mit
1,804
var global = window; var Stack = require('lib/swing/stack'), Card = require('lib/swing/card'); global.gajus = global.gajus || {}; global.gajus.Swing = { Stack: Stack, Card: Card }; module.exports = { Stack: Stack, Card: Card };
unbug/generator-webappstarter
app/templates/app/src/lib/swing/swing.js
JavaScript
mit
242