text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Fix string encoding when the argument is already a str(). Former-commit-id: 812fd79675590659b3dc4251ed998f84c4bf2395
import os import sys import hashlib def e(s): if type(s) == str: return s return s.encode('utf-8') def d(s): if type(s) == unicode: return s return unicode(s, 'utf-8') def mkid(s): return hashlib.sha1(e(s)).hexdigest()[:2*4] def running_in_tools_labs(): return os.path.exists('/etc/wmflabs-project') class Logger(object): def __init__(self): self._mode = 'INFO' def progress(self, message): message = e(message) if not sys.stderr.isatty(): return if self._mode == 'PROGRESS': print >>sys.stderr, '\r', print >>sys.stderr, message, self._mode = 'PROGRESS' def info(self, message): message = e(message) if self._mode == 'PROGRESS': print >>sys.stderr print >>sys.stderr, message self._mode = 'INFO'
import os import sys import hashlib def e(s): if type(s) == str: return str return s.encode('utf-8') def d(s): if type(s) == unicode: return s return unicode(s, 'utf-8') def mkid(s): return hashlib.sha1(e(s)).hexdigest()[:2*4] def running_in_tools_labs(): return os.path.exists('/etc/wmflabs-project') class Logger(object): def __init__(self): self._mode = 'INFO' def progress(self, message): message = e(message) if not sys.stderr.isatty(): return if self._mode == 'PROGRESS': print >>sys.stderr, '\r', print >>sys.stderr, message, self._mode = 'PROGRESS' def info(self, message): message = e(message) if self._mode == 'PROGRESS': print >>sys.stderr print >>sys.stderr, message self._mode = 'INFO'
Use os.urandom instead of OpenSSL.rand.bytes Follows suggestion in pyOpenSSL changelog https://github.com/pyca/pyopenssl/blob/1eac0e8f9b3829c5401151fabb3f78453ad772a4/CHANGELOG.rst#backward-incompatible-changes-1
import binascii from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import hashes from os import urandom as generate_bytes from knox.settings import knox_settings, CONSTANTS sha = knox_settings.SECURE_HASH_ALGORITHM def create_token_string(): return binascii.hexlify( generate_bytes(int(knox_settings.AUTH_TOKEN_CHARACTER_LENGTH / 2)) ).decode() def create_salt_string(): return binascii.hexlify( generate_bytes(int(CONSTANTS.SALT_LENGTH / 2))).decode() def hash_token(token, salt): ''' Calculates the hash of a token and salt. input is unhexlified ''' digest = hashes.Hash(sha(), backend=default_backend()) digest.update(binascii.unhexlify(token)) digest.update(binascii.unhexlify(salt)) return binascii.hexlify(digest.finalize()).decode()
import binascii from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import hashes from OpenSSL.rand import bytes as generate_bytes from knox.settings import knox_settings, CONSTANTS sha = knox_settings.SECURE_HASH_ALGORITHM def create_token_string(): return binascii.hexlify( generate_bytes(int(knox_settings.AUTH_TOKEN_CHARACTER_LENGTH / 2)) ).decode() def create_salt_string(): return binascii.hexlify( generate_bytes(int(CONSTANTS.SALT_LENGTH / 2))).decode() def hash_token(token, salt): ''' Calculates the hash of a token and salt. input is unhexlified ''' digest = hashes.Hash(sha(), backend=default_backend()) digest.update(binascii.unhexlify(token)) digest.update(binascii.unhexlify(salt)) return binascii.hexlify(digest.finalize()).decode()
Work with plain SQL files
import sys import sqlparse from .checks import has_cross_join def parse_file(filename): return open(filename, 'r').readlines() CHECKS = ( (has_cross_join, 'query contains cross join'), ) def check_query(el): """ Run each of the defined checks on a query. """ stmt = sqlparse.parse(el) for check in CHECKS: if check[0](stmt[0]): return False, check[1] return True, '' def main(): argv = sys.argv try: queries = parse_file(argv[1]) except IndexError: raise Exception('Filename required') failed = False for query in queries: passed, message = check_query(query) if not passed: failed = True print_message(message, query) sys.exit(255 if failed else 0) def print_message(message, query): print "FAILED - %s" % (message) print "-----------------------------------------------------------------" print print "Query:" print "%s" % query
import sys import sqlparse from .checks import has_cross_join def parse_file(filename): import json with open(filename, 'r') as fh: return json.load(fh) CHECKS = ( (has_cross_join, 'query contains cross join'), ) def check_query(el): """ Run each of the defined checks on a query. """ stmt = sqlparse.parse(el) for check in CHECKS: if check[0](stmt[0]): return False, check[1] return True, '' def main(): argv = sys.argv try: queries = parse_file(argv[1]) except IndexError: raise Exception('Filename required') failed = False for query, tests in queries.iteritems(): passed, message = check_query(query) if not passed: failed = True print_message(message, tests, query) sys.exit(255 if failed else 0) def print_message(message, tests, query): print "FAILED - %s" % (message) print "-----------------------------------------------------------------" print "Test Methods:" print "%s" % "\n".join(tests) print print "Query:" print "%s" % query
Build for all non-windows platforms
// +build !windows package pb import ( "runtime" "syscall" "unsafe" ) const ( TIOCGWINSZ = 0x5413 TIOCGWINSZ_OSX = 1074295912 ) func bold(str string) string { return "\033[1m" + str + "\033[0m" } func terminalWidth() (int, error) { w := new(window) tio := syscall.TIOCGWINSZ if runtime.GOOS == "darwin" { tio = TIOCGWINSZ_OSX } res, _, err := syscall.Syscall(syscall.SYS_IOCTL, uintptr(syscall.Stdin), uintptr(tio), uintptr(unsafe.Pointer(w)), ) if int(res) == -1 { return 0, err } return int(w.Col), nil }
// +build linux darwin freebsd package pb import ( "runtime" "syscall" "unsafe" ) const ( TIOCGWINSZ = 0x5413 TIOCGWINSZ_OSX = 1074295912 ) func bold(str string) string { return "\033[1m" + str + "\033[0m" } func terminalWidth() (int, error) { w := new(window) tio := syscall.TIOCGWINSZ if runtime.GOOS == "darwin" { tio = TIOCGWINSZ_OSX } res, _, err := syscall.Syscall(syscall.SYS_IOCTL, uintptr(syscall.Stdin), uintptr(tio), uintptr(unsafe.Pointer(w)), ) if int(res) == -1 { return 0, err } return int(w.Col), nil }
Add check for permissions for every component
<?php class Kwc_Editable_ComponentsModel extends Kwf_Model_Data_Abstract { public function __construct(array $config = array()) { $data = array(); $components = Kwf_Component_Data_Root::getInstance() ->getComponentsByClass(array('Kwc_Editable_Component', 'Kwc_Editable_Trl_Component')); foreach ($components as $c) { $user = Kwf_Registry::get('userModel')->getAuthedUser(); if (Kwf_Registry::get('acl')->getComponentAcl()->isAllowed($user, $c)) { $data[] = array( 'id' => $c->dbId, 'name' => $c->getComponent()->getNameForEdit(), 'content_component_class' => $c->getChildComponent('-content')->componentClass, ); } } $this->_data = $data; parent::__construct($config); } }
<?php class Kwc_Editable_ComponentsModel extends Kwf_Model_Data_Abstract { public function __construct(array $config = array()) { $data = array(); $components = Kwf_Component_Data_Root::getInstance() ->getComponentsByClass(array('Kwc_Editable_Component', 'Kwc_Editable_Trl_Component')); foreach ($components as $c) { $data[] = array( 'id' => $c->dbId, 'name' => $c->getComponent()->getNameForEdit(), 'content_component_class' => $c->getChildComponent('-content')->componentClass, ); } $this->_data = $data; parent::__construct($config); } }
Disable the search when the input pattern's length is less than or equal to 1
'use strict' const Fuse = require('fuse.js') let fuse = null let fuseIndex = [] const fuseOptions = { shouldSort: true, tokenize: true, matchAllTokens: true, findAllMatches: true, threshold: 0.2, location: 0, distance: 100, maxPatternLength: 32, minMatchCharLength: 1, keys: [ 'description', 'language' ] } function resetFuseIndex (list) { fuseIndex = list } function initFuseSearch () { fuse = new Fuse(fuseIndex, fuseOptions) } function addToFuseIndex (item) { fuseIndex.push(item) } function updateFuseIndex (item) { const newIndex = fuseIndex.filter(gist => { return gist.id !== item.id }) newIndex.push(item) fuseIndex = newIndex } function fuseSearch (pattern) { const trimmedPattern = pattern.trim() if (!trimmedPattern || trimmedPattern.length <= 1) return [] return fuse.search(trimmedPattern) } module.exports = { resetFuseIndex: resetFuseIndex, updateFuseIndex: updateFuseIndex, addToFuseIndex: addToFuseIndex, initFuseSearch: initFuseSearch, fuseSearch: fuseSearch }
'use strict' const Fuse = require('fuse.js') let fuse = null let fuseIndex = [] const fuseOptions = { shouldSort: true, tokenize: true, matchAllTokens: true, findAllMatches: true, threshold: 0.2, location: 0, distance: 100, maxPatternLength: 32, minMatchCharLength: 1, keys: [ 'description', 'language' ] } function resetFuseIndex (list) { fuseIndex = list } function initFuseSearch () { fuse = new Fuse(fuseIndex, fuseOptions) } function addToFuseIndex (item) { fuseIndex.push(item) } function updateFuseIndex (item) { const newIndex = fuseIndex.filter(gist => { return gist.id !== item.id }) newIndex.push(item) fuseIndex = newIndex } function fuseSearch (pattern) { return fuse.search(pattern.trim() || '') } module.exports = { resetFuseIndex: resetFuseIndex, updateFuseIndex: updateFuseIndex, addToFuseIndex: addToFuseIndex, initFuseSearch: initFuseSearch, fuseSearch: fuseSearch }
Fix wrong variable reference in configuration
#!/usr/bin/env python3 import os from datetime import timedelta _BAYESIAN_JOBS_DIR = os.path.dirname(os.path.realpath(__file__)) DEFAULT_SERVICE_PORT = 34000 SWAGGER_YAML_PATH = os.path.join(_BAYESIAN_JOBS_DIR, 'swagger.yaml') DEFAULT_JOB_DIR = os.path.join(_BAYESIAN_JOBS_DIR, 'default_jobs') TOKEN_VALID_TIME = timedelta(days=14) AUTH_ORGANIZATION = 'fabric8-analytics' GITHUB_CONSUMER_KEY = os.getenv('GITHUB_CONSUMER_KEY', 'not-set') GITHUB_CONSUMER_SECRET = os.getenv('GITHUB_CONSUMER_SECRET', 'not-set') GITHUB_ACCESS_TOKENS = os.getenv('GITHUB_ACCESS_TOKENS', '').split(',') APP_SECRET_KEY = os.getenv('APP_SECRET_KEY', 'not-set') AWS_ACCESS_KEY_ID = os.getenv('AWS_SQS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.getenv('AWS_SQS_SECRET_ACCESS_KEY') AWS_SQS_REGION = os.getenv('AWS_SQS_REGION', 'us-east-1') DEPLOYMENT_PREFIX = os.getenv('DEPLOYMENT_PREFIX', os.getenv('USER')) # keep disabled authentication by default DISABLE_AUTHENTICATION = os.getenv('DISABLE_AUTHENTICATION', '1') in ('1', 'True', 'true')
#!/usr/bin/env python3 import os from datetime import timedelta _BAYESIAN_JOBS_DIR = os.path.dirname(os.path.realpath(__file__)) DEFAULT_SERVICE_PORT = 34000 SWAGGER_YAML_PATH = os.path.join(_BAYESIAN_JOBS_DIR, 'swagger.yaml') DEFAULT_JOB_DIR = os.path.join(_BAYESIAN_JOBS_DIR, 'default_jobs') TOKEN_VALID_TIME = timedelta(days=14) AUTH_ORGANIZATION = 'fabric8-analytics' GITHUB_CONSUMER_KEY = os.getenv('GITHUB_CONSUMER_KEY', 'not-set') GITHUB_CONSUMER_SECRET = os.getenv('GITHUB_CONSUMER_SECRET', 'not-set') GITHUB_ACCESS_TOKENS = os.getenv('GITHUB_ACCESS_TOKENS', '').split(',') APP_SECRET_KEY = os.getenv('APP_SECRET_KEY', 'not-set') AWS_ACCESS_KEY_ID = os.getenv('AWS_SQS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.getenv('AWS_SQS_SECRET_ACCESS_KEY') AWS_SQS_REGION = os.getenv('AWS_SQS_REGION', 'us-east-1') DEPLOYMENT_PREFIX = os.getenv('AWS_SQS_REGION', 'us-east-1') # keep disabled authentication by default DISABLE_AUTHENTICATION = os.getenv('DISABLE_AUTHENTICATION', '1') in ('1', 'True', 'true')
Use constants PACKET_EOF and PACKET_ERR
package mysqlproto import ( "errors" ) type ResultSet struct { stream *Stream } func (r ResultSet) Row() ([]byte, error) { packet, err := r.stream.NextPacket() if err != nil { return nil, err } if packet.Payload[0] == PACKET_EOF { return nil, nil } return packet.Payload, nil } func ComQueryResponse(stream *Stream) (ResultSet, error) { packet, err := stream.NextPacket() if err != nil { return ResultSet{}, err } if packet.Payload[0] == PACKET_ERR { return ResultSet{}, errors.New(string(packet.Payload)) } columns, _, _ := lenDecInt(packet.Payload) skip := int(columns) + 1 // skip column definition + first EOF for i := 0; i < skip; i++ { packet, err := stream.NextPacket() if err != nil { return ResultSet{}, err } if packet.Payload[0] == PACKET_ERR { return ResultSet{}, errors.New(string(packet.Payload)) } } return ResultSet{stream}, nil }
package mysqlproto import ( "errors" ) type ResultSet struct { stream *Stream } func (r ResultSet) Row() ([]byte, error) { packet, err := r.stream.NextPacket() if err != nil { return nil, err } if packet.Payload[0] == 0xfe { // EOF return nil, nil } return packet.Payload, nil } func ComQueryResponse(stream *Stream) (ResultSet, error) { packet, err := stream.NextPacket() if err != nil { return ResultSet{}, err } if packet.Payload[0] == 0xff { return ResultSet{}, errors.New(string(packet.Payload)) } columns, _, _ := lenDecInt(packet.Payload) skip := int(columns) + 1 // skip column definition + first EOF for i := 0; i < skip; i++ { packet, err := stream.NextPacket() if err != nil { return ResultSet{}, err } if packet.Payload[0] == 0xff { return ResultSet{}, errors.New(string(packet.Payload)) } } return ResultSet{stream}, nil }
Entity: Remove components as class attribute It is meant to be an instance attribute and should be defined in init() instead.
"""This module contains base classes for defining game objects as well as their individual components and behaviours. """ from pygame.sprite import Sprite class Entity(Sprite): """An object within the game. It contains several Component objects that are used to define how it is handled graphically and physically, as well as its behaviour. Since it inherits from PyGame's Sprite class, it can be added to any Groups you have created. (Components will automatically add it to the appropriate Groups.) This also makes discarding it from the game simple, as it will automatically be removed from memory once it belongs to no Groups. Attributes: components (list): Contains all of the Component objects that are contained in this Entity. * Note that components will also be added as unique attributes automatically. This will make it possible to access each component directly, rather than having to add .components. in-between this Entity's name and the component's name. """ pass class Component(object): """Part of an Entity object. It will handle one facet of the Entity, which can be graphics, physics, or part of its behaviour. Subclasses should define their own attributes and methods in order to accomplish this. Ideally, a game would have many Component subclasses to define the many different parts that make up different game objects. Attributes: entity (Entity): This Component is bound to it and has access to all of its members. """ pass
"""This module contains base classes for defining game objects as well as their individual components and behaviours. """ from pygame.sprite import Sprite class Entity(Sprite): """An object within the game. It contains several Component objects that are used to define how it is handled graphically and physically, as well as its behaviour. Since it inherits from PyGame's Sprite class, it can be added to any Groups you have created. (Components will automatically add it to the appropriate Groups.) This also makes discarding it from the game simple, as it will automatically be removed from memory once it belongs to no Groups. Attributes: components (list): Contains all of the Component objects that are contained in this Entity. * Note that components will also be added as unique attributes automatically. This will make it possible to access each component directly, rather than having to add .components. in-between this Entity's name and the component's name. """ components = [] class Component(object): """Part of an Entity object. It will handle one facet of the Entity, which can be graphics, physics, or part of its behaviour. Subclasses should define their own attributes and methods in order to accomplish this. Ideally, a game would have many Component subclasses to define the many different parts that make up different game objects. Attributes: entity (Entity): This Component is bound to it and has access to all of its members. """ pass
Make PyTarget object work again We now save a base64 encoded pickled version of the object.
from ..target import Target import hashlib import dill import joblib class PyTarget(Target): def __init__(self, name, obj=None): self._name = name self._obj = obj super(PyTarget, self).__init__() if not obj is None: self.set(obj) def identifier(self): return self._name def get(self): return self._obj def set(self, obj): self._obj = obj self._memory['obj'] = dill.dumps(obj).encode('base64') def is_damaged(self): mem = self.stored() if mem: if self._obj is None: self._obj = dill.loads(mem['obj'].decode('base64')) return stored._obj is None else: return joblib.hash(self._obj) != joblib.hash(dill.loads(mem['obj'].decode('base64'))) else: return self._obj is None
from ..target import Target import hashlib import dill import joblib class PyTarget(Target): def __init__(self, name, obj=None): self._name = name self._obj = obj super(PyTarget, self).__init__() if not obj is None: self.set(obj) def identifier(self): return self._name def get(self): return self._obj def set(self, obj): self._obj = obj def is_damaged(self): stored = self.stored() if stored: if self._obj is None: self._obj = stored._obj return stored._obj is None else: return joblib.hash(self._obj) != joblib.hash(stored._obj) else: return self._obj is None
Fix class rename in caller class
package info.u_team.u_team_test.init; import info.u_team.u_team_core.util.registry.SyncedWorker; import info.u_team.u_team_test.TestMod; import info.u_team.u_team_test.screen.*; import net.minecraft.client.gui.ScreenManager; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.common.Mod.EventBusSubscriber; import net.minecraftforge.fml.common.Mod.EventBusSubscriber.Bus; import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent; @EventBusSubscriber(modid = TestMod.MODID, bus = Bus.MOD, value = Dist.CLIENT) public class TestScreens { @SubscribeEvent public static void register(FMLClientSetupEvent event) { SyncedWorker.runOnMainThread(() -> { ScreenManager.registerFactory(TestContainers.BASIC, BasicTileEntityScreen::new); ScreenManager.registerFactory(TestContainers.BASIC_ENERGY_CREATOR, BasicEnergyCreatorScreen::new); ScreenManager.registerFactory(TestContainers.BASIC_FLUID_INVENTORY, BasicFluidInventoryScreen::new); }); } }
package info.u_team.u_team_test.init; import info.u_team.u_team_core.util.registry.RegistryWorker; import info.u_team.u_team_test.TestMod; import info.u_team.u_team_test.screen.*; import net.minecraft.client.gui.ScreenManager; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.common.Mod.EventBusSubscriber; import net.minecraftforge.fml.common.Mod.EventBusSubscriber.Bus; import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent; @EventBusSubscriber(modid = TestMod.MODID, bus = Bus.MOD, value = Dist.CLIENT) public class TestScreens { @SubscribeEvent public static void register(FMLClientSetupEvent event) { RegistryWorker.runOnMainThread(() -> { ScreenManager.registerFactory(TestContainers.BASIC, BasicTileEntityScreen::new); ScreenManager.registerFactory(TestContainers.BASIC_ENERGY_CREATOR, BasicEnergyCreatorScreen::new); ScreenManager.registerFactory(TestContainers.BASIC_FLUID_INVENTORY, BasicFluidInventoryScreen::new); }); } }
Add binding to json decode transformer
<?php use Marquine\Etl\Container; $container = Container::getInstance(); // Database $container->singleton(Marquine\Etl\Database\Manager::class); $container->alias(Marquine\Etl\Database\Manager::class, 'db'); // Extractors $container->bind('extractor.collection', Marquine\Etl\Extractors\Collection::class); $container->bind('extractor.csv', Marquine\Etl\Extractors\Csv::class); $container->bind('extractor.fixed_width', Marquine\Etl\Extractors\FixedWidth::class); $container->bind('extractor.json', Marquine\Etl\Extractors\Json::class); $container->bind('extractor.query', Marquine\Etl\Extractors\Query::class); $container->bind('extractor.table', Marquine\Etl\Extractors\Table::class); $container->bind('extractor.xml', Marquine\Etl\Extractors\Xml::class); // Transformers $container->bind('transformer.json_decode', Marquine\Etl\Transformers\JsonDecode::class); $container->bind('transformer.json_encode', Marquine\Etl\Transformers\JsonEncode::class); $container->bind('transformer.trim', Marquine\Etl\Transformers\Trim::class); // Loaders $container->bind('loader.insert', Marquine\Etl\Loaders\Insert::class); $container->bind('loader.insert_update', Marquine\Etl\Loaders\InsertUpdate::class);
<?php use Marquine\Etl\Container; $container = Container::getInstance(); // Database $container->singleton(Marquine\Etl\Database\Manager::class); $container->alias(Marquine\Etl\Database\Manager::class, 'db'); // Extractors $container->bind('extractor.collection', Marquine\Etl\Extractors\Collection::class); $container->bind('extractor.csv', Marquine\Etl\Extractors\Csv::class); $container->bind('extractor.fixed_width', Marquine\Etl\Extractors\FixedWidth::class); $container->bind('extractor.json', Marquine\Etl\Extractors\Json::class); $container->bind('extractor.query', Marquine\Etl\Extractors\Query::class); $container->bind('extractor.table', Marquine\Etl\Extractors\Table::class); $container->bind('extractor.xml', Marquine\Etl\Extractors\Xml::class); // Transformers $container->bind('transformer.json_encode', Marquine\Etl\Transformers\JsonEncode::class); $container->bind('transformer.trim', Marquine\Etl\Transformers\Trim::class); // Loaders $container->bind('loader.insert', Marquine\Etl\Loaders\Insert::class); $container->bind('loader.insert_update', Marquine\Etl\Loaders\InsertUpdate::class);
Test de l'authentification steam avec l'api
<?php //Version 3.2 $steamauth['apikey'] = "36279F3810C6E7E1DF117281B92E6F6A"; // Your Steam WebAPI-Key found at http://steamcommunity.com/dev/apikey $steamauth['domainname'] = "preprod.evilcup.kry.wtf"; // The main URL of your website displayed in the login page $steamauth['logoutpage'] = ""; // Page to redirect to after a successfull logout (from the directory the SteamAuth-folder is located in) - NO slash at the beginning! $steamauth['loginpage'] = ""; // Page to redirect to after a successfull login (from the directory the SteamAuth-folder is located in) - NO slash at the beginning! // System stuff if (empty($steamauth['apikey'])) {die("<div style='display: block; width: 100%; background-color: red; text-align: center;'>SteamAuth:<br>Please supply an API-Key!</div>");} if (empty($steamauth['domainname'])) {$steamauth['domainname'] = $_SERVER['SERVER_NAME'];} if (empty($steamauth['logoutpage'])) {$steamauth['logoutpage'] = $_SERVER['PHP_SELF'];} if (empty($steamauth['loginpage'])) {$steamauth['loginpage'] = $_SERVER['PHP_SELF'];} ?>
<?php //Version 3.2 $steamauth['apikey'] = "8F25D1AE8072C7EEC4D51A90324B549D"; // Your Steam WebAPI-Key found at http://steamcommunity.com/dev/apikey $steamauth['domainname'] = "evilcup.kry.wtf"; // The main URL of your website displayed in the login page $steamauth['logoutpage'] = ""; // Page to redirect to after a successfull logout (from the directory the SteamAuth-folder is located in) - NO slash at the beginning! $steamauth['loginpage'] = ""; // Page to redirect to after a successfull login (from the directory the SteamAuth-folder is located in) - NO slash at the beginning! // System stuff if (empty($steamauth['apikey'])) {die("<div style='display: block; width: 100%; background-color: red; text-align: center;'>SteamAuth:<br>Please supply an API-Key!</div>");} if (empty($steamauth['domainname'])) {$steamauth['domainname'] = $_SERVER['SERVER_NAME'];} if (empty($steamauth['logoutpage'])) {$steamauth['logoutpage'] = $_SERVER['PHP_SELF'];} if (empty($steamauth['loginpage'])) {$steamauth['loginpage'] = $_SERVER['PHP_SELF'];} ?>
Add version option to the command line arguments
from paste import httpserver import argparse from .app import app from .version import __version__ """ A server for providing the app anywhere, no need for GAE """ def main(): desc=""" The youtube-dl API server. """ default_port = 9191 parser = argparse.ArgumentParser(description=desc) parser.add_argument('-p','--port', default= default_port, type=int, help='The port the server will use. The default is: {}'.format(default_port) ) parser.add_argument('--version', action='store_true', help='Print the version of the server') args = parser.parse_args() if args.version: print(__version__) exit(0) httpserver.serve(app, host='localhost', port=args.port) if __name__ == '__main__': main()
from paste import httpserver import argparse from .app import app """ A server for providing the app anywhere, no need for GAE """ def main(): desc=""" The youtube-dl API server. """ default_port = 9191 parser = argparse.ArgumentParser(description=desc) parser.add_argument('-p','--port', default= default_port, type=int, help='The port the server will use. The default is: {}'.format(default_port) ) args = parser.parse_args() httpserver.serve(app, host='localhost', port=args.port) if __name__ == '__main__': main()
Fix lint errors in tests
import os import testinfra.utils.ansible_runner testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner( os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all') def test_hosts_file(host): """Basic checks on the host.""" f = host.file('/etc/hosts') assert f.exists assert f.user == 'root' assert f.group == 'root' def test_cvmfs_client(host): """Test that the CVMFS client is properly installed.""" pkg = host.package('cvmfs') client = host.file('/usr/bin/cvmfs2') version = '2.4.3' assert pkg.is_installed assert pkg.version.startswith(version) assert client.exists def test_CODE_RADE_mounted(host): """Check that the CODE-RADE repo is mounted""" assert host.mount_point("/cvmfs/code-rade.africa-grid.org").exists def test_CODE_RADE_version(host): """Check CODE-RADE version.""" cvmfs_version = host.file('/cvmfs/code-rade.africa-grid.org/version') assert cvmfs_version.exists assert cvmfs_version.contains('FR3')
import os import testinfra.utils.ansible_runner testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner( os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all') def test_hosts_file(host): f = host.file('/etc/hosts') assert f.exists assert f.user == 'root' assert f.group == 'root' def test_cvmfs_client(host): """Test that the CVMFS client is properly installed""" pkg = host.package('cvmfs') client = host.file('/usr/bin/cvmfs2') version = '2.4.3' assert pkg.is_installed assert pkg.version.startswith(version) def test_CODE_RADE_mounted(host): """Check that the CODE-RADE repo is mounted""" assert host.mount_point("/cvmfs/code-rade.africa-grid.org").exists def test_CODE_RADE_version(host): """Check CODE-RADE version""" cvmfs_version = host.file('/cvmfs/code-rade.africa-grid.org/version') assert cvmfs_version.exists assert cvmfs_version.contains('FR3')
Refactor common serializer selection code.
from rest_framework import viewsets from paranuara_api.models import Company, Person from paranuara_api.serializers import ( CompanySerializer, CompanyListSerializer, PersonListSerializer, PersonSerializer ) class MultiSerializerMixin(object): def get_serializer_class(self): return self.serializers[self.action] class CompanyViewSet(MultiSerializerMixin, viewsets.ReadOnlyModelViewSet): queryset = Company.objects.all() lookup_field = 'index' serializers = { 'list': CompanyListSerializer, 'retrieve': CompanySerializer, } class PersonViewSet(MultiSerializerMixin, viewsets.ReadOnlyModelViewSet): queryset = Person.objects.all() lookup_field = 'index' serializers = { 'list': PersonListSerializer, 'retrieve': PersonSerializer, }
from rest_framework import viewsets from paranuara_api.models import Company, Person from paranuara_api.serializers import ( CompanySerializer, CompanyListSerializer, PersonListSerializer, PersonSerializer ) class CompanyViewSet(viewsets.ReadOnlyModelViewSet): queryset = Company.objects.all() lookup_field = 'index' serializers = { 'list': CompanyListSerializer, 'retrieve': CompanySerializer, } def get_serializer_class(self): return self.serializers[self.action] class PersonViewSet(viewsets.ReadOnlyModelViewSet): queryset = Person.objects.all() lookup_field = 'index' serializers = { 'list': PersonListSerializer, 'retrieve': PersonSerializer, } def get_serializer_class(self): return self.serializers[self.action]
Add node modules to ignore watch
module.exports = { apps : [ { name: "CaSS", script: "./src/main/server.js", watch: true, ignore_watch: ["logs", "node_modules"], instances: 1, log_file: 'logs/cass.log', env: { "CASS_LOOPBACK": "http://localhost:8080/api/", "ELASTICSEARCH_ENDPOINT": "http://localhost:9200", "PORT": "8080", "CASS_BASE": "/cass" }, node_args: [ "--max-old-space-size=512" ] } ] }
module.exports = { apps : [ { name: "CaSS", script: "./src/main/server.js", watch: true, ignore_watch: ["logs"], instances: 1, log_file: 'logs/cass.log', env: { "CASS_LOOPBACK": "http://localhost:8080/api/", "ELASTICSEARCH_ENDPOINT": "http://localhost:9200", "PORT": "8080", "CASS_BASE": "/cass" }, node_args: [ "--max-old-space-size=512" ] } ] }
Fix error handler on remove job
var express = require('express'); var kue = require('kue'); var Bot = require('../models/bot'); var router = express.Router(); /* GET home page. */ router.get('/', function(req, res, next) { res.render('index'); }); router.post('/destroy_jobs', function(req, res, next) { kue.Job.rangeByState('delayed', 0, 10000, 'asc', function( err, jobs ) { jobs.forEach(function(job) { job.remove(function() {}); }); res.send(); }); }); router.post('/destroy_all_the_things', function(req, res, next) { kue.Job.rangeByState('delayed', 0, 10000, 'asc', function( err, jobs ) { jobs.forEach(function(job) { job.remove(function(err) { if (err) console.log(err); }); }); }); Bot.remove({}) .then(function(result) { }) .catch(function(err) { res.status(500).send(err); }); res.send(); }); module.exports = router;
var express = require('express'); var kue = require('kue'); var Bot = require('../models/bot'); var router = express.Router(); /* GET home page. */ router.get('/', function(req, res, next) { res.render('index'); }); router.post('/destroy_jobs', function(req, res, next) { kue.Job.rangeByState('delayed', 0, 10000, 'asc', function( err, jobs ) { jobs.forEach(function(job) { job.remove(function() {}); }); res.send(); }); }); router.post('/destroy_all_the_things', function(req, res, next) { kue.Job.rangeByState('delayed', 0, 10000, 'asc', function( err, jobs ) { jobs.forEach(function(job) { job.remove() .then(function(res) { }) .catch(function(err) { res.status(500).send(err); }); }); }); Bot.remove({}) .then(function(result) { }) .catch(function(err) { res.status(500).send(err); }); res.send(); }); module.exports = router;
fix(envify): Apply envify globally so that local react files get processed by it.
const babelify = require('babelify') const envify = require('envify/custom') const markdown = require('browserify-markdown') const through = require('through2') const YAML = require('yamljs') const babelConfig = require('./babel-config') const util = require('./util') module.exports = function transform ({ config, env }) { util.configureEnvironment({config, env}) return [ htmlTransform, markdown({ html: true }), yamlTransform, babelify.configure(babelConfig(env)), [envify(process.env), {global: true}] // Envify needs to happen last... ] } function htmlTransform (filename) { if (!/\.html$/i.test(filename)) { return through() } return through(function (buf, enc, next) { this.push('module.exports=' + JSON.stringify(buf.toString('utf8'))) next() }) } function yamlTransform (filename) { if (!/\.yml|\.yaml$/i.test(filename)) { return through() } return through(function (buf, enc, next) { this.push('module.exports=' + JSON.stringify(YAML.parse(buf.toString('utf8')))) next() }) }
const babelify = require('babelify') const envify = require('envify/custom') const markdown = require('browserify-markdown') const through = require('through2') const YAML = require('yamljs') const babelConfig = require('./babel-config') const util = require('./util') module.exports = function transform ({ config, env }) { util.configureEnvironment({config, env}) return [ htmlTransform, markdown({ html: true }), yamlTransform, babelify.configure(babelConfig(env)), envify(process.env) // Envify needs to happen last... ] } function htmlTransform (filename) { if (!/\.html$/i.test(filename)) { return through() } return through(function (buf, enc, next) { this.push('module.exports=' + JSON.stringify(buf.toString('utf8'))) next() }) } function yamlTransform (filename) { if (!/\.yml|\.yaml$/i.test(filename)) { return through() } return through(function (buf, enc, next) { this.push('module.exports=' + JSON.stringify(YAML.parse(buf.toString('utf8')))) next() }) }
Add method for check file path in bundle's configurations
<?php /* * This file is part of the Artscore Studio Framework package. * * (c) Nicolas Claverie <info@artscore-studio.fr> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace ASF\CoreBundle\DependencyInjection; use Symfony\Component\HttpKernel\DependencyInjection\Extension; use Symfony\Component\DependencyInjection\ContainerBuilder; /** * Base class to define Bundle Extension * * @author Nicolas Claverie <info@artscore-studio.fr> * */ abstract class ASFExtension extends Extension { /** * Maps parameters in container * * @param ContainerBuilder $container * @param string $rootNodeName * @param array $config */ public function mapsParameters(ContainerBuilder $container, $rootNodeName, $config) { foreach($config as $name => $value) { if ( is_array($value) ) { $this->mapsParameters($container, $rootNodeName . '.' . $name, $value); } else { $container->setParameter($rootNodeName . '.' . $name, $value); } } } /** * Check the validity of a path done in bundle's configuration parameter * * @param string $path * @param ContainerBuilder $container * * @return boolean */ public function checkPath($path, ContainerBuilder $container) { $path = str_replace('%kernel.root_dir%', $container->getParameter('kernel.root_dir'), $path); return file_exists($path); } }
<?php /* * This file is part of the Artscore Studio Framework package. * * (c) Nicolas Claverie <info@artscore-studio.fr> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace ASF\CoreBundle\DependencyInjection; use Symfony\Component\HttpKernel\DependencyInjection\Extension; use Symfony\Component\DependencyInjection\ContainerBuilder; /** * Base class to define Bundle Extension * * @author Nicolas Claverie <info@artscore-studio.fr> * */ abstract class ASFExtension extends Extension { /** * Maps parameters in container * * @param ContainerBuilder $container * @param string $rootNodeName * @param array $config */ public function mapsParameters(ContainerBuilder $container, $rootNodeName, $config) { foreach($config as $name => $value) { if ( is_array($value) ) { $this->mapsParameters($container, $rootNodeName . '.' . $name, $value); } else { $container->setParameter($rootNodeName . '.' . $name, $value); } } } }
Fix tests for legacy phpunit versions
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Serializer\Mapping; /** * Stores metadata needed for serializing and deserializing attributes. * * Primarily, the metadata stores serialization groups. * * @internal * * @author Kévin Dunglas <dunglas@gmail.com> */ interface AttributeMetadataInterface { /** * Gets the attribute name. * * @return string */ public function getName(); /** * Adds this attribute to the given group. * * @param string $group */ public function addGroup($group); /** * Gets groups of this attribute. * * @return string[] */ public function getGroups(); /** * Sets the serialization max depth for this attribute. * * @param int|null $maxDepth */ public function setMaxDepth($maxDepth); /** * Gets the serialization max depth for this attribute. * * @return int|null */ public function getMaxDepth(); /** * Merges an {@see AttributeMetadataInterface} with in the current one. */ public function merge(AttributeMetadataInterface $attributeMetadata); }
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Serializer\Mapping; /** * Stores metadata needed for serializing and deserializing attributes. * * Primarily, the metadata stores serialization groups. * * @internal * * @author Kévin Dunglas <dunglas@gmail.com> */ interface AttributeMetadataInterface { /** * Gets the attribute name. * * @return string */ public function getName(); /** * Adds this attribute to the given group. * * @param string $group */ public function addGroup($group); /** * Gets groups of this attribute. * * @return string[] */ public function getGroups(); /** * Sets the serialization max depth for this attribute. * * @param int|null $maxDepth */ public function setMaxDepth($maxDepth); /** * Gets the serialization max depth for this attribute. * * @return int|null */ public function getMaxDepth(); /** * Merges an {@see AttributeMetadataInterface} with in the current one. */ public function merge(self $attributeMetadata); }
Change container visibility in controller
<?php namespace App\Controllers; use Psr\Http\Message\ResponseInterface; use Slim\Container; class Controller { /** * @var Container */ protected $container; /** * @param Container $container */ public function __construct(Container $container) { $this->container = $container; } /** * @param ResponseInterface $response * @param string $template * @param array $data */ public function render( ResponseInterface $response, $template, array $data = [] ) { $this->container->view->render($response, $template, $data); } /** * @param string $name * * @return mixed */ public function __get($name) { return $this->container->get($name); } }
<?php namespace App\Controllers; use Psr\Http\Message\ResponseInterface; use Slim\Container; class Controller { /** * @var Container */ private $container; /** * @param Container $container */ public function __construct(Container $container) { $this->container = $container; } /** * @param ResponseInterface $response * @param string $template * @param array $data */ public function render( ResponseInterface $response, $template, array $data = [] ) { $this->container->view->render($response, $template, $data); } /** * @param string $name * * @return mixed */ public function __get($name) { return $this->container->get($name); } }
Use 'auth:api' middleware instead 'auth:basic' to support Passport authenticated requests
<?php namespace AlgoWeb\PODataLaravel\Providers; use Illuminate\Support\Facades\Route; use Illuminate\Support\ServiceProvider; class MetadataRouteProvider extends ServiceProvider { /** * Bootstrap the application services. * * @return void */ public function boot() { self::setupRoute(); } private static function setupRoute() { Route::any( 'odata.svc/{section}', [ 'uses' => 'AlgoWeb\PODataLaravel\Controllers\ODataController@index', 'middleware' => 'auth:api'] ) ->where(['section' => '.*']); Route::any( 'odata.svc', [ 'uses' => 'AlgoWeb\PODataLaravel\Controllers\ODataController@index', 'middleware' => 'auth:api'] ); } /** * Register the application services. * * @return void */ public function register() { // } }
<?php namespace AlgoWeb\PODataLaravel\Providers; use Illuminate\Support\Facades\Route; use Illuminate\Support\ServiceProvider; class MetadataRouteProvider extends ServiceProvider { /** * Bootstrap the application services. * * @return void */ public function boot() { self::setupRoute(); } private static function setupRoute() { Route::any( 'odata.svc/{section}', [ 'uses' => 'AlgoWeb\PODataLaravel\Controllers\ODataController@index', 'middleware' => 'auth.basic'] ) ->where(['section' => '.*']); Route::any( 'odata.svc', [ 'uses' => 'AlgoWeb\PODataLaravel\Controllers\ODataController@index', 'middleware' => 'auth.basic'] ); } /** * Register the application services. * * @return void */ public function register() { // } }
Allow more symbols in authorization token
<?php namespace hiapi\Core\Auth; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Server\MiddlewareInterface; use Psr\Http\Server\RequestHandlerInterface; abstract class AuthMiddleware implements MiddlewareInterface { /** * @inheritDoc */ public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface { $this->authenticate($request); return $handler->handle($request); } abstract public function authenticate(ServerRequestInterface $request); protected function getAccessToken(ServerRequestInterface $request): ?string { return $this->getBearerToken($request) ?? $this->getParam($request, 'access_token'); } protected function getBearerToken(ServerRequestInterface $request): ?string { $header = $request->getHeaderLine('Authorization'); if (preg_match('/^Bearer\s+([a-zA-Z0-9._-]{30,50})$/', $header, $matches)) { return $matches[1]; } return null; } public function getParam(ServerRequestInterface $request, string $name): ?string { return $request->getParsedBody()[$name] ?? $request->getQueryParams()[$name] ?? null; } }
<?php namespace hiapi\Core\Auth; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Server\MiddlewareInterface; use Psr\Http\Server\RequestHandlerInterface; abstract class AuthMiddleware implements MiddlewareInterface { /** * @inheritDoc */ public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface { $this->authenticate($request); return $handler->handle($request); } abstract public function authenticate(ServerRequestInterface $request); protected function getAccessToken(ServerRequestInterface $request): ?string { return $this->getBearerToken($request) ?? $this->getParam($request, 'access_token'); } protected function getBearerToken(ServerRequestInterface $request): ?string { $header = $request->getHeaderLine('Authorization'); if (preg_match('/^Bearer\s+([a-fA-F0-9]{30,50})$/', $header, $matches)) { return $matches[1]; } return null; } public function getParam(ServerRequestInterface $request, string $name): ?string { return $request->getParsedBody()[$name] ?? $request->getQueryParams()[$name] ?? null; } }
Improve the clarity of the totalLength assignment
define(['dojo/_base/lang', 'dojo/when'], function (lang, when) { // TODO: Make this API more extensible, possibly with an options function forEach(callback, instance) { return when(this, function(data) { for (var i = 0, l = data.length; i < l; i++){ callback.call(instance, data[i], data); } }); } return function (data, options) { var hasTotalLength = options && 'totalLength' in options; if(data.then) { data = lang.delegate(data); // a promise for the eventual realization of the totalLenght, in // case it comes from the resolved data var totalLengthPromise = data.then(function (data) { // calculate total length, now that we have access to the resolved data var totalLength = hasTotalLength ? options.totalLength : data.totalLength || data.length; // make it available on the resolved data data.totalLength = totalLength; return totalLength; }); // make the totalLength available on the promise (whether through the options or the enventual // access to the resolved data) data.totalLength = hasTotalLength ? options.totalLength : totalLengthPromise; } else { data.totalLength = hasTotalLength ? options.totalLength : data.length; } data.forEach = forEach; return data; }; });
define(['dojo/_base/lang', 'dojo/when'], function (lang, when) { // TODO: Make this API more extensible, possibly with an options function forEach(callback, instance) { return when(this, function(data) { for (var i = 0, l = data.length; i < l; i++){ callback.call(instance, data[i], data); } }); } return function (data, options) { var hasTotalLength = options && 'totalLength' in options; if(data.then) { data = lang.delegate(data); var totalLengthPromise = data.then(function (data) { return (data.totalLength = hasTotalLength ? options.totalLength : data.totalLength || data.length); }); data.totalLength = hasTotalLength ? options.totalLength : totalLengthPromise; } else { data.totalLength = hasTotalLength ? options.totalLength : data.length; } data.forEach = forEach; return data; }; });
Set popup height equal to window height
$(document).ready(function(){ $('.popup__toggle').on('click', popup); function popup() { $('#popup').toggleClass("open"); } function fileHandler(event){ var file = event.target.files[0]; //event.target references the object that dispatched the event (so here it is the input element) var reader = new FileReader(); reader.onload = function(event){ var data = event.target.result; //again event.target references the object that dispatched the event (here it is reader). $("#preview-img").attr('src', data); }; reader.readAsDataURL(file); } function addImgToInfo() { $("#preview-img").clone().attr('id', '').appendTo('#image-wrapper'); } $('#file').on("change", fileHandler); $('#submit-img').on('click', addImgToInfo); }); var map; function initMap() { map = new google.maps.Map(document.getElementById('map'), { center: {lat: -34.397, lng: 150.644}, zoom: 8 }); $("html, body, #popup").css({ height: $(window).height() }); }
$(document).ready(function(){ $('.popup__toggle').on('click', popup); function popup() { $('#popup').toggleClass("open"); } function fileHandler(event){ var file = event.target.files[0]; //event.target references the object that dispatched the event (so here it is the input element) var reader = new FileReader(); reader.onload = function(event){ var data = event.target.result; //again event.target references the object that dispatched the event (here it is reader). $("#preview-img").attr('src', data); }; reader.readAsDataURL(file); } function addImgToInfo() { $("#preview-img").clone().attr('id', '').appendTo('#image-wrapper'); } $('#file').on("change", fileHandler); $('#submit-img').on('click', addImgToInfo); }); var map; function initMap() { map = new google.maps.Map(document.getElementById('map'), { center: {lat: -34.397, lng: 150.644}, zoom: 8 }); }
Use plain `expected` for self-testing samples
'use strict'; var assert = require('assert'); function testHandler(actual) { var expected = testHandler.expected; assert.strictEqual(actual.length, expected.length); assert.strictEqual( actual[0](), expected[0]()); assert.strictEqual( actual[1](10, 20), expected[1](10, 20)); assert.deepEqual( actual[2]('book'), expected[2]('book')); } testHandler.expected = [ function () { return 42; }, function (x, y) { return x + y; }, function (foo) { var result = 'There is my ' + foo + ' at the table.'; return { first: 42, second: 'sum', third: result }; } ]; module.exports = testHandler;
'use strict'; var assert = require('assert'); function testHandler(actual) { var expected = testHandler.getExpectedData(); assert.strictEqual(actual.length, expected.length); assert.strictEqual( actual[0](), expected[0]()); assert.strictEqual( actual[1](10, 20), expected[1](10, 20)); assert.deepEqual( actual[2]('book'), expected[2]('book')); } testHandler.getExpectedData = function getExpectedData() { return [ function () { return 42; }, function (x, y) { return x + y; }, function (foo) { var result = 'There is my ' + foo + ' at the table.'; return { first: 42, second: 'sum', third: result }; } ]; }; module.exports = testHandler;
Patch when no data received. If there was not a response from the Mojang servers then an error would occur: ``` SyntaxError: Unexpected end of input at Object.parse (native) at IncomingMessage.<anonymous> (/home/player-info/node_modules/mojang/lib/_request.js:18:21) at emitNone (events.js:85:20) at IncomingMessage.emit (events.js:179:7) at endReadableNT (_stream_readable.js:913:12) at _combinedTickCallback (node.js:377:13) at process._tickCallback (node.js:401:11) ``` You can replicate by looking up a username which does not exist.
'use strict'; const https = require('https'); function _request(options, body) { return new Promise(function(resolve, reject) { const request = https.request(Object.assign({ hostname: 'api.mojang.com', headers: { 'Content-Type': 'application/json' }, }, options), function(resp) { let data = []; resp.on('data', function(chunk) { data.push(chunk); }); resp.on('end', function() { if(data.length < 1){ return reject(new Error("No data received.")); } data = JSON.parse(Buffer.concat(data).toString()); resolve(data); }); resp.on('error', reject); }); request.on('error', reject); if (typeof body === 'object' && !(body instanceof Buffer)) { request.write(JSON.stringify(body)); } else if (typeof body !== 'undefined') { request.write(body); } request.end(); }); } module.exports = _request;
'use strict'; const https = require('https'); function _request(options, body) { return new Promise(function(resolve, reject) { const request = https.request(Object.assign({ hostname: 'api.mojang.com', headers: { 'Content-Type': 'application/json' }, }, options), function(resp) { let data = []; resp.on('data', function(chunk) { data.push(chunk); }); resp.on('end', function() { data = JSON.parse(Buffer.concat(data).toString()); resolve(data); }); resp.on('error', reject); }); request.on('error', reject); if (typeof body === 'object' && !(body instanceof Buffer)) { request.write(JSON.stringify(body)); } else if (typeof body !== 'undefined') { request.write(body); } request.end(); }); } module.exports = _request;
Add the check for children
import { enqueueRender } from './component'; export let i = 0; /** * * @param {any} defaultValue */ export function createContext(defaultValue) { const ctx = {}; const context = { _id: '__cC' + i++, _defaultValue: defaultValue, Consumer(props, context) { this.shouldComponentUpdate = function (_props, _state, _context) { return _context !== context || this.props.children !== _props.children; }; return props.children(context); }, Provider(props) { if (!this.getChildContext) { const subs = []; this.getChildContext = () => { ctx[context._id] = this; return ctx; }; this.shouldComponentUpdate = props => { subs.some(c => { // Check if still mounted if (c._parentDom) { c.context = props.value; enqueueRender(c); } }); }; this.sub = (c) => { subs.push(c); let old = c.componentWillUnmount; c.componentWillUnmount = () => { subs.splice(subs.indexOf(c), 1); old && old.call(c); }; }; } return props.children; } }; context.Consumer.contextType = context; return context; }
import { enqueueRender } from './component'; export let i = 0; /** * * @param {any} defaultValue */ export function createContext(defaultValue) { const ctx = {}; const context = { _id: '__cC' + i++, _defaultValue: defaultValue, Consumer(props, context) { return props.children(context); }, Provider(props) { if (!this.getChildContext) { const subs = []; this.getChildContext = () => { ctx[context._id] = this; return ctx; }; this.shouldComponentUpdate = props => { subs.some(c => { // Check if still mounted if (c._parentDom) { c.context = props.value; enqueueRender(c); } }); }; this.sub = (c) => { subs.push(c); let old = c.componentWillUnmount; c.componentWillUnmount = () => { subs.splice(subs.indexOf(c), 1); old && old.call(c); }; }; } return props.children; } }; context.Consumer.contextType = context; return context; }
Revert "middleware.CloseNotify: Remove defer cancel()" This reverts commit e135f36c819d75a0d55d95b1c6e2c6faf132dafa. Turns out that this commit started leaking goroutines, when the underlying client kept persistent connection to the server and reused it for multiple requests.
package middleware import ( "net/http" "github.com/pressly/chi" "golang.org/x/net/context" ) // 499 Client Closed Request (Nginx) // https://en.wikipedia.org/wiki/List_of_HTTP_status_codes const StatusClientClosedRequest = 499 // CloseNotify cancels the ctx when the underlying connection has gone away. // This middleware can be used to cancel long operations on the server // if the client has disconnected before the response is ready. func CloseNotify(next chi.Handler) chi.Handler { fn := func(ctx context.Context, w http.ResponseWriter, r *http.Request) { cn, ok := w.(http.CloseNotifier) if !ok { panic("middleware.CloseNotify expects http.ResponseWriter to implement http.CloseNotifier interface") } ctx, cancel := context.WithCancel(ctx) defer cancel() go func() { select { case <-ctx.Done(): return case <-cn.CloseNotify(): w.WriteHeader(StatusClientClosedRequest) cancel() return } }() next.ServeHTTPC(ctx, w, r) } return chi.HandlerFunc(fn) }
package middleware import ( "net/http" "github.com/pressly/chi" "golang.org/x/net/context" ) // 499 Client Closed Request (Nginx) // https://en.wikipedia.org/wiki/List_of_HTTP_status_codes const StatusClientClosedRequest = 499 // CloseNotify cancels the ctx when the underlying connection has gone away. // This middleware can be used to cancel long operations on the server // if the client has disconnected before the response is ready. func CloseNotify(next chi.Handler) chi.Handler { fn := func(ctx context.Context, w http.ResponseWriter, r *http.Request) { cn, ok := w.(http.CloseNotifier) if !ok { panic("middleware.CloseNotify expects http.ResponseWriter to implement http.CloseNotifier interface") } ctx, cancel := context.WithCancel(ctx) go func() { select { case <-ctx.Done(): return case <-cn.CloseNotify(): w.WriteHeader(StatusClientClosedRequest) cancel() return } }() next.ServeHTTPC(ctx, w, r) } return chi.HandlerFunc(fn) }
Put in date = self.request.get(date) in order to call the date from the HTML.
# request handler for editing page (/edit) goes here # assume admin login has already been handled import cgi from google.appengine.api import users import webapp2 class DateHandler(webapp2.RequestHandler): def get(self): date = self.request.get(date) template_values = { } template = jinja_environment.get_template('dates.html') self.response.out.write(template.render(template_values)) class EditHandler(webapp2.RequestHandler): def get(self): template_values = { } template = jinja_environment.get_template('edit.html') self.response.out.write(template.render(template_values)) app = webapp2.WSGIApplication([ ('/date', DateHandler) ('/edit', EditHandler) ], debug=True)
# request handler for editing page (/edit) goes here # assume admin login has already been handled import cgi from google.appengine.api import users import webapp2 class DateHandler(webapp2.RequestHandler): def get(self): template_values = { } template = jinja_environment.get_template('dates.html') self.response.out.write(template.render(template_values)) class EditHandler(webapp2.RequestHandler): def get(self): template_values = { } template = jinja_environment.get_template('edit.html') self.response.out.write(template.render(template_values)) app = webapp2.WSGIApplication([ ('/date', DateHandler) ('/edit', EditHandler) ], debug=True)
Remove bad torrents assumes torrent_to_search_string already ran.
from providers.popularity.provider import PopularityProvider from utils.torrent_util import torrent_to_search_string, remove_bad_torrent_matches IDENTIFIER = "Torrentz" class Provider(PopularityProvider): PAGES_TO_FETCH = 1 def get_popular(self): results = [] for page in range(Provider.PAGES_TO_FETCH): terms = ["movies", "hd", "-xxx", "-porn"] url = "https://torrentz.eu/search?q=%s&p=%s" % ( "+".join(terms), page ) results += self.parse_html(url, ".results dt a") results = [torrent_to_search_string(name) for name in results] results = remove_bad_torrent_matches(results) return results
from providers.popularity.provider import PopularityProvider from utils.torrent_util import torrent_to_search_string, remove_bad_torrent_matches IDENTIFIER = "Torrentz" class Provider(PopularityProvider): PAGES_TO_FETCH = 1 def get_popular(self): results = [] for page in range(Provider.PAGES_TO_FETCH): terms = ["movies", "hd", "-xxx", "-porn"] url = "https://torrentz.eu/search?q=%s&p=%s" % ( "+".join(terms), page ) results += self.parse_html(url, ".results dt a") results = remove_bad_torrent_matches(results) results = [torrent_to_search_string(name) for name in results] return results
Use button instead of link to navigate to search results
import React from 'react' import { sparqlConnect } from '../sparql/configure-sparql' import { LOADING, LOADED, FAILED } from 'sparql-connect' import { browserHistory } from 'react-router' import { uriToLink } from '../router-mapping' import { connect } from 'react-redux' import { changeKeyword } from '../actions/app-state' function SearchInput({ keyword, changeKeyword }) { return ( <span> Search everything : <input type="search" placeholder="Enter a keyword" name="search_input" value={keyword} onChange={e => changeKeyword(e.target.value)} /> <button onClick={() => browserHistory.push(uriToLink.searchItems(keyword))}> OK </button> </span> ) } const mapStateToProps = state => ({ keyword: state.appState.keyword }) export default connect(mapStateToProps, { changeKeyword })(SearchInput)
import React from 'react' import { sparqlConnect } from '../sparql/configure-sparql' import { LOADING, LOADED, FAILED } from 'sparql-connect' import { Link } from 'react-router' import { uriToLink } from '../router-mapping' import { connect } from 'react-redux' import { changeKeyword } from '../actions/app-state' function SearchInput({ keyword, changeKeyword }) { return ( <span> Search everything : <input type="search" placeholder="Enter a keyword" name="search_input" value={keyword} onChange={e => changeKeyword(e.target.value)} /> <Link to={uriToLink.searchItems(keyword)}>Search</Link> </span> ) } const mapStateToProps = state => ({ keyword: state.appState.keyword }) export default connect(mapStateToProps, { changeKeyword })(SearchInput)
Set up creating files for unused items
""" Includes execution logic for the commands """ import os import csv import random def run_create(count): file_list = [filename for filename in os.listdir('.') if os.path.isfile(filename)] sets = {} for filename in file_list: content = open(os.path.join(os.curdir, filename)).read().split('\n') random.shuffle(content) sets[filename[:filename.index('.')].title()] = content if not os.path.exists('Lists'): os.mkdir('Lists') break_point = count for i in xrange(count): try: f = open(os.path.join(os.curdir, 'Lists', str(i+1) + '.txt'), 'w') file_content = '' for category, category_list in sets.items(): file_content += (category + ' -- ' + category_list[i] + '\n') f.write(file_content) f.close() except IndexError: break_point = i break try: print sets for category, category_list in sets.items(): f = open(os.path.join(os.curdir, 'Remaining_' + category + '.txt'), 'w') file_content = "\n".join(category_list[break_point:]) f.write(file_content) f.close() except NameError, e: print e pass return
""" Includes execution logic for the commands """ import os import csv import random def run_create(count): file_list = [filename for filename in os.listdir('.') if os.path.isfile(filename)] sets = {} for filename in file_list: content = open(os.path.join(os.curdir, filename)).read().split('\n') random.shuffle(content) sets[filename[:filename.index('.')].title()] = content if not os.path.exists('Lists'): os.mkdir('Lists') for i in xrange(count): try: f = open(os.path.join(os.curdir, 'Lists', str(i+1) + '.txt'), 'w') file_content = '' for category, category_list in sets.items(): file_content += (category + ' -- ' + category_list[i] + '\n') f.write(file_content) f.close() except IndexError: break_point = i break return
Improve title design of foolproof dialog
import React, { PropTypes } from 'react' import classnames from 'classnames' import classes from './FoolproofDialog.scss' import Button from 'components/Button' class FoolproofDialog extends React.Component { handleClickDeleteButton = () => { this.props.onCompleted(this.props.ID) } render () { return (<dialog className={classnames('mdl-dialog', classes.dialog)}> <h4 className={classnames('mdl-dialog__title', classes.title)}> Delete <i>{this.props.name}</i> ? </h4> <div className='mdl-dialog__content'> This operation can not be undone. </div> <div className='mdl-dialog__actions'> <Button onClick={this.handleClickDeleteButton} name='DELETE' class='mdl-button--accent' /> <Button onClick={this.props.onCanceled} name='Cancel' /> </div> </dialog>) } } FoolproofDialog.propTypes = { onCompleted: PropTypes.func.isRequired, onCanceled: PropTypes.func.isRequired, name: PropTypes.string.isRequired, ID: PropTypes.string.isRequired } export default FoolproofDialog
import React, { PropTypes } from 'react' import classnames from 'classnames' import classes from './FoolproofDialog.scss' import Button from 'components/Button' class FoolproofDialog extends React.Component { handleClickDeleteButton = () => { this.props.onCompleted(this.props.ID) } render () { return (<dialog className={classnames('mdl-dialog', classes.dialog)}> <h2 className={classnames('mdl-dialog__title', classes.title)}> Delete {this.props.name} </h2> <div className='mdl-dialog__content'> This operation can not be undone. </div> <div className='mdl-dialog__actions'> <Button onClick={this.handleClickDeleteButton} name='DELETE' class='mdl-button--accent' /> <Button onClick={this.props.onCanceled} name='Cancel' /> </div> </dialog>) } } FoolproofDialog.propTypes = { onCompleted: PropTypes.func.isRequired, onCanceled: PropTypes.func.isRequired, name: PropTypes.string.isRequired, ID: PropTypes.string.isRequired } export default FoolproofDialog
Switch to a test schedule based on the environment Switching an environment variable and kicking the `clock` process feels like a neater solution than commenting out one line, uncommenting another, and redeploying.
from apscheduler.schedulers.blocking import BlockingScheduler import logging import warner import archiver import announcer import flagger import os # When testing changes, set the "TEST_SCHEDULE" envvar to run more often if os.getenv("TEST_SCHEDULE"): schedule_kwargs = {"hour": "*", "minute": "*/10"} else: schedule_kwargs = {"hour": 4} logging.basicConfig() sched = BlockingScheduler() @sched.scheduled_job("cron", **schedule_kwargs) def destalinate_job(): print("Destalinating") if "SB_TOKEN" not in os.environ or "API_TOKEN" not in os.environ: print("ERR: Missing at least one Slack environment variable.") else: scheduled_warner = warner.Warner() scheduled_archiver = archiver.Archiver() scheduled_announcer = announcer.Announcer() scheduled_flagger = flagger.Flagger() print("Warning") scheduled_warner.warn() print("Archiving") scheduled_archiver.archive() print("Announcing") scheduled_announcer.announce() print("Flagging") scheduled_flagger.flag() print("OK: destalinated") print("END: destalinate_job") sched.start()
from apscheduler.schedulers.blocking import BlockingScheduler import logging import warner import archiver import announcer import flagger import os logging.basicConfig() sched = BlockingScheduler() @sched.scheduled_job("cron", hour=4) #@sched.scheduled_job("cron", hour="*", minute="*/10") # for testing def destalinate_job(): print("Destalinating") if "SB_TOKEN" not in os.environ or "API_TOKEN" not in os.environ: print("ERR: Missing at least one Slack environment variable.") else: scheduled_warner = warner.Warner() scheduled_archiver = archiver.Archiver() scheduled_announcer = announcer.Announcer() scheduled_flagger = flagger.Flagger() print("Warning") scheduled_warner.warn() print("Archiving") scheduled_archiver.archive() print("Announcing") scheduled_announcer.announce() print("Flagging") scheduled_flagger.flag() print("OK: destalinated") print("END: destalinate_job") sched.start()
Update blueprint installed package versions. This was already updated upstream, just want to make sure we keep these in sync.
module.exports = { normalizeEntityName: function() { // this prevents an error when the entityName is // not specified (since that doesn't actually matter // to us }, afterInstall: function() { var addonContext = this; return this.addBowerPackageToProject('qunit', '~1.17.0') .then(function() { return addonContext.addBowerPackageToProject('stefanpenner/ember-cli-shims', '0.0.3'); }) .then(function() { return addonContext.addBowerPackageToProject('ember-qunit-notifications', '0.0.5'); }) .then(function() { return addonContext.addBowerPackageToProject('ember-qunit', '0.1.8'); }); } };
module.exports = { normalizeEntityName: function() { // this prevents an error when the entityName is // not specified (since that doesn't actually matter // to us }, afterInstall: function() { var addonContext = this; return this.addBowerPackageToProject('qunit', '~1.16.0') .then(function() { return addonContext.addBowerPackageToProject('stefanpenner/ember-cli-shims', '0.0.3'); }) .then(function() { return addonContext.addBowerPackageToProject('ember-qunit-notifications', '0.0.4'); }) .then(function() { return addonContext.addBowerPackageToProject('ember-qunit', '0.1.8'); }); } };
REMOVE unnecessary comment, bug is fixed
import React from 'react'; import PropTypes from 'prop-types'; import { SyntaxHighlighter } from '@storybook/components'; const Code = ({ language, code }) => ( <SyntaxHighlighter bordered copyable language={language}> {code} </SyntaxHighlighter> ); Code.propTypes = { language: PropTypes.string.isRequired, code: PropTypes.string.isRequired, }; export { Code }; export function Blockquote({ children }) { const style = { fontSize: '1.88em', fontFamily: 'Menlo, Monaco, "Courier New", monospace', borderLeft: '8px solid #fafafa', padding: '1rem', }; return <blockquote style={style}>{children}</blockquote>; } Blockquote.propTypes = { children: PropTypes.node }; Blockquote.defaultProps = { children: null }; export { default as Pre } from './pre/pre';
import React from 'react'; import PropTypes from 'prop-types'; import { SyntaxHighlighter } from '@storybook/components'; // XXX: is this a bug? should it be (props) => ? const Code = ({ language, code }) => ( <SyntaxHighlighter bordered copyable language={language}> {code} </SyntaxHighlighter> ); Code.propTypes = { language: PropTypes.string.isRequired, code: PropTypes.string.isRequired, }; export { Code }; export function Blockquote({ children }) { const style = { fontSize: '1.88em', fontFamily: 'Menlo, Monaco, "Courier New", monospace', borderLeft: '8px solid #fafafa', padding: '1rem', }; return <blockquote style={style}>{children}</blockquote>; } Blockquote.propTypes = { children: PropTypes.node }; Blockquote.defaultProps = { children: null }; export { default as Pre } from './pre/pre';
Update verbiage to be more generic on the base class.
<?php namespace Droath\ProjectX\Engine; use Droath\ProjectX\ProjectXAwareTrait; use League\Container\ContainerAwareInterface; use League\Container\ContainerAwareTrait; use Robo\Common\IO; use Robo\Contract\BuilderAwareInterface; use Robo\Contract\IOAwareInterface; use Robo\LoadAllTasks; /** * Define Project-X project type. */ abstract class EngineType implements BuilderAwareInterface, ContainerAwareInterface, IOAwareInterface, EngineTypeInterface { use IO; use LoadAllTasks; use ContainerAwareTrait; use ProjectXAwareTrait; /** * {@inheritdoc} */ public function up() { $this->say('Project engine is preparing for takeoff. 🚀'); } /** * {@inheritdoc} */ public function down() { $this->say('Project engine is preparing to shutdown. 💥'); } /** * {@inheritdoc} */ public function install() { $this->say('Project engine is running the install process. 🤘'); } /** * Define engine type identifier. * * @return string */ abstract public function getTypeId(); }
<?php namespace Droath\ProjectX\Engine; use Droath\ProjectX\ProjectXAwareTrait; use League\Container\ContainerAwareInterface; use League\Container\ContainerAwareTrait; use Robo\Common\IO; use Robo\Contract\BuilderAwareInterface; use Robo\Contract\IOAwareInterface; use Robo\LoadAllTasks; /** * Define Project-X project type. */ abstract class EngineType implements BuilderAwareInterface, ContainerAwareInterface, IOAwareInterface, EngineTypeInterface { use IO; use LoadAllTasks; use ContainerAwareTrait; use ProjectXAwareTrait; /** * {@inheritdoc} */ public function up() { $this->say('Docker engine is preparing for takeoff. 🚀'); } /** * {@inheritdoc} */ public function down() { $this->say('Docker engine is preparing to shutdown. 💥'); } /** * {@inheritdoc} */ public function install() { $this->say('Docker engine is running the install process. 🤘'); } /** * Define engine type identifier. * * @return string */ abstract public function getTypeId(); }
Add a has_expired() method to the Timer class.
inf = infinity = float('inf') class Timer: def __init__(self, duration, *callbacks): self.duration = duration self.callbacks = list(callbacks) self.elapsed = 0 self.expired = False self.paused = False def register(self, callback): self.callbacks.append(callback) def unregister(self, callback): self.callbacks.remove(callback) def pause(self): self.paused = True def unpause(self): self.pause = False def update(self, time): if self.expired: return if self.elapsed > self.duration: return self.elapsed += time if self.elapsed > self.duration: self.expired = True for callback in self.callbacks: callback() def has_expired(self): return self.expired
inf = infinity = float('inf') class Timer: def __init__(self, duration, *callbacks): self.duration = duration self.callbacks = list(callbacks) self.elapsed = 0 self.paused = False def register(self, callback): self.callbacks.append(callback) def unregister(self, callback): self.callbacks.remove(callback) def pause(self): self.paused = True def unpause(self): self.pause = False def update(self, time): if self.elapsed > self.duration: return self.elapsed += time if self.elapsed > self.duration: for callback in self.callbacks: callback()
Fix name of offsetdb in toml
package file import "github.com/vektra/cypress" import "path/filepath" type Plugin struct { Paths []string OffsetDB string `toml:"offsetdb"` } func (p *Plugin) Generator() (cypress.Generator, error) { m := NewMonitor() var files []string for _, pat := range p.Paths { matches, err := filepath.Glob(pat) if err != nil { return nil, err } files = append(files, matches...) } if p.OffsetDB != "" { err := m.OpenOffsetDB(p.OffsetDB) if err != nil { return nil, err } } err := m.OpenFiles(false, files) if err != nil { return nil, err } return m.Generator() } func (p *Plugin) Receiver() (cypress.Receiver, error) { return nil, cypress.ErrNoReceiver } func init() { cypress.AddPlugin("file", func() cypress.Plugin { return &Plugin{} }) }
package file import "github.com/vektra/cypress" import "path/filepath" type Plugin struct { Paths []string OffsetDB string } func (p *Plugin) Generator() (cypress.Generator, error) { m := NewMonitor() var files []string for _, pat := range p.Paths { matches, err := filepath.Glob(pat) if err != nil { return nil, err } files = append(files, matches...) } if p.OffsetDB != "" { err := m.OpenOffsetDB(p.OffsetDB) if err != nil { return nil, err } } err := m.OpenFiles(false, files) if err != nil { return nil, err } return m.Generator() } func (p *Plugin) Receiver() (cypress.Receiver, error) { return nil, cypress.ErrNoReceiver } func init() { cypress.AddPlugin("file", func() cypress.Plugin { return &Plugin{} }) }
Fix missing default empty options
module.exports = client => async (key, get, options = {}) => { if ((typeof options === 'object' && options.asSeconds) || typeof options === 'number') { options = { expire: options }; } if (typeof options.expire === 'object' && options.expire.asSeconds) { options.expire = options.expire.asSeconds(); } let value; if (client.getJSON) { value = await client.getJSON(key); } else { value = await client.get(key); } if (!value || (options.invalidate && options.invalidate(value))) { value = await get(); if (client.setJSON) { await client.setJSON(key, value, options.expire); } else { if (options.expire) { await client.set(key, value, 'EX', options.expire); } else { await client.set(key, value); } } } else if (options.refresh) { await client.expire(key, options.expire); } return value; };
module.exports = client => async (key, get, options) => { if ((typeof options === 'object' && options.asSeconds) || typeof options === 'number') { options = { expire: options }; } if (typeof options.expire === 'object' && options.expire.asSeconds) { options.expire = options.expire.asSeconds(); } let value; if (client.getJSON) { value = await client.getJSON(key); } else { value = await client.get(key); } if (!value || (options.invalidate && options.invalidate(value))) { value = await get(); if (client.setJSON) { await client.setJSON(key, value, options.expire); } else { if (options.expire) { await client.set(key, value, 'EX', options.expire); } else { await client.set(key, value); } } } else if (options.refresh) { await client.expire(key, options.expire); } return value; };
Add option to disable enforcer
package config type Server struct { Debug bool API API DB DB Helm Helm LDAP LDAP SecretsDir string `valid:"dir"` Enforcer Enforcer } func (s Server) IsDebug() bool { return s.Debug } // LDAP contains configuration for LDAP sync service (host, port, DN, filter query and mapping of LDAP properties to Aptomi attributes) type LDAP struct { Host string Port int BaseDN string Filter string LabelToAttributes map[string]string } // GetAttributes Returns the list of attributes to be retrieved from LDAP func (cfg *LDAP) GetAttributes() []string { result := []string{} for _, attr := range cfg.LabelToAttributes { result = append(result, attr) } return result } type Helm struct { ChartsDir string `valid:"dir,required"` } type DB struct { Connection string `valid:"required"` } type Enforcer struct { Disabled bool }
package config type Server struct { Debug bool API API DB DB Helm Helm LDAP LDAP SecretsDir string `valid:"dir"` Enforcer Enforcer } func (s Server) IsDebug() bool { return s.Debug } // LDAP contains configuration for LDAP sync service (host, port, DN, filter query and mapping of LDAP properties to Aptomi attributes) type LDAP struct { Host string Port int BaseDN string Filter string LabelToAttributes map[string]string } // GetAttributes Returns the list of attributes to be retrieved from LDAP func (cfg *LDAP) GetAttributes() []string { result := []string{} for _, attr := range cfg.LabelToAttributes { result = append(result, attr) } return result } type Helm struct { ChartsDir string `valid:"dir,required"` } type DB struct { Connection string `valid:"required"` } type Enforcer struct { SkipApply bool }
Use class constants instead of class names.
<?php namespace solutionweb\gatekeeper\utils; use mako\application\Package; use solutionweb\gatekeeper\utils\commands\ActivateUserCommand; use solutionweb\gatekeeper\utils\commands\CreateGroupCommand; use solutionweb\gatekeeper\utils\commands\CreateUserCommand; use solutionweb\gatekeeper\utils\commands\DeleteGroupCommand; use solutionweb\gatekeeper\utils\commands\GroupMemberCommand; use solutionweb\gatekeeper\utils\commands\SetPasswordCommand; /** * Package registraion class. * * @author Bert Peters <bert@solution-web.nl> */ class GatekeeperUtilsPackage extends Package { protected $packageName = "solution-web/gatekeeper-utils"; /** * Register the available commands. */ protected $commands = [ "gatekeeper::user.create" => CreateUserCommand::class, "gatekeeper::user.activate" => ActivateUserCommand::class, "gatekeeper::user.password" => SetPasswordCommand::class, "gatekeeper::group.create" => CreateGroupCommand::class, "gatekeeper::group.delete" => DeleteGroupCommand::class, "gatekeeper::group.member" => GroupMemberCommand::class, ]; }
<?php namespace solutionweb\gatekeeper\utils; use mako\application\Package; /** * Package registraion class. * * @author Bert Peters <bert@solution-web.nl> */ class GatekeeperUtilsPackage extends Package { protected $packageName = "solution-web/gatekeeper-utils"; /** * Register the available commands. */ protected $commands = [ "gatekeeper::user.create" => 'solutionweb\gatekeeper\utils\commands\CreateUserCommand', "gatekeeper::user.activate" => 'solutionweb\gatekeeper\utils\commands\ActivateUserCommand', "gatekeeper::user.password" => 'solutionweb\gatekeeper\utils\commands\SetPasswordCommand', "gatekeeper::group.create" => 'solutionweb\gatekeeper\utils\commands\CreateGroupCommand', "gatekeeper::group.delete" => 'solutionweb\gatekeeper\utils\commands\DeleteGroupCommand', "gatekeeper::group.member" => 'solutionweb\gatekeeper\utils\commands\GroupMemberCommand', ]; }
Fix compatibility with Numpy 1.4.1
# Licensed under a 3-clause BSD style license - see LICENSE.rst import numpy as np from ....tests.compat import assert_allclose from ....tests.helper import pytest from ..make_kernel import make_kernel try: import scipy HAS_SCIPY = True except ImportError: HAS_SCIPY = False @pytest.mark.skipif('not HAS_SCIPY') def test_airy(): """ Test kerneltype airy, a.k.a. brickwall Checks https://github.com/astropy/astropy/pull/939 """ k1 = make_kernel([3, 3], kernelwidth=0.5, kerneltype='airy') ref = np.array([[ 0.06375119, 0.12992753, 0.06375119], [ 0.12992753, 0.22528514, 0.12992753], [ 0.06375119, 0.12992753, 0.06375119]]) assert_allclose(k1, ref, rtol=0, atol=1e-7)
# Licensed under a 3-clause BSD style license - see LICENSE.rst import numpy as np from numpy.testing import assert_allclose from ....tests.helper import pytest from ..make_kernel import make_kernel try: import scipy HAS_SCIPY = True except ImportError: HAS_SCIPY = False @pytest.mark.skipif('not HAS_SCIPY') def test_airy(): """ Test kerneltype airy, a.k.a. brickwall Checks https://github.com/astropy/astropy/pull/939 """ k1 = make_kernel([3, 3], kernelwidth=0.5, kerneltype='airy') ref = np.array([[ 0.06375119, 0.12992753, 0.06375119], [ 0.12992753, 0.22528514, 0.12992753], [ 0.06375119, 0.12992753, 0.06375119]]) assert_allclose(k1, ref, rtol=0, atol=1e-7)
Set nose.collector as the test_suite
# Python imports from setuptools import setup # Project imports from notable import app # Attributes AUTHOR = 'John McFarlane' DESCRIPTION = 'A very simple note taking application' EMAIL = 'john.mcfarlane@rockfloat.com' NAME = 'Notable' PYPI = 'http://pypi.python.org/packages/source/N/Notable' URL = 'https://github.com/jmcfarlane/Notable' CLASSIFIERS = """ Development Status :: 2 - Pre-Alpha Intended Audience :: Developers License :: OSI Approved :: MIT License Operating System :: OS Independent Programming Language :: Python Topic :: Internet :: WWW/HTTP Intended Audience :: End Users/Desktop Topic :: Office/Business :: News/Diary Topic :: Security :: Cryptography Topic :: Utilities """ setup( author = AUTHOR, author_email = EMAIL, classifiers = [c for c in CLASSIFIERS.split('\n') if c], description = DESCRIPTION, download_url = '%s/Notable-%s.tar.gz' % (PYPI, app.version), include_package_data = True, name = NAME, packages = ['notable'], scripts = ['scripts/notable'], test_suite='nose.collector', url = URL, version = app.version )
# Python imports from setuptools import setup # Project imports from notable import app # Attributes AUTHOR = 'John McFarlane' DESCRIPTION = 'A very simple note taking application' EMAIL = 'john.mcfarlane@rockfloat.com' NAME = 'Notable' PYPI = 'http://pypi.python.org/packages/source/N/Notable' URL = 'https://github.com/jmcfarlane/Notable' CLASSIFIERS = """ Development Status :: 2 - Pre-Alpha Intended Audience :: Developers License :: OSI Approved :: MIT License Operating System :: OS Independent Programming Language :: Python Topic :: Internet :: WWW/HTTP Intended Audience :: End Users/Desktop Topic :: Office/Business :: News/Diary Topic :: Security :: Cryptography Topic :: Utilities """ setup( author = AUTHOR, author_email = EMAIL, classifiers = [c for c in CLASSIFIERS.split('\n') if c], description = DESCRIPTION, download_url = '%s/Notable-%s.tar.gz' % (PYPI, app.version), include_package_data = True, name = NAME, packages = ['notable'], scripts = ['scripts/notable'], url = URL, version = app.version )
Add user input to daemon
#!/usr/bin/env python from daemon import Daemon, SerialDispatcher from serial import Serial from threading import Thread import sys def callback(event): if event: print("EVENT: {0.house}{0.unit}: {0.command}".format(event)) def listen(daemon): house, unit, act = input().split() unit = int(unit) if act.upper() == "ON": daemon.on(house, unit) elif act.upper() == "OFF": daemon.off(house, unit) def main(args): serial_port = args[1] baud = 9600 s = Serial(serial_port, baud) dispatcher = SerialDispatcher(s) daemon = Daemon(dispatcher) daemon.subscribe(callback) daemon_thread = Thread(target=daemon.listen, name="daemon-listener") daemon_thread.start() user_thread = Thread(target=listen, args=(daemon,), name="user-listener") user_thread.start() daemon_thread.join() user_thread.join() s.close() if __name__ == "__main__": # TODO: Parse arguments for things main(sys.argv)
#!/usr/bin/env python from daemon import Daemon, SerialDispatcher from serial import Serial from threading import Thread import sys def callback(event): if event: print("EVENT: {0.house}{0.unit}: {0.command}".format(event)) def listen(daemon): house, unit, act = input().split() unit = int(unit) if act.upper() == "ON": daemon.on(house, unit) elif act.upper() == "OFF": daemon.off(house, unit) def main(args): serial_port = args[1] baud = 9600 s = Serial(serial_port, baud) dispatcher = SerialDispatcher(s) daemon = Daemon(dispatcher) daemon.subscribe(callback) daemon_thread = Thread(target=daemon.listen, name="daemon-listener") daemon_thread.start() daemon_thread.join() s.close() if __name__ == "__main__": # TODO: Parse arguments for things main(sys.argv)
Disable dark blue from being chosen by the worldist
var fs = require('fs'), _ = require('lodash'), gameConstants = require('../common/game-constants'); var WordList = function WordList(maxLength) { // Should be stored in a database instead. this.colors = ['blue', 'purple', 'green', 'yellow', 'red']; var that = this; //#GHETTOHACK. Should be in a database or at least read async. Redis maybe? var file = fs.readFileSync(__dirname + '/data/wordlist.txt', { encoding: 'utf8' }); this.words = file.split('\r\n'); this.words = this.words.filter(function(word) { return word.length <= maxLength; }); } WordList.prototype.getWords = function(n) { var words = _.sample(this.words, n); var wordList = words.map(function(word, index) { return { word: word, id: index, x: _.random(gameConstants.LEFT_WALL, gameConstants.WIDTH - gameConstants.RIGHT_WALL - word.length), color: _.sample(this.colors, 1)[0] }; }, this); return wordList; } module.exports = WordList;
var fs = require('fs'), _ = require('lodash'), gameConstants = require('../common/game-constants'); var WordList = function WordList(maxLength) { // Should be stored in a database instead. this.colors = ['blue', 'darkBlue', 'purple', 'green', 'yellow', 'red']; var that = this; //#GHETTOHACK. Should be in a database or at least read async. Redis maybe? var file = fs.readFileSync(__dirname + '/data/wordlist.txt', { encoding: 'utf8' }); this.words = file.split('\r\n'); this.words = this.words.filter(function(word) { return word.length <= maxLength; }); } WordList.prototype.getWords = function(n) { var words = _.sample(this.words, n); var wordList = words.map(function(word, index) { return { word: word, id: index, x: _.random(gameConstants.LEFT_WALL, gameConstants.WIDTH - gameConstants.RIGHT_WALL - word.length), color: _.sample(this.colors, 1)[0] }; }, this); return wordList; } module.exports = WordList;
Update Dotenv config to the new version
<?php declare(strict_types=1); /* * This file is part of gpupo/common * Created by Gilmar Pupo <contact@gpupo.com> * For the information of copyright and license you should read the file * LICENSE which is distributed with this source code. * Para a informação dos direitos autorais e de licença você deve ler o arquivo * LICENSE que é distribuído com este código-fonte. * Para obtener la información de los derechos de autor y la licencia debe leer * el archivo LICENSE que se distribuye con el código fuente. * For more information, see <https://opensource.gpupo.com/>. * */ use Symfony\Component\Dotenv\Dotenv; if (!class_exists('\Gpupo\Common\Console\Application')) { require __DIR__.'/../vendor/autoload.php'; } if (!class_exists(Dotenv::class)) { throw new RuntimeException('Please run "composer require symfony/dotenv" to load the ".env" files configuring the application.'); } // load all the .env files (new Dotenv(true))->loadEnv(dirname(__DIR__).'/.env');
<?php declare(strict_types=1); /* * This file is part of gpupo/common * Created by Gilmar Pupo <contact@gpupo.com> * For the information of copyright and license you should read the file * LICENSE which is distributed with this source code. * Para a informação dos direitos autorais e de licença você deve ler o arquivo * LICENSE que é distribuído com este código-fonte. * Para obtener la información de los derechos de autor y la licencia debe leer * el archivo LICENSE que se distribuye con el código fuente. * For more information, see <https://opensource.gpupo.com/>. * */ use Symfony\Component\Dotenv\Dotenv; if (!class_exists('\Gpupo\Common\Console\Application')) { require __DIR__.'/../vendor/autoload.php'; } if (!class_exists(Dotenv::class)) { throw new RuntimeException('Please run "composer require symfony/dotenv" to load the ".env" files configuring the application.'); } // load all the .env files (new Dotenv())->loadEnv(dirname(__DIR__).'/.env');
Remove wrong @since comment in docblock
<?php /** * SampleTask file * * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) * Copyright (c) Cake Software Foundation, Inc. (http://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. (http://cakefoundation.org) * @link http://cakephp.org CakePHP(tm) Project * @license http://www.opensource.org/licenses/mit-license.php MIT License */ namespace TestApp\Shell\Task; use Cake\Console\Shell; class SampleTask extends Shell { public function getOptionParser() { $parser = parent::getOptionParser(); $parser->addOption('sample', [ 'short' => 's', 'help' => 'This is a sample option for the sample task.', ]); return $parser; } }
<?php /** * SampleTask file * * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) * Copyright (c) Cake Software Foundation, Inc. (http://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. (http://cakefoundation.org) * @link http://cakephp.org CakePHP(tm) Project * @since 1.2.0 * @license http://www.opensource.org/licenses/mit-license.php MIT License */ namespace TestApp\Shell\Task; use Cake\Console\Shell; class SampleTask extends Shell { public function getOptionParser() { $parser = parent::getOptionParser(); $parser->addOption('sample', [ 'short' => 's', 'help' => 'This is a sample option for the sample task.', ]); return $parser; } }
Fix register and login y0
from grum import app, db from grum.models import User from flask import render_template, request, redirect @app.route("/", methods=['GET', 'POST']) def main(): if request.method == "POST": # Login verification code username = request.form['username'] password = request.form['password'] user = User.query.filter_by(username=username).first_or_404() if user.validate_password(password): return redirect("/mail") return render_template("index.html") @app.route("/register", methods=['GET', 'POST']) def register(): if request.method == "POST": username = request.form['username'] password = request.form['password'] confirm_password = request.form['confirm'] if password != confirm_password: return redirect("/register") new_user = User( username=username, password=password ) db.session.add(new_user) db.session.commit() return redirect("/mail") return render_template("register.html") @app.route("/mail") def mail(): return render_template('mail.html')
from grum import app, db from grum.models import User from flask import render_template, request @app.route("/") def main(): # # Login verification code # username = request.form('username') # password = request.form('password') # # user = User.query.filter_by(username=username).first_or_404() # if user.validate_password(password): # # Logged in # # Not Logged In return render_template("index.html") @app.route("/register", methods=['GET', 'POST']) def register(): if request.method == "POST": username = request.form('username') password = request.form('password') confirm_password = request.form('confirm') if password != confirm_password: return redirect("/register") new_user = User( username=username, password=password ) db.session.add(new_user) db.session.commit() return render_template("register.html") @app.route("/mail") def mail(): return render_template('mail.html')
Remove _name attribute on hr.employee
# -*- coding: utf-8 -*- # © 2011 Michael Telahun Makonnen <mmakonnen@gmail.com> # © 2016 OpenSynergy Indonesia # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from openerp import models, fields class HrEmployee(models.Model): _inherit = 'hr.employee' emergency_contact_ids = fields.Many2many( string='Emergency Contacts', comodel_name='res.partner', relation='rel_employee_emergency_contact', column1='employee_id', column2='partner_id', domain=[ ('is_company', '=', False), ('parent_id', '=', False), ] )
# -*- coding: utf-8 -*- # © 2011 Michael Telahun Makonnen <mmakonnen@gmail.com> # © 2016 OpenSynergy Indonesia # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from openerp import models, fields class HrEmployee(models.Model): _name = 'hr.employee' _inherit = 'hr.employee' emergency_contact_ids = fields.Many2many( string='Emergency Contacts', comodel_name='res.partner', relation='rel_employee_emergency_contact', column1='employee_id', column2='partner_id', domain=[ ('is_company', '=', False), ('parent_id', '=', False), ] )
Manage new Enum syntax in Ludwig
var _ = require('lodash'); var moment = require('moment'); var requestedVariables = require('../openfisca/mapping/common').requestedVariables; module.exports = function extractResults(openfiscaResults, date) { var period = moment(date).format('YYYY-MM'); var individuId = openfiscaResults.menages._.personne_de_reference[0]; var aideEntity = _.assign({}, openfiscaResults.familles._, openfiscaResults.individus[individuId]); return _.reduce(requestedVariables, function(result, aide, aideId) { if (aide.type == 'string') { return result; } var non_calculable = (aideEntity[aideId + '_non_calculable'] && aideEntity[aideId + '_non_calculable'][period]); if (non_calculable && non_calculable != 'calculable') { result[aideId] = non_calculable; return result; } result[aideId] = aideEntity[aideId] && aideEntity[aideId][period]; if (result[aideId] && ((! aide.type) || aide.type == 'float')) { result[aideId] = Number(result[aideId].toFixed(2)); } return result; }, {}); };
var _ = require('lodash'); var moment = require('moment'); var requestedVariables = require('../openfisca/mapping/common').requestedVariables; module.exports = function extractResults(openfiscaResults, date) { var period = moment(date).format('YYYY-MM'); var individuId = openfiscaResults.menages._.personne_de_reference[0]; var aideEntity = _.assign({}, openfiscaResults.familles._, openfiscaResults.individus[individuId]); return _.reduce(requestedVariables, function(result, aide, aideId) { if (aide.type == 'string') { return result; } var non_calculable = (aideEntity[aideId + '_non_calculable'] && aideEntity[aideId + '_non_calculable'][period]); if (non_calculable) { result[aideId] = non_calculable; return result; } result[aideId] = aideEntity[aideId] && aideEntity[aideId][period]; if (result[aideId] && ((! aide.type) || aide.type == 'float')) { result[aideId] = Number(result[aideId].toFixed(2)); } return result; }, {}); };
Remove mistakenly added testing line.
"use strict"; function Kablammo() { // When hit is to complement of nucleotide sequence (whether for query or // subject), we will show the HSPs relative to the coordinates of the // original (i.e., input or DB) sequence if this value is false, or relative // to the coordinates of its complement if this value is true. var use_complement_coords = false; this._aln_viewer = new AlignmentViewer(); this._aln_exporter = new AlignmentExporter(); this._grapher = new Grapher(this._aln_viewer, this._aln_exporter, use_complement_coords); this._parser = new BlastParser(use_complement_coords); this._loader = new BlastResultsLoader(this._parser); this._iface = new Interface(this._grapher, this._loader); this._img_exporter = new ImageExporter('#results-container', '.export-to-svg', '.export-to-png'); } function main() { new Kablammo(); } main();
"use strict"; function Kablammo() { // When hit is to complement of nucleotide sequence (whether for query or // subject), we will show the HSPs relative to the coordinates of the // original (i.e., input or DB) sequence if this value is false, or relative // to the coordinates of its complement if this value is true. var use_complement_coords = false; this._aln_viewer = new AlignmentViewer(); this._aln_exporter = new AlignmentExporter(); this._grapher = new Grapher(this._aln_viewer, this._aln_exporter, use_complement_coords); this._parser = new BlastParser(use_complement_coords); this._loader = new BlastResultsLoader(this._parser); this._iface = new Interface(this._grapher, this._loader); this._img_exporter = new ImageExporter('#results-container', '.export-to-svg', '.export-to-png'); $('.start-tour').click(); } function main() { new Kablammo(); } main();
Add another test method skeleton
<?php use Illuminate\Foundation\Testing\WithoutMiddleware; use Illuminate\Foundation\Testing\DatabaseMigrations; use Illuminate\Foundation\Testing\DatabaseTransactions; /* * Functional tests for the forgot password screen */ class ForgotPasswordFunctionalTest extends TestCase { /** * Checks that viewing the forgot password screen is not possible if logged in */ public function checkRedirectAndErrorIfLoggedIn() { } /** * Checks that the user is given an easy, explicit route back to the login page */ public function checkRememberedPasswordAfterAllLinkExists() { } /** * Checks that the submission of an empty email address results in an error */ public function testSubmitEmptyEmail() { } /** * Test that the submission of an invalid email results in an error * * Valid means "contains exactly one @ symbol, and at least one dot in the domain part" */ public function testInvalidEmail() { } /** * Test that the submission of a valid email results in a success message * * Note there is no distinction between addresses that exist and those that do not. * * In test mode, no actual email should be sent, though we cannot test for this. */ public function testValidEmail() { } }
<?php use Illuminate\Foundation\Testing\WithoutMiddleware; use Illuminate\Foundation\Testing\DatabaseMigrations; use Illuminate\Foundation\Testing\DatabaseTransactions; /* * Functional tests for the forgot password screen */ class ForgotPasswordFunctionalTest extends TestCase { /** * Checks that the user is given an easy, explicit route back to the login page */ public function checkRememberedPasswordAfterAll() { } /** * Checks that the submission of an empty email address results in an error */ public function testSubmitEmptyEmail() { } /** * Test that the submission of an invalid email results in an error * * Valid means "contains exactly one @ symbol, and at least one dot in the domain part" */ public function testInvalidEmail() { } /** * Test that the submission of a valid email results in a success message * * Note there is no distinction between addresses that exist and those that do not. * * In test mode, no actual email should be sent, though we cannot test for this. */ public function testValidEmail() { } }
Send name back on sucess
var pg = require( 'pg' ), db = require( './db' ); exports.add = function( req, res ) { var client = new pg.Client( db.conn ); client.connect(); var queryString = "INSERT INTO neighborhood_collection ( name, uuid, confidence, comments, geom ) VALUES( "; queryString += "'" + req.body.name + "', "; queryString += "'" + req.body.uuid + "', "; queryString += req.body.confidence + ", "; queryString += req.body.comments ? "'" + req.body.comments + "', " : "NULL, "; queryString += "ST_GeomFromGeoJSON( '" + req.body.geojson + "' ) )" console.log( queryString ); var query = client.query( queryString ); query.on( 'end', function() { res.send( req.body.name ); client.end(); }); }
var pg = require( 'pg' ), db = require( './db' ); exports.add = function( req, res ) { var client = new pg.Client( db.conn ); client.connect(); var queryString = "INSERT INTO neighborhood_collection ( name, uuid, confidence, comments, geom ) VALUES( "; queryString += "'" + req.body.name + "', "; queryString += "'" + req.body.uuid + "', "; queryString += req.body.confidence + ", "; queryString += req.body.comments ? "'" + req.body.comments + "', " : "NULL, "; queryString += "ST_GeomFromGeoJSON( '" + req.body.geojson + "' ) )" console.log( queryString ); var query = client.query( queryString ); query.on( 'end', function() { res.send( "OK" ); client.end(); }); }
Implement tokenization in preprocess function
from nltk.tokenize import word_tokenize, sent_tokenize import getopt import sys import os import io def load_data(dir_doc): docs = {} for dirpath, dirnames, filenames in os.walk(dir_doc): for name in filenames: file = os.path.join(dirpath, name) with io.open(file, 'r+') as f: docs[name] = f.read() return docs def preprocess(docs): processed_docs = {} for doc_id, doc in docs.items(): processed_docs[doc_id] = word_tokenize(doc) return processed_docs def usage(): print("usage: " + sys.argv[0] + " -i directory-of-documents -d dictionary-file -p postings-file") if __name__ == '__main__': dir_doc = dict_file = postings_file = None try: opts, args = getopt.getopt(sys.argv[1:], 'i:d:p:') except getopt.GetoptError as err: usage() sys.exit(2) for o, a in opts: if o == '-i': dir_doc = a elif o == '-d': dict_file = a elif o == '-p': postings_file = a else: assert False, "unhandled option" if dir_doc == None or dict_file == None or postings_file == None: usage() sys.exit(2) docs = load_data(dir_doc) docs = preprocess(docs)
from nltk.tokenize import word_tokenize, sent_tokenize import getopt import sys import os import io def load_data(dir_doc): docs = {} for dirpath, dirnames, filenames in os.walk(dir_doc): for name in filenames: file = os.path.join(dirpath, name) with io.open(file, 'r+') as f: docs[name] = f.read() return docs def usage(): print("usage: " + sys.argv[0] + " -i directory-of-documents -d dictionary-file -p postings-file") if __name__ == '__main__': dir_doc = dict_file = postings_file = None try: opts, args = getopt.getopt(sys.argv[1:], 'i:d:p:') except getopt.GetoptError as err: usage() sys.exit(2) for o, a in opts: if o == '-i': dir_doc = a elif o == '-d': dict_file = a elif o == '-p': postings_file = a else: assert False, "unhandled option" if dir_doc == None or dict_file == None or postings_file == None: usage() sys.exit(2) docs = load_data(dir_doc)
Exclude any future tests sub-packages from build.
from setuptools import setup, find_packages with open('README.rst') as f: long_description = f.read() setup( name='ocdsmerge', version='0.5.6', author='Open Contracting Partnership', author_email='data@open-contracting.org', url='https://github.com/open-contracting/ocds-merge', description='A library and reference implementation for merging OCDS releases', license='BSD', packages=find_packages(exclude=['tests', 'tests.*']), long_description=long_description, install_requires=[ 'jsonref', 'requests', ], extras_require={ 'test': [ 'coveralls', 'jsonschema', 'pytest', 'pytest-cov', 'pytest-vcr', ], }, classifiers=[ 'License :: OSI Approved :: BSD License', 'Programming Language :: Python :: 3.6', ], )
from setuptools import setup, find_packages with open('README.rst') as f: long_description = f.read() setup( name='ocdsmerge', version='0.5.6', author='Open Contracting Partnership', author_email='data@open-contracting.org', url='https://github.com/open-contracting/ocds-merge', description='A library and reference implementation for merging OCDS releases', license='BSD', packages=find_packages(exclude=['tests']), long_description=long_description, install_requires=[ 'jsonref', 'requests', ], extras_require={ 'test': [ 'coveralls', 'jsonschema', 'pytest', 'pytest-cov', 'pytest-vcr', ], }, classifiers=[ 'License :: OSI Approved :: BSD License', 'Programming Language :: Python :: 3.6', ], )
Add DeleteObject() method to lib/objectserver.FullObjectServer interface.
package objectserver import ( "github.com/Symantec/Dominator/lib/hash" "io" ) type FullObjectServer interface { DeleteObject(hashVal hash.Hash) error ObjectServer ListObjectSizes() map[hash.Hash]uint64 ListObjects() []hash.Hash NumObjects() uint64 } type ObjectGetter interface { GetObject(hashVal hash.Hash) (uint64, io.ReadCloser, error) } type ObjectsReader interface { Close() error NextObject() (uint64, io.ReadCloser, error) } type ObjectServer interface { AddObject(reader io.Reader, length uint64, expectedHash *hash.Hash) ( hash.Hash, bool, error) CheckObjects(hashes []hash.Hash) ([]uint64, error) ObjectGetter GetObjects(hashes []hash.Hash) (ObjectsReader, error) } func GetObject(objSrv ObjectServer, hashVal hash.Hash) ( uint64, io.ReadCloser, error) { return getObject(objSrv, hashVal) }
package objectserver import ( "github.com/Symantec/Dominator/lib/hash" "io" ) type FullObjectServer interface { ObjectServer ListObjectSizes() map[hash.Hash]uint64 ListObjects() []hash.Hash NumObjects() uint64 } type ObjectGetter interface { GetObject(hashVal hash.Hash) (uint64, io.ReadCloser, error) } type ObjectsReader interface { Close() error NextObject() (uint64, io.ReadCloser, error) } type ObjectServer interface { AddObject(reader io.Reader, length uint64, expectedHash *hash.Hash) ( hash.Hash, bool, error) CheckObjects(hashes []hash.Hash) ([]uint64, error) ObjectGetter GetObjects(hashes []hash.Hash) (ObjectsReader, error) } func GetObject(objSrv ObjectServer, hashVal hash.Hash) ( uint64, io.ReadCloser, error) { return getObject(objSrv, hashVal) }
Remove atomic transaction from command to reduce memory usage
import logging from django.core.management.base import BaseCommand from django.db import transaction from document.models import Document from document.models import Submitter logger = logging.getLogger(__name__) class Command(BaseCommand): def handle(self, *args, **options): self.do() # @transaction.atomic def do(self): submitters = Submitter.objects.all() documents = Document.objects.all() counter = 1 n_docs = documents.count() print(n_docs) for document in documents: print('document ' + str(counter) + '/' + str(n_docs)) doc_submitters = submitters.filter(document=document) person_ids = [] for doc_sub in doc_submitters: if doc_sub.person.id in person_ids: doc_sub.delete() else: person_ids.append(doc_sub.person.id) counter += 1
import logging from django.core.management.base import BaseCommand from django.db import transaction from document.models import Document from document.models import Submitter logger = logging.getLogger(__name__) class Command(BaseCommand): def handle(self, *args, **options): self.do() @transaction.atomic def do(self): submitters = Submitter.objects.all() documents = Document.objects.all() counter = 1 n_docs = documents.count() print(n_docs) for document in documents: print('document ' + str(counter) + '/' + str(n_docs)) doc_submitters = submitters.filter(document=document) person_ids = [] for doc_sub in doc_submitters: if doc_sub.person.id in person_ids: doc_sub.delete() else: person_ids.append(doc_sub.person.id) counter += 1
Change the url builder to handle integrations.
/** * @constructor */ webfont.FontApiUrlBuilder = function(apiUrl) { if (apiUrl) { this.apiUrl_ = apiUrl; } else { var protocol = 'https:' == window.location.protocol ? 'https:' : 'http:'; this.apiUrl_ = protocol + webfont.FontApiUrlBuilder.DEFAULT_API_URL; } this.fontFamilies_ = null; }; webfont.FontApiUrlBuilder.DEFAULT_API_URL = '//fonts.googleapis.com/css'; webfont.FontApiUrlBuilder.prototype.setFontFamilies = function(fontFamilies) { // maybe clone? this.fontFamilies_ = fontFamilies; }; webfont.FontApiUrlBuilder.prototype.webSafe = function(string) { return string.replace(/ /g, '+'); }; webfont.FontApiUrlBuilder.prototype.build = function() { if (!this.fontFamilies_) { throw new Error('No fonts to load !'); } if (this.apiUrl_.indexOf("kit=") != -1) { return this.apiUrl_; } var length = this.fontFamilies_.length; var sb = []; for (var i = 0; i < length; i++) { sb.push(this.webSafe(this.fontFamilies_[i])); } var url = this.apiUrl_ + '?family=' + sb.join('%7C'); // '|' escaped. return url; };
/** * @constructor */ webfont.FontApiUrlBuilder = function(apiUrl) { if (apiUrl) { this.apiUrl_ = apiUrl; } else { var protocol = 'https:' == window.location.protocol ? 'https:' : 'http:'; this.apiUrl_ = protocol + webfont.FontApiUrlBuilder.DEFAULT_API_URL; } this.fontFamilies_ = null; }; webfont.FontApiUrlBuilder.DEFAULT_API_URL = '//fonts.googleapis.com/css'; webfont.FontApiUrlBuilder.prototype.setFontFamilies = function(fontFamilies) { // maybe clone? this.fontFamilies_ = fontFamilies; }; webfont.FontApiUrlBuilder.prototype.webSafe = function(string) { return string.replace(/ /g, '+'); }; webfont.FontApiUrlBuilder.prototype.build = function() { if (!this.fontFamilies_) { throw new Error('No fonts to load !'); } var length = this.fontFamilies_.length; var sb = []; for (var i = 0; i < length; i++) { sb.push(this.webSafe(this.fontFamilies_[i])); } var url = this.apiUrl_ + '?family=' + sb.join('%7C'); // '|' escaped. return url; };
Print stylesheet must be separate, and is not currently available anyway
<?php /** * Groups configuration for default Minify implementation * @package Minify */ /** * You may wish to use the Minify URI Builder app to suggest * changes. http://yourdomain/min/builder/ **/ return array( // 'js' => array('//js/file1.js', '//js/file2.js'), // 'css' => array('//css/file1.css', '//css/file2.css'), // custom source example /*'js2' => array( dirname(__FILE__) . '/../min_unit_tests/_test_files/js/before.js', // do NOT process this file new Minify_Source(array( 'filepath' => dirname(__FILE__) . '/../min_unit_tests/_test_files/js/before.js', 'minifier' => create_function('$a', 'return $a;') )) ),//*/ /*'js3' => array( dirname(__FILE__) . '/../min_unit_tests/_test_files/js/before.js', // do NOT process this file new Minify_Source(array( 'filepath' => dirname(__FILE__) . '/../min_unit_tests/_test_files/js/before.js', 'minifier' => array('Minify_Packer', 'minify') )) ),//*/ 'js' => array('//js/main.js'), 'css' => array('//css/reset.css', '//css/main.css'), );
<?php /** * Groups configuration for default Minify implementation * @package Minify */ /** * You may wish to use the Minify URI Builder app to suggest * changes. http://yourdomain/min/builder/ **/ return array( // 'js' => array('//js/file1.js', '//js/file2.js'), // 'css' => array('//css/file1.css', '//css/file2.css'), // custom source example /*'js2' => array( dirname(__FILE__) . '/../min_unit_tests/_test_files/js/before.js', // do NOT process this file new Minify_Source(array( 'filepath' => dirname(__FILE__) . '/../min_unit_tests/_test_files/js/before.js', 'minifier' => create_function('$a', 'return $a;') )) ),//*/ /*'js3' => array( dirname(__FILE__) . '/../min_unit_tests/_test_files/js/before.js', // do NOT process this file new Minify_Source(array( 'filepath' => dirname(__FILE__) . '/../min_unit_tests/_test_files/js/before.js', 'minifier' => array('Minify_Packer', 'minify') )) ),//*/ 'js' => array('//js/main.js'), 'css' => array('//css/reset.css', '//css/main.css', '//css/print.css'), );
Create default gulp task, that depends on build
var gulp = require('gulp'), sass = require('gulp-sass'), cssmin = require('gulp-minify-css'), prefix = require('gulp-autoprefixer'), rename = require('gulp-rename'), header = require('gulp-header'), pkg = require('./package.json'), banner = [ '/*!', ' <%= pkg.name %> v<%= pkg.version %>', ' Written by <%= pkg.author.name %>', ' <%= pkg.author.url %>', ' <%= pkg.author.email %>', ' License: <%= pkg.license %>', '*/','' ].join('\n'); gulp.task('build', function() { return gulp.src('src/*.scss') .pipe( sass() ) .pipe( prefix('> 1%', 'last 2 versions', 'Firefox ESR', 'Opera 12.1') ) .pipe( header(banner, {pkg: pkg}) ) .pipe( gulp.dest('dist/') ) .pipe( cssmin() ) .pipe( rename({suffix: '.min'}) ) .pipe( gulp.dest('dist/') ); }); gulp.task('default',['build']);
var gulp = require('gulp'), sass = require('gulp-sass'), cssmin = require('gulp-minify-css'), prefix = require('gulp-autoprefixer'), rename = require('gulp-rename'), header = require('gulp-header'), pkg = require('./package.json'), banner = [ '/*!', ' <%= pkg.name %> v<%= pkg.version %>', ' Written by <%= pkg.author.name %>', ' <%= pkg.author.url %>', ' <%= pkg.author.email %>', ' License: <%= pkg.license %>', '*/','' ].join('\n'); gulp.task('build', function() { return gulp.src('src/*.scss') .pipe( sass() ) .pipe( prefix('> 1%', 'last 2 versions', 'Firefox ESR', 'Opera 12.1') ) .pipe( header(banner, {pkg: pkg}) ) .pipe( gulp.dest('dist/') ) .pipe( cssmin() ) .pipe( rename({suffix: '.min'}) ) .pipe( gulp.dest('dist/') ); });
Add configBasedir to properly look up the plugins
var _ = require('lodash'); var path = require('path'); var stylelint = require('stylelint'); var STYLELINT_CONFIG = require('./config/stylelint'); var glob = require('glob'); var ruleUtils = require('./rule_utils'); var customRules = {}; var runLinter = function(contents, file, context) { var customRules = context.customRules || {}; _.merge(stylelint.rules, customRules); var config = context.lintConfig; var configs = [{}, STYLELINT_CONFIG]; if (_.isObject(config)) { configs.push(config); } config = _.merge.apply(_, configs); return stylelint.lint( { code: contents, codeFileName: file, config: config, configBasedir: path.resolve(__dirname, '..'), formatter: 'json', syntax: 'scss' } ); }; var globOptions = { cwd: __dirname }; module.exports = function(contents, file, context) { context.customRules = customRules; glob.sync( './lint_css_rules/*.js', globOptions ).forEach( function(item, index) { var id = ruleUtils.getRuleId(item); customRules[id] = require(item); } ); return runLinter(contents, file, context); }; module.exports.stylelint = stylelint; module.exports.linter = stylelint.linter; module.exports.runLinter = runLinter;
var _ = require('lodash'); var stylelint = require('stylelint'); var STYLELINT_CONFIG = require('./config/stylelint'); var glob = require('glob'); var ruleUtils = require('./rule_utils'); var customRules = {}; var runLinter = function(contents, file, context) { var customRules = context.customRules || {}; _.merge(stylelint.rules, customRules); var config = context.lintConfig; var configs = [{}, STYLELINT_CONFIG]; if (_.isObject(config)) { configs.push(config); } config = _.merge.apply(_, configs); return stylelint.lint( { code: contents, codeFileName: file, config: config, formatter: 'json', syntax: 'scss' } ); }; var globOptions = { cwd: __dirname }; module.exports = function(contents, file, context) { context.customRules = customRules; glob.sync( './lint_css_rules/*.js', globOptions ).forEach( function(item, index) { var id = ruleUtils.getRuleId(item); customRules[id] = require(item); } ); return runLinter(contents, file, context); }; module.exports.stylelint = stylelint; module.exports.linter = stylelint.linter; module.exports.runLinter = runLinter;
Add .md and .txt files to package
#!/usr/bin/env python import collections from setuptools import setup from pip.req import parse_requirements dependency_links = [] install_requires = [] ReqOpts = collections.namedtuple('ReqOpts', ['skip_requirements_regex', 'default_vcs']) opts = ReqOpts(None, 'git') for ir in parse_requirements("requirements.txt", options=opts): if ir is not None: if ir.url is not None: dependency_links.append(str(ir.url)) if ir.req is not None: install_requires.append(str(ir.req)) setup( name='vertica-python', version='0.1', description='A native Python client for the Vertica database.', author='Justin Berka', author_email='justin@uber.com', url='https://github.com/uber/vertica-python/', keywords="database vertica", packages=['vertica_python'], package_data={ '': ['*.txt', '*.md'], }, license="MIT", install_requires=install_requires, dependency_links=dependency_links, classifiers = [ "Development Status :: 3 - Alpha", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Programming Language :: Python", "Topic :: Database", "Topic :: Database :: Database Engines/Servers", "Operating System :: OS Independent" ] )
#!/usr/bin/env python import collections from setuptools import setup from pip.req import parse_requirements dependency_links = [] install_requires = [] ReqOpts = collections.namedtuple('ReqOpts', ['skip_requirements_regex', 'default_vcs']) opts = ReqOpts(None, 'git') for ir in parse_requirements("requirements.txt", options=opts): if ir is not None: if ir.url is not None: dependency_links.append(str(ir.url)) if ir.req is not None: install_requires.append(str(ir.req)) setup( name='vertica-python', version='0.1', description='A native Python client for the Vertica database.', author='Justin Berka', author_email='justin@uber.com', url='https://github.com/uber/vertica-python/', keywords="database vertica", packages=['vertica_python'], license="MIT", install_requires=install_requires, dependency_links=dependency_links, classifiers = [ "Development Status :: 3 - Alpha", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Programming Language :: Python", "Topic :: Database", "Topic :: Database :: Database Engines/Servers", "Operating System :: OS Independent" ] )
Stop directly importing non-module symbol
from chainer.functions.activation import elu def selu(x, alpha=1.6732632423543772848170429916717, scale=1.0507009873554804934193349852946): """Scaled Exponential Linear Unit function. For parameters :math:`\\alpha` and :math:`\\lambda`, it is expressed as .. math:: f(x) = \\lambda \\left \\{ \\begin{array}{ll} x & {\\rm if}~ x \\ge 0 \\\\ \\alpha (\\exp(x) - 1) & {\\rm if}~ x < 0, \\end{array} \\right. See: https://arxiv.org/abs/1706.02515 Args: x (:class:`~chainer.Variable` or :class:`numpy.ndarray` or \ :class:`cupy.ndarray`): Input variable. A :math:`(s_1, s_2, ..., s_N)`-shaped float array. alpha (float): Parameter :math:`\\alpha`. scale (float): Parameter :math:`\\lambda`. Returns: ~chainer.Variable: Output variable. A :math:`(s_1, s_2, ..., s_N)`-shaped float array. """ return scale * elu.elu(x, alpha=alpha)
from chainer.functions.activation.elu import elu def selu(x, alpha=1.6732632423543772848170429916717, scale=1.0507009873554804934193349852946): """Scaled Exponential Linear Unit function. For parameters :math:`\\alpha` and :math:`\\lambda`, it is expressed as .. math:: f(x) = \\lambda \\left \\{ \\begin{array}{ll} x & {\\rm if}~ x \\ge 0 \\\\ \\alpha (\\exp(x) - 1) & {\\rm if}~ x < 0, \\end{array} \\right. See: https://arxiv.org/abs/1706.02515 Args: x (:class:`~chainer.Variable` or :class:`numpy.ndarray` or \ :class:`cupy.ndarray`): Input variable. A :math:`(s_1, s_2, ..., s_N)`-shaped float array. alpha (float): Parameter :math:`\\alpha`. scale (float): Parameter :math:`\\lambda`. Returns: ~chainer.Variable: Output variable. A :math:`(s_1, s_2, ..., s_N)`-shaped float array. """ return scale * elu(x, alpha=alpha)
Add logging of the url.
package musicbrainz import ( "encoding/xml" "io/ioutil" "log" "net/http" "net/url" ) func MakeQuery(url string) []byte { log.Printf("Getting URL %s", url) res, err := http.Get(url) if err != nil { log.Fatal(err) } bytes, err := ioutil.ReadAll(res.Body) res.Body.Close() if err != nil { log.Fatal(err) } return bytes } func SearchArtist(artist string) ArtistResult { result := ArtistResult{} bytes := MakeQuery("http://musicbrainz.org/ws/2/artist/?limit=10&query=artist:" + url.QueryEscape(artist)) xml.Unmarshal(bytes, &result) return result } func GetReleases(artistId string) ReleaseResult { result := ReleaseResult{} bytes := MakeQuery("http://musicbrainz.org/ws/2/release?artist=" + artistId) xml.Unmarshal(bytes, result) return result }
package musicbrainz import ( "encoding/xml" "io/ioutil" "log" "net/http" "net/url" ) func MakeQuery(url string) []byte { res, err := http.Get(url) if err != nil { log.Fatal(err) } bytes, err := ioutil.ReadAll(res.Body) res.Body.Close() if err != nil { log.Fatal(err) } return bytes } func SearchArtist(artist string) ArtistResult { result := ArtistResult{} bytes := MakeQuery("http://musicbrainz.org/ws/2/artist/?limit=10&query=artist:" + url.QueryEscape(artist)) xml.Unmarshal(bytes, &result) return result } func GetReleases(artistId string) ReleaseResult { result := ReleaseResult{} bytes := MakeQuery("http://musicbrainz.org/ws/2/release?artist=" + artistId) xml.Unmarshal(bytes, result) return result }
[UserMilestone] Use PHP 7.1 type declarations
<?php /** * @author Pierre-Henry Soria <hi@ph7.me> * @copyright (c) 2018-2022, Pierre-Henry Soria. All Rights Reserved. * @license MIT License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory. * @package PH7 / App / System / Core / Class */ declare(strict_types=1); namespace PH7; class UserMilestoneCore { public const MILLENARIAN = 1000; private const NUMBER_USERS = [ 100, 500, 1000, 2500, 5000, 7500, 10000, 25000, 50000, 100000, 250000, 500000, 1000000 // Congrats! ]; private UserCoreModel $oUserModel; public function __construct(UserCoreModel $oUserModel) { $this->oUserModel = $oUserModel; } public function isTotalUserReached(): bool { return in_array( $this->oUserModel->total(), self::NUMBER_USERS, true ); } }
<?php /** * @author Pierre-Henry Soria <hi@ph7.me> * @copyright (c) 2018-2019, Pierre-Henry Soria. All Rights Reserved. * @license MIT License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory. * @package PH7 / App / System / Core / Class */ namespace PH7; class UserMilestoneCore { const MILLENARIAN = 1000; const NUMBER_USERS = [ 100, 500, 1000, 2500, 5000, 7500, 10000, 25000, 50000, 100000, 250000, 500000, 1000000 // Congrats! ]; /** @var UserCoreModel */ private $oUserModel; public function __construct(UserCoreModel $oUserModel) { $this->oUserModel = $oUserModel; } /** * @return bool */ public function isTotalUserReached() { return in_array( $this->oUserModel->total(), self::NUMBER_USERS, true ); } }
Add arrival time and update constructor.
package cloudSimulator.dto; import org.springframework.data.annotation.Id; public class RequestDetails { @Id private String id; private long requestId; private double requestArrivalTime; private double responseTime; public RequestDetails() { } public RequestDetails(long requestId, double requestArrivalTime) { this.requestId = requestId; this.requestArrivalTime = requestArrivalTime; } public RequestDetails(long requestId, double requestArrivalTime, double responseTime) { this.requestId = requestId; this.requestArrivalTime = requestArrivalTime; this.responseTime = responseTime; } public String getId() { return id; } public void setId(String id) { this.id = id; } public long getRequestId() { return requestId; } public void setRequestId(long requestId) { this.requestId = requestId; } public double getRequestArrivalTime() { return requestArrivalTime; } public void setRequestArrivalTime(double requestArrivalTime) { this.requestArrivalTime = requestArrivalTime; } public double getResponseTime() { return responseTime; } public void setResponseTime(double responseTime) { this.responseTime = responseTime; } }
package cloudSimulator.dto; import org.springframework.data.annotation.Id; public class RequestDetails { @Id private String id; private long requestId; private double responseTime; public RequestDetails() { } public RequestDetails(long requestId, double responseTime) { this.requestId = requestId; this.responseTime = responseTime; } public String getId() { return id; } public void setId(String id) { this.id = id; } public long getRequestId() { return requestId; } public void setRequestId(long requestId) { this.requestId = requestId; } public double getResponseTime() { return responseTime; } public void setResponseTime(double responseTime) { this.responseTime = responseTime; } }
Update redirect after new lead created
import ApiService from '../../../services/Api' const addHousehold = (household) => { return { type: 'ADD_HOUSEHOLD_SUCCESS', household } } export const convertLead = (id, history) => { return dispatch => { return ApiService.post(`/households/${id}/convert`) .then(client => { console.log(client) dispatch(convertLeadComplete(client)) history.push(`/households/${client.id}`) }) } } export const fetchHouseholdsComplete = households => { return { type: 'FETCH_HOUSEHOLDS_SUCCESS', households } } const convertLeadComplete = (client) => { return { type: 'CONVERT_LEAD_COMPLETE', client } } export const createHousehold = (household, history) => { return dispatch => { return ApiService.post(`/households`, household) .then(data => { dispatch(addHousehold(data)) history.replace('/households/leads') }) } } export const fetchHouseholds = () => { return dispatch => { return ApiService.get(`/households`) .then(data => { dispatch(fetchHouseholdsComplete(data)) }) } }
import ApiService from '../../../services/Api' const addHousehold = (household) => { return { type: 'ADD_HOUSEHOLD_SUCCESS', household } } export const convertLead = (id, history) => { return dispatch => { return ApiService.post(`/households/${id}/convert`) .then(client => { console.log(client) dispatch(convertLeadComplete(client)) history.push(`/households/${client.id}`) }) } } export const fetchHouseholdsComplete = households => { return { type: 'FETCH_HOUSEHOLDS_SUCCESS', households } } const convertLeadComplete = (client) => { return { type: 'CONVERT_LEAD_COMPLETE', client } } export const createHousehold = (household, history) => { return dispatch => { return ApiService.post(`/households`, household) .then(data => { dispatch(addHousehold(data)) history.replace('/leads') }) } } export const fetchHouseholds = () => { return dispatch => { return ApiService.get(`/households`) .then(data => { dispatch(fetchHouseholdsComplete(data)) }) } }
Move HTTP POST to service
angular .module('app', [ ]) .controller('ChatBoxController', ['services', function(services) { const chat = this; chat.msgs = ['Welcome to Chat Bot!']; chat.submitMsg = function() { chat.msgs.push(chat.msg); services.postMsg(); } }]) .service('services', function($http) { const services = this; services.postMsg = function() { $http.post('/users', {}) .then(function(data) { console.log('success with post') }); } }) .directive('chatBox', function() { return { template: ` <div class="messages"> <div ng-repeat="msg in chatBox.msgs track by $index"> {{msg}} </div> </div> <form ng-submit="chatBox.submitMsg()" > <input class="user-input" ng-model="chatBox.msg" type="text"> </form> ` } })
angular .module('app', [ ]) .controller('ChatBoxController', ['$http', function($http) { const chat = this; chat.msgs = ['Welcome to Chat Bot!']; chat.submitMsg = function() { chat.msgs.push(chat.msg); $http.post('/users', { }) .then(function(data) { console.log('success with post') }); } }]) .directive('chatBox', function() { return { template: ` <div class="messages"> <div ng-repeat="msg in chatBox.msgs track by $index"> {{msg}} </div> </div> <form ng-submit="chatBox.submitMsg()" > <input class="user-input" ng-model="chatBox.msg" type="text"> </form> ` } })
Reset row number after deleting all responses.
package com.openxc.openxcdiagnostic.diagnostic; import java.util.ArrayList; import java.util.List; import android.widget.LinearLayout; import com.openxc.messages.DiagnosticRequest; import com.openxc.messages.DiagnosticResponse; import com.openxc.openxcdiagnostic.R; public class DiagnosticOutputTable { private DiagnosticActivity mContext; private List<DiagnosticOutputRow> rows = new ArrayList<>(); private LinearLayout mView; private int rowNumber = 1; public DiagnosticOutputTable(DiagnosticActivity context) { mContext = context; mView = (LinearLayout) context.findViewById(R.id.outputRows); } public void addRow(DiagnosticRequest req, DiagnosticResponse resp) { DiagnosticOutputRow row = new DiagnosticOutputRow(mContext, this, req, resp, rowNumber++); rows.add(0, row); mView.addView(row.getView(), 0); } public void removeRow(DiagnosticOutputRow row) { mView.removeView(row.getView()); rows.remove(row); } public void deleteAllRows() { mView.removeAllViews(); rows.clear(); resetRowCounter(); } private void resetRowCounter() { rowNumber = 1; } }
package com.openxc.openxcdiagnostic.diagnostic; import java.util.ArrayList; import java.util.List; import android.widget.LinearLayout; import com.openxc.messages.DiagnosticRequest; import com.openxc.messages.DiagnosticResponse; import com.openxc.openxcdiagnostic.R; public class DiagnosticOutputTable { private DiagnosticActivity mContext; private List<DiagnosticOutputRow> rows = new ArrayList<>(); private LinearLayout mView; private int rowNumber = 1; public DiagnosticOutputTable(DiagnosticActivity context) { mContext = context; mView = (LinearLayout) context.findViewById(R.id.outputRows); } public void addRow(DiagnosticRequest req, DiagnosticResponse resp) { DiagnosticOutputRow row = new DiagnosticOutputRow(mContext, this, req, resp, rowNumber++); rows.add(0, row); mView.addView(row.getView(), 0); } public void removeRow(DiagnosticOutputRow row) { mView.removeView(row.getView()); rows.remove(row); } public void deleteAllRows() { mView.removeAllViews(); rows.clear(); } }
Update no longer takes an argument See the docs: http://bmi-python.readthedocs.io.
#! /usr/bin/env python import sys import subprocess class BmiIlamb(object): _command = 'run_ilamb' _args = None _env = None def __init__(self): self._time = self.get_start_time() @property def args(self): return [self._command] + (self._args or []) def get_component_name(self): return 'ILAMB' def initialize(self, filename): self._args = [filename or 'ILAMB_PARA_SETUP'] def update(self): subprocess.check_call(self.args, shell=False, env=self._env) self._time = self.get_end_time() def update_until(self, time): self.update(time) def finalize(self): pass def get_input_var_names(self): return () def get_output_var_names(self): return () def get_start_time(self): return 0.0 def get_end_time(self): return 1.0 def get_current_time(self): return self._time
#! /usr/bin/env python import sys import subprocess class BmiIlamb(object): _command = 'run_ilamb' _args = None _env = None def __init__(self): self._time = self.get_start_time() @property def args(self): return [self._command] + (self._args or []) def get_component_name(self): return 'ILAMB' def initialize(self, filename): self._args = [filename or 'ILAMB_PARA_SETUP'] def update(self, time): subprocess.check_call(self.args, shell=False, env=self._env) self._time = self.get_end_time() def update_until(self, time): self.update(time) def finalize(self): pass def get_input_var_names(self): return () def get_output_var_names(self): return () def get_start_time(self): return 0.0 def get_end_time(self): return 1.0 def get_current_time(self): return self._time
Add newline before custom error header
"""Base error used to create custom errors for loaders.""" ERROR_TITLE_TEMPLATE = "\n****************************ERROR****************************\n" ERROR_FILENAME_TEMPLATE = "File: {filename}\n" ERROR_REFERENCE_TEMPLATE = "Referenced in: {reference}\n" ERROR_SUGGESTIONS_TEMPLATE = """ - Did you spell the name of the file correctly? - Does the file exist? - Is the file saved in the correct directory? """ class Error(Exception): """Base class for Errors. (Exceptions from external sources such as inputs). """ def __init__(self): """Create the base class for errors.""" self.base_message = ERROR_TITLE_TEMPLATE + ERROR_FILENAME_TEMPLATE self.reference_message = ERROR_REFERENCE_TEMPLATE self.missing_file_suggestions = ERROR_SUGGESTIONS_TEMPLATE
"""Base error used to create custom errors for loaders.""" ERROR_TITLE_TEMPLATE = "****************************ERROR****************************\n" ERROR_FILENAME_TEMPLATE = "File: {filename}\n" ERROR_REFERENCE_TEMPLATE = "Referenced in: {reference}\n" ERROR_SUGGESTIONS_TEMPLATE = """ - Did you spell the name of the file correctly? - Does the file exist? - Is the file saved in the correct directory? """ class Error(Exception): """Base class for Errors. (Exceptions from external sources such as inputs). """ def __init__(self): """Create the base class for errors.""" self.base_message = ERROR_TITLE_TEMPLATE + ERROR_FILENAME_TEMPLATE self.reference_message = ERROR_REFERENCE_TEMPLATE self.missing_file_suggestions = ERROR_SUGGESTIONS_TEMPLATE
Revert "Throw FilterException instead of ApplicationException when allocated sequence counter is starved" This reverts commit 82c7964ae1abb805a63aeed677afa2979f573137.
package org.bricolages.streaming.filter; import org.bricolages.streaming.ApplicationError; import org.bricolages.streaming.SequencialNumberRepository; import lombok.*; class SequenceOp extends SingleColumnOp { static final void register(OpBuilder builder) { builder.registerOperator("sequence", (def) -> new SequenceOp(def, builder.sequencialNumberRepository) ); } long currentValue; long upperValue; SequenceOp(OperatorDefinition def) { super(def); } SequenceOp(OperatorDefinition def, SequencialNumberRepository repo) { this(def); val seq = repo.allocate(); this.currentValue = seq.getLastValue(); this.upperValue = seq.getNextValue(); } private long getNextValue() { currentValue ++; if (currentValue > upperValue) { throw new ApplicationError("sequence number is starved"); } return currentValue; } @Override public Object applyValue(Object value, Record record) throws FilterException { return getNextValue(); } }
package org.bricolages.streaming.filter; import org.bricolages.streaming.ApplicationError; import org.bricolages.streaming.SequencialNumberRepository; import lombok.*; class SequenceOp extends SingleColumnOp { static final void register(OpBuilder builder) { builder.registerOperator("sequence", (def) -> new SequenceOp(def, builder.sequencialNumberRepository) ); } long currentValue; long upperValue; SequenceOp(OperatorDefinition def) { super(def); } SequenceOp(OperatorDefinition def, SequencialNumberRepository repo) { this(def); val seq = repo.allocate(); this.currentValue = seq.getLastValue(); this.upperValue = seq.getNextValue(); } private long getNextValue() throws FilterException { currentValue ++; if (currentValue > upperValue) { throw new FilterException("sequence number is starved"); } return currentValue; } @Override public Object applyValue(Object value, Record record) throws FilterException { return getNextValue(); } }
Change date to unix timestamp
export class Notification { /** * @typedef NotificationData * @property {boolean} [read] * @property {string} title * @property {string} message * @property {('basic'|'sms')} [type='basic'] * @property {number} [date] * @property {object} [metadata] */ /** * * @param {NotificationData} data */ constructor(data) { this.read = 'read' in data ? data.read : false; this.title = data.title; this.message = data.message; this.date = 'date' in data ? data.date : null; this.metadata = 'metadata' in data ? data.metadata : ''; this.id = this.title + this.message + this.date + JSON.stringify(this.metadata); } /** * Converts the notification to a JSON object * @return {object} */ toJSON() { return { read: this.read, title: this.title, message: this.message, date: this.date, metadata: this.metadata, }; } static fromJSON(json) { return new Notification(json); } }
export class Notification { /** * @typedef NotificationData * @property {boolean} [read] * @property {string} title * @property {string} message * @property {('basic'|'sms')} [type='basic'] * @property {string} [date] * @property {object} [metadata] */ /** * * @param {NotificationData} data */ constructor(data) { this.read = 'read' in data ? data.read : false; this.title = data.title; this.message = data.message; this.date = 'date' in data ? data.date : null; this.metadata = 'metadata' in data ? data.metadata : ''; this.id = this.title + this.message + this.date + JSON.stringify(this.metadata); } /** * Converts the notification to a JSON object * @return {object} */ toJSON() { return { read: this.read, title: this.title, message: this.message, date: this.date, metadata: this.metadata, }; } static fromJSON(json) { return new Notification(json); } }
Use log, rather than printf.
package openzwave import "log" // A logger interface. Modelled on github.com/juju/loggo so that can be used substituted by default. type Logger interface { // Log an info message. Infof(message string, args ...interface{}) // Log a warning message. Warningf(message string, args ...interface{}) // Log an error message. Errorf(message string, args ...interface{}) // Log a debug message. Debugf(message string, args ...interface{}) // Log a trace message. Tracef(message string, args ...interface{}) } type defaultLogger struct { } func (defaultLogger) Infof(message string, args ...interface{}) { log.Printf(message, args...) } func (defaultLogger) Warningf(message string, args ...interface{}) { log.Printf(message, args...) } func (defaultLogger) Errorf(message string, args ...interface{}) { log.Printf(message, args...) } func (defaultLogger) Debugf(message string, args ...interface{}) { log.Printf(message, args...) } func (defaultLogger) Tracef(message string, args ...interface{}) { log.Printf(message, args...) }
package openzwave import "fmt" // A logger interface. Modelled on github.com/juju/loggo so that can be used substituted by default. type Logger interface { // Log an info message. Infof(message string, args ...interface{}) // Log a warning message. Warningf(message string, args ...interface{}) // Log an error message. Errorf(message string, args ...interface{}) // Log a debug message. Debugf(message string, args ...interface{}) // Log a trace message. Tracef(message string, args ...interface{}) } type defaultLogger struct { } func (defaultLogger) Infof(message string, args ...interface{}) { fmt.Printf(message, args...) } func (defaultLogger) Warningf(message string, args ...interface{}) { fmt.Printf(message, args...) } func (defaultLogger) Errorf(message string, args ...interface{}) { fmt.Printf(message, args...) } func (defaultLogger) Debugf(message string, args ...interface{}) { fmt.Printf(message, args...) } func (defaultLogger) Tracef(message string, args ...interface{}) { fmt.Printf(message, args...) }
Add missing 'h' in https in Requestor doc.
"""Provides the HTTP request handling interface.""" import requests from . import const class Requestor(object): """Requestor provides an interface to HTTP requests.""" def __init__(self, user_agent): """Create an instance of the Requestor class. :param user_agent: The user-agent for your application. Please follow reddit's user-agent guidlines: https://github.com/reddit/reddit/wiki/API#rules """ self._http = requests.Session() self._http.headers['User-Agent'] = '{} {}'.format( user_agent, const.USER_AGENT) def __getattr__(self, attribute): """Pass all undefined attributes to the _http attribute.""" return getattr(self._http, attribute)
"""Provides the HTTP request handling interface.""" import requests from . import const class Requestor(object): """Requestor provides an interface to HTTP requests.""" def __init__(self, user_agent): """Create an instance of the Requestor class. :param user_agent: The user-agent for your application. Please follow reddit's user-agent guidlines: ttps://github.com/reddit/reddit/wiki/API#rules """ self._http = requests.Session() self._http.headers['User-Agent'] = '{} {}'.format( user_agent, const.USER_AGENT) def __getattr__(self, attribute): """Pass all undefined attributes to the _http attribute.""" return getattr(self._http, attribute)
Exclude nulls in translator when operator is range, gt, gte Previously, nulls were included in all cases making it appear that null was but 0 and infinity. Now, null is effectively treated as 0. Signed-off-by: Don Naegely <e690a32c1e2176a2bfface09e204830e1b5491e3@gmail.com>
from avocado.query.translators import Translator, registry from modeltree.tree import trees class AllowNullsTranslator(Translator): """For data sources that only apply to SNPs, this translator ensures only SNPs are filtered down and not other types of variants. """ def translate(self, field, roperator, rvalue, tree, **kwargs): output = super(AllowNullsTranslator, self).translate( field, roperator, rvalue, tree, **kwargs) # We are excluding nulls in the case of range, gt, and gte operators. # If we did not do this, then null values would be included all the # time which would be confusing, especially then they are included # for both lt and gt queries as it appears nulls are simultaneously # 0 and infinity. if roperator not in ('range', 'gt', 'gte'): # Create a null condition for this field null_condition = trees[tree].query_condition( field.field, 'isnull', True) # Allow the null condition output['query_modifiers']['condition'] |= null_condition return output registry.register(AllowNullsTranslator, 'Allow Nulls')
from avocado.query.translators import Translator, registry from modeltree.tree import trees class AllowNullsTranslator(Translator): """For data sources that only apply to SNPs, this translator ensures only SNPs are filtered down and not other types of variants. """ def translate(self, field, roperator, rvalue, tree, **kwargs): output = super(AllowNullsTranslator, self).translate( field, roperator, rvalue, tree, **kwargs) # Create a null condition for this field null_condition = trees[tree].query_condition( field.field, 'isnull', True) # Allow the null condition output['query_modifiers']['condition'] |= null_condition return output registry.register(AllowNullsTranslator, 'Allow Nulls')
Make sure the name is up to date
'use strict'; var config = { channels: [ '#kokarn' ], server: 'irc.freenode.net', botName: 'BoilBot' }, irc = require( 'irc' ), bot = new irc.Client( config.server, config.botName, { channels: config.channels } ), dagensMix = new ( require( './DagensMix.botplug.js' ) )(), gitHub = require( './GitHub.botplug.js' ), pushbullet = require( './Pushbullet.botplug.js' ), rss = require( './RSS.botplug.js' ), urlchecker = require( './Urlchecker.botplug.js' ); dagensMix.addBot( bot ); gitHub.setup( bot ); pushbullet.setup( bot ); urlchecker.setup( bot ); rss.setup( bot ); bot.addListener( 'error', function( message ){ console.log( 'error: ', message ); });
'use strict'; var config = { channels: [ '#kokarn' ], server: 'irc.freenode.net', botName: 'KokBot' }, irc = require( 'irc' ), bot = new irc.Client( config.server, config.botName, { channels: config.channels } ), dagensMix = new ( require( './DagensMix.botplug.js' ) )(), gitHub = require( './GitHub.botplug.js' ), pushbullet = require( './Pushbullet.botplug.js' ), rss = require( './RSS.botplug.js' ), urlchecker = require( './Urlchecker.botplug.js' ); dagensMix.addBot( bot ); gitHub.setup( bot ); pushbullet.setup( bot ); urlchecker.setup( bot ); rss.setup( bot ); bot.addListener( 'error', function( message ){ console.log( 'error: ', message ); });
Add test for trace address parsing in config
package veneur import ( "os" "strings" "testing" "time" "github.com/stretchr/testify/assert" ) func TestReadConfig(t *testing.T) { exampleConfig, err := os.Open("example.yaml") assert.NoError(t, err) defer exampleConfig.Close() c, err := readConfig(exampleConfig) if err != nil { t.Fatal(err) } assert.Equal(t, "https://app.datadoghq.com", c.APIHostname) assert.Equal(t, 96, c.NumWorkers) interval, err := c.ParseInterval() assert.NoError(t, err) assert.Equal(t, interval, 10*time.Second) assert.Equal(t, c.TraceAddress, "localhost:8128") } func TestReadBadConfig(t *testing.T) { const exampleConfig = `--- api_hostname: :bad` r := strings.NewReader(exampleConfig) c, err := readConfig(r) assert.NotNil(t, err, "Should have encountered parsing error when reading invalid config file") assert.Equal(t, c, Config{}, "Parsing invalid config file should return zero struct") }
package veneur import ( "os" "strings" "testing" "time" "github.com/stretchr/testify/assert" ) func TestReadConfig(t *testing.T) { exampleConfig, err := os.Open("example.yaml") assert.NoError(t, err) defer exampleConfig.Close() c, err := readConfig(exampleConfig) if err != nil { t.Fatal(err) } assert.Equal(t, "https://app.datadoghq.com", c.APIHostname) assert.Equal(t, 96, c.NumWorkers) interval, err := c.ParseInterval() assert.NoError(t, err) assert.Equal(t, interval, 10*time.Second) } func TestReadBadConfig(t *testing.T) { const exampleConfig = `--- api_hostname: :bad` r := strings.NewReader(exampleConfig) c, err := readConfig(r) assert.NotNil(t, err, "Should have encountered parsing error when reading invalid config file") assert.Equal(t, c, Config{}, "Parsing invalid config file should return zero struct") }
Fix for stripping properties before adding to swagger.
'use strict'; var _ = require('lodash'); var swagger = require('swagger-spec-express'); var schemaKeys = Object.keys(require('swagger-spec-express/lib/schemas/schema.json').properties); schemaKeys.push('definitions'); module.exports = function addModel(schema) { var modelSchema = _.cloneDeep(_.pick(schema, schemaKeys)); filterProperties(modelSchema.properties); if (modelSchema.definitions) { Object.keys(modelSchema.definitions).forEach(function (definitionName) { var definitionValue = modelSchema.definitions[definitionName]; filterProperties(definitionValue.properties); }); } swagger.common.addModel(modelSchema, {validation: 'warn'}); }; function filterProperties(properties) { Object.keys(properties).forEach(function (propertyName) { var propertyValue = properties[propertyName]; Object.keys(propertyValue).forEach(function (key) { if (schemaKeys.indexOf(key) < 0) { delete propertyValue[key]; } if (key.toLowerCase() === 'properties') { filterProperties(propertyValue.properties); } }); }); }
'use strict'; var _ = require('lodash'); var swagger = require('swagger-spec-express'); var schemaKeys = Object.keys(require('swagger-spec-express/lib/schemas/schema.json').properties); schemaKeys.push('definitions'); module.exports = function addModel(schema) { var modelSchema = _.cloneDeep(_.pick(schema, schemaKeys)); stripSpecificProperties(modelSchema); swagger.common.addModel(modelSchema, {validation: 'warn'}); }; const propertiesToStrip = ['faker', 'chance']; function stripSpecificProperties(schema) { if (_.isArray(schema)) { schema.forEach(function (item) { stripSpecificProperties(item); }); return; } if (!_.isObject(schema)) { return; } propertiesToStrip.forEach(function (key) { delete schema[key]; }); _.valuesIn(schema).forEach(stripSpecificProperties); }
Fix tests for new Atom versions
'use babel'; describe('Filesize plugin', () => { let workspaceView = null; beforeEach(() => { waitsForPromise(() => atom.workspace.open(`${__dirname}/fixtures/atom_icon.png`)); waitsForPromise(() => atom.packages.activatePackage('status-bar')); waitsForPromise(() => atom.packages.activatePackage('filesize')); workspaceView = atom.views.getView(atom.workspace); }); describe('when activating', () => { it('should appear as active to Atom', () => { expect(atom.packages.isPackageActive('filesize')).toEqual(true); }); it('should appear on the status-bar component', () => { const statusBar = workspaceView.querySelector('.status-bar'); expect(statusBar.querySelector('.file-size')).not.toEqual(null); }); }); describe('when deactivating', () => { beforeEach(() => { atom.packages.disablePackage('filesize'); }); it('should appear as inactive to Atom', () => { expect(atom.packages.isPackageDisabled('filesize')).toEqual(true); }); xit('should disappear from the status-bar component', () => { const statusBar = workspaceView.querySelector('.status-bar'); expect(statusBar.querySelector('.file-size')).toEqual(null); }); }); });
'use babel'; describe('Filesize plugin', () => { let workspaceView = null; beforeEach(() => { waitsForPromise(() => atom.workspace.open(`${__dirname}/fixtures/atom_icon.png`)); waitsForPromise(() => atom.packages.activatePackage('status-bar')); waitsForPromise(() => atom.packages.activatePackage('filesize')); workspaceView = atom.views.getView(atom.workspace); }); describe('when activating', () => { it('should appear as active to Atom', () => { expect(atom.packages.isPackageActive('filesize')).toEqual(true); }); it('should appear on the status-bar component', () => { const statusBar = workspaceView.querySelector('.status-bar'); expect(statusBar.querySelector('.file-size')).not.toEqual(null); }); }); describe('when deactivating', () => { beforeEach(() => { atom.packages.deactivatePackage('filesize'); }); it('should appear as inactive to Atom', () => { expect(atom.packages.isPackageActive('filesize')).toEqual(false); }); it('should disappear from the status-bar component', () => { const statusBar = workspaceView.querySelector('.status-bar'); expect(statusBar.querySelector('.file-size')).toEqual(null); }); }); });
Use IndicesClient to get full URL
from django.core.management import BaseCommand from corehq.apps.cleanup.utils import confirm_destructive_operation from corehq.elastic import get_es_new from corehq.util.es.elasticsearch import IndicesClient class Command(BaseCommand): """ Wipe all data from BlobDB. """ def add_arguments(self, parser): parser.add_argument( '--commit', action='store_true', dest='commit', default=False, ) def handle(self, *args, **options): confirm_destructive_operation() data = wipe_es(options['commit']) if data: print(data) if not options['commit']: print("You need to run with --commit for the deletion to happen.") def wipe_es(commit=False): """ The equivalent of calling :: $ curl -X DELETE "$PROTO://$HOSTNAME:$PORT/_all" """ es = get_es_new() client = IndicesClient(es) if commit: client.delete('_all')
from django.core.management import BaseCommand from corehq.apps.cleanup.utils import confirm_destructive_operation from corehq.elastic import get_es_new class Command(BaseCommand): """ Wipe all data from BlobDB. """ def add_arguments(self, parser): parser.add_argument( '--commit', action='store_true', dest='commit', default=False, ) def handle(self, *args, **options): confirm_destructive_operation() data = wipe_es(options['commit']) if data: print(data) if not options['commit']: print("You need to run with --commit for the deletion to happen.") def wipe_es(commit=False): """ The equivalent of calling :: $ curl -X DELETE "$PROTO://$HOSTNAME:$PORT/_all" """ es = get_es_new() if commit: return es.transport.perform_request('DELETE', '_all')
Add warning if CERT_PASSWORD is not defined
const installer = require('electron-installer-windows'); const { CERT_PASSWORD, APPVEYOR_REPO_TAG } = process.env; if (typeof CERT_PASSWORD !== 'string' && APPVEYOR_REPO_TAG === 'true') { console.log('Error: The certificate password is not a string'); throw new Error('The certificate password is not a string'); } else { console.log('Warning: The package will not be signed'); } const options = { src: 'build/Headset-win32-ia32', dest: 'build/installers/', productDescription: 'Headset is a desktop app that turns YouTube into a world class music streaming service.' + 'Create collections, tune-in to a music subreddit or quickly play that song ' + 'you’ve had stuck in your head all day!', icon: 'Headset.ico', iconUrl: 'https://raw.githubusercontent.com/headsetapp/headset-electron/master/windows/Headset.ico', licenseUrl: 'https://raw.githubusercontent.com/headsetapp/headset-electron/master/LICENSE', certificateFile: 'sig/headset.pfx', certificatePassword: CERT_PASSWORD, }; console.log('Creating package (this may take a while)'); installer(options) .then(() => console.log(`Successfully created package at ${options.dest}`)) .catch((err) => { console.log('Error creating package'); console.error(err, err.stack); process.exit(1); });
const installer = require('electron-installer-windows'); if (typeof process.env.CERT_PASSWORD !== 'string') { console.log('Error: The certificate password is not a string'); throw new Error('The certificate password is not a string'); } const options = { src: 'build/Headset-win32-ia32', dest: 'build/installers/', productDescription: 'Headset is a desktop app that turns YouTube into a world class music streaming service.' + 'Create collections, tune-in to a music subreddit or quickly play that song ' + 'you’ve had stuck in your head all day!', icon: 'Headset.ico', iconUrl: 'https://raw.githubusercontent.com/headsetapp/headset-electron/master/windows/Headset.ico', licenseUrl: 'https://raw.githubusercontent.com/headsetapp/headset-electron/master/LICENSE', certificateFile: 'sig/headset.pfx', certificatePassword: process.env.CERT_PASSWORD, }; console.log('Creating package (this may take a while)'); installer(options) .then(() => console.log(`Successfully created package at ${options.dest}`)) .catch((err) => { console.log('Error creating package'); console.error(err, err.stack); process.exit(1); });
Fix a legit broken import that Deepscan caught
/* global Vulcan */ import { Comments } from '../../lib/collections/comments' import { Posts } from '../../lib/collections/posts' import { wrapVulcanAsyncScript } from '../scripts/utils' import { batchUpdateScore } from '../updateScores.js'; Vulcan.forceBatchUpdateScores = wrapVulcanAsyncScript('forceBatchUpdateScores', async () => { // Posts const nActivePostsUpdated = await batchUpdateScore({ collection: Posts, forceUpdate: true }) // eslint-disable-next-line no-console console.log('nActivePostsUpdated', nActivePostsUpdated) const nInactivePostsUpdated = await batchUpdateScore({ collection: Posts, inactive: true, forceUpdate: true }) // eslint-disable-next-line no-console console.log('nInactivePostsUpdated', nInactivePostsUpdated) // Comments const nActiveCommentsUpdated = await batchUpdateScore({ collection: Comments, forceUpdate: true }) // eslint-disable-next-line no-console console.log('nActiveCommentsUpdated', nActiveCommentsUpdated) const nInactiveCommentsUpdated = await batchUpdateScore({ collection: Comments, inactive: true, forceUpdate: true }) // eslint-disable-next-line no-console console.log('nInactiveCommentsUpdated', nInactiveCommentsUpdated) })
/* global Vulcan */ import { Comments } from '../../lib/collections/comments' import { Posts } from '../../lib/collections/posts' import { wrapVulcanAsyncScript } from '../scripts/utils' import { batchUpdateScore } from '../../lib/modules/scoring.js'; Vulcan.forceBatchUpdateScores = wrapVulcanAsyncScript('forceBatchUpdateScores', async () => { // Posts const nActivePostsUpdated = await batchUpdateScore({ collection: Posts, forceUpdate: true }) // eslint-disable-next-line no-console console.log('nActivePostsUpdated', nActivePostsUpdated) const nInactivePostsUpdated = await batchUpdateScore({ collection: Posts, inactive: true, forceUpdate: true }) // eslint-disable-next-line no-console console.log('nInactivePostsUpdated', nInactivePostsUpdated) // Comments const nActiveCommentsUpdated = await batchUpdateScore({ collection: Comments, forceUpdate: true }) // eslint-disable-next-line no-console console.log('nActiveCommentsUpdated', nActiveCommentsUpdated) const nInactiveCommentsUpdated = await batchUpdateScore({ collection: Comments, inactive: true, forceUpdate: true }) // eslint-disable-next-line no-console console.log('nInactiveCommentsUpdated', nInactiveCommentsUpdated) })
Bump to next dev 0.1.5.dev1
#!/usr/bin/env python3 # encoding: utf-8 from setuptools import setup, find_packages setup( name='pyatv', version='0.1.5.dev1', license='MIT', url='https://github.com/postlund/pyatv', author='Pierre Ståhl', author_email='pierre.staahl@gmail.com', description='Library for controlling an Apple TV', packages=find_packages(exclude=['tests', 'tests.*']), include_package_data=True, zip_safe=False, platforms='any', install_requires=[ 'aiohttp==1.3.1', 'zeroconf==0.18.0', ], test_suite='tests', keywords=['apple', 'tv'], tests_require=['tox'], entry_points={ 'console_scripts': [ 'atvremote = pyatv.__main__:main' ] }, classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Topic :: Software Development :: Libraries', 'Topic :: Home Automation', ], )
#!/usr/bin/env python3 # encoding: utf-8 from setuptools import setup, find_packages setup( name='pyatv', version='0.1.4', license='MIT', url='https://github.com/postlund/pyatv', author='Pierre Ståhl', author_email='pierre.staahl@gmail.com', description='Library for controlling an Apple TV', packages=find_packages(exclude=['tests', 'tests.*']), include_package_data=True, zip_safe=False, platforms='any', install_requires=[ 'aiohttp==1.3.1', 'zeroconf==0.18.0', ], test_suite='tests', keywords=['apple', 'tv'], tests_require=['tox'], entry_points={ 'console_scripts': [ 'atvremote = pyatv.__main__:main' ] }, classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Topic :: Software Development :: Libraries', 'Topic :: Home Automation', ], )
Change the @match metadata to the */job/*/configure pattern to be as generic as possible
/* Copyright 2015 Ops For Developers Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // ==UserScript== // @name Jenkins Show Advanced // @namespace http://opsfordevelopers.com/jenkins/userscripts // @description Automatically shows the configuration hidden beneath the "Advanced..." buttons in Jenkins jobs // @match */job/*/configure // @require https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js // @run-at document-end // @version 1.0 // @grant none // ==/UserScript== function showAdvancedTables () { // hide the "Advanced..." buttons and show the advanced tables jQuery("div.advancedLink").hide(); jQuery("table.advancedBody").show(); // give to the advanced tables the full width and remove the adjacent td tags jQuery("table.advancedBody").parent("td").attr("colspan", 4); jQuery("table.advancedBody").parentsUntil("tbody").children("td:empty").remove(); } jQuery(document).ready(function(){ jQuery.noConflict(); showAdvancedTables(); });
/* Copyright 2015 Ops For Developers Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // ==UserScript== // @name Jenkins Show Advanced // @namespace http://opsfordevelopers.com/jenkins/userscripts // @description Automatically shows the configuration hidden beneath the "Advanced..." buttons in Jenkins jobs // @match https://*/jenkins/* // @match http://*/jenkins/* // @require https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js // @run-at document-end // @version 1.0 // @grant none // ==/UserScript== function showAdvancedTables () { // hide the "Advanced..." buttons and show the advanced tables jQuery("div.advancedLink").hide(); jQuery("table.advancedBody").show(); // give to the advanced tables the full width and remove the adjacent td tags jQuery("table.advancedBody").parent("td").attr("colspan", 4); jQuery("table.advancedBody").parentsUntil("tbody").children("td:empty").remove(); } jQuery(document).ready(function(){ jQuery.noConflict(); showAdvancedTables(); });
Use backquote in tests in newMatcherTests
package main import ( "reflect" "regexp" "testing" ) var genMatcherTests = []struct { src string dst *regexp.Regexp }{ {`abc`, regexp.MustCompile(`(abc)`)}, {`abcdef`, regexp.MustCompile(`(abcdef)`)}, {`a,b`, regexp.MustCompile(`(a|b)`)}, {`a,bc,def`, regexp.MustCompile(`(a|bc|def)`)}, {`a\,b`, regexp.MustCompile(`(a,b)`)}, {`a\,bc\,def`, regexp.MustCompile(`(a,bc,def)`)}, {`a\,b,c`, regexp.MustCompile(`(a,b|c)`)}, {`a,bc\,def`, regexp.MustCompile(`(a|bc,def)`)}, } func TestGenMatcher(t *testing.T) { for _, test := range genMatcherTests { expect := test.dst actual, err := newMatcher(test.src) if err != nil { t.Errorf("NewSubvert(%q) returns %q, want nil", test.src, err) } if !reflect.DeepEqual(actual, expect) { t.Errorf("%q: got %q, want %q", test.src, actual, expect) } } }
package main import ( "reflect" "regexp" "testing" ) var genMatcherTests = []struct { src string dst *regexp.Regexp }{ {"abc", regexp.MustCompile(`(abc)`)}, {"abcdef", regexp.MustCompile(`(abcdef)`)}, {"a,b", regexp.MustCompile(`(a|b)`)}, {"a,bc,def", regexp.MustCompile(`(a|bc|def)`)}, {"a\\,b", regexp.MustCompile(`(a,b)`)}, {"a\\,bc\\,def", regexp.MustCompile(`(a,bc,def)`)}, {"a\\,b,c", regexp.MustCompile(`(a,b|c)`)}, {"a,bc\\,def", regexp.MustCompile(`(a|bc,def)`)}, } func TestGenMatcher(t *testing.T) { for _, test := range genMatcherTests { expect := test.dst actual, err := newMatcher(test.src) if err != nil { t.Errorf("NewSubvert(%q) returns %q, want nil", test.src, err) } if !reflect.DeepEqual(actual, expect) { t.Errorf("%q: got %q, want %q", test.src, actual, expect) } } }
Add back 1.0.X compatibility for Router URL resolution. Signed-off-by: Simon Willison <088e16a1019277b15d58faf0541e11910eb756f6@simonwillison.net>
from django.conf.urls.defaults import patterns from django.core import urlresolvers class Router(object): """ Convenient wrapper around Django's urlresolvers, allowing them to be used from normal application code. from django.http import HttpResponse from django_openid.request_factory import RequestFactory from django.conf.urls.defaults import url router = Router( url('^foo/$', lambda r: HttpResponse('foo'), name='foo'), url('^bar/$', lambda r: HttpResponse('bar'), name='bar') ) rf = RequestFactory() print router(rf.get('/bar/')) """ def __init__(self, *urlpairs): self.urlpatterns = patterns('', *urlpairs) # for 1.0 compatibility we pass in None for urlconf_name and then # modify the _urlconf_module to make self hack as if its the module. self.resolver = urlresolvers.RegexURLResolver(r'^/', None) self.resolver._urlconf_module = self def handle(self, request): path = request.path_info callback, callback_args, callback_kwargs = self.resolver.resolve(path) return callback(request, *callback_args, **callback_kwargs) def __call__(self, request): return self.handle(request)
from django.conf.urls.defaults import patterns from django.core import urlresolvers class Router(object): """ Convenient wrapper around Django's urlresolvers, allowing them to be used from normal application code. from django.http import HttpResponse from django_openid.request_factory import RequestFactory from django.conf.urls.defaults import url router = Router( url('^foo/$', lambda r: HttpResponse('foo'), name='foo'), url('^bar/$', lambda r: HttpResponse('bar'), name='bar') ) rf = RequestFactory() print router(rf.get('/bar/')) """ def __init__(self, *urlpairs): self.urlpatterns = patterns('', *urlpairs) self.resolver = urlresolvers.RegexURLResolver(r'^/', self) def handle(self, request): path = request.path_info callback, callback_args, callback_kwargs = self.resolver.resolve(path) return callback(request, *callback_args, **callback_kwargs) def __call__(self, request): return self.handle(request)
Install Env Production of project Sylius
<?php /* * This file is part of the Sylius package. * * (c) Paweł Jędrzejewski * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ use Symfony\Component\ClassLoader\ApcClassLoader; use Symfony\Component\HttpFoundation\Request; /* * Sylius front controller. * Live (production) environment. */ $loader = require_once __DIR__.'/../app/bootstrap.php.cache'; //$loader = new ApcClassLoader('sylius', $loader); //$loader->register(true); require_once __DIR__.'/../app/AppKernel.php'; //require_once __DIR__.'/../app/AppCache.php'; $kernel = new AppKernel('prod', true); //$kernel = new AppCache($kernel); $request = Request::createFromGlobals(); Request::enableHttpMethodParameterOverride(); $response = $kernel->handle($request); $response->send(); $kernel->terminate($request, $response);
<?php /* * This file is part of the Sylius package. * * (c) Paweł Jędrzejewski * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ use Symfony\Component\ClassLoader\ApcClassLoader; use Symfony\Component\HttpFoundation\Request; /* * Sylius front controller. * Live (production) environment. */ $loader = require_once __DIR__.'/../app/bootstrap.php.cache'; //$loader = new ApcClassLoader('sylius', $loader); //$loader->register(true); require_once __DIR__.'/../app/AppKernel.php'; //require_once __DIR__.'/../app/AppCache.php'; $kernel = new AppKernel('prod', false); //$kernel = new AppCache($kernel); $request = Request::createFromGlobals(); Request::enableHttpMethodParameterOverride(); $response = $kernel->handle($request); $response->send(); $kernel->terminate($request, $response);
Fix of tests with unicode strings
"""Sample unittests.""" import unittest2 as unittest from domain_models import model from domain_models import fields class User(model.DomainModel): """Example user domain model.""" id = fields.Int() email = fields.String() first_name = fields.Unicode() last_name = fields.Unicode() gender = fields.String() birth_date = fields.String() __view_key__ = [id, email] __unique_key__ = id class SampleTests(unittest.TestCase): """Sample tests tests.""" def test_set_and_get_attrs(self): """Test setting and getting of domain model attributes.""" user = User() user.id = 1 user.email = 'example@example.com' user.first_name = 'John' user.last_name = 'Smith' user.gender = 'male' user.birth_date = '05/04/1988' self.assertEqual(user.id, 1) self.assertEqual(user.email, 'example@example.com') self.assertEqual(user.first_name, unicode('John')) self.assertEqual(user.last_name, unicode('Smith')) self.assertEqual(user.gender, 'male') self.assertEqual(user.birth_date, '05/04/1988')
"""Sample unittests.""" import unittest2 as unittest from domain_models import model from domain_models import fields class User(model.DomainModel): """Example user domain model.""" id = fields.Int() email = fields.String() first_name = fields.Unicode() last_name = fields.Unicode() gender = fields.String() birth_date = fields.String() __view_key__ = [id, email] __unique_key__ = id class SampleTests(unittest.TestCase): """Sample tests tests.""" def test_set_and_get_attrs(self): """Test setting and getting of domain model attributes.""" user = User() user.id = 1 user.email = 'example@example.com' user.first_name = 'John' user.last_name = 'Smith' user.gender = 'male' user.birth_date = '05/04/1988' self.assertEqual(user.id, 1) self.assertEqual(user.email, 'example@example.com') self.assertEqual(user.first_name, u'John') self.assertEqual(user.last_name, u'Smith') self.assertEqual(user.gender, 'male') self.assertEqual(user.birth_date, '05/04/1988')
Use secure gravatar and fix gravatar image size Fixes #106 Fixes #112
""" gravatar_url from https://en.gravatar.com/site/implement/images/django/ """ from django import template from django.conf import settings import urllib import hashlib register = template.Library() class GravatarUrlNode(template.Node): def __init__(self, email): self.email = template.Variable(email) def render(self, context): try: email = self.email.resolve(context) except template.VariableDoesNotExist: return '' email_hash = hashlib.md5(email.lower()).hexdigest() query_str = urllib.urlencode({'d': 'megaminerai.com/static/img/default_profile_image.png', 's': 200}) url = "https://secure.gravatar.com/avatar/{0}?{1}" return url.format(email_hash, query_str) @register.tag def gravatar_url(parser, token): try: tag_name, email = token.split_contents() except ValueError: raise template.TemplateSyntaxError, "%r tag requires a single argument" % token.contents.split()[0] return GravatarUrlNode(email)
""" gravatar_url from https://en.gravatar.com/site/implement/images/django/ """ from django import template from django.conf import settings import urllib import hashlib register = template.Library() class GravatarUrlNode(template.Node): def __init__(self, email): self.email = template.Variable(email) def render(self, context): try: email = self.email.resolve(context) except template.VariableDoesNotExist: return '' email_hash = hashlib.md5(email.lower()).hexdigest() query_str = urllib.urlencode({'d': 'megaminerai.com/static/img/default_profile_image.png'}) url = "http://www.gravatar.com/avatar/{0}?{1}" return url.format(email_hash, query_str) @register.tag def gravatar_url(parser, token): try: tag_name, email = token.split_contents() except ValueError: raise template.TemplateSyntaxError, "%r tag requires a single argument" % token.contents.split()[0] return GravatarUrlNode(email)
Add canvas width height vars
/** * @fileoverview WebGL.js - Set up WebGL context * @author Ben Brooks (beb12@aber.ac.uk) * @version 1.0 */ /** * Initialise the WebGL context and return it * @params canvas - HTML5 Canvas element */ function initWebGL(canvas) { var devicePixelRatio = window.devicePixelRatio || 1; var width = canvas.clientWidth; var height = canvas.clientHeight; // set the display size of the canvas. canvas.style.width = width + "px"; canvas.style.height = height + "px"; // set the size of the drawingBuffer canvas.width = width * devicePixelRatio; canvas.height = height * devicePixelRatio; glContext = canvas.getContext("webgl") || canvas.getContext("experimental-webgl"); glContext.viewportWidth = canvas.width; glContext.viewportHeight = canvas.height; if (!glContext) { alert("Unable to initialise WebGL. Your browser may not support it."); } return glContext; }
/** * @fileoverview WebGL.js - Set up WebGL context * @author Ben Brooks (beb12@aber.ac.uk) * @version 1.0 */ /** * Initialise the WebGL context and return it * @params canvas - HTML5 Canvas element */ function initWebGL(canvas) { var devicePixelRatio = window.devicePixelRatio || 1; var width = canvas.clientWidth; var height = canvas.clientHeight; // set the display size of the canvas. canvas.style.width = width + "px"; canvas.style.height = height + "px"; // set the size of the drawingBuffer canvas.width = width * devicePixelRatio; canvas.height = height * devicePixelRatio; glContext = canvas.getContext("webgl") || canvas.getContext("experimental-webgl"); if (!glContext) { alert("Unable to initialise WebGL. Your browser may not support it."); } return glContext; }
Fix issue when running nosetests and django_nose is not required
from nose.plugins import Plugin class DjangoNosePlugin(Plugin): ''' Adaptor that allows usage of django_nose package plugin from the nosetests command line. Imports and instantiates django_nose plugin after initialization so that the django environment does not have to be configured when running nosetests -p ''' name = 'djangonose' enabled = False @property def plugin(self): if self._plugin == None: from django_nose.runner import NoseTestSuiteRunner from django_nose.plugin import DjangoSetUpPlugin runner = NoseTestSuiteRunner() self._plugin = DjangoSetUpPlugin(runner) return self._plugin def __init__(self): super(DjangoNosePlugin, self).__init__() self._plugin = None def configure(self, *args, **kw_args): super(DjangoNosePlugin, self).configure(*args, **kw_args) if self.enabled: self.plugin.configure(*args, **kw_args) def prepareTest(self, test): self.plugin.prepareTest(test) def finalize(self, result): self.plugin.finalize(result)
from nose.plugins import Plugin class DjangoNosePlugin(Plugin): ''' Adaptor that allows usage of django_nose package plugin from the nosetests command line. Imports and instantiates django_nose plugin after initialization so that the django environment does not have to be configured when running nosetests -p ''' name = 'djangonose' enabled = False @property def plugin(self): if self._plugin == None: from django_nose.runner import NoseTestSuiteRunner from django_nose.plugin import DjangoSetUpPlugin runner = NoseTestSuiteRunner() self._plugin = DjangoSetUpPlugin(runner) return self._plugin def __init__(self): super(DjangoNosePlugin, self).__init__() self._plugin = None def configure(self, *args, **kw_args): super(DjangoNosePlugin, self).configure(*args, **kw_args) self.plugin.configure(*args, **kw_args) def prepareTest(self, test): self.plugin.prepareTest(test) def finalize(self, result): self.plugin.finalize(result)
Check if GPS specifically is enabled for all API versions.
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package info.zamojski.soft.towercollector.utils; import android.Manifest; import android.content.Context; import android.location.LocationManager; import android.os.Build; import androidx.core.content.PermissionChecker; public class GpsUtils { public static boolean isGpsEnabled(Context context) { if (PermissionChecker.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PermissionChecker.PERMISSION_GRANTED) { LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); boolean isEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { return isEnabled && locationManager.isLocationEnabled(); } return isEnabled; } // to cover the case when permission denied on API lower than 21 return false; } }
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package info.zamojski.soft.towercollector.utils; import android.Manifest; import android.content.Context; import android.location.LocationManager; import android.os.Build; import androidx.core.content.PermissionChecker; public class GpsUtils { public static boolean isGpsEnabled(Context context) { if (PermissionChecker.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PermissionChecker.PERMISSION_GRANTED) { LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { return locationManager.isLocationEnabled(); } else { return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); } } // to cover the case when permission denied on API lower than 21 return false; } }
Update max log file size
// @flow import path from 'path'; import express, { Router } from 'express'; import serveIndex from 'serve-index'; import winston from 'winston'; import expressWinston from 'express-winston'; import basicauth from 'basicauth-middleware'; import sha1 from 'sha1'; // requests logger const logsLogger = expressWinston.logger({ transports: [new winston.transports.File({ filename: './logs/logs-logger.log', maxsize: 2000000, maxFiles: 5 })] }); // error logger const logsErrorLogger = expressWinston.errorLogger({ transports: [new winston.transports.File({ filename: './logs/logs-error-logger.log', maxsize: 2000000, maxFiles: 5 })] }); // serve logs files const logsServe = Router(); logsServe.use('/logs', basicauth((username: string, password: string): boolean => ( username === process.env.LOGS_USERNAME && sha1(password) === process.env.LOGS_PASSWORD )), express.static(path.join(__dirname, '../../', 'logs')), serveIndex(path.join(__dirname, '../../', 'logs'), { icons: true }) ); export { logsLogger, logsErrorLogger, logsServe };
// @flow import path from 'path'; import express, { Router } from 'express'; import serveIndex from 'serve-index'; import winston from 'winston'; import expressWinston from 'express-winston'; import basicauth from 'basicauth-middleware'; import sha1 from 'sha1'; // requests logger const logsLogger = expressWinston.logger({ transports: [new winston.transports.File({ filename: './logs/logs-logger.log', maxsize: 5000000, maxFiles: 5 })] }); // error logger const logsErrorLogger = expressWinston.errorLogger({ transports: [new winston.transports.File({ filename: './logs/logs-error-logger.log', maxsize: 5000000, maxFiles: 5 })] }); // serve logs files const logsServe = Router(); logsServe.use('/logs', basicauth((username: string, password: string): boolean => ( username === process.env.LOGS_USERNAME && sha1(password) === process.env.LOGS_PASSWORD )), express.static(path.join(__dirname, '../../', 'logs')), serveIndex(path.join(__dirname, '../../', 'logs'), { icons: true }) ); export { logsLogger, logsErrorLogger, logsServe };
Fix broken test on Python 3.3
# -*- coding: utf-8 -*- # # Copyright 2013 Mark Lee # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import sys try: unicode except NameError: unicode = None if sys.version_info < (3,): # pragma: no cover from urllib import quote as url_quote to_bytes = lambda s: s.encode('utf-8') if isinstance(s, unicode) else s else: # pragma: no cover from urllib.parse import quote as url_quote to_bytes = lambda s: bytes(s, 'utf-8') if isinstance(s, str) else s __all__ = ['to_bytes', 'url_quote']
# -*- coding: utf-8 -*- # # Copyright 2013 Mark Lee # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import sys if sys.version_info < (3,): # pragma: no cover from urllib import quote as url_quote to_bytes = lambda s: s.encode('utf-8') if isinstance(s, unicode) else s else: # pragma: no cover from urllib.parse import quote as url_quote to_bytes = lambda s: bytes(s, 'utf-8') if isinstance(s, str) else s __all__ = ['to_bytes', 'url_quote']
[Core] Add scheduler for running unfinish transaction
var transactionData = require('../models/transactionData.js'); var sqsHelper = require('../helpers/aws/sqsHelper.js'); var schedule = require('node-schedule'); var job = schedule.scheduleJob('*/10 * * * *', function(){ transactionData.readUnfinishedTransaction().then(function(result) { if (result.rowCount > 0) { result.rows.forEach(function(item){ var message = { "txHash": item.txhash, "contractId": item.contractid, "contractFunctionId": item.contractfunctionid, "data": JSON.parse(item.data) }; sqsHelper.send(JSON.stringify(message), process.env.AWS_TRANSACTION_QUEUE_URL, 10, 'transaction'); }); } }).catch(function(err){ console.log(err.message, err.stack); }); });
var transactionData = require('../models/transactionData.js'); var sqsHelper = require('../helpers/aws/sqsHelper.js'); var schedule = require('node-schedule'); var job = schedule.scheduleJob('*/1 * * * *', function(){ transactionData.readUnfinishedTransaction().then(function(result) { if (result.rowCount > 0) { result.rows.forEach(function(item){ var message = { "txHash": item.txhash, "contractId": item.contractid, "contractFunctionId": item.contractfunctionid, "data": JSON.parse(item.data) }; sqsHelper.send(JSON.stringify(message), process.env.AWS_TRANSACTION_QUEUE_URL, 10, 'transaction'); }); } }).catch(function(err){ console.log(err.message, err.stack); }); });
Fix bad key format for config component
<?php namespace PhpTabs\Component; abstract class Config { /** * @var array config options */ private static $data = array(); /** * Gets a defined option * * @param string $key option name * @param mixed $default optional return value if not defined */ public static function get($key, $default = null) { return is_string($key) && isset(self::$data[$key]) ? self::$data[$key] : $default; } /** * Sets an option * * @param string $key option name * @param mixed $value optional option value */ public static function set($key, $value = null) { if (is_string($key)) { self::$data[$key] = $value; } } /** * Gets all defined options * * @return array All defined options */ public static function getAll() { return self::$data; } }
<?php namespace PhpTabs\Component; abstract class Config { /** * @var array config options */ private static $data = array(); /** * Gets a defined option * * @param string $key option name * @param mixed $default optional return value if not defined */ public static function get($key, $default = null) { return isset(self::$data[$key]) ? self::$data[$key] : $default; } /** * Sets an option * * @param string $key option name * @param mixed $value optional option value */ public static function set($key, $value = null) { if (is_string($key)) { self::$data[$key] = $value; } } /** * Gets all defined options * * @return array All defined options */ public static function getAll() { return self::$data; } }