text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Patch from Chuck Thier to properly install subpackages (eventlet.hubs and eventlet.support) now that we have subpackages
#!/usr/bin/env python from setuptools import setup, find_packages setup( name='eventlet', version='0.2', description='Coroutine-based networking library', author='Linden Lab', author_email='eventletdev@lists.secondlife.com', url='http://wiki.secondlife.com/wiki/Eventlet', packages=find_packages(), install_requires=['greenlet'], long_description=""" Eventlet is a networking library written in Python. It achieves high scalability by using non-blocking io while at the same time retaining high programmer usability by using coroutines to make the non-blocking io operations appear blocking at the source code level.""", classifiers=[ "License :: OSI Approved :: MIT License", "Programming Language :: Python", "Topic :: Internet", "Topic :: Software Development :: Libraries :: Python Modules", "Intended Audience :: Developers", "Development Status :: 4 - Beta"] )
#!/usr/bin/env python from setuptools import setup setup( name='eventlet', version='0.2', description='Coroutine-based networking library', author='Linden Lab', author_email='eventletdev@lists.secondlife.com', url='http://wiki.secondlife.com/wiki/Eventlet', packages=['eventlet'], install_requires=['greenlet'], long_description=""" Eventlet is a networking library written in Python. It achieves high scalability by using non-blocking io while at the same time retaining high programmer usability by using coroutines to make the non-blocking io operations appear blocking at the source code level.""", classifiers=[ "License :: OSI Approved :: MIT License", "Programming Language :: Python", "Topic :: Internet", "Topic :: Software Development :: Libraries :: Python Modules", "Intended Audience :: Developers", "Development Status :: 4 - Beta"] )
Apply default style on import
import sys, os # Add param submodule to sys.path cwd = os.path.abspath(os.path.split(__file__)[0]) sys.path.insert(0, os.path.join(cwd, '..', 'param')) import param __version__ = param.Version(release=(0,7), fpath=__file__, commit="$Format:%h$", reponame='dataviews') from .views import * # pyflakes:ignore (API import) from .dataviews import * # pyflakes:ignore (API import) from .sheetviews import * # pyflakes:ignore (API import) from .ndmapping import * # pyflakes:ignore (API import) from .styles import set_style set_style('default') def public(obj): if not isinstance(obj, type): return False baseclasses = [NdMapping, View, Dimension, Overlay] return any([issubclass(obj, bc) for bc in baseclasses]) _public = list(set([_k for _k, _v in locals().items() if public(_v)])) __all__ = _public + ["boundingregion", "ipython", "plotting", "sheetcoords" ]
import sys, os # Add param submodule to sys.path cwd = os.path.abspath(os.path.split(__file__)[0]) sys.path.insert(0, os.path.join(cwd, '..', 'param')) import param __version__ = param.Version(release=(0,7), fpath=__file__, commit="$Format:%h$", reponame='dataviews') from .views import * # pyflakes:ignore (API import) from .dataviews import * # pyflakes:ignore (API import) from .sheetviews import * # pyflakes:ignore (API import) from .ndmapping import * # pyflakes:ignore (API import) def public(obj): if not isinstance(obj, type): return False baseclasses = [NdMapping, View, Dimension, Overlay] return any([issubclass(obj, bc) for bc in baseclasses]) _public = list(set([_k for _k, _v in locals().items() if public(_v)])) __all__ = _public + ["boundingregion", "ipython", "plotting", "sheetcoords" ]
Fix path for clustercontroller set state api for applications.
// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.orchestrator.controller; import javax.ws.rs.Consumes; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; /** * @author hakonhall */ public interface ClusterControllerJaxRsApi { @POST @Path("/cluster/v2/{clusterName}/storage/{storageNodeIndex}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) ClusterControllerStateResponse setNodeState( @PathParam("clusterName") String clusterName, @PathParam("storageNodeIndex") int storageNodeIndex, ClusterControllerStateRequest request); @POST @Path("/cluster/v2/{clusterName}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) ClusterControllerStateResponse setClusterState( @PathParam("clusterName") String clusterName, ClusterControllerStateRequest request); }
// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.orchestrator.controller; import javax.ws.rs.Consumes; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; /** * @author hakonhall */ public interface ClusterControllerJaxRsApi { @POST @Path("/cluster/v2/{clusterName}/storage/{storageNodeIndex}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) ClusterControllerStateResponse setNodeState( @PathParam("clusterName") String clusterName, @PathParam("storageNodeIndex") int storageNodeIndex, ClusterControllerStateRequest request); @POST @Path("/cluster/v2/{clusterName}/storage") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) ClusterControllerStateResponse setClusterState( @PathParam("clusterName") String clusterName, ClusterControllerStateRequest request); }
Fix: Add new measure -> headCircumference
package sizebay.catalog.client.model; import lombok.*; @Getter @Setter @EqualsAndHashCode @ToString public class ModelingSizeMeasures { String sizeName = null; ModelingMeasureRange chest = null; ModelingMeasureRange hip = null; ModelingMeasureRange waist = null; ModelingMeasureRange sleeve = null; ModelingMeasureRange length = null; ModelingMeasureRange insideLeg = null; ModelingMeasureRange biceps = null; ModelingMeasureRange height = null; ModelingMeasureRange fist = null; ModelingMeasureRange neck = null; ModelingMeasureRange thigh = null; ModelingMeasureRange centralSeam = null; ModelingMeasureRange underBust = null; ModelingMeasureRange shoulderWidth = null; ModelingMeasureRange insoleLength = null; ModelingMeasureRange insoleWidth = null; ModelingMeasureRange waistUpper = null; ModelingMeasureRange waistLower = null; ModelingMeasureRange label1 = null; ModelingMeasureRange label2 = null; ModelingMeasureRange label3 = null; ModelingMeasureRange ageChart = null; ModelingMeasureRange weightChart = null; ModelingMeasureRange equivalence = null; ModelingMeasureRange headCircumference = null; }
package sizebay.catalog.client.model; import lombok.*; @Getter @Setter @EqualsAndHashCode @ToString public class ModelingSizeMeasures { String sizeName = null; ModelingMeasureRange chest = null; ModelingMeasureRange hip = null; ModelingMeasureRange waist = null; ModelingMeasureRange sleeve = null; ModelingMeasureRange length = null; ModelingMeasureRange insideLeg = null; ModelingMeasureRange biceps = null; ModelingMeasureRange height = null; ModelingMeasureRange fist = null; ModelingMeasureRange neck = null; ModelingMeasureRange thigh = null; ModelingMeasureRange centralSeam = null; ModelingMeasureRange underBust = null; ModelingMeasureRange shoulderWidth = null; ModelingMeasureRange insoleLength = null; ModelingMeasureRange insoleWidth = null; ModelingMeasureRange waistUpper = null; ModelingMeasureRange waistLower = null; ModelingMeasureRange label1 = null; ModelingMeasureRange label2 = null; ModelingMeasureRange label3 = null; ModelingMeasureRange ageChart = null; ModelingMeasureRange weightChart = null; ModelingMeasureRange equivalence = null; }
Add Report class from Realm
/** * mSupply Mobile * Sustainable Solutions (NZ) Ltd. 2019 */ import Realm from 'realm'; export class Address extends Realm.Object {} export class ItemCategory extends Realm.Object {} export class ItemDepartment extends Realm.Object {} export class Report extends Realm.Object {} export class Setting extends Realm.Object {} export class SyncOut extends Realm.Object {} export class TransactionCategory extends Realm.Object {} export class User extends Realm.Object {} export { Item } from './Item'; export { ItemBatch } from './ItemBatch'; export { ItemStoreJoin } from './ItemStoreJoin'; export { MasterList } from './MasterList'; export { MasterListItem } from './MasterListItem'; export { MasterListNameJoin } from './MasterListNameJoin'; export { Name } from './Name'; export { NameStoreJoin } from './NameStoreJoin'; export { NumberSequence } from './NumberSequence'; export { NumberToReuse } from './NumberToReuse'; export { Options } from './Options'; export { Period } from './Period'; export { PeriodSchedule } from './PeriodSchedule'; export { Requisition } from './Requisition'; export { RequisitionItem } from './RequisitionItem'; export { Stocktake } from './Stocktake'; export { StocktakeBatch } from './StocktakeBatch'; export { StocktakeItem } from './StocktakeItem'; export { Transaction } from './Transaction'; export { TransactionBatch } from './TransactionBatch'; export { TransactionItem } from './TransactionItem'; export { Unit } from './Unit';
/** * mSupply Mobile * Sustainable Solutions (NZ) Ltd. 2019 */ import Realm from 'realm'; export class Address extends Realm.Object {} export class ItemCategory extends Realm.Object {} export class ItemDepartment extends Realm.Object {} export class Setting extends Realm.Object {} export class SyncOut extends Realm.Object {} export class TransactionCategory extends Realm.Object {} export class User extends Realm.Object {} export { Item } from './Item'; export { ItemBatch } from './ItemBatch'; export { ItemStoreJoin } from './ItemStoreJoin'; export { MasterList } from './MasterList'; export { MasterListItem } from './MasterListItem'; export { MasterListNameJoin } from './MasterListNameJoin'; export { Name } from './Name'; export { NameStoreJoin } from './NameStoreJoin'; export { NumberSequence } from './NumberSequence'; export { NumberToReuse } from './NumberToReuse'; export { Options } from './Options'; export { Period } from './Period'; export { PeriodSchedule } from './PeriodSchedule'; export { Requisition } from './Requisition'; export { RequisitionItem } from './RequisitionItem'; export { Stocktake } from './Stocktake'; export { StocktakeBatch } from './StocktakeBatch'; export { StocktakeItem } from './StocktakeItem'; export { Transaction } from './Transaction'; export { TransactionBatch } from './TransactionBatch'; export { TransactionItem } from './TransactionItem'; export { Unit } from './Unit';
Add a few exception strings
from client.sources.common import importing from client.sources.doctest import models import logging import os log = logging.getLogger(__name__) def load(file, name, args): """Loads doctests from a specified filepath. PARAMETERS: file -- str; a filepath to a Python module containing OK-style tests. RETURNS: Test """ if not os.path.isfile(file) or not file.endswith('.py'): log.info('Cannot import doctests from {}'.format(file)) # TODO(albert): raise appropriate error raise Exception('Cannot import doctests from {}'.format(file)) module = importing.load_module(file) if not hasattr(module, name): # TODO(albert): raise appropriate error raise Exception('Module {} has no function {}'.format(module.__name__, name)) func = getattr(module, name) if not callable(func): # TODO(albert): raise appropriate error raise Exception return models.Doctest(file, args.verbose, args.interactive, args.timeout, name=name, points=1, docstring=func.__doc__)
from client.sources.common import importing from client.sources.doctest import models import logging import os log = logging.getLogger(__name__) def load(file, name, args): """Loads doctests from a specified filepath. PARAMETERS: file -- str; a filepath to a Python module containing OK-style tests. RETURNS: Test """ if not os.path.isfile(file) or not file.endswith('.py'): log.info('Cannot import doctests from {}'.format(file)) # TODO(albert): raise appropriate error raise Exception module = importing.load_module(file) if not hasattr(module, name): # TODO(albert): raise appropriate error raise Exception func = getattr(module, name) if not callable(func): # TODO(albert): raise appropriate error raise Exception return models.Doctest(file, args.verbose, args.interactive, args.timeout, name=name, points=1, docstring=func.__doc__)
Set protocol correctly ... oops
new Vue({ el: '#app', // Using ES6 string litteral delimiters because // Go uses {{ . }} for its templates delimiters: ['${', '}'], data: { ws: null, message: '', chat: [], }, created: function() { let protocol = (window.location.protocol === 'https:') ? 'wss:' : 'ws:' this.ws = new WebSocket(`${protocol}//${window.location.host}/ws`) this.ws.addEventListener('message', (e) => { let { user, avatar, content } = JSON.parse(e.data) this.chat.push({ user, avatar, content }) }) }, methods: { send: function() { if (!this.message) { return } this.ws.send( JSON.stringify({ content: this.message, }) ) this.message = '' }, } })
new Vue({ el: '#app', // Using ES6 string litteral delimiters because // Go uses {{ . }} for its templates delimiters: ['${', '}'], data: { ws: null, message: '', chat: [], }, created: function() { let protocol = (window.location.protocol === 'https') ? 'wss' : 'ws' this.ws = new WebSocket(`${protocol}://${window.location.host}/ws`) this.ws.addEventListener('message', (e) => { let { user, avatar, content } = JSON.parse(e.data) this.chat.push({ user, avatar, content }) }) }, methods: { send: function() { if (!this.message) { return } this.ws.send( JSON.stringify({ content: this.message, }) ) this.message = '' }, } })
Fix stupid typo in requirements specification.
from setuptools import setup import jasinja, sys requires = ['Jinja2'] if sys.version_info < (2, 6): requires += ['simplejson'] setup( name='jasinja', version=jasinja.__version__, url='http://bitbucket.org/djc/jasinja', license='BSD', author='Dirkjan Ochtman', author_email='dirkjan@ochtman.nl', description='A JavaScript code generator for Jinja templates', classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Topic :: Software Development :: Libraries :: Python Modules' ], packages=['jasinja', 'jasinja.tests'], package_data={ 'jasinja': ['*.js'] }, install_requires=requires, test_suite='jasinja.tests.run.suite', entry_points={ 'console_scripts': ['jasinja-compile = jasinja.compile:main'], }, )
from setuptools import setup import jasinja, sys requires = ['Jinja2'] if sys.version_info < (2, 6): requirements += ['simplejson'] setup( name='jasinja', version=jasinja.__version__, url='http://bitbucket.org/djc/jasinja', license='BSD', author='Dirkjan Ochtman', author_email='dirkjan@ochtman.nl', description='A JavaScript code generator for Jinja templates', classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Topic :: Software Development :: Libraries :: Python Modules' ], packages=['jasinja', 'jasinja.tests'], package_data={ 'jasinja': ['*.js'] }, install_requires=requires, test_suite='jasinja.tests.run.suite', entry_points={ 'console_scripts': ['jasinja-compile = jasinja.compile:main'], }, )
Fix test case for https redirects
from starlette.applications import Starlette from starlette.middleware.httpsredirect import HTTPSRedirectMiddleware from starlette.responses import PlainTextResponse from starlette.testclient import TestClient def test_https_redirect_middleware(): app = Starlette() app.add_middleware(HTTPSRedirectMiddleware) @app.route("/") def homepage(request): return PlainTextResponse("OK", status_code=200) client = TestClient(app, base_url="https://testserver") response = client.get("/") assert response.status_code == 200 client = TestClient(app) response = client.get("/", allow_redirects=False) assert response.status_code == 307 assert response.headers["location"] == "https://testserver/" client = TestClient(app, base_url="http://testserver:80") response = client.get("/", allow_redirects=False) assert response.status_code == 307 assert response.headers["location"] == "https://testserver/" client = TestClient(app, base_url="http://testserver:443") response = client.get("/", allow_redirects=False) assert response.status_code == 307 assert response.headers["location"] == "https://testserver/" client = TestClient(app, base_url="http://testserver:123") response = client.get("/", allow_redirects=False) assert response.status_code == 307 assert response.headers["location"] == "https://testserver:123/"
from starlette.applications import Starlette from starlette.middleware.httpsredirect import HTTPSRedirectMiddleware from starlette.responses import PlainTextResponse from starlette.testclient import TestClient def test_https_redirect_middleware(): app = Starlette() app.add_middleware(HTTPSRedirectMiddleware) @app.route("/") def homepage(request): return PlainTextResponse("OK", status_code=200) client = TestClient(app, base_url="https://testserver") response = client.get("/") assert response.status_code == 200 client = TestClient(app) response = client.get("/", allow_redirects=False) assert response.status_code == 308 assert response.headers["location"] == "https://testserver/" client = TestClient(app, base_url="http://testserver:80") response = client.get("/", allow_redirects=False) assert response.status_code == 308 assert response.headers["location"] == "https://testserver/" client = TestClient(app, base_url="http://testserver:443") response = client.get("/", allow_redirects=False) assert response.status_code == 308 assert response.headers["location"] == "https://testserver/" client = TestClient(app, base_url="http://testserver:123") response = client.get("/", allow_redirects=False) assert response.status_code == 308 assert response.headers["location"] == "https://testserver:123/"
fix: Fix issue only exposed by certain situations with the shadydom polyfill.
import props from './props'; function getValue (elem) { const type = elem.type; if (type === 'checkbox' || type === 'radio') { return elem.checked ? elem.value || true : false; } return elem.value; } export default function (elem, target) { return (e) => { // We fallback to checking the composed path. Unfortunately this behaviour // is difficult to impossible to reproduce as it seems to be a possible // quirk in the shadydom polyfill that incorrectly returns null for the // target but has the target as the first point in the path. // TODO revisit once all browsers have native support. const localTarget = e.target || e.composedPath()[0]; const value = getValue(localTarget); const localTargetName = target || localTarget.name || 'value'; if (localTargetName.indexOf('.') > -1) { const parts = localTargetName.split('.'); const firstPart = parts[0]; const propName = parts.pop(); const obj = parts.reduce((prev, curr) => (prev && prev[curr]), elem); obj[propName || e.target.name] = value; props(elem, { [firstPart]: elem[firstPart] }); } else { props(elem, { [localTargetName]: value }); } }; }
import props from './props'; function getValue (elem) { const type = elem.type; if (type === 'checkbox' || type === 'radio') { return elem.checked ? elem.value || true : false; } return elem.value; } export default function (elem, target) { return (e) => { // We fallback to checking the composed path. Unfortunately this behaviour // is difficult to impossible to reproduce as it seems to be a possible // quirk in the shadydom polyfill that incorrectly returns null for the // target but has the target as the first point in the path. // TODO revisit once all browsers have native support. const localTarget = target || e.target || e.composedPath()[0]; const value = getValue(localTarget); const localTargetName = e.target.name || 'value'; if (localTargetName.indexOf('.') > -1) { const parts = localTargetName.split('.'); const firstPart = parts[0]; const propName = parts.pop(); const obj = parts.reduce((prev, curr) => (prev && prev[curr]), elem); obj[propName || e.target.name] = value; props(elem, { [firstPart]: elem[firstPart] }); } else { props(elem, { [localTargetName]: value }); } }; }
Test shell with a command that will work on Windows too.
<?php namespace CommerceGuys\Platform\Cli\Tests; use CommerceGuys\Platform\Cli\Helper\ShellHelper; class ShellHelperTest extends \PHPUnit_Framework_TestCase { /** @var ShellHelper */ protected $shellHelper; public function setUp() { $this->shellHelper = new ShellHelper(); } /** * Test ShellHelper::execute(); */ public function testExecute() { $this->assertNotEmpty($this->shellHelper->execute('help')); $this->assertEmpty($this->shellHelper->execute('which nonexistent')); $this->assertEmpty($this->shellHelper->execute('nonexistent command test')); } /** * Test ShellHelper::executeArgs(). */ public function testExecuteArgs() { $this->assertNotEmpty($this->shellHelper->executeArgs(array('help')), false); $this->assertEmpty($this->shellHelper->executeArgs(array('which', 'nonexistent'), false)); $this->assertNotEmpty($this->shellHelper->executeArgs(array('help')), true); $this->setExpectedException('Symfony\\Component\\Process\\Exception\\ProcessFailedException'); $this->shellHelper->executeArgs(array('which', 'nonexistent'), true); } }
<?php namespace CommerceGuys\Platform\Cli\Tests; use CommerceGuys\Platform\Cli\Helper\ShellHelper; class ShellHelperTest extends \PHPUnit_Framework_TestCase { /** @var ShellHelper */ protected $shellHelper; public function setUp() { $this->shellHelper = new ShellHelper(); } /** * Test ShellHelper::execute(); */ public function testExecute() { $this->assertNotEmpty($this->shellHelper->execute('which git')); $this->assertEmpty($this->shellHelper->execute('which nonexistent')); $this->assertEmpty($this->shellHelper->execute('nonexistent command test')); } /** * Test ShellHelper::executeArgs(). */ public function testExecuteArgs() { $this->assertNotEmpty($this->shellHelper->executeArgs(array('which', 'git')), false); $this->assertEmpty($this->shellHelper->executeArgs(array('which', 'nonexistent'), false)); $this->assertNotEmpty($this->shellHelper->executeArgs(array('which', 'git')), true); $this->setExpectedException('Symfony\\Component\\Process\\Exception\\ProcessFailedException'); $this->shellHelper->executeArgs(array('which', 'nonexistent'), true); } }
Throw exception when trying to access undefined property
<?php namespace Fathomminds\Rest; use Fathomminds\Rest\Contracts\ISchema; use Fathomminds\Rest\Schema\TypeValidators\ValidatorFactory; use Fathomminds\Rest\Exceptions\RestException; abstract class Schema implements ISchema { public function __construct($object = null) { if ($object === null) { return; } if (gettype($object) !== 'object') { throw new RestException('Schema constructor expects object or null as parameter', [ 'parameter' => $object, ]); } foreach (get_object_vars($object) as $name => $value) { $this->{$name} = $value; } } public function __get($name) { if (!isset($this->{$name})) { throw new RestException( 'Trying to access undefined property ' . $name, [] ); } } abstract public function schema(); }
<?php namespace Fathomminds\Rest; use Fathomminds\Rest\Contracts\ISchema; use Fathomminds\Rest\Schema\TypeValidators\ValidatorFactory; use Fathomminds\Rest\Exceptions\RestException; abstract class Schema implements ISchema { public function __construct($object = null) { if ($object === null) { return; } if (gettype($object) !== 'object') { throw new RestException('Schema constructor expects object or null as parameter', [ 'parameter' => $object, ]); } foreach (get_object_vars($object) as $name => $value) { $this->{$name} = $value; } } public function __get($name) { if (!isset($this->{$name})) { throw new RestException() { 'Trying to access undefined property ' . $name, [] } } } abstract public function schema(); }
Update to pet model for provisioner
from google.appengine.ext import ndb # This is to store alternate linart versions of the same pets class SpeciesVersion(ndb.Model): name = ndb.StringProperty() base_image = ndb.StringProperty() base_psd = ndb.StringProperty() default_image = ndb.StringProperty() # Pets are divided into species and species are divided into variations class Species(ndb.Model): name = ndb.StringProperty() versions = ndb.StructuredProperty(SpeciesVersion) description = ndb.TextProperty() class SpeciesVariation(ndb.Model): species_id = ndb.StringProperty() name = ndb.StringProperty() description = ndb.TextProperty() class Pet(ndb.Model): pet_id = ndb.StringProperty() owner_id = ndb.IntegerProperty() variation_key = ndb.KeyProperty() # Only set if the pet is a variation species_name = ndb.StringProperty() # Note the denormalization # Personal profile information for the pet name = ndb.StringProperty() css = ndb.TextProperty() description = ndb.TextProperty() # If either of these is set to a number other than 0, the pet is for sale ss_price = ndb.IntegerProperty(default=0) cc_price = ndb.IntegerProperty(default=0)
from google.appengine.ext import ndb # This is to store alternate linart versions of the same pets class SpeciesVersion(ndb.Model): name = ndb.StringProperty() base_image = ndb.StringProperty() base_psd = ndb.StringProperty() default_image = ndb.StringProperty() # Pets are divided into species and species are divided into variations class Species(ndb.Model): name = ndb.StringProperty(indexed=True) versions = ndb.StructuredProperty(SpeciesVersion, repeated=True) description = ndb.StringProperty() class SpeciesVariation(ndb.Model): species_key = ndb.KeyProperty(indexed=True) name = ndb.StringProperty(indexed=True) description = ndb.StringProperty() class Pet(ndb.Model): user_key = ndb.KeyProperty(indexed=True) variation_key = ndb.KeyProperty(indexed=True) # Only set if the pet is a variation species_name = ndb.StringProperty(indexed=True) # Note the denormalization # Personal profile information for the pet name = ndb.StringProperty() css = ndb.StringProperty() description = ndb.StringProperty() # If either of these is set to a number other than 0, the pet is for sale ss_price = ndb.IntegerProperty(default=0, indexed=True) cc_price = ndb.IntegerProperty(default=0, indexed=True)
Add client routes in production
const http = require('http'); const path = require('path'); const bodyParser = require('body-parser'); const cors = require('cors'); const express = require('express'); const isProduction = process.env.NODE_ENV === 'production'; if (!isProduction) require('dotenv').config(); var app = express(); const PORT = process.env.PORT || 4000; const server = http.createServer(app); const io = require('socket.io')(server, { origins: '*:*' }); // Attach the io instance to the express app object // to make it accessible from the routes app.io = io; io.on('connection', (socket) => { console.log('New client connected'); }); app.use(bodyParser.urlencoded({ extended: true })) .use(bodyParser.json()) .use(cors({ origin: process.env.CLIENT_URL || '*', allowedHeaders: 'Origin, X-Requested-With, Content-Type, Accept' })) .use(express.static(path.resolve(__dirname, 'build'))) .use('/', require('./routes')); // Render the client routes if any other URL is passed in // Do this ony in production. The local client server is used otherwise if (isProduction) { app.get('*', (req, res) => { res.sendFile(path.resolve(__dirname, 'build', 'index.html')); }); } // Must use http server as listener rather than express app server.listen(PORT, () => console.log(`Listening on ${ PORT }`));
const http = require('http'); const bodyParser = require('body-parser'); const cors = require('cors'); const express = require('express'); const isProduction = process.env.NODE_ENV === 'production'; if (!isProduction) require('dotenv').config(); var app = express(); const PORT = process.env.PORT || 4000; const server = http.createServer(app); const io = require('socket.io')(server, { origins: '*:*' }); // Attach the io instance to the express app object // to make it accessible from the routes app.io = io; io.on('connection', (socket) => { console.log('New client connected'); }); app.use(bodyParser.urlencoded({ extended: true })) .use(bodyParser.json()) .use(cors({ origin: process.env.CLIENT_URL || '*', allowedHeaders: 'Origin, X-Requested-With, Content-Type, Accept' })) .use(express.static('public')) .use('/', require('./routes')); // Must use http server as listener rather than express app server.listen(PORT, () => console.log(`Listening on ${ PORT }`));
Exclude tests and cmt folder from installed packages.
from setuptools import setup, find_packages import versioneer def read_requirements(): import os path = os.path.dirname(os.path.abspath(__file__)) requirements_file = os.path.join(path, 'requirements.txt') try: with open(requirements_file, 'r') as req_fp: requires = req_fp.read().split() except IOError: return [] else: return [require.split() for require in requires] setup(name='PyMT', version=versioneer.get_version(), cmdclass=versioneer.get_cmdclass(), description='The CSDMS Python Modeling Toolkit', author='Eric Hutton', author_email='huttone@colorado.edu', url='http://csdms.colorado.edu', setup_requires=['setuptools', ], packages=find_packages(exclude=("tests*", "cmt")), entry_points={ 'console_scripts': [ 'cmt-config=cmt.cmd.cmt_config:main', ], }, )
from setuptools import setup, find_packages import versioneer def read_requirements(): import os path = os.path.dirname(os.path.abspath(__file__)) requirements_file = os.path.join(path, 'requirements.txt') try: with open(requirements_file, 'r') as req_fp: requires = req_fp.read().split() except IOError: return [] else: return [require.split() for require in requires] setup(name='PyMT', version=versioneer.get_version(), cmdclass=versioneer.get_cmdclass(), description='The CSDMS Python Modeling Toolkit', author='Eric Hutton', author_email='huttone@colorado.edu', url='http://csdms.colorado.edu', setup_requires=['setuptools', ], packages=find_packages(), entry_points={ 'console_scripts': [ 'cmt-config=cmt.cmd.cmt_config:main', ], }, )
Add a test of the linearity of scalar multiplication
import pytest # type: ignore from hypothesis import given from hypothesis.strategies import floats from utils import vectors from ppb_vector import Vector2 @pytest.mark.parametrize("x, y, expected", [ (Vector2(6, 1), 0, Vector2(0, 0)), (Vector2(6, 1), 2, Vector2(12, 2)), (Vector2(0, 0), 3, Vector2(0, 0)), (Vector2(-1.5, 2.4), -2, Vector2(3.0, -4.8)), (Vector2(1, 2), 0.1, Vector2(0.1, 0.2)) ]) def test_scalar_multiplication(x, y, expected): assert x * y == expected @given( x=floats(min_value=-1e75, max_value=1e75), y=floats(min_value=-1e75, max_value=1e75), v=vectors(max_magnitude=1e150) ) def test_scalar_associative(x: float, y: float, v: Vector2): left = (x * y) * v right = x * (y * v) assert left.isclose(right) @given( l=floats(min_value=-1e150, max_value=1e150), x=vectors(max_magnitude=1e150), y=vectors(max_magnitude=1e150), ) def test_scalar_linear(l: float, x: Vector2, y: Vector2): assert (l * (x + y)).isclose(l*x + l*y)
import pytest # type: ignore from hypothesis import given from hypothesis.strategies import floats from utils import vectors from ppb_vector import Vector2 @pytest.mark.parametrize("x, y, expected", [ (Vector2(6, 1), 0, Vector2(0, 0)), (Vector2(6, 1), 2, Vector2(12, 2)), (Vector2(0, 0), 3, Vector2(0, 0)), (Vector2(-1.5, 2.4), -2, Vector2(3.0, -4.8)), (Vector2(1, 2), 0.1, Vector2(0.1, 0.2)) ]) def test_scalar_multiplication(x, y, expected): assert x * y == expected @given( x=floats(min_value=-1e75, max_value=1e75), y=floats(min_value=-1e75, max_value=1e75), v=vectors(max_magnitude=1e150) ) def test_scalar_associative(x: float, y: float, v: Vector2): left = (x * y) * v right = x * (y * v) assert left.isclose(right)
Fix the testing endpoint's root set op
package consul import ( "github.com/hashicorp/consul/agent/structs" ) // Test is an RPC endpoint that is only available during `go test` when // `TestEndpoint` is called. This is not and must not ever be available // during a real running Consul agent, since it this endpoint bypasses // critical ACL checks. type Test struct { // srv is a pointer back to the server. srv *Server } // ConnectCASetRoots sets the current CA roots state. func (s *Test) ConnectCASetRoots( args []*structs.CARoot, reply *interface{}) error { // Get the highest index state := s.srv.fsm.State() idx, _, err := state.CARoots(nil) if err != nil { return err } // Commit resp, err := s.srv.raftApply(structs.ConnectCARequestType, &structs.CARequest{ Op: structs.CAOpSetRoots, Index: idx, Roots: args, }) if err != nil { s.srv.logger.Printf("[ERR] consul.test: Apply failed %v", err) return err } if respErr, ok := resp.(error); ok { return respErr } return nil }
package consul import ( "github.com/hashicorp/consul/agent/structs" ) // Test is an RPC endpoint that is only available during `go test` when // `TestEndpoint` is called. This is not and must not ever be available // during a real running Consul agent, since it this endpoint bypasses // critical ACL checks. type Test struct { // srv is a pointer back to the server. srv *Server } // ConnectCASetRoots sets the current CA roots state. func (s *Test) ConnectCASetRoots( args []*structs.CARoot, reply *interface{}) error { // Get the highest index state := s.srv.fsm.State() idx, _, err := state.CARoots(nil) if err != nil { return err } // Commit resp, err := s.srv.raftApply(structs.ConnectCARequestType, &structs.CARequest{ Op: structs.CAOpSet, Index: idx, Roots: args, }) if err != nil { s.srv.logger.Printf("[ERR] consul.test: Apply failed %v", err) return err } if respErr, ok := resp.(error); ok { return respErr } return nil }
Use the (L1 C2) form to report node positions here as well
/* * Copyright (C) 2007 Reto Schuettel, Robin Stocker * * IFS Institute for Software, HSR Rapperswil, Switzerland * */ package ch.hsr.ifs.pystructure.typeinference.model.definitions; import org.python.pydev.parser.jython.ast.Assign; import ch.hsr.ifs.pystructure.typeinference.model.base.IModule; import ch.hsr.ifs.pystructure.typeinference.model.base.NameAdapter; /** * Definition of a variable by an assignment. */ public class AssignDefinition extends Definition<Assign> { private final Value value; public AssignDefinition(IModule module, NameAdapter name, Assign assign, Value value) { super(module, name, assign); this.value = value; } public String toString() { return "Variable " + getName() + getNodePosition(); } public Value getValue() { return value; } }
/* * Copyright (C) 2007 Reto Schuettel, Robin Stocker * * IFS Institute for Software, HSR Rapperswil, Switzerland * */ package ch.hsr.ifs.pystructure.typeinference.model.definitions; import org.python.pydev.parser.jython.ast.Assign; import ch.hsr.ifs.pystructure.typeinference.model.base.IModule; import ch.hsr.ifs.pystructure.typeinference.model.base.NameAdapter; /** * Definition of a variable by an assignment. */ public class AssignDefinition extends Definition<Assign> { private final Value value; public AssignDefinition(IModule module, NameAdapter name, Assign assign, Value value) { super(module, name, assign); this.value = value; } public String toString() { return "Variable " + getName() + " defined at line " + getNode().beginLine + ", column " + getNode().beginColumn; } public Value getValue() { return value; } }
Rename the filename argument to spreadsheet.
from qiprofile_rest_client.helpers import database from qiprofile_rest_client.model.subject import Subject from qiprofile_rest_client.model.imaging import Session from . import (clinical, imaging) def update(project, collection, subject, session, spreadsheet): """ Updates the qiprofile database from the clinical spreadsheet and XNAT database for the given session. :param project: the XNAT project name :param collection: the image collection name :param subject: the subject number :param session: the XNAT session number :param spreadsheet: the spreadsheet input file location :param modeling_technique: the modeling technique """ # Get or create the subject database subject. key = dict(project=project, collection=collection, number=subject) sbj = database.get_or_create(Subject, key) # Update the clinical information from the XLS input. clinical.update(sbj, spreadsheet) # Update the imaging information from XNAT. imaging.update(sbj, session)
from qiprofile_rest_client.helpers import database from qiprofile_rest_client.model.subject import Subject from qiprofile_rest_client.model.imaging import Session from . import (clinical, imaging) def update(project, collection, subject, session, filename): """ Updates the qiprofile database from the clinical spreadsheet and XNAT database for the given session. :param project: the XNAT project name :param collection: the image collection name :param subject: the subject number :param session: the XNAT session number :param filename: the XLS input file location """ # Get or create the subject database subject. key = dict(project=project, collection=collection, number=subject) sbj = database.get_or_create(Subject, key) # Update the clinical information from the XLS input. clinical.update(sbj, filename) # Update the imaging information from XNAT. imaging.update(sbj, session)
Update image content type for Postgres
package com.leevilehtonen.cookagram.domain; import org.hibernate.annotations.Type; import org.springframework.data.jpa.domain.AbstractPersistable; import javax.persistence.Entity; @Entity public class ImageEntity extends AbstractPersistable<Long> { private String name; private String mediaType; private Long size; @Type(type = "org.hibernate.type.BinaryType") private byte[] content; public byte[] getContent() { return content; } public void setContent(byte[] content) { this.content = content; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getMediaType() { return mediaType; } public void setMediaType(String mediaType) { this.mediaType = mediaType; } public Long getSize() { return size; } public void setSize(Long size) { this.size = size; } }
package com.leevilehtonen.cookagram.domain; import org.springframework.data.jpa.domain.AbstractPersistable; import javax.persistence.Entity; import javax.persistence.Lob; @Entity public class ImageEntity extends AbstractPersistable<Long> { private String name; private String mediaType; private Long size; @Lob private byte[] content; public byte[] getContent() { return content; } public void setContent(byte[] content) { this.content = content; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getMediaType() { return mediaType; } public void setMediaType(String mediaType) { this.mediaType = mediaType; } public Long getSize() { return size; } public void setSize(Long size) { this.size = size; } }
Update order of sinin chai and jquery for Phanton test as well
module.exports = function(config) { config.set({ basePath: '', frameworks: ['mocha', 'chai-jquery', 'jquery-1.11.0', 'sinon-chai', 'chai', 'fixture'], files: [ 'public/javascripts/vendor/d3.v3.min.js', 'public/javascripts/vendor/raphael-min.js', 'public/javascripts/vendor/morris.min.js', 'public/javascripts/helpers/helper.js', 'public/javascripts/traffic.js', 'tests/**/*Spec.js', 'tests/fixtures/**/*' ], exclude: [ '**/*.swp' ], preprocessors: { 'public/javascripts/*.js': ['coverage'], 'tests/**/*.json' : ['json_fixtures'] }, jsonFixturesPreprocessor: { variableName: '__json__' }, reporters: ['progress', 'coverage', 'coveralls'], coverageReporter: { reporters: [ { type: 'html', subdir: 'report-html' }, { type: 'lcov', subdir: 'lcov-report' }, ], }, port: 9876, colors: true, logLevel: config.LOG_INFO, autoWatch: true, browsers: ['PhantomJS'], singleRun: false }); };
module.exports = function(config) { config.set({ basePath: '', frameworks: ['mocha', 'chai-jquery', 'jquery-2.1.0', 'chai', 'sinon-chai', 'fixture'], files: [ 'public/javascripts/vendor/d3.v3.min.js', 'public/javascripts/vendor/raphael-min.js', 'public/javascripts/vendor/morris.min.js', 'public/javascripts/helpers/helper.js', 'public/javascripts/traffic.js', 'tests/**/*Spec.js', 'tests/fixtures/**/*' ], exclude: [ '**/*.swp' ], preprocessors: { 'public/javascripts/*.js': ['coverage'], 'tests/**/*.json' : ['json_fixtures'] }, jsonFixturesPreprocessor: { variableName: '__json__' }, reporters: ['progress', 'coverage', 'coveralls'], coverageReporter: { reporters: [ { type: 'html', subdir: 'report-html' }, { type: 'lcov', subdir: 'lcov-report' }, ], }, port: 9876, colors: true, logLevel: config.LOG_INFO, autoWatch: true, browsers: ['PhantomJS'], singleRun: false }); };
Send schema info error as 400 This assume schema info failure is due to user input, not application code. This could be that the server is unavailable however. Regardless it is something to be expected as opposed to an internal server error
require('../typedefs'); const router = require('express').Router(); const mustHaveConnectionAccess = require('../middleware/must-have-connection-access.js'); const ConnectionClient = require('../lib/connection-client'); const wrap = require('../lib/wrap'); /** * @param {Req} req * @param {Res} res */ async function getSchemaInfo(req, res) { const { models, user } = req; const { connectionId } = req.params; const reload = req.query.reload === 'true'; const conn = await models.connections.findOneById(connectionId); if (!conn) { return res.utils.notFound(); } const connectionClient = new ConnectionClient(conn, user); const schemaCacheId = connectionClient.getSchemaCacheId(); let schemaInfo = await models.schemaInfo.getSchemaInfo(schemaCacheId); if (schemaInfo && !reload) { return res.utils.data(schemaInfo); } try { schemaInfo = await connectionClient.getSchema(); } catch (error) { // Assumption is that error is due to user configuration // letting it bubble up results in 500, but it should be 400 return res.utils.error(error); } if (Object.keys(schemaInfo).length) { await models.schemaInfo.saveSchemaInfo(schemaCacheId, schemaInfo); } return res.utils.data(schemaInfo); } router.get( '/api/schema-info/:connectionId', mustHaveConnectionAccess, wrap(getSchemaInfo) ); module.exports = router;
require('../typedefs'); const router = require('express').Router(); const mustHaveConnectionAccess = require('../middleware/must-have-connection-access.js'); const ConnectionClient = require('../lib/connection-client'); const wrap = require('../lib/wrap'); /** * @param {Req} req * @param {Res} res */ async function getSchemaInfo(req, res) { const { models, user } = req; const { connectionId } = req.params; const reload = req.query.reload === 'true'; const conn = await models.connections.findOneById(connectionId); if (!conn) { return res.utils.notFound(); } const connectionClient = new ConnectionClient(conn, user); const schemaCacheId = connectionClient.getSchemaCacheId(); let schemaInfo = await models.schemaInfo.getSchemaInfo(schemaCacheId); if (schemaInfo && !reload) { return res.utils.data(schemaInfo); } schemaInfo = await connectionClient.getSchema(); if (Object.keys(schemaInfo).length) { await models.schemaInfo.saveSchemaInfo(schemaCacheId, schemaInfo); } return res.utils.data(schemaInfo); } router.get( '/api/schema-info/:connectionId', mustHaveConnectionAccess, wrap(getSchemaInfo) ); module.exports = router;
Change http -> https. Latest browser need https
module.exports = { website: { assets: "./assets", css: [ "facebook.css" ], js: [ "https://connect.facebook.net/en_US/all.js", "facebook.js" ], html: { "body:start": function() { var appKey = this.options.pluginsConfig.facebook.appKey; return '<div class="fb_id" data-id="' + appKey +'"></div>'; } } }, hooks: { "page": function(page) { page.sections[0].content += '<br><div class="fb-comments" data-numposts="5" data-width="100%"></div>'; return page; } } };
module.exports = { website: { assets: "./assets", css: [ "facebook.css" ], js: [ "http://connect.facebook.net/en_US/all.js", "facebook.js" ], html: { "body:start": function() { var appKey = this.options.pluginsConfig.facebook.appKey; return '<div class="fb_id" data-id="' + appKey +'"></div>'; } } }, hooks: { "page": function(page) { page.sections[0].content += '<br><div class="fb-comments" data-numposts="5" data-width="100%"></div>'; return page; } } };
Change comment about debugging output.
package rpcd import ( "errors" "fmt" "github.com/Symantec/Dominator/proto/imageserver" ) func (t *rpcType) AddImage(request imageserver.AddImageRequest, reply *imageserver.AddImageResponse) error { if imageDataBase.CheckImage(request.ImageName) { return errors.New("image already exists") } // Verify all objects are available. objectServer := imageDataBase.ObjectServer() for _, inode := range request.Image.FileSystem.RegularInodeTable { found, err := objectServer.CheckObject(inode.Hash) if err != nil { return err } if !found { return errors.New(fmt.Sprintf("object: %x is not available", inode.Hash)) } } // TODO(rgooch): Remove debugging output. fmt.Printf("AddImage(%s)\n", request.ImageName) return imageDataBase.AddImage(request.Image, request.ImageName) }
package rpcd import ( "errors" "fmt" "github.com/Symantec/Dominator/proto/imageserver" ) func (t *rpcType) AddImage(request imageserver.AddImageRequest, reply *imageserver.AddImageResponse) error { if imageDataBase.CheckImage(request.ImageName) { return errors.New("image already exists") } // Verify all objects are available. objectServer := imageDataBase.ObjectServer() for _, inode := range request.Image.FileSystem.RegularInodeTable { found, err := objectServer.CheckObject(inode.Hash) if err != nil { return err } if !found { return errors.New(fmt.Sprintf("object: %x is not available", inode.Hash)) } } fmt.Printf("AddImage(%s)\n", request.ImageName) // HACK return imageDataBase.AddImage(request.Image, request.ImageName) }
Add all tests to the suite
/** * Copyright 2017 the original author or authors. * * 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. */ package com.allegient.candidate.stockquote; import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; import com.allegient.candidate.stockquote.app.QuoteFinderTest; import com.allegient.candidate.stockquote.datasource.FakeQuoteGeneratorTest; import com.allegient.candidate.stockquote.datasource.InMemoryDataSourceTest; import com.allegient.candidate.stockquote.datasource.RandomPriceGeneratorTest; import com.allegient.candidate.stockquote.http.QuoteControllerTest; @RunWith(Suite.class) @SuiteClasses({ QuoteFinderTest.class, FakeQuoteGeneratorTest.class, InMemoryDataSourceTest.class, RandomPriceGeneratorTest.class, QuoteControllerTest.class }) /** * This class lets us run all the tests easily so we can verify coverage in * Eclipse * * @author Jeff Butler * */ public class RunAllTests { }
/** * Copyright 2017 the original author or authors. * * 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. */ package com.allegient.candidate.stockquote; import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; import com.allegient.candidate.stockquote.app.QuoteFinderTest; import com.allegient.candidate.stockquote.http.QuoteControllerTest; @RunWith(Suite.class) @SuiteClasses({ QuoteFinderTest.class, QuoteControllerTest.class }) /** * This class lets us run all the tests easily so we can verify coverage in * Eclipse * * @author Jeff Butler * */ public class RunAllTests { }
typing-status: Initialize lastTypingStart as "long ago", not "now". Similarly to the parent commit for presence, this was causing us not to report the user typing in the first 15 seconds after starting the app.
/* @flow strict-local */ import differenceInSeconds from 'date-fns/difference_in_seconds'; import type { Dispatch, GetState, Narrow } from '../types'; import * as api from '../api'; import { PRESENCE_RESPONSE } from '../actionConstants'; import { getAuth, tryGetAuth } from '../selectors'; import { isPrivateOrGroupNarrow } from '../utils/narrow'; let lastReportPresence = new Date(0); let lastTypingStart = new Date(0); export const reportPresence = (hasFocus: boolean = true, newUserInput: boolean = false) => async ( dispatch: Dispatch, getState: GetState, ) => { const auth = tryGetAuth(getState()); if (!auth) { return; // not logged in } if (differenceInSeconds(new Date(), lastReportPresence) < 60) { return; } lastReportPresence = new Date(); const response = await api.reportPresence(auth, hasFocus, newUserInput); dispatch({ type: PRESENCE_RESPONSE, presence: response.presences, serverTimestamp: response.server_timestamp, }); }; export const sendTypingEvent = (narrow: Narrow) => async ( dispatch: Dispatch, getState: GetState, ) => { if (!isPrivateOrGroupNarrow(narrow)) { return; } if (differenceInSeconds(new Date(), lastTypingStart) > 15) { const auth = getAuth(getState()); api.typing(auth, narrow[0].operand, 'start'); lastTypingStart = new Date(); } };
/* @flow strict-local */ import differenceInSeconds from 'date-fns/difference_in_seconds'; import type { Dispatch, GetState, Narrow } from '../types'; import * as api from '../api'; import { PRESENCE_RESPONSE } from '../actionConstants'; import { getAuth, tryGetAuth } from '../selectors'; import { isPrivateOrGroupNarrow } from '../utils/narrow'; let lastReportPresence = new Date(0); let lastTypingStart = new Date(); export const reportPresence = (hasFocus: boolean = true, newUserInput: boolean = false) => async ( dispatch: Dispatch, getState: GetState, ) => { const auth = tryGetAuth(getState()); if (!auth) { return; // not logged in } if (differenceInSeconds(new Date(), lastReportPresence) < 60) { return; } lastReportPresence = new Date(); const response = await api.reportPresence(auth, hasFocus, newUserInput); dispatch({ type: PRESENCE_RESPONSE, presence: response.presences, serverTimestamp: response.server_timestamp, }); }; export const sendTypingEvent = (narrow: Narrow) => async ( dispatch: Dispatch, getState: GetState, ) => { if (!isPrivateOrGroupNarrow(narrow)) { return; } if (differenceInSeconds(new Date(), lastTypingStart) > 15) { const auth = getAuth(getState()); api.typing(auth, narrow[0].operand, 'start'); lastTypingStart = new Date(); } };
Add database, params and bindings in query
<?php /** * @author @fabfuel <fabian@fabfuel.de> * @created 14.11.14, 08:39 */ namespace Fabfuel\Prophiler\Plugin\Phalcon\Db; use Fabfuel\Prophiler\Benchmark\BenchmarkInterface; use Fabfuel\Prophiler\Plugin\PluginAbstract; use Phalcon\Events\Event; use Phalcon\Db\Adapter; /** * Class AdapterPlugin */ class AdapterPlugin extends PluginAbstract { /** * @var BenchmarkInterface */ private $benchmark; /** * Start the query benchmark * * @param Event $event * @param Adapter $database */ public function beforeQuery(Event $event, Adapter $database) { $metadata = [ 'query' => $database->getSQLStatement(), 'params' => $database->getSQLVariables(), 'bindtypes' => $database->getSQLBindTypes() ]; $desc = $database->getDescriptor(); if (isset($desc['dbname'])) { $metadata['database'] = $desc['dbname']; } $this->benchmark = $this->getProfiler()->start(get_class($event->getSource()) . '::query', $metadata, 'Database'); } /** * Stop the query benchmark */ public function afterQuery() { $this->getProfiler()->stop($this->benchmark); } }
<?php /** * @author @fabfuel <fabian@fabfuel.de> * @created 14.11.14, 08:39 */ namespace Fabfuel\Prophiler\Plugin\Phalcon\Db; use Fabfuel\Prophiler\Benchmark\BenchmarkInterface; use Fabfuel\Prophiler\Plugin\PluginAbstract; use Phalcon\Events\Event; use Phalcon\Db\Adapter; /** * Class Dispatcher * @package Rocket\Toolbar\Plugin */ class AdapterPlugin extends PluginAbstract { /** * @var BenchmarkInterface */ private $benchmark; /** * Start the query benchmark * * @param Event $event * @param Adapter $database */ public function beforeQuery(Event $event, Adapter $database) { $metadata = [ 'query' => $database->getSQLStatement() ]; $this->benchmark = $this->getProfiler()->start(get_class($event->getSource()) . '::query', $metadata, 'Database'); } /** * Stop the query benchmark */ public function afterQuery() { $this->getProfiler()->stop($this->benchmark); } }
Fix incorrect method call after a previous refactoring
package org.metaborg.meta.lang.dynsem.interpreter.nabl2.sg.nodes; import org.metaborg.meta.lang.dynsem.interpreter.nabl2.NaBL2SolutionUtils; import org.metaborg.meta.lang.dynsem.interpreter.nabl2.sg.TermIndex; import org.metaborg.meta.lang.dynsem.interpreter.nodes.building.NativeOpBuild; import org.metaborg.meta.lang.dynsem.interpreter.nodes.building.TermBuild; import org.metaborg.meta.lang.dynsem.interpreter.terms.ITerm; import com.oracle.truffle.api.dsl.NodeChild; import com.oracle.truffle.api.dsl.Specialization; import com.oracle.truffle.api.source.SourceSection; @NodeChild(value = "term", type = TermBuild.class) public abstract class GetTopLevelTermIndex extends NativeOpBuild { public GetTopLevelTermIndex(SourceSection source) { super(source); } @Specialization public TermIndex executeTermIndex(ITerm term) { mb.nabl2.stratego.TermIndex termIndex = NaBL2SolutionUtils.getTermIndex(term.getStrategoTerm()); return new TermIndex(termIndex.getResource(), 0); } public static GetTopLevelTermIndex create(SourceSection source, TermBuild term) { return ScopeNodeFactories.createGetTopLevelTermIndex(source, term); } }
package org.metaborg.meta.lang.dynsem.interpreter.nabl2.sg.nodes; import org.metaborg.meta.lang.dynsem.interpreter.nabl2.NaBL2SolutionUtils; import org.metaborg.meta.lang.dynsem.interpreter.nabl2.sg.TermIndex; import org.metaborg.meta.lang.dynsem.interpreter.nodes.building.NativeOpBuild; import org.metaborg.meta.lang.dynsem.interpreter.nodes.building.TermBuild; import org.metaborg.meta.lang.dynsem.interpreter.terms.ITerm; import com.oracle.truffle.api.dsl.NodeChild; import com.oracle.truffle.api.dsl.Specialization; import com.oracle.truffle.api.source.SourceSection; @NodeChild(value = "term", type = TermBuild.class) public abstract class GetTopLevelTermIndex extends NativeOpBuild { public GetTopLevelTermIndex(SourceSection source) { super(source); } @Specialization public TermIndex executeTermIndex(ITerm term) { mb.nabl2.stratego.TermIndex termIndex = NaBL2SolutionUtils.getTermIndex(nabl2Context(), term.getStrategoTerm()); return new TermIndex(termIndex.getResource(), 0); } public static GetTopLevelTermIndex create(SourceSection source, TermBuild term) { return ScopeNodeFactories.createGetTopLevelTermIndex(source, term); } }
twitch: Add error checking in API response
import requests from allauth.socialaccount.providers.oauth2.client import OAuth2Error from allauth.socialaccount.providers.oauth2.views import ( OAuth2Adapter, OAuth2CallbackView, OAuth2LoginView, ) from .provider import TwitchProvider class TwitchOAuth2Adapter(OAuth2Adapter): provider_id = TwitchProvider.id access_token_url = 'https://api.twitch.tv/kraken/oauth2/token' authorize_url = 'https://api.twitch.tv/kraken/oauth2/authorize' profile_url = 'https://api.twitch.tv/kraken/user' def complete_login(self, request, app, token, **kwargs): params = {"oauth_token": token.token, "client_id": app.client_id} response = requests.get(self.profile_url, params=params) data = response.json() if response.status_code >= 400: error = data.get("error", "") message = data.get("message", "") raise OAuth2Error("Twitch API Error: %s (%s)" % (error, message)) if "_id" not in data: raise OAuth2Error("Invalid data from Twitch API: %r" % (data)) return self.get_provider().sociallogin_from_response(request, data) oauth2_login = OAuth2LoginView.adapter_view(TwitchOAuth2Adapter) oauth2_callback = OAuth2CallbackView.adapter_view(TwitchOAuth2Adapter)
import requests from allauth.socialaccount.providers.oauth2.views import ( OAuth2Adapter, OAuth2CallbackView, OAuth2LoginView, ) from .provider import TwitchProvider class TwitchOAuth2Adapter(OAuth2Adapter): provider_id = TwitchProvider.id access_token_url = 'https://api.twitch.tv/kraken/oauth2/token' authorize_url = 'https://api.twitch.tv/kraken/oauth2/authorize' profile_url = 'https://api.twitch.tv/kraken/user' def complete_login(self, request, app, token, **kwargs): resp = requests.get( self.profile_url, params={'oauth_token': token.token, 'client_id': app.client_id}) extra_data = resp.json() return self.get_provider().sociallogin_from_response(request, extra_data) oauth2_login = OAuth2LoginView.adapter_view(TwitchOAuth2Adapter) oauth2_callback = OAuth2CallbackView.adapter_view(TwitchOAuth2Adapter)
Kill cache sessions for now.
from .base import * DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'docs', 'USER': 'postgres', # Not used with sqlite3. 'PASSWORD': '', 'HOST': 'golem', 'PORT': '', } } DEBUG = False TEMPLATE_DEBUG = False CELERY_ALWAYS_EAGER = False MEDIA_URL = 'http://media.readthedocs.org/' ADMIN_MEDIA_PREFIX = MEDIA_URL + 'admin/' CACHE_BACKEND = 'memcached://localhost:11211/' #SESSION_ENGINE = "django.contrib.sessions.backends.cached_db" HAYSTACK_SEARCH_ENGINE = 'solr' HAYSTACK_SOLR_URL = 'http://odin:8983/solr' try: from local_settings import * except: pass
from .base import * DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'docs', 'USER': 'postgres', # Not used with sqlite3. 'PASSWORD': '', 'HOST': 'golem', 'PORT': '', } } DEBUG = False TEMPLATE_DEBUG = False CELERY_ALWAYS_EAGER = False MEDIA_URL = 'http://media.readthedocs.org/' ADMIN_MEDIA_PREFIX = MEDIA_URL + 'admin/' CACHE_BACKEND = 'memcached://localhost:11211/' SESSION_ENGINE = "django.contrib.sessions.backends.cached_db" HAYSTACK_SEARCH_ENGINE = 'solr' HAYSTACK_SOLR_URL = 'http://odin:8983/solr' try: from local_settings import * except: pass
Fix sitemap memory consumption during generation - Defer ALL FireDepartment fields except for those required to create a sitemap - Was causing node startup to hang see #321
from django.contrib import sitemaps from firecares.firestation.models import FireDepartment from django.db.models import Max from django.core.urlresolvers import reverse class BaseSitemap(sitemaps.Sitemap): protocol = 'https' def items(self): return ['media', 'models_performance_score', 'models_community_risk', 'safe_grades', 'login', 'contact_us', 'firedepartment_list'] def priority(self, item): return 1 def location(self, item): return reverse(item) class DepartmentsSitemap(sitemaps.Sitemap): protocol = 'https' max_population = 1 def items(self): queryset = FireDepartment.objects.filter(archived=False).only('population', 'featured', 'name') self.max_population = queryset.aggregate(Max('population'))['population__max'] return queryset def location(self, item): return item.get_absolute_url() def priority(self, item): if item.featured is True: return 1 if item.population is None: return 0 # adding a bit to the total so featured items are always above others priority = item.population / float(self.max_population + 0.1) return priority def lastmod(self, item): return item.modified
from django.contrib import sitemaps from firecares.firestation.models import FireDepartment from django.db.models import Max from django.core.urlresolvers import reverse class BaseSitemap(sitemaps.Sitemap): protocol = 'https' def items(self): return ['media', 'models_performance_score', 'models_community_risk', 'safe_grades', 'login', 'contact_us', 'firedepartment_list'] def priority(self, item): return 1 def location(self, item): return reverse(item) class DepartmentsSitemap(sitemaps.Sitemap): protocol = 'https' max_population = 1 def items(self): queryset = FireDepartment.objects.filter(archived=False) self.max_population = queryset.aggregate(Max('population'))['population__max'] return queryset def location(self, item): return item.get_absolute_url() def priority(self, item): if item.featured is True: return 1 if item.population is None: return 0 # adding a bit to the total so featured items are always above others priority = item.population / float(self.max_population + 0.1) return priority def lastmod(self, item): return item.modified
Allow PhantomJS process to free stack frames
/* eslint-disable */ 'use strict'; var system = require('system'); var webpage = require('webpage'); var page; var methods = { exit: function(callback) { callback(true); }, open: function(url, callback) { page = webpage.create(); page.open(url, function(status) { callback(status === 'success'); }); }, evaluate: function(functionBody, callback) { callback(page.evaluate(new Function(functionBody))); }, sendEvent: function() { var params = Array.prototype.slice.call(arguments, 0, -1); var callback = arguments[arguments.length - 1]; page.sendEvent.apply(page, params); callback(true); } }; function processRequest() { var request = JSON.parse(system.stdin.readLine()); function callback(result) { system.stdout.writeLine(JSON.stringify({id: request.id, result: result})); if (request.method === 'exit') { phantom.exit(0); } else { setTimeout(processRequest, 0); } } methods[request.method].apply(null, request.params.concat(callback)); } processRequest();
/* eslint-disable */ 'use strict'; var system = require('system'); var webpage = require('webpage'); var page; var methods = { exit: function(callback) { callback(true); }, open: function(url, callback) { page = webpage.create(); page.open(url, function(status) { callback(status === 'success'); }); }, evaluate: function(functionBody, callback) { callback(page.evaluate(new Function(functionBody))); }, sendEvent: function() { var params = Array.prototype.slice.call(arguments, 0, -1); var callback = arguments[arguments.length - 1]; page.sendEvent.apply(page, params); callback(true); } }; function processRequest() { var request = JSON.parse(system.stdin.readLine()); function callback(result) { system.stdout.writeLine(JSON.stringify({id: request.id, result: result})); if (request.method === 'exit') { phantom.exit(0); } else { processRequest(); } } methods[request.method].apply(null, request.params.concat(callback)); } processRequest();
Include a __typename in the pull request result fixture
function createCommitResult(attrs = {}) { return { commit: { status: { contexts: [ {state: 'PASSED'} ] } } }; } export function createPullRequestResult(attrs = {}) { const o = { number: 0, repositoryID: 'repository0', states: null, headRefName: 'master', ...attrs, }; const commit = { id: 'commit0', }; if (o.states === null) { commit.status = null; } else { commit.status = { contexts: o.states.map((state, id) => ({state, id: `state${id}`})), }; } return { __typename: 'PullRequest', id: `pullrequest${o.number}`, number: o.number, title: `Pull Request ${o.number}`, url: `https://github.com/owner/repo/pulls/${o.number}`, author: { __typename: 'User', login: 'me', avatarUrl: 'https://avatars3.githubusercontent.com/u/000?v=4', id: 'user0' }, createdAt: '2018-06-12T14:50:08Z', headRefName: o.headRefName, repository: { id: o.repositoryID, }, commits: {nodes: [{commit, id: 'node0'}]}, } }
function createCommitResult(attrs = {}) { return { commit: { status: { contexts: [ {state: 'PASSED'} ] } } }; } export function createPullRequestResult(attrs = {}) { const o = { number: 0, repositoryID: 'repository0', states: null, headRefName: 'master', ...attrs, }; const commit = { id: 'commit0', }; if (o.states === null) { commit.status = null; } else { commit.status = { contexts: o.states.map((state, id) => ({state, id: `state${id}`})), }; } return { id: `pullrequest${o.number}`, number: o.number, title: `Pull Request ${o.number}`, url: `https://github.com/owner/repo/pulls/${o.number}`, author: { __typename: 'User', login: 'me', avatarUrl: 'https://avatars3.githubusercontent.com/u/000?v=4', id: 'user0' }, createdAt: '2018-06-12T14:50:08Z', headRefName: o.headRefName, repository: { id: o.repositoryID, }, commits: {nodes: [{commit, id: 'node0'}]}, } }
Remove --name from 'envy list'
from cloudenvy.envy import Envy class EnvyList(object): def __init__(self, argparser): self._build_subparser(argparser) def _build_subparser(self, subparsers): help_str = 'List all ENVys in your current project.' subparser = subparsers.add_parser('list', help=help_str, description=help_str) subparser.set_defaults(func=self.run) return subparser def run(self, config, args): envy = Envy(config) for server in envy.list_servers(): if server.name.startswith(envy.name): print server.name
from cloudenvy.envy import Envy class EnvyList(object): def __init__(self, argparser): self._build_subparser(argparser) def _build_subparser(self, subparsers): help_str = 'List all ENVys in your current project.' subparser = subparsers.add_parser('list', help=help_str, description=help_str) subparser.set_defaults(func=self.run) subparser.add_argument('-n', '--name', action='store', default='', help='Specify custom name for an ENVy.') return subparser def run(self, config, args): envy = Envy(config) for server in envy.list_servers(): if server.name.startswith(envy.name): print server.name
Fix equality statement to use === rather than ==.
Application.Services.factory('watcher', function () { var watcherService = {}; watcherService.watch = function (scope, variable, fn) { scope.$watch(variable, function (newval, oldval) { if (!newval && !oldval) { return; } else if (newval === "" && oldval) { fn(oldval); } else { fn(newval); } }); }; return watcherService; });
Application.Services.factory('watcher', function () { var watcherService = {}; watcherService.watch = function (scope, variable, fn) { scope.$watch(variable, function (newval, oldval) { if (!newval && !oldval) { return; } else if (newval == "" && oldval) { fn(oldval); } else { fn(newval); } }); }; return watcherService; });
Fix require once issue in faq taxonomy type
<?php if ( ! class_exists( 'FAQ_Taxonomy_Type' ) ) { require_once __DIR__ . '/faq-taxonomy-type.php'; } class FAQ_Extra_Taxonomy_Type extends FAQ_Taxonomy_Type { /** * Define our Taxonomy Type meta data. * * @return array */ public function meta() { return [ 'name' => 'FAQ Extra taxonomy', 'description' => 'This is a faq extra taxonomy', 'template' => 'pages/faq-extra-taxonomy.php' ]; } /** * Define our properties. */ public function register() { $this->box( 'Content', [ papi_property( [ 'description' => 'FAQ 2', 'post_type' => 'faq', 'type' => 'string', 'title' => 'Name' ] ) ] ); } }
<?php if ( ! class_exists( 'FAQ_Taxonomy_Type' ) ) { require_once __DIR__ . '/faq-Taxonomy-type.php'; } class FAQ_Extra_Taxonomy_Type extends FAQ_Taxonomy_Type { /** * Define our Taxonomy Type meta data. * * @return array */ public function meta() { return [ 'name' => 'FAQ Extra taxonomy', 'description' => 'This is a faq extra taxonomy', 'template' => 'pages/faq-extra-taxonomy.php' ]; } /** * Define our properties. */ public function register() { $this->box( 'Content', [ papi_property( [ 'description' => 'FAQ 2', 'post_type' => 'faq', 'type' => 'string', 'title' => 'Name' ] ) ] ); } }
Add new tab JSON field Review URL: https://codereview.chromium.org/14329012
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.sdk.internal.wip.protocol.input; import java.util.List; import org.chromium.sdk.internal.protocolparser.JsonOptionalField; import org.chromium.sdk.internal.protocolparser.JsonProtocolParseException; import org.chromium.sdk.internal.protocolparser.JsonSubtypeCasting; import org.chromium.sdk.internal.protocolparser.JsonType; @JsonType(subtypesChosenManually=true) public interface WipTabList { @JsonSubtypeCasting List<TabDescription> asTabList() throws JsonProtocolParseException; @JsonType interface TabDescription { String id(); String faviconUrl(); String title(); String url(); String thumbnailUrl(); // TODO: consider adding enum here String type(); @JsonOptionalField String description(); @JsonOptionalField String devtoolsFrontendUrl(); @JsonOptionalField String webSocketDebuggerUrl(); } }
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.sdk.internal.wip.protocol.input; import java.util.List; import org.chromium.sdk.internal.protocolparser.JsonOptionalField; import org.chromium.sdk.internal.protocolparser.JsonProtocolParseException; import org.chromium.sdk.internal.protocolparser.JsonSubtypeCasting; import org.chromium.sdk.internal.protocolparser.JsonType; @JsonType(subtypesChosenManually=true) public interface WipTabList { @JsonSubtypeCasting List<TabDescription> asTabList() throws JsonProtocolParseException; @JsonType interface TabDescription { String id(); String faviconUrl(); String title(); String url(); String thumbnailUrl(); // TODO: consider adding enum here String type(); @JsonOptionalField String devtoolsFrontendUrl(); @JsonOptionalField String webSocketDebuggerUrl(); } }
Replace let with var to support older node versions
'use strict' var postcss = require('postcss') var isVendorPrefixed = require('is-vendor-prefixed') module.exports = postcss.plugin('postcss-remove-prefixes', function (options) { if (!options) { options = {}; } var ignore = options.ignore ? Array.isArray(options.ignore) ? options.ignore : false : []; if (ignore === false) { throw TypeError("options.ignore must be an array") } for (var i = 0; i < ignore.length; ++i) { var value = ignore[i]; if (typeof value === "string") { value = new RegExp(value + "$", "i") } else if (value instanceof RegExp) { } else { throw TypeError("options.ignore values can either be a string or a regular expression") } ignore[i] = value; } return function removePrefixes(root, result) { root.walkDecls(function (declaration) { if (isVendorPrefixed(declaration.prop) || isVendorPrefixed(declaration.value)) { var isIgnored = false; for (var i = 0; i < ignore.length; ++i) { var value = ignore[i]; if (value.test(declaration.prop)) { isIgnored = true; break; } } if (!isIgnored) { declaration.remove() } } }) } })
'use strict' var postcss = require('postcss') var isVendorPrefixed = require('is-vendor-prefixed') module.exports = postcss.plugin('postcss-remove-prefixes', function (options) { if (!options) { options = {}; } let ignore = options.ignore ? Array.isArray(options.ignore) ? options.ignore : false : []; if (ignore === false) { throw TypeError("options.ignore must be an array") } for (let i = 0; i < ignore.length; ++i) { let value = ignore[i]; if (typeof value === "string") { value = new RegExp(value + "$", "i") } else if (value instanceof RegExp) { } else { throw TypeError("options.ignore values can either be a string or a regular expression") } ignore[i] = value; } return function removePrefixes(root, result) { root.walkDecls(function (declaration) { if (isVendorPrefixed(declaration.prop) || isVendorPrefixed(declaration.value)) { let isIgnored = false; for (let i = 0; i < ignore.length; ++i) { let value = ignore[i]; if (value.test(declaration.prop)) { isIgnored = true; break; } } if (!isIgnored) { declaration.remove() } } }) } })
Remove third dimension from image array
#!/usr/bin/env python import sys import time import zmq import numpy as np try: import progressbar except ImportError: progressbar = None try: import pylepton except ImportError: print "Couldn't import pylepton, using Dummy data!" Lepton = None # importing packages in parent folders is voodoo from common.Frame import Frame port = "5556" context = zmq.Context() socket = context.socket(zmq.PUB) socket.bind("tcp://*:{}".format(port)) widgets = ['Got ', progressbar.Counter(), ' frames (', progressbar.Timer(), ')'] pbar = progressbar.ProgressBar(widgets=widgets, maxval=progressbar.UnknownLength).start() if pylepton is not None: with pylepton.Lepton("/dev/spidev0.1") as lepton: n = 0 while True: arr, idx = lepton.capture() frame = Frame(idx, np.squeeze(arr)) #frame = Frame(-1, np.random.random_integers(4095, size=(60.,80.))) socket.send(frame.encode()) pbar.update(n) n += 1
#!/usr/bin/env python import sys import time import zmq import numpy as np try: import progressbar except ImportError: progressbar = None try: import pylepton except ImportError: print "Couldn't import pylepton, using Dummy data!" Lepton = None # importing packages in parent folders is voodoo from common.Frame import Frame port = "5556" context = zmq.Context() socket = context.socket(zmq.PUB) socket.bind("tcp://*:{}".format(port)) widgets = ['Got ', progressbar.Counter(), ' frames (', progressbar.Timer(), ')'] pbar = progressbar.ProgressBar(widgets=widgets, maxval=progressbar.UnknownLength).start() if pylepton is not None: with pylepton.Lepton("/dev/spidev0.1") as lepton: n = 0 while True: arr, idx = lepton.capture() frame = Frame(idx, arr) #frame = Frame(-1, np.random.random_integers(4095, size=(60.,80.))) socket.send(frame.encode()) pbar.update(n) n += 1
Fix warning about type safety
package com.suse.salt.netapi.calls.modules; import com.suse.salt.netapi.calls.LocalCall; import com.google.gson.reflect.TypeToken; import java.util.Arrays; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Optional; /** * salt.modules.state */ public class State { private State() { } public static LocalCall<Map<String, Object>> apply(List<String> mods) { return apply(mods, Optional.empty()); } public static LocalCall<Map<String, Object>> apply(String... mods) { return apply(Arrays.asList(mods), Optional.empty()); } public static LocalCall<Map<String, Object>> apply(List<String> mods, Optional<Map<String, Object>> pillar) { Map<String, Object> args = new LinkedHashMap<>(); args.put("mods", mods); if (pillar.isPresent()) { args.put("pillar", pillar.get()); } return new LocalCall<>("state.apply", Optional.empty(), Optional.of(args), new TypeToken<Map<String, Object>>() { }); } public static LocalCall<Object> showHighstate() { return new LocalCall<>("state.show_highstate", Optional.empty(), Optional.empty(), new TypeToken<Object>() { }); } }
package com.suse.salt.netapi.calls.modules; import com.suse.salt.netapi.calls.LocalCall; import com.google.gson.reflect.TypeToken; import java.util.Arrays; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Optional; /** * salt.modules.state */ public class State { private State() { } public static LocalCall<Map<String, Object>> apply(List<String> mods) { return apply(mods, Optional.empty()); } public static LocalCall<Map<String, Object>> apply(String... mods) { return apply(Arrays.asList(mods), Optional.empty()); } public static LocalCall<Map<String, Object>> apply(List<String> mods, Optional<Map<String, Object>> pillar) { Map<String, Object> args = new LinkedHashMap(); args.put("mods", mods); if (pillar.isPresent()) { args.put("pillar", pillar.get()); } return new LocalCall<>("state.apply", Optional.empty(), Optional.of(args), new TypeToken<Map<String, Object>>() { }); } public static LocalCall<Object> showHighstate() { return new LocalCall<>("state.show_highstate", Optional.empty(), Optional.empty(), new TypeToken<Object>() { }); } }
Remove namespace from network ext test Change-Id: Id9b97d67ac6745fe962a76ccd9c0e4f7cbed4a89
# 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 six from openstack.tests.functional import base class TestExtension(base.BaseFunctionalTest): def test_list_and_find(self): extensions = list(self.conn.network.extensions()) self.assertGreater(len(extensions), 0) for ext in extensions: self.assertIsInstance(ext.name, six.string_types) self.assertIsInstance(ext.alias, six.string_types)
# 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 six from openstack.tests.functional import base class TestExtension(base.BaseFunctionalTest): def test_list_and_find(self): extensions = list(self.conn.network.extensions()) self.assertGreater(len(extensions), 0) for ext in extensions: self.assertIsInstance(ext.name, six.string_types) self.assertIsInstance(ext.namespace, six.string_types) self.assertIsInstance(ext.alias, six.string_types)
Make sure the public repository remains compilable
package nl.rug.search.cpptool.api; import com.google.common.collect.ImmutableList; import nl.rug.search.cpptool.api.util.ContextTools; import javax.annotation.Nonnull; import java.util.Optional; public interface SourceFile { Iterable<Declaration> MISSING_DECLARATIONS_DUMMY = ImmutableList.of(); /** * @return */ @Nonnull String path(); /** * @return */ @Nonnull Iterable<SourceFile> includes(); /** * @return */ @Nonnull Iterable<SourceFile> includedBy(); /** * @return */ @Nonnull Optional<DeclContext> localContext(); /** * @return */ @Nonnull default Iterable<Declaration> declarations() { return localContext().map(ContextTools::traverseDeclarations).orElse(MISSING_DECLARATIONS_DUMMY); } }
package nl.rug.search.cpptool.api; import com.google.common.collect.ImmutableList; import nl.rug.search.cpptool.api.util.ContextTools; import javax.annotation.Nonnull; import java.util.Optional; public interface SourceFile { Iterable<Declaration> MISSING_DECLARATIONS_DUMMY = ImmutableList.of(); /** * @return */ @Nonnull String path(); /** * @return */ @Nonnull Iterable<SourceFile> includes(); /** * @return */ @Nonnull Iterable<SourceFile> includedBy(); /** * @return */ @Nonnull Optional<DeclContext> localContext(); /** * @return */ @Nonnull default Iterable<Declaration> declarations() { return localContext().map(ContextTools::traverseDecls).orElse(MISSING_DECLARATIONS_DUMMY); } }
Rename test to be more fitting
from scraper.tivix import get_list_of_tivix_members from scraper.tivix import get_random_tivix_member_bio def test_get_all_tivix_members(): members = get_list_of_tivix_members() assert members assert '/team-members/jack-muratore/' in members assert '/team-members/kyle-connors/' in members assert '/team-members/tan-nguyen/' in members assert '/team-members/will-liu/' in members assert '/team-members/george-bush/' not in members def test_bio_to_alexa_string(): bret_bio = get_random_tivix_member_bio('bret-waters') assert 'Bret Waters' in bret_bio assert 'ridiculously smart team' in bret_bio flavio_bio = get_random_tivix_member_bio('flavio-zhingri') assert 'hardest person' in flavio_bio
from scraper.tivix import get_list_of_tivix_members from scraper.tivix import get_random_tivix_member_bio def test_get_all_tivix_members(): members = get_list_of_tivix_members() assert members assert '/team-members/jack-muratore/' in members assert '/team-members/kyle-connors/' in members assert '/team-members/tan-nguyen/' in members assert '/team-members/will-liu/' in members assert '/team-members/george-bush/' not in members def test_output_random_bio(): bret_bio = get_random_tivix_member_bio('bret-waters') assert 'Bret Waters' in bret_bio assert 'ridiculously smart team' in bret_bio flavio_bio = get_random_tivix_member_bio('flavio-zhingri') assert 'hardest person' in flavio_bio
Load post id from route params, and create editor with it.
'use strict'; /* global CartUtility */ module.exports = function($scope, $location, $anchorScroll, $routeParams, $dataService, $editorService) { CartUtility.log('CartBlogNewCtrl'); $scope.aceEditor = $editorService.createEditor('markdown-edit', 'markdown-preview', $routeParams.postId, CartUtility.getPureAbsUrlFromLocation($location)); $scope.toggleToc = CartUtility.toggleToc; $scope.$on('$routeChangeStart', function() { CartUtility.log('CartBlogNewCtrl $routeChangeStart entered!'); // anchor link logic var prevHash = $location.hash(); if (typeof prevHash === 'string' && prevHash !== '') { $location.hash(CartUtility.escapeAnchorName(prevHash)); $anchorScroll(); $location.hash(prevHash); } }); };
'use strict'; /* global CartUtility */ module.exports = function($scope, $location, $anchorScroll, $dataService, $editorService) { CartUtility.log('CartBlogNewCtrl'); $scope.aceEditor = $editorService.createEditor('markdown-edit', 'markdown-preview', CartUtility.getPureAbsUrlFromLocation($location)); $scope.toggleToc = CartUtility.toggleToc; $scope.$on('$routeChangeStart', function() { CartUtility.log('CartBlogNewCtrl $routeChangeStart entered!'); // anchor link logic var prevHash = $location.hash(); if (typeof prevHash === 'string' && prevHash !== '') { $location.hash(CartUtility.escapeAnchorName(prevHash)); $anchorScroll(); $location.hash(prevHash); } }); };
Fix title when posting contact form
const router = require('express').Router() const contactController = require('./controllers/details') const contactEditController = require('./controllers/edit') const contactArchiveController = require('./controllers/archive') const contactInteractionController = require('./controllers/interactions') router .route('/create') .get(contactEditController.editDetails) .post(contactEditController.postDetails) router.get('/:contactId', contactController.getCommon, contactController.getDetails) router .route('/:contactId/edit') .get(contactController.getCommon, contactEditController.editDetails) .post(contactController.getCommon, contactEditController.postDetails) router.post('/:id/archive', contactArchiveController.archiveContact) router.get('/:id/unarchive', contactArchiveController.unarchiveContact) router.get('/:contactId/interactions', contactController.getCommon, contactInteractionController.getInteractions) module.exports = router
const router = require('express').Router() const contactController = require('./controllers/details') const contactEditController = require('./controllers/edit') const contactArchiveController = require('./controllers/archive') const contactInteractionController = require('./controllers/interactions') router .route('/create') .get(contactEditController.editDetails) .post(contactEditController.postDetails) router.get('/:contactId', contactController.getCommon, contactController.getDetails) router .route('/:contactId/edit') .get(contactController.getCommon, contactEditController.editDetails) .post(contactEditController.postDetails) router.post('/:id/archive', contactArchiveController.archiveContact) router.get('/:id/unarchive', contactArchiveController.unarchiveContact) router.get('/:contactId/interactions', contactController.getCommon, contactInteractionController.getInteractions) module.exports = router
Add module key to $entities arrays, fix typos
<?php $entities = array(); try { $res = civicrm_api3('FinancialType', 'getsingle', array("name" => "Donation", 'return' => array('id'))); } catch (CiviCRM_API3_Exception $e) { $res = NULL; } if (!$res) { $entities[] = array( 'name' => 'au.org.greens.raisely', 'module' => 'au.org.greens.raisely', 'entity' => 'FinancialType', 'params' => array( 'version' => 3, 'name' => 'Donation', 'description' => 'Donation', 'is_reserved' => 1, 'is_active' => 1, ), ); } try { $res = civicrm_api3('LocationType', 'getsingle', array('name' => 'Previous', 'return' => array('id'))); } catch (CiviCRM_API3_Exception $e) { $res = NULL; } if (!$res) { $entities[] = array( 'name' => 'au.org.greens.raisely', 'module' => 'au.org.greens.raisely', 'entity' => 'LocationType', 'params' => array( 'version' => 3, 'name' => 'Previous', 'description' => 'For old addresses no longer valid', 'is_active' => 1, 'is_reserved' => 1, 'is_default' => 0, ), ); } return $entities;
<?php $entities = array(); try { $res = civicrm_api3('FinancialType', 'getSingle', array("name" => "Donation", 'return' => array('id'))); } catch (CiviCRM_API3_Exception $e) { $res = NULL; } if (!$res) { $entites[] = array( 'name' => 'au.org.greens.raisely', 'entity' => 'FinancialType', 'params' => array( 'version' => 3, 'name' => 'Donation', 'description' => 'Donation', 'is_reserved' => 1, 'is_active' => 1, ), ); } try { $res = civicrm_api3('LocationType', 'getsingle', array('name' => 'Previous', 'return' => array('id'))); } catch (CiviCRM_API3_Exception $e) { $res = NULL; } if (!$res) { $entites[] = array( 'name' => 'au.org.greens.raisely', 'entity' => 'LocationType', 'params' => array( 'version' => 3, 'name' => 'Previous', 'description' => 'For old addresses no longer valid', 'is_active' => 1, 'is_reserved' => 1, 'is_default' => 0, ), ); } return $entites;
Rename sys modules access to web module
"""This module is for testing the online checker.""" import sys from unittest import TestCase ONLINE_CHECKER = sys.modules["Rainmeter.web.online_checker"] class TestRmDocOnlineChecker(TestCase): """Test of the online checks for Rainmeter Documentation using unittest.""" def test_is_rm_doc_online(self): """Rainmeter Documentation should be up to synchronize with it.""" is_online = ONLINE_CHECKER.is_rm_doc_online() self.assertTrue(is_online) class TestGithubOnlineChecker(TestCase): """Test of the online checks for Github using unittest.""" def test_is_gh_online(self): """Github should be up to download stuff from it.""" is_online = ONLINE_CHECKER.is_gh_online() self.assertTrue(is_online) class TestRawGithubOnlineChecker(TestCase): """Test of the online checks for Raw Github using unittest since raw is served from different service.""" def test_is_raw_gh_online(self): """Raw Github should be up to download stuff from it.""" is_online = ONLINE_CHECKER.is_gh_raw_online() self.assertTrue(is_online)
"""This module is for testing the online checker.""" import sys from unittest import TestCase ONLINE_CHECKER = sys.modules["Rainmeter.http.online_checker"] class TestRmDocOnlineChecker(TestCase): """Test of the online checks for Rainmeter Documentation using unittest.""" def test_is_rm_doc_online(self): """Rainmeter Documentation should be up to synchronize with it.""" is_online = ONLINE_CHECKER.is_rm_doc_online() self.assertTrue(is_online) class TestGithubOnlineChecker(TestCase): """Test of the online checks for Github using unittest.""" def test_is_gh_online(self): """Github should be up to download stuff from it.""" is_online = ONLINE_CHECKER.is_gh_online() self.assertTrue(is_online) class TestRawGithubOnlineChecker(TestCase): """Test of the online checks for Raw Github using unittest since raw is served from different service.""" def test_is_raw_gh_online(self): """Raw Github should be up to download stuff from it.""" is_online = ONLINE_CHECKER.is_gh_raw_online() self.assertTrue(is_online)
Repair option if params not exists.
var PermissionConstructor = require('./PermissionConstructor').PermissionConstructor; function WebService(currentUser) { this._currentUser = currentUser; this._dependencies = {}; this.runRef = undefined; } WebService.prototype.runWrapper = function () { var self = this; return function (name, allowedTypeAccount, params) { return function (req, res) { params.req = req; params.res = res; self.runRef(name, allowedTypeAccount, params); }; }; }; WebService.prototype.run = function (name, allowedTypeAccount, params) { var self = this; var permissionsInit = new PermissionConstructor(allowedTypeAccount, this._currentUser); var webServices = require('../ServiceDirectories/Web/Public'); params = params || {}; if (permissionsInit.check()) { webServices[name].call(undefined, self._dependencies, params); } else { webServices['accessDenied'].call(undefined, self._dependencies, params); } }; WebService.prototype.addDependency = function (name, value) { this._dependencies[name] = value; }; module.exports.WebService = WebService;
var PermissionConstructor = require('./PermissionConstructor').PermissionConstructor; function WebService(currentUser) { this._currentUser = currentUser; this._dependencies = {}; this.runRef = undefined; } WebService.prototype.runWrapper = function () { var self = this; return function (name, allowedTypeAccount, params) { return function (req, res) { params.req = req; params.res = res; self.runRef(name, allowedTypeAccount, params); }; }; }; WebService.prototype.run = function (name, allowedTypeAccount, params) { var self = this; var permissionsInit = new PermissionConstructor(allowedTypeAccount, this._currentUser); var webServices = require('../ServiceDirectories/Web/Public'); if (permissionsInit.check()) { webServices[name].call(undefined, self._dependencies, params); } else { webServices['accessDenied'].call(undefined, self._dependencies, params); } }; WebService.prototype.addDependency = function (name, value) { this._dependencies[name] = value; }; module.exports.WebService = WebService;
Add datetime field to Event model in sensor.core
# 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/. from django.db import models VALUE_MAX_LEN = 128 class GenericEvent(models.Model): """Represents a measurement event abstracting away what exactly is measured. """ sensor = models.ForeignKey('core.GenericSensor') datetime = models.DateTimeField() value = models.CharField(max_length=VALUE_MAX_LEN) class Event(models.Model): """Base class for sensor-specific event types""" generic_event = models.OneToOneField('core.GenericEvent') datetime = models.DateTimeField() def value_to_string(self): """Event.value_to_string() -> unicode Returns a string representation of the """ raise NotImplementedError(self.__class__.value_to_string) class Meta: abstract = True
# 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/. from django.db import models VALUE_MAX_LEN = 128 class GenericEvent(models.Model): """Represents a measurement event abstracting away what exactly is measured. """ sensor = models.ForeignKey('core.GenericSensor') datetime = models.DateTimeField() value = models.CharField(max_length=VALUE_MAX_LEN) class Event(models.Model): """Base class for sensor-specific event types""" generic_event = models.OneToOneField('core.GenericEvent') def value_to_string(self): """Event.value_to_string() -> unicode Returns a string representation of the """ raise NotImplementedError(self.__class__.value_to_string) class Meta: abstract = True
Test that the environment as non-nil storage.
// Copyright 2013 Canonical Ltd. // Licensed under the AGPLv3, see LICENCE file for details. package local_test import ( gc "launchpad.net/gocheck" "launchpad.net/juju-core/environs/local" jc "launchpad.net/juju-core/testing/checkers" ) type environSuite struct { baseProviderSuite } var _ = gc.Suite(&environSuite{}) func (*environSuite) TestOpenFailsWithoutDirs(c *gc.C) { testConfig := minimalConfig(c) environ, err := local.Provider.Open(testConfig) c.Assert(err, gc.ErrorMatches, "storage directory .* does not exist, bootstrap first") c.Assert(environ, gc.IsNil) } func (s *environSuite) TestNameAndStorage(c *gc.C) { c.Logf("root: %s", s.root) c.Assert(s.root, jc.IsDirectory) testConfig := minimalConfig(c) err := local.CreateDirs(c, testConfig) c.Assert(err, gc.IsNil) environ, err := local.Provider.Open(testConfig) c.Assert(err, gc.IsNil) c.Assert(environ.Name(), gc.Equals, "test") c.Assert(environ.Storage(), gc.NotNil) c.Assert(environ.SharedStorate(), gc.NotNil) }
// Copyright 2013 Canonical Ltd. // Licensed under the AGPLv3, see LICENCE file for details. package local_test import ( gc "launchpad.net/gocheck" "launchpad.net/juju-core/environs/local" jc "launchpad.net/juju-core/testing/checkers" ) type environSuite struct { baseProviderSuite } var _ = gc.Suite(&environSuite{}) func (*environSuite) TestOpenFailsWithoutDirs(c *gc.C) { testConfig := minimalConfig(c) environ, err := local.Provider.Open(testConfig) c.Assert(err, gc.ErrorMatches, "storage directory .* does not exist, bootstrap first") c.Assert(environ, gc.IsNil) } func (s *environSuite) TestName(c *gc.C) { c.Logf("root: %s", s.root) c.Assert(s.root, jc.IsDirectory) testConfig := minimalConfig(c) err := local.CreateDirs(c, testConfig) c.Assert(err, gc.IsNil) environ, err := local.Provider.Open(testConfig) c.Assert(err, gc.IsNil) c.Assert(environ.Name(), gc.Equals, "test") }
Add o $scope para a chamada de $parse()(...). Habia esquecido, pode causar bugs [corrigido].
Module.directive('menuAction',['$parse','MenuService','$swipe', function($parse,MenuService,$swipe){ return { restrict: 'A', priority: 10, scope: false, /* * The object that is spected is in the form: * { MenuName:{ MenuAction:'AttrName' } } * where: * - MenuName: the of the menu used in the "menu" directive * - MenuAction: name o the method to call in the menu object. Ex.: 'toggle', 'add'... * - AttrName: name of the class to pass to the method. Ex.: 'open'... */ link: function($scope, $element, $attrs, $ctrls){ var obj = $parse( $attrs.menuAction )($scope); if( !obj ) return; $swipe.bind( $element, { start: function(pos, ev){ for(var menuName in obj){ var menuObj = obj[menuName]; for( var menuAction in menuObj ){ var attrName = menuObj[menuAction]; MenuService.get( menuName )[ menuAction ]( attrName ); } } } }); } }; }]);
Module.directive('menuAction',['$parse','MenuService','$swipe', function($parse,MenuService,$swipe){ return { restrict: 'A', priority: 10, scope: false, /* * The object that is spected is in the form: * { MenuName:{ MenuAction:'AttrName' } } * where: * - MenuName: the of the menu used in the "menu" directive * - MenuAction: name o the method to call in the menu object. Ex.: 'toggle', 'add'... * - AttrName: name of the class to pass to the method. Ex.: 'open'... */ link: function($scope, $element, $attrs, $ctrls){ var obj = $parse( $attrs.menuAction )(); if( !obj ) return; $swipe.bind( $element, { start: function(pos, ev){ for(var menuName in obj){ var menuObj = obj[menuName]; for( var menuAction in menuObj ){ var attrName = menuObj[menuAction]; MenuService.get( menuName )[ menuAction ]( attrName ); } } } }); } }; }]);
Clean up old code no longer used
"""Basic views with no home""" import logging from pyramid.view import view_config from bookie.models import BmarkMgr from bookie.models.auth import ActivationMgr from bookie.models.auth import UserMgr LOG = logging.getLogger(__name__) @view_config( route_name="dashboard", renderer="/stats/dashboard.mako") def dashboard(request): """A public dashboard of the system """ # Generate some user data and stats user_count = UserMgr.count() pending_activations = ActivationMgr.count() # Generate some bookmark data. bookmark_count = BmarkMgr.count() unique_url_count = BmarkMgr.count(distinct=True) users_with_bookmarks = BmarkMgr.count(distinct_users=True) return { 'bookmark_data': { 'count': bookmark_count, 'unique_count': unique_url_count, }, 'user_data': { 'count': user_count, 'activations': pending_activations, 'with_bookmarks': users_with_bookmarks, } }
"""Basic views with no home""" import logging from pyramid.view import view_config from bookie.bcelery import tasks from bookie.models import BmarkMgr from bookie.models.auth import ActivationMgr from bookie.models.auth import UserMgr LOG = logging.getLogger(__name__) @view_config( route_name="dashboard", renderer="/stats/dashboard.mako") def dashboard(request): """A public dashboard of the system """ res = tasks.count_total.delay() # Generate some user data and stats user_count = UserMgr.count() pending_activations = ActivationMgr.count() # Generate some bookmark data. bookmark_count = BmarkMgr.count() unique_url_count = BmarkMgr.count(distinct=True) users_with_bookmarks = BmarkMgr.count(distinct_users=True) return { 'bookmark_data': { 'count': bookmark_count, 'unique_count': unique_url_count, }, 'user_data': { 'count': user_count, 'activations': pending_activations, 'with_bookmarks': users_with_bookmarks, } }
Add alternative solution for 'Reverse words in string III'
# Time: O(n) # Space: O(1) # Given a string, you need to reverse the order of characters in each word within a sentence # while still preserving whitespace and initial word order. # # Example 1: # Input: "Let's take LeetCode contest" # Output: "s'teL ekat edoCteeL tsetnoc" # Note: In the string, each word is separated by single space and # there will not be any extra space in the string. class Solution(object): def reverseWords(self, s): """ :type s: str :rtype: str """ def reverse(s, begin, end): for i in xrange((end - begin) // 2): s[begin + i], s[end - 1 - i] = s[end - 1 - i], s[begin + i] s, i = list(s), 0 for j in xrange(len(s) + 1): if j == len(s) or s[j] == ' ': reverse(s, i, j) i = j + 1 return "".join(s) class Solution2(object): def reverseWords(self, s): reversed_words = [word[::-1] for word in s.split(' ')] return ' '.join(reversed_words)
# Time: O(n) # Space: O(1) # Given a string, you need to reverse the order of characters in each word within a sentence # while still preserving whitespace and initial word order. # # Example 1: # Input: "Let's take LeetCode contest" # Output: "s'teL ekat edoCteeL tsetnoc" # Note: In the string, each word is separated by single space and # there will not be any extra space in the string. class Solution(object): def reverseWords(self, s): """ :type s: str :rtype: str """ def reverse(s, begin, end): for i in xrange((end - begin) // 2): s[begin + i], s[end - 1 - i] = s[end - 1 - i], s[begin + i] s, i = list(s), 0 for j in xrange(len(s) + 1): if j == len(s) or s[j] == ' ': reverse(s, i, j) i = j + 1 return "".join(s)
Disable print dialog in Firefox because Ctrl + P is used to open the player. [IQSLDSH-378]
'use strict'; angular.module('core').controller('HeaderController', ['$scope', '$window', 'Authentication', 'Menus', '$state', '$rootScope', function($scope, $window, Authentication, Menus, $state, $rootScope) { $scope.authentication = Authentication; $scope.isCollapsed = false; $scope.menu = Menus.getMenu('topbar'); $scope.toggleCollapsibleMenu = function() { $scope.isCollapsed = !$scope.isCollapsed; }; $(document).keydown(function (e) { if (e.keyCode == 80 && e.ctrlKey) { e.preventDefault(); $window.open('/slideshow#!/player', '_blank'); } }); $scope.isItemSelected = function (item) { var currentUrl = $state.current.url.substring(1); // Remove leading slash. if (item.link === currentUrl) { return true; } else { return _.some(item.items, { link: currentUrl }); } }; // Collapsing the menu after navigation $scope.$on('$stateChangeSuccess', function() { $scope.isCollapsed = false; }); } ]);
'use strict'; angular.module('core').controller('HeaderController', ['$scope', '$window', 'Authentication', 'Menus', '$state', '$rootScope', function($scope, $window, Authentication, Menus, $state, $rootScope) { $scope.authentication = Authentication; $scope.isCollapsed = false; $scope.menu = Menus.getMenu('topbar'); $scope.toggleCollapsibleMenu = function() { $scope.isCollapsed = !$scope.isCollapsed; }; $(document).keydown(function (e) { if (e.keyCode == 80 && e.ctrlKey) { $window.open('/slideshow#!/player', '_blank'); } }); $scope.isItemSelected = function (item) { var currentUrl = $state.current.url.substring(1); // Remove leading slash. if (item.link === currentUrl) { return true; } else { return _.some(item.items, { link: currentUrl }); } }; // Collapsing the menu after navigation $scope.$on('$stateChangeSuccess', function() { $scope.isCollapsed = false; }); } ]);
Allow newest versions of numpy and pandas
#! /usr/bin/env python """Setup information of demandlib. """ from setuptools import setup, find_packages import os def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup(name='demandlib', version='0.1.5dev', author='oemof developer group', url='https://oemof.org/', license='GPL3', author_email='oemof@rl-institut.de', description='Demandlib of the open energy modelling framework', long_description=read('README.rst'), packages=find_packages(), install_requires=['numpy >= 1.7.0, <= 1.15', 'pandas >= 0.18.0, <= 0.23.4'], package_data={ 'demandlib': [os.path.join('bdew_data', '*.csv')], 'demandlib.examples': ['*.csv']}, )
#! /usr/bin/env python """Setup information of demandlib. """ from setuptools import setup, find_packages import os def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup(name='demandlib', version='0.1.5dev', author='oemof developer group', url='https://oemof.org/', license='GPL3', author_email='oemof@rl-institut.de', description='Demandlib of the open energy modelling framework', long_description=read('README.rst'), packages=find_packages(), install_requires=['numpy >= 1.7.0, <= 1.14.3', 'pandas >= 0.18.0, <= 0.23'], package_data={ 'demandlib': [os.path.join('bdew_data', '*.csv')], 'demandlib.examples': ['*.csv']}, )
Add TypeError thrown when a non-String/Array argument is provided
"use strict"; function transformWildcardToPattern(wildcardString) { var length = wildcardString.length; var character; var pattern = ''; for (var index = 0; index < length; index++) { character = wildcardString.charAt(index); if (character === '*') { pattern = pattern + '.*' } else { pattern = pattern + character; } } return pattern; }; function transformArrayToPattern(arrayOfWildcardStrings) { var length = arrayOfWildcardStrings.length; var wildcardString; var nextSubPattern; var pattern = ''; for (var index = 0; index < length; index++) { wildcardString = arrayOfWildcardStrings[index]; nextSubPattern = transformWildcardToPattern(wildcardString); if (index === 0) { pattern = pattern + nextSubPattern; } else { pattern = pattern + '|' + nextSubPattern; } } return pattern; }; function wildcardRegex(stringOrArray) { var pattern; if (stringOrArray.constructor === String) { pattern = transformWildcardToPattern(string) } else if (stringOrArray.constructor === Array) { pattern = transformArrayToPattern(stringOrArray) } else { throw TypeError('WildcardRegex only accepts a string or array as an argument'); } var regex = new RegExp(pattern); return regex; }; module.exports = wildcardRegex;
"use strict"; function transformWildcardToPattern(wildcardString) { var length = wildcardString.length; var character; var pattern = ''; for (var index = 0; index < length; index++) { character = wildcardString.charAt(index); if (character === '*') { pattern = pattern + '.*' } else { pattern = pattern + character; } } return pattern; }; function transformArrayToPattern(arrayOfWildcardStrings) { var length = arrayOfWildcardStrings.length; var wildcardString; var nextSubPattern; var pattern = ''; for (var index = 0; index < length; index++) { wildcardString = arrayOfWildcardStrings[index]; nextSubPattern = transformWildcardToPattern(wildcardString); if (index === 0) { pattern = pattern + nextSubPattern; } else { pattern = pattern + '|' + nextSubPattern; } } return pattern; }; function wildcardRegex(stringOrArray) { var pattern; if (stringOrArray.constructor === String) { pattern = transformWildcardToPattern(string) } else if (stringOrArray.constructor === Array) { pattern = transformArrayToPattern(stringOrArray) } var regex = new RegExp(pattern); return regex; }; module.exports = wildcardRegex;
Correct the description of a helper function.
/** * Replaces existential operators with a defined check. * * @param {Object} node * @param {MagicString} patcher */ export default function patchExistentialOperator(node, patcher) { if (node.type === 'UnaryExistsOp') { const expression = node.expression; const parens = needsParens(node); if (expression.type === 'Identifier') { const checked = expression.data; let replacement = `typeof ${checked} !== "undefined" && ${checked} !== null`; if (parens) { replacement = `(${replacement})`; } patcher.replace(node.range[0], node.range[1], replacement); } else { let replacement = ` != null`; if (parens) { patcher.insert(node.range[0], '('); replacement += ')'; } patcher.replace(node.range[1] - 1, node.range[1], replacement); } } } /** * Determines whether the given node needs parentheses. * * @param {Object} node * @returns {boolean} */ function needsParens(node) { return node.parent.type !== 'Block'; }
/** * Replaces existential operators with a defined check. * * @param {Object} node * @param {MagicString} patcher */ export default function patchExistentialOperator(node, patcher) { if (node.type === 'UnaryExistsOp') { const expression = node.expression; const parens = needsParens(node); if (expression.type === 'Identifier') { const checked = expression.data; let replacement = `typeof ${checked} !== "undefined" && ${checked} !== null`; if (parens) { replacement = `(${replacement})`; } patcher.replace(node.range[0], node.range[1], replacement); } else { let replacement = ` != null`; if (parens) { patcher.insert(node.range[0], '('); replacement += ')'; } patcher.replace(node.range[1] - 1, node.range[1], replacement); } } } /** * Wraps the given string unless the node, normally needing parens, would be * unambiguous without them. * * @param {Object} node * @returns {boolean} */ function needsParens(node) { return node.parent.type !== 'Block'; }
Add nodejs 12.x to supported runtimes
// native runtime support for AWS // https://docs.aws.amazon.com/lambda/latest/dg/lambda-runtimes.html // .NET CORE export const supportedDotnetcore = new Set([ // deprecated // 'dotnetcore1.0', // 'dotnetcore2.0', // supported // 'dotnetcore2.1' ]) // GO export const supportedGo = new Set([ // 'go1.x' ]) // JAVA export const supportedJava = new Set([ // 'java8' ]) // NODE.JS export const supportedNodejs = new Set([ // deprecated, but still working 'nodejs4.3', 'nodejs6.10', 'nodejs8.10', // supported 'nodejs10.x', 'nodejs12.x', ]) // PROVIDED export const supportedProvided = new Set(['provided']) // PYTHON export const supportedPython = new Set(['python2.7', 'python3.6', 'python3.7']) // RUBY export const supportedRuby = new Set(['ruby2.5']) // deprecated runtimes // https://docs.aws.amazon.com/lambda/latest/dg/runtime-support-policy.html export const supportedRuntimes = new Set([ ...supportedDotnetcore, ...supportedGo, ...supportedJava, ...supportedNodejs, ...supportedProvided, ...supportedPython, ...supportedRuby, ])
// native runtime support for AWS // https://docs.aws.amazon.com/lambda/latest/dg/lambda-runtimes.html // .NET CORE export const supportedDotnetcore = new Set([ // deprecated // 'dotnetcore1.0', // 'dotnetcore2.0', // supported // 'dotnetcore2.1' ]) // GO export const supportedGo = new Set([ // 'go1.x' ]) // JAVA export const supportedJava = new Set([ // 'java8' ]) // NODE.JS export const supportedNodejs = new Set([ // deprecated, but still working 'nodejs4.3', 'nodejs6.10', // supported 'nodejs8.10', 'nodejs10.x', ]) // PROVIDED export const supportedProvided = new Set(['provided']) // PYTHON export const supportedPython = new Set(['python2.7', 'python3.6', 'python3.7']) // RUBY export const supportedRuby = new Set(['ruby2.5']) // deprecated runtimes // https://docs.aws.amazon.com/lambda/latest/dg/runtime-support-policy.html export const supportedRuntimes = new Set([ ...supportedDotnetcore, ...supportedGo, ...supportedJava, ...supportedNodejs, ...supportedProvided, ...supportedPython, ...supportedRuby, ])
Apply params in header and footer.
var _ = require('underscore'), fs = require('fs'); function Writer() { function gen(templates, numSegments, params, outFile, cb) { var stream = fs.createWriteStream(outFile, { flags: 'w', encoding: 'utf-8' }), segmentId = 0; stream.on('error', function (err) { console.error('Error: ' + err); }); stream.on('close', function () { cb(); }); function _apply(text, params) { _.keys(params).forEach(function (param) { text = text.replace(new RegExp('{' + param + '}', 'g'), params[param]); }); return text; } stream.write(_apply(templates.header, params)); while (segmentId++ < numSegments) { var segmentParams = _.clone(params); segmentParams.segment_id = segmentId; stream.write(_apply(templates.segment, segmentParams)); } stream.end(_apply(templates.footer, params)); } return { gen: gen }; } exports.Writer = Writer;
var _ = require('underscore'), fs = require('fs'); function Writer() { function gen(templates, numSegments, params, outFile, cb) { var stream = fs.createWriteStream(outFile, { flags: 'w', encoding: 'utf-8' }), segmentId = 0; stream.on('error', function (err) { console.error('Error: ' + err); }); stream.on('close', function () { cb(); }); stream.write(templates.header); function _writeSegment(segmentId) { var segment = templates.segment; params.segment_id = segmentId; function _apply(param) { segment = segment.replace(new RegExp('{' + param + '}', 'g'), params[param]); } _.keys(params).forEach(_apply); stream.write(segment); } while (segmentId++ < numSegments) { _writeSegment(segmentId); } stream.end(templates.footer); } return { gen: gen }; } exports.Writer = Writer;
Stop "git blame" from printing "^" markers on root repository commits Summary: Depends on D19391. Ref T13126. See that task for some details on what's going on here. Test Plan: - Viewed a file which includes lines that were added during the first commit to the repository. - Before D19391: fatal. - After D19391: blank. - After this patch: accurate blame information. Reviewers: amckinley Reviewed By: amckinley Maniphest Tasks: T13126 Differential Revision: https://secure.phabricator.com/D19392
<?php final class DiffusionGitBlameQuery extends DiffusionBlameQuery { protected function newBlameFuture(DiffusionRequest $request, $path) { $repository = $request->getRepository(); $commit = $request->getCommit(); // NOTE: The "--root" flag suppresses the addition of the "^" boundary // commit marker. Without it, root commits render with a "^" before them, // and one fewer character of the commit hash. return $repository->getLocalCommandFuture( '--no-pager blame --root -s -l %s -- %s', $commit, $path); } protected function resolveBlameFuture(ExecFuture $future) { list($err, $stdout) = $future->resolve(); if ($err) { return null; } $result = array(); $lines = phutil_split_lines($stdout); foreach ($lines as $line) { list($commit) = explode(' ', $line, 2); $result[] = $commit; } return $result; } }
<?php final class DiffusionGitBlameQuery extends DiffusionBlameQuery { protected function newBlameFuture(DiffusionRequest $request, $path) { $repository = $request->getRepository(); $commit = $request->getCommit(); return $repository->getLocalCommandFuture( '--no-pager blame -s -l %s -- %s', $commit, $path); } protected function resolveBlameFuture(ExecFuture $future) { list($err, $stdout) = $future->resolve(); if ($err) { return null; } $result = array(); $lines = phutil_split_lines($stdout); foreach ($lines as $line) { list($commit) = explode(' ', $line, 2); $result[] = $commit; } return $result; } }
Test with file from Jackub git-svn-id: 0eea5547755d67006ec5687992a7464f0ad96b59@379 acbc63fc-6c75-0410-9d68-8fa99cba188a
# encoding: utf-8 """ Tests of io.axonio """ try: import unittest2 as unittest except ImportError: import unittest from neo.io import AxonIO from neo.test.io.common_io_test import BaseTestIO class TestAxonIO(BaseTestIO, unittest.TestCase): files_to_test = ['File_axon_1.abf', 'File_axon_2.abf', 'File_axon_3.abf', 'File_axon_4.abf', 'File_axon_5.abf', 'File_axon_6.abf', ] files_to_download = files_to_test ioclass = AxonIO if __name__ == "__main__": unittest.main()
# encoding: utf-8 """ Tests of io.axonio """ try: import unittest2 as unittest except ImportError: import unittest from neo.io import AxonIO from neo.test.io.common_io_test import BaseTestIO class TestAxonIO(BaseTestIO, unittest.TestCase): files_to_test = ['File_axon_1.abf', 'File_axon_2.abf', 'File_axon_3.abf', 'File_axon_4.abf',] files_to_download = files_to_test ioclass = AxonIO if __name__ == "__main__": unittest.main()
Clean school data in redux
/* This file is a part of libertysoil.org website Copyright (C) 2015 Loki Education (Social Enterprise) This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ import i from 'immutable'; import { keyBy } from 'lodash'; import * as a from '../actions'; function cleanupSchoolObject(school) { if (school.description === null) { school.description = ''; } if (school.lat === null) { school.lat = 0.0; } if (school.lon === null) { school.lon = 0.0; } return school; } const initialState = i.Map({}); export default function reducer(state=initialState, action) { switch (action.type) { case a.ADD_SCHOOL: { const school = cleanupSchoolObject(action.school); state = state.set(school.id, i.fromJS(school)); break; } case a.SET_SCHOOLS: { const schools = keyBy(action.schools.map(school => cleanupSchoolObject(school)), 'id'); state = state.merge(i.fromJS(schools)); break; } } return state; }
/* This file is a part of libertysoil.org website Copyright (C) 2015 Loki Education (Social Enterprise) This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ import i from 'immutable'; import _ from 'lodash'; import * as a from '../actions'; const initialState = i.Map({}); export default function reducer(state=initialState, action) { switch (action.type) { case a.ADD_SCHOOL: { const school = action.school; state = state.set(school.id, i.fromJS(school)); break; } case a.SET_SCHOOLS: { const schools = _.keyBy(action.schools, 'id'); state = state.merge(i.fromJS(schools)); break; } } return state; }
Fix module exports related warning src\core\se\jbee\inject\bootstrap\Supply.java:52: warning: [exports] class Logger in module java.logging is not indirectly exported using requires transitive public static final Supplier<Logger> LOGGER = (dep, context) //
/* * Copyright (c) 2012-2020, Jan Bernitt * * Licensed under the Apache License, Version 2.0, http://www.apache.org/licenses/LICENSE-2.0 */ /** * Defines the API of Silk DI. * * @uses se.jbee.inject.declare.Bundle * @uses se.jbee.inject.declare.ModuleWith */ module se.jbee.inject { exports se.jbee.inject; exports se.jbee.inject.action; exports se.jbee.inject.bind; exports se.jbee.inject.bind.serviceloader; exports se.jbee.inject.bootstrap; exports se.jbee.inject.config; exports se.jbee.inject.container; exports se.jbee.inject.declare; exports se.jbee.inject.event; exports se.jbee.inject.extend; exports se.jbee.inject.scope; requires transitive java.logging; requires java.desktop; requires java.management; uses se.jbee.inject.declare.Bundle; uses se.jbee.inject.declare.ModuleWith; }
/* * Copyright (c) 2012-2020, Jan Bernitt * * Licensed under the Apache License, Version 2.0, http://www.apache.org/licenses/LICENSE-2.0 */ /** * Defines the API of Silk DI. * * @uses se.jbee.inject.declare.Bundle * @uses se.jbee.inject.declare.ModuleWith */ module se.jbee.inject { exports se.jbee.inject; exports se.jbee.inject.action; exports se.jbee.inject.bind; exports se.jbee.inject.bind.serviceloader; exports se.jbee.inject.bootstrap; exports se.jbee.inject.config; exports se.jbee.inject.container; exports se.jbee.inject.declare; exports se.jbee.inject.event; exports se.jbee.inject.extend; exports se.jbee.inject.scope; requires java.logging; requires java.desktop; requires java.management; uses se.jbee.inject.declare.Bundle; uses se.jbee.inject.declare.ModuleWith; }
Remove possible jquery-prototype conflict when using both libs
/* * Smart event highlighting * Handles when events span rows, or don't have a background color */ jQuery(document).ready(function($) { var highlight_color = "#2EAC6A"; // highlight events that have a background color $(".ec-event-bg").live("mouseover", function() { event_id = $(this).attr("data-event-id"); $(".ec-event-"+event_id).css("background-color", highlight_color); }); $(".ec-event-bg").live("mouseout", function() { event_id = $(this).attr("data-event-id"); event_color = $(this).attr("data-color"); $(".ec-event-"+event_id).css("background-color", event_color); }); // highlight events that don't have a background color $(".ec-event-no-bg").live("mouseover", function() { ele = $(this); ele.css("color", "white"); ele.find("a").css("color", "white"); ele.find(".ec-bullet").css("background-color", "white"); ele.css("background-color", highlight_color); }); $(".ec-event-no-bg").live("mouseout", function() { ele = $(this); event_color = $(this).attr("data-color"); ele.css("color", event_color); ele.find("a").css("color", event_color); ele.find(".ec-bullet").css("background-color", event_color); ele.css("background-color", "transparent"); }); });
/* * Smart event highlighting * Handles when events span rows, or don't have a background color */ $(document).ready(function() { var highlight_color = "#2EAC6A"; // highlight events that have a background color $(".ec-event-bg").live("mouseover", function() { event_id = $(this).attr("data-event-id"); $(".ec-event-"+event_id).css("background-color", highlight_color); }); $(".ec-event-bg").live("mouseout", function() { event_id = $(this).attr("data-event-id"); event_color = $(this).attr("data-color"); $(".ec-event-"+event_id).css("background-color", event_color); }); // highlight events that don't have a background color $(".ec-event-no-bg").live("mouseover", function() { ele = $(this); ele.css("color", "white"); ele.find("a").css("color", "white"); ele.find(".ec-bullet").css("background-color", "white"); ele.css("background-color", highlight_color); }); $(".ec-event-no-bg").live("mouseout", function() { ele = $(this); event_color = $(this).attr("data-color"); ele.css("color", event_color); ele.find("a").css("color", event_color); ele.find(".ec-bullet").css("background-color", event_color); ele.css("background-color", "transparent"); }); });
Rename flag_x to flagX to keep GoLint happy
package main //----------------------------------------------------------------------------- // Package factored import statement: //----------------------------------------------------------------------------- import ( // Native imports: "flag" "fmt" // External imports: "github.com/calavera/dkvolume" ) //----------------------------------------------------------------------------- // Package variable declarations factored into a block: //----------------------------------------------------------------------------- var ( flagA = flag.Bool("flagA", false, "Flag A is true or false") flagB = flag.Bool("flagB", false, "Flag B is true or false") ) //----------------------------------------------------------------------------- // func init() is called after all the variable declarations in the package // have evaluated their initializers, and those are evaluated only after all // the imported packages have been initialized: //----------------------------------------------------------------------------- func init() { flag.Parse() } //----------------------------------------------------------------------------- // Function main of package main: //----------------------------------------------------------------------------- func main() { fmt.Printf("Hello World!\n") d := myDummyDriver{} h := dkvolume.NewHandler(d) h.ServeUnix("root", "dummy_volume") }
package main //----------------------------------------------------------------------------- // Package factored import statement: //----------------------------------------------------------------------------- import ( // Native imports: "flag" "fmt" // External imports: "github.com/calavera/dkvolume" ) //----------------------------------------------------------------------------- // Package variable declarations factored into a block: //----------------------------------------------------------------------------- var ( flag_a = flag.Bool("flag_a", false, "Flag a is true or false") flag_b = flag.Bool("flag_b", false, "Flag b is true or false") ) //----------------------------------------------------------------------------- // func init() is called after all the variable declarations in the package // have evaluated their initializers, and those are evaluated only after all // the imported packages have been initialized: //----------------------------------------------------------------------------- func init() { flag.Parse() } //----------------------------------------------------------------------------- // Function main of package main: //----------------------------------------------------------------------------- func main() { fmt.Printf("Hello World!\n") d := myDummyDriver{} h := dkvolume.NewHandler(d) h.ServeUnix("root", "dummy_volume") }
Add KazooClient to top-level module
import os from kazoo.zkclient import ZooKeeperClient from kazoo.client import KazooClient __all__ = ['ZooKeeperClient', 'KazooClient'] # ZK C client likes to spew log info to STDERR. disable that unless an # env is present. def disable_zookeeper_log(): import zookeeper zookeeper.set_log_stream(open('/dev/null')) if not "KAZOO_LOG_ENABLED" in os.environ: disable_zookeeper_log() def patch_extras(): # workaround for http://code.google.com/p/gevent/issues/detail?id=112 # gevent isn't patching threading._sleep which causes problems # for Condition objects from gevent import sleep import threading threading._sleep = sleep if "KAZOO_TEST_GEVENT_PATCH" in os.environ: from gevent import monkey; monkey.patch_all() patch_extras()
import os from kazoo.zkclient import ZooKeeperClient __all__ = ['ZooKeeperClient'] # ZK C client likes to spew log info to STDERR. disable that unless an # env is present. def disable_zookeeper_log(): import zookeeper zookeeper.set_log_stream(open('/dev/null')) if not "KAZOO_LOG_ENABLED" in os.environ: disable_zookeeper_log() def patch_extras(): # workaround for http://code.google.com/p/gevent/issues/detail?id=112 # gevent isn't patching threading._sleep which causes problems # for Condition objects from gevent import sleep import threading threading._sleep = sleep if "KAZOO_TEST_GEVENT_PATCH" in os.environ: from gevent import monkey; monkey.patch_all() patch_extras()
Update "HijiNKS Ensue" after feed change
from comics.aggregator.crawler import CrawlerBase, CrawlerImage from comics.core.comic_data import ComicDataBase class ComicData(ComicDataBase): name = "HijiNKS Ensue" language = "en" url = "http://hijinksensue.com/" start_date = "2007-05-11" rights = "Joel Watson" active = False class Crawler(CrawlerBase): history_capable_date = '2015-03-11' time_zone = "US/Central" def crawl(self, pub_date): feed = self.parse_feed("http://hijinksensue.com/feed/") for entry in feed.for_date(pub_date): if "/comic/" not in entry.link: continue url = entry.content0.src('img[srcset*="-300x120"]') if not url: continue url = url.replace("-300x120", "") title = entry.title return CrawlerImage(url, title)
from comics.aggregator.crawler import CrawlerBase, CrawlerImage from comics.core.comic_data import ComicDataBase class ComicData(ComicDataBase): name = "HijiNKS Ensue" language = "en" url = "http://hijinksensue.com/" start_date = "2007-05-11" rights = "Joel Watson" class Crawler(CrawlerBase): history_capable_days = 180 time_zone = "US/Central" def crawl(self, pub_date): feed = self.parse_feed("http://hijinksensue.com/feed/") for entry in feed.for_date(pub_date): if "/comic/" not in entry.link: continue url = entry.content0.src('img[src*="-300x120"]') if not url: continue url = url.replace("-300x120", "") title = entry.title return CrawlerImage(url, title)
Stop browser-sync from opening a browser automatically
var dest = "./build/"; var src = './app/'; module.exports = { browserSync: { open: false, // Stop it from automatically stopping the browser server: { baseDir: dest }, files: [ dest + "**", // Exclude Map files "!" + dest + "**.map" ] }, sass: { src: src + "sass/**/*.{sass,scss}", dest: dest }, icons: { src: [src + "icons/*"], dest: [dest + "icons"], }, images: { src: src + "images/**", dest: dest + "images" }, markup: { src: src + "htdocs/*", dest: dest }, browserify: { // Enable source maps debug: true, // Additional file extentions to make optional // extensions: ['.coffee', '.hbs'], // A separate bundle will be generated for each // bundle config in the list below bundleConfigs: [{ entries: src + 'index.js', dest: dest, outputName: 'app.js' }] } };
var dest = "./build/"; var src = './app/'; module.exports = { browserSync: { server: { baseDir: dest }, files: [ dest + "**", // Exclude Map files "!" + dest + "**.map" ] }, sass: { src: src + "sass/**/*.{sass,scss}", dest: dest }, icons: { src: [src + "icons/*"], dest: [dest + "icons"], }, images: { src: src + "images/**", dest: dest + "images" }, markup: { src: src + "htdocs/*", dest: dest }, browserify: { // Enable source maps debug: true, // Additional file extentions to make optional // extensions: ['.coffee', '.hbs'], // A separate bundle will be generated for each // bundle config in the list below bundleConfigs: [{ entries: src + 'index.js', dest: dest, outputName: 'app.js' }] } };
Use /projects/ not /+projects/ when caching This prevents staticgenerator from sending out an annoying email every 10 minutes.
# This file is part of OpenHatch. # Copyright (C) 2010 OpenHatch, Inc. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import datetime import logging from django.core.management.base import BaseCommand import staticgenerator class Command(BaseCommand): help = "Run this once every 10 minutes for the OpenHatch profile app." def handle(self, *args, **options): # Every 10 minutes, refresh /projects/ root_logger = logging.getLogger('') root_logger.setLevel(logging.WARN) staticgenerator.quick_publish('/projects/')
# This file is part of OpenHatch. # Copyright (C) 2010 OpenHatch, Inc. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import datetime import logging from django.core.management.base import BaseCommand import staticgenerator class Command(BaseCommand): help = "Run this once every 10 minutes for the OpenHatch profile app." def handle(self, *args, **options): # Every 10 minutes, refresh /+projects/ root_logger = logging.getLogger('') root_logger.setLevel(logging.WARN) staticgenerator.quick_publish('/+projects/')
Add a test for resolving namespace constant
<?php namespace ParserReflection\Stub; abstract class ExplicitAbstractClass {} abstract class ImplicitAbstractClass { abstract function test(); } final class FinalClass {} interface SimpleInterface {} interface InterfaceWithMethod { function foo(); } trait SimpleTrait { function foo() { return __CLASS__; } } class SimpleInheritance extends ExplicitAbstractClass {} abstract class SimpleAbstractInheritance extends ImplicitAbstractClass {} class ClassWithInterface implements SimpleInterface {} class ClassWithTrait { use SimpleTrait; } class ClassWithTraitAndInterface implements InterfaceWithMethod { use SimpleTrait; } class NoCloneable { private function __clone() {} } class NoInstantiable { private function __construct() {} } interface AbstractInterface { public function foo(); public function bar(); } class ClassWithScalarConstants { const A = 10, A1 = 11; const B = 42.0; const C = 'foo'; const D = false; } class ClassWithMagicConstants { const A = __DIR__; const B = __FILE__; const C = __NAMESPACE__; const D = __CLASS__; const E = __LINE__; } const NS_CONST = 'test'; class ClassWithComplexConstantsAndInheritance extends ClassWithMagicConstants { const H = M_PI; const J = NS_CONST; }
<?php namespace ParserReflection\Stub; abstract class ExplicitAbstractClass {} abstract class ImplicitAbstractClass { abstract function test(); } final class FinalClass {} interface SimpleInterface {} interface InterfaceWithMethod { function foo(); } trait SimpleTrait { function foo() { return __CLASS__; } } class SimpleInheritance extends ExplicitAbstractClass {} abstract class SimpleAbstractInheritance extends ImplicitAbstractClass {} class ClassWithInterface implements SimpleInterface {} class ClassWithTrait { use SimpleTrait; } class ClassWithTraitAndInterface implements InterfaceWithMethod { use SimpleTrait; } class NoCloneable { private function __clone() {} } class NoInstantiable { private function __construct() {} } interface AbstractInterface { public function foo(); public function bar(); } class ClassWithScalarConstants { const A = 10, A1 = 11; const B = 42.0; const C = 'foo'; const D = false; } class ClassWithMagicConstants { const A = __DIR__; const B = __FILE__; const C = __NAMESPACE__; const D = __CLASS__; const E = __LINE__; } class ClassWithComplexConstantsAndInheritance extends ClassWithMagicConstants { const H = M_PI; }
Allow entered text to be used as a tag In user research a common problem with tagging was discovered. Users would enter text into the input field then click away or on the submit button. The default behaviour would hide the tag drop down and lear the tag input. So forms were being submitted without the intended tags. * Use the select2 option “selectOnBlur” to turn user input into a tag on blur
(function () { "use strict" var root = this, $ = root.jQuery; if (typeof root.GOVUK === 'undefined') { root.GOVUK = {}; } root.GOVUK.Tagging = { ready: function(options) { $('.js-tag-list').select2({ tags: options['autocompleteWith'], selectOnBlur: true, tokenSeparators: [','], initSelection: function (input, setTags) { setTags( $(input.val().split(",")).map(function () { return { id: $.trim(this), text: $.trim(this) }; }) ) } }) } }; }).call(this);
(function () { "use strict" var root = this, $ = root.jQuery; if (typeof root.GOVUK === 'undefined') { root.GOVUK = {}; } root.GOVUK.Tagging = { ready: function(options) { $('.js-tag-list').select2({ tags: options['autocompleteWith'], tokenSeparators: [','], initSelection: function (input, setTags) { setTags( $(input.val().split(",")).map(function () { return { id: $.trim(this), text: $.trim(this) }; }) ) } }) } }; }).call(this);
Remove <1.9 limit on Django version
import os from setuptools import setup with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme: README = readme.read() # allow setup.py to be run from any path os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir))) setup( name='django-zendesk-tickets', version='0.3', packages=['zendesk_tickets'], include_package_data=True, license='MIT License', description='', long_description=README, install_requires=['Django>=1.8', 'requests', ], classifiers=[ 'Framework :: Django', 'Intended Audience :: Python Developers', ], test_suite='runtests.runtests' )
import os from setuptools import setup with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme: README = readme.read() # allow setup.py to be run from any path os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir))) setup( name='django-zendesk-tickets', version='0.3', packages=['zendesk_tickets'], include_package_data=True, license='MIT License', description='', long_description=README, install_requires=['Django>=1.8,<1.9', 'requests', ], classifiers=[ 'Framework :: Django', 'Intended Audience :: Python Developers', ], test_suite='runtests.runtests' )
Add timeout to requests so that they do get death-locked
import requests from bot.api.domain import ApiObject class TelegramBotApi: def __init__(self, auth_token, debug: bool): self.base_url = "https://api.telegram.org/bot" + auth_token + "/" self.debug = debug def get_me(self): return self.__send_request("getMe") def send_message(self, chat_id, text): return self.__send_request("sendMessage", chat_id=chat_id, text=text) def get_updates(self, offset=None, timeout=None): return self.__send_request("getUpdates", offset=offset, timeout=timeout) def __send_request(self, command, **params): request = requests.get(self.base_url + command, params=params, timeout=60) self.__log_request(request) response = request.json() self.__log_response(response) if not response["ok"]: raise TelegramBotApiException(response["description"]) return ApiObject.wrap_api_object(response["result"]) def __log_request(self, request): if self.debug: print(">> " + request.url) def __log_response(self, response): if self.debug: print("<< " + str(response)) class TelegramBotApiException(Exception): pass
import requests from bot.api.domain import ApiObject class TelegramBotApi: def __init__(self, auth_token, debug: bool): self.base_url = "https://api.telegram.org/bot" + auth_token + "/" self.debug = debug def get_me(self): return self.__send_request("getMe") def send_message(self, chat_id, text): return self.__send_request("sendMessage", chat_id=chat_id, text=text) def get_updates(self, offset=None, timeout=None): return self.__send_request("getUpdates", offset=offset, timeout=timeout) def __send_request(self, command, **params): request = requests.get(self.base_url + command, params=params) self.__log_request(request) response = request.json() self.__log_response(response) if not response["ok"]: raise TelegramBotApiException(response["description"]) return ApiObject.wrap_api_object(response["result"]) def __log_request(self, request): if self.debug: print(">> " + request.url) def __log_response(self, response): if self.debug: print("<< " + str(response)) class TelegramBotApiException(Exception): pass
Add new config for github deploy
/* jshint node: true */ module.exports = function(environment) { var ENV = { modulePrefix: 'eapp', environment: environment, baseURL: '/', locationType: 'hash', EmberENV: { FEATURES: { // Here you can enable experimental features on an ember canary build // e.g. 'with-controller': true } }, APP: { // Here you can pass flags/options to your application instance // when it is created }, sassOptions: { includePaths: ['bower_components/materialize/sass'] } }; if (environment === 'development') { // ENV.APP.LOG_RESOLVER = true; // ENV.APP.LOG_ACTIVE_GENERATION = true; // ENV.APP.LOG_TRANSITIONS = true; // ENV.APP.LOG_TRANSITIONS_INTERNAL = true; // ENV.APP.LOG_VIEW_LOOKUPS = true; } if (environment === 'test') { // Testem prefers this... ENV.baseURL = '/'; ENV.locationType = 'none'; // keep test console output quieter ENV.APP.LOG_ACTIVE_GENERATION = false; ENV.APP.LOG_VIEW_LOOKUPS = false; ENV.APP.rootElement = '#ember-testing'; } if (environment === 'production') { ENV.baseURL = '/hooli'; } return ENV; };
/* jshint node: true */ module.exports = function(environment) { var ENV = { modulePrefix: 'eapp', environment: environment, baseURL: '/', locationType: 'auto', EmberENV: { FEATURES: { // Here you can enable experimental features on an ember canary build // e.g. 'with-controller': true } }, APP: { // Here you can pass flags/options to your application instance // when it is created }, sassOptions: { includePaths: ['bower_components/materialize/sass'] } }; if (environment === 'development') { // ENV.APP.LOG_RESOLVER = true; // ENV.APP.LOG_ACTIVE_GENERATION = true; // ENV.APP.LOG_TRANSITIONS = true; // ENV.APP.LOG_TRANSITIONS_INTERNAL = true; // ENV.APP.LOG_VIEW_LOOKUPS = true; } if (environment === 'test') { // Testem prefers this... ENV.baseURL = '/'; ENV.locationType = 'none'; // keep test console output quieter ENV.APP.LOG_ACTIVE_GENERATION = false; ENV.APP.LOG_VIEW_LOOKUPS = false; ENV.APP.rootElement = '#ember-testing'; } if (environment === 'production') { ENV.baseURL = 'http://vysakh0.github.io/hooli/'; } return ENV; };
Fix printing 'time: 303 µs' on py2.7
from __future__ import print_function try: from time import monotonic except ImportError: from monotonic import monotonic from IPython.core.magics.execution import _format_time as format_delta class LineWatcher(object): """Class that implements a basic timer. Notes ----- * Register the `start` and `stop` methods with the IPython events API. """ __slots__ = ['start_time'] def start(self): self.start_time = monotonic() def stop(self): delta = monotonic() - self.start_time print(u'time: {}'.format(format_delta(delta))) timer = LineWatcher() def load_ipython_extension(ip): timer.start() ip.events.register('pre_run_cell', timer.start) ip.events.register('post_run_cell', timer.stop) def unload_ipython_extension(ip): ip.events.unregister('pre_run_cell', timer.start) ip.events.unregister('post_run_cell', timer.stop) from ._version import get_versions __version__ = get_versions()['version'] del get_versions
from __future__ import print_function try: from time import monotonic except ImportError: from monotonic import monotonic from IPython.core.magics.execution import _format_time as format_delta class LineWatcher(object): """Class that implements a basic timer. Notes ----- * Register the `start` and `stop` methods with the IPython events API. """ __slots__ = ['start_time'] def start(self): self.start_time = monotonic() def stop(self): delta = monotonic() - self.start_time print('time: {}'.format(format_delta(delta))) timer = LineWatcher() def load_ipython_extension(ip): timer.start() ip.events.register('pre_run_cell', timer.start) ip.events.register('post_run_cell', timer.stop) def unload_ipython_extension(ip): ip.events.unregister('pre_run_cell', timer.start) ip.events.unregister('post_run_cell', timer.stop) from ._version import get_versions __version__ = get_versions()['version'] del get_versions
Optimize string building for NamespacedName Kubernetes-commit: 668d5606189d93f2c396b3881ff71f14d9c2c322
/* Copyright 2015 The Kubernetes Authors. 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. */ package types // NamespacedName comprises a resource name, with a mandatory namespace, // rendered as "<namespace>/<name>". Being a type captures intent and // helps make sure that UIDs, namespaced names and non-namespaced names // do not get conflated in code. For most use cases, namespace and name // will already have been format validated at the API entry point, so we // don't do that here. Where that's not the case (e.g. in testing), // consider using NamespacedNameOrDie() in testing.go in this package. type NamespacedName struct { Namespace string Name string } const ( Separator = '/' ) // String returns the general purpose string representation func (n NamespacedName) String() string { return n.Namespace + string(Separator) + n.Name }
/* Copyright 2015 The Kubernetes Authors. 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. */ package types import ( "fmt" ) // NamespacedName comprises a resource name, with a mandatory namespace, // rendered as "<namespace>/<name>". Being a type captures intent and // helps make sure that UIDs, namespaced names and non-namespaced names // do not get conflated in code. For most use cases, namespace and name // will already have been format validated at the API entry point, so we // don't do that here. Where that's not the case (e.g. in testing), // consider using NamespacedNameOrDie() in testing.go in this package. type NamespacedName struct { Namespace string Name string } const ( Separator = '/' ) // String returns the general purpose string representation func (n NamespacedName) String() string { return fmt.Sprintf("%s%c%s", n.Namespace, Separator, n.Name) }
Fix allowing/rejecting application access through ui
package com.intuso.housemate.web.client.bootstrap.widget.application.instance; import com.intuso.housemate.web.client.bootstrap.extensions.CommandToggleSwitch; import com.intuso.housemate.web.client.object.GWTProxyApplicationInstance; import com.intuso.housemate.web.client.object.GWTProxyCommand; /** * Created with IntelliJ IDEA. * User: tomc * Date: 10/02/14 * Time: 18:49 * To change this template use File | Settings | File Templates. */ public class AccessWidget extends CommandToggleSwitch { private GWTProxyApplicationInstance applicationInstance; public AccessWidget() { setOnText("Allowed"); setOffText("Rejected"); } public void setApplicationInstance(GWTProxyApplicationInstance applicationInstance) { this.applicationInstance = applicationInstance; setValue(applicationInstance.getStatusValue()); } @Override protected boolean isTrue() { return applicationInstance.getStatus() == com.intuso.housemate.object.v1_0.api.ApplicationInstance.Status.Allowed; } @Override protected GWTProxyCommand getTrueCommand() { return applicationInstance.getAllowCommand(); } @Override protected GWTProxyCommand getFalseCommand() { return applicationInstance.getRejectCommand(); } }
package com.intuso.housemate.web.client.bootstrap.widget.application.instance; import com.intuso.housemate.web.client.bootstrap.extensions.CommandToggleSwitch; import com.intuso.housemate.web.client.object.GWTProxyApplicationInstance; import com.intuso.housemate.web.client.object.GWTProxyCommand; /** * Created with IntelliJ IDEA. * User: tomc * Date: 10/02/14 * Time: 18:49 * To change this template use File | Settings | File Templates. */ public class AccessWidget extends CommandToggleSwitch { private GWTProxyApplicationInstance applicationInstance; public AccessWidget() { setOnText("Allowed"); setOffText("Rejected"); } public void setApplicationInstance(GWTProxyApplicationInstance applicationInstance) { this.applicationInstance = applicationInstance; setValue(applicationInstance.getStatusValue()); } @Override protected boolean isTrue() { return applicationInstance.getStatus() == com.intuso.housemate.object.v1_0.api.ApplicationInstance.Status.Allowed; } @Override protected GWTProxyCommand getTrueCommand() { return applicationInstance.getRejectCommand(); } @Override protected GWTProxyCommand getFalseCommand() { return applicationInstance.getAllowCommand(); } }
Remove unused import in Problem 219
package leetcode; import java.util.HashMap; import java.util.Map; /** * https://leetcode.com/problems/contains-duplicate-ii/ */ public class Problem219 { public boolean containsNearbyDuplicate(int[] nums, int k) { // the key is the num value, the value is the index Map<Integer, Integer> map = new HashMap<>(); for (int i = 0; i < nums.length; i++) { int num = nums[i]; if (map.containsKey(num)) { int idx = map.get(num); if (Math.abs(i - idx) <= k) { return true; } } map.put(num, i); } return false; } public static void main(String[] args) { Problem219 prob = new Problem219(); System.out.println(prob.containsNearbyDuplicate(new int[]{99, 99}, 2)); } }
package leetcode; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; /** * https://leetcode.com/problems/contains-duplicate-ii/ */ public class Problem219 { public boolean containsNearbyDuplicate(int[] nums, int k) { // the key is the num value, the value is the index Map<Integer, Integer> map = new HashMap<>(); for (int i = 0; i < nums.length; i++) { int num = nums[i]; if (map.containsKey(num)) { int idx = map.get(num); if (Math.abs(i - idx) <= k) { return true; } } map.put(num, i); } return false; } public static void main(String[] args) { Problem219 prob = new Problem219(); System.out.println(prob.containsNearbyDuplicate(new int[]{99, 99}, 2)); } }
Fix error when no options are passed
var deselectCurrent = require('toggle-selection'); function copy(text, options) { var reselectPrevious, selection, range, mark, debug, message; if (!options) { options = {}; } debug = options.debug || false; message = options.message || 'Copy to clipboard: Ctrl+C, Enter'; try { reselectPrevious = deselectCurrent(); range = document.createRange(); selection = document.getSelection(); mark = document.createElement('mark'); mark.innerHTML = text; document.body.appendChild(mark); range.selectNode(mark); selection.addRange(range); var successful = document.execCommand('copy'); if (!successful) { throw new Error('copy command was unsuccessful'); } } catch (err) { debug && console.error('unable to copy, trying IE specific stuff'); try { window.clipboardData.setData('text', text); } catch (err) { debug && console.error('unable to copy, falling back to prompt'); window.prompt(message, text); } } finally { if (selection) { if (typeof selection.removeRange == 'function') { selection.removeRange(range); } else { selection.removeAllRanges(); } } if (mark) { document.body.removeChild(mark); } reselectPrevious(); } } module.exports = copy;
var deselectCurrent = require('toggle-selection'); function copy(text, options) { var reselectPrevious, selection, range, mark, debug, message; debug = options.debug || false; message = options.message || 'Copy to clipboard: Ctrl+C, Enter'; try { reselectPrevious = deselectCurrent(); range = document.createRange(); selection = document.getSelection(); mark = document.createElement('mark'); mark.innerHTML = text; document.body.appendChild(mark); range.selectNode(mark); selection.addRange(range); var successful = document.execCommand('copy'); if (!successful) { throw new Error('copy command was unsuccessful'); } } catch (err) { debug && console.error('unable to copy, trying IE specific stuff'); try { window.clipboardData.setData('text', text); } catch (err) { debug && console.error('unable to copy, falling back to prompt'); window.prompt(message, text); } } finally { if (selection) { if (typeof selection.removeRange == 'function') { selection.removeRange(range); } else { selection.removeAllRanges(); } } if (mark) { document.body.removeChild(mark); } reselectPrevious(); } } module.exports = copy;
Fix deployment script to include yarn"
require('shelljs/global'); const platform = { path: 'sashimi-platform', buildPath: 'public' }; const webapp = { path: 'sashimi-webapp', buildPath: 'dist' }; let statusBuild = -1; let statusStart = -1; printTitle('Build web application'); cd(`./${webapp.path}`); exec('yarn'); statusBuild = exec('yarn run build').code; throwErrorIfFailedToExec(statusBuild, 'build failed') printTitle('Copy webapp to server folder'); rm('-rf', `../${platform.path}/${platform.buildPath}/*`); cp('-R', `${webapp.buildPath}/*`, `../${platform.path}/${platform.buildPath}/`); cd(`..`); printTitle('Run web server') cd(`./${platform.path}`); exec('yarn') statusStart = exec('yarn start').code; throwErrorIfFailedToExec(statusStart, 'run failed') function throwErrorIfFailedToExec(statusCode, message) { if (statusCode !== 0) { printTitle(`Error: ${message}`); printMessage(`Script exit(${statusCode})`); exit(1); } } function printMessage(message) { let echoMsg = message || ''; echo(` [Deploy] > ${echoMsg}`); } function printTitle(message) { let echoMsg = message || '----------------'; echo(''); echo(` [Deploy] ${echoMsg}`); echo(''); }
require('shelljs/global'); const platform = { path: 'sashimi-platform', buildPath: 'public' }; const webapp = { path: 'sashimi-webapp', buildPath: 'dist' }; let statusBuild = -1; let statusStart = -1; printTitle('Build web application') cd(`./${webapp.path}`); statusBuild = exec('yarn run build').code; throwErrorIfFailedToExec(statusBuild, 'build failed') printTitle('Copy webapp to server folder'); rm('-rf', `../${platform.path}/${platform.buildPath}/*`); cp('-R', `${webapp.buildPath}/*`, `../${platform.path}/${platform.buildPath}/`); cd(`..`); printTitle('Run web server') cd(`./${platform.path}`); statusStart = exec('yarn start').code; throwErrorIfFailedToExec(statusStart, 'run failed') function throwErrorIfFailedToExec(statusCode, message) { if (statusCode !== 0) { printTitle(`Error: ${message}`); printMessage(`Script exit(${statusCode})`); exit(1); } } function printMessage(message) { let echoMsg = message || ''; echo(` [Deploy] > ${echoMsg}`); } function printTitle(message) { let echoMsg = message || '----------------'; echo(''); echo(` [Deploy] ${echoMsg}`); echo(''); }
Change event listener to command
window.addEventListener('load', function() { // https://developer.mozilla.org/en/Code_snippets/Tabbed_browser var browser = window.opener.getBrowser(); var doc = window.opener.content.document; var c = doc.SimpleMap; Components.utils.reportError(c.addresses); // DEBUG var addressArray = c.addresses; var addrArrayLen = addressArray.length; for(i = 0; i < addrArrayLen; i++) { var addrList = document.getElementById("address-list"); addrList.appendItem(addressArray[i].toString()); } document.getElementById("show-map").addEventListener("command", function(e) { var addr = document.getElementById("address-list").getSelectedItem(0).getAttribute("label"); var link = GoogleMap.getLinkToAddress(addr); gBrowser.selectedTab = gBrowser.addTab(link); },false); document.getElementById("show-directions").addEventListener("command", function(e) { var addr = document.getElementById("address-list").getSelectedItem(0).getAttribute("label"); var link = GoogleMap.getLinkToAddressDirection(addr, c.getPreferences().getMyLocation()); gBrowser.selectedTab = gBrowser.addTab(link); }, false); }, false);
window.addEventListener('load', function() { // https://developer.mozilla.org/en/Code_snippets/Tabbed_browser var browser = window.opener.getBrowser(); var doc = window.opener.content.document; var c = doc.SimpleMap; Components.utils.reportError(c.addresses); // DEBUG var addressArray = c.addresses; var addrArrayLen = addressArray.length; for(i = 0; i < addrArrayLen; i++) { var addrList = document.getElementById("address-list"); addrList.appendItem(addressArray[i].toString()); } document.getElementById("show-map").addEventListener("oncommand", function() { var addr = document.getElementById("address-list").getSelectedItem(0).getAttribute("label"); var link = GoogleMap.getLinkToAddress(addr); gBrowser.selectedTab = gBrowser.addTab(link); },false); document.getElementById("show-directions").addEventListener("oncommand", function() { var addr = document.getElementById("address-list").getSelectedItem(0).getAttribute("label"); var link = GoogleMap.getLinkToAddressDirection(addr, c.getPreferences().getMyLocation()); gBrowser.selectedTab = gBrowser.addTab(link); }, false); }, false);
Add site footer to each documentation generator
var _ = require('lodash') var fs = require('fs') var gzip = require('gzip-size') var filesize = require('filesize') var cssstats = require('cssstats') var module = require('tachyons-line-height/package.json') var moduleCss = fs.readFileSync('node_modules/tachyons-line-height/tachyons-line-height.min.css', 'utf8') var moduleObj = cssstats(moduleCss) var moduleSize = filesize(moduleObj.gzipSize) var srcCSS = fs.readFileSync('./src/_line-height.css', 'utf8') var navDocs = fs.readFileSync('./templates/nav_docs.html', 'utf8') var siteFooter = fs.readFileSync('./templates/footer.html', 'utf8') var template = fs.readFileSync('./templates/docs/line-height/index.html', 'utf8') var tpl = _.template(template) var html = tpl({ moduleVersion: module.version, moduleSize: moduleSize, moduleObj: moduleObj, srcCSS: srcCSS, navDocs: navDocs, siteFooter: siteFooter }) fs.writeFileSync('./docs/typography/line-height/index.html', html)
var _ = require('lodash') var fs = require('fs') var gzip = require('gzip-size') var filesize = require('filesize') var cssstats = require('cssstats') var module = require('tachyons-line-height/package.json') var moduleCss = fs.readFileSync('node_modules/tachyons-line-height/tachyons-line-height.min.css', 'utf8') var moduleObj = cssstats(moduleCss) var moduleSize = filesize(moduleObj.gzipSize) var srcCSS = fs.readFileSync('./src/_line-height.css', 'utf8') var navDocs = fs.readFileSync('./templates/nav_docs.html', 'utf8') var template = fs.readFileSync('./templates/docs/line-height/index.html', 'utf8') var tpl = _.template(template) var html = tpl({ moduleVersion: module.version, moduleSize: moduleSize, moduleObj: moduleObj, srcCSS: srcCSS, navDocs: navDocs }) fs.writeFileSync('./docs/typography/line-height/index.html', html)
Disable redux devtools for fixing invalid object on mobile browser
import React from 'react' import { applyMiddleware, createStore, compose } from 'redux' import { render } from 'react-dom' import { Provider } from 'react-redux' import { applyRouterMiddleware, browserHistory, Router } from 'react-router' import { ReduxAsyncConnect } from 'redux-connect' import { persistState } from 'redux-devtools' import { routerMiddleware, syncHistoryWithStore } from 'react-router-redux' import useScroll from 'react-router-scroll' import PromiseMiddleware from './middlewares/PromiseMiddleware' import reducers from './reducers' import routes from './routes' const initialState = decodeURIComponent(window.__INITIAL_STATE__) const store = createStore( reducers, initialState, // compose( applyMiddleware( PromiseMiddleware, routerMiddleware(browserHistory) ), // (window.devToolsExtension // ? window.devToolsExtension() // : null), // persistState(window.location.href.match(/[?&]debug_session=([^&]+)\b/)) // ), ) const history = syncHistoryWithStore(browserHistory, store) render( <Provider store={ store }> <Router render={ (renderProps) => { return ( <ReduxAsyncConnect { ...renderProps } render={ applyRouterMiddleware(useScroll()) } /> ) } } history={ history }> { routes(store) } </Router> </Provider>, document.getElementById('root') )
import React from 'react' import { applyMiddleware, createStore, compose } from 'redux' import { render } from 'react-dom' import { Provider } from 'react-redux' import { applyRouterMiddleware, browserHistory, Router } from 'react-router' import { ReduxAsyncConnect } from 'redux-connect' import { persistState } from 'redux-devtools' import { routerMiddleware, syncHistoryWithStore } from 'react-router-redux' import useScroll from 'react-router-scroll' import PromiseMiddleware from './middlewares/PromiseMiddleware' import reducers from './reducers' import routes from './routes' const initialState = decodeURIComponent(window.__INITIAL_STATE__) const store = createStore( reducers, initialState, compose( applyMiddleware( PromiseMiddleware, routerMiddleware(browserHistory) ), window.devToolsExtension && window.devToolsExtension(), persistState(window.location.href.match(/[?&]debug_session=([^&]+)\b/)) ), ) const history = syncHistoryWithStore(browserHistory, store) render( <Provider store={ store }> <Router render={ (renderProps) => { return ( <ReduxAsyncConnect { ...renderProps } render={ applyRouterMiddleware(useScroll()) } /> ) } } history={ history }> { routes(store) } </Router> </Provider>, document.getElementById('root') )
Remove unneeded env var to set siteaccess
<?php namespace Boris\Loader\Provider; class EzPublish extends AbstractProvider { public $name = 'ezpublish'; public function assertDir($dir) { return is_file("$dir/ezpublish/bootstrap.php.cache") && is_file("$dir/ezpublish/EzPublishKernel.php"); } public function initialize(\Boris\Boris $boris, $dir) { parent::initialize($boris, $dir); require "$dir/ezpublish/bootstrap.php.cache"; require_once "$dir/ezpublish/EzPublishKernel.php"; $kernel = new \EzPublishKernel('dev', true); $kernel->loadClassCache(); $kernel->boot(); $boris->onStart(function ($worker, $vars) use ($kernel) { $worker->setLocal('kernel', $kernel); $worker->setLocal('container', $kernel->getContainer()); }); } }
<?php namespace Boris\Loader\Provider; class EzPublish extends AbstractProvider { public $name = 'ezpublish'; public function assertDir($dir) { return is_file("$dir/ezpublish/bootstrap.php.cache") && is_file("$dir/ezpublish/EzPublishKernel.php"); } public function initialize(\Boris\Boris $boris, $dir) { parent::initialize($boris, $dir); putenv("EZPUBLISH_SITEACCESS=fr"); require "$dir/ezpublish/bootstrap.php.cache"; require_once "$dir/ezpublish/EzPublishKernel.php"; $kernel = new \EzPublishKernel('dev', true); $kernel->loadClassCache(); $kernel->boot(); $boris->onStart(function ($worker, $vars) use ($kernel) { $worker->setLocal('kernel', $kernel); $worker->setLocal('container', $kernel->getContainer()); }); } }
Fix gene regex per parul suggestion [ci skip]
// eslint-disable-next-line no-unused-vars function dega_bed_parser(line, index) { // Here is where we convert the content of a specific BED file format to the desired JSON structure // In Parul's file, there are two entities- a cis regulatory element (the position column // used for tabix queries) and a promoter that affects a gene (a string column with an ID) var fields = line.split('\t'); var chrom = fields[0].replace('chr', ''); // assume format chr1:123-456_GENE or chr1:123-456 (chr prefix optional) var second_item = fields[3].match(/^(?:chr)?(\d+):(\d+)-(\d+)(?:_)?(\S+)?$/); var score = fields[4]; score = (score === '.') ? null : +score; return { // Note: The query is based on position of element 1, not element 2. It's possible for a loop to be in the // region, but the tabix query to not find it. chrom: chrom, start1: +fields[1], end1: +fields[2], start2: +second_item[2], end2: +second_item[3], // Optional field: chromatin interaction files have it; coaccessibility files do not target: second_item[4] || null, score: score, id: index, // Dummy ID: position in the list of lines TODO: create a better unique ID }; }
// eslint-disable-next-line no-unused-vars function dega_bed_parser(line, index) { // Here is where we convert the content of a specific BED file format to the desired JSON structure // In Parul's file, there are two entities- a cis regulatory element (the position column // used for tabix queries) and a promoter that affects a gene (a string column with an ID) var fields = line.split('\t'); var chrom = fields[0].replace('chr', ''); // assume format chr1:123-456_GENE or chr1:123-456 (chr prefix optional) var second_item = fields[3].match(/^(?:chr)?(\d+):(\d+)-(\d+)(?:_)?(\w+)?$/); var score = fields[4]; score = (score === '.') ? null : +score; return { // Note: The query is based on position of element 1, not element 2. It's possible for a loop to be in the // region, but the tabix query to not find it. chrom: chrom, start1: +fields[1], end1: +fields[2], start2: +second_item[2], end2: +second_item[3], // Optional field: chromatin interaction files have it; coaccessibility files do not target: second_item[4] || null, score: score, id: index, // Dummy ID: position in the list of lines TODO: create a better unique ID }; }
Use 127.0.0.1 instead of localhost
package org.zeromq.czmq; import org.junit.Assert; import org.junit.Test; public class ZSockTest { @Test public void testZSockSendRecv() { try (final ZSock push = new ZSock(ZMQ.ZMQ_PUSH); final ZSock pull = new ZSock(ZMQ.ZMQ_PULL)) { ZMsg msg = new ZMsg(); pull.bind("tcp://*:1234"); push.connect("tcp://127.0.0.1:1234"); String expected = "hello"; msg.pushstr(expected); ZMsg.send(msg, push); ZMsg resp = ZMsg.recv(pull); String actual = resp.popstr(); Assert.assertEquals(expected, actual); resp.close(); } } }
package org.zeromq.czmq; import org.junit.Assert; import org.junit.Test; public class ZSockTest { @Test public void testZSockSendRecv() { try (final ZSock push = new ZSock(ZMQ.ZMQ_PUSH); final ZSock pull = new ZSock(ZMQ.ZMQ_PULL)) { ZMsg msg = new ZMsg(); pull.bind("tcp://*:1234"); push.connect("tcp://localhost:1234"); String expected = "hello"; msg.pushstr(expected); ZMsg.send(msg, push); ZMsg resp = ZMsg.recv(pull); String actual = resp.popstr(); Assert.assertEquals(expected, actual); resp.close(); } } }
Allow for parameters to __init__() Signed-off-by: Steve Loranz <749f95e2748aaf836ea2a030a8b369f33fe35144@redhat.com>
# Copyright 2011 Red Hat, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. class Singleton(object): _instance = None def __new__(cls, *args, **kwargs): if cls._instance is None: instance = super(Singleton, cls).__new__(cls, *args, **kwargs) instance._singleton_init(*args, **kwargs) cls._instance = instance elif args or kwargs: cls._instance.log.warn('Attempted re-initialize of singleton: %s' % (cls._instance, )) return cls._instance def __init__(self, *args, **kwargs): pass def _singleton_init(self, *args, **kwargs): """Initialize a singleton instance before it is registered.""" pass
# Copyright 2011 Red Hat, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. class Singleton(object): _instance = None def __new__(cls, *args, **kwargs): if cls._instance is None: instance = super(Singleton, cls).__new__(cls, *args, **kwargs) instance._singleton_init(*args, **kwargs) cls._instance = instance elif args or kwargs: cls._instance.log.warn('Attempted re-initialize of singleton: %s' % (cls._instance, )) return cls._instance def __init__(self): pass def _singleton_init(self): """Initialize a singleton instance before it is registered.""" pass
[FIX] l10n_br_coa_generic: Use admin user to create COA
# Copyright (C) 2020 - Gabriel Cardoso de Faria <gabriel.cardoso@kmee.com.br> # License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html from odoo import api, tools, SUPERUSER_ID def post_init_hook(cr, registry): env = api.Environment(cr, SUPERUSER_ID, {}) coa_generic_tmpl = env.ref( 'l10n_br_coa_generic.l10n_br_coa_generic_template') if env['ir.module.module'].search_count([ ('name', '=', 'l10n_br_account'), ('state', '=', 'installed'), ]): from odoo.addons.l10n_br_account.hooks import load_fiscal_taxes # Relate fiscal taxes to account taxes. load_fiscal_taxes(env, coa_generic_tmpl) # Load COA to Demo Company if not tools.config.get('without_demo'): user_admin = env.ref('base.user_admin') user_admin.company_id = env.ref( 'l10n_br_base.empresa_lucro_presumido') coa_generic_tmpl.sudo( user=user_admin.id).try_loading_for_current_company() user_admin.company_id = env.ref('base.main_company')
# Copyright (C) 2020 - Gabriel Cardoso de Faria <gabriel.cardoso@kmee.com.br> # License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html from odoo import api, tools, SUPERUSER_ID def post_init_hook(cr, registry): env = api.Environment(cr, SUPERUSER_ID, {}) coa_generic_tmpl = env.ref( 'l10n_br_coa_generic.l10n_br_coa_generic_template') if env['ir.module.module'].search_count([ ('name', '=', 'l10n_br_account'), ('state', '=', 'installed'), ]): from odoo.addons.l10n_br_account.hooks import load_fiscal_taxes # Relate fiscal taxes to account taxes. load_fiscal_taxes(env, coa_generic_tmpl) # Load COA to Demo Company if not tools.config.get('without_demo'): env.user.company_id = env.ref( 'l10n_br_fiscal.empresa_lucro_presumido') coa_generic_tmpl.try_loading_for_current_company()
SimonStewart: Make the selenium-backed webdriver emulate the normal webdriver's xpath mode r10674
/* Copyright 2007-2009 WebDriver committers Copyright 2007-2009 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.openqa.selenium.internal.selenesedriver; import com.thoughtworks.selenium.Selenium; import org.openqa.selenium.Capabilities; import org.openqa.selenium.Platform; import java.util.HashMap; import java.util.Map; public class NewSession implements SeleneseFunction<Map<String, Object>> { public Map<String, Object> apply(Selenium selenium, Map<String, ?> args) { selenium.start(); // Emulate behaviour of webdriver selenium.useXpathLibrary("javascript-xpath"); selenium.allowNativeXpath("true"); Capabilities capabilities = (Capabilities) args.get("desiredCapabilities"); Map<String, Object> seenCapabilities = new HashMap<String, Object>(); seenCapabilities.put("browserName", capabilities.getBrowserName()); seenCapabilities.put("version", capabilities.getVersion()); seenCapabilities.put("platform", Platform.getCurrent().toString()); seenCapabilities.put("javascriptEnabled", true); return seenCapabilities; } }
/* Copyright 2007-2009 WebDriver committers Copyright 2007-2009 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.openqa.selenium.internal.selenesedriver; import com.thoughtworks.selenium.Selenium; import org.openqa.selenium.Capabilities; import org.openqa.selenium.Platform; import java.util.HashMap; import java.util.Map; public class NewSession implements SeleneseFunction<Map<String, Object>> { public Map<String, Object> apply(Selenium selenium, Map<String, ?> args) { selenium.start(); Capabilities capabilities = (Capabilities) args.get("desiredCapabilities"); Map<String, Object> seenCapabilities = new HashMap<String, Object>(); seenCapabilities.put("browserName", capabilities.getBrowserName()); seenCapabilities.put("version", capabilities.getVersion()); seenCapabilities.put("platform", Platform.getCurrent().toString()); seenCapabilities.put("javascriptEnabled", true); return seenCapabilities; } }
Return route, hip rank and total rank
from os import environ from urllib2 import urlopen from flask import Flask, json, jsonify app = Flask(__name__) from hip import get_ranking_array url = 'http://open.mapquestapi.com/directions/v2/route' params = '?key={apikey}&ambiguities=ignore&routeType=pedestrian' rel = url + params + '&from={flat},{flng}&to={tlat},{tlng}' @app.route("/route/<from_lat>,<from_lng>/<to_lat>,<to_lng>") def route(from_lat, from_lng, to_lat, to_lng): resp = urlopen(rel.format(apikey=environ['MAPQUEST_API_KEY'], flat=from_lat, flng=from_lng, tlat=to_lat, tlng=to_lng)) route = json.loads(resp.read().decode("utf-8")) coords = [(man['startPoint']['lat'], man['startPoint']['lng']) for leg in route['route']['legs'] for man in leg['maneuvers']] hip_rank, total_rank = get_ranking_array(coords) return jsonify(route=route, hip_rank=list(hip_rank), total_rank=total_rank) if __name__ == "__main__": app.run(debug=environ.get('FLASK_DEBUG', False))
from os import environ from urllib2 import urlopen from flask import Flask, json, make_response app = Flask(__name__) url = 'http://open.mapquestapi.com/directions/v2/route' params = '?key={apikey}&ambiguities=ignore&routeType=pedestrian' rel = url + params + '&from={flat},{flng}&to={tlat},{tlng}' @app.route("/route/<from_lat>,<from_lng>/<to_lat>,<to_lng>") def get_coords(from_lat, from_lng, to_lat, to_lng): resp = urlopen(rel.format(apikey=environ['MAPQUEST_API_KEY'], flat=from_lat, flng=from_lng, tlat=to_lat, tlng=to_lng)) resp_dict = json.loads(resp.read().decode("utf-8")) res = [(man['startPoint']['lat'], man['startPoint']['lng']) for leg in resp_dict['route']['legs'] for man in leg['maneuvers']] return make_response(json.dumps(res)) if __name__ == "__main__": app.run(debug=environ.get('FLASK_DEBUG', False))
Fix editor document id creation
export const getCKEditorDocumentId = (documentId, userId, formType) => { if (documentId) return `${documentId}-${formType}` return `${userId}-${formType}` } export function generateTokenRequest(documentId, userId, formType) { return () => { return new Promise( ( resolve, reject ) => { const xhr = new XMLHttpRequest(); xhr.open( 'GET', '/ckeditor-token' ); xhr.addEventListener( 'load', () => { const statusCode = xhr.status; const xhrResponse = xhr.response; if ( statusCode < 200 || statusCode > 299 ) { return reject( new Error( 'Cannot download a new token!' ) ); } return resolve( xhrResponse ); } ); xhr.addEventListener( 'error', () => reject( new Error( 'Network error' ) ) ); xhr.addEventListener( 'abort', () => reject( new Error( 'Abort' ) ) ); if (documentId) xhr.setRequestHeader( 'document-id', documentId ); if (userId) xhr.setRequestHeader( 'user-id', userId ); if (formType) xhr.setRequestHeader( 'form-type', formType ); xhr.send(); } ); } }
export const getCKEditorDocumentId = (documentId, userId, formType) => { if (documentId) return `${documentId}-${userId}-${formType}` return `${userId}-${formType}` } export function generateTokenRequest(documentId, userId, formType) { return () => { return new Promise( ( resolve, reject ) => { const xhr = new XMLHttpRequest(); xhr.open( 'GET', '/ckeditor-token' ); xhr.addEventListener( 'load', () => { const statusCode = xhr.status; const xhrResponse = xhr.response; if ( statusCode < 200 || statusCode > 299 ) { return reject( new Error( 'Cannot download a new token!' ) ); } return resolve( xhrResponse ); } ); xhr.addEventListener( 'error', () => reject( new Error( 'Network error' ) ) ); xhr.addEventListener( 'abort', () => reject( new Error( 'Abort' ) ) ); if (documentId) xhr.setRequestHeader( 'document-id', documentId ); if (userId) xhr.setRequestHeader( 'user-id', userId ); if (formType) xhr.setRequestHeader( 'form-type', formType ); xhr.send(); } ); } }
Gravatar: Use https url to avoid serving insecure content
from django.conf import settings from PIL import Image from appconf import AppConf class AvatarConf(AppConf): DEFAULT_SIZE = 80 RESIZE_METHOD = Image.ANTIALIAS STORAGE_DIR = 'avatars' STORAGE_PARAMS = {} GRAVATAR_FIELD = 'email' GRAVATAR_BASE_URL = 'https://www.gravatar.com/avatar/' GRAVATAR_BACKUP = True GRAVATAR_DEFAULT = None DEFAULT_URL = 'avatar/img/default.jpg' MAX_AVATARS_PER_USER = 42 MAX_SIZE = 1024 * 1024 THUMB_FORMAT = 'JPEG' THUMB_QUALITY = 85 USERID_AS_USERDIRNAME = False HASH_FILENAMES = False HASH_USERDIRNAMES = False ALLOWED_FILE_EXTS = None CACHE_TIMEOUT = 60 * 60 STORAGE = settings.DEFAULT_FILE_STORAGE CLEANUP_DELETED = False AUTO_GENERATE_SIZES = (DEFAULT_SIZE,) AVATAR_ALLOWED_MIMETYPES = [] def configure_auto_generate_avatar_sizes(self, value): return value or getattr(settings, 'AVATAR_AUTO_GENERATE_SIZES', (self.DEFAULT_SIZE,))
from django.conf import settings from PIL import Image from appconf import AppConf class AvatarConf(AppConf): DEFAULT_SIZE = 80 RESIZE_METHOD = Image.ANTIALIAS STORAGE_DIR = 'avatars' STORAGE_PARAMS = {} GRAVATAR_FIELD = 'email' GRAVATAR_BASE_URL = 'http://www.gravatar.com/avatar/' GRAVATAR_BACKUP = True GRAVATAR_DEFAULT = None DEFAULT_URL = 'avatar/img/default.jpg' MAX_AVATARS_PER_USER = 42 MAX_SIZE = 1024 * 1024 THUMB_FORMAT = 'JPEG' THUMB_QUALITY = 85 USERID_AS_USERDIRNAME = False HASH_FILENAMES = False HASH_USERDIRNAMES = False ALLOWED_FILE_EXTS = None CACHE_TIMEOUT = 60 * 60 STORAGE = settings.DEFAULT_FILE_STORAGE CLEANUP_DELETED = False AUTO_GENERATE_SIZES = (DEFAULT_SIZE,) AVATAR_ALLOWED_MIMETYPES = [] def configure_auto_generate_avatar_sizes(self, value): return value or getattr(settings, 'AVATAR_AUTO_GENERATE_SIZES', (self.DEFAULT_SIZE,))
Add random gold or blue
var _ = require('underscore'); // Load .env for development environments require('dotenv').load(); exports.initLocals = function(req, res, next) { var locals = res.locals; locals.user = req.user; locals.buy = { ticket: req.query.ticket, discount: req.query.discount, }; locals.twoco_seller_id = process.env.TWOCO_SELLER_ID; locals.twoco_public_key = process.env.TWOCO_PUBLIC_KEY; console.log(Math.random()); locals.gold = req.query.g == '' ? (Math.random() > 0.5 ? 'gold' : '') : ''; next(); }; exports.flashMessages = function(req, res, next) { var flashMessages = { info: req.flash('info'), success: req.flash('success'), warning: req.flash('warning'), error: req.flash('error') }; res.locals.messages = _.any(flashMessages, function(msgs) { return msgs.length; }) ? flashMessages : false; next(); }; exports.requireUser = function(req, res, next) { if (!req.user) { req.flash('error', 'Please sign in to access this page.'); res.redirect('/keystone/signin'); } else { next(); } };
var _ = require('underscore'); // Load .env for development environments require('dotenv').load(); exports.initLocals = function(req, res, next) { var locals = res.locals; locals.user = req.user; locals.buy = { ticket: req.query.ticket, discount: req.query.discount, }; locals.twoco_seller_id = process.env.TWOCO_SELLER_ID; locals.twoco_public_key = process.env.TWOCO_PUBLIC_KEY; locals.gold = req.query.g == '' ? 'gold' : ''; next(); }; exports.flashMessages = function(req, res, next) { var flashMessages = { info: req.flash('info'), success: req.flash('success'), warning: req.flash('warning'), error: req.flash('error') }; res.locals.messages = _.any(flashMessages, function(msgs) { return msgs.length; }) ? flashMessages : false; next(); }; exports.requireUser = function(req, res, next) { if (!req.user) { req.flash('error', 'Please sign in to access this page.'); res.redirect('/keystone/signin'); } else { next(); } };
Make global title available from layout, request, and render stream
// DecentCMS (c) 2014 Bertrand Le Roy, under MIT. See LICENSE.txt for licensing details. 'use strict'; /** * @description * The title part handler looks for a title property on the content * item. It renders a title shape, and also sets the title on the * renderer if the display type is 'main' (which means this is the * main content item on the page). */ var TitlePart = { feature: 'core-parts', service: 'shape-handler', handle: function handleTitlePart(context, done) { var content = context.shape; if (!content.meta || content.meta.type !== 'content' || !content.temp || !content.temp.item || !content.temp.item.title) return done(); var temp = content.temp; var item = temp.item; var title = item.title; if (title && temp.displayType === 'main') { var renderer = context.renderStream; renderer.title = context.scope.title = context.scope.layout.title = title; } temp.shapes.push({ meta: {type: 'title'}, temp: {displayType: temp.displayType}, text: title }); done(); } }; module.exports = TitlePart;
// DecentCMS (c) 2014 Bertrand Le Roy, under MIT. See LICENSE.txt for licensing details. 'use strict'; /** * @description * The title part handler looks for a title property on the content * item. It renders a title shape, and also sets the title on the * renderer if the display type is 'main' (which means this is the * main content item on the page). */ var TitlePart = { feature: 'core-parts', service: 'shape-handler', handle: function handleTitlePart(context, done) { var content = context.shape; if (!content.meta || content.meta.type !== 'content' || !content.temp || !content.temp.item || !content.temp.item.title) return done(); var temp = content.temp; var item = temp.item; var title = item.title; if (title && temp.displayType === 'main') { var renderer = context.renderStream; renderer.title = title; } temp.shapes.push({ meta: {type: 'title'}, temp: {displayType: temp.displayType}, text: title }); done(); } }; module.exports = TitlePart;
Fix ruler menu for breakpoints Review URL: http://codereview.chromium.org/99357 git-svn-id: 1dc80909446f7a7ee3e21dd4d1b8517df524e9ee@6 fc8a088e-31da-11de-8fef-1f5ae417a2df
// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.debug.ui.editors; import org.eclipse.ui.editors.text.TextEditor; /** * A simplistic Javascript editor which supports its own key binding scope. */ public class JsEditor extends TextEditor { /** The ID of this editor as defined in plugin.xml */ public static final String EDITOR_ID = "org.chromium.debug.ui.editors.JsEditor"; //$NON-NLS-1$ /** The ID of the editor context menu */ public static final String EDITOR_CONTEXT = EDITOR_ID + ".context"; //$NON-NLS-1$ /** The ID of the editor ruler context menu */ public static final String RULER_CONTEXT = EDITOR_ID + ".ruler"; //$NON-NLS-1$ @Override protected void initializeEditor() { super.initializeEditor(); setEditorContextMenuId(EDITOR_CONTEXT); setRulerContextMenuId(RULER_CONTEXT); } public JsEditor() { super(); setSourceViewerConfiguration(new JsSourceViewerConfiguration()); setKeyBindingScopes(new String[] { "org.eclipse.ui.textEditorScope", //$NON-NLS-1$ "org.chromium.debug.ui.editors.JsEditor.context" }); //$NON-NLS-1$ } }
// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.debug.ui.editors; import org.eclipse.ui.editors.text.TextEditor; /** * A simplistic Javascript editor which supports its own key binding scope. */ public class JsEditor extends TextEditor { /** The ID of this editor as defined in plugin.xml */ public static final String EDITOR_ID = "org.chromium.debug.ui.editors.JsEditor"; //$NON-NLS-1$ /** The ID of the editor context menu */ public static final String EDITOR_CONTEXT = EDITOR_ID + ".context"; //$NON-NLS-1$ /** The ID of the editor ruler context menu */ public static final String RULER_CONTEXT = EDITOR_CONTEXT + ".ruler"; //$NON-NLS-1$ protected void initializeEditor() { super.initializeEditor(); setEditorContextMenuId(EDITOR_CONTEXT); setRulerContextMenuId(RULER_CONTEXT); } public JsEditor() { super(); setSourceViewerConfiguration(new JsSourceViewerConfiguration()); setKeyBindingScopes(new String[] { "org.eclipse.ui.textEditorScope", //$NON-NLS-1$ "org.chromium.debug.ui.editors.JsEditor.context" }); //$NON-NLS-1$ } }
Fix the location of the C extension
# Licensed under a 3-clause BSD style license - see LICENSE.rst from setuptools import setup, Extension import numpy as np from Cython.Build import cythonize fastss_ext = Extension("Ska.Numpy.fastss", ['Ska/Numpy/fastss.pyx'], include_dirs=[np.get_include()]) try: from testr.setup_helper import cmdclass except ImportError: cmdclass = {} setup(name='Ska.Numpy', author='Tom Aldcroft', description='Numpy utilities', author_email='aldcroft@head.cfa.harvard.edu', py_modules=['Ska.Numpy'], use_scm_version=True, setup_requires=['setuptools_scm', 'setuptools_scm_git_archive'], ext_modules=cythonize([fastss_ext]), zip_safe=False, packages=['Ska', 'Ska.Numpy', 'Ska.Numpy.tests'], tests_require=['pytest'], cmdclass=cmdclass, )
# Licensed under a 3-clause BSD style license - see LICENSE.rst from setuptools import setup, Extension import numpy as np from Cython.Build import cythonize fastss_ext = Extension("*", ['Ska/Numpy/fastss.pyx'], include_dirs=[np.get_include()]) try: from testr.setup_helper import cmdclass except ImportError: cmdclass = {} setup(name='Ska.Numpy', author='Tom Aldcroft', description='Numpy utilities', author_email='aldcroft@head.cfa.harvard.edu', py_modules=['Ska.Numpy'], use_scm_version=True, setup_requires=['setuptools_scm', 'setuptools_scm_git_archive'], ext_modules=cythonize([fastss_ext]), zip_safe=False, packages=['Ska', 'Ska.Numpy', 'Ska.Numpy.tests'], tests_require=['pytest'], cmdclass=cmdclass, )
Simplify conditional for choosing WheelDistribution
from pip._internal.distributions.source import SourceDistribution from pip._internal.distributions.wheel import WheelDistribution from pip._internal.utils.typing import MYPY_CHECK_RUNNING if MYPY_CHECK_RUNNING: from pip._internal.distributions.base import AbstractDistribution from pip._internal.req.req_install import InstallRequirement def make_distribution_for_install_requirement(install_req): # type: (InstallRequirement) -> AbstractDistribution """Returns a Distribution for the given InstallRequirement """ # If it's not an editable, is a wheel, it's a WheelDistribution if install_req.editable: return SourceDistribution(install_req) if install_req.is_wheel: return WheelDistribution(install_req) # Otherwise, a SourceDistribution return SourceDistribution(install_req)
from pip._internal.distributions.source import SourceDistribution from pip._internal.distributions.wheel import WheelDistribution from pip._internal.utils.typing import MYPY_CHECK_RUNNING if MYPY_CHECK_RUNNING: from pip._internal.distributions.base import AbstractDistribution from pip._internal.req.req_install import InstallRequirement def make_distribution_for_install_requirement(install_req): # type: (InstallRequirement) -> AbstractDistribution """Returns a Distribution for the given InstallRequirement """ # If it's not an editable, is a wheel, it's a WheelDistribution if install_req.editable: return SourceDistribution(install_req) if install_req.link and install_req.is_wheel: return WheelDistribution(install_req) # Otherwise, a SourceDistribution return SourceDistribution(install_req)
Stop reporting 404 errors to sentry We get lots of these and they are all crawlers or bad actors. We should just ignore them.
<?php namespace App\EventListener; use App\Service\Config; use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; use function Sentry\init as sentryInit; use function Sentry\captureException as sentryCaptureException; /** * Sends errors to symfony */ class SentryCaptureListener { /** * @var bool */ protected $errorCaptureEnabled; public function __construct( Config $config, string $sentryDSN ) { $this->errorCaptureEnabled = $config->get('errorCaptureEnabled'); if ($this->errorCaptureEnabled) { sentryInit(['dsn' => $sentryDSN]); } } public function onKernelException(GetResponseForExceptionEvent $event) { if ($this->errorCaptureEnabled) { $exception = $event->getException(); //don't report 404s to Sentry if ($exception instanceof NotFoundHttpException) { return; } sentryCaptureException($exception); } } }
<?php namespace App\EventListener; use App\Service\Config; use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent; use function Sentry\init as sentryInit; use function Sentry\captureException as sentryCaptureException; /** * Sends errors to symfony */ class SentryCaptureListener { /** * @var bool */ protected $errorCaptureEnabled; public function __construct( Config $config, string $sentryDSN ) { $this->errorCaptureEnabled = $config->get('errorCaptureEnabled'); if ($this->errorCaptureEnabled) { sentryInit(['dsn' => $sentryDSN]); } } public function onKernelException(GetResponseForExceptionEvent $event) { if ($this->errorCaptureEnabled) { sentryCaptureException($event->getException()); } } }
Fix the params object in the find
// Use this hook to manipulate incoming or outgoing data. // For more information on hooks see: http://docs.feathersjs.com/api/hooks.html module.exports = function (options = {}) { // eslint-disable-line no-unused-vars return function (hook) { const { facebook, facebookId } = hook.data; return this.find({ query: { facebookId } }).then(user => { if (user.data.length < 1) { const { profile } = facebook; const { name, gender, emails } = profile; const email = emails && emails.length && emails[0].value || undefined; hook.data = Object.assign( {}, { firstName: name && name.givenName || undefined, lastName: name && name.familyName || undefined, facebookId, email, gender, } ); } return hook; }); }; };
// Use this hook to manipulate incoming or outgoing data. // For more information on hooks see: http://docs.feathersjs.com/api/hooks.html module.exports = function (options = {}) { // eslint-disable-line no-unused-vars return function (hook) { const { facebook, facebookId } = hook.data; return this.find({ facebookId }).then(user => { if (user.data.length < 1) { const { profile } = facebook; const { name, gender, emails } = profile; const email = emails && emails.length && emails[0].value || undefined; hook.data = Object.assign( {}, { firstName: name && name.givenName || undefined, lastName: name && name.familyName || undefined, facebookId, email, gender, } ); } return hook; }); }; };
UPDATE - Unused use class removed.
<?php namespace DoctrineExtensions\Query\Mysql; use Doctrine\ORM\Query\QueryException; /** * @author Vas N <phpvas@gmail.com> */ class DateSub extends DateAdd { public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker) { $unit = strtoupper(is_string($this->unit) ? $this->unit : $this->unit->value); if (!in_array($unit, self::$allowedUnits)) { throw QueryException::semanticalError('DATE_SUB() does not support unit "' . $unit . '".'); } return 'DATE_SUB(' . $this->firstDateExpression->dispatch($sqlWalker) . ', INTERVAL ' . $this->intervalExpression->dispatch($sqlWalker) . ' ' . $unit . ')'; } }
<?php namespace DoctrineExtensions\Query\Mysql; use Doctrine\ORM\Query\Lexer, Doctrine\ORM\Query\QueryException; /** * @author Vas N <phpvas@gmail.com> */ class DateSub extends DateAdd { public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker) { $unit = strtoupper(is_string($this->unit) ? $this->unit : $this->unit->value); if (!in_array($unit, self::$allowedUnits)) { throw QueryException::semanticalError('DATE_SUB() does not support unit "' . $unit . '".'); } return 'DATE_SUB(' . $this->firstDateExpression->dispatch($sqlWalker) . ', INTERVAL ' . $this->intervalExpression->dispatch($sqlWalker) . ' ' . $unit . ')'; } }